@needle-tools/engine 4.6.1 → 4.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/dist/generateMeshBVH.worker-BaNp_Xtp.js +25 -0
  3. package/dist/{gltf-progressive-Bm9eEfgu.min.js → gltf-progressive-Bl4okF1b.min.js} +1 -1
  4. package/dist/{gltf-progressive-GjIqwSG3.js → gltf-progressive-DSpdn0QT.js} +2 -2
  5. package/dist/{gltf-progressive-Dn6o99rH.umd.cjs → gltf-progressive-P8b8a0qY.umd.cjs} +1 -1
  6. package/dist/needle-engine.bundle-D0XWaCQs.min.js +1575 -0
  7. package/dist/{needle-engine.bundle-BVg46UWZ.js → needle-engine.bundle-DGcStTA7.js} +9715 -9555
  8. package/dist/needle-engine.bundle-DmYMLdWP.umd.cjs +1575 -0
  9. package/dist/needle-engine.js +352 -351
  10. package/dist/needle-engine.min.js +1 -1
  11. package/dist/needle-engine.umd.cjs +1 -1
  12. package/dist/{postprocessing-CRQa6Qxn.umd.cjs → postprocessing-CjW23fio.umd.cjs} +18 -18
  13. package/dist/{postprocessing-D6W1EyZ-.js → postprocessing-DYLNOL3W.js} +4 -3
  14. package/dist/{postprocessing-DF8AlRgW.min.js → postprocessing-xYQWCHFu.min.js} +26 -26
  15. package/dist/{three-DMrv-4ar.umd.cjs → three-B_hneGZr.umd.cjs} +4 -4
  16. package/dist/{three-Bz6X1mrw.js → three-DrqIzZTH.js} +4198 -4198
  17. package/dist/{three-Boa-jOq-.min.js → three-DuDKwKB8.min.js} +33 -33
  18. package/dist/{three-examples-GggCDHv0.js → three-examples-B50TT3Iu.js} +5 -5
  19. package/dist/{three-examples-DuVhxqft.min.js → three-examples-DaDLBuy6.min.js} +14 -14
  20. package/dist/{three-examples-C7ryg8vN.umd.cjs → three-examples-X3OadjXB.umd.cjs} +3 -3
  21. package/dist/{three-mesh-ui-CY6Izc7C.min.js → three-mesh-ui-B3p3gyUz.min.js} +1 -1
  22. package/dist/{three-mesh-ui-CwlN0FUC.umd.cjs → three-mesh-ui-CQiIQIlA.umd.cjs} +1 -1
  23. package/dist/{three-mesh-ui-CLNOfsWn.js → three-mesh-ui-CxuWt7m-.js} +1 -1
  24. package/dist/{vendor-zxXa3Dmr.min.js → vendor-BlSxe9JJ.min.js} +3 -3
  25. package/dist/{vendor-BSD1RQIh.js → vendor-BmYIgaS1.js} +3 -3
  26. package/dist/{vendor-DHr4aqIZ.umd.cjs → vendor-Cavtu3CP.umd.cjs} +3 -3
  27. package/lib/engine/engine_context.d.ts +4 -1
  28. package/lib/engine/engine_context.js +9 -2
  29. package/lib/engine/engine_context.js.map +1 -1
  30. package/lib/engine/engine_three_utils.d.ts +17 -14
  31. package/lib/engine/engine_three_utils.js +106 -53
  32. package/lib/engine/engine_three_utils.js.map +1 -1
  33. package/lib/engine/engine_tonemapping.d.ts +4 -0
  34. package/lib/engine/engine_tonemapping.js +21 -18
  35. package/lib/engine/engine_tonemapping.js.map +1 -1
  36. package/lib/engine/engine_utils.js.map +1 -1
  37. package/lib/engine/engine_utils_screenshot.d.ts +1 -1
  38. package/lib/engine/engine_utils_screenshot.js +11 -2
  39. package/lib/engine/engine_utils_screenshot.js.map +1 -1
  40. package/lib/engine/webcomponents/needle-engine.d.ts +4 -1
  41. package/lib/engine/webcomponents/needle-engine.extras.js +3 -3
  42. package/lib/engine/webcomponents/needle-engine.extras.js.map +1 -1
  43. package/lib/engine/webcomponents/needle-engine.js +11 -21
  44. package/lib/engine/webcomponents/needle-engine.js.map +1 -1
  45. package/lib/engine-components/CameraUtils.js.map +1 -1
  46. package/lib/engine-components/postprocessing/Effects/Antialiasing.js +3 -1
  47. package/lib/engine-components/postprocessing/Effects/Antialiasing.js.map +1 -1
  48. package/lib/engine-components/postprocessing/Effects/BloomEffect.d.ts +2 -2
  49. package/lib/engine-components/postprocessing/Effects/BloomEffect.js +5 -2
  50. package/lib/engine-components/postprocessing/Effects/BloomEffect.js.map +1 -1
  51. package/lib/engine-components/postprocessing/Effects/ColorAdjustments.d.ts +8 -0
  52. package/lib/engine-components/postprocessing/Effects/ColorAdjustments.js +27 -8
  53. package/lib/engine-components/postprocessing/Effects/ColorAdjustments.js.map +1 -1
  54. package/lib/engine-components/postprocessing/Effects/ScreenspaceAmbientOcclusionN8.js +1 -0
  55. package/lib/engine-components/postprocessing/Effects/ScreenspaceAmbientOcclusionN8.js.map +1 -1
  56. package/lib/engine-components/postprocessing/Effects/Sharpening.d.ts +1 -0
  57. package/lib/engine-components/postprocessing/Effects/Sharpening.js +4 -0
  58. package/lib/engine-components/postprocessing/Effects/Sharpening.js.map +1 -1
  59. package/lib/engine-components/postprocessing/Effects/Tonemapping.d.ts +2 -9
  60. package/lib/engine-components/postprocessing/Effects/Tonemapping.js +23 -71
  61. package/lib/engine-components/postprocessing/Effects/Tonemapping.js.map +1 -1
  62. package/lib/engine-components/postprocessing/Effects/Tonemapping.utils.d.ts +13 -0
  63. package/lib/engine-components/postprocessing/Effects/Tonemapping.utils.js +52 -0
  64. package/lib/engine-components/postprocessing/Effects/Tonemapping.utils.js.map +1 -0
  65. package/lib/engine-components/postprocessing/PostProcessingEffect.d.ts +18 -0
  66. package/lib/engine-components/postprocessing/PostProcessingEffect.js +22 -3
  67. package/lib/engine-components/postprocessing/PostProcessingEffect.js.map +1 -1
  68. package/lib/engine-components/postprocessing/PostProcessingHandler.d.ts +20 -4
  69. package/lib/engine-components/postprocessing/PostProcessingHandler.js +209 -112
  70. package/lib/engine-components/postprocessing/PostProcessingHandler.js.map +1 -1
  71. package/lib/engine-components/postprocessing/Volume.d.ts +2 -1
  72. package/lib/engine-components/postprocessing/Volume.js +51 -33
  73. package/lib/engine-components/postprocessing/Volume.js.map +1 -1
  74. package/lib/engine-components/postprocessing/index.d.ts +1 -0
  75. package/lib/engine-components/postprocessing/index.js +1 -0
  76. package/lib/engine-components/postprocessing/index.js.map +1 -1
  77. package/lib/engine-components/postprocessing/utils.d.ts +43 -0
  78. package/lib/engine-components/postprocessing/utils.js +82 -0
  79. package/lib/engine-components/postprocessing/utils.js.map +1 -1
  80. package/package.json +1 -1
  81. package/src/engine/engine_context.ts +13 -4
  82. package/src/engine/engine_three_utils.ts +134 -58
  83. package/src/engine/engine_tonemapping.ts +23 -24
  84. package/src/engine/engine_utils.ts +2 -2
  85. package/src/engine/engine_utils_screenshot.ts +13 -3
  86. package/src/engine/webcomponents/needle-engine.extras.ts +3 -3
  87. package/src/engine/webcomponents/needle-engine.ts +14 -25
  88. package/src/engine-components/CameraUtils.ts +3 -3
  89. package/src/engine-components/postprocessing/Effects/Antialiasing.ts +3 -1
  90. package/src/engine-components/postprocessing/Effects/BloomEffect.ts +6 -4
  91. package/src/engine-components/postprocessing/Effects/ColorAdjustments.ts +24 -13
  92. package/src/engine-components/postprocessing/Effects/ScreenspaceAmbientOcclusionN8.ts +1 -0
  93. package/src/engine-components/postprocessing/Effects/Sharpening.ts +5 -0
  94. package/src/engine-components/postprocessing/Effects/Tonemapping.ts +26 -80
  95. package/src/engine-components/postprocessing/Effects/Tonemapping.utils.ts +60 -0
  96. package/src/engine-components/postprocessing/PostProcessingEffect.ts +23 -3
  97. package/src/engine-components/postprocessing/PostProcessingHandler.ts +239 -119
  98. package/src/engine-components/postprocessing/Volume.ts +54 -38
  99. package/src/engine-components/postprocessing/index.ts +2 -1
  100. package/src/engine-components/postprocessing/utils.ts +102 -2
  101. package/dist/generateMeshBVH.worker-Cdfpaq5W.js +0 -25
  102. package/dist/needle-engine.bundle-AOXFIsYk.umd.cjs +0 -1563
  103. package/dist/needle-engine.bundle-Dt52m2jf.min.js +0 -1563
@@ -0,0 +1,1575 @@
1
+ var OC=Object.defineProperty,wv=o=>{throw TypeError(o)},kC=(o,e,t)=>e in o?OC(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t,a=(o,e,t)=>kC(o,typeof e!="symbol"?e+"":e,t),xm=(o,e,t)=>e.has(o)||wv("Cannot "+t),fe=(o,e,t)=>(xm(o,e,"read from private field"),t?t.call(o):e.get(o)),Us=(o,e,t)=>e.has(o)?wv("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(o):e.set(o,t),zs=(o,e,t,s)=>(xm(o,e,"write to private field"),s?s.call(o,t):e.set(o,t),t),cd=(o,e,t)=>(xm(o,e,"access private method"),t);import{Vector2 as le,Vector3 as x,Vector4 as ye,Quaternion as H,PlaneGeometry as Ns,WebGLRenderer as pr,PerspectiveCamera as we,OrthographicCamera as hd,Scene as wi,Mesh as q,Texture as De,Uniform$1 as Xi,Color as ae,ShaderMaterial as Ws,Box3 as xi,ShadowMaterial as xv,Euler as jt,MeshStandardMaterial as vt,Box3Helper as MC,GridHelper as Sm,Object3D as E,Material as Pe,Matrix3 as Sv,Matrix4 as se,Layers as ho,Ray as uo,MathUtils as Cn,AxesHelper as Si,MeshBasicMaterial as Me,DoubleSide as Ci,BufferGeometry as Vs,Group as po,CylinderGeometry as Cv,SphereGeometry as dd,BoxGeometry as ba,SpriteMaterial as RC,Sprite as TC,Shape as EC,ExtrudeGeometry as AC,Fog as Pv,DirectionalLight as Cm,PointLight as Pm,EdgesGeometry as IC,LineSegments as Ov,LineBasicMaterial as kv,Line as Wl,BufferAttribute as bt,Raycaster as ud,Sphere as pd,ArrayCamera as LC,Plane as mr,SkinnedMesh as Pn,InterleavedBufferAttribute as Mv,Skeleton as jC,Bone as DC,Source as BC,WebGLCubeRenderTarget as FC,CubeCamera as UC,AnimationClip as mo,FileLoader as Om,TextureLoader as _a,PropertyBinding as wa,LinearSRGBColorSpace as On,ShaderChunk as Gt,UniformsLib as zC,DataTexture as km,RGBAFormat as md,EquirectangularReflectionMapping as kn,SRGBColorSpace as Mn,Clock as NC,NeutralToneMapping as xa,AgXToneMapping as gd,ACESFilmicToneMapping as fd,NoToneMapping as yd,PCFSoftShadowMap$1 as WC,BasicNodeLibrary as VC,WebGLRenderTarget as Hs,DepthTexture as Rv,NearestFilter as vd,LoopRepeat as HC,LoopOnce as Mm,AnimationMixer as Rm,CompressedTexture as $C,FrontSide as go,Camera as GC,Frustum as Tv,AudioListener as qC,PositionalAudio as XC,AudioLoader as Tm,EventDispatcher as Em,BackSide as bd,MeshDepthMaterial as QC,CustomBlending as YC,MaxEquation as KC,AmbientLight as ZC,HemisphereLight as JC,AlwaysStencilFunc as eP,GreaterEqualStencilFunc as tP,NotEqualStencilFunc as iP,GreaterStencilFunc as sP,LessEqualStencilFunc as nP,EqualStencilFunc as oP,LessStencilFunc as rP,NeverStencilFunc as Ev,InvertStencilOp as aP,DecrementWrapStencilOp as lP,IncrementWrapStencilOp as cP,DecrementStencilOp as hP,IncrementStencilOp as dP,ReplaceStencilOp as uP,ZeroStencilOp as pP,KeepStencilOp as mP,RawShaderMaterial as Av,GLSL3 as gP,AlwaysDepth as fP,GreaterEqualDepth as yP,GreaterDepth as vP,LessEqualDepth as bP,LessDepth as _P,NotEqualDepth as wP,EqualDepth as xP,BatchedMesh as Iv,MeshPhysicalMaterial as Am,LinearFilter as _d,UnsignedByteType as SP,RingGeometry as CP,Line3 as PP,AdditiveBlending as Lv,BoxHelper as OP,SpotLight as kP,DirectionalLightHelper as MP,CameraHelper as RP,LOD as TP,Triangle as EP,NormalBlending as AP,ReinhardToneMapping as Im,LinearToneMapping as Lm,HalfFloatType as jm,VideoTexture as IP,CubeTexture as LP,CompressedCubeTexture as jP,EquirectangularRefractionMapping as DP,VectorKeyframeTrack as BP,QuaternionKeyframeTrack as FP,Audio as UP,ShaderLib as wd,UniformsUtils as jv,MirroredRepeatWrapping as Dv,MeshNormalMaterial as zP,AudioContext as NP,PMREMGenerator$1 as WP}from"./three-DuDKwKB8.min.js";import{createLoaders as Dm,getRaycastMesh as Bv,LODsManager as Sa,NEEDLE_progressive as Xe,addDracoAndKTX2Loaders as VP,configureLoader as HP,setKTX2TranscoderLocation as $P,setDracoDecoderLocation as GP}from"./gltf-progressive-Bl4okF1b.min.js";import{GroundedSkybox as Ca,Font as qP,TextGeometry as XP,FontLoader as QP,GLTFLoader as Rn,TransformControlsGizmo as Fv,EXRLoader as xd,RGBELoader as Bm,Stats as YP,nodeFrame as KP,OrbitControls as Uv,PositionalAudioHelper as ZP,HorizontalBlurShader as JP,VerticalBlurShader as eO,GLTFExporter as zv,strToU8 as Nv,zipSync as tO,XRControllerModelFactory as iO,XRHandMeshModel as sO,Line2 as nO,LineGeometry as oO,LineMaterial as rO,KTX2Loader as aO,TransformControls as lO,InteractiveGroup as cO,HTMLMesh as hO,VertexNormalsHelper as dO,OBJLoader as Fm,FBXLoader as Wv,mergeVertices as uO}from"./three-examples-DaDLBuy6.min.js";import{fetchProfile as pO,MotionController as mO,$70d766613f57b014$export$2e2bcd8739ae039 as Vv,ByteBuffer as gO,v5 as Hv,md5 as $v,SIZE_PREFIX_LENGTH as Gv,Builder as Um,createNoise4D as fO,Matrix4 as zm,BatchedParticleRenderer as yO,ParticleSystem as vO,RenderMode as Tn,ConstantColor as bO,Vector4 as _O,ConstantValue as wO,TrailParticle as qv,WorkerBase as xO,MeshBVH as SO}from"./vendor-BlSxe9JJ.min.js";import{__webpack_exports__default as Re,__webpack_exports__Text as Xv,__webpack_exports__Block as Qv,__webpack_exports__update as CO,SimpleStateBehavior as PO,__webpack_exports__Inline as Nm,__webpack_exports__FontLibrary as Yv,ThreeMeshUI as Kv}from"./three-mesh-ui-B3p3gyUz.min.js";import{EffectAttribute as Zv}from"./postprocessing-xYQWCHFu.min.js";const Wm=new Map;function qt(o=(e=>(e=globalThis.location)==null?void 0:e.hostname)()){if(Wm.has(o))return Wm.get(o);const e=/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})|localhost/.test(o);return Wm.set(o,e),e===!0}function Jv(){return window.location.hostname.includes("glitch.me")}const OO='<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 160 187.74"><defs><linearGradient id="a" x1="89.64" y1="184.81" x2="90.48" y2="21.85" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#62d399"/><stop offset=".51" stop-color="#acd842"/><stop offset=".9" stop-color="#d7db0a"/></linearGradient><linearGradient id="b" x1="69.68" y1="178.9" x2="68.08" y2="16.77" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#0ba398"/><stop offset=".5" stop-color="#4ca352"/><stop offset="1" stop-color="#76a30a"/></linearGradient><linearGradient id="c" x1="36.6" y1="152.17" x2="34.7" y2="84.19" gradientUnits="userSpaceOnUse"><stop offset=".19" stop-color="#36a382"/><stop offset=".54" stop-color="#49a459"/><stop offset="1" stop-color="#76a30b"/></linearGradient><linearGradient id="d" x1="15.82" y1="153.24" x2="18" y2="90.86" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#267880"/><stop offset=".51" stop-color="#457a5c"/><stop offset="1" stop-color="#717516"/></linearGradient><linearGradient id="e" x1="135.08" y1="135.43" x2="148.93" y2="63.47" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#b0d939"/><stop offset="1" stop-color="#eadb04"/></linearGradient><linearGradient id="f" x1="-4163.25" y1="2285.12" x2="-4160.81" y2="2215.34" gradientTransform="rotate(20 4088.49 13316.712)" gradientUnits="userSpaceOnUse"><stop offset=".17" stop-color="#74af52"/><stop offset=".48" stop-color="#99be32"/><stop offset="1" stop-color="#c0c40a"/></linearGradient><symbol id="g" viewBox="0 0 160 187.74"><path style="fill:url(#a)" d="M79.32 36.98v150.76L95 174.54l6.59-156.31-22.27 18.75z"/><path style="fill:url(#b)" d="M79.32 36.98 57.05 18.23l6.59 156.31 15.68 13.2V36.98z"/><path style="fill:url(#c)" d="m25.19 104.83 8.63 49.04 12.5-14.95-2.46-56.42-18.67 22.33z"/><path style="fill:url(#d)" d="M25.19 104.83 0 90.24l16.97 53.86 16.85 9.77-8.63-49.04z"/><path style="fill:#9c3" d="M43.86 82.5 18.69 67.98 0 90.24l25.18 14.59L43.86 82.5z"/><path style="fill:url(#e)" d="m134.82 78.69-9.97 56.5 15.58-9.04L160 64.1l-25.18 14.59z"/><path style="fill:url(#f)" d="m134.82 78.69-18.68-22.33-2.86 65 11.57 13.83 9.97-56.5z"/><path style="fill:#ffe113" d="m160 64.1-18.69-22.26-25.17 14.52 18.67 22.33L160 64.1z"/><path style="fill:#f3e600" d="M101.59 18.23 79.32 0 57.05 18.23l22.27 18.75 22.27-18.75z"/></symbol></defs><use width="160" height="187.74" xlink:href="#g"/></svg>',kO=btoa(OO),MO="data:image/svg+xml;base64,"+kO,eb=MO,RO=`<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN' 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'> <svg clip-rule="evenodd" fill-rule="evenodd" stroke-linejoin="round" stroke-miterlimit="2" version="1.1" viewBox="0 0 1014 282" xml:space="preserve" xmlns="http://www.w3.org/2000/svg"> <g transform="matrix(1.008 0 0 1.008 -2.239 .61874)"> <path d="m665.95 132.73v44.88l-10.56-8.4c-0.8-0.64-1.2-1.44-1.2-2.4v-32.4c0-6.48-4.12-9.72-12.36-9.72-2.16 0-4.18 0.4-6.06 1.2s-3.54 1.8-4.98 3-2.56 2.5-3.36 3.9-1.2 2.7-1.2 3.9v40.92l-10.68-8.4c-0.72-0.64-1.08-1.44-1.08-2.4v-53.76l10.92 8.52c0.32 0.24 0.56 0.44 0.72 0.6s0.36 0.32 0.6 0.48c0.96-1.2 2.14-2.28 3.54-3.24s2.92-1.76 4.56-2.4 3.34-1.14 5.1-1.5 3.44-0.54 5.04-0.54c1.44 0 2.92 0.04 4.44 0.12s2.84 0.28 3.96 0.6c4.56 1.12 7.8 3.12 9.72 6s2.88 6.56 2.88 11.04z" fill-rule="nonzero"/> </g> <g transform="matrix(1.008 0 0 1.008 -2.239 .61874)"> <path d="m732.38 146.05c0 0.88 0.02 1.5 0.06 1.86s-0.02 0.98-0.18 1.86h-7.08c-2.08 0-4.44-0.02-7.08-0.06s-5.36-0.06-8.16-0.06h-22.08c0 2.88 0.56 5.36 1.68 7.44s2.6 3.8 4.44 5.16 3.94 2.36 6.3 3 4.74 0.96 7.14 0.96c3.04 0 5.9-0.76 8.58-2.28s4.94-3.52 6.78-6c0.64 0.56 1.54 1.48 2.7 2.76s2.94 3.2 5.34 5.76c-2.8 3.36-6.22 6.02-10.26 7.98s-8.42 2.94-13.14 2.94-8.92-0.64-12.84-1.92-7.32-3.24-10.2-5.88-5.12-5.98-6.72-10.02-2.4-8.82-2.4-14.34c0-4.96 0.66-9.42 1.98-13.38s3.22-7.32 5.7-10.08 5.44-4.9 8.88-6.42 7.32-2.28 11.64-2.28c5.76 0 10.52 0.88 14.28 2.64s6.72 4.16 8.88 7.2 3.66 6.54 4.5 10.5 1.26 8.18 1.26 12.66zm-29.4-22.8c-2.16 0.16-4.16 0.72-6 1.68s-3.42 2.2-4.74 3.72-2.36 3.28-3.12 5.28-1.14 4.12-1.14 6.36h33.12c0-2-0.22-4.06-0.66-6.18s-1.3-4.02-2.58-5.7-3.1-3.02-5.46-4.02-5.5-1.38-9.42-1.14z" fill-rule="nonzero"/> </g> <g transform="matrix(1.008 0 0 1.008 -2.239 .61874)"> <path d="m795.93 146.05c0 0.88 0.02 1.5 0.06 1.86s-0.02 0.98-0.18 1.86h-7.08c-2.08 0-4.44-0.02-7.08-0.06s-5.36-0.06-8.16-0.06h-22.08c0 2.88 0.56 5.36 1.68 7.44s2.6 3.8 4.44 5.16 3.94 2.36 6.3 3 4.74 0.96 7.14 0.96c3.04 0 5.9-0.76 8.58-2.28s4.94-3.52 6.78-6c0.64 0.56 1.54 1.48 2.7 2.76s2.94 3.2 5.34 5.76c-2.8 3.36-6.22 6.02-10.26 7.98s-8.42 2.94-13.14 2.94-8.92-0.64-12.84-1.92-7.32-3.24-10.2-5.88-5.12-5.98-6.72-10.02-2.4-8.82-2.4-14.34c0-4.96 0.66-9.42 1.98-13.38s3.22-7.32 5.7-10.08 5.44-4.9 8.88-6.42 7.32-2.28 11.64-2.28c5.76 0 10.52 0.88 14.28 2.64s6.72 4.16 8.88 7.2 3.66 6.54 4.5 10.5 1.26 8.18 1.26 12.66zm-29.4-22.8c-2.16 0.16-4.16 0.72-6 1.68s-3.42 2.2-4.74 3.72-2.36 3.28-3.12 5.28-1.14 4.12-1.14 6.36h33.12c0-2-0.22-4.06-0.66-6.18s-1.3-4.02-2.58-5.7-3.1-3.02-5.46-4.02-5.5-1.38-9.42-1.14z" fill-rule="nonzero"/> </g> <g transform="matrix(1.008 0 0 1.008 -2.239 .61874)"> <path d="m858.57 97.21c0.64 0.48 0.96 1.16 0.96 2.04v74.88c-0.08 1.04-0.12 2.12-0.12 3.24-1.84-1.52-3.56-2.92-5.16-4.2-1.36-1.12-2.66-2.18-3.9-3.18s-2.06-1.66-2.46-1.98c-1.76 2.48-4.26 4.44-7.5 5.88s-7.02 2.16-11.34 2.16c-3.84 0-7.4-0.7-10.68-2.1s-6.14-3.44-8.58-6.12-4.34-5.94-5.7-9.78-2.04-8.16-2.04-12.96c0-4.32 0.78-8.34 2.34-12.06s3.6-6.92 6.12-9.6 5.38-4.78 8.58-6.3 6.48-2.28 9.84-2.28c2.56 0 4.82 0.22 6.78 0.66s3.68 1.06 5.16 1.86 2.78 1.74 3.9 2.82 2.16 2.22 3.12 3.42v-35.04l10.68 8.64zm-27.96 67.92c3.6 0 6.52-0.68 8.76-2.04s3.98-3.06 5.22-5.1 2.1-4.22 2.58-6.54 0.72-4.44 0.72-6.36v-1.2c0-1.12-0.22-2.7-0.66-4.74s-1.28-4.06-2.52-6.06-3-3.7-5.28-5.1-5.22-2.02-8.82-1.86c-3.44 0-6.26 0.74-8.46 2.22s-3.96 3.26-5.28 5.34-2.24 4.2-2.76 6.36-0.78 3.92-0.78 5.28c0 1.84 0.24 3.92 0.72 6.24s1.36 4.48 2.64 6.48 3.04 3.68 5.28 5.04 5.12 2.04 8.64 2.04z" fill-rule="nonzero"/> </g> <g transform="matrix(1.008 0 0 1.008 -2.239 .61874)"> <path d="m882.81 97.09c0.64 0.48 0.96 1.12 0.96 1.92l-0.12 41.04v37.08l-10.56-8.4c-0.72-0.64-1.08-1.44-1.08-2.4v-77.88l10.8 8.64z" fill-rule="nonzero"/> </g> <g transform="matrix(1.008 0 0 1.008 -2.239 .61874)"> <path d="m950.36 146.05c0 0.88 0.02 1.5 0.06 1.86s-0.02 0.98-0.18 1.86h-7.08c-2.08 0-4.44-0.02-7.08-0.06s-5.36-0.06-8.16-0.06h-22.08c0 2.88 0.56 5.36 1.68 7.44s2.6 3.8 4.44 5.16 3.94 2.36 6.3 3 4.74 0.96 7.14 0.96c3.04 0 5.9-0.76 8.58-2.28s4.94-3.52 6.78-6c0.64 0.56 1.54 1.48 2.7 2.76s2.94 3.2 5.34 5.76c-2.8 3.36-6.22 6.02-10.26 7.98s-8.42 2.94-13.14 2.94-8.92-0.64-12.84-1.92-7.32-3.24-10.2-5.88-5.12-5.98-6.72-10.02-2.4-8.82-2.4-14.34c0-4.96 0.66-9.42 1.98-13.38s3.22-7.32 5.7-10.08 5.44-4.9 8.88-6.42 7.32-2.28 11.64-2.28c5.76 0 10.52 0.88 14.28 2.64s6.72 4.16 8.88 7.2 3.66 6.54 4.5 10.5 1.26 8.18 1.26 12.66zm-29.4-22.8c-2.16 0.16-4.16 0.72-6 1.68s-3.42 2.2-4.74 3.72-2.36 3.28-3.12 5.28-1.14 4.12-1.14 6.36h33.12c0-2-0.22-4.06-0.66-6.18s-1.3-4.02-2.58-5.7-3.1-3.02-5.46-4.02-5.5-1.38-9.42-1.14z" fill-rule="nonzero"/> </g> <g transform="matrix(1.8559 0 0 .7642 45.348 36.475)"> <g transform="translate(2.7114)"> <path d="m3.935 173.02c-0.331 0-0.497-0.402-0.497-1.207v-51.002c0-0.738 0.138-1.107 0.414-1.107h1.781c0.277 0 0.415 0.335 0.415 1.006v5.935c0 0.336 0.027 0.553 0.083 0.654 0.055 0.101 0.151-0.017 0.289-0.352 0.912-1.744 1.754-3.236 2.527-4.477 0.773-1.24 1.554-2.179 2.341-2.816s1.65-0.956 2.588-0.956c1.685 0 3.011 0.922 3.977 2.766 0.967 1.845 1.602 3.84 1.905 5.986 0.056 0.268 0.139 0.369 0.249 0.302s0.221-0.235 0.331-0.503c0.939-1.811 1.802-3.353 2.589-4.628 0.787-1.274 1.581-2.246 2.382-2.917s1.671-1.006 2.61-1.006c2.016 0 3.569 1.392 4.66 4.175 1.09 2.783 1.636 6.421 1.636 10.915v37.925c0 0.871-0.18 1.307-0.539 1.307h-1.739c-0.138 0-0.249-0.1-0.332-0.301-0.083-0.202-0.124-0.503-0.124-0.906v-36.315c0-3.555-0.338-6.321-1.015-8.3-0.676-1.978-1.76-2.967-3.251-2.967-0.884 0-1.726 0.386-2.527 1.157s-1.519 1.727-2.154 2.867-1.201 2.213-1.699 3.219c-0.248 0.469-0.421 0.905-0.517 1.308-0.097 0.402-0.145 0.972-0.145 1.71v37.221c0 0.871-0.166 1.307-0.497 1.307h-1.74c-0.166 0-0.29-0.1-0.373-0.301-0.083-0.202-0.124-0.503-0.124-0.906v-36.315c0-3.555-0.332-6.321-0.994-8.3-0.663-1.978-1.754-2.967-3.273-2.967-1.242 0-2.375 0.704-3.396 2.112-1.022 1.409-2.223 3.555-3.604 6.439v39.031c0 0.805-0.18 1.207-0.539 1.207h-1.698z" fill-rule="nonzero" stroke="#000" stroke-width=".7px"/> </g> <g transform="translate(2.7114)"> <path d="m53.642 166.28c-1.077 2.549-2.237 4.477-3.479 5.785-1.243 1.307-2.61 1.961-4.101 1.961-2.154 0-3.853-1.324-5.095-3.973-1.243-2.649-1.864-6.187-1.864-10.613 0-3.488 0.4-6.489 1.201-9.004s1.988-4.51 3.562-5.985c1.574-1.476 3.521-2.414 5.841-2.817l3.686-0.704c0.221-0.067 0.394-0.218 0.518-0.453 0.124-0.234 0.187-0.587 0.187-1.056v-2.917c0-3.89-0.504-6.975-1.512-9.255s-2.354-3.42-4.039-3.42c-1.298 0-2.472 0.72-3.521 2.162s-2.002 3.572-2.858 6.388c-0.083 0.268-0.159 0.453-0.228 0.554-0.069 0.1-0.172 0.083-0.311-0.051l-1.698-1.71c-0.083-0.134-0.138-0.285-0.166-0.453-0.027-0.167 0.014-0.452 0.125-0.855 0.856-3.353 2.009-6.052 3.459-8.098 1.449-2.045 3.224-3.068 5.322-3.068 1.74 0 3.211 0.687 4.412 2.062s2.112 3.37 2.734 5.986c0.621 2.615 0.932 5.7 0.932 9.255v35.712c0 0.536-0.035 0.888-0.104 1.056s-0.2 0.251-0.393 0.251h-1.533c-0.166 0-0.29-0.117-0.373-0.352-0.083-0.234-0.124-0.553-0.124-0.955l-0.083-5.231c-0.055-0.939-0.221-1.006-0.497-0.202zm0.456-19.314c0-1.14-0.194-1.643-0.58-1.509l-3.107 0.603c-1.436 0.202-2.686 0.638-3.749 1.308-1.063 0.671-1.953 1.543-2.671 2.616s-1.257 2.33-1.616 3.772-0.538 3.102-0.538 4.98c0 3.152 0.455 5.616 1.367 7.393 0.911 1.778 2.14 2.666 3.686 2.666 0.939 0 1.85-0.419 2.734-1.257s1.671-1.895 2.361-3.169c0.663-1.408 1.181-2.85 1.553-4.326 0.373-1.475 0.56-2.883 0.56-4.225v-8.852z" fill-rule="nonzero" stroke="#000" stroke-width=".7px"/> </g> <g transform="translate(2.7114)"> <path d="m79.034 173.02c-0.166 0-0.297-0.117-0.394-0.352-0.096-0.234-0.145-0.553-0.145-0.955v-4.628c0-0.536-0.041-0.838-0.124-0.905s-0.207 0.1-0.373 0.503c-0.276 0.67-0.69 1.593-1.242 2.766-0.553 1.174-1.271 2.23-2.154 3.169-0.884 0.939-1.961 1.408-3.231 1.408-1.74 0-3.314-0.989-4.722-2.967-1.409-1.979-2.534-4.963-3.376-8.953-0.843-3.991-1.264-8.937-1.264-14.838 0-5.701 0.415-10.68 1.243-14.939s1.988-7.595 3.479-10.009c1.492-2.415 3.204-3.622 5.137-3.622 1.436 0 2.616 0.57 3.541 1.71 0.926 1.14 1.719 2.381 2.382 3.722 0.249 0.47 0.414 0.637 0.497 0.503s0.125-0.536 0.125-1.207v-23.841c0-0.805 0.151-1.208 0.455-1.208h1.864c0.276 0 0.414 0.369 0.414 1.107v72.128c0 0.537-0.041 0.905-0.124 1.107-0.083 0.201-0.235 0.301-0.455 0.301h-1.533zm-0.621-42.049c-0.939-2.213-1.885-3.94-2.838-5.181s-2.009-1.861-3.169-1.861c-1.463 0-2.768 0.889-3.914 2.666s-2.044 4.376-2.693 7.796-0.973 7.578-0.973 12.474c0 5.097 0.338 9.272 1.015 12.524 0.676 3.253 1.567 5.651 2.672 7.193 1.104 1.543 2.305 2.314 3.603 2.314 1.188 0 2.258-0.704 3.211-2.113 0.952-1.408 1.705-3.118 2.257-5.13s0.829-3.957 0.829-5.835v-24.847z" fill-rule="nonzero" stroke="#000" stroke-width=".7px"/> </g> <g transform="translate(2.7114)"> <path d="m89.514 149.38c0 3.42 0.345 6.606 1.035 9.557 0.691 2.951 1.609 5.315 2.755 7.092s2.437 2.666 3.873 2.666c1.519 0 2.837-0.738 3.956-2.213 1.118-1.476 2.064-3.655 2.837-6.539 0.083-0.336 0.166-0.52 0.249-0.554 0.083-0.033 0.179 0.017 0.29 0.151l1.408 1.912c0.221 0.268 0.235 0.67 0.041 1.207-0.69 2.548-1.47 4.661-2.34 6.337-0.87 1.677-1.857 2.935-2.962 3.773-1.104 0.838-2.319 1.257-3.645 1.257-2.043 0-3.838-1.14-5.385-3.42-1.546-2.28-2.761-5.482-3.645-9.607-0.884-4.124-1.325-8.836-1.325-14.134 0-5.901 0.455-10.931 1.367-15.089 0.911-4.158 2.14-7.377 3.686-9.658 1.547-2.28 3.3-3.42 5.261-3.42 1.988 0 3.714 1.073 5.178 3.219 1.463 2.146 2.595 5.231 3.396 9.255s1.201 8.886 1.201 14.587c0 0.469-0.02 0.939-0.062 1.408-0.041 0.469-0.214 0.704-0.517 0.704h-16.362c-0.083 0-0.152 0.151-0.207 0.453-0.056 0.302-0.083 0.654-0.083 1.056zm13.752-6.237c0.304 0 0.497-0.1 0.58-0.302 0.083-0.201 0.124-0.57 0.124-1.106 0-3.219-0.283-6.187-0.849-8.903s-1.367-4.896-2.402-6.539c-1.036-1.643-2.272-2.464-3.708-2.464-1.629 0-2.996 0.955-4.101 2.867-1.104 1.911-1.94 4.342-2.506 7.293s-0.849 6.002-0.849 9.154h13.711z" fill-rule="nonzero" stroke="#000" stroke-width=".7px"/> </g> <g transform="translate(2.7114)"> <path d="m148.54 119.7c0.165 0 0.283 0.117 0.352 0.352s0.076 0.52 0.02 0.855l-6.254 50.902c-0.028 0.47-0.104 0.788-0.228 0.956s-0.297 0.251-0.518 0.251h-1.615c-0.442 0-0.718-0.402-0.829-1.207l-5.26-40.138c-0.111-0.604-0.201-0.905-0.27-0.905s-0.131 0.301-0.186 0.905l-5.012 40.138c-0.028 0.47-0.097 0.788-0.207 0.956-0.111 0.168-0.277 0.251-0.497 0.251h-1.74c-0.442 0-0.718-0.402-0.829-1.207l-6.503-50.801c-0.055-0.403-0.048-0.721 0.021-0.956s0.2-0.352 0.393-0.352h1.823c0.166 0 0.297 0.067 0.393 0.201 0.097 0.134 0.159 0.403 0.187 0.805l5.302 41.848c0.083 0.671 0.179 0.989 0.29 0.956 0.11-0.034 0.207-0.386 0.29-1.056l5.219-41.949c0.055-0.268 0.124-0.47 0.207-0.604s0.193-0.201 0.331-0.201h1.533c0.138 0 0.262 0.067 0.373 0.201 0.11 0.134 0.179 0.403 0.207 0.805l5.468 41.848c0.083 0.671 0.179 0.989 0.29 0.956 0.11-0.034 0.207-0.386 0.29-1.056l5.053-41.849c0.055-0.335 0.138-0.57 0.249-0.704 0.11-0.134 0.234-0.201 0.373-0.201h1.284z" fill-rule="nonzero" stroke="#000" stroke-width=".7px"/> </g> <g transform="translate(2.7114)"> <path d="m156.49 171.51c0 0.604-0.042 1.006-0.125 1.208-0.082 0.201-0.262 0.301-0.538 0.301h-1.533c-0.221 0-0.366-0.083-0.435-0.251s-0.103-0.486-0.103-0.956v-50.902c0-0.805 0.152-1.207 0.456-1.207h1.822c0.304 0 0.456 0.402 0.456 1.207v50.6zm0.165-63.979c0 1.207-0.207 1.811-0.621 1.811h-1.905c-0.221 0-0.366-0.135-0.435-0.403s-0.104-0.67-0.104-1.207v-7.847c0-1.006 0.18-1.509 0.539-1.509h1.988c0.359 0 0.538 0.47 0.538 1.409v7.746z" fill-rule="nonzero" stroke="#000" stroke-width=".7px"/> </g> <g transform="translate(2.7114)"> <path d="m168.3 124.83c-0.221 0-0.331 0.269-0.331 0.805v33.801c0 3.42 0.221 5.667 0.663 6.74 0.441 1.073 1.09 1.609 1.946 1.609h3.024c0.138 0 0.242 0.084 0.311 0.252 0.069 0.167 0.103 0.419 0.103 0.754v2.716c0 0.537-0.138 0.906-0.414 1.107-0.248 0.067-0.614 0.134-1.098 0.201-0.483 0.067-0.959 0.118-1.429 0.151-0.469 0.034-0.828 0.05-1.077 0.05-1.712 0-2.934-0.955-3.665-2.867-0.732-1.911-1.098-5.013-1.098-9.305v-35.108c0-0.604-0.124-0.906-0.373-0.906h-3.521c-0.248 0-0.373-0.268-0.373-0.804v-3.521c0-0.537 0.111-0.805 0.332-0.805h3.686c0.166 0 0.263-0.268 0.29-0.805l0.415-16.095c0-0.805 0.124-1.207 0.372-1.207h1.492c0.303 0 0.455 0.436 0.455 1.307v15.995c0 0.537 0.097 0.805 0.29 0.805h5.468c0.221 0 0.331 0.268 0.331 0.805v3.521c0 0.536-0.124 0.804-0.373 0.804h-5.426z" fill-rule="nonzero" stroke="#000" stroke-width=".7px"/> </g> <g transform="translate(2.7114)"> <path d="m179.4 173.02c-0.331 0-0.497-0.402-0.497-1.207v-72.329c0-0.738 0.138-1.107 0.414-1.107h1.782c0.276 0 0.414 0.336 0.414 1.006v27.162c0 0.335 0.034 0.536 0.103 0.603s0.159-0.033 0.27-0.302c0.994-1.81 1.898-3.319 2.713-4.526 0.814-1.208 1.629-2.113 2.444-2.717 0.814-0.603 1.691-0.905 2.63-0.905 2.182 0 3.839 1.375 4.971 4.125 1.132 2.749 1.698 6.404 1.698 10.965v37.925c0 0.871-0.166 1.307-0.497 1.307h-1.74c-0.165 0-0.29-0.1-0.373-0.301-0.082-0.202-0.124-0.503-0.124-0.906v-36.315c0-3.555-0.366-6.321-1.097-8.3-0.732-1.978-1.899-2.967-3.501-2.967-0.883 0-1.705 0.318-2.464 0.956-0.76 0.637-1.526 1.576-2.299 2.816-0.773 1.241-1.643 2.834-2.61 4.779v39.031c0 0.805-0.179 1.207-0.538 1.207h-1.699z" fill-rule="nonzero" stroke="#000" stroke-width=".7px"/> </g> </g> <g transform="matrix(.80638 0 0 .80638 452.53 65.421)" fill-rule="nonzero"> <path d="m79.32 36.98v150.76l15.68-13.2 6.59-156.31-22.27 18.75z" fill="url(#f)"/> <path d="m79.32 36.98-22.27-18.75 6.59 156.31 15.68 13.2v-150.76z" fill="url(#e)"/> <path d="m25.19 104.83 8.63 49.04 12.5-14.95-2.46-56.42-18.67 22.33z" fill="url(#d)"/> <path d="m25.19 104.83-25.19-14.59 16.97 53.86 16.85 9.77-8.63-49.04z" fill="url(#c)"/> <path d="M43.86,82.5L18.69,67.98L0,90.24L25.18,104.83L43.86,82.5Z" fill="#9c3"/> <path d="m134.82 78.69-9.97 56.5 15.58-9.04 19.57-62.05-25.18 14.59z" fill="url(#b)"/> <path d="m134.82 78.69-18.68-22.33-2.86 65 11.57 13.83 9.97-56.5z" fill="url(#a)"/> <path d="m160 64.1-18.69-22.26-25.17 14.52 18.67 22.33 25.19-14.59z" fill="#ffe113"/> <path d="M101.59,18.23L79.32,0L57.05,18.23L79.32,36.98L101.59,18.23Z" fill="#f3e600"/> </g> <defs> <linearGradient id="f" x2="1" gradientTransform="matrix(.84 -162.96 162.96 .84 89.64 184.81)" gradientUnits="userSpaceOnUse"><stop stop-color="#62d399" offset="0"/><stop stop-color="#acd842" offset=".51"/><stop stop-color="#d7db0a" offset=".9"/><stop stop-color="#d7db0a" offset="1"/></linearGradient> <linearGradient id="e" x2="1" gradientTransform="matrix(-1.6,-162.13,162.13,-1.6,69.68,178.9)" gradientUnits="userSpaceOnUse"><stop stop-color="#0ba398" offset="0"/><stop stop-color="#4ca352" offset=".5"/><stop stop-color="#76a30a" offset="1"/></linearGradient> <linearGradient id="d" x2="1" gradientTransform="matrix(-1.9,-67.98,67.98,-1.9,36.6,152.17)" gradientUnits="userSpaceOnUse"><stop stop-color="#36a382" offset="0"/><stop stop-color="#36a382" offset=".19"/><stop stop-color="#49a459" offset=".54"/><stop stop-color="#76a30b" offset="1"/></linearGradient> <linearGradient id="c" x2="1" gradientTransform="matrix(2.18,-62.38,62.38,2.18,15.82,153.24)" gradientUnits="userSpaceOnUse"><stop stop-color="#267880" offset="0"/><stop stop-color="#457a5c" offset=".51"/><stop stop-color="#717516" offset="1"/></linearGradient> <linearGradient id="b" x2="1" gradientTransform="matrix(13.85,-71.96,71.96,13.85,135.08,135.43)" gradientUnits="userSpaceOnUse"><stop stop-color="#b0d939" offset="0"/><stop stop-color="#eadb04" offset="1"/></linearGradient> <linearGradient id="a" x2="1" gradientTransform="matrix(26.159 -64.737 64.737 26.159 107.42 128.14)" gradientUnits="userSpaceOnUse"><stop stop-color="#74af52" offset="0"/><stop stop-color="#74af52" offset=".17"/><stop stop-color="#99be32" offset=".48"/><stop stop-color="#c0c40a" offset="1"/></linearGradient> </defs> </svg>`;btoa(RO);const TO='<svg viewBox="0 0 509 154" xmlns="http://www.w3.org/2000/svg" xml:space="preserve" style="fill-rule:evenodd;clip-rule:evenodd;stroke-linejoin:round;stroke-miterlimit:2"><path d="M665.95 132.73v44.88l-10.56-8.4c-.8-.64-1.2-1.44-1.2-2.4v-32.4c0-6.48-4.12-9.72-12.36-9.72-2.16 0-4.18.4-6.06 1.2-1.88.8-3.54 1.8-4.98 3-1.44 1.2-2.56 2.5-3.36 3.9-.8 1.4-1.2 2.7-1.2 3.9v40.92l-10.68-8.4c-.72-.64-1.08-1.44-1.08-2.4v-53.76l10.92 8.52c.32.24.56.44.72.6.16.16.36.32.6.48.96-1.2 2.14-2.28 3.54-3.24 1.4-.96 2.92-1.76 4.56-2.4 1.64-.64 3.34-1.14 5.1-1.5 1.76-.36 3.44-.54 5.04-.54 1.44 0 2.92.04 4.44.12 1.52.08 2.84.28 3.96.6 4.56 1.12 7.8 3.12 9.72 6 1.92 2.88 2.88 6.56 2.88 11.04ZM732.38 146.05c0 .88.02 1.5.06 1.86.04.36-.02.98-.18 1.86h-7.08c-2.08 0-4.44-.02-7.08-.06-2.64-.04-5.36-.06-8.16-.06h-22.08c0 2.88.56 5.36 1.68 7.44 1.12 2.08 2.6 3.8 4.44 5.16 1.84 1.36 3.94 2.36 6.3 3 2.36.64 4.74.96 7.14.96 3.04 0 5.9-.76 8.58-2.28 2.68-1.52 4.94-3.52 6.78-6 .64.56 1.54 1.48 2.7 2.76 1.16 1.28 2.94 3.2 5.34 5.76-2.8 3.36-6.22 6.02-10.26 7.98-4.04 1.96-8.42 2.94-13.14 2.94-4.72 0-8.92-.64-12.84-1.92-3.92-1.28-7.32-3.24-10.2-5.88-2.88-2.64-5.12-5.98-6.72-10.02-1.6-4.04-2.4-8.82-2.4-14.34 0-4.96.66-9.42 1.98-13.38 1.32-3.96 3.22-7.32 5.7-10.08s5.44-4.9 8.88-6.42c3.44-1.52 7.32-2.28 11.64-2.28 5.76 0 10.52.88 14.28 2.64 3.76 1.76 6.72 4.16 8.88 7.2 2.16 3.04 3.66 6.54 4.5 10.5.84 3.96 1.26 8.18 1.26 12.66Zm-29.4-22.8c-2.16.16-4.16.72-6 1.68-1.84.96-3.42 2.2-4.74 3.72-1.32 1.52-2.36 3.28-3.12 5.28-.76 2-1.14 4.12-1.14 6.36h33.12c0-2-.22-4.06-.66-6.18-.44-2.12-1.3-4.02-2.58-5.7-1.28-1.68-3.1-3.02-5.46-4.02-2.36-1-5.5-1.38-9.42-1.14ZM795.93 146.05c0 .88.02 1.5.06 1.86.04.36-.02.98-.18 1.86h-7.08c-2.08 0-4.44-.02-7.08-.06-2.64-.04-5.36-.06-8.16-.06h-22.08c0 2.88.56 5.36 1.68 7.44 1.12 2.08 2.6 3.8 4.44 5.16 1.84 1.36 3.94 2.36 6.3 3 2.36.64 4.74.96 7.14.96 3.04 0 5.9-.76 8.58-2.28 2.68-1.52 4.94-3.52 6.78-6 .64.56 1.54 1.48 2.7 2.76 1.16 1.28 2.94 3.2 5.34 5.76-2.8 3.36-6.22 6.02-10.26 7.98-4.04 1.96-8.42 2.94-13.14 2.94-4.72 0-8.92-.64-12.84-1.92-3.92-1.28-7.32-3.24-10.2-5.88-2.88-2.64-5.12-5.98-6.72-10.02-1.6-4.04-2.4-8.82-2.4-14.34 0-4.96.66-9.42 1.98-13.38 1.32-3.96 3.22-7.32 5.7-10.08s5.44-4.9 8.88-6.42c3.44-1.52 7.32-2.28 11.64-2.28 5.76 0 10.52.88 14.28 2.64 3.76 1.76 6.72 4.16 8.88 7.2 2.16 3.04 3.66 6.54 4.5 10.5.84 3.96 1.26 8.18 1.26 12.66Zm-29.4-22.8c-2.16.16-4.16.72-6 1.68-1.84.96-3.42 2.2-4.74 3.72-1.32 1.52-2.36 3.28-3.12 5.28-.76 2-1.14 4.12-1.14 6.36h33.12c0-2-.22-4.06-.66-6.18-.44-2.12-1.3-4.02-2.58-5.7-1.28-1.68-3.1-3.02-5.46-4.02-2.36-1-5.5-1.38-9.42-1.14ZM858.57 97.21c.64.48.96 1.16.96 2.04v74.88c-.08 1.04-.12 2.12-.12 3.24-1.84-1.52-3.56-2.92-5.16-4.2-1.36-1.12-2.66-2.18-3.9-3.18-1.24-1-2.06-1.66-2.46-1.98-1.76 2.48-4.26 4.44-7.5 5.88-3.24 1.44-7.02 2.16-11.34 2.16-3.84 0-7.4-.7-10.68-2.1-3.28-1.4-6.14-3.44-8.58-6.12-2.44-2.68-4.34-5.94-5.7-9.78-1.36-3.84-2.04-8.16-2.04-12.96 0-4.32.78-8.34 2.34-12.06 1.56-3.72 3.6-6.92 6.12-9.6 2.52-2.68 5.38-4.78 8.58-6.3 3.2-1.52 6.48-2.28 9.84-2.28 2.56 0 4.82.22 6.78.66 1.96.44 3.68 1.06 5.16 1.86s2.78 1.74 3.9 2.82a35.92 35.92 0 0 1 3.12 3.42V88.57l10.68 8.64Zm-27.96 67.92c3.6 0 6.52-.68 8.76-2.04 2.24-1.36 3.98-3.06 5.22-5.1a20.5 20.5 0 0 0 2.58-6.54c.48-2.32.72-4.44.72-6.36v-1.2c0-1.12-.22-2.7-.66-4.74-.44-2.04-1.28-4.06-2.52-6.06s-3-3.7-5.28-5.1c-2.28-1.4-5.22-2.02-8.82-1.86-3.44 0-6.26.74-8.46 2.22-2.2 1.48-3.96 3.26-5.28 5.34-1.32 2.08-2.24 4.2-2.76 6.36-.52 2.16-.78 3.92-.78 5.28 0 1.84.24 3.92.72 6.24.48 2.32 1.36 4.48 2.64 6.48s3.04 3.68 5.28 5.04c2.24 1.36 5.12 2.04 8.64 2.04ZM882.81 97.09c.64.48.96 1.12.96 1.92l-.12 41.04v37.08l-10.56-8.4c-.72-.64-1.08-1.44-1.08-2.4V88.45l10.8 8.64ZM950.36 146.05c0 .88.02 1.5.06 1.86.04.36-.02.98-.18 1.86h-7.08c-2.08 0-4.44-.02-7.08-.06-2.64-.04-5.36-.06-8.16-.06h-22.08c0 2.88.56 5.36 1.68 7.44 1.12 2.08 2.6 3.8 4.44 5.16 1.84 1.36 3.94 2.36 6.3 3 2.36.64 4.74.96 7.14.96 3.04 0 5.9-.76 8.58-2.28 2.68-1.52 4.94-3.52 6.78-6 .64.56 1.54 1.48 2.7 2.76 1.16 1.28 2.94 3.2 5.34 5.76-2.8 3.36-6.22 6.02-10.26 7.98-4.04 1.96-8.42 2.94-13.14 2.94-4.72 0-8.92-.64-12.84-1.92-3.92-1.28-7.32-3.24-10.2-5.88-2.88-2.64-5.12-5.98-6.72-10.02-1.6-4.04-2.4-8.82-2.4-14.34 0-4.96.66-9.42 1.98-13.38 1.32-3.96 3.22-7.32 5.7-10.08s5.44-4.9 8.88-6.42c3.44-1.52 7.32-2.28 11.64-2.28 5.76 0 10.52.88 14.28 2.64 3.76 1.76 6.72 4.16 8.88 7.2 2.16 3.04 3.66 6.54 4.5 10.5.84 3.96 1.26 8.18 1.26 12.66Zm-29.4-22.8c-2.16.16-4.16.72-6 1.68-1.84.96-3.42 2.2-4.74 3.72-1.32 1.52-2.36 3.28-3.12 5.28-.76 2-1.14 4.12-1.14 6.36h33.12c0-2-.22-4.06-.66-6.18-.44-2.12-1.3-4.02-2.58-5.7-1.28-1.68-3.1-3.02-5.46-4.02-2.36-1-5.5-1.38-9.42-1.14Z" style="fill-rule:nonzero" transform="translate(-452.406 -63.709) scale(1.00797)"/><path d="M79.32 36.98v150.76L95 174.54l6.59-156.31-22.27 18.75Z" style="fill:url(#a);fill-rule:nonzero" transform="matrix(.80638 0 0 .80638 2.361 1.094)"/><path d="M79.32 36.98 57.05 18.23l6.59 156.31 15.68 13.2V36.98Z" style="fill:url(#b);fill-rule:nonzero" transform="matrix(.80638 0 0 .80638 2.361 1.094)"/><path d="m25.19 104.83 8.63 49.04 12.5-14.95-2.46-56.42-18.67 22.33Z" style="fill:url(#c);fill-rule:nonzero" transform="matrix(.80638 0 0 .80638 2.361 1.094)"/><path d="M25.19 104.83 0 90.24l16.97 53.86 16.85 9.77-8.63-49.04Z" style="fill:url(#d);fill-rule:nonzero" transform="matrix(.80638 0 0 .80638 2.361 1.094)"/><path d="M43.86 82.5 18.69 67.98 0 90.24l25.18 14.59L43.86 82.5Z" style="fill:#9c3;fill-rule:nonzero" transform="matrix(.80638 0 0 .80638 2.361 1.094)"/><path d="m134.82 78.69-9.97 56.5 15.58-9.04L160 64.1l-25.18 14.59Z" style="fill:url(#e);fill-rule:nonzero" transform="matrix(.80638 0 0 .80638 2.361 1.094)"/><path d="m134.82 78.69-18.68-22.33-2.86 65 11.57 13.83 9.97-56.5Z" style="fill:url(#f);fill-rule:nonzero" transform="matrix(.80638 0 0 .80638 2.361 1.094)"/><path d="m160 64.1-18.69-22.26-25.17 14.52 18.67 22.33L160 64.1Z" style="fill:#ffe113;fill-rule:nonzero" transform="matrix(.80638 0 0 .80638 2.361 1.094)"/><path d="M101.59 18.23 79.32 0 57.05 18.23l22.27 18.75 22.27-18.75Z" style="fill:#f3e600;fill-rule:nonzero" transform="matrix(.80638 0 0 .80638 2.361 1.094)"/><defs><linearGradient id="a" x1="0" y1="0" x2="1" y2="0" gradientUnits="userSpaceOnUse" gradientTransform="matrix(.84 -162.96 162.96 .84 89.64 184.81)"><stop offset="0" style="stop-color:#62d399;stop-opacity:1"/><stop offset=".51" style="stop-color:#acd842;stop-opacity:1"/><stop offset=".9" style="stop-color:#d7db0a;stop-opacity:1"/><stop offset="1" style="stop-color:#d7db0a;stop-opacity:1"/></linearGradient><linearGradient id="b" x1="0" y1="0" x2="1" y2="0" gradientUnits="userSpaceOnUse" gradientTransform="rotate(-90.565 123.412 54.953) scale(162.14)"><stop offset="0" style="stop-color:#0ba398;stop-opacity:1"/><stop offset=".5" style="stop-color:#4ca352;stop-opacity:1"/><stop offset="1" style="stop-color:#76a30a;stop-opacity:1"/></linearGradient><linearGradient id="c" x1="0" y1="0" x2="1" y2="0" gradientUnits="userSpaceOnUse" gradientTransform="scale(-68) rotate(88.4 .881 -1.396)"><stop offset="0" style="stop-color:#36a382;stop-opacity:1"/><stop offset=".19" style="stop-color:#36a382;stop-opacity:1"/><stop offset=".54" style="stop-color:#49a459;stop-opacity:1"/><stop offset="1" style="stop-color:#76a30b;stop-opacity:1"/></linearGradient><linearGradient id="d" x1="0" y1="0" x2="1" y2="0" gradientUnits="userSpaceOnUse" gradientTransform="rotate(-88 87.255 68.431) scale(62.42)"><stop offset="0" style="stop-color:#267880;stop-opacity:1"/><stop offset=".51" style="stop-color:#457a5c;stop-opacity:1"/><stop offset="1" style="stop-color:#717516;stop-opacity:1"/></linearGradient><linearGradient id="e" x1="0" y1="0" x2="1" y2="0" gradientUnits="userSpaceOnUse" gradientTransform="rotate(-79.1 149.53 -14.065) scale(73.28)"><stop offset="0" style="stop-color:#b0d939;stop-opacity:1"/><stop offset="1" style="stop-color:#eadb04;stop-opacity:1"/></linearGradient><linearGradient id="f" x1="0" y1="0" x2="1" y2="0" gradientUnits="userSpaceOnUse" gradientTransform="rotate(-67.997 148.705 -15.558) scale(69.8226)"><stop offset="0" style="stop-color:#74af52;stop-opacity:1"/><stop offset=".17" style="stop-color:#74af52;stop-opacity:1"/><stop offset=".48" style="stop-color:#99be32;stop-opacity:1"/><stop offset="1" style="stop-color:#c0c40a;stop-opacity:1"/></linearGradient></defs></svg>',EO=btoa(TO),AO="data:image/svg+xml;charset=utf-8;base64,"+EO,IO=AO,tb=typeof window!==void 0?window.location.search.includes("debugcontext"):!1;var me=(o=>(o.ContextRegistered="ContextRegistered",o.ContextCreationStart="ContextCreationStart",o.ContextCreated="ContextCreated",o.ContextFirstFrameRendered="ContextFirstFrameRendered",o.ContextDestroying="ContextDestroying",o.ContextDestroyed="ContextDestroyed",o.MissingCamera="MissingCamera",o.ContextClearing="ContextClearing",o.ContextCleared="ContextCleared",o))(me||{});class pe{static get Current(){return globalThis["NeedleEngine.Context.Current"]}static set Current(e){globalThis["NeedleEngine.Context.Current"]=e}static get All(){return this.Registered}static register(e){this.Registered.indexOf(e)===-1&&(tb&&console.warn("Registering context"),this.Registered.push(e),this.dispatchCallback("ContextRegistered",e))}static unregister(e){const t=this.Registered.indexOf(e);t!==-1&&(tb&&console.warn("Unregistering context"),this.Registered.splice(t,1))}static registerCallback(e,t){this._callbacks[e]||(this._callbacks[e]=[]),this._callbacks[e].push(t)}static unregisterCallback(e,t){if(!this._callbacks[e])return;const s=this._callbacks[e].indexOf(t);s!==-1&&this._callbacks[e].splice(s,1)}static dispatchCallback(e,t,s){if(!this._callbacks[e])return!0;const n={event:e,context:t};if(s)for(const l in s)n[l]=s[l];const r=new Array;return this._callbacks[e].forEach(l=>{const c=l(n);c instanceof Promise&&r.push(c)}),Promise.all(r)}static addContextCreatedCallback(e){this.registerCallback("ContextCreated",e)}static addContextDestroyedCallback(e){this.registerCallback("ContextDestroyed",e)}}a(pe,"Registered",[]),a(pe,"_callbacks",{});const ib=()=>o=>o;function LO(o){return ib()(o)}function jO(){return!!C("debug")}class Pi{constructor(e,t){a(this,"_factory"),a(this,"_cache",[]),a(this,"_maxSize"),a(this,"_index",0),this._factory=e,this._maxSize=t}get(){const e=this._index%this._maxSize;return this._index++,this._cache.length<=e&&(this._cache[e]=this._factory()),this._cache[e]}}let gr=!1;const Vm=new Array;typeof window<"u"&&setTimeout(()=>{if(gr){const o={},e=new URL(window.location.href),t=new URL(e);t.searchParams.append("console","");const s=t.toString().replace(/=$|=(?=&)/g,"");for(const r of Vm){const l=new URL(e);l.searchParams.append(r,""),o[r]=l.toString().replace(/=$|=(?=&)/g,"")}console.log(`\u{1F335} ?help: Debug Options for Needle Engine.
2
+ Append any of these parameters to the URL to enable specific debug options.
3
+ Example: ${s} will show an onscreen console window.`);const n=gr===!0?"":` (containing "${gr}")`;console.group("Available URL parameters:"+n);for(const r of Object.keys(o).sort())typeof gr=="string"&&!r.toLowerCase().includes(gr.toLowerCase())||(console.groupCollapsed(r),console.log("Reload with this flag enabled:"),console.log(o[r]),console.groupEnd());console.groupEnd()}},100);function Vl(){var o;return new URLSearchParams((o=globalThis.location)==null?void 0:o.search)}function C(o){gr&&!Vm.includes(o)&&Vm.push(o);const e=Vl();if(e.has(o)){const t=e.get(o);if(t){const s=Number(t);return isNaN(s)?t:s}else return!0}return!1}gr=C("help");function DO(o,e){const t=Vl();t.has(o)?t.set(o,e):t.append(o,e),document.location.search=t.toString()}function Hl(o,e,t=!0){const s=Vl();s.has(o)?e===null?s.delete(o):s.set(o,e):e!==null&&s.append(o,e),t?sb(o,s):$m(o,s)}function Hm(o,e,t){o.has(e)?o.set(e,t.toString()):o.append(e,t.toString())}function sb(o,e,t){window.history.pushState(t,o,"?"+e.toString())}function $m(o,e,t){window.history.replaceState(t,o,"?"+e.toString())}function BO(o){for(var e="",t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",s=t.length,n=0;n<o;n++)e+=t.charAt(Math.floor(Math.random()*s));return e}function FO(o,e){return Math.floor(Math.random()*(e-o+1))+o}const nb=["smol","tiny","giant","interesting","smart","bright","dull","extreme","beautiful","pretty","dark","epic","salty","silly","funny","lame","lazy","loud","lucky","mad","mean","mighty","mysterious","nasty","odd","old","powerful","quiet","rapid","scary","shiny","shy","silly","smooth","sour","spicy","stupid","sweet","tasty","terrible","ugly","unusual","vast","wet","wild","witty","wrong","zany","zealous","zippy","zombie","zorro"],ob=["cat","dog","mouse","pig","cow","horse","sheep","chicken","duck","goat","panda","tiger","lion","elephant","monkey","bird","fish","snake","frog","turtle","hamster","penguin","kangaroo","whale","dolphin","crocodile","snail","ant","bee","beetle","butterfly","dragon","eagle","fish","giraffe","lizard","panda","penguin","rabbit","snake","spider","tiger","zebra"];function rb(){const o=nb[Math.floor(Math.random()*nb.length)],e=ob[Math.floor(Math.random()*ob.length)];return o+"_"+e}function ab(o){return o=o.replace(/[^a-z0-9áéíóúñü \.,_-]/gim,""),o.trim()}function Pa(o,e,t=!0,s=!1){var n;if(e==null)return null;if(e.userData&&e.userData.guid===o||e.guid==o)return e;if(s&&(n=e.userData)!=null&&n.components){for(const r of e.userData.components)if(r.guid===o)return r}if(t){if(e.scenes)for(const r in e.scenes){const l=e.scenes[r],c=Pa(o,l,t,s);if(c)return c}if(e.children)for(const r in e.children){const l=e.children[r],c=Pa(o,l,t,s);if(c)return c}}}function $l(o,e){if(o!=null&&typeof o=="object"){let t;Array.isArray(o)?t=[]:(t=Object.create(o),Object.assign(t,o));for(const s of Object.keys(o)){const n=o[s];e&&!e(o,s,n)?t[s]=n:n?.clone!==void 0&&typeof n.clone=="function"?t[s]=n.clone():t[s]=$l(n,e)}return t}return o}function ys(o){return new Promise((e,t)=>{setTimeout(e,o)})}function Gl(o,e){if(o<=0)return Promise.resolve();if(e||(e=pe.Current),!e)return Promise.reject("No context");const t=e.time.frameCount+o;return new Promise((s,n)=>{if(!e)return n("No context");const r=()=>{e.time.frameCount>=t&&(e.pre_update_callbacks.splice(e.pre_update_callbacks.indexOf(r),1),s())};e.pre_update_callbacks.push(r)})}const Sd=C("debugresolveurl"),lb="rel:";function UO(o,e){return fo(o,e)}function fo(o,e){if(e===void 0)return Sd&&console.warn("getPath: uri is undefined, returning uri",e),e;if(e.startsWith("./"))return e;if(e.startsWith("http"))return Sd&&console.warn("getPath: uri is absolute, returning uri",e),e;if(o===void 0)return Sd&&console.warn("getPath: source is undefined, returning uri",e),e;e.startsWith(lb)&&(e=e.substring(4));const t=o.lastIndexOf("/");if(t>=0){const s=o.substring(0,t+1);for(;s.endsWith("/")&&e.startsWith("/");)e=e.substring(1);const n=s+e;return Sd&&console.log("source:",o,`changed uri
4
+ from`,e,`
5
+ to `,n,`
6
+ basePath: `+s),n}return e}class zO{constructor(e,t){a(this,"writeCallbacks",[]),a(this,"_applied",!1),a(this,"_object"),a(this,"_prop"),a(this,"_wrapperProp"),this._object=e,this._prop=t,this._wrapperProp=Symbol("$"+t),this.apply()}subscribeWrite(e){this.writeCallbacks.push(e)}unsubscribeWrite(e){const t=this.writeCallbacks.indexOf(e);t!==-1&&this.writeCallbacks.splice(t,1)}apply(){if(this._applied||!this._object)return;const e=this._object,t=this._prop;if(e[t]===void 0)return;this._applied=!0,e[this._wrapperProp]!==void 0&&console.warn("Watcher is being applied to an object that already has a wrapper property. This is not (yet) supported");const s=e[t];e[this._wrapperProp]=s,Object.defineProperty(e,t,{get:()=>e[this._wrapperProp],set:n=>{e[this._wrapperProp]=n;for(const r of this.writeCallbacks)r(n,this._prop)}})}revoke(){if(!this._applied||!this._object)return;this._applied=!1;const e=this._object,t=this._prop;Reflect.deleteProperty(e,t);const s=e[this._wrapperProp];e[t]=s,Reflect.deleteProperty(e,this._wrapperProp)}dispose(){this.revoke(),this.writeCallbacks.length=0,this._object=null}}class lo{constructor(e,t){if(a(this,"_watches",[]),Array.isArray(t))for(const s of t)this._watches.push(new lo(e,s));else this._watches.push(new zO(e,t))}subscribeWrite(e){for(const t of this._watches)t.subscribeWrite(e)}unsubscribeWrite(e){for(const t of this._watches)t.unsubscribeWrite(e)}apply(){for(const e of this._watches)e.apply()}revoke(){for(const e of this._watches)e.revoke()}dispose(){for(const e of this._watches)e.dispose();this._watches.length=0}}const Oa=Symbol("needle:watches");function Cd(o,e){if(!o[Oa])if(o instanceof le)o[Oa]=new lo(o,["x","y"]);else if(o instanceof x)o[Oa]=new lo(o,["x","y","z"]);else if(o instanceof ye||o instanceof H)o[Oa]=new lo(o,["x","y","z","w"]);else return!1;return o[Oa].subscribeWrite(e),!0}function Gm(o,e){if(!o)return;const t=o[Oa];t&&t.unsubscribeWrite(e)}var Y;(o=>{let e;function t(){if(e!==void 0)return e;const j=window.navigator.userAgent,Q=/Windows|MacOS|Mac OS/.test(j),J=/Windows NT/.test(j)&&/Edg/.test(j)&&!/Win64/.test(j);return e=Q&&!J&&!w()}o.isDesktop=t;let s;function n(){return s!==void 0?s:typeof window.orientation<"u"||navigator.userAgent.indexOf("IEMobile")!==-1?s=!0:s=/iPhone|iPad|iPod|Android|IEMobile/i.test(navigator.userAgent)}o.isMobileDevice=n;function r(){return c()}o.isIPad=r;let l;function c(){return l!==void 0?l:l=/iPad/.test(navigator.userAgent)}o.isiPad=c;let h;function d(){return h!==void 0?h:h=/Android/.test(navigator.userAgent)}o.isAndroidDevice=d;let u;function p(){return u!==void 0?u:u=/WebXRViewer\//i.test(navigator.userAgent)}o.isMozillaXR=p;let g;function f(){if(g!==void 0)return g;if(navigator.userAgentData)return g=navigator.userAgentData.platform==="macOS";{const j=navigator.userAgent.toLowerCase();return g=j.includes("mac os x")||j.includes("macintosh")}}o.isMacOS=f;let y;function b(){return y!==void 0?y:y=f()&&"xr"in navigator}o.isVisionOS=b;let v;const _=["iPad Simulator","iPhone Simulator","iPod Simulator","iPad","iPhone","iPod"];function w(){return v!==void 0?v:v=_.includes(navigator.platform)||navigator.userAgent.includes("Mac")&&"ontouchend"in document}o.isiOS=w;let S;function k(){return S!==void 0||(S=/^((?!chrome|android).)*safari/i.test(navigator.userAgent)),S}o.isSafari=k;let M;function T(){return M!==void 0?M:M=navigator.userAgent.includes("OculusBrowser")}o.isQuest=T;let L;function B(){return L!==void 0||(L=document.createElement("a").relList.supports("ar")),L}o.supportsQuickLookAR=B;async function z(){try{return(await navigator.permissions.query({name:"microphone"})).state!=="denied"}catch(j){return console.error("Error querying `microphone` permissions.",j),!1}}o.microphonePermissionsGranted=z;let D;function V(){if(D!==void 0)return D;const j=navigator.userAgent.match(/iPhone OS (\d+_\d+)/);if(j&&(D=j[1].replace("_",".")),!D){const Q=navigator.userAgent.match(/(?:\(Macintosh;|iPhone;|iPad;).*Version\/(\d+\.\d+)/);Q&&(D=Q[1])}return D||(D=null),D}o.getiOSVersion=V;let $;function U(){if($!==void 0)return $;const j=navigator.userAgent.match(/(?:CriOS|Chrome)\/(\d+\.\d+\.\d+\.\d+)/);return j?$=j[1].replace("_","."):$=null,$}o.getChromeVersion=U})(Y||(Y={}));function NO(){return Y.isDesktop()}function WO(){return Y.isMobileDevice()}function VO(){return Y.isiPad()}function HO(){return Y.isiPad()}function $O(){return Y.isAndroidDevice()}function GO(){return Y.isMozillaXR()}function qO(){return Y.isMacOS()}function XO(){return Y.isiOS()}function QO(){return Y.isSafari()}function YO(){return Y.isQuest()}async function KO(){return Y.microphonePermissionsGranted()}const yo=new WeakMap;function cb(o,e,t){if(!yo.get(o)){const n=new MutationObserver(r=>{ZO(o,r)});yo.set(o,{observer:n,attributeChangedListeners:new Map}),n.observe(o,{attributes:!0})}const s=yo.get(o).attributeChangedListeners;s.has(e)||s.set(e,[]),s.get(e).push(t)}function hb(o,e,t){if(!yo.get(o))return;const s=yo.get(o).attributeChangedListeners;if(!s.has(e))return;const n=s.get(e),r=n.indexOf(t);if(r!==-1&&(n.splice(r,1),n.length<=0)){s.delete(e);const l=yo.get(o);l?.observer.disconnect(),yo.delete(o)}}function ZO(o,e){const t=yo.get(o).attributeChangedListeners;for(const s of e)if(s.type==="attributes"){const n=s.attributeName,r=o.getAttribute(n);if(t.has(n))for(const l of t.get(n))l(r)}}class qm{constructor(e){a(this,"reason"),this.reason=e}}async function Xm(o){const e=await Promise.allSettled(o).catch(n=>[new qm(n.message)]);let t=!1;const s=e.map(n=>"value"in n?n.value:(t=!0,new qm(n.reason)));return{anyFailed:t,results:s}}async function db(o){var e;if(!globalThis.QRCode){const d="https://cdn.jsdelivr.net/gh/davidshimjs/qrcodejs@gh-pages/qrcode.min.js";let u=document.head.querySelector(`script[src="${d}"]`);u||(u=document.createElement("script"),u.src=d,document.head.appendChild(u)),await new Promise((p,g)=>{u.addEventListener("load",()=>{p(!0)})})}const t=globalThis.QRCode,s=o.domElement??document.createElement("div"),n=new t(s,{width:o.width??256,height:o.height??256,colorDark:"#000000",colorLight:"#ffffff",correctLevel:o.showLogo?t.CorrectionLevel.H:t.CorrectLevel.M,...o}),r=n?._oQRCode.moduleCount||0,l=(e=n?._oDrawing)==null?void 0:e._elCanvas;let c=.25;r<40?c=Math.floor(r/4)/r:c=Math.floor(r/6)/r;const h=Math.floor(r/20)/r;try{const d=await JO(l,{showLogo:o.showLogo,logoSize:c,logoPadding:h}).catch(u=>{});d&&(s.innerHTML="",s.append(d))}catch{}if(o.showUrl!==!1&&o.text){const d=s.querySelector(".qr-code-link-label");let u=o.text.replace(/^(https?:\/\/)?(www\.)?/,"").replace(/\/+$/,"").replace(/\?+$/,"");if(u="Scan to visit "+u,d)d.textContent=u;else{const p=document.createElement("div");p.classList.add("qr-code-link-label"),o.text=u,p.textContent=o.text,p.addEventListener("click",g=>{g.stopImmediatePropagation()}),p.style.textAlign="center",p.style.fontSize="0.8em",p.style.marginTop="0.1em",p.style.color="#000000",p.style.fontFamily="'Roboto Flex', sans-serif",p.style.opacity="0.5",p.style.wordBreak="break-all",p.style.wordWrap="break-word",p.style.marginBottom="0.3em",s.style.width="calc(210px + 20px)",s.appendChild(p)}}return s}async function JO(o,e){if(!o)return;const t=8,s=20,n=e.logoPadding||1/32,r="transparent",l=0,c=new Image,h=document.querySelector("needle-engine"),d=h?.getAttribute("loading-logo-src")||eb;if(!d)return;let u=!1;e.showLogo!==!1&&(c.src=d,u=await new Promise((w,S)=>{c.onload=()=>w(!0),c.onerror=k=>{console.error("Error loading favicon image for QR code",k),w(!1)}}));const p=document.createElement("canvas");p.width=o.width+t,p.height=o.height+t;const g=p.getContext("2d");if(!g)return;g.fillStyle="#ffffff",g.fillRect(0,0,p.width,p.height),g.drawImage(o,t/2,t/2),g.imageSmoothingEnabled=!0,g.imageSmoothingQuality="high",g.mozImageSmoothingEnabled=!0,g.webkitImageSmoothingEnabled=!0,g.globalCompositeOperation="lighten";const f=g.createLinearGradient(0,0,0,p.height);f.addColorStop(0,"rgb(45, 45, 45)"),f.addColorStop(1,"rgb(45, 45, 45)"),g.fillStyle=f,g.fillRect(0,0,p.width,p.height),g.globalCompositeOperation="source-over";let y=Math.min(o.width,o.height)*(e.logoSize||.25),b=y;if(u){const w=c.width/c.height;w>1?b=y/w:y=b*w;const S=n*o.width,k=Math.max(y,b),M=Math.round(k+S),T=Math.round(k+S),L=(p.width-k)/2,B=(p.height-k)/2;g.shadowColor=r,g.shadowBlur=s;const z=l,D=Math.round(L-S/2),V=Math.round(B-S/2);g.beginPath(),g.moveTo(D+z,V),g.lineTo(D+M-z,V),g.quadraticCurveTo(D+M,V,D+M,V+z),g.lineTo(D+M,V+T-z),g.quadraticCurveTo(D+M,V+T,D+M-z,V+T),g.lineTo(D+z,V+T),g.quadraticCurveTo(D,V+T,D,V+T-z),g.lineTo(D,V+z),g.quadraticCurveTo(D,V,D+z,V),g.fillStyle="#ffffff",g.closePath(),g.fill(),g.clip(),g.shadowColor="transparent";const $=(p.width-y)/2,U=(p.height-b)/2;g.drawImage(c,$,U,y,b)}const v=p.toDataURL("image/png"),_=document.createElement("img");return _.src=v,_.style.width="100%",_.style.height="auto",_}const ub=C("debugdebug");let ql=!1;(C("noerrors")||C("nooverlaymessages"))&&(ql=!0);const Qm="needle_engine_global_error_container";var Oi=(o=>(o[o.Log=0]="Log",o[o.Warn=1]="Warn",o[o.Error=2]="Error",o))(Oi||{});function Ym(){return fb}const Km=new Array;function ek(o){Km.push(o)}let Zm=!1;function tk(...o){if(!Zm){Zm=!0;try{for(let e=0;e<Km.length;e++)Km[e](...o)}catch(e){console.error(e)}Zm=!1}}const pb=console.error,mb=function(...o){pb.apply(console,o),nk(o),$s(2,o),Jm(...o)};function gb(o){ql=!o,o?console.error=mb:console.error=pb}function ik(o){return gb(o)}function sk(){ql||(ub&&console.warn("Patch console",window.location.hostname),console.error=mb,window.addEventListener("error",o=>{if(!o)return;const e=o.error;if(e===void 0){qt()&&console.warn("Received unknown error",o,o.target);return}$s(2,e,o.filename,o.lineno),Jm(o)},!0),window.addEventListener("unhandledrejection",o=>{ql||o&&(o.reason?$s(2,o.reason.message,o.reason.stack):$s(2,"unhandled rejection"),Jm(o))}))}let fb=0;function Jm(...o){fb+=1,tk(...o)}function nk(o){if(Array.isArray(o))for(let e=0;e<o.length;e++){const t=o[e];typeof t=="string"&&t.startsWith("THREE.PropertyBinding: Trying to update node for track:")&&(o[e]="Some animated objects couldn't be found: see console for details")}}function $s(o,e,t,s){if(ql)return;const n=pe.Current,r=n?.domElement??document.querySelector("needle-engine");if(r){if(Array.isArray(e)){let l="";for(let c=0;c<e.length;c++){let h=e[c];h instanceof Error&&(h=h.message),typeof h!="object"&&(c>0&&(l+=" "),l+=h)}e=l}!e||e.length<=0||ok(o,r,e)}}const Xl=new Map;function ok(o,e,t){if(t==null)return;const s=lk(e);if(s.childElementCount>=20){const c=s.lastElementChild;vb(c)}t.length>400&&(t=t.substring(0,400)+"...");const n=t;if(Xl.has(n))return;const r=ck(o,t);s.prepend(r);const l=()=>{Xl.delete(n),vb(r)};Xl.set(n,l),setTimeout(l,1e4)}function rk(){ub&&console.log("Clearing messages");for(const o of Xl.values())o?.call(o);Xl.clear()}const ak=`
7
+
8
+ @import url('https://fonts.googleapis.com/css2?family=Roboto+Flex:opsz,wght@8..144,100..1000&display=swap');
9
+
10
+ div[data-needle_engine_debug_overlay] {
11
+ font-family: 'Roboto Flex', sans-serif;
12
+ font-weight: 400;
13
+ font-size: 16px;
14
+ }
15
+
16
+ div[data-needle_engine_debug_overlay] strong {
17
+ font-weight: 700;
18
+ }
19
+
20
+ div[data-needle_engine_debug_overlay] a {
21
+ color: white;
22
+ text-decoration: none;
23
+ border-bottom: 1px solid rgba(255, 255, 255, 0.3);
24
+ }
25
+
26
+ div[data-needle_engine_debug_overlay] a:hover {
27
+ text-decoration: none;
28
+ border: none;
29
+ }
30
+
31
+ div[data-needle_engine_debug_overlay] .log strong {
32
+ color: rgba(200,200,200,.9);
33
+ }
34
+
35
+ div[data-needle_engine_debug_overlay] .warn strong {
36
+ color: rgba(255,255,230, 1);
37
+ }
38
+
39
+ div[data-needle_engine_debug_overlay] .error strong {
40
+ color: rgba(255,100,120, 1);
41
+ }
42
+ `;function lk(o){globalThis[Qm]||(globalThis[Qm]=new Map);const e=globalThis[Qm];if(e.has(o))return e.get(o);{const t=document.createElement("div");e.set(o,t),t.setAttribute("data-needle_engine_debug_overlay",""),t.classList.add("debug-container"),t.style.cssText=`
43
+ position: absolute;
44
+ top: 0;
45
+ right: 5px;
46
+ padding-top: 0px;
47
+ max-width: 70%;
48
+ max-height: calc(100% - 5px);
49
+ z-index: 9999999999;
50
+ pointer-events: scroll;
51
+ display: flex;
52
+ align-items: end;
53
+ flex-direction: column;
54
+ color: white;
55
+ overflow: auto;
56
+ word-break: break-word;
57
+ `,o.shadowRoot?o.shadowRoot.appendChild(t):o.appendChild(t);const s=document.createElement("style");return s.innerHTML=ak,t.appendChild(s),t}}const yb=Symbol("logtype"),Pd=new Map;function vb(o){o.remove();const e=o[yb],t=Pd.get(e)??[];t.push(o),Pd.set(e,t)}function ck(o,e){if(Pd.has(o)){const s=Pd.get(o);if(s.length>0){const n=s.pop();return n.innerHTML=e,n}}const t=document.createElement("div");switch(t.setAttribute("data-id","__needle_engine_debug_overlay"),t.style.marginRight="5px",t.style.padding=".5em",t.style.backgroundColor="rgba(0,0,0,.9)",t.style.marginTop="5px",t.style.marginBottom="3px",t.style.borderRadius="8px",t.style.pointerEvents="all",t.style.userSelect="text",t.style.maxWidth="250px",t.style.whiteSpace="pre-wrap",t.style["backdrop-filter"]="blur(10px)",t.style["-webkit-backdrop-filter"]="blur(10px)",t.style.backgroundColor="rgba(20,20,20,.8)",t.style.boxShadow="inset 0 0 80px rgba(0,0,0,.2), 0 0 5px rgba(0,0,0,.2)",t.style.border="1px solid rgba(160,160,160,.2)",t[yb]=o,o){case 0:t.classList.add("log"),t.style.color="rgba(200,200,200,.7)",t.style.backgroundColor="rgba(40,40,40,.7)";break;case 1:t.classList.add("warn"),t.style.color="rgb(255, 255, 150)",t.style.backgroundColor="rgba(50,50,20,.8)";break;case 2:t.classList.add("error"),t.style.color="rgb(255, 50, 50",t.style.backgroundColor="rgba(50,20,20,.8)";break}return t.title="Open the browser console (F12) for more information",t.innerHTML=e,t}class hk{constructor(){a(this,"Rad2Deg",180/Math.PI),a(this,"Deg2Rad",Math.PI/180),a(this,"Epsilon",1e-5)}random(e,t){return Array.isArray(e)?e.length<=0?null:e[Math.floor(Math.random()*e.length)]:e!==void 0&&t!==void 0?Math.random()*(t-e)+e:Math.random()}randomVector3(e,t=0,s=1){e.x=this.random(t,s),e.y=this.random(t,s),e.z=this.random(t,s)}clamp(e,t,s){return e<t?t:e>s?s:e}clamp01(e){return this.clamp(e,0,1)}lerp(e,t,s){return s=s<0?0:s,s=s>1?1:s,e+(t-e)*s}inverseLerp(e,t,s){return(s-e)/(t-e)}remap(e,t,s,n,r){return n+(r-n)*(e-t)/(s-t)}moveTowards(e,t,s){return e+=s,(s<0&&e<t||s>0&&e>t)&&(e=t),e}toDegrees(e){return e*180/Math.PI}toRadians(e){return e*Math.PI/180}tan(e){return Math.tan(e)}gammaToLinear(e){return Math.pow(e,2.2)}linearToGamma(e){return Math.pow(e,1/2.2)}approximately(e,t,s=Number.EPSILON){for(const n of dk){const r=e[n],l=t[n];if(r===void 0||l===void 0)break;if(Math.abs(r-l)>s)return!1}return!0}easeInOutCubic(e){return e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2}}const dk=["x","y","z","w"],W=new hk;class bb{constructor(e){a(this,"y"),a(this,"s"),a(this,"alpha",0),this.setAlpha(e),this.y=null,this.s=null}setAlpha(e){if(e<=0||e>1)throw new Error;this.alpha=e}filter(e,t){t&&this.setAlpha(t);let s;return this.y?s=this.alpha*e+(1-this.alpha)*this.s:s=e,this.y=e,this.s=s,s}lastValue(){return this.y}reset(e){this.y=e,this.s=e}}class Od{constructor(e,t=1,s=0,n=1){if(a(this,"freq"),a(this,"minCutOff"),a(this,"beta"),a(this,"dCutOff"),a(this,"x"),a(this,"dx"),a(this,"lasttime"),e<=0||t<=0||n<=0)throw new Error;this.freq=e,this.minCutOff=t,this.beta=s,this.dCutOff=n,this.x=new bb(this.alpha(this.minCutOff)),this.dx=new bb(this.alpha(this.dCutOff)),this.lasttime=null}alpha(e){const t=1/this.freq;return 1/(1+1/(2*Math.PI*e)/t)}filter(e,t=null){this.lasttime&&t&&(this.freq=1/(t-this.lasttime)),this.lasttime=t;const s=this.x.lastValue(),n=s?(e-s)*this.freq:0,r=this.dx.filter(n,this.alpha(this.dCutOff)),l=this.minCutOff+this.beta*Math.abs(r);return this.x.filter(e,this.alpha(l))}reset(e){e!=null&&this.x.reset(e),this.x.alpha=this.alpha(this.minCutOff),this.dx.alpha=this.alpha(this.dCutOff),this.lasttime=null}}class eg{constructor(e,t=1,s=0,n=1){a(this,"x"),a(this,"y"),a(this,"z"),this.x=new Od(e,t,s,n),this.y=new Od(e,t,s,n),this.z=new Od(e,t,s,n)}filter(e,t,s=null){t.x=this.x.filter(e.x,s),t.y=this.y.filter(e.y,s),t.z=this.z.filter(e.z,s)}reset(e){this.x.reset(e?.x),this.y.reset(e?.y),this.z.reset(e?.z)}}const kd="needle:cameraController";function _b(o){return o[kd]}function tg(o,e,t){t?o[kd]=e:o[kd]===e&&(o[kd]=null)}const ig="needle:autofit";function wb(o){return o[ig]===void 0?!0:o[ig]!==!1}function Md(o,e){o[ig]=e}function uk(o,e,t){const s=o.length(),n=e.length(),r=W.lerp(s,n,t);return o.lerp(e,t).normalize().multiplyScalar(r)}const sg=new H,xb=new H().setFromAxisAngle(new x(0,1,0),Math.PI);function pk(o,e){o.lookAt(e),o.quaternion.multiply(xb)}function Ql(o,e,t=!0,s=!1){if(o===e)return;sg.copy(o.quaternion);const n=te(e),r=te(o);if(s){if(Qi(o,Se(e)),t){const l=r.y,c=r.sub(kb(o));c.y=l,o.lookAt(c),o.quaternion.multiply(xb)}Number.isNaN(o.quaternion.x)&&o.quaternion.copy(sg);return}t&&(n.y=r.y),o.lookAt(n),Number.isNaN(o.quaternion.x)&&o.quaternion.copy(sg)}function mk(o,e,t,s=1){if(t){const n=X(0,0,0),r=e.x/window.innerWidth*2-1,l=-(e.y/window.innerHeight)*2+1;n.set(r,l,0),n.unproject(t);const c=t.worldPosition,h=o.worldPosition.distanceTo(c),d=n.sub(c);d.multiplyScalar(s*3.6*h);const u=t.worldPosition.add(d);return o.lookAt(u),u}return null}const gk=new Pi(()=>new x,100);function X(o,e,t){const s=gk.get();return s.set(0,0,0),o instanceof x?s.copy(o):Array.isArray(o)?s.set(o[0],o[1],o[2]):o instanceof DOMPointReadOnly?s.set(o.x,o.y,o.z):typeof o=="number"?(s.x=o,s.y=e!==void 0?e:s.x,s.z=t!==void 0?t:s.x):typeof o=="object"&&(s.x=o.x,s.y=o.y,s.z=o.z),s}const fk=new Pi(()=>new ae,30);function Sb(o){const e=fk.get();return o?e.copy(o):e.set(0,0,0),e}const yk=new Pi(()=>new H,100);function vs(o){const e=yk.get();return e.identity(),o instanceof H?e.copy(o):o instanceof DOMPointReadOnly&&e.set(o.x,o.y,o.z,o.w),e}const ng=new Pi(()=>new x,100),Cb=Symbol("lastMatrixWorldUpdateKey");function te(o,e=null,t=!0){const s=e??ng.get();return o?o.parent?(t&&o.updateWorldMatrix(!0,!1),o.matrixWorldNeedsUpdate&&o[Cb]!==Date.now()&&(o[Cb]=Date.now(),o.updateMatrixWorld()),s.setFromMatrixPosition(o.matrixWorld),s):s.copy(o.position):s.set(0,0,0)}function lt(o,e){if(!o)return o;const t=ng.get();return e!==t&&t.copy(e),(o?.parent??o).worldToLocal(t),o.position.set(t.x,t.y,t.z),o}function fr(o,e,t,s){const n=ng.get();return n.set(e,t,s),lt(o,n),o}const Rd=new Pi(()=>new H,100),yr=new H,og=new H;function Se(o,e=null){if(!o)return Rd.get().identity();const t=e??Rd.get();return o.parent?(o.getWorldQuaternion(t),t):t.copy(o.quaternion)}function Qi(o,e){if(!o)return;e!==yr&&yr.copy(e);const t=yr,s=o?.parent;s?.getWorldQuaternion(og),og.invert();const n=og.multiply(t);o.quaternion.set(n.x,n.y,n.z,n.w)}function rg(o,e,t,s,n){yr.set(e,t,s,n),Qi(o,yr)}const vk=new Pi(()=>new x,100),bk=new x;function Ge(o,e=null){return e||(e=vk.get()),o?o.parent?(o.getWorldScale(e),e):e.copy(o.scale):e.set(0,0,0)}function ka(o,e){if(!o)return;if(!o.parent){o.scale.copy(e);return}const t=bk;o.parent.getWorldScale(t),o.scale.copy(e),o.scale.divide(t)}const _k=new x,Pb=new H;function wk(o){return Se(o,Pb),_k.set(0,0,1).applyQuaternion(Pb)}const xk=new Pi(()=>new x,100),Ob=new H;function kb(o,e){return e||(e=xk.get().set(0,0,1)),Se(o,Ob),e.applyQuaternion(Ob)}const Mb=new jt,Rb=new jt,Sk=new x;function ag(o){const e=Rd.get();return o.getWorldQuaternion(e),Rb.setFromQuaternion(e),Rb}function lg(o,e){const t=Rd.get();Qi(o,t.setFromEuler(e))}function Td(o){const e=ag(o),t=Sk;return t.set(e.x,e.y,e.z),t.x=W.toDegrees(t.x),t.y=W.toDegrees(t.y),t.z=W.toDegrees(t.z),t}function Tb(o,e){Yl(o,e.x,e.y,e.z,!0)}function Yl(o,e,t,s,n=!0){n&&(e=W.toRadians(e),t=W.toRadians(t),s=W.toRadians(s)),Mb.set(e,t,s),yr.setFromEuler(Mb),Qi(o,yr)}function Ed(o,e=!0){o&&(e?function t(s){console.groupCollapsed((s.name?s.name:"(no name : "+s.type+")")+" %o",s),s.children.forEach(t),console.groupEnd()}(o):o.traverse(function(t){for(var s="|___",n=t;n.parent!==null;)s=" "+s,n=n.parent;console.log(s+t.name+" <"+t.type+">")}))}function Ck(o){let e=o?.name||"";if(!o)return e;let t=o.parent;for(;t;)e=t.name+"/"+e,t=t.parent;return e}function Eb(o){if(o){const e=o;return e.blendMode!==void 0&&e.clampWhenFinished!==void 0&&e.enabled!==void 0&&e.fadeIn!==void 0&&e.getClip!==void 0}return!1}const Ab=class dC extends Ws{constructor(){super({vertexShader:dC.vertex,uniforms:{map:new Xi(null),flipY:new Xi(!0),writeDepth:new Xi(!1),depthTexture:new Xi(null)},fragmentShader:`
58
+ uniform sampler2D map;
59
+ uniform bool flipY;
60
+ uniform bool writeDepth;
61
+ uniform sampler2D depthTexture;
62
+
63
+ varying vec2 vUv;
64
+
65
+ void main(){
66
+ vec2 uv = vUv;
67
+ if (flipY) uv.y = 1.0 - uv.y;
68
+ gl_FragColor = texture2D(map, uv);
69
+
70
+ if (writeDepth) {
71
+ float depth = texture2D(depthTexture, uv).r;
72
+ gl_FragDepth = depth;
73
+
74
+ // float linearDepth = (depth - 0.99) * 100.0; // Enhance near 1.0 values
75
+ // gl_FragColor = vec4(linearDepth, linearDepth, linearDepth, 1.0);
76
+ }
77
+ }`})}reset(){this.uniforms.map.value=null,this.uniforms.flipY.value=!0,this.uniforms.writeDepth.value=!1,this.uniforms.depthTexture.value=null,this.needsUpdate=!0,this.uniformsNeedUpdate=!0}};a(Ab,"vertex",`
78
+ varying vec2 vUv;
79
+ void main(){
80
+ vUv = uv;
81
+ gl_Position = vec4(position.xy, 0., 1.0);
82
+ }`);let Ib=Ab;const Gs=class{static copyTexture(e,t){t||(t=this.blitMaterial),this.blitMaterial.reset();const s=t||this.blitMaterial;s.uniforms.map.value=e,s.needsUpdate=!0,s.uniformsNeedUpdate=!0;const n=s.vertexShader;s.vertexShader=Ib.vertex;const r=this.mesh;r.material=s,r.frustumCulled=!1,this.scene.children.length=0,this.scene.add(r),this.renderer.setSize(e.image.width,e.image.height),this.renderer.clear(),this.renderer.render(this.scene,this.perspectiveCam);const l=new De(this.renderer.domElement);return l.name="Copy",l.needsUpdate=!0,s.vertexShader=n,l}static blit(e,t,s){const{renderer:n=this.renderer,blitMaterial:r=this.blitMaterial,flipY:l=!1,depthTexture:c=null,depthTest:h=!0,depthWrite:d=!0}=s||{};this.blitMaterial.reset(),r.uniforms.map&&(r.uniforms.map.value=e),r.uniforms.flipY&&(r.uniforms.flipY.value=l),c?(r.uniforms.writeDepth=new Xi(!0),r.uniforms.depthTexture.value=c):(r.uniforms.writeDepth=new Xi(!1),r.uniforms.depthTexture.value=null),r.needsUpdate=!0,r.uniformsNeedUpdate=!0;const u=this.mesh;u.material=r,u.frustumCulled=!1,this.scene.children.length=0,this.scene.add(u);const p=n.getRenderTarget(),g=n.getContext(),f=g.getParameter(g.DEPTH_TEST),y=g.getParameter(g.DEPTH_WRITEMASK),b=g.getParameter(g.DEPTH_FUNC);h?n.getContext().enable(n.getContext().DEPTH_TEST):n.getContext().disable(n.getContext().DEPTH_TEST),n.state.buffers.depth.setMask(d),n.setClearColor(new ae(0,0,0),0),n.setPixelRatio(window.devicePixelRatio),n.setRenderTarget(t),n.clear(),n.render(this.scene,this.perspectiveCam),n.setRenderTarget(p);const v=n.state.buffers.depth;v.setTest(f),v.setMask(y),v.setFunc(b)}static textureToCanvas(e,t=!1){if(!e)return null;(t===!0||e.isCompressedTexture===!0)&&(e=Lb(e));const s=e.image;if(Ok(s)){const n=document.createElement("canvas");n.width=s.width,n.height=s.height;const r=n.getContext("2d");return r?(r.drawImage(s,0,0,s.width,s.height,0,0,n.width,n.height),n):(console.error("Failed getting canvas 2d context"),null)}return null}};a(Gs,"planeGeometry",new Ns(2,2,1,1)),a(Gs,"renderer",new pr({antialias:!1,alpha:!0})),a(Gs,"perspectiveCam",new we),a(Gs,"orthographicCam",new hd),a(Gs,"scene",new wi),a(Gs,"blitMaterial",new Ib),a(Gs,"mesh",new q(Gs.planeGeometry,Gs.blitMaterial));let Kl=Gs;function Lb(o){return Kl.copyTexture(o)}function Pk(o,e=!1){return Kl.textureToCanvas(o,e)}function Ok(o){return typeof HTMLImageElement<"u"&&o instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&o instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&o instanceof OffscreenCanvas||typeof ImageBitmap<"u"&&o instanceof ImageBitmap}function kk(o){const e=o.type;return e==="Mesh"||e==="SkinnedMesh"}function cg(o,e){e?o["needle:rendercustomshadow"]=!0:o["needle:rendercustomshadow"]=!1}function jb(o){return!!(o&&(o["needle:rendercustomshadow"]===!0||o["needle:rendercustomshadow"]==null))}function ii(o,e=void 0,t=void 0,s=void 0){const n=s||new xi;n.makeEmpty();const r=[];function l(h){let d=!0;if(h.visible&&wb(h)!==!1&&!(h.type==="TransformControlsGizmo"||h.type==="TransformControlsPlane")){if(h instanceof MC&&(d=!1),h instanceof Sm&&(d=!1),h instanceof Ca&&(d=!1),h.isGizmo===!0&&(d=!1),h.material instanceof xv&&(d=!1),kk(h)||(d=!1),t&&h.layers.test(t)===!1&&(d=!1),d&&(e&&Array.isArray(e)&&e!=null&&e.includes(h)||typeof e=="function"&&e(h)===!0))return;if(h.isUI!==!0){if(d){const u=h.children;h.children=r;const p=h.position,g=h.scale;if(Number.isNaN(p.x)||Number.isNaN(p.y)||Number.isNaN(p.z)){console.warn(`Object "${h.name}" has NaN values in position or scale.... will ignore it`,p,g);return}n.expandByObject(h,!0),h.children=u}for(const u of h.children)l(u)}}}let c=!1;Array.isArray(o)||(o=[o]);for(const h of o)h&&(c=!0,h.updateMatrixWorld(),l(h));return c||console.warn("No objects to fit camera to..."),n}function Db(o,e,t){const s=ii([o],t?.ignore),n=new x;s.getSize(n);const r=new x;s.getCenter(r);const l=new x;e.getSize(l);const c=new x;e.getCenter(c);const h=new x;h.set(l.x/n.x,l.y/n.y,l.z/n.z);const d=Math.min(h.x,h.y,h.z),u=t?.scale!==!1;if(u&&ka(o,Ge(o).multiplyScalar(d)),t?.position!==!1){const p=new x;s.getCenter(p),p.y=s.min.y;const g=new x;e.getCenter(g),g.y=e.min.y;const f=g.clone().sub(p);u&&f.multiplyScalar(d),lt(o,te(o).add(f))}return{boundsBefore:s,scale:h}}function Bb(o,e){const t=ii([o]),s=new x;t.getCenter(s),s.y=t.min.y;const n=e.clone().sub(s),r=te(o);return lt(o,r.add(n)),{offset:n,bounds:t}}function hg(o,e,t,s){if(Array.isArray(e)){let l=!0;for(let c=0;c<e.length;c++)hg(o,e[c],c,e)||(l=!1);return l}if(e.type==="MeshStandardMaterial"||e.type==="MeshBasicMaterial")return!1;if(e["material:fbx"]!=null)return!0;const n=new vt;n["material:fbx"]=e;const r=e;return r&&(r.map?n.color.set(1,1,1):n.color.copyLinearToSRGB(r.color),n.emissive.copyLinearToSRGB(r.emissive),n.emissiveIntensity=r.emissiveIntensity,n.opacity=r.opacity,n.displacementScale=r.displacementScale,n.transparent=r.transparent,n.bumpMap=r.bumpMap,n.aoMap=r.aoMap,n.map=r.map,n.displacementMap=r.displacementMap,n.emissiveMap=r.emissiveMap,n.normalMap=r.normalMap,n.envMap=r.envMap,n.alphaMap=r.alphaMap,n.metalness=r.reflectivity,n.vertexColors=r.vertexColors,r.shininess&&(n.roughness=1-Math.sqrt(r.shininess)/10),n.needsUpdate=!0),t===void 0?o.material=n:s[t]=n,!0}let Ad=!1;ek((...o)=>{var e;F()&&(e=pe.Current)!=null&&e.isInXR&&(vr(!0),Fb("error",...o))});function vr(o){if(o){if(Ad)return;Ad=!0,Rk()}else{if(!Ad)return;Ad=!1,Tk()}}const Zl={log:void 0,warn:void 0,error:void 0};class Mk{constructor(){a(this,"familyName","needle-xr"),a(this,"root",null),a(this,"context",null),a(this,"defaultFontSize",.06),a(this,"targetObject",new E),a(this,"userForwardViewPoint",new x),a(this,"oneEuroFilter",new eg(90,.8)),a(this,"_lastElementRemoveTime",0),a(this,"onBeforeRender",()=>{var e,t;const s=(e=this.context)==null?void 0:e.mainCamera;if(this.context&&s instanceof we){const n=this.getRoot();Number.isNaN(n.position.x)&&n.position.set(0,0,0),Number.isNaN(n.quaternion.x)&&n.quaternion.set(0,0,0,1),this.context.scene.add(this.targetObject);const r=((t=this.context.xr)==null?void 0:t.rigScale)??1,l=3.5*r,c=s.worldForward;c.y=0,c.normalize().multiplyScalar(l),this.userForwardViewPoint.copy(s.worldPosition).sub(c),this.targetObject.position.distanceTo(this.userForwardViewPoint)>2*r&&(this.targetObject.position.copy(this.userForwardViewPoint),Ql(this.targetObject,s,!0,!0),this.targetObject.rotateY(Math.PI)),this.oneEuroFilter.filter(this.targetObject.position,n.position,this.context.time.time);const h=this.context.time.deltaTime;if(n.quaternion.slerp(this.targetObject.quaternion,h*5),n.scale.setScalar(r),this.targetObject.removeFromParent(),this.context.scene.add(n),this.context.time.time-this._lastElementRemoveTime>.1){this._lastElementRemoveTime=this.context.time.time;const d=Date.now();for(let u=0;u<this._activeTexts.length;u++){const p=this._activeTexts[u];if(p instanceof Re.Text&&d-p._activatedTime>2e4){p.removeFromParent(),this._textBuffer.push(p),this._activeTexts.splice(u,1);break}}}}}),a(this,"textOptions",{fontSize:this.defaultFontSize,fontFamily:this.familyName,padding:.03,margin:.005,color:0,backgroundColor:16777215,backgroundOpacity:.4,borderRadius:.03,offset:.025}),a(this,"_textBuffer",[]),a(this,"_activeTexts",[]),this.ensureFont()}onEnable(){this.context=pe.Current||pe.All[0],this.context.pre_render_callbacks.push(this.onBeforeRender)}onDisable(){var e,t,s;(t=this.context)==null||t.pre_render_callbacks.splice((e=this.context)==null?void 0:e.pre_render_callbacks.indexOf(this.onBeforeRender),1),(s=this.root)==null||s.removeFromParent()}addLog(e,t){const s=this.getRoot(),n=this.getText();let r=16777215,l=0;switch(e){case"log":r=16777215,l=0;break;case"warn":r=16772761,l=4465152;break;case"error":r=16755370,l=7798784;break}t.length>1e3&&(t=t.substring(0,1e3)+"...");const c=new Date().toISOString().split("T")[1].split(".")[0];n.textContent="["+c+"] "+t,n.visible=!0,n._activatedTime=Date.now(),s.add(n),this._activeTexts.push(n),this.context&&this.context.scene.add(s),n.set({backgroundColor:r,color:l}),Re.update()}ensureFont(){let e=Re.FontLibrary.getFontFamily(this.familyName);if(!e){e=Re.FontLibrary.addFontFamily(this.familyName);const t=e.addVariant("normal","normal","./include/needle/arial-msdf.json","./include/needle/arial.png");t?.addEventListener("ready",()=>{Re.update()})}}getText(){const e=this.getRoot();if(this._textBuffer.length>0){const s=this._textBuffer.pop();return s.visible=!0,setTimeout(()=>this.disableDepthTestRecursive(s),100),s}if(e.children.length>20&&this._activeTexts.length>0)return this._activeTexts.shift();const t=new Re.Text(this.textOptions);return setTimeout(()=>this.disableDepthTestRecursive(t),500),setTimeout(()=>this.disableDepthTestRecursive(t),1500),t}disableDepthTestRecursive(e,t=0){for(let n=0;n<e.children.length;n++){const r=e.children[n];r instanceof E&&this.disableDepthTestRecursive(r,t+1)}e.renderOrder=10*t,e.layers.set(2);const s=e.material;s&&(s.depthWrite=!1,s.depthTest=!1,s.transparent=!0),t===0&&Re.update()}getRoot(){if(this.root)return this.root;const e=this.defaultFontSize,t={boxSizing:"border-box",fontFamily:this.familyName,width:"2.6",fontSize:e,color:0,lineHeight:1,backgroundColor:16777215,backgroundOpacity:0,whiteSpace:"pre-wrap",flexDirection:"column-reverse"};return this.root=new Re.Block(t),this.root}}let bs=null;function Rk(){bs||(bs=new Mk),bs.onEnable();for(const o in Zl){Zl[o]=console[o];let e=!1;console[o]=function(){var t;if((t=Zl[o])==null||t.apply(console,arguments),!e)try{e=!0,Fb(o,...arguments)}finally{e=!1}}}}function Tk(){bs?.onDisable();for(const o in Zl)console[o]=Zl[o]}const Jl=new Map;function Fb(o,...e){try{switch(Jl.clear(),o){case"log":bs?.addLog("log",t());break;case"warn":bs?.addLog("warn",t());break;case"error":bs?.addLog("error",t());break}}catch(r){console.error("Error in spatial console",r)}finally{Jl.clear()}function t(){let r="";for(let l=0;l<e.length;l++){const c=e[l];r+=s(c),l<e.length-1&&(r+=", ")}return r}function s(r,l=0){if(typeof r=="string")return'"'+r+'"';if(typeof r=="number"){if(r%1!==0){const c=r.toFixed(5),h=c.indexOf(".");let d=c.length-1;for(;d>h&&c[d]==="0";)d--;return c.substring(0,d+1)}return r.toString()}else if(Array.isArray(r)){let c="[";for(let h=0;h<r.length;h++){const d=r[h];c+=s(d,l+1),h<r.length-1&&(c+=", ")}return c+="]",c}else{if(r===null)return"null";if(r===void 0)return"undefined";if(typeof r=="function")return r.name+"()"}if(r instanceof le)return`(${s(r.x)}, ${s(r.y)})`;if(r instanceof x)return`(${s(r.x)}, ${s(r.y)}, ${s(r.z)})`;if(r instanceof ye)return`(${s(r.x)}, ${s(r.y)}, ${s(r.z)}, ${s(r.w)})`;if(r instanceof H)return`(${s(r.x)}, ${s(r.y)}, ${s(r.z)}, ${s(r.w)})`;if(r instanceof Pe||r instanceof De)return r.name;if(r instanceof Sv)return`[${r.elements.join(", ")}]`;if(r instanceof se)return`[${r.elements.join(", ")}]`;if(r instanceof ho)return r.mask.toString();if(typeof r=="object"){if(Jl.has(r))return"*";let c=`{
83
+ `;c+=n(l);const h=Object.keys(r);let d="";for(let u=0;u<h.length;u++){const p=h[u],g=r[p];if(Jl.has(g)){d+="";continue}Jl.set(g,!0),d+=p+":"+s(g,l+1),u<h.length-1&&(d+=", "),d.length>=60&&(d+=`
84
+ `,d+=n(l),c+=d,d="")}return c+=d,c+=`
85
+ }`,c}return r}function n(r){let l="";for(let c=0;c<r;c++)l+=" ";return l}}const Ek=C("nodevlogs");function Be(o,e=Oi.Log){$s(e,o)}function be(o){Be(o,Oi.Warn)}function ec(o){Be(o,Oi.Error)}let dg,ug;function F(){if(Ek)return!1;if(dg!==void 0)return dg;if(ug!==void 0)return ug;let o=qt();return o||(o=window.location.hostname.endsWith(".local-credentialless.webcontainer.io")),ug=o,o}function Ak(o){dg=o}let si,Yi=null,qs=null,tc=!1,Ub=null;const zb="terminal",ic=C("console"),Ik=C("noerrors")||C("noconsole")||window.crossOriginIsolated;if(ic&&mg(),!Ik&&(ic||qt())){if(qt()&&!ic){const e=new URL(window.location.href);e.searchParams.set("console","1"),console.log('\u{1F335} Tip: You can add the "?console" query parameter to the url to show the debug console (on mobile it will automatically open in the bottom right corner when your get errors during development. In VR a spatial console will appear.)',`
86
+ Open this page to get the console: `+e.toString())}const o=Y.isMobileDevice()||Y.isQuest()&&F();if((o||ic)&&(sk(),Wb(),Hb(!0),o)){const e=document.querySelector("needle-engine");e?.addEventListener("enter-ar",()=>{(ic||si||Ym()>0)&&C("noerrors")}),e?.addEventListener("exit-ar",()=>{Bk()})}}const pg=Symbol("consoleParent");function mg(){if(si){si.showSwitch();return}Hb()}function Nb(){si&&(si.hide(),si.hideSwitch())}function Wb(){Ub||(Ub=setInterval(Lk,500))}let Vb=0;function Lk(){const o=Ym(),e=o!==Vb;Vb=o,e&&jk()}function jk(){mg(),qs&&(qs.setAttribute("error","true"),qs.innerText="\u{1F92C}")}function Dk(){qs&&(qs.removeAttribute("error"),qs.innerText=zb)}function Bk(){Yi&&Yi[pg]&&Yi[pg].appendChild(Yi)}function Hb(o=!1){if(si!==void 0||tc)return;tc=!0;const e=document.createElement("script");e.onload=()=>{if(!globalThis.VConsole){console.warn("\u{1F335} Debug console failed to load."),tc=!1,si=null;return}tc=!1,Wb(),si=new VConsole({pluginOrder:["default","needle-console"]});const t=globalThis["needle:codegen_files"];if(t&&t.length>0&&si.addPlugin(Fk()),Yi=zk(),Yi&&(Yi[pg]=Yi.parentElement,Yi.style.position="absolute",Yi.style.zIndex=Number.MAX_SAFE_INTEGER.toString()),si.setSwitchPosition(20,30),qs=Uk(),qs){qs.innerText=zb,qs.addEventListener("click",Dk);const s=document.createElement("style"),n=40;s.innerHTML=`
87
+ #__vconsole .vc-switch {
88
+ border: 1px solid rgba(255, 255, 255, .1);
89
+ border-radius: 50%;
90
+ width: ${n}px;
91
+ height: ${n}px;
92
+ padding: 0;
93
+ line-height: ${n}px;
94
+ font-size: ${n*.4}px;
95
+ text-align: center;
96
+ background: #ffffff5c;
97
+ backdrop-filter: blur(16px);
98
+ -webkit-backdrop-filter: blur(16px);
99
+ user-select: none;
100
+ pointer-events: auto;
101
+ transition: transform .2s ease-in-out;
102
+ box-shadow: 0px 7px 0.5rem 0px rgb(0 0 0 / 6%), inset 0px 0px 1.3rem rgba(0,0,0,.05);
103
+
104
+ font-family: 'Material Symbols Outlined';
105
+ color: black;
106
+ font-size: 2.3em;
107
+ font-weight: 100;
108
+ }
109
+ #__vconsole .vc-switch:hover {
110
+ cursor: pointer;
111
+ transform: scale(1.1);
112
+ transition: transform .1s ease-in-out, background .1s linear;
113
+ background: rgba(245, 245, 245, .8);
114
+ outline: rgba(0, 0, 0, .05) 1px solid;
115
+ }
116
+ #__vconsole .vc-switch[error] {
117
+ background: rgba(255,0,0,.2);
118
+ animation: vconsole-notify 1s ease-in-out;
119
+ line-height: 35px;
120
+ }
121
+ @keyframes vconsole-notify {
122
+ from {
123
+ transform: scale(1, 1);
124
+ }
125
+ 10% {
126
+ transform: scale(1.3, 1.3);
127
+ }
128
+ 70% {
129
+ transform: scale(1.4, 1.4);
130
+ }
131
+ to {
132
+ transform: scale(1, 1);
133
+ }
134
+ }
135
+ #__vconsole .vc-panel {
136
+ font-family: monospace;
137
+ font-size: 11px;
138
+ }
139
+ #__vconsole .vc-plugin-box.vc-actived {
140
+ height: 100%;
141
+ }
142
+ #__vconsole .vc-mask {
143
+ overflow: hidden;
144
+ }
145
+ `,Yi?.prepend(s),o===!0&&Ym()<=0&&Nb(),console.log("\u{1F335} Debug console has loaded")}},e.onerror=()=>{console.warn("\u{1F335} Debug console failed to load."+(window.crossOriginIsolated?"This page is using cross-origin isolation, so external scripts can't be loaded.":"")),tc=!1,si=null},e.src="https://cdn.jsdelivr.net/npm/vconsole@3.9.1/dist/vconsole.min.js",document.body.appendChild(e)}function Fk(){if(!globalThis.VConsole)return;const o=new VConsole.VConsolePlugin("needle-console","\u{1F335} Inspect glTF"),e=()=>document.querySelector("#__vc_plug_"+o._id+" iframe");return o.on("renderTab",function(t){const s=globalThis["needle:codegen_files"];if(!s||s.length===0)return;let n=globalThis["needle:codegen_files"][0];const r=n.indexOf("?");r>-1&&(n=n.substring(0,r));const l=location.protocol+"//"+location.host+location.pathname+"/"+n,c=encodeURIComponent(l);o.fullUrl="https://viewer.needle.tools?inspect&file="+c;var h='<iframe src="" style="width: 100%; height: 99%; border: none;"></iframe>';t(h)}),o.on("show",function(){const t=e();t&&t.src!==o.fullUrl&&(t.src=o.fullUrl)}),o.on("hide",function(){const t=e();t&&(t.src="")}),o.on("addTopBar",function(t){var s=new Array;s.push({name:"Open in new window \u2197",onClick:function(n){window.open(o.fullUrl,"_blank"),si?.hide()}}),s.push({name:"Reload",onClick:function(n){const r=e();r&&(r.src=o.fullUrl)}}),s.push({name:"Fullscreen",onClick:function(n){const r=e();r.requestFullscreen?r.requestFullscreen():r.webkitRequestFullscreen instanceof Function&&r.webkitRequestFullscreen()}}),t(s)}),o}function Uk(){return document.querySelector("#__vconsole .vc-switch")||null}function zk(){return document.querySelector("#__vconsole")||null}const $b=C("debugdefines");vo('if(!globalThis["NEEDLE_ENGINE_VERSION"]) globalThis["NEEDLE_ENGINE_VERSION"] = "0.0.0";'),vo('if(!globalThis["NEEDLE_ENGINE_GENERATOR"]) globalThis["NEEDLE_ENGINE_GENERATOR"] = "unknown";'),vo('if(!globalThis["NEEDLE_PROJECT_BUILD_TIME"]) globalThis["NEEDLE_PROJECT_BUILD_TIME"] = "unknown";'),vo('if(!globalThis["NEEDLE_PUBLIC_KEY"]) globalThis["NEEDLE_PUBLIC_KEY"] = "unknown";'),vo('globalThis["__NEEDLE_ENGINE_VERSION__"] = "4.6.2";'),vo('globalThis["__NEEDLE_ENGINE_GENERATOR__"] = "undefined";'),vo('globalThis["__NEEDLE_PROJECT_BUILD_TIME__"] = "Wed Jul 23 2025 11:22:42 GMT+0000 (Coordinated Universal Time)";'),vo('globalThis["__NEEDLE_PUBLIC_KEY__"] = "'+NEEDLE_PUBLIC_KEY+'";');const _s="4.6.2",Id="undefined",gg="Wed Jul 23 2025 11:22:42 GMT+0000 (Coordinated Universal Time)";$b&&console.log(`Engine version: ${_s} (generator: ${Id})
146
+ Project built at ${gg}`);const Ma=NEEDLE_PUBLIC_KEY,En="needle_isActiveInHierarchy",br="builtin_components",sc="needle_editor_guid";function vo(o){try{(0,eval)(o)}catch(e){$b&&console.error(e)}}let Gb,qb=null;function ws(){return Gb}function fg(o){if(o==null){console.warn("Oh no: someone tried registering a non-existend gltf-loader. When you see this log it might mean that needle-engine is being imported multiple times. Please check your project setup.");return}qb!==o&&(qb=o,Gb=new o)}const ki=Symbol("shadowDomOwner"),Nk=C("debugpatch");function Ld(o,e,t,s){const n=Nk===e;if(!t&&!s)return;const r=e+"___needle";Vk(o,e,t,s);const l=Object.getOwnPropertyDescriptor(o,e),c=o[e];n&&console.log("Patch",o.constructor.name,e,l,c),l?(n&&console.log("Apply patch with existing descriptor",o.constructor.name,e,l),typeof l.value=="function"&&(o[e]=Qb(l.value,o,e))):(n&&console.log("Create patch with new property",o.constructor.name,e,l),Object.defineProperty(o,e,{set:function(h){if(typeof h=="function")this[r]=Qb(h,o,e);else{const d=this[r];Yb(o,e,this,d,h),this[r]=h,Kb(o,e,this,d,h)}},get:function(){const h=this[r];return typeof h=="function"&&h[r]?h[r]:h}}))}function Wk(o,e,t){const s=vg(o,e);if(s)for(let n=s.length-1;n>=0;n--){const r=s[n];r.prefix===t&&(r.prefix=null),r.postfix===t&&(r.postfix=null),!r.prefix&&!r.postfix&&s.splice(n,1)}}const Xb=Symbol("Needle:Patches:WrappedFunction");function Qb(o,e,t){if(o[Xb])return o;const s=function(...n){Yb(e,t,this,...n);const r=o.apply(this,n);return Kb(e,t,this,r,...n),r};return s[Xb]=!0,s}const jd="Needle:Patches";function yg(){return globalThis[jd]||(globalThis[jd]=new WeakMap),globalThis[jd]}function vg(o,e){const t=yg().get(o);return t?t.get(e):null}function Vk(o,e,t,s){let n=yg().get(o);n||(n=new Map,yg().set(o,n));let r=n.get(e);r||(r=[],n.set(e,r)),r.push({prefix:t,postfix:s})}function Yb(o,e,t,...s){var n;if(!t)return;const r=vg(o,e);if(r)for(const l of r)(n=l.prefix)==null||n.call(t,...s)}function Kb(o,e,t,s,...n){var r;if(!t)return;const l=vg(o,e);if(l)for(const c of l)(r=c.postfix)==null||r.call(t,s,...n)}const Ra=[];function Dd(o){Ra.indexOf(o)===-1&&Ra.push(o)}function Hk(o){const e=Ra.indexOf(o);e!==-1&&Ra.splice(e,1)}const Ta=[];function bg(o){Ta.indexOf(o)===-1&&Ta.push(o)}function $k(o){const e=Ta.indexOf(o);e!==-1&&Ta.splice(e,1)}function Zb(o){globalThis.dispatchEvent(new CustomEvent("needle-xrsession-start",{detail:o}));for(let e=0;e<Ra.length;e++)Ra[e](o)}function Jb(o){globalThis.dispatchEvent(new CustomEvent("needle-xrsession-end",{detail:o}));for(let e=0;e<Ta.length;e++)Ta[e](o)}const ct=C("debuginput");var Bd=(o=>(o.Mouse="mouse",o.Touch="touch",o.Controller="controller",o.Hand="hand",o))(Bd||{}),Fe=(o=>(o.PointerDown="pointerdown",o.PointerUp="pointerup",o.PointerMove="pointermove",o.KeyDown="keydown",o.KeyUp="keyup",o.KeyPressed="keypress",o))(Fe||{});class An extends PointerEvent{constructor(e,t,s){super(e,s),a(this,"clientZ"),a(this,"deviceIndex"),a(this,"origin"),a(this,"source"),a(this,"mode"),a(this,"_ray"),a(this,"space"),a(this,"isClick",!1),a(this,"isDoubleClick",!1),a(this,"_used",!1),a(this,"_pointerid"),a(this,"_pointerType"),a(this,"_type"),a(this,"metadata",{}),a(this,"intersections",new Array),a(this,"_immediatePropagationStopped",!1),a(this,"_propagationStopped",!1),this.clientZ=s.clientZ,this._pointerid=s.pointerId,this._pointerType=s.pointerType,this._type=e,this.deviceIndex=s.deviceIndex,this.origin=s.origin,this.source=t,this.mode=s.mode,this._ray=s.ray,this.space=s.device}get isSpatial(){return this.mode!="screen"}get ray(){return this._ray||(this._ray=new uo(this.space.worldPosition.clone(),this.space.worldForward.clone())),this._ray}set ray(e){this._ray=e}get hasRay(){return this._ray!==void 0}get used(){return this._used}use(){this._used=!0}get pointerId(){return this._pointerid}get pointerType(){return this._pointerType}get type(){return this._type}get immediatePropagationStopped(){return this._immediatePropagationStopped}get propagationStopped(){return this._immediatePropagationStopped||this._propagationStopped}stopImmediatePropagation(){var e;this._immediatePropagationStopped=!0,super.stopImmediatePropagation(),(e=this.source)==null||e.stopImmediatePropagation()}stopPropagation(){var e;this._propagationStopped=!0,super.stopPropagation(),(e=this.source)==null||e.stopPropagation(),ct&&console.warn("Stop propagation...",this.pointerId,this.pointerType)}}class nc extends KeyboardEvent{constructor(e,t,s){super(e,s),a(this,"source"),this.source=t}stopImmediatePropagation(){var e;super.stopImmediatePropagation(),(e=this.source)==null||e.stopImmediatePropagation()}}class Gk{constructor(e){a(this,"key"),a(this,"keyType"),a(this,"source"),this.key=e.key,this.keyType=e.type,this.source=e}}var ni=(o=>(o[o.Early=-100]="Early",o[o.Default=0]="Default",o[o.Late=100]="Late",o))(ni||{});class e_{constructor(e){a(this,"_eventListeners",{}),a(this,"_doubleClickTimeThreshold",.2),a(this,"_longPressTimeThreshold",1),a(this,"_setCursorTypes",[]),a(this,"context"),a(this,"_pointerDown",[!1]),a(this,"_pointerUp",[!1]),a(this,"_pointerClick",[!1]),a(this,"_pointerDoubleClick",[!1]),a(this,"_pointerPressed",[!1]),a(this,"_pointerPositions",[new le]),a(this,"_pointerPositionsLastFrame",[new le]),a(this,"_pointerPositionsDelta",[new le]),a(this,"_pointerPositionsRC",[new le]),a(this,"_pointerPositionDown",[new x]),a(this,"_pointerDownTime",[]),a(this,"_pointerUpTime",[]),a(this,"_pointerUpTimestamp",[]),a(this,"_pointerIds",[]),a(this,"_pointerTypes",[""]),a(this,"_mouseWheelChanged",[!1]),a(this,"_mouseWheelDeltaY",[0]),a(this,"_pointerEvent",[]),a(this,"_pointerEventsPressed",[]),a(this,"_pointerSpace",[]),a(this,"_pressedStack",new Map),a(this,"_htmlEventSource"),a(this,"onLostFocus",()=>{for(const t in this.keysPressed)this.keysPressed[t].pressed=!1}),a(this,"_receivedPointerMoveEventsThisFrame",new Array),a(this,"onEndOfFrame",()=>{this._receivedPointerMoveEventsThisFrame.length=0;for(let t=0;t<this._pointerUp.length;t++)this._pointerUp[t]=!1;for(let t=0;t<this._pointerDown.length;t++)this._pointerDown[t]=!1;for(let t=0;t<this._pointerClick.length;t++)this._pointerClick[t]=!1;for(let t=0;t<this._pointerDoubleClick.length;t++)this._pointerDoubleClick[t]=!1;for(const t of this._pointerPositionsDelta)t.set(0,0);for(let t=0;t<this._mouseWheelChanged.length;t++)this._mouseWheelChanged[t]=!1;for(let t=0;t<this._mouseWheelDeltaY.length;t++)this._mouseWheelDeltaY[t]=0}),a(this,"onContextMenu",t=>{this.canReceiveInput(t)!==!1&&t instanceof PointerEvent&&t.pointerType}),a(this,"keysPressed",{}),a(this,"onKeyDown",t=>{if(ct&&console.log(`key down ${t.code}, ${this.context.application.hasFocus}`,t),!this.context.application.hasFocus)return;const s=this.keysPressed[t.code];if(s&&s.pressed)return;this.keysPressed[t.code]={pressed:!0,frame:this.context.time.frameCount+1,startFrame:this.context.time.frameCount+1,key:t.key,code:t.code};const n=new nc("keydown",t,t);this.onDispatchEvent(n)}),a(this,"onKeyPressed",t=>{if(!this.context.application.hasFocus)return;const s=this.keysPressed[t.code];if(!s)return;s.pressed=!0,s.frame=this.context.time.frameCount+1;const n=new nc("keypress",t,t);this.onDispatchEvent(n)}),a(this,"onKeyUp",t=>{if(!this.context.application.hasFocus)return;const s=this.keysPressed[t.code];if(!s)return;s.pressed=!1,s.frame=this.context.time.frameCount+1;const n=new nc("keyup",t,t);this.onDispatchEvent(n)}),a(this,"onWheelWindow",t=>{document.pointerLockElement&&this.onMouseWheel(t)}),a(this,"onMouseWheel",t=>{if(this.canReceiveInput(t)===!1)return;this._mouseWheelDeltaY.length<=0&&this._mouseWheelDeltaY.push(0),this._mouseWheelChanged.length<=0&&this._mouseWheelChanged.push(!1),this._mouseWheelChanged[0]=!0;const s=this._mouseWheelDeltaY[0];this._mouseWheelDeltaY[0]=s+t.deltaY}),a(this,"onPointerDown",t=>{if(this.context.isInAR||this.canReceiveInput(t)===!1)return;t.target instanceof HTMLElement&&t.target.setPointerCapture(t.pointerId);const s=this.getPointerId(t);ct&&Be(`pointer down #${s}, identifier:${t.pointerId}`);const n=this.getAndUpdateSpatialObjectForScreenPosition(s,t.clientX,t.clientY),r=new An("pointerdown",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:s,button:t.button,clientX:t.clientX,clientY:t.clientY,pointerType:t.pointerType,buttonName:this.getButtonName(t),device:n,pressure:t.pressure});this.onDown(r)}),a(this,"onPointerMove",t=>{if(this.context.isInAR||this._receivedPointerMoveEventsThisFrame.includes(t.pointerId))return;this._receivedPointerMoveEventsThisFrame.push(t.pointerId);let s=t.button;t.pointerType==="mouse"&&(s=this.getFirstPressedButtonForPointer(0)??0);const n=this.getPointerId(t,s);s===-1&&(s=n);const r=this.getAndUpdateSpatialObjectForScreenPosition(n,t.clientX,t.clientY),l=new An("pointermove",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:n,button:s,clientX:t.clientX,clientY:t.clientY,pointerType:t.pointerType,buttonName:this.getButtonName(t),device:r,pressure:t.pressure});this.onMove(l)}),a(this,"onPointerCancel",t=>{this.context.isInAR||(ct&&console.log("Pointer cancel",t),this.onPointerUp(t))}),a(this,"onPointerUp",t=>{if(this.context.isInAR)return;t.target instanceof HTMLElement&&t.target.releasePointerCapture(t.pointerId);const s=this.getPointerId(t),n=new An("pointerup",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:s,button:t.button,clientX:t.clientX,clientY:t.clientY,pointerType:t.pointerType,buttonName:this.getButtonName(t),device:this.getAndUpdateSpatialObjectForScreenPosition(s,t.clientX,t.clientY),pressure:t.pressure});this.onUp(n),this._pointerIds[s]=-1,ct&&console.log("ID="+s,"PointerId="+t.pointerId,"ALL:",[...this._pointerIds])}),a(this,"onTouchStart",t=>{if(this.context.isInAR)for(let s=0;s<t.changedTouches.length;s++){const n=t.changedTouches[s],r=this.getPointerIndex(n.identifier),l=this.getAndUpdateSpatialObjectForScreenPosition(r,n.clientX,n.clientY),c=new An("pointerdown",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:r,button:0,clientX:n.clientX,clientY:n.clientY,pointerType:"touch",buttonName:"unknown",device:l,pressure:n.force});this.onDown(c)}}),a(this,"onTouchMove",t=>{if(this.context.isInAR)for(let s=0;s<t.changedTouches.length;s++){const n=t.changedTouches[s],r=this.getPointerIndex(n.identifier),l=this.getAndUpdateSpatialObjectForScreenPosition(r,n.clientX,n.clientY),c=new An("pointermove",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:r,button:0,clientX:n.clientX,clientY:n.clientY,pointerType:"touch",buttonName:"unknown",device:l,pressure:n.force});this.onMove(c)}}),a(this,"onTouchEnd",t=>{if(this.context.isInAR)for(let s=0;s<t.changedTouches.length;s++){const n=t.changedTouches[s],r=this.getPointerIndex(n.identifier),l=new An("pointerup",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:r,button:0,clientX:n.clientX,clientY:n.clientY,pointerType:"touch",buttonName:"unknown",device:this.getAndUpdateSpatialObjectForScreenPosition(r,n.clientX,n.clientY),pressure:n.force});this.onUp(l),this._pointerIds[r]=-1}}),a(this,"tempNearPlaneVector",new x),a(this,"tempFarPlaneVector",new x),a(this,"tempLookMatrix",new se),this.context=e,this.context.post_render_callbacks.push(this.onEndOfFrame)}addEventListener(e,t,s){if(this._eventListeners[e]||(this._eventListeners[e]=[]),!t||typeof t!="function"){console.error("Invalid call to addEventListener: callback is required and must be a function!");return}s?s={...s}:s={};let n=0;s?.queue!=null&&(n=s.queue);const r=this._eventListeners[e],l=r.find(c=>c.priority===n);l?l.listeners.push({callback:t,options:s}):(r.push({priority:n,listeners:[{callback:t,options:s}]}),r.sort((c,h)=>c.priority-h.priority))}removeEventListener(e,t,s){if(!this._eventListeners[e]||!t)return;const n=this._eventListeners[e];if(s?.queue!=null){const r=n.find(c=>c.priority===s.queue);if(!r)return;const l=r.listeners.findIndex(c=>c.callback===t);l>=0&&r.listeners.splice(l,1)}else for(const r of n){const l=r.listeners.findIndex(c=>c.callback===t);l>=0&&r.listeners.splice(l,1)}}dispatchEvent(e){var t,s,n,r;let l=!1;if(e instanceof nc){const c=this._eventListeners[e.type];if(c)for(const h of c)for(let d=0;d<h.listeners.length;d++){const u=h.listeners[d];if((s=(t=u.options)==null?void 0:t.signal)!=null&&s.aborted){h.listeners.splice(d,1),d--;continue}u.options.once&&(h.listeners.splice(d,1),d--),u.callback(e)}}if(e instanceof An){const c=this._eventListeners[e.type];if(c)for(const h of c){if(l)break;for(let d=0;d<h.listeners.length;d++){const u=h.listeners[d];if((r=(n=u.options)==null?void 0:n.signal)!=null&&r.aborted){h.listeners.splice(d,1),d--;continue}if(e.immediatePropagationStopped){l=!0,ct&&console.log("immediatePropagationStopped",e.type);break}else e.propagationStopped&&(l=!0,ct&&console.log("propagationStopped",e.type));u.options.once&&(h.listeners.splice(d,1),d--),u.callback(e)}}}}get mousePosition(){return this._pointerPositions[0]}get mousePositionRC(){return this._pointerPositionsRC[0]}get mouseDown(){return this._pointerDown[0]}get mouseUp(){return this._pointerUp[0]}get mouseClick(){return this._pointerClick[0]}get mouseDoubleClick(){return this._pointerDoubleClick[0]}get mousePressed(){return this._pointerPressed[0]}get mouseWheelChanged(){return this.getMouseWheelChanged(0)}get click(){return this._pointerClick[0]}get doubleClick(){return this._pointerDoubleClick[0]}getGamepad(e=0){return typeof navigator<"u"&&"getGamepads"in navigator&&navigator.getGamepads()[e]||null}setCursorPointer(){this.setCursor("pointer")}setCursorNormal(){this.unsetCursor("pointer")}setCursor(e){this._setCursorTypes.push(e),this._setCursorTypes.length>10&&this._setCursorTypes.shift(),this.updateCursor()}unsetCursor(e){for(let t=this._setCursorTypes.length-1;t>=0;t--)if(this._setCursorTypes[t]===e){this._setCursorTypes.splice(t,1),this.updateCursor();break}}updateCursor(){var e;((e=this._setCursorTypes)==null?void 0:e.length)==0?this.context.domElement.style.cursor="default":this.context.domElement.style.cursor=this._setCursorTypes[this._setCursorTypes.length-1]}getIsPointerIdInUse(e){for(const t of this._pointerEventsPressed)if(t.pointerId===e&&t.used)return!0;return!1}getPointerPressedCount(){let e=0;for(let t=0;t<this._pointerPressed.length;t++)this._pointerPressed[t]&&e++;return e}getPointerPosition(e){return e>=this._pointerPositions.length?null:this._pointerPositions[e]}getPointerPositionLastFrame(e){return e>=this._pointerPositionsLastFrame.length?null:this._pointerPositionsLastFrame[e]}getPointerPositionDelta(e){return e>=this._pointerPositionsDelta.length?null:this._pointerPositionsDelta[e]}getPointerPositionRC(e){return e>=this._pointerPositionsRC.length?null:this._pointerPositionsRC[e]}getPointerDown(e){return e>=this._pointerDown.length?!1:this._pointerDown[e]}getPointerUp(e){return e>=this._pointerUp.length?!1:this._pointerUp[e]}getPointerPressed(e){return e>=this._pointerPressed.length?!1:this._pointerPressed[e]}getPointerClicked(e){return e>=this._pointerClick.length?!1:this._pointerClick[e]}getPointerDoubleClicked(e){return e>=this._pointerDoubleClick.length?!1:this._pointerDoubleClick[e]}getPointerDownTime(e){return e>=this._pointerDownTime.length?-1:this._pointerDownTime[e]}getPointerUpTime(e){return e>=this._pointerUpTime.length?-1:this._pointerUpTime[e]}getPointerLongPress(e){return e>=this._pointerDownTime.length?!1:this.getPointerPressed(e)&&this.context.time.time-this._pointerDownTime[e]>this._longPressTimeThreshold}getIsMouse(e){return e<0||e>=this._pointerTypes.length?!1:this._pointerTypes[e]==="mouse"}getIsTouch(e){return e<0||e>=this._pointerTypes.length?!1:this._pointerTypes[e]==="touch"}getTouchesPressedCount(){let e=0;for(let t=0;t<this._pointerPressed.length;t++)this._pointerPressed[t]&&this.getIsTouch(t)&&e++;return e}getMouseWheelChanged(e=0){return e>=this._mouseWheelChanged.length?!1:this._mouseWheelChanged[e]}getMouseWheelDeltaY(e=0){return e>=this._mouseWheelDeltaY.length?0:this._mouseWheelDeltaY[e]}getPointerEvent(e){if(!(e>=this._pointerEvent.length))return this._pointerEvent[e]??void 0}*foreachPointerId(e){for(let t=0;t<this._pointerTypes.length;t++)if(this._pointerIsActive(t)){if(e!==void 0){const s=this._pointerTypes[t];if(Array.isArray(e)){let n=!1;for(const r of e)if(s===r){n=!0;break}if(!n)continue}else if(e!==s)continue}yield t}}*foreachTouchId(){for(let e=0;e<this._pointerTypes.length;e++)this._pointerTypes[e]==="touch"&&this._pointerIsActive[e]&&(yield e)}_pointerIsActive(e){return e<0?!1:this._pointerPressed[e]||this._pointerDown[e]||this._pointerUp[e]}onDownButton(e,t){let s=this._pressedStack.get(e);s||(s=[],this._pressedStack.set(e,s)),s.push(t)}onReleaseButton(e,t){const s=this._pressedStack.get(e);if(!s)return;const n=s.indexOf(t);n>=0&&s.splice(n,1)}getFirstPressedButtonForPointer(e){const t=this._pressedStack.get(e);if(t)return t[0]}getLatestPressedButtonForPointer(e){const t=this._pressedStack.get(e);if(t)return t[t.length-1]}getKeyDown(e){if(e!==void 0)return this.isKeyDown(e);for(const t in this.keysPressed){const s=this.keysPressed[t];if(s.startFrame===this.context.time.frameCount)return s.key}return null}getKeyPressed(e){if(e!==void 0)return this.isKeyPressed(e);for(const t in this.keysPressed){const s=this.keysPressed[t];if(s.pressed)return s.key}return null}getKeyUp(e){if(e!==void 0)return this.isKeyUp(e);for(const t in this.keysPressed){const s=this.keysPressed[t];return s.pressed===!1&&s.frame===this.context.time.frameCount}return null}isKeyDown(e){if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const t=this.getCodeForCommonKeyName(e);if(t!==null){for(const n of t)if(this.isKeyDown(n))return!0;return!1}const s=this.keysPressed[e];return s?s.startFrame===this.context.time.frameCount&&s.pressed:!1}isKeyUp(e){if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const t=this.getCodeForCommonKeyName(e);if(t!==null){for(const n of t)if(this.isKeyUp(n))return!0;return!1}const s=this.keysPressed[e];return s?s.frame===this.context.time.frameCount&&s.pressed===!1:!1}isKeyPressed(e){if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const t=this.getCodeForCommonKeyName(e);if(t!==null){for(const n of t)if(this.isKeyPressed(n))return!0;return!1}const s=this.keysPressed[e];return s&&s.pressed||!1}getCodeForCommonKeyName(e){if(e.length===1){if(e>="0"&&e<="9")return["Digit"+e];if(e>="a"&&e<="z")return["Key"+e.toUpperCase()];if(e==" ")return["Space"]}switch(e){case"shift":case"Shift":return["ShiftLeft","ShiftRight"];case"control":case"Control":return["ControlLeft","ControlRight"];case"alt":case"Alt":return["AltLeft","AltRight"]}return null}createInputEvent(e){switch(e.type){case"pointerdown":ct&&Be("Create Pointer down"),this.onDownButton(e.deviceIndex,e.button),this.onDown(e);break;case"pointermove":ct&&Be("Create Pointer move"),this.onMove(e);break;case"pointerup":ct&&Be("Create Pointer up"),this.onUp(e),this.onReleaseButton(e.deviceIndex,e.button);break}}convertScreenspaceToRaycastSpace(e){return e.x=(e.x-this.context.domX)/this.context.domWidth*2-1,e.y=-((e.y-this.context.domY)/this.context.domHeight)*2+1,e}bindEvents(){this.unbindEvents(),this._htmlEventSource=this.context.renderer.domElement,window.addEventListener("contextmenu",this.onContextMenu),this._htmlEventSource.addEventListener("pointerdown",this.onPointerDown,{passive:!0}),window.addEventListener("pointermove",this.onPointerMove,{passive:!0,capture:!0}),window.addEventListener("pointerup",this.onPointerUp,{passive:!0}),window.addEventListener("pointercancel",this.onPointerCancel,{passive:!0}),window.addEventListener("touchstart",this.onTouchStart,{passive:!0}),window.addEventListener("touchmove",this.onTouchMove,{passive:!0}),window.addEventListener("touchend",this.onTouchEnd,{passive:!0}),this._htmlEventSource.addEventListener("wheel",this.onMouseWheel,{passive:!0}),window.addEventListener("wheel",this.onWheelWindow,{passive:!0}),window.addEventListener("keydown",this.onKeyDown,!1),window.addEventListener("keypress",this.onKeyPressed,!1),window.addEventListener("keyup",this.onKeyUp,!1),window.addEventListener("blur",this.onLostFocus)}unbindEvents(){var e,t;window.removeEventListener("contextmenu",this.onContextMenu),(e=this._htmlEventSource)==null||e.removeEventListener("pointerdown",this.onPointerDown),window.removeEventListener("pointermove",this.onPointerMove),window.removeEventListener("pointerup",this.onPointerUp),window.removeEventListener("pointercancel",this.onPointerCancel),window.removeEventListener("touchstart",this.onTouchStart),window.removeEventListener("touchmove",this.onTouchMove),window.removeEventListener("touchend",this.onTouchEnd),(t=this._htmlEventSource)==null||t.removeEventListener("wheel",this.onMouseWheel,!1),window.removeEventListener("wheel",this.onWheelWindow,!1),window.removeEventListener("keydown",this.onKeyDown,!1),window.removeEventListener("keypress",this.onKeyPressed,!1),window.removeEventListener("keyup",this.onKeyUp,!1),window.removeEventListener("blur",this.onLostFocus)}dispose(){const e=this.context.post_render_callbacks.indexOf(this.onEndOfFrame);e>=0&&this.context.post_render_callbacks.splice(e,1),this.unbindEvents()}canReceiveInput(e){var t;return e.target===((t=this.context.renderer)==null?void 0:t.domElement)||e.target===this.context.domElement||this.context.isInAR||this.context.isInAR&&e.target===document.body&&Y.isMozillaXR()?!0:(ct&&console.warn("CanReceiveInput:False for",e.target),!1)}getPointerId(e,t){return e.pointerType==="mouse"?0+(t??e.button):this.getPointerIndex(e.pointerId)}getButtonName(e){const t=e.button;if(e.pointerType==="mouse")switch(t){case 0:return"left";case 1:return"middle";case 2:return"right"}return"unknown"}getAndUpdateSpatialObjectForScreenPosition(e,t,s){let n=this._pointerSpace[e];n||(n=new E,this._pointerSpace[e]=n),this._pointerSpace[e]=n;const r=this.context.mainCamera;if(r){const l=this.tempNearPlaneVector.set(t,s,-1);this.convertScreenspaceToRaycastSpace(l);const c=this.tempFarPlaneVector.set(l.x,l.y,1);l.unproject(r),c.unproject(r);const h=r.worldUp||X(0,1,0).applyQuaternion(Se(r));this.tempLookMatrix.lookAt(c,l,h),n.position.set(l.x,l.y,l.z),n.quaternion.setFromRotationMatrix(this.tempLookMatrix)}return n}isInRect(e){if(this.context.isInXR)return!0;const t=this.context.domElement.getBoundingClientRect(),s=e.clientX,n=e.clientY,r=s>=t.x&&s<=t.right&&n>=t.y&&n<=t.bottom;return ct&&!r&&console.log("Not in rect",t,s,n),r}onDown(e){const t=e.pointerId;if(this.getPointerPressed(t)&&console.warn(`Received pointerDown for pointerId that is already pressed: ${t}`,ct?e:""),ct&&console.log(e.pointerType,"DOWN",t),!!this.isInRect(e)){for(this.setPointerState(t,this._pointerPressed,!0),this.setPointerState(t,this._pointerDown,!0),this.setPointerStateT(t,this._pointerEvent,e.source);t>=this._pointerTypes.length;)this._pointerTypes.push(e.pointerType);for(this._pointerTypes[t]=e.pointerType;t>=this._pointerPositionDown.length;)this._pointerPositionDown.push(new x);for(this._pointerPositionDown[t].set(e.clientX,e.clientY,e.clientZ??0);t>=this._pointerPositions.length;)this._pointerPositions.push(new le);this._pointerPositions[t].set(e.clientX,e.clientY),t>=this._pointerDownTime.length&&this._pointerDownTime.push(0),this._pointerDownTime[t]=this.context.time.realtimeSinceStartup,this.updatePointerPosition(e),this._pointerEventsPressed.push(e),this.onDispatchEvent(e)}}onMove(e){const t=e.pointerId,s=this.getPointerPressed(t);s===!1&&!this.isInRect(e)||e.pointerType==="touch"&&!s||(this.updatePointerPosition(e),this.setPointerStateT(t,this._pointerEvent,e.source),this.onDispatchEvent(e))}onUp(e){const t=e.pointerId;if(!this.getPointerPressed(t)){ct&&console.log(e.pointerType,"UP",t,"was not down");return}ct&&console.log(e.pointerType,"UP",t),this.setPointerState(t,this._pointerPressed,!1),this.setPointerStateT(t,this._pointerEvent,e.source),this.setPointerState(t,this._pointerUp,!0),this.updatePointerPosition(e);for(let c=this._pointerEventsPressed.length-1;c>=0;c--)if(this._pointerEventsPressed[c].pointerId===t){this._pointerEventsPressed.splice(c,1);break}if(!this._pointerPositionDown[t]){ct&&be("Received pointer up event without matching down event for button: "+t),console.warn("Received pointer up event without matching down event for button: "+t);return}const s=this._pointerUpTime[t],n=this._pointerDownTime[t],r=this.context.time.realtimeSinceStartup,l=r-n;if(t>=this._pointerUpTime.length&&this._pointerUpTime.push(-99),this._pointerUpTime[t]=r,l<1){let c=e.clientX-this._pointerPositionDown[t].x,h=e.clientY-this._pointerPositionDown[t].y,d=0;if(e.isSpatial&&e.clientZ!=null&&(d=e.clientZ-this._pointerPositionDown[t].z,c*=200,h*=200,d*=200),Math.abs(c)<5&&Math.abs(h)<5&&Math.abs(d)<5){this.setPointerState(t,this._pointerClick,!0),e.isClick=!0;const u=r-s;ct&&console.log("CLICK",t,c,h,d,u),u<this._doubleClickTimeThreshold&&u>0&&(this.setPointerState(t,this._pointerDoubleClick,!0),e.isDoubleClick=!0)}}this.onDispatchEvent(e)}updatePointerPosition(e){const t=e.pointerId;for(;t>=this._pointerPositions.length;)this._pointerPositions.push(new le);for(;t>=this._pointerPositionsLastFrame.length;)this._pointerPositionsLastFrame.push(new le);for(;t>=this._pointerPositionsDelta.length;)this._pointerPositionsDelta.push(new le);const s=this._pointerPositionsLastFrame[t];s.copy(this._pointerPositions[t]);const n=this._pointerPositionsDelta[t];let r=e.clientX-s.x,l=e.clientY-s.y;if(e.source instanceof MouseEvent||e.source instanceof TouchEvent){const u=e.source;r===0&&u.movementX!==0&&(r=u.movementX||0),l===0&&u.movementY!==0&&(l=u.movementY||0)}n.x+=r,n.y+=l,this._pointerPositions[t].x=e.clientX,this._pointerPositions[t].y=e.clientY;const c=e.clientX,h=e.clientY;for(;t>=this._pointerPositionsRC.length;)this._pointerPositionsRC.push(new le);const d=this._pointerPositionsRC[t];d.set(c,h),this.convertScreenspaceToRaycastSpace(d)}getPointerIndex(e){let t=-1;for(let s=0;s<this._pointerIds.length;s++){if(this._pointerIds[s]===e)return s;t===-1&&this._pointerIds[s]===-1&&(t=s)}return t!==-1?(this._pointerIds[t]=e,t):(ct&&console.log("PUSH pointerId:",e),this._pointerIds.push(e),this._pointerIds.length-1)}setPointerState(e,t,s){t[e]=s}setPointerStateT(e,t,s){return t[e]=s,s}onDispatchEvent(e){const t=ee.Current;try{ee.Current=this.context,this.dispatchEvent(e)}finally{ee.Current=t}}}const Ea=new se().makeRotationY(Math.PI),Ki=new H().setFromAxisAngle(new x(0,1,0),Math.PI),qk=C("debugwebxr");class Xk{constructor(){if(a(this,"priority",-1e5),a(this,"gameObject"),this.gameObject=new E,this.gameObject.name="Implicit XR Rig",qk){const e=Fg(16733661);e.position.y+=.5,this.gameObject.add(e)}}isXRRig(){return!0}get isActive(){return this.gameObject.visible}}const In=C("debugwebxr"),Fd=C("debugcustomgesture"),Qk="https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles",Yk="generic-trigger",Kk=new H().setFromEuler(new jt(Cn.degToRad(0),Cn.degToRad(-90),Cn.degToRad(-90))),Zk=new x(.04,-.04,0);class _g{constructor(e,t,s){a(this,"xr"),a(this,"inputSource"),a(this,"index",0),a(this,"emitEvents",!0),a(this,"_connected",!0),a(this,"_isTracking",!1),a(this,"__gamepad"),a(this,"__hand"),a(this,"__side"),a(this,"_hitTestSource"),a(this,"_hasSelectEvent",!1),a(this,"_isMxInk",!1),a(this,"_isMetaQuestTouchController",!1),a(this,"_handJointPoses",new Map),a(this,"_gripMatrix",new se),a(this,"_gripPosition",new x),a(this,"_gripQuaternion",new H),a(this,"_linearVelocity",new x),a(this,"_rayPositionRaw",new x),a(this,"_rayRotationRaw",new H),a(this,"_rayMatrix",new se),a(this,"_rayPosition",new x),a(this,"_rayQuaternion",new H),a(this,"_gripWorldPosition",new x),a(this,"_gripWorldQuaternion",new H),a(this,"_rayWorldPosition",new x),a(this,"_rayWorldQuaternion",new H),a(this,"_pinchPosition",new x),a(this,"_ray"),a(this,"_hand_wristDotUp"),a(this,"_object"),a(this,"_gripSpaceObject"),a(this,"_raySpaceObject"),a(this,"model",null),a(this,"_debugAxesHelper",new Si(.15)),a(this,"_debugGripAxesHelper",new Si(.07)),a(this,"_debugRayAxesHelper",new Si(.07)),a(this,"_hitTestSourcePromise",null),a(this,"onPointerHits",n=>{}),a(this,"_needleGamepadButtons",{}),a(this,"_buttonMap",new Map),a(this,"_motioncontroller"),a(this,"_layout"),a(this,"getMotionController"),a(this,"emitPointerDownEvent",!0),a(this,"emitPointerUpEvent",!0),a(this,"emitPointerMoveEvent",!0),a(this,"pointerMoveDistanceThreshold",.03),a(this,"pointerMoveAngleThreshold",.05),a(this,"_selectButtonIndex"),a(this,"_squeezeButtonIndex"),a(this,"onSelectStart",n=>{var r,l,c,h;if(!this.emitPointerDownEvent||this.inputSource!==n.inputSource)return;this.onUpdateFrame(n.frame),this._hasSelectEvent=!0;const d=(r=this._layout)==null?void 0:r.selectComponentId,u=(h=(c=(l=this._layout)==null?void 0:l.components[d])==null?void 0:c.gamepadIndices)==null?void 0:h.button;u!==void 0&&(this._selectButtonIndex=u),!Fd&&(In&&G.DrawDirection(this.rayWorldPosition,X(0,.01,1).applyQuaternion(this.rayWorldQuaternion),16711680,10),this.emitPointerEvent(Fe.PointerDown,this._selectButtonIndex||0,"xr-standard-trigger",!0,n))}),a(this,"onSelectEnd",n=>{this.emitPointerUpEvent&&(Fd||this.inputSource===n.inputSource&&this.emitPointerEvent(Fe.PointerUp,this._selectButtonIndex||0,"xr-standard-trigger",!0,n))}),a(this,"onSequeezeStart",n=>{var r,l,c;this.emitPointerDownEvent&&this.inputSource===n.inputSource&&(this._squeezeButtonIndex=(c=(l=(r=this._layout)==null?void 0:r.components["xr-standard-squeeze"])==null?void 0:l.gamepadIndices)==null?void 0:c.button,this._squeezeButtonIndex!==void 0&&(In&&G.DrawDirection(this.rayWorldPosition,X(0,.01,1).applyQuaternion(this.rayWorldQuaternion),255,10),this.emitPointerEvent(Fe.PointerDown,this._squeezeButtonIndex||0,"xr-standard-squeeze",!0,n)))}),a(this,"onSequeezeEnd",n=>{this.emitPointerUpEvent&&this.inputSource===n.inputSource&&this._squeezeButtonIndex!==void 0&&this.emitPointerEvent(Fe.PointerUp,this._squeezeButtonIndex||0,"xr-standard-squeeze",!0,n)}),a(this,"states",{}),a(this,"_didMoveLastFrame",!1),a(this,"_lastPointerMovePosition",new x),a(this,"_lastPointerMoveQuaternion",new H),a(this,"pointerInit"),this.xr=e,this.inputSource=t,this.index=s,this._object=new E,this._object.name=`NeedleXRController_${s}`,In&&(this._object.add(this._debugAxesHelper),this._gripSpaceObject=new E,this._raySpaceObject=new E,this._gripSpaceObject.name=`NeedleXRController_${s}_gripSpace`,this._raySpaceObject.name=`NeedleXRController_${s}_raySpace`,this._gripSpaceObject.add(this._debugGripAxesHelper),this._raySpaceObject.add(this._debugRayAxesHelper),this.xr.context.scene.add(this._gripSpaceObject),this.xr.context.scene.add(this._raySpaceObject)),this.xr.context.scene.add(this._object),this._ray=new uo,this.pointerInit={origin:this,pointerType:this.hand?"hand":"controller",deviceIndex:this.index,pointerId:-1,mode:this.inputSource.targetRayMode,ray:this._ray,device:this._object,buttonName:"none"},this.initialize(),this.subscribeEvents()}get context(){return this.xr.context}get connected(){return this._connected}get isTracking(){return this._isTracking}get gamepad(){return this.__gamepad??(this.__gamepad=this.inputSource.gamepad)}get isHand(){return this.hand!=null}get hand(){return this.__hand??(this.__hand=this.inputSource.hand)}get handObject(){return this.context.renderer.xr.getHand(this.index)}get profiles(){return this.inputSource.profiles}get layout(){return this._layout}get targetRayMode(){return this.inputSource.targetRayMode}get targetRaySpace(){return this.inputSource.targetRaySpace}get gripSpace(){return this.inputSource.gripSpace}get side(){return this.__side??(this.__side=this.inputSource.handedness)}get isRight(){return this.side==="right"}get isLeft(){return this.side==="left"}get isStylus(){return this._isMxInk}getHitTestSource(){return this._hitTestSource||this._requestHitTestSource(),this._hitTestSource}get hasHitTestSource(){return this._hitTestSource}cancelHitTestSource(){this._hitTestSource&&(this._hitTestSource.cancel(),this._hitTestSource=void 0)}get hasSelectEvent(){return this._hasSelectEvent}getHitTest(){return this.xr.getHitTest(this)}getHandJointPose(e,t){var s;if(t=t||this.xr.frame,!this.hand||!(t!=null&&t.getJointPose)||!this.xr.referenceSpace)return null;let n=(s=this._handJointPoses)==null?void 0:s.get(e);return n||(n=t.getJointPose(e,this.xr.referenceSpace),n&&this._handJointPoses.set(e,n),n)}get gripPosition(){return X(this._gripPosition)}get gripQuaternion(){return vs(this._gripQuaternion)}get gripMatrix(){return this._gripMatrix}get gripLinearVelocity(){return X(this._linearVelocity).applyQuaternion(Ki)}get rayPosition(){return X(this._rayPosition)}get rayQuaternion(){return vs(this._rayQuaternion)}get gripWorldPosition(){return X(this._gripWorldPosition)}get gripWorldQuaternion(){return vs(this._gripWorldQuaternion)}get rayWorldPosition(){return X(this._rayWorldPosition)}updateRayWorldPosition(){var e;const t=(e=this.xr.context.mainCamera)==null?void 0:e.parent;this._rayWorldPosition.copy(this._rayPositionRaw),t&&this._rayWorldPosition.applyMatrix4(t.matrixWorld)}get rayWorldQuaternion(){return vs(this._rayWorldQuaternion)}get pinchPosition(){return X(this._pinchPosition)}updateRayWorldQuaternion(){var e;const t=(e=this.xr.context.mainCamera)==null?void 0:e.parent,s=t?Se(t):void 0;this._rayWorldQuaternion.copy(this._rayRotationRaw).multiply(Ki),s&&this._rayWorldQuaternion.premultiply(s)}get ray(){return this._ray.origin.copy(this.rayWorldPosition),this._ray.direction.copy(X(0,0,1).applyQuaternion(this.rayWorldQuaternion)),this._ray}get handWristDotUp(){var e;if(this._hand_wristDotUp!==void 0)return this._hand_wristDotUp;const t=(e=this.handObject)==null?void 0:e.joints.wrist;if(t){const s=X(0,1,0).applyQuaternion(t.quaternion),n=X(0,1,0).dot(s);return this._hand_wristDotUp=n}}get isHandUpsideDown(){return this.handWristDotUp!==void 0?this.handWristDotUp<-.7:!1}get isTeleportGesture(){var e;return this.isHandUpsideDown&&((e=this.getGesture("pinch"))==null?void 0:e.isDown)}get object(){return this._object}async getModelUrl(){var e;return(e=this.getMotionController)==null?void 0:e.then(t=>t?.assetUrl||null)}_requestHitTestSource(){var e;return this._hitTestSourcePromise?this._hitTestSourcePromise:this.xr.mode==="immersive-ar"&&this.inputSource.targetRayMode==="tracked-pointer"&&this.xr.session.requestHitTestSourceForTransientInput?this._hitTestSourcePromise=((e=this.xr.session.requestHitTestSourceForTransientInput({profile:this.inputSource.profiles[0],offsetRay:new XRRay}))==null?void 0:e.then(t=>(this._hitTestSourcePromise=null,this.connected?this._hitTestSource=t:(t.cancel(),null))))??null:null}onUpdate(e){this.onUpdateFrame(e),this.updateInputEvents(),this.onUpdateMove()}onRenderDebug(){var e;G.DrawSphere(this.rayWorldPosition,.003),G.DrawDirection(this.rayWorldPosition,X(0,0,10).applyQuaternion(this.rayWorldQuaternion));const t=(this.inputSource.gripSpace?this.gripWorldPosition:this.object.worldPosition).sub(this.object.worldForward.multiplyScalar(.1)),s=this.inputSource.profiles.join(`
147
+ `);let n=`Controller[${this.index}] (${this.inputSource.targetRayMode}, ${this.side})
148
+ C:${this.connected?"x":"-"} T:${this.isTracking?"x":"-"} Hand:${this.inputSource.hand?"x":"-"} Pen: ${this._isMxInk?"x":"-"}`;if(this.inputSource.hand&&(n+=`
149
+ Pinch: ${(e=this.getGesture("pinch"))==null?void 0:e.value.toFixed(3)}`),n+=`
150
+ `+s,n+=`
151
+ `+(this.inputSource.targetRaySpace?"Ray: x":"Ray: -")+(this.inputSource.gripSpace?" Grip: x":" Grip: -")+(this.inputSource.gamepad?` Gamepad: ${this.inputSource.gamepad.mapping}`:" Gamepad: -"),this.inputSource.gamepad){const r=this.inputSource.gamepad;let l="[btns "+r.buttons.length+"]: "+r.buttons.map(c=>c.value.toPrecision(1)).join(",");l+=`
152
+ [axes `+r.axes.length+"]: "+r.axes.map(c=>c.toPrecision(1)).join(","),n+=`
153
+ `+l}G.DrawLabel(t,n,.006)}onUpdateFrame(e){var t,s,n,r,l,c,h,d,u,p,g;if(this._handJointPoses.clear(),this._hand_wristDotUp=void 0,!this.xr.referenceSpace){this._isTracking=!1;return}const f=e.getPose(this.inputSource.targetRaySpace,this.xr.referenceSpace);this._isTracking=f!=null;let y=null,b=null,v=null,_=null;if(f){const M=f.transform;this._rayMatrix.fromArray(M.matrix).premultiply(Ea),this._rayMatrix.decompose(this._rayPosition,this._rayQuaternion,X(1,1,1)),v=X(M.position),_=vs(M.orientation),this._rayPositionRaw.copy(v),this._rayRotationRaw.copy(_)}if(this.inputSource.gripSpace){const M=e.getPose(this.inputSource.gripSpace,this.xr.referenceSpace);if(M){const T=M.transform;if(y=X(T.position),b=vs(T.orientation),this._gripMatrix.fromArray(T.matrix).premultiply(Ea),this._gripMatrix.decompose(this._gripPosition,this._gripQuaternion,X(1,1,1)),"linearVelocity"in M&&M.linearVelocity){const L=M.linearVelocity;this._linearVelocity.set(L.x,L.y,L.z)}}}(t=this.xr.context.mainCamera)!=null&&t.parent&&(this._object.parent!==((s=this.xr.context.mainCamera)==null?void 0:s.parent)&&this.xr.context.mainCamera.parent.add(this._object),this._gripSpaceObject!==void 0&&((n=this._gripSpaceObject)==null?void 0:n.parent)!==((r=this.xr.context.mainCamera)==null?void 0:r.parent)&&this.xr.context.mainCamera.parent.add(this._gripSpaceObject),this._raySpaceObject!==void 0&&((l=this._raySpaceObject)==null?void 0:l.parent)!==((c=this.xr.context.mainCamera)==null?void 0:c.parent)&&this.xr.context.mainCamera.parent.add(this._raySpaceObject));const w=this.hand;if(w){let M=!1;const T=w.get("wrist"),L=T&&this.getHandJointPose(T,e);if(L){M=!0;const D=L.transform.position,V=L.transform.orientation;this._object.position.set(D.x,D.y,D.z),this._object.quaternion.set(V.x,V.y,V.z,V.w).multiply(Ki)}M||(this._object.position.copy(this._rayPosition),this._object.quaternion.copy(this._rayQuaternion).multiply(Ki));const B=w.get("middle-finger-metacarpal"),z=B&&this.getHandJointPose(B,e);z&&(this._gripMatrix.fromArray(z.transform.matrix).premultiply(Ea),this._gripMatrix.decompose(this._gripPosition,this._gripQuaternion,X(1,1,1)),y=X().copy(z.transform.position),b=vs().copy(z.transform.orientation),b.multiply(Kk),y.add(X(Zk).applyQuaternion(b)))}else this.inputSource.gripSpace&&this.targetRayMode==="transient-pointer"&&y&&b?(this._object.position.copy(y),this._object.quaternion.copy(b).multiply(Ki)):v&&_&&(this._object.position.copy(v),this._object.quaternion.copy(_).multiply(Ki));In&&(v&&_&&((h=this._raySpaceObject)==null||h.position.copy(v),(d=this._raySpaceObject)==null||d.quaternion.copy(_).multiply(Ki)),y&&b&&((u=this._gripSpaceObject)==null||u.position.copy(y),(p=this._gripSpaceObject)==null||p.quaternion.copy(b).multiply(Ki)));const S=(g=this.xr.context.mainCamera)==null?void 0:g.parent,k=S?Se(S):void 0;y&&b&&(this._gripWorldPosition.copy(y),S&&this._gripWorldPosition.applyMatrix4(S.matrixWorld),this._gripWorldQuaternion.copy(b),this._gripWorldQuaternion.multiply(Ki),k&&this._gripWorldQuaternion.premultiply(k)),this.updateRayWorldPosition(),this.updateRayWorldQuaternion()}onDisconnected(){var e,t,s,n,r,l;this._connected=!1,In&&console.warn("Controller disconnected",this.index);for(const c of this._object.children)this.xr.context.scene.attach(c);(e=this._object)==null||e.removeFromParent(),(t=this._debugAxesHelper)==null||t.removeFromParent(),(s=this._debugGripAxesHelper)==null||s.removeFromParent(),(n=this._debugRayAxesHelper)==null||n.removeFromParent(),(r=this._gripSpaceObject)==null||r.removeFromParent(),(l=this._raySpaceObject)==null||l.removeFromParent(),this.unsubscribeEvents(),this._hitTestSource&&(this._hitTestSource.cancel(),this._hitTestSource=void 0)}getButton(e){var t;if(!this._layout)return;switch(e){case"primary-button":if(this.isLeft)e="x-button";else if(this.isRight)e="a-button";else return;break;case"primary":return this.hand?this.getGesture("pinch"):this.toNeedleGamepadButton(0,e)}if(this._buttonMap.has(e))return this.toNeedleGamepadButton(this._buttonMap.get(e),e);const s=(t=this._layout)==null?void 0:t.components[e];if(s!=null&&s.gamepadIndices)switch(s.type){case"button":case"squeeze":if(this.inputSource.gamepad){const n=s.gamepadIndices.button;return this._buttonMap.set(e,n),this.toNeedleGamepadButton(n,e)}break;default:console.warn("Unsupported component type",s.type);break}this._buttonMap.set(e,void 0)}getGesture(e){const t=this.states[e];if(!t)return null;this.states[e]=t;const s=this._needleGamepadButtons[e]||new i_(void 0,e);return s.pressed=t.pressed,s.value=t.value,s.isDown=t.isDown,s.isUp=t.isUp,this._needleGamepadButtons[e]=s,s}getPointerId(e){if((e==="primary"||e==="pinch")&&(e=0),typeof e!="number"){const t=this._buttonMap.get(e);if(t===void 0)return;e=t}return this.index*10+e}toNeedleGamepadButton(e,t){var s,n;if(!((s=this.inputSource.gamepad)!=null&&s.buttons))return;const r=(n=this.inputSource.gamepad)==null?void 0:n.buttons[e],l=this.states[e],c=this._needleGamepadButtons[e]||new i_(e,t);return r&&(c.pressed=r.pressed,c.value=r.value,c.touched=r.touched),l&&(c.isDown=l.isDown,c.isUp=l.isUp),this._needleGamepadButtons[e]=c,c}getStick(e){var t,s,n,r,l,c,h,d,u;if(!this._layout)return{x:0,y:0,z:0};if(e==="primary"){const g=((t=this.inputSource.gamepad)==null?void 0:t.axes[0])||0,f=((s=this.inputSource.gamepad)==null?void 0:s.axes[1])||0,y=((r=(n=this.inputSource.gamepad)==null?void 0:n.buttons[3])==null?void 0:r.value)||0;return{x:g,y:f,z:y}}const p=(l=this._layout)==null?void 0:l.components[e];if(p!=null&&p.gamepadIndices)switch(p.type){case"thumbstick":if(this.inputSource.gamepad){const g=p.gamepadIndices.xAxis,f=p.gamepadIndices.yAxis;let y=(c=this.inputSource.gamepad)==null?void 0:c.axes[g],b=(h=this.inputSource.gamepad)==null?void 0:h.axes[f];y*=-1,b*=-1;const v=p.gamepadIndices.button,_=(u=(d=this.inputSource.gamepad)==null?void 0:d.buttons[v])==null?void 0:u.value;return{x:y,y:b,z:_}}}return{x:0,y:0,z:0}}initialize(){if(this._hasSelectEvent=this.profiles.includes("generic-hand-select")||this.profiles.some(e=>e.startsWith("generic-trigger")),this._isMetaQuestTouchController=this.profiles.includes("meta-quest-touch-plus")||this.profiles.includes("oculus-touch-v3"),this._isMxInk=this.profiles.includes("logitech-mx-ink"),!this._layout){if(this.inputSource.targetRayMode==="transient-pointer")return;const e=pO(this.inputSource,Qk,Yk);this.getMotionController=e.then(t=>{var s;if(!this.connected)return null;this._motioncontroller=new mO(this.inputSource,t.profile,t.assetPath||"");const n=t.profile.layouts[this.inputSource.handedness];if(this._layout=n,this._layout&&!((s=this._layout.gamepad)!=null&&s.length)){this._layout.gamepad=[];for(const r in this._layout.components){const l=this._layout.components[r];this._layout.gamepad[l.gamepadIndices.button]=r}}return this._motioncontroller}).catch(t=>(this.inputSource&&console.warn("Couldn't initialize motion controller profile for ",this.inputSource,t),null))}}subscribeEvents(){this.xr.session.addEventListener("selectstart",this.onSelectStart),this.xr.session.addEventListener("selectend",this.onSelectEnd),this.xr.session.addEventListener("squeezestart",this.onSequeezeStart),this.xr.session.addEventListener("squeezeend",this.onSequeezeEnd)}unsubscribeEvents(){this.xr.session.removeEventListener("selectstart",this.onSelectStart),this.xr.session.removeEventListener("selectend",this.onSelectEnd),this.xr.session.removeEventListener("squeezestart",this.onSequeezeStart),this.xr.session.removeEventListener("squeezeend",this.onSequeezeEnd)}updateInputEvents(){var e,t,s;if((e=this.gamepad)!=null&&e.buttons){for(let n=0;n<this.gamepad.buttons.length;n++){const r=this.gamepad.buttons[n],l=this.states[n]||new t_;let c=null;this._isMxInk&&(n===4||n===5)?(r.value>0&&!l.pressed?(c="pointerdown",l.isDown=!0,l.isUp=!1):r.value===0&&l.pressed?(c="pointerup",l.isDown=!1,l.isUp=!0):l.pressed&&(c="pointermove",l.isDown=!1,l.isUp=!1),l.pressed=r.value>0,l.value=r.value):(r.pressed&&!l.pressed?(c="pointerdown",l.isDown=!0,l.isUp=!1):!r.pressed&&l.pressed?(c="pointerup",l.isDown=!1,l.isUp=!0):(l.isDown=!1,l.isUp=!1),l.pressed=r.pressed,l.value=r.value),this.states[n]=l;const h=n!==this._selectButtonIndex&&n!==this._squeezeButtonIndex;if(c!=null&&h){let d=(t=this._layout)==null?void 0:t.gamepad[n];this._isMxInk&&n===4&&(d="stylus-touch"),this._isMxInk&&n===5&&(d="stylus-tip"),(In||Fd)&&console.log("Emitting pointer event",c,n,d,r.value,this.gamepad,this._layout),this.emitPointerEvent(c,n,d??"none",!1,null,r.value)}}if(this._isMetaQuestTouchController){const n=this.gamepad.buttons.length-1,r=this.states[n];if(r&&r.isDown){const l=this.context.menu;l.spatialMenuIsVisible?l.setSpatialMenuVisible(!1):this.context.menu.setSpatialMenuVisible(!0)}}}if(this.hand){const n=this.handObject;if(n){const r=n.joints["index-finger-tip"],l=n.joints["thumb-tip"];if(r&&l){const c=r.position.distanceTo(l.position);this._pinchPosition.lerpVectors(r.position,l.position,.5);const h=(s=this.xr.context.mainCamera)==null?void 0:s.parent;if(h&&this._pinchPosition.applyMatrix4(h.matrixWorld),c!==0){const d=this.states.pinch||new t_,u=(.02+.01)*1.5;d.value=1-(c-.02)/u;const p=c<.02-.01,g=c>.02+.01;p&&!d.pressed?(Fd&&console.log("pinch start",c),d.isDown=!0,d.isUp=!1,d.pressed=!0):g&&d.pressed?(d.isDown=!1,d.isUp=!0,d.pressed=!1):(d.isDown=!1,d.isUp=!1),this.states.pinch=d}}}}}onUpdateMove(){var e,t;if(!this.emitPointerMoveEvent)return;let s=!1;if(this._lastPointerMovePosition.distanceTo(this.gripWorldPosition)>this.pointerMoveDistanceThreshold*this.xr.rigScale&&(s=!0),s||this._lastPointerMoveQuaternion.angleTo(this.gripWorldQuaternion)>this.pointerMoveAngleThreshold&&(s=!0),s){this._didMoveLastFrame=!0,this._lastPointerMovePosition.copy(this.gripWorldPosition),this._lastPointerMoveQuaternion.copy(this.gripWorldQuaternion),In&&G.DrawLabel(this.rayWorldPosition.add(this.object.worldForward.multiplyScalar(.1)),"move",.01);let n=this.xr.context.input.getFirstPressedButtonForPointer(this.index);n===void 0&&(n=0);const r=(t=(e=this.gamepad)==null?void 0:e.buttons[n])==null?void 0:t.value;this.emitPointerEvent("pointermove",n,"none",!1,null,r)}else this._didMoveLastFrame=!1}emitPointerEvent(e,t,s,n,r=null,l){if(!this.emitEvents){In&&e!==Fe.PointerMove&&console.warn("Pointer events are disabled for this controller",this.index,e,t);return}if(this.xr.mode==="immersive-vr"||this.xr.isPassThrough){this.pointerInit.origin=this,this.pointerInit.pointerId=this.getPointerId(t),this.pointerInit.pointerType=this.hand?"hand":"controller",this.pointerInit.button=t,this.pointerInit.buttonName=s,this.pointerInit.isPrimary=n,this.pointerInit.mode=this.inputSource.targetRayMode,this.pointerInit.ray=this.ray,this.pointerInit.device=this.object,this.pointerInit.pressure=l,this.pointerInit.clientX=this._rayPosition.x/this.xr.rigScale,this.pointerInit.clientY=this._rayPosition.y/this.xr.rigScale,this.pointerInit.clientZ=this._rayPosition.z/this.xr.rigScale;const c=ee.Current;ee.Current=this.xr.context,In&&e!=="pointermove"&&console.warn("Pointer event",e,t,s,{...this.pointerInit}),this.xr.context.input.createInputEvent(new An(e,r,this.pointerInit)),ee.Current=c}}}class t_{constructor(){a(this,"isDown",!1),a(this,"isUp",!1),a(this,"pressed",!1),a(this,"value",0)}}class i_{constructor(e,t){a(this,"index"),a(this,"name"),a(this,"touched",!1),a(this,"pressed",!1),a(this,"value",0),a(this,"isDown",!1),a(this,"isUp",!1),this.index=e,this.name=t}}var wg=(o=>(o.Visible="application-visible",o.Hidden="application-hidden",o.MuteChanged="application-mutechanged",o))(wg||{});let Ud=!1;const Aa=[];function _r(){if(Ud)return;F()&&console.debug("User interaction registered: audio can now be played"),Ud=!0;const o=[...Aa];Aa.length=0,o.forEach(e=>e())}document.addEventListener("mousedown",_r),document.addEventListener("pointerup",_r),document.addEventListener("click",_r),document.addEventListener("dragstart",_r),document.addEventListener("touchend",_r),document.addEventListener("keydown",_r);const xg=class extends EventTarget{constructor(e){super(),a(this,"_mute",!1),a(this,"context"),a(this,"_isVisible",!0),this.context=e,window.addEventListener("visibilitychange",this.onVisiblityChanged.bind(this),!1)}static get userInteractionRegistered(){return Ud}static registerWaitForInteraction(e){if(e!==null){if(Ud){e();return}Aa.indexOf(e)===-1&&Aa.push(e)}}static unregisterWaitForInteraction(e){const t=Aa.indexOf(e);t!==-1&&Aa.splice(t,1)}get muted(){return this._mute}set muted(e){e!==this._mute&&(this._mute=e,this.dispatchEvent(new Event("application-mutechanged")))}get hasFocus(){return document.hasFocus()}get isVisible(){return this._isVisible}onVisiblityChanged(e){switch(e.target.visibilityState){case"hidden":this._isVisible=!1,this.dispatchEvent(new Event("application-hidden"));break;case"visible":this._isVisible=!0,this.dispatchEvent(new Event("application-visible"));break}}};a(xg,"registerWaitForAllowAudio",xg.registerWaitForInteraction);let Ln=xg;const Ia=new Map,La=new Map;let s_=0;function jn(o,e,t){if(Ia.has(e)||Ia.set(e,new Array),Ia.get(e).push({method:o,options:{once:!1,...t}}),s_<30){const s=La.get(e);s&&s?.length>100&&(s_+=1,console.warn(`You have ${s.length} methods registered for Event ${e}.
154
+
155
+ This might be a performance issue!
156
+ Consider unregistering the methods when they are not needed anymore!
157
+
158
+ To unregister you can call the function returned by your event hook (e.g.const unregister = onStart(...))
159
+
160
+ or by using the once option like onStart(()=>{}, { once:true }).
161
+
162
+ See https://engine.needle.tools/docs/scripting.html#special-lifecycle-hooks for more information.`))}}function bo(o,e){const t=La.get(e);if(t){for(let n=0;n<t.length;n++)if(t[n].method===o){t.splice(n,1);return}}const s=Ia.get(e);if(s){for(let n=0;n<s.length;n++)if(s[n].method===o){s.splice(n,1);return}}}function Xs(o,e){e===me.ContextCreated&&Sg.delete(o),n_(o,e)}function n_(o,e){e===Oe.Start&&Ia.get(me.ContextCreated)&&n_(o,me.ContextCreated);const t=e===Oe.Start||e===me.ContextCreated,s=La.get(e);s&&s.length>0&&r_(o,s,t);const n=Ia.get(e);if(n&&n.length>0){const r=[...n];n.length=0,r_(o,r,t),r.length>0&&(La.has(e)||La.set(e,new Array),La.get(e).push(...r))}}const zd=new Array,o_={context:null};function r_(o,e,t){var s,n;zd.length=0;for(let l=0;l<e.length;l++)zd.push(e[l]);let r=Sg.get(o);for(let l=0;l<zd.length;l++){const c=zd[l];let h=!0;if(r&&r.has(c)&&(h=!1),h)try{o_.context=o,(s=c.method)==null||s.call(o_,o)}catch(d){console.error("Error in lifecycle method",d)}if((n=c.options)!=null&&n.once){for(let d=0;d<e.length;d++)if(e[d]===c){e.splice(d,1);break}}else t&&(r||(r=new Set,Sg.set(o,r)),r.add(c))}}const Sg=new WeakMap,Cg={};function Pg(o,e){Cg[o]=e}function a_(o){const e=o.getBufferIdentifier(),t=Cg[e];return t(o)}function l_(o){return typeof o.guid=="function"?o.guid():null}let Og;function Jk(){return Og}function eM(o){Og=o}function c_(o,e){return e||(e={}),e={...Og,...e},o?new Vv(o,e):new Vv(e)}async function h_(){const o=await import("./vendor-BlSxe9JJ.min.js").then(e=>e.bundler);return console.log(o),o.default===void 0?o:o.default}class d_{constructor(){a(this,"_host"),a(this,"_client"),a(this,"_clientData"),this.onEnable()}get isHost(){return this._host!==void 0}onEnable(){this.trySetupHost("HOST-5980e65c-8438-453e-8b35-f13c736dcd81")}async trySetupHost(e){const t=await h_(),s=new t(e);s.on("error",n=>{console.error(n),this._host=void 0,this.trySetupClient(e)}),s.on("open",n=>{this._host=new iM(s)})}async trySetupClient(e){const t=await h_();this._client=new t,this._client.on("error",s=>{console.error("Client error",s)}),this._client.on("open",s=>{console.log("client connected",s),this._clientData=this._client.connect(e,{metadata:{id:s}}),this._clientData.on("open",()=>{console.log("Connected to host")}),this._clientData.on("data",n=>{console.log("<<",n)})})}}class tM{constructor(e){a(this,"_peer"),this._peer=e}}class iM extends tM{constructor(e){var t;super(e),a(this,"_connections",[]),console.log("I AM THE HOST"),(t=this._peer)==null||t.on("connection",this.onConnection.bind(this)),this._peer.on("close",()=>{this.broadcast("BYE")}),setInterval(()=>{this.broadcast("HELLO")},2e3)}get isHost(){return!0}onConnection(e){console.log("host connection",e),e.on("open",()=>{this._connections.push(e),this.broadcastConnection(e)})}broadcastConnection(e){const t=this._connections.map(s=>{var n;return(n=s.metadata)==null?void 0:n.id}).filter(s=>s!==void 0);this.broadcast({type:"connection-list",connections:t})}broadcast(e){if(e!=null){console.log(">>",e);for(const t in this._peer.connections){const s=this._peer.connections[t];if(s)if(Array.isArray(s))for(const n of s)n&&n.send(e);else console.warn(s)}}}}var xs=(o=>(o[o.OnConnection=0]="OnConnection",o[o.OnRoomJoin=1]="OnRoomJoin",o[o.Queued=2]="Queued",o[o.Immediate=3]="Immediate",o))(xs||{});const u_="https://urls.needle.tools/default-networking-backend/index";let Mi="wss://networking.needle.tools/socket";const oi=!!C("debugnet"),oc=!!(oi||C("debugowner")),Nd=C("debugnetbin");var p_=(o=>(o.ConnectionInfo="connection-start-info",o))(p_||{}),ie=(o=>(o.Join="join-room",o.Leave="leave-room",o.JoinedRoom="joined-room",o.LeftRoom="left-room",o.UserJoinedRoom="user-joined-room",o.UserLeftRoom="user-left-room",o.RoomStateSent="room-state-sent",o))(ie||{});class sM{constructor(){a(this,"room"),a(this,"viewId"),a(this,"allowEditing"),a(this,"inRoom")}}class nM{constructor(){a(this,"room")}}class oM{constructor(){a(this,"userId")}}var m_=(o=>(o.RequestHasOwner="request-has-owner",o.ResponseHasOwner="response-has-owner",o.RequestIsOwner="request-is-owner",o.ResponseIsOwner="response-is-owner",o.RequestOwnership="request-ownership",o.GainedOwnership="gained-ownership",o.RemoveOwnership="remove-ownership",o.LostOwnership="lost-ownership",o.GainedOwnershipBroadcast="gained-ownership-broadcast",o.LostOwnershipBroadcast="lost-ownership-broadcast",o))(m_||{});class kg{constructor(e,t){a(this,"guid"),a(this,"connection"),a(this,"_hasOwnership",!1),a(this,"_isOwned"),a(this,"_gainSubscription"),a(this,"_lostSubscription"),a(this,"_hasOwnerResponse"),a(this,"_isWaitingForOwnershipResponseCallback",null),this.connection=e,this.guid=t,this._gainSubscription=this.onGainedOwnership.bind(this),this._lostSubscription=this.onLostOwnership.bind(this),e.beginListen("lost-ownership",this._lostSubscription),e.beginListen("gained-ownership-broadcast",this._gainSubscription),this._hasOwnerResponse=this.onHasOwnerResponse.bind(this),e.beginListen("response-has-owner",this._hasOwnerResponse)}get hasOwnership(){return this._hasOwnership}get isOwned(){return this._isOwned}get isConnected(){return this.connection.isConnected}updateIsOwned(){this.connection.send("request-has-owner",{guid:this.guid})}onHasOwnerResponse(e){e.guid===this.guid&&(this._isOwned=e.value)}requestOwnershipIfNotOwned(){return this._isWaitingForOwnershipResponseCallback!==null?this:(this._isWaitingForOwnershipResponseCallback=this.waitForHasOwnershipRequestResponse.bind(this),this.connection.beginListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this.connection.send("request-has-owner",{guid:this.guid}),this)}waitForHasOwnershipRequestResponse(e){e.guid===this.guid&&(this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this._isOwned=e.value,e.value||(oc&&console.log("request ownership",this.guid),this.requestOwnership()))}requestOwnershipAsync(){return new Promise((e,t)=>{this.requestOwnership();let s=0;const n=()=>{if(s++>10)return t("Timeout");setTimeout(()=>{this.hasOwnership?e(this):n()},100)};n()})}requestOwnership(){return oc&&console.log("Request ownership",this.guid),this.connection.send("request-ownership",{guid:this.guid}),this}freeOwnership(){return this.connection.send("remove-ownership",{guid:this.guid}),this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this}destroy(){this.connection.stopListen("gained-ownership",this._gainSubscription),this.connection.stopListen("lost-ownership",this._lostSubscription),this.connection.stopListen("response-has-owner",this._hasOwnerResponse),this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null)}onGainedOwnership(e){e.guid===this.guid&&(this._isOwned=!0,this.connection.connectionId===e.owner?(oc&&console.log("GAINED OWNERSHIP",this.guid),this._hasOwnership=!0):this._hasOwnership=!1)}onLostOwnership(e){e===this.guid&&(oc&&console.log("LOST OWNERSHIP",this.guid),this._hasOwnership=!1,this._isOwned=!1)}}class g_{constructor(e){a(this,"context"),a(this,"_peer",null),a(this,"_usersInRoomCopy",[]),a(this,"_defaultMessagesBuffer",[]),a(this,"_defaultMessagesBufferArray",[]),a(this,"netWebSocketUrlProvider"),a(this,"_listeners",{}),a(this,"_listenersBinary",{}),a(this,"connected",!1),a(this,"channelId"),a(this,"_connectionId",null),a(this,"_ws"),a(this,"_waitingForSocket",{}),a(this,"_isInRoom",!1),a(this,"_currentRoomName",null),a(this,"_currentRoomViewId",null),a(this,"_currentRoomAllowEditing",!0),a(this,"_currentInRoom",[]),a(this,"_state",{}),a(this,"_currentDelay",-1),a(this,"_connectingToWebsocketPromise",null),this.context=e}get peer(){return this._peer||(this._peer=new d_),this._peer}tryGetState(e){return e==="invalid"?null:this._state[e]}get connectionId(){return this._connectionId}get isDebugEnabled(){return oi}get isConnected(){return this.connected}get currentRoomName(){return this._currentRoomName}get allowEditing(){return this._currentRoomAllowEditing}get currentRoomViewId(){return this._currentRoomViewId}getViewOnlyUrl(){if(this.currentRoomViewId===null)return null;const e=new URL(window.location.href);return e.searchParams.set("view",this.currentRoomViewId),e.href}get isInRoom(){return this._isInRoom}get currentLatency(){return this._currentDelay}get currentServerUrl(){var e;return((e=this._ws)==null?void 0:e.url)??null}sendPing(){this.send("ping",{time:this.context.time.time})}userIsInRoom(e){return this._currentInRoom.indexOf(e)!==-1}usersInRoom(e=null){e||(e=this._usersInRoomCopy),e.length=0;for(const t of this._currentInRoom)e.push(t);return e}joinRoom(e,t=!1){return e?e.length>1024?(console.error('Room name too long, can not join: "'+e+'". Max length is 1024 characters.'),!1):(this.isInRoom&&this.currentRoomName!==e&&console.warn("Needle Engine is already connected to a networking room. Connecting to multiple rooms is not supported"),this.connect(),oi&&console.log("join: "+e),this.send("join-room",{room:e,viewOnly:t},xs.OnConnection),!0):(console.error('Missing room name, can not join: "'+e+'"'),!1)}leaveRoom(e=null){return e||(e=this.currentRoomName),e?(this.send("leave-room",{room:e}),!0):(console.error('Missing room name, can not join: "'+e+'"'),!1)}send(e,t=null,s=xs.Queued){if(t===null&&(t={}),s===xs.Queued){this._defaultMessagesBuffer.push({key:e,value:t});return}return this.sendWithWebsocket(e,t,s)}sendDeleteRemoteState(e){this.send("delete-state",{guid:e,dontSave:!0}),delete this._state[e]}sendDeleteRemoteStateAll(){this.send("delete-all-state"),this._state={}}sendBinary(e){var t;Nd&&console.log("<< send binary",this.context.time.frame,e.length/1024+" KB"),(t=this._ws)==null||t.send(e)}sendBufferedMessagesNow(){var e;if(!this._ws)return;this._defaultMessagesBufferArray.length=0;const t=Object.keys(this._defaultMessagesBuffer).length;for(const n in this._defaultMessagesBuffer){const r=this._defaultMessagesBuffer[n];if(t<=1){this.sendWithWebsocket(r.key,r.value,xs.Immediate);break}const l=this.toMessage(r.key,r.value);this._defaultMessagesBufferArray.push(l)}if(this._defaultMessagesBuffer.length=0,this._defaultMessagesBufferArray.length>0&&oi&&console.log("SEND BUFFERED",this._defaultMessagesBufferArray.length),this._defaultMessagesBufferArray.length<=0)return;const s=JSON.stringify(this._defaultMessagesBufferArray);(e=this._ws)==null||e.send(s)}beginListen(e,t){return this._listeners[e]||(this._listeners[e]=[]),this._listeners[e].push(t),t}stopListening(e,t){return this.stopListen(e,t)}stopListen(e,t){if(!t||!this._listeners[e])return;const s=this._listeners[e].indexOf(t);s>=0&&this._listeners[e].splice(s,1)}beginListenBinary(e,t){return this._listenersBinary[e]||(this._listenersBinary[e]=[]),this._listenersBinary[e].push(t),t}stopListenBinary(e,t){if(!this._listenersBinary[e])return;const s=this._listenersBinary[e].indexOf(t);s>=0&&this._listenersBinary[e].splice(s,1)}registerProvider(e){this.netWebSocketUrlProvider=e}async connect(e){var t;if(this.connected&&e&&e!==Mi)return Promise.reject("Can not connect to different server url. Please disconnect first.");if(this.connected)return Promise.resolve(!0);e&&console.debug("Connecting to user provided url "+e);const s=e||((t=this.netWebSocketUrlProvider)==null?void 0:t.getWebsocketUrl());return s?Mi=s:Jv()&&(Mi="wss://"+window.location.host+"/socket"),this.connectWebsocket()}disconnect(){var e;(e=this._ws)==null||e.close(),this._ws=void 0,Mi=void 0,this._currentRoomAllowEditing=!0,this._currentRoomName=null,this._currentRoomViewId=null,this._isInRoom=!1,this._currentInRoom.length=0,this._state={},this._currentDelay=-1}connectWebsocket(){return this._connectingToWebsocketPromise?this._connectingToWebsocketPromise:this._connectingToWebsocketPromise=new Promise(async(e,t)=>{var s,n;let r=!1;const l=p=>{r||(r=!0,e(p))};if(Mi===void 0&&(console.log("Fetch default backend url: "+u_),Mi=await(await fetch(u_)).text()),Mi===void 0){l(!1);return}console.debug(`\u22A1 Connecting to networking backend on
163
+ `+Mi);const c=await import("./vendor-BlSxe9JJ.min.js").then(p=>p.index),h=((s=c.default)==null?void 0:s.WebsocketBuilder)??c.WebsocketBuilder,d=((n=c.default)==null?void 0:n.ExponentialBackoff)??c.ExponentialBackoff,u=new h(Mi).withMaxRetries(10).withBackoff(new d(2e3,4)).onOpen(()=>{this._connectingToWebsocketPromise=null,this._ws=u,this.connected=!0,F()||oi?console.log(`\u229E Connected to networking backend
164
+ `+Mi):console.debug("\u229E Connected to networking backend",Mi),l(!0),this.onSendQueued(xs.OnConnection)}).onClose(p=>{this._connectingToWebsocketPromise=null,this.connected=!1,this._isInRoom=!1,l(!1);let g="Websocket connection closed...";Mi!=null&&Mi.includes("/socket")||(g+=' Do you perhaps mean to connect to "/socket"?'),console.error(g)}).onError(p=>{console.error("\u22A0 Websocket connection failed..."),l(!1)}).onRetry(()=>{console.log("\u2192 Retry connecting to networking websocket")}).build();u.addEventListener(c.WebsocketEvent.message,(p,g)=>{this.onMessage(p,g)})})}onMessage(e,t){const s=t.data;try{if(typeof s!="string"){s.size&&this.handleIncomingBinaryMessage(s);return}const n=JSON.parse(s);if(Array.isArray(n))for(const r of n)this.handleIncomingStringMessage(r);else this.handleIncomingStringMessage(n);return}catch(n){oi&&s==="pong"?console.log("<<",s):F()&&console.error("Failed to parse message",n)}}async handleIncomingBinaryMessage(e){Nd&&console.log("<< bin",this.context.time.frame);const t=await e.arrayBuffer();var s=new Uint8Array(t);const n=new gO(s),r=n.getBufferIdentifier(),l=this._listenersBinary[r],c=a_(n),h=l_(c);if(h&&typeof h=="string"&&(this._state[h]=c),!l)return;const d=c??n;for(const u of l)u(d)}handleIncomingStringMessage(e){var t,s;if(oi&&console.log("<<",e.key??e),e.key)switch(e.key){case"connection-start-info":if(e.data){const h=e.data;h&&(console.assert(h.id!==void 0&&h.id!==null&&h.id.length>0,"server did not send connection id",h.id),console.debug("Your id is: "+h.id,this.context.alias??""),this._connectionId=h.id)}else console.warn("Expected connection id in "+e.key);break;case"joined-room":if(oi&&console.log(e),e){this._isInRoom=!0;const h=e;this._currentRoomName=h.room,this._currentRoomViewId=h.viewId,this._currentRoomAllowEditing=h.allowEditing??!0,this._currentInRoom.length=0,this._currentInRoom.push(...h.inRoom),(Nd||F())&&console.debug("Joined Needle Engine Room: "+h.room);const d=new URL(window.location.href);d.searchParams.has("room")&&d.searchParams.delete("room"),d.searchParams.set("view",this._currentRoomViewId),console.debug(`Room view id: ${this._currentRoomViewId}
165
+ ${d.href}`)}this.onSendQueued(xs.OnRoomJoin);break;case"left-room":const l=e;l.room===this.currentRoomName&&(this._isInRoom=!1,this._currentRoomName=null,this._currentRoomAllowEditing=!0,this._currentInRoom.length=0,(Nd||F())&&console.debug("Left Needle Engine Room: "+l.room));break;case"user-joined-room":if(e.data){const h=e.data;this._currentInRoom.push(h.userId),oi&&console.log(h.userId+" joined","now in room:",this._currentInRoom)}break;case"user-left-room":if(e.data){const h=e.data,d=this._currentInRoom.indexOf(h.userId);d>=0&&(oi&&console.log(h.userId+" left","now in room:",this._currentInRoom),this._currentInRoom.splice(d,1)),h.userId===this.connectionId&&console.log("you left the room")}break;case"all-room-state-deleted":oi&&console.log("RECEIVED all-room-state-deleted"),this._state={};break;case"ping":case"pong":const c=(t=e.data)==null?void 0:t.time;c&&(this._currentDelay=this.context.time.time-c),oi&&console.log(`Current latency: ${(this._currentDelay*1e3).toFixed()} ms`,"Clients in room: "+((s=this._currentInRoom)==null?void 0:s.length));break}const n=e.data;n&&(this._state[n.guid]=n);let r=this._listeners[e.key];if(r){r=[...r];for(const l of r)try{l(e.data)}catch(c){console.error('Error invoking callback for "'+e.key+'"',c)}}}toMessage(e,t){return{key:e,data:t}}sendWithWebsocket(e,t,s=xs.OnRoomJoin){if(!this._ws){const r=this._waitingForSocket[s]||[];r.push(()=>this.sendWithWebsocket(e,t,s)),this._waitingForSocket[s]=r;return}const n=JSON.stringify(this.toMessage(e,t));oi&&console.log(">>",e),this._ws.send(n)}onSendQueued(e){const t=this._waitingForSocket[e];if(t){for(const s of t)s();t.length=0}}}const rc=C("debugwebxr");class Mg{constructor(e,t){a(this,"controllerStates",[]),a(this,"userId"),a(this,"context"),a(this,"userStateEvtName"),a(this,"onReceivedControllerState",s=>{rc&&console.log(`XRSync: Received change for ${this.userId}: ${s.type} ${s.handedness}; tracked=${s.isTracking}`);let n=!1;for(let r=0;r<this.controllerStates.length;r++)if(this.controllerStates[r].index===s.index){this.controllerStates[r]=s,n=!0;break}n||this.controllerStates.push(s)}),this.userId=e,this.context=t,this.userStateEvtName="xr-sync-user-state-"+e,this.context.connection.beginListen(this.userStateEvtName,this.onReceivedControllerState)}dispose(){this.context.connection.stopListen(this.userStateEvtName,this.onReceivedControllerState)}update(e){if(this.context.connection.isConnected!=!1){for(let t=this.controllerStates.length-1;t>=0;t--){const s=this.controllerStates[t];let n=!1;for(let r=0;r<e.controllers.length;r++)e.controllers[r].index===s.index&&(n=!0);n||(rc&&console.log(`XRSync: ${s.type} ${s.handedness} removed`,s.index),this.controllerStates.splice(t,1),this.sendControllerRemoved(s))}for(const t of e.controllers)this.updateControllerStates(t)}}onExitXR(e){for(const t of this.controllerStates)this.sendControllerRemoved(t);this.controllerStates.length=0}sendControllerRemoved(e){e.isTracking=!1,e.guid="",this.context.connection.send(this.userStateEvtName,e),this.context.connection.sendDeleteRemoteState(e.guid)}updateControllerStates(e){const t=this.controllerStates.find(s=>s.index===e.index);if(t){let s=!1;s||(s=t.isTracking!=e.isTracking),s&&(t.isTracking=e.isTracking,this.context.connection.send(this.userStateEvtName,t))}else{const s={guid:this.userId+"-"+e.index,isTracking:e.isTracking,handedness:e.side,index:e.index,type:e.hand?"hand":"controller"};this.controllerStates.push(s),this.context.connection.send(this.userStateEvtName,s),rc&&console.log(`XRSync: ${s.type} ${s.handedness} added`,s.index)}}}class f_{constructor(e){a(this,"context"),a(this,"onJoinedRoom",()=>{if(this.context.connection.connectionId){this._states.has(this.context.connection.connectionId)||(rc&&console.log("XRSync: Local user joined room",this.context.connection.connectionId),this._states.set(this.context.connection.connectionId,new Mg(this.context.connection.connectionId,this.context)));for(const t of this.context.connection.usersInRoom())this._states.has(t)||this._states.set(t,new Mg(t,this.context))}}),a(this,"onLeftRoom",()=>{if(this.context.connection.connectionId&&!this._states.has(this.context.connection.connectionId)){const t=this._states.get(this.context.connection.connectionId);t?.dispose(),this._states.delete(this.context.connection.connectionId)}}),a(this,"onOtherUserJoinedRoom",t=>{const s=t.userId;this._states.has(s)||(rc&&console.log("XRSync: Remote user joined room",s),this._states.set(s,new Mg(s,this.context)))}),a(this,"onOtherUserLeftRoom",t=>{const s=t.userId;if(!this._states.has(s)){const n=this._states.get(s);n?.dispose(),this._states.delete(s)}}),a(this,"_states",new Map),this.context=e,this.context.connection.beginListen(ie.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(ie.LeftRoom,this.onLeftRoom),this.context.connection.beginListen(ie.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.beginListen(ie.UserLeftRoom,this.onOtherUserLeftRoom)}hasState(e){return e?this._states.has(e):!1}isTracking(e,t){if(!e)return;const s=this._states.get(e);if(!s)return;const n=s.controllerStates.find(r=>r.handedness===t);return n?.isTracking||!1}getDeviceType(e,t){if(!e)return;const s=this._states.get(e);if(!s)return;const n=s.controllerStates.find(r=>r.handedness===t);return n?.type||"unknown"}destroy(){this.context.connection.stopListen(ie.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(ie.LeftRoom,this.onLeftRoom),this.context.connection.stopListen(ie.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.stopListen(ie.UserLeftRoom,this.onOtherUserLeftRoom)}onUpdate(e){if(this.context.connection.isConnected&&this.context.connection.connectionId){const t=this._states.get(this.context.connection.connectionId);t?.update(e)}}onExitXR(e){if(this.context.connection.isConnected&&this.context.connection.connectionId){const t=this._states.get(this.context.connection.connectionId);t?.onExitXR(e)}}}class y_{constructor(){a(this,"_fadeToColorQuad"),a(this,"_fadeToColorMaterial"),a(this,"_requestedFadeValue",0),a(this,"_transitionPromise",null),a(this,"_transitionResolve",null),this._fadeToColorMaterial=new Me({color:0,transparent:!0,depthTest:!1,fog:!1,side:Ci}),this._fadeToColorQuad=new q(new Ns(10,10),this._fadeToColorMaterial)}dispose(){this._fadeToColorQuad.geometry.dispose(),this._fadeToColorMaterial.dispose()}update(e,t){const s=this._fadeToColorQuad,n=this._fadeToColorMaterial;s.parent!==e&&n.opacity>0?e.add(s):n.opacity===0&&s.removeFromParent(),s.layers.set(2),s.material=this._fadeToColorMaterial,s.position.z=-1,s.renderOrder=1/0;const r=this._requestedFadeValue;n.opacity=W.lerp(n.opacity,r,t/.03),Math.abs(n.opacity-r)<=.01&&this._transitionResolve&&(this._transitionResolve(),this._transitionResolve=null,this._transitionPromise=null,this._requestedFadeValue=0)}remove(){this._fadeToColorQuad.removeFromParent()}fadeTransition(){if(this._transitionPromise)return this._transitionPromise;this._requestedFadeValue=1;const e=new Promise(t=>{this._transitionResolve=t});return this._transitionPromise=e,e}}var wr=(o=>(o[o.Quad=0]="Quad",o[o.Cube=1]="Cube",o[o.Sphere=2]="Sphere",o[o.Cylinder=3]="Cylinder",o[o.RoundedCube=10]="RoundedCube",o))(wr||{}),Wd,Rg;class _o{static createText(e,t){let s=null;const n=t?.font||aM(t?.familyFamily||null);n instanceof qP?s=cd(this,Wd,Rg).call(this,e,n,t):s==null&&(s=new Vs);const r=t?.color||16777215,l=new q(s,t?.material??new vt({color:r}));return this.applyDefaultObjectOptions(l,t),n instanceof Promise?n.then(c=>{l.geometry=cd(this,Wd,Rg).call(this,e,c,t),t!=null&&t.onGeometry&&t.onGeometry(l)}):t!=null&&t.onGeometry&&t.onGeometry(l),l}static createOccluder(e){const t=new Me({colorWrite:!1,depthWrite:!0,side:Ci});return this.createPrimitive(e,{material:t})}static createPrimitive(e,t){let s;const n=t?.color||16777215;switch(e){case"Quad":case 0:{const r=new Ns(1,1,1,1),l=t?.material??new vt({color:n});t!=null&&t.texture&&"map"in l&&(l.map=t.texture),s=new q(r,l),s.name="Quad"}break;case"Cube":case 1:{const r=new ba(1,1,1),l=t?.material??new vt({color:n});t!=null&&t.texture&&"map"in l&&(l.map=t.texture),s=new q(r,l),s.name="Cube"}break;case 10:case"RoundedCube":{const r=rM(1,1,1,.1,2),l=t?.material??new vt({color:n});t!=null&&t.texture&&"map"in l&&(l.map=t.texture),s=new q(r,l),s.name="RoundedCube"}break;case"Sphere":case 2:{const r=new dd(.5,16,16),l=t?.material??new vt({color:n});t!=null&&t.texture&&"map"in l&&(l.map=t.texture),s=new q(r,l),s.name="Sphere"}break;case"Cylinder":case 3:{const r=new Cv(.5,.5,1,32),l=t?.material??new vt({color:n});t!=null&&t.texture&&"map"in l&&(l.map=t.texture),s=new q(r,l),s.name="Cylinder"}break;case"ShaderBall":s=new po,s.name="ShaderBall",lM(s,t);break}return this.applyDefaultObjectOptions(s,t),s}static createSprite(e){const t=new RC({color:16777215});e!=null&&e.texture&&"map"in t&&(t.map=e.texture);const s=new TC(t);return this.applyDefaultObjectOptions(s,e),s}static applyDefaultObjectOptions(e,t){e.receiveShadow=!0,e.castShadow=!0,t!=null&&t.name&&(e.name=t.name),t!=null&&t.position&&(Array.isArray(t.position)?e.position.set(t.position[0],t.position[1],t.position[2]):e.position.set(t.position.x,t.position.y,t.position.z)),t!=null&&t.rotation&&(Array.isArray(t.rotation)?e.rotation.set(t.rotation[0],t.rotation[1],t.rotation[2]):e.rotation.set(t.rotation.x,t.rotation.y,t.rotation.z)),t!=null&&t.scale&&(typeof t.scale=="number"?e.scale.set(t.scale,t.scale,t.scale):Array.isArray(t.scale)?e.scale.set(t.scale[0],t.scale[1],t.scale[2]):e.scale.set(t.scale.x,t.scale.y,t.scale.z)),t?.receiveShadow!=null&&(e.receiveShadow=t.receiveShadow),t?.castShadow!=null&&(e.castShadow=t.castShadow),t!=null&&t.parent&&t.parent.add(e)}}Wd=new WeakSet,Rg=function(o,e,t){const s=t?.depth||.1;return new XP(o,{font:e,size:1,depth:s,height:s,bevelEnabled:t?.bevel||!1,bevelThickness:.01,bevelOffset:.01,bevelSize:.01})},Us(_o,Wd);function rM(o,e,t,s,n){const r=new EC,l=1e-5,c=s-l;r.absarc(l,l,l,-Math.PI/2,-Math.PI,!0),r.absarc(l,e-c*2,l,Math.PI,Math.PI/2,!0),r.absarc(o-c*2,e-c*2,l,Math.PI/2,0,!0),r.absarc(o-c*2,l,l,0,-Math.PI/2,!0);const h=new AC(r,{bevelEnabled:!0,bevelSegments:n*2,steps:1,bevelSize:c,bevelThickness:s,curveSegments:n});return h.scale(1,1,1-s),h.center(),h.computeVertexNormals(),h}const Vd=new Map;function aM(o){let e="";switch(o){default:case"OpenSans":e="https://cdn.needle.tools/static/fonts/facetype/Open Sans_Regular_ascii.json";break;case"Helvetiker":e="https://raw.githubusercontent.com/mrdoob/three.js/master/examples/fonts/helvetiker_regular.typeface.json";break}if(Vd.has(e)){const n=Vd.get(e);if(n)return n}const t=new QP,s=new Promise((n,r)=>{t.load(e,l=>{Vd.set(e,l),n(l)},void 0,r)});return Vd.set(e,s),s}let Tg=!1,Eg=null;function lM(o,e){if(Eg===null){const t="https://cdn.needle.tools/static/models/shaderball.glb",s=new Rn,n=Dm(null);s.setDRACOLoader(n.dracoLoader),s.setKTX2Loader(n.ktx2Loader),Tg=!0,Eg=s.loadAsync(t).then(r=>{const l=r.scene;return l.position.y-=.5,l}).catch(r=>(console.warn("Failed to load shaderball mesh: "+r.message),b_())).finally(()=>{Tg=!1})}if(Tg){const t=b_();t.name="ShaderBall-Placeholder";const s=t.children[0];s?.type==="Mesh"&&v_(s,e),o.add(t)}Eg.then(t=>{o.children.forEach(r=>{r.name==="ShaderBall-Placeholder"&&o.remove(r)});const s=t.clone(),n=s.children[0];n?.type==="Mesh"&&v_(n,e),o.add(s)})}function v_(o,e){var t;if(e?.color||e?.material||e?.texture){const s=e?.material??((t=o.material)==null?void 0:t.clone())??new vt;e.color&&"color"in s&&s.color instanceof ae&&s.color.set(e.color),e!=null&&e.texture&&"map"in s&&(s.map=e.texture),o.material=s}}function b_(){return new po().add(_o.createPrimitive("Sphere",{material:new Me({transparent:!0,opacity:.1})}))}const Ag=class uC{constructor(e,t,s){a(this,"_session"),a(this,"_mode"),a(this,"_init"),a(this,"_renderer"),a(this,"_camera"),a(this,"_scene"),a(this,"onEnd",()=>{var n;(n=this._session)==null||n.removeEventListener("end",this.onEnd),this._renderer.setAnimationLoop(null),this._renderer.dispose(),this._scene.clear()}),a(this,"_lastTime",0),a(this,"onFrame",(n,r)=>{const l=n-this._lastTime;this.update(n,l),this._camera.parent!==this._scene&&this._scene.add(this._camera),this._renderer.render(this._scene,this._camera)}),a(this,"_objects",[]),this._mode=e,this._init=t,this._session=s,this._session.addEventListener("end",this.onEnd),this._renderer=new pr({alpha:!0}),this._renderer.setAnimationLoop(this.onFrame),this._renderer.xr.setSession(s),this._renderer.xr.enabled=!0,this._camera=new we,this._scene=new wi,this._scene.fog=new Pv(4473924,10,250),this._scene.add(this._camera),this.setupScene()}static get active(){return this._active}static async start(e,t){if(this._active)return console.error("Cannot start a new XR session while one is already active"),null;if(this._requestInFlight)return console.error("Cannot start a new XR session while a request is already in flight"),null;if("xr"in navigator&&navigator.xr){if(!t)return console.error("XRSessionInit must be provided"),null;this._requestInFlight=!0;const s=await navigator.xr.requestSession(e,t);return s.addEventListener("end",()=>{this._active=null}),this._requestInFlight?(this._requestInFlight=!1,this._active=new uC(e,t,s),this._active):(s.end(),null)}return null}static async handoff(){return this._active?this._active.handoff():null}static async stop(){this._requestInFlight=!1,this._active&&(await this._active.end(),await ys(100)),this._active=null}get isAR(){return this._mode==="immersive-ar"}end(){return this._session?this._session.end():Promise.resolve()}async handoff(){if(!this._session)throw new Error("Cannot handoff a session that has already ended");const e={session:this._session,mode:this._mode,init:this._init};return await this.onBeforeHandoff(),this.onEnd(),this._session=null,e}async onBeforeHandoff(){await ys(1e3),this._scene.clear()}setupScene(){this._scene.background=new ae(0),this._scene.add(new Sm(5,10,1118481,1118481));const e=new Cm(16777215,1);e.position.set(0,20,0),e.castShadow=!1,this._scene.add(e);const t=new Cm(16777215,1);t.position.set(0,-1,0),t.castShadow=!1,this._scene.add(t);const s=new Pm(16777215,1,100,1);s.position.set(0,2,0),s.castShadow=!1,s.distance=200,this._scene.add(s);const n=50;for(let r=0;r<100;r++){const l=new vt({color:2236962,metalness:1,roughness:.8});this.isAR&&(l.emissive=new ae(Math.random(),Math.random(),Math.random()),l.emissiveIntensity=Math.random());const c=W.random(0,1)>.5?wr.Sphere:wr.Cube,h=_o.createPrimitive(c,{material:l});h.position.x=W.random(-n,n),h.position.y=W.random(-2,n),h.position.z=W.random(-n,n),h.rotation.x=W.random(0,Math.PI*2),h.rotation.y=W.random(0,Math.PI*2),h.rotation.z=W.random(0,Math.PI*2),h.scale.multiplyScalar(.5+Math.random()*10);const d=h.position.distanceTo(this._camera.position)-h.scale.x;d<1&&h.position.multiplyScalar(1+1/d),this._objects.push(h),this._scene.add(h)}}update(e,t){const s=e*4e-4;for(let n=0;n<this._objects.length;n++){const r=this._objects[n];r.position.y+=Math.sin(s+n*.5)*.005,r.rotateY(.002)}}};a(Ag,"_active",null),a(Ag,"_requestInFlight",!1);let Hd=Ag;var ac;(o=>{const e=[];function t(){if(!(e!=null&&e.length))return!1;for(const r of e)r.exportAndOpen();return!0}o.exportAndOpen=t;function s(r){e.push(r)}o.registerExporter=s;function n(r){if(!e)return;const l=e.indexOf(r);l>=0&&e.splice(l,1)}o.unregisterExporter=n})(ac||(ac={}));const Je=C("debugwebxr"),__=C("stats");let Ig=0;function cM(o){let e=null;const t=o;return t.getAROverlayContainer?e=t.getAROverlayContainer():e=o,e}hM();async function hM(){var o;if(C("debugasap")){let e=globalThis["needle:XRSession"];if(e instanceof Promise){delete globalThis["needle:XRSession"],pe.addContextCreatedCallback(async t=>{if(!e)return;vr(!0);const s=await e;if(s){const n=ne.getDefaultSessionInit("immersive-vr");ne.setSession("immersive-vr",s,n,t.context)}else console.error("NeedleXRSession: ASAP session was rejected");e=void 0});return}}if("xr"in navigator){if(/WebXRViewer\//i.test(navigator.userAgent)){console.warn("WebXRViewer does not support addEventListener");return}(o=navigator.xr)==null||o.addEventListener("sessiongranted",async()=>{vr(!0),console.log("Received Session Granted..."),await ys(100);const e=sessionStorage.getItem("needle_xr_session_mode"),t=sessionStorage.getItem("needle_xr_session_init")??null,s=t?JSON.parse(t):null;let n=null;if(w_()&&(await Hd.start(e||"immersive-vr",s||ne.getDefaultSessionInit("immersive-vr")),await pM(),n=await Hd.handoff()),n)ne.setSession(n.mode,n.session,n.init,ee.Current);else if(e&&t){console.log("Session Granted: Restore last session");const r=JSON.parse(t);ne.start(e,r).catch(l=>console.warn(l))}else ne.start("immersive-vr").catch(r=>console.warn("Session Granted failed:",r))},{once:!0})}}function dM(o,e){sessionStorage.setItem("needle_xr_session_mode",o),sessionStorage.setItem("needle_xr_session_init",JSON.stringify(e))}function uM(){sessionStorage.removeItem("needle_xr_session_mode"),sessionStorage.removeItem("needle_xr_session_init")}const Lg=new Set;pe.registerCallback(me.ContextCreationStart,async o=>{Lg.add(o.context)}),pe.registerCallback(me.ContextCreated,async o=>{var e;Lg.delete(o.context);const t=((e=o.context)==null?void 0:e.domElement.getAttribute("autostart"))||null;mM(t)});function w_(){return Lg.size>0}function pM(){return new Promise(o=>{const e=Date.now(),t=setInterval(()=>{(!w_()||Date.now()-e>6e4)&&(clearInterval(t),o())},100)})}Y.isDesktop()&&F()&&window.addEventListener("keydown",o=>{(o.key==="x"||o.key==="Escape")&&ne.active&&ne.stop()});function mM(o){if(o)switch(o?.toLowerCase()){case"ar":Ln.registerWaitForInteraction(()=>{ne.start("ar")});break}}const ri=class fa{constructor(e,t,s,n){a(this,"context"),a(this,"session"),a(this,"mode"),a(this,"controllers",[]),a(this,"_rigScale",1),a(this,"_lastRigScaleUpdate",-1),a(this,"_rigs",[]),a(this,"_viewerHitTestSource",null),a(this,"_defaultRig"),a(this,"_xr_scripts"),a(this,"_xr_update_scripts",[]),a(this,"_inactive_scripts",[]),a(this,"_controllerAdded"),a(this,"_controllerRemoved"),a(this,"_originalCameraWorldPosition"),a(this,"_originalCameraWorldRotation"),a(this,"_originalCameraWorldScale"),a(this,"_originalCameraParent"),a(this,"_mainCamera",null),a(this,"onRendererSessionSet",()=>{var c;this.running&&(this.context.renderer.xr.enabled=!0,this.context.renderer.xr.updateCamera(this.context.mainCamera),(c=this.context.mainCameraComponent)==null||c.applyClearFlags())}),a(this,"onInputSourceAdded",c=>{if(c.targetRayMode==="screen")return;let h=0;for(let u=0;u<this.session.inputSources.length;u++)if(this.session.inputSources[u]===c){h=u;break}if(this.controllers.find(u=>u.inputSource===c)){console.debug("Controller already exists for input source",h);return}else if(this._newControllers.find(u=>u.inputSource===c)){console.debug("Controller already registered for input source",h);return}const d=new _g(this,c,h);this._newControllers.push(d)}),a(this,"_ended",!1),a(this,"_newControllers",[]),a(this,"onEnd",c=>{var h,d,u;if(this._ended)return;this._ended=!0,console.debug("XR Session ended"),uM(),this.onAfterRender(),this.revertCustomForward(),this._didStart=!1,this._previousCameraParent=null,bo(this.onBefore,Oe.LateUpdate);const p=this.context.pre_render_callbacks.indexOf(this.onBeforeRender);p>=0&&this.context.pre_render_callbacks.splice(p,1);const g=this.context.post_render_callbacks.indexOf(this.onAfterRender);g>=0&&this.context.post_render_callbacks.splice(g,1),this.context.xr=null,this.context.renderer.xr.enabled=!1,this.context.pre_update_oneshot_callbacks.push(()=>{var y,b;(y=this.context.mainCameraComponent)==null||y.applyClearFlags(),(b=this.context.mainCameraComponent)==null||b.applyClippingPlane()}),Jb({session:this});for(const y of fa._xrEndListeners)y({xr:this});const f=[...this.controllers];for(let y=0;y<f.length;y++)this.disconnectInputSource(f[y].inputSource);this._newControllers.length=0,this.controllers.length=0;for(const y of this._xr_scripts)(h=y?.onLeaveXR)==null||h.call(y,{xr:this});(d=this.sync)==null||d.onExitXR(this),this.context.mainCamera&&((u=this._originalCameraParent)==null||u.add(this.context.mainCamera),this._originalCameraWorldPosition&&lt(this.context.mainCamera,this._originalCameraWorldPosition),this._originalCameraWorldRotation&&Qi(this.context.mainCamera,this._originalCameraWorldRotation),this._originalCameraWorldScale&&ka(this.context.mainCamera,this._originalCameraWorldScale)),this.context.requestSizeUpdate(),this._defaultRig.gameObject.removeFromParent(),vr(!1)}),a(this,"_didStart",!1),a(this,"onBefore",c=>{var h,d,u,p,g,f,y,b;const v=c.xrFrame;if(!v)return;this.context.xr=this,this.context.mainCameraComponent&&this.context.mainCameraComponent!==this._mainCamera&&(this._mainCamera=this.context.mainCameraComponent),((h=this.rig)==null?void 0:h.isActive)==!1&&(Je&&console.warn("Latest rig is not active - trying to activate a different rig",this.rig),this.updateActiveXRRig()),this.rig&&(d=this._mainCamera)!=null&&d.gameObject&&((p=(u=this._mainCamera)==null?void 0:u.gameObject)==null?void 0:p.parent)!==this.rig.gameObject&&this.rig.gameObject.add((g=this._mainCamera)==null?void 0:g.gameObject),this.internalUpdateState(),this.applyCustomForward();const _={xr:this};if(this._didStart){if(this.context.new_scripts_xr.length>0){const w=[...this.context.new_scripts_xr];for(let S=0;S<w.length;S++){const k=this.context.new_scripts_xr[S];if(!k||k.destroyed||((f=k.supportsXR)==null?void 0:f.call(k,this.mode))==!1){this.context.new_scripts_xr.splice(S,1);continue}if(!k.activeAndEnabled){this.context.new_scripts_xr.splice(S,1),this.markInactive(k);continue}if(this.addScript(k)){this.invokeCallback_EnterXR(k);for(const M of this.controllers)this.invokeCallback_ControllerAdded(k,M)}}}}else{if(this._didStart=!0,this.mode==="immersive-vr"){const S=ii(this.context.scene.children);if(S){const k=S.getSize(X());if(k.length()>0){const M=this._defaultRig.gameObject;M.position.set(S.min.x+k.x*.5,S.min.y,S.max.z+k.z*.5+1.5);const T=S.getCenter(X());T.y=M.position.y,M.lookAt(T)}}}Zb({session:this}),_r();for(const S of fa._xrStartListeners)S(_);const w=[...this._xr_scripts];Je&&console.log("NeedleXRSession start, handle scripts:",w);for(const S of w){if(S.destroyed){this._script_to_remove.push(S);continue}if(!S.activeAndEnabled){this.markInactive(S);continue}this.invokeCallback_EnterXR(S);for(const k of this.controllers)this.invokeCallback_ControllerAdded(S,k)}}this.syncCameraCullingMask();for(const w of this.controllers)w.onUpdate(v);if(this._newControllers.length>0){const w=[...this._newControllers];this._newControllers.length=0;for(const S of w){if(!S.connected){console.warn("New controller is not connected",S);continue}this.controllers.push(S);for(const k of this._xr_scripts){if(k.destroyed){this._script_to_remove.push(k);continue}k.activeAndEnabled!==!1&&this.invokeCallback_ControllerAdded(k,S)}}this.controllers.sort((S,k)=>S.index-k.index)}Je&&this.context.time.frame%30===0&&this.controllers.length<=0&&this.session.inputSources.length>0&&(vr(!0),console.error("XRControllers are not added but inputSources are present"));for(const w of this._xr_update_scripts){if(w.destroyed===!0){this._script_to_remove.push(w);continue}if(w.activeAndEnabled===!1){this.markInactive(w);continue}w.onUpdateXR&&w.onUpdateXR(_)}if(this.handleInactiveScripts(),this._script_to_remove.length>0){const w=[...new Set(this._script_to_remove)];this._script_to_remove.length=0;for(const S of w)!S.destroyed&&this.running&&((y=S.onLeaveXR)==null||y.call(S,_)),this.removeScript(S)}(b=this.sync)==null||b.onUpdate(this),this.onRenderDebug()}),a(this,"onBeforeRender",()=>{this.context.mainCamera&&this.updateFade(this.context.mainCamera)}),a(this,"onAfterRender",()=>{if(this.onUpdateFade_PostRender(),Y.isDesktop()||!this._renderOnceOnDevice){const c=this.context.renderer;if(c.xr.isPresenting&&this.context.mainCamera){this._renderOnceOnDevice=!0;const h=c.xr.enabled,d=c.getRenderTarget(),u=this.context.scene.background;c.xr.enabled=!1,c.setRenderTarget(null),this.isPassThrough&&(this.context.scene.background=null),this.context.composer?this.context.composer.render(this.context.time.deltaTime):c.render(this.context.scene,this.context.mainCamera),c.xr.enabled=h,c.setRenderTarget(d),this.context.scene.background=u}}}),a(this,"_script_to_remove",[]),a(this,"_camera"),a(this,"_cameraRenderParent",new E().rotateY(Math.PI)),a(this,"_previousCameraParent"),a(this,"_customforward",!0),a(this,"originalCameraNearPlane"),a(this,"_viewerPose"),a(this,"_transformOrientation",new H),a(this,"_transformPosition",new x),a(this,"_transition");var r,l;dM(e,n.init),this.session=t,this.mode=e,this.context=s,(Je||C("console"))&&vr(!0),this._xr_scripts=[...n.scripts],this._xr_update_scripts=this._xr_scripts.filter(c=>typeof c.onUpdateXR=="function"),this._controllerAdded=n.controller_added,this._controllerRemoved=n.controller_removed,jn(this.onBefore,Oe.LateUpdate),this.context.pre_render_callbacks.push(this.onBeforeRender),this.context.post_render_callbacks.push(this.onAfterRender),((r=n.init.optionalFeatures)!=null&&r.includes("hit-test")||(l=n.init.requiredFeatures)!=null&&l.includes("hit-test"))&&t.requestReferenceSpace("viewer").then(c=>{var h,d;return(d=(h=t.requestHitTestSource)==null?void 0:h.call(t,{space:c}))==null?void 0:d.then(u=>this._viewerHitTestSource=u).catch(u=>console.error(u))}).catch(c=>console.error(c)),this.context.mainCamera&&(this._originalCameraWorldPosition=te(this.context.mainCamera,new x),this._originalCameraWorldRotation=Se(this.context.mainCamera,new H),this._originalCameraWorldScale=Ge(this.context.mainCamera,new x),this._originalCameraParent=this.context.mainCamera.parent),this._defaultRig=new Xk,this.context.scene.add(this._defaultRig.gameObject),this.addRig(this._defaultRig);for(let c=0;c<t.inputSources.length;c++){const h=t.inputSources[c];if(!h.handedness){console.warn("Input source in xr session has no handedness - ignoring",c);continue}this.onInputSourceAdded(h)}this.session.addEventListener("end",this.onEnd),this.session.addEventListener("inputsourceschange",c=>{for(const h of c.removed)this.disconnectInputSource(h);for(const h of c.added)this.onInputSourceAdded(h)}),this.context.xr=this,this.context.renderer.xr.setSession(this.session).then(this.onRendererSessionSet),"controllerAutoUpdate"in this.context.renderer.xr?(console.debug("Disabling three.js controllerAutoUpdate"),this.context.renderer.xr.controllerAutoUpdate=!1):Je&&console.warn("controllerAutoUpdate is not available in three.js - cannot disable it")}static getXRSync(e){return this._sync||(this._sync=new f_(e)),this._sync}static get currentSessionRequest(){return this._currentSessionRequestMode}static get active(){return this._activeSession}static get activeMode(){var e;return((e=this._activeSession)==null?void 0:e.mode)??null}static get xrSystem(){return"xr"in navigator?navigator.xr:void 0}static isXRSupported(){return Promise.all([this.isVRSupported(),this.isARSupported()]).then(e=>e.some(t=>t)).catch(()=>!1)}static isVRSupported(){return this.isSessionSupported("immersive-vr")}static isARSupported(){return this.isSessionSupported("immersive-ar")}static isSessionSupported(e){var t;return((t=this.xrSystem)==null?void 0:t.isSessionSupported(e).catch(s=>(Je&&console.error(s),!1)))??Promise.resolve(!1)}static onSessionRequestStart(e){this._sessionRequestStartListeners.push(e)}static offSessionRequestStart(e){const t=this._sessionRequestStartListeners.indexOf(e);t>=0&&this._sessionRequestStartListeners.splice(t,1)}static onSessionRequestEnd(e){this._sessionRequestEndListeners.push(e)}static offSessionRequestEnd(e){const t=this._sessionRequestEndListeners.indexOf(e);t>=0&&this._sessionRequestEndListeners.splice(t,1)}static onXRSessionStart(e){this._xrStartListeners.push(e)}static offXRSessionStart(e){const t=this._xrStartListeners.indexOf(e);t>=0&&this._xrStartListeners.splice(t,1)}static onXRSessionEnd(e){this._xrEndListeners.push(e)}static offXRSessionEnd(e){const t=this._xrEndListeners.indexOf(e);t>=0&&this._xrEndListeners.splice(t,1)}static onControllerAdded(e){this._controllerAddedListeners.push(e)}static offControllerAdded(e){const t=this._controllerAddedListeners.indexOf(e);t>=0&&this._controllerAddedListeners.splice(t,1)}static onControllerRemoved(e){this._controllerRemovedListeners.push(e)}static offControllerRemoved(e){const t=this._controllerRemovedListeners.indexOf(e);t>=0&&this._controllerRemovedListeners.splice(t,1)}static offerSession(e,t,s){return"xr"in navigator&&navigator.xr&&"offerSession"in navigator.xr?(typeof navigator.xr.offerSession=="function"&&(console.log("WebXR offerSession is available - requesting mode: "+e),t=="default"&&(t=this.getDefaultSessionInit(e)),navigator.xr.offerSession(e,{...t}).then(n=>fa.setSession(e,n,t,s)).catch(n=>{console.log("XRSession offer rejected (perhaps because another call to offerSession was made or a call to requestSession was made)")})),!0):!1}static getDefaultSessionInit(e){switch(e){case"immersive-ar":const t=["anchors","local-floor","layers","dom-overlay","hit-test","unbounded"];return Y.isVisionOS()||t.push("hand-tracking"),{optionalFeatures:t};case"immersive-vr":const s=["local-floor","bounded-floor","high-fixed-foveation-level","layers"];return Y.isVisionOS()||s.push("hand-tracking"),{optionalFeatures:s};default:return console.warn("No default session init for mode",e),{}}}static async start(e,t,s){var n,r,l,c;if(Y.isiOS()){if(e==="ar")if(await this.isARSupported())e="immersive-ar";else return ac.exportAndOpen(),null}else e=="ar"&&(e="immersive-ar");if(F()&&C("debugxrpreroom"))return console.warn("Debug: Starting temporary XR session"),await Hd.start(e,t||fa.getDefaultSessionInit(e)),null;if(this._currentSessionRequest)return console.warn("A XRSession is already being requested"),(Je||F())&&be("A XRSession is already being requested"),this._currentSessionRequest.then(()=>this._activeSession);if(this._activeSession)return console.error("A XRSession is already running"),this._activeSession;if(s||(s=ee.Current),s||(s=pe.All[0]),!s)throw new Error("No Needle Engine Context found");switch(t||(t={}),e){case"immersive-ar":{if(await((n=this.xrSystem)==null?void 0:n.isSessionSupported("immersive-ar"))!==!0)return console.error(e+" is not supported by this browser."),null;const u=this.getDefaultSessionInit(e),p=cM(s.domElement);p&&!Y.isQuest()&&(u.domOverlay={root:p},u.optionalFeatures.push("dom-overlay")),t={...u,...t}}break;case"immersive-vr":{if(await((r=this.xrSystem)==null?void 0:r.isSessionSupported("immersive-vr"))!==!0)return console.error(e+" is not supported by this browser."),null;t={...this.getDefaultSessionInit(e),...t}}break;default:console.warn("No default session init for mode",e);break}t.optionalFeatures??(t.optionalFeatures=[]),t.requiredFeatures??(t.requiredFeatures=[]),await Hd.stop();const h=e=="immersive-ar"?s.scripts_immersive_ar:s.scripts_immersive_vr;Je?console.log(`%cRequesting ${e} session`,"font-weight:bold;",t,h):console.log(`%cRequesting ${e} session`,"font-weight:bold;");for(const u of h)u.onBeforeXR&&u.onBeforeXR(e,t);for(const u of this._sessionRequestStartListeners)u({mode:e,init:t});Je&&Be("Requesting "+e+" session ("+Date.now()+")"),this._currentSessionRequest=(l=navigator.xr)==null?void 0:l.requestSession(e,t),this._currentSessionRequestMode=e;const d=await((c=this._currentSessionRequest)==null?void 0:c.catch(u=>{console.error(u,"Code: "+u.code),u.code===9&&be("Make sure your device has the required permissions (e.g. camera access)"),console.log("If the specified XR configuration is not supported (e.g. entering AR doesnt work) - make sure you access the website on a secure connection (HTTPS) and your device has the required permissions (e.g. camera access)"),location.protocol==="http:"&&be("XR requires a secure connection (HTTPS)")}));this._currentSessionRequest=void 0,this._currentSessionRequestMode=null;for(const u of this._sessionRequestEndListeners)u({mode:e,init:t,newSession:d||null});return d?this.setSession(e,d,t,s):(console.warn("XR Session request was rejected"),null)}static setSession(e,t,s,n){if(this._activeSession)return console.error("A XRSession is already running"),this._activeSession;const r=e=="immersive-ar"?n.scripts_immersive_ar:n.scripts_immersive_vr;return this._activeSession=new fa(e,t,n,{scripts:r,controller_added:this._controllerAddedListeners,controller_removed:this._controllerRemovedListeners,init:s}),t.addEventListener("end",this.onEnd),Je?console.log(`%cStarted ${e} session`,"font-weight:bold;",r):console.log(`%cStarted ${e} session`,"font-weight:bold;"),this._activeSession}static stop(){const e=this._activeSession;e&&(e[this.$_stop_request]===void 0?(Je&&console.log("[NeedleXRSession] Stopping XR Session... (new)"),e[this.$_stop_request]=setTimeout(()=>{e.end()})):Je&&console.warn("[NeedleXRSession] XR Session stop already requested"))}get sync(){return fa._sync}get running(){return!this._ended&&this.session!=null}get interactionMode(){return this.session.interactionMode}get visibilityState(){return this.session.visibilityState}get isVisibleBlurred(){return this.session.visibilityState==="visible-blurred"}get isSystemKeyboardSupported(){return this.session.isSystemKeyboardSupported}get environmentBlendMode(){return this.session.environmentBlendMode}get frame(){return this.context.xrFrame}get leftController(){return this.controllers.find(e=>e.side==="left")}get rightController(){return this.controllers.find(e=>e.side==="right")}getController(e){return typeof e=="number"?this.controllers[e]||null:this.controllers.find(t=>t.side===e)||null}get isPassThrough(){return!!(this.environmentBlendMode!=="opaque"&&this.interactionMode==="world-space"||this.mode==="immersive-ar"&&this.environmentBlendMode!=="opaque"&&this.controllers.some(e=>e.inputSource.targetRayMode==="tracked-pointer")||F()&&Y.isDesktop()&&this.mode==="immersive-ar")}get isAR(){return this.mode==="immersive-ar"}get isVR(){return this.mode==="immersive-vr"}get isScreenBasedAR(){return this.isAR&&!this.isPassThrough}get posePosition(){return this._transformPosition}get poseOrientation(){return this._transformOrientation}get referenceSpace(){return this.context.renderer.xr.getReferenceSpace()}get viewerPose(){return this._viewerPose}get isTrackingImages(){if(this.frame&&"getImageTrackingResults"in this.frame&&typeof this.frame.getImageTrackingResults=="function")try{const e=this.frame.getImageTrackingResults();for(const t of e)if(t.trackingState==="tracked")return!0}catch{return!1}return!1}get rig(){const e=this._rigs[0]??null;return e!=null&&e.gameObject&&Mr(e.gameObject)||e?.isActive===!1?(this.updateActiveXRRig(),this._rigs[0]??null):e}get rigScale(){return this._rigs[0]?(this._lastRigScaleUpdate!==this.context.time.frame&&(this._lastRigScaleUpdate=this.context.time.frame,this._rigScale=this._rigs[0].gameObject.worldScale.x),this._rigScale):1}addRig(e){this._rigs.indexOf(e)>=0||(e.priority===void 0&&(e.priority=0),this._rigs.push(e),this.updateActiveXRRig())}removeRig(e){const t=this._rigs.indexOf(e);t!==-1&&(this._rigs.splice(t,1),this.updateActiveXRRig())}setRigActive(e){const t=this._rigs.indexOf(e),s=this._rigs[0];this._rigs.splice(t,1),this._rigs.unshift(e),e.priority=s?.priority??0,this.updateActiveXRRig()}getUserOffsetInRig(){var e;const t=(e=this.context.mainCamera)==null?void 0:e.position;if(!t||!this.rig)return X(0,0,0);const s=X(t);return s.x*=-1,s.z*=-1,s.applyQuaternion(vs(this.rig.gameObject.quaternion)),s}updateActiveXRRig(){const e=this._rigs[0]??null;this._defaultRig.gameObject.parent!==this.context.scene&&this.context.scene.add(this._defaultRig.gameObject),this._defaultRig.gameObject.visible=!0,this._rigs.includes(this._defaultRig)||this._rigs.push(this._defaultRig);let t=this._rigs[0];t&&t.priority===void 0&&(t.priority=0);for(let s=1;s<this._rigs.length;s++){const n=this._rigs[s];if(n.isActive){if(Mr(n.gameObject)){this._rigs.splice(s,1),s--;continue}(!t||t.isActive===!1||n.priority!==void 0&&n.priority>t.priority)&&(t=n)}}if(e!==t){const s=this._rigs.indexOf(t);s>=0&&this._rigs.splice(s,1),this._rigs.unshift(t)}Je&&(e===t?console.log("Updated Active XR Rig:",t,"prev:",e):console.log("Updated Active XRRig:",t," (the same as before)"))}getHitTest(e){if(e)return this.getControllerHitTest(e);if(!this._viewerHitTestSource)return null;const t=this._viewerHitTestSource,s=this.frame.getHitTestResults(t);if(s.length>0){const n=s[0];return this.convertHitTestResult(n)}return null}getControllerHitTest(e){const t=e.getHitTestSource();if(!t)return null;const s=this.frame.getHitTestResultsForTransientInput(t);for(const n of s)if(n.inputSource===e.inputSource)for(const r of n.results)return this.convertHitTestResult(r);return null}convertHitTestResult(e){const t=this.context.renderer.xr.getReferenceSpace(),s=t&&e.getPose(t);if(s){const n=X(s.transform.position),r=vs(s.transform.orientation),l=this.context.mainCamera;if(l?.parent!==this._cameraRenderParent&&n.applyMatrix4(Ea),l!=null&&l.parent){n.applyMatrix4(l.parent.matrixWorld),r.multiply(Ki);const c=Se(l.parent);c.premultiply(Ki),r.premultiply(c)}return{hit:e,position:n,quaternion:r}}return null}convertSpace(e){const t=X(e.position);t.applyMatrix4(Ea);const s=vs(e.orientation);return s.premultiply(Ki),{position:t,quaternion:s}}disconnectInputSource(e){const t=(s,n,r)=>{if(s.inputSource===e){Je&&console.log("Disconnecting controller",s.index),this.controllers.splice(r,1),this.invokeControllerEvent(s,this._controllerRemoved,"removed");const l={xr:this,controller:s,change:"removed"};for(const c of this._xr_scripts)c.onXRControllerRemoved&&c.onXRControllerRemoved(l);s.onDisconnected()}};for(let s=this.controllers.length-1;s>=0;s--){const n=this.controllers[s];t(n,this.controllers,s)}for(let s=this._newControllers.length-1;s>=0;s--){const n=this._newControllers[s];t(n,this._newControllers,s)}}end(){this._ended||this.session.end().catch(e=>console.warn(e))}onRenderDebug(){if(Je)for(const e of this.controllers)e.onRenderDebug();if((Je||__)&&this.rig&&(Ig++,Ig>=20)){const e=this.rig.gameObject.worldPosition,t=this.rig.gameObject.worldForward;e.add(t.multiplyScalar(1.5));const s=this.rig.gameObject.worldUp;e.add(s.multiplyScalar(2.5));let n="";if(n+=`${this.context.time.smoothedFps.toFixed(0)} FPS`,n+=`, calls: ${this.context.renderer.info.render.calls}, tris: ${this.context.renderer.info.render.triangles.toLocaleString()}`,Je||__)for(const r of this.controllers)n+=`
166
+ ${r.hand?"hand":"ctrl"} ${r.inputSource.handedness}[${r.index}] con:${r.connected} tr:${r.isTracking} hts:${r.hasHitTestSource?"yes":"no"}`;Ig=0,G.DrawLabel(e,n,void 0,1/60*20)}}addScript(e){return this._xr_scripts.includes(e)?!1:(Je&&console.log("Register new XRScript",e),this._xr_scripts.push(e),typeof e.onUpdateXR=="function"&&this._xr_update_scripts.push(e),!0)}markInactive(e){if(!(this._inactive_scripts.indexOf(e)>=0)){this.removeScript(e,!1),this._inactive_scripts.push(e);for(const t of this.controllers)this.invokeCallback_ControllerRemoved(e,t);this.invokeCallback_LeaveXR(e)}}handleInactiveScripts(){if(this._inactive_scripts.length>0)for(let e=this._inactive_scripts.length-1;e>=0;e--){const t=this._inactive_scripts[e];if(t.activeAndEnabled){this._inactive_scripts.splice(e,1),this.addScript(t),this.invokeCallback_EnterXR(t);for(const s of this.controllers)this.invokeCallback_ControllerAdded(t,s)}}}removeScript(e,t=!0){Je&&console.log("Remove XRScript",e);const s=this._xr_scripts.indexOf(e);s>=0&&this._xr_scripts.splice(s,1);const n=this._xr_update_scripts.indexOf(e);if(n>=0&&this._xr_update_scripts.splice(n,1),t){const r=this._inactive_scripts.indexOf(e);r>=0&&this._inactive_scripts.splice(r,1)}}invokeCallback_EnterXR(e){e.onEnterXR&&e.onEnterXR({xr:this})}invokeCallback_ControllerAdded(e,t){e.onXRControllerAdded&&e.onXRControllerAdded({xr:this,controller:t,change:"added"})}invokeCallback_ControllerRemoved(e,t){e.onXRControllerRemoved&&e.onXRControllerRemoved({xr:this,controller:t,change:"removed"})}invokeCallback_LeaveXR(e){e.onLeaveXR&&!e.destroyed&&e.onLeaveXR({xr:this})}syncCameraCullingMask(){var e;const t=this.context.xrCamera,s=(e=this.context.mainCameraComponent)==null?void 0:e.cullingMask;if(t&&s!==void 0){for(const n of t.cameras)n.layers.mask=s;t.layers.mask=s}else if(t){for(const n of t.cameras)n.layers.enableAll();t.layers.enableAll()}}invokeControllerEvent(e,t,s){for(let n=t.length-1;n>=0;n--){const r=t[n];if(r)try{r({xr:this,controller:e,change:s})}catch(l){console.error(l)}}}applyCustomForward(){var e;if(this.context.mainCamera&&this._customforward){this._camera=this.context.mainCamera,this._camera.parent!==this._cameraRenderParent&&(this._previousCameraParent=this._camera.parent,(e=this._previousCameraParent)==null||e.add(this._cameraRenderParent)),this._cameraRenderParent.name="XR Camera Render Parent",this._cameraRenderParent.add(this._camera);let t=.02;if(this.rig){const s=Ge(this.rig.gameObject);t*=s.x}this._camera instanceof we&&this._camera.near>t&&(this.originalCameraNearPlane=this._camera.near,this._camera.near=t)}}revertCustomForward(){this._camera&&this._previousCameraParent&&this._previousCameraParent.add(this._camera),this._previousCameraParent=null,this._camera instanceof we&&this.originalCameraNearPlane!=null&&(this._camera.near=this.originalCameraNearPlane)}internalUpdateState(){const e=this.context.renderer.xr.getReferenceSpace();if(!e){this._viewerPose=void 0;return}if(this._viewerPose=this.frame.getViewerPose(e),this._viewerPose){const t=this._viewerPose.transform;this._transformPosition.set(t.position.x,t.position.y,t.position.z),this._transformOrientation.set(t.orientation.x,t.orientation.y,t.orientation.z,t.orientation.w)}}get transition(){return this._transition||(this._transition=new y_),this._transition}fadeTransition(){return this._transition||(this._transition=new y_),this._transition.fadeTransition()}updateFade(e){this._transition&&e instanceof we&&this._transition.update(e,this.context.time.deltaTime)}onUpdateFade_PostRender(){var e;(e=this._transition)==null||e.remove()}};a(ri,"_sync",null),a(ri,"_currentSessionRequestMode",null),a(ri,"_currentSessionRequest"),a(ri,"_activeSession"),a(ri,"_sessionRequestStartListeners",[]),a(ri,"_sessionRequestEndListeners",[]),a(ri,"_xrStartListeners",[]),a(ri,"_xrEndListeners",[]),a(ri,"_controllerAddedListeners",[]),a(ri,"_controllerRemovedListeners",[]),a(ri,"$_stop_request",Symbol()),a(ri,"onEnd",()=>{Je&&console.log("XR Session ended"),ri._activeSession=null});let ne=ri;const jg=C("debugwebxr");class x_{static tryFindAvatarObjects(e,t,s){if(s.head&&s.leftHand&&s.rightHand)return;const n=e.name.toLocaleLowerCase();!s.head&&n.includes("head")&&(jg&&console.log("FOUND AVATAR HEAD",e.name),s.head=new ce("",t,e)),n.includes("hand")&&(!s.leftHand&&n.includes("left")&&(jg&&console.log("FOUND AVATAR LEFT HAND",e.name),s.leftHand=new ce("",t,e)),!s.rightHand&&n.includes("right")&&(jg&&console.log("FOUND AVATAR RIGHT HAND",e.name),s.rightHand=new ce("",t,e)));for(let r=0;r<e.children.length;r++){if(s.head&&s.leftHand&&s.rightHand)return;const l=e.children[r];this.tryFindAvatarObjects(l,t,s)}}}const Dt=new x,S_=new x,C_=new H,gM=C("debuggizmos"),Ss=8947848,Dg=32,Bg=class Bs{constructor(){}static isGizmo(e){return e[Ug]!==void 0}static setVisible(e){for(const t of Ee.timedObjectsBuffer)t.visible=e}static DrawLabel(e,t,s=.05,n=0,r,l,c){var h;if(!Bs.enabled)return null;r||(r=Ss);const d=((h=ne.active)==null?void 0:h.rigScale)??1,u=Ee.getTextLabel(n,t,s*d,r,l);return c instanceof E&&c.add(u),u.position.x=e.x,u.position.y=e.y,u.position.z=e.z,u}static DrawRay(e,t,s=Ss,n=0,r=!0){if(!Bs.enabled)return;const l=Ee.getLine(n),c=l.geometry.getAttribute("position");c.setXYZ(0,e.x,e.y,e.z),Dt.set(t.x,t.y,t.z).multiplyScalar(999999999),c.setXYZ(1,e.x+Dt.x,e.y+Dt.y,e.z+Dt.z),c.needsUpdate=!0,l.material.color.set(s),l.material.depthTest=r,l.material.depthWrite=!1}static DrawDirection(e,t,s=Ss,n=0,r=!0,l=1){if(!Bs.enabled)return;const c=Ee.getLine(n),h=c.geometry.getAttribute("position");h.setXYZ(0,e.x,e.y,e.z),t.w!==void 0?(Dt.set(0,0,-l),C_.set(t.x,t.y,t.z,t.w),Dt.applyQuaternion(C_)):(Dt.set(t.x,t.y,t.z),Dt.multiplyScalar(l)),h.setXYZ(1,e.x+Dt.x,e.y+Dt.y,e.z+Dt.z),h.needsUpdate=!0,c.material.color.set(s),c.material.depthTest=r,c.material.depthWrite=!1}static DrawLine(e,t,s=Ss,n=0,r=!0){if(!Bs.enabled)return;const l=Ee.getLine(n),c=l.geometry.getAttribute("position");c.setXYZ(0,e.x,e.y,e.z),c.setXYZ(1,t.x,t.y,t.z),c.needsUpdate=!0,l.material.color.set(s),l.material.depthTest=r,l.material.depthWrite=!1,l.material.fog=!1}static DrawCircle(e,t,s,n=Ss,r=0,l=!0){if(!Bs.enabled)return;const c=Ee.getCircle(r);c.position.set(e.x,e.y,e.z),c.scale.set(s,s,s),c.quaternion.setFromUnitVectors(this._up,Dt.set(t.x,t.y,t.z).normalize()),c.material.color.set(n),c.material.depthTest=l,c.material.depthWrite=!1,c.material.fog=!1}static DrawWireSphere(e,t,s=Ss,n=0,r=!0){if(!Bs.enabled)return;const l=Ee.getSphere(t,n,!0);fr(l,e.x,e.y,e.z),l.material.color.set(s),l.material.depthTest=r,l.material.depthWrite=!1,l.material.fog=!1}static DrawSphere(e,t,s=Ss,n=0,r=!0){if(!Bs.enabled)return;const l=Ee.getSphere(t,n,!1);fr(l,e.x,e.y,e.z),l.material.color.set(s),l.material.depthTest=r,l.material.depthWrite=!1}static DrawWireBox(e,t,s=Ss,n=0,r=!0){if(!Bs.enabled)return;const l=Ee.getBox(n);l.position.set(e.x,e.y,e.z),l.scale.set(t.x,t.y,t.z),l.material.color.set(s),l.material.depthTest=r,l.material.wireframe=!0,l.material.depthWrite=!1,l.material.fog=!1}static DrawWireBox3(e,t=Ss,s=0,n=!0){if(!Bs.enabled)return;const r=Ee.getBox(s);r.position.copy(e.getCenter(Dt)),r.scale.copy(e.getSize(Dt)),r.material.color.set(t),r.material.depthTest=n,r.material.wireframe=!0,r.material.depthWrite=!1,r.material.fog=!1}static DrawArrow(e,t,s=Ss,n=0,r=!0,l=!1){if(!Bs.enabled)return;const c=Ee.getArrowHead(n);c.position.set(t.x,t.y,t.z),c.quaternion.setFromUnitVectors(this._up.set(0,1,0),Dt.set(t.x,t.y,t.z).sub(S_.set(e.x,e.y,e.z)).normalize());const h=Dt.set(t.x,t.y,t.z).sub(S_.set(e.x,e.y,e.z)).length()*.1;c.scale.set(h,h,h),c.material.color.set(s),c.material.depthTest=r,c.material.wireframe=l,this.DrawLine(e,t,s,n,r)}static DrawWireMesh(e){const t=Ee.getMesh(e.duration??0);"mesh"in e?(t.geometry=e.mesh.geometry,t.matrix.copy(e.mesh.matrixWorld)):(t.geometry=e.geometry,t.matrix.copy(e.matrix)),t.matrixAutoUpdate=!1,t.matrixWorldAutoUpdate=!1,t.material.color.set(e.color??Ss),t.material.depthTest=e.depthTest??!0,t.material.wireframe=!0}};a(Bg,"enabled",!0),a(Bg,"_up",new x(0,1,0));let G=Bg;const fM=new ba(1,1,1);function Fg(o=null){const e=new ae(o??14540253),t=new IC(fM);return new Ov(t,new kv({color:e}))}const Ug=Symbol("GizmoCache");class Ee{static ensureFont(){let e=Re.FontLibrary.getFontFamily(this.familyName);if(!e){e=Re.FontLibrary.addFontFamily(this.familyName);const t=e.addVariant("normal","normal","https://uploads.needle.tools/include/font-msdf.json","https://uploads.needle.tools/include/font.png");t?.addEventListener("ready",()=>{Re.update()})}}static getTextLabel(e,t,s,n,r){this.ensureFont();let l=this.textLabelCache.pop(),c=1;r&&typeof r=="string"&&r?.length>=8&&r.startsWith("#")?(c=parseInt(r.substring(7),16)/255,r=r.substring(0,7),gM&&console.log(r,c)):typeof r=="object"&&r.a!==void 0&&(c=r.a);const h={boxSizing:"border-box",fontFamily:this.familyName,width:"auto",fontSize:s,color:n,lineHeight:1,backgroundColor:r??void 0,backgroundOpacity:c,textContent:t,borderRadius:.5*s,padding:.8*s,whiteSpace:"pre",offset:.05*s};if(l)l.set(h);else{l=new Xv(h);const d=this,u=l;u.setText=function(p){this.set({textContent:p}),d.tmuiNeedsUpdate=!0}}return this.tmuiNeedsUpdate=!0,this.registerTimedObject(ee.Current,l,e,this.textLabelCache),l}static getBox(e){let t=this.boxesCache.pop();if(!t){const s=new ba(1,1,1);t=new q(s)}return this.registerTimedObject(ee.Current,t,e,this.boxesCache),t}static getLine(e){let t=this.linesCache.pop();if(!t){t=new Wl;let s=t.geometry.getAttribute("position");s||(s=new bt(new Float32Array(6),3),t.geometry.setAttribute("position",s))}return t.frustumCulled=!1,this.registerTimedObject(ee.Current,t,e,this.linesCache),t}static getCircle(e){let t=this.circlesCache.pop();if(!t){t=new Wl;let s=t.geometry.getAttribute("position");if(!s){s=new bt(new Float32Array(Dg*3),3),t.geometry.setAttribute("position",s);const n=X(0,1,0),r=X(0,0,1),l=X(r);l.cross(n).normalize();const c=X(l),h=Math.PI*2/(Dg-1);for(let d=0;d<Dg+1;d++){const u=h*d;n.copy(c).multiplyScalar(Math.cos(u)*1),l.copy(r).multiplyScalar(Math.sin(u)*1);const p=n.add(l);s.setXYZ(d,p.x,p.y,p.z)}}}return t.frustumCulled=!1,this.registerTimedObject(ee.Current,t,e,this.circlesCache),t}static getSphere(e,t,s){let n=this.spheresCache.pop();return n||(n=new q(new dd(1,8,8))),n.scale.set(e,e,e),n.material.wireframe=s,this.registerTimedObject(ee.Current,n,t,this.spheresCache),n}static getArrowHead(e){let t=this.arrowHeadsCache.pop();return t||(t=new q(new Cv(0,.5,1,8))),this.registerTimedObject(ee.Current,t,e,this.arrowHeadsCache),t}static getMesh(e){let t=this.mesh.pop();return t||(t=new q,t.material=new Me),this.registerTimedObject(ee.Current,t,e,this.mesh),t}static registerTimedObject(e,t,s,n){if(!e){console.error("No Needle Engine context available. Did you call a Gizmos function in global scope?");return}const r=this.contextBeforeRenderCallbacks.get(e),l=this.contextPostRenderCallbacks.get(e);if(r){if(e.pre_render_callbacks[e.pre_render_callbacks.length-1]!==r){const c=e.pre_render_callbacks.indexOf(r);c>=0&&e.pre_render_callbacks.splice(c,1),e.pre_render_callbacks.push(r)}}else{const c=()=>{this.onBeforeRender(e,this.timedObjectsBuffer)};this.contextBeforeRenderCallbacks.set(e,c),e.pre_render_callbacks.push(c)}if(l){if(e.post_render_callbacks[e.post_render_callbacks.length-1]!==l){const c=e.post_render_callbacks.indexOf(l);c>=0&&e.post_render_callbacks.splice(c,1),e.post_render_callbacks.push(l)}}else{const c=()=>{this.onPostRender(e,this.timedObjectsBuffer,this.timesBuffer)};this.contextPostRenderCallbacks.set(e,c),e.post_render_callbacks.push(c)}t.traverse(c=>{c.layers.disableAll(),c.layers.enable(2)}),t.renderOrder=999999,t[Ug]=n,t.castShadow=!1,t.receiveShadow=!1,t.isGizmo=!0,this.timedObjectsBuffer.push(t),this.timesBuffer.push(ee.Current.time.realtimeSinceStartup+s),e.scene.add(t)}static onBeforeRender(e,t){this.tmuiNeedsUpdate&&(this.tmuiNeedsUpdate=!1,Re.update());for(let s=0;s<t.length;s++){const n=t[s];if(e.mainCamera&&n instanceof Re.MeshUIBaseElement){if(Mr(n))continue;const r=e.isInVR,l=!1,c=!r;Ql(n,e.mainCamera,l,c)}}}static onPostRender(e,t,s){const n=e.time.realtimeSinceStartup;for(let r=t.length-1;r>=0;r--){const l=t[r];n>=s[r]-1e-6&&(t.splice(r,1),s.splice(r,1),l.removeFromParent(),Mr(l)!=!0&&l[Ug].push(l))}}}a(Ee,"familyName","needle-gizmos"),a(Ee,"linesCache",[]),a(Ee,"circlesCache",[]),a(Ee,"spheresCache",[]),a(Ee,"boxesCache",[]),a(Ee,"arrowHeadsCache",[]),a(Ee,"mesh",[]),a(Ee,"textLabelCache",[]),a(Ee,"timedObjectsBuffer",new Array),a(Ee,"timesBuffer",new Array),a(Ee,"contextPostRenderCallbacks",new Map),a(Ee,"contextBeforeRenderCallbacks",new Map),a(Ee,"tmuiNeedsUpdate",!1);const Ri=C("debugphysics"),P_=new ho;class Qs{constructor(){a(this,"ray"),a(this,"cam"),a(this,"screenPoint"),a(this,"raycaster"),a(this,"results"),a(this,"targets"),a(this,"recursive",!0),a(this,"minDistance"),a(this,"maxDistance"),a(this,"lineThreshold"),a(this,"layerMask"),a(this,"ignore"),a(this,"testObject"),a(this,"useAcceleratedRaycast")}screenPointFromOffset(e,t){this.screenPoint===void 0&&(this.screenPoint=new le),this.screenPoint.x=e/window.innerWidth*2-1,this.screenPoint.y=-(t/window.innerHeight)*2+1}setLayer(e){P_.set(e),this.layerMask=P_}setMask(e){this.layerMask||(this.layerMask=new ho);const t=this.layerMask;t?t.mask=e:this.layerMask=e}}a(Qs,"AllLayers",4294967295);class zg{constructor(e,t,s){a(this,"distance"),a(this,"point"),a(this,"object"),this.object=e,this.distance=t,this.point=s}}const O_=class uv{constructor(e){a(this,"context"),a(this,"engine"),a(this,"raycaster",new ud),a(this,"defaultRaycastOptions",new Qs),a(this,"targetBuffer",new Array(1)),a(this,"defaultThresholds",{Mesh:{},Line:{threshold:-1},LOD:{},Points:{threshold:0},Sprite:{}}),a(this,"sphereResults",new Array),a(this,"sphereMask",new ho),a(this,"sphere",new pd),a(this,"tempBoundingBox",new xi),this.context=e}static get raycasting(){return this._raycasting>0}raycastPhysicsFast(e,t=void 0,s=1/0,n=!0){var r;return((r=this.context.physics.engine)==null?void 0:r.raycast(e,t,{maxDistance:s,solid:n}))??null}raycastPhysicsFastAndGetNormal(e,t=void 0,s=1/0,n=!0){var r;return((r=this.context.physics.engine)==null?void 0:r.raycastAndGetNormal(e,t,{maxDistance:s,solid:n}))??null}sphereOverlapPhysics(e,t){var s;return((s=this.context.physics.engine)==null?void 0:s.sphereOverlap(e,t))??null}sphereOverlap(e,t,s=!0,n=!1,r=null){if(this.sphereResults.length=0,!this.context.scene)return this.sphereResults;const l=this.sphereMask;l.enableAll(),l.disable(2);for(const c of this.context.scene.children)this.intersectSphere(c,e,t,l,this.sphereResults,s,n,r);return this.sphereResults.sort((c,h)=>c.distance-h.distance)}raycastFromRay(e,t=null){const s=t??this.defaultRaycastOptions;s.ray=e;const n=this.raycast(s);return s===this.defaultRaycastOptions&&(s.ray=void 0),n}raycast(e=null){Ri&&performance.mark("raycast.start"),e||(e=this.defaultRaycastOptions);const t=e.screenPoint??this.context.input.mousePositionRC,s=e.raycaster??this.raycaster;if(s.near=e.minDistance??0,s.far=e.maxDistance??1/0,s.params=this.defaultThresholds,e.lineThreshold===void 0&&(e.lineThreshold=-1),s.params.Line={threshold:e.lineThreshold},e.ray)s.ray.copy(e.ray);else{const c=e.cam??this.context.mainCamera;if(!c)return Ri&&console.error("Can not perform raycast - no main camera found"),this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),this.defaultRaycastOptions.results??[];const h=this.context.xrCamera;this.context.isInXR&&h instanceof LC&&h.cameras.length>0?s.setFromCamera(t,h.cameras[0]):s.setFromCamera(t,c)}let n=e.targets;n||(n=this.targetBuffer,n.length=1,n[0]=this.context.scene);let r=e.results;this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),r||(this.defaultRaycastOptions.results||(this.defaultRaycastOptions.results=new Array),r=this.defaultRaycastOptions.results),e.layerMask!==void 0?e.layerMask instanceof ho?s.layers.mask=e.layerMask.mask:s.layers.mask=e.layerMask:(s.layers.enableAll(),s.layers.disable(2)),Ri&&console.time("raycast"),r.length=0,uv._raycasting++,this.intersect(this.raycaster,n,r,e),r.sort((c,h)=>c.distance-h.distance);const l=e.ignore;return l!==void 0&&l.length>0&&(r=r.filter(c=>!l.includes(c.object))),uv._raycasting--,Ri&&(console.timeEnd("raycast"),console.warn("#"+this.context.time.frame+", hits:",r!=null&&r.length?[...r]:"nothing"),performance.mark("raycast.end"),performance.measure("raycast","raycast.start","raycast.end")),r}intersect(e,t,s,n){var r,l,c;for(const h of t){if(!h||h.visible===!1||G.isGizmo(h)||n.lineThreshold!==void 0&&n.lineThreshold<0&&h instanceof Wl)continue;let d=!0;const u=h,p=u.geometry;if(n.testObject){const g=(r=n.testObject)==null?void 0:r.call(n,h);if(g===!1)continue;g==="continue in children"&&(d=!1)}if(d&&(p&&k_(p)||(d=!1)),d){const g=Bv(h);g&&(u.geometry=g);const f=s.length;let y=!0;if(n.precise===!1&&(y=!1),y||(y=((c=(l=p.getAttribute("position"))==null?void 0:l.array)==null?void 0:c.length)<64),u instanceof Ca&&(y=!1),!y&&vM(u,e,s)||(n.useAcceleratedRaycast!==!1?Gd.runMeshBVHRaycast(e,u,s,this.context):e.intersectObject(u,!1,s)),Ri&&s.length!=f){const b=s[s.length-1],v=g?8969557:7798784;G.DrawWireSphere(b.point,.1,v,1,!1),G.DrawWireMesh({mesh:h,depthTest:!1,duration:.2,color:v})}u.geometry=p}n.recursive!==!1&&this.intersect(e,h.children,s,n)}return s}intersectSphere(e,t,s,n,r,l,c,h){let d=e&&e.isMesh&&e.layers.test(n)&&!G.isGizmo(e);d&&(d=e.visible),d&&(d=!(e instanceof Wl)),d&&(d=!(e instanceof Ca));const u=e,p=u.geometry;if(d&&h){const g=h(e);if(g===!1)return;g==="continue in children"&&(d=!1)}if(p&&k_(p)||(d=!1),d){if(c){const g=this.sphere;g.center.copy(t),g.radius=s;const f=r.length;if(Gd.runMeshBVHRaycast(this.sphere,u,r,this.context),f!=r.length&&!l)return}else if(p.boundingBox||p.computeBoundingBox(),p.boundingBox){u.matrixWorldNeedsUpdate&&u.updateWorldMatrix(!1,!1);const g=this.tempBoundingBox.copy(p.boundingBox).applyMatrix4(u.matrixWorld),f=this.sphere;if(f.center.copy(t),f.radius=s,f.intersectsBox(g)){const y=te(e),b=y.distanceTo(f.center),v=new zg(e,b,y);if(r.push(v),!l)return}}}if(e.children)for(const g of e.children){const f=r.length;if(this.intersectSphere(g,t,s,n,r,l,c,h),f!=r.length&&!l)return}}};a(O_,"_raycasting",0);let Ng=O_;function k_(o){return!(o.index&&o.index.array.length<3)}const xr=new pd,$d=new mr,yM=new Sv;function vM(o,e,t){const s=o._computeIntersections;if(!s)return!1;let n=o["_computeIntersections:Needle"];return n||(n=o["_computeIntersections:Needle"]=function(r,l,c){const h=this,d=h.geometry.boundingSphere;if(d){if(h instanceof Ca){$d.setFromNormalAndCoplanarPoint(X(0,1,0),X(0,-h.position.y,0)),$d.applyMatrix4(h.matrixWorld,yM);const p=r.ray.intersectPlane($d,X());if(p){xr.copy(d),xr.applyMatrix4(h.matrixWorld);const g=X(p).sub(r.ray.origin).length(),f=xr.radius*.5;g<f&&l.push({distance:g,point:p,object:h,normal:$d.normal.clone()})}return}xr.copy(d),xr.applyMatrix4(h.matrixWorld);const u=r.ray.intersectSphere(xr,X());if(u){const p=X(u).sub(r.ray.origin),g=p.length();if(g>xr.radius){const f=p.clone().normalize();l.push({distance:g,point:u,object:h,normal:f})}}}}),o._computeIntersections=n,e.intersectObject(o,!1,t),o._computeIntersections=s,!0}var Gd;(o=>{function e(_,w,S,k){var M,T,L;if(!w.geometry||!w.geometry.hasAttribute("position"))return!1;const B=w.geometry;if(w!=null&&w.isSkinnedMesh){const z=w,D=z.bvhNeedsUpdate;if(!z.staticGenerator)c(),r&&(z.staticGenerator=new r(w),z.staticGenerator.applyWorldTransforms=!1,z.staticGeometry=z.staticGenerator.generate(),B.boundsTree=l?.call(z.staticGeometry),z.staticGeometryLastUpdate=performance.now()+Math.random()*200,z.autoUpdateMeshBVH===void 0&&(z.autoUpdateMeshBVH=!1));else if(B.boundsTree&&(z.autoUpdateMeshBVH===!0||D===!0)){const V=performance.now(),$=V-z.staticGeometryLastUpdate;(D||$>100)&&(z.bvhNeedsUpdate=!1,z.staticGeometryLastUpdate=V,(M=z.staticGenerator)==null||M.generate(z.staticGeometry),B.boundsTree.refit())}}else if(!B.boundsTree){d||v();let z=!0;if((k.xr||B[f]===!1||(T=B.getAttribute("position"))!=null&&T.isInterleavedBufferAttribute||B.index&&(L=B.index)!=null&&L.isInterleavedBufferAttribute)&&(z=!1),z&&p){if(B[g]===void 0){let D=null;if(b.length>0){const V=b.shift();V&&!V.running&&(D=V)}if(!D&&y.length<3&&(D=new p,y.push(D)),D!=null&&!D.running){const V=w.name;Ri&&console.log("<<<< worker start",V,D),B[g]="queued",performance.mark("bvh.create.start");const $=B.clone();try{D.generate($).then(U=>{B[g]="done",B.boundsTree=U}).catch(U=>{B[g]="failed - "+U?.message,B[f]=!1,Ri&&console.error("Failed to generate mesh bvh on worker",U)}).finally(()=>{Ri&&console.log(">>>>> worker done",V,{hasBoundsTre:B.boundsTree!=null}),b.push(D),$.dispose(),performance.mark("bvh.create.end"),performance.measure("bvh.create (worker)","bvh.create.start","bvh.create.end")})}catch(U){console.error("Failed to generate mesh bvh on worker",U)}}else Ri&&console.warn("No worker available")}}else(!u||!z)&&(c(),n&&(performance.mark("bvh.create.start"),B.boundsTree=new n(B),performance.mark("bvh.create.end"),performance.measure("bvh.create","bvh.create.start","bvh.create.end")))}if(_ instanceof ud){const z=_,D=w.raycast;B.boundsTree?(c(),s&&(w.acceleratedRaycast||(w.acceleratedRaycast=s.bind(w),Ri&&console.debug(`Physics: bind acceleratedRaycast fn to "${w.name}"`)),w.raycast=w.acceleratedRaycast)):Ri&&console.warn("No bounds tree found for mesh",w.name,{workerTask:B[g],hasAcceleratedRaycast:s!=null});const V=z.firstHitOnly;return z.firstHitOnly=!1,z.intersectObject(w,!1,S),z.firstHitOnly=V,w.raycast=D,!0}else if(_ instanceof pd){const z=B.boundsTree;if(z){const D=_;if(h.copy(w.matrixWorld).invert(),D.applyMatrix4(h),z.intersectsSphere(D)){const V=te(w),$=V.distanceTo(D.center),U=new zg(w,$,V);S.push(U)}}return!0}return!1}o.runMeshBVHRaycast=e;let t=!1,s=null,n=null,r=null,l=null;function c(){t||(t=!0,import("./vendor-BlSxe9JJ.min.js").then(_=>_.index$1).then(_=>{s=_.acceleratedRaycast,n=_.MeshBVH,r=_.StaticGeometryGenerator,l=_.computeBoundsTree}).catch(_=>{(Ri||F())&&console.error("Failed to load BVH library...",_.message)}))}const h=new se;let d=!1,u=!1,p=null;const g=Symbol("Needle:MeshBVH-Worker"),f=Symbol("Needle:MeshBVH-CanUseWorker"),y=[],b=[];function v(){d=!0,u=!0,Promise.resolve().then(()=>UL).then(_=>{p=_.GenerateMeshBVHWorker}).catch(_=>{(Ri||F())&&console.warn("Failed to setup mesh bvh worker")}).finally(()=>{u=!1})}})(Gd||(Gd={}));const M_=Symbol("gltf-loader-internal-usage-tracker"),bM=C("debugusers"),R_=class um{constructor(e){a(this,"parser"),a(this,"_getDependency"),a(this,"_loadingId"),a(this,"_loadedObjects",new Set),this.parser=e,this._getDependency=this.parser.getDependency,this._loadingId=Date.now().toString()}get name(){return"NEEDLE_internal_usage_tracker"}static isLoading(e){return um._loadingProcesses>0}beforeRoot(){um._loadingProcesses++;const e=this,t=this._getDependency;return this.parser.getDependency=function(s,n){const r=t.call(this,s,n);return r.then(l=>(l&&(e._loadedObjects.add(l),l[M_]=e._loadingId),l)),r},null}afterRoot(e){um._loadingProcesses--,this.parser.getDependency=this._getDependency;for(const t of this._loadedObjects)delete t[M_],t instanceof E&&(t.parent||t instanceof q&&setTimeout(()=>{bM&&console.warn("> GLTF LOADER: Mesh not used in scene!",t),t.material=null,t.geometry=null},1e3));return null}};a(R_,"_loadingProcesses",0);let T_=R_;class E_{constructor(){window.addEventListener("unhandledrejection",e=>{var t;if(e.defaultPrevented)return;const s=(t=e?.reason)==null?void 0:t.path;if(s){const n=s[0];n&&n.tagName==="IMG"&&(console.warn(`Could not load image:
167
+ `+n.src),e.preventDefault())}})}}const qd=C("trackresources");function A_(){return qd==="dispose"}let Sr=!0;qd===0&&(Sr=!1);function _M(o){Sr=o}function I_(){return Sr}const L_=Symbol("disposable");function Wg(o,e){o&&(o[L_]=e,Cr&&console.warn("Set disposable",e,o))}const j_=Symbol("disposed");function wM(o){return o[j_]===!0}function Te(o){var e;if(o){if(o[L_]===!1){Cr&&console.warn("Object is marked as not disposable",o);return}if(typeof o=="object"&&(o[j_]=!0),o instanceof wi)Te(o.environment),Te(o.background),Te(o.customDepthMaterial),Te(o.customDistanceMaterial);else if(o instanceof Pn)Te(o.geometry),Te(o.material),Te(o.skeleton),Te(o.bindMatrix),Te(o.bindMatrixInverse),Te(o.customDepthMaterial),Te(o.customDistanceMaterial),o.geometry=null,o.material=null,o.visible=!1;else if(o instanceof q)Te(o.geometry),Te(o.material),Te(o.customDepthMaterial),Te(o.customDistanceMaterial),o.geometry=null,o.material=null,o.visible=!1;else if(o instanceof Vs){ja(o);for(const t of Object.keys(o.attributes)){const s=o.attributes[t];Te(s)}}else if(o instanceof bt||o instanceof Mv)Cr&&console.warn("BufferAttribute dispose not supported",o.count);else if(o instanceof Array)for(const t of o)t instanceof Pe&&Te(t);else if(o instanceof Pe){ja(o);for(const s of Object.keys(o)){const n=o[s];n instanceof De&&(Te(n),o[s]=null)}const t=o.uniforms;if(t)for(const s of Object.keys(t)){const n=t[s];n instanceof De?(Te(n),t[s]=null):n instanceof Xi&&(Te(n.value),n.value=null)}}else o instanceof De?(ja(o),ja(o.source),((e=o.source)==null?void 0:e.data)instanceof ImageBitmap&&ja(o.source.data)):o instanceof jC?(ja(o.boneTexture),o.boneTexture=null):o instanceof DC||!(o instanceof E)&&Cr&&console.warn("Unknown object type",o)}}function ja(o){o&&((Cr||A_()||qd)&&console.warn("\u{1F9E8} FREE",o),o instanceof ImageBitmap?o.close():o instanceof BC?o.data=null:o.dispose())}function D_(o){(o instanceof q||o instanceof Pn)&&(o.material=null,o.geometry=null)}const xM=new Set;function Vg(o,e,t=null,s){if(s||(s=xM,s.clear()),!o)return s;const n=o[lc];if(n)for(const r of n)s.has(r)||t?.call(null,r)!==!1&&(s.add(r),e&&Vg(r,!0,t,s));return s}function SM(o){return o[cc]}const Cr=C("debugresourceusers")||C("debugmemory"),lc=Symbol("needle-resource-users"),cc=Symbol("needle-resource-users-count");function Xt(o,e){Ld(o,e,function(t,s){Sr&&!Ng.raycasting&&(Xd(lc,this,t,!1),Xd(lc,this,s,!0))})}Sr&&(Xt(q.prototype,"material"),Xt(q.prototype,"geometry"),Xt(Pe.prototype,"map"),Xt(Pe.prototype,"bumpMap"),Xt(Pe.prototype,"alphaMap"),Xt(Pe.prototype,"normalMap"),Xt(Pe.prototype,"displacementMap"),Xt(Pe.prototype,"roughnessMap"),Xt(Pe.prototype,"metalnessMap"),Xt(Pe.prototype,"emissiveMap"),Xt(Pe.prototype,"specularMap"),Xt(Pe.prototype,"envMap"),Xt(Pe.prototype,"lightMap"),Xt(Pe.prototype,"aoMap"),Xt(Pe.prototype,"gradientMap"));function CM(o){if(Sr===!1)return;const e=o[lc];if(e)for(const t of e)Xd(lc,t,o,!1)}Sr&&Ld(Pe.prototype,"dispose",function(){CM(this)});let Hg=0;function Xd(o,e,t,s){if(Hg>0)return;if(Array.isArray(t)){for(const r of t)Xd(o,e,r,s);return}if(!t)return;let n=t[o];if(n||(n=new Set),s){if(e&&!n.has(e)){n.add(e);let r=t[cc]||0;r+=1,t[cc]=r,Cr&&console.warn(`\u{1F7E2} Added user of "${t.type}"`,e,t,r,"users:",n)}}else if(e&&n.has(e)){n.delete(e);let r=t[cc]||0;r>0&&(r-=1,t[cc]=r),Cr&&console.warn(`\u{1F534} Removed user of "${t.type}"`,e,t,r,"users:",n),r<=0&&(T_.isLoading(t)||(qd&&console.warn(`\u{1F534} Removed all user of "${t.type}"`,t),A_()&&Te(t)))}t[o]=n}try{Ld(pr.prototype,"render",function(){Hg++},function(){Hg--})}catch(o){console.warn("Could not wrap WebGLRenderer.render",o)}const B_=C("debugcomponentevents");class hc{static addComponentLifecylceEventListener(e,t){this.eventListeners.has(e)&&this.eventListeners.set(e,[]);let s=this.eventListeners.get(e);s||(s=[]),s.push(t),this.eventListeners.set(e,s),B_&&console.log("Added event listener for "+e,this.eventListeners)}static removeComponentLifecylceEventListener(e,t){const s=this.eventListeners.get(e);if(!s)return;const n=s.indexOf(t);n<0||s.splice(n,1)}static dispatchComponentLifecycleEvent(e,t){const s=this.eventListeners.get(e);if(B_&&console.log("Dispatching event "+e,s),!!s)for(const n of s)n(t)}}a(hc,"eventListeners",new Map);const dc=Symbol("NEEDLE_NEED_UPDATE_INSTANCE"),F_=Symbol("isUsingInstancing"),U_=Symbol("instancingRenderer"),uc=Symbol("instancingAutoUpdateBounds");class ds{static isUsingInstancing(e){return e[F_]===!0}static getRenderer(e){return e[U_]||null}setAutoUpdateBounds(e,t){const s=ds.getRenderer(e);s&&(s[uc]=t)}static markDirty(e,t=!0){if(e&&(this.isUsingInstancing(e)&&(e[dc]=!0,e.matrixWorldNeedsUpdate=!0),t))for(const s of e.children)ds.markDirty(s,!0)}}function Da(o,e){try{e||o()}catch(t){return console.error(t),!1}return!0}const $g=C("debugnewscripts"),PM=C("debughierarchy"),Ue=[];function OM(){return Ue.length>0}function Qd(o){if($g&&console.log("Register new components",o.new_scripts.length,[...o.new_scripts],o.alias?"element: "+o.alias:o.hash,o),o.new_scripts_pre_setup_callbacks.length>0){for(const e of o.new_scripts_pre_setup_callbacks)e&&e();o.new_scripts_pre_setup_callbacks.length=0}if(!(o.new_scripts.length<=0)){Ue.length=0,o.new_scripts.length>0&&Ue.push(...o.new_scripts),o.new_scripts.length=0;for(let e=0;e<Ue.length;e++)try{const t=Ue[e];if(t.isComponent!==!0){(F()||$g)&&console.error(`Registered script is not a Needle Engine component.
168
+ The script will be ignored. Please make sure your component extends "Behaviour" imported from "@needle-tools/engine"
169
+ `,t),Ue.splice(e,1),e--;continue}if(t.destroyed)continue;if(!t.gameObject){console.warn(`Component can not be initialized: no GameObject assigned.
170
+ Did you add and remove a component in the same frame?`),Ue.splice(e,1),e--;continue}t.context=o,pc(t.gameObject),Gg(t,o)}catch(t){console.error(t),Dn(Ue[e],o),Ue.splice(e,1),e--}for(let e=0;e<Ue.length;e++)try{const t=Ue[e];if(t.destroyed){Dn(Ue[e],o),Ue.splice(e,1),e--;continue}if(t.registering)try{t.registering()}catch(s){console.error(s)}t.__internalAwake!==void 0&&(t.gameObject||console.error("Calling awake for a component without a GameObject",t,t.gameObject),pc(t.gameObject),t.activeAndEnabled&&Da(t.__internalAwake.bind(t)))}catch(t){console.error(t),Dn(Ue[e],o),Ue.splice(e,1),e--}for(let e=0;e<Ue.length;e++)try{const t=Ue[e];if(t.destroyed||t.enabled===!1||(pc(t.gameObject),t.activeAndEnabled===!1))continue;t.__internalEnable!==void 0&&(t.enabled=!0,Da(t.__internalEnable.bind(t)))}catch(t){console.error(t),Dn(Ue[e],o),Ue.splice(e,1),e--}for(let e=0;e<Ue.length;e++)try{const t=Ue[e];if(t.destroyed||!t.gameObject)continue;o.new_script_start.push(t)}catch(t){console.error(t),Dn(Ue[e],o),Ue.splice(e,1),e--}Ue.length=0;for(const e of o.new_scripts_post_setup_callbacks)e&&e();o.new_scripts_post_setup_callbacks.length=0}}function kM(o){o&&(o.__internalDisable(!0),Dn(o,o.context))}function z_(o,e){for(let t=0;t<o.new_script_start.length;t++)try{const s=o.new_script_start[t];if(e!==void 0&&s.gameObject!==e||s.destroyed||s.activeAndEnabled===!1)continue;Da(s.__internalAwake.bind(s)),s.enabled&&(Da(s.__internalEnable.bind(s)),Da(s.__internalStart.bind(s)),o.new_script_start.splice(t,1),t--)}catch(s){console.error(s),Dn(o.new_script_start[t],o),o.new_script_start.splice(t,1),t--}}function Gg(o,e){e.scripts.indexOf(o)===-1&&(e.scripts.push(o),o.earlyUpdate&&e.scripts_earlyUpdate.push(o),o.update&&e.scripts_update.push(o),o.lateUpdate&&e.scripts_lateUpdate.push(o),o.onBeforeRender&&e.scripts_onBeforeRender.push(o),o.onAfterRender&&e.scripts_onAfterRender.push(o),o.onPausedChanged&&e.scripts_pausedChanged.push(o),qg(o,null)&&e.new_scripts_xr.push(o),qg(o,"immersive-vr")&&e.scripts_immersive_vr.push(o),qg(o,"immersive-ar")&&e.scripts_immersive_ar.push(o))}function Dn(o,e){Zi(o,e.new_scripts),Zi(o,e.new_script_start),Zi(o,e.scripts),Zi(o,e.scripts_earlyUpdate),Zi(o,e.scripts_update),Zi(o,e.scripts_lateUpdate),Zi(o,e.scripts_onBeforeRender),Zi(o,e.scripts_onAfterRender),Zi(o,e.scripts_pausedChanged),Zi(o,e.new_scripts_xr),Zi(o,e.scripts_immersive_vr),Zi(o,e.scripts_immersive_ar),e.stopAllCoroutinesFrom(o)}function Zi(o,e){const t=e.indexOf(o);t>=0&&e.splice(t,1)}function qg(o,e){var t;if(o){const s=o;if(s.onBeforeXR||s.onEnterXR||s.onUpdateXR||s.onLeaveXR||s.onXRControllerAdded||s.onXRControllerRemoved)return!(e!=null&&((t=s.supportsXR)==null?void 0:t.call(s,e))===!1)}return!1}function Yd(o){if(o||(o=pe.Current.scene),!o){console.trace("Invalid call - no current context.");return}const e=za(o);N_(o,e,!0)||($g||F()?console.error(`Error updating hierarchy
171
+ Do you have circular references in your project? <a target="_blank" href="https://docs.needle.tools/circular-reference"> Click here for more information.`,o):console.error('Failed to update active state in hierarchy of "'+o.name+'"',o),console.warn(" \u2191 this error might be caused by circular references. Please make sure you don't have files with circular references (e.g. one GLB 1 is loading GLB 2 which is then loading GLB 1 again)."))}function N_(o,e,t,s=0){if(s>1e3)return console.warn("Hierarchy is too deep (> 1000 level) - will abort updating active state"),!1;const n=za(o);if(e&&(e=n,e&&o.parent)){const c=o.parent;e=c[En],e===void 0&&(c instanceof wi||(e=!0))}const r=o[En]!==e;o[En]=e,r&&(PM&&console.warn("ACTIVE CHANGE",o.name,n,o.visible,e,"changed?"+r,o),MM(o,c=>{e?c.enabled&&(Da(c.__internalAwake.bind(c)),c.enabled&&c.__internalEnable()):c.__didAwake&&c.enabled&&(c.__didEnable=!1,c.onDisable())}));let l=!0;if(o.children)for(const c of o.children)N_(c,e,t,s+1)===!1&&(l=!1);return l}function pc(o){let e=!0,t=o,s=!1;for(;t&&t;){if(t.type==="Scene"&&(s=!0),!za(t)){e=!1;break}t=t.parent}if(!o){console.error("GO is null");return}o[En]=e&&s}function MM(o,e){var t;if((t=o.userData)!=null&&t.components)for(const s of o.userData.components)e(s)}const Kd=new Map,W_=Symbol("prewarmFlag"),Xg=Symbol("waitingForPrewarm"),Qg=C("debugprewarm");function RM(o,e){!o||o[W_]===!0||o[Xg]===!0||(Kd.has(e)||Kd.set(e,[]),o[Xg]=!0,Kd.get(e).push(o),Qg&&console.debug("register prewarm",o.name))}let Yg=null,Kg=null;function TM(o){if(!o)return;const e=Kd.get(o);if(!(e!=null&&e.length))return;const t=o.mainCamera;if(t){Qg&&console.log("prewarm",e.length,"objects",[...e]);const s=o.renderer;if(s.compile){const n=o.scene;s.compile(n,t),Yg??(Yg=new FC(64)),Kg??(Kg=new UC(.001,9999999,Yg)),Kg.update(s,n);for(const r of e)r[W_]=!0,r[Xg]=!1;e.length=0,Qg&&console.log("prewarm done")}}}pe.registerCallback(me.ContextCreated,o=>{const e=o.context;X_(e),$_(e)});const Zd=C("debugcomponents"),V_="eff8ba80-635d-11ec-90d6-0242ac120003";class Lt{constructor(e){a(this,"_originalSeed"),a(this,"_seed"),typeof e=="string"&&(e=Lt.hash(e)),this._originalSeed=e,this._seed=e}get seed(){return this._seed}set seed(e){this._seed=e}reset(){this._seed=this._originalSeed}generateUUID(e){if(typeof e=="string")return Hv(e,V_);const t=this._seed;return this._seed-=1,Hv(t.toString(),V_)}initialize(e){typeof e=="string"?this._seed=Lt.hash(e):this._seed=e}static createFromString(e){return new Lt(this.hash(e))}static hash(e){let t=0;for(let s=0;s<e.length;s++)t=e.charCodeAt(s)+((t<<5)-t);return t}}var H_=(o=>(o.NewInstanceCreated="new-instance-created",o.InstanceDestroyed="instance-destroyed",o))(H_||{});class EM{constructor(e){a(this,"guid"),a(this,"dontSave"),this.guid=e}}function mc(o,e,t=!0,s){if(!o)return;const n=o;if(Ei(o,t),!e){console.warn("Can not send destroy: No networking connection provided",o.guid);return}if(!e.isConnected){F()&&console.debug("Can not send destroy: not connected",o.guid);return}let r=o.guid;if(!r&&n.uuid&&(r=n.uuid),!r){console.warn("Can not send destroy: failed to find guid",o);return}Zg(r,e,s)}function Zg(o,e,t){const s=new EM(o);t?.saveInRoom===!1&&(s.dontSave=!0),e.send("instance-destroyed",s,xs.Queued)}function $_(o){o.connection.beginListen("instance-destroyed",e=>{Zd&&console.log("[Remote] Destroyed",o.scene,e);const t=hf(e.guid,o.scene);t&&Ei(t)})}class AM{constructor(e,t,s){a(this,"filename"),a(this,"hash"),a(this,"size"),this.filename=e,this.hash=t,this.size=s}}class G_{constructor(e,t){a(this,"guid"),a(this,"originalGuid"),a(this,"seed"),a(this,"visible"),a(this,"hostData"),a(this,"dontSave"),a(this,"parent"),a(this,"position"),a(this,"rotation"),a(this,"scale"),a(this,"preventCreation"),a(this,"deleteStateOnDisconnect"),this.originalGuid=e,this.guid=t}}function Jg(o,e,t,s){var n,r;const l=o;if(!l.guid)return console.warn("Can not instantiate: No guid",l),null;if(e.context||(e.context=ee.Current),!e.context)return console.error("Missing network instantiate options / reference to network connection in sync instantiate"),null;const c=e?{...e}:null,{instance:h,seed:d}=IM(l,e);if(h){const u=h;if(u.guid){Zd&&console.log("[Local] new instance","gameobject:",h?.guid);const p=new G_(l.guid,u.guid);p.seed=d,e.deleteOnDisconnect===!0&&(p.deleteStateOnDisconnect=!0),c&&(c.position&&(p.position={x:c.position.x,y:c.position.y,z:c.position.z}),c.rotation&&(p.rotation={x:c.rotation.x,y:c.rotation.y,z:c.rotation.z,w:c.rotation.w}),c.scale&&(p.scale={x:c.scale.x,y:c.scale.y,z:c.scale.z})),p.position||(p.position={x:u.position.x,y:u.position.y,z:u.position.z}),p.rotation||(p.rotation={x:u.quaternion.x,y:u.quaternion.y,z:u.quaternion.z,w:u.quaternion.w}),p.scale||(p.scale={x:u.scale.x,y:u.scale.y,z:u.scale.z}),p.visible=l.visible,c!=null&&c.parent&&(typeof c.parent=="string"?p.parent=c.parent:p.parent=c.parent.guid),p.hostData=t,s===!1&&(p.dontSave=!0),!((n=e?.context)!=null&&n.connection)&&F()&&console.debug("Object will be instantiated but it will not be synced: not connected",l.guid),e.context.connection.isInRoom&&Ba.push(new WeakRef(u)),(r=e?.context)==null||r.connection.send("new-instance-created",p)}else console.warn("Missing guid, can not send new instance event",u)}return h}function q_(){return Math.random()*9999999}const Ba=new Array;function X_(o){o.connection.beginListen("new-instance-created",async e=>{const t=await LM(e.originalGuid,o.scene);if(e.preventCreation===!0)return;if(!t){console.warn("could not find object that was instantiated: "+e.guid);return}const s=new Fs;e.position&&(s.position=new x(e.position.x,e.position.y,e.position.z)),e.rotation&&(s.rotation=new H(e.rotation.x,e.rotation.y,e.rotation.z,e.rotation.w)),e.scale&&(s.scale=new x(e.scale.x,e.scale.y,e.scale.z)),s.parent=e.parent,e.seed&&(s.idProvider=new Lt(e.seed)),s.visible=e.visible,s.context=o,Zd&&o.alias&&console.log("[Remote] instantiate in: "+o.alias);const n=Wa(t,s);Ba.push(new WeakRef(n)),n&&(e.parent==="scene"&&o.scene.add(n),Zd&&console.log("[Remote] new instance","gameobject:",n?.guid,t))}),o.connection.beginListen("left-room",()=>{Ba.length>0&&console.debug(`Left networking room, cleaning up ${Ba.length} instantiated objects`);for(const e of Ba){const t=e.deref();t&&t.destroy()}Ba.length=0})}function IM(o,e){const t=q_(),s=e??new Fs;s.idProvider=new Lt(t);const n=Wa(o,s);return{seed:t,instance:n}}const Q_={};function Y_(o,e){Q_[o]=e}async function LM(o,e){const t=Q_[o];if(t!=null){const s=await t(o);if(s)return s}return K_(o,e)}function K_(o,e){if(e===null||!o)return null;if(e.guid===o)return e;if(e.children)for(const t of e.children){const s=K_(o,t);if(s)return s}return null}const gc=C("gizmos"),_t=C("debugextension"),ef=C("debugtypes");class jM{constructor(){a(this,"_types",new Map),ef&&console.warn("TypeStore: Created",this)}add(e,t){ef&&console.warn("ADD TYPE",e);const s=this._types.get(e);s?ef&&s!==t&&console.warn("Type name exists multiple times in your project and may lead to runtime errors:",e):this._types.set(e,t)}get(e){return this._types.get(e)||null}getKey(e){for(const[t,s]of this._types)if(s===e)return t;return null}}const DM=Symbol("BuiltInType"),R=new jM,BM=function(o){R.get(o.name)||R.add(o.name,o)},tf=C("debugresolvedependencies"),FM=["/extensions/","extensions/"],UM=[{prefix:"/nodes/",dependencyName:"node"},{prefix:"/meshes/",dependencyName:"mesh"},{prefix:"/materials/",dependencyName:"material"},{prefix:"/textures/",dependencyName:"texture"},{prefix:"/animations/",dependencyName:"animation"},{prefix:"nodes/",dependencyName:"node"},{prefix:"meshes/",dependencyName:"mesh"},{prefix:"materials/",dependencyName:"material"},{prefix:"textures/",dependencyName:"texture"},{prefix:"animations/",dependencyName:"animation"}];async function sf(o,e){tf&&console.log(o,e);const t=[];nf(UM,o,e,t);const s=await Promise.all(t);return typeof e=="string"&&s.length===1?s[0]:s}function Z_(o,e){return!o||!e?!1:o["needle:identifier"]!=null&&e["needle:identifier"]!=null?o["needle:identifier"]===e["needle:identifier"]:!1}function zM(o,e){o["needle:identifier"]=e}function nf(o,e,t,s){if(typeof t=="object"&&t!==void 0&&t!==null)for(const n of Object.keys(t)){const r=t[n];if(typeof r=="string"){const l=J_(e,r);if(l!=null)typeof l.then=="function"?s.push(l.then(c=>t[n]=c)):t[n]=l;else{const c=ew(o,e,r);if(c){s.push(c.then(h=>(t[n]=h,h)));continue}}}else if(Array.isArray(r))for(let l=0;l<r.length;l++){const c=r[l],h=J_(e,c);if(h!==null){typeof h.then=="function"?s.push(h.then(d=>r[l]=d)):r[l]=h;continue}for(const d of o){const u=tw(d.prefix,c);if(u>=0){tf&&console.log(d,u,d.dependencyName),s.push(e.getDependency(d.dependencyName,u).then(p=>r[l]=p));break}}typeof c=="object"&&nf(o,e,c,s)}else typeof r=="object"&&nf(o,e,r,s)}else if(typeof t=="string"){const n=ew(o,e,t);n&&s.push(n)}}function J_(o,e){if(o&&o.plugins&&typeof e=="string"){for(const t of FM)if(e.startsWith(t)){let s=e.substring(t.length);const n=s.indexOf("/");n>=0&&(s=s.substring(0,n));const r=o.plugins[s];if(_t&&console.log(s,r),typeof r?.resolve=="function"){const l=e.substring(t.length+s.length+1);return r.resolve(o,l)}break}}return null}function ew(o,e,t){for(const s of o){const n=tw(s.prefix,t);if(n>=0)return tf&&console.warn("GET DEPENDENCY",s,n,s.dependencyName),e.getDependency(s.dependencyName,n)}return null}function tw(o,e){if(typeof e=="string"&&e.startsWith(o)){const t=e.substring(o.length),s=Number.parseInt(t);if(s>=0)return s}return-1}const of="NEEDLE_persistent_assets";function NM(o){return o?.___persistentAsset===!0}class WM{constructor(e){a(this,"parser"),this.parser=e}get name(){return of}async afterRoot(e){var t,s;if(!((s=(t=this.parser)==null?void 0:t.json)!=null&&s.extensions))return;const n=this.parser.json.extensions[of];if(!n)return;_t&&console.log(n);const r=new Array;for(const l of n?.assets){const c=sf(this.parser,l);c&&r.push(c)}await Promise.all(r)}resolve(e,t){const s=Number.parseInt(t);if(s>=0){_t&&console.log(t);const n=e.json.extensions[of];if(n){const r=n?.assets[s];if(r&&typeof r=="object"){r.___persistentAsset=!0;const l=r.__type;l&&R.get(l)}return r}}return null}}const Ys=C("debugserializer");class VM{constructor(){a(this,"typeMap",new Map)}register(e,t){if(this.typeMap.has(e)){const s=this.typeMap.get(e);if(s===t)return;Ys&&console.warn("Type: "+e+" is already registered",t,s)}Ys&&console.log("Register type serializer",t.name,t,e),this.typeMap.set(e,t)}getSerializer(e){if(e)return this.typeMap.get(e)}getSerializerForConstructor(e,t=0){if(t>20)return;if(!e||!e.constructor){Ys&&console.log("invalid type");return}const s=e.name,n=this.getSerializer(e);if(n!==void 0)return Ys&&console.log("FOUND SERIALIZER",n?.name,e.name,e.constructor.name,"for type: "+s,n,e,this.typeMap),n;const r=Object.getPrototypeOf(e);if(r&&r!==e){const l=this.getSerializerForConstructor(r,++t);if(l){const c=r.constructor||r.prototype;Ys&&console.log("FOUND SERIALIZER(in constructor) "+c.constructor.name,c.name,c,l),this.register(c,l)}return l}Ys&&console.warn("No serializer found for "+s,e,e.name,e.constructor.name)}}const Jd=new VM;class Ji{constructor(e,t){if(a(this,"name"),this.name=t,Array.isArray(e))for(const s of e)Jd.register(s,this);else Jd.register(e,this)}}class HM{constructor(){a(this,"isDevMode",qt()),a(this,"cache",{})}registerDefinedKeys(e,t){if(this.isDevMode&&this.cache[e]===void 0){this.cache[e]=Object.keys(t);const s=t;s.$serializedTypes&&Object.keys(s.$serializedTypes)&&this.cache[e].push(...Object.keys(s.$serializedTypes)),Ys&&console.log("registerDefinedKeys for "+e,this.cache[e],t)}}getDefinedKey(e,t){return this.cache[e]===void 0?!1:this.cache[e].includes(t)}}class rf{constructor(e){a(this,"root"),a(this,"gltf"),a(this,"gltfId"),a(this,"object"),a(this,"target"),a(this,"nodeId"),a(this,"nodeToObject"),a(this,"objectToNode"),a(this,"context"),a(this,"path"),a(this,"type"),a(this,"serializable"),a(this,"implementationInformation"),this.root=e}}function iw(o,e){const t=o.$serializedTypes;if(t===void 0)return null;const s={};for(const r in t){const l=o[r];if(l!=null&&typeof l=="object"){const c=Jd.getSerializerForConstructor(l);if(c){s[r]=c.onSerialize(l,e);continue}}s[r]=l}function n(r){const l=R._types;for(const[c,h]of l)if(h===o.constructor)return c;return r.__name||r.constructor.name}return s.name=n(o),typeof o.guid=="string"&&(s.guid=o.guid),s}const eu=[];function sw(o,e){if(!o)return e;typeof o.$serializedTypes=="object"&&(e||(e={}),Object.assign(e,o.$serializedTypes));const t=Object.getPrototypeOf(o);return sw(t,e)}function tu(o,e,t){if(!o)return!1;if(t.target=o,o.onBeforeDeserialize!==void 0){const n=o.onBeforeDeserialize(e,t);if(typeof n=="boolean")return n}const s=sw(o);if(e){if(typeof e.guid=="string"&&(o.guid=e.guid),s)for(const n in s){let r=function(h){const d=h.type;return d?af(c,d,t,void 0,o[n]):af(c,h,t,void 0,o[n])};const l=s[n],c=e[n];if(Ys&&console.log(n,c,o,l),!(o[n]!==void 0&&c===void 0)&&(t.type=void 0,t.path=n,t.serializable=l,!(o.onBeforeDeserializeMember!==void 0&&o.onBeforeDeserializeMember(n,c,t)===!0))){if(l===null)o[n]=c;else{if(Array.isArray(l))for(let h=0;h<l.length;h++){const d=l[h],u=r(d);if(u!==void 0||h===l.length-1){o[n]=u;break}}else o[n]=r(l);eu.length=0}o.onAfterDeserializeMember!==void 0&&o.onAfterDeserializeMember(n,c,t)}}qM(o,e)}return GM(o,e,t.implementationInformation),o.onAfterDeserialize!==void 0&&o.onAfterDeserialize(e,t),!0}const $M=C("noerrors");function GM(o,e,t){var s,n;if($M||!e||!qt()||!o||o.constructor&&o.constructor[DM]===!0)return;const r=(s=o.constructor)==null?void 0:s.name,l=Object.getOwnPropertyNames(e);for(const c of l){if(c==="sourceId")continue;const h=o[c];if(h==null)continue;const d=e[c];if(t?.getDefinedKey(r,c)===!1){const u=c.charAt(0).toUpperCase()+c.slice(1);t.getDefinedKey(r,u)&&($s(Oi.Warn,'<strong>Please rename</strong> "'+u+'" to "'+c+'" in '+r),console.warn('Please use lowercase for field: "'+u+'" in '+r,d,o));continue}if(d!=null){if(typeof d=="object"&&(h===void 0||!h.isObject3D)){if(typeof d.node=="number"||typeof d.guid=="string"){if(d.could_not_resolve)continue;if(!(h!==void 0&&Object.keys(h).length>1)){$s(Oi.Warn,`<strong>Missing serialization for object reference!</strong>
172
+
173
+ Please change to:
174
+ @serializable(Object3D)
175
+ ${c}? : Object3D;
176
+
177
+ in ${r}.ts
178
+ <a href="https://docs.needle.tools/serializable" target="_blank">See documentation</a>`),console.warn(r,c,o[c],o);continue}}else if(!Array.isArray(h)){const u=(n=h.constructor)==null?void 0:n.name;if(u==="Object"&&!h.constructor["did_warn:missing_serializable"]){h.constructor["did_warn:missing_serializable"]=!0;const p='You might be missing a @serializable(Type) decorator for field "'+c+'" in '+r+".ts";console.warn(p+`
179
+ ${c}:`,d,u),$s(Oi.Warn,"Dev Warning: Are you missing a type in @serializable? Please check the browser console for details")}}}if(typeof h=="string"&&typeof d=="string"&&(d.endsWith(".gltf")||d.endsWith(".glb"))){$s(Oi.Warn,`<strong>Missing serialization for object reference!</strong>
180
+
181
+ Please change to:
182
+ @serializable(AssetReference)
183
+ ${c}? : AssetReference;
184
+
185
+ in script ${r}.ts
186
+ <a href="https://docs.needle.tools/serializable" target="_blank">documentation</a>`),console.warn(r,c,o[c],o);continue}}}}function qM(o,e){for(const t of Object.keys(e)){const s=e[t];if(typeof s=="object"&&s!==null&&s!==void 0){const n=o[t];if(!n){Ys&&console.log(t,"is undefined on",o);continue}for(const r of Object.keys(s))if(n[r]===void 0&&nw(s[r])&&!nw(n)){const l=XM(n,r);if(l&&(l?.writable===void 0||l?.writable===!1)&&l.set===void 0){Ys&&console.warn('Property is not writable "'+r+'"',n,l,s[r],n[r]);continue}n[r]=s[r]}}}}function XM(o,e){for(;o;){const t=Object.getOwnPropertyDescriptor(o,e);if(t)return t;o=Object.getPrototypeOf(o)}}function nw(o){switch(typeof o){case"number":case"string":case"boolean":return!0}return!1}function af(o,e,t,s,n){let r=typeof e=="function"&&e.prototype===void 0,l=e;if(r)try{if(l=e?.call(e,n),r=!1,l==null)return}catch(u){console.error("Error in callback",u,o)}if(t.type=l,!r&&n&&(n instanceof Pe||n instanceof q||n instanceof Vs||n instanceof mo))return n;if(s||(s={serializer:Jd.getSerializerForConstructor(l)}),n&&typeof n=="object"&&NM(n)){if(n.__concreteInstance)return n.__concreteInstance;const u=n;if(!u.$serializedTypes&&l.prototype.$serializedTypes&&(u.$serializedTypes=l.prototype.$serializedTypes),u.$serializedTypes&&tu(u,o,t),n&&l!==void 0)try{let p=null;s.serializer&&(p=s.serializer.onDeserialize(o,t)),p||(p=new l,_t&&console.log("Create concrete instance for persistent asset",n,"instance:",p),Fa(p,n)),n.__concreteInstance=p,n=p}catch(p){console.error("Error creating instance or creating values on instance",p,n,l)}return n}if(Array.isArray(o)){const u=[];for(let p=0;p<o.length;p++){const g=o[p],f=af(g,e,t,s,g);u.push(f)}return u}const c=s?.serializer;if(c)return c.onDeserialize(o,t);if(n instanceof De)return n;let h;if(o&&(o.isMaterial||o.isTexture||o.isObject3D||o instanceof mo))h=o;else{if(o===void 0)return;if(o===null&&(l===Pe||l===De||l===q||l===mo))return null;try{h=new l(...QM(o))}catch(u){console.error("Error creating "+t.path,t.target,u);return}}const d=h;return d.$serializedTypes&&tu(d,o,t),h}function QM(o){if(eu.length=0,typeof o=="object"&&o!==null&&o!==void 0)for(const e of Object.keys(o))eu.push(o[e]);return eu}const lf=Symbol("assigned component properties");function Fa(o,e,t,s){var n;if(e==null||o==null)return;o[lf]=!0;const r=((n=o.constructor)==null?void 0:n.name)??"unknown";t?.registerDefinedKeys(r,o);for(const l of Object.keys(e)){const c=YM(o,l);if(typeof c?.value!="function"){if(!c||c.writable===!0){const h=s!=null&&s.onAssign?s.onAssign(e,l,e[l]):e[l];o[l]=h}else if(c?.set!==void 0){const h=s!=null&&s.onAssign?s.onAssign(e,l,e[l]):e[l];o[l]=h}}}delete o[lf]}function YM(o,e){let t;do t=Object.getOwnPropertyDescriptor(o,e);while(!t&&(o=Object.getPrototypeOf(o)));return t}const ow=Symbol("customVisibilityFlag");function Bn(o,e){o.layers[ow]=e}const rw=Symbol("DidPatchLayers");function KM(){const o=ho.prototype;if(o[rw])return;o[rw]=!0;const e=o.test;o.test=function(t){return this[ow]===!1?!1:e.call(this,t)}}KM(),Object.defineProperty(we.prototype,"fov",{get:function(){return this._fov},set:function(o){const e=o!==this._fov;this._fov=o,e&&this.view!==void 0&&this.updateProjectionMatrix()},configurable:!0}),Object.defineProperty(we.prototype,"near",{get:function(){return this._near},set:function(o){const e=o!==this._near;this._near=o,e&&this.view!==void 0&&this.updateProjectionMatrix()},configurable:!0}),Object.defineProperty(we.prototype,"far",{get:function(){return this._far},set:function(o){const e=o!==this._far;this._far=o,e&&this.view!==void 0&&this.updateProjectionMatrix()},configurable:!0});const aw=new Map;function lw(o,e){if(!o)return;if(!e){console.warn("No prototype found",o,o.prototype,o.constructor);return}const t=aw.get(e);t&&t.apply(o)}function cw(o){const e=ZM(o.prototype);aw.set(o,e)}function ZM(o){return new JM(o)}class JM{constructor(e){a(this,"$symbol"),a(this,"extensions"),a(this,"descriptors"),this.$symbol=Symbol("prototype-extension"),this.extensions=Object.keys(e),this.descriptors=new Array;for(let t=0;t<this.extensions.length;t++){const s=this.extensions[t],n=Object.getOwnPropertyDescriptor(e,s);n&&this.descriptors.push(n)}}apply(e){if(!e[this.$symbol]){e[this.$symbol]=!0;for(let t=0;t<this.extensions.length;t++){const s=this.extensions[t],n=this.descriptors[t];n&&Object.defineProperty(e,s,n)}}}}const eR=C("debuggetcomponent"),hw=()=>eR||globalThis.NEEDLE_DEBUG_GETCOMPONENT===!0;function tR(o){return o==null||o.isObject3D?o:o.object&&o.object.isObject3D?o.object:o}function cf(o,e){if(!o||!o.userData.components)return e;const t=o.userData.components.indexOf(e);return t<0||(hc.dispatchComponentLifecycleEvent("removing-component",e),e.gameObject=null,o.userData.components.splice(t,1)),e}function fc(o,e,t){return Or(o,e)||Ti(o,e,t)}const dw=new Lt("addComponentIdProvider");function Pr(o,e,t=!0){o.userData||(o.userData={}),o.userData.components||(o.userData.components=[]),o.userData.components.push(e),e.gameObject=o,(e.guid===void 0||e.guid==="invalid")&&(e.guid=dw.generateUUID()),su(o),yu(e,e.context);try{t&&e.__internalAwake&&(pc(o),e.activeAndEnabled&&e.__internalAwake()),hc.dispatchComponentLifecycleEvent("component-added",e)}catch(s){console.error(s)}return e}function Ti(o,e,t,s){var n;if(typeof e=="function"){const r=new e;t&&r.__internalNewInstanceCreated(t);let l=!0;return s?.callAwake!=null&&(l=s.callAwake),Pr(o,r,l)}if(e.destroyed)return console.warn("Can not move/add a destroyed component",e),e;if(e.gameObject===o)return e;if(e.gameObject&&(n=e.gameObject.userData)!=null&&n.components){const r=e.gameObject.userData.components.indexOf(e);e.gameObject.userData.components.splice(r,1)}if(o.userData||(o.userData={}),!o.userData.components)o.userData.components=[];else if(o.userData.components.includes(e))return e;return o.userData.components.push(e),e.gameObject=o,(e.guid===void 0||e.guid==="invalid")&&(e.guid=dw.generateUUID()),t&&e._internalInit(t),yu(e,e.context),e}function uw(o){if(o.gameObject&&o.gameObject.userData.components){const e=o.gameObject.userData.components.indexOf(o);o.gameObject.userData.components.splice(e,1)}o.__internalDisable&&o.__internalDisable(),Dn(o,o.context??ee.Current),o.destroy(),o.gameObject=null}let pw=!1;function mw(o,e,t){var s;if(o==null)return null;if(!o.isObject3D)return console.error("Object is not object3D"),null;if(!((s=o?.userData)!=null&&s.components)||(typeof e=="string"&&(pw||(pw=!0,console.warn(`Accessing components by name is not supported.
187
+ Please use the component type instead. This may keep working in local development but it will fail when bundling your application.
188
+
189
+ You can import other modules your main module to get access to types
190
+ or if you use npmdefs you can make types available globally using globalThis:
191
+ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis`,e))),hw()&&console.log("[onGetComponent] FIND",e),e==null))return null;for(let n=0;n<o.userData.components.length;n++){const r=o.userData.components[n];let l=Object.getPrototypeOf(r);for(;l;){if(l===e.prototype)if(hw()&&console.log("[onGetComponent] MATCH BY PROTOYPE",l),t)t.push(r);else return r;l=Object.getPrototypeOf(l)}}return t||null}function Or(o,e){const t=mw(o,e);return t?Array.isArray(t)?t[0]:t:null}function yc(o,e,t,s=!0){return t||(t=[]),s&&(t.length=0),mw(o,e,t),t}function vc(o,e,t){var s;if(t===!1&&o[En]===!1)return null;const n=Or(o,e);if(t===!1&&n?.enabled===!1)return null;if(n)return n;for(let r=0;r<((s=o?.children)==null?void 0:s.length);r++){const l=vc(o.children[r],e);if(l)return l}return null}function Ua(o,e,t,s=!0){var n;t||(t=[]),s&&(t.length=0),yc(o,e,t,!1);for(let r=0;r<((n=o?.children)==null?void 0:n.length);r++)Ua(o.children[r],e,t,!1);return t}function bc(o,e){if(!o)return null;if(Array.isArray(o)){for(let s=0;s<o.length;s++){const n=tR(o[s]),r=bc(n,e);if(r)return r}return null}return Or(o,e)||(o.parent?bc(o.parent,e):null)}function iu(o,e,t,s=!0){return t||(t=[]),s&&(t.length=0),o?(yc(o,e,t,!1),o.parent?iu(o.parent,e,t,!1):t):t}function _c(o,e=void 0,t=!0){if(!o)return null;if(!e&&(e=ee.Current,!e))return console.error("Can not search object without any needle context or scene!!!"),null;let s=e;return s.isScene||(s=e?.scene),s&&vc(s,o,t)||null}function gw(o,e,t=void 0){if(!o)return e??[];if(e||(e=[]),e.length=0,!t&&(t=ee.Current,!t))return console.error("Can not search object without any needle context or scene!!!"),e;"scene"in t&&(t=t.scene);const s=t;return s&&Ua(s,o,e,!1),e}function su(o){o&&o.isObject3D===!0&&lw(o,E)}E.prototype.SetActive=function(o){this.visible=o},E.prototype.setActive=function(o){this.visible=o},E.prototype.destroy=function(){Ei(this)},E.prototype.addComponent=function(o,e){return Ti(this,o,e)},E.prototype.addNewComponent=function(o,e){return Ti(this,o,e)},E.prototype.removeComponent=function(o){return cf(this,o)},E.prototype.getOrAddComponent=function(o,e){return fc(this,o,e)},E.prototype.getComponent=function(o){return Or(this,o)},E.prototype.getComponents=function(o,e){return yc(this,o,e)},E.prototype.getComponentInChildren=function(o){return vc(this,o)},E.prototype.getComponentsInChildren=function(o,e){return Ua(this,o,e)},E.prototype.getComponentInParent=function(o){return bc(this,o)},E.prototype.getComponentsInParent=function(o,e){return iu(this,o,e)},Object.getOwnPropertyDescriptor(E.prototype,"activeSelf")||Object.defineProperty(E.prototype,"activeSelf",{get:function(){return za(this)},set:function(o){wc(this,o)}}),Object.getOwnPropertyDescriptor(E.prototype,"worldPosition")||Object.defineProperty(E.prototype,"worldPosition",{get:function(){return this instanceof Fv?te(this.object):te(this)},set:function(o){lt(this,o)}}),Object.getOwnPropertyDescriptor(E.prototype,"worldQuaternion")||Object.defineProperty(E.prototype,"worldQuaternion",{get:function(){return this instanceof Fv?Se(this.object):Se(this)},set:function(o){Qi(this,o)}}),Object.getOwnPropertyDescriptor(E.prototype,"worldRotation")||Object.defineProperty(E.prototype,"worldRotation",{get:function(){return Td(this)},set:function(o){Tb(this,o)}}),Object.getOwnPropertyDescriptor(E.prototype,"worldScale")||Object.defineProperty(E.prototype,"worldScale",{get:function(){return Ge(this)},set:function(o){ka(this,o)}}),Object.getOwnPropertyDescriptor(E.prototype,"worldForward")||Object.defineProperty(E.prototype,"worldForward",{get:function(){return X().set(0,0,1).applyQuaternion(Se(this))}}),Object.getOwnPropertyDescriptor(E.prototype,"worldRight")||Object.defineProperty(E.prototype,"worldRight",{get:function(){return X().set(1,0,0).applyQuaternion(Se(this))}}),Object.getOwnPropertyDescriptor(E.prototype,"worldUp")||Object.defineProperty(E.prototype,"worldUp",{get:function(){return X().set(0,1,0).applyQuaternion(Se(this))}}),cw(E);class he extends ae{constructor(e,t,s,n){super(),a(this,"alpha",1),typeof e=="number"&&typeof t=="number"&&typeof s=="number"?(this.set(e,t,s),this.alpha=typeof n=="number"?n:1):e!==void 0&&(this.set(e),this.alpha=1)}get isRGBAColor(){return!0}set a(e){this.alpha=e}get a(){return this.alpha}clone(){const e=super.clone();return e.alpha=this.alpha,e}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,"alpha"in e&&typeof e.alpha=="number"?this.alpha=e.alpha:typeof e.a=="number"&&(this.alpha=e.a),this}lerp(e,t){const s=e;return s.alpha!=null&&(this.alpha=W.lerp(this.alpha,s.alpha,t)),super.lerp(e,t)}lerpColors(e,t,s){const n=e,r=t;return n.alpha!=null&&r.alpha!=null&&(this.alpha=W.lerp(n.alpha,r.alpha,s)),super.lerpColors(e,t,s)}multiply(e){const t=e;return t.alpha!=null&&(this.alpha=this.alpha*t.alpha),super.multiply(e)}fromArray(e,t=0){return this.alpha=e[t+3],super.fromArray(e,t)}static fromColorRepresentation(e){if(typeof e=="string"){if(e.trim()==="transparent")return new he(0,0,0,0);if(e.startsWith("#")&&e.length===9){const t=parseInt(e.slice(1,9),16),s=t>>24&255,n=t>>16&255,r=t>>8&255,l=t>>0&255;return new he(s/255,n/255,r/255,l/255)}else if(e.startsWith("#")){const t=parseInt(e.slice(1),16),s=t>>16&255,n=t>>8&255,r=t>>0&255;return new he(s/255,n/255,r/255,1)}else if(e.startsWith("rgba")){const t=e.slice(5,-1).split(",").map(Number);return new he(t[0]/255,t[1]/255,t[2]/255,t[3])}else if(e.startsWith("rgb")){const t=e.slice(4,-1).split(",").map(Number);return new he(t[0]/255,t[1]/255,t[2]/255,1)}}else if(Array.isArray(e)){if(e.length===4)return new he(e[0],e[1],e[2],e[3]);if(e.length===3)return new he(e[0],e[1],e[2],1);console.error("Invalid color array length. Expected 3 or 4, got "+e.length)}return new he(e)}}const nu=C("debuggetcomponent"),kr=C("debuginstantiate");class Fs{constructor(){a(this,"idProvider"),a(this,"parent"),a(this,"keepWorldPosition"),a(this,"position"),a(this,"rotation"),a(this,"scale"),a(this,"visible"),a(this,"context"),a(this,"components")}clone(){var e,t,s;const n=new Fs;return n.idProvider=this.idProvider,n.parent=this.parent,n.keepWorldPosition=this.keepWorldPosition,n.position=(e=this.position)==null?void 0:e.clone(),n.rotation=(t=this.rotation)==null?void 0:t.clone(),n.scale=(s=this.scale)==null?void 0:s.clone(),n.visible=this.visible,n.context=this.context,n.components=this.components,n}cloneAssign(e){var t,s,n;this.idProvider=e.idProvider,this.parent=e.parent,this.keepWorldPosition=e.keepWorldPosition,this.position=(t=e.position)==null?void 0:t.clone(),this.rotation=(s=e.rotation)==null?void 0:s.clone(),this.scale=(n=e.scale)==null?void 0:n.clone(),this.visible=e.visible,this.context=e.context,this.components=e.components}}function za(o){return o.visible}function wc(o,e){return typeof e=="number"&&(e=e>.5),o.visible=e,o.visible}function fw(o){return o[En]||ou(o)}function yw(o,e){o[F_]=e}function ou(o){return ds.isUsingInstancing(o)}function hf(o,e){return Pa(o,e,!0,!0)}const vw=Symbol("isDestroyed");function Mr(o){return o[vw]}function bw(o,e){o[vw]=e}const df=Symbol("isDontDestroy");function Na(o,e=!0){o[df]=e}const ru=[],au=[];function Ei(o,e=!0,t=!1){ru.length=0,au.length=0,uf(o,e,!0);for(const s of ru)s.gameObject=null,s.context=null;for(const s of au)bw(s,!0),t&&Te(s),D_(s);au.length=0,ru.length=0}function uf(o,e=!0,t=!0){var s;if(o==null)return;const n=o;if(n.isComponent){if(n[df])return;ru.push(n);const c=n.gameObject;n.__internalDisable(),n.__internalDestroy(),n.gameObject=c;return}if(o[df])return;const r=o;nu&&console.log(r),au.push(r);const l=(s=r.userData)==null?void 0:s.components;if(l!=null&&Array.isArray(l)){let c=l.length;for(let h=0;h<l.length;h++){const d=l[h];uf(d,e,!1),l.length<c&&(c=l.length,h--)}}if(e&&r.children)for(const c of r.children)uf(c,e,!1);t&&r.removeFromParent()}function Rr(o,e,t=!0){return _w(o,e,t)}function*lu(o,e,t=!1,s=999,n=0){if(o!=null&&o.userData.components&&!(n>s)){for(const r of o.userData.components)e&&r?.isComponent===!0&&r instanceof e?yield r:yield r;if(t===!0)for(const r of o.children)yield*lu(r,e,!0,s,n+1)}}function _w(o,e,t,s=0){var n;if(o){if(o.isObject3D,s>1e3){console.warn("Failed to iterate components: too many levels");return}if((n=o.userData)!=null&&n.components)for(let r=0;r<o.userData.components.length;r++){const l=o.userData.components[r];if(l?.isComponent===!0){const c=e(l);if(c!==void 0)return c}}if(t&&o.children){const r=s+1;for(let l=0;l<o.children.length;l++){const c=o.children[l];if(!c)continue;const h=_w(c,e,t,r);if(h!==void 0)return h}}}}function Wa(o,e){if("isAssetReference"in o)return o.instantiate(e??void 0);let t=null;e!=null&&(e.x!==void 0?(t=new Fs,t.position=e):t=e);let s=ee.Current;t!=null&&t.context&&(s=t.context),nu&&s.alias&&console.log("context",s.alias),t&&!t.idProvider&&(t.idProvider=new Lt(Date.now()));const n=[],r={},l={},c=ww(s,o,t,n,r,l);c&&(sR(r),iR(l,r)),nu&&(Ed(o,!0),Ed(c,!0));const h={};if(t?.components!==!1){for(const d in n){const u=n[d],p=u.guid;t&&t.idProvider&&(u.guid=t.idProvider.generateUUID(),h[p]=u.guid,nu&&console.log(u.name,u.guid)),yu(u,s),u.__internalNewInstanceCreated&&u.__internalNewInstanceCreated()}for(const d in n){const u=n[d];u.resolveGuids&&u.resolveGuids(h),u.enabled!==!1&&(u.enabled=!0)}Qd(s)}return c}function ww(o,e,t,s,n,r){var l;if(!e||e[ki])return null;const c=e.userData;e.userData={};const h=e.children;e.children=[];const d=e.clone(!1);if(su(d),e.userData=c,e.children=h,n[e.uuid]={original:e,clone:d},kr&&console.log("ADD",e,d),e.type==="SkinnedMesh"&&(r[e.uuid]={original:e,clone:d}),t?.visible!==void 0&&(d.visible=t.visible),t!=null&&t.idProvider){d.uuid=t.idProvider.generateUUID();const p=d;p&&(p.guid=d.uuid)}e.animations&&e.animations.length>0&&(d.animations=[...e.animations]);const u=e.parent;if(u&&u.add(d),t!=null&&t.position?lt(d,t.position):d.position.copy(e.position),t!=null&&t.rotation?Qi(d,t.rotation):d.quaternion.copy(e.quaternion),t!=null&&t.scale?d.scale.copy(t.scale):d.scale.copy(e.scale),t!=null&&t.parent&&t.parent!=="scene"){let p=null;if(typeof t.parent=="string"?p=Pa(t.parent,o.scene,!0):p=t.parent,p){const g=t.keepWorldPosition===!0?p.attach:p.add;g?g.call(p,d):console.error("Invalid parent object",p,"received when instantiating:",e)}else console.warn("could not find parent:",t.parent)}for(const[p,g]of Object.entries(e.userData))p!=="components"&&(d.userData[p]=g);if((l=e.userData)!=null&&l.components){const p=e.userData.components,g=[];d.userData.components=g;for(let f=0;f<p.length;f++){const y=p[f],b=new y.constructor;Fa(b,y,void 0,{}),y[sc]!==void 0&&(b[sc]=y[sc]),g.push(b),b.gameObject=d,s.push(b),n[y.guid]={original:y,clone:b},hc.dispatchComponentLifecycleEvent("component-added",b)}}t&&(t.position=void 0,t.rotation=void 0,t.scale=void 0,t.parent=void 0,t.visible=void 0);for(const p in e.children){const g=e.children[p],f=ww(o,g,t,s,n,r);f&&(n[f.uuid]={original:g,clone:f},d.add(f))}return d}function iR(o,e){for(const t in o){const s=o[t],n=s.original,r=n.skeleton,l=s.clone;if(!r){console.warn("Skinned mesh has no skeleton?",s);continue}const c=r.bones,h=l.skeleton.clone();l.skeleton=h,l.bindMatrix.clone().copy(n.bindMatrix),l.bindMatrixInverse.copy(n.bindMatrixInverse);const d=[];h.bones=d;for(let u=0;u<c.length;u++){const p=c[u],g=e[p.uuid].clone;d.push(g)}}for(const t in o){const s=o[t].clone;s.skeleton.update(),s.bind(s.skeleton,s.bindMatrix),s.updateMatrixWorld(!0)}}function sR(o){var e;for(const t in o){const s=o[t].clone;if(s!=null&&s.isObject3D&&(e=s?.userData)!=null&&e.components)for(let n=0;n<s.userData.components.length;n++){const r=s.userData.components[n],l=Object.entries(r);for(const[c,h]of l)if(Array.isArray(h)){const d=[];r[c]=d;for(let u=0;u<h.length;u++){const p=h[u];if(typeof p!="object"){d.push(p);continue}const g=xw(r,c,p,o);g!==void 0?(kr&&console.log("Found new instance for",c,p,"->",g),d.push(g)):(kr&&console.warn("Could not find new instance for",c,p),d.push(p))}}else if(typeof h=="object"){const d=xw(r,c,h,o);d!==void 0?r[c]=d:kr&&console.warn("Could not find new instance for",c,h)}}}}function xw(o,e,t,s){var n,r;if(t!=null)if(t.isComponent===!0){const l=t.gameObject;if(l){const c=l.uuid,h=(n=s[c])==null?void 0:n.clone;if(!h){kr&&console.log("reference did not change",e,o,t);return}const d=l.userData.components.indexOf(t);if(d>=0&&h.isObject3D)return kr&&console.log(e,c),h.userData.components[d];console.warn("could not find component",e,t)}}else if(t.isObject3D===!0){if(e==="gameObject")return;const l=t;if(l){const c=l.uuid,h=(r=s[c])==null?void 0:r.clone;if(h)return kr&&console.log(e,"old",t,"new",h),h}}else{if(t.isVector4||t.isVector3||t.isVector2||t.isQuaternion||t.isEuler||t.isColor===!0)return t.clone();if(t.isEventList===!0)return t.__internalOnInstantiate(s)}}var Tr;(o=>{o.baseUrl="https://networking.needle.tools";function e(h){return $v(new Uint8Array(h))}o.hashMD5=e;function t(h){const d=$v(new Uint8Array(h),{encoding:"binary",asBytes:!0});return btoa(String.fromCharCode(...d))}o.hashMD5_Base64=t;function s(h){const d=new Uint8Array(h);return crypto.subtle.digest("SHA-256",d).then(u=>btoa(String.fromCharCode(...new Uint8Array(u))))}o.hashSha256=s;function n(h){const d=h.filesize/1024/1024;return Js()?d<50:d<5}o.canUpload=n;async function r(h,d){var u;const p=o.baseUrl;if(p){if(!h.name)return console.error("Upload: file name is missing"),null}else return console.error("Blob storage base url is not set"),null;let g=null;h instanceof File?g=await h.arrayBuffer():g=h.data;const f=g.byteLength,y=f/1024/1024;if(y>50)return d?.silent!==!0&&be(`File (${y.toFixed(1)}MB) is too large for uploading (see console for details)`),console.warn(`Your file is too large for uploading (${y.toFixed(1)}MB). Max allowed size is 50MB`),null;if(!Js()&&y>5)return d?.silent!==!0&&be('File is too large for uploading. Please get a <a href="https://needle.tools/pricing" target="_blank">commercial license</a> to upload files larger than 5MB'),console.warn(`Your file is too large for uploading (${y.toFixed(1)}MB). Max size is 5MB for non-commercial users. Please get a commercial license at https://needle.tools/pricing for larger files (up to 50MB)`),null;if(f<1)return console.warn(`Your file is too small for uploading (${y.toFixed(1)}MB). Min size is 1 byte`),null;const b=t(g),v={filename:h.name,"Content-Md5":b,"Content-Type":h.type||"application/octet-stream",FileSize:f.toString(),"Content-Disposition":`attachment; filename="${h.name}"`,"x-amz-server-side-encryption":"AES256"},_=await fetch(p+"/api/needle/blob",{method:"POST",headers:v,signal:d?.abort}).then(w=>w.json()).catch(w=>(console.error(w),null));if(_==null)return console.warn("Upload failed..."),null;if("error"in _)return console.error(_.error),null;if("upload"in _&&_.upload){let w=function(M){var T;return(T=d?.onProgress)==null||T.call(null,{progress01:0,state:"inprogress"}),fetch(M,{method:"PUT",headers:v,body:g,signal:d?.abort}).then(L=>{var B;return(B=d?.onProgress)==null||B.call(null,{progress01:1,state:"finished"}),L}).catch(L=>L)};console.debug("Uploading file",_.upload);let S=!1,k=null;for(let M=0;M<3;M++)try{if(S)break;if((u=d?.abort)!=null&&u.aborted)return console.debug("Aborted upload"),null;const T=await w(_.upload);T instanceof Error?(k=T,await ys(1e3*M)):T.ok&&(console.debug("File uploaded successfully"),S=!0)}catch(T){console.error(T)}if(!S)return console.error(k?.message||"Failed to upload file"),null}if("download"in _){const w=p+_.download;return console.debug("File found in blob storage",w),{key:_.key,success:!0,download_url:w}}return null}o.upload=r;function l(h){return`${o.baseUrl}/api/needle/blob/${h}`}o.getBlobUrlForKey=l;async function c(h,d){const u=new Om;u.setResponseType("arraybuffer");const p=await u.loadAsync(h,g=>{d&&d.call(null,g)});return p instanceof ArrayBuffer?new Uint8Array(p):(console.error("Download failed, no arraybuffer returned"),null)}o.download=c})(Tr||(Tr={}));const wo=C("debugaddressables");class Sw{constructor(e){a(this,"_context"),a(this,"_assetReferences",{}),a(this,"preUpdate",()=>{}),this._context=e,this._context.pre_update_callbacks.push(this.preUpdate)}dispose(){const e=this._context.pre_update_callbacks.indexOf(this.preUpdate);e>=0&&this._context.pre_update_callbacks.splice(e,1);for(const t in this._assetReferences){const s=this._assetReferences[t];s?.unload()}this._assetReferences={}}findAssetReference(e){return this._assetReferences[e]||null}registerAssetReference(e){return e.url&&(this._assetReferences[e.url]?console.warn("Asset reference already registered",e):this._assetReferences[e.url]=e),e}unregisterAssetReference(e){e.url&&delete this._assetReferences[e.url]}}const pf=Symbol("assetReference"),Cw=class Ll{constructor(e,t,s=null){a(this,"_loading"),a(this,"_asset"),a(this,"_glbRoot"),a(this,"_url"),a(this,"_urlName"),a(this,"_progressListeners",[]),a(this,"_hash"),a(this,"_hashedUri"),a(this,"_isLoadingRawBinary",!1),a(this,"_rawBinary"),this._url=e;const n=e.lastIndexOf("/");if(n>=0){this._urlName=e.substring(n+1);const r=this._urlName.lastIndexOf(".");r>=0&&(this._urlName=this._urlName.substring(0,r))}else this._urlName=e;this._hash=t,e.includes("?v=")?this._hashedUri=e:this._hashedUri=t?e+"?v="+t:e,s!==null&&(this.asset=s),Y_(this._url,this.onResolvePrefab.bind(this))}static getOrCreateFromUrl(e,t){if(!t&&(t=ee.Current,!t))throw new Error('Context is required when sourceId is a string. When you call this method from a component you can call it with "getOrCreate(this, url)" where "this" is the component.');const s=t.addressables,n=s.findAssetReference(e);if(n)return n;const r=new Ll(e,t.hash);return s.registerAssetReference(r),r}static getOrCreate(e,t,s){if(typeof e=="string"){if(!s&&(s=ee.Current,!s))throw new Error('Context is required when sourceId is a string. When you call this method from a component you can call it with "getOrCreate(this, url)" where "this" is the component.')}else s=e.context,e=e.sourceId;const n=fo(e,t);wo&&console.log("GetOrCreate Addressable from",e,t,"FinalPath=",n);const r=s.addressables,l=r.findAssetReference(n);if(l)return l;const c=new Ll(n,s.hash);return r.registerAssetReference(c),c}get isAssetReference(){return!0}get asset(){return this._glbRoot??this._asset}set asset(e){this._asset=e}get uri(){return this._url}get url(){return this._url}get urlName(){return this._urlName}get hasUrl(){return this._url!==void 0&&(this._url.startsWith("http")||this._url.startsWith("blob:")||this._url.startsWith("www.")||this._url.includes("/"))}get rawAsset(){return this._asset}async onResolvePrefab(e){return e===this.url&&(this.mustLoad&&await this.loadAssetAsync(),this.asset)?this.asset:null}get mustLoad(){return!this.asset||this.asset.__destroyed===!0||Mr(this.asset)===!0}isLoaded(){return this._rawBinary||this.asset!==void 0}unload(){this.asset&&(wo&&console.log("Unload",this.asset),"scene"in this.asset&&this.asset.scene&&Ei(this.asset.scene,!0,!0),Ei(this.asset,!0,!0)),this.asset=null,this._rawBinary=void 0,this._glbRoot=null,this._loading=void 0,ee.Current&&ee.Current.addressables.unregisterAssetReference(this)}async preload(){if(!this.mustLoad||this._isLoadingRawBinary)return null;if(this._rawBinary!==void 0)return this._rawBinary;this._isLoadingRawBinary=!0,wo&&console.log("Preload",this._hashedUri);const e=await Tr.download(this._hashedUri,t=>{this.raiseProgressEvent(t)});return this._rawBinary=e?.buffer??null,this._isLoadingRawBinary=!1,this._rawBinary}async loadAssetAsync(e){if(wo&&console.log("loadAssetAsync",this.url),!this.mustLoad)return this.asset;if(e&&this._progressListeners.push(e),this._loading!==void 0)return this._loading.then(n=>this.asset);const t=ee.Current;if(this._rawBinary){if(!(this._rawBinary instanceof ArrayBuffer))return console.error("Invalid raw binary data",this._rawBinary),null;this._loading=ws().parseSync(t,this._rawBinary,this.url,null),this.raiseProgressEvent(new ProgressEvent("progress",{loaded:this._rawBinary.byteLength,total:this._rawBinary.byteLength}))}else wo&&console.log("Load async",this.url),this._loading=ws().loadSync(t,this._hashedUri,this.url,null,n=>{this.raiseProgressEvent(n)});const s=await this._loading;return this._progressListeners.length=0,this._glbRoot=this.tryGetActualGameObjectRoot(s),this._loading=void 0,s?(s[pf]=this,this._glbRoot&&(this._glbRoot[pf]=this),this.asset&&(this.asset[pf]=this),Qd(t),s.scene!==void 0&&(this.asset=s),this.asset):null}instantiate(e){return this.onInstantiate(e,!1)}instantiateSynced(e,t=!0){return this.onInstantiate(e,!0,t)}beginListenDownload(e){this._progressListeners.indexOf(e)<0&&this._progressListeners.push(e)}endListenDownload(e){const t=this._progressListeners.indexOf(e);t>=0&&this._progressListeners.splice(t,1)}raiseProgressEvent(e){for(const t of this._progressListeners)t(this,e)}async onInstantiate(e,t=!1,s){const n=ee.Current,r=new Fs;if(e instanceof E?r.parent=e:e&&(Object.assign(r,e),r.cloneAssign(e)),r.parent===void 0&&(r.parent=n.scene),this.mustLoad&&await this.loadAssetAsync(),wo&&console.log("Instantiate",this.url,"parent:",e),this.asset){wo&&console.log("Add to scene",this.asset);let l=Ll.currentlyInstantiating.get(this.url);if(l!==void 0&&l>=1e4)return console.error("Recursive or too many instantiations of "+this.url+" in the same frame ("+l+")"),null;try{if(l===void 0&&(l=0),l+=1,Ll.currentlyInstantiating.set(this.url,l),t){r.context=n;const c=this.asset;c.guid=this.url;const h=Jg(c,r,void 0,s);if(h)return h}else{const c=Wa(this.asset,r);if(c)return c}}finally{n.post_render_callbacks.push(()=>{l===void 0||l<0?l=0:l-=1,Ll.currentlyInstantiating.set(this.url,l)})}}else wo&&console.warn("Failed to load asset",this.url);return null}tryGetActualGameObjectRoot(e){if(e&&e.scene){const t=e.scene;return t.isGroup&&t.children.length===1&&t.children[0].name+"glb"===t.name?t.children[0]:t}return null}};a(Cw,"currentlyInstantiating",new Map);let ce=Cw;class nR extends Ji{constructor(){super([ce],"AssetReferenceSerializer")}onSerialize(e,t){if(e&&e.uri!==void 0&&typeof e.uri=="string")return e.uri}onDeserialize(e,t){if(typeof e=="string")return t.context?t.gltfId?ce.getOrCreate(t.gltfId,e,t.context):(console.error("Missing source id"),null):(console.error("Missing context"),null);if(e instanceof E){if(!t.context)return console.error("Missing context"),null;if(!t.gltfId)return console.error("Missing source id"),null;const s=e,n=t.context,r=s.guid??s.uuid,l=n.addressables.findAssetReference(r);if(l)return l;const c=new ce(r,void 0,s);return n.addressables.registerAssetReference(c),c}return null}}new nR;const oR=Promise.resolve(null),Pw=class pm{constructor(e){a(this,"url"),a(this,"_bitmap"),a(this,"_bitmapObject"),a(this,"loader",null),this.url=e}static getOrCreate(e){let t=pm.imageReferences.get(e);return t||(t=new pm(e),pm.imageReferences.set(e,t)),t}dispose(){this._bitmapObject&&this._bitmapObject.close(),this._bitmap=void 0}createHTMLImage(){const e=new Image;return e.src=this.url,e}createTexture(){return this.url?(this.loader||(this.loader=new _a),this.loader.setCrossOrigin("anonymous"),this.loader.loadAsync(this.url).then(e=>{var t;return e&&!((t=e.name)!=null&&t.length)&&(e.name=this.url.split("/").pop()??this.url),e})):(console.error("Can not load texture without url"),oR)}getBitmap(){return this._bitmap?this._bitmap:(this._bitmap=new Promise((e,t)=>{const s=document.createElement("img");s.addEventListener("load",()=>{this._bitmap=createImageBitmap(s).then(n=>(this._bitmapObject=n,e(n),n))}),s.addEventListener("error",n=>{console.error("Failed to load image:"+this.url,n),e(null)}),s.src=this.url}),this._bitmap)}};a(Pw,"imageReferences",new Map);let mf=Pw;class Ow extends Ji{constructor(){super([mf],"ImageReferenceSerializer")}onSerialize(e,t){return null}onDeserialize(e,t){if(typeof e=="string"){const s=fo(t.gltfId,e);return mf.getOrCreate(s)}}}new Ow;const kw=class mm{constructor(e){a(this,"url"),a(this,"res"),this.url=e}static getOrCreate(e){let t=mm.cache.get(e);return t||(t=new mm(e),mm.cache.set(e,t)),t}async loadRaw(){return this.res||(this.res=fetch(this.url)),this.res.then(e=>e.blob())}async loadText(){return this.res||(this.res=fetch(this.url)),this.res.then(e=>e.text())}};a(kw,"cache",new Map);let gf=kw;class Mw extends Ji{constructor(){super([gf],"FileReferenceSerializer")}onSerialize(e,t){return null}onDeserialize(e,t){if(typeof e=="string"){const s=fo(t.gltfId,e);return gf.getOrCreate(s)}}}new Mw;class rR{constructor(e){a(this,"context"),a(this,"mixers",[]),this.context=e}onDestroy(){this.mixers.forEach(e=>e.stopAllAction()),this.mixers.length=0}registerAnimationMixer(e){if(!e){console.warn("AnimationsRegistry.registerAnimationMixer called with null or undefined mixer");return}this.mixers.includes(e)||this.mixers.push(e)}unregisterAnimationMixer(e){if(!e){console.warn("AnimationsRegistry.unregisterAnimationMixer called with null or undefined mixer");return}const t=this.mixers.indexOf(e);t!==-1&&this.mixers.splice(t,1)}}class Va{static tryGetActionsFromMixer(e){return e._actions||null}static tryGetAnimationClipsFromObjectHierarchy(e,t){if(t||(t=new Array),e)e.animations&&t.push(...e.animations);else return t;if(e.children)for(const s of e.children)this.tryGetAnimationClipsFromObjectHierarchy(s,t);return t}static assignAnimationsFromFile(e,t){if(!e||!e.animations){console.debug("No animations found in file");return}for(let n=0;n<e.animations.length;n++){const r=e.animations[n];if(!r.tracks||r.tracks.length<=0){console.warn("Animation has no tracks");continue}for(const l in r.tracks){const c=r.tracks[l],h=wa.parseTrackName(c.name);let d=wa.findNode(e.scene,h.nodeName);if(!d){const p=c.__objectName??c.name.substring(0,c.name.indexOf("."));if(d=e.scene.getObjectByProperty("uuid",p),!d)continue}let u=s(d);if(!u){if(!(t!=null&&t.createAnimationComponent)){console.warn("No AnimationComponent found in parent hierarchy of object and no 'createAnimationComponent' callback was provided in options.");continue}u=t.createAnimationComponent(e.scene,r)}u.addClip&&u.addClip(r)}}function s(n){var r;if(!n)return null;const l=(r=n.userData)==null?void 0:r.components;if(l&&l.length>0){for(let c=0;c<l.length;c++)if(l[c].isAnimationComponent===!0)return n}return s(n.parent)}}}function*ff(o,e=null){const t=e?e.time:ee.Current.time,s=t.time;for(;t.time-s<o;)yield}function*aR(o){for(let e=0;e<o;e++)yield}function*Rw(o){let e=!0;for(o.then(()=>e=!1),o.catch(()=>e=!1);e;)yield}const Tw="NEEDLE_lightmaps",xc=C("debuglightmapsextension")||C("debuglightmaps");var xo=(o=>(o[o.Lightmap=0]="Lightmap",o[o.Skybox=1]="Skybox",o[o.Reflection=2]="Reflection",o))(xo||{});class lR{constructor(e,t,s){a(this,"parser"),a(this,"registry"),a(this,"source"),this.parser=e,this.registry=t,this.source=s}get name(){return Tw}afterRoot(e){const t=this.parser.json.extensions;if(t){const s=t[Tw];if(s){const n=s.textures;return n!=null&&n.length?(xc&&console.log(s),new Promise(async(r,l)=>{const c=[];for(const d of n)if(d.pointer){xc&&console.log(d);let u=null;if(d.pointer.startsWith("/textures/"))xc&&console.log("Load texture from gltf",d.pointer),u=sf(this.parser,d.pointer).then(p=>this.resolveTexture(d,p));else if(typeof d.pointer=="string"){xc&&console.log("Load texture from path",d.pointer);const p=fo(this.source,d.pointer);let g;p.endsWith(".exr")?g=new xd(this.parser.options.manager):p.endsWith(".hdr")?g=new Bm(this.parser.options.manager):g=new _a(this.parser.options.manager),u=g.loadAsync(p,void 0).then(f=>this.resolveTexture(d,f))}else d.pointer;u&&c.push(u)}const h=await Xm(c);h!=null&&h.anyFailed&&F()&&console.error("Failed to load lightmap extension",h),r()})):null}}return null}resolveTexture(e,t){const s=t;xc&&console.log("Lightmap loaded:",s),s!=null&&s.isTexture&&(this.registry?(s.colorSpace=On,this.registry.registerTexture(this.source,e.type,s,e.index)):console.log(xo[e.type],e.pointer,s))}}const Ew=!!C("debuglightmaps");class cR{constructor(e){a(this,"_context"),a(this,"_lightmaps",new Map),this._context=e}clear(){this._lightmaps.clear()}registerTexture(e,t,s,n){Ew&&console.log("Registering ",xo[t]+' "'+e+'"',s),this._lightmaps.has(e)||this._lightmaps.set(e,new Map);const r=this._lightmaps.get(e),l=r?.get(t)??[];l.length<n&&(l.length=n+1),l[n]=s,r?.set(t,l)}tryGetLightmap(e,t=0){return this.tryGet(e,xo.Lightmap,t)}tryGetSkybox(e){return this.tryGet(e,xo.Skybox,0)}tryGetReflection(e){return this.tryGet(e,xo.Reflection,0)}tryGet(e,t,s){if(!e)return Ew&&console.warn("Missing source id"),null;const n=this._lightmaps.get(e);if(!n)return null;const r=n.get(t);return r===void 0||!(r!=null&&r.length)||r.length<=s?null:r[s]}}Gt.lights_fragment_maps=Gt.lights_fragment_maps.replace("vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );",`
192
+ vec2 lUv = vLightMapUv.xy * lightmapScaleOffset.xy + vec2(lightmapScaleOffset.z, (1. - (lightmapScaleOffset.y + lightmapScaleOffset.w)));
193
+ vec4 lightMapTexel = texture2D( lightMap, lUv);
194
+ // The range of RGBM lightmaps goes from 0 to 34.49 (5^2.2) in linear space, and from 0 to 5 in gamma space.
195
+ lightMapTexel.rgb *= lightMapTexel.a * 8.; // no idea where that "8" comes from... heuristically derived
196
+ lightMapTexel.a = 1.;
197
+ lightMapTexel = conv_sRGBToLinear(lightMapTexel);
198
+ `),Gt.lightmap_pars_fragment=`
199
+ #ifdef USE_LIGHTMAP
200
+ uniform sampler2D lightMap;
201
+ uniform float lightMapIntensity;
202
+ uniform vec4 lightmapScaleOffset;
203
+
204
+ // took from threejs 05fc79cd52b79e8c3e8dec1e7dca72c5c39983a4
205
+ vec4 conv_sRGBToLinear( in vec4 value ) {
206
+ return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a );
207
+ }
208
+ #endif
209
+ `,Gt.lights_fragment_begin=Gt.lights_fragment_begin.replace("irradiance += getLightProbeIrradiance( lightProbe, geometry.normal );",`
210
+ #if defined(USE_LIGHTMAP)
211
+ irradiance += 0.;
212
+ #else
213
+ irradiance += getLightProbeIrradiance( lightProbe, geometry.normal );
214
+ #endif`),zC.lightmap.lightmapScaleOffset={value:new ye(1,1,0,0)};const yf=C("debugprogressive"),cu=new xi,hu=new pd;class hR{constructor(e){a(this,"context"),a(this,"_lodsManager"),this.context=e}get manager(){return this._lodsManager}get targetTriangleDensity(){var e;return((e=this._lodsManager)==null?void 0:e.targetTriangleDensity)??-1}set targetTriangleDensity(e){this._lodsManager&&(this._lodsManager.targetTriangleDensity=e)}setRenderer(e){var t;(t=this._lodsManager)==null||t.disable(),Sa.removePlugin(this),Sa.addPlugin(this),Sa.debugDrawLine=G.DrawLine,this._lodsManager=Sa.get(e),this._lodsManager.enable()}disable(){var e;(e=this._lodsManager)==null||e.disable(),Sa.removePlugin(this)}onAfterUpdatedLOD(e,t,s,n,r){yf&&this.onRenderDebug(s,n,r)}onRenderDebug(e,t,s){var n,r,l;if(!t.geometry||!Xe.hasLODLevelAvailable(t.geometry)&&!Xe.hasLODLevelAvailable(t.material))return;const c=Sa.getObjectLODState(t);if(!c)return;let h=s.mesh_lod;const d=s.mesh_lod!=c.lastLodLevel_Mesh||s.texture_lod!=c.lastLodLevel_Texture;if(yf&&t.geometry.boundingSphere){const u=t.geometry.boundingSphere;hu.copy(u),hu.applyMatrix4(t.matrixWorld);const p=hu.center,g=hu.radius,f=["#76c43e","#bcc43e","#c4ac3e","#c4673e","#ff3e3e"];if(d)G.DrawWireSphere(p,g,f[h],.1);else{const y=((n=t.geometry.index)==null?void 0:n.count)??0,b=(r=Xe.getMeshLODInformation(t.geometry))==null?void 0:r.lods;h=b?Math.min(b?.length-1,h):0;let v="";if(b&&c.lastScreenCoverage>0)for(let S=0;S<b.length;S++){const k=b[S].density,M=S==b.length-1;v+=k.toFixed(0)+">"+(k/c.lastScreenCoverage).toFixed(0)+(M?"":",")}const _=b?(l=b[h])==null?void 0:l.density:-1;let w="LOD "+s.mesh_lod+`
215
+ TEX `+s.texture_lod;if(yf=="density"&&(w+=`
216
+ `+y+` tris
217
+ `+(_/c.lastScreenCoverage).toFixed(0)+` dens
218
+ `+(c.lastScreenCoverage*100).toFixed(1)+`% cov
219
+ `+(c.lastCentrality*100).toFixed(1)+`% centr
220
+ `+(cu.min.x.toFixed(2)+"-"+cu.max.x.toFixed(2)+"x"+cu.min.y.toFixed(2)+"-"+cu.max.y.toFixed(2))+" scr"),c.lastScreenCoverage>.1){const S=e,k=S.worldForward,M=S.worldPosition,T=X(k).multiplyScalar(g*.7).add(p),L=T.distanceTo(M),B=f[Math.min(f.length-1,Math.max(0,h))]+"88",z=this.context.domHeight>0?screen.height/this.context.domHeight:1,D=e.isPerspectiveCamera?Math.tan(e.fov*Math.PI/180/2):1;G.DrawLabel(T,w,L*.012*z*D,void 0,16777215,B)}}}}}const dR=C("debugplayerview");var So=(o=>(o.Browser="browser",o.Headset="headset",o.Handheld="handheld",o))(So||{});class Aw{constructor(e,t){a(this,"userId"),a(this,"context"),a(this,"viewDevice","browser"),a(this,"removed",!1),a(this,"_object"),this.userId=e,this.context=t}get currentObject(){return this._object}set currentObject(e){this._object=e}get isConnected(){return this.context.connection.userIsInRoom(this.userId)}}class Iw{constructor(e){a(this,"context"),a(this,"playerViews",new Map),this.context=e}setPlayerView(e,t,s){let n=this.playerViews.get(e);n||(n=new Aw(e,this.context),this.playerViews.set(e,n)),n.viewDevice=s,n.currentObject=t,n.removed=!1}getPlayerView(e){if(!!e){if(!this.context.connection.userIsInRoom(e)){this.playerViews.delete(e);return}return this.playerViews.get(e)}}removePlayerView(e,t){const s=this.playerViews.get(e);s?.viewDevice===t&&(dR&&console.log("REMOVE",e),s.removed=!0,this.playerViews.delete(e))}}new Om;const Sc=new Uint8Array(4);Sc[0]=255,Sc[1]=255,Sc[2]=255,Sc[3]=255;const uR=new km(Sc,1,1,md);function vf(o,e=1){const t="alpha"in o,s=e*e,n=new Uint8Array(4*s),r=Math.floor(o.r*255),l=Math.floor(o.g*255),c=Math.floor(o.b*255);for(let d=0;d<s;d++){const u=d*4;n[u+0]=r,n[u+1]=l,n[u+2]=c,t?n[u+3]=Math.floor(o.alpha*255):n[u+3]=255}const h=new km(n,e,e);return h.needsUpdate=!0,h}function pR(o,e,t,s=1,n=3){const r=s*n,l=[o,e,t],c=l.length,h=new Uint8Array(4*c*r),d=new ae;for(let p=0;p<n;p++){const g=Math.floor(p/n*c),f=W.clamp(g+1,0,c-1),y=l[g],b=l[f],v=p/n*c%1;d.lerpColors(y,b,v);const _=Math.floor(d.r*255),w=Math.floor(d.g*255),S=Math.floor(d.b*255);for(let k=0;k<s;k++){const M=(p*s+k)*4;h[M+0]=_,h[M+1]=w,h[M+2]=S,h[M+3]=255}}const u=new km(h,s,n);return u.needsUpdate=!0,u}function du(o,e){const t=o.elements;e||(e=[]),e.length=0;for(let s=0;s<16;s+=4){const n=t[s],r=t[s+1],l=t[s+2],c=t[s+3],h=new ye(n,r,l,c);e.push(h)}return e}const bf=[],Lw=[];function mR(o,e){if(bf.length===0)for(let t=0;t<27;t++)bf.push(0);e||(e=bf);for(let t=0;t<27;t++)Lw[t]=e[t];e=Lw,o.unity_SHAr={value:new ye(e[9],e[3],e[6],e[0])},o.unity_SHBr={value:new ye(e[12],e[15],e[18],e[21])},o.unity_SHAg={value:new ye(e[10],e[4],e[7],e[1])},o.unity_SHBg={value:new ye(e[13],e[16],e[19],e[22])},o.unity_SHAb={value:new ye(e[11],e[5],e[8],e[2])},o.unity_SHBb={value:new ye(e[14],e[17],e[20],e[23])},o.unity_SHC={value:new ye(e[24],e[25],e[26],1)}}class gR{constructor(e,t,s){a(this,"vertexShader"),a(this,"fragmentShader"),a(this,"technique"),this.vertexShader=e,this.fragmentShader=t,this.technique=s}}async function fR(o,e){if(!o)return console.error("Can not find technique: no shader data"),null;const t=o.programs[e],s=t.vertexShader,n=t.fragmentShader;if(s!==void 0&&n!==void 0){const r=o.shaders[s],l=o.shaders[n];if(r.uri&&l.uri||r.code&&l.code){if(!r.code&&r.uri&&await jw(r),!l.code&&l.uri&&await jw(l),!r.code||!l.code)return null;const c=o.techniques[e];return new gR(r.code,l.code,c)}}return console.error("Shader technique not found",e),null}async function jw(o){const e=o.uri;if(e)if(e.endsWith(".glsl")){const t=await new Om().loadAsync(e);o.code=t.toString()}else o.code=yR(o.uri)}function yR(o){return decodeURIComponent(Array.prototype.map.call(atob(o),function(e){return"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)}).join(""))}const Cs=C("debugenvlight");var Ha=(o=>(o[o.Skybox=0]="Skybox",o[o.Trilight=1]="Trilight",o[o.Flat=3]="Flat",o[o.Custom=4]="Custom",o))(Ha||{}),uu=(o=>(o[o.Skybox=0]="Skybox",o[o.Custom=1]="Custom",o))(uu||{});class Dw{constructor(e){a(this,"context"),a(this,"_currentLightSettingsId"),a(this,"_sceneLightSettings"),a(this,"_timevec4",new ye),a(this,"__currentReflectionId",null),a(this,"_lighting",{}),this.context=e,this.context.pre_update_callbacks.push(this.preUpdate.bind(this))}preUpdate(){const e=this.context.time;this._timevec4.x=e.time,this._timevec4.y=Math.sin(e.time),this._timevec4.z=Math.cos(e.time),this._timevec4.w=e.deltaTime}get timeVec4(){return this._timevec4}get environmentIntensity(){if(!this._sceneLightSettings||!this._currentLightSettingsId)return 1;const e=this._sceneLightSettings.get(this._currentLightSettingsId);return e?e.ambientIntensity:1}get sceneLightSettings(){var e;return(e=this._sceneLightSettings)==null?void 0:e.values()}enable(e){var t;e instanceof ce&&(e=e.url);const s=(t=this._sceneLightSettings)==null?void 0:t.get(e);return s?(Cs&&console.log("Enable scene light settings",e,s),e!==this._currentLightSettingsId&&this._currentLightSettingsId&&this.disable(this._currentLightSettingsId),this._currentLightSettingsId=e,s.enabled=!0,!0):(Cs&&console.warn("No light settings found for",e),!1)}disable(e){var t;if(e instanceof ce&&(e=e.url),e==null)return!1;const s=(t=this._sceneLightSettings)==null?void 0:t.get(e);return s?(Cs&&console.log("Disable scene light settings",e,s),s.enabled=!1,!0):!1}disableCurrent(){if(this._currentLightSettingsId){const e=this._currentLightSettingsId;return this.disable(this._currentLightSettingsId),e}return null}internalRegisterSceneLightSettings(e){const t=e.sourceId;if(!t){console.error("Missing source id for scene light settings, can not register:",e);return}Cs&&console.log("Register "+e?.sourceId+" lighting",e),this._sceneLightSettings||(this._sceneLightSettings=new Map),this._sceneLightSettings.set(t,e)}internalUnregisterSceneLightSettings(e){const t=e.sourceId;if(!t){console.error("Missing source id for scene light settings, can not unregister:",e);return}Cs&&console.log("Unregister "+e?.sourceId+" lighting",e),this._sceneLightSettings&&this._sceneLightSettings.delete(t)}internalRegisterReflection(e,t){Cs&&console.log("Register reflection",e,t);const s=new Bw(this.context,t,1);this._lighting[e]=s}internalGetReflection(e){return this._lighting[e]}internalEnableReflection(e){var t;this.__currentReflectionId=e;const s=(t=this._sceneLightSettings)==null?void 0:t.get(e);switch(Cs&&console.log("Enable reflection",e,s?Ha[s.ambientMode]:"Unknown ambient mode",s),s?.ambientMode){case 0:case 4:const n=this.internalGetReflection(e);if(n&&n.Source){Cs&&console.log("Setting environment reflection",n);const r=this.context.scene,l=n.Source;l.mapping=kn,r.environment=l;return}else Cs&&console.warn("Could not find reflection for source",e);break}if(s?.environmentReflectionSource===1)switch(s?.ambientMode){case 1:if(s.ambientTrilight){const n=s.ambientTrilight,r=pR(n[0],n[1],n[2],64,64);r.colorSpace=Mn,r.mapping=kn,this.context.scene.environment=r}else console.error("Missing ambient trilight",s.sourceId);return;case 3:if(s.ambientLight){const n=vf(s.ambientLight,64);n.colorSpace=Mn,n.mapping=kn,this.context.scene.environment=n}else console.error("Missing ambientlight",s.sourceId);return;default:return}}internalDisableReflection(e){if(e&&e!==this.__currentReflectionId){Cs&&console.log("Not disabling reflection for",e,"because it is not the current light settings id",this.__currentReflectionId);return}Cs&&console.log("Disable reflection",e);const t=this.context.scene;t.environment=null}}class Bw{constructor(e,t,s=1){a(this,"_source"),this._source=t,t.mapping=kn}get Source(){return this._source}}const Fw=C("timescale");let _f=1;typeof Fw=="number"&&(_f=Fw);class Uw{constructor(){a(this,"_time",0),a(this,"_deltaTime",0),a(this,"_deltaTimeUnscaled",0),a(this,"timeScale",1),a(this,"_frame",0),a(this,"clock",new NC),a(this,"_smoothedFps",0),a(this,"_smoothedDeltaTime",0),a(this,"_fpsSamples",[]),a(this,"_fpsSampleIndex",0),typeof _f=="number"&&(this.timeScale=_f)}get time(){return this._time}set time(e){this._time=e}get deltaTime(){return this._deltaTime}set deltaTime(e){this._deltaTime=e}get deltaTimeUnscaled(){return this._deltaTimeUnscaled}get frame(){return this._frame}set frame(e){this._frame=e}get frameCount(){return this.frame}get realtimeSinceStartup(){return this.clock.elapsedTime}get fps(){return 1/this.deltaTime}get smoothedFps(){return this._smoothedFps}get smoothedDeltaTime(){return 1/this._smoothedFps}update(){this.deltaTime=this.clock.getDelta(),this.deltaTime=Math.min(.1,this.deltaTime),this._deltaTimeUnscaled=this.deltaTime,this.deltaTime<=0&&(this.deltaTime=1e-12),this.deltaTime*=this.timeScale,this.frame+=1,this.time+=this.deltaTime,this._fpsSamples.length<60?this._fpsSamples.push(this.deltaTime):this._fpsSamples[this._fpsSampleIndex++%60]=this.deltaTime;let e=0;for(let t=0;t<this._fpsSamples.length;t++)e+=this._fpsSamples[t];this._smoothedDeltaTime=e/this._fpsSamples.length,this._smoothedFps=1/this._smoothedDeltaTime}}let zw=!1;function Nw(o){zw||(zw=!0,vR(),bR())}Nw();function vR(){const o=`
221
+ float startCompression = 0.8;
222
+ float desaturation = 0.5;
223
+ // Patched tonemapping function
224
+ vec3 NeutralToneMapping( vec3 color ) {
225
+ color *= toneMappingExposure;
226
+
227
+ float d = 1. - startCompression;
228
+ // float peak = dot(color, vec3(0.299, 0.587, 0.114));
229
+ float peak = max(color.r, max(color.g, color.b));
230
+ if (peak < startCompression) return color;
231
+ float newPeak = 1. - d * d / (peak + d - startCompression);
232
+ float invPeak = 1. / peak;
233
+
234
+ float extraBrightness = dot(color * (1. - startCompression * invPeak), vec3(1, 1, 1));
235
+
236
+ color *= newPeak * invPeak;
237
+ float g = 1. - 3. / (desaturation * extraBrightness + 3.);
238
+ return mix(color, vec3(1, 1, 1), g);
239
+ }
240
+ `,e="vec3 NeutralToneMapping( vec3 color ) {",t=`return mix( color, vec3( newPeak ), g );
241
+ }`,s=Gt.tonemapping_pars_fragment.indexOf(e),n=Gt.tonemapping_pars_fragment.indexOf(t,s);if(s>=0&&n>=0){const r=Gt.tonemapping_pars_fragment.substring(s,n+t.length);Gt.tonemapping_pars_fragment=Gt.tonemapping_pars_fragment.replace(r,o)}else F()&&console.error("Couldn't find NeutralToneMapping in ShaderChunk.tonemapping_pars_fragment")}function bR(){const o=`
242
+ // 0: Default, 1: Golden, 2: Punchy
243
+ #define AGX_LOOK 0
244
+
245
+ vec3 userSlope = vec3(1.0);
246
+ vec3 userOffset = vec3(0.0);
247
+ vec3 userPower = vec3(1.0);
248
+ float userSaturation = 1.0;
249
+
250
+ // Mean error^2: 3.6705141e-06
251
+ vec3 _agxDefaultContrastApprox(vec3 x) {
252
+ vec3 x2 = x * x;
253
+ vec3 x4 = x2 * x2;
254
+
255
+ return + 15.5 * x4 * x2
256
+ - 40.14 * x4 * x
257
+ + 31.96 * x4
258
+ - 6.868 * x2 * x
259
+ + 0.4298 * x2
260
+ + 0.1191 * x
261
+ - 0.00232;
262
+ }
263
+
264
+ vec3 _agx(vec3 val) {
265
+ const mat3 agx_mat = mat3(
266
+ 0.842479062253094, 0.0423282422610123, 0.0423756549057051,
267
+ 0.0784335999999992, 0.878468636469772, 0.0784336,
268
+ 0.0792237451477643, 0.0791661274605434, 0.879142973793104);
269
+
270
+ const float min_ev = -12.47393;
271
+ const float max_ev = 4.026069;
272
+
273
+ // val = pow(val, vec3(2.2));
274
+
275
+ // Input transform (inset)
276
+ val = agx_mat * val;
277
+
278
+ // Log2 space encoding
279
+ val = clamp(log2(val), min_ev, max_ev);
280
+ val = (val - min_ev) / (max_ev - min_ev);
281
+
282
+ // Apply sigmoid function approximation
283
+ val = _agxDefaultContrastApprox(val);
284
+
285
+ return val;
286
+ }
287
+
288
+ vec3 _agxEotf(vec3 val) {
289
+ const mat3 agx_mat_inv = mat3(
290
+ 1.19687900512017, -0.0528968517574562, -0.0529716355144438,
291
+ -0.0980208811401368, 1.15190312990417, -0.0980434501171241,
292
+ -0.0990297440797205, -0.0989611768448433, 1.15107367264116);
293
+
294
+ // Inverse input transform (outset)
295
+ val = agx_mat_inv * val;
296
+
297
+ // sRGB IEC 61966-2-1 2.2 Exponent Reference EOTF Display
298
+ // NOTE: We're linearizing the output here. Comment/adjust when
299
+ // *not* using a sRGB render target
300
+ val = pow(val, vec3(2.2));
301
+
302
+ return val;
303
+ }
304
+
305
+ vec3 _agxLook(vec3 val) {
306
+ const vec3 lw = vec3(0.2126, 0.7152, 0.0722);
307
+ float luma = dot(val, lw);
308
+
309
+ // Default
310
+ vec3 offset = vec3(0.0);
311
+ vec3 slope = vec3(1.0);
312
+ vec3 power = vec3(1.0);
313
+ float sat = 1.0;
314
+
315
+ #if AGX_LOOK == 1
316
+ // Golden
317
+ slope = vec3(1.0, 0.9, 0.5);
318
+ power = vec3(0.8);
319
+ sat = 0.8;
320
+ #elif AGX_LOOK == 2
321
+ // Punchy
322
+ slope = vec3(1.0);
323
+ power = vec3(1.35, 1.35, 1.35);
324
+ sat = 1.4;
325
+ #endif
326
+
327
+ // Needle
328
+ slope = vec3(1.05);
329
+ power = vec3(1.10, 1.10, 1.10);
330
+ sat = 1.15;
331
+
332
+ // User
333
+ // slope = userSlope;
334
+ // offset = userOffset;
335
+ // power = userPower;
336
+ // sat = userSaturation;
337
+
338
+ // ASC CDL
339
+ val = pow(val * slope + offset, power);
340
+ return luma + sat * (val - luma);
341
+ }
342
+
343
+
344
+ vec3 AgXToneMapping( vec3 color ) {
345
+ // apply AGX
346
+ color *= toneMappingExposure;
347
+ color = _agx(color);
348
+ color = _agxLook(color); // Optional
349
+ color = _agxEotf(color);
350
+ return color;
351
+ `,e="vec3 AgXToneMapping( vec3 color ) {",t="return color;",s=Gt.tonemapping_pars_fragment.indexOf(e),n=Gt.tonemapping_pars_fragment.indexOf(t,s);if(s>=0&&n>=0){const r=Gt.tonemapping_pars_fragment.substring(s,n+t.length);Gt.tonemapping_pars_fragment=Gt.tonemapping_pars_fragment.replace(r,o)}else F()&&console.error("Couldn't find AgXToneMapping in ShaderChunk.tonemapping_pars_fragment")}function Ww(o){if(typeof o=="string")switch(o=o.toLowerCase(),o){case"none":return yd;case"neutral":return xa;case"aces":return fd;case"agx":return gd;case"khronos_neutral":return xa;default:console.warn("[PostProcessing] Unknown tone mapping mode",o);return}}function kt(o){const e=document.createElement("span");return e.style.maxWidth="48px",e.style.maxHeight="48px",e.style.overflow="hidden",e.classList.add("material-symbols-outlined","notranslate"),e.setAttribute("translate","no"),e.innerText=o,e}function Vw(o){var e;return((e=o.classList)==null?void 0:e.contains("material-symbols-outlined"))||!1}const pu=new Map;async function wf(o){const e="Material Symbols Outlined";if(document.fonts.check(`1em '${e}'`)||(console.log("Font not loaded yet"),await document.fonts.ready),pu.has(o))return pu.get(o);const t=document.createElement("canvas"),s=48;t.width=s,t.height=s;const n=t.getContext("2d");if(n){n.font=`${s}px '${e}'`,n.fillStyle="black",n.fillText(o,0,s);const r=t.toDataURL(),l=new De;return l.name=o+" icon",l.image=new Image,l.image.src=r,l.needsUpdate=!0,pu.set(o,l),l}return pu.set(o,null),null}const Hw=class pv{constructor(){a(this,"_fullscreenButton"),a(this,"_muteButton"),a(this,"_qrButton"),a(this,"_customQRButtonUrl")}static get instance(){return this.getOrCreate()}static getOrCreate(){return this._instance||(this._instance=new pv),this._instance}static create(){return new pv}get fullscreenButton(){return this._fullscreenButton}createFullscreenButton(e){if(this._fullscreenButton)return this._fullscreenButton;if(!document.fullscreenEnabled)return F()&&console.warn("NeedleMenu: Fullscreen button could not be created, device doesn't support the Fullscreen API"),null;const t=document.createElement("button");this._fullscreenButton=t,t.classList.add("fullscreen-button"),t.title="Click to enter fullscreen mode";const s=kt("fullscreen"),n=kt("fullscreen_exit");return t.appendChild(s),t.onclick=()=>{document.fullscreenElement?document.exitFullscreen():"webkitRequestFullscreen"in e.domElement&&typeof e.domElement.webkitRequestFullscreen=="function"?e.domElement.webkitRequestFullscreen():"requestFullscreen"in e.domElement&&e.domElement.requestFullscreen()},document.addEventListener("fullscreenchange",()=>{document.fullscreenElement?(s.remove(),t.appendChild(n),t.title="Click to enter fullscreen mode"):(n.remove(),t.appendChild(s),t.title="Click to exit fullscreen mode")}),globalThis.addEventListener("needle-xrsession-start",()=>{t.style.display="none"}),globalThis.addEventListener("needle-xrsession-end",()=>{t.style.display=""}),t}get muteButton(){return this._muteButton}createMuteButton(e){if(this._muteButton)return this._muteButton;const t=document.createElement("button");this._muteButton=t,t.classList.add("mute-button"),t.title="Click to mute/unmute";const s=kt("volume_off"),n=kt("volume_up");return e.application.muted?t.appendChild(s):t.appendChild(n),t.onclick=()=>{e.application.muted?(s.remove(),t.appendChild(n),e.application.muted=!1):(n.remove(),t.appendChild(s),e.application.muted=!0)},t}get qrButton(){return this._qrButton}set qrButtonUrl(e){try{new URL(e),this._customQRButtonUrl=e}catch{console.warn(`[Needle] QR code button URL is not a valid URL '${e}'`)}}get qrButtonUrl(){return this._customQRButtonUrl||window.location.href}createQRCode(){if(this._qrButton)return this._qrButton;const e=this,t=document.createElement("button");this._qrButton=t,t.innerText="QR Code",t.prepend(kt("qr_code")),t.title="Scan this QR code with your phone to open this page",this.hideElementDuringXRSession(t);const s=document.createElement("div");s.style.cssText=`
352
+ position: fixed;
353
+ display: inline-block;
354
+ padding: 0.5rem;
355
+ background-color: white;
356
+ border-radius: 0.4rem;
357
+ cursor: pointer;
358
+ z-index: 1000;
359
+ box-shadow: 0 0 12px rgba(0, 0, 0, 0.2);
360
+ `;const n=document.createElement("div");n.classList.add("qr-code-container"),s.appendChild(n),t.addEventListener("click",()=>{if(s.parentNode)return l();F()&&window.location.href.includes("://localhost")&&be("To access your website from another device in the same local network you have to use the IP address instead of localhost. The IP address is logged in your development server console when you start the server."),r()});async function r(){await c(),document.body.appendChild(s);const h=n.getBoundingClientRect(),d=t.getBoundingClientRect();s.style.left=d.left+d.width*.5-h.width*.5+"px";const u=d.top<h.height,p="1.3rem";u?s.style.top=`calc(${d.bottom}px + ${s.style.padding} + 0.0rem)`:s.style.top=`calc(${d.top-h.height}px - ${s.style.padding} - ${p})`,s.style.opacity="0",s.style.pointerEvents="all",s.style.transition="opacity 0.2s ease-in-out",setTimeout(()=>{s.style.opacity="1",window.addEventListener("click",l,{once:!0})}),window.addEventListener("resize",l),window.addEventListener("scroll",l),document.fullscreenElement?document.fullscreenElement.appendChild(s):document.body.appendChild(s)}function l(){s.style.pointerEvents="none",s.style.transition="opacity 0.2s",s.style.opacity="0",setTimeout(()=>{var h;return(h=s.parentNode)==null?void 0:h.removeChild(s)},500),window.removeEventListener("click",l),window.removeEventListener("resize",l),window.removeEventListener("scroll",l)}async function c(){const h=await db({text:e.qrButtonUrl,width:200,height:200});n.innerHTML="",n.appendChild(h)}return t.addEventListener("pointerenter",()=>{c()},{once:!0}),t}hideElementDuringXRSession(e){Dd(t=>{e["previous-display"]=e.style.display,e.style.display="none"}),bg(t=>{e["previous-display"]!=null&&(e.style.display=e["previous-display"])})}};a(Hw,"_instance");let Co=Hw;function mu(o,e){const t=e?.element||document.head,s=Array.from(t.querySelectorAll(`link[rel=stylesheet][href*='${o}']`));if(s.length<=0){const n=document.createElement("link");n.href=o,n.rel="stylesheet",t.appendChild(n),s.push(n)}if(e!=null&&e.loadedCallback)for(let n=0;n<s.length;n++)e!=null&&e.loadedCallback&&s[n].addEventListener("load",e.loadedCallback)}function $w(){mu("https://fonts.googleapis.com/css2?family=Roboto+Flex:opsz,wght@8..144,100..1000&display=swap")}const xf="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@24,400,0,0&display=block",gu="needle-logo-element";class Gw extends HTMLElement{constructor(){super(),a(this,"_root"),a(this,"wrapper"),a(this,"logoElement",document.createElement("img")),a(this,"textElement",document.createElement("span")),this._root=this.attachShadow({mode:"closed"});const e=document.createElement("template");e.innerHTML=`<style>
361
+ :host {
362
+ position: relative;
363
+ min-width: fit-content;
364
+ /* height: 100%; can not have height 100% because of align-items: stretch; in the parent */
365
+ display: flex;
366
+ }
367
+
368
+ .wrapper {
369
+ position: relative;
370
+ display: grid;
371
+ grid-template-columns: auto auto;
372
+ padding: .1rem;
373
+ }
374
+ .wrapper:hover {
375
+ cursor: pointer;
376
+ }
377
+ img {
378
+ width: 95px;
379
+ height: 100%;
380
+ align-self: end;
381
+ margin-left: 0.6rem;
382
+ }
383
+ span {
384
+ font-size: 1rem;
385
+ white-space: nowrap;
386
+ }
387
+ </style>
388
+ <div class="wrapper">
389
+ <img class="logo" src=${IO} />
390
+ </div>
391
+ `,this._root.appendChild(e.content.cloneNode(!0)),this.wrapper=this._root.querySelector(".wrapper"),this._root.appendChild(this.wrapper),this.addEventListener("click",()=>{globalThis.open("https://needle.tools","_blank")}),this.wrapper.setAttribute("title","Made with Needle Engine")}static get elementName(){return gu}static create(){return document.createElement(gu)}setLogoVisible(e){this.logoElement.style.display=e?"block":"none"}}customElements.get(gu)||customElements.define(gu,Gw);const Sf=C("debugspatialmenu");class _R{constructor(e,t){a(this,"_context"),a(this,"needleMenu"),a(this,"htmlButtonsMap",new Map),a(this,"enabled",!0),a(this,"userRequestedMenu",!1),a(this,"uiisDirty",!1),a(this,"_showNeedleLogo"),a(this,"_wasInXR",!1),a(this,"preRender",()=>{var r;if(!this.enabled){(r=this.menu)==null||r.removeFromParent();return}Sf&&Y.isDesktop()&&this.updateMenu();const l=this._context.xr;if(!(l!=null&&l.running)){this._wasInXR&&(this._wasInXR=!1,this.onExitXR());return}this._wasInXR||(this._wasInXR=!0,this.onEnterXR()),this.updateMenu()}),a(this,"_menuTarget",new E),a(this,"positionFilter",new eg(90,.5)),a(this,"familyName","Needle Spatial Menu"),a(this,"menu"),a(this,"_poweredByNeedleElement");var s;this._context=e,this._context.pre_render_callbacks.push(this.preRender),this.needleMenu=t;const n=(s=this.needleMenu.shadowRoot)==null?void 0:s.querySelector(".options");n?new MutationObserver(r=>{if(this.enabled&&!(this._context.isInXR==!1&&!Sf))for(const l of r)l.type==="childList"&&(l.addedNodes.forEach(c=>{this.createButtonFromHTMLNode(c)}),l.removedNodes.forEach(c=>{const h=c,d=this.htmlButtonsMap.get(h);d&&(this.htmlButtonsMap.delete(h),d.remove(),Re.update())}))}).observe(n,{childList:!0}):console.error("Could not find options container in needle menu")}setEnabled(e){var t;this.enabled=e,e||(t=this.menu)==null||t.removeFromParent()}setDisplay(e){return this.enabled?(this.userRequestedMenu=e,!0):!1}onDestroy(){const e=this._context.pre_render_callbacks.indexOf(this.preRender);e>-1&&this._context.pre_render_callbacks.splice(e,1)}markDirty(){this.uiisDirty=!0}showNeedleLogo(e){this._showNeedleLogo=e}onEnterXR(){var e;const t=(e=this.needleMenu.shadowRoot)==null?void 0:e.querySelector(".options");t&&t.childNodes.forEach(s=>{this.createButtonFromHTMLNode(s)})}onExitXR(){var e;(e=this.menu)==null||e.removeFromParent()}createButtonFromHTMLNode(e){const t=this.getMenu(),s=this.htmlButtonsMap.get(e);if(s){s.add();return}if(e instanceof HTMLButtonElement){const n=this.createButton(t,e);this.htmlButtonsMap.set(e,n),n.add()}else e instanceof HTMLSlotElement&&e.assignedNodes().forEach(n=>{this.createButtonFromHTMLNode(n)})}updateMenu(){var e,t;const s=this.getMenu();this.handleNeedleWatermark(),this._context.scene.add(s);const n=this._context.mainCamera,r=this._context.xr,l=r?.rigScale||1;if(n){const c=n.worldPosition,h=n.worldForward.multiplyScalar(-1),d=h.y>.6,u=h.y>.4,p=(s.visible?u:d)||this.userRequestedMenu,g=!s.visible&&p;s.visible=p||Y.isDesktop()&&Sf,h.multiplyScalar(3*l),c.add(h),g&&(s.position.copy(this._menuTarget.position),s.position.y+=.25,this._menuTarget.position.copy(s.position),this.positionFilter.reset(s.position),s.quaternion.copy(this._menuTarget.quaternion),this.markDirty());const f=this._menuTarget.position.distanceTo(c);(g||f>1.5*l)&&(this.ensureRenderOnTop(this.menu),this._menuTarget.position.copy(c),this._context.scene.add(this._menuTarget),Ql(this._menuTarget,this._context.mainCamera,!0,!0),this._menuTarget.removeFromParent()),this.positionFilter.filter(this._menuTarget.position,s.position,this._context.time.time),(e=this.menu)==null||e.quaternion.slerp(this._menuTarget.quaternion,this._context.time.deltaTime*5),(t=this.menu)==null||t.scale.setScalar(l)}this.uiisDirty&&(this.uiisDirty=!1,Re.update())}ensureRenderOnTop(e,t=0){e instanceof q&&(e.material.depthTest=!1,e.material.depthWrite=!1),e.renderOrder=1e3+t*2;for(const s of e.children)this.ensureRenderOnTop(s,t+1)}get isVisible(){var e;return(e=this.menu)==null?void 0:e.visible}getMenu(){if(this.menu)return this.menu;this.ensureFont(),this.menu=new Re.Block({boxSizing:"border-box",fontFamily:this.familyName,height:"auto",fontSize:.1,color:0,lineHeight:1,backgroundColor:16777215,backgroundOpacity:.55,borderRadius:1,whiteSpace:"pre-wrap",flexDirection:"row",alignItems:"center",padding:new ye(0,.05,0,.05),borderColor:0,borderOpacity:.05,borderWidth:.005});const e=R.get("ObjectRaycaster");return e&&Pr(this.menu,new e),this.menu}handleNeedleWatermark(){var e;if(!this._poweredByNeedleElement){this._poweredByNeedleElement=new Re.Block({width:"auto",height:"auto",fontSize:.05,whiteSpace:"pre-wrap",flexDirection:"row",flexWrap:"wrap",justifyContent:"center",margin:.02,borderRadius:.02,padding:.02,backgroundColor:16777215,backgroundOpacity:1}),this._poweredByNeedleElement["needle:use_eventsystem"]=!0;const t=new qw(this._context,()=>globalThis.open("https://needle.tools","_self"));Pr(this._poweredByNeedleElement,t);const s=new Re.Text({textContent:"Powered by",width:"auto",height:"auto"}),n=new Re.Text({textContent:"needle",width:"auto",height:"auto",fontSize:.07,margin:new ye(0,0,0,.02)});this._poweredByNeedleElement.add(s),this._poweredByNeedleElement.add(n),(e=this.menu)==null||e.add(this._poweredByNeedleElement),this.markDirty(),new _a().load("./include/needle/poweredbyneedle.webp",r=>{var l;t.allowModifyUI=!1,s.removeFromParent(),n.removeFromParent();const c=r.image.width/r.image.height;(l=this._poweredByNeedleElement)==null||l.set({backgroundImage:r,backgroundOpacity:1,width:.1*c,height:.1}),this.markDirty()})}if(this.menu){const t=this.menu.children.indexOf(this._poweredByNeedleElement);if(!this._showNeedleLogo&&Zs())t>=0&&(this._poweredByNeedleElement.removeFromParent(),this.markDirty());else{this._poweredByNeedleElement.visible=!0,this.menu.add(this._poweredByNeedleElement);const s=this.menu.children.indexOf(this._poweredByNeedleElement);t!==s&&this.markDirty()}}}ensureFont(){let e=Re.FontLibrary.getFontFamily(this.familyName);if(!e){e=Re.FontLibrary.addFontFamily(this.familyName);const t=e.addVariant("normal","normal","./include/needle/arial-msdf.json","./include/needle/arial.png");t?.addEventListener("ready",()=>{this.markDirty()})}}createButton(e,t){const s=new Re.Block({width:"auto",height:"auto",whiteSpace:"pre-wrap",flexDirection:"row",flexWrap:"wrap",justifyContent:"center",backgroundColor:16777215,backgroundOpacity:0,padding:.02,margin:.01,borderRadius:.02,cursor:"pointer",fontSize:.05}),n=new Re.Text({textContent:"",width:"auto",justifyContent:"center",alignItems:"center",backgroundOpacity:0,backgroundColor:16777215,fontFamily:this.familyName,color:0,borderRadius:.02,padding:.01});s.add(n),s["needle:use_eventsystem"]=!0;const r=new qw(this._context,()=>t.click());return Pr(s,r),new wR(this,e,t,s,n)}}class wR{constructor(e,t,s,n,r){a(this,"menu"),a(this,"root"),a(this,"htmlbutton"),a(this,"spatialContainer"),a(this,"spatialText"),a(this,"spatialIcon"),a(this,"_lastText",""),a(this,"_lastTexture"),this.menu=e,this.root=t,this.htmlbutton=s,this.spatialContainer=n,this.spatialText=r,new MutationObserver(l=>{for(const c of l)c.type==="attributes"?c.attributeName==="style"&&this.updateVisible():c.type==="childList"&&this.updateText()}).observe(s,{attributes:!0,childList:!0}),this.updateText()}add(){this.spatialContainer.parent!=this.root&&(this.root.add(this.spatialContainer),this.menu.markDirty(),this.updateVisible(),this.updateText())}remove(){this.spatialContainer.parent&&(this.spatialContainer.removeFromParent(),this.menu.markDirty())}updateVisible(){const e=this.spatialContainer.visible;this.spatialContainer.visible=this.htmlbutton.style.display!=="none",e!==this.spatialContainer.visible&&this.menu.markDirty()}updateText(){let e="",t="";this.htmlbutton.childNodes.forEach(s=>{s.nodeType===Node.TEXT_NODE?e+=s.textContent:s instanceof HTMLElement&&Vw(s)&&s.textContent&&(t=s.textContent)}),this._lastText!==e&&(this._lastText=e,this.spatialText.name=e,this.spatialText.set({textContent:e}),this.menu.markDirty()),e.length<=0?this.spatialText.parent&&(this.spatialText.removeFromParent(),this.menu.markDirty()):this.spatialText.parent||(this.spatialContainer.add(this.spatialText),this.menu.markDirty()),t&&this.createIcon(t)}async createIcon(e){var t;if(!this.spatialIcon){const n=await wf(e);if(n&&!this.spatialIcon){const r=new Re.Block({width:.08,height:.08,backgroundColor:16777215,backgroundImage:n,backgroundOpacity:1,margin:new ye(0,.005,0,0)});this.spatialIcon=r,this.spatialContainer.add(r),this.menu.markDirty()}}if(e!=this._lastTexture){this._lastTexture=e;const n=await wf(e);n&&((t=this.spatialIcon)==null||t.set({backgroundImage:n}),this.menu.markDirty())}const s=this.spatialContainer.children.indexOf(this.spatialIcon);s>0&&(this.spatialContainer.children.splice(s,1),this.spatialContainer.children.unshift(this.spatialIcon),this.menu.markDirty())}}class qw{constructor(e,t){a(this,"isComponent",!0),a(this,"enabled",!0),a(this,"gameObject"),a(this,"allowModifyUI",!0),a(this,"context"),a(this,"onclick"),this.context=e,this.onclick=t}get activeAndEnabled(){return!0}__internalAwake(){}__internalEnable(){}__internalDisable(){}__internalStart(){}onEnable(){}onDisable(){}get element(){return this.gameObject}onPointerEnter(){this.context.input.setCursor("pointer"),this.allowModifyUI&&(this.element.set({backgroundOpacity:1}),Re.update())}onPointerExit(){this.context.input.unsetCursor("pointer"),this.allowModifyUI&&(this.element.set({backgroundOpacity:0}),Re.update())}onPointerDown(e){e.use()}onPointerUp(e){e.use()}onPointerClick(e){e.use(),this.onclick()}}const Er="needle-menu",Cc=C("debugmenu"),Xw=C("debugnoncommercial");let xR=class{constructor(o){a(this,"_context"),a(this,"_menu"),a(this,"_spatialMenu"),a(this,"onPostMessage",e=>{if(e.origin===globalThis.location.origin&&typeof e.data=="object"){const t=e.data,s=t.type;if(s==="needle:menu"){const n=t.button;if(n){if(!n.label)return console.error("NeedleMenu: buttoninfo.label is required");if(!n.onclick)return console.error("NeedleMenu: buttoninfo.onclick is required");const r=document.createElement("button");if(r.textContent=n.label,n.icon){const l=kt(n.icon);r.prepend(l)}n.priority&&r.setAttribute("priority",n.priority.toString()),r.onclick=()=>{if(n.onclick){const l=n.onclick.startsWith("http")||n.onclick.startsWith("www."),c=n.target||"_blank";l?globalThis.open(n.onclick,c):console.error("NeedleMenu: onclick is not a valid link",n.onclick)}},this._menu.appendChild(r)}else Cc&&console.error("NeedleMenu: unknown postMessage event",t)}else Cc&&console.warn("NeedleMenu: unknown postMessage type",s,t)}}),a(this,"onStartXR",e=>{e.session.isScreenBasedAR&&(this._menu.previousParent=this._menu.parentNode,this._context.arOverlayElement.appendChild(this._menu),e.session.session.addEventListener("end",this.onExitXR),this._menu.closeFoldout())}),a(this,"onExitXR",()=>{this._menu.previousParent&&(this._menu.previousParent.appendChild(this._menu),delete this._menu.previousParent)}),a(this,"_muteButton"),a(this,"_fullscreenButton"),this._menu=Qw.getOrCreate(o.domElement,o),this._context=o,this._spatialMenu=new _R(o,this._menu),window.addEventListener("message",this.onPostMessage),Dd(this.onStartXR)}onDestroy(){window.removeEventListener("message",this.onPostMessage),this._menu.remove(),this._spatialMenu.onDestroy()}setPosition(o){this._menu.setPosition(o)}setVisible(o){this._menu.setVisible(o)}showNeedleLogo(o){var e;this._menu.showNeedleLogo(o),(e=this._spatialMenu)==null||e.showNeedleLogo(o)}get logoIsVisible(){return this._menu.logoIsVisible}showSpatialMenu(o){this._spatialMenu.setEnabled(o)}setSpatialMenuVisible(o){this._spatialMenu.setDisplay(o)}get spatialMenuIsVisible(){return this._spatialMenu.isVisible}showQRCodeButton(o){if(o==="desktop-only"&&(o=!Y.isMobileDevice()),o){const e=Co.getOrCreate().createQRCode();return e.style.display="",this._menu.appendChild(e),e}else{const e=Co.getOrCreate().qrButton;return e&&(e.style.display="none"),e??null}}showAudioPlaybackOption(o){var e;if(!o){(e=this._muteButton)==null||e.remove();return}this._muteButton=Co.getOrCreate().createMuteButton(this._context),this._muteButton.setAttribute("priority","100"),this._menu.appendChild(this._muteButton)}showFullscreenOption(o){var e;if(!o){(e=this._fullscreenButton)==null||e.remove();return}this._fullscreenButton=Co.getOrCreate().createFullscreenButton(this._context),this._fullscreenButton&&(this._fullscreenButton.setAttribute("priority","150"),this._menu.appendChild(this._fullscreenButton))}appendChild(o){return this._menu.appendChild(o)}};var fu;const SR=class pC extends HTMLElement{constructor(){var e,t,s,n,r,l;super(),a(this,"_domElement",null),a(this,"_context",null),a(this,"_sizeChangeInterval"),Us(this,fu,b=>{if(!b.defaultPrevented&&b.target==this._domElement&&b instanceof PointerEvent&&b.button===0&&this.root.classList.contains("open")){const v=this.foldout.getBoundingClientRect(),_=b;_.clientX>v.left&&_.clientX<v.right&&_.clientY>v.top&&_.clientY<v.bottom||this.root.classList.toggle("open",!1)}}),a(this,"_userRequestedLogoVisible"),a(this,"_userRequestedMenuVisible"),a(this,"root"),a(this,"wrapper"),a(this,"options"),a(this,"logoContainer"),a(this,"compactMenuButton"),a(this,"foldout"),a(this,"_isHandlingChange",!1),a(this,"_didSort",new Map),a(this,"_lastAvailableWidthChange",0),a(this,"_timeoutHandle",0),a(this,"handleSizeChange",(b,v)=>{if(!this._domElement)return;const _=this._domElement.clientWidth;if(_<100){clearTimeout(this._timeoutHandle),this.root.classList.add("compact"),this.foldout.classList.add("floating-panel-style");return}const w=_-40;if(!v&&Math.abs(w-this._lastAvailableWidthChange)<1)return;this._lastAvailableWidthChange=w,clearTimeout(this._timeoutHandle),this._timeoutHandle=setTimeout(()=>{const M=k();M<0?(this.root.classList.add("compact"),this.foldout.classList.add("floating-panel-style")):M>0&&(this.root.classList.remove("compact"),this.foldout.classList.remove("floating-panel-style"),k()<0&&(this.root.classList.add("compact"),this.foldout.classList.add("floating-panel-style")))},5);const S=()=>this.options.clientWidth+this.logoContainer.clientWidth,k=()=>w-S()});const c=document.createElement("template");c.innerHTML=`<style>
392
+
393
+ #root {
394
+ position: absolute;
395
+ width: auto;
396
+ max-width: 95%;
397
+ left: 50%;
398
+ transform: translateX(-50%);
399
+ top: min(20px, 10vh);
400
+ padding: 0.3rem;
401
+ display: flex;
402
+ visibility: visible;
403
+ flex-direction: row-reverse; /* if we overflow this should be right aligned so the logo is always visible */
404
+ pointer-events: all;
405
+ z-index: 1000;
406
+ }
407
+
408
+ /** hide the menu if it's empty **/
409
+ #root.has-no-options.logo-hidden {
410
+ display: none;
411
+ }
412
+
413
+ /** using a div here because then we can change the class for placement **/
414
+ #root.bottom {
415
+ top: auto;
416
+ bottom: min(30px, 10vh);
417
+ }
418
+ #root.top {
419
+ top: calc(.7rem + env(safe-area-inset-top));
420
+ }
421
+
422
+ .wrapper {
423
+ position: relative;
424
+ display: flex;
425
+ flex-direction: row;
426
+ justify-content: center;
427
+ align-items: stretch;
428
+ gap: 0px;
429
+ padding: 0 0rem;
430
+ }
431
+
432
+ .wrapper > *, .options > button, .options > select, ::slotted(*) {
433
+ position: relative;
434
+ border: none;
435
+ border-radius: 0;
436
+ outline: 1px solid rgba(0,0,0,0);
437
+ display: flex;
438
+ justify-content: center;
439
+ align-items: center;
440
+ max-height: 2.3rem;
441
+ max-width: 100%;
442
+
443
+ /** basic font settings for all entries **/
444
+ font-size: 1rem;
445
+ font-family: 'Roboto Flex', sans-serif;
446
+ font-optical-sizing: auto;
447
+ font-weight: 500;
448
+ font-weight: 200;
449
+ font-variation-settings: "wdth" 100;
450
+ color: rgb(20,20,20);
451
+ }
452
+
453
+ .options > select[multiple]:hover {
454
+ max-height: 300px;
455
+ }
456
+
457
+ .floating-panel-style {
458
+ background: rgba(255, 255, 255, .4);
459
+ outline: rgb(0 0 0 / 5%) 1px solid;
460
+ border: 1px solid rgba(255, 255, 255, .1);
461
+ box-shadow: 0px 7px 0.5rem 0px rgb(0 0 0 / 6%), inset 0px 0px 1.3rem rgba(0,0,0,.05);
462
+ border-radius: 1.5rem;
463
+ /**
464
+ * to make nested background filter work
465
+ * https://stackoverflow.com/questions/60997948/backdrop-filter-not-working-for-nested-elements-in-chrome
466
+ **/
467
+ &::before {
468
+ content: '';
469
+ position: absolute;
470
+ width: 100%;
471
+ height: 100%;
472
+ top: 0;
473
+ left: 0;
474
+ z-index: -1;
475
+ border-radius: 1.5rem;
476
+ -webkit-backdrop-filter: blur(8px);
477
+ backdrop-filter: blur(8px);
478
+ }
479
+ }
480
+
481
+ a {
482
+ color: inherit;
483
+ text-decoration: none;
484
+ }
485
+
486
+ .options {
487
+ display: flex;
488
+ flex-direction: row;
489
+ align-items: center;
490
+ }
491
+
492
+ .options > *, ::slotted(*) {
493
+ max-height: 2.25rem;
494
+ padding: .4rem .5rem;
495
+ }
496
+
497
+ :host .options > *, ::slotted(*) {
498
+ background: transparent;
499
+ border: none;
500
+ white-space: nowrap;
501
+ transition: all 0.1s linear .02s;
502
+ border-radius: 1.5rem;
503
+ user-select: none;
504
+ }
505
+ :host .options > *:hover, ::slotted(*:hover) {
506
+ cursor: pointer;
507
+ color: black;
508
+ background: rgba(245, 245, 245, .8);
509
+ box-shadow: inset 0 0 1rem rgba(0,0,30,.2);
510
+ outline: rgba(0,0,0,.1) 1px solid;
511
+ }
512
+ :host .options > *:active, ::slotted(*:active) {
513
+ background: rgba(255, 255, 255, .8);
514
+ box-shadow: inset 0px 1px 1px rgba(255,255,255,.5), inset 0 0 2rem rgba(0,0,30,.2), inset 0px 2px 4px rgba(0,0,20,.5);
515
+ transition: all 0.05s linear;
516
+ }
517
+ :host .options > *:focus, ::slotted(*:focus) {
518
+ outline: rgba(255,255,255,.5) 1px solid;
519
+ }
520
+ :host .options > *:focus-visible, ::slotted(*:focus-visible) {
521
+ outline: rgba(0,0,0,.5) 1px solid;
522
+ }
523
+
524
+ :host .options > *:disabled, ::slotted(*:disabled) {
525
+ background: rgba(0,0,0,.05);
526
+ color: rgba(60,60,60,.7);
527
+ pointer-events: none;
528
+ }
529
+
530
+ button, ::slotted(button) {
531
+ gap: 0.3rem;
532
+ }
533
+
534
+ /** XR button animation **/
535
+ :host button.this-mode-is-requested {
536
+ background: repeating-linear-gradient(to right, #fff 0%, #fff 40%, #aaffff 55%, #fff 80%);
537
+ background-size: 200% auto;
538
+ background-position: 0 100%;
539
+ animation: AnimationName .7s ease infinite forwards;
540
+ }
541
+ :host button.other-mode-is-requested {
542
+ opacity: .5;
543
+ }
544
+
545
+ @keyframes AnimationName {
546
+ 0% { background-position: 0% 0 }
547
+ 100% { background-position: -200% 0 }
548
+ }
549
+
550
+
551
+
552
+
553
+ .logo {
554
+ cursor: pointer;
555
+ padding-left: 0.6rem;
556
+ padding-bottom: .02rem;
557
+ margin-right: 0.5rem;
558
+ }
559
+ .logo-hidden {
560
+ .logo {
561
+ display: none;
562
+ }
563
+ }
564
+ :host .has-options .logo {
565
+ border-left: 1px solid rgba(40,40,40,.4);
566
+ margin-left: 0.3rem;
567
+ margin-right: 0.5rem;
568
+ }
569
+
570
+ .logo > span {
571
+ white-space: nowrap;
572
+ }
573
+
574
+
575
+
576
+ /** COMPACT */
577
+
578
+ /** Hide the menu button normally **/
579
+ .compact-menu-button { display: none; }
580
+ /** And show it when we're in compact mode **/
581
+ .compact .compact-menu-button {
582
+ position: relative;
583
+ display: block;
584
+ background: none;
585
+ border: none;
586
+ border-radius: 2rem;
587
+
588
+ margin: 0;
589
+ padding: 0 .3rem;
590
+ padding-top: .2rem;
591
+
592
+ z-index: 100;
593
+
594
+ color: #000;
595
+
596
+ &:hover {
597
+ background: rgba(255,255,255,.2);
598
+ cursor: pointer;
599
+ }
600
+ &:focus {
601
+ outline: 1px solid rgba(255,255,255,.5);
602
+ }
603
+ &:focus-visible {
604
+ outline: 1px solid rgba(0,0,0,.5);
605
+ }
606
+ & .expanded-click-area {
607
+ position: absolute;
608
+ left: 0;
609
+ right: 0;
610
+ top: 10%;
611
+ bottom: 10%;
612
+ transform: scale(1.8);
613
+ }
614
+ }
615
+ .has-no-options .compact-menu-button {
616
+ display: none;
617
+ }
618
+ .open .compact-menu-button {
619
+ background: rgba(255,255,255,.2);
620
+ }
621
+ .logo-visible .compact-menu-button {
622
+ margin-left: .2rem;
623
+ }
624
+
625
+ /** Open and hide menu **/
626
+ .compact .foldout {
627
+ display: none;
628
+ }
629
+ .open .options, .open .foldout {
630
+ display: flex;
631
+ justify-content: center;
632
+ }
633
+ .compact .wrapper {
634
+ padding: 0;
635
+ }
636
+ .compact .wrapper, .compact .options {
637
+ height: auto;
638
+ max-height: initial;
639
+ flex-direction: row;
640
+ gap: .12rem;
641
+ }
642
+ .compact .options {
643
+ flex-wrap: wrap;
644
+ gap: .3rem;
645
+ }
646
+ .compact .top .options {
647
+ height: auto;
648
+ flex-direction: row;
649
+ }
650
+ .compact .bottom .wrapper {
651
+ height: auto;
652
+ flex-direction: column;
653
+ }
654
+
655
+ .compact .foldout {
656
+ max-height: min(100ch, calc(100vh - 100px));
657
+ overflow: auto;
658
+ overflow-x: hidden;
659
+ align-items: center;
660
+
661
+ position: fixed;
662
+ bottom: calc(100% + 5px);
663
+ z-index: 100;
664
+ width: auto;
665
+ left: .2rem;
666
+ right: .2rem;
667
+ padding: .2rem;
668
+
669
+ }
670
+ .compact.logo-hidden .foldout {
671
+ /** for when there's no logo we want to center the foldout **/
672
+ min-width: 24ch;
673
+ margin-left: 50%;
674
+ transform: translateX(calc(-50% - .2rem));
675
+ }
676
+
677
+ .compact.top .foldout {
678
+ top: calc(100% + 5px);
679
+ bottom: auto;
680
+ }
681
+
682
+ ::-webkit-scrollbar {
683
+ max-width: 7px;
684
+ background: rgba(100,100,100,.2);
685
+ border-radius: .2rem;
686
+ }
687
+ ::-webkit-scrollbar-thumb {
688
+ background: rgba(255, 255, 255, .3);
689
+ border-radius: .2rem;
690
+ }
691
+ ::-webkit-scrollbar-thumb:hover {
692
+ background: rgb(150,150,150);
693
+ }
694
+
695
+ .compact .options > *, .compact .options > ::slotted(*) {
696
+ font-size: 1.2rem;
697
+ padding: .6rem .5rem;
698
+ width: 100%;
699
+ }
700
+ .compact.has-options .logo {
701
+ border: none;
702
+ padding-left: 0;
703
+ margin-left: 1rem;
704
+ margin-bottom: .02rem;
705
+ }
706
+ .compact .options {
707
+ /** e.g. if we have a very wide menu item like a select with long option names we don't want to overflow **/
708
+ max-width: 100%;
709
+
710
+ & > button, & > select {
711
+ display: flex;
712
+ flex-basis: 100%;
713
+ min-height: 3rem;
714
+ }
715
+ & > button.row2 {
716
+ //border: 1px solid red !important;
717
+ display: flex;
718
+ flex: 1;
719
+ flex-basis: 30%;
720
+ }
721
+ }
722
+
723
+ /** If there's really not enough space then just hide all options **/
724
+ @media (max-width: 100px) or (max-height: 100px){
725
+ .foldout {
726
+ display: none !important;
727
+ }
728
+ .compact-menu-button {
729
+ display: none !important;
730
+ }
731
+ }
732
+
733
+ /* dark mode */
734
+ /*
735
+ @media (prefers-color-scheme: dark) {
736
+ :host {
737
+ background: rgba(0,0,0, .6);
738
+ }
739
+ :host button {
740
+ color: rgba(200,200,200);
741
+ }
742
+ :host button:hover {
743
+ background: rgba(100,100,100, .8);
744
+ }
745
+ }
746
+ */
747
+
748
+ </style>
749
+
750
+ <div id="root" class="logo-hidden floating-panel-style bottom">
751
+ <div class="wrapper">
752
+ <div class="foldout">
753
+ <div class="options" part="options">
754
+ <slot></slot>
755
+ </div>
756
+ <div class="options" part="options">
757
+ <slot name="end"></slot>
758
+ </div>
759
+ </div>
760
+ <div style="user-select:none" class="logo">
761
+ <span class="madewith notranslate">powered by</span>
762
+ </div>
763
+ </div>
764
+ <button class="compact-menu-button">
765
+ <div class="expanded-click-area"></div>
766
+ </button>
767
+ </div>
768
+ `;const h=this.attachShadow({mode:"open"});$w(),mu(xf,{loadedCallback:()=>{this.handleSizeChange()}}),mu(xf,{element:h});const d=c.content.cloneNode(!0);h?.appendChild(d),this.root=h.querySelector("#root"),this.wrapper=(e=this.root)==null?void 0:e.querySelector(".wrapper"),this.options=(t=this.root)==null?void 0:t.querySelector(".options"),this.logoContainer=(s=this.root)==null?void 0:s.querySelector(".logo"),this.compactMenuButton=(n=this.root)==null?void 0:n.querySelector(".compact-menu-button"),this.compactMenuButton.append(kt("more_vert")),this.foldout=(r=this.root)==null?void 0:r.querySelector(".foldout"),(l=this.root)==null||l.appendChild(this.wrapper),this.wrapper.classList.add("wrapper");const u=Gw.create();u.style.minHeight="1rem",this.logoContainer.append(u),this.logoContainer.addEventListener("click",()=>{globalThis.open("https://needle.tools","_blank")});try{window.requestAnimationFrame(()=>TR(b=>{if(b==!0&&Js()&&!Xw){let v=this._userRequestedLogoVisible;v===void 0&&(v=!1),this.___onSetLogoVisible(v)}else this.___onSetLogoVisible(!0)}))}catch(b){console.error("[Needle Menu] License check failed.",b)}this.compactMenuButton.addEventListener("click",b=>{b.preventDefault(),this.root.classList.toggle("open")});let p=this._context;setTimeout(()=>p=this._context);let g=0;const f=(b,v)=>{var _,w,S;Cc&&console.log("Set menu visible",v),p!=null&&p.isInAR&&p.arOverlayElement?b!=p.arOverlayElement&&p.arOverlayElement.appendChild(this):this.parentNode!=((_=this._domElement)==null?void 0:_.shadowRoot)&&((S=(w=this._domElement)==null?void 0:w.shadowRoot)==null||S.appendChild(this)),this.style.display=v?"flex":"none",this.style.visibility="visible",this.style.opacity="1"};let y=!1;new MutationObserver(b=>{var v;if(!y)try{y=!0,this.onChangeDetected(b);const _=this==null?void 0:this.parentNode;if((this.style.display!="flex"||this.style.visibility!="visible"||this.style.opacity!="1"||_!=((v=this._domElement)==null?void 0:v.shadowRoot))&&!Js()){const w=g++;qt()&&this._userRequestedMenuVisible===!1?(w===0&&f(_,this._userRequestedMenuVisible),w===1&&console.warn("Needle Menu Warning: You need a PRO license to hide the Needle Engine menu \u2192 The menu will be visible in your deployed website if you don't have a PRO license. See https://needle.tools/pricing for details.")):w===0?f(_,!0):setTimeout(()=>f(_,!0),5)}}finally{y=!1}}).observe(this.root,{childList:!0,subtree:!0,attributes:!0}),Cc&&this.___insertDebugOptions()}static create(){return document.createElement(Er,{is:Er})}static getOrCreate(e,t){let s=e.querySelector(Er);return!s&&e.shadowRoot&&(s=e.shadowRoot.querySelector(Er)),s||(s=window.document.body.querySelector(Er)),s||(s=pC.create(),e.shadowRoot?e.shadowRoot.appendChild(s):e.appendChild(s)),s._domElement=e,s._context=t,s}connectedCallback(){window.addEventListener("resize",this.handleSizeChange),this.handleMenuVisible(),this._sizeChangeInterval=setInterval(()=>this.handleSizeChange(void 0,!0),5e3),setTimeout(()=>{var e,t;(e=this._domElement)==null||e.addEventListener("resize",this.handleSizeChange),(t=this._domElement)==null||t.addEventListener("click",fe(this,fu))},1)}disconnectedCallback(){var e,t;window.removeEventListener("resize",this.handleSizeChange),clearInterval(this._sizeChangeInterval),(e=this._domElement)==null||e.removeEventListener("resize",this.handleSizeChange),(t=this._context)==null||t.domElement.removeEventListener("click",fe(this,fu))}showNeedleLogo(e){this._userRequestedLogoVisible=e,!(!e&&(!Js()||Xw)&&(console.warn("[Needle Engine] You need a PRO license to hide the Needle Engine logo in production."),!qt()))&&this.___onSetLogoVisible(e)}get logoIsVisible(){return!this.root.classList.contains("logo-hidden")}___onSetLogoVisible(e){this.logoContainer.style.display="",this.logoContainer.style.opacity="1",this.logoContainer.style.visibility="visible",e?(this.root.classList.remove("logo-hidden"),this.root.classList.add("logo-visible")):(this.root.classList.remove("logo-visible"),this.root.classList.add("logo-hidden"))}setPosition(e){if(e!=="top"&&e!=="bottom")return console.error("NeedleMenu.setPosition: invalid position",e);this.root.classList.remove("top","bottom"),this.root.classList.add(e)}setVisible(e){this._userRequestedMenuVisible=e,this.style.display=e?"flex":"none"}closeFoldout(){this.root.classList.remove("open")}append(...e){for(const t of e)if(typeof t=="string"){const s=document.createTextNode(t);this.options.appendChild(s)}else this.options.appendChild(t)}appendChild(e){var t;if(!(e instanceof Node)){const s=document.createElement("button");if(s.textContent=e.label,s.onclick=e.onClick,s.setAttribute("priority",((t=e.priority)==null?void 0:t.toString())??"0"),e.title&&(s.title=e.title),e.icon){const n=kt(e.icon);e.iconSide==="right"?s.appendChild(n):s.prepend(n)}e.class&&s.classList.add(e.class),e=s}return this.options.appendChild(e)}prepend(...e){for(const t of e)if(typeof t=="string"){const s=document.createTextNode(t);this.options.prepend(s)}else this.options.prepend(t)}onChangeDetected(e){if(!this._isHandlingChange){this._isHandlingChange=!0;try{this.handleMenuVisible();for(const t of e)t.target==this.options&&this.onOptionsChildrenChanged(t)}finally{this._isHandlingChange=!1}}}onOptionsChildrenChanged(e){if(this.root.classList.toggle("has-options",this.hasAnyVisibleOptions),this.root.classList.toggle("has-no-options",!this.hasAnyVisibleOptions),this.handleSizeChange(void 0,!0),e.type==="childList"&&e.addedNodes.length>0){const t=Array.from(this.options.children);t.sort((n,r)=>{const l=parseInt(n.getAttribute("priority")||"0"),c=parseInt(r.getAttribute("priority")||"0");return l-c});let s=!1;for(let n=0;n<t.length;n++){const r=this.options.children[n],l=t[n];if(r!==l){s=!0;break}}if(s)for(const n of t)this.options.appendChild(n)}}handleMenuVisible(){Cc&&console.log("Update VisibleState: Any Content?",this.hasAnyContent),this.hasAnyContent?this.root.style.display="":this.root.style.display="none",this.root.classList.toggle("has-options",this.hasAnyVisibleOptions),this.root.classList.toggle("has-no-options",!this.hasAnyVisibleOptions)}get hasAnyContent(){return!!(this.logoContainer.style.display!="none"||this.hasAnyVisibleOptions)}get hasAnyVisibleOptions(){for(let e=0;e<this.options.children.length;e++){const t=this.options.children[e];if(t.tagName==="SLOT"){const s=t.assignedNodes();for(const n of s)if(n instanceof HTMLElement&&n.style.display!="none")return!0}else if(t.style.display!="none")return!0}return!1}___insertDebugOptions(){window.addEventListener("keydown",s=>{s.key==="p"&&this.setPosition(this.root.classList.contains("top")?"bottom":"top")});const e=document.createElement("button");e.textContent="Hide Buttons",e.onclick=()=>{const s=new Array(this.options.children.length);for(let n=0;n<this.options.children.length;n++)s[n]=this.options.children[n];for(const n of s)this.options.removeChild(n);setTimeout(()=>{for(const n of s)this.options.appendChild(n)},1e3)},this.appendChild(e);const t=document.createElement("button");t.textContent="Toggle Logo",t.addEventListener("click",()=>{this.logoContainer.style.display=this.logoContainer.style.display==="none"?"":"none"}),this.appendChild(t)}};fu=new WeakMap;let Qw=SR;customElements.get(Er)||customElements.define(Er,Qw);const et=C("debugcontext"),CR=C("stats"),PR=C("debugactive"),OR=C("debugframerate"),kR=C("debugcoroutine"),MR={};class RR{constructor(){a(this,"name"),a(this,"alias"),a(this,"hash"),a(this,"runInBackground"),a(this,"domElement"),a(this,"renderer"),a(this,"camera"),a(this,"scene")}}var Oe=(o=>(o[o.Start=-1]="Start",o[o.EarlyUpdate=0]="EarlyUpdate",o[o.Update=1]="Update",o[o.LateUpdate=2]="LateUpdate",o[o.OnBeforeRender=3]="OnBeforeRender",o[o.OnAfterRender=4]="OnAfterRender",o[o.PrePhysicsStep=9]="PrePhysicsStep",o[o.PostPhysicsStep=10]="PostPhysicsStep",o[o.Undefined=-1]="Undefined",o))(Oe||{});function yu(o,e){if(!o)return;if(!o.isComponent){(F()||et)&&console.error(`Registered script is not a Needle Engine component.
769
+ The script will be ignored. Please make sure your component extends "Behaviour" imported from "@needle-tools/engine"
770
+ `,o);return}e||(e=ee.Current,et&&console.warn("> Registering component without context"));const t=e?.new_scripts;t.includes(o)||t.push(o)}const Cf=class Le{constructor(e){a(this,"name"),a(this,"alias"),a(this,"isManagedExternally",!1),a(this,"isPaused",!1),a(this,"runInBackground",!1),a(this,"targetFrameRate"),a(this,"physicsSteps",1),a(this,"hash"),a(this,"domElement"),a(this,"_resolutionScaleFactor",1),a(this,"_boundingClientRectFrame",-1),a(this,"_boundingClientRect",null),a(this,"_domX"),a(this,"_domY"),a(this,"xr",null),a(this,"_xrFrame",null),a(this,"_currentFrameEvent",-1),a(this,"scene"),a(this,"renderer"),a(this,"composer",null),a(this,"scripts",[]),a(this,"scripts_pausedChanged",[]),a(this,"scripts_earlyUpdate",[]),a(this,"scripts_update",[]),a(this,"scripts_lateUpdate",[]),a(this,"scripts_onBeforeRender",[]),a(this,"scripts_onAfterRender",[]),a(this,"scripts_WithCorroutines",[]),a(this,"scripts_immersive_vr",[]),a(this,"scripts_immersive_ar",[]),a(this,"coroutines",{}),a(this,"post_setup_callbacks",[]),a(this,"pre_update_callbacks",[]),a(this,"pre_render_callbacks",[]),a(this,"post_render_callbacks",[]),a(this,"pre_update_oneshot_callbacks",[]),a(this,"new_scripts",[]),a(this,"new_script_start",[]),a(this,"new_scripts_pre_setup_callbacks",[]),a(this,"new_scripts_post_setup_callbacks",[]),a(this,"new_scripts_xr",[]),a(this,"mainCameraComponent"),a(this,"_mainCamera",null),a(this,"_fallbackCamera",null),a(this,"application"),a(this,"animations"),a(this,"time"),a(this,"input"),a(this,"physics"),a(this,"connection"),a(this,"assets"),a(this,"mainLight",null),a(this,"sceneLighting"),a(this,"addressables"),a(this,"lightmaps"),a(this,"players"),a(this,"lodsManager"),a(this,"menu"),a(this,"_needsUpdateSize",!1),a(this,"_isCreated",!1),a(this,"_isCreating",!1),a(this,"_isVisible",!1),a(this,"_stats",CR?new YP:null),a(this,"_intersectionObserver",null),a(this,"_disposeCallbacks",[]),a(this,"maxRenderResolution"),a(this,"_devicePixelRatio","auto"),a(this,"_originalCreationArgs"),a(this,"onUnhandledRejection",n=>{this.onError(n.reason)}),a(this,"_cameraStack",[]),a(this,"_onBeforeRenderListeners",new Map),a(this,"_onAfterRenderListeners",new Map),a(this,"_requireDepthTexture",!1),a(this,"_requireColorTexture",!1),a(this,"_renderTarget"),a(this,"_isRendering",!1),a(this,"_createId",0),a(this,"_renderlooperrors",0),a(this,"_lastTimestamp",0),a(this,"_accumulatedTime",0),a(this,"_dispatchReadyAfterFrame",!1),a(this,"_tempClearColor",new ae),a(this,"_tempClearColor2",new ae),a(this,"_contextRestoreTries",0),a(this,"_wasPaused",!1),this.name=e?.name||"",this.alias=e?.alias,this.domElement=e?.domElement||document.body,this.hash=e?.hash,e!=null&&e.renderer&&(this.renderer=e.renderer,this.isManagedExternally=!0),e?.runInBackground!==void 0&&(this.runInBackground=e.runInBackground),e!=null&&e.scene?this.scene=e.scene:this.scene=new wi,e!=null&&e.camera&&(this._mainCamera=e.camera),this.application=new Ln(this),this.time=new Uw,this.input=new e_(this),this.physics=new Ng(this),this.connection=new g_(this),this.assets=new E_,this.sceneLighting=new Dw(this),this.addressables=new Sw(this),this.lightmaps=new cR(this),this.players=new Iw(this),this.menu=new xR(this),this.lodsManager=new hR(this),this.animations=new rR(this);const t=()=>this._needsUpdateSize=!0;window.addEventListener("resize",t),this._disposeCallbacks.push(()=>window.removeEventListener("resize",t));const s=new ResizeObserver(n=>this._needsUpdateSize=!0);s.observe(this.domElement),this._disposeCallbacks.push(()=>s.disconnect()),this._intersectionObserver=new IntersectionObserver(n=>{this._isVisible=n[0].isIntersecting}),this._disposeCallbacks.push(()=>{var n;return(n=this._intersectionObserver)==null?void 0:n.disconnect()}),pe.register(this)}static get DefaultTargetFrameRate(){return Le._defaultTargetFramerate.value}static set DefaultTargetFrameRate(e){Le._defaultTargetFramerate.value=e}static get DefaultWebGLRendererParameters(){return Le._defaultWebglRendererParameters}get version(){return _s}static get Current(){return pe.Current}static set Current(e){pe.Current=e}static get All(){return pe.All}appendHTMLElement(e){return this.domElement.shadowRoot?this.domElement.shadowRoot.appendChild(e):this.domElement.appendChild(e)}get resolutionScaleFactor(){return this._resolutionScaleFactor}set resolutionScaleFactor(e){if(e!==this._resolutionScaleFactor&&typeof e=="number"){if(e<=0){console.error("Invalid resolution scale factor",e);return}this._resolutionScaleFactor=e,this.updateSize()}}calculateBoundingClientRect(){if(this.xr){this._domX=0,this._domY=0;return}this._boundingClientRectFrame!==this.time.frame&&(this._boundingClientRectFrame=this.time.frame,this._boundingClientRect=this.domElement.getBoundingClientRect(),this._domX=this._boundingClientRect.x,this._domY=this._boundingClientRect.y)}get domWidth(){return this.isInAR?window.innerWidth:this.domElement.clientWidth}get domHeight(){return this.isInAR?window.innerHeight:this.domElement.clientHeight}get domX(){return this.calculateBoundingClientRect(),this._domX}get domY(){return this.calculateBoundingClientRect(),this._domY}get isInXR(){var e,t;return((t=(e=this.renderer)==null?void 0:e.xr)==null?void 0:t.isPresenting)||!1}get xrSessionMode(){var e;return(e=this.xr)==null?void 0:e.mode}get isInVR(){return this.xrSessionMode==="immersive-vr"}get isInAR(){return this.xrSessionMode==="immersive-ar"}get isInPassThrough(){return this.xr?this.xr.isPassThrough:!1}get xrSession(){var e,t;return(t=(e=this.renderer)==null?void 0:e.xr)==null?void 0:t.getSession()}get xrFrame(){return this._xrFrame}get xrCamera(){var e,t;return this.renderer.xr.isPresenting?(t=(e=this.renderer)==null?void 0:e.xr)==null?void 0:t.getCamera():void 0}get arOverlayElement(){const e=this.domElement;return typeof e.getAROverlayContainer=="function"?e.getAROverlayContainer():this.domElement}get currentFrameEvent(){return this._currentFrameEvent}get mainCamera(){if(this._mainCamera)return this._mainCamera;if(this.mainCameraComponent){const e=this.mainCameraComponent;return e.threeCamera||e.buildCamera(),e.threeCamera}return this._fallbackCamera||(this._fallbackCamera=new we(75,this.domWidth/this.domHeight,.1,1e3)),this._fallbackCamera}set mainCamera(e){this._mainCamera=e}get rendererData(){return this.sceneLighting}get isCreated(){return this._isCreated}createNewRenderer(e){var t,s,n;if((t=this.renderer)==null||t.dispose(),e={...Le.DefaultWebGLRendererParameters,...e},!e.canvas){const r=(n=(s=this.domElement)==null?void 0:s.shadowRoot)==null?void 0:n.querySelector("canvas");r&&(e.canvas=r,et&&console.log("Using canvas from shadow root",r))}return et&&console.log("Using Renderer Parameters:",e,this.domElement),this.renderer=new pr(e),this.renderer.debug.checkShaderErrors=F()||C("checkshadererrors")===!0,this.renderer.toneMappingExposure=1,this.renderer.toneMapping=yd,this.renderer.setClearColor(new ae("lightgrey"),0),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=WC,this.renderer.setSize(this.domWidth,this.domHeight),this.renderer.outputColorSpace=Mn,this.renderer.nodes={library:new VC,modelViewMatrix:null,modelNormalViewMatrix:null},this.lodsManager.setRenderer(this.renderer),this.input.bindEvents(),this.renderer}internalOnUpdateVisible(){var e,t;(e=this._intersectionObserver)==null||e.disconnect(),(t=this._intersectionObserver)==null||t.observe(this.domElement)}requestSizeUpdate(){this._needsUpdateSize=!0}get devicePixelRatio(){return this._devicePixelRatio}set devicePixelRatio(e){e!==this._devicePixelRatio&&(this._devicePixelRatio=e,this._needsUpdateSize=!0)}updateSize(e=!1){var t,s,n;if(e||!this.isManagedExternally&&((t=this.renderer.xr)==null?void 0:t.isPresenting)===!1){this._needsUpdateSize=!1;const r=this.resolutionScaleFactor;let l=this.domWidth*r,c=this.domHeight*r;this.maxRenderResolution&&(this.maxRenderResolution.x=Math.max(1,this.maxRenderResolution.x),l=Math.min(this.maxRenderResolution.x,l),this.maxRenderResolution.y=Math.max(1,this.maxRenderResolution.y),c=Math.min(this.maxRenderResolution.y,c));const h=this.mainCamera;this.updateAspect(h),this.renderer.setSize(l,c,!0),this.renderer.domElement.style.width="100%",this.renderer.domElement.style.height="100%";const d=typeof this.devicePixelRatio=="number"?this.devicePixelRatio:this.devicePixelRatio==="auto"?window.devicePixelRatio:void 0;d!==void 0&&this.renderer.setPixelRatio(d),this.composer&&((s=this.composer.setSize)==null||s.call(this.composer,l,c),d!==void 0&&"setPixelRatio"in this.composer&&typeof this.composer.setPixelRatio=="function"&&((n=this.composer.setPixelRatio)==null||n.call(this.composer,window.devicePixelRatio)))}}updateAspect(e,t,s){if(!e)return;t===void 0&&(t=this.domWidth),s===void 0&&(s=this.domHeight);const n=t/s;if(e.isPerspectiveCamera){const r=e,l=r.aspect;r.aspect=n,l!==r.aspect&&e.updateProjectionMatrix()}else if(e.isOrthographicCamera){const r=e,l=r.top-r.bottom,c=l*n/2,h=l/2;(r.left!=-c||r.top!=h)&&(r.left=-c,r.right=c,r.top=h,r.bottom=-h,e.updateProjectionMatrix())}}recreate(){this.clear(),this.create(this._originalCreationArgs)}async onCreate(e){return this.create(e)}async create(e){try{this._isCreating=!0,e!==this._originalCreationArgs&&(this._originalCreationArgs=$l(e)),window.addEventListener("unhandledrejection",this.onUnhandledRejection);const t=await this.internalOnCreate(e);return this._isCreated=t,t}finally{window.removeEventListener("unhandledrejection",this.onUnhandledRejection),this._isCreating=!1}}onError(e){this.domElement.dispatchEvent(new CustomEvent("error",{detail:e}))}clear(){var e,t,s,n;pe.dispatchCallback(me.ContextClearing,this),Xs(this,me.ContextClearing),Ei(this.scene,!0,!0),this.scene=new wi,(e=this.addressables)==null||e.dispose(),(t=this.lightmaps)==null||t.clear(),(n=(s=this.physics)==null?void 0:s.engine)==null||n.clearCaches(),this.lodsManager.disable(),this._onBeforeRenderListeners.clear(),this._onAfterRenderListeners.clear(),this.isManagedExternally||this.renderer&&(this.renderer.renderLists.dispose(),this.renderer.state.reset(),this.renderer.resetState()),pe.dispatchCallback(me.ContextCleared,this)}dispose(){this.internalOnDestroy()}onDestroy(){this.internalOnDestroy()}internalOnDestroy(){var e,t;Le.Current=this,pe.dispatchCallback(me.ContextDestroying,this),Xs(this,me.ContextDestroying),this.clear(),(e=this.renderer)==null||e.setAnimationLoop(null),this.renderer&&(this.renderer.setClearAlpha(0),this.renderer.clear(),this.isManagedExternally||(et&&console.log("Disposing renderer"),this.renderer.dispose())),this.scene=null,this.renderer=null,this.input.dispose(),this.menu.onDestroy(),this.animations.onDestroy();for(const s of this._disposeCallbacks)try{s()}catch(n){console.error("Error in on dispose callback:",n,s)}(t=this.domElement)!=null&&t.parentElement&&this.domElement.parentElement.removeChild(this.domElement),this._isCreated=!1,pe.dispatchCallback(me.ContextDestroyed,this),Xs(this,me.ContextDestroyed),pe.unregister(this),Le.Current===this&&(Le.Current=null)}registerCoroutineUpdate(e,t,s){return typeof t?.next!="function"?(console.error("Registered invalid coroutine function from "+e.name+`
771
+ Coroutine functions must be generators: "*myCoroutine() {...}"
772
+ Start a coroutine from a component by calling "this.startCoroutine(myCoroutine())"`),t):(this.coroutines[s]||(this.coroutines[s]=[]),this.coroutines[s].push({comp:e,main:t}),t)}unregisterCoroutineUpdate(e,t){if(!this.coroutines[t])return;const s=this.coroutines[t].findIndex(n=>n.main===e);s>=0&&this.coroutines[t].splice(s,1)}stopAllCoroutinesFrom(e){for(const t in this.coroutines){const s=this.coroutines[t];for(let n=s.length-1;n>=0;n--)s[n].comp===e&&s.splice(n,1)}}setCurrentCamera(e){var t;if(!e)return;if(e.threeCamera||e.buildCamera(),!e.threeCamera){console.warn("Camera component is missing camera",e);return}const s=this._cameraStack.indexOf(e);s>=0&&this._cameraStack.splice(s,1),this._cameraStack.push(e),this.mainCameraComponent=e;const n=e.threeCamera;n.isPerspectiveCamera&&this.updateAspect(n),(t=this.mainCameraComponent)==null||t.applyClearFlagsIfIsActiveCamera()}removeCamera(e){if(!e)return;const t=this._cameraStack.indexOf(e);if(t>=0&&this._cameraStack.splice(t,1),this.mainCameraComponent===e&&(this.mainCameraComponent=void 0,this._cameraStack.length>0)){const s=this._cameraStack[this._cameraStack.length-1];this.setCurrentCamera(s)}}addBeforeRenderListener(e,t){if(!this._onBeforeRenderListeners.has(e.uuid)){const s=[];this._onBeforeRenderListeners.set(e.uuid,s),e.onBeforeRender=this._createRenderCallbackWrapper(s)}this._onBeforeRenderListeners.get(e.uuid).push(t)}removeBeforeRenderListener(e,t){if(this._onBeforeRenderListeners.has(e.uuid)){const s=this._onBeforeRenderListeners.get(e.uuid),n=s.indexOf(t);n>=0&&s.splice(n,1)}}addAfterRenderListener(e,t){var s;if(!this._onAfterRenderListeners.has(e.uuid)){const n=[];this._onAfterRenderListeners.set(e.uuid,n),e.onAfterRender=this._createRenderCallbackWrapper(n)}(s=this._onAfterRenderListeners.get(e.uuid))==null||s.push(t)}removeAfterRenderListener(e,t){if(this._onAfterRenderListeners.has(e.uuid)){const s=this._onAfterRenderListeners.get(e.uuid),n=s.indexOf(t);n>=0&&s.splice(n,1)}}_createRenderCallbackWrapper(e){return(t,s,n,r,l,c)=>{for(let h=0;h<e.length;h++){const d=e[h];d(t,s,n,r,l,c)}}}get isRendering(){return this._isRendering}setRequireDepth(e){this._requireDepthTexture=e}setRequireColor(e){this._requireColorTexture=e}get depthTexture(){var e;return((e=this._renderTarget)==null?void 0:e.depthTexture)||null}get opaqueColorTexture(){var e;return((e=this._renderTarget)==null?void 0:e.texture)||null}get isVisibleToUser(){if(this.isInXR)return!0;if(!this._isVisible)return!1;const e=getComputedStyle(this.domElement);return e.visibility!=="hidden"&&e.display!=="none"&&e.opacity!=="0"}async internalOnCreate(e){var t,s,n,r,l,c,h;const d=++this._createId;et&&console.log("Creating context",this.name,e);const u=globalThis["needle:dependencies:ready"];u instanceof Promise&&(et&&console.log("Waiting for dependencies to be ready"),await u.catch(v=>{if(et||F()){if(ec("Needle Engine dependencies failed to load. Please check the console for more details"),v instanceof ReferenceError){let _="YourComponentName";const w=v.message.indexOf("'");if(w>0){const S=v.message.indexOf("'",w+1);if(S>0){const k=v.message.substring(w+1,S);k.length>3&&(_=k)}}console.error(`Needle Engine dependencies failed to load:
773
+
774
+ # Make sure you don't have circular imports in your scripts!
775
+
776
+ Possible solutions:
777
+ \u2192 Replace @serializable(${_}) in your script with @serializable(Behaviour)
778
+ \u2192 If you only need type information try importing the type only, e.g: import { type ${_} }
779
+
780
+ ---`,v);return}console.error("Needle Engine dependencies failed to load",v)}}).then(()=>{et&&console.log("Needle Engine dependencies are ready")})),this.clear();const p=this.renderer,g=!p||p.isDisposed===!0;this.isManagedExternally===!1&&g?this.createNewRenderer():this.lodsManager.setRenderer(this.renderer),(t=this.renderer)==null||t.setAnimationLoop(null),await ys(1),Le.Current=this,await pe.dispatchCallback(me.ContextCreationStart,this);let f=!0,y;try{Le.Current=this,e?y=await this.internalLoadInitialContent(d,e):y=[]}catch(v){console.error(v),f=!1}if(!f)return this.onError("Failed to load initial content"),!1;if(d!==this._createId||(s=e?.abortSignal)!=null&&s.aborted)return!1;if(this.internalOnUpdateVisible(),!this.renderer)return et&&console.warn("Context has no renderer (perhaps it was disconnected?",this.domElement.isConnected),!1;!this.isManagedExternally&&!this.domElement.shadowRoot&&this.domElement.prepend(this.renderer.domElement),Le.Current=this,Le.Current=this;for(let v=0;v<this.new_scripts.length;v++){const _=this.new_scripts[v];if(_.gameObject!==void 0&&_.gameObject!==null){_.gameObject.userData===void 0&&(_.gameObject.userData={}),_.gameObject.userData.components===void 0&&(_.gameObject.userData.components=[]);const w=_.gameObject.userData.components;w.includes(_)||w.push(_)}}if(this.post_setup_callbacks)for(let v=0;v<this.post_setup_callbacks.length;v++)Le.Current=this,await this.post_setup_callbacks[v](this);if(!this._mainCamera){Le.Current=this;let v=null;Rr(this.scene,_=>{const w=_;if(w!=null&&w.isCamera){if(pc(w.gameObject),!w.activeAndEnabled)return;if(w.tag==="MainCamera")return v=w,!0;v=w}}),v?this.setCurrentCamera(v):!pe.dispatchCallback(me.MissingCamera,this,{files:y})&&!this.mainCamera&&!this.isManagedExternally&&console.warn("Missing camera in main scene",this)}this.input.bindEvents(),Le.Current=this,Qd(this),this.physics.engine&&((n=this.physics.engine)==null||n.step(0),(r=this.physics.engine)==null||r.postStep()),!this.isManagedExternally&&this.composer&&this.mainCamera,this._needsUpdateSize=!0,this._stats&&(this._stats.showPanel(0),this._stats.dom.style.position="absolute",(l=this.domElement.shadowRoot)==null||l.appendChild(this._stats.dom)),et&&Ed(this.scene,!0),this.targetFrameRate===void 0?(et&&console.warn("No target framerate set, using default",Le.DefaultTargetFrameRate),this.targetFrameRate=Le._defaultTargetFramerate):et&&console.log("Target framerate set to",this.targetFrameRate),this._dispatchReadyAfterFrame=!0;const b=pe.dispatchCallback(me.ContextCreated,this,{files:y});if(b){const v=this.domElement;"internalSetLoadingMessage"in v&&typeof v.internalSetLoadingMessage=="function"&&v?.internalSetLoadingMessage("finish loading"),await b}return(c=e?.abortSignal)!=null&&c.aborted?!1:(Xs(this,me.ContextCreated),et&&console.log("Context Created...",this.renderer,this.renderer.domElement),this._isCreating=!1,!this.isManagedExternally&&!((h=e?.abortSignal)!=null&&h.aborted)&&this.restartRenderLoop(),!0)}async internalLoadInitialContent(e,t){var s,n,r,l;const c=new Array;if(t.files.length===0)return c;const h=[...t.files],d={name:"",progress:null,index:0,count:h.length},u=ws(),p=0;for(let g=0;g<h.length;g++){if((s=t.abortSignal)!=null&&s.aborted){et&&console.log("Aborting loading because of abort signal");break}if(e!==this._createId){et&&console.log("Aborting loading because create id changed",e,this._createId);break}const f=h[g];(n=t?.onLoadingStart)==null||n.call(this,g,f),et&&console.log("Context Load "+f);const y=await u.loadSync(this,f,f,p,b=>{var v,_;(v=t.abortSignal)!=null&&v.aborted||(d.name=f,d.progress=b,d.index=g,d.count=h.length,(_=t.onLoadingProgress)==null||_.call(this,d))});(r=t?.onLoadingFinished)==null||r.call(this,g,f,y??null),y?c.push({src:f,file:y}):console.warn("Could not load file: "+f)}if(e!==this._createId||(l=t.abortSignal)!=null&&l.aborted){et&&console.log("Aborting loading because create id changed or abort signal was set",e,this._createId);for(const g of c)if(g&&g.file)for(const f of g.file.scenes)Ei(f,!0,!0)}else{let g=!1;for(const f of c)f&&f.file&&(f.file.scene?(g=!0,this.scene.add(f.file.scene)):console.warn("No scene found in loaded file"));if(!g){for(const f of c)if(f&&f.file&&"parser"in f.file){let y=0;if(!Array.isArray(f.file.parser.json.materials))continue;for(let b=0;b<f.file.parser.json.materials.length;b++){const v=await f.file.parser.getDependency("material",b),_=new E;_.position.x=b*1.1,_.position.y=y,this.scene.add(_),_o.createPrimitive("ShaderBall",{parent:_,material:v})}y+=1}}}return c}restartRenderLoop(){return this.renderer?this._isCreating?(console.warn("Can not start render loop while creating context"),!1):(this.renderer.setAnimationLoop((e,t)=>{this.isManagedExternally||this.update(e,t)}),!0):(console.error("Can not start render loop without renderer"),!1)}update(e,t){if(t===void 0&&(t=null),F()||et||OM())try{this.internalStep(e,t),this._renderlooperrors=0}catch(s){this._renderlooperrors+=1,(F()||et)&&(s instanceof Error||s instanceof TypeError)&&Be("Caught unhandled exception during render-loop - see console for details.",Oi.Error),console.error("Frame #"+this.time.frame+`
781
+ `,s),this._renderlooperrors>=3&&(console.warn("Stopping render loop due to error"),this.renderer.setAnimationLoop(null)),this.domElement.dispatchEvent(new CustomEvent("error",{detail:s}))}else this.internalStep(e,t)}updatePhysics(e){this.internalUpdatePhysics(e)}internalStep(e,t){this.internalOnBeforeRender(e,t)!==!1&&(this.internalOnRender(),this.internalOnAfterRender())}internalOnBeforeRender(e,t){var s;this.renderer.info.autoReset=!!t,this.renderer.info.autoReset===!1&&this.renderer.info.reset();const n=t!==null&&this._xrFrame===null;if(this._xrFrame=t,n&&this.domElement.dispatchEvent(new CustomEvent("xr-session-started",{detail:{context:this,session:this.xrSession,frame:t}})),this._currentFrameEvent=-1,this.isManagedExternally===!1&&this.isInXR===!1&&this.targetFrameRate!==void 0){this._lastTimestamp===0&&(this._lastTimestamp=e),this._accumulatedTime+=(e-this._lastTimestamp)/1e3,this._lastTimestamp=e;let r=this.targetFrameRate;if(typeof r=="object"&&(r=r.value),this._accumulatedTime<1/(r+1))return!1;this._accumulatedTime=0}if((s=this._stats)==null||s.begin(),Le.Current=this,this.onHandlePaused())return!1;for(Le.Current=this,this.time.update(),OR&&console.log("FPS",this.time.smoothedFps.toFixed(0)),Qd(this),Yd(this.scene),z_(this),Xs(this,-1);this._cameraStack.length>0&&(!this.mainCameraComponent||this.mainCameraComponent.destroyed);){this._cameraStack.splice(this._cameraStack.length-1,1);const r=this._cameraStack[this._cameraStack.length-1];this.setCurrentCamera(r)}if(this.pre_update_oneshot_callbacks){for(const r in this.pre_update_oneshot_callbacks)this.pre_update_oneshot_callbacks[r]();this.pre_update_oneshot_callbacks.length=0}if(this.pre_update_callbacks)for(const r in this.pre_update_callbacks)this.pre_update_callbacks[r]();this._currentFrameEvent=0;for(let r=0;r<this.scripts_earlyUpdate.length;r++){const l=this.scripts_earlyUpdate[r];l.activeAndEnabled&&l.earlyUpdate!==void 0&&(Le.Current=this,l.earlyUpdate())}if(this.executeCoroutines(0),Xs(this,0),this.onHandlePaused())return!1;this._currentFrameEvent=1;for(let r=0;r<this.scripts_update.length;r++){const l=this.scripts_update[r];l.activeAndEnabled&&l.update!==void 0&&(Le.Current=this,l.update())}if(this.executeCoroutines(1),Xs(this,1),this.onHandlePaused())return!1;this._currentFrameEvent=2;for(let r=0;r<this.scripts_lateUpdate.length;r++){const l=this.scripts_lateUpdate[r];l.activeAndEnabled&&l.lateUpdate!==void 0&&(Le.Current=this,l.lateUpdate())}if(this.executeCoroutines(2),Xs(this,2),this.onHandlePaused()||(this.physicsSteps===void 0&&(this.physicsSteps=1),this.physics.engine&&this.physicsSteps>0&&this.internalUpdatePhysics(this.physicsSteps),this.onHandlePaused()))return!1;if(this.isVisibleToUser||this.runInBackground){this._currentFrameEvent=3;for(let r=0;r<this.scripts_onBeforeRender.length;r++){const l=this.scripts_onBeforeRender[r];l.activeAndEnabled&&l.onBeforeRender!==void 0&&(Le.Current=this,l.onBeforeRender(t))}if(this.executeCoroutines(3),Xs(this,3),this._needsUpdateSize&&this.updateSize(),this.pre_render_callbacks)for(const r in this.pre_render_callbacks)this.pre_render_callbacks[r](t)}return!0}internalUpdatePhysics(e){if(!this.physics.engine)return!1;const t=e,s=this.time.deltaTime/t;for(let n=0;n<t;n++)this._currentFrameEvent=9,this.executeCoroutines(9),this.physics.engine.step(s),this._currentFrameEvent=10,this.executeCoroutines(10);return this.physics.engine.postStep(),!0}internalOnRender(){this.isManagedExternally||(TM(this),this._currentFrameEvent=-1,KP.update(),this.renderNow(),this._currentFrameEvent=4)}internalOnAfterRender(){if(this.isVisibleToUser||this.runInBackground){for(let e=0;e<this.scripts_onAfterRender.length;e++){const t=this.scripts_onAfterRender[e];t.activeAndEnabled&&t.onAfterRender!==void 0&&(Le.Current=this,t.onAfterRender())}if(this.executeCoroutines(4),Xs(this,4),this.post_render_callbacks)for(const e in this.post_render_callbacks)this.post_render_callbacks[e]()}this._currentFrameEvent=-1,this.connection.sendBufferedMessagesNow(),this._stats&&(this._stats.end(),this.time.frameCount%150===0&&console.log(this.renderer.info.render.calls+" DrawCalls",`
782
+ Render:`,{...this.renderer.info.render},`
783
+ Memory:`,{...this.renderer.info.memory},`
784
+ Target Framerate: `+this.targetFrameRate)),this._dispatchReadyAfterFrame&&(this._dispatchReadyAfterFrame=!1,this.domElement.dispatchEvent(new CustomEvent("ready")),pe.dispatchCallback(me.ContextFirstFrameRendered,this))}renderNow(e){var t;if(!e&&(e=this.mainCamera,!e))return!1;if(this.handleRendererContextLost(),this._isRendering=!0,this.renderRequiredTextures(),this.renderer.toneMapping!==yd&&Nw(),this.composer&&!this.isInXR){e&&"setMainCamera"in this.composer&&((t=this.composer.passes[0])==null?void 0:t.mainCamera)!=e&&this.composer.setMainCamera(e);const s=this.renderer.getClearColor(this._tempClearColor);this._tempClearColor2.copy(s),this.renderer.setClearColor(s.convertSRGBToLinear()),this.composer.render(this.time.deltaTime),this.renderer.setClearColor(this._tempClearColor2)}else e&&(this.isInXR&&Y.isMacOS()&&this.renderer.clearDepth(),this.renderer.render(this.scene,e));return this._isRendering=!1,!0}handleRendererContextLost(){this.time.frame%10&&this.renderer.getContext().isContextLost()&&this._contextRestoreTries++<100&&(console.warn("Attempting to recover WebGL context..."),this.renderer.forceContextRestore())}onHandlePaused(){const e=this.evaluatePaused();if(this._wasPaused!==e){PR&&console.log("Paused?",e,"context:"+this.alias);for(let t=0;t<this.scripts_pausedChanged.length;t++){const s=this.scripts_pausedChanged[t];s.activeAndEnabled&&s.onPausedChanged!==void 0&&(Le.Current=this,s.onPausedChanged(e,this._wasPaused))}}return this._wasPaused=e,e}evaluatePaused(){return this.isInXR?!1:this.isPaused?!0:this.runInBackground?!1:!this.isVisibleToUser}renderRequiredTextures(){if(!this.mainCamera||!this._requireDepthTexture&&!this._requireColorTexture)return;if(!this._renderTarget){if(this._renderTarget=new Hs(this.domWidth,this.domHeight),this._requireDepthTexture){const s=new Rv(this.domWidth,this.domHeight);this._renderTarget.depthTexture=s}this._requireColorTexture&&(this._renderTarget.texture=new De,this._renderTarget.texture.generateMipmaps=!1,this._renderTarget.texture.minFilter=vd,this._renderTarget.texture.magFilter=vd,this._renderTarget.texture.format=md)}const e=this._renderTarget;e.texture&&(e.texture.colorSpace=this.renderer.outputColorSpace);const t=this.renderer.getRenderTarget();this.renderer.setRenderTarget(e),this.renderer.render(this.scene,this.mainCamera),this.renderer.setRenderTarget(t)}executeCoroutines(e){var t;if(this.coroutines[e]){const n=this.coroutines[e];for(let r=0;r<n.length;r++)try{const l=n[r];if(!l.comp||l.comp.destroyed||!l.main||l.comp.enabled===!1){kR&&console.log("Removing coroutine",l.comp,l.comp.enabled),n.splice(r,1),--r;continue}const c=l.chained;if(c&&c.length>0){const u=c[c.length-1].next();if(u.done&&c.pop(),s(u)&&(l.chained||(l.chained=[]),l.chained.push(u.value)),!u.done)continue}const h=l.main.next();if(h.done===!0){n.splice(r,1),--r;continue}const d=h.value;if(s(d)){if(d.next().done)continue;l.chained||(l.chained=[]),l.chained.push(d)}else if(d instanceof Promise){const u=d;l.chained||(l.chained=[]);const p=Rw(u);(t=l.chained)==null||t.push(p);continue}}catch(l){console.error(l)}}function s(n){return!!(n&&n.next&&n.return)}}};a(Cf,"_defaultTargetFramerate",{value:90,toString(){return this.value}}),a(Cf,"_defaultWebglRendererParameters",{antialias:!0,alpha:!1,powerPreference:Y.isiOS()||Y.isMacOS()?"default":"high-performance",stencil:!0});let ee=Cf;const Ai=C("debuglicense"),Yw=[];let Ks="basic";Ai&&console.log("License Type: "+Ks);function Zs(){switch(Ks){case"pro":case"enterprise":return!0}return!1}function Pc(){switch(Ks){case"indie":return!0}return!1}function Pf(){switch(Ks){case"edu":return!0}return!1}function Js(){return Zs()||Pc()||Pf()}function TR(o){if(Zs()||Pc()||Pf())return o(!0);Yw.push(o)}function vu(o){for(const e of Yw)try{e(o)}catch{}}pe.registerCallback(me.ContextRegistered,o=>{IR(o.context),AR(o.context),setTimeout(()=>jR(o.context),2e3)});let Ar,Of=!1,bu="";async function ER(){if(Ar)return Ar;if(Ks==="basic")try{const o="https://engine.needle.tools/licensing/check?location="+encodeURIComponent(window.location.href)+"&version="+_s+"&generator="+encodeURIComponent(Id),e=await fetch(o,{method:"GET"}).catch(t=>{Ai&&console.error("License check failed",t)});e?.status===200?(Of=!1,Ai&&console.log("License check succeeded"),Ks="pro",vu(!0)):e?.status===403?(vu(!1),Of=!0,bu=await e.text()):(vu(!1),Ai&&console.log("License check failed with status "+e?.status))}catch(o){vu(!1),Ai&&console.error("License check failed",o)}else Ai&&console.log('Runtime license check is skipped because license is already applied as "'+Ks+'"')}Ar=ER();async function AR(o){function e(){const n=document.createElement("div");n.className="needle-forbidden",n.style.cssText=`
785
+ position: fixed;
786
+ top: 0;
787
+ left: 0;
788
+ width: 100%;
789
+ height: 100%;
790
+ pointer-events: all;
791
+ zIndex: 2147483647;
792
+ line-height: 1.5;
793
+ backdrop-filter: blur(15px);
794
+ -webkit-backdrop-filter: blur(15px);
795
+ `;const r=n.style.cssText,l=document.createElement("div");n.appendChild(l),l.style.cssText=`
796
+ position: absolute;
797
+ left: 0;
798
+ right: 0;
799
+ top:0;
800
+ bottom: 0;
801
+ padding: 10%;
802
+ color: white;
803
+ font-size: 20px;
804
+ font-family: sans-serif;
805
+ text-align: center;
806
+ pointer-events: all;
807
+ display: flex;
808
+ justify-content: center;
809
+ align-items: center;
810
+ background-color: rgba(0,0,0,.3);
811
+ text-shadow: 0 0 2px black;
812
+ `;const c=l.style.cssText,h=bu?.length>1?bu:"This web application has been paused.<br/>You might be in violation of the Needle Engine terms of use.<br/>Please contact the Needle support if you think this is a mistake.";return l.innerHTML=h,setInterval(()=>{l.innerHTML!==h&&(l.innerHTML=h),l.parentNode!==n&&n.appendChild(l),n.style.cssText!==r&&(n.style.cssText=r),l.style.cssText!==c&&(l.style.cssText=c)},500),n}let t=e();const s=t.style.cssText;setInterval(()=>{var n;Of===!0&&(t.style.cssText!==s&&(t=e()),o.domElement.shadowRoot?t.parentNode!==o.domElement.shadowRoot&&((n=o.domElement.shadowRoot)==null||n.appendChild(t)):t.parentNode!=document.body&&document.body.appendChild(t))},500)}async function IR(o){try{if(!Zs()&&!Pc())return kf(o)}catch(e){return Ai&&console.log("License check failed",e),kf(o)}Ai&&kf(o)}async function kf(o){let e=!1;o.domElement.addEventListener("ready",()=>e=!0),await Ar?.catch(()=>{}),!(Zs()||Pc())&&(Js()===!1&&LR(),e?Mf(o):o.domElement.addEventListener("ready",()=>{Mf(o)}))}function Mf(o){var e;const t=`
813
+ position: relative;
814
+ display: block;
815
+ background-size: 20px;
816
+ background-position: 10px 5px;
817
+ background-repeat:no-repeat;
818
+ background-image:url('${Kw}');
819
+ background-max-size: 40px;
820
+ padding: 10px;
821
+ padding-left: 30px;
822
+ `;if(Ks==="edu")console.log("%c This project is supported by Needle for Education \u2013 https://needle.tools",t);else return;const s=document.createElement("div");s.className="needle-non-commercial-use",s.innerHTML="Made with Needle for Education",(e=o.domElement.shadowRoot)==null||e.appendChild(s);let n=`
823
+ position: absolute;
824
+ font-family: system-ui, Avenir, Helvetica, Arial, sans-serif;
825
+ font-size: 12px;
826
+ color: rgb(100, 100, 100);
827
+ /*mix-blend-mode: difference;*/
828
+ background-color: transparent;
829
+ z-index: 10000;
830
+
831
+ cursor: pointer;
832
+ user-select: none;
833
+ opacity: 0;
834
+
835
+ bottom: 6px;
836
+ right: 12px;
837
+ transform: translateY(0px);
838
+ transition: all .5s ease-in-out 1s;
839
+ `;s.style.cssText=n,s.addEventListener("click",()=>{window.open("https://needle.tools","_blank")});let r=s.style.cssText;setTimeout(()=>{n=n.replace("opacity: 0","opacity: 1"),n=n.replace("transform: translateY(10px)","transform: translateY(0)"),s.style.cssText=n,r=s.style.cssText},100);const l=setInterval(()=>{const c=o.domElement.shadowRoot||o.domElement;s.parentNode!==c&&c.appendChild(s),r!=s.style.cssText&&(s.style.cssText=n,r=s.style.cssText)},1e3);Pf()&&setTimeout(()=>{clearInterval(l),s?.remove(),setTimeout(()=>{o.domElement.parentNode&&Mf(o)},1e3*60*5)},2e4)}const Kw="data:image/webp;base64,UklGRrABAABXRUJQVlA4WAoAAAAQAAAAHwAAHwAAQUxQSKEAAAARN6CmbSM4WR7vdARON11EBDq3fLiNbVtVzpMCPlKAEzsx0Y/x+Ovuv4dn0EFE/ydAvz6YggXzgh5sVgXM/zOC/4sii7qgGvB5N7hmuQYwkvazWAu1JPW41FXSHq6pnaQWvqYH18Fc0j1hO/BFTtIeSBlJi5w6qIIO7IOrwhFsB2Yxukif0FTRLpXswHR8MxbslKe9VZsn/Ub5C7YFOpqSTABWUDgg6AAAAFAGAJ0BKiAAIAA+7VyoTqmkpCI3+qgBMB2JbACdMt69DwMIQBLhkTO6XwY00UEDK6cNIDnuNibPf0EgAP7Y1myuiQHLDsF/0h5unrGh6WAbv7aegg2ZMd3uRKfT/3SJztcaujYfTvMXspfCTmYcoO6a+vhC3ss4M8uM58t4siiu59I4aOl59e9Sr6xoxYlHf2v+NnBNpJYeJf8jABQAId/PXuBkLEFkiCucgSGEcfhvajql/j3reCGl0M5/9gQWy7ayNPs+wlvIxFnNfSlfuND4CZOCyxOHhRqOmHN4ULHo3tCSrUNvgAA=";let Zw=0;async function LR(o){var e;const t=Date.now();if(t-Zw<2e3)return;Zw=t;const s=`
840
+ position: relative;
841
+ display: block;
842
+ font-size: 18px;
843
+ background-size: 20px;
844
+ background-position: 10px 5px;
845
+ background-repeat:no-repeat;
846
+ background-image:url('${Kw}');
847
+ background-max-size: 40px;
848
+ margin-bottom: 5px;
849
+ margin-top: .3em;
850
+ margin-bottom: .5em;
851
+ padding: .2em;
852
+ padding-left: 25px;
853
+ border-radius: .5em;
854
+ border: 2px solid rgba(160,160,160,.3);
855
+ `,n=`Needle Engine \u2014 No license active, commercial use is not allowed. Visit https://needle.tools/pricing for more information and licensing options! v${_s}`;(e=ee.Current)!=null&&e.xr?console.log(n):console.log("%c "+n,s)}async function jR(o){var e,t;if(!window.crossOriginIsolated){if(Ks==="pro"){const s=(e=o?.domElement)==null?void 0:e.getAttribute("no-telemetry");if(s===""||s==="true"||s==="1"){Ai&&console.debug("Telemetry is disabled");return}Ai&&console.debug("Telemetry attribute: "+s)}try{const s="https://needle-engine-analytics-v2-r26roub2hq-lz.a.run.app";if(s){const n=window.location.href.split("?")[0];let r="api/v2/new/request";s.endsWith("/")||(r="/"+r);const l=Ks,c=`${s}${r}`;Ai&&console.debug("Sending beacon");const h={license:l,url:n,hostname:window.location.hostname,pathname:window.location.pathname,version:_s,generator:Id,build_time:gg,public_key:Ma},d=(t=navigator.sendBeacon)==null?void 0:t.call(navigator,c,JSON.stringify(h));Ai&&console.debug("Sent beacon: "+d)}}catch(s){Ai&&console.log("Failed to send non-commercial usage message to analytics backend",s)}}}const DR=C("debugdecoders");let Rf=null;function Jw(){if(!Rf){const o=Dm(null);Rf={dracoLoader:o.dracoLoader,ktx2Loader:o.ktx2Loader,meshoptDecoder:o.meshoptDecoder}}return Rf}function ex(o){o!==void 0&&typeof o=="string"&&GP(o)}function tx(o){if(o!==void 0&&typeof o=="string"&&o!=="js"){const e=Jw();DR&&console.log("Setting draco decoder type to",o),e.dracoLoader.setDecoderConfig({type:o})}}function ix(o){o!==void 0&&typeof o=="string"&&$P(o)}function Tf(o,e){const t=Jw();return e.renderer?t.ktx2Loader.detectSupport(e.renderer):console.warn("No renderer provided to detect ktx2 support - loading KTX2 textures will probably fail"),VP(o),o.dracoLoader||o.setDRACOLoader(t.dracoLoader),o.ktx2Loader||o.setKTX2Loader(t.ktx2Loader),o.meshoptDecoder||o.setMeshoptDecoder(t.meshoptDecoder),HP(o,{progressive:!0}),o}const Ir=function(o){return m(o)},m=function(o){if(o===void 0&&(o=null),!Array.isArray(o))o=sx(o);else for(let e=0;e<o.length;e++){const t=o[e];o[e]=sx(t)}return function(e,t){if(!e){console.error("Found @serializable decorator without a target");return}typeof t!="string"&&(t=t.name),Object.getOwnPropertyDescriptor(e,"$serializedTypes")||(e.$serializedTypes={});const s=e.$serializedTypes=e.$serializedTypes||{};s[t]=o}};function sx(o){var e,t;switch((t=(e=o?.prototype)==null?void 0:e.constructor)==null?void 0:t.name){case"Number":case"String":case"Boolean":return null}return o}const Po=C("debughotreload");let Oc=!1;const kc=new Map;function BR(){return Oc}function Ef(){return globalThis.NEEDLE_HOT_RELOAD_ENABLED===!0}function nx(o){var e;if(Oc){Po&&console.warn("[Needle Engine] Hot reloading is in progress, not registering instance",o);return}Po&&console.log("[Needle Engine] Registering hot reload instance",o);const t=o.constructor.name;kc.has(t)?(e=kc.get(t))==null||e.push(o):kc.set(t,[o])}function ox(o){if(Oc){Po&&console.warn("[Needle Engine] Hot reloading is in progress, not unregistering instance",o);return}Po&&console.log("[Needle Engine] Unregistering hot reload instance",o);const e=o.constructor.name,t=kc.get(e);if(!t)return;const s=t.indexOf(o);s!==-1&&t.splice(s,1)}let rx=!1;function FR(){if(Po||rx)return;rx=!0;const o=console.error;console.error=(...e)=>{if(e.length){const t=e[0];if(typeof t=="string"&&t.includes("[hmr] Failed to reload ")){console.log("[Needle Engine] Hot reloading failed"),window.location.reload();return}}o.apply(console,e)}}function UR(o){Po&&console.log("[HMR] Apply changes",o,Object.keys(o)),FR();for(const e of Object.keys(o))try{Oc=!0;const t=R.get(e);if(!t){Po&&console.log("[HMR] Type not found: "+e);continue}const s=o[e],n=kc.get(s.name);let r="[Needle Engine] Updating type: "+e;const l=n?.length??-1;l>0?r+=" x"+l:r+=" (No instances registered)",console.log(r);const c=Object.getOwnPropertyNames(t.prototype),h=Object.getOwnPropertyDescriptors(s.prototype);for(const d in h)h[d].writable&&(t.prototype[d]=o[e].prototype[d]);for(const d of c)h[d]||delete t.prototype[d];if(n){const d=new s,u=Object.getOwnPropertyDescriptors(d);for(const p of n){const g=p,f=g.isComponent===!0,y=f?g.activeAndEnabled:!0,b=f?g.context:void 0;try{if(f&&b&&Dn(g,b),f&&y&&(g.enabled=!1),p.onBeforeHotReloadFields&&p.onBeforeHotReloadFields()===!1)continue;for(const v in u)if(u[v].writable){if(p[v]===void 0)p[v]=d[v];else if(typeof p[v]=="function"&&!p[v].prototype){const _=p[v],w=_.name,S="bound ";if(w===S)continue;const k=_.name.substring(S.length),M=s.prototype[k];M&&(p[v]=M.bind(p))}}p.onAfterHotReloadFields&&p.onAfterHotReloadFields()}finally{f&&b&&Gg(g,b),f&&y&&(g.enabled=!0)}}}}catch(t){if(Po)console.error(t);else return!1}finally{Oc=!1,$s(Oi.Log,"Script changes applied (HMR)")}return!0}class P extends E{constructor(){super(...arguments),a(this,"guid")}static isDestroyed(e){return Mr(e)}static setActive(e,t,s=!0){e&&(wc(e,t),Yd(e),t&&s&&z_(ee.Current,e))}static isActiveSelf(e){return za(e)}static isActiveInHierarchy(e){return fw(e)}static markAsInstancedRendered(e,t){yw(e,t)}static isUsingInstancing(e){return ou(e)}static foreachComponent(e,t,s=!0){return Rr(e,t,s)}static instantiateSynced(e,t){return e?Jg(e,t):null}static instantiate(e,t=null){return"isAssetReference"in e,Wa(e,t)}static destroySynced(e,t,s=!0){if(!e)return;const n=e;t=t??ee.Current,mc(n,t.connection,s)}static destroy(e,t=!0){return Ei(e,t)}static add(e,t,s){if(!(!e||!t)){if(e===t){console.warn("Can not add object to self",e);return}s||(s=ee.Current),t.add(e),wc(e,!0),Yd(e),s?P.foreachComponent(e,n=>{Gg(n,s),!n.__internalDidAwakeAndStart&&s.new_script_start.includes(n)===!1&&s.new_script_start.push(n)},!0):console.warn("Missing context")}}static remove(e){var t;e&&((t=e.parent)==null||t.remove(e),wc(e,!1),Yd(e),P.foreachComponent(e,s=>{kM(s)},!0))}static invokeOnChildren(e,t,...s){this.invoke(e,t,!0,s)}static invoke(e,t,s=!1,...n){e&&this.foreachComponent(e,r=>{const l=r[t];l&&typeof l=="function"&&l?.call(r,...n)},s)}static addNewComponent(e,t,s,n=!0){return Ti(e,t,s,{callAwake:n})}static addComponent(e,t,s,n){return Ti(e,t,s,n)}static moveComponent(e,t){return Ti(e,t)}static removeComponent(e){return cf(e.gameObject,e),e}static getOrAddComponent(e,t){return fc(e,t)}static getComponent(e,t){return e===null?null:Or(e,t)}static getComponents(e,t,s=null){return e===null?s??[]:yc(e,t,s)}static findByGuid(e,t){return hf(e,t)}static findObjectOfType(e,t,s=!0){return _c(e,t??ee.Current,s)}static findObjectsOfType(e,t){const s=[];return gw(e,s,t),s}static getComponentInChildren(e,t){return vc(e,t)}static getComponentsInChildren(e,t,s=null){return Ua(e,t,s??void 0)}static getComponentInParent(e,t){return bc(e,t)}static getComponentsInParent(e,t,s=null){return iu(e,t,s)}static getAllComponents(e){var t;const s=(t=e.userData)==null?void 0:t.components;return s?[...s]:[]}static*iterateComponents(e){var t;const s=(t=e?.userData)==null?void 0:t.components;if(s&&Array.isArray(s))for(let n=0;n<s.length;n++)yield s[n]}}const _u=class gm{constructor(e){a(this,"__context"),a(this,"__name"),a(this,"gameObject"),a(this,"guid","invalid"),a(this,"sourceId"),a(this,"__didAwake",!1),a(this,"__didStart",!1),a(this,"__didEnable",!1),a(this,"__isEnabled"),a(this,"__destroyed",!1),a(this,"_eventListeners",new Map),this.__didAwake=!1,this.__didStart=!1,this.__didEnable=!1,this.__isEnabled=void 0,this.__destroyed=!1,this._internalInit(e),Ef()&&nx(this)}get isComponent(){return!0}get context(){return this.__context??ee.Current}set context(e){this.__context=e}get scene(){return this.context.scene}get layer(){var e,t;return(t=(e=this.gameObject)==null?void 0:e.userData)==null?void 0:t.layer}get name(){var e,t;return(e=this.gameObject)!=null&&e.name?this.gameObject.name:(t=this.gameObject)==null?void 0:t.userData.name}set name(e){this.gameObject?(this.gameObject.userData||(this.gameObject.userData={}),this.gameObject.userData.name=e,this.__name=e):this.__name=e}get tag(){var e;return(e=this.gameObject)==null?void 0:e.userData.tag}set tag(e){this.gameObject&&(this.gameObject.userData||(this.gameObject.userData={}),this.gameObject.userData.tag=e)}get static(){var e;return(e=this.gameObject)==null?void 0:e.userData.static}set static(e){this.gameObject&&(this.gameObject.userData||(this.gameObject.userData={}),this.gameObject.userData.static=e)}get activeAndEnabled(){return!(this.destroyed||this.__isEnabled===!1||!this.__isActiveInHierarchy)}get __isActive(){return this.gameObject.visible}get __isActiveInHierarchy(){if(!this.gameObject)return!1;const e=this.gameObject[En];return e===void 0?!0:e}set __isActiveInHierarchy(e){this.gameObject&&(this.gameObject[En]=e)}awake(){}onEnable(){}onDisable(){}onDestroy(){this.__destroyed=!0}startCoroutine(e,t=Oe.Update){return this.context.registerCoroutineUpdate(this,e,t)}stopCoroutine(e,t=Oe.Update){this.context.unregisterCoroutineUpdate(e,t)}get destroyed(){return this.__destroyed}destroy(){this.__destroyed||this.__internalDestroy()}get __internalDidAwakeAndStart(){return this.__didAwake&&this.__didStart}__internalNewInstanceCreated(e){return this.__didAwake=!1,this.__didStart=!1,this.__didEnable=!1,this.__isEnabled=void 0,this.__destroyed=!1,this._internalInit(e),this}_internalInit(e){if(typeof e=="object")for(const t of Object.keys(e)){const s=e[t];typeof s!="function"&&(this[t]=s)}}__internalAwake(){this.__didAwake||(this.__didAwake=!0,this.awake())}__internalStart(){this.__didStart||(this.__didStart=!0,this.start&&this.start())}__internalEnable(e){return this.__destroyed?(F()&&console.warn("[Needle Engine Dev] Trying to enable destroyed component"),!1):this.__didAwake?this.__didEnable?(e!==!0&&(this.__isEnabled=!0),!1):(this.__didEnable=!0,this.__isEnabled=!0,this.onEnable(),!0):!1}__internalDisable(e){if(this.__didAwake){if(!this.__didEnable){e!==!0&&(this.__isEnabled=!1);return}this.__didEnable=!1,this.__isEnabled=!1,this.onDisable()}}__internalDestroy(){var e;this.__destroyed||(this.__destroyed=!0,this.__didAwake&&((e=this.onDestroy)==null||e.call(this),this.dispatchEvent(new CustomEvent("destroyed",{detail:this}))),uw(this),Ef()&&ox(this))}get enabled(){return typeof this.__isEnabled=="boolean"?this.__isEnabled:!0}set enabled(e){if(this.__destroyed){F()&&console.warn(`[Needle Engine Dev] Trying to ${e?"enable":"disable"} destroyed component`);return}if(typeof e=="number"&&(e>=.5?e=!0:e=!1),!this.__didAwake){this.__isEnabled=e;return}e?this.__internalEnable():this.__internalDisable()}get worldPosition(){return te(this.gameObject)}set worldPosition(e){lt(this.gameObject,e)}setWorldPosition(e,t,s){fr(this.gameObject,e,t,s)}get worldQuaternion(){return Se(this.gameObject)}set worldQuaternion(e){Qi(this.gameObject,e)}setWorldQuaternion(e,t,s,n){rg(this.gameObject,e,t,s,n)}get worldEuler(){return ag(this.gameObject)}set worldEuler(e){lg(this.gameObject,e)}get worldRotation(){return this.gameObject.worldRotation}set worldRotation(e){this.setWorldRotation(e.x,e.y,e.z,!0)}setWorldRotation(e,t,s,n=!0){Yl(this.gameObject,e,t,s,n)}get forward(){return gm._forward.set(0,0,-1).applyQuaternion(this.worldQuaternion)}get right(){return gm._right.set(1,0,0).applyQuaternion(this.worldQuaternion)}get up(){return gm._up.set(0,1,0).applyQuaternion(this.worldQuaternion)}addEventListener(e,t){this._eventListeners[e]=this._eventListeners[e]||[],this._eventListeners[e].push(t)}removeEventListener(e,t){if(!this._eventListeners[e])return;const s=this._eventListeners[e].indexOf(t);s>=0&&this._eventListeners[e].splice(s,1)}dispatchEvent(e){if(!e||!this._eventListeners[e.type])return!1;const t=this._eventListeners[e.type];for(let s=0;s<t.length;s++)t[s](e);return!1}};a(_u,"_forward",new x),a(_u,"_right",new x),a(_u,"_up",new x);let I=_u;const zR=Object.freeze(Object.defineProperty({__proto__:null,Behaviour:I,Component:I,GameObject:P},Symbol.toStringTag,{value:"Module"}));var NR=Object.defineProperty,ax=(o,e,t,s)=>{for(var n=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=l(e,t,n)||n);return n&&NR(e,t,n),n};class Mc extends I{constructor(){super(...arguments),a(this,"from"),a(this,"to"),a(this,"width",0),a(this,"centered",!0),a(this,"_centerPos")}awake(){this._centerPos=new x}update(){if(!this.from||!this.to)return;const e=te(this.from).clone(),t=te(this.to).clone(),s=e.distanceTo(t);this._centerPos.copy(e),this._centerPos.add(t),this._centerPos.multiplyScalar(.5),lt(this.gameObject,this.centered?this._centerPos:e),this.gameObject.lookAt(te(this.to).clone()),this.gameObject.scale.set(this.width,this.width,s)}}ax([m(P)],Mc.prototype,"from"),ax([m(P)],Mc.prototype,"to");var WR=Object.defineProperty,VR=Object.getOwnPropertyDescriptor,Lr=(o,e,t,s)=>{for(var n=s>1?void 0:s?VR(e,t):e,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=(s?l(e,t,n):l(n))||n);return s&&n&&WR(e,t,n),n};const Oo=C("debuganimation");let lx=class{constructor(){a(this,"x"),a(this,"y")}};class Bt extends I{constructor(){super(...arguments),a(this,"playAutomatically",!0),a(this,"randomStartTime",!0),a(this,"minMaxSpeed"),a(this,"minMaxOffsetNormalized"),a(this,"loop",!0),a(this,"clampWhenFinished",!1),a(this,"_tempAnimationClipBeforeGameObjectExisted",null),a(this,"_tempAnimationsArray"),a(this,"mixer"),a(this,"_actions"),a(this,"_handles")}get isAnimationComponent(){return!0}addClip(e){this.animations||(this.animations=[]),this.animations.push(e)}get time(){if(this.actions){for(const e of this.actions)if(e.isRunning())return e.time}return 0}set time(e){if(this.actions)for(const t of this.actions)t.time=e}get clip(){var e;return(e=this.animations)!=null&&e.length?this.animations[0]:null}set clip(e){if(!this.__didAwake){Oo&&console.warn("Assign clip during serialization",e),this._tempAnimationClipBeforeGameObjectExisted=e;return}e&&(this.gameObject.animations||(this.gameObject.animations=[]),!this.animations.includes(e)&&(this.animations.length>0?this.animations.splice(0,0,e):this.animations.push(e)))}set clips(e){this.animations=e}set animations(e){e==null||!Array.isArray(e)||(this.gameObject?this.gameObject.animations=e:this._tempAnimationsArray=e)}get animations(){return this.gameObject.animations||this._tempAnimationsArray||[]}get actions(){return this._actions}set actions(e){this._actions=e}awake(){this.mixer=void 0,Oo&&console.log("Animation Awake",this.name,this),this._tempAnimationsArray&&(this.animations=this._tempAnimationsArray,this._tempAnimationsArray=void 0),this._tempAnimationClipBeforeGameObjectExisted&&(this.clip=this._tempAnimationClipBeforeGameObjectExisted,this._tempAnimationClipBeforeGameObjectExisted=null),this.actions=[],this._handles=[]}onEnable(){var e;if(this.playAutomatically&&((e=this.animations)==null?void 0:e.length)>0){const t=Math.floor(Math.random()*this.animations.length),s=this.animations[t];this.play(t,{exclusive:!0,fadeDuration:0,startTime:this.randomStartTime?Math.random()*s.duration:0,loop:this.loop,clampWhenFinished:this.clampWhenFinished})}}update(){this.mixer&&(this.mixer.update(this.context.time.deltaTime),this._handles.forEach(e=>e.update()))}onDisable(){this.mixer&&this.mixer.stopAllAction()}onDestroy(){this.context.animations.unregisterAnimationMixer(this.mixer)}getAction(e){var t;return((t=this.actions)==null?void 0:t.find(s=>s.getClip().name===e))||null}get isPlaying(){if(this.actions){for(let e=0;e<this.actions.length;e++)if(this.actions[e].isRunning())return!0}return!1}stopAll(e){if(this.actions)for(const t of this.actions)e!=null&&e.fadeDuration?t.fadeOut(e.fadeDuration):t.stop()}stop(e,t){if(e===void 0){this.stopAll();return}else if(typeof e=="number"){if(e>=this.animations.length){Oo&&console.log("No animation at index",e);return}e=this.animations[e]}else typeof e=="string"&&(e=this.animations.find(n=>n.name===e));if(!e){console.error("Could not find clip",e);return}const s=this.actions.find(n=>n.getClip()===e);if(!s){console.error("Could not find action",e);return}t!=null&&t.fadeDuration?s.fadeOut(t.fadeDuration):s.stop()}pause(e,t=!1){if(e===void 0){for(const n of this.actions)n.paused=!t;return}else if(typeof e=="number"){if(e>=this.animations.length){Oo&&console.log("No animation at index",e);return}e=this.animations[e]}else typeof e=="string"&&(e=this.animations.find(n=>n.name===e));if(!e){console.error("Could not find clip",e);return}const s=this.actions.find(n=>n.getClip()===e);if(!s){console.error("Could not find action",e);return}s.paused=!t}resume(){for(const e of this.actions)e.paused=!1}play(e=0,t){if(Oo&&console.log("PLAY",e),this.ensureMixer(),!this.mixer){Oo&&console.warn("Missing mixer",this);return}e===void 0&&(e=0);let s=e;if(typeof e=="number"){if(e>=this.animations.length){Oo&&console.log("No animation at index",e);return}s=this.animations[e]}else typeof e=="string"&&(s=this.animations.find(r=>r.name===e));if(!s){console.error("Could not find clip",e);return}t||(t={});for(const r of this.actions)if(r.getClip()===s)return this.internalOnPlay(r,t);if(!s.tracks){console.warn("Clip is no AnimationClip",s);return}const n=this.mixer.clipAction(s);return this.actions.push(n),this.internalOnPlay(n,t)}internalOnPlay(e,t){var s=this.actions.find(r=>r===e);if(s===e&&s.isRunning()&&s.time<s.getClip().duration){const r=this.tryFindHandle(e);if(s.paused&&(s.paused=!1),r)return r.waitForFinish()}if(t.loop===void 0&&(t.loop=this.loop),t.clampWhenFinished===void 0&&(t.clampWhenFinished=this.clampWhenFinished),t.minMaxOffsetNormalized===void 0&&this.randomStartTime&&(t.minMaxOffsetNormalized=this.minMaxOffsetNormalized),t.minMaxSpeed===void 0&&(t.minMaxSpeed=this.minMaxSpeed),t?.exclusive??!0)for(const r of this.actions)r!=s&&(t.fadeDuration?r.fadeOut(t.fadeDuration):r.stop());if(t!=null&&t.fadeDuration&&e.fadeIn(t.fadeDuration),e.enabled=!0,t?.startTime!=null)e.time=t.startTime;else if(t!=null&&t.minMaxOffsetNormalized&&t.minMaxOffsetNormalized.x!=0&&t.minMaxOffsetNormalized.y!=0){const r=e.getClip();e.time=W.lerp(t.minMaxOffsetNormalized.x,t.minMaxOffsetNormalized.y,Math.random())*r.duration}else e.time>=e.getClip().duration&&(e.time=0);t!=null&&t.minMaxSpeed?e.timeScale=W.lerp(t.minMaxSpeed.x,t.minMaxSpeed.y,Math.random()):e.timeScale=t?.speed??1,t?.loop!=null?e.loop=t.loop?HC:Mm:e.loop=Mm,t!=null&&t.clampWhenFinished&&(e.clampWhenFinished=!0),e.paused=!1,e.play(),Oo&&console.log("PLAY",e.getClip().name,e);const n=new HR(e,this.mixer,t,r=>{this._handles.splice(this._handles.indexOf(n),1)});return this._handles.push(n),n.waitForFinish()}tryFindHandle(e){for(const t of this._handles)if(t.action===e)return t}ensureMixer(){if(!this.mixer){const e="animationMixer";this.gameObject[e]&&(this.mixer=this.gameObject[e]),(!this.mixer||!this.mixer.clipAction)&&(this.mixer=new Rm(this.gameObject),this.gameObject[e]=this.mixer)}this.context.animations.registerAnimationMixer(this.mixer)}}Lr([m()],Bt.prototype,"playAutomatically",2),Lr([m()],Bt.prototype,"randomStartTime",2),Lr([m(lx)],Bt.prototype,"minMaxSpeed",2),Lr([m(lx)],Bt.prototype,"minMaxOffsetNormalized",2),Lr([m()],Bt.prototype,"loop",2),Lr([m()],Bt.prototype,"clampWhenFinished",2),Lr([m(mo)],Bt.prototype,"clips",1);class HR{constructor(e,t,s,n){a(this,"mixer"),a(this,"action"),a(this,"promise",null),a(this,"_options"),a(this,"_resolveCallback",null),a(this,"_resolvedOrRejectedCallback"),a(this,"onFinished",r=>{r.action===this.action&&this.onResolve()}),this.action=e,this.mixer=t,this._resolvedOrRejectedCallback=n,this._options=s}waitForFinish(){return this.promise?this.promise:(this.promise=new Promise(e=>{this._resolveCallback=e}),this.mixer.addEventListener("finished",this.onFinished),this.promise)}update(){this._options&&this._options.endTime!==void 0&&this.action.time>this._options.endTime&&(this._options.loop===!0?this.action.time=this._options.startTime??0:(this.action.time=this._options.endTime,this.action.timeScale=0,this.onResolve()))}onResolve(){var e,t;this.dispose(),(e=this._resolvedOrRejectedCallback)==null||e.call(this,this),(t=this._resolveCallback)==null||t.call(this,this.action)}dispose(){this.mixer.removeEventListener("finished",this.onFinished)}}const wu=Symbol("objectIsAnimatedData");function cx(o,e,t){if(!o)return;if(o[wu]===void 0){if(!t)return;o[wu]=new Set}const s=o[wu];t?s.add(e):s.has(e)&&s.delete(e)}function $R(o){if(!o)return!1;const e=o[wu];return e!==void 0&&e.size>0}class GR{constructor(){a(this,"_context")}get context(){return this._context??ee.Current}get isStateMachineBehaviour(){return!0}}class Rc{constructor(e,t,s,n){a(this,"name"),a(this,"nameHash"),a(this,"normalizedTime"),a(this,"length"),a(this,"speed"),a(this,"action"),a(this,"hasTransitions");var r;this.name=e.name,this.nameHash=e.hash,this.normalizedTime=t,this.length=s,this.speed=n,this.action=e.motion.action||null,this.hasTransitions=((r=e.transitions)==null?void 0:r.length)>0||!1}}function hx(o,e){return{name:"Empty",isLooping:!1,guid:e?.generateUUID()??Cn.generateUUID(),index:-1,clip:new mo(o,0,[])}}var ko=(o=>(o[o.If=1]="If",o[o.IfNot=2]="IfNot",o[o.Greater=3]="Greater",o[o.Less=4]="Less",o[o.Equals=6]="Equals",o[o.NotEqual=7]="NotEqual",o))(ko||{}),Af=(o=>(o[o.Float=1]="Float",o[o.Int=3]="Int",o[o.Bool=4]="Bool",o[o.Trigger=9]="Trigger",o))(Af||{});const ht=C("debuganimatorcontroller"),xu=C("debugrootmotion");class us{constructor(e){a(this,"_speed",1),a(this,"normalizedStartOffset",0),a(this,"animator"),a(this,"model"),a(this,"_mixer"),a(this,"_activeState"),a(this,"_activeStates",[]),a(this,"_heldActions",[]),a(this,"rootMotionHandler"),this.model=e,ht&&console.log(this)}static createFromClips(e,t={looping:!1,autoTransition:!0,transitionDuration:0}){const s=[];for(let r=0;r<e.length;r++){const l=e[r],c=[];if(t.autoTransition!==!1){const d=t.transitionDuration??0,u=d/l.duration;let p=r;(t.autoTransition===void 0||t.autoTransition===!0)&&(p=(r+1)%e.length),c.push({exitTime:1-u,offset:0,duration:d,hasExitTime:!0,destinationState:p,conditions:[]})}const h={name:l.name,hash:r,motion:{name:l.name,clip:l,isLooping:t?.looping??!1},transitions:c,behaviours:[]};s.push(h)}const n={name:"AnimatorController",guid:new Lt(Date.now()).generateUUID(),parameters:[],layers:[{name:"Base Layer",stateMachine:{defaultState:0,states:s}}]};return new us(n)}play(e,t=-1,s=Number.NEGATIVE_INFINITY,n=0){if(t<0)t=0;else if(t>=this.model.layers.length){console.warn("invalid layer");return}const r=this.model.layers[t].stateMachine;for(const l of r.states)if(l.name===e||l.hash===e){ht&&console.log("transition to ",l),this.transitionTo(l,n,s);return}console.warn("Could not find "+e+" to play")}reset(){this.setStartTransition()}setBool(e,t){var s,n;const r=typeof e=="string"?"name":"hash";return(n=(s=this.model)==null?void 0:s.parameters)==null?void 0:n.filter(l=>l[r]===e).forEach(l=>l.value=t)}getBool(e){var t,s,n;const r=typeof e=="string"?"name":"hash";return((n=(s=(t=this.model)==null?void 0:t.parameters)==null?void 0:s.find(l=>l[r]===e))==null?void 0:n.value)??!1}setFloat(e,t){var s,n;const r=typeof e=="string"?"name":"hash",l=(n=(s=this.model)==null?void 0:s.parameters)==null?void 0:n.filter(c=>c[r]===e);return l.forEach(c=>c.value=t),l?.length>0}getFloat(e){var t,s,n;const r=typeof e=="string"?"name":"hash";return((n=(s=(t=this.model)==null?void 0:t.parameters)==null?void 0:s.find(l=>l[r]===e))==null?void 0:n.value)??0}setInteger(e,t){var s,n;const r=typeof e=="string"?"name":"hash";return(n=(s=this.model)==null?void 0:s.parameters)==null?void 0:n.filter(l=>l[r]===e).forEach(l=>l.value=t)}getInteger(e){var t,s,n;const r=typeof e=="string"?"name":"hash";return((n=(s=(t=this.model)==null?void 0:t.parameters)==null?void 0:s.find(l=>l[r]===e))==null?void 0:n.value)??0}setTrigger(e){var t,s;ht&&console.log("SET TRIGGER",e);const n=typeof e=="string"?"name":"hash";return(s=(t=this.model)==null?void 0:t.parameters)==null?void 0:s.filter(r=>r[n]===e).forEach(r=>r.value=!0)}resetTrigger(e){var t,s;const n=typeof e=="string"?"name":"hash";return(s=(t=this.model)==null?void 0:t.parameters)==null?void 0:s.filter(r=>r[n]===e).forEach(r=>r.value=!1)}getTrigger(e){var t,s,n;const r=typeof e=="string"?"name":"hash";return((n=(s=(t=this.model)==null?void 0:t.parameters)==null?void 0:s.find(l=>l[r]===e))==null?void 0:n.value)??!1}isInTransition(){return this._activeStates.length>1}setSpeed(e){this._speed=e}FindState(e){return this.findState(e)}findState(e){if(!e)return null;if(Array.isArray(this.model.layers)){for(const t of this.model.layers)for(const s of t.stateMachine.states)if(s.name===e||s.hash==e)return s}return null}getCurrentStateInfo(){if(!this._activeState)return null;const e=this._activeState.motion.action;if(!e)return null;const t=this._activeState.motion.clip.duration,s=t<=0?0:Math.abs(e.time/t);return new Rc(this._activeState,s,t,this._speed)}get currentAction(){return this._activeState&&this._activeState.motion.action||null}get context(){var e;return(e=this.animator)==null?void 0:e.context}get mixer(){return this._mixer}dispose(){var e;if(this._mixer.stopAllAction(),this.animator){this._mixer.uncacheRoot(this.animator.gameObject);for(const t of this._activeStates)t.motion.clip&&this.mixer.uncacheAction(t.motion.clip,this.animator.gameObject)}(e=this.context)==null||e.animations.unregisterAnimationMixer(this._mixer)}bind(e){var t,s;e?this.animator!==e&&(this._mixer&&(this._mixer.stopAllAction(),(t=this.context)==null||t.animations.unregisterAnimationMixer(this._mixer)),this.animator=e,this._mixer=new Rm(this.animator.gameObject),(s=this.context)==null||s.animations.registerAnimationMixer(this._mixer),this.createActions(this.animator)):console.error("AnimatorController.bind: animator is null")}clone(){if(typeof this.model=="string")return console.warn("AnimatorController has not been resolved, can not create model from string",this.model),null;ht&&console.warn("AnimatorController clone()",this.model);const e=$l(this.model,(t,s,n)=>n==null?!0:!(n.type==="Object3D"||n.isObject3D===!0||Eb(n)||n.tracks!==void 0||n instanceof us));return console.assert(e!==this.model),new us(e)}update(e){var t,s;if(!this.animator)return;this.evaluateTransitions(),this.updateActiveStates(e);const n=this.animator.context.time.deltaTime;this.animator.applyRootMotion&&((t=this.rootMotionHandler)==null||t.onBeforeUpdate(e)),this._mixer.update(n),this.animator.applyRootMotion&&((s=this.rootMotionHandler)==null||s.onAfterUpdate(e))}get activeState(){return this._activeState}updateActiveStates(e){for(let t=0;t<this._activeStates.length;t++){const s=this._activeStates[t],n=s.motion;if(!n.action)this._activeStates.splice(t,1),t--;else{const r=n.action;r.weight=e,r.getEffectiveWeight()<=0&&!r.isRunning()&&(ht&&console.debug("REMOVE",s.name,r.getEffectiveWeight(),r.isRunning(),r.isScheduled()),this._activeStates.splice(t,1),t--)}}}setStartTransition(){var e;this.model.layers.length>1&&(ht||F())&&console.warn("Multiple layers are not supported yet "+((e=this.animator)==null?void 0:e.name));for(const t of this.model.layers){const s=t.stateMachine;s.defaultState===void 0&&(ht&&console.warn("AnimatorController default state is undefined, will assign state 0 as default",t),s.defaultState=0);const n=s.states[s.defaultState];this.transitionTo(n,0,this.normalizedStartOffset);break}}evaluateTransitions(){var e;let t=!1;if(!this._activeState){if(this.setStartTransition(),!this._activeState)return;t=!0}const s=this._activeState,n=s.motion.action;for(const l of s.transitions){if(!l.hasExitTime&&l.conditions.length<=0)continue;let c=!0;for(const h of l.conditions)if(!this.evaluateCondition(h)){c=!1;break}if(c)if(n){const h=s.motion.clip.duration,d=h<=0?1:Math.abs(n.time/h);let u=l.exitTime;n.timeScale<0&&(u=1-u);let p=!1;if(l.hasExitTime?n.timeScale>0?p=d>=l.exitTime:n.timeScale<0&&(p=1-d>=l.exitTime):p=!0,p){for(const g of l.conditions){const f=this.model.parameters.find(y=>y.name===g.parameter);f?.type===Af.Trigger&&f.value&&(f.value=!1)}if(n.clampWhenFinished=!0,ht){const g=this.getState(l.destinationState,0);console.log(`Transition to ${l.destinationState} / ${g?.name}`,l,`
856
+ Timescale: `+n.timeScale,`
857
+ Normalized time: `+d.toFixed(3),`
858
+ Exit Time: `+u,l.hasExitTime)}this.transitionTo(l.destinationState,l.duration,l.offset);return}}else{this.transitionTo(l.destinationState,l.duration,l.offset);return}}n&&this.setTimescale(n,s);let r=!1;if(s.motion.isLooping&&n&&(n.time>=n.getClip().duration?(r=!0,n.reset(),n.time=0,n.play()):n.time<=0&&n.timeScale<0&&(r=!0,n.reset(),n.time=n.getClip().duration,n.play())),!r&&s&&!t&&n&&this.animator&&s.behaviours){const l=n?.getClip().duration,c=n.time/l,h=new Rc(this._activeState,c,l,this._speed);for(const d of s.behaviours)d.instance&&((e=d.instance.onStateUpdate)==null||e.call(d.instance,this.animator,h,0))}}setTimescale(e,t){let s=t.speed??1;t.speedParameter&&(s*=this.getFloat(t.speedParameter)),s!==void 0&&(e.timeScale=s*this._speed)}getState(e,t){return typeof e=="number"&&(e==-1&&(e=this.model.layers[t].stateMachine.defaultState,e===void 0&&(ht&&console.warn("AnimatorController default state is undefined: ",this.model,"Layer: "+t),e=0)),e=this.model.layers[t].stateMachine.states[e]),e}releaseHeldActions(e){for(const t of this._heldActions)t.fadeOut(e);this._heldActions.length=0}transitionTo(e,t,s){var n,r,l,c,h,d,u,p;if(!this.animator)return;const g=0;if(e=this.getState(e,g),!(e!=null&&e.motion)||!e.motion.clip||!(e.motion.clip instanceof mo))return;const f=this._activeState===e;if(f){const w=e.motion;if(!w.action_loopback&&w.clip){const S=this.rootMotionHandler?this.animator.gameObject.matrix.clone():null;this._mixer.uncacheAction(w.clip,this.animator.gameObject),S&&S.decompose(this.animator.gameObject.position,this.animator.gameObject.quaternion,this.animator.gameObject.scale),w.action_loopback=this.createAction(w.clip)}}if((n=this._activeState)!=null&&n.behaviours&&this._activeState.motion.action){const w=(r=this._activeState)==null?void 0:r.motion.clip.duration,S=this._activeState.motion.action.time/w,k=new Rc(this._activeState,S,w,this._speed);for(const M of this._activeState.behaviours)(c=(l=M.instance)==null?void 0:l.onStateExit)==null||c.call(M.instance,this.animator,k,g)}const y=(h=this._activeState)==null?void 0:h.motion.action;f&&(e.motion.action=e.motion.action_loopback,e.motion.action_loopback=y);const b=this._activeState;this._activeState=e;const v=(d=e.motion)==null?void 0:d.action,_=e.motion.clip;if(_?.duration<=0&&_.tracks.length<=0?y&&this._heldActions.push(y):y&&(y.fadeOut(t),this.releaseHeldActions(t)),v){if(s=Math.max(0,Math.min(1,s)),e.cycleOffsetParameter){let S=this.getFloat(e.cycleOffsetParameter);typeof S=="number"?(S<0&&(S+=1),s+=S,s%=1):ht&&console.warn("AnimatorController cycle offset parameter is not a number",e.cycleOffsetParameter)}else typeof e.cycleOffset=="number"&&(s+=e.cycleOffset,s%=1);v.isRunning()&&v.stop(),v.reset(),v.enabled=!0,this.setTimescale(v,e);const w=e.motion.clip.duration;if(v.time=f?0:s*w,v.timeScale<0&&(v.time=w-v.time),v.clampWhenFinished=!0,v.setLoop(Mm,0),t>0?v.fadeIn(t):v.weight=1,v.play(),this.rootMotionHandler&&this.rootMotionHandler.onStart(v),this._activeStates.includes(e)||this._activeStates.push(e),this._activeState.behaviours){const S=new Rc(e,s,w,this._speed);for(const k of this._activeState.behaviours)(p=(u=k.instance)==null?void 0:u.onStateEnter)==null||p.call(k.instance,this.animator,S,g)}}else ht&&(e.__warned_no_motion||(e.__warned_no_motion=!0,console.warn("No action",e.motion,this)));ht&&console.log("TRANSITION FROM "+b?.name+" TO "+e.name,t,y,v,v?.getEffectiveTimeScale(),v?.getEffectiveWeight(),v?.isRunning(),v?.isScheduled(),v?.paused)}createAction(e){var t,s;if(this._mixer.existingAction(e)&&this._mixer.uncacheAction(e,(t=this.animator)==null?void 0:t.gameObject),(s=this.animator)!=null&&s.applyRootMotion){this.rootMotionHandler||(this.rootMotionHandler=new XR(this));const n=this.animator.gameObject;return this.rootMotionHandler.createClip(this._mixer,n,e)}else return this._mixer.clipAction(e)}evaluateCondition(e){const t=this.model.parameters.find(s=>s.name===e.parameter);if(!t)return!1;switch(e.mode){case ko.If:return t.value===!0;case ko.IfNot:return t.value===!1;case ko.Greater:return t.value>e.threshold;case ko.Less:return t.value<e.threshold;case ko.Equals:return t.value===e.threshold;case ko.NotEqual:return t.value!==e.threshold}return!1}createActions(e){var t,s,n,r;ht&&console.log("AnimatorController createActions",this.model);for(const l of this.model.layers){const c=l.stateMachine;for(let h=0;h<c.states.length;h++){const d=c.states[h];d.transitions||(d.transitions=[]);for(const u of d.transitions)u.conditions||(u.conditions=[]);if(d.motion||(ht&&console.warn("No motion",d),d.motion=hx(d.name)),this.animator&&d.motion.clips){const u=(t=d.motion.clips)==null?void 0:t.find(p=>{var g,f;return p.node.name===((f=(g=this.animator)==null?void 0:g.gameObject)==null?void 0:f.name)});u?d.motion.clip=u.clip:(ht||F())&&console.warn('Could not find clip for animator "'+((n=(s=this.animator)==null?void 0:s.gameObject)==null?void 0:n.name)+'"',d.motion.clips.map(p=>p.node.name))}if(!d.motion.clip){ht&&console.warn("No clip assigned to state",d);const u=new mo(void 0,void 0,[]);d.motion.clip=u}if((r=d.motion)!=null&&r.clip){const u=d.motion.clip;if(u instanceof mo){const p=this.createAction(u);d.motion.action=p}else(ht||F())&&console.warn("No valid animationclip assigned",d)}if(d.behaviours&&Array.isArray(d.behaviours))for(const u of d.behaviours){if(!(u!=null&&u.typeName))continue;const p=R.get(u.typeName);if(p){const g=new p;g.isStateMachineBehaviour&&(g._context=this.context??void 0,Fa(g,u.properties),u.instance=g),ht&&console.log("Created animator controller behaviour",d.name,u.typeName,u.properties,g)}else(ht||F())&&console.warn("Could not find AnimatorBehaviour type: "+u.typeName)}}}}*enumerateActions(){if(this.model.layers)for(const e of this.model.layers){const t=e.stateMachine;for(let s=0;s<t.states.length;s++){const n=t.states[s];n!=null&&n.motion&&(n.motion.action&&(yield n.motion.action),n.motion.action_loopback&&(yield n.motion.action_loopback))}}}}class dx{constructor(e,t){a(this,"track"),a(this,"createdInterpolant"),a(this,"originalEvaluate"),a(this,"customEvaluate"),this.track=e;const s=e,n=s.createInterpolant.bind(e);s.createInterpolant=()=>(s.createInterpolant=n,this.createdInterpolant=n(),this.originalEvaluate=this.createdInterpolant.evaluate.bind(this.createdInterpolant),this.customEvaluate=r=>{if(!this.originalEvaluate)return;const l=this.originalEvaluate(r);return t(r,l)},this.createdInterpolant.evaluate=this.customEvaluate,this.createdInterpolant)}dispose(){this.createdInterpolant&&this.originalEvaluate&&(this.createdInterpolant.evaluate=this.originalEvaluate),this.track=void 0,this.createdInterpolant=null,this.originalEvaluate=void 0,this.customEvaluate=void 0}}const Mo=class Ot{constructor(e,t,s,n,r){if(a(this,"_action"),a(this,"root"),a(this,"clip"),a(this,"positionWrapper",null),a(this,"rotationWrapper",null),a(this,"context"),a(this,"positionChange",new x),a(this,"rotationChange",new H),a(this,"_prevTime",0),this.context=e,this.root=t,this.clip=s,Ot.firstKeyframeRotation[this.cacheId]||(Ot.firstKeyframeRotation[this.cacheId]=new H),r){const l=r.values;Ot.firstKeyframeRotation[this.cacheId].set(l[0],l[1],l[2],l[3])}Ot.spaceRotation[this.cacheId]||(Ot.spaceRotation[this.cacheId]=new H),Ot.effectiveSpaceRotation[this.cacheId]||(Ot.effectiveSpaceRotation[this.cacheId]=new H),Ot.clipOffsetRotation[this.cacheId]=new H,r&&Ot.clipOffsetRotation[this.cacheId].set(r.values[0],r.values[1],r.values[2],r.values[3]).invert(),this.handlePosition(s,n),this.handleRotation(s,r)}set action(e){this._action=e}get action(){return this._action}get cacheId(){return this.root.uuid}onStart(e){if(e.getClip()!==this.clip)return;Ot.lastObjRotation[this.cacheId]||(Ot.lastObjRotation[this.cacheId]=this.root.quaternion.clone());const t=Ot.lastObjRotation[this.cacheId];if(Ot.spaceRotation[this.cacheId].copy(t),xu){const s=new jt().setFromQuaternion(t);console.log("START",this.clip.name,W.toDegrees(s.y),this.root.position.z)}}getClipRotationOffset(){return Ot.clipOffsetRotation[this.cacheId]}handlePosition(e,t){if(t){const s=this.root;xu&&s.add(new Si),Ot.lastObjPosition[this.cacheId]||(Ot.lastObjPosition[this.cacheId]=this.root.position.clone());const n=new x,r=new x;this.positionWrapper=new dx(t,(l,c)=>{const h=this.action.getEffectiveWeight();return xu&&s.position.length()>8&&s.position.set(0,s.position.y,0),l>this._prevTime&&(n.set(c[0],c[1],c[2]),n.sub(r),n.multiplyScalar(h),n.applyQuaternion(this.getClipRotationOffset()),n.applyQuaternion(s.quaternion),this.positionChange.copy(n)),r.fromArray(c),this._prevTime=l,c[0]=0,c[1]=0,c[2]=0,c})}}handleRotation(e,t){if(t){if(xu){const l=t.values,c=new jt().setFromQuaternion(new H(l[0],l[1],l[2],l[3]));console.log(e.name,t.name,"FIRST ROTATION IN TRACK",W.toDegrees(c.y));const h=t.values.length-4,d=new H().set(l[h],l[h+1],l[h+2],l[h+3]),u=new jt().setFromQuaternion(d);console.log(e.name,t.name,"LAST ROTATION IN TRACK",W.toDegrees(u.y))}let s=0;const n=new H,r=new H;this.rotationWrapper=new dx(t,(l,c)=>(l>s&&(r.set(c[0],c[1],c[2],c[3]),n.invert(),r.multiply(n),this.rotationChange.copy(r)),n.fromArray(c),s=l,c[0]=0,c[1]=0,c[2]=0,c[3]=1,c))}}onBeforeUpdate(e){this.positionChange.set(0,0,0),this.rotationChange.set(0,0,0,1)}onAfterUpdate(e){return!this.action||(e*=this.action.getEffectiveWeight(),e<=0)?!1:(this.positionChange.multiplyScalar(e),this.rotationChange.slerp(Ot.identityQuaternion,1-e),!0)}};a(Mo,"lastObjPosition",{}),a(Mo,"lastObjRotation",{}),a(Mo,"firstKeyframeRotation",{}),a(Mo,"spaceRotation",{}),a(Mo,"effectiveSpaceRotation",{}),a(Mo,"clipOffsetRotation",{}),a(Mo,"identityQuaternion",new H);let qR=Mo;class XR{constructor(e){a(this,"controller"),a(this,"handler",[]),a(this,"root"),a(this,"basePosition",new x),a(this,"baseQuaternion",new H),a(this,"baseRotation",new jt),a(this,"summedPosition",new x),a(this,"summedRotation",new H),this.controller=e}createClip(e,t,s){this.root=t,t&&"name"in t&&t.name;const n=this.findRootTrack(s,".position"),r=this.findRootTrack(s,".quaternion"),l=new qR(this.controller.context,t,s,n,r);this.handler.push(l);const c=e.clipAction(s);return l.action=c,c}onStart(e){for(const t of this.handler)t.onStart(e)}onBeforeUpdate(e){this.basePosition.copy(this.root.position),this.baseQuaternion.copy(this.root.quaternion);for(const t of this.handler)t.onBeforeUpdate(e)}onAfterUpdate(e){if(!(e<=0)){this.root.position.copy(this.basePosition),this.root.quaternion.copy(this.baseQuaternion),this.summedPosition.set(0,0,0),this.summedRotation.set(0,0,0,1);for(const t of this.handler)t.onAfterUpdate(e)&&(this.summedPosition.add(t.positionChange),this.summedRotation.multiply(t.rotationChange));this.root.position.add(this.summedPosition),this.root.quaternion.multiply(this.summedRotation)}}findRootTrack(e,t){const s=e.tracks;if(!s)return null;for(const n of s)if(n.name.endsWith(t))return n;return null}}class QR extends Ji{onSerialize(e,t){}onDeserialize(e,t){if(t.type===us&&e?.__type==="AnimatorController")return new us(e)}}new QR(us);var YR=Object.defineProperty,KR=Object.getOwnPropertyDescriptor,Su=(o,e,t,s)=>{for(var n=s>1?void 0:s?KR(e,t):e,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=(s?l(e,t,n):l(n))||n);return s&&n&&YR(e,t,n),n};const es=C("debuganimator");class Mt extends I{constructor(){super(...arguments),a(this,"applyRootMotion",!1),a(this,"hasRootMotion",!1),a(this,"keepAnimatorControllerStateOnDisable",!1),a(this,"_parametersAreDirty",!1),a(this,"_isDirty",!1),a(this,"_speed",1),a(this,"_normalizedStartOffset",0),a(this,"_animatorController",null),a(this,"_initializeWithRuntimeAnimatorController")}get isAnimationComponent(){return!0}set runtimeAnimatorController(e){var t;this._animatorController&&this._animatorController.model===e||(e?e instanceof us?(e.animator&&e.animator!==this&&(console.warn("AnimatorController can not be bound to multiple animators",(t=e.model)==null?void 0:t.name),e.model||console.error("AnimatorController has no model"),e=new us(e.model)),this._animatorController=e,this._animatorController.bind(this)):(es&&console.log("Assign animator controller",e,this),this._animatorController=new us(e),this.__didAwake&&this._animatorController.bind(this)):this._animatorController=null)}get runtimeAnimatorController(){return this._animatorController}getCurrentStateInfo(){var e;return(e=this.runtimeAnimatorController)==null?void 0:e.getCurrentStateInfo()}get currentAction(){var e;return((e=this.runtimeAnimatorController)==null?void 0:e.currentAction)||null}get parametersAreDirty(){return this._parametersAreDirty}get isDirty(){return this._isDirty}Play(e,t=-1,s=Number.NEGATIVE_INFINITY,n=0){this.play(e,t,s,n)}play(e,t=-1,s=Number.NEGATIVE_INFINITY,n=0){var r;(r=this.runtimeAnimatorController)==null||r.play(e,t,s,n),this._isDirty=!0}Reset(){this.reset()}reset(){var e;(e=this._animatorController)==null||e.reset(),this._isDirty=!0}SetBool(e,t){this.setBool(e,t)}setBool(e,t){var s,n;es&&console.log("setBool",e,t),((s=this.runtimeAnimatorController)==null?void 0:s.getBool(e))!==t&&(this._parametersAreDirty=!0),(n=this.runtimeAnimatorController)==null||n.setBool(e,t)}GetBool(e){return this.getBool(e)}getBool(e){var t;const s=((t=this.runtimeAnimatorController)==null?void 0:t.getBool(e))??!1;return es&&console.log("getBool",e,s),s}toggleBool(e){this.setBool(e,!this.getBool(e))}SetFloat(e,t){this.setFloat(e,t)}setFloat(e,t){var s,n;((s=this.runtimeAnimatorController)==null?void 0:s.getFloat(e))!==t&&(this._parametersAreDirty=!0),es&&console.log("setFloat",e,t),(n=this.runtimeAnimatorController)==null||n.setFloat(e,t)}GetFloat(e){return this.getFloat(e)}getFloat(e){var t;const s=((t=this.runtimeAnimatorController)==null?void 0:t.getFloat(e))??-1;return es&&console.log("getFloat",e,s),s}SetInteger(e,t){this.setInteger(e,t)}setInteger(e,t){var s,n;((s=this.runtimeAnimatorController)==null?void 0:s.getInteger(e))!==t&&(this._parametersAreDirty=!0),es&&console.log("setInteger",e,t),(n=this.runtimeAnimatorController)==null||n.setInteger(e,t)}GetInteger(e){return this.getInteger(e)}getInteger(e){var t;const s=((t=this.runtimeAnimatorController)==null?void 0:t.getInteger(e))??-1;return es&&console.log("getInteger",e,s),s}SetTrigger(e){this.setTrigger(e)}setTrigger(e){var t;this._parametersAreDirty=!0,es&&console.log("setTrigger",e),(t=this.runtimeAnimatorController)==null||t.setTrigger(e)}ResetTrigger(e){this.resetTrigger(e)}resetTrigger(e){var t;this._parametersAreDirty=!0,es&&console.log("resetTrigger",e),(t=this.runtimeAnimatorController)==null||t.resetTrigger(e)}GetTrigger(e){this.getTrigger(e)}getTrigger(e){var t;const s=(t=this.runtimeAnimatorController)==null?void 0:t.getTrigger(e);return es&&console.log("getTrigger",e,s),s}IsInTransition(){return this.isInTransition()}isInTransition(){var e;return((e=this.runtimeAnimatorController)==null?void 0:e.isInTransition())??!1}SetSpeed(e){return this.setSpeed(e)}setSpeed(e){var t;e!==this._speed&&(es&&console.log("setSpeed",e),this._speed=e,((t=this._animatorController)==null?void 0:t.animator)==this&&this._animatorController.setSpeed(e))}set minMaxSpeed(e){var t;this._speed=W.lerp(e.x,e.y,Math.random()),((t=this._animatorController)==null?void 0:t.animator)==this&&this._animatorController.setSpeed(this._speed)}set minMaxOffsetNormalized(e){var t;this._normalizedStartOffset=W.lerp(e.x,e.y,Math.random()),((t=this.runtimeAnimatorController)==null?void 0:t.animator)==this&&(this.runtimeAnimatorController.normalizedStartOffset=this._normalizedStartOffset)}awake(){es&&console.log("ANIMATOR",this.name,this),this.gameObject&&this.initializeRuntimeAnimatorController()}initializeRuntimeAnimatorController(e=!1){const t=e||this.runtimeAnimatorController!==this._initializeWithRuntimeAnimatorController;if(this.runtimeAnimatorController&&t){const s=this.runtimeAnimatorController.clone();this._initializeWithRuntimeAnimatorController=s,s?(console.assert(this.runtimeAnimatorController!==s),this.runtimeAnimatorController=s,console.assert(this.runtimeAnimatorController===s),this.runtimeAnimatorController.bind(this),this.runtimeAnimatorController.setSpeed(this._speed),this.runtimeAnimatorController.normalizedStartOffset=this._normalizedStartOffset):console.warn("Could not clone animator controller",this.runtimeAnimatorController)}}onDisable(){var e;this.keepAnimatorControllerStateOnDisable||(e=this._animatorController)==null||e.reset()}onBeforeRender(){this._isDirty=!1,this._parametersAreDirty=!1,!$R(this.gameObject)&&this._animatorController&&this._animatorController.update(1)}}Su([m()],Mt.prototype,"applyRootMotion",2),Su([m()],Mt.prototype,"hasRootMotion",2),Su([m()],Mt.prototype,"keepAnimatorControllerStateOnDisable",2),Su([m()],Mt.prototype,"runtimeAnimatorController",1);const ux=Symbol("previous-visibility"),px=class td extends Hs{render(e,t,s){if("addPass"in s)this._unsupported_effectcomposer_warning||(console.warn("RenderTexture.render() does not yet support EffectComposer"),this._unsupported_effectcomposer_warning=!0);else if(s instanceof pr){this.onBeforeRender();const n=s.getRenderTarget(),r=s.xr.enabled;s.xr.enabled=!1,s.setRenderTarget(this),s.clear(!0,!0,!0),s.render(e,t),s.setRenderTarget(n),s.xr.enabled=r,this.onAfterRender()}}onBeforeRender(){td._userSet.clear();const e=Vg(this.texture,!0,null,td._userSet);for(const t of e)t instanceof q&&(t[ux]=t.visible,t.visible=!1)}onAfterRender(){for(const e of td._userSet)e instanceof q&&(e.visible=e[ux]);td._userSet.clear()}};a(px,"_userSet",new Set);let Tc=px;var ZR=Object.defineProperty,JR=Object.getOwnPropertyDescriptor,Ec=(o,e,t,s)=>{for(var n=s>1?void 0:s?JR(e,t):e,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=(s?l(e,t,n):l(n))||n);return s&&n&&ZR(e,t,n),n};const Cu=C("debuggroundprojection");class en extends I{constructor(){super(...arguments),a(this,"applyOnAwake",!1),a(this,"autoFit",!0),a(this,"_radius",50),a(this,"_height",3),a(this,"_arblending",0),a(this,"_lastBackground"),a(this,"_lastRadius"),a(this,"_lastHeight"),a(this,"_projection"),a(this,"_watcher"),a(this,"_needsTextureUpdate",!1),a(this,"_blurrynessShader",null),a(this,"_lastBlurriness",-1)}set radius(e){this._radius=e,this._projection&&this.updateProjection()}get radius(){return this._radius}set height(e){this._height=e,this._projection&&this.updateProjection()}get height(){return this._height}set arBlending(e){this._arblending=e,this._needsTextureUpdate=!0}get arBlending(){return this._arblending}awake(){this.applyOnAwake&&this.updateAndCreate()}onEnable(){this.context.time.frameCount>0&&this.applyOnAwake&&this.updateAndCreate(),this._watcher||(this._watcher=new lo(this.context.scene,"background"),this._watcher.subscribeWrite(e=>{Cu&&console.log("Background changed",this.context.scene.background),this._needsTextureUpdate=!0}))}onDisable(){var e,t;(e=this._watcher)==null||e.revoke(),(t=this._projection)==null||t.removeFromParent()}onEnterXR(){this.activeAndEnabled&&(this._needsTextureUpdate=!0,this.updateProjection())}async onLeaveXR(){this.activeAndEnabled&&(await Gl(1),this.updateProjection())}onBeforeRender(){this._projection&&this.scene.backgroundRotation&&this._projection.rotation.copy(this.scene.backgroundRotation),this.context.scene.backgroundBlurriness!==void 0&&this._lastBlurriness!=this.context.scene.backgroundBlurriness&&this.context.scene.backgroundBlurriness>.001?this.updateProjection():this._needsTextureUpdate&&this.context.scene.background instanceof De&&this.updateBlurriness(this.context.scene.background,this.context.scene.backgroundBlurriness)}updateAndCreate(){var e;this.updateProjection(),(e=this._watcher)==null||e.apply()}updateProjection(){var e,t,s,n,r,l;if(!this.context.scene.background){(e=this._projection)==null||e.removeFromParent();return}const c=this.context.scene.background;if(!(c instanceof De)){(t=this._projection)==null||t.removeFromParent();return}if(((s=this.context.xr)!=null&&s.isPassThrough||(n=this.context.xr)!=null&&n.isAR)&&this.arBlending===0){(r=this._projection)==null||r.removeFromParent();return}if(!this.gameObject||this.destroyed)return;let h=!0;const d=0,u=c!==this._lastBackground||this._height!==this._lastHeight||this._radius!==this._lastRadius;if(!this._projection||u){Cu&&console.log("Create/Update Ground Projection",c.name),(l=this._projection)==null||l.removeFromParent();try{this._projection=new Ca(c,this._height,this._radius,64)}catch(p){console.error("Error creating three GroundProjection",p);return}this._projection.position.y=this._height-d,this._projection.name="GroundProjection",cg(this._projection,!1)}else h=!1;if(this._projection.parent||this.gameObject.add(this._projection),this.autoFit&&h){this._projection.updateWorldMatrix(!0,!0);const p=ii(this.context.scene.children,[this._projection]),g=p.min.y;if(g<1/0){const f=X();f.x=p.min.x+(p.max.x-p.min.x)*.5;const y=Ge(this.gameObject).x;f.y=g+this._height*y-d,f.z=p.min.z+(p.max.z-p.min.z)*.5,lt(this._projection,f)}Cu&&G.DrawWireBox3(p,65280,5)}this.context.scene.backgroundBlurriness>.001&&this._needsTextureUpdate&&this.updateBlurriness(c,this.context.scene.backgroundBlurriness),this._lastBackground=c,this._lastHeight=this._height,this._lastRadius=this._radius,this._needsTextureUpdate=!1}updateBlurriness(e,t){var s;if(this._projection){if(!e)return}else return;this._needsTextureUpdate=!1,Cu&&console.log("Update Blurriness",t),this._blurrynessShader??(this._blurrynessShader=new Ws({name:"GroundProjectionBlurriness",uniforms:{map:{value:e},blurriness:{value:t},blending:{value:0},alphaFactor:{value:1}},vertexShader:eT,fragmentShader:tT})),this._blurrynessShader.depthWrite=!1,this._blurrynessShader.uniforms.map.value=e,this._blurrynessShader.uniforms.blurriness.value=t,this._lastBlurriness=t,e.needsUpdate=!0;const n=this._projection.material.transparent;this._projection.material.transparent=(((s=this.context.xr)==null?void 0:s.isAR)===!0&&this.arBlending>1e-6)??!1,this._projection.material.transparent?this._blurrynessShader.uniforms.blending.value=this.arBlending:this._blurrynessShader.uniforms.blending.value=0,this.context.isInPassThrough?this._blurrynessShader.uniforms.alphaFactor.value=.95:this._blurrynessShader.uniforms.alphaFactor.value=1,n!==this._projection.material.transparent&&(this._projection.material.needsUpdate=!0),this._projection.material.map=Kl.copyTexture(e,this._blurrynessShader),this._projection.material.depthTest=!0,this._projection.material.depthWrite=!1}}Ec([m()],en.prototype,"applyOnAwake",2),Ec([m()],en.prototype,"autoFit",2),Ec([m()],en.prototype,"radius",1),Ec([m()],en.prototype,"height",1),Ec([m()],en.prototype,"arBlending",1);const eT=`
859
+ varying vec2 vUv;
860
+
861
+ void main() {
862
+ vUv = uv;
863
+ gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
864
+ }
865
+ `,tT=`
866
+ uniform sampler2D map;
867
+ uniform float blurriness;
868
+ uniform float alphaFactor;
869
+ uniform float blending;
870
+ varying vec2 vUv;
871
+
872
+ const float PI = 3.14159265359;
873
+
874
+ // Gaussian function
875
+ float gaussian(float x, float sigma) {
876
+ return exp(-(x * x) / (2.0 * sigma * sigma)) / (sqrt(2.0 * PI) * sigma);
877
+ }
878
+
879
+ // Custom smoothstep function for desired falloff
880
+ float customSmoothstep(float edge0, float edge1, float x) {
881
+ float t = clamp((x - edge0) / (edge1 - edge0), 0.0, 1.0);
882
+ return t * t * (3.0 - 2.0 * t);
883
+ }
884
+
885
+ void main() {
886
+ vec2 center = vec2(0.0, 0.0);
887
+ vec2 pos = vUv;
888
+ pos.x = 0.0; // Only consider vertical distance
889
+ float distance = length(pos - center);
890
+
891
+ // Calculate blur amount based on custom falloff
892
+ float blurAmount = customSmoothstep(0.5, 1.0, distance * 2.0);
893
+ blurAmount = clamp(blurAmount, 0.0, 1.0); // Ensure blur amount is within valid range
894
+
895
+ // Gaussian blur
896
+ vec2 pixelSize = 1.0 / vec2(textureSize(map, 0));
897
+ vec4 color = vec4(0.0);
898
+ float totalWeight = 0.0;
899
+ int blurSize = int(60.0 * min(1.0, blurriness) * blurAmount); // Adjust blur size based on distance and blurriness
900
+ float lodLevel = log2(float(blurSize)) * 0.5; // Compute LOD level
901
+
902
+ for (int x = -blurSize; x <= blurSize; x++) {
903
+ for (int y = -blurSize; y <= blurSize; y++) {
904
+ vec2 offset = vec2(float(x), float(y)) * pixelSize * blurAmount;
905
+ float weight = gaussian(length(vec2(float(x), float(y))), 1000.0 * blurAmount); // Use a fixed sigma value
906
+ color += textureLod(map, vUv + offset, lodLevel) * weight;
907
+ totalWeight += weight;
908
+ }
909
+ }
910
+
911
+ color = totalWeight > 0.0 ? color / totalWeight : texture2D(map, vUv);
912
+
913
+ gl_FragColor = color;
914
+
915
+ float brightness = dot(gl_FragColor.rgb, vec3(0.299, 0.587, 0.114));
916
+ float stepFactor = blending - brightness * .1;
917
+ gl_FragColor.a = pow(1.0 - blending * customSmoothstep(0.35 * stepFactor, 0.45 * stepFactor, distance), 5.);
918
+ gl_FragColor.a *= alphaFactor;
919
+ // gl_FragColor.rgb = vec3(1.0);
920
+
921
+ // #include <tonemapping_fragment>
922
+ // #include <colorspace_fragment>
923
+
924
+ // Uncomment to visualize blur amount
925
+ // gl_FragColor = vec4(blurAmount, 0.0, 0.0, 1.0);
926
+ }
927
+ `;var iT=Object.defineProperty,If=(o,e,t,s)=>{for(var n=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=l(e,t,n)||n);return n&&iT(e,t,n),n};class jr extends I{constructor(){super(...arguments),a(this,"constraintActive",!0),a(this,"locked",!1),a(this,"sources",[])}}If([m()],jr.prototype,"constraintActive"),If([m()],jr.prototype,"locked"),If([m(E)],jr.prototype,"sources");function mx(o,e){return jn(o,me.ContextCreated,e),()=>bo(o,me.ContextCreated)}function sT(o,e){return jn(o,me.ContextClearing,e),()=>bo(o,me.ContextClearing)}function nT(o,e){return jn(o,me.ContextDestroying,e),()=>bo(o,me.ContextDestroying)}function gx(o,e){return jn(o,Oe.Start,e),()=>bo(o,Oe.Start)}function fx(o,e){return jn(o,Oe.Update,e),()=>bo(o,Oe.Update)}function oT(o,e){return jn(o,Oe.OnBeforeRender,e),()=>bo(o,Oe.OnBeforeRender)}function rT(o,e){return jn(o,Oe.OnAfterRender,e),()=>bo(o,Oe.OnAfterRender)}let Dr=class{constructor(){a(this,"bb",null),a(this,"bb_pos",0)}__init(o,e){return this.bb_pos=o,this.bb=e,this}x(){return this.bb.readFloat32(this.bb_pos)}y(){return this.bb.readFloat32(this.bb_pos+4)}z(){return this.bb.readFloat32(this.bb_pos+8)}static sizeOf(){return 12}static createVec3(o,e,t,s){return o.prep(4,12),o.writeFloat32(s),o.writeFloat32(t),o.writeFloat32(e),o.offset()}};class yx{constructor(){a(this,"bb",null),a(this,"bb_pos",0)}__init(e,t){return this.bb_pos=e,this.bb=t,this}position(e){return(e||new Dr).__init(this.bb_pos,this.bb)}rotation(e){return(e||new Dr).__init(this.bb_pos+12,this.bb)}scale(e){return(e||new Dr).__init(this.bb_pos+24,this.bb)}static sizeOf(){return 36}static createTransform(e,t,s,n,r,l,c,h,d,u){return e.prep(4,36),e.prep(4,12),e.writeFloat32(u),e.writeFloat32(d),e.writeFloat32(h),e.prep(4,12),e.writeFloat32(c),e.writeFloat32(l),e.writeFloat32(r),e.prep(4,12),e.writeFloat32(n),e.writeFloat32(s),e.writeFloat32(t),e.offset()}}class co{constructor(){a(this,"bb",null),a(this,"bb_pos",0)}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsSyncedTransformModel(e,t){return(t||new co).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSyncedTransformModel(e,t){return e.setPosition(e.position()+Gv),(t||new co).__init(e.readInt32(e.position())+e.position(),e)}guid(e){const t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}fast(){const e=this.bb.__offset(this.bb_pos,6);return e?!!this.bb.readInt8(this.bb_pos+e):!1}transform(e){const t=this.bb.__offset(this.bb_pos,8);return t?(e||new yx).__init(this.bb_pos+t,this.bb):null}dontSave(){const e=this.bb.__offset(this.bb_pos,10);return e?!!this.bb.readInt8(this.bb_pos+e):!1}static startSyncedTransformModel(e){e.startObject(4)}static addGuid(e,t){e.addFieldOffset(0,t,0)}static addFast(e,t){e.addFieldInt8(1,+t,0)}static addTransform(e,t){e.addFieldStruct(2,t,0)}static addDontSave(e,t){e.addFieldInt8(3,+t,0)}static endSyncedTransformModel(e){return e.endObject()}static finishSyncedTransformModelBuffer(e,t){e.finish(t)}static finishSizePrefixedSyncedTransformModelBuffer(e,t){e.finish(t,void 0,!0)}}var A;(o=>{(e=>{e.MAYBEMODULE=null;const t=[];function s(){return e.MODULE?Promise.resolve(e.MODULE):new Promise(r=>{t.push(r)})}e.ready=s;async function n(){if(e.MODULE)return e.MODULE;const r=await import("./rapier-CyWhltHY.min.js");return e.MODULE=r,e.MAYBEMODULE=r,t.forEach(l=>l(r)),t.length=0,r}e.load=n})(o.RAPIER_PHYSICS||(o.RAPIER_PHYSICS={})),(e=>{e.MAYBEMODULE=null;const t=[];function s(){return e.MODULE?Promise.resolve(e.MODULE):new Promise(r=>{t.push(r)})}e.ready=s;async function n(){if(e.MODULE)return e.MODULE;const r=await import("./postprocessing-xYQWCHFu.min.js").then(l=>l.index);return e.MODULE=r,e.MAYBEMODULE=r,t.forEach(l=>l(r)),t.length=0,r}e.load=n})(o.POSTPROCESSING||(o.POSTPROCESSING={})),(e=>{e.MAYBEMODULE=null;const t=[];function s(){return e.MODULE?Promise.resolve(e.MODULE):new Promise(r=>{t.push(r)})}e.ready=s;async function n(){if(e.MODULE)return e.MODULE;const r=await import("./postprocessing-xYQWCHFu.min.js").then(l=>l.N8AO);return e.MODULE=r,e.MAYBEMODULE=r,t.forEach(l=>l(r)),t.length=0,r}e.load=n})(o.POSTPROCESSING_AO||(o.POSTPROCESSING_AO={}))})(A||(A={}));var wt=(o=>(o[o.Average=0]="Average",o[o.Multiply=1]="Multiply",o[o.Minimum=2]="Minimum",o[o.Maximum=3]="Maximum",o))(wt||{}),Pu=(o=>(o[o.Discrete=0]="Discrete",o[o.Continuous=1]="Continuous",o))(Pu||{}),Qe=(o=>(o[o.None=0]="None",o[o.FreezePositionX=2]="FreezePositionX",o[o.FreezePositionY=4]="FreezePositionY",o[o.FreezePositionZ=8]="FreezePositionZ",o[o.FreezePosition=14]="FreezePosition",o[o.FreezeRotationX=16]="FreezeRotationX",o[o.FreezeRotationY=32]="FreezeRotationY",o[o.FreezeRotationZ=64]="FreezeRotationZ",o[o.FreezeRotation=112]="FreezeRotation",o[o.FreezeAll=126]="FreezeAll",o))(Qe||{}),$a=(o=>(o[o.None=0]="None",o[o.X=2]="X",o[o.Y=4]="Y",o[o.Z=8]="Z",o[o.All=-1]="All",o))($a||{});const Rt=function(o,e){return function(t,s,n){aT(t,s,n,o,e)}};function aT(o,e,t,s,n){if(!n&&!s&&!o.onValidate)return;if(t!==void 0){console.error("Invalid usage of validate decorator. Only fields can be validated.",o,e,t),Be("Invalid usage of validate decorator. Only fields can be validated. Property: "+e,Oi.Error);return}let r="";if(typeof e=="string"?r=e:r=e.name,o.__internalAwake){const l=Symbol(r),c=o.__internalAwake;o.__internalAwake=function(){var h;if(!this.onValidate){F()&&console.warn('Usage of @validate decorate detected but there is no onValidate method in your class: "'+((h=o.constructor)==null?void 0:h.name)+'"');return}if(this[l]===void 0){this[l]=this[r];const d=this[r];if(d instanceof le||d instanceof x||d instanceof ye||d instanceof H){const u=this[r];Cd(u,()=>{this.onValidate(r)})}Object.defineProperty(this,r,{set:function(u){var p;if(this[lf]===!0)this[l]=u;else{s?.call(this,u);const g=this[l];this[l]=u,(p=this.onValidate)==null||p.call(this,r,g)}},get:function(){return n?.call(this),this[l]}})}c.call(this)}}}const lT=function(o){return function(e,t,s){let n="";typeof t=="string"?n=t:n=t.name;const r=o.prototype,l=Object.getOwnPropertyDescriptor(r,n);if(!(l!=null&&l.value)){console.warn("Can not apply prefix: type does not have method named",t,o);return}const c=l.value,h=e[n];Object.defineProperty(r,n,{value:function(...d){const u=h?.call(this,...d);if(u instanceof Promise){u.then(p=>{if(p!==!1)return c.call(this,...d)});return}if(u!==!1)return c.call(this,...d)}})}};var cT=Object.defineProperty,hT=Object.getOwnPropertyDescriptor,Ii=(o,e,t,s)=>{for(var n=s>1?void 0:s?hT(e,t):e,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=(s?l(e,t,n):l(n))||n);return s&&n&&cT(e,t,n),n};class dT{constructor(e,t){a(this,"positionChanged",!1),a(this,"rotationChanged",!1),a(this,"position"),a(this,"quaternion"),a(this,"_positionKeys",["x","y","z"]),a(this,"_quaternionKeys",["_x","_y","_z","_w"]),a(this,"mute",!1),a(this,"context"),a(this,"obj"),a(this,"_positionWatch"),a(this,"_rotationWatch"),this.context=t,this.obj=e}get isDirty(){return this.positionChanged||this.rotationChanged}reset(e=!1){if(this.positionChanged=!1,this.rotationChanged=!1,this.mute=!1,e){if(this.position)for(const t of this._positionKeys)delete this.position[t];if(this.quaternion)for(const t of this._quaternionKeys)delete this.quaternion[t]}}syncValues(){for(const e of this._positionKeys)this.position[e]=this.obj.position[e];for(const e of this._quaternionKeys)this.quaternion[e]=this.obj.quaternion[e]}applyValues(){if(this.positionChanged&&this.position)for(const e of this._positionKeys){const t=this.position[e];t!==void 0&&(this.obj.position[e]=t)}if(this.rotationChanged&&this.quaternion)for(const e of this._quaternionKeys){const t=this.quaternion[e];t!==void 0&&(this.obj.quaternion[e]=t)}}start(e,t){this.reset(),e&&(this._positionWatch||(this._positionWatch=new lo(this.obj.position,["x","y","z"])),this._positionWatch.apply(),this.position={},this._positionWatch.subscribeWrite((r,l)=>{var c;if((c=this.context.physics.engine)!=null&&c.isUpdating||this.mute)return;const h=this.position[l];Math.abs(h-r)<1e-5||(this.position[l]=r,this.positionChanged=!0)})),t&&(this._rotationWatch||(this._rotationWatch=new lo(this.obj.quaternion,["_x","_y","_z","_w"])),this._rotationWatch.apply(),this.quaternion={},this._rotationWatch.subscribeWrite((r,l)=>{var c;if((c=this.context.physics.engine)!=null&&c.isUpdating||this.mute)return;const h=this.quaternion[l];Math.abs(h-r)<1e-5||(this.quaternion[l]=r,this.rotationChanged=!0)}));const s=this.obj.matrixWorld.multiplyMatrices.bind(this.obj.matrixWorld),n=new se;this.obj.matrixWorld.multiplyMatrices=(r,l)=>{var c;return(c=this.context.physics.engine)!=null&&c.isUpdating||this.mute||n.equals(r)||(this.positionChanged=!0,this.rotationChanged=!0,n.copy(r)),s(r,l)}}stop(){var e,t;(e=this._positionWatch)==null||e.revoke(),(t=this._rotationWatch)==null||t.revoke()}}var Ga;const ai=(Ga=class extends I{constructor(){super(...arguments),a(this,"autoMass",!0),a(this,"_mass",0),a(this,"useGravity",!0),a(this,"centerOfMass",new x(0,0,0)),a(this,"constraints",Qe.None),a(this,"isKinematic",!1),a(this,"drag",0),a(this,"angularDrag",1),a(this,"detectCollisions",!0),a(this,"sleepThreshold",.01),a(this,"collisionDetectionMode",Pu.Discrete),a(this,"_gravityScale",1),a(this,"dominanceGroup",0),a(this,"_propertiesChanged",!1),a(this,"_currentVelocity",new x),a(this,"_smoothedVelocity",new x),a(this,"_smoothedVelocityGetter",new x),a(this,"_lastPosition",new x),a(this,"_watch")}get isRigidbody(){return!0}set mass(o){o!==this._mass&&(this._mass=o,this._propertiesChanged=!0,this.__didAwake&&(this.autoMass=!1))}get mass(){var o,e;return this.autoMass?((e=(o=this.context.physics.engine)==null?void 0:o.getBody(this))==null?void 0:e.mass())??-1:this._mass}get lockPositionX(){return(this.constraints&Qe.FreezePositionX)!==0}get lockPositionY(){return(this.constraints&Qe.FreezePositionY)!==0}get lockPositionZ(){return(this.constraints&Qe.FreezePositionZ)!==0}get lockRotationX(){return(this.constraints&Qe.FreezeRotationX)!==0}get lockRotationY(){return(this.constraints&Qe.FreezeRotationY)!==0}get lockRotationZ(){return(this.constraints&Qe.FreezeRotationZ)!==0}set lockPositionX(o){o?this.constraints|=Qe.FreezePositionX:this.constraints&=~Qe.FreezePositionX}set lockPositionY(o){o?this.constraints|=Qe.FreezePositionY:this.constraints&=~Qe.FreezePositionY}set lockPositionZ(o){o?this.constraints|=Qe.FreezePositionZ:this.constraints&=~Qe.FreezePositionZ}set lockRotationX(o){o?this.constraints|=Qe.FreezeRotationX:this.constraints&=~Qe.FreezeRotationX}set lockRotationY(o){o?this.constraints|=Qe.FreezeRotationY:this.constraints&=~Qe.FreezeRotationY}set lockRotationZ(o){o?this.constraints|=Qe.FreezeRotationZ:this.constraints&=~Qe.FreezeRotationZ}set gravityScale(o){this._gravityScale=o}get gravityScale(){return this._gravityScale}awake(){this._watch=void 0,this._propertiesChanged=!1}onEnable(){this._watch||(this._watch=new dT(this.gameObject,this.context)),this._watch.start(!0,!0),this.startCoroutine(this.beforePhysics(),Oe.LateUpdate),F()&&(globalThis.NEEDLE_USE_RAPIER?A.RAPIER_PHYSICS.ready().then(async()=>{var o;await Gl(3),(o=this.context.physics.engine)!=null&&o.getBody(this)||console.warn(`Rigidbody could not be created. Ensure "${this.name}" has a Collider component.`)}):console.warn("Rigidbody could not be created: Rapier physics are explicitly disabled."))}onDisable(){var o,e;(o=this._watch)==null||o.stop(),(e=this.context.physics.engine)==null||e.removeBody(this)}onDestroy(){var o;(o=this.context.physics.engine)==null||o.removeBody(this)}onValidate(){this._propertiesChanged=!0}*beforePhysics(){for(var o,e,t,s;;)this._propertiesChanged&&(this._propertiesChanged=!1,(o=this.context.physics.engine)==null||o.updateProperties(this)),(e=this._watch)!=null&&e.isDirty?(this._watch.mute=!0,this._watch.applyValues(),(t=this.context.physics.engine)==null||t.updateBody(this,this._watch.positionChanged,this._watch.rotationChanged),this._watch.reset()):(s=this._watch)==null||s.syncValues(),this.captureVelocity(),yield}teleport(o,e=!0){var t;(t=this._watch)==null||t.reset(!0),e?this.gameObject.position.set(o.x,o.y,o.z):this.setWorldPosition(o.x,o.y,o.z),this.resetForcesAndTorques(),this.resetVelocities()}resetForces(o=!0){var e;(e=this.context.physics.engine)==null||e.resetForces(this,o)}resetTorques(o=!0){var e;(e=this.context.physics.engine)==null||e.resetTorques(this,o)}resetVelocities(){this.setVelocity(0,0,0),this.setAngularVelocity(0,0,0)}resetForcesAndTorques(){this.resetForces(),this.resetTorques()}wakeUp(){var o;(o=this.context.physics.engine)==null||o.wakeup(this)}get isSleeping(){var o;return(o=this.context.physics.engine)==null?void 0:o.isSleeping(this)}updateProperties(){var o;return this._propertiesChanged=!1,(o=this.context.physics.engine)==null?void 0:o.updateProperties(this)}applyForce(o,e,t=!0){var s;this._propertiesChanged&&this.updateProperties(),(s=this.context.physics.engine)==null||s.addForce(this,o,t)}applyImpulse(o,e=!0){var t;this._propertiesChanged&&this.updateProperties(),(t=this.context.physics.engine)==null||t.applyImpulse(this,o,e)}setForce(o,e,t,s=!0){var n,r,l;(n=this.context.physics.engine)==null||n.resetForces(this,s),typeof o=="number"?(e??(e=0),t??(t=0),(r=this.context.physics.engine)==null||r.addForce(this,{x:o,y:e,z:t},s)):(l=this.context.physics.engine)==null||l.addForce(this,o,s)}getVelocity(){var o;const e=(o=this.context.physics.engine)==null?void 0:o.getLinearVelocity(this);return e?(this._currentVelocity.x=e.x,this._currentVelocity.y=e.y,this._currentVelocity.z=e.z,this._currentVelocity):this._currentVelocity.set(0,0,0)}setVelocity(o,e,t,s=!0){var n,r;if(o instanceof x){const l=o;(n=this.context.physics.engine)==null||n.setLinearVelocity(this,l,s);return}e===void 0||t===void 0||(r=this.context.physics.engine)==null||r.setLinearVelocity(this,{x:o,y:e,z:t},s)}getAngularVelocity(){var o;const e=(o=this.context.physics.engine)==null?void 0:o.getAngularVelocity(this);return e?(this._currentVelocity.x=e.x,this._currentVelocity.y=e.y,this._currentVelocity.z=e.z,this._currentVelocity):this._currentVelocity.set(0,0,0)}setAngularVelocity(o,e,t,s=!0){var n,r;if(typeof o=="object"){const l=o;(n=this.context.physics.engine)==null||n.setAngularVelocity(this,l,s);return}if(e===void 0||t===void 0||typeof e=="boolean"){console.warn("setAngularVelocity expects either a Vec3 or 3 numbers");return}(r=this.context.physics.engine)==null||r.setAngularVelocity(this,{x:o,y:e,z:t},s)}setTorque(o,e,t){typeof o=="number"?this.setAngularVelocity(o,e,t):this.setAngularVelocity(o)}get smoothedVelocity(){return this._smoothedVelocityGetter.copy(this._smoothedVelocity),this._smoothedVelocityGetter.multiplyScalar(1/this.context.time.deltaTime)}setBodyFromGameObject(o=null){}captureVelocity(){const o=this.gameObject.matrixWorld;Ga.tempPosition.setFromMatrixPosition(o);const e=Ga.tempPosition.sub(this._lastPosition);this._lastPosition.copy(Ga.tempPosition),this._smoothedVelocity.lerp(e,this.context.time.deltaTime/.1)}},a(Ga,"tempPosition",new x),Ga);Ii([Rt()],ai.prototype,"autoMass",2),Ii([m()],ai.prototype,"mass",1),Ii([Rt(),m()],ai.prototype,"useGravity",2),Ii([m(x)],ai.prototype,"centerOfMass",2),Ii([Rt(),m()],ai.prototype,"constraints",2),Ii([Rt(),m()],ai.prototype,"isKinematic",2),Ii([Rt(),m()],ai.prototype,"drag",2),Ii([Rt(),m()],ai.prototype,"angularDrag",2),Ii([Rt(),m()],ai.prototype,"detectCollisions",2),Ii([Rt(),m()],ai.prototype,"sleepThreshold",2),Ii([Rt(),m()],ai.prototype,"collisionDetectionMode",2),Ii([Rt()],ai.prototype,"_gravityScale",2),Ii([Rt()],ai.prototype,"dominanceGroup",2);let dt=ai;new x,new x;const Ro=C("debugsync"),Ac="STRS";Pg(Ac,co.getRootAsSyncedTransformModel);const tn=new Um;function vx(o,e,t=!0){tn.clear();const s=tn.createString(o);co.startSyncedTransformModel(tn),co.addGuid(tn,s),co.addFast(tn,t);const n=e.worldPosition,r=e.worldEuler,l=e.gameObject.scale;co.addTransform(tn,yx.createTransform(tn,n.x,n.y,n.z,r.x,r.y,r.z,l.x,l.y,l.z));const c=co.endSyncedTransformModel(tn);return tn.finish(c,Ac),tn.asUint8Array()}let Lf=0,Ic=0;fx(o=>{var e;const t=(e=o.connection.currentServerUrl)!=null&&e.includes("glitch")?10:40;Ic=Math.floor(Lf/t),Lf=0,Ro&&Ic>0&&console.log("Sync Transform Fast Interval",Ic)});class sn extends I{constructor(){super(...arguments),a(this,"overridePhysics",!0),a(this,"interpolatePosition",!0),a(this,"interpolateRotation",!0),a(this,"fastMode",!1),a(this,"syncDestroy",!1),a(this,"_model",null),a(this,"_needsUpdate",!0),a(this,"rb",null),a(this,"_wasKinematic",!1),a(this,"_receivedDataBefore",!1),a(this,"_targetPosition"),a(this,"_targetRotation"),a(this,"_receivedFastUpdate",!1),a(this,"_shouldRequestOwnership",!1),a(this,"joinedRoomCallback",null),a(this,"receivedDataCallback",null),a(this,"tempEuler",new jt),a(this,"receivedUpdate",!1),a(this,"lastPosition"),a(this,"lastRotation"),a(this,"lastScale")}requestOwnership(){Ro&&console.log("Request ownership"),this._model?this._model.requestOwnership():(this._shouldRequestOwnership=!0,this._needsUpdate=!0)}freeOwnership(){var e;(e=this._model)==null||e.freeOwnership()}hasOwnership(){var e;return((e=this._model)==null?void 0:e.hasOwnership)??void 0}isOwned(){var e;return(e=this._model)==null?void 0:e.isOwned}awake(){Ro&&console.log("new instance",this.guid,this),this._receivedDataBefore=!1,this._targetPosition=new x,this._targetRotation=new H,this.lastPosition=new x,this.lastRotation=new H,this.lastScale=new x,this.rb=P.getComponentInChildren(this.gameObject,dt),this.rb&&(this._wasKinematic=this.rb.isKinematic),this.receivedUpdate=!0,this._model=new kg(this.context.connection,this.guid),this.context.connection.isConnected&&this.tryGetLastState(),this.joinedRoomCallback=this.tryGetLastState.bind(this),this.context.connection.beginListen(ie.JoinedRoom,this.joinedRoomCallback),this.receivedDataCallback=this.onReceivedData.bind(this),this.context.connection.beginListenBinary(Ac,this.receivedDataCallback)}onDestroy(){this.syncDestroy&&Zg(this.guid,this.context.connection),this._model=null,this.context.connection.stopListen(ie.JoinedRoom,this.joinedRoomCallback),this.context.connection.stopListenBinary(Ac,this.receivedDataCallback)}tryGetLastState(){const e=this.context.connection.tryGetState(this.guid);e&&this.onReceivedData(e)}onReceivedData(e){var t;if(!this.destroyed&&typeof e.guid=="function"&&e.guid()===this.guid){Ro&&console.log("new data",this.context.connection.connectionId,this.context.time.frameCount,this.guid,e),this.receivedUpdate=!0,this._receivedFastUpdate=e.fast();const s=e.transform();if(s){ds.markDirty(this.gameObject,!0);const n=s.position();n&&(this.interpolatePosition&&((t=this._targetPosition)==null||t.set(n.x(),n.y(),n.z())),(!this.interpolatePosition||!this._receivedDataBefore)&&this.setWorldPosition(n.x(),n.y(),n.z()));const r=s.rotation();r&&(this.tempEuler.set(r.x(),r.y(),r.z()),this.interpolateRotation&&this._targetRotation.setFromEuler(this.tempEuler),(!this.interpolateRotation||!this._receivedDataBefore)&&lg(this.gameObject,this.tempEuler));const l=s.scale();l&&this.gameObject.scale.set(l.x(),l.y(),l.z())}this._receivedDataBefore=!0}}onEnable(){this.lastPosition.copy(this.worldPosition),this.lastRotation.copy(this.worldQuaternion),this.lastScale.copy(this.gameObject.scale),this._needsUpdate=!0,this._model&&this._model.updateIsOwned()}onDisable(){this._model&&this._model.freeOwnership()}onBeforeRender(){if(!this.activeAndEnabled||!this.context.connection.isConnected)return;if(!this.context.connection.isInRoom||!this._model){Ro&&console.log("no model or room",this.name,this.guid,this.context.connection.isInRoom);return}this._shouldRequestOwnership&&(this._shouldRequestOwnership=!1,this._model.requestOwnership());const e=this.worldPosition,t=this.worldQuaternion,s=this.gameObject.scale;if(this._model.isOwned&&!this.receivedUpdate){const l=this._model.hasOwnership||this.fastMode?1e-4:.001;(e.distanceTo(this.lastPosition)>l||t.angleTo(this.lastRotation)>l||s.distanceTo(this.lastScale)>l)&&(this._model.hasOwnership?this._needsUpdate=!0:(Ro&&console.log(this.guid,"reset because not owned but",this.gameObject.name,this.lastPosition),this.worldPosition=this.lastPosition,e.copy(this.lastPosition),this.worldQuaternion=this.lastRotation,t.copy(this.lastRotation),this.gameObject.scale.copy(this.lastScale),ds.markDirty(this.gameObject,!0),this._needsUpdate=!1))}if(this._model&&!this._model.hasOwnership&&this._model.isOwned&&this._receivedDataBefore){const l=this._receivedFastUpdate||this.fastMode?.5:.3;let c=!1;if(this.interpolatePosition&&this._targetPosition){const h=this.worldPosition;h.lerp(this._targetPosition,l),this.worldPosition=h,c=!0}if(this.interpolateRotation&&this._targetRotation){const h=this.worldQuaternion;h.slerp(this._targetRotation,l),this.worldQuaternion=h,c=!0}c&&ds.markDirty(this.gameObject,!0)}if(this.receivedUpdate=!1,this.lastPosition.copy(e),this.lastRotation.copy(t),this.lastScale.copy(s),!this._model||!this._model||this._model.hasOwnership===void 0||!this._model.hasOwnership)return;this.rb&&this.overridePhysics&&this._wasKinematic!==void 0&&(Ro&&console.log("reset kinematic",this.rb.name,this._wasKinematic),this.rb.isKinematic=this._wasKinematic);const n=10,r=this.rb||this.fastMode;if(this._needsUpdate&&(this.context.time.frameCount%n===0||r)){if(Lf++,r&&Ic>0&&this.context.time.frameCount%Ic!==0)return;Ro&&console.debug("[SyncedTransform] Send update",this.context.connection.connectionId,this.guid,this.gameObject.name,this.gameObject.guid),this._needsUpdate=!1;const l=vx(this.guid,this,!!r);this.context.connection.sendBinary(l)}}}class ad{constructor(e,t){a(this,"event"),a(this,"button"),a(this,"buttonName"),a(this,"_used",!1),a(this,"_propagationStopped",!1),a(this,"z__pointer_ctured",!1),a(this,"z__pointer_cture_rleased",!1),a(this,"inputSource"),a(this,"object"),a(this,"point"),a(this,"normal"),a(this,"face"),a(this,"distance"),a(this,"instanceId"),a(this,"intersection"),a(this,"isDown"),a(this,"isUp"),a(this,"isPressed"),a(this,"isClick"),a(this,"isDoubleClick"),a(this,"input"),this.event=t,this.input=e,this.button=t.button}get deviceIndex(){return this.event.deviceIndex}get pointerId(){return this.event.pointerId}get pressure(){return this.event.pressure}get used(){return this._used}use(){this._used||(this._used=!0,this.event.use())}get propagationStopped(){return this._propagationStopped}stopPropagation(){this._propagationStopped=!0,this.event.stopImmediatePropagation()}stopImmediatePropagation(){this._propagationStopped=!0,this.event.stopImmediatePropagation()}setPointerCapture(){this.z__pointer_ctured=!0}releasePointerCapture(){this.z__pointer_cture_rleased=!0}get mode(){return this.event.mode}clone(){const e=new ad(this.input,this.event);return Object.assign(e,this),e}Use(){this.use()}StopPropagation(){this.event.stopImmediatePropagation()}}function Ou(o,e){return P.foreachComponent(o,t=>{if(!t.enabled)return;const s=t;if(e)switch(e){case"pointerdown":if(s.onPointerDown)return!0;break;case"pointerup":if(s.onPointerUp||s.onPointerClick)return!0;break;case"pointermove":if(s.onPointerEnter||s.onPointerExit||s.onPointerMove)return!0;break}else if(s.onPointerDown||s.onPointerUp||s.onPointerEnter||s.onPointerExit||s.onPointerClick)return!0},!1)===!0}const Fn=new Array;class Un{constructor(e,t,s,n){a(this,"enabled",!0),a(this,"target"),a(this,"methodName"),a(this,"arguments"),this.target=e,this.methodName=t||null,this.arguments=s,n!=null&&(this.enabled=n)}get canClone(){return this.target instanceof Object}invoke(...e){if(this.enabled!==!1){if(typeof this.target=="function")this.arguments?(Fn.length=0,e!==void 0&&e.length>0&&Fn.push(...e),Fn.push(...this.arguments),this.target(...this.arguments),Fn.length=0):this.target(...e);else if(this.methodName!=null){const t=this.target[this.methodName];typeof t=="function"?this.arguments?(Fn.length=0,e!==void 0&&e.length>0&&Fn.push(...e),Fn.push(...this.arguments),t.call(this.target,...Fn),Fn.length=0):t.call(this.target,...e):this.arguments?this.target[this.methodName]=this.arguments[0]||e[0]:this.target[this.methodName]=e[0]}}}}const uT=o=>/^[A-Z]*$/.test(o);class ku extends Event{constructor(){super(...arguments),a(this,"args")}}class xe{constructor(e){if(a(this,"isEventList",!0),a(this,"target"),a(this,"key"),a(this,"_isInvoking",!1),a(this,"methods",[]),a(this,"_methodsCopy",[]),this.methods=[],Array.isArray(e))for(const t of e)t instanceof Un?this.methods.push(t):typeof t=="function"&&this.methods.push(new Un(t));else typeof e=="function"&&this.methods.push(new Un(e))}__internalOnInstantiate(e){var t;const s=new Array;for(let n=0;n<this.methods.length;n++){const r=this.methods[n];if(!(r.target instanceof Function)){const l=r.target;let c=l?.uuid;if(l&&(c=l.guid),c){const h=e[c];if(h){const d=(t=r.arguments)==null?void 0:t.map(u=>u instanceof Object&&u.uuid?e[u.uuid]:u!=null&&u.isComponent?e[u.guid]:u);s.push(new Un(h.clone,r.methodName,d,r.enabled))}else F()&&console.warn("Could not find target for event listener")}}}return new xe(s)}setEventTarget(e,t){if(this.key=e,this.target=t,this.key!==void 0){let s="",n=!1;for(const r of this.key)n&&uT(r)&&(s+="-"),n=!0,s+=r.toLowerCase();this.key=s}}get listenerCount(){var e;return((e=this.methods)==null?void 0:e.length)??0}get isInvoking(){return this._isInvoking}static from(...e){return new xe(e)}invoke(...e){var t;if(this._isInvoking)return console.warn("Circular event invocation detected. Please check your event listeners for circular references.",this),!1;if(((t=this.methods)==null?void 0:t.length)<=0)return!1;this._isInvoking=!0;try{this._methodsCopy.length=0,this._methodsCopy.push(...this.methods);for(const s of this._methodsCopy)s.invoke(...e);if(typeof this.target=="object"&&typeof this.key=="string"){const s=this.target.dispatchEvent;if(typeof s=="function"){const n=new ku(this.key);n.args=e,s.call(this.target,n)}}}finally{this._isInvoking=!1,this._methodsCopy.length=0}return!0}addEventListener(e){return this.methods.push(new Un(e)),e}removeEventListener(e){if(e)for(let t=this.methods.length-1;t>=0;t--)this.methods[t].target===e&&(this.methods[t].enabled=!1,this.methods.splice(t,1))}removeAllEventListeners(){this.methods.length=0}}class pT extends Ji{constructor(){super([ae,he],"ColorSerializer")}onDeserialize(e){if(e!=null)return e.a!==void 0?new he(e.r,e.g,e.b,e.a):e.alpha!==void 0?new he(e.r,e.g,e.b,e.alpha):new ae(e.r,e.g,e.b)}onSerialize(e){if(e!=null)return e.a!==void 0?{r:e.r,g:e.g,b:e.b,a:e.a}:{r:e.r,g:e.g,b:e.b}}}const mT=new pT;class gT extends Ji{constructor(){super([jt],"EulerSerializer")}onDeserialize(e,t){if(e!=null){if(e.order)return new jt(e.x,e.y,e.z,e.order);if(e.x!=null)return new jt(e.x,e.y,e.z)}}onSerialize(e,t){return{x:e.x,y:e.y,z:e.z,order:e.order}}}const fT=new gT;class yT extends Ji{constructor(){super(E,"ObjectSerializer")}onSerialize(e,t){if(t.objectToNode!==void 0&&e.uuid){const s=t.objectToNode[e.uuid];return _t&&console.log(s,e.name,e.uuid),{node:s}}}onDeserialize(e,t){var s,n,r;if(typeof e=="string"){if(e.endsWith(".glb")||e.endsWith(".gltf")){if(t.serializable instanceof Array&&t.serializable.includes(ce))return;F()&&be("Detected wrong usage of @serializable with Object3D or GameObject. Instead you should use AssetReference here! Please see the console for details.");const l=(n=(s=t.target)==null?void 0:s.constructor)==null?void 0:n.name;console.warn(`Wrong usage of @serializable detected in your script "${l}"
928
+
929
+ It looks like you used @serializable(Object3D) or @serializable(GameObject) for a prefab or scene reference which is exported to a separate glTF file.
930
+
931
+ To fix this please change your code to:
932
+
933
+ @serializable(AssetReference)
934
+ ${t.path}! : AssetReference;
935
+ \0`)}return}if(e){if(e.node!==void 0&&t.nodeToObject){const l=t.nodeToObject[e.node];return _t&&console.log("Deserialized object reference?",e,l,t?.nodeToObject),l||console.warn("Did not find node: "+e.node,t.nodeToObject,t.object),l}else if(e.guid){if(!t.context){console.error("Missing context");return}let l;const c=(r=t.gltf)==null?void 0:r.scene;return c&&(l=P.findByGuid(e.guid,c)),l||(l=P.findByGuid(e.guid,t.context.scene)),l?(l&&l.isComponent===!0&&(_t&&console.warn("Deserialized object reference is a component"),l=l.gameObject),_t&&console.log("Deserialized object reference?",e,l,t?.nodeToObject)):((F()||_t)&&console.warn("Could not resolve object reference",t.path,e,t.target,t.context.scene),e.could_not_resolve=!0),l}}}}const bx=new yT;class vT extends Ji{constructor(){super([I,I],"ComponentSerializer")}onSerialize(e,t){if(e!=null&&e.guid)return{guid:e.guid}}onDeserialize(e,t){var s;if(e!=null&&e.guid){if(e.___persistentAsset){_t&&console.log("Skipping component deserialization because it's a persistent asset",e);return}const n=t.path;_t&&console.log(e.guid,t.root,t.object,t.target);let r=this.findObjectForGuid(e.guid,t.root);if(r||t.context&&(r=this.findObjectForGuid(e.guid,(s=t.context)==null?void 0:s.scene),r))return r;(F()||_t)&&console.warn('Could not resolve component reference: "'+n+'" using guid '+e.guid,t.target),e.could_not_resolve=!0;return}}findObjectForGuid(e,t){if(t.guid===e)return t;const s=P.foreachComponent(t,n=>{if(n.guid===e)return n},!1);if(s!==void 0)return s;for(let n=0;n<t.children.length;n++){const r=t.children[n],l=this.findObjectForGuid(e,r);if(l)return l}}}const Mu=new vT;class bT extends Ji{constructor(){super([xe])}onSerialize(e,t){console.log("TODO: SERIALIZE EVENT")}onDeserialize(e,t){var s,n,r;if(typeof e=="function")return new xe([new Un(e,null,[],!0)]);if(e&&e.type==="EventList"){_t&&console.log("DESERIALIZE EVENT",e);const l=new Array;if(e.calls&&Array.isArray(e.calls))for(const d of e.calls){let u=function(f){if(typeof f=="object"){let y=bx.onDeserialize(f,t);if(y||(y=Mu.onDeserialize(f,t)),y)return y}return f};_t&&console.log(d);let p=Mu.findObjectForGuid(d.target,t.root);!p&&(s=t.context)!=null&&s.scene&&(p=Mu.findObjectForGuid(d.target,(n=t.context)==null?void 0:n.scene));const g=((r=d.method)==null?void 0:r.length)>0;if(p&&g){const f=()=>{const y=d.method[0].toUpperCase()+d.method.slice(1);if(typeof p[y]=="function"){console.warn(`EventList method:
936
+ Could not find method ${d.method} on object ${p.name}. Please rename ${d.method} to ${y}?
937
+ `,p[y],`
938
+ in script: `,p),be("EventList methods must start with lowercase letter, see console for details");return}else console.warn(`EventList method:
939
+ Could not find method ${d.method} on object ${p.name}`,p,typeof p[d.method])};if(typeof p[d.method]!="function"){let y=!1,b=p;for(;b;){const v=Object.getOwnPropertyDescriptor(b,d.method);if(v&&(v.writable===!0||v.set)){y=!0;break}b=Object.getPrototypeOf(b)}!y&&(F()||_t)&&f()}}if(p){let f=d.argument;if(f!==void 0?f=u(f):d.arguments!==void 0&&(f=d.arguments.map(u)),!p[d.method])console.warn(`EventList method not found: "${d.method}" on ${p?.name}`);else{f!==void 0&&!Array.isArray(f)&&(f=[f]);const y=new Un(p,d.method,f,d.enabled);l.push(y)}}else F()&&console.warn("[Debug] EventList: Could not find event listener in scene",d,t.object,e)}const c=new xe(l);_t&&console.log(c);const h=t.target;return h!==void 0&&t.path!==void 0&&c.setEventTarget(t.path,h),c}}}const _T=new bT,Ru=new WeakMap,wT=De.prototype.clone;De.prototype.clone=function(){const o=wT.call(this);return Ru.has(o)||Ru.set(o,this),o};class _x extends Ji{constructor(){super([Tc,Hs])}onSerialize(e,t){}onDeserialize(e,t){if(e instanceof De&&t.type===Tc){let s=e;Ru.has(s)&&(s=Ru.get(s)),s.isRenderTargetTexture=!0,s.flipY=!0,s.offset.y=1,s.repeat.y=-1,s.needsUpdate=!0,s.mipmaps=[],s instanceof $C&&(s.isCompressedTexture=!1,s.format=md);const n=new Tc(s.image.width,s.image.height,{colorSpace:On});return n.texture=s,n}}}new _x;class wx extends Ji{constructor(){super([URL])}onSerialize(e,t){return null}onDeserialize(e,t){if(typeof e=="string"&&e.length>0)return fo(t.gltfId,e)}}new wx;var xT=Object.defineProperty,ST=(o,e,t,s)=>{for(var n=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=l(e,t,n)||n);return n&&xT(e,t,n),n};class qa extends I{awake(){ti.createIfNoneExists(this.context)}onEnable(){var e;(e=ti.get(this.context))==null||e.register(this)}onDisable(){var e;(e=ti.get(this.context))==null||e.unregister(this)}}class Li extends qa{constructor(){super(...arguments),a(this,"targets",null),a(this,"raycastHits",[]),a(this,"ignoreSkinnedMeshes",!1)}start(){this.targets=[this.gameObject]}performRaycast(e=null){if(!this.targets)return null;e??(e=new Qs),e.targets=this.targets,e.results=this.raycastHits,e.useAcceleratedRaycast=!0;const t=e.testObject;this.ignoreSkinnedMeshes&&(e.testObject=n=>n instanceof Pn?"continue in children":t?t(n):!0);const s=this.context.physics.raycast(e);return e.testObject=t,s}}ST([m()],Li.prototype,"ignoreSkinnedMeshes");class Tu extends Li{constructor(){super(),this.ignoreSkinnedMeshes=!0}}const xx=class mC extends qa{performRaycast(e){if(!ne.active||!mC.allow||!(e!=null&&e.ray))return null;const t=e.ray.origin;return this.context.physics.sphereOverlap(t,.015,!1,!0)}};a(xx,"allow",!0);let Lc=xx;class jf{static getObject(e){const t=e[ki];return t&&(t.isComponent===!0?e=t.gameObject:e=t),e}static isInteractable(e,t){if(t&&(t.canvasGroup=void 0,t.graphic=void 0),e==null||!e.visible||(e=this.getObject(e),!e.visible))return!1;const s=this.tryFindCanvasGroup(e);if(s?.isCanvasGroup===!0&&(t&&(t.canvasGroup=s),s.blocksRaycasts===!1||s.interactable===!1))return!1;const n=Rr(e,r=>{if(r.isGraphic===!0)return r},!1);return t&&n?.isGraphic===!0&&(t.graphic=n),!(n?.raycastTarget===!1||n?.layer===2)}static tryFindCanvasGroup(e){if(!e)return null;const t=Rr(e,s=>{const n=s;if(n.blocksRaycasts!==void 0&&n.interactable!==void 0)return n},!1);return t!==void 0?t:this.tryFindCanvasGroup(e.parent)}}function Df(o){return o[ki]||(o.parent?Df(o.parent):null)}function CT(o){return o.isUI===!0||typeof o[ki]=="object"}function Eu(o,e){if(!o)return;const t=o.material;if(t?.isMaterial===!0){const s=o.parent;s&&s.isText,t.side=e.doubleSided??!0?Ci:go,t.shadowSide=e.doubleSided?Ci:go,o.castShadow=e.castShadows?e.castShadows:!1,o.receiveShadow=e.receiveShadows?e.receiveShadows:!1}for(const s of o.children)Eu(s,e)}function Xa(o,e,t){o[e]===void 0&&console.warn("Field",e,"is undefined on",o);const s=Proxy.revocable(o[e],{set(l,c,h,d){const u=l[c],p=Reflect.set(l,c,h,d);return t(h,u),p}}),n=s.revoke,r=o[e];return s.revoke=()=>{o[e]=r,n()},o[e]=s.proxy,s}const Sx=Symbol("Scheduled action");function PT(o,e,t=Oe.OnBeforeRender){let s=o[Sx];s||(s=o[Sx]={});const n=e.name;s[t]||(s[t]={});const r=s[t];if(r[n])return;function*l(){e?.call(o),r[n]=null}const c=o.startCoroutine(l(),t);r[n]=c}const To=C("debugeventsystem");var Bf=(o=>(o.BeforeHandleInput="BeforeHandleInput",o.AfterHandleInput="AfterHandleInput",o))(Bf||{});mx(o=>{ti.createIfNoneExists(o)});class ti extends I{constructor(){super(...arguments),a(this,"raycaster",[]),a(this,"pressedByID",new Map),a(this,"hoveredByID",new Map),a(this,"onPointerEvent",e=>{if(e===void 0||e.propagationStopped||e.defaultPrevented||e.used)return;const t=new ad(this.context.input,e);this._currentPointerEventName=e.type,t.inputSource=this.context.input,t.isClick=e.isClick,t.isDoubleClick=e.isDoubleClick,t.isDown=e.type==Fe.PointerDown,t.isUp=e.type==Fe.PointerUp,t.isPressed=this.context.input.getPointerPressed(e.pointerId),To&&(t.isDown?console.log("DOWN",t.pointerId):t.isUp&&console.log("UP",t.pointerId),t.isClick&&console.log("CLICK",t.pointerId));const s=new Qs;e.hasRay?s.ray=e.ray:s.screenPoint=this.context.input.getPointerPositionRC(e.pointerId);const n=this.performRaycast(s);if(n){for(const l of n)l.event=e,e.intersections.push(l);e.origin.onPointerHits&&e.origin.onPointerHits({sender:this,event:e,hits:n})}To&&t.isClick&&Be("EventSystem: "+t.pointerId+" - "+this.context.time.frame+" - Up:"+t.isUp+", Down:"+t.isDown);const r={sender:this,args:t,hasActiveUI:this.currentActiveMeshUIComponents.length>0};this.dispatchEvent(new CustomEvent("BeforeHandleInput",{detail:r})),this.handleIntersections(n,t),this.dispatchEvent(new CustomEvent("AfterHandleInput",{detail:r}))}),a(this,"_sortedHits",[]),a(this,"_testObjectsCache",new Map),a(this,"_currentlyActiveRaycaster",null),a(this,"_currentPointerEventName",null),a(this,"shouldRaycastObject",e=>{var t;const s=e&&"getComponent"in e?e.getComponent(qa):null;if(s&&s!=this._currentlyActiveRaycaster)return!1;let n=null;if(CT(e)&&(n=(t=e[ki])==null?void 0:t.gameObject),this._testObjectsCache.has(e)||n&&this._testObjectsCache.has(n))return this._testObjectsCache.get(e)===!1?"continue in children":!0;{let r=Ou(e,this._currentPointerEventName);if(!r&&n&&(r=Ou(n,this._currentPointerEventName)),r){this._testObjectsCache.set(e,!0);for(const l of e.children)this.shouldRaycastObject_AddToYesCache(l);return!0}return this._testObjectsCache.set(e,!1),"continue in children"}}),a(this,"_sortingBuffer",[]),a(this,"_noDepthTestingResults",[]),a(this,"out",{}),a(this,"_capturedPointer",{}),a(this,"pointerEnterSymbol",Symbol("pointerEnter")),a(this,"pointerExitSymbol",Symbol("pointerExit")),a(this,"currentActiveMeshUIComponents",[])}static ensureUpdateMeshUI(e,t,s=!1){Eo.update(e,t,s)}static markUIDirty(e){Eo.markDirty()}static createIfNoneExists(e){e.scene.getComponent(ti)||e.scene.addComponent(ti)}static get(e){return this.createIfNoneExists(e),e.scene.getComponent(ti)}static get instance(){return this.get(ee.Current)}register(e){var t;e&&this.raycaster&&!this.raycaster.includes(e)&&((t=this.raycaster)==null||t.push(e))}unregister(e){var t,s;const n=(t=this.raycaster)==null?void 0:t.indexOf(e);n!==void 0&&n!==-1&&((s=this.raycaster)==null||s.splice(n,1))}get hasActiveUI(){return this.currentActiveMeshUIComponents.length>0}get isHoveringObjects(){return this.hoveredByID.size>0}awake(){this.gameObject!==this.context.scene&&(console.debug(`[Needle Engine] EventSystem is only allowed on the scene root. Disabling EventSystem on '${this.gameObject.name}'`),this.enabled=!1)}start(){this.context.scene.getComponent(qa)||this.context.scene.addComponent(Li)}onEnable(){this.context.input.addEventListener(Fe.PointerDown,this.onPointerEvent),this.context.input.addEventListener(Fe.PointerUp,this.onPointerEvent),this.context.input.addEventListener(Fe.PointerMove,this.onPointerEvent)}onDisable(){this.context.input.removeEventListener(Fe.PointerDown,this.onPointerEvent),this.context.input.removeEventListener(Fe.PointerUp,this.onPointerEvent),this.context.input.removeEventListener(Fe.PointerMove,this.onPointerEvent)}onBeforeRender(){this.resetMeshUIStates()}shouldRaycastObject_AddToYesCache(e){this._testObjectsCache.set(e,!0);for(const t of e.children)this.shouldRaycastObject_AddToYesCache(t)}performRaycast(e){if(!this.raycaster)return null;this._testObjectsCache.clear(),this._sortedHits.length=0,e||(e=new Qs),e.testObject=this.shouldRaycastObject;for(const t of this.raycaster){if(!t.activeAndEnabled)continue;this._currentlyActiveRaycaster=t;const s=t.performRaycast(e);this._currentlyActiveRaycaster=null,s&&s.length>0&&this._sortedHits.push(...s)}return this._sortedHits.sort((t,s)=>t.distance-s.distance),this._sortedHits}assignHitInformation(e,t){t?(e.intersection=t,e.point=t.point,e.normal=t.normal,e.face=t.face,e.distance=t.distance,e.instanceId=t.instanceId):(e.intersection=void 0,e.point=void 0,e.normal=void 0,e.face=void 0,e.distance=void 0,e.instanceId=void 0)}handleIntersections(e,t){var s;if(e!=null&&e.length){e=this.sortCandidates(e);for(const r of e){if(t.event.immediatePropagationStopped)return!1;if(this.assignHitInformation(t,r),this.handleEventOnObject(r.object,t))return!0}}this.assignHitInformation(t,e?.[0]),this.invokePointerCapture(t);const n=this.hoveredByID.get(t.pointerId);return n&&this.propagatePointerExit(n.obj,n.data,null),this.hoveredByID.delete(t.pointerId),t.isUp&&((s=this.pressedByID.get(t.pointerId))==null||s.handlers.forEach(r=>this.invokeOnPointerUp(t,r)),this.pressedByID.delete(t.pointerId)),!1}sortCandidates(e){this._sortingBuffer.length=0,this._noDepthTestingResults.length=0;for(let t=0;t<e.length;t++){const s=e[t],n=s.object;if(n.material&&n.material.depthTest===!1){this._noDepthTestingResults.push(s);continue}this._sortingBuffer.push(s)}for(const t of this._sortingBuffer)this._noDepthTestingResults.push(t);return this._noDepthTestingResults}handleEventOnObject(e,t){if(!this.testIsVisible(e))return t.isClick&&To&&console.log("not allowed",e),!1;if(t.pointerId===void 0)return To&&console.error("Event without pointer can't be handled",t),!1;t.object=e;const s=e.parent,n=t.isClick??!1;let r=null;if(s&&s.isUI){const d=(t.isPressed||t.isClick)??!1;if(s[ki]){const u=s[ki].gameObject;if(u){if(!jf.isInteractable(u,this.out))return!1;r=this.out.canvasGroup??null,this.handleMeshUIIntersection(e,d),e=u}}}n&&To&&console.log(this.context.time.frame,e);const l=this.hoveredByID.get(t.pointerId),c=l?.obj;c!==e&&c&&this.propagatePointerExit(c,l.data,e);const h=this.hoveredByID.get(t.pointerId);if(h?(h.obj=e,h.data=t):this.hoveredByID.set(t.pointerId,{obj:e,data:t}),t.isDown){const d=this.pressedByID.get(t.pointerId);d?(d.obj=e,d.data=t):this.pressedByID.set(t.pointerId,{obj:e,data:t,handlers:new Set})}return(r===null||r.interactable)&&this.handleMainInteraction(e,t,c??null),!0}propagate(e,t){for(;e;)P.foreachComponent(e,s=>{t(s)},!1),e=e.parent}handleMainInteraction(e,t,s){const n=this.pressedByID.get(t.pointerId),r=s!==e;let l=!0;switch(t.event.pointerType){case"mouse":case"touch":const c=this.context.input.getPointerPositionLastFrame(t.pointerId),h=this.context.input.getPointerPosition(t.pointerId);l=c&&!W.approximately(c,h);break}this.propagate(e,c=>{var h;const d=c;d.interactable!==!1&&(!d.activeAndEnabled||!d.enabled||(d.onPointerEnter&&r&&this.handlePointerEnter(d,t),t.isDown&&d.onPointerDown&&(d.onPointerDown(t),n?.handlers.add(d),this.handlePointerCapture(t,d)),d.onPointerMove&&(l&&d.onPointerMove(t),this.handlePointerCapture(t,d)),t.isUp&&(d.onPointerUp&&(this.invokeOnPointerUp(t,d),n?.handlers.delete(d)),d.onPointerExit&&((h=t.event)==null?void 0:h.pointerType)===Bd.Touch&&(this.handlePointerExit(d,t),this.hoveredByID.delete(t.pointerId))),t.isClick&&d.onPointerClick&&d.onPointerClick(t)))}),t.isUp&&(n?.handlers.forEach(c=>{this.invokeOnPointerUp(t,c)}),this.pressedByID.delete(t.pointerId))}propagatePointerExit(e,t,s){this.propagate(e,n=>{if(!n.gameObject||n.destroyed)return;const r=n;if(r.onPointerExit||r.onPointerEnter){if(s&&this.isChild(s,n.gameObject))return;this.handlePointerExit(r,t)}})}invokeOnPointerUp(e,t){var s;(s=t.onPointerUp)==null||s.call(t,e),this.releasePointerCapture(e,t)}handlePointerEnter(e,t){e.onPointerEnter&&this.updatePointerState(e,t.pointerId,this.pointerEnterSymbol,!0)&&e.onPointerEnter(t),this.updatePointerState(e,t.pointerId,this.pointerExitSymbol,!1)}handlePointerExit(e,t){e.onPointerExit&&this.updatePointerState(e,t.pointerId,this.pointerExitSymbol,!0)&&e.onPointerExit(t),this.updatePointerState(e,t.pointerId,this.pointerEnterSymbol,!1)}updatePointerState(e,t,s,n){let r=e[s];if(n)return r&&r.includes(t)?!1:(r=r||[],r.push(t),e[s]=r,!0);{if(!r||!r.includes(t))return!1;const l=r.indexOf(t);return l!==-1&&r.splice(l,1),!0}}handlePointerCapture(e,t){if(e.z__pointer_ctured){e.z__pointer_ctured=!1;const s=e.pointerId;if(t.onPointerMove){const n=this._capturedPointer[s]||[];n.push(t),this._capturedPointer[s]=n}else F()&&!t.z__warned_no_pointermove&&(t.z__warned_no_pointermove=!0,console.warn("PointerCapture was requested but the component doesn't implement onPointerMove. It will not receive any pointer events"))}else e.z__pointer_cture_rleased&&(e.z__pointer_cture_rleased=!1,this.releasePointerCapture(e,t))}releasePointerCapture(e,t){const s=e.pointerId;if(this._capturedPointer[s]){const n=this._capturedPointer[s].indexOf(t);n!==-1&&(this._capturedPointer[s].splice(n,1),To&&console.log("released pointer capture",s,t,this._capturedPointer))}}invokePointerCapture(e){var t;if(e.event.type===Fe.PointerMove){const s=e.pointerId,n=this._capturedPointer[s];if(n){To&&console.log("Captured",s,n);for(let r=0;r<n.length;r++){const l=n[r];if(l.destroyed){n.splice(r,1),r--;continue}(t=l.onPointerMove)==null||t.call(l,e)}}}}isChild(e,t){return!e||!t?!1:e===t?!0:e.parent?this.isChild(e.parent,t):!1}handleMeshUiObjectWithoutShadowDom(e,t){return!e||!e.isUI?!0:this.handleMeshUIIntersection(e,t)}handleMeshUIIntersection(e,t){const s=Eo.updateState(e,t);return s&&this.currentActiveMeshUIComponents.push(s),s!==null}resetMeshUIStates(){if(this.context.input.getPointerPressedCount()>0&&Eo.resetLastSelected(),!(!this.currentActiveMeshUIComponents||this.currentActiveMeshUIComponents.length<=0)){for(let e=0;e<this.currentActiveMeshUIComponents.length;e++){const t=this.currentActiveMeshUIComponents[e];Eo.resetState(t)}this.currentActiveMeshUIComponents.length=0}}testIsVisible(e){return e?P.isActiveSelf(e)?this.testIsVisible(e.parent):!1:!0}}class Eo{static markDirty(){this.needsUpdate=!0}static update(e,t,s=!1){if(s){e.update();return}const n=t.time.frameCount;for(const r of this.lastUpdateFrame)if(r.context===t){if(n===r.frame)return;r.frame=n;let l=this.needsUpdate||n<1;r.nextUpdate<=n&&(l=!0),l&&(To&&console.log("Update threemeshui"),this.needsUpdate=!1,r.nextUpdate=n+60,e.update());return}this.lastUpdateFrame=[{context:t,frame:n,nextUpdate:n+60}],e.update(),this.needsUpdate=!1}static updateState(e,t){let s=null;if(e&&(s=this.findBlockOrTextInParent(e),s&&s!==this.lastSelected)){if(s.interactable===!1)return null;this.needsUpdate=!0}return s}static resetLastSelected(){const e=this.lastSelected;e&&(this.lastSelected=null,this.resetState(e))}static resetState(e){e&&(this.needsUpdate=!0)}static findBlockOrTextInParent(e){return e?e.isBlock||e.isText?e:this.findBlockOrTextInParent(e.parent):null}}a(Eo,"lastSelected",null),a(Eo,"lastUpdateFrame",[]),a(Eo,"needsUpdate",!1);var OT=Object.defineProperty,ze=(o,e,t,s)=>{for(var n=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=l(e,t,n)||n);return n&&OT(e,t,n),n};const ts=C("debugorbit"),Ff=C("freecam"),jc=C("debugcamerafit"),Au=C("smoothcam"),kT={LEFT:"",UP:"",RIGHT:"",BOTTOM:""};let Uf;class Dc extends CustomEvent{constructor(e,t){super("target-reached",{detail:{controls:e,type:t}})}}class _e extends I{constructor(){super(...arguments),a(this,"autoTarget",!0),a(this,"autoFit",!1),a(this,"enableRotate",!0),a(this,"autoRotate",!1),a(this,"autoRotateSpeed",1),a(this,"minAzimuthAngle",1/0),a(this,"maxAzimuthAngle",1/0),a(this,"minPolarAngle",0),a(this,"maxPolarAngle",Math.PI),a(this,"enableKeys",!1),a(this,"enableDamping",!0),a(this,"dampingFactor",.1),a(this,"enableZoom",!0),a(this,"minZoom",0),a(this,"maxZoom",1/0),a(this,"zoomSpeed",1),a(this,"zoomToCursor",!1),a(this,"enablePan",!0),a(this,"lookAtConstraint",null),a(this,"lookAtConstraint01",1),a(this,"allowInterrupt",!0),a(this,"middleClickToFocus",!0),a(this,"doubleClickToFocus",!0),a(this,"clickBackgroundToFitScene",2),a(this,"debugLog",!1),a(this,"targetLerpDuration",1),a(this,"_controls",null),a(this,"_cameraObject",null),a(this,"_lookTargetLerpActive",!1),a(this,"_lookTargetStartPosition",new x),a(this,"_lookTargetEndPosition",new x),a(this,"_lookTargetLerp01",0),a(this,"_lookTargetLerpDuration",0),a(this,"_cameraLerpActive",!1),a(this,"_cameraStartPosition",new x),a(this,"_cameraEndPosition",new x),a(this,"_cameraLerp01",0),a(this,"_cameraLerpDuration",0),a(this,"_fovLerpActive",!1),a(this,"_fovLerpStartValue",0),a(this,"_fovLerpEndValue",0),a(this,"_fovLerp01",0),a(this,"_fovLerpDuration",0),a(this,"_inputs",0),a(this,"_enableTime",0),a(this,"_startedListeningToKeyEvents",!1),a(this,"_eventSystem"),a(this,"_afterHandleInputFn"),a(this,"_camera",null),a(this,"_syncedTransform"),a(this,"_didSetTarget",0),a(this,"targetElement",null),a(this,"_activePointerEvents"),a(this,"_lastTimeClickOnBackground",-1),a(this,"_clickOnBackgroundCount",0),a(this,"_onPointerDown",e=>{this._activePointerEvents.push(e)}),a(this,"_onPointerDownLate",e=>{e.used&&this._controls&&(this._controls.enabled=!1)}),a(this,"_onPointerUp",e=>{for(let t=this._activePointerEvents.length-1;t>=0;t--){const s=this._activePointerEvents[t];if(s.pointerId===e.pointerId&&s.button===e.button){this._activePointerEvents.splice(t,1);break}}if(this.clickBackgroundToFitScene>0&&e.isClick&&e.button===0){if(e.hasRay||e.intersections.push(...this.context.physics.raycast()),e.intersections.length<=0){const t=this.context.time.time-this._lastTimeClickOnBackground;this._lastTimeClickOnBackground=this.context.time.time,this.clickBackgroundToFitScene<=1||t<this.clickBackgroundToFitScene*.15?(this._clickOnBackgroundCount+=1,this._clickOnBackgroundCount>=this.clickBackgroundToFitScene-1&&this.fitCamera(this.context.scene.children,{immediate:!1})):this._clickOnBackgroundCount=0}ts&&console.log(this.clickBackgroundToFitScene,e.intersections.length,this._clickOnBackgroundCount)}}),a(this,"_onPointerUpLate",e=>{this.doubleClickToFocus&&e.isDoubleClick&&!e.used&&this.setTargetFromRaycast()}),a(this,"_orbitStartAngle",0),a(this,"onControlsChangeStarted",()=>{this._controls&&(this._orbitStartAngle=this._controls.getAzimuthalAngle()+this._controls.getPolarAngle()),this._syncedTransform&&this._syncedTransform.requestOwnership()}),a(this,"onControlsChangeEnded",()=>{if(this._controls&&this.autoTarget){const e=this._controls.getAzimuthalAngle()+this._controls.getPolarAngle()-this._orbitStartAngle;Math.abs(e)<.01?(ts&&console.debug("OrbitControls: No movement detected, updating target now"),this.updateTargetNow()):ts&&console.debug("OrbitControls: Movement detected",e)}}),a(this,"_shouldDisable",!1),a(this,"__onPreRender",()=>{const e=this.context.pre_render_callbacks.indexOf(this.__onPreRender);e>=0&&this.context.pre_render_callbacks.splice(e,1),this.autoFit&&(this.autoFit=!1,this.fitCamera({centerCamera:"y",immediate:!0,objects:this.scene.children}))}),a(this,"_haveAttachedKeyboardEvents",!1)}get isCameraController(){return!0}get controls(){return this._controls}get controllerObject(){return this._cameraObject}onStartInteraction(e){var t;(t=this.controls)==null||t.addEventListener("start",e)}get targetLerpSpeed(){return 5}set targetLerpSpeed(e){this.targetLerpDuration=1/e}awake(){ts&&console.debug("OrbitControls",this),this._didSetTarget=0,this._startedListeningToKeyEvents=!1}start(){this._eventSystem=ti.get(this.context)??void 0,this._eventSystem&&(this._afterHandleInputFn=this.afterHandleInput.bind(this),this._eventSystem.addEventListener(Bf.AfterHandleInput,this._afterHandleInputFn))}onDestroy(){var e,t;(e=this._controls)==null||e.dispose(),(t=this._eventSystem)==null||t.removeEventListener(Bf.AfterHandleInput,this._afterHandleInputFn)}onEnable(){this._didSetTarget=0,this._enableTime=this.context.time.time;const e=P.getComponent(this.gameObject,li);this._camera=e;let t=e?.threeCamera;if(!t&&this.gameObject instanceof we&&(t=this.gameObject),t&&tg(t,this,!0),!this._controls&&t instanceof E){this._cameraObject=t;const s=this.targetElement??this.context.renderer.domElement,n=t?.quaternion.clone();this._controls=new Uv(t,s),t?.quaternion.copy(n),Uf===void 0&&(Uf={...this._controls.keys});const r=te(t),l=this.gameObject.worldForward,c=r.clone().sub(l.multiplyScalar(2.5));this._controls.target.copy(c)}if(this._controls)if(Ff&&(this.enablePan=!0,this.enableZoom=!0,this.middleClickToFocus=!0,Y.isMobileDevice()&&(this.doubleClickToFocus=!0)),this._controls.addEventListener("start",this.onControlsChangeStarted),this._controls.addEventListener("end",this.onControlsChangeEnded),!this._startedListeningToKeyEvents&&this.enableKeys)this._startedListeningToKeyEvents=!0,this._controls.listenToKeyEvents(this.context.domElement);else try{this._controls.stopListenToKeyEvents()}catch{}this._syncedTransform=P.getComponent(this.gameObject,sn)??void 0,this.context.pre_render_callbacks.push(this.__onPreRender),this._activePointerEvents=[],this.context.input.addEventListener("pointerdown",this._onPointerDown,{queue:ni.Early}),this.context.input.addEventListener("pointerdown",this._onPointerDownLate,{queue:ni.Late}),this.context.input.addEventListener("pointerup",this._onPointerUp,{queue:ni.Early}),this.context.input.addEventListener("pointerup",this._onPointerUpLate,{queue:ni.Late})}onDisable(){var e;if((e=this._camera)!=null&&e.threeCamera&&tg(this._camera.threeCamera,this,!1),this._controls){this._controls.enabled=!1,this._controls.autoRotate=!1,this._controls.removeEventListener("start",this.onControlsChangeStarted),this._controls.removeEventListener("end",this.onControlsChangeEnded);try{this._controls.stopListenToKeyEvents()}catch{}this._startedListeningToKeyEvents=!1}this._activePointerEvents.length=0,this.context.input.removeEventListener("pointerdown",this._onPointerDown),this.context.input.removeEventListener("pointerdown",this._onPointerDownLate),this.context.input.removeEventListener("pointerup",this._onPointerUp),this.context.input.removeEventListener("pointerup",this._onPointerUpLate)}updateTargetNow(){var e,t,s;const n=new uo((e=this._cameraObject)==null?void 0:e.worldPosition,(t=this._cameraObject)==null?void 0:t.worldForward.multiplyScalar(-1)),r=this.context.physics.raycastFromRay(n),l=r.length>0?r[0]:void 0;l&&l.distance>this.minZoom&&l.distance<this.maxZoom&&(ts&&G.DrawWireSphere(l.point,.1,16711680,2),(s=this._controls)==null||s.target.copy(r[0].point))}afterHandleInput(e){e.detail.args.pointerId===0&&(e.detail.args.isDown?this._controls&&this._eventSystem&&(this._shouldDisable=this._eventSystem.hasActiveUI):(!e.detail.args.isPressed||e.detail.args.isUp)&&(this._shouldDisable=!1))}onBeforeRender(){var e,t,s,n;if(!!this._controls){if(this._cameraObject!==this.context.mainCamera){this._controls.enabled=!1;return}if(this._controls.enabled=!0,(this.context.input.getPointerDown(1)||this.context.input.getPointerDown(2)||this.context.input.mouseWheelChanged||this.context.input.getPointerPressed(0)&&(e=this.context.input.getPointerPositionDelta(0))!=null&&e.length())&&(this._inputs+=1),this._inputs>0&&this.allowInterrupt&&(this.enableRotate&&(this.autoRotate=!1),this._cameraLerpActive=!1,this._lookTargetLerpActive=!1),this._inputs=0,this.autoTarget&&this._didSetTarget++===0){const r=P.getComponent(this.gameObject,li);if(r&&!this.setLookTargetFromConstraint()){this.debugLog&&console.log("NO TARGET");const l=te(r.threeCamera),c=Math.max(.01,l.length()),h=new x(0,0,-c).applyMatrix4(r.threeCamera.matrixWorld);ts&&G.DrawLine(l,h,5592575,10),this.setLookTargetPosition(h,!0)}if(!this.setLookTargetFromConstraint()){const l=new Qs;l.screenPoint=new le(0,0),l.lineThreshold=.1;const c=this.context.physics.raycast(l);c.length>0&&this.setLookTargetPosition(c[0].point,!0),jc&&console.log("OrbitControls hits",...c)}}if(this.middleClickToFocus&&this.context.input.getPointerClicked(1)&&this.setTargetFromRaycast(),this._lookTargetLerpActive||this._cameraLerpActive||this._fovLerpActive){if(this._cameraLerpActive&&this._cameraObject)if(this._cameraLerp01+=this.context.time.deltaTime/this._cameraLerpDuration,this._cameraLerp01>=1)this._cameraObject.position.copy(this._cameraEndPosition),this._cameraLerpActive=!1,this.dispatchEvent(new Dc(this,"camera"));else{const r=W.easeInOutCubic(this._cameraLerp01);this._cameraObject.position.lerpVectors(this._cameraStartPosition,this._cameraEndPosition,r)}if(this._lookTargetLerpActive)if(this._lookTargetLerp01+=this.context.time.deltaTime/this._lookTargetLerpDuration,this._lookTargetLerp01>=1)this._controls.target.copy(this._lookTargetEndPosition),this._lookTargetLerpActive=!1,this.dispatchEvent(new Dc(this,"lookat"));else{const r=W.easeInOutCubic(this._lookTargetLerp01);this._controls.target.lerpVectors(this._lookTargetStartPosition,this._lookTargetEndPosition,r)}if(this._fovLerpActive&&this._cameraObject){const r=this._cameraObject;if(this._fovLerp01+=this.context.time.deltaTime/this._fovLerpDuration,this._fovLerp01>=1)r.fov=this._fovLerpEndValue,this._fovLerpActive=!1;else{const l=W.easeInOutCubic(this._fovLerp01);r.fov=W.lerp(this._fovLerpStartValue,this._fovLerpEndValue,l)}r.updateProjectionMatrix()}}if(this._controls){if(this.debugLog&&(this._controls.domElement=this.context.renderer.domElement),this._controls.enabled=!this._shouldDisable&&this._camera===this.context.mainCameraComponent&&!this.context.isInXR&&!this._activePointerEvents.some(r=>r.used),this._controls.keys=this.enableKeys?Uf:kT,this._controls.autoRotate=this.autoRotate,this._controls.autoRotateSpeed=this.autoRotateSpeed,this._controls.enableZoom=this.enableZoom,this._controls.zoomSpeed=this.zoomSpeed,this._controls.zoomToCursor=this.zoomToCursor,this._controls.enableDamping=this.enableDamping,this._controls.dampingFactor=this.dampingFactor,this._controls.enablePan=this.enablePan,this._controls.enableRotate=this.enableRotate,this._controls.minAzimuthAngle=this.minAzimuthAngle,this._controls.maxAzimuthAngle=this.maxAzimuthAngle,this._controls.minPolarAngle=this.minPolarAngle,this._controls.maxPolarAngle=this.maxPolarAngle,Ff||(((s=(t=this._camera)==null?void 0:t.threeCamera)==null?void 0:s.type)==="PerspectiveCamera"?(this._controls.minDistance=this.minZoom,this._controls.maxDistance=this.maxZoom,this._controls.minZoom=0,this._controls.maxZoom=1/0):(this._controls.minDistance=0,this._controls.maxDistance=1/0,this._controls.minZoom=this.minZoom,this._controls.maxZoom=this.maxZoom)),typeof Au=="number"||Au===!0){this._controls.enableDamping=!0;const r=typeof Au=="number"?Au:.99;this._controls.dampingFactor=Math.max(.001,1-Math.min(1,r))}this.allowInterrupt||(this._lookTargetLerpActive&&(this._controls.enablePan=!1),this._cameraLerpActive&&(this._controls.enableRotate=!1,this._controls.autoRotate=!1),(this._lookTargetLerpActive||this._cameraLerpActive)&&(this._controls.enableZoom=!1)),this.context.isInXR||(!Ff&&(n=this.lookAtConstraint)!=null&&n.locked&&this.setLookTargetFromConstraint(0,this.lookAtConstraint01),this._controls.update(this.context.time.deltaTime),ts&&G.DrawWireSphere(this._controls.target,.1,65280))}}}setCameraAndLookTarget(e,t=!1){if(!e)return(F()||ts)&&console.warn("[OrbitControls] setCameraAndLookTarget target is null"),!1;if(!(e instanceof E)&&!(e instanceof li))return(F()||ts)&&console.warn("[OrbitControls] setCameraAndLookTarget target is not an Object3D or Camera"),!1;e instanceof li&&(e=e.gameObject);const s=e.worldPosition,n=e.worldForward;e instanceof GC&&(ts&&console.debug("[OrbitControls] setCameraAndLookTarget flip forward direction for camera"),n.multiplyScalar(-1));const r=new uo(s,n);return ts&&G.DrawRay(r.origin,r.direction,16711680,10),this.setTargetFromRaycast(r,t)||this.setLookTargetPosition(r.at(2,X()),t),this.setCameraTargetPosition(s,t),!0}setCameraTargetPosition(e,t=!1){var s;e&&(e instanceof E&&(e=te(e)),this._cameraEndPosition||(this._cameraEndPosition=new x),this._cameraEndPosition.copy(e),t===!0?(this._cameraLerpActive=!1,this._cameraObject&&this._cameraObject.position.copy(this._cameraEndPosition)):this._cameraObject&&(this._cameraLerpActive=!0,this._cameraLerp01=0,this._cameraStartPosition.copy((s=this._cameraObject)==null?void 0:s.position),typeof t=="number"?this._cameraLerpDuration=t:this._cameraLerpDuration=this.targetLerpDuration))}get cameraLerpActive(){return this._cameraLerpActive}stopCameraLerp(){this._cameraLerpActive=!1}setFieldOfView(e,t=!1){var s;if(!this._controls||typeof e!="number")return;const n=(s=this._camera)==null?void 0:s.threeCamera;n&&(t===!0?n.fov=e:(this._fovLerpActive=!0,this._fovLerp01=0,this._fovLerpStartValue=n.fov,this._fovLerpEndValue=e,typeof t=="number"?this._fovLerpDuration=t:this._fovLerpDuration=this.targetLerpDuration))}setLookTargetPosition(e=null,t=!1){this._controls&&e&&(e instanceof E&&(e=te(e)),this._lookTargetEndPosition.copy(e),this._didSetTarget++,ts&&(console.warn("OrbitControls: setLookTargetPosition",e,t),G.DrawWireSphere(this._lookTargetEndPosition,.2,16711680,2)),t===!0?this._controls.target.copy(this._lookTargetEndPosition):(this._lookTargetLerpActive=!0,this._lookTargetLerp01=0,this._lookTargetStartPosition.copy(this._controls.target),typeof t=="number"?this._lookTargetLerpDuration=t:this._lookTargetLerpDuration=this.targetLerpDuration))}get lookTargetLerpActive(){return this._lookTargetLerpActive}stopLookTargetLerp(){this._lookTargetLerpActive=!1}setLookTargetFromConstraint(e=0,t=1){var s,n;if(!this._controls||((s=this.lookAtConstraint)==null?void 0:s.enabled)===!1)return!1;const r=(n=this.lookAtConstraint)==null?void 0:n.sources;if(r&&r.length>0){const l=r[e];if(l)return l.getWorldPosition(this._lookTargetEndPosition),this.lerpLookTarget(this._lookTargetEndPosition,t),!0}return!1}lerpTarget(e,t){return this.lerpLookTarget(e,t)}lerpLookTarget(e,t){this._controls&&(t>=1?this._controls.target.copy(e):this._controls.target.lerp(e,t))}setTargetFromRaycast(e,t=!1){if(!this.controls)return!1;const s=e?this.context.physics.raycastFromRay(e):this.context.physics.raycast();for(const n of s)if(n.distance>0&&P.isActiveInHierarchy(n.object)){const r=Df(n.object);if(r){const l=r.canvas;if(l!=null&&l.screenspace)break}return this.setLookTargetPosition(n.point,t),!0}return!1}fitCamera(e,t){var s,n;if(this.context.isInXR)return;let r;if(Array.isArray(e)?r=e:e&&"type"in e?r=e.children:e&&typeof e=="object"&&!(e instanceof E)&&!Array.isArray(e)&&(t=e,r=t.objects),r&&!Array.isArray(r)&&(r=r.children),(!Array.isArray(r)||r&&r.length<=0)&&(r=this.context.scene.children),!Array.isArray(r)||r.length<=0){console.warn("No objects to fit camera to...");return}const l=this._cameraObject,c=this._controls;if(!l||!c){console.warn("No camera or controls found to fit camera to objects...");return}t||(t={});const{immediate:h=!1,centerCamera:d="y",cameraNearFar:u="auto",fitOffset:p=1.1,fov:g=l?.fov}=t,f=new x,y=new x,b=ii(r,void 0,(n=(s=this._camera)==null?void 0:s.threeCamera)==null?void 0:n.layers),v=b.clone();l.updateMatrixWorld(),l.updateProjectionMatrix(),b.getCenter(y);const _=new x;if(b.getSize(_),b.applyMatrix4(l.matrixWorldInverse),b.getSize(f),b.setFromCenterAndSize(y,f),Number.isNaN(f.x)||Number.isNaN(f.y)||Number.isNaN(f.z)){console.warn("Camera fit size resultet in NaN",l,b,[...r]);return}if(f.length()<=1e-10){jc&&console.warn("Camera fit size is zero",b,[...r]);return}const w=t.fov||l.fov,S=2*Math.atan(Math.tan(w*Math.PI/360/2)*l.aspect)/Math.PI*360,k=f.y/(2*Math.atan(Math.PI*w/360)),M=f.x/(2*Math.atan(Math.PI*S/360)),T=p*Math.max(k,M)+f.z/2;jc&&console.log("Fit camera to objects",{fitHeightDistance:k,fitWidthDistance:M,distance:T,verticalFov:w,horizontalFov:S}),this.maxZoom=T*10,this.minZoom=T*.01;const L=.05,B=y.clone();if(B.y-=f.y*L,this.setLookTargetPosition(B,h),this.setFieldOfView(t.fov,h),u==null||u=="auto"){const U=P.findObjectOfType(en),j=U?U.radius:0,Q=Math.max(_.x,_.y,_.z,j);l.near=T/100,l.far=Q+T*10,U&&(this.maxZoom=Math.max(Math.min(this.maxZoom,j*.5),T))}const z=c.getDistance();z<this.minZoom&&(this.minZoom=z*.9),z>this.maxZoom&&(this.maxZoom=z*1.1),l.updateMatrixWorld(),l.updateProjectionMatrix();const D=te(l),V=y.clone();V.sub(D),d==="y"&&(V.y=0),V.normalize(),V.multiplyScalar(T),d==="y"&&(V.y+=-L*4*T);let $=y.clone().sub(V);l.parent&&($=l.parent.worldToLocal($)),this.setCameraTargetPosition($,h),(jc||t.debug)&&(G.DrawWireBox3(b,16777011,10),G.DrawWireBox3(v,65280,10),!this._haveAttachedKeyboardEvents&&jc&&(this._haveAttachedKeyboardEvents=!0,document.body.addEventListener("keydown",U=>{if(U.code==="KeyF"){let j;this._cameraObject instanceof we&&(j=Math.random()*Math.random()*170+10),this.fitCamera({objects:r,fitOffset:p,immediate:!1,fov:j})}U.code==="KeyV"&&this._cameraObject instanceof we&&(this._cameraObject.fov=60)}))),this.onBeforeRender()}}ze([m()],_e.prototype,"autoTarget"),ze([m()],_e.prototype,"autoFit"),ze([m()],_e.prototype,"enableRotate"),ze([m()],_e.prototype,"autoRotate"),ze([m()],_e.prototype,"autoRotateSpeed"),ze([m()],_e.prototype,"minAzimuthAngle"),ze([m()],_e.prototype,"maxAzimuthAngle"),ze([m()],_e.prototype,"minPolarAngle"),ze([m()],_e.prototype,"maxPolarAngle"),ze([m()],_e.prototype,"enableKeys"),ze([m()],_e.prototype,"enableDamping"),ze([m()],_e.prototype,"dampingFactor"),ze([m()],_e.prototype,"enableZoom"),ze([m()],_e.prototype,"minZoom"),ze([m()],_e.prototype,"maxZoom"),ze([m()],_e.prototype,"zoomSpeed"),ze([m()],_e.prototype,"enablePan"),ze([m(jr)],_e.prototype,"lookAtConstraint"),ze([m()],_e.prototype,"lookAtConstraint01"),ze([m()],_e.prototype,"allowInterrupt"),ze([m()],_e.prototype,"middleClickToFocus"),ze([m()],_e.prototype,"doubleClickToFocus"),ze([m()],_e.prototype,"clickBackgroundToFitScene"),ze([m()],_e.prototype,"targetLerpDuration");var MT=Object.defineProperty,RT=Object.getOwnPropertyDescriptor,Qt=(o,e,t,s)=>{for(var n=s>1?void 0:s?RT(e,t):e,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=(s?l(e,t,n):l(n))||n);return s&&n&&MT(e,t,n),n},Ao=(o=>(o[o.None=0]="None",o[o.Skybox=1]="Skybox",o[o.SolidColor=2]="SolidColor",o[o.Uninitialized=4]="Uninitialized",o))(Ao||{});const Io=C("debugcam"),Cx=C("debugscreenpointtoray");var Lo;const Ft=(Lo=class extends I{constructor(){super(...arguments),a(this,"_nearClipPlane",.1),a(this,"_farClipPlane",1e3),a(this,"orthographic",!1),a(this,"orthographicSize",5),a(this,"ARBackgroundAlpha",0),a(this,"_cullingMask",4294967295),a(this,"_backgroundBlurriness"),a(this,"_backgroundIntensity"),a(this,"_backgroundRotation"),a(this,"_environmentIntensity"),a(this,"_targetTexture",null),a(this,"_backgroundColor"),a(this,"_fov"),a(this,"_cam",null),a(this,"_clearFlags",2),a(this,"_skybox"),a(this,"_frustum"),a(this,"_projScreenMatrix",new se)}get isCamera(){return!0}get aspect(){return this._cam instanceof we?this._cam.aspect:this.context.domWidth/this.context.domHeight}set aspect(o){this._cam instanceof we&&this._cam.aspect!==o&&(this._cam.aspect=o,this._cam.updateProjectionMatrix())}get fieldOfView(){return this._cam instanceof we?this._cam.fov:this._fov}set fieldOfView(o){const e=this.fieldOfView!=o;if(this._fov=o,e&&this._cam&&this._cam instanceof we){if(this._fov===void 0){console.warn("Can not set undefined fov on PerspectiveCamera");return}this._cam.fov=this._fov,this._cam.updateProjectionMatrix()}}get nearClipPlane(){return this._nearClipPlane}set nearClipPlane(o){const e=this._nearClipPlane!=o;this._nearClipPlane=o,this._cam&&(e||this._cam.near!=o)&&(this._cam.near=o,this._cam.updateProjectionMatrix())}get farClipPlane(){return this._farClipPlane}set farClipPlane(o){const e=this._farClipPlane!=o;this._farClipPlane=o,this._cam&&(e||this._cam.far!=o)&&(this._cam.far=o,this._cam.updateProjectionMatrix())}applyClippingPlane(){this._cam&&(this._cam.near=this._nearClipPlane,this._cam.far=this._farClipPlane,this._cam.updateProjectionMatrix())}get clearFlags(){return this._clearFlags}set clearFlags(o){if(typeof o=="string")switch(o){case"skybox":o=1;break;case"solidcolor":o=2;break;default:o=0;break}o!==this._clearFlags&&(this._clearFlags=o,this.applyClearFlagsIfIsActiveCamera())}set cullingMask(o){this._cullingMask=o,this._cam&&(this._cam.layers.mask=o)}get cullingMask(){return this._cam?this._cam.layers.mask:this._cullingMask}set cullingLayer(o){this.cullingMask=(1<<o|0)>>>0}set backgroundBlurriness(o){o!==this._backgroundBlurriness&&(o===void 0?this._backgroundBlurriness=void 0:this._backgroundBlurriness=Math.min(Math.max(o,0),1),this.applyClearFlagsIfIsActiveCamera())}get backgroundBlurriness(){return this._backgroundBlurriness}set backgroundIntensity(o){o!==this._backgroundIntensity&&(o===void 0?this._backgroundIntensity=void 0:this._backgroundIntensity=Math.min(Math.max(o,0),10),this.applyClearFlagsIfIsActiveCamera())}get backgroundIntensity(){return this._backgroundIntensity}set backgroundRotation(o){o!==this._backgroundRotation&&(o===void 0?this._backgroundRotation=void 0:this._backgroundRotation=o,this.applyClearFlagsIfIsActiveCamera())}get backgroundRotation(){return this._backgroundRotation}set environmentIntensity(o){this._environmentIntensity=o}get environmentIntensity(){return this._environmentIntensity}get backgroundColor(){return this._backgroundColor??null}set backgroundColor(o){o&&(this._backgroundColor||(this._backgroundColor=new he(1,1,1,1)),this._backgroundColor.copy(o),(!("alpha"in o)||o.alpha===void 0)&&(this._backgroundColor.alpha=1),this.applyClearFlagsIfIsActiveCamera())}set targetTexture(o){this._targetTexture=o}get targetTexture(){return this._targetTexture}get cam(){return this.threeCamera}get threeCamera(){return this.activeAndEnabled&&this.buildCamera(),this._cam}screenPointToRay(o,e,t){const s=this.threeCamera,n=Lo._origin;n.set(o,e,-1),this.context.input.convertScreenspaceToRaycastSpace(n),Cx&&console.log("screenPointToRay",o.toFixed(2),e.toFixed(2),"now:",n.x.toFixed(2),n.y.toFixed(2),"isInXR:"+this.context.isInXR),n.z=-1,n.unproject(s);const r=Lo._direction.set(n.x,n.y,n.z),l=te(s);return r.sub(l),r.normalize(),t?(t.set(l,r),t):new uo(l.clone(),r.clone())}getFrustum(){return this._frustum||(this._frustum=new Tv,this.updateFrustum()),this._frustum}updateFrustum(){this._frustum||(this._frustum=new Tv),this._frustum.setFromProjectionMatrix(this.getProjectionScreenMatrix(this._projScreenMatrix,!0),this.context.renderer.coordinateSystem)}getProjectionScreenMatrix(o,e){return e&&this._projScreenMatrix.multiplyMatrices(this.threeCamera.projectionMatrix,this.threeCamera.matrixWorldInverse),o===this._projScreenMatrix?o:o.copy(this._projScreenMatrix)}awake(){Cx&&window.addEventListener("pointerdown",o=>{const e=o.clientX,t=o.clientY;console.log("touch",e.toFixed(2),t.toFixed(2));const s=this.screenPointToRay(e,t),n="#"+Math.floor(Math.random()*16777215).toString(16);G.DrawRay(s.origin,s.direction,n,10)})}onEnable(){Io&&console.log(`Camera enabled: "${this.name}". ClearFlags=${Ao[this._clearFlags]}`,this),this.buildCamera(),(this.tag=="MainCamera"||!this.context.mainCameraComponent)&&(this.context.setCurrentCamera(this),ET(this)),this.applyClearFlagsIfIsActiveCamera({applySkybox:!0})}onDisable(){this.context.removeCamera(this)}onBeforeRender(){if(this._cam&&(this._frustum&&this.updateFrustum(),this._clearFlags===2&&this.applyClearFlagsIfIsActiveCamera(),this._targetTexture)){this.context.isManagedExternally&&(this._warnedAboutExternalRenderer||(this._warnedAboutExternalRenderer=!0,console.warn("Rendering with external renderer is not supported yet. This may not work or throw errors. Please remove the the target texture from your camera: "+this.name,this.targetTexture))),this.context.composer;const o=this.context.renderer;if(o){const e=this.context.mainCameraComponent;this.applyClearFlags(),this._targetTexture.render(this.context.scene,this._cam,o),e?.applyClearFlags()}}}buildCamera(){if(this._cam)return;const o=this.gameObject.isCamera;let e=null;if(o?(e=this.gameObject,e?.layers.enableAll(),e instanceof we&&(this._fov=e.fov)):e=this.gameObject.children[0],e&&e.isCamera)e instanceof we&&(this._fov&&(e.fov=this._fov),e.near=this._nearClipPlane,e.far=this._farClipPlane,e.updateProjectionMatrix());else if(!this.orthographic)e=new we(this.fieldOfView,window.innerWidth/window.innerHeight,this._nearClipPlane,this._farClipPlane),this.fieldOfView&&(e.fov=this.fieldOfView),this.gameObject.add(e);else{const t=this.orthographicSize*100;e=new hd(window.innerWidth/-t,window.innerWidth/t,window.innerHeight/t,window.innerHeight/-t,this._nearClipPlane,this._farClipPlane),this.gameObject.add(e)}this._cam=e,this._cam.layers.mask=this._cullingMask,this.tag=="MainCamera"&&this.context.setCurrentCamera(this)}applyClearFlagsIfIsActiveCamera(o){this.context.mainCameraComponent===this&&this.applyClearFlags(o)}applyClearFlags(o){var e;if(!this._cam){Io&&console.log("Camera does not exist (apply clear flags)");return}if(this.fieldOfView=this._fov,Io){const s=`[Camera] Apply ClearFlags: ${Ao[this._clearFlags]} - "${this.name}"`;console.debug(s)}const t=this.context.domElement.getAttribute("background-image")||this.context.domElement.getAttribute("background-color")||this.context.domElement.getAttribute("skybox-image");switch(this._clearFlags){case 0:return;case 1:if(Lo.backgroundShouldBeTransparent(this.context)&&(!this.ARBackgroundAlpha||this.ARBackgroundAlpha<.001)){this.context.scene.background=null,this.context.renderer.setClearColor(0,0);return}(!this.scene.background||!this._skybox||o?.applySkybox===!0)&&this.applySceneSkybox(),this._backgroundBlurriness!==void 0&&!this.context.domElement.getAttribute("background-blurriness")?this.context.scene.backgroundBlurriness=this._backgroundBlurriness:Io&&console.warn(`Camera "${this.name}" has no background blurriness`),this._backgroundIntensity!==void 0&&!this.context.domElement.getAttribute("background-intensity")&&(this.context.scene.backgroundIntensity=this._backgroundIntensity),this._backgroundRotation!==void 0&&!this.context.domElement.getAttribute("background-rotation")?this.context.scene.backgroundRotation=this._backgroundRotation:Io&&console.warn(`Camera "${this.name}" has no background intensity`);break;case 2:if(this._backgroundColor&&!t){let s=this._backgroundColor.alpha;Lo.backgroundShouldBeTransparent(this.context)&&(s=this.ARBackgroundAlpha??0),this.context.scene.background=null,(e=this.context.xr)!=null&&e.isVR?this.context.renderer.setClearColor(Sb(this._backgroundColor).convertLinearToSRGB()):this.context.renderer.setClearColor(this._backgroundColor,s)}else this._backgroundColor||Io&&console.warn(`[Camera] has no background color "${this.name}" `);break;case 4:t||(this.context.scene.background=null,this.context.renderer.setClearColor(0,0));break}}applySceneSkybox(){this._skybox||(this._skybox=new TT(this)),this._skybox.apply()}static backgroundShouldBeTransparent(o){var e,t,s,n;const r=(e=o.renderer.xr)==null?void 0:e.getSession();if(!r)return!1;if(typeof r._transparent=="boolean")return r._transparent;const l=r.environmentBlendMode;Io&&Be("Environment blend mode: "+l+" on "+navigator.userAgent);let c=l==="additive"||l==="alpha-blend";return o.isInAR&&l==="opaque"&&((t=navigator.userAgent)!=null&&t.includes("OculusBrowser")||(s=navigator.userAgent)!=null&&s.includes("Mozilla")&&(n=navigator.userAgent)!=null&&n.includes("Mobile WebXRViewer/v2"))&&(c=!0),r._transparent=c,c}},a(Lo,"_origin",new x),a(Lo,"_direction",new x),Lo);Qt([m()],Ft.prototype,"aspect",1),Qt([m()],Ft.prototype,"fieldOfView",1),Qt([m()],Ft.prototype,"nearClipPlane",1),Qt([m()],Ft.prototype,"farClipPlane",1),Qt([m()],Ft.prototype,"clearFlags",1),Qt([m()],Ft.prototype,"orthographic",2),Qt([m()],Ft.prototype,"orthographicSize",2),Qt([m()],Ft.prototype,"ARBackgroundAlpha",2),Qt([m()],Ft.prototype,"cullingMask",1),Qt([m()],Ft.prototype,"backgroundBlurriness",1),Qt([m()],Ft.prototype,"backgroundIntensity",1),Qt([m(jt)],Ft.prototype,"backgroundRotation",1),Qt([m()],Ft.prototype,"environmentIntensity",1),Qt([m(he)],Ft.prototype,"backgroundColor",1),Qt([m(Tc)],Ft.prototype,"targetTexture",1);let li=Ft;class TT{constructor(e){a(this,"_camera"),a(this,"_skybox"),this._camera=e}get context(){var e;return(e=this._camera)==null?void 0:e.context}apply(){var e;if(this._skybox=this.context.lightmaps.tryGetSkybox(this._camera.sourceId),!this._skybox)this._did_log_failed_to_find_skybox||(this._did_log_failed_to_find_skybox=!0,console.warn(`Camera "${this._camera.name}" has no skybox texture. ${this._camera.sourceId}`));else if(this.context.scene.background!==this._skybox){const t=this.context.domElement.getAttribute("background-image")||this.context.domElement.getAttribute("background-color")||this.context.domElement.getAttribute("skybox-image");Io&&console.debug(`[Camera] Apply Skybox ${(e=this._skybox)==null?void 0:e.name} ${t} - "${this._camera.name}"`),t!=null&&t.length||(this._skybox.mapping=kn,this.context.scene.background=this._skybox)}}}function ET(o){C("freecam")&&o.context.mainCameraComponent===o&&P.getOrAddComponent(o.gameObject,_e)}class zn extends I{constructor(){super(...arguments),a(this,"_listener",null),a(this,"onInteraction",()=>{this.destroyed||this.listener==null||this.addListenerIfItExists()})}get listener(){return this._listener==null&&(this._listener=new qC),this._listener}onEnable(){Ln.registerWaitForInteraction(this.onInteraction),this.addListenerIfItExists()}onDisable(){Ln.unregisterWaitForInteraction(this.onInteraction),this.removeListenerIfItExists()}addListenerIfItExists(){const e=this._listener;if(!e||e!=null&&e.parent)return;const t=this.context.mainCameraComponent||P.getComponentInParent(this.gameObject,li);t!=null&&t.threeCamera?t.threeCamera.add(e):this.gameObject.add(e),e.filter?(e.gain.connect(e.filter),e.filter.connect(e.context.destination)):e.gain.connect(e.context.destination)}removeListenerIfItExists(){const e=this._listener;e&&(e.removeFromParent(),e.filter&&e.filter.disconnect(),e.gain&&e.gain.disconnect())}}var AT=Object.defineProperty,IT=Object.getOwnPropertyDescriptor,Ps=(o,e,t,s)=>{for(var n=s>1?void 0:s?IT(e,t):e,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=(s?l(e,t,n):l(n))||n);return s&&n&&AT(e,t,n),n};const Tt=C("debugaudio"),is=class hr extends I{constructor(){super(...arguments),a(this,"clip",""),a(this,"playOnAwake",!1),a(this,"preload",!0),a(this,"playInBackground",!0),a(this,"_spatialBlend",0),a(this,"_minDistance",1),a(this,"_maxDistance",100),a(this,"_volume",1),a(this,"rollOffMode",0),a(this,"_loop",!1),a(this,"sound",null),a(this,"helper",null),a(this,"wasPlaying",!1),a(this,"audioLoader",null),a(this,"shouldPlay",!1),a(this,"_lastClipStartedLoading",null),a(this,"_audioElement",null),a(this,"onVisibilityChanged",()=>{switch(document.visibilityState){case"hidden":(this.playInBackground===!1||Y.isMobileDevice())&&(this.wasPlaying=this.isPlaying,this.isPlaying&&this.pause());break;case"visible":Tt&&console.log("visible",this.enabled,this.playOnAwake,!this.isPlaying,hr.userInteractionRegistered,this.wasPlaying),this.enabled&&this.playOnAwake&&!this.isPlaying&&hr.userInteractionRegistered&&this.wasPlaying&&this.play();break}}),a(this,"onApplicationMuteChanged",()=>{var e,t;this.context.application.muted?(e=this.sound)==null||e.setVolume(0):(t=this.sound)==null||t.setVolume(this.volume)}),a(this,"createAudio",e=>{if(this.destroyed){Tt&&console.warn("AudioSource destroyed, not creating audio",this.name);return}Tt&&console.log("AudioBuffer finished loading",e);const t=this.Sound;if(!t){Tt&&console.warn("Failed getting sound?",this.name);return}t.isPlaying&&t.stop(),e&&t.setBuffer(e),t.loop=this._loop,this.context.application.muted?t.setVolume(0):t.setVolume(this.volume),t.autoplay=this.shouldPlay&&hr.userInteractionRegistered,this.applySpatialDistanceSettings(),t.isPlaying&&t.stop(),hr.registerWaitForAllowAudio(this.__onAllowAudioCallback)}),a(this,"__onAllowAudioCallback",()=>{this.shouldPlay&&this.play()}),a(this,"_lastContextTime",0),a(this,"_hasEnded",!0),a(this,"_needUpdateSpatialDistanceSettings",!1)}static get userInteractionRegistered(){return Ln.userInteractionRegistered}static registerWaitForAllowAudio(e){Ln.registerWaitForInteraction(e)}get isPlaying(){var e;return((e=this.sound)==null?void 0:e.isPlaying)??!1}get duration(){var e,t;return(t=(e=this.sound)==null?void 0:e.buffer)==null?void 0:t.duration}get time01(){var e;const t=this.duration;return t&&this.sound?((e=this.sound)==null?void 0:e.context.currentTime)/t:0}set time01(e){const t=this.duration;t&&this.sound&&(this.time=e*t)}get time(){var e,t;return(e=this.sound)!=null&&e.source?((t=this.sound.source)==null?void 0:t.context.currentTime)-this._lastContextTime+this.sound.offset:0}set time(e){if(this.sound){if(e===this.sound.offset)return;const t=this.isPlaying;this.stop(),this.sound.offset=e,t&&this.play()}}get loop(){return this.sound&&(this._loop=this.sound.getLoop()),this._loop}set loop(e){this._loop=e,this.sound&&this.sound.setLoop(e)}get spatialBlend(){return this._spatialBlend}set spatialBlend(e){e!==this._spatialBlend&&(this._spatialBlend=e,this._needUpdateSpatialDistanceSettings=!0)}get minDistance(){return this._minDistance}set minDistance(e){this._minDistance!==e&&(this._minDistance=e,this._needUpdateSpatialDistanceSettings=!0)}get maxDistance(){return this._maxDistance}set maxDistance(e){this._maxDistance!==e&&(this._maxDistance=e,this._needUpdateSpatialDistanceSettings=!0)}get volume(){return this._volume}set volume(e){this._volume=e,this.sound&&!this.context.application.muted&&(Tt&&console.log(this.name,"audio set volume",e),this.sound.setVolume(e))}set pitch(e){this.sound&&this.sound.setPlaybackRate(e)}get pitch(){return this.sound?this.sound.getPlaybackRate():1}get Sound(){var e;if(!this.sound&&hr.userInteractionRegistered){let t=this.gameObject.getComponent(zn)??this.context.mainCamera.getComponent(zn)??_c(zn,this.context,!1);!t&&this.context.mainCamera&&(t=this.context.mainCamera.addComponent(zn)),t!=null&&t.listener?(this.sound=new XC(t.listener),(e=this.gameObject)==null||e.add(this.sound)):Tt&&console.warn("No audio listener found in scene - can not play audio")}return this.sound}get ShouldPlay(){return this.shouldPlay}get audioContext(){var e;return(e=this.sound)==null?void 0:e.context}awake(){Tt&&console.log("[AudioSource]",this),this.audioLoader=new Tm,this.playOnAwake&&(this.shouldPlay=!0),this.preload&&typeof this.clip=="string"&&this.audioLoader.load(this.clip,this.createAudio,()=>{},console.error)}onEnable(){this.sound&&this.gameObject.add(this.sound),hr.userInteractionRegistered?this.playOnAwake&&this.context.application.isVisible&&this.play():hr.registerWaitForAllowAudio(()=>{this.enabled&&!this.destroyed&&this.shouldPlay&&this.onNewClip(this.clip)}),globalThis.addEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.addEventListener(wg.MuteChanged,this.onApplicationMuteChanged)}onDisable(){globalThis.removeEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.removeEventListener(wg.MuteChanged,this.onApplicationMuteChanged),this.pause()}applySpatialDistanceSettings(){const e=this.sound;if(!e)return;this._needUpdateSpatialDistanceSettings=!1;const t=W.lerp(10*this._maxDistance/Math.max(1e-4,this.spatialBlend),this._minDistance,this.spatialBlend);switch(Tt&&console.log(this.name,this._minDistance,this._maxDistance,this.spatialBlend,"Ref distance="+t),e.setRefDistance(t),e.setMaxDistance(Math.max(.01,this._maxDistance)),this.rollOffMode){case 0:e.setDistanceModel("exponential");break;case 1:e.setDistanceModel("linear");break;case 2:console.warn("Custom rolloff for AudioSource is not supported: "+this.name);break}this.spatialBlend>0?Tt&&!this.helper&&(this.helper=new ZP(e,e.getRefDistance()),e.add(this.helper)):this.helper&&this.helper.parent&&this.helper.removeFromParent()}async onNewClip(e){if(e&&(this.clip=e),typeof e=="string")if(Tt&&console.log(e),e.endsWith(".mp3")||e.endsWith(".wav")){if(this.audioLoader||(this.audioLoader=new Tm),this.shouldPlay=!0,this._lastClipStartedLoading===e){Tt&&console.log("Is currently loading:",this._lastClipStartedLoading,this);return}this._lastClipStartedLoading=e,Tt&&console.log("load audio",e);const t=await this.audioLoader.loadAsync(e).catch(console.error);if(this.destroyed)return;this._lastClipStartedLoading===e&&(this._lastClipStartedLoading=null),t&&this.createAudio(t)}else console.warn("Unsupported audio clip type",e);else this.shouldPlay=!0,this.createAudio()}play(e=void 0){var t,s,n;!e&&this.clip&&(e=this.clip),e!==void 0&&typeof e!="string"&&!(e instanceof MediaStream)&&(F()&&console.warn("Called play on AudioSource with unknown argument type:",e+`
940
+ Using the assigned clip instead:`,this.clip),e=this.clip);let r=!this.sound||e&&e!==this.clip;if(typeof e=="string"&&!this.audioLoader&&(r=!0),(e instanceof MediaStream||typeof e=="string")&&(this.clip=e),r){this.shouldPlay=!0,this.onNewClip(e);return}if(this.shouldPlay=!0,this._hasEnded=!1,Tt&&console.log("play",(t=this.sound)==null?void 0:t.getVolume(),this.sound),this.sound&&!this.sound.isPlaying){const l=this.context.application.muted;l&&this.sound.setVolume(0),(s=this.gameObject)==null||s.add(this.sound),this.clip instanceof MediaStream?(this.sound.setMediaStreamSource(this.clip),this._audioElement||(this._audioElement=document.createElement("audio"),this._audioElement.style.display="none"),this._audioElement.parentNode||(n=this.context.domElement.shadowRoot)==null||n.append(this._audioElement),this._audioElement.srcObject=this.clip,this._audioElement.autoplay=!1):(this._audioElement&&this._audioElement.remove(),this.sound.play(l?.1:0))}}pause(){var e,t;Tt&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.isPlaying&&this.sound.source&&(this._lastContextTime=(e=this.sound)==null?void 0:e.context.currentTime,this.sound.pause()),(t=this._audioElement)==null||t.remove()}stop(){var e,t;Tt&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.source&&(this._lastContextTime=(e=this.sound)==null?void 0:e.context.currentTime,Tt&&console.log(this._lastContextTime),this.sound.stop()),(t=this._audioElement)==null||t.remove()}update(){this.helper&&(this.isPlaying&&this.helper.update(),this.helper.visible=this.isPlaying),this._needUpdateSpatialDistanceSettings&&this.applySpatialDistanceSettings(),this.sound&&!this.sound.isPlaying&&this.shouldPlay&&!this._hasEnded&&(this._hasEnded=!0,Tt&&console.log("Audio clip ended",this.clip),this.dispatchEvent(new CustomEvent("ended",{detail:this})))}};Ps([m(URL)],is.prototype,"clip",2),Ps([m()],is.prototype,"playOnAwake",2),Ps([m()],is.prototype,"preload",2),Ps([m()],is.prototype,"playInBackground",2),Ps([m()],is.prototype,"loop",1),Ps([m()],is.prototype,"spatialBlend",1),Ps([m()],is.prototype,"minDistance",1),Ps([m()],is.prototype,"maxDistance",1),Ps([m()],is.prototype,"volume",1),Ps([m()],is.prototype,"pitch",1),Ps([m()],is.prototype,"rollOffMode",2);let ss=is;const LT=C("debugavatar"),Iu=class wn extends I{constructor(){super(...arguments),a(this,"connectionId"),a(this,"avatar")}static getAvatar(e){return e>=0&&e<wn.instances.length?wn.instances[e]:null}static onAvatarMarkerCreated(e){return wn._onNewAvatarMarkerAdded.push(e),e}static onAvatarMarkerDestroyed(e){return wn._onAvatarMarkerDestroyed.push(e),e}awake(){wn.instances.push(this),LT&&console.log(this);for(const e of wn._onNewAvatarMarkerAdded)e({avatarMarker:this,gameObject:this.gameObject})}onDestroy(){wn.instances.splice(wn.instances.indexOf(this),1);for(const e of wn._onAvatarMarkerDestroyed)e({avatarMarker:this,gameObject:this.gameObject})}isLocalAvatar(){return this.connectionId===this.context.connection.connectionId}};a(Iu,"instances",[]),a(Iu,"_onNewAvatarMarkerAdded",[]),a(Iu,"_onAvatarMarkerDestroyed",[]);let ci=Iu;class Nn{static Add(e,t,s=null){if(t){for(const n of this.Pois)if(n.obj===t)return;this.Pois.push({obj:t,avatar:s}),this.LastChangeTime=e.time.time}}static Remove(e,t){var s;if(t){for(const n of this.Pois)if(n.obj===t){this.Pois.splice(this.Pois.indexOf(n),1),this.LastChangeTime=e?.time.time??((s=ee.Current)==null?void 0:s.time.time);return}}}}a(Nn,"Pois",[]),a(Nn,"LastChangeTime",0);class jT{constructor(){a(this,"guid"),a(this,"position",new x)}}class Bc extends I{constructor(){super(...arguments),a(this,"target",null),a(this,"avatar",null),a(this,"_model",null),a(this,"_targetModel",new jT),a(this,"_currentTargetObject",null),a(this,"_lastUpdateTime",0),a(this,"_lookDuration",0),a(this,"_lastPoiChangedTime",0)}set controlledTarget(e){this.target=e;const t=R.get("MoveRandom");if(t&&this.target){const s=P.getComponent(this.target,t);s&&s.destroy()}}awake(){if(this.avatar=P.getComponentInParent(this.gameObject,ci),this.avatar){const e=P.getComponentInParent(this.gameObject,ci);this._model=new kg(this.context.connection,this.guid),e!=null&&e.isLocalAvatar&&this._model.requestOwnership()}this.context.connection.beginListen("avatar-look-target-changed",e=>{var t;this.target&&e&&e.guid===((t=this.avatar)==null?void 0:t.guid)&&lt(this.target,e.position)})}update(){var e;if((!this.context.connection.isConnected||(e=this._model)!=null&&e.hasOwnership)&&(Nn.LastChangeTime!==this._lastPoiChangedTime&&(this._lastPoiChangedTime=Nn.LastChangeTime,this._lookDuration=0),this.selectTarget(),this._currentTargetObject&&this.context.time.frameCount%10===0&&this.target)){const t=te(this._currentTargetObject);lt(this.target,t),this.context.connection.isConnected&&this.avatar&&(this.context.connection.send("avatar-look-target-changed",this._targetModel),this._targetModel.guid=this.avatar.guid,this._targetModel.position.copy(t))}}selectTarget(){if(this.context.time.time-this._lastUpdateTime>this._lookDuration){this._lastUpdateTime=this.context.time.time,this._lookDuration=Math.random()*.5+.2;const e=Nn.Pois;if(e.length>0){const t=e[Math.floor(Math.random()*e.length)];if(t&&t.obj){if(t.avatar&&t.avatar===this.avatar)return;this._currentTargetObject=t.obj}}}}}function Px(o){const e=o;return!!(e.parser&&e.parser.json)}var Lu=(o=>(o[o.None=0]="None",o[o.DontExport=1]="DontExport",o))(Lu||{});function Ox(o){return o&&o.isComponent}const DT=Symbol("object"),zf=new Pi(()=>new x,20);class kx{constructor(e,t,s,n,r,l){a(this,"_point"),a(this,"_normal"),a(this,"_tangentVelocity"),a(this,"distance"),a(this,"impulse"),a(this,"friction"),this._point=e,this.distance=t,this._normal=s,this.impulse=n,this.friction=r,this._tangentVelocity=l}get point(){return zf.get().set(this._point.x,this._point.y,this._point.z)}get normal(){return zf.get().set(this._normal.x,this._normal.y,this._normal.z)}get tangentVelocity(){return zf.get().set(this._tangentVelocity.x,this._tangentVelocity.y,this._tangentVelocity.z)}}class Mx{constructor(e,t,s){a(this,"contacts"),a(this,"me"),a(this,"_collider"),a(this,"_gameObject"),this.me=e,this._collider=t,this._gameObject=t.gameObject,this.contacts=s}get collider(){return this._collider}get gameObject(){return this._gameObject}get rigidBody(){var e;return(e=this.collider)==null?void 0:e.attachedRigidbody}}class Rx{constructor(e,t){a(this,"object"),a(this,"collider"),this.object=e,this.collider=t}}const Ye=C("debugnetworkingstreams");var nn=(o=>(o.Connected="peer-user-connected",o.StreamReceived="receive-stream",o.StreamEnded="call-ended",o.Disconnected="peer-user-disconnected",o.UserJoined="user-joined",o))(nn||{});class Nf{constructor(e,t){a(this,"type","call-ended"),a(this,"userId"),a(this,"direction"),this.userId=e,this.direction=t}}class Tx{constructor(e,t,s){a(this,"type","receive-stream"),a(this,"userId"),a(this,"stream"),a(this,"target"),this.userId=e,this.stream=t,this.target=s}}class BT{constructor(e,t){a(this,"guid"),a(this,"peerId"),a(this,"dontSave",!0),this.guid=e.id,this.peerId=t}}var Ex=(o=>(o.Incoming="incoming",o.Outgoing="outgoing",o))(Ex||{});class FT extends Em{constructor(e,t,s,n=null){super(),a(this,"peerId"),a(this,"userId"),a(this,"direction"),a(this,"call"),a(this,"_stream",null),a(this,"_isDisposed",!1),this.peerId=t.peer,this.userId=e,this.call=t,this.direction=s,this._stream=n,t.on("stream",r=>{if(Ye&&console.log("Receive stream",`
941
+ Audio:`,r.getAudioTracks(),`
942
+ Video:`,r.getVideoTracks()),this._stream=r,s==="incoming"){const l=new Tx(e,r,this);this.dispatchEvent(l)}}),t.on("close",()=>{this.dispatchEvent(new Nf(e,s))})}get stream(){return this._stream}close(){this._isDisposed||(this._isDisposed=!0,this.call.close(),on(this._stream))}get isOpen(){var e;return((e=this.call.peerConnection)==null?void 0:e.connectionState)==="connected"}get isOpening(){var e;return((e=this.call.peerConnection)==null?void 0:e.connectionState)==="connecting"}get isClosed(){return!this.isOpen||this._isDisposed}}function Ax(o){return o=o.replace("a=fmtp:111 minptime=10;useinbandfec=1","a=fmtp:111 ptime=5;useinbandfec=1;stereo=1;maxplaybackrate=48000;maxaveragebitrat=128000;sprop-stereo=1"),o}const Ix=class id extends Em{constructor(e,t){super(),a(this,"updateCalls",()=>{var s;for(let n=this._incomingCalls.length-1;n>=0;n--){const r=this._incomingCalls[n];r.isClosed&&!r.isOpening&&this._incomingCalls.splice(n,1)}for(let n=this._outgoingCalls.length-1;n>=0;n--){const r=this._outgoingCalls[n];let l=!1;r.isClosed&&!r.isOpening&&((s=r.stream)!=null&&s.active?Ye&&console.warn("!!! Stream is still active, don't remove call",r.userId,"Your id: "+this.context.connection.connectionId):(Ye&&console.warn("!!! Remove closed call",r.userId),l=!0)),this.context.connection.userIsInRoom(r.userId)===!1&&(Ye&&console.warn("!!! User is not in room anymore, remove call",r.userId),l=!0),l&&(r.close(),this._outgoingCalls.splice(n,1))}}),a(this,"id"),a(this,"context"),a(this,"_incomingCalls",[]),a(this,"_outgoingCalls",[]),a(this,"_peer"),a(this,"_enabled",!1),a(this,"_enabledPeer",!1),a(this,"onConnectRoomFn",this.onConnectRoom.bind(this)),a(this,"onPeerConnect",s=>{if(Ye&&console.log("PEER opened as",s),s===null){console.error("Peer connection failed",s);return}this.context.connection.send("peer-user-connected",new BT(this,s))}),a(this,"onPeerClose",()=>{Ye&&console.log("PEER closed"),this.updateCalls()}),a(this,"onPeerDisconnected",()=>{Ye&&console.log("PEER disconnected"),this.updateCalls()}),a(this,"onPeerError",s=>{Ye&&console.error("PEER error",s)}),a(this,"onPeerReceivingCall",s=>{s.answer(void 0,{sdpTransform:n=>Ax(n)}),this.registerCall(s,"incoming",null)}),this.context=e,this.id=t,this.setupPeer(),navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia}static getOrCreate(e,t){if(id.instances.has(t))return id.instances.get(t);const s=new id(e,t);return id.instances.set(t,s),s}getMyPeerId(){if(this.context.connection.connectionId)return this.getPeerIdFromUserId(this.context.connection.connectionId)}getPeerIdFromUserId(e){return this.id+"-"+e}getUserIdFromPeerId(e){return e.substring(this.id.length+1)}makeCall(e,t){var s;if(!(t!=null&&t.id)){Ye?console.warn("Can not make a call: mediastream has no id or is undefined"):console.debug("Can not make a call: mediastream has no id or is undefined");return}const n={metadata:{userId:this.context.connection.connectionId,streamId:t.id},sdpTransform:l=>Ax(l)},r=(s=this._peer)==null?void 0:s.call(e,t,n);if(r){const l=this.registerCall(r,"outgoing",t);return Ye&&console.warn(`\u{1F4DE} CALL ${e}`,`
943
+ Outgoing:`,this._outgoingCalls,`
944
+ Incoming:`,this._incomingCalls),l}else Ye&&console.error("Failed to make call",e,t,this._peer)}closeAll(){for(const e of this._incomingCalls)e.close();for(const e of this._outgoingCalls)e.close();this.updateCalls()}get peer(){return this._peer}get incomingCalls(){return this._incomingCalls}enable(){this._enabled||(this._enabled=!0,this.context.connection.beginListen(ie.JoinedRoom,this.onConnectRoomFn),this.subscribePeerEvents())}disable(){this._enabled&&(this._enabled=!1,this.context.connection.stopListen(ie.JoinedRoom,this.onConnectRoomFn),this.unsubscribePeerEvents())}onConnectRoom(){this.setupPeer()}setupPeer(){if(this.context.connection.connectionId&&!this._enabledPeer){if(this._enabledPeer=!0,!this._peer){const e=this.getMyPeerId();e?this._peer=c_(e):console.error("Failed to setup peerjs because we dont have a connection id",this.context.connection.connectionId)}this._enabled&&this.subscribePeerEvents()}}subscribePeerEvents(){this._peer&&(this._peer.on("open",this.onPeerConnect),this._peer.on("close",this.onPeerClose),this._peer.on("call",this.onPeerReceivingCall),this._peer.on("disconnected",this.onPeerDisconnected),this._peer.on("error",this.onPeerError))}unsubscribePeerEvents(){this._peer&&(this._peer.off("open",this.onPeerConnect),this._peer.off("close",this.onPeerClose),this._peer.off("call",this.onPeerReceivingCall),this._peer.off("disconnected",this.onPeerDisconnected),this._peer.off("error",this.onPeerError))}registerCall(e,t,s){const n=e.metadata;(!n||!n.userId)&&console.error("Missing call metadata",e);const r=n.userId;t==="incoming"&&Ye?console.warn("\u2190 Receive call from",e.metadata,e.connectionId):Ye&&console.warn("\u2192 Make call to",e.metadata);const l=t==="incoming"?this._incomingCalls:this._outgoingCalls,c=new FT(r,e,t,s);return l.push(c),e.on("error",h=>{console.error("Call error",h)}),e.on("close",()=>{Ye&&console.log("Call ended",e.metadata);const h=l.indexOf(c);h!==-1&&l.splice(h,1),c.close(),this.dispatchEvent(new Nf(r,t))}),c.addEventListener("call-ended",h=>{this.dispatchEvent(h)}),t==="incoming"&&(c.addEventListener("receive-stream",h=>{this.dispatchEvent(h)}),e.on("stream",()=>{Ye&&console.log("Received stream for call",e.metadata);let h=0;const d=setInterval(()=>{const u=h===0;!c.isOpen&&u&&(Ye&&console.warn("Close call because stream is not active",e.metadata),h+=1,clearInterval(d),c.close())},2e3)})),c}};a(Ix,"instances",new Map);let ju=Ix;class ld extends Em{constructor(e,t){if(super(),a(this,"context"),a(this,"peer"),a(this,"_sendingStreams",new Map),a(this,"debug",!1),a(this,"_enabled",!1),a(this,"_tickIntervalId"),a(this,"tick",()=>{this.updateSendingCalls()}),a(this,"onJoinedRoom",s=>{this._sendingStreams.size>0&&(this.debug&&console.warn(`${s!=null&&s.userId?`User ${s.userId}`:"You"} joined room`,s,this._sendingStreams.size),this.updateSendingCalls())}),a(this,"onLeftRoom",s=>{this.debug&&console.warn(`${s?.userId||"You"} left room`,s),this.stopCallsToUsersThatAreNotInTheRoomAnymore(),this.peer.closeAll()}),a(this,"onCallStreamReceived",s=>{this.debug&&console.log("Call with "+s.userId+" started"),this.dispatchEvent({type:"receive-stream",target:this,stream:s.stream,userId:s.userId}),this.debug&&this.debugLogCurrentState()}),a(this,"onCallEnded",s=>{this.debug&&console.log("Call with "+s.userId+" ended"),this.dispatchEvent(s),this.debug&&this.debugLogCurrentState()}),a(this,"onUserConnected",s=>{if(this.peer.id===s.guid){this.debug&&console.log("PEER USER CONNECTED",s.guid,s,this._sendingStreams.size);const n=this._sendingStreams.keys().next().value;this.peer.makeCall(s.peerId,n)}else Ye&&console.log("Unknown user connected",s.guid,s.peerId)}),a(this,"onUserLeft",s=>{this.debug&&console.log("User left room: "+s.userId),this.stopCallsToUsersThatAreNotInTheRoomAnymore()}),Ox(e)){const s=e;e=s.context,t=ju.getOrCreate(s.context,s.guid)}else typeof t=="string"&&(t=ju.getOrCreate(e,t));if(e){if(!(e instanceof ee))throw new Error("Failed to create NetworkedStreams because context is not an instance of Context")}else throw new Error("Failed to create NetworkedStreams because context is undefined");if(!t)throw new Error("Failed to create NetworkedStreams because peer is undefined");this.context=e,this.peer=t,Ye&&(this.debug=!0)}static create(e,t){const s=ju.getOrCreate(e.context,t||e.context.connection.connectionId||e.guid);return new ld(e.context,s)}startSendingStream(e){this._sendingStreams.has(e)?console.warn("Received start sending stream with stream that is already being sent"):(this._sendingStreams.set(e,[]),this.updateSendingCalls())}stopSendingStream(e){if(e){const t=this._sendingStreams.get(e);if(t){for(const s of t)s.close();t.length=0}this._sendingStreams.delete(e),t&&this.debug&&this.debugLogCurrentState()}this.updateSendingCalls()}get enabled(){return this._enabled}enable(){this._enabled||(this._enabled=!0,this.peer.enable(),this.peer.addEventListener("receive-stream",this.onCallStreamReceived),this.peer.addEventListener("call-ended",this.onCallEnded),this.context.connection.beginListen("peer-user-connected",this.onUserConnected),this.context.connection.beginListen(ie.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(ie.UserJoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(ie.UserLeftRoom,this.onUserLeft),this.context.connection.beginListen(ie.LeftRoom,this.onLeftRoom),this._tickIntervalId=setInterval(this.tick,5e3))}disable(){this._enabled&&(this._enabled=!1,this.peer.disable(),this.peer.removeEventListener("receive-stream",this.onCallStreamReceived),this.peer.removeEventListener("call-ended",this.onCallEnded),this.context.connection.stopListen("peer-user-connected",this.onUserConnected),this.context.connection.stopListen(ie.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(ie.UserJoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(ie.UserLeftRoom,this.onUserLeft),this.context.connection.stopListen(ie.LeftRoom,this.onLeftRoom),this._tickIntervalId!=null&&(clearInterval(this._tickIntervalId),this._tickIntervalId=void 0))}updateSendingCalls(){const e=this.context.connection.connectionId;for(const t of this._sendingStreams.keys()){const s=this._sendingStreams.get(t)||[];for(const n of this.context.connection.usersInRoom()){if(n===e)continue;const r=this.peer.getPeerIdFromUserId(n);if(s.find(l=>{var c;return l.peerId===r&&l.direction==="outgoing"&&!l.isClosed&&((c=l.stream)==null?void 0:c.active)}))Ye&&console.debug("Already have a call with user "+n+" / peer "+r);else{const l=this.peer.makeCall(r,t);l&&s.push(l)}}this._sendingStreams.set(t,s)}this.stopCallsToUsersThatAreNotInTheRoomAnymore()}stopCallsToUsersThatAreNotInTheRoomAnymore(){for(const e of this._sendingStreams.keys()){const t=this._sendingStreams.get(e);if(t)for(let s=t.length-1;s>=0;s--){const n=t[s];this.context.connection.userIsInRoom(n.userId)?Ye&&(this.context.connection.connectionId===n.userId?console.warn(`You are still in the room [${s}] ${n.userId}`):console.log(`User is still in room [${s}] ${n.userId}`)):(Ye&&console.log(`Remove call ${[s]} to user that is not in room anymore ${n.userId}`),n.close(),t.splice(s,1))}}this.peer.updateCalls(),this.debug&&this.debugLogCurrentState()}debugLogCurrentState(){console.warn(`You (${this.context.connection.connectionId}) are currently sending ${this._sendingStreams.size} and receiving ${this.peer.incomingCalls.length} calls (${this.peer.incomingCalls.map(e=>e.userId).join(", ")})`,this.peer.incomingCalls)}}function on(o){if(o&&o instanceof MediaStream)for(const e of o.getTracks())e.stop()}var UT=Object.defineProperty,Wf=(o,e,t,s)=>{for(var n=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=l(e,t,n)||n);return n&&UT(e,t,n),n};const zT="noVoip",NT=C("debugvoip");class jo extends I{constructor(){super(...arguments),a(this,"autoConnect",!0),a(this,"runInBackground",!0),a(this,"createMenuButton",!0),a(this,"debug",!1),a(this,"_net"),a(this,"_menubutton"),a(this,"_allowSending",!0),a(this,"_outputStream",null),a(this,"onJoinedRoom",async()=>{this.debug&&console.log("VOIP: Joined room"),await ys(300),this.autoConnect&&!this.isSending&&this._allowSending&&this.connect()}),a(this,"onLeftRoom",()=>{this.debug&&console.log("VOIP: Left room"),this.disconnect();for(const e of this._incomingStreams.values())on(e.srcObject);this._incomingStreams.clear()}),a(this,"_incomingStreams",new Map),a(this,"onReceiveStream",e=>{const t=e.target.userId,s=e.stream;let n=this._incomingStreams.get(t);n||(n=new Audio,this._incomingStreams.set(t,n)),n.srcObject=s,n.setAttribute("autoplay","true"),Ln.registerWaitForInteraction(()=>{n?.play().catch(r=>{console.error("VOIP: Failed to play audio",r)})})}),a(this,"onStreamEnded",e=>{const t=this._incomingStreams.get(e.userId);on(t?.srcObject),this._incomingStreams.delete(e.userId)}),a(this,"onEnabledChanged",()=>{for(const e of this._incomingStreams){const t=e[1];t.muted=!this.enabled}}),a(this,"onVisibilityChanged",()=>{if(this.runInBackground)return;const e=document.visibilityState!=="visible";this.setMuted(e);for(const t of this._incomingStreams){const s=t[1];s.muted=e}})}awake(){NT&&(this.debug=!0),this.debug&&(console.log("VOIP debugging: press 'v' to toggle mute or 'c' to toggle connect/disconnect"),window.addEventListener("keydown",async e=>{switch(e.key.toLowerCase()){case"v":console.log("MUTE?",!this.isMuted),this.setMuted(!this.isMuted);break;case"c":this.isSending?this.disconnect():this.connect();break}}),window.addEventListener("blur",()=>{console.log("VOIP: MUTE ON BLUR"),this.setMuted(!0)}),window.addEventListener("focus",()=>{console.log("VOIP: UNMUTE ON FOCUS"),this.setMuted(!1)}))}onEnable(){this._net||(this._net=ld.create(this)),this.debug&&(this._net.debug=!0),this._net.addEventListener(nn.StreamReceived,this.onReceiveStream),this._net.addEventListener(nn.StreamEnded,this.onStreamEnded),this._net.enable(),this.autoConnect&&this.context.connection.isConnected&&this.connect(),this.context.connection.beginListen(ie.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(ie.LeftRoom,this.onLeftRoom),this.onEnabledChanged(),this.updateButton(),window.addEventListener("visibilitychange",this.onVisibilityChanged)}onDisable(){var e;this._net&&(this._net.stopSendingStream(this._outputStream),this._net.removeEventListener(nn.StreamReceived,this.onReceiveStream),this._net.removeEventListener(nn.StreamEnded,this.onStreamEnded),(e=this._net)==null||e.disable()),this.context.connection.stopListen(ie.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(ie.LeftRoom,this.onLeftRoom),this.onEnabledChanged(),this.updateButton(),window.removeEventListener("visibilitychange",this.onVisibilityChanged)}onDestroy(){var e;(e=this._menubutton)==null||e.remove(),this._menubutton=void 0}get isSending(){return this._outputStream!=null&&this._outputStream.active}async connect(e){var t,s;if(!this._net)return console.error("Cannot connect to voice chat - NetworkedStreams not initialized. Make sure the component is enabled before calling this method."),!1;if(this.context.connection.isConnected){if(!await Y.microphonePermissionsGranted())return console.error("Cannot connect to voice chat - microphone permissions not granted"),this.updateButton(),!1}else return console.error("Cannot connect to voice chat - not connected to server"),this.updateButton(),!1;return this._allowSending=!0,(t=this._net)==null||t.stopSendingStream(this._outputStream),on(this._outputStream),this._outputStream=await this.getAudioStream(e),this._outputStream?(this.debug&&console.log("VOIP: Got audio stream"),(s=this._net)==null||s.startSendingStream(this._outputStream),this.updateButton(),!0):(this.updateButton(),await Y.microphonePermissionsGranted()?console.error("VOIP: Could not get audio stream - please make sure to connect an audio device and grant microphone permissions"):ec("Microphone permissions not granted: Please grant microphone permissions to use voice chat"),(this.debug||F())&&console.log("VOIP: Failed to get audio stream"),!1)}disconnect(e){var t;e!=null&&e.remember&&(this._allowSending=!1),(t=this._net)==null||t.stopSendingStream(this._outputStream),on(this._outputStream),this._outputStream=null,this.updateButton()}setMuted(e){var t;const s=(t=this._outputStream)==null?void 0:t.getAudioTracks();if(s)for(const n of s)n.enabled=!e}get isMuted(){var e;if(this._outputStream===null)return!1;const t=(e=this._outputStream)==null?void 0:e.getAudioTracks();if(t){for(const s of t)if(!s.enabled)return!0}return!1}async updateButton(){var e;if(this.createMenuButton){if(this._menubutton||(this._menubutton=document.createElement("button"),this._menubutton.addEventListener("click",()=>{this.isSending?this.disconnect({remember:!0}):this.connect(),Y.microphonePermissionsGranted().then(t=>{t||be("<strong>Microphone permissions not granted</strong>. Please allow your browser to use the microphone to be able to talk. Click on the button on the left side of your browser's address bar to allow microphone permissions.")})})),this._menubutton){this.context.menu.appendChild(this._menubutton),this.activeAndEnabled?this._menubutton.style.display="":this._menubutton.style.display="none",this._menubutton.title=this.isSending?"Click to disable your microphone":"Click to enable your microphone";let t=(this.isSending,""),s=this.isSending?"mic":"mic_off";await Y.microphonePermissionsGranted()||(t="No Permission",s="mic_off",this._menubutton.title="Microphone permissions not granted. Please allow your browser to use the microphone to be able to talk. This can usually be done in the addressbar of the webpage."),this._menubutton.innerText=t,this._menubutton.prepend(kt(s)),this.context.connection.isConnected==!1?this._menubutton.setAttribute("disabled",""):this._menubutton.removeAttribute("disabled")}}else this.activeAndEnabled||(e=this._menubutton)==null||e.remove()}getFrequency(e){return this.unsupported_getfrequency||(this.unsupported_getfrequency=!0,F()&&be("VOIP: getFrequency is currently not supported"),console.warn("VOIP: getFrequency is currently not supported")),null}async getAudioStream(e){if(!navigator.mediaDevices.getUserMedia)return console.error("No getDisplayMedia support"),null;const t=async n=>await navigator.mediaDevices.getUserMedia({audio:n??!0,video:!1}).catch(r=>(console.warn("VOIP failed getting audio stream",r),null)),s=await t(e);if(!s)return null;if(Y.isiOS()&&e?.deviceId===void 0){const n=(await navigator.mediaDevices.enumerateDevices()).find(r=>(r.kind==="audioinput"||r.kind==="audiooutput")&&!r.label.includes("iPhone"));if(n){const r=Object.assign({},e);return r.deviceId=n.deviceId,await t(r)}}return s}}Wf([m()],jo.prototype,"autoConnect"),Wf([m()],jo.prototype,"runInBackground"),Wf([m()],jo.prototype,"createMenuButton");var WT=Object.defineProperty,Lx=(o,e,t,s)=>{for(var n=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=l(e,t,n)||n);return n&&WT(e,t,n),n};const VT=C("debugmouth");class Fc extends I{constructor(){super(...arguments),a(this,"idle",[]),a(this,"talking",[]),a(this,"marker",null),a(this,"voip",null),a(this,"lastMouthChangeTime",0),a(this,"mouthChangeLength",0)}awake(){setTimeout(()=>{this.voip=P.findObjectOfType(jo,this.context),this.marker||(this.marker=P.getComponentInParent(this.gameObject,ci))},3e3)}update(){var e;if(!this.voip||this.context.time.frameCount%10!==0)return;let t=((e=this.marker)==null?void 0:e.connectionId)??null;if(!t){VT&&(t=null);return}const s=this.voip.getFrequency(t)??0;this.updateLips(s)}updateLips(e){if(this.context.time.time-this.lastMouthChangeTime>this.mouthChangeLength){if(this.mouthChangeLength=.05+Math.random()*.1,this.talking&&this.talking.length>0&&e>30){this.lastMouthChangeTime=this.context.time.time;const t=Math.floor(Math.random()*this.talking.length);this.setMouthShapeActive(this.talking,t)}else if(this.idle.length>0&&this.context.time.time-this.lastMouthChangeTime>.5){this.lastMouthChangeTime=this.context.time.time;const t=Math.floor(Math.random()*this.idle.length);this.setMouthShapeActive(this.idle,t)}}}setMouthShapeActive(e,t){if(e){e!=this.idle?this.idle.map(s=>s.visible=!1):this.talking.map(s=>s.visible=!1);for(let s=0;s<e.length;s++){const n=e[s];n&&(n.visible=s===t)}}}}Lx([m(E)],Fc.prototype,"idle"),Lx([m(E)],Fc.prototype,"talking");class Vf extends I{constructor(){super(...arguments),a(this,"voip",null),a(this,"marker",null),a(this,"_startPosition",null)}awake(){this.voip=P.findObjectOfType(jo,this.context),this.marker=P.getComponentInParent(this.gameObject,ci)}update(){if(!this.voip||!this.marker||this.context.time.frameCount%10!==0)return;const e=this.marker.connectionId,t=this.voip.getFrequency(e);if(t==null)return;this._startPosition||(this._startPosition=this.gameObject.position.clone());const s=t/100;this.gameObject.position.y=this._startPosition.y+s*.07}}var HT=Object.defineProperty,$T=(o,e,t,s)=>{for(var n=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=l(e,t,n)||n);return n&&HT(e,t,n),n};const Qa=C("debugxrflags"),jx=C("disablexrflags");jx&&console.warn("XRFlags are disabled");var rn=(o=>(o[o.Never=0]="Never",o[o.Browser=1]="Browser",o[o.AR=2]="AR",o[o.VR=4]="VR",o[o.FirstPerson=8]="FirstPerson",o[o.ThirdPerson=16]="ThirdPerson",o[o.All=4294967295]="All",o))(rn||{});const Hf=class{constructor(){a(this,"Mask",17)}Has(e){return(this.Mask&e)!==0}Set(e){Qa&&console.warn("Set XR flag state to",e),this.Mask=e,ns.Apply()}Enable(e){this.Mask|=e,ns.Apply()}Disable(e){this.Mask&=~e,ns.Apply()}Toggle(e){this.Mask^=e,ns.Apply()}EnableAll(){this.Mask=-1,ns.Apply()}DisableAll(){this.Mask=0,ns.Apply()}};a(Hf,"Global",new Hf);let ji=Hf;var Di;const Dx=(Di=class extends I{constructor(){super(...arguments),a(this,"visibleIn")}static Apply(){for(const o of this.registry)o.UpdateVisible(ji.Global)}awake(){Di.registry.push(this)}onEnable(){Di.firstApply?this.UpdateVisible(ji.Global):(Di.firstApply=!0,Di.Apply())}onDestroy(){const o=Di.registry.indexOf(this);o>=0&&Di.registry.splice(o,1)}get isOn(){return this.gameObject.visible}UpdateVisible(o=null){if(jx)return;let e;const t=o;if(t&&typeof t=="number"&&(console.assert(typeof t=="number","XRFlag.UpdateVisible: state must be a number",t),Qa&&console.log(t),Di.buffer.Mask=t,o=Di.buffer),o instanceof ji?(Qa&&console.warn(this.name,"use passed in mask",o.Mask,this.visibleIn),e=o.Has(this.visibleIn)):(Qa&&console.log(this.name,"use global mask"),ji.Global.Has(this.visibleIn)),e!==void 0)if(e)Qa&&console.log(this.name,"is visible",this.gameObject.uuid),P.setActive(this.gameObject,!0);else{if(Qa&&console.log(this.name,"is not visible",this.gameObject.uuid),!this.gameObject.visible)return;this.gameObject.visible=!1}}},a(Di,"registry",[]),a(Di,"firstApply"),a(Di,"buffer",new ji),Di);$T([m()],Dx.prototype,"visibleIn");let ns=Dx;var GT=Object.defineProperty,Du=(o,e,t,s)=>{for(var n=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=l(e,t,n)||n);return n&&GT(e,t,n),n};class Br extends I{constructor(){super(...arguments),a(this,"eyes",[]),a(this,"lastBlinkTime",0),a(this,"blinkLength",0),a(this,"eyesOpen",!0),a(this,"state",null)}awake(){this.state=P.getComponentInParent(this.gameObject,ns)}update(){if(!(!this.gameObject||!this.gameObject.visible||!this.eyes||!Array.isArray(this.eyes)||this.eyes.length===0)&&this.context.time.time-this.lastBlinkTime>this.blinkLength){if(this.lastBlinkTime=this.context.time.time,this.state&&!this.state.isOn||!this.activeAndEnabled)return;if(this.eyesOpen=!this.eyesOpen,this.blinkLength=Math.random(),this.eyesOpen?(this.blinkLength*=3,this.blinkLength+=.5,Math.random()<.1&&(this.blinkLength=.1+Math.random()*.2)):(this.blinkLength*=Math.random()*.2,this.blinkLength+=.1),Math.random()<.1&&(this.blinkLength*=3),this.blinkLength=Math.max(.2,this.blinkLength),this.blinkLength=Math.min(3,this.blinkLength),this.eyes)for(const e of this.eyes)e&&(e.visible=this.eyesOpen)}}}Du([m(E)],Br.prototype,"eyes"),Du([m()],Br.prototype,"lastBlinkTime"),Du([m()],Br.prototype,"blinkLength"),Du([m()],Br.prototype,"eyesOpen");var qT=Object.defineProperty,$f=(o,e,t,s)=>{for(var n=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=l(e,t,n)||n);return n&&qT(e,t,n),n},Bu;const Fu=(Bu=class extends I{constructor(){super(...arguments),a(this,"head",null),a(this,"eyes",null),a(this,"target",null),a(this,"brain",null),a(this,"vec",new x),a(this,"currentTargetPoint",new x)}awake(){this.brain||(this.brain=P.getComponentInParent(this.gameObject,Bc)),this.brain||(this.brain=P.addComponent(this.gameObject,Bc)),this.brain&&this.target&&(this.brain.controlledTarget=this.target)}update(){const o=this.target;if(o&&this.head){const e=this.eyes;if(e){const t=te(o);this.currentTargetPoint.lerp(t,this.context.time.deltaTime/.1);const s=te(this.head),n=this.vec.copy(this.currentTargetPoint).sub(s).normalize();if(n.length()<.1)return;const r=Bu.forward;if(r.set(0,0,1),r.applyQuaternion(Se(this.head)),r.dot(n)>.45)for(let l=0;l<e.length;l++)e[l].lookAt(this.currentTargetPoint)}}}},a(Bu,"forward",new x(0,0,1)),Bu);$f([m(E)],Fu.prototype,"head"),$f([m(E)],Fu.prototype,"eyes"),$f([m(E)],Fu.prototype,"target");let Gf=Fu;var XT=Object.defineProperty,qf=(o,e,t,s)=>{for(var n=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=l(e,t,n)||n);return n&&XT(e,t,n),n};class Ya extends I{constructor(){super(...arguments),a(this,"length",1),a(this,"depthTest",!0),a(this,"isGizmo",!1),a(this,"_axes",null)}onEnable(){if(this.isGizmo&&!gc)return;this._axes||(this._axes=new Si(this.length)),this._axes.layers.disableAll(),this._axes.layers.set(this.layer),this.gameObject.add(this._axes);const e=this._axes.material;e&&e.depthTest!==void 0&&(e.depthTest=this.depthTest)}onDisable(){this._axes&&this.gameObject.remove(this._axes)}}qf([m()],Ya.prototype,"length"),qf([m()],Ya.prototype,"depthTest"),qf([m()],Ya.prototype,"isGizmo");class Xf extends I{constructor(){super(...arguments),a(this,"from"),a(this,"to"),a(this,"hint"),a(this,"desiredDistance",1)}onEnable(){}update(){if(!this.from||!this.to||!this.hint)return;const e=te(this.to).clone(),t=te(this.from).clone(),s=e.distanceTo(t),n=e.clone();n.sub(t);const r=t.clone();r.add(e),r.multiplyScalar(.5);const l=te(this.hint).clone();l.sub(r);const c=new x;c.crossVectors(l,n),c.crossVectors(n,c),c.normalize();const h=s*.5,d=Math.max(this.desiredDistance,h),u=Math.sqrt(d*d-h*h),p=c.clone();p.multiplyScalar(u),p.add(r),lt(this.gameObject,p);const g=r.clone();g.sub(c),this.gameObject.lookAt(g)}}const QT=C("gizmos"),YT=C("debugboxhelper"),Uc=class xn extends I{constructor(){super(...arguments),a(this,"box",null),a(this,"_lastMatrixUpdateFrame",-1),a(this,"_helper",null),a(this,"_color",null)}isInBox(e){var t;if(!e)return;if(this.box||(this.box=new xi),ii([e],void 0,void 0,xn.testBox),xn.testBox.isEmpty()){const n=te(e,xn._position);xn.testBox.setFromCenterAndSize(n,xn._emptyObjectSize)}this.updateBox();const s=(t=this.box)==null?void 0:t.intersectsBox(xn.testBox);return s&&YT&&G.DrawWireBox3(xn.testBox,16711680,5),s}intersects(e){return e?this.updateBox(!1).intersectsBox(e):!1}updateBox(e=!1){if(this.box||(this.box=new xi),e||this.context.time.frameCount!=this._lastMatrixUpdateFrame){const t=this._lastMatrixUpdateFrame<0;this._lastMatrixUpdateFrame=this.context.time.frameCount;const s=t,n=te(this.gameObject,xn._position,s),r=Ge(this.gameObject,xn._size);this.box.setFromCenterAndSize(n,r)}return this.box}awake(){this._helper=null,this._color=null,this.box=null}showHelper(e=null,t=!1){var s;if(!(!QT&&!t)){if(this._helper){e&&((s=this._color)==null||s.set(e)),this.gameObject.add(this._helper);return}this._helper=Fg(e),this.gameObject.add(this._helper)}}};a(Uc,"testBox",new xi),a(Uc,"_position",new x),a(Uc,"_size",new x(.01,.01,.01)),a(Uc,"_emptyObjectSize",new x(.01,.01,.01));let Do=Uc;var KT=Object.defineProperty,hi=(o,e,t,s)=>{for(var n=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=l(e,t,n)||n);return n&&KT(e,t,n),n};class di extends I{constructor(){super(...arguments),a(this,"attachedRigidbody",null),a(this,"isTrigger",!1),a(this,"sharedMaterial"),a(this,"membership",[0]),a(this,"filter"),a(this,"updateProperties",()=>{var e;(e=this.context.physics.engine)==null||e.updateProperties(this)})}get isCollider(){return!0}awake(){super.awake(),this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(dt))}start(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(dt))}onEnable(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(dt))}onDisable(){var e;(e=this.context.physics.engine)==null||e.removeBody(this)}get body(){var e;return(e=this.context.physics.engine)==null?void 0:e.getBody(this)}updatePhysicsMaterial(){var e;(e=this.context.physics.engine)==null||e.updatePhysicsMaterial(this)}}hi([m(dt)],di.prototype,"attachedRigidbody"),hi([m()],di.prototype,"isTrigger"),hi([m()],di.prototype,"sharedMaterial"),hi([m()],di.prototype,"membership"),hi([m()],di.prototype,"filter");class Ka extends di{constructor(){super(...arguments),a(this,"radius",.5),a(this,"center",new x(0,0,0))}onEnable(){var e;super.onEnable(),(e=this.context.physics.engine)==null||e.addSphereCollider(this),Cd(this.gameObject.scale,this.updateProperties)}onDisable(){super.onDisable(),Gm(this.gameObject.scale,this.updateProperties)}onValidate(){this.updateProperties()}}hi([Rt(),m()],Ka.prototype,"radius"),hi([m(x)],Ka.prototype,"center");const Qf=class gC extends di{constructor(){super(...arguments),a(this,"size",new x(1,1,1)),a(this,"center",new x(0,0,0))}static add(e,t){const s=Ti(e,gC);return s.autoFit(),t?.rigidbody===!0&&Ti(e,dt,{isKinematic:!1}),s}onEnable(){var e;super.onEnable(),(e=this.context.physics.engine)==null||e.addBoxCollider(this,this.size),Cd(this.gameObject.scale,this.updateProperties)}onDisable(){super.onDisable(),Gm(this.gameObject.scale,this.updateProperties)}onValidate(){this.updateProperties()}autoFit(e){const t=this.gameObject,s=t.position.clone(),n=t.quaternion.clone(),r=t.scale.clone(),l=t.parent;t.position.set(0,0,0),t.quaternion.set(0,0,0,1),t.scale.set(1,1,1),t.parent=null,t.updateMatrix();const c=ii([t]);t.position.copy(s),t.quaternion.copy(n),t.scale.copy(r),t.parent=l,e?.debug===!0&&G.DrawWireBox3(c,16768256,20),this.size=c.getSize(new x)||new x(1,1,1),this.center=c.getCenter(new x)||new x(0,0,0),this.size.length()<=0&&this.size.set(.01,.01,.01)}};hi([Rt(),m(x)],Qf.prototype,"size"),hi([m(x)],Qf.prototype,"center");let Uu=Qf;class Bo extends di{constructor(){super(...arguments),a(this,"sharedMesh"),a(this,"convex",!1)}onEnable(){var e,t,s;if(super.onEnable(),!this.context.physics.engine)return;(e=this.sharedMesh)!=null&&e.isMesh||(this.gameObject instanceof q||this.gameObject instanceof po)&&(this.sharedMesh=this.gameObject);const n=0;if((t=this.sharedMesh)!=null&&t.isMesh)this.context.physics.engine.addMeshCollider(this,this.sharedMesh,this.convex),Xe.assignMeshLOD(this.sharedMesh,n).then(r=>{r&&this.activeAndEnabled&&this.context.physics.engine&&this.sharedMesh&&(this.context.physics.engine.removeBody(this),this.sharedMesh.geometry=r,this.context.physics.engine.addMeshCollider(this,this.sharedMesh,this.convex))});else{const r=this.sharedMesh;if(r!=null&&r.isGroup){console.warn(`MeshCollider mesh is a group "${((s=this.sharedMesh)==null?void 0:s.name)||this.gameObject.name}", adding all children as colliders. This is currently not fully supported (colliders can not be removed from world again)`,this);const l=new Array;for(const c in r.children){const h=r.children[c];h.isMesh&&(this.context.physics.engine.addMeshCollider(this,h,this.convex),l.push(Xe.assignMeshLOD(h,n)))}Promise.all(l).then(c=>{var h,d;if(c.some(p=>p)==!1)return;(h=this.context.physics.engine)==null||h.removeBody(this);const u=new q;for(const p of c)p&&this.activeAndEnabled&&(u.geometry=p,(d=this.context.physics.engine)==null||d.addMeshCollider(this,u,this.convex))})}else(F()||C("showcolliders"))&&console.warn(`[MeshCollider] A MeshCollider mesh is assigned to an unknown object on "${this.gameObject.name}", but it's neither a Mesh nor a Group. Please double check that you attached the collider component to the right object and report a bug otherwise!`,this)}}}hi([m(q)],Bo.prototype,"sharedMesh"),hi([m()],Bo.prototype,"convex");class Wn extends di{constructor(){super(...arguments),a(this,"center",new x(0,0,0)),a(this,"radius",.5),a(this,"height",2)}onEnable(){var e;super.onEnable(),(e=this.context.physics.engine)==null||e.addCapsuleCollider(this,this.height,this.radius)}}hi([m(x)],Wn.prototype,"center"),hi([m()],Wn.prototype,"radius"),hi([m()],Wn.prototype,"height");var ZT=Object.defineProperty,Vn=(o,e,t,s)=>{for(var n=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=l(e,t,n)||n);return n&&ZT(e,t,n),n};const Bx=C("debugcharactercontroller");class Fr extends I{constructor(){super(...arguments),a(this,"center",new x(0,0,0)),a(this,"radius",.5),a(this,"height",2),a(this,"_rigidbody",null),a(this,"_activeGroundCollisions"),a(this,"_contactVelocity",new x)}get rigidbody(){return this._rigidbody?this._rigidbody:(this._rigidbody=this.gameObject.getComponent(dt),this._rigidbody||(this._rigidbody=this.gameObject.addComponent(dt)),this.rigidbody)}awake(){this._activeGroundCollisions=new Set}onEnable(){const e=this.rigidbody;let t=this.gameObject.getComponent(Wn);t||(t=this.gameObject.addComponent(Wn)),t.center.copy(this.center),t.radius=this.radius,t.height=this.height;const s=new x(0,0,1),n=new x(1,0,0),r=new x(0,1,0),l=this.gameObject.getWorldDirection(new x);l.y=0;const c=n.dot(l)<0?-1:1,h=s.angleTo(l)*c;this.gameObject.setRotationFromAxisAngle(r,h),e.lockRotationX=!0,e.lockRotationY=!0,e.lockRotationZ=!0}move(e){this.gameObject.position.add(e)}onCollisionEnter(e){(e.contacts.length==0||e.contacts.some(t=>t.normal.y>.2))&&(this._activeGroundCollisions.add(e),Bx&&console.log(`Collision(${this._activeGroundCollisions.size}): ${e.contacts.map(t=>t.normal.y.toFixed(2)).join(", ")} - ${this.isGrounded}`))}onCollisionExit(e){this._activeGroundCollisions.delete(e),Bx&&console.log(`Collision(${this._activeGroundCollisions.size}) - ${this.isGrounded}`)}get isGrounded(){return this._activeGroundCollisions.size>0}get contactVelocity(){var e;this._contactVelocity.set(0,0,0);for(const t of this._activeGroundCollisions){const s=(e=this.context.physics.engine)==null?void 0:e.getLinearVelocity(t.collider);s&&(this._contactVelocity.x+=s.x,this._contactVelocity.y+=s.y,this._contactVelocity.z+=s.z)}return this._contactVelocity}}Vn([m(x)],Fr.prototype,"center"),Vn([m()],Fr.prototype,"radius"),Vn([m()],Fr.prototype,"height");class Hn extends I{constructor(){super(...arguments),a(this,"controller"),a(this,"movementSpeed",2),a(this,"rotationSpeed",2),a(this,"jumpForce",1),a(this,"doubleJumpForce",2),a(this,"animator"),a(this,"lookForward",!0),a(this,"lookInput",new le(0,0)),a(this,"moveInput",new le(0,0)),a(this,"jumpInput",!1),a(this,"_currentSpeed",new x(0,0,0)),a(this,"_currentAngularSpeed",new x(0,0,0)),a(this,"_temp",new x(0,0,0)),a(this,"_jumpCount",0),a(this,"_currentRotation"),a(this,"_raycastOptions",new Qs)}awake(){this._currentRotation=new H}update(){const e=this.context.input;e.isKeyPressed("KeyW")?this.moveInput.y+=1:e.isKeyPressed("KeyS")&&(this.moveInput.y-=1),e.isKeyPressed("KeyD")?this.lookInput.x+=1:e.isKeyPressed("KeyA")&&(this.lookInput.x-=1),this.jumpInput||(this.jumpInput=e.isKeyDown("Space"))}move(e){this.moveInput.add(e)}look(e){this.lookInput.add(e)}jump(){this.jumpInput=!0}onBeforeRender(){this.handleInput(this.moveInput,this.lookInput,this.jumpInput),this.lookInput.set(0,0),this.moveInput.set(0,0),this.jumpInput=!1}handleInput(e,t,s){var n,r,l,c,h,d,u,p,g,f,y;if((n=this.controller)!=null&&n.isGrounded&&(this._jumpCount=0,this.doubleJumpForce>0&&((r=this.animator)==null||r.setBool("doubleJump",!1))),this._currentSpeed.z+=e.y*this.movementSpeed*this.context.time.deltaTime,(l=this.animator)==null||l.setBool("running",e.length()>.01),(h=this.animator)==null||h.setBool("jumping",((c=this.controller)==null?void 0:c.isGrounded)===!0&&s),this._temp.copy(this._currentSpeed),this._temp.applyQuaternion(this.gameObject.quaternion),this.controller?this.controller.move(this._temp):this.gameObject.position.add(this._temp),this._currentAngularSpeed.y+=W.toRadians(-t.x*this.rotationSpeed)*this.context.time.deltaTime,this.lookForward&&Math.abs(this._currentAngularSpeed.y)<.01){const b=this.context.mainCameraComponent.forward;b.y=0,b.normalize(),this._currentRotation.setFromUnitVectors(new x(0,0,1),b),this.gameObject.quaternion.slerp(this._currentRotation,this.context.time.deltaTime*10)}if(this.gameObject.rotateY(this._currentAngularSpeed.y),this._currentSpeed.multiplyScalar(1-this.context.time.deltaTime*10),this._currentAngularSpeed.y*=1-this.context.time.deltaTime*10,this.controller&&s&&this.jumpForce>0){let b=(d=this.controller)==null?void 0:d.isGrounded;if(this.doubleJumpForce>0&&!((u=this.controller)!=null&&u.isGrounded)&&this._jumpCount===1&&(b=!0,(p=this.animator)==null||p.setBool("doubleJump",!0)),b){this._jumpCount+=1;const v=this.controller.rigidbody,_=this._jumpCount===2?this.doubleJumpForce:this.jumpForce;v.applyImpulse(new x(0,1,0).multiplyScalar(_))}}if(this.controller){const b=(g=this.controller)==null?void 0:g.rigidbody.getVelocity().y;if(b<-1){this._raycastOptions.ray||(this._raycastOptions.ray=new uo),this._raycastOptions.ray.origin.copy(te(this.gameObject)),this._raycastOptions.ray.direction.set(0,-1,0);const v=this.layer;this.gameObject.layers.disableAll(),this.gameObject.layers.set(2);const _=this.context.physics.raycast(this._raycastOptions);this.gameObject.layers.set(v),(_.length&&_[0].distance>2||b<-10)&&((f=this.animator)==null||f.setBool("falling",!0))}else(y=this.animator)==null||y.setBool("falling",!1)}}}Vn([m(Fr)],Hn.prototype,"controller"),Vn([m()],Hn.prototype,"movementSpeed"),Vn([m()],Hn.prototype,"rotationSpeed"),Vn([m()],Hn.prototype,"jumpForce"),Vn([m()],Hn.prototype,"doubleJumpForce"),Vn([m(Mt)],Hn.prototype,"animator");var JT=Object.defineProperty,Za=(o,e,t,s)=>{for(var n=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=l(e,t,n)||n);return n&&JT(e,t,n),n};const zc=C("debugcontactshadows");gx(o=>{const e=o.domElement.getAttribute("contactshadows")||o.domElement.getAttribute("contact-shadows");if(e!=null&&e!="0"&&e!="false"){console.debug("Auto-creating ContactShadows because of `contactshadows` attribute");const t=Nc.auto(o),s=parseFloat(e);isNaN(s)||(t.opacity=s,t.darkness=s)}});var Ur;const zr=(Ur=class extends I{constructor(){super(...arguments),a(this,"autoFit",!1),a(this,"darkness",.5),a(this,"opacity",.5),a(this,"blur",4),a(this,"occludeBelowGround",!1),a(this,"backfaceShadows",!0),a(this,"minSize"),a(this,"manualUpdate",!1),a(this,"_needsUpdate",!1),a(this,"shadowsRoot",new E),a(this,"shadowCamera"),a(this,"shadowGroup",new po),a(this,"renderTarget"),a(this,"renderTargetBlur"),a(this,"plane"),a(this,"occluderMesh"),a(this,"blurPlane"),a(this,"depthMaterial"),a(this,"horizontalBlurMaterial"),a(this,"verticalBlurMaterial"),a(this,"textureSize",512)}static auto(o){if(o||(o=ee.Current),!o)throw new Error("No context provided and no current context set.");let e=this._instances.get(o);if(!e||e.destroyed){const t=new E;e=Ti(t,Ur,{autoFit:!1,occludeBelowGround:!1}),this._instances.set(o,e)}return o.scene.add(e.gameObject),e.fitShadows(),e}set needsUpdate(o){this._needsUpdate=o}get needsUpdate(){return this._needsUpdate}fitShadows(){zc&&console.warn("Fitting shadows to scene"),Md(this.shadowsRoot,!1);const o=ii(this.context.scene.children,[this.shadowsRoot]),e=Math.max(1,this.blur/32),t=o.max.x-o.min.x,s=o.max.z-o.min.z;o.expandByVector(new x(e*t,0,e*s)),zc&&G.DrawWireBox3(o,16776960,60),this.gameObject.parent&&o.applyMatrix4(this.gameObject.parent.matrixWorld.clone().invert());const n=o.min,r=Math.max(1e-5,(o.max.y-n.y)*.002);o.max.y+=r,this.shadowsRoot.position.set((n.x+o.max.x)/2,n.y-r,(n.z+o.max.z)/2),this.shadowsRoot.scale.set(o.max.x-n.x,o.max.y-n.y,o.max.z-n.z),this.applyMinSize(),this.shadowsRoot.matrixWorldNeedsUpdate=!0,zc&&console.log("Fitted shadows to scene",this.shadowsRoot.scale.clone())}awake(){Ur._instances.set(this.context,this),this.shadowsRoot.hideFlags=Lu.DontExport,Md(this.shadowsRoot,!1)}start(){zc&&console.log("Create ContactShadows on "+this.gameObject.name,this),this.gameObject.add(this.shadowsRoot),this.shadowsRoot.add(this.shadowGroup),this.renderTarget=new Hs(this.textureSize,this.textureSize),this.renderTarget.texture.generateMipmaps=!1,this.renderTargetBlur=new Hs(this.textureSize,this.textureSize),this.renderTargetBlur.texture.generateMipmaps=!1;const o=new Ns(1,1).rotateX(Math.PI/2);this.gameObject instanceof q&&(console.warn("ContactShadows can not be added to a Mesh. Please add it to a Group or an empty Object"),Bn(this.gameObject,!1));const e=new Me({map:this.renderTarget.texture,opacity:this.opacity,color:0,transparent:!0,depthWrite:!1,side:go});this.plane=new q(o,e),this.plane.scale.y=-1,this.plane.layers.set(2),this.shadowsRoot.add(this.plane),this.plane&&(this.plane.renderOrder=1),this.occluderMesh=new q(this.plane.geometry,new Me({depthWrite:!0,stencilWrite:!0,colorWrite:!1,side:bd})).translateY(-1e-4),this.occluderMesh.renderOrder=-100,this.occluderMesh.layers.set(2),this.shadowsRoot.add(this.occluderMesh),this.blurPlane=new q(o),this.blurPlane.visible=!1,this.shadowGroup.add(this.blurPlane);const t=0,s=1;this.shadowCamera=new hd(-1/2,1/2,1/2,-1/2,t,s),this.shadowCamera.layers.enableAll(),this.shadowCamera.rotation.x=Math.PI/2,this.shadowGroup.add(this.shadowCamera),this.depthMaterial=new QC,this.depthMaterial.userData.darkness={value:this.darkness},this.depthMaterial.blending=YC,this.depthMaterial.blendEquation=KC,this.depthMaterial.onBeforeCompile=n=>{this.depthMaterial&&(n.uniforms.darkness=this.depthMaterial.userData.darkness,n.fragmentShader=`
945
+ uniform float darkness;
946
+ ${n.fragmentShader.replace("gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );","gl_FragColor = vec4( vec3( 1.0 ), ( 1.0 - fragCoordZ ) * darkness * opacity * (gl_FrontFacing ? 1.0 : 0.66) );")}
947
+ `)},this.depthMaterial.depthTest=!1,this.depthMaterial.depthWrite=!1,this.horizontalBlurMaterial=new Ws(JP),this.horizontalBlurMaterial.depthTest=!1,this.verticalBlurMaterial=new Ws(eO),this.verticalBlurMaterial.depthTest=!1,this.shadowGroup.visible=!1,this.autoFit?this.fitShadows():this.applyMinSize()}onEnable(){this._needsUpdate=!0}onDestroy(){var o,e,t,s,n,r,l,c;Ur._instances.get(this.context)===this&&Ur._instances.delete(this.context),(o=this.renderTarget)==null||o.dispose(),(e=this.renderTargetBlur)==null||e.dispose(),(t=this.depthMaterial)==null||t.dispose(),(s=this.horizontalBlurMaterial)==null||s.dispose(),(n=this.verticalBlurMaterial)==null||n.dispose(),(r=this.blurPlane)==null||r.geometry.dispose(),(l=this.plane)==null||l.geometry.dispose(),(c=this.occluderMesh)==null||c.geometry.dispose()}onBeforeRender(o){if(this.manualUpdate&&!this._needsUpdate)return;if(this._needsUpdate=!1,!this.renderTarget||!this.renderTargetBlur||!this.depthMaterial||!this.shadowCamera||!this.blurPlane||!this.shadowGroup||!this.plane||!this.horizontalBlurMaterial||!this.verticalBlurMaterial){zc&&console.error("ContactShadows: not initialized yet");return}const e=this.context.scene,t=this.context.renderer,s=t.getRenderTarget();this.shadowGroup.visible=!0,this.occluderMesh&&(this.occluderMesh.visible=!1);const n=this.plane.visible;this.plane.visible=!1,this.gameObject instanceof q&&Bn(this.gameObject,!1);const r=e.background;e.background=null,e.overrideMaterial=this.depthMaterial,this.backfaceShadows?this.depthMaterial.side=Ci:this.depthMaterial.side=go;const l=t.getClearAlpha();t.setClearAlpha(0);const c=t.xr.enabled;t.xr.enabled=!1;const h=this.context.scene.matrixWorldAutoUpdate;this.context.scene.matrixWorldAutoUpdate=!1;const d=t.renderLists.get(e,0),u=d.transparent;Fx.length=0,d.transparent=Fx,Yf.length=0;for(const g of d.opaque){if(!g.object.visible)continue;const f=g.material;let y=g.material.colorWrite==!1||f.wireframe===!0||jb(g.object)===!1;!y&&g.material.isLineMaterial&&(y=!0),!y&&g.material.isPointsMaterial&&(y=!0),y&&(Yf.push(g.object),g.object["needle:visible"]=g.object.visible,g.object.visible=!1)}t.setRenderTarget(this.renderTarget),t.clear(),t.render(e,this.shadowCamera),d.transparent=u;for(const g of Yf)g["needle:visible"]!=null&&(g.visible=g["needle:visible"]);e.overrideMaterial=null;const p=Math.max(this.blur,.05);this.blurShadow(p*2),this.blurShadow(p*.5),this.shadowGroup.visible=!1,this.occluderMesh&&(this.occluderMesh.visible=this.occludeBelowGround),this.plane.visible=n,t.setRenderTarget(s),t.setClearAlpha(l),e.background=r,t.xr.enabled=c,this.context.scene.matrixWorldAutoUpdate=h}blurShadow(o){if(!this.blurPlane||!this.shadowCamera||!this.renderTarget||!this.renderTargetBlur||!this.horizontalBlurMaterial||!this.verticalBlurMaterial)return;this.blurPlane.visible=!0;const e=this.shadowsRoot.worldScale,t=(e.x+e.z)/2,s=e.z/t,n=e.x/t;this.blurPlane.material=this.horizontalBlurMaterial,this.blurPlane.material.uniforms.tDiffuse.value=this.renderTarget.texture,this.horizontalBlurMaterial.uniforms.h.value=o*1/this.textureSize*s;const r=this.context.renderer,l=r.getRenderTarget();r.setRenderTarget(this.renderTargetBlur),r.render(this.blurPlane,this.shadowCamera),this.blurPlane.material=this.verticalBlurMaterial,this.blurPlane.material.uniforms.tDiffuse.value=this.renderTargetBlur.texture,this.verticalBlurMaterial.uniforms.v.value=o*1/this.textureSize*n,r.setRenderTarget(this.renderTarget),r.render(this.blurPlane,this.shadowCamera),this.blurPlane.visible=!1,r.setRenderTarget(l)}applyMinSize(){this.minSize&&this.shadowsRoot.scale.set(Math.max(this.minSize.x||0,this.shadowsRoot.scale.x),Math.max(this.minSize.y||0,this.shadowsRoot.scale.y),Math.max(this.minSize.z||0,this.shadowsRoot.scale.z))}},a(Ur,"_instances",new Map),Ur);Za([m()],zr.prototype,"autoFit"),Za([m()],zr.prototype,"darkness"),Za([m()],zr.prototype,"opacity"),Za([m()],zr.prototype,"blur"),Za([m()],zr.prototype,"occludeBelowGround"),Za([m()],zr.prototype,"backfaceShadows");let Nc=zr;const Fx=[],Yf=new Array,eE=C("logstats");class Kf extends I{onEnable(){console.log(this),eE&&this.startCoroutine(this.run(),Oe.OnAfterRender)}*run(){for(;this.enabled;){const e=this.context.renderer.info;console.log(e.memory,e.render,e.programs),yield}}}class Wc extends I{constructor(){super(...arguments),a(this,"isUsed",!0),a(this,"usedBy",null)}}class Zf extends I{}const Ux=C("debugdeletable"),zx=class fm extends Do{onEnable(){fm._instances.push(this)}onDisable(){const e=fm._instances.indexOf(this);e>=0&&fm._instances.splice(e,1)}};a(zx,"_instances",[]);let zu=zx;class Jf extends I{update(){for(const e of zu._instances){const t=this.gameObject;if(e.isInBox(t)===!0){const s=P.getComponentInParent(this.gameObject,Wc);if(s)Ux&&console.warn("DeleteBox: Not deleting object with usage marker",this.guid,s);else{if(Ux)try{if(e.box){const n=e.box,r=Do.testBox;G.DrawWireBox3(n,16711680,5),G.DrawWireBox3(r,255,5),console.log("DeleteBox: Destroying",this.gameObject,{deleteBoxArea:n,deletedObjectArea:r})}else console.log("DeleteBox: Destroying",this.gameObject)}catch{}mc(this.gameObject,this.context.connection)}}}}}var tE=Object.defineProperty,iE=(o,e,t,s)=>{for(var n=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=l(e,t,n)||n);return n&&tE(e,t,n),n};class Nu extends I{constructor(){super(...arguments),a(this,"visibleOn")}onEnable(){this.apply()}apply(){this.test()||P.setActive(this.gameObject,!1)}test(){return this.visibleOn<0?!0:Y.isMobileDevice()?(this.visibleOn&2)!==0:(this.visibleOn&1)!==0}}iE([m()],Nu.prototype,"visibleOn");var sE=Object.defineProperty,Nr=(o,e,t,s)=>{for(var n=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=l(e,t,n)||n);return n&&sE(e,t,n),n};const an=C("debugdrag"),e0=[];var t0=(o=>(o[o.XZPlane=0]="XZPlane",o[o.Attached=1]="Attached",o[o.HitNormal=2]="HitNormal",o[o.DynamicViewAngle=3]="DynamicViewAngle",o[o.SnapToSurfaces=4]="SnapToSurfaces",o[o.None=5]="None",o))(t0||{}),Ut;const Fo=(Ut=class extends I{constructor(){super(...arguments),a(this,"dragMode",3),a(this,"snapGridResolution",0),a(this,"keepRotation",!0),a(this,"xrDragMode",1),a(this,"xrKeepRotation",!1),a(this,"xrDistanceDragFactor",1),a(this,"showGizmo",!1),a(this,"_rigidbody",null),a(this,"_targetObject",null),a(this,"_dragHelper",null),a(this,"_draggingRigidbodies",[]),a(this,"_potentialDragStartEvt",null),a(this,"_dragHandlers",new Map),a(this,"_totalMovement",new x),a(this,"_marker",null),a(this,"_isDragging",!1),a(this,"_didDrag",!1)}static get HasAnySelected(){return this._active>0}static get CurrentlySelected(){e0.length=0;for(const o of this._instances)o._isDragging&&e0.push(o);return e0}get draggedObject(){return this._targetObject}setTargetObject(o){var e,t;this._targetObject=o;for(const n of this._dragHandlers.values())n.setTargetObject(o);const s="_rigidbody-was-kinematic";((e=this._rigidbody)==null?void 0:e[s])===!1&&(this._rigidbody.isKinematic=!1,this._rigidbody[s]=void 0),this._rigidbody=null,o&&(this._rigidbody=P.getComponentInChildren(o,dt),((t=this._rigidbody)==null?void 0:t.isKinematic)===!1&&(this._rigidbody.isKinematic=!0,this._rigidbody[s]=!1))}awake(){this._potentialDragStartEvt=null,this._dragHandlers=new Map,this._totalMovement=new x,this._marker=null,this._isDragging=!1,this._didDrag=!1,this._dragHelper=null,this._draggingRigidbodies=[]}start(){this.gameObject.getComponentInParent(Li)||this.gameObject.addComponent(Li)}onEnable(){Ut._instances.push(this)}onDisable(){Ut._instances=Ut._instances.filter(o=>o!==this)}allowEdit(o=null){return this.context.connection.allowEditing}onPointerEnter(o){if(!this.allowEdit(this.gameObject)||o.mode!=="screen"||(o.event.mode==="tracked-pointer"||o.event.mode==="transient-pointer"?this.xrDragMode:this.dragMode)===5)return;const e=P.getComponentInParent(o.object,Ut);!e||e!==this||(Ut.lastHovered=o.object,this.context.domElement.style.cursor="pointer")}onPointerMove(o){(this._isDragging||this._potentialDragStartEvt!==null)&&o.use()}onPointerExit(o){this.allowEdit(this.gameObject)&&o.mode==="screen"&&Ut.lastHovered===o.object&&(this.context.domElement.style.cursor="auto")}onPointerDown(o){if(!(!this.allowEdit(this.gameObject)||o.used||(o.mode==="tracked-pointer"||o.mode==="transient-pointer"?this.xrDragMode:this.dragMode)===5)&&(Ut.lastHovered=o.object,o.button===0)){this._dragHandlers.size===0&&(this._didDrag=!1,this._totalMovement.set(0,0,0),this._potentialDragStartEvt=o),this._targetObject||this.setTargetObject(this.gameObject),Ut._active+=1;const e=new i0(this,this._targetObject);if(this._dragHandlers.set(o.event.space,e),e.onDragStart(o),this._dragHandlers.size===2){const t=this._dragHandlers.values(),s=t.next().value,n=t.next().value;if(s instanceof i0&&n instanceof i0){const r=new nE(this,this._targetObject,s,n);this._dragHandlers.set(this.gameObject,r),r.onDragStart(o)}else console.error("Attempting to construct a MultiTouchDragHandler with invalid DragPointerHandlers. This is likely a bug.",{a:s,b:n})}o.use()}}onPointerUp(o){if(an&&G.DrawLabel(o.point??this.gameObject.worldPosition,"POINTERUP:"+o.pointerId+", "+o.button,.03,3),!this.allowEdit(this.gameObject)||o.button!==0)return;this._potentialDragStartEvt=null;const e=this._dragHandlers.get(o.event.space),t=this._dragHandlers.get(this.gameObject);t&&(t.handlerA===e||t.handlerB===e)&&(this._dragHandlers.delete(this.gameObject),t.onDragEnd(o)),e&&(Ut._active>0&&(Ut._active-=1),this.setTargetObject(null),e.onDragEnd&&e.onDragEnd(o),this._dragHandlers.delete(o.event.space),this._dragHandlers.size===0&&this.onLastDragEnd(o),o.use())}update(){for(const o of this._dragHandlers.values())o.collectMovementInfo&&o.collectMovementInfo(),o.getTotalMovement&&this._totalMovement.add(o.getTotalMovement());if(this._potentialDragStartEvt){if(!this._didDrag)if(this._totalMovement.length()>3e-4)this._didDrag=!0;else return;const o=this._potentialDragStartEvt;this._potentialDragStartEvt=null,this.onFirstDragStart(o)}for(const o of this._dragHandlers.values())o.onDragUpdate&&o.onDragUpdate(this._dragHandlers.size);this._dragHelper&&this._dragHelper.hasSelected&&this.onAnyDragUpdate()}onFirstDragStart(o){if(!o||!o.object)return;const e=P.getComponentInParent(o.object,Ut);if(!e||e!==this&&e._isDragging)return;const t=this._targetObject||this.gameObject;if(!t)return;this._isDragging=!0;const s=P.getComponentInChildren(t,sn);an&&console.log("DRAG START",s,t),s&&(s.fastMode=!0,s?.requestOwnership()),this._marker=P.addComponent(t,Wc),this._draggingRigidbodies.length=0;const n=P.getComponentsInChildren(t,dt);n&&this._draggingRigidbodies.push(...n)}onAnyDragUpdate(){if(!this._dragHelper)return;this._dragHelper.showGizmo=this.showGizmo,this._dragHelper.onUpdate(this.context);for(const e of this._draggingRigidbodies)e.wakeUp(),e.resetVelocities(),e.resetForcesAndTorques();const o=this._targetObject||this.gameObject;ds.markDirty(o)}onLastDragEnd(o){if(!this||!this._isDragging)return;this._isDragging=!1;for(const t of this._draggingRigidbodies)t.setVelocity(t.smoothedVelocity);if(this._draggingRigidbodies.length=0,this._targetObject=null,o!=null&&o.object){const t=P.getComponentInChildren(o.object,sn);t&&(t.fastMode=!1)}if(this._marker&&this._marker.destroy(),!this._dragHelper)return;const e=this._dragHelper.selected;an&&console.log("DRAG END",e,e?.visible),this._dragHelper.setSelected(null,this.context)}},a(Ut,"_active",0),a(Ut,"_instances",[]),a(Ut,"lastHovered"),Ut);Nr([m()],Fo.prototype,"dragMode"),Nr([m()],Fo.prototype,"snapGridResolution"),Nr([m()],Fo.prototype,"keepRotation"),Nr([m()],Fo.prototype,"xrDragMode"),Nr([m()],Fo.prototype,"xrKeepRotation"),Nr([m()],Fo.prototype,"xrDistanceDragFactor"),Nr([m()],Fo.prototype,"showGizmo");let Wr=Fo;class nE{constructor(e,t,s,n){a(this,"handlerA"),a(this,"handlerB"),a(this,"context"),a(this,"settings"),a(this,"gameObject"),a(this,"_handlerAAttachmentPoint",new x),a(this,"_handlerBAttachmentPoint",new x),a(this,"_followObject"),a(this,"_manipulatorObject"),a(this,"_deviceMode"),a(this,"_followObjectStartWorldQuaternion",new H),a(this,"_manipulatorPosOffset",new x),a(this,"_manipulatorRotOffset",new H),a(this,"_manipulatorScaleOffset",new x),a(this,"_tempVec1",new x),a(this,"_tempVec2",new x),a(this,"_tempVec3",new x),a(this,"tempLookMatrix",new se),a(this,"_initialScale",new x),a(this,"_initialDistance",0);var r,l;this.context=e.context,this.settings=e,this.gameObject=t,this.handlerA=s,this.handlerB=n,this._followObject=new E,this._manipulatorObject=new E,this.context.scene.add(this._manipulatorObject);const c=(l=(r=ne.active)==null?void 0:r.rig)==null?void 0:l.gameObject;if(!this.handlerA||!this.handlerB||!this.handlerA.hitPointInLocalSpace||!this.handlerB.hitPointInLocalSpace){console.error("Invalid: MultiTouchDragHandler needs two valid DragPointerHandlers with hitPointInLocalSpace set.");return}if(this._tempVec1.copy(this.handlerA.hitPointInLocalSpace),this._tempVec2.copy(this.handlerB.hitPointInLocalSpace),this.gameObject.localToWorld(this._tempVec1),this.gameObject.localToWorld(this._tempVec2),c&&(c.worldToLocal(this._tempVec1),c.worldToLocal(this._tempVec2)),this._initialDistance=this._tempVec1.distanceTo(this._tempVec2),this._initialDistance<.02?(an&&console.log("Finding alternative drag attachment points since initial distance is too low: "+this._initialDistance.toFixed(2)),this.handlerA.followObject.parent.getWorldPosition(this._tempVec1),this.handlerB.followObject.parent.getWorldPosition(this._tempVec2),this._handlerAAttachmentPoint.copy(this._tempVec1),this._handlerBAttachmentPoint.copy(this._tempVec2),this.gameObject.worldToLocal(this._handlerAAttachmentPoint),this.gameObject.worldToLocal(this._handlerBAttachmentPoint),this._initialDistance=this._tempVec1.distanceTo(this._tempVec2),this._initialDistance<.001&&(console.warn("Not supported right now \u2013 controller drag points for multitouch are too close!"),this._initialDistance=1)):(this._handlerAAttachmentPoint.copy(this.handlerA.hitPointInLocalSpace),this._handlerBAttachmentPoint.copy(this.handlerB.hitPointInLocalSpace)),this._tempVec3.lerpVectors(this._tempVec1,this._tempVec2,.5),this._initialScale.copy(t.scale),an){this._followObject.add(new Si(2)),this._manipulatorObject.add(new Si(5));const h=d=>`${d.x.toFixed(2)}, ${d.y.toFixed(2)}, ${d.z.toFixed(2)}`;G.DrawLine(this._tempVec1,this._tempVec2,65535,0,!1),G.DrawLabel(this._tempVec3,"A:B "+this._initialDistance.toFixed(2)+`
948
+ `+h(this._tempVec1)+`
949
+ `+h(this._tempVec2),.03,5)}}onDragStart(e){this.gameObject.add(this._followObject),this._followObject.matrixAutoUpdate=!1,this._followObject.matrix.identity(),this._deviceMode=e.mode,this._followObjectStartWorldQuaternion.copy(this._followObject.worldQuaternion),this.alignManipulator(),this._manipulatorObject.attach(this._followObject),this._manipulatorPosOffset.copy(this._followObject.position),this._manipulatorRotOffset.copy(this._followObject.quaternion),this._manipulatorScaleOffset.copy(this._followObject.scale)}onDragEnd(e){if(!this.handlerA||!this.handlerB){console.error("onDragEnd called on MultiTouchDragHandler without valid handlers. This is likely a bug.");return}this.handlerA.recenter(),this.handlerB.recenter(),this._manipulatorObject.removeFromParent(),this._followObject.removeFromParent(),this._manipulatorObject.destroy(),this._followObject.destroy()}alignManipulator(){if(!this.handlerA||!this.handlerB){console.error("alignManipulator called on MultiTouchDragHandler without valid handlers. This is likely a bug.",this);return}if(!this.handlerA.followObject||!this.handlerB.followObject){console.error("alignManipulator called on MultiTouchDragHandler without valid follow objects. This is likely a bug.",this.handlerA,this.handlerB);return}this._tempVec1.copy(this._handlerAAttachmentPoint),this._tempVec2.copy(this._handlerBAttachmentPoint),this.handlerA.followObject.localToWorld(this._tempVec1),this.handlerB.followObject.localToWorld(this._tempVec2),this._tempVec3.lerpVectors(this._tempVec1,this._tempVec2,.5),this._manipulatorObject.position.copy(this._tempVec3);const e=this.context.mainCamera;this.tempLookMatrix.lookAt(this._tempVec3,this._tempVec2,e.worldUp),this._manipulatorObject.quaternion.setFromRotationMatrix(this.tempLookMatrix);const t=this._tempVec1.distanceTo(this._tempVec2);this._manipulatorObject.scale.copy(this._initialScale).multiplyScalar(t/this._initialDistance),this._manipulatorObject.updateMatrix(),this._manipulatorObject.updateMatrixWorld(!0),an&&(G.DrawLabel(this._tempVec3.clone().add(new x(0,.2,0)),"A:B "+t.toFixed(2),.03),G.DrawLine(this._tempVec1,this._tempVec2,65280,0,!1))}onDragUpdate(){this.alignManipulator();const e=30,t=1;this._followObject.position.copy(this._manipulatorPosOffset),this._followObject.quaternion.copy(this._manipulatorRotOffset),this._followObject.scale.copy(this._manipulatorScaleOffset);const s=this.gameObject,n=this._followObject;if(!s){console.error("MultiTouchDragHandler has no dragged object. This is likely a bug.");return}n.updateMatrix(),n.updateMatrixWorld(!0);const r=this._deviceMode==="tracked-pointer"||this._deviceMode==="transient-pointer"?this.settings.xrKeepRotation:this.settings.keepRotation;if(this.settings.snapGridResolution>0){const u=this._followObject.worldPosition,p=this.settings.snapGridResolution;u.x=Math.round(u.x/p)*p,u.y=Math.round(u.y/p)*p,u.z=Math.round(u.z/p)*p,this._followObject.worldPosition=u,this._followObject.updateMatrix()}r&&(this._followObject.worldQuaternion=this._followObjectStartWorldQuaternion,this._followObject.updateMatrix());const l=W.clamp01(this.context.time.deltaTime*e*t),c=s.worldPosition;c.lerp(n.worldPosition,l),s.worldPosition=c;const h=s.worldQuaternion;h.slerp(n.worldQuaternion,l),s.worldQuaternion=h;const d=s.worldScale;d.lerp(n.worldScale,l),s.worldScale=d}setTargetObject(e){this.gameObject=e}}class i0{constructor(e,t){a(this,"context"),a(this,"gameObject"),a(this,"settings"),a(this,"_lastRig"),a(this,"_followObject"),a(this,"_totalMovement",new x),a(this,"_totalMovementAlongRayDirection",0),a(this,"_grabStartDistance",0),a(this,"_deviceMode"),a(this,"_followObjectStartPosition",new x),a(this,"_followObjectStartQuaternion",new H),a(this,"_followObjectStartWorldQuaternion",new H),a(this,"_lastDragPosRigSpace"),a(this,"_tempVec",new x),a(this,"_tempMat",new se),a(this,"_hitPointInLocalSpace",new x),a(this,"_hitNormalInLocalSpace",new x),a(this,"_bottomCenter",new x),a(this,"_backCenter",new x),a(this,"_backBottomCenter",new x),a(this,"_bounds",new xi),a(this,"_dragPlane",new mr(new x(0,1,0))),a(this,"_draggedOverObject",null),a(this,"_draggedOverObjectLastSetUp",null),a(this,"_draggedOverObjectLastNormal",new x),a(this,"_draggedOverObjectDuration",0),a(this,"_hasLastSurfaceHitPoint",!1),a(this,"_lastSurfaceHitPoint",new x),this.settings=e,this.context=e.context,this.gameObject=t,this._followObject=new E}getTotalMovement(){return this._totalMovement}get followObject(){return this._followObject}get hitPointInLocalSpace(){return this._hitPointInLocalSpace}setTargetObject(e){this.gameObject=e}recenter(){var e,t;if(!this._followObject.parent){console.warn("Error: space follow object doesn't have parent but recenter() is called. This is likely a bug");return}if(!this.gameObject){console.warn("Error: space follow object doesn't have a gameObject");return}const s=this._followObject.parent;this.gameObject.add(this._followObject),this._followObject.matrixAutoUpdate=!1,this._followObject.position.set(0,0,0),this._followObject.quaternion.set(0,0,0,1),this._followObject.scale.set(1,1,1),this._followObject.updateMatrix(),this._followObject.updateMatrixWorld(!0),s.attach(this._followObject),this._followObjectStartPosition.copy(this._followObject.position),this._followObjectStartQuaternion.copy(this._followObject.quaternion),this._followObjectStartWorldQuaternion.copy(this._followObject.worldQuaternion),this._followObject.updateMatrix(),this._followObject.updateMatrixWorld(!0);const n=this._hitPointInLocalSpace.clone();this.gameObject.localToWorld(n),this._grabStartDistance=n.distanceTo(s.worldPosition);const r=(t=(e=ne.active)==null?void 0:e.rig)==null?void 0:t.gameObject,l=r?.worldScale.x||1;this._grabStartDistance/=l,this._totalMovementAlongRayDirection=0,this._lastDragPosRigSpace=void 0,an&&(G.DrawLine(n,s.worldPosition,65280,.5,!1),G.DrawLabel(s.worldPosition.add(new x(0,.1,0)),this._grabStartDistance.toFixed(2),.03,.5))}onDragStart(e){if(!this.gameObject){console.warn("Error: space follow object doesn't have a gameObject");return}if(e.event.space.add(this._followObject),this._lastDragPosRigSpace=void 0,e.point&&e.normal)this._hitPointInLocalSpace.copy(e.point),this.gameObject.worldToLocal(this._hitPointInLocalSpace),this._hitNormalInLocalSpace.copy(e.normal);else if(e){const f=e.event.space,y=f.worldPosition;this.gameObject.worldToLocal(y),this._hitPointInLocalSpace.copy(y);const b=f.worldUp;this._tempMat.copy(this.gameObject.matrixWorld).invert(),b.transformDirection(this._tempMat),this._hitNormalInLocalSpace.copy(b)}this.recenter(),this._totalMovement.set(0,0,0),this._deviceMode=e.mode;const t=this._followObject.parent.worldForward,s=this._deviceMode==="tracked-pointer"||this._deviceMode==="transient-pointer"?this.settings.xrDragMode:this.settings.dragMode,n=this._hitPointInLocalSpace.clone();switch(this.gameObject.localToWorld(n),s){case 0:const f=new x(0,1,0);this.gameObject.parent&&f.transformDirection(this.gameObject.parent.matrixWorld.clone().invert()),this._dragPlane.setFromNormalAndCoplanarPoint(f,n);break;case 2:const y=this._hitNormalInLocalSpace.clone();y.transformDirection(this.gameObject.matrixWorld),this._dragPlane.setFromNormalAndCoplanarPoint(y,n);break;case 1:this._dragPlane.setFromNormalAndCoplanarPoint(t,n);break;case 3:this.setPlaneViewAligned(n,!0);break;case 4:this.setPlaneViewAligned(n,!1);break}const r=this.gameObject.parent,l=this.gameObject.position.clone(),c=this.gameObject.quaternion.clone(),h=this.gameObject.scale.clone(),d=this.gameObject.matrixWorld.clone();r&&r.remove(this.gameObject),this.gameObject.position.set(0,0,0),this.gameObject.quaternion.set(0,0,0,1),this.gameObject.scale.set(1,1,1);const u=ii([this.gameObject]);u.expandByPoint(this.gameObject.worldPosition);const p=new x;u.getCenter(p);const g=new x;u.getSize(g),this._bottomCenter.copy(p.clone().add(new x(0,-g.y/2,0))),this._backCenter.copy(p.clone().add(new x(0,0,g.z/2))),this._backBottomCenter.copy(p.clone().add(new x(0,-g.y/2,g.z/2))),this._bounds.copy(u),r&&r.add(this.gameObject),this.gameObject.position.copy(l),this.gameObject.quaternion.copy(c),this.gameObject.scale.copy(h),this.gameObject.matrixWorld.copy(d),this._draggedOverObject=null,this._draggedOverObjectLastSetUp=null,this._draggedOverObjectLastNormal.set(0,1,0),this._draggedOverObjectDuration=0}collectMovementInfo(){var e,t;if(!this._followObject.parent)return;const s=this._followObject.parent;this._followObject.updateMatrix();const n=s.worldPosition,r=(t=(e=ne.active)==null?void 0:e.rig)==null?void 0:t.gameObject;r&&r.worldToLocal(n),(this._lastDragPosRigSpace===void 0||r!=this._lastRig)&&(this._lastDragPosRigSpace=n.clone(),this._lastRig=r),this._tempVec.copy(n).sub(this._lastDragPosRigSpace);const l=s.worldForward;if(r&&(this._tempMat.copy(r.matrixWorld).invert(),l.transformDirection(this._tempMat)),this._totalMovementAlongRayDirection+=l.dot(this._tempVec),this._tempVec.x=Math.abs(this._tempVec.x),this._tempVec.y=Math.abs(this._tempVec.y),this._tempVec.z=Math.abs(this._tempVec.z),this._totalMovement.add(this._tempVec),this._lastDragPosRigSpace.copy(n),an){let c=n;r&&(c=c.clone(),c.transformDirection(r.matrixWorld)),G.DrawRay(c,l,255)}}onDragUpdate(e){if(e>1)return;const t=this.gameObject;if(!t||!this._followObject){console.warn("Warning: DragPointerHandler doesn't have a dragged object. This is likely a bug.");return}const s=this._followObject.parent;if(!s){console.warn("Warning: DragPointerHandler doesn't have a drag source. This is likely a bug.");return}this._followObject.updateMatrix();const n=s.worldPosition,r=s.worldForward,l=this._deviceMode==="tracked-pointer"||this._deviceMode==="transient-pointer",c=l?this.settings.xrKeepRotation:this.settings.keepRotation,h=l?this.settings.xrDragMode:this.settings.dragMode;if(h===5)return;const d=10;c&&(this._followObject.worldQuaternion=this._followObjectStartWorldQuaternion),this._followObject.updateMatrix(),this._followObject.updateMatrixWorld(!0);let u=1,p=2;if(l&&this._grabStartDistance>.5){const w=1+this._totalMovementAlongRayDirection*(2*this.settings.xrDistanceDragFactor);u=Math.max(0,w),u=u*u*u}else this._grabStartDistance<=.5&&(p=3);this._followObject.position.copy(this._followObjectStartPosition),c||this._followObject.quaternion.copy(this._followObjectStartQuaternion),this._followObject.position.multiplyScalar(u),this._followObject.updateMatrix();const g=this._hasLastSurfaceHitPoint;this._hasLastSurfaceHitPoint=!1;const f=new uo(n,r);if(h==4){const w=this.context.physics.raycastFromRay(f,{testObject:S=>S!==this.followObject&&S!==s&&S!==t});if(w.length>0){const S=w[0];if(this._draggedOverObject===S.object?this._draggedOverObjectDuration+=this.context.time.deltaTime:(this._draggedOverObject=S.object,this._draggedOverObjectDuration=0),S.face){this._hasLastSurfaceHitPoint=!0,this._lastSurfaceHitPoint.copy(S.point);const k=this._draggedOverObjectDuration>=.15,M=this._totalMovement.length()>=.001,T=X(S.normal||S.face.normal).applyQuaternion(S.object.worldQuaternion);if((k||M)&&(this._draggedOverObjectLastSetUp!==this._draggedOverObject||this._draggedOverObjectLastNormal.dot(T)<.999999||this.context.time.frame%60===0)){this._draggedOverObjectLastSetUp=this._draggedOverObject,this._draggedOverObjectLastNormal.copy(S.face.normal);const L=X(),B=X();this._bounds.getCenter(L),this._bounds.getSize(B),L.sub(B.multiplyScalar(.5).multiply(T)),this._hitPointInLocalSpace.copy(L),this._hitNormalInLocalSpace.copy(S.face.normal),this._bounds.getCenter(L),this._bounds.getSize(B),L.add(B.multiplyScalar(.5).multiply(S.face.normal));const z=X(this._hitPointInLocalSpace).add(L);this._followObject.localToWorld(z);const D=S.point;this._dragPlane.setFromNormalAndCoplanarPoint(T,D)}else if(!(k||M))return}}else g&&this.gameObject&&this.setPlaneViewAligned(this.gameObject.worldPosition,!1)}if(h!==1&&f.intersectPlane(this._dragPlane,this._tempVec)){this._followObject.worldPosition=this._tempVec,this._followObject.updateMatrix(),this._followObject.updateMatrixWorld(!0);const w=X(this._hitPointInLocalSpace);this._followObject.localToWorld(w),an&&G.DrawLine(w,this._tempVec,65535,0,!1),this._followObject.worldPosition=this._tempVec.multiplyScalar(2).sub(w),this._followObject.updateMatrix(),this._followObject.updateMatrix()}if(this.settings.snapGridResolution>0){const w=this._followObject.worldPosition,S=this.settings.snapGridResolution;w.x=Math.round(w.x/S)*S,w.y=Math.round(w.y/S)*S,w.z=Math.round(w.z/S)*S,this._followObject.worldPosition=w,this._followObject.updateMatrix()}c&&(this._followObject.worldQuaternion=this._followObjectStartWorldQuaternion,this._followObject.updateMatrix());const y=W.clamp01(this.context.time.deltaTime*d*p),b=W.clamp01(this.context.time.deltaTime*d*.5*p),v=t.worldPosition;v.lerp(this._followObject.worldPosition,y),t.worldPosition=v;const _=t.worldQuaternion;if(_.slerp(this._followObject.worldQuaternion,b),t.worldQuaternion=_,an){const w=this._hitPointInLocalSpace.clone();t.localToWorld(w),G.DrawSphere(w,.02,16711680);const S=this._hitNormalInLocalSpace.clone();S.applyQuaternion(_),G.DrawRay(w,S,16711680),G.DrawLabel(v.add(new x(0,.25,0)),`Distance: ${this._totalMovement.length().toFixed(2)}
950
+
951
+ Along Ray: ${this._totalMovementAlongRayDirection.toFixed(2)}
952
+
953
+ Session: ${!!ne.active}
954
+
955
+ Device: ${this._deviceMode}
956
+
957
+ `,.03);const k=this._bottomCenter.clone(),M=this._backCenter.clone(),T=this._backBottomCenter.clone();t.localToWorld(k),t.localToWorld(M),t.localToWorld(T),G.DrawSphere(k,.01,65280,0,!1),G.DrawSphere(M,.01,255,0,!1),G.DrawSphere(T,.01,16711935,0,!1),G.DrawLine(k,T,65535,0,!1),G.DrawLine(T,M,65535,0,!1)}}onDragEnd(e){console.assert(this._followObject.parent===e.event.space,"Drag end: _followObject is not parented to the space object"),this._followObject.removeFromParent(),this._followObject.destroy(),this._lastDragPosRigSpace=void 0}setPlaneViewAligned(e,t){if(!this._followObject.parent)return!1;const s=this._followObject.parent.worldForward,n=X(0,1,0),r=s,l=n.angleTo(r),c=.5;return t&&(l>Math.PI/2+c||l<Math.PI/2-c)?this._dragPlane.setFromNormalAndCoplanarPoint(n,e):this._dragPlane.setFromNormalAndCoplanarPoint(s,e),!0}}const Nx=class fC{constructor(e){a(this,"showGizmo",!0),a(this,"useViewAngle",!0),a(this,"_selected",null),a(this,"_context",null),a(this,"_camera"),a(this,"_cameraPlane",new mr),a(this,"_hasGroundPlane",!1),a(this,"_groundPlane",new mr),a(this,"_groundOffset",new x),a(this,"_groundOffsetFactor",0),a(this,"_groundDistance",0),a(this,"_groundPlanePoint",new x),a(this,"_raycaster",new ud),a(this,"_cameraPlaneOffset",new x),a(this,"_intersection",new x),a(this,"_worldPosition",new x),a(this,"_inverseMatrix",new se),a(this,"_rbs",[]),a(this,"_groundLine"),a(this,"_groundMarker"),a(this,"_groundOffsetVector",new x(0,1,0)),a(this,"_requireUpdateGroundPlane",!0),a(this,"_didDragOnGroundPlaneLastFrame",!1),this._camera=e;const t=new Wl(fC.geometry),s=t.material;s.color=new ae(.4,.4,.4),t.layers.set(2),t.name="line",t.scale.y=1,this._groundLine=t;const n=new dd(.5,22,22),r=new Me({color:s.color}),l=new q(n,r);l.visible=!1,l.layers.set(2),this._groundMarker=l}get hasSelected(){return this._selected!==null&&this._selected!==void 0}get selected(){return this._selected}setSelected(e,t){if(this._selected&&t)for(const s of this._rbs)s.wakeUp(),s.setVelocity(0,0,0);if(this._selected&&Nn.Remove(t,this._selected),this._selected=e,this._context=t,this._rbs.length=0,e?(t.scene.add(this._groundLine),t.scene.add(this._groundMarker)):(this._groundLine.removeFromParent(),this._groundMarker.removeFromParent()),this._selected){if(!t){console.error("DragHelper: no context");return}Nn.Add(t,this._selected,null),this._groundOffsetFactor=0,this._hasGroundPlane=!0,this._groundOffset.set(0,0,0),this._requireUpdateGroundPlane=!0,this.onUpdateScreenSpacePlane()}}onUpdate(e){this._selected}onUpdateWorldPosition(e,t,s){if(this._selected){if(s){const n=te(this._selected);n.y=e.y,e=n}if(lt(this._selected,e),lt(this._groundLine,e),this._hasGroundPlane?this._groundLine.scale.y=this._groundDistance:this._groundLine.scale.y=1e3,this._groundLine.visible=this.showGizmo,this._groundMarker.visible=t!==null&&this.showGizmo,t){const n=te(this._camera).distanceTo(t)*.01;this._groundMarker.scale.set(n,n,n),lt(this._groundMarker,t)}}}onUpdateScreenSpacePlane(){if(!this._selected||!this._context)return;const e=this._context.input.getPointerPositionRC(0);e&&(this._raycaster.setFromCamera(e,this._camera),this._cameraPlane.setFromNormalAndCoplanarPoint(this._camera.getWorldDirection(this._cameraPlane.normal),this._worldPosition.setFromMatrixPosition(this._selected.matrixWorld)),this._raycaster.ray.intersectPlane(this._cameraPlane,this._intersection)&&this._selected.parent&&(this._inverseMatrix.copy(this._selected.parent.matrixWorld).invert(),this._cameraPlaneOffset.copy(this._intersection).sub(this._worldPosition.setFromMatrixPosition(this._selected.matrixWorld))))}onUpdateGroundPlane(){if(!this._selected||!this._context)return;const e=te(this._selected),t=new uo(X(0,.1,0).add(e),X(0,-1,0)),s=new Qs;s.testObject=r=>r!==this._selected;const n=this._context.physics.raycastFromRay(t,s);for(let r=0;r<n.length;r++){const l=n[r];if(!l.face||this.contains(this._selected,l.object))continue;const c=X(0,1,0);this._groundPlane.setFromNormalAndCoplanarPoint(c,l.point);break}this._hasGroundPlane=!0,this._groundPlane.setFromNormalAndCoplanarPoint(t.direction.multiplyScalar(-1),t.origin),this._raycaster.ray.intersectPlane(this._groundPlane,this._intersection),this._groundDistance=this._intersection.distanceTo(e),this._groundOffset.copy(this._intersection).sub(e)}contains(e,t){if(e===t)return!0;if(e.children){for(const s of e.children)if(this.contains(s,t))return!0}return!1}};a(Nx,"geometry",new Vs().setFromPoints([new x(0,0,0),new x(0,-1,0)]));let QL=Nx;var Wx=(o=>(o.File_Spawned="file-spawned",o))(Wx||{});class oE{constructor(e,t,s,n,r,l,c,h,d){a(this,"guid"),a(this,"file_name"),a(this,"file_hash"),a(this,"file_size"),a(this,"position"),a(this,"scale"),a(this,"seed"),a(this,"sender"),a(this,"downloadUrl"),a(this,"parentGuid"),a(this,"boundsSize"),this.seed=t,this.guid=s,this.file_name=n,this.file_hash=r,this.file_size=l,this.position=c,this.scale=h,this.sender=e,this.downloadUrl=d}}var Uo;(o=>{const e=new Map;function t(n){var r;e.has(n.guid)&&s(n.guid);const l=new E;e.set(n.guid,l);const c=new E;c.position.y=-.5,l.add(c);const h=new q(new ba(1,1,1,1,1,1),new Me({color:14540253,wireframe:!0,transparent:!0,opacity:.3}));h.position.y=.5,c.add(h);const d=new E;c.add(d);const u=new q(new ba(1,1,1,1,1,1),new Me({color:12307660,transparent:!0,opacity:.4}));u.position.y=.5,d.scale.y=.01,d.add(u);const p=new q(new Ns(1,1,1,1),new Me({color:34,transparent:!0,opacity:.05,depthTest:!1}));return p.rotateX(-Math.PI/2),p.position.y=.51,u.add(p),n.parent.add(l),l.rotateY(Math.PI/2),n.position&&((r=l.position)==null||r.copy(n.position)),n.size&&(l.worldScale=new x().copy(n.size)),l.position.y=l.scale.y/2,{object:l,onProgress:g=>{d instanceof E&&d.scale.set(1,g,1)}}}o.addPreview=t;function s(n){const r=e.get(n);r&&(e.delete(n),r.removeFromParent())}o.removePreview=s})(Uo||(Uo={}));const Ja=[],Wu=[];var s0;(o=>{function e(s,n){const r={name:n?.name,priority:n?.priority??0,callback:s};return Ja.push(r),Ja.sort((l,c)=>l.priority===c.priority?0:l.priority>c.priority?-1:1),()=>{const l=Ja.indexOf(r);l>=0&&Ja.splice(l,1)}}o.onCreateCustomModelLoader=e;function t(s){return Wu.push(s),()=>{const n=Wu.indexOf(s);n>=0&&Wu.splice(n,1)}}o.onDetermineModelMimetype=t})(s0||(s0={}));const Vc=C("debugfileformat");function Vx(o){switch((o.split(".").pop()||o).toUpperCase()){case"GLTF":return"model/gltf+json";case"VRM":return"model/vrm";case"GLB":return"model/gltf-binary";case"FBX":return"model/fbx";case"USD":return"model/vnd.usd+zip";case"USDA":return"model/vnd.usda+zip";case"USDZ":return"model/vnd.usdz+zip";case"OBJ":return"model/obj";default:return null}}async function Hx(o,e){var t;const{useExtension:s=!0}=e;if(s){const l=o,c=new URL(l,globalThis.location.href);let h=null;const d=c.searchParams.get("filetype");switch(d&&(h=d.toUpperCase()),h!=null&&h.length||(h=(t=c.pathname.split(".").pop())==null?void 0:t.toUpperCase()),Vc&&console.warn(`[Needle Engine] Try to use file extension to determine type: '${h}'`),h){case"GLTF":return"model/gltf+json";case"VRM":return"model/vrm";case"GLB":return"model/gltf-binary";case"FBX":return"model/fbx";case"USD":return"model/vnd.usd+zip";case"USDA":return"model/vnd.usda+zip";case"USDZ":return"model/vnd.usdz+zip";case"OBJ":return"model/obj"}}const n=o;if(!o.startsWith("blob:")){const l=new URL(o,globalThis.location.href);l.searchParams.append("range","true"),o=l.toString()}const r=await fetch(o,{method:"GET",headers:{range:"bytes=0-32"}}).catch(l=>null);if(r!=null&&r.ok){const l=await r.arrayBuffer(),c=$x(n,l,r);return Vc&&console.log("[Needle Engine] Determined file type from header: "+c),c}return"unknown"}function $x(o,e,t){if(e.byteLength<4)return"unknown";const s=new Uint8Array(e);if(Vc&&console.warn(`[Needle Engine] Trying to determine file type from binary data
958
+ `,'"'+new TextDecoder().decode(e)+`"
959
+ `,s),s[0]==103&&s[1]==108&&s[2]==84&&s[3]==70&&(s[4]==10||s[4]===2))return console.debug("GLTF detected"),"model/gltf+json";if(s[0]==103&&s[1]==108&&s[2]==84&&s[3]==70&&s[4]==98)return console.debug("GLB detected"),"model/gltf-binary";if(s[0]==80&&s[1]==75&&s[2]==3&&s[3]==4)return console.debug("USDZ detected"),"model/vnd.usdz+zip";if(s[0]==80&&s[1]==88&&s[2]==82&&s[3]==45&&s[4]==85&&s[5]==83&&s[6]==68&&s[7]==67)return console.debug("Binary USD detected"),"model/vnd.usd";if(s[0]==35&&s[1]==117&&s[2]==115&&s[3]==100&&s[4]==97)return console.debug("ASCII USD detected"),"model/vnd.usda";if(s[0]==75&&s[1]==97&&s[2]==121&&s[3]==100&&s[4]==97&&s[5]==114&&s[6]==97&&s[7]==32)return console.debug("Binary FBX detected"),"model/fbx";if(s[0]==59&&s[1]==32&&s[2]==70&&s[3]==66&&s[4]==88&&s[5]==32)return console.debug("ASCII FBX detected"),"model/fbx";if(s[0]==35&&s[1]==32&&s[2]==66&&s[3]==108&&s[4]==101&&s[5]==110&&s[6]==100&&s[7]==101&&s[8]==114&&s[9]==32||s[0]==35&&s[1]==32&&s[2]==65&&s[3]==108&&s[4]==105&&s[5]==97&&s[6]==115&&s[7]==32&&s[8]==79&&s[9]==66&&s[10]==74)return console.debug("OBJ detected"),"model/obj";if(t.headers.has("content-type")){const n=t.headers.get("content-type");if(n!=null&&n.startsWith("image/"))return console.debug("Image detected, not a model file"),"unsupported";switch(console.debug("Content-Type: "+n),n){case"model/gltf+json":case"model/gltf-binary":case"model/vrm":case"model/vnd.usdz+zip":case"model/vnd.usd+zip":case"model/vnd.usd":case"model/vnd.usda+zip":case"model/vnd.usda":case"model/vnd.usdc":case"model/fbx":case"model/vnd.autodesk.fbx":case"model/obj":return n}}if(s[0]==118&&s[1]==32||s[0]==102&&s[1]==32)return console.debug("OBJ detected (the file has no header and starts with vertex or face)"),"obj";if(s[0]==35&&s[1]==32&&s[2]==70&&s[3]==105&&s[4]==108&&s[5]==101&&s[6]==32&&s[7]==101&&s[8]==120&&s[9]==112&&s[10]==111&&s[11]==114&&s[12]==116&&s[13]==101&&s[14]==100&&s[15]==32&&s[16]==98&&s[17]==121&&s[18]==32&&s[19]==90&&s[20]==66&&s[21]==114&&s[22]==117&&s[23]==115&&s[24]==104)return console.debug("OBJ detected (exported by ZBrush)"),"obj";if(s[0]==109&&s[1]==116&&s[2]==108&&s[3]==108&&s[4]==105&&s[5]==98)return console.debug("OBJ detected (mtllib)"),"obj";for(const n of Wu){const r=n({url:o,response:t,contentType:t.headers.get("content-type"),bytes:s});if(r)return Vc&&console.debug(`Mimetype callback returned: ${r}`),r}if(F()||Vc){const n=new TextDecoder().decode(e.slice(0,Math.min(e.byteLength,32)));console.warn(`Could not determine file type.
960
+
961
+ Consider registering a custom loader via the 'onCreateCustomModelLoader' callback: 'NeedleEngineModelLoader.onCreateCustomModelLoader(args => { })'
962
+
963
+ Content-Type: "${t.headers.get("content-type")}
964
+ "Text: "${n}"
965
+ Binary:`,s)}else console.debug("Could not determine file type from binary data");return"unknown"}var rE=Object.defineProperty,el=(o,e,t,s)=>{for(var n=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=l(e,t,n)||n);return n&&rE(e,t,n),n};const Bi=C("debugdroplistener");class aE extends CustomEvent{constructor(e){super("object-added",{detail:e})}}const lE="blob";class $n extends I{constructor(){super(...arguments),a(this,"useNetworking",!0),a(this,"dropArea"),a(this,"fitIntoVolume",!1),a(this,"fitVolumeSize",new x(1,1,1)),a(this,"placeAtHitPosition",!0),a(this,"onDropped",new xe),a(this,"onNetworkEvent",e=>{var t;if(!this.useNetworking){Bi&&console.debug("[DropListener] Ignoring networked event because networking is disabled",e);return}if((t=e.guid)!=null&&t.startsWith(this.guid)){const s=e.url;if(console.debug("[DropListener] Received networked event",e),s)if(Array.isArray(s))for(const n of s)this.addFromUrl(n,{screenposition:new le,point:e.point,size:e.size},!0);else this.addFromUrl(s,{screenposition:new le,point:e.point,size:e.size},!0)}}),a(this,"handlePaste",e=>{this.context.connection.allowEditing===!1||e.defaultPrevented||navigator.clipboard.readText().then(t=>{if(t&&(t.startsWith("http")||t.startsWith("https")||t.startsWith("blob"))){const s={screenposition:new le(this.context.input.mousePosition.x,this.context.input.mousePosition.y)};this.testIfIsInDropArea(s)&&this.addFromUrl(t,s,!1)}}).catch(console.warn)}),a(this,"onDrag",e=>{this.context.connection.allowEditing!==!1&&e.preventDefault()}),a(this,"onDrop",async e=>{if(this.context.connection.allowEditing===!1||(Bi&&console.log(e),!(e!=null&&e.dataTransfer))||e["droplistener:handled"])return;e.preventDefault();const t={screenposition:new le(e.offsetX,e.offsetY)};if(this.dropArea&&this.testIfIsInDropArea(t)===!1)return;e["droplistener:handled"]=!0;const s=e.dataTransfer.items;if(!s)return;const n=[];for(const r in s){const l=s[r];if(l.kind==="file"){const c=l.getAsFile();if(!c)continue;n.push(c)}else l.kind==="string"&&l.type=="text/plain"&&l.getAsString(c=>{this.addFromUrl(c,t,!1)})}n.length>0&&await this.addDroppedFiles(n,t)}),a(this,"_abort",null),a(this,"_addedObjects",new Array),a(this,"_addedModels",new Array)}onEnable(){this.context.renderer.domElement.addEventListener("dragover",this.onDrag),this.context.renderer.domElement.addEventListener("drop",this.onDrop),window.addEventListener("paste",this.handlePaste),this.context.connection.beginListen("droplistener",this.onNetworkEvent)}onDisable(){this.context.renderer.domElement.removeEventListener("dragover",this.onDrag),this.context.renderer.domElement.removeEventListener("drop",this.onDrop),window.removeEventListener("paste",this.handlePaste),this.context.connection.stopListen("droplistener",this.onNetworkEvent)}loadFromURL(e,t){this.addFromUrl(e,{screenposition:new le,point:t?.point,size:t?.size},!0)}forgetObjects(){this.removePreviouslyAddedObjects(!1)}async addFromUrl(e,t,s){Bi&&console.log("dropped url",e);try{if(e.startsWith("https://github.com/")){const l=e.split("/"),c=l[3],h=l[4],d=l[6],u=l.slice(7).join("/");e=`https://raw.githubusercontent.com/${c}/${h}/${d}/${u}`}else e.startsWith("https://polyhaven.com/a")&&(e=cE(e));if(!e)return null;const n=e.toLowerCase();if(n.endsWith(".hdr")||n.endsWith(".hdri")||n.endsWith(".exr")||n.endsWith(".png")||n.endsWith(".jpg")||n.endsWith(".jpeg"))return null;this.removePreviouslyAddedObjects();const r=await Vu.loadFileFromURL(new URL(e),{guid:this.guid,context:this.context,parent:this.gameObject,point:t.point,size:t.size});if(r&&this._addedObjects.length<=0)return t.url=e,this.addObject(r,t,s)}catch{console.warn("String is not a valid URL",e)}return null}async addDroppedFiles(e,t){var s,n;if(Bi&&console.log("Add files",e),!!Array.isArray(e)&&e.length){this.deleteDropEvent(),this.removePreviouslyAddedObjects(),Hl(lE,null),(s=this._abort)==null||s.abort("New files dropped"),this._abort=new AbortController;for(const r of e){if(!r)continue;if(r.type.startsWith("image/")){Bi&&console.warn("Ignoring dropped image file",r.name,r.type);continue}else if(r.name.endsWith(".bin")){Bi&&console.warn("Ignoring dropped binary file",r.name,r.type);continue}console.debug("Load file "+r.name+" + "+r.type);const l=await Vu.loadFile(r,this.context,{guid:this.guid});if(l){this.dispatchEvent(new CustomEvent("file-dropped",{detail:r})),t.file=r;const c=this.addObject(l,t,!1);c&&this.context.connection.isConnected&&this.useNetworking&&(console.debug("Uploading dropped file to blob storage"),Tr.upload(r,{abort:(n=this._abort)==null?void 0:n.signal}).then(h=>{h!=null&&h.download_url&&this._addedObjects.includes(c)&&this.sendDropEvent(h.download_url,c,l.contentMD5)}).catch(console.warn));break}}}}removePreviouslyAddedObjects(e=!0){if(e)for(const t of this._addedObjects)t.parent===this.gameObject&&Ei(t,!0,!0);this._addedObjects.length=0,this._addedModels.length=0}addObject(e,t,s){var n,r;const{model:l,contentMD5:c}=e;if(Bi&&console.log(`Dropped ${this.gameObject.name}`,l),!(l!=null&&l.scene))return console.warn("No object specified to add to scene",l),null;this.removePreviouslyAddedObjects();const h=l.scene;this.gameObject.attach(h),h.position.set(0,0,0),h.quaternion.identity(),this._addedObjects.push(h),this._addedModels.push(l);const d=new xi().setFromCenterAndSize(new x(0,this.fitVolumeSize.y*.5,0).add(this.gameObject.worldPosition),this.fitVolumeSize);if(Bi&&G.DrawWireBox3(d,255,5),this.fitIntoVolume&&Db(h,d,{position:!this.placeAtHitPosition}),this.placeAtHitPosition&&t&&t.screenposition){h.visible=!1;const p=this.context.physics.raycast({screenPoint:this.context.input.convertScreenspaceToRaycastSpace(t.screenposition.clone())});if(h.visible=!0,p&&p.length>0)for(const g of p){const f=g.point.clone();Bi&&console.log("Place object at hit",g),Bb(h,f);break}}Va.assignAnimationsFromFile(l,{createAnimationComponent:p=>Ti(p,Bt)});const u=new aE({sender:this,gltf:l,model:l,object:h,contentMD5:c,dropped:t.file||(t.url?new URL(t.url):void 0)});return this.dispatchEvent(u),(n=this.onDropped)==null||n.invoke(u.detail),!s&&(r=t.url)!=null&&r.startsWith("http")&&this.context.connection.isConnected&&h&&this.sendDropEvent(t.url,h,c),h}async sendDropEvent(e,t,s){if(!this.useNetworking){Bi&&console.debug("[DropListener] Ignoring networked event because networking is disabled",e);return}if(this.context.connection.isConnected){console.debug('Sending drop event "'+t.name+'"',e);const n=ii([t]),r={name:t.name,guid:this.guid,url:e,point:t.worldPosition.clone(),size:n.getSize(new x),contentMD5:s};this.context.connection.send("droplistener",r)}}deleteDropEvent(){this.context.connection.sendDeleteRemoteState(this.guid)}testIfIsInDropArea(e){if(this.dropArea){const t=this.context.input.convertScreenspaceToRaycastSpace(e.screenposition.clone());if(!this.context.physics.raycast({targets:[this.dropArea],screenPoint:t,recursive:!0,testObject:s=>!this._addedObjects.includes(s)}).length)return F()&&console.log(`Dropped outside of drop area for DropListener "${this.name}".`),!1}return!0}}el([m()],$n.prototype,"useNetworking"),el([m(E)],$n.prototype,"dropArea"),el([m()],$n.prototype,"fitIntoVolume"),el([m(x)],$n.prototype,"fitVolumeSize"),el([m()],$n.prototype,"placeAtHitPosition"),el([m(xe)],$n.prototype,"onDropped");function cE(o){if(!o.startsWith("https://polyhaven.com/"))return o;const e="https://dl.polyhaven.org/file/ph-assets/Models/gltf/4k/",t=new URL(o).pathname.split("/").pop(),s=`${e}${t}/${t}_4k.gltf`;return console.log("Resolved polyhaven asset url",o,"\u2192",s),s}var Vu;(o=>{async function e(s,n,r){const l=r.guid,c=new Lt(l),h=new Blob([s],{type:s.type||Vx(s.name)||void 0}),d=URL.createObjectURL(h),u=await ws().loadSync(n,d,s.name,c).catch(p=>(console.error(`Failed to load file "${s.name}" (${s.type}):`,p),null));return URL.revokeObjectURL(d),u?new Promise((p,g)=>{const f=new FileReader;f.readAsArrayBuffer(s),f.onloadend=async y=>{const b=f.result,v=Tr.hashMD5(b);return p({model:u,contentMD5:v})}}):(console.warn(`Failed to load "${s.name}" (${s.type})`),null)}o.loadFile=e;async function t(s,n){return new Promise(async(r,l)=>{const c=new Lt(n.guid),h=s.toString();Bi&&G.DrawWireSphere(n.point,.1,16711680,3);const d=Uo.addPreview({guid:n.guid,parent:n.parent,position:n?.point,size:n?.size}),u=await ws().loadSync(n.context,h,h,c,p=>{d.onProgress(p.loaded/p.total)}).catch(console.warn);if(u){const p=await fetch(h).then(f=>f.arrayBuffer()),g=Tr.hashMD5(p);Bi?setTimeout(()=>Uo.removePreview(n.guid),3e3):Uo.removePreview(n.guid),r({model:u,contentMD5:g})}else Bi?setTimeout(()=>Uo.removePreview(n.guid),3e3):Uo.removePreview(n.guid),console.warn("Unsupported file type: "+s.toString())})}o.loadFileFromURL=t})(Vu||(Vu={}));var hE=Object.defineProperty,n0=(o,e,t,s)=>{for(var n=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=l(e,t,n)||n);return n&&hE(e,t,n),n};const Hu=class yC extends I{constructor(){super(...arguments),a(this,"parent",null),a(this,"object",null),a(this,"limitCount",60),a(this,"_currentCount",0),a(this,"_startPosition",null),a(this,"_startQuaternion",null),a(this,"_forwardPointerEvents",new Map)}start(){var e,t;if(this._currentCount=0,this._startPosition=null,this._startQuaternion=null,this.object||(this.object=this.gameObject),this.object){if(this.object===this.gameObject){const n=new Lt(this.guid);this.object=P.instantiate(this.object,{idProvider:n,keepWorldPosition:!1});const r=P.getComponent(this.object,yC);r?.destroy();let l=this.object.getComponentInChildren(Wr);l||(l=this.object.addComponent(Wr,{dragMode:t0.SnapToSurfaces}),l.guid=n.generateUUID());let c=P.getComponent(l.gameObject,sn);c||(c=l.gameObject.addComponent(sn),c.guid=n.generateUUID())}this.object.visible=!1;const s=this.gameObject.getComponent(Wr);s&&(s.enabled=!1),this._startPosition=((e=this.object.position)==null?void 0:e.clone())??new x(0,0,0),this._startQuaternion=((t=this.object.quaternion)==null?void 0:t.clone())??new H(0,0,0,1)}this.gameObject.getComponentInParent(Li)||this.gameObject.addComponent(Li)}onEnable(){this.startCoroutine(this.cloneLimitIntervalFn())}onPointerEnter(e){e.used||this.object&&this.context.connection.allowEditing&&e.button===0&&this.context.input.setCursor("pointer")}onPointerExit(e){e.used||this.object&&this.context.connection.allowEditing&&e.button===0&&this.context.input.unsetCursor("pointer")}onPointerDown(e){if(e.used||!this.object||!this.context.connection.allowEditing||e.button!==0)return;const t=this.handleDuplication();if(t){const s=P.getComponent(t,Wr);s?(s.onPointerDown(e),this._forwardPointerEvents.set(e.event.space,s)):console.warn("Duplicated object does not have DragControls",t)}else this._currentCount>=this.limitCount?console.warn(`[Duplicatable] Limit of ${this.limitCount} objects created within a few seconds reached. Please wait a moment before creating more objects.`):console.warn("[Duplicatable] Could not duplicate object.")}onPointerUp(e){if(e.used)return;const t=this._forwardPointerEvents.get(e.event.space);t&&(t.onPointerUp(e),this._forwardPointerEvents.delete(e.event.space))}*cloneLimitIntervalFn(){for(;this.activeAndEnabled&&!this.destroyed;)this._currentCount>0?this._currentCount-=1:this._currentCount<0&&(this._currentCount=0),yield ff(1)}handleDuplication(){var e;if(!this.object||this.limitCount>0&&this._currentCount>=this.limitCount||this.object===this.gameObject)return null;if(P.isDestroyed(this.object))return this.object=null,null;this.object.visible=!0,this._startPosition&&this.object.position.copy(this._startPosition),this._startQuaternion&&this.object.quaternion.copy(this._startQuaternion);const t=new Fs;this.parent||(this.parent=this.gameObject.parent),this.parent&&(t.parent=this.parent.guid??((e=this.parent.userData)==null?void 0:e.guid),t.keepWorldPosition=!0),t.position=this.worldPosition,t.rotation=this.worldQuaternion,t.context=this.context,this._currentCount+=1;const s=P.instantiateSynced(this.object,t);return console.assert(s!==this.object,"Duplicated object is original"),this.object.visible=!1,this._startPosition&&this.object.position.clone().copy(this._startPosition),this._startQuaternion&&this.object.quaternion.clone().copy(this._startQuaternion),s}};n0([m(E)],Hu.prototype,"parent"),n0([m(E)],Hu.prototype,"object"),n0([m()],Hu.prototype,"limitCount");let o0=Hu;var Gn=(o=>(o[o.PointerEnter=0]="PointerEnter",o[o.PointerExit=1]="PointerExit",o[o.PointerDown=2]="PointerDown",o[o.PointerUp=3]="PointerUp",o[o.PointerClick=4]="PointerClick",o[o.Drag=5]="Drag",o[o.Drop=6]="Drop",o[o.Scroll=7]="Scroll",o[o.UpdateSelected=8]="UpdateSelected",o[o.Select=9]="Select",o[o.Deselect=10]="Deselect",o[o.Move=11]="Move",o[o.InitializePotentialDrag=12]="InitializePotentialDrag",o[o.BeginDrag=13]="BeginDrag",o[o.EndDrag=14]="EndDrag",o[o.Submit=15]="Submit",o[o.Cancel=16]="Cancel",o))(Gn||{}),dE=Object.defineProperty,r0=(o,e,t,s)=>{for(var n=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=l(e,t,n)||n);return n&&dE(e,t,n),n};class a0{constructor(){a(this,"eventID"),a(this,"callback",new xe)}}r0([m()],a0.prototype,"eventID"),r0([m(xe)],a0.prototype,"callback");class $u extends I{constructor(){super(...arguments),a(this,"triggers",[])}invoke(e){var t;if(this.triggers)for(const s of this.triggers)s.eventID===e&&((t=s.callback)==null||t.invoke())}hasTrigger(e){var t;return((t=this.triggers)==null?void 0:t.some(s=>s.eventID===e))??!1}shouldChangeCursor(){return this.hasTrigger(Gn.PointerClick)||this.hasTrigger(Gn.PointerDown)||this.hasTrigger(Gn.PointerUp)}onPointerClick(e){this.invoke(Gn.PointerClick)}onPointerEnter(e){this.shouldChangeCursor()&&this.context.input.setCursor("pointer"),this.invoke(Gn.PointerEnter)}onPointerExit(e){this.shouldChangeCursor()&&this.context.input.unsetCursor("pointer"),this.invoke(Gn.PointerExit)}onPointerDown(e){this.invoke(Gn.PointerDown)}onPointerUp(e){this.invoke(Gn.PointerUp)}}r0([m(a0)],$u.prototype,"triggers");class Gx{constructor(e){a(this,"writer"),this.writer=e}writeNode(e){}}class uE extends Gx{beforeWriteNode(e,t){G.isGizmo(e)&&(t.keep=!1)}}class qx extends Gx{beforeWriteTexture(e,t){e.isRenderTargetTexture&&(t.newTexture=vf(new he(1,1,1,0)))}}function l0(o){const e=Lu.DontExport;return!(o.hideFlags&e)}const c0=C("debugexr");class pE{constructor(e){a(this,"parser"),this.parser=e,c0&&console.log(e)}get name(){return"EXT_texture_exr"}loadTexture(e){const t=this.name,s=this.parser,n=s.json.textures[e];if(c0&&console.log("EXT_texture_exr.loadTexture",e,n),!n.extensions||!n.extensions[t])return null;const r=n.extensions[t],l=new xd(s.options.manager);return c0&&console.log("EXT_texture_exr.loadTexture",r),s.loadTextureImage(e,r.source,l)}}typeof window<"u"&&window.addEventListener("unhandledrejection",o=>{});const qn=_t,Gu="$___Export_Components",mE="NEEDLE_components";var Xx;Xx=br;class gE{constructor(){a(this,Xx)}}class fE{constructor(e,t,s){a(this,"node"),a(this,"nodeIndex"),a(this,"nodeDef"),this.node=e,this.nodeIndex=t,this.nodeDef=s}}class Qx{constructor(){a(this,"parser"),a(this,"nodeToObjectMap",{}),a(this,"gltf",null),a(this,"exportContext"),a(this,"objectToNodeMap",{}),a(this,"context"),a(this,"writer")}get name(){return mE}registerExport(e){e.register(t=>{if("serializeUserData"in t){const s=t.serializeUserData.bind(t);this.writer=t,t.serializeUserData=(n,r)=>{try{this.serializeUserData(n,r)&&(t.extensionsUsed[this.name]=!0),s(n,r)}finally{this.afterSerializeUserData(n,r)}}}return this})}beforeParse(){this.exportContext={},this.objectToNodeMap={}}serializeUserData(e,t){var s;const n=(s=e.userData)==null?void 0:s.components;return!n||n.length<=0?!1:(delete e.userData.components,e[Gu]=n,!0)}afterSerializeUserData(e,t){if(e.type==="Scene"&&qn&&console.log("DONE",JSON.stringify(t)),e[Gu]===void 0)return;const s=e[Gu];delete e[Gu],s!==null&&(e.userData.components=s)}writeNode(e,t){const s=this.writer.json.nodes.length;qn&&console.log(e.name,s,e.uuid);const n=new fE(e,s,t);this.exportContext[s]=n,this.objectToNodeMap[e.uuid]=s}afterParse(e){var t;qn&&console.log("AFTER",e);for(const s in this.exportContext){const n=this.exportContext[s],r=n.node,l=n.nodeDef,c=n.nodeIndex,h=(t=r.userData)==null?void 0:t.components;if(!h||h.length<=0)continue;const d=new gE;l.extensions=l.extensions||{},l.extensions[this.name]=d,this.context.object=r,this.context.nodeId=c,this.context.objectToNode=this.objectToNodeMap;const u=[];for(const p of h){this.context.target=p;const g=ws().writeBuiltinComponentData(p,this.context);g!==null&&u.push(g)}u.length>0&&(d[br]=u,qn&&console.log("DID WRITE",r,"nodeIndex",c,u))}}beforeRoot(){return qn&&console.log("BEGIN LOAD"),this.nodeToObjectMap={},null}async afterRoot(e){this.gltf=e;const t=e.parser,s=t?.extensions;if(!s)return;const n=s[this.name];qn&&console.log("After root",e,this.parser,s);const r=[];if(n===!0){const l=t.json.nodes;if(l){for(let c=0;c<l.length;c++){const h=await t.getDependency("node",c);this.nodeToObjectMap[c]=h}for(let c=0;c<l.length;c++){const h=l[c],d=c,u=h.extensions;if(!u)continue;const p=u[this.name];if(!p)continue;qn&&console.log("NODE",h);const g=this.nodeToObjectMap[d];if(!g){console.error("Could not find object for node index: "+d,h,t);continue}su(g),r.push(this.createComponents(g,p))}}}await Promise.all(r);for(const l of t.associations.keys()){const c=t.associations.get(l);if(c?.materials!=null){const h="/materials/"+c.materials;zM(l,h)}}}async createComponents(e,t){if(!t)return;const s=t[br];if(s){const n=new Array;qn&&console.log(e.name,s);for(const r in s){const l=s[r];qn&&console.log("Serialized data",JSON.parse(JSON.stringify(l))),l&&this.parser&&n.push(sf(this.parser,l).catch(c=>console.error(`Error while resolving references (see console for details)
966
+ `,c,e,l))),e.userData=e.userData||{},e.userData[br]=e.userData[br]||[],e.userData[br].push(l)}await Promise.all(n).catch(r=>{console.error("Error while loading components",r)})}}}const Yx="NEEDLE_gameobject_data";class yE{constructor(e){a(this,"parser"),this.parser=e}get name(){return Yx}afterRoot(e){var t;const s=[];for(let n=0;n<((t=this.parser.json.nodes)==null?void 0:t.length);n++){const r=this.parser.json.nodes[n];if(r&&r.extensions){const l=r.extensions[Yx];if(l){const c=this.findAndApplyExtensionData(n,l);s.push(c)}}}return Promise.all(s).then(()=>null)}async findAndApplyExtensionData(e,t){const s=await this.parser.getDependency("node",e);s&&this.applyExtensionData(s,t)}applyExtensionData(e,t){t.layers===void 0&&(t.layers=0),e.userData.layer=t.layers,e.layers.disableAll(),e.layers.set(t.layers),e.userData.tag=t.tag??"none",e.hideFlags=0,e.userData.static=t.static??!1,e.visible=t.activeSelf??!0,e.guid=t.guid}}const Kx="NEEDLE_lighting_settings",tl=C("debugenvlight");class vE{constructor(e,t,s){a(this,"parser"),a(this,"sourceId"),a(this,"context"),this.parser=e,this.sourceId=t,this.context=s}get name(){return Kx}afterRoot(e){const t=this.parser.json.extensions;if(t){const s=t[Kx];if(s){tl&&console.log('Loaded "'+this.name+'", src: "'+this.sourceId+'"',s);let n;if(e.scene.children.length===1){const r=e.scene.children[0];n=P.addComponent(r,qu,{},{callAwake:!1})}else{const r=new E;r.name="LightSettings "+this.sourceId,e.scene.add(r),n=P.addComponent(r,qu,{},{callAwake:!1})}n.sourceId=this.sourceId,n.ambientIntensity=s.ambientIntensity,n.ambientLight=new ae().fromArray(s.ambientLight),Array.isArray(s.ambientTrilight)&&(n.ambientTrilight=s.ambientTrilight.map(r=>new ae().fromArray(r))),n.ambientMode=s.ambientMode,n.environmentReflectionSource=s.environmentReflectionSource}}return null}}pe.registerCallback(me.ContextCreated,o=>{const e=o.context,t=P.findObjectOfType(qu,e);t!=null&&t.sourceId&&(t.enabled=!0)});class qu extends I{constructor(){super(...arguments),a(this,"ambientMode",Ha.Skybox),a(this,"ambientLight"),a(this,"ambientTrilight"),a(this,"ambientIntensity",1),a(this,"environmentReflectionSource",uu.Skybox),a(this,"_hasReflection",!1),a(this,"_ambientLightObj"),a(this,"_hemisphereLightObj")}awake(){var e;if(this.sourceId){const s=this.environmentReflectionSource===uu.Skybox?xo.Skybox:xo.Reflection,n=this.context.lightmaps.tryGet(this.sourceId,s,0);this._hasReflection=n!=null,n&&this.context.sceneLighting.internalRegisterReflection(this.sourceId,n)}this.enabled=!1,this.context.sceneLighting.internalRegisterSceneLightSettings(this),tl&&window.addEventListener("keydown",s=>{if(!this.destroyed)switch(s.key){case"l":this.enabled=!this.enabled;break}});const t=(e=this.gameObject.userData)==null?void 0:e.components;if(t){const s=t.indexOf(this);t.splice(s,1),t.push(this)}}onDestroy(){this.context.sceneLighting.internalUnregisterSceneLightSettings(this)}calculateIntensityFactor(e){const t=Math.max(e.r,e.g,e.b);return 2.2*W.lerp(0,1.33,t)}onEnable(){if(tl&&console.warn("\u{1F4A1}\u{1F7E1} >>> Enable lighting",this.sourceId,this.enabled,this),this.ambientMode==Ha.Flat){if(this.ambientLight&&!this._ambientLightObj){const e=this.calculateIntensityFactor(this.ambientLight);this._ambientLightObj=new ZC(this.ambientLight,this.ambientIntensity*e),tl&&console.log("Created ambient light",this.sourceId,this._ambientLightObj,this.ambientIntensity,e)}this._ambientLightObj&&this.gameObject.add(this._ambientLightObj)}else if(this.ambientMode===Ha.Trilight){if(this.ambientTrilight){const e=this.ambientTrilight[0],t=this.ambientTrilight[this.ambientTrilight.length-1],s=this.calculateIntensityFactor(t);this._hemisphereLightObj=new JC(t,e,this.ambientIntensity*s),this.gameObject.add(this._hemisphereLightObj),tl&&console.log("Created hemisphere ambient light",this.sourceId,this._hemisphereLightObj,this.ambientIntensity,s)}}else this._ambientLightObj&&this._ambientLightObj.removeFromParent(),this._hemisphereLightObj&&this._hemisphereLightObj.removeFromParent();this.sourceId&&this.context.sceneLighting.internalEnableReflection(this.sourceId)}onDisable(){tl&&console.warn("\u{1F4A1}\u26AB <<< Disable lighting:",this.sourceId,this),this._ambientLightObj&&this._ambientLightObj.removeFromParent(),this._hemisphereLightObj&&this._hemisphereLightObj.removeFromParent(),this.sourceId&&this.context.sceneLighting.internalDisableReflection(this.sourceId)}}const h0=C("debugstencil");function bE(o,e){return(o&1<<e.layer)!=0}const _E=Symbol("stencils"),Zx=class jl{constructor(e,t){a(this,"parser"),a(this,"source"),this.parser=e,this.source=t}get name(){return"NEEDLE_render_objects"}static applyStencil(e){if(!e)return;const t=e.sourceId;if(h0&&console.log(t,jl.stencils),!t)return;const s=jl.stencils[t];if(s)for(let n=s.length-1;n>=0;n--){const r=s[n];if(bE(r.layer,e)){h0&&console.log(r),setTimeout(()=>{qt()&&ou(e.gameObject)&&(be("Stencil not supported on instanced objects"),console.warn("Stencil not supported on instanced objects",e))},500);for(let l=0;l<e.sharedMaterials.length;l++){let c=e.sharedMaterials[l];c&&(c=c.clone(),c[_E]=!0,c.stencilWrite=!0,c.stencilWriteMask=255,c.stencilFuncMask=255,c.stencilRef=r.value,c.stencilFunc=r.compareFunc,c.stencilZPass=r.passOp,c.stencilFail=r.failOp,c.stencilZFail=r.zFailOp,e.sharedMaterials[l]=c)}e.gameObject.renderOrder=r.event*1e3+r.index*50;break}}}afterRoot(e){const t=this.parser.json.extensions;if(t){const s=t[xE];if(s){h0&&console.log(s);const n=s.stencil;if(n&&Array.isArray(n))for(const r of n){const l={...r};l.compareFunc=wE(l.compareFunc),l.passOp=d0(l.passOp),l.failOp=d0(l.failOp),l.zFailOp=d0(l.zFailOp),jl.stencils[this.source]||(jl.stencils[this.source]=[]),jl.stencils[this.source].push(l)}}}return null}};a(Zx,"stencils",{});let Jx=Zx;function d0(o){switch(o){case 0:return mP;case 1:return pP;case 2:return uP;case 3:return dP;case 4:return hP;case 6:return cP;case 7:return lP;case 5:return aP}return 0}function wE(o){switch(o){case 1:return Ev;case 2:return rP;case 3:return oP;case 4:return nP;case 5:return sP;case 6:return iP;case 7:return tP;case 8:return eP}return Ev}const xE="NEEDLE_render_objects";var e1=(o=>(o[o.INT=5124]="INT",o[o.FLOAT=5126]="FLOAT",o[o.FLOAT_VEC2=35664]="FLOAT_VEC2",o[o.FLOAT_VEC3=35665]="FLOAT_VEC3",o[o.FLOAT_VEC4=35666]="FLOAT_VEC4",o[o.INT_VEC2=35667]="INT_VEC2",o[o.INT_VEC3=35668]="INT_VEC3",o[o.INT_VEC4=35669]="INT_VEC4",o[o.BOOL=35670]="BOOL",o[o.BOOL_VEC2=35671]="BOOL_VEC2",o[o.BOOL_VEC3=35672]="BOOL_VEC3",o[o.BOOL_VEC4=35673]="BOOL_VEC4",o[o.FLOAT_MAT2=35674]="FLOAT_MAT2",o[o.FLOAT_MAT3=35675]="FLOAT_MAT3",o[o.FLOAT_MAT4=35676]="FLOAT_MAT4",o[o.SAMPLER_2D=35678]="SAMPLER_2D",o[o.SAMPLER_3D=35680]="SAMPLER_3D",o[o.SAMPLER_CUBE=35681]="SAMPLER_CUBE",o[o.UNKNOWN=0]="UNKNOWN",o))(e1||{});const ln=C("debugcustomshader"),il="NEEDLE_techniques_webgl";class SE{constructor(){a(this,"objectToWorldMatrix",new se),a(this,"worldToObjectMatrix",new se),a(this,"objectToWorld",new Array),a(this,"worldToObject",new Array)}updateFrom(e){this.objectToWorldMatrix.copy(e.matrixWorld),du(this.objectToWorldMatrix,this.objectToWorld),this.worldToObjectMatrix.copy(e.matrixWorld).invert(),du(this.worldToObjectMatrix,this.worldToObject)}}const cn=class He extends Av{constructor(e,...t){super(...t),a(this,"identifier"),a(this,"onBeforeRenderSceneCallback",this.onBeforeRenderScene.bind(this)),a(this,"_sphericalHarmonicsName","unity_SpecCube0"),a(this,"_objToWorldName","hlslcc_mtx4x4unity_ObjectToWorld"),a(this,"_worldToObjectName","hlslcc_mtx4x4unity_WorldToObject"),a(this,"_viewProjectionName","hlslcc_mtx4x4unity_MatrixVP"),a(this,"_viewMatrixName","hlslcc_mtx4x4unity_MatrixV"),a(this,"_rendererData",new SE),this.identifier=e,ln&&console.log(this),this.type="NEEDLE_CUSTOM_SHADER",this.uniforms[this._objToWorldName]||(this.uniforms[this._objToWorldName]={value:[]}),this.uniforms[this._worldToObjectName]||(this.uniforms[this._worldToObjectName]={value:[]}),this.uniforms[this._viewProjectionName]||(this.uniforms[this._viewProjectionName]={value:[]}),this.uniforms[this._sphericalHarmonicsName],(this.depthTextureUniform||this.opaqueTextureUniform)&&ee.Current.pre_render_callbacks.push(this.onBeforeRenderSceneCallback)}clone(){const e=super.clone();return i1(e),e}dispose(){super.dispose();const e=ee.Current.pre_render_callbacks.indexOf(this.onBeforeRenderSceneCallback);e>=0&&ee.Current.pre_render_callbacks.splice(e,1)}get depthTextureUniform(){if(this.uniforms)return this.uniforms._CameraDepthTexture}get opaqueTextureUniform(){if(this.uniforms)return this.uniforms._CameraOpaqueTexture}onBeforeRenderScene(){this.opaqueTextureUniform&&ee.Current.setRequireColor(!0),this.depthTextureUniform&&ee.Current.setRequireDepth(!0)}onBeforeRender(e,t,s,n,r,l){n.attributes.tangent||n.computeTangents(),this.onUpdateUniforms(s,r)}onUpdateUniforms(e,t){const s=ee.Current;if(e&&(He.viewProjection&&this.uniforms[this._viewProjectionName]&&(He.viewProjection.copy(e.projectionMatrix).multiply(e.matrixWorldInverse),du(He.viewProjection,He._viewProjectionValues)),He.viewMatrix&&this.uniforms[this._viewMatrixName]&&(He.viewMatrix.copy(e.matrixWorldInverse),du(He.viewMatrix,He._viewMatrixValues)),this.uniforms[He._worldSpaceCameraPosName]&&He._worldSpaceCameraPos.setFromMatrixPosition(e.matrixWorld)),this.uniforms._TimeParameters&&(this.uniforms._TimeParameters.value=s.sceneLighting.timeVec4),this.uniforms._Time){const c=this.uniforms._Time.value;c.x=s.sceneLighting.timeVec4.x/20,c.y=s.sceneLighting.timeVec4.x,c.z=s.sceneLighting.timeVec4.x*2,c.w=s.sceneLighting.timeVec4.x*3}if(this.uniforms._SinTime){const c=this.uniforms._SinTime.value;c.x=Math.sin(s.sceneLighting.timeVec4.x/8),c.y=Math.sin(s.sceneLighting.timeVec4.x/4),c.z=Math.sin(s.sceneLighting.timeVec4.x/2),c.w=Math.sin(s.sceneLighting.timeVec4.x)}if(this.uniforms._CosTime){const c=this.uniforms._CosTime.value;c.x=Math.cos(s.sceneLighting.timeVec4.x/8),c.y=Math.cos(s.sceneLighting.timeVec4.x/4),c.z=Math.cos(s.sceneLighting.timeVec4.x/2),c.w=Math.cos(s.sceneLighting.timeVec4.x)}if(this.uniforms.unity_DeltaTime){const c=this.uniforms.unity_DeltaTime.value;c.x=s.time.deltaTime,c.y=1/s.time.deltaTime,c.z=s.time.smoothedDeltaTime,c.w=1/s.time.smoothedDeltaTime}const n=s.mainLight;if(n){const c=te(n.gameObject,He._mainLightPosition);this.uniforms._MainLightPosition={value:c.normalize()},He._mainLightColor.set(n.color.r,n.color.g,n.color.b,0),this.uniforms._MainLightColor={value:He._mainLightColor};const h=n.intensity;He._lightData.z=h,this.uniforms.unity_LightData={value:He._lightData}}if(e&&(He.viewProjection&&this.uniforms[this._viewProjectionName]&&(this.uniforms[this._viewProjectionName].value=He._viewProjectionValues),He.viewMatrix&&this.uniforms[this._viewMatrixName]&&(this.uniforms[this._viewMatrixName].value=He._viewMatrixValues),this.uniforms[He._worldSpaceCameraPosName]&&(this.uniforms[He._worldSpaceCameraPosName]={value:He._worldSpaceCameraPos}),s.mainCameraComponent)){if(this.uniforms._ProjectionParams){const c=this.uniforms._ProjectionParams.value;c.x=1,c.y=s.mainCameraComponent.nearClipPlane,c.z=s.mainCameraComponent.farClipPlane,c.w=1/c.z,this.uniforms._ProjectionParams.value=c}if(this.uniforms._ZBufferParams){const c=this.uniforms._ZBufferParams.value,h=s.mainCameraComponent;c.x=1-h.farClipPlane/h.nearClipPlane,c.y=h.farClipPlane/h.nearClipPlane,c.z=c.x/h.farClipPlane,c.w=c.y/h.farClipPlane,this.uniforms._ZBufferParams.value=c}if(this.uniforms._ScreenParams){const c=this.uniforms._ScreenParams.value;c.x=s.domWidth,c.y=s.domHeight,c.z=1+1/c.x,c.w=1+1/c.y,this.uniforms._ScreenParams.value=c}if(this.uniforms._ScaledScreenParams){const c=this.uniforms._ScaledScreenParams.value;c.x=s.domWidth,c.y=s.domHeight,c.z=1+1/c.x,c.w=1+1/c.y,this.uniforms._ScaledScreenParams.value=c}}const r=this.depthTextureUniform;r&&(r.value=s.depthTexture);const l=this.opaqueTextureUniform;if(l&&(l.value=s.opaqueColorTexture),t){const c=this._rendererData;c.updateFrom(t),this.uniforms[this._worldToObjectName].value=c.worldToObject,this.uniforms[this._objToWorldName].value=c.objectToWorld}this.uniformsNeedUpdate=!0}};a(cn,"viewProjection",new se),a(cn,"_viewProjectionValues",[]),a(cn,"viewMatrix",new se),a(cn,"_viewMatrixValues",[]),a(cn,"_worldSpaceCameraPosName","_WorldSpaceCameraPos"),a(cn,"_worldSpaceCameraPos",new x),a(cn,"_mainLightColor",new ye),a(cn,"_mainLightPosition",new x),a(cn,"_lightData",new ye);let t1=cn;class CE{constructor(e,t){a(this,"parser"),a(this,"identifier"),this.parser=e,this.identifier=t}get name(){return il}loadMaterial(e){const t=this.parser.json.materials[e];if(!t)return ln&&console.log(e,this.parser.json.materials),null;if(!t.extensions||!t.extensions[il])return ln&&console.log(`Material ${e} does not use NEEDLE_techniques_webgl`),null;ln&&console.log(`Material ${e} uses NEEDLE_techniques_webgl`,t);const s=t.extensions[il].technique;if(s<0)return console.debug(`Material ${e} does not have a valid technique index`),null;const n=this.parser.json.extensions[il];if(!n)return ln?console.error("Missing shader data",this.parser.json.extensions):console.debug("Missing custom shader data in parser.json.extensions"),null;ln&&console.log(n);const r=n.techniques[s];return r?new Promise(async(l,c)=>{var h,d,u;const p=await fR(n,r.program),g=p?.fragmentShader,f=p?.vertexShader;if(!g||!f)return c();ln&&console.log("loadMaterial",t,p);const y={},b=r.uniforms;(f.includes("_Time")||g.includes("_Time"))&&(y._Time={value:new ye(0,0,0,0)}),(f.includes("_SinTime")||g.includes("_SinTime"))&&(y._SinTime={value:new ye(0,0,0,0)}),(f.includes("_CosTime")||g.includes("_CosTime"))&&(y._CosTime={value:new ye(0,0,0,0)}),(f.includes("unity_DeltaTime")||g.includes("unity_DeltaTime"))&&(y.unity_DeltaTime={value:new ye(0,0,0,0)});for(const w in b){const S=w;switch(S){case"_TimeParameters":const k=new ye;y[S]={value:k};break;case"hlslcc_mtx4x4unity_MatrixV":case"hlslcc_mtx4x4unity_MatrixVP":y[S]={value:[]};break;case"_MainLightPosition":case"_MainLightColor":case"_WorldSpaceCameraPos":y[S]={value:[0,0,0,1]};break;case"unity_OrthoParams":break;case"unity_SpecCube0":y[S]={value:null};break;default:case"_ScreenParams":case"_ZBufferParams":case"_ProjectionParams":y[S]={value:[0,0,0,0]};break;case"_CameraOpaqueTexture":case"_CameraDepthTexture":y[S]={value:null};break}}let v=!1;if(t.extensions&&t.extensions[il]){const w=t.extensions[il];if(w.technique===s){ln&&console.log(t.name,"Material Properties",w);for(const S in w.values){const k=w.values[S];if(typeof k=="string"){if(k.startsWith("/textures/")){const M=k.substring(10),T=Number.parseInt(M);if(T>=0){const L=await this.parser.getDependency("texture",T);L instanceof De&&(L.colorSpace=On,L.needsUpdate=!0),y[S]={value:L};continue}}switch(S){case"alphaMode":k==="BLEND"&&(v=!0);continue}}if(Array.isArray(k)&&k.length===4){y[S]={value:new ye(k[0],k[1],k[2],k[3])};continue}y[S]={value:k}}}}const _=new t1(this.identifier,{name:t.name??"",uniforms:y,vertexShader:f,fragmentShader:g,lights:!1});switch(_.glslVersion=gP,_.vertexShader=_.vertexShader.replace("#version 300 es",""),_.fragmentShader=_.fragmentShader.replace("#version 300 es",""),(h=y._Cull)==null?void 0:h.value){case 0:_.side=Ci;break;case 1:_.side=bd;break;case 2:_.side=go;break;default:_.side=go;break}switch((d=y._ZTest)==null?void 0:d.value){case 3:_.depthTest=!0,_.depthFunc=xP;break;case 6:_.depthTest=!0,_.depthFunc=wP;break;case 2:_.depthTest=!0,_.depthFunc=_P;break;case 4:_.depthTest=!0,_.depthFunc=bP;break;case 5:_.depthTest=!0,_.depthFunc=vP;break;case 7:_.depthTest=!0,_.depthFunc=yP;break;case 8:_.depthTest=!1,_.depthFunc=fP;break}_.transparent=v,v&&(_.depthWrite=!1),mR(y),_.onUpdateUniforms();for(const w in b){const S=w,k=b[w].type;if(((u=y[S])==null?void 0:u.value)===void 0)switch(k){case e1.SAMPLER_2D:y[S]={value:uR},console.warn("Missing/unassigned texture, fallback to white: "+S);break;default:S==="unity_OrthoParams"||console.warn("TODO: EXPECTED UNIFORM / fallback NOT SET: "+S,b[w]);break}}ln&&console.log(_.uuid,y),i1(_),l(_)}):null}}function i1(o){if(o.uniforms){ln&&console.log("Uniforms:",o.uniforms);for(const t in o.uniforms)switch(e(t,t),t){case"_Color":e("color",t);break}}function e(t,s){Object.getOwnPropertyDescriptor(o,t)||Object.defineProperty(o,t,{get:()=>o.uniforms[s].value,set:n=>{o.uniforms[s].value=n,o.needsUpdate=!0}})}}const PE=C("debugextensions");let Xu;const OE=import("./three-examples-DaDLBuy6.min.js").then(o=>o.GLTFLoaderAnimationPointer).then(async o=>(Xu=o.GLTFAnimationPointerExtension,Xu)).catch(o=>{console.warn("Failed to import GLTFLoaderAnimationPointer. Please use @needle-tools/three for full KHR_animation support",o)}),Vr=new Array;function kE(o){Vr.includes(o)||Vr.push(o)}function ME(o){const e=Vr.indexOf(o);e>=0&&Vr.splice(e,1)}function u0(o){if(o instanceof Rn){const e=new Qx;return o.register(t=>(e.parser=t,e)),e}return null}class RE{resolvePath(e){return e.includes("/extensions/builtin_components/")?e.replace("/extensions/builtin_components/","/userData/components/"):e.includes("extensions/builtin_components/")?e.replace("extensions/builtin_components/","/userData/components/"):e}}async function Qu(o,e,t){const s=t.indexOf("?");s>=0&&(t=t.substring(0,s)),o.register(n=>new yE(n)),o.register(n=>new WM(n)),o.register(n=>new lR(n,e.lightmaps,t)),o.register(n=>new vE(n,t,e)),o.register(n=>new CE(n,t)),o.register(n=>new Jx(n,t)),o.register(n=>new Xe(n,t)),o.register(n=>new pE(n)),I_()&&o.register(n=>new T_(n)),await OE.catch(n=>{}),o.register(n=>{if(Xu){const r=new Xu(n);return r.setAnimationPointerResolver.bind(r)(new RE),r}else return(PE||F())&&console.error("Missing KHR_animation_pointer extension..."),{name:"KHR_animation_pointer_NOT_AVAILABLE"}});for(const n of Vr)n.onImport&&n.onImport(o,t,e)}function p0(o,e){for(const t of Vr)t.onExport&&t.onExport(o,e)}function s1(o,e,t){for(const s of Vr)s.onLoaded&&s.onLoaded(o,e,t)}class n1{constructor(e){this.writer=e,this.name="EXT_mesh_gpu_instancing"}writeNode(e,t){if(e.constructor.name!=="InstancedMesh")return;const s=this.writer,n=s.extensionsUsed,r={};t.extensions=t.extensions||{},t.extensions[this.name]=r;let l=new se;const c=new Array,h=new Array,d=new Array;for(let f=0;f<e.count;f++){e.getMatrixAt(f,l);let y=new x,b=new H,v=new x;l.decompose(y,b,v),c.push(y.x,y.y,y.z),h.push(b.x,b.y,b.z,b.w),d.push(v.x,v.y,v.z)}const u=new Float32Array(c),p=new Float32Array(h),g=new Float32Array(d);r.attributes={TRANSLATION:s.processAccessor(new bt(u,3)),ROTATION:s.processAccessor(new bt(p,4)),SCALE:s.processAccessor(new bt(g,3))},n[this.name]=!0}}var TE=Object.defineProperty,o1=(o,e,t,s)=>{for(var n=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=l(e,t,n)||n);return n&&TE(e,t,n),n};const Hc=C("debugreflectionprobe"),r1=C("noreflectionprobe"),m0=Symbol("reflectionProbeKey"),a1=Symbol("original material");var os;const g0=(os=class extends I{constructor(){var o;super(),a(this,"_texture"),a(this,"center"),a(this,"size"),a(this,"_boxHelper"),os._probes.has(this.context)||os._probes.set(this.context,[]),(o=os._probes.get(this.context))==null||o.push(this)}static isUsingReflectionProbe(o){var e;return!!(o[m0]||(e=o[a1])!=null&&e[m0])}static get(o,e,t,s){if(!o||o.isObject3D!==!0||r1)return null;const n=os._probes.get(e);if(n){for(const r of n)if(r.__didAwake||r.__internalAwake(),r.activeAndEnabled){if(s){if(r.gameObject===s)return r}else if(r.isInBox(o))return Hc&&console.log("Found reflection probe",o.name,r.name),r}}return Hc&&console.debug("Did not find reflection probe",o.name,t,o),null}set texture(o){if(o&&!(o instanceof De)){console.error("ReflectionProbe.texture must be a Texture",o);return}this._texture=o,o&&(o.mapping=kn,o.colorSpace=On,o.needsUpdate=!0)}get texture(){return this._texture}isInBox(o){var e;return(e=this._boxHelper)==null?void 0:e.isInBox(o)}awake(){this._boxHelper=this.gameObject.addComponent(Do),this._boxHelper.updateBox(!0),Hc&&this._boxHelper.showHelper(5592320,!0),this._texture&&(this._texture.mapping=kn,this._texture.colorSpace=On,this._texture.needsUpdate=!0)}start(){!this._texture&&F()&&(console.warn(`[ReflectionProbe] Missing texture. Please assign a custom cubemap texture. To use reflection probes assign them to your renderer's "anchor" property.`),be("ReflectionProbe configuration hint: See browser console for details"))}onDestroy(){const o=os._probes.get(this.context);if(o){const e=o.indexOf(this);e>=0&&o.splice(e,1)}}onSet(o){var e;if(r1||!this.enabled||((e=o.sharedMaterials)==null?void 0:e.length)<=0||!this.texture)return;let t=os._rendererMaterialsCache.get(o);t||(t=[],os._rendererMaterialsCache.set(o,t));for(let s=0;s<o.sharedMaterials.length;s++){const n=o.sharedMaterials[s];if(!n||n.envMap===void 0||n instanceof Me)continue;let r=t[s];const l=n===r?.copy,c=!r||r.material.uuid!==n.uuid||r.copy.version!==n.version;if(!l&&c){if(Hc){let u="";r?r.material!==n?u="reference changed; cached instance?: "+l:r.copy.version!==n.version&&(u="version changed"):u="not cached",console.warn("Cloning material",n.name,n.version,"Reason:",u,`
967
+ `,n.uuid,`
968
+ `,r?.copy.uuid,`
969
+ `,o.name)}const d=n.clone();d.version=n.version,r?(r.copy=d,r.material=n):(r={material:n,copy:d},t.push(r)),d[m0]=this,d[a1]=n,Hc&&console.log("Set reflection",o.name,o.guid)}r&&r.copy&&(r.copy.onBeforeCompile=n.onBeforeCompile);const h=r?.copy;h.envMap=this.texture,o.sharedMaterials[s]=h}}onUnset(o){const e=os._rendererMaterialsCache.get(o);if(e)for(let t=0;t<e.length;t++){const s=e[t];o.sharedMaterials[t]=s.material}}},a(os,"_probes",new Map),a(os,"_rendererMaterialsCache",new Map),os);o1([m(x)],g0.prototype,"center"),o1([m(x)],g0.prototype,"size");let $c=g0;const ui=C("debuginstancing"),Yu=class vC{constructor(){a(this,"objs",[])}setup(e,t,s,n,r,l=0){e.applySettings(t);const c=this.tryCreateOrAddInstance(t,s,r);if(c){n===null&&(n=[]),n.push(c),Xe.assignTextureLOD(c.renderer.material,0);for(let h=0;h<e.sharedMeshes.length;h++){const d=e.sharedMeshes[h],u=d.geometry;Xe.assignMeshLOD(d,0).then(p=>{p&&e.activeAndEnabled&&u!=p&&c.setGeometry(p)})}}else if(l<=0&&t.type!=="Mesh"){const h=l+1;for(const d of t.children)n=this.setup(e,d,s,n,r,h)}return l===0&&r.useMatrixWorldAutoUpdate&&n&&n.length>=0&&this.autoUpdateInstanceMatrix(t),n}tryCreateOrAddInstance(e,t,s){if(e.type==="Mesh"){const n=s.foundMeshes;if(s.foundMeshes+=1,!s.rend.enableInstancing)return null;if(s.rend.enableInstancing!==!0){if(n>=s.rend.enableInstancing.length)return ui&&console.error("Something is wrong with instance setup",e,s.rend.enableInstancing,n),null;if(!s.rend.enableInstancing[n])return null}const r=e,l=r.material;for(const u of this.objs)if(!!u.canAdd(r.geometry,l))return u.addInstance(r);let c=vC.getStartInstanceCount(e);(!c||c<0)&&(c=4);let h=e.name;h!=null&&h.length||(h=rb());const d=new c1(h,r.geometry,l,c,t);return this.objs.push(d),d.addInstance(r)}return null}autoUpdateInstanceMatrix(e){const t=e.matrixWorld.multiplyMatrices.bind(e.matrixWorld),s=e.matrixWorld.clone(),n=(r,l)=>{const c=t(r,l);return(e[dc]||s.equals(c)===!1)&&(s.copy(c),e[dc]=!0),c};e.matrixWorld.multiplyMatrices=n}};a(Yu,"instance",new Yu),a(Yu,"getStartInstanceCount",o=>4);let Ku=Yu;const l1=class ym{constructor(e,t){a(this,"object"),a(this,"renderer"),a(this,"__instanceIndex",-1),a(this,"__reservedVertexRange",0),a(this,"__reservedIndexRange",0),a(this,"__geometryIndex",-1),a(this,"meshInformation"),this.__instanceIndex=-1,this.object=e,this.renderer=t,e[U_]=t,this.meshInformation=Hr(e.geometry),ym.all.push(this)}get name(){return this.object.name}get isActive(){return this.__instanceIndex>=0}get vertexCount(){return this.object.geometry.attributes.position.count}get maxVertexCount(){return Math.max(this.meshInformation.vertexCount,this.vertexCount)}get reservedVertexCount(){return this.__reservedVertexRange}get indexCount(){return this.object.geometry.index?this.object.geometry.index.count:0}get maxIndexCount(){return Math.max(this.meshInformation.indexCount,this.indexCount)}get reservedIndexCount(){return this.__reservedIndexRange}updateMeshInformation(){const e=Hr(this.object.geometry),t=this.meshInformation.vertexCount,s=this.meshInformation.indexCount;return Object.assign(this.meshInformation,e),t!==this.meshInformation.vertexCount||s!==this.meshInformation.indexCount}updateInstanceMatrix(e=!1,t=!0){this.__instanceIndex<0||(t&&this.object.updateWorldMatrix(!0,e),this.renderer.updateInstance(this.object.matrixWorld,this.__instanceIndex))}setMatrix(e){this.__instanceIndex<0||this.renderer.updateInstance(e,this.__instanceIndex)}setGeometry(e){if(this.__geometryIndex<0)return!1;const t=this;if(this.vertexCount>this.__reservedVertexRange)return s(`Instancing: Can not update geometry (${this.name}), reserved vertex range is too small: ${this.__reservedVertexRange.toLocaleString()} < ${this.vertexCount.toLocaleString()} vertices for ${this.name}`);if(this.indexCount>this.__reservedIndexRange)return s(`Instancing: Can not update geometry (${this.name}), reserved index range is too small: ${this.__reservedIndexRange.toLocaleString()} < ${this.indexCount.toLocaleString()} indices for ${this.name}`);return this.renderer.updateGeometry(e,this.__geometryIndex);function s(n){return t.updateMeshInformation()&&(t.renderer.remove(t,!0),t.renderer.add(t))?!0:((F()||ui)&&console.error(n),!1)}}add(){this.__instanceIndex>=0||(this.renderer.add(this),P.markAsInstancedRendered(this.object,!0))}remove(e){if(!(this.__instanceIndex<0)&&(this.renderer.remove(this,e),P.markAsInstancedRendered(this.object,!1),e)){const t=ym.all.indexOf(this);t>=0&&ym.all.splice(t,1)}}};a(l1,"all",[]);let f0=l1;class c1{constructor(e,t,s,n,r){a(this,"allowResize",!0),a(this,"name",""),a(this,"geometry"),a(this,"material"),a(this,"_context"),a(this,"_batchedMesh"),a(this,"_handles",[]),a(this,"_geometryIds",new Map),a(this,"_maxInstanceCount"),a(this,"_currentInstanceCount",0),a(this,"_currentVertexCount",0),a(this,"_currentIndexCount",0),a(this,"_maxVertexCount"),a(this,"_maxIndexCount"),a(this,"_needUpdateBounds",!1),a(this,"_debugMaterial",null),a(this,"onBeforeRender",()=>{this._batchedMesh.layers.enableAll(),this._needUpdateBounds&&this._batchedMesh[uc]===!0&&(ui==="verbose"&&console.log("Update instancing bounds",this.name,this._batchedMesh.matrixWorldNeedsUpdate),this.updateBounds())}),a(this,"onAfterRender",()=>{this._batchedMesh.layers.disableAll()}),this.name=e,this.geometry=t,this.material=s,this._context=r,this._maxInstanceCount=Math.max(2,n),ui&&(this._debugMaterial=h1());const l=this.tryEstimateVertexCountSize(this._maxInstanceCount,[t],n);this._maxVertexCount=l.vertexCount,this._maxIndexCount=l.indexCount,this._batchedMesh=new Iv(this._maxInstanceCount,this._maxVertexCount,this._maxIndexCount,this._debugMaterial??this.material),this._batchedMesh[uc]=!0,this._batchedMesh.visible=!0,this._context.scene.add(this._batchedMesh),s instanceof Av&&(s.defines.USE_INSTANCING=!0,s.needsUpdate=!0),r.pre_render_callbacks.push(this.onBeforeRender),r.post_render_callbacks.push(this.onAfterRender),ui&&console.log(`Instanced renderer created with ${this._maxInstanceCount} instances, ${this._maxVertexCount} max vertices and ${this._maxIndexCount} max indices for "${e}"`)}get batchedMesh(){return this._batchedMesh}get visible(){return this._batchedMesh.visible}set visible(e){this._batchedMesh.visible=e}get castShadow(){return this._batchedMesh.castShadow}set castShadow(e){this._batchedMesh.castShadow=e}set receiveShadow(e){this._batchedMesh.receiveShadow=e}get count(){return this._currentInstanceCount}updateBounds(e=!0,t=!0){if(this._needUpdateBounds=!1,e&&this._batchedMesh.computeBoundingBox(),t&&this._batchedMesh.computeBoundingSphere(),ui&&this._batchedMesh.boundingSphere){const s=this._batchedMesh.boundingSphere;G.DrawWireSphere(s.center,s.radius,65280)}}canAdd(e,t){return this._maxVertexCount>1e7||t!==this.material||!this.validateGeometry(e)?!1:!!(!this.mustGrow(e)||this.allowResize)}dispose(){ui&&console.warn("Dispose instanced renderer",this.name),this._context.scene.remove(this._batchedMesh),this._batchedMesh.dispose(),this._batchedMesh=null,this._handles=[]}addInstance(e){const t=new f0(e,this);e.castShadow===!0&&this._batchedMesh.castShadow===!1&&(this._batchedMesh.castShadow=!0),e.receiveShadow===!0&&this._batchedMesh.receiveShadow===!1&&(this._batchedMesh.receiveShadow=!0);try{this.add(t)}catch(s){if(console.error(`Failed adding mesh to instancing (object name: "${e.name}", instances: ${this._currentInstanceCount.toLocaleString()}/${this._maxInstanceCount.toLocaleString()}, vertices: ${this._currentVertexCount.toLocaleString()}/${this._maxVertexCount.toLocaleString()}, indices: ${this._currentIndexCount.toLocaleString()}/${this._maxIndexCount.toLocaleString()})
970
+ `,s),F()){ec("Failed instancing mesh. See the browser console for details.");debugger}return null}return t}add(e){const t=e.object.geometry;if(!t||!t.attributes)return console.error("Cannot add object to instancing without geometry",e.name),!1;if(this.mustGrow(t))if(this.allowResize)this.grow(t);else return console.error("Cannot add instance, max count reached",this.name,this.count,this._maxInstanceCount),!1;return e.object.updateWorldMatrix(!0,!0),this.addGeometry(e),this._handles[e.__instanceIndex]=e,this._currentInstanceCount+=1,this.markNeedsUpdate(),this._currentInstanceCount>0&&(this._batchedMesh.visible=!0),!0}remove(e,t){e&&(e.__instanceIndex<0||this._handles[e.__instanceIndex]!=e||this._currentInstanceCount<=0||(this.removeGeometry(e,t),this._handles[e.__instanceIndex]=null,e.__instanceIndex=-1,this._currentInstanceCount>0&&(this._currentInstanceCount-=1),this._currentInstanceCount<=0&&(this._batchedMesh.visible=!1),this.markNeedsUpdate()))}updateInstance(e,t){this._batchedMesh.setMatrixAt(t,e),this.markNeedsUpdate()}updateGeometry(e,t){return this.validateGeometry(e)?(this.mustGrow()&&this.grow(e),ui&&console.debug("[Instancing] UPDATE GEOMETRY at "+t,this._batchedMesh._geometryCount,e.name,Hr(e),e.attributes.position.count,e.index?e.index.count:0),this._batchedMesh.setGeometryAt(t,e),this._geometryIds.set(e,t),this.markNeedsUpdate(),!0):!1}validateGeometry(e){const t=this.geometry;for(const s in t.attributes)if(s!=="batchId"&&!e.hasAttribute(s))return F()&&console.warn(`BatchedMesh: Added geometry missing "${s}". All geometries must have consistent attributes.`),!1;return!0}markNeedsUpdate(){ui==="verbose"&&console.warn("Marking instanced mesh dirty",this.name),this._needUpdateBounds=!0}mustGrow(e){if(this.count>=this._maxInstanceCount)return!0;if(!e||!e.attributes)return!1;const t=Hr(e),s=t.vertexCount,n=t.indexCount;return this._currentVertexCount+s>this._maxVertexCount||this._currentIndexCount+n>this._maxIndexCount}grow(e){var t,s;const n=Math.ceil(this._maxInstanceCount*2),r=this.tryEstimateVertexCountSize(n,[e]),l=Math.max(this._maxVertexCount,r.vertexCount),c=Math.max(this._maxIndexCount,r.indexCount,Math.ceil(this._maxVertexCount*2));if(ui){const u=Hr(e);console.warn(`[Instancing] Growing Buffer
971
+ Mesh: "${this.name}${(t=e.name)!=null&&t.length?"/"+e.name:""}"
972
+ ${u.vertexCount} vertices, ${u.indexCount} indices
973
+ Max count ${this._maxInstanceCount} \u2192 ${n}
974
+ Max vertex count ${this._maxVertexCount} -> ${l}
975
+ Max index count ${this._maxIndexCount} -> ${c}`),this._debugMaterial=h1()}else F()&&console.debug(`[Instancing] Growing Buffer
976
+ Mesh: "${this.name}${(s=e.name)!=null&&s.length?"/"+e.name:""}"
977
+ Max count ${this._maxInstanceCount} \u2192 ${n}
978
+ Max vertex count ${this._maxVertexCount} -> ${l}
979
+ Max index count ${this._maxIndexCount} -> ${c}`);this._maxVertexCount=l,this._maxIndexCount=c;const h=new Iv(n,this._maxVertexCount,this._maxIndexCount,this._debugMaterial??this.material);h.layers=this._batchedMesh.layers,h.castShadow=this._batchedMesh.castShadow,h.receiveShadow=this._batchedMesh.receiveShadow,h.visible=this._batchedMesh.visible,h[uc]=this._batchedMesh[uc],h.matrixAutoUpdate=this._batchedMesh.matrixAutoUpdate,h.matrixWorldNeedsUpdate=this._batchedMesh.matrixWorldNeedsUpdate,h.matrixAutoUpdate=this._batchedMesh.matrixAutoUpdate,h.matrixWorld.copy(this._batchedMesh.matrixWorld),h.matrix.copy(this._batchedMesh.matrix),this._batchedMesh.dispose(),this._batchedMesh.removeFromParent(),this._geometryIds.clear(),this._batchedMesh=h,this._maxInstanceCount=n;const d=[...this._handles];this._handles=[];for(const u of d)u&&u.__instanceIndex>=0&&(this.addGeometry(u),this._handles[u.__instanceIndex]=u);this._context.scene.add(h)}tryEstimateVertexCountSize(e,t,s=1){const n=new Map;for(const d of this._handles)if(d&&d.__instanceIndex>=0&&d.object.geometry)if(n.has(d.object.geometry)){const u=n.get(d.object.geometry);u.count+=1}else{const u={count:1,...Hr(d.object.geometry)};n.set(d.object.geometry,u)}let r=0,l=0;for(const[d,u]of n)r+=u.vertexCount*u.count,l+=u.indexCount*u.count;let c=Math.ceil(r/Math.max(1,this._currentInstanceCount))*e,h=Math.ceil(l/Math.max(1,this._currentInstanceCount))*e*2;if(t)for(const d of t){const u=Hr(d);u!=null&&(c+=u.vertexCount*s,h+=u.indexCount*s)}return{vertexCount:c,indexCount:h}}addGeometry(e){const t=e.object.geometry;if(!t)return;let s=this._geometryIds.get(t);s==null?(ui&&console.debug(`[Instancing] > ADD NEW GEOMETRY "${e.name} (${t.name}; ${t.uuid})"
980
+ ${this._currentInstanceCount} instances, ${e.maxVertexCount} max vertices, ${e.maxIndexCount} max indices`),s=this._batchedMesh.addGeometry(t,e.maxVertexCount,e.maxIndexCount),this._geometryIds.set(t,s)):ui==="verbose"&&console.log(`[Instancing] > ADD INSTANCE "${e.name}"
981
+ GEOMETRY_ID=${s}
982
+ ${this._currentInstanceCount} instances`),this._currentVertexCount+=e.maxVertexCount,this._currentIndexCount+=e.maxIndexCount;const n=this._batchedMesh.addInstance(s);e.__geometryIndex=s,e.__instanceIndex=n,e.__reservedVertexRange=e.maxVertexCount,e.__reservedIndexRange=e.maxIndexCount,this._batchedMesh.setMatrixAt(n,e.object.matrixWorld),ui&&console.debug(`[Instancing] > ADDED INSTANCE "${e.name}"
983
+ GEOMETRY_ID=${s}
984
+ ${this._currentInstanceCount} instances
985
+ Index: ${e.__instanceIndex}`)}removeGeometry(e,t){if(e.__instanceIndex<0){console.warn("Cannot remove geometry, instance index is invalid",e.name);return}ui&&console.debug(`[Instancing] < REMOVE INSTANCE "${e.name}" at [${e.__instanceIndex}]
986
+ GEOMETRY_ID=${e.__geometryIndex}
987
+ ${this._currentInstanceCount} instances
988
+ Index: ${e.__instanceIndex}`),this._batchedMesh.deleteInstance(e.__instanceIndex)}}a(c1,"nullMatrix",new se);function Hr(o){var e,t;if(!o)return F()&&console.error("Cannot get mesh information from null geometry"),{vertexCount:0,indexCount:0};let s=((t=(e=o.attributes)==null?void 0:e.position)==null?void 0:t.count)||0,n=o.index?o.index.count:0;const r=Xe.getMeshLODInformation(o);if(r){const l=r.lods[0];let c=l.vertexCount,h=l.indexCount;const d=Math.min(200,Math.ceil(c*.05));c+=d,h+=20,s=Math.max(s,c),n=Math.max(n,h)}return s=Math.ceil(s),n=Math.ceil(n),{vertexCount:s,indexCount:n}}function h1(){const o=new vt({color:new ae(Math.random(),Math.random(),Math.random())});return o.emissive=o.color,o.emissiveIntensity=.3,C("wireframe")&&(o.wireframe=!0),o}const sl=C("debuglightmaps");class Zu{constructor(e,t){a(this,"lightmapIndex",-1),a(this,"lightmapScaleOffset",new ye(1,1,0,0)),a(this,"context"),a(this,"gameObject"),a(this,"lightmapTexture",null),a(this,"lightmapScaleOffsetUniform",{value:new ye(1,1,0,0)}),a(this,"lightmapUniform",{value:null}),a(this,"onBeforeCompile",(s,n)=>{sl&&console.log(`Lightmaps, before compile
989
+ `,s),this.lightmapScaleOffsetUniform.value=this.lightmapScaleOffset,this.lightmapUniform.value=this.lightmapTexture,s.uniforms.lightmapScaleOffset=this.lightmapScaleOffsetUniform}),this.gameObject=e,this.context=t}get lightmap(){return this.lightmapTexture}set lightmap(e){e!==this.lightmapTexture&&(this.lightmapTexture=e,this.applyLightmap(),this.lightmapTexture&&Xe.assignTextureLOD(this.lightmapTexture,0).then(t=>{t!=null&&t.isTexture&&(this.lightmapTexture=t)}))}init(e,t,s){console.assert(this.gameObject!==void 0&&this.gameObject!==null,"Missing gameobject",this),this.lightmapIndex=e,!(this.lightmapIndex<0)&&(this.lightmapScaleOffset=t,this.lightmapTexture=s,Xe.assignTextureLOD(s,0).then(n=>{n!=null&&n.isTexture&&(this.lightmapTexture=n)}),sl=="show"?(console.log("Lightmap:",this.gameObject.name,e,`
990
+ ScaleOffset:`,t,`
991
+ Texture:`,s),this.setLightmapDebugMaterial()):sl&&console.log("Use debuglightmaps=show to render lightmaps only in the scene."),this.applyLightmap())}updateLightmapUniforms(e){const t=e.uniforms;t&&t.lightmap&&(this.lightmapScaleOffsetUniform.value=this.lightmapScaleOffset,t.lightmapScaleOffset=this.lightmapScaleOffsetUniform)}applyLightmap(){if(this.gameObject.type==="Object3D"){sl&&console.warn("Can not add lightmap. Is this object missing a renderer?",this.gameObject.name);return}if(this.gameObject.type==="Group"){this.gameObject["Needle:Multimaterial-LightmapWarning"]===void 0&&(this.gameObject["Needle:Multimaterial-LightmapWarning"]=!0,console.warn("Lightmap on multimaterial object is not supported yet... please open a feature request on https://github.com/needle-tools/needle-engine-support if your project requires it"));return}console.assert(this.gameObject.type==="Mesh","Lightmap only works on meshes",this);const e=this.gameObject;if(e.geometry.getAttribute("uv1")||e.geometry.setAttribute("uv1",e.geometry.getAttribute("uv")),Array.isArray(this.gameObject.material)){const t=this.gameObject.material;for(let s=0;s<t.length;s++)t[s]=this.ensureLightmapMaterial(t[s])}else this.gameObject.material=this.ensureLightmapMaterial(this.gameObject.material);if(this.lightmapIndex>=0&&this.lightmapTexture){this.lightmapTexture.channel=1;const t=this.gameObject.material;if(Array.isArray(t))for(const s of t)this.assignLightmapTexture(s);else t&&this.assignLightmapTexture(t)}}ensureLightmapMaterial(e){return e.userData||(e.userData={}),e["NEEDLE:lightmap-material-version"]!=e.version&&e["NEEDLE:lightmap-material-version"]==null&&(sl&&console.warn("Cloning material for lightmap "+e.name),e=e.clone(),e.onBeforeCompile=this.onBeforeCompile),e}assignLightmapTexture(e){!e||e instanceof Am&&e.transmission>0||!(e.lightMap!==this.lightmapTexture||e["NEEDLE:lightmap-material-version"]!==e.version)||(sl&&console.log("Assigning lightmap",e.name,e.version),e.lightMap=this.lightmapTexture,e["NEEDLE:lightmap-material-version"]=e.version)}setLightmapDebugMaterial(){this.gameObject.material=new Ws({vertexShader:`
992
+ varying vec2 vUv1;
993
+ void main()
994
+ {
995
+ vUv1 = uv1;
996
+ gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
997
+ }
998
+ `,fragmentShader:`
999
+ uniform sampler2D lightMap;
1000
+ uniform float lightMapIntensity;
1001
+ uniform vec4 lightmapScaleOffset;
1002
+ varying vec2 vUv1;
1003
+
1004
+ // took from threejs 05fc79cd52b79e8c3e8dec1e7dca72c5c39983a4
1005
+ vec4 conv_sRGBToLinear( in vec4 value ) {
1006
+ return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a );
1007
+ }
1008
+
1009
+ void main() {
1010
+ vec2 lUv = vUv1.xy * lightmapScaleOffset.xy + vec2(lightmapScaleOffset.z, (1. - (lightmapScaleOffset.y + lightmapScaleOffset.w)));
1011
+
1012
+ vec4 lightMapTexel = texture2D( lightMap, lUv);
1013
+ gl_FragColor = lightMapTexel;
1014
+ gl_FragColor.a = 1.;
1015
+ }
1016
+ `,defines:{USE_LIGHTMAP:""}})}}var EE=Object.defineProperty,Xn=(o,e,t,s)=>{for(var n=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=l(e,t,n)||n);return n&&EE(e,t,n),n};const Gc=C("debugrenderer"),d1=C("debugskinnedmesh"),u1=C("noinstancing"),AE=C("wireframe");class p1{constructor(){a(this,"path",null),a(this,"asset",null),a(this,"default")}}class IE{constructor(e,t){a(this,"_renderer"),a(this,"_targets",[]),a(this,"_indexMapMaxIndex"),a(this,"_indexMap"),a(this,"_changed",!1),this._renderer=e;const s=this.setMaterial.bind(this),n=this.getMaterial.bind(this),r=e.gameObject;if(this._targets=[],r)switch(r.type){case"Group":this._targets=[...r.children];break;case"SkinnedMesh":case"Mesh":this._targets.push(r);break}let l=!1,c,h=0;for(let d=0;d<this._targets.length;d++){const u=this._targets[d];if(!u)continue;const p=u.material;if(p){p.shadowSide=p.side;for(let g=0;g<t.length;g++){const f=t[g];if(!f){l=!0;continue}if(p.name===f.name){c===void 0&&(c=new Map),c.set(g,d),h=Math.max(h,g);break}}}}if(l){this._indexMapMaxIndex=h,this._indexMap=c;const d=`Renderer ${e.name} was initialized with missing materials - this may lead to unexpected behaviour when trying to access sharedMaterials by index.`;console.warn(d),qt()&&be("Found renderer with missing materials: please check the console for details.")}return new Proxy(this,{get(d,u){if(typeof u=="string"){const p=parseInt(u);if(!isNaN(p))return n(p)}return d[u]},set(d,u,p){return typeof u=="string"&&s(p,Number.parseInt(u)),Reflect.set(d,u,p)?(p instanceof Pe&&(d.changed=!0),!0):!1}})}get changed(){return this._changed}set changed(e){e===!0&&Gc&&console.warn("SharedMaterials have changed: "+this._renderer.name,this),this._changed=e}is(e){return this._renderer===e}get length(){return this._indexMapMaxIndex!==void 0?this._indexMapMaxIndex+1:this._targets.length}*[Symbol.iterator](){for(let e=0;e<this.length;e++)yield this.getMaterial(e)}resolveIndex(e){const t=this._indexMap;return t&&t.has(e)?t.get(e):e}setMaterial(e,t){if(t=this.resolveIndex(t),t<0||t>=this._targets.length)return;const s=this._targets[t];!s||s.material===void 0||(s.material=e,this.changed=!0)}getMaterial(e){if(e=this.resolveIndex(e),e<0)return null;const t=this._targets;if(e>=t.length)return null;const s=t[e];return s?s.material:null}}const hn=class vm extends I{constructor(){super(...arguments),a(this,"receiveShadows",!1),a(this,"shadowCastingMode",0),a(this,"lightmapIndex",-1),a(this,"lightmapScaleOffset",new ye(1,1,0,0)),a(this,"enableInstancing"),a(this,"renderOrder"),a(this,"allowOcclusionWhenDynamic",!0),a(this,"probeAnchor"),a(this,"reflectionProbeUsage",0),a(this,"_lightmaps"),a(this,"_sharedMeshes",[]),a(this,"_sharedMaterials"),a(this,"_originalMaterials"),a(this,"_probeAnchorLastFrame"),a(this,"_lightmapTextureOverride"),a(this,"allowProgressiveLoading",!0),a(this,"_firstFrame",-1),a(this,"_isInstancingEnabled",!1),a(this,"_handles"),a(this,"_handlesTempArray",[]),a(this,"onBeforeRenderThree",(e,t,s,n,r,l)=>{var c;if(r.envMapIntensity!==void 0){const h=this.hasLightmap?Math.PI:1,d=((c=this.context.mainCameraComponent)==null?void 0:c.environmentIntensity)??1;r.envMapIntensity=Math.max(0,d*this.context.sceneLighting.environmentIntensity/h)}if(this._lightmaps)for(const h of this._lightmaps)h.updateLightmapUniforms(r),h.applyLightmap()}),a(this,"_reflectionProbe",null)}static setInstanced(e,t){const s=fc(e,vm);return s.setInstancingEnabled(t),s}static isInstanced(e){const t=Or(e,vm);return t?t.isInstancingActive:ds.isUsingInstancing(e)}static setVisible(e,t){Bn(e,t)}get sharedMesh(){if(this.gameObject.type==="Mesh")return this.gameObject;if(this.gameObject.type==="SkinnesMesh")return this.gameObject;if(this.gameObject.type==="Group")return this.gameObject.children[0]}get sharedMeshes(){if(this.destroyed||!this.gameObject)return this._sharedMeshes;if(this._sharedMeshes.length=0,this.gameObject.type==="Group")for(const e of this.gameObject.children)(e.type==="Mesh"||e.type==="SkinnedMesh")&&this._sharedMeshes.push(e);else(this.gameObject.type==="Mesh"||this.gameObject.type==="SkinnedMesh")&&this._sharedMeshes.push(this.gameObject);return this._sharedMeshes}get sharedMaterial(){return this.sharedMaterials[0]}set sharedMaterial(e){this.sharedMaterials[0]!==e&&(this.sharedMaterials[0]=e,this.applyLightmapping())}get material(){return this.sharedMaterials[0]}set material(e){this.sharedMaterial=e}set sharedMaterials(e){if(!this._originalMaterials)this._originalMaterials=e;else if(e){let t=!1;for(let s=0;s<this._sharedMaterials.length;s++){const n=s<e.length?e[s]:null;n&&n instanceof Pe?this.sharedMaterials[s]=n:t||(t=!0,console.warn("Can not assign null as material: "+this.name,n))}}}get sharedMaterials(){return(!this._sharedMaterials||!this._sharedMaterials.is(this))&&(this._originalMaterials||(this._originalMaterials=[]),this._sharedMaterials=new IE(this,this._originalMaterials)),this._sharedMaterials}static get shouldSuppressInstancing(){return u1}get lightmap(){var e;return(e=this._lightmaps)!=null&&e.length?this._lightmaps[0].lightmap:null}set lightmap(e){var t;if(this._lightmapTextureOverride=e,e===void 0&&(e=this.context.lightmaps.tryGetLightmap(this.sourceId,this.lightmapIndex)),(t=this._lightmaps)!=null&&t.length)for(const s of this._lightmaps)s.lightmap=e}get hasLightmap(){return this.lightmap!=null}registering(){this.enabled||this.setVisibility(!1)}awake(){if(this._firstFrame=this.context.time.frame,Gc&&console.log("Renderer ",this.name,this),this.clearInstancingState(),this.probeAnchor&&Gc&&this.probeAnchor.add(new Si(.2)),this._reflectionProbe=null,this.isMultiMaterialObject(this.gameObject)){for(const e of this.gameObject.children)this.context.addBeforeRenderListener(e,this.onBeforeRenderThree),e.layers.mask=this.gameObject.layers.mask;if(this.renderOrder!==void 0){let e=0;for(let t=0;t<this.gameObject.children.length;t++){const s=this.gameObject.children[t];if(!(!this.isMeshOrSkinnedMesh(s)||P.getComponent(s,vm))){if(this.renderOrder.length<=e){console.warn("Incorrect renderOrder element count",this,this.renderOrder.length+" but expected "+this.gameObject.children.length,"Index: "+e,"ChildElement:",s);continue}s.renderOrder=this.renderOrder[e],e+=1}}}}else this.isMeshOrSkinnedMesh(this.gameObject)?(this.context.addBeforeRenderListener(this.gameObject,this.onBeforeRenderThree),this.renderOrder!==void 0&&this.renderOrder.length>0&&(this.gameObject.renderOrder=this.renderOrder[0])):this.context.addBeforeRenderListener(this.gameObject,this.onBeforeRenderThree);if(this.applyLightmapping(),AE)for(let e=0;e<this.sharedMaterials.length;e++){const t=this.sharedMaterials[e];t&&(t.wireframe=!0)}}applyLightmapping(){var e;if(this.lightmapIndex>=0){const t=this.gameObject.type,s=this._lightmapTextureOverride!==void 0?this._lightmapTextureOverride:this.context.lightmaps.tryGetLightmap(this.sourceId,this.lightmapIndex);if(s){if(this._lightmaps||(this._lightmaps=[]),t==="Mesh"){const n=this.gameObject.material;if(n!=null&&n.isMeshBasicMaterial)n&&console.warn("Lightmapping is not supported on MeshBasicMaterial",n.name);else{if(this._lightmaps.length<=0){const r=new Zu(this.gameObject,this.context);this._lightmaps.push(r)}this._lightmaps[0].init(this.lightmapIndex,this.lightmapScaleOffset,s)}}else if(this.isMultiMaterialObject(this.gameObject)&&this.sharedMaterials.length>0)for(let n=0;n<this.gameObject.children.length;n++){const r=this.gameObject.children[n];if(!((e=r.material)!=null&&e.isMeshBasicMaterial)){let l;n>=this._lightmaps.length?(l=new Zu(r,this.context),this._lightmaps.push(l)):l=this._lightmaps[n],l.init(this.lightmapIndex,this.lightmapScaleOffset,s)}}}else Gc&&console.warn("Lightmap not found",this.sourceId,this.lightmapIndex)}}get isInstancingActive(){return this._handles!=null&&this._handles.length>0&&this._isInstancingEnabled}get instances(){if(!this._handles||this._handles.length<=0)return null;if(this._handlesTempArray.length=0,this._handles)for(const e of this._handles)this._handlesTempArray.push(e);return this._handlesTempArray}setInstancingEnabled(e){if(this._isInstancingEnabled===e)return e&&(this._handles===void 0||this._handles!=null&&this._handles.length>0);if(this._isInstancingEnabled=e,e){if(this.enableInstancing===void 0&&(this.enableInstancing=!0),this._handles===void 0){if(this._handles=Ku.instance.setup(this,this.gameObject,this.context,null,{rend:this,foundMeshes:0,useMatrixWorldAutoUpdate:this.useInstanceMatrixWorldAutoUpdate()}),this._handles)return P.markAsInstancedRendered(this.gameObject,!0),!0}else if(this._handles!==null){for(const t of this._handles)t.updateInstanceMatrix(!0),t.add();return P.markAsInstancedRendered(this.gameObject,!0),!0}}else{if(this._handles)for(const t of this._handles)t.remove(this.destroyed);return!0}return!1}clearInstancingState(){this._isInstancingEnabled=!1,this._handles=void 0}useInstanceMatrixWorldAutoUpdate(){return!0}start(){if(this.enableInstancing&&!u1&&(this.setInstancingEnabled(!0),ds.markDirty(this.gameObject)),this.gameObject.frustumCulled=this.allowOcclusionWhenDynamic,this.isMultiMaterialObject(this.gameObject))for(let e=0;e<this.gameObject.children.length;e++){const t=this.gameObject.children[e];t.frustumCulled=this.allowOcclusionWhenDynamic}}onEnable(){this.sharedMeshes,this.setVisibility(!0),this._isInstancingEnabled||this.enableInstancing==!0||Array.isArray(this.enableInstancing)&&this.enableInstancing.some(e=>e)?this.__internalDidAwakeAndStart&&this.setInstancingEnabled(!0):this.enabled&&this.applyStencil(),this.updateReflectionProbe()}onDisable(){this.setVisibility(!1),this._handles&&this._handles.length>0&&this.setInstancingEnabled(!1)}onDestroy(){if(this._handles=null,this.isMultiMaterialObject(this.gameObject))for(const e of this.gameObject.children)this.context.removeBeforeRenderListener(e,this.onBeforeRenderThree);else this.context.removeBeforeRenderListener(this.gameObject,this.onBeforeRenderThree)}onBeforeRender(){var e,t,s;if(this.gameObject){if(this._probeAnchorLastFrame!==this.probeAnchor&&((e=this._reflectionProbe)==null||e.onUnset(this),this.updateReflectionProbe()),Gc==this.name&&this.gameObject instanceof q){this.gameObject.geometry.computeBoundingSphere();const n=X(this.gameObject.geometry.boundingSphere.center).applyMatrix4(this.gameObject.matrixWorld);G.DrawWireSphere(n,this.gameObject.geometry.boundingSphere.radius,56831)}if(this.isMultiMaterialObject(this.gameObject)&&((t=this.gameObject.children)==null?void 0:t.length)>0)for(const n of this.gameObject.children)this.applySettings(n);else this.applySettings(this.gameObject);if(this.sharedMaterials.changed&&(this.sharedMaterials.changed=!1,this.applyLightmapping()),(s=this._handles)!=null&&s.length&&this.gameObject[dc]===!0){this.gameObject[dc]=!1;for(let n=this._handles.length-1;n>=0;n--)this._handles[n].updateInstanceMatrix();this.gameObject.matrixWorldNeedsUpdate=!1}if(this._handles&&this._handles.length<=0&&P.markAsInstancedRendered(this.gameObject,!1),this._isInstancingEnabled&&this._handles)for(let n=0;n<this._handles.length;n++){const r=this._handles[n];Bn(r.object,!1)}this.reflectionProbeUsage!==0&&this._reflectionProbe&&this._reflectionProbe.onSet(this);for(const n of this._sharedMaterials)n&&"envMap"in n&&"envMapIntensity"in n&&!$c.isUsingReflectionProbe(n)&&(n.envMap=this.context.scene.environment)}}onAfterRender(){if(this._isInstancingEnabled&&this._handles)for(let e=0;e<this._handles.length;e++){const t=this._handles[e];Bn(t.object,!0)}this.reflectionProbeUsage!==0&&this._reflectionProbe&&this._reflectionProbe.onUnset(this),this.static&&this.gameObject.matrixAutoUpdate&&(this.gameObject.matrixAutoUpdate=!1)}applyStencil(){Jx.applyStencil(this)}applySettings(e){e.receiveShadow=this.receiveShadows,this.shadowCastingMode==1?e.castShadow=!0:e.castShadow=!1}updateReflectionProbe(){this._reflectionProbe=null,this.reflectionProbeUsage!==0&&(this.startCoroutine(this._updateReflectionProbe(),Oe.LateUpdate),this._probeAnchorLastFrame=this.probeAnchor)}*_updateReflectionProbe(){const e=this.probeAnchor||this.gameObject,t=!!this.probeAnchor;this._reflectionProbe=$c.get(e,this.context,t,this.probeAnchor)}setVisibility(e){if(!this.isMultiMaterialObject(this.gameObject))Bn(this.gameObject,e);else for(const t of this.gameObject.children)this.isMeshOrSkinnedMesh(t)&&Bn(t,e)}isMultiMaterialObject(e){return e.type==="Group"}isMeshOrSkinnedMesh(e){return e.type==="Mesh"||e.type==="SkinnedMesh"}};Xn([m()],hn.prototype,"receiveShadows"),Xn([m()],hn.prototype,"shadowCastingMode"),Xn([m()],hn.prototype,"lightmapIndex"),Xn([m(ye)],hn.prototype,"lightmapScaleOffset"),Xn([m()],hn.prototype,"enableInstancing"),Xn([m()],hn.prototype,"renderOrder"),Xn([m()],hn.prototype,"allowOcclusionWhenDynamic"),Xn([m(E)],hn.prototype,"probeAnchor"),Xn([m()],hn.prototype,"reflectionProbeUsage");let Fi=hn;class qc extends Fi{}class y0 extends qc{constructor(){super(...arguments),a(this,"_needUpdateBoundingSphere",!1)}awake(){var e;super.awake(),d1&&console.log('SkinnedMeshRenderer for "'+this.name+'"',this),this.allowOcclusionWhenDynamic=!1;for(const t of this.sharedMeshes)(e=t.parent)==null||e.updateWorldMatrix(!1,!0),this.markBoundsDirty()}onAfterRender(){if(super.onAfterRender(),this._needUpdateBoundingSphere){for(const e of this.sharedMeshes)if(e instanceof Pn){this._needUpdateBoundingSphere=!1;try{const t=e.geometry,s=Bv(e);s&&(e.geometry=s),e.computeBoundingSphere(),e.geometry=t}catch(t){console.error(`Error updating bounding sphere for ${e.name}`,t)}}}if(d1){for(const e of this.sharedMeshes)if(e instanceof Pn&&e.boundingSphere){const t=X(e.boundingSphere.center).applyMatrix4(e.matrixWorld);G.DrawWireSphere(t,e.boundingSphere.radius,"red")}}}markBoundsDirty(){this._needUpdateBoundingSphere=!0}}var LE=Object.defineProperty,m1=(o,e,t,s)=>{for(var n=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=l(e,t,n)||n);return n&&LE(e,t,n),n};const Ju=C("debuggltfexport");class v0 extends Do{constructor(){super(...arguments),a(this,"sceneRoot")}}const b0=class Dl extends I{constructor(){super(...arguments),a(this,"binary",!0),a(this,"objects",[]),a(this,"ext")}async exportNow(e,t){Ju&&console.log("Exporting objects as glTF",this.objects),e||(e="scene"),(!this.objects||this.objects.length<=0)&&(this.objects=[this.context.scene]);const s={binary:this.binary,pivot:Dl.calculateCenter(this.objects),...t},n=await this.export(this.objects,s).catch(r=>(console.error(r),!1));return n===!1?!1:(this.binary?e.endsWith(".glb")||(e+=".glb"):e.endsWith(".gltf")||(e+=".gltf"),this.binary?Dl.saveArrayBuffer(n,e):Dl.saveJson(n,e),!0)}async export(e,t){if(!e||e.length<=0){console.warn("No objects set to export");return}const s=new zv;s.register(d=>new n1(d)),s.register(d=>new qx(d)),p0(s,this.context),Dl.filterTopmostParent(e);const n={trs:!1,onlyVisible:!0,truncateDrawRange:!1,binary:!0,maxTextureSize:1/0,embedImages:!0,includeCustomExtensions:!0,animations:t?.animations||Dl.collectAnimations(e),...t},r=new Array,l=new E;t!=null&&t.pivot&&l.position.sub(t.pivot),Ju&&console.log("EXPORT",e),e.forEach(d=>{d&&l0(d)&&(l.children.push(d),d.matrixAutoUpdate=!1,d.matrix.copy(d.matrixWorld),P.getComponentsInChildren(d,Fi).forEach(u=>{P.isActiveInHierarchy(u.gameObject)&&u.setInstancingEnabled(!1)}),d.traverse(u=>{if(!l0(u)){const p=u.parent;u.removeFromParent(),r.push(()=>{p&&p.add(u)})}}))});const c=new rf(l);return t!=null&&t.needleComponents&&(this.ext=new Qx),this.ext&&(this.ext.registerExport(s),this.ext.context=c),new Promise((d,u)=>{Ju&&console.log("Starting glTF export.");try{s?.parse(l,p=>{h(),d(p)},p=>{h(),u(p)},n)}catch(p){console.error(p),u(p)}finally{r.forEach(p=>p()),Ju&&console.log("Finished glTF export.")}});function h(){e.forEach(d=>{d&&(d.matrixAutoUpdate=!0,P.getComponentsInChildren(d,Fi).forEach(u=>{P.isActiveInHierarchy(u.gameObject)&&u.setInstancingEnabled(!1)}))})}}static saveArrayBuffer(e,t){this.save(new Blob([e],{type:"application/octet-stream"}),t)}static saveJson(e,t){this.save("data: text/json;charset=utf-8,"+encodeURIComponent(JSON.stringify(e)),t)}static save(e,t){const s=document.createElement("a");s.style.display="none",document.body.appendChild(s),typeof e=="string"?s.href=e:s.href=URL.createObjectURL(e),s.download=t,s.click(),s.remove()}static collectAnimations(e,t){t=t||[];for(const s of e)s&&s.traverseVisible(n=>{n.animations&&n.animations.length>0&&t.push(...n.animations)});return t}static calculateCenter(e,t){const s=t||new x;return s.set(0,0,0),e.forEach(n=>{s.add(te(n))}),s.divideScalar(e.length),s}static filterTopmostParent(e){if(!(e.length<=0))for(let t=0;t<e.length;t++){let s=e[t];if(!s){e.splice(t,1),t--;continue}for(;s.parent;){if(e.includes(s.parent)){e.splice(t,1),t--;break}s=s.parent}}}};m1([m()],b0.prototype,"binary"),m1([m(E)],b0.prototype,"objects");let _0=b0;typeof globalThis!==void 0&&!("OffscreenCanvas"in globalThis)&&(globalThis.OffscreenCanvas=class{constructor(o,e){return a(this,"canvas"),this.canvas=document.createElement("canvas"),this.canvas.width=o,this.canvas.height=e,this.canvas.convertToBlob=(t,s)=>new Promise(n=>{this.canvas.toBlob(n,t,s)}),this.canvas}});const jE=C("debugprogress");function g1(o){o=o||new Date;const e=o.getMonth()+1,t=o.getDate(),s=o.getHours(),n=o.getMinutes(),r=o.getSeconds(),l=(e<10?"0":"")+e,c=(t<10?"0":"")+t,h=(s<10?"0":"")+s,d=(n<10?"0":"")+n,u=(r<10?"0":"")+r;return o.getFullYear()+l+c+"-"+h+d+u}class de{static start(e,t){typeof t=="string"&&(t={parentScope:t});const s=new DE(e,t);Xc.set(e,s)}static report(e,t){const s=Xc.get(e);if(!s){console.warn("Reporting progress for non-existing scope",e);return}typeof t=="string"&&(t={message:t,autoStep:!0}),s.report(t)}static end(e){const t=Xc.get(e);t&&(t.end(),Xc.delete(e))}}const Xc=new Map;class DE{constructor(e,t){a(this,"scopeLabel"),a(this,"parentScope"),a(this,"childScopes",[]),a(this,"parentDepth",0),a(this,"lastStep",0),a(this,"lastAutoStepWeight",1),a(this,"lastTotalSteps",0),a(this,"onProgress"),a(this,"showLogs",!1),a(this,"selfProgress",0),a(this,"totalProgress",0),a(this,"selfReports",0),a(this,"totalReports",0),this.parentScope=t!=null&&t.parentScope?Xc.get(t.parentScope):void 0,this.parentScope&&(this.parentScope.childScopes.push(this),this.parentDepth=this.parentScope.parentDepth+1),this.scopeLabel=" ".repeat(this.parentDepth*2)+e,this.showLogs=t?.logTimings??!!jE,this.showLogs&&console.time(this.scopeLabel),this.onProgress=t?.onProgress}report(e,t=!1){if(e){if(e.totalSteps!==void 0&&(this.lastTotalSteps=e.totalSteps),e.currentStep!==void 0&&(this.lastStep=e.currentStep),e.autoStep!==void 0){if(e.currentStep===void 0){this.lastStep===void 0&&(this.lastStep=0);const n=typeof e.autoStep=="number"?e.autoStep:1;this.lastStep+=this.lastAutoStepWeight,this.lastAutoStepWeight=n,e.currentStep=this.lastStep}e.totalSteps=this.lastTotalSteps}e.progress!==void 0?this.selfProgress=e.progress:e.currentStep!==void 0&&e.totalSteps!==void 0&&(this.selfProgress=e.currentStep/e.totalSteps)}if(this.childScopes.length>0){let n=0,r=0;for(const c of this.childScopes)n+=c.selfProgress,r+=1;r>0&&(n/=r);const l=this.lastAutoStepWeight/(this.lastTotalSteps??1);this.totalProgress=this.selfProgress+n*l}else this.totalProgress=this.selfProgress;this.selfProgress=Math.min(1,this.selfProgress),this.totalProgress=Math.min(1,this.totalProgress);let s=(this.totalProgress*100).toFixed(3)+"%";this.childScopes.length>0&&(s+=" ("+(this.selfProgress*100).toFixed(3)+"% self)"),e!=null&&e.message&&(s=e.message+" \u2013 "+s),this.lastStep!==void 0&&this.lastTotalSteps!==void 0&&(s="Step "+(this.lastStep+(this.lastAutoStepWeight!=1?"\u2013"+(this.lastStep+this.lastAutoStepWeight):"")+"/"+this.lastTotalSteps)+" "+s),t?this.totalReports++:(this.selfReports++,this.totalReports++),this.showLogs&&console.timeLog(this.scopeLabel,s),this.onProgress&&this.onProgress(this.totalProgress),this.parentScope&&this.parentScope.report(void 0,!0)}end(){this.report({progress:1,autoStep:!0},!0),this.showLogs&&(console.timeLog(this.scopeLabel,"Total reports: "+this.totalReports,"Self reports: "+this.selfReports),console.timeEnd(this.scopeLabel));let e=!1;for(const t of this.childScopes)if(!(t.selfProgress>=1)){e=!0;break}e&&console.warn("Progress end with child scopes that are still running",this),this.onProgress=void 0}}function Os(o){return o=o.replace(/[^a-zA-Z0-9_]/g,""),o.match(/^[a-zA-Z_]/)||(o="_"+o),o}function f1(o){return o=o.replace('"','\\"'),o}function y1(o){if(o.length===0)return null;const e=o.map(t=>{const s=new Array;for(;t.parent;)s.unshift(t.parent),t=t.parent;return s});return e[0].findLast(t=>e.every(s=>s.includes(t)))||null}function v1(o){const e=y1(o),t=new Set;for(const s of o){let n=s.parent;for(;n&&n!==e;)o.includes(n)||t.add(n),n=n.parent}return t}const BE=new x,FE=new H,UE=new x(1,1,1),b1=class Bl{constructor(e,t,s=null,n=null,r=null,l=null,c=null,h=null){a(this,"uuid"),a(this,"name"),a(this,"type"),a(this,"extraSchemas",[]),a(this,"displayName"),a(this,"visibility"),a(this,"transform",null),a(this,"_isDynamic"),a(this,"geometry"),a(this,"material"),a(this,"camera"),a(this,"parent"),a(this,"skinnedMesh"),a(this,"children",[]),a(this,"animations"),a(this,"_eventListeners"),a(this,"needsTranslate",!1),a(this,"needsOrient",!1),a(this,"needsScale",!1);var d,u,p;this.uuid=e,this.name=Os(t),this.displayName=t,s?this.transform={position:((d=s.position)==null?void 0:d.clone())||null,quaternion:((u=s.quaternion)==null?void 0:u.clone())||null,scale:((p=s.scale)==null?void 0:p.clone())||null}:this.transform=null,this.geometry=n,this.material=r,this.camera=l,this.parent=null,this.children=[],this._eventListeners={},this._isDynamic=!1,this.skinnedMesh=c,this.animations=h}getMatrix(){if(!this.transform)return new se;const{position:e,quaternion:t,scale:s}=this.transform,n=new se;return n.compose(e||BE,t||FE,s||UE),n}setMatrix(e){if(!e||!(e instanceof se)){this.transform=null;return}const t=new x,s=new H,n=new x;e.decompose(t,s,n),this.transform={position:t,quaternion:s,scale:n}}get matrix(){return this.getMatrix()}set matrix(e){this.setMatrix(e)}get isDynamic(){return this._isDynamic}set isDynamic(e){this._isDynamic=e}static createEmptyParent(e){const t=new Bl(Cn.generateUUID(),e.name+"_empty_"+Bl.USDObject_export_id++,e.transform),s=e.parent;return s&&s.add(t),t.add(e),t.isDynamic=!0,e.transform=null,t}static createEmpty(){const e=new Bl(Cn.generateUUID(),"Empty_"+Bl.USDObject_export_id++);return e.isDynamic=!0,e}is(e){return e?this.uuid===e.uuid:!1}isEmpty(){return!this.geometry}clone(){const e=new Bl(Cn.generateUUID(),this.name,this.transform,this.geometry,this.material);return e.isDynamic=this.isDynamic,e}deepClone(){const e=this.clone();for(const t of this.children)t&&e.add(t.deepClone());return e}getPath(){let e=this.parent,t=this.name;for(;e;)t=(e.parent?e.name:e.name+"/Scenes/Scene")+"/"+t,e=e.parent;return"</"+t+">"}add(e){e.parent&&e.parent.remove(e),e.parent=this,this.children.push(e)}remove(e){const t=this.children.indexOf(e);t>=0&&(e.parent===this&&(e.parent=null),this.children.splice(t,1))}addEventListener(e,t){this._eventListeners[e]||(this._eventListeners[e]=[]),this._eventListeners[e].push(t)}removeEventListener(e,t){if(!this._eventListeners[e])return;const s=this._eventListeners[e].indexOf(t);s>=0&&this._eventListeners[e].splice(s,1)}onSerialize(e,t){const s=this._eventListeners.serialize;s&&s.forEach(n=>n(e,t))}};a(b1,"USDObject_export_id",0);let pi=b1;class w0 extends pi{constructor(){super(void 0,"StageRoot",null,null,null,null),a(this,"stageLength"),this.children=[],this.stageLength=200}get isDocumentRoot(){return!0}get isDynamic(){return!1}add(e){e.parent=this,this.children.push(e)}remove(e){const t=this.children.indexOf(e);t>=0&&(e.parent===this&&(e.parent=null),this.children.splice(t,1))}traverse(e,t=null){if(t!==null?e(t):t=this,t.children)for(const s of t.children)this.traverse(e,s)}findById(e){let t=!1;function s(n){if(!t){if(n.uuid===e)return t=!0,n;if(n.children)for(const r of n.children){if(!r)continue;const l=s(r);if(l)return l}}}return s(this)}buildHeader(e){var t,s,n;const r=(t=e.extensions)==null?void 0:t.find(f=>f?.extensionName==="animation"),l=(s=e.extensions)==null?void 0:s.find(f=>f?.extensionName==="Behaviour"),c=(n=e.extensions)==null?void 0:n.find(f=>f?.extensionName==="Physics"),h=r?.getStartTimeCode()??0,d=r?.getEndTimeCode()??0;let u="";const p=r?.registeredClips;if(p)for(const f of p)u+=` # Animation: ${f.name}, start=${r.getStartTimeByClip(f)*60}, length=${f.duration*60}
1017
+ `;const g=u;return`#usda 1.0
1018
+ (
1019
+ customLayerData = {
1020
+ string creator = "Needle Engine ${_s}"
1021
+ dictionary Needle = {
1022
+ bool animations = ${r?1:0}
1023
+ bool interactive = ${l?1:0}
1024
+ bool physics = ${c?1:0}
1025
+ bool quickLookCompatible = ${e.quickLookCompatible?1:0}
1026
+ }
1027
+ }
1028
+ defaultPrim = "${Os(this.name)}"
1029
+ metersPerUnit = 1
1030
+ upAxis = "Y"
1031
+ startTimeCode = ${h}
1032
+ endTimeCode = ${d}
1033
+ timeCodesPerSecond = 60
1034
+ framesPerSecond = 60
1035
+ doc = """Generated by Needle Engine USDZ Exporter ${_s}"""
1036
+ ${g}
1037
+ )
1038
+ `}}const nl=`
1039
+ `,Yt="</StageRoot/Materials";class _1{constructor(){a(this,"str"),a(this,"indent"),this.str="",this.indent=0}clear(){this.str="",this.indent=0}beginBlock(e=void 0,t="{",s=!0){e!==void 0?(e=this.applyIndent(e),this.str+=e,s?(this.str+=nl,this.str+=this.applyIndent(t)):this.str+=" "+t):this.str+=this.applyIndent(t),this.str+=nl,this.indent+=1}closeBlock(e="}"){this.indent-=1,this.str+=this.applyIndent(e)+nl}beginArray(e){e=this.applyIndent(e+" = ["),this.str+=e,this.str+=nl,this.indent+=1}closeArray(){this.indent-=1,this.str+=this.applyIndent("]")+nl}appendLine(e=""){e=this.applyIndent(e),this.str+=e,this.str+=nl}toString(){return this.str}applyIndent(e){let t="";for(let s=0;s<this.indent;s++)t+=" ";return t+e}}class zE{constructor(e,t,s){a(this,"root"),a(this,"exporter"),a(this,"extensions",[]),a(this,"quickLookCompatible"),a(this,"exportInvisible"),a(this,"materials"),a(this,"textures"),a(this,"files"),a(this,"document"),a(this,"output"),a(this,"animations"),this.root=e,this.exporter=t,this.quickLookCompatible=s.quickLookCompatible,this.exportInvisible=s.exportInvisible,s.extensions&&(this.extensions=s.extensions),this.materials=new Map,this.textures={},this.files={},this.document=new w0,this.output="",this.animations=[]}}class x0{constructor(){a(this,"ar",{anchoring:{type:"plane"},planeAnchoring:{alignment:"horizontal"}}),a(this,"quickLookCompatible",!1),a(this,"extensions",[]),a(this,"maxTextureSize",4096),a(this,"exportInvisible",!1)}}let w1=class{constructor(){a(this,"debug"),a(this,"pruneUnusedNodes"),a(this,"sceneAnchoringOptions",new x0),a(this,"extensions",[]),a(this,"keepObject"),a(this,"beforeWritingDocument"),this.debug=!1,this.pruneUnusedNodes=!0}async parse(o,e=new x0){var t,s;e=Object.assign(new x0,e),this.sceneAnchoringOptions=e;const n=new zE(o,this,e);this.extensions=n.extensions;const r=n.files,l="model.usda";r[l]=null;const c=n.materials,h=n.textures;de.report("export-usdz","Invoking onBeforeBuildDocument"),await ep(n,"onBeforeBuildDocument"),de.report("export-usdz","Done onBeforeBuildDocument"),de.report("export-usdz","Reparent bones to common ancestor");const d=[],u=new Set;o?.traverse(w=>{if(!(!e.exportInvisible&&!w.visible)&&w instanceof Pn){const S=w.skeleton.bones,k=y1(S);if(k){const M={object:w,originalParent:w.parent,newParent:k};d.push(M),u.add(M.object.uuid),M.newParent&&u.add(M.newParent.uuid),M.originalParent&&u.add(M.originalParent.uuid)}}});for(const w of d){const{object:S,originalParent:k,newParent:M}=w;M.add(S)}de.report("export-usdz","Traversing hierarchy"),o&&x1(o,n.document,n,this.keepObject),de.report("export-usdz","Invoking onAfterBuildDocument"),await ep(n,"onAfterBuildDocument");const p=n.extensions.find(w=>w.extensionName==="Behaviour"),g=p?.getAllTargetUuids()??new Set;if(this.pruneUnusedNodes){const w={allBehaviorTargets:g,debug:!1,boneReparentings:u,quickLookCompatible:n.quickLookCompatible};this.debug&&S1(n.document,"Hierarchy BEFORE pruning",w),C1(n.document,w),this.debug&&S1(n.document,"Hierarchy AFTER pruning")}else this.debug&&console.log("Pruning of empty nodes is disabled. This may result in a larger USDZ file.");de.report("export-usdz",{message:"Parsing document",autoStep:10}),await NE(n,()=>(de.report("export-usdz","Building materials"),QE(c,h,e.quickLookCompatible))),de.report("export-usdz","Invoking onAfterSerialize"),await ep(n,"onAfterSerialize");for(const w of d){const{object:S,originalParent:k,newParent:M}=w;k&&k.add(S)}(s=(t=n.exporter)==null?void 0:t.beforeWritingDocument)==null||s.call(t);const f=n.document.buildHeader(n)+`
1040
+ `+n.output;this.debug&&console.log(f),r[l]=Nv(f),n.output="",de.report("export-usdz",{message:"Exporting textures",autoStep:10}),de.start("export-usdz-textures",{parentScope:"export-usdz",logTimings:!1});const y=new pr({antialias:!1,alpha:!0,premultipliedAlpha:!1,preserveDrawingBuffer:!0}),b=Object.keys(h).length;de.report("export-usdz-textures",{totalSteps:b*3,currentStep:0});const v=async w=>{const S=h[w],k=S.texture,M=j1.includes(k.format);let T={imageData:k.image};de.report("export-usdz-textures",{message:"read back texture",autoStep:!0});const L=S.scale!==void 0&&S.scale.x!==1&&S.scale.y!==1&&S.scale.z!==1&&S.scale.w!==1;(k.isCompressedTexture||k.isRenderTargetTexture||L)&&(T=await O1(k,e.maxTextureSize,y,S.scale)),de.report("export-usdz-textures",{message:"convert texture to canvas",autoStep:!0});const B=await VE(T.imageBitmap||T.imageData,e.maxTextureSize).catch(z=>{console.error("Error converting texture to canvas",k,z)});if(B){de.report("export-usdz-textures",{message:"convert canvas to blob",autoStep:!0});const z=await B.convertToBlob({type:M?"image/png":"image/jpeg",quality:.95});r[`textures/${w}.${M?"png":"jpg"}`]=new Uint8Array(await z.arrayBuffer())}else console.warn("Can`t export texture: ",k)};for(const w in h)await v(w);y.dispose(),de.end("export-usdz-textures");let _=0;for(const w in r){const S=r[w],k=34+w.length;_+=k;const M=_&63;if(M!==4){const T=64-M,L=new Uint8Array(T);r[w]=[S,{extra:{12345:L}}]}_=S.length}return de.report("export-usdz","zip archive"),tO(r,{level:0})}};function x1(o,e,t,s){var n;if(!t.exportInvisible&&!o.visible)return;let r,l,c;const h={position:o.position,quaternion:o.quaternion,scale:o.scale};if(o.position.x===0&&o.position.y===0&&o.position.z===0&&(h.position=null),o.quaternion.x===0&&o.quaternion.y===0&&o.quaternion.z===0&&o.quaternion.w===1&&(h.quaternion=null),o.scale.x===1&&o.scale.y===1&&o.scale.z===1&&(h.scale=null),(o instanceof q||o instanceof Pn)&&(l=o.geometry,c=o.material),s&&!s(o)&&(l=void 0,c=void 0),(o instanceof q||o instanceof Pn)&&c&&(c instanceof vt||c instanceof Me||c instanceof Pe&&c.type==="MeshLineMaterial")){const d=sp(o),u=o instanceof Pn?o:null;r=new pi(o.uuid,d,h,l,c,void 0,u,o.animations)}else if(o instanceof we||o instanceof hd){const d=sp(o);r=new pi(o.uuid,d,h,void 0,void 0,o)}else{const d=sp(o);r=new pi(o.uuid,d,h,void 0,void 0,void 0,void 0,o.animations)}if(r){if(r.displayName=((n=o.userData)==null?void 0:n.name)||o.name,r.visibility=o.visible?void 0:"invisible",e&&e.add(r),e=r,t.extensions)for(const d of t.extensions)d.onExportObject&&d.onExportObject.call(d,o,r,t)}else{const d=sp(o),u=new pi(o.uuid,d,{position:o.position,quaternion:o.quaternion,scale:o.scale});e&&e.add(u),e=u}for(const d of o.children)x1(d,e,t,s)}function S1(o,e,...t){const s={};let n=0;function r(l,c){n++;let h=l.displayName||l.name;h+=" ("+l.uuid+")",(l.geometry||l.material||l.camera||l.skinnedMesh)&&(h+=" ("+(l.geometry?"geo, ":"")+(l.material?"mat, ":"")+(l.camera?"cam, ":"")+(l.skinnedMesh?"skin, ":"")+")"),c[h]={};const d={object:l};l.material&&(d.mat=!0),l.geometry&&(d.geo=!0),l.camera&&(d.cam=!0),l.skinnedMesh&&(d.skin=!0),c[h]._self=d;for(const u of l.children)u&&r(u,c[h])}r(o,s),console.log(e+" ("+n+" nodes)",s,...t)}function C1(o,e){var t;let s=!0;const n=new Array,r=new Array;if(o.children.length===0)s=!0;else{const u=[...o.children];for(const p of u)if(p){const g=C1(p,e);e.debug&&(g?n.push(p):r.push(p)),s=s&&g}}const l=e.allBehaviorTargets.has(o.uuid),c=o.geometry||o.material||o.camera&&!e.quickLookCompatible||o.skinnedMesh||!1,h=e.boneReparentings.has(o.uuid),d=s&&!l&&!c&&!h;return d?(e.debug&&console.log("Pruned object:",(o.displayName||o.name)+" ("+o.uuid+")",{isVisible:c,isBehaviorSourceOrTarget:l,allChildsWerePruned:s,isBoneReparenting:h,object:o,prunedChilds:n,keptChilds:r}),(t=o.parent)==null||t.remove(o)):e.debug&&console.log("Kept object:",(o.displayName||o.name)+" ("+o.uuid+")",{isVisible:c,isBehaviorSourceOrTarget:l,allChildsWerePruned:s,isBoneReparenting:h,object:o,prunedChilds:n,keptChilds:r}),d}async function NE(o,e){de.start("export-usdz-resources","export-usdz");const t=[];for(const h of o.document.children)P1(h,o,t);const s=t.length;for(let h=0;h<s;h++)de.report("export-usdz-resources",{totalSteps:s,currentStep:h}),await new Promise((d,u)=>{t[h](),d()});de.end("export-usdz-resources");const n=new _1,r=o.exporter.sceneAnchoringOptions.ar;n.beginBlock(`def Xform "${o.document.name}"`),n.beginBlock(`def Scope "Scenes" (
1041
+ kind = "sceneLibrary"
1042
+ )`),n.beginBlock('def Xform "Scene"',"(",!1),n.appendLine('apiSchemas = ["Preliminary_AnchoringAPI"]'),n.appendLine("customData = {"),n.appendLine(" bool preliminary_collidesWithEnvironment = 0"),n.appendLine(' string sceneName = "Scene"'),n.appendLine("}"),n.appendLine('sceneName = "Scene"'),n.closeBlock(")"),n.beginBlock(),n.appendLine(`token preliminary:anchoring:type = "${r.anchoring.type}"`),r.anchoring.type==="plane"&&n.appendLine(`token preliminary:planeAnchoring:alignment = "${r.planeAnchoring.alignment}"`),r.anchoring.type==="image"&&n.appendLine(`rel preliminary:imageAnchoring:referenceImage = </${o.document.name}/Scenes/Scene/AnchoringReferenceImage>`),n.appendLine();const l=h=>{if(!h)return 0;let d=1;for(const u of h.children)d+=l(u);return d},c=l(o.document);de.start("export-usdz-xforms","export-usdz"),de.report("export-usdz-xforms",{totalSteps:c,currentStep:1});for(const h of o.document.children)R1(h,n,o);de.end("export-usdz-xforms"),de.report("export-usdz","invoke onAfterHierarchy"),ep(o,"onAfterHierarchy",n),n.closeBlock(),n.closeBlock(),n.appendLine(e()),n.closeBlock(),de.report("export-usdz","write to string"),o.output+=n.toString()}function P1(o,e,t){if(!o)return;const s=o.geometry,n=o.material;if(s)if(n&&("isMeshStandardMaterial"in n&&n.isMeshStandardMaterial||"isMeshBasicMaterial"in n&&n.isMeshBasicMaterial||n.type==="MeshLineMaterial")){const r="geometries/"+C0(s,o.name)+".usda";if(!(r in e.files)){const l=()=>{var c,h;const d=GE(s,(h=(c=o.skinnedMesh)==null?void 0:c.skeleton)==null?void 0:h.bones,e.quickLookCompatible);e.files[r]=$E(d)};t.push(l)}}else console.warn("NeedleUSDZExporter: Unsupported material type (USDZ only supports MeshStandardMaterial)",n?.name);n&&(n.uuid in e.materials||(e.materials[n.uuid]=n));for(const r of o.children)P1(r,e,t)}async function ep(o,e,t=null){if(o.extensions){for(const s of o.extensions)if(s&&typeof s[e]=="function"){const n=s[e].call(s,o,t);n instanceof Promise&&await n}}}let tp=null,Kt=null,S0,ol,ip;async function O1(o,e=1/0,t=null,s=void 0){S0||(S0=new Ns(2,2,1,1)),ol||(ol=new Ws({uniforms:{blitTexture:new Xi(o),flipY:new Xi(!1),scale:new Xi(new ye(1,1,1,1))},vertexShader:`
1043
+ varying vec2 vUv;
1044
+ uniform bool flipY;
1045
+ void main(){
1046
+ vUv = uv;
1047
+ if (flipY)
1048
+ vUv.y = 1. - vUv.y;
1049
+ gl_Position = vec4(position.xy * 1.0,0.,.999999);
1050
+ }`,fragmentShader:`
1051
+ uniform sampler2D blitTexture;
1052
+ uniform vec4 scale;
1053
+ varying vec2 vUv;
1054
+
1055
+ void main(){
1056
+ gl_FragColor = vec4(vUv.xy, 0, 1);
1057
+
1058
+ #ifdef IS_SRGB
1059
+ gl_FragColor = sRGBTransferOETF( texture2D( blitTexture, vUv) );
1060
+ #else
1061
+ gl_FragColor = texture2D( blitTexture, vUv);
1062
+ #endif
1063
+
1064
+ gl_FragColor.rgba *= scale.rgba;
1065
+ }`}));const n=ol.uniforms;n.blitTexture.value=o,n.flipY.value=!1,n.scale.value=new ye(1,1,1,1),s!==void 0&&n.scale.value.copy(s),ol.defines.IS_SRGB=o.colorSpace==Mn,ol.needsUpdate=!0,ip||(ip=new q(S0,ol),ip.frustumCulled=!1);const r=new we,l=new wi;l.add(ip),t||(t=tp=new pr({antialias:!1,alpha:!0,premultipliedAlpha:!1,preserveDrawingBuffer:!0}));const c=Math.min(o.image.width,e),h=Math.min(o.image.height,e);Kt&&(Kt.width!==c||Kt.height!==h)&&(Kt.dispose(),Kt=null),Kt||(Kt=new Hs(c,h,{format:md,type:SP,minFilter:_d,magFilter:_d})),t.setRenderTarget(Kt),t.setSize(c,h),t.clear(),t.render(l,r),tp&&(tp.dispose(),tp=null);const d=new Uint8ClampedArray(Kt.width*Kt.height*4);t.readRenderTargetPixels(Kt,0,0,Kt.width,Kt.height,d);const u=new ImageData(d,Kt.width,Kt.height,void 0),p=await createImageBitmap(u,{premultiplyAlpha:"none"});return{imageData:u,imageBitmap:p}}function WE(o){return typeof HTMLImageElement<"u"&&o instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&o instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&o instanceof OffscreenCanvas||typeof ImageBitmap<"u"&&o instanceof ImageBitmap}async function VE(o,e=4096){const t=e/Math.max(o.width,o.height),s=o.width*Math.min(1,t),n=o.height*Math.min(1,t),r=new OffscreenCanvas(s,n),l={premultiplyAlpha:"none"};o.width!==s&&(l.resizeWidth=s),o.height!==n&&(l.resizeHeight=n);const c=await createImageBitmap(o,l),h=r.getContext("bitmaprenderer");return h&&h.transferFromImageBitmap(c),r}async function k1(o,e=void 0,t=!1,s=4096){if(WE(o)){const n=s/Math.max(o.width,o.height),r=new OffscreenCanvas(o.width*Math.min(1,n),o.height*Math.min(1,n)),l=r.getContext("2d",{alpha:!0,premultipliedAlpha:!1});if(!l)throw new Error("Could not get canvas 2D context");if(t===!0&&(l.translate(0,r.height),l.scale(1,-1)),l.drawImage(o,0,0,r.width,r.height),e!==void 0){const c=e.x,h=e.y,d=e.z,u=e.w,p=l.getImageData(0,0,r.width,r.height),g=p.data;for(let f=0;f<g.length;f+=4)g[f+0]=g[f+0]*c,g[f+1]=g[f+1]*h,g[f+2]=g[f+2]*d,g[f+3]=g[f+3]*u;l.putImageData(p,0,0)}return r}else throw new Error("NeedleUSDZExporter: No valid image data found. Unable to process texture.")}const Ae=7;function HE(){return`#usda 1.0
1066
+ (
1067
+ customLayerData = {
1068
+ string creator = "Needle Engine USDZExporter"
1069
+ }
1070
+ metersPerUnit = 1
1071
+ upAxis = "Y"
1072
+ )
1073
+ `}function $E(o,e){let t=HE();return t+=o,Nv(t)}function sp(o){return o.name.replace(/[-<>\(\)\[\]§$%&\/\\\=\?\,\;]/g,"")+"_"+o.id}function M1(o){return Os(o.name||"bone_"+o.uuid)}function C0(o,e){return Os(o.name||"Geometry")+"_"+o.id}function P0(o){return Os(o.name||"Material")+"_"+o.id}function rl(o,e){let t=M1(o),s=o.parent;for(;s&&s!==e;)t=M1(s)+"/"+t,s=s.parent;return t}function R1(o,e,t){var s;if(o==null)return;de.report("export-usdz-xforms",{message:"buildXform "+o.displayName||o.name,autoStep:!0});const n=o.transform,r=o.geometry,l=o.material,c=o.camera,h=o.name;if(o.animations)for(const y of o.animations)t.animations.push(y);const d=r&&r.isBufferGeometry&&r.attributes.skinIndex!==void 0&&r.attributes.skinIndex.count>0,u=d?"SkelRoot":"Xform",p=new Array,g=l&&l instanceof Me&&l.color&&l.color.r===1&&l.color.g===1&&l.color.b===1&&!l.map&&l.opacity===1&&r?.attributes.color;if(r!=null&&r.attributes.color&&!g&&console.warn("NeedleUSDZExporter: Geometry has vertex colors. Vertex colors will only be shown in QuickLook for unlit materials with white color and no texture. Otherwise, they will be ignored.",o.displayName),e.appendLine(),r?(e.beginBlock(`def ${u} "${h}"`,"(",!1),t.quickLookCompatible&&l&&l.side===Ci&&!d?e.appendLine(`prepend references = @./geometries/${C0(r)}.usda@</Geometry_doubleSided>`):e.appendLine(`prepend references = @./geometries/${C0(r)}.usda@</Geometry>`),g||p.push("MaterialBindingAPI"),d&&p.push("SkelBindingAPI")):c&&!t.quickLookCompatible?e.beginBlock(`def Camera "${h}"`,"(",!1):o.type!==void 0?e.beginBlock(`def ${o.type} "${h}"`):e.beginBlock(`def Xform "${h}"`,"(",!1),o.type===void 0&&((s=o.extraSchemas)!=null&&s.length&&p.push(...o.extraSchemas),p.length&&e.appendLine(`prepend apiSchemas = [${p.map(y=>`"${y}"`).join(", ")}]`)),o.displayName&&e.appendLine(`displayName = "${f1(o.displayName)}"`),(c||o.type===void 0)&&(e.closeBlock(")"),e.beginBlock()),r&&l){if(!g){const y=P0(l);e.appendLine(`rel material:binding = </StageRoot/Materials/${y}>`)}!t.quickLookCompatible&&l.side===Ci&&(e.beginBlock('over "Geometry" '),e.appendLine("uniform bool doubleSided = 1"),e.closeBlock())}let f=!1;if(d?(e.appendLine("rel skel:skeleton = <Rig>"),e.appendLine("rel skel:animationSource = <Rig/_anim>"),f=!1):o.type===void 0&&n&&(f=f||n.position!==null||n.quaternion!==null||n.scale!==null,n.position&&(o.needsTranslate=!0,e.appendLine(`double3 xformOp:translate = (${ue(n.position.x)}, ${ue(n.position.y)}, ${ue(n.position.z)})`)),n.quaternion&&(o.needsOrient=!0,e.appendLine(`quatf xformOp:orient = (${ue(n.quaternion.w)}, ${ue(n.quaternion.x)}, ${ue(n.quaternion.y)}, ${ue(n.quaternion.z)})`)),n.scale&&(o.needsScale=!0,e.appendLine(`double3 xformOp:scale = (${ue(n.scale.x)}, ${ue(n.scale.y)}, ${ue(n.scale.z)})`))),o.visibility!==void 0&&e.appendLine(`token visibility = "${o.visibility}"`),c&&!t.quickLookCompatible&&("isOrthographicCamera"in c&&c.isOrthographicCamera?(e.appendLine(`float2 clippingRange = (${c.near}, ${c.far})`),e.appendLine(`float horizontalAperture = ${((Math.abs(c.left)+Math.abs(c.right))*10).toPrecision(Ae)}`),e.appendLine(`float verticalAperture = ${((Math.abs(c.top)+Math.abs(c.bottom))*10).toPrecision(Ae)}`),e.appendLine('token projection = "orthographic"')):"isPerspectiveCamera"in c&&c.isPerspectiveCamera&&(e.appendLine(`float2 clippingRange = (${c.near.toPrecision(Ae)}, ${c.far.toPrecision(Ae)})`),e.appendLine(`float focalLength = ${c.getFocalLength().toPrecision(Ae)}`),e.appendLine(`float focusDistance = ${c.focus.toPrecision(Ae)}`),e.appendLine(`float horizontalAperture = ${c.getFilmWidth().toPrecision(Ae)}`),e.appendLine('token projection = "perspective"'),e.appendLine(`float verticalAperture = ${c.getFilmHeight().toPrecision(Ae)}`))),o.onSerialize&&o.onSerialize(e,t),o.type===void 0){const y=new Array;o.needsTranslate&&y.push('"xformOp:translate"'),o.needsOrient&&y.push('"xformOp:orient"'),o.needsScale&&y.push('"xformOp:scale"'),y.length&&e.appendLine(`uniform token[] xformOpOrder = [${y.join(", ")}]`)}if(o.children){e.appendLine();for(const y of o.children)R1(y,e,t)}e.closeBlock()}function ue(o){return Number.isInteger(o)?o.toString():o.toFixed(10)}function T1(o){const e=o.elements;return`( ${np(e,0)}, ${np(e,4)}, ${np(e,8)}, ${np(e,12)} )`}function np(o,e){return`(${ue(o[e+0])}, ${ue(o[e+1])}, ${ue(o[e+2])}, ${ue(o[e+3])})`}function GE(o,e=[],t=!0){return`
1074
+ def "Geometry"
1075
+ ${qE(o,e,t)}
1076
+ `}function qE(o,e=[],t=!0){const s="Geometry",n=o.attributes,r=n.position.count,l=e&&e.length>0,c=[],h=[];let d=new Array,u=n.skinIndex;if(l){const g=[];for(const v of e)c.push({bone:v,index:e.indexOf(v)}),g.push(v.uuid);let f=1e4;for(;g.length<e.length&&f-- >0;)for(const v of c){const _=v.bone.children;for(const w of _)g.indexOf(w.uuid)===-1&&e.indexOf(w)!==-1&&(c.push({bone:w,index:e.indexOf(w)}),g.push(w.uuid))}f<=0&&console.error("Failed to sort bones in skinned mesh",c,e,g);for(const v of v1(e))c.push({bone:v,index:c.length});const y=c[0].bone.parent;c.sort((v,_)=>rl(v.bone,y)>rl(_.bone,y)?1:-1),c.map(v=>'"'+rl(v.bone,y)+'"').join(", ");for(const v in c)h[c[v].index]=parseInt(v);const b=n.skinIndex;d=new Array;for(let v=0;v<b.count;v++){const _=b.getX(v),w=b.getY(v),S=b.getZ(v),k=b.getW(v);d.push(h[_],h[w],h[S],h[k])}u=new bt(new Uint16Array(d),4)}const p=n.skinWeight&&n.skinIndex;return`
1077
+ {
1078
+ def Mesh "${s}" ${p?`(
1079
+ prepend apiSchemas = ["SkelBindingAPI"]
1080
+ )`:""}
1081
+ {
1082
+ int[] faceVertexCounts = [${O0(o)}]
1083
+ int[] faceVertexIndices = [${k0(o)}]
1084
+ ${n.normal||t?`normal3f[] normals = [${op(n.normal,r)}] (
1085
+ interpolation = "vertex"
1086
+ )`:""}
1087
+ point3f[] points = [${op(n.position,r)}]
1088
+ ${n.uv?`texCoord2f[] primvars:st = [${A1(n.uv,r,!0)}] (
1089
+ interpolation = "vertex"
1090
+ )`:""}
1091
+ ${n.uv1?M0("st1",n.uv1):""}
1092
+ ${n.uv2?M0("st2",n.uv2):""}
1093
+ ${n.uv3?M0("st3",n.uv3):""}
1094
+ ${p?`matrix4d primvars:skel:geomBindTransform = ( (1, 0, 0, 0), (0, 1, 0, 0), (0, 0, 1, 0), (0, 0, 0, 1) ) (
1095
+ elementSize = 1
1096
+ interpolation = "constant"
1097
+ )`:""}
1098
+ ${n.skinIndex?`int[] primvars:skel:jointIndices = [${E1(u,!0)}] (
1099
+ elementSize = 4
1100
+ interpolation = "vertex"
1101
+ )`:""}
1102
+ ${n.skinWeight?`float[] primvars:skel:jointWeights = [${E1(n.skinWeight)}] (
1103
+ elementSize = 4
1104
+ interpolation = "vertex"
1105
+ )`:""}
1106
+ ${n.color?`color3f[] primvars:displayColor = [${op(n.color,r)}] (
1107
+ interpolation = "vertex"
1108
+ )`:""}
1109
+ uniform token subdivisionScheme = "none"
1110
+ }
1111
+ }
1112
+ ${t?`
1113
+ # This is a workaround for QuickLook/RealityKit not supporting the doubleSided attribute. We're adding a second
1114
+ # geometry definition here, that uses the same mesh data but appends extra faces with reversed winding order.
1115
+ def "${s}_doubleSided" (
1116
+ prepend references = </Geometry>
1117
+ )
1118
+ {
1119
+ over "Geometry"
1120
+ {
1121
+ int[] faceVertexCounts = [${O0(o)+", "+O0(o)}]
1122
+ int[] faceVertexIndices = [${k0(o)+", "+k0(o,!0)}]
1123
+ }
1124
+ }
1125
+ `:""}
1126
+ `}function O0(o){const e=o.index!==null?o.index.count:o.attributes.position.count;return Array(Math.floor(e/3)).fill(3).join(", ")}function k0(o,e=!1){const t=o.index,s=[];if(t!==null)for(let n=0;n<t.count;n++){let r=n;e&&(r=n%3===0?n+2:n%3===2?n-2:n),s.push(t.getX(r))}else{const n=o.attributes.position.count;for(let r=0;r<n;r++){let l=r;e&&(l=r%3===0?r+2:r%3===2?r-2:r),s.push(l)}}return s.join(", ")}function M0(o,e){const t=e.itemSize;switch(t){case 2:return`texCoord2f[] primvars:${o} = [${A1(e,t,!0)}] (
1127
+ interpolation = "vertex"
1128
+ )`;case 3:return`texCoord3f[] primvars:${o} = [${op(e,t)}] (
1129
+ interpolation = "vertex"
1130
+ )`;case 4:return`double4[] primvars:${o} = [${XE(e,t)}] (
1131
+ interpolation = "vertex"
1132
+ )`;default:return console.warn("USDZExporter: Attribute with "+t+" components are currently not supported. Results may be undefined for "+o+"."),""}}function op(o,e){if(o===void 0)return console.warn("USDZExporter: A mesh attribute is missing and will be set with placeholder data. The result may look incorrect."),Array(e).fill("(0, 0, 1)").join(", ");const t=[];for(let s=0;s<o.count;s++){const n=o.getX(s),r=o.getY(s),l=o.getZ(s);t.push(`(${n.toPrecision(Ae)}, ${r.toPrecision(Ae)}, ${l.toPrecision(Ae)})`)}return t.join(", ")}function XE(o,e){if(o===void 0)return console.warn("USDZExporter: Attribute is missing. Results may be undefined."),Array(e).fill("(0, 0, 0, 0)").join(", ");const t=[];for(let s=0;s<o.count;s++){const n=o.getX(s),r=o.getY(s),l=o.getZ(s)||0,c=o.getW(s)||0;t.push(`(${n.toPrecision(Ae)}, ${r.toPrecision(Ae)}, ${l.toPrecision(Ae)}, ${c.toPrecision(Ae)})`)}return t.join(", ")}function E1(o,e=!1){const t=[];for(let s=0;s<o.count;s++){const n=o.getX(s),r=o.getY(s),l=o.getZ(s),c=o.getW(s);t.push(`${e?n:n.toPrecision(Ae)}`),t.push(`${e?r:r.toPrecision(Ae)}`),t.push(`${e?l:l.toPrecision(Ae)}`),t.push(`${e?c:c.toPrecision(Ae)}`)}return t.join(", ")}function A1(o,e,t=!1){if(o===void 0)return console.warn("USDZExporter: UVs missing."),Array(e).fill("(0, 0)").join(", ");const s=[];for(let n=0;n<o.count;n++){const r=o.getX(n);let l=o.getY(n);t&&(l=1-l),s.push(`(${r.toPrecision(Ae)}, ${l.toPrecision(Ae)})`)}return s.join(", ")}function QE(o,e,t=!1){const s=[];for(const n in o){const r=o[n];s.push(YE(r,e,t))}return`
1133
+ def "Materials"
1134
+ {
1135
+ ${s.join("")}
1136
+ }`}function YE(o,e,t=!1){var s,n,r;const l=P0(o);if(o.colorWrite===!1||((s=o.userData)==null?void 0:s.isShadowCatcherMaterial)||((n=o.userData)==null?void 0:n.isLightBlendMaterial)){const v=o.userData.isLightBlendMaterial||o.userData.isShadowCatcherMaterial?"ND_realitykit_shadowreceiver_surfaceshader":"ND_realitykit_occlusion_surfaceshader";return`
1137
+
1138
+ def Material "${l}" ${o.name?`(
1139
+ displayName = "${o.name}"
1140
+ )`:""}
1141
+ {
1142
+ token outputs:mtlx:surface.connect = ${Yt}/${l}/Occlusion.outputs:out>
1143
+
1144
+ def Shader "Occlusion"
1145
+ {
1146
+ uniform token info:id = "${v}"
1147
+ token outputs:out
1148
+ }
1149
+ }`}const c=" ",h=[],d=[],u=new Set;function p(v){var _;return Os(v.name)+"_"+(((_=v.source)==null?void 0:_.id)??v.id)}function g(v,_,w=void 0,S=void 0){const k=p(v),M=k+(S!==void 0&&S!==1?"_"+S:""),T=t&&S!==void 0&&S!==1,L=T?new ye(1,1,1,S):void 0;S===void 0&&(S=1),T&&(S=1),L&&L.w<=.05&&(L.w=.05),e[M]={texture:v,scale:L};const B=v.channel>0?"st"+v.channel:"st";u.add(v.channel);const z=j1.includes(v.format),D={1e3:"repeat",1001:"clamp",1002:"mirror"},V=v.repeat.clone(),$=v.offset.clone(),U=v.rotation,j=Math.sin(U),Q=Math.cos(U);$.y=1-$.y-V.y,t?(V.x===0&&(V.x=1e-4),V.y===0&&(V.y=1e-4),$.x=$.x/V.x,$.y=$.y/V.y,$.x+=j/V.x,$.y+=Q-1):($.x+=j*V.x,$.y+=(1-Q)*V.y);const J=V.x!=1||V.y!=1||$.x!=0||$.y!=0||U!=0,oe=`${Yt}/${l}/${"uvReader_"+B}.outputs:result>`,re=`${Yt}/${l}/Transform2d_${_}.outputs:result>`,ge=_!=="normal"&&w&&(w.r!==1||w.g!==1||w.b!==1||S!==1)||!1,je=_==="normal",$e=o instanceof vt&&o.normalScale?o.normalScale.x*2:2,ms=$e.toFixed(Ae),gs=(-1*($e/2)).toFixed(Ae),Ul=(1-$e).toFixed(Ae);return`
1150
+ ${J?`def Shader "Transform2d_${_}" (
1151
+ sdrMetadata = {
1152
+ string role = "math"
1153
+ }
1154
+ )
1155
+ {
1156
+ uniform token info:id = "UsdTransform2d"
1157
+ float2 inputs:in.connect = ${oe}
1158
+ float2 inputs:scale = ${L1(V)}
1159
+ float2 inputs:translation = ${L1($)}
1160
+ float inputs:rotation = ${(U/Math.PI*180).toFixed(Ae)}
1161
+ float2 outputs:result
1162
+ }
1163
+ `:""}
1164
+ def Shader "${k}_${_}"
1165
+ {
1166
+ uniform token info:id = "UsdUVTexture"
1167
+ asset inputs:file = @textures/${M}.${z?"png":"jpg"}@
1168
+ token inputs:sourceColorSpace = "${v.colorSpace==="srgb"?"sRGB":"raw"}"
1169
+ float2 inputs:st.connect = ${J?re:oe}
1170
+ ${ge?`
1171
+ float4 inputs:scale = (${w?w.r+", "+w.g+", "+w.b:"1, 1, 1"}, ${S})
1172
+ `:""}
1173
+ ${je?`
1174
+ float4 inputs:scale = (${ms}, ${ms}, ${ms}, 1)
1175
+ float4 inputs:bias = (${gs}, ${gs}, ${Ul}, 0)
1176
+ `:""}
1177
+ token inputs:wrapS = "${D[v.wrapS]}"
1178
+ token inputs:wrapT = "${D[v.wrapT]}"
1179
+ float outputs:r
1180
+ float outputs:g
1181
+ float outputs:b
1182
+ float3 outputs:rgb
1183
+ ${o.transparent||o.alphaTest>0?"float outputs:a":""}
1184
+ }`}let f=o.transparent||o.alphaTest?o.opacity:1,y=!1,b=!1;if(o instanceof Am&&o.transmission!==void 0&&(f*=1-o.transmission*(1-o.roughness*.5)),o.map?(h.push(`${c}color3f inputs:diffuseColor.connect = ${Yt}/${l}/${p(o.map)}_diffuse.outputs:rgb>`),o instanceof Me&&o.transparent&&o.alphaTest==0&&t?(h.push(`${c}float inputs:opacity.connect = ${Yt}/${l}/${p(o.map)}_diffuse.outputs:a>`),y=!0,h.push(`${c}float inputs:opacityThreshold = ${1e-10}`),b=!0):o.transparent?(h.push(`${c}float inputs:opacity.connect = ${Yt}/${l}/${p(o.map)}_diffuse.outputs:a>`),y=!0):o.alphaTest>0&&(h.push(`${c}float inputs:opacity.connect = ${Yt}/${l}/${p(o.map)}_diffuse.outputs:a>`),y=!0,h.push(`${c}float inputs:opacityThreshold = ${o.alphaTest}`),b=!0),d.push(g(o.map,"diffuse",o.color,f))):h.push(`${c}color3f inputs:diffuseColor = ${I1(o.color)}`),o.alphaHash&&t&&(b?console.warn("Opacity threshold for "+o.name+" was already connected. Skipping alphaHash opacity threshold."):(h.push(`${c}float inputs:opacityThreshold = 0.0000000001`),b=!0)),o.aoMap&&(h.push(`${c}float inputs:occlusion.connect = ${Yt}/${l}/${p(o.aoMap)}_occlusion.outputs:r>`),d.push(g(o.aoMap,"occlusion"))),o.alphaMap?(h.push(`${c}float inputs:opacity.connect = ${Yt}/${l}/${p(o.alphaMap)}_opacity.outputs:r>`),h.push(`${c}float inputs:opacityThreshold = 0.0000000001`),y=!0,b=!0,d.push(g(o.alphaMap,"opacity",new ae(1,1,1),f))):(y?console.warn("Opacity for "+o.name+" was already connected. Skipping default opacity."):(h.push(`${c}float inputs:opacity = ${f}`),y=!0),o.alphaTest>0&&(b?console.warn("Opacity threshold for "+o.name+" was already connected. Skipping default opacity threshold."):(h.push(`${c}float inputs:opacityThreshold = ${o.alphaTest}`),b=!0))),o instanceof vt){if(o.emissiveMap){h.push(`${c}color3f inputs:emissiveColor.connect = ${Yt}/${l}/${p(o.emissiveMap)}_emissive.outputs:rgb>`);const v=o.emissive.clone();v.multiplyScalar(o.emissiveIntensity),d.push(g(o.emissiveMap,"emissive",v))}else if(((r=o.emissive)==null?void 0:r.getHex())>0){const v=o.emissive.clone();v.multiplyScalar(o.emissiveIntensity),h.push(`${c}color3f inputs:emissiveColor = ${I1(v)}`)}o.normalMap&&(h.push(`${c}normal3f inputs:normal.connect = ${Yt}/${l}/${p(o.normalMap)}_normal.outputs:rgb>`),d.push(g(o.normalMap,"normal"))),o.roughnessMap&&o.roughness===1?(h.push(`${c}float inputs:roughness.connect = ${Yt}/${l}/${p(o.roughnessMap)}_roughness.outputs:g>`),d.push(g(o.roughnessMap,"roughness"))):h.push(`${c}float inputs:roughness = ${o.roughness!==void 0?o.roughness:1}`),o.metalnessMap&&o.metalness===1?(h.push(`${c}float inputs:metallic.connect = ${Yt}/${l}/${p(o.metalnessMap)}_metallic.outputs:b>`),d.push(g(o.metalnessMap,"metallic"))):h.push(`${c}float inputs:metallic = ${o.metalness!==void 0?o.metalness:0}`)}return o instanceof Am&&(h.push(`${c}float inputs:clearcoat = ${o.clearcoat}`),h.push(`${c}float inputs:clearcoatRoughness = ${o.clearcoatRoughness}`),h.push(`${c}float inputs:ior = ${o.ior}`),!o.transparent&&!(o.alphaTest>0)&&o.transmissionMap&&(h.push(`${c}float inputs:opacity.connect = ${Yt}/${l}/${p(o.transmissionMap)}_transmission.outputs:r>`),d.push(g(o.transmissionMap,"transmission")))),u.size>2?console.warn("USDZExporter: Material "+o.name+" uses more than 2 UV channels. Currently, only UV0 and UV1 are supported."):u.size===2&&(!u.has(0)||!u.has(1))&&console.warn("USDZExporter: Material "+o.name+" uses UV channels other than 0 and 1. Currently, only UV0 and UV1 are supported."),`
1185
+
1186
+ def Material "${l}" ${o.name?`(
1187
+ displayName = "${f1(o.name)}"
1188
+ )`:""}
1189
+ {
1190
+ token outputs:surface.connect = ${Yt}/${l}/PreviewSurface.outputs:surface>
1191
+
1192
+ def Shader "PreviewSurface"
1193
+ {
1194
+ uniform token info:id = "UsdPreviewSurface"
1195
+ ${h.join(`
1196
+ `)}
1197
+ int inputs:useSpecularWorkflow = ${o instanceof Me?"1":"0"}
1198
+ token outputs:surface
1199
+ }
1200
+ ${d.length>0?`
1201
+ ${u.has(0)?`
1202
+ def Shader "uvReader_st"
1203
+ {
1204
+ uniform token info:id = "UsdPrimvarReader_float2"
1205
+ token inputs:varname = "st"
1206
+ float2 inputs:fallback = (0.0, 0.0)
1207
+ float2 outputs:result
1208
+ }
1209
+ `:""}
1210
+ ${u.has(1)?`
1211
+ def Shader "uvReader_st1"
1212
+ {
1213
+ uniform token info:id = "UsdPrimvarReader_float2"
1214
+ token inputs:varname = "st1"
1215
+ float2 inputs:fallback = (0.0, 0.0)
1216
+ float2 outputs:result
1217
+ }
1218
+ `:""}
1219
+ ${d.join(`
1220
+ `)}`:""}
1221
+ }`}function I1(o){return`(${o.r}, ${o.g}, ${o.b})`}function L1(o){return`(${o.x}, ${o.y})`}const j1=[1023,33777,33778,33779,35842,35843,37496,37808,37809,37810,37811,37812,37813,37814,37815,37816,37817,37818,37819,37820,37821,36492];C("debugusdz");const D1=class bC{constructor(e,t,s){a(this,"id"),a(this,"trigger"),a(this,"action"),a(this,"exclusive",!1),this.id="Behavior_"+Os(e)+"_"+bC.global_id++,this.trigger=t,this.action=s}makeExclusive(e){return this.exclusive=e,this}writeTo(e,t,s){if(!this.trigger||!this.action)return;s.beginBlock(`def Preliminary_Behavior "${this.id}"`);let n="";if(Array.isArray(this.trigger)){n="[";for(let r=0;r<this.trigger.length;r++){const l=this.trigger[r];n+="<"+l.id+">",r+1<this.trigger.length&&(n+=", ")}n+="]"}else n=`<${this.trigger.id}>`;if(s.appendLine(`rel triggers = ${n}`),s.appendLine(`rel actions = <${this.action.id}>`),s.appendLine(`uniform bool exclusive = ${this.exclusive?1:0}`),s.appendLine(),Array.isArray(this.trigger))for(const r of this.trigger)r.writeTo(t,s),s.appendLine();else this.trigger.writeTo(t,s);s.appendLine(),this.action.writeTo(t,s),s.closeBlock()}};a(D1,"global_id",0);let Zt=D1;const al=new Set;function R0(o,e){var t,s;let n="";if(Array.isArray(o)){al.clear();let r="[ ";for(let l=0;l<o.length;l++){let c=o[l];if(!c){console.warn("Invalid target object in behavior",o+". Is the object exported?");continue}if(typeof c=="string"){if(al.has(c))continue;r+=c,al.add(c)}else if(typeof c=="object"){if(c.isObject3D&&(c=e.findById(c.uuid),!c)){console.warn("Invalid target object in behavior",o+". Is the object exported?");continue}const h=(t=c.getPath)==null?void 0:t.call(c);if(al.has(h))continue;r+=h,al.add(h)}l+1<o.length&&(r+=", ")}r+=" ]",n=r,al.clear()}else if(typeof o=="object"){const r=o;if(r.isObject3D&&(o=e.findById(r.uuid)),!o)throw console.error("Invalid target object in behavior, the target object is likely missing from USDZ export. Is the object exported?",r),new Error(`Invalid target object in behavior, the target object is likely missing from USDZ export. Please report a bug. uuid: ${r.uuid}.`);n=(s=o.getPath)==null?void 0:s.call(o)}return n}const B1=class _C{constructor(e,t){a(this,"id"),a(this,"targetId"),a(this,"tokenId"),a(this,"type"),a(this,"distance"),e&&(this.targetId=e),t?this.id=t:this.id="Trigger_"+_C.global_id++}writeTo(e,t){t.beginBlock(`def Preliminary_Trigger "${this.id}"`),this.targetId&&(typeof this.targetId!="string"&&(this.targetId=R0(this.targetId,e)),t.appendLine("rel affectedObjects = "+this.targetId)),this.tokenId&&t.appendLine(`token info:id = "${this.tokenId}"`),this.type&&t.appendLine(`token type = "${this.type}"`),typeof this.distance=="number"&&t.appendLine(`double distance = ${this.distance}`),t.closeBlock()}};a(B1,"global_id",0);let ll=B1;function F1(o,e={direct:!0,indirect:!0}){const t=pi.createEmpty();t.name="InputTarget_"+t.name,t.displayName=void 0,t.type="RealityKitComponent",t.onSerialize=s=>{s.appendLine("bool allowsDirectInput = "+(e.direct?1:0)),s.appendLine("bool allowsIndirectInput = "+(e.indirect?1:0)),s.appendLine('uniform token info:id = "RealityKit.InputTarget"')},o.add(t)}class Et{static sceneStartTrigger(){if(this.__sceneStartTrigger!==void 0)return this.__sceneStartTrigger;const e=new ll(void 0,"SceneStart");return e.tokenId="SceneTransition",e.type="enter",this.__sceneStartTrigger=e,e}static tapTrigger(e,t={direct:!0,indirect:!0}){const s=new ll(e);if(Array.isArray(e)&&e.length>1)for(const n of e)n instanceof pi&&F1(n,t);else e instanceof pi&&F1(e,t);return s.tokenId="TapGesture",s}static isTapTrigger(e){return e?.tokenId==="TapGesture"}static proximityToCameraTrigger(e,t){const s=new ll(e);return s.tokenId="ProximityToCamera",s.distance=t,s}}a(Et,"__sceneStartTrigger");class zo{constructor(e,t){a(this,"id"),a(this,"actions"),a(this,"loops",0),a(this,"performCount",1),a(this,"type","serial"),a(this,"multiplePerformOperation"),this.id=e,this.actions=t}static getId(){return this.global_id++}addAction(e){return this.actions.push(e),this}makeParallel(){return this.type="parallel",this}makeSequence(){return this.type="serial",this}makeLooping(){return this.loops=1,this.performCount=0,this}makeRepeat(e){return this.performCount=e,this}writeTo(e,t){t.beginBlock(`def Preliminary_Action "${this.id}"`),t.beginArray("rel actions");for(const s of this.actions){if(!s)continue;const n=s===this.actions[this.actions.length-1];t.appendLine("<"+s.id+">"+(n?"":", "))}t.closeArray(),t.appendLine(),t.appendLine('token info:id = "Group"'),t.appendLine(`bool loops = ${this.loops}`),t.appendLine(`int performCount = ${this.loops>0?0:Math.max(0,this.performCount)}`),t.appendLine(`token type = "${this.type}"`),typeof this.multiplePerformOperation=="string"&&t.appendLine(`token multiplePerformOperation = "${this.multiplePerformOperation}"`),t.appendLine();for(const s of this.actions)s&&(s.writeTo(e,t),t.appendLine());t.closeBlock()}}a(zo,"global_id",0);const U1=class mv{constructor(e,t){a(this,"id"),a(this,"tokenId"),a(this,"affectedObjects"),a(this,"easeType"),a(this,"motionType"),a(this,"duration"),a(this,"moveDistance"),a(this,"style"),a(this,"type"),a(this,"front"),a(this,"up"),a(this,"start"),a(this,"animationSpeed"),a(this,"reversed"),a(this,"pingPong"),a(this,"xFormTarget"),a(this,"audio"),a(this,"gain"),a(this,"auralMode"),a(this,"multiplePerformOperation"),a(this,"velocity"),a(this,"comment"),a(this,"animationName"),e&&(this.affectedObjects=e),t?this.id=t:this.id="Action",this.id+="_"+mv.global_id++}clone(){const e=new mv,t=e.id;return Object.assign(e,this),e.id=t,e}writeTo(e,t){t.beginBlock(`def Preliminary_Action "${this.id}"`),this.comment&&t.appendLine(`# ${this.comment}`),this.affectedObjects&&(typeof this.affectedObjects!="string"&&(this.affectedObjects=R0(this.affectedObjects,e)),t.appendLine("rel affectedObjects = "+this.affectedObjects)),typeof this.duration=="number"&&(typeof this.animationSpeed=="number"&&this.animationSpeed!==1?t.appendLine(`double duration = ${this.duration/this.animationSpeed} `):t.appendLine(`double duration = ${this.duration} `)),this.easeType&&t.appendLine(`token easeType = "${this.easeType}"`),this.tokenId&&t.appendLine(`token info:id = "${this.tokenId}"`),this.tokenId==="ChangeScene"&&t.appendLine("rel scene = </StageRoot/Scenes/Scene>"),this.motionType!==void 0&&t.appendLine(`token motionType = "${this.motionType}"`),typeof this.moveDistance=="number"&&t.appendLine(`double moveDistance = ${this.moveDistance} `),this.style&&t.appendLine(`token style = "${this.style}"`),this.type&&t.appendLine(`token type = "${this.type}"`),this.front&&t.appendLine(`vector3d front = (${this.front.x}, ${this.front.y}, ${this.front.z})`),this.up&&t.appendLine(`vector3d upVector = (${this.up.x}, ${this.up.y}, ${this.up.z})`),typeof this.start=="number"&&t.appendLine(`double start = ${this.start} `),typeof this.animationSpeed=="number"&&t.appendLine(`double animationSpeed = ${this.animationSpeed.toFixed(2)} `),typeof this.reversed=="boolean"&&t.appendLine(`bool reversed = ${this.reversed}`),typeof this.pingPong=="boolean"&&t.appendLine(`bool reverses = ${this.pingPong}`),this.xFormTarget&&(typeof this.xFormTarget!="string"&&(this.xFormTarget=R0(this.xFormTarget,e)),t.appendLine(`rel xformTarget = ${this.xFormTarget}`)),typeof this.audio=="string"&&t.appendLine(`asset audio = @${this.audio}@`),typeof this.gain=="number"&&t.appendLine(`double gain = ${this.gain}`),typeof this.auralMode=="string"&&t.appendLine(`token auralMode = "${this.auralMode}"`),typeof this.multiplePerformOperation=="string"&&t.appendLine(`token multiplePerformOperation = "${this.multiplePerformOperation}"`),typeof this.velocity=="object"&&t.appendLine(`vector3d velocity = (${this.velocity.x}, ${this.velocity.y}, ${this.velocity.z})`),t.closeBlock()}};a(U1,"global_id",0);let ks=U1;class ps{constructor(e,t,s){a(this,"x",0),a(this,"y",0),a(this,"z",0),this.x=e,this.y=t,this.z=s}static get up(){return new ps(0,1,0)}static get right(){return new ps(1,0,0)}static get forward(){return new ps(0,0,1)}static get back(){return new ps(0,0,-1)}static get zero(){return new ps(0,0,0)}}class ve{static sequence(...e){return new zo("Group_"+zo.getId(),e).makeSequence()}static parallel(...e){return new zo("Group_"+zo.getId(),e).makeParallel()}static fadeAction(e,t,s){const n=new ks(e);return n.tokenId="Visibility",n.type=s?"show":"hide",n.duration=t,n.style="basic",n.motionType="none",n.moveDistance=0,n.easeType="none",n}static startAnimationAction(e,t,s=!1,n=!1){const r=new ks(e);r.tokenId="StartAnimation";const l=t.start,c=t.duration,h=t.speed,d=t.clipName;if(r.comment=`Animation: ${d}, start=${l*60}, length=${c*60}, end=${(l+c)*60}`,r.animationName=d,r.start=l,r.duration=c,r.animationSpeed=h,r.reversed=s,r.pingPong=n,r.multiplePerformOperation="allow",s&&(r.start-=c),n){r.pingPong=!1;const u=r.clone();return u.reversed=!s,u.start=r.start,u.reversed&&(u.start-=c),ve.sequence(r,u)}return r}static waitAction(e){const t=new ks;return t.tokenId="Wait",t.duration=e,t.motionType=void 0,t}static lookAtCameraAction(e,t,s,n){const r=new ks(e);return r.tokenId="LookAtCamera",r.duration=t===void 0?9999999999999:t,r.front=s??ps.forward,r.up=n??ps.up,r}static emphasize(e,t,s="bounce",n=1,r="basic"){const l=new ks(e);return l.tokenId="Emphasize",l.duration=t,l.style=r??"basic",l.motionType=s,l.moveDistance=n,l}static transformAction(e,t,s,n,r="inout"){const l=new ks(e);return l.tokenId="Transform",l.duration=s,l.duration=Math.max(1e-6,s),l.type=n,l.easeType=s>0?r:"none",Array.isArray(t)&&console.error("Transform target must not be an array",t),l.xFormTarget=t,l}static playAudioAction(e,t,s="play",n=1,r="spatial"){const l=new ks(e);return l.tokenId="Audio",l.type=s,l.audio=t,l.gain=n,l.auralMode=r,l.multiplePerformOperation="allow",l}static impulseAction(e,t){const s=new ks(e);return s.tokenId="Impulse",s.velocity=t,s}}class KE{constructor(e){a(this,"object"),a(this,"model"),this.object=e}get id(){return this.object.uuid}apply(e){if(!this.model&&(this.model=e.findById(this.object.uuid),!this.model)){console.error("could not find model with id "+this.object.uuid);return}this.onApply(e)}}class T0 extends KE{constructor(e,t,s,n){super(e),a(this,"matrix"),a(this,"material"),a(this,"geometry"),a(this,"_enableAction"),a(this,"_disableAction"),this.matrix=t,this.material=s,this.geometry=n}onApply(e){var t,s;const n=this.model;if(!n)return;(t=n.parent)!=null&&t.isDynamic||pi.createEmptyParent(n);const r=n.clone();this.matrix&&r.setMatrix(this.matrix),this.material&&(r.material=this.material),this.geometry&&(r.geometry=this.geometry),(s=n.parent)==null||s.add(r)}enable(){return this._enableAction?this._enableAction:(this._enableAction=ve.fadeAction(this.object,0,!0),this._enableAction)}disable(){return this._disableAction?this._disableAction:(this._disableAction=ve.fadeAction(this.object,0,!1),this._disableAction)}}class z1{constructor(e){a(this,"actions"),a(this,"sortedActions"),this.actions=[...e]}organize(){this.sortedActions={};for(const e of this.actions){const t=e.id;this.sortedActions[t]||(this.sortedActions[t]=[]),this.sortedActions[t].push(e)}}getActions(e){return this.sortedActions||this.organize(),this.sortedActions[e.uuid]}}const dn=C("debugusdzanimation"),E0=C("debugusdzanimationserialization");class ur{constructor(e,t,s){a(this,"_start"),a(this,"ext"),a(this,"root"),a(this,"_nearestAnimatedRoot"),a(this,"clip"),a(this,"speed"),this.ext=e,this.root=t,this.clip=s,this._nearestAnimatedRoot=this.getNearestAnimatedRoot()}get start(){return this._start===void 0&&(this._start=this.ext.getStartTimeByClip(this.clip)),this._start}get duration(){var e;return((e=this.clip)==null?void 0:e.duration)??ut.restPoseClipDuration}get nearestAnimatedRoot(){return this._nearestAnimatedRoot}get clipName(){var e;return((e=this.clip)==null?void 0:e.name)??"rest"}static isDescendantOf(e,t){let s=t;if(!s||!e)return!1;for(;s;){if(!s)return!1;if(s===e)return!0;s=s.parent}return!1}getNearestAnimatedRoot(){var e;let t;try{for(const s of((e=this.clip)==null?void 0:e.tracks)??[]){const n=wa.parseTrackName(s.name);let r=wa.findNode(this.root,n.nodeName);if(r)if(!t)t=r;else{if(r===t||ur.isDescendantOf(t,r))continue;if(!ur.isDescendantOf(r,t)){for(;!ur.isDescendantOf(r,t)&&r.parent;)r=r.parent;ur.isDescendantOf(r,t)||console.error("USDZExporter: Animation clip targets multiple roots that are not parent/child. Please report a bug",this.root,this.clip,t,r)}t=r}}}catch(s){console.error("USDZExporter: Exception when trying to find nearest animated root. Please report a bug",s),t=void 0}return t}}const rp=class bm{constructor(e,t,s){if(a(this,"clip"),a(this,"pos"),a(this,"rot"),a(this,"scale"),a(this,"root"),a(this,"target"),a(this,"duration",0),a(this,"useRootMotion",!1),this.root=e,this.target=t,this.clip=s,s?this.duration=s.duration:this.duration=bm.restPoseClipDuration,s&&s.tracks){const r=Math.max(...s.tracks.map(l=>l.times[l.times.length-1]));r!==this.duration&&(console.warn("USDZExporter: Animation clip duration does not match the maximum time value in the tracks.",s,r,this.duration),this.duration=r)}const n=P.getComponent(e,Mt);n&&(this.useRootMotion=n.applyRootMotion)}addTrack(e){var t,s;if(!this.clip){console.error("This is a rest clip but you're trying to add tracks to it \u2013 this is likely a bug");return}e.name.endsWith("position")?this.pos=e:e.name.endsWith("quaternion")?this.rot=e:e.name.endsWith("scale")?this.scale=e:(e.name.endsWith("activeSelf")?console.warn("[USDZ] Animation of enabled/disabled state is not supported for USDZ export and will NOT be exported: "+e.name+" on "+(((t=this.root)==null?void 0:t.name)??this.target.name)+". Animate scale 0/1 instead."):console.warn("[USDZ] Animation track type not supported for USDZ export and will NOT be exported: "+e.name+" on "+(((s=this.root)==null?void 0:s.name)??this.target.name)+". Only .position, .rotation, .scale are supported."),F()&&be("[USDZ] Some animations can't be exported. See console for details."))}getFrames(){var e,t,s,n,r,l;return this.clip?Math.max(((t=(e=this.pos)==null?void 0:e.times)==null?void 0:t.length)??0,((n=(s=this.rot)==null?void 0:s.times)==null?void 0:n.length)??0,((l=(r=this.scale)==null?void 0:r.times)==null?void 0:l.length)??0):2}getDuration(){return this.duration}getSortedTimesArray(e=!0,t=!0,s=!0){var n,r,l;if(!this.clip)return[0,this.duration];const c=(n=this.pos)==null?void 0:n.times,h=(r=this.rot)==null?void 0:r.times,d=(l=this.scale)==null?void 0:l.times,u=[];if(e&&c)for(const p of c)u.push(p);if(t&&h)for(const p of h)u.push(p);if(s&&d)for(const p of d)u.push(p);return u.includes(0)||u.push(0),u.sort((p,g)=>p-g),[...new Set(u)]}*getValues(e,t=!0,s=!0,n=!0){var r,l,c;const h=new x,d=new H,u=new x(1,1,1),p=this.target,g=t?(r=this.pos)==null?void 0:r.createInterpolant():void 0,f=s?(l=this.rot)==null?void 0:l.createInterpolant():void 0,y=n?(c=this.scale)==null?void 0:c.createInterpolant():void 0;g||h.set(p.position.x,p.position.y,p.position.z),f||d.set(p.quaternion.x,p.quaternion.y,p.quaternion.z,p.quaternion.w),y||u.set(p.scale.x,p.scale.y,p.scale.z),g&&g.valueSize!==3&&(g.valueSize=3),f&&f.valueSize!==4&&(f.valueSize=4),y&&y.valueSize!==3&&(y.valueSize=3);const b=0;for(let v=0-b;v<e.length+b;v++){let _=0,w=0;if(v<0?(_=e[0],w=_-bm.animationDurationPadding/2+1/60):v>=e.length?(_=e[e.length-1],w=_+bm.animationDurationPadding/2-1/60):(_=e[v],w=_),g){const S=g.evaluate(_);h.set(S[0],S[1],S[2])}if(f){const S=f.evaluate(_);d.set(S[0],S[1],S[2],S[3])}if(y){const S=y.evaluate(_);u.set(S[0],S[1],S[2])}if(this.useRootMotion&&p===this.root){const S=new se;S.compose(h,d,u),S.multiply(p.matrix),S.decompose(h,d,u)}yield{time:w,translation:h,rotation:d,scale:u,index:v}}}};a(rp,"frameRate",60),a(rp,"animationDurationPadding",6/60),a(rp,"restPoseClipDuration",6/60);let ut=rp;class ap{constructor(e){a(this,"dict",new Map),a(this,"rootTargetMap",new Map),a(this,"rootAndClipToRegisteredAnimationMap",new Map),a(this,"rootToRegisteredClip",new Map),a(this,"lastClipEndTime",0),a(this,"clipToStartTime",new Map),a(this,"clipToHoldClip",new Map),a(this,"serializers",[]),a(this,"injectRestPoses",!1),a(this,"injectImplicitBehaviours",!1),this.injectRestPoses=e,this.injectImplicitBehaviours=e}get extensionName(){return"animation"}get animationData(){return this.dict}get registeredClips(){return this.clipToStartTime.keys()}get animatedRoots(){return this.rootTargetMap.keys()}get holdClipMap(){return this.clipToHoldClip}getStartTimeCode(){return!this.injectRestPoses||this.rootAndClipToRegisteredAnimationMap.size===0?0:(ut.restPoseClipDuration+ut.animationDurationPadding)*60}getEndTimeCode(){let e=0;for(const[t,s]of this.rootAndClipToRegisteredAnimationMap){const n=s.start+s.duration;n>e&&(e=n)}return e*60}getClipCount(e){var t;return((t=this.rootToRegisteredClip.get(e))==null?void 0:t.length)??0??0}getStartTimeByClip(e){return e?this.clipToStartTime.has(e)?this.clipToStartTime.get(e):(console.error("USDZExporter: Missing start time for clip \u2013 please report a bug.",e),0):0}registerAnimation(e,t){var s;if(!e)return null;this.rootTargetMap.has(e)||this.rootTargetMap.set(e,[]);const n=e.uuid+(t?.uuid??"-rest");if(this.rootAndClipToRegisteredAnimationMap.has(n))return this.rootAndClipToRegisteredAnimationMap.get(n);dn&&console.log("registerAnimation",e,t);const r=this.injectRestPoses?1:0,l=(((s=this.rootToRegisteredClip.get(e))==null?void 0:s.length)??0)+r,c=this.rootTargetMap.get(e),h=new Set(c);if(t&&t.tracks)for(const u of t.tracks){const p=wa.parseTrackName(u.name),g=wa.findNode(e,p.nodeName);if(!g){console.warn("no object found for track",u.name,"using "+e.name+" instead");continue}this.dict.has(g)||this.dict.set(g,[]);const f=this.dict.get(g);if(!f){console.warn("no transform data found for target ",g,"at slot "+l+", this is likely a bug");continue}h.delete(g),this.injectRestPoses&&!f[0]&&(console.log("Injecting rest pose",g,t,"at slot",l),f[0]=new ut(null,g,null));let y=f[l];y||(y=new ut(e,g,t),f[l]=y),y.addTrack(u),c!=null&&c.includes(g)||c==null||c.push(g)}dn&&console.log("Unregistered nodes for this clip",h,"clip",t,"at slot",l,"for root",e,"targets",c);for(const u of h){const p=this.dict.get(u);if(!p)continue;if(this.injectRestPoses&&!p[0]){console.warn("Adding rest pose for ",u,t,"at slot",l,"This is likely a bug, should have been added earlier.");const f=new ut(null,u,null);p[0]=f}let g=p[l];g||(dn&&console.log("Adding padding clip for ",u,t,"at slot",l),g=new ut(e,u,t),p[l]=g)}const d=new ur(this,e,t);if(this.rootAndClipToRegisteredAnimationMap.set(n,d),dn&&console.log({root:e,clip:t,info:d}),t){const u=this.rootToRegisteredClip.get(e);if(u?u.push(t):this.rootToRegisteredClip.set(e,[t]),!this.clipToStartTime.get(t)){this.lastClipEndTime==null&&(this.lastClipEndTime=ut.restPoseClipDuration);let p=this.lastClipEndTime+ut.animationDurationPadding,g=p+t.duration;const f=Math.round(p*60)/60,y=Math.round(g*60)/60;Math.abs(f-p)<.01&&(p=f),Math.abs(y-g)<.01&&(g=y),p=Math.ceil(p),g=p+t.duration,this.clipToStartTime.set(t,p),this.lastClipEndTime=g}}return d}onAfterHierarchy(e){dn&&console.log("Animation clips per animation target node",this.dict)}onAfterBuildDocument(e){var t,s;dn&&console.log("Animation data",{dict:this.dict,rootTargetMap:this.rootTargetMap,rootToRegisteredClip:this.rootToRegisteredClip});for(const n of this.rootTargetMap.keys()){const r=this.rootTargetMap.get(n);if(!r)continue;let l;const c=[];for(const h of r){const d=this.dict.get(h);if(!d){console.error("No data found for target on USDZ export \u2013 please report a bug!",h);continue}l===void 0&&(l=d?.length),l!==d?.length&&console.error("Different array lengths for targets \u2013 please report a bug!",d);for(let u=0;u<d.length;u++){let p=d[u];if(!p){const f=u-(this.injectRestPoses?1:0);d[u]=new ut(null,h,this.rootToRegisteredClip.get(n)[f]),p=d[u]}const g=p.getDuration();if(c[u]===void 0)c[u]=g;else if(c[u]!==g){console.error("Error during UDSZ export: Encountered different animation durations for animated targets. Please report a bug!",{datas:d,target:h}),c[u]=g;continue}}}}for(const n of this.serializers){const r=(t=n.model)==null?void 0:t.parent,l=r?.isDynamic===!0;E0&&console.log(l,(s=n.model)==null?void 0:s.parent),l&&n.registerCallback(r)}}onExportObject(e,t,s){P.foreachComponent(e,r=>{const l=r;typeof l.createAnimation=="function"&&l.createAnimation(this,t,s)},!1);const n=new ZE(e,this);this.serializers.push(n),n.registerCallback(t)}}class ZE{constructor(e,t){a(this,"model"),a(this,"object"),a(this,"animationData"),a(this,"ext"),a(this,"callback"),this.object=e,this.animationData=t.animationData,this.ext=t}registerCallback(e){this.model&&this.callback&&this.model.removeEventListener("serialize",this.callback),this.callback||(this.callback=this.onSerialize.bind(this)),E0&&console.log("REPARENT",e),this.model=e,this.callback&&this.model.addEventListener("serialize",this.callback)}skinnedMeshExport(e,t,s){var n;const r=this.model,l=this.animationData;if(r&&r.skinnedMesh){let c=function(U){const j=[];for(const[Q,J]of U){let oe=`${Q} : [`;const re=[];for(const ge of J)re.push(`(${ue(ge.x)}, ${ue(ge.y)}, ${ue(ge.z)})`);oe=oe.concat(re.join(", ")),oe=oe.concat("],"),j.push(oe)}return j},h=function(U){const j=[];for(const[Q,J]of U){let oe=`${Q} : [`;const re=[];for(const ge of J)re.push(`(${ue(ge.w)}, ${ue(ge.x)}, ${ue(ge.y)}, ${ue(ge.z)})`);oe=oe.concat(re.join(", ")),oe=oe.concat("],"),j.push(oe)}return j},d=function(U){let j,Q=!0;const J=new Map;for(const[re,ge]of U){j===void 0&&(j=ge.length),j!==ge.length&&(Q=!1);let je=0;for(const $e of ge)je++,$e||(J.has(re)||J.set(re,[]),J.get(re).push(je))}dn&&console.log("Bone count: ",U.size,"TransformData entries per bone: ",j,"Undefined bone entries: ",J),console.assert(Q,"All bones should have the same number of TransformData entries",U),console.assert(J.size===0,"All TransformData entries should be set",J);const oe=[];for(const[re,ge]of U)for(let je=0;je<ge.length;je++){const $e=ge[je],ms=s.getStartTimeByClip($e.clip);oe.length<=je&&oe.push({pos:[],rot:[],scale:[],timeOffset:ms});const gs=oe[je];gs.pos.push(...$e.getSortedTimesArray(!0,!1,!1)),gs.rot.push(...$e.getSortedTimesArray(!1,!0,!1)),gs.scale.push(...$e.getSortedTimesArray(!1,!1,!0))}for(const re of oe)re.pos.sort((ge,je)=>ge-je),re.rot.sort((ge,je)=>ge-je),re.scale.sort((ge,je)=>ge-je),re.pos=[...new Set(re.pos)],re.rot=[...new Set(re.rot)],re.scale=[...new Set(re.scale)];return oe},u=function(U,j,Q){const J=new Map,oe=new Map,re=new Map,ge=j.length;for(const je of Q){const $e=U.get(je);let ms;$e?console.assert($e.length===ge,"We should have the same number of TransformData entries for each bone",$e,j):ms=new ut(null,je,null);for(let gs=0;gs<ge;gs++){const Ul=$e?$e[gs]:ms,va=j[gs];for(const{time:zl,translation:Nl}of Ul.getValues(va.pos,!0,!1,!1)){const fs=(zl+va.timeOffset)*60;J.has(fs)||J.set(fs,new Array),J.get(fs).push(Nl.clone())}for(const{time:zl,rotation:Nl}of Ul.getValues(va.rot,!1,!0,!1)){const fs=(zl+va.timeOffset)*60;oe.has(fs)||oe.set(fs,new Array),oe.get(fs).push(Nl.clone())}for(const{time:zl,scale:Nl}of Ul.getValues(va.scale,!1,!1,!0)){const fs=(zl+va.timeOffset)*60;re.has(fs)||re.set(fs,new Array),re.get(fs).push(Nl.clone())}}}return{position:J.size==0?void 0:J,quaternion:oe.size==0?void 0:oe,scale:re.size==0?void 0:re}},p=function(U){const j=[];for(const Q of U)j.push(`(${ue(Q.x)}, ${ue(Q.y)}, ${ue(Q.z)})`);return j.join(", ")},g=function(U){const j=[];for(const Q of U)j.push(`(${ue(Q.w)}, ${ue(Q.x)}, ${ue(Q.y)}, ${ue(Q.z)})`);return j.join(", ")},f=function(U){const j=new Map;if(dn){const Q=new Array;for(const[J,oe]of l)Q.push(J.uuid+": "+oe.length+" "+oe.map(re=>{var ge;return(ge=re.clip)==null?void 0:ge.uuid.substring(0,6)}).join(" "));console.log(`getPerBoneTransformData
1222
+ `+Q.join(`
1223
+ `))}for(const Q of U){const J=l.get(Q);J&&j.set(Q,J)}return j},y=function(U){const j=f(U),Q=d(j);return u(j,Q,U)};const b=r.skinnedMesh.skeleton,v=new Array,_=[],w=[];for(const U of b.bones){_.push(U),w.push(U.uuid);const j=b.boneInverses[b.bones.indexOf(U)];v.push({bone:U,inverse:j})}let S=1e4;for(;w.length<b.bones.length&&S-- >0;)for(const U of _){const j=U.children;for(const Q of j)if(w.indexOf(Q.uuid)===-1&&b.bones.indexOf(Q)!==-1){_.push(Q),w.push(Q.uuid);const J=b.boneInverses[b.bones.indexOf(Q)];v.push({bone:Q,inverse:J})}}S<=0&&console.error("Failed to sort bones in skinned mesh",r.skinnedMesh,b.bones,w);for(const U of v1(b.bones))v.push({bone:U,inverse:U.matrixWorld.clone().invert()});const k=v[0].bone.parent;k||console.error("No bone parent found for skinned mesh during USDZ export",r.skinnedMesh),v.sort((U,j)=>rl(U.bone,k)>rl(j.bone,k)?1:-1);const M=t.quickLookCompatible,T=[],L=[],B=[],z=[];for(const{bone:U}of v){if(M){const j=U.scale;j.x==0&&(j.x=1e-5),j.y==0&&(j.y=1e-5),j.z==0&&(j.z=1e-5),T.push(new se().compose(U.position,U.quaternion,U.scale))}else T.push(U.matrix.clone());L.push(U.position),B.push(U.quaternion),z.push(U.scale)}const D=v.map(U=>'"'+rl(U.bone,k)+'"').join(", "),V=v.map(U=>T1(U.inverse.clone().invert())).join(", ");e.beginBlock('def Skeleton "Rig"'),e.appendLine(`uniform matrix4d[] bindTransforms = [${V}]`),e.appendLine(`uniform token[] joints = [${D}]`),e.appendLine('uniform token purpose = "guide"'),e.appendLine(`uniform matrix4d[] restTransforms = [${T.map(U=>T1(U)).join(", ")}]`);const $=y(v.map(U=>U.bone));if(dn){let U=1e7,j=0;for(const Q of((n=$.position)==null?void 0:n.keys())??[])U=Math.min(U,Q),j=Math.max(j,Q);console.log("Time samples",U,j,$)}if(e.beginBlock('def SkelAnimation "_anim"'),e.appendLine(`uniform token[] joints = [${D}]`),e.appendLine(`quatf[] rotations = [${g(B)}]`),$&&$.quaternion){e.beginBlock("quatf[] rotations.timeSamples = {","");const U=h($.quaternion);for(const j of U)e.appendLine(j);e.closeBlock()}if(e.appendLine(`half3[] scales = [${p(z)}]`),$&&$.scale){e.beginBlock("half3[] scales.timeSamples = {","");const U=c($.scale);for(const j of U)e.appendLine(j);e.closeBlock()}if(e.appendLine(`float3[] translations = [${p(L)}]`),$&&$.position){e.beginBlock("float3[] translations.timeSamples = {","");const U=c($.position);for(const j of U)e.appendLine(j);e.closeBlock()}e.closeBlock(),e.closeBlock()}}onSerialize(e,t){if(!this.model)return;const s=this.animationData.get(this.object);if(s)for(let u=0;u<s.length;u++)s[u]===void 0&&(s[u]=new ut(null,this.object,null));const n=this.ext;this.skinnedMeshExport(e,t,n);const r=this.object,l=this.model,c=this.animationData.get(r);if(!c||r.isSkinnedMesh)return;E0&&console.log("SERIALIZE",this.model.name,this.object.type,c);const h=Intl.NumberFormat("en-US",{maximumFractionDigits:3,minimumFractionDigits:0,useGrouping:!1});function d(u,p){var g;if(u.some(f=>f&&{position:f.pos,rotation:f.rot,scale:f.scale}[p])){switch(p){case"position":l.needsTranslate=!0,e.beginBlock("double3 xformOp:translate.timeSamples = {","");break;case"rotation":l.needsOrient=!0,e.beginBlock("quatf xformOp:orient.timeSamples = {","");break;case"scale":l.needsScale=!0,e.beginBlock("double3 xformOp:scale.timeSamples = {","");break}for(let f=0;f<u.length;f++){const y=u[f];if(!y)continue;const b=n.getStartTimeByClip(y.clip),v=y.getSortedTimesArray(p==="position",p==="rotation",p==="scale");if(!v||v.length===0){console.error("got an animated object but no time values?",r,y);continue}const _=!y.clip,w=p==="position"&&(y.pos||_),S=p==="rotation"&&(y.rot||_),k=p==="scale"&&(y.scale||_);if(w||S||k){const M=((g=y.clip)==null?void 0:g.name)??"rest",T=y.getDuration();dn&&console.log("Write .timeSamples:",M,b,T,u),e.appendLine("# "+M+": start="+h.format(b*ut.frameRate)+", length="+h.format(T*ut.frameRate)+", frames="+y.getFrames())}if(w)for(const{time:M,translation:T}of y.getValues(v,!0,!1,!1)){const L=`${h.format((b+M)*ut.frameRate)}: (${ue(T.x)}, ${ue(T.y)}, ${ue(T.z)}),`;e.appendLine(L)}if(S)for(const{time:M,rotation:T}of y.getValues(v,!1,!0,!1)){const L=`${h.format((b+M)*ut.frameRate)}: (${ue(T.w)}, ${ue(T.x)}, ${ue(T.y)}, ${ue(T.z)}),`;e.appendLine(L)}if(k)for(const{time:M,scale:T}of y.getValues(v,!1,!1,!0)){const L=`${h.format((b+M)*ut.frameRate)}: (${ue(T.x)}, ${ue(T.y)}, ${ue(T.z)}),`;e.appendLine(L)}}e.closeBlock()}}d(c,"position"),d(c,"rotation"),d(c,"scale")}}const JE=C("debugusdz");class ya{constructor(){a(this,"files",new Array)}static getName(e){var t;const s=e.split(".").pop();let n=(t=e.split(".").slice(0,-1).join(".").split("/").pop())==null?void 0:t.replace(".","_");return n||(n="Audio_"+Math.random().toString(36).substring(2,15)),Os(n)+"."+s}get extensionName(){return"Audio"}onExportObject(e,t,s){const n=P.getComponents(e,ss);if(n.length)for(const r of n){if(!r.clip||typeof r.clip!="string"||!r.playOnAwake)continue;const l=r.clip.split("/").pop()||"Audio",c=ya.getName(r.clip),h=Os(c);if(!this.files.some(d=>d.path===r.clip)){this.files.push({path:r.clip,name:c});const d=c.toLowerCase();s.quickLookCompatible&&!d.endsWith(".mp3")&&!d.endsWith(".wav")&&!d.endsWith(".m4a")&&console.error("Audio file "+r.clip+" from "+r.name+" is not an MP3 or WAV file. QuickLook may not support playing it.")}s.quickLookCompatible||t.addEventListener("serialize",(d,u)=>{d.appendLine(),d.beginBlock(`def SpatialAudio "${h}"`,"(",!1),d.appendLine(`displayName = "${l}"`),d.closeBlock(")"),d.beginBlock(),d.appendLine(`uniform asset filePath = @audio/${c}@`),d.appendLine(`uniform token auralMode = "${r.spatialBlend>0?"spatial":"nonSpatial"}"`),d.appendLine(`uniform token playbackMode = "${r.loop?"loopFromStage":"onceFromStart"}"`),d.appendLine(`uniform float gain = ${r.volume}`),d.closeBlock()})}}async onAfterSerialize(e){for(const t of this.files){const s="audio/"+t.name;if(e.files[s]){JE&&console.warn("Audio file with name "+s+" already exists in the context. Skipping.");continue}const n=await(await(await fetch(t.path)).blob()).arrayBuffer(),r=new Uint8Array(n);e.files[s]=r}}}var eA=Object.defineProperty,Ne=(o,e,t,s)=>{for(var n=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=l(e,t,n)||n);return n&&eA(e,t,n),n};const N1=C("debugusdzbehaviours");function Qc(o){o&&(o.getComponentInParent(qa)||(F()&&console.debug('Raycaster on "'+o.name+'" was automatically added, because no raycaster was found in the parent hierarchy.'),o.addComponent(Li)))}class $r extends I{constructor(){super(...arguments),a(this,"object"),a(this,"target"),a(this,"duration",1),a(this,"relativeMotion",!1),a(this,"coroutine",null),a(this,"targetPos",new x),a(this,"targetRot",new H),a(this,"targetScale",new x)}start(){Qc(this.gameObject)}onPointerClick(e){e.use(),this.coroutine&&this.stopCoroutine(this.coroutine),this.relativeMotion?this.coroutine=this.startCoroutine(this.moveRelative()):this.coroutine=this.startCoroutine(this.moveToTarget())}*moveToTarget(){if(!this.target||!this.object)return;const e=te(this.object).clone(),t=te(this.target).clone(),s=Se(this.object).clone(),n=Se(this.target).clone(),r=Ge(this.object).clone(),l=Ge(this.target).clone(),c=e.distanceTo(t),h=s.angleTo(n),d=r.distanceTo(l);if(c<.01&&h<.01&&d<.01){lt(this.object,t),Qi(this.object,n),ka(this.object,l),this.coroutine=null;return}let u=0,p=0;for(;u<1;)u+=this.context.time.deltaTime/this.duration,u>1&&(u=1),p=u<.5?4*u*u*u:1-Math.pow(-2*u+2,3)/2,this.targetPos.lerpVectors(e,t,p),this.targetRot.slerpQuaternions(s,n,p),this.targetScale.lerpVectors(r,l,p),lt(this.object,this.targetPos),Qi(this.object,this.targetRot),ka(this.object,this.targetScale),yield;this.coroutine=null}*moveRelative(){if(!this.target||!this.object)return;const e=this.object.position.clone(),t=this.object.quaternion.clone(),s=this.object.scale.clone(),n=this.target.position.clone(),r=this.target.quaternion.clone(),l=this.target.scale.clone();n.applyQuaternion(this.object.quaternion),this.targetPos.copy(this.object.position).add(n),this.targetRot.copy(this.object.quaternion).multiply(r),this.targetScale.copy(this.object.scale).multiply(l);let c=0,h=0;for(;c<1;)c+=this.context.time.deltaTime/this.duration,c>1&&(c=1),h=c<.5?4*c*c*c:1-Math.pow(-2*c+2,3)/2,this.object.position.lerpVectors(e,this.targetPos,h),this.object.quaternion.slerpQuaternions(t,this.targetRot,h),this.object.scale.lerpVectors(s,this.targetScale,h),yield;this.coroutine=null}beforeCreateDocument(e){var t;if(this.target&&this.object&&this.gameObject){const s=new Zt("Move to "+((t=this.target)==null?void 0:t.name),Et.tapTrigger(this.gameObject),ve.transformAction(this.object,this.target,this.duration,this.relativeMotion?"relative":"absolute"));e.addBehavior(s)}}}Ne([m(E)],$r.prototype,"object"),Ne([m(E)],$r.prototype,"target"),Ne([m()],$r.prototype,"duration"),Ne([m()],$r.prototype,"relativeMotion");var tt;const lp=(tt=class extends I{constructor(){super(...arguments),a(this,"materialToSwitch"),a(this,"variantMaterial"),a(this,"fadeDuration",0),a(this,"_objectsWithThisMaterial",null),a(this,"selfModel"),a(this,"targetModels")}start(){var o;this._objectsWithThisMaterial=this.objectsWithThisMaterial,Qc(this.gameObject),F()&&this._objectsWithThisMaterial.length<=0&&console.warn('ChangeMaterialOnClick: No objects found with material "'+((o=this.materialToSwitch)==null?void 0:o.name)+'"')}onPointerEnter(o){this.context.input.setCursor("pointer")}onPointerExit(o){this.context.input.unsetCursor("pointer")}onPointerClick(o){if(o.use(),!!this.variantMaterial)for(let e=0;e<this.objectsWithThisMaterial.length;e++){const t=this.objectsWithThisMaterial[e];t.material=this.variantMaterial}}get objectsWithThisMaterial(){return this._objectsWithThisMaterial!=null?this._objectsWithThisMaterial:(this._objectsWithThisMaterial=[],this.variantMaterial&&this.materialToSwitch&&this.context.scene.traverse(o=>{if(o instanceof q)if(Array.isArray(o.material)){for(const e of o.material)if(e===this.materialToSwitch){this.objectsWithThisMaterial.push(o);break}}else o.material===this.materialToSwitch?this.objectsWithThisMaterial.push(o):Z_(o.material,this.materialToSwitch)&&this.objectsWithThisMaterial.push(o)}),this._objectsWithThisMaterial)}async beforeCreateDocument(o,e){this.targetModels=[],tt._materialTriggersPerId={},tt.variantSwitchIndex=0,this.materialToSwitch&&await Xe.assignTextureLOD(this.materialToSwitch,0),this.variantMaterial&&await Xe.assignTextureLOD(this.variantMaterial,0)}createBehaviours(o,e,t){this.objectsWithThisMaterial.find(s=>s.uuid===e.uuid)&&this.targetModels.push(e),this.gameObject.uuid===e.uuid&&(this.selfModel=e,this.materialToSwitch&&(tt._materialTriggersPerId[this.materialToSwitch.uuid]||(tt._materialTriggersPerId[this.materialToSwitch.uuid]=[]),tt._materialTriggersPerId[this.materialToSwitch.uuid].push(this)))}afterCreateDocument(o,e){if(!this.materialToSwitch)return;const t=tt._materialTriggersPerId[this.materialToSwitch.uuid];if(t){const s={};for(const n of t){const r=n.createVariants();r&&r.length>0&&(s[n.selfModel.uuid]=r)}for(const n of t){const r=[];for(const l in s)l!==n.selfModel.uuid&&r.push(...s[l]);n.createAndAttachBehaviors(o,s[n.selfModel.uuid],r)}}delete tt._materialTriggersPerId[this.materialToSwitch.uuid]}createAndAttachBehaviors(o,e,t){const s=[],n=Math.max(0,this.fadeDuration);s.push(ve.fadeAction([...this.targetModels,...t],n,!1)),s.push(ve.fadeAction(e,n,!0)),o.addBehavior(new Zt("Select_"+this.selfModel.name,Et.tapTrigger(this.selfModel),ve.parallel(...s))),tt._parallelStartHiddenActions.push(...e),tt._startHiddenBehaviour||(tt._startHiddenBehaviour=new Zt("StartHidden_"+this.selfModel.name,Et.sceneStartTrigger(),ve.fadeAction(tt._parallelStartHiddenActions,n,!1)),o.addBehavior(tt._startHiddenBehaviour))}static getMaterialName(o){return Os(o.name||"Material")+"_"+o.id}createVariants(){if(!this.variantMaterial)return null;const o=[];for(const e of this.targetModels){const t=e.clone();t.name+="_Variant_"+tt.variantSwitchIndex+++"_"+tt.getMaterialName(this.variantMaterial),t.displayName=t.displayName+": Variant with material "+this.variantMaterial.name,t.material=this.variantMaterial,t.geometry=e.geometry,t.transform=e.transform,(!e.parent||!e.parent.isEmpty())&&pi.createEmptyParent(e),e.parent&&e.parent.add(t),o.push(t)}return o}},a(tt,"_materialTriggersPerId",{}),a(tt,"_startHiddenBehaviour",null),a(tt,"_parallelStartHiddenActions",[]),a(tt,"variantSwitchIndex",0),tt);Ne([m(Pe)],lp.prototype,"materialToSwitch"),Ne([m(Pe)],lp.prototype,"variantMaterial"),Ne([m()],lp.prototype,"fadeDuration");let A0=lp;var ke;const Yc=(ke=class extends I{constructor(){super(...arguments),a(this,"target"),a(this,"toggleOnClick",!1),a(this,"targetState",!0),a(this,"hideSelf",!0),a(this,"selfModel"),a(this,"selfModelClone"),a(this,"targetModel"),a(this,"toggleModel"),a(this,"stateBeforeCreatingDocument",!1),a(this,"targetStateBeforeCreatingDocument",!1)}start(){Qc(this.gameObject)}onPointerClick(o){o.use(),!this.toggleOnClick&&this.hideSelf&&(this.gameObject.visible=!1),this.target&&(this.target.visible=this.toggleOnClick?!this.target.visible:this.targetState)}createBehaviours(o,e,t){e.uuid===this.gameObject.uuid&&(this.selfModel=e,this.selfModelClone=e.clone())}beforeCreateDocument(){this.target&&(this.gameObject[ke.wasVisible]===void 0&&(this.gameObject[ke.wasVisible]=this.gameObject.activeSelf),this.target[ke.wasVisible]===void 0&&(this.target[ke.wasVisible]=this.target.activeSelf),this.stateBeforeCreatingDocument=this.gameObject[ke.wasVisible],this.targetStateBeforeCreatingDocument=this.target[ke.wasVisible],this.gameObject.visible=!0,this.target.visible=!0)}afterCreateDocument(o,e){if(!this.target)return;this.targetModel=e.document.findById(this.target.uuid);const t=this.selfModel;if(this.selfModel&&this.targetModel){let s=this.selfModel,n=this.targetState;if(this.toggleOnClick)if(n=!this.targetStateBeforeCreatingDocument,!this.selfModelClone.geometry)(!this.selfModel.parent||this.selfModel.parent.isEmpty())&&w0.createEmptyParent(this.selfModel),this.toggleModel=this.selfModel.deepClone(),this.toggleModel.name+="_toggle",this.selfModel.parent.add(this.toggleModel);else{if(!this.gameObject[ke.toggleClone]){const c=this.selfModelClone.clone();c.setMatrix(new se),c.name+="_toggle"+ke.clonedToggleIndex++,t.add(c),this.gameObject[ke.toggleClone]=c,console.warn("USDZExport: Toggle "+this.gameObject.name+" doesn't have geometry. It will be deep cloned and nested behaviours will likely not work.")}const l=this.gameObject[ke.toggleClone];if(!this.gameObject[ke.reverseToggleClone]){const c=this.selfModelClone.clone();c.setMatrix(new se),c.name+="_toggleReverse"+ke.clonedToggleIndex++,t.add(c),this.gameObject[ke.reverseToggleClone]=c}this.toggleModel=this.gameObject[ke.reverseToggleClone],(!this.toggleModel.geometry||!l.geometry)&&console.error("triggers without childs and without geometry won't work!",this,t.geometry),s=l,t.geometry=null,t.material=null}if(this.toggleModel){if(this.toggleOnClick){const l=[];l.push(ve.fadeAction(s,0,!1)),l.push(ve.fadeAction(this.toggleModel,0,!0)),l.push(ve.fadeAction(this.targetModel,0,n)),o.addBehavior(new Zt("Toggle_"+s.name+"_ToggleTo"+(n?"On":"Off"),Et.tapTrigger(s),ve.parallel(...l)));const c=[];c.push(ve.fadeAction(this.toggleModel,0,!1)),c.push(ve.fadeAction(s,0,!0)),c.push(ve.fadeAction(this.targetModel,0,!n)),o.addBehavior(new Zt("Toggle_"+s.name+"_ToggleTo"+(n?"Off":"On"),Et.tapTrigger(this.toggleModel),ve.parallel(...c)))}}else{const l=[];this.hideSelf&&l.push(ve.fadeAction(s,0,!1)),l.push(ve.fadeAction(this.targetModel,0,n)),o.addBehavior(new Zt("Toggle_"+s.name+"_ToggleTo"+(n?"On":"Off"),Et.tapTrigger(s),l.length>1?ve.parallel(...l):l[0]))}const r=new Array;this.targetStateBeforeCreatingDocument||r.push(this.targetModel),this.stateBeforeCreatingDocument||r.push(t),this.toggleModel&&r.push(this.toggleModel),cp.add(r,o)}}afterSerialize(o,e){this.gameObject[ke.wasVisible]!==void 0&&(this.gameObject.visible=this.gameObject[ke.wasVisible],delete this.gameObject[ke.wasVisible]),this.target&&this.target[ke.wasVisible]!==void 0&&(this.target.visible=this.target[ke.wasVisible],delete this.target[ke.wasVisible]),delete this.gameObject[ke.toggleClone],delete this.gameObject[ke.reverseToggleClone]}},a(ke,"clonedToggleIndex",0),a(ke,"wasVisible",Symbol("usdz_SetActiveOnClick_wasVisible")),a(ke,"toggleClone",Symbol("clone for toggling")),a(ke,"reverseToggleClone",Symbol("clone for reverse toggling")),ke);Ne([m(E)],Yc.prototype,"target"),Ne([m()],Yc.prototype,"toggleOnClick"),Ne([m()],Yc.prototype,"targetState"),Ne([m()],Yc.prototype,"hideSelf");let I0=Yc;const L0=class dr extends I{constructor(){super(...arguments),a(this,"wasVisible",!1)}static add(e,t){const s=Array.isArray(e)?e:[e];for(const n of s)dr._fadeObjects.includes(n)||(console.log("adding hide on start",n),dr._fadeObjects.push(n));dr._fadeBehaviour===void 0&&(dr._fadeBehaviour=new Zt("HideOnStart",Et.sceneStartTrigger(),ve.fadeAction(dr._fadeObjects,0,!1)),t.addBehavior(dr._fadeBehaviour))}start(){P.setActive(this.gameObject,!1)}createBehaviours(e,t,s){t.uuid===this.gameObject.uuid&&(this.wasVisible||dr.add(t,e))}beforeCreateDocument(){this.wasVisible=P.isActiveSelf(this.gameObject)}};a(L0,"_fadeBehaviour"),a(L0,"_fadeObjects",[]);let cp=L0;class cl extends I{constructor(){super(...arguments),a(this,"target"),a(this,"duration",.5),a(this,"motionType","bounce")}beforeCreateDocument(){}createBehaviours(e,t,s){if(this.target&&t.uuid===this.gameObject.uuid){const n=new Zt("emphasize "+this.name,Et.tapTrigger(this.gameObject),ve.emphasize(this.target,this.duration,this.motionType,void 0,"basic"));e.addBehavior(n)}}afterCreateDocument(e,t){}}Ne([m()],cl.prototype,"target"),Ne([m()],cl.prototype,"duration"),Ne([m()],cl.prototype,"motionType");class No extends I{constructor(){super(...arguments),a(this,"target"),a(this,"clip",""),a(this,"toggleOnClick",!1),a(this,"trigger","tap")}start(){Qc(this.gameObject)}ensureAudioSource(){if(!this.target){const e=this.gameObject.addComponent(ss);e&&(this.target=e,e.spatialBlend=1,e.volume=1,e.loop=!1,e.preload=!0)}}onPointerClick(e){var t;e.use(),!(!((t=this.target)!=null&&t.clip)&&!this.clip)&&(this.ensureAudioSource(),this.target&&(this.target.isPlaying&&this.toggleOnClick?this.target.stop():(!this.toggleOnClick&&this.target.isPlaying&&this.target.stop(),this.clip?this.target.play(this.clip):this.target.play())))}createBehaviours(e,t,s){if(!(!this.target&&!this.clip)&&t.uuid===this.gameObject.uuid){const n=this.clip?this.clip:this.target?this.target.clip:void 0;if(!n||typeof n!="string")return;const r=this.target?this.target.gameObject:this.gameObject;ya.getName(n);const l=this.target?this.target.volume:1,c=this.target&&this.target.spatialBlend==0?"nonSpatial":"spatial";let h=!1;this.gameObject.traverse(g=>{g instanceof q&&g.visible&&(h=!0)}),h=!0;const d=e.addAudioClip(n);let u=ve.playAudioAction(r,d,"play",l,c);this.target&&this.target.loop&&(u=ve.sequence(u).makeLooping());const p=this.name?"_"+this.name:"";if(h&&this.trigger==="tap"){this.toggleOnClick&&(u.multiplePerformOperation="stop");const g=new Zt("playAudio"+p,Et.tapTrigger(t),u);e.addBehavior(g)}if(this.target&&this.target.playOnAwake&&this.target.enabled)if(h&&this.trigger==="tap")console.warn("USDZExport: Audio sources that are played on tap can't also auto-play at scene start due to a QuickLook bug.");else{const g=new Zt("playAudioOnStart"+p,Et.sceneStartTrigger(),u);e.addBehavior(g)}}}}Ne([m(ss)],No.prototype,"target"),Ne([m(URL)],No.prototype,"clip"),Ne([m()],No.prototype,"toggleOnClick");var Ui;const j0=(Ui=class extends I{constructor(){super(...arguments),a(this,"animator"),a(this,"stateName"),a(this,"trigger","tap"),a(this,"animation"),a(this,"selfModel"),a(this,"stateAnimationModel"),a(this,"animationSequence",new Array),a(this,"animationLoopAfterSequence",new Array),a(this,"randomOffsetNormalized",0)}get target(){var o,e;return((o=this.animator)==null?void 0:o.gameObject)||((e=this.animation)==null?void 0:e.gameObject)}start(){Qc(this.gameObject)}onPointerClick(o){var e;o.use(),this.target&&this.stateName&&((e=this.animator)==null||e.play(this.stateName,0,0,.1))}createBehaviours(o,e,t){e.uuid===this.gameObject.uuid&&(this.selfModel=e)}afterSerialize(){if(Ui.rootsWithExclusivePlayback.size>1){const o='Multiple root objects targeted by more than one animation. To work around QuickLook bug FB13410767, animations will be set as "exclusive" and activating them will stop other animations being marked as exclusive.';F()&&be(o),console.warn(o,...Ui.rootsWithExclusivePlayback)}Ui.animationActions=[],Ui.rootsWithExclusivePlayback=new Set}afterCreateDocument(o,e){if(this.animationSequence===void 0&&this.animationLoopAfterSequence===void 0||!this.stateAnimationModel||!this.target)return;const t=e.document,s=e.extensions.find(l=>l instanceof ap);if(!s)return;const n=s.getClipCount(this.target)>1;n&&(F()&&console.warn("Setting exclusive playback for "+this.target.name+"@"+this.stateName+" because it has "+s.getClipCount(this.target)+" animations. This works around QuickLook bug FB13410767."),Ui.rootsWithExclusivePlayback.add(this.target));const r=this.name?this.name:"";t.traverse(l=>{var c,h;if(l.uuid===((c=this.target)==null?void 0:c.uuid)){const d=Ui.getActionForSequences(t,l,this.animationSequence,this.animationLoopAfterSequence,this.randomOffsetNormalized),u=new Zt(this.trigger+"_"+r+"_toPlayAnimation_"+this.stateName+"_on_"+((h=this.target)==null?void 0:h.name),this.trigger=="tap"?Et.tapTrigger(this.selfModel):Et.sceneStartTrigger(),d);n&&u.makeExclusive(!0),o.addBehavior(u)}})}static getActionForSequences(o,e,t,s,n){const r=(c,h)=>{let d=Ui.animationActions.find(u=>u.affectedObjects==c&&u.start==h.start&&u.duration==h.duration&&u.animationSpeed==h.speed);return d||(d=ve.startAnimationAction(c,h),Ui.animationActions.push(d)),d},l=ve.sequence();if(t&&t.length>0)for(const c of t)l.addAction(r(e,c));if(s&&s.length>0){const c=l.actions.length==0?l:ve.sequence();for(const h of s)c.addAction(r(e,h));c.makeLooping(),l!==c&&l.addAction(c)}return n&&n>0&&l.actions.unshift(ve.waitAction(n)),l}static getAndRegisterAnimationSequences(o,e,t){var s,n,r,l,c,h,d,u;if(!e)return;const p=e.getComponent(Mt),g=e.getComponent(Bt);if(!p&&!g)return;if(p&&!t)throw new Error("PlayAnimationOnClick: No stateName specified for animator "+p.name+" on "+e.name);let f=[],y=[];if(g){const M=o.registerAnimation(e,g.clip);M&&(g.loop?y.push(M):f.push(M));let T=0;if(g.minMaxOffsetNormalized){const L=g.minMaxOffsetNormalized.x,B=g.minMaxOffsetNormalized.y;T=(((s=g.clip)==null?void 0:s.duration)||1)*(L+Math.random()*(B-L))}return{animationSequence:f,animationLoopAfterSequence:y,randomTimeOffset:T}}const b=p?.runtimeAnimatorController;let v=b?.findState(t),_=[],w=[];if(b&&v){const M=new Array;M.push(v);let T=!1;for(;M.length<100;){if(!v||v===null||!v.transitions||v.transitions.length===0){(n=v.motion)!=null&&n.isLooping&&(T=!0);break}const L=v.transitions.find(z=>z.conditions.length===0),B=L?b.getState(L.destinationState,0):null;if(B&&M.includes(B)){v=B,T=!0;break}else if(L){if(v=B,!v)break;M.push(v)}else{T=((r=v.motion)==null?void 0:r.isLooping)??!1;break}}if(T&&v){const L=M.indexOf(v);_=M.slice(0,L),w=M.slice(L),N1&&console.log("found loop from "+t,"states until loop",_,"states looping",w)}else _=M,w=[],N1&&console.log("found no loop from "+t,"states",_);if(!w.length){const L=_[_.length-1],B=(l=L.motion)==null?void 0:l.clip;if(B){let z;if(o.holdClipMap.has(B))z=o.holdClipMap.get(B);else{const D=L.name+"_hold";z=B.clone(),z.duration=1,z.name=D;const V=B.duration;z.tracks=B.tracks.map($=>{const U=$.clone();U.times=new Float32Array([0,V]);const j=$.values.length,Q=$.getValueSize(),J=$.values.slice(j-Q,j);return U.values=new Float32Array(2*Q),U.values.set(J,0),U.values.set(J,Q),U}),z.name=D,o.holdClipMap.set(B,z)}if(z){const D={name:z.name,motion:{clip:z,isLooping:!1,name:z.name},speed:1,transitions:[],behaviours:[],hash:L.hash+1};w.push(D)}}}}if(_.length===1&&(!((c=_[0].motion)!=null&&c.clip)||((d=(h=_[0].motion)==null?void 0:h.clip.tracks)==null?void 0:d.length)===0)){f=new Array;const M=o.registerAnimation(e,null);M&&f.push(M);return}if(_=_.filter(M=>{var T,L,B;return((T=M.motion)==null?void 0:T.clip)&&((B=(L=M.motion)==null?void 0:L.clip.tracks)==null?void 0:B.length)>0}),w=w.filter(M=>{var T,L,B;return((T=M.motion)==null?void 0:T.clip)&&((B=(L=M.motion)==null?void 0:L.clip.tracks)==null?void 0:B.length)>0}),_.length===0&&w.length===0){console.warn("No clips found for state "+t+" on "+p?.name+", can't export animation data");return}const S=(M,T)=>{if(!e)return;const L=o.registerAnimation(e,M.motion.clip??null);L?(L.speed=M.speed,T.push(L)):console.warn("Couldn't register animation for state "+M.name+" on "+p?.name)};if(_.length>0){f=new Array;for(const M of _)S(M,f)}if(w.length>0){y=new Array;for(const M of w)S(M,y)}let k=0;if(p&&b&&p.minMaxOffsetNormalized){const M=p.minMaxOffsetNormalized.x,T=p.minMaxOffsetNormalized.y,L=_.length?_[0]:w.length?w[0]:null;k=(((u=L?.motion.clip)==null?void 0:u.duration)||1)*(M+Math.random()*(T-M))}return{animationSequence:f,animationLoopAfterSequence:y,randomTimeOffset:k}}createAnimation(o,e,t){if(!this.target||!this.animator&&!this.animation)return;const s=Ui.getAndRegisterAnimationSequences(o,this.target,this.stateName);s&&(this.animationSequence=s.animationSequence,this.animationLoopAfterSequence=s.animationLoopAfterSequence,this.randomOffsetNormalized=s.randomTimeOffset,this.stateAnimationModel=e)}},a(Ui,"animationActions",[]),a(Ui,"rootsWithExclusivePlayback",new Set),Ui);Ne([m(Mt)],j0.prototype,"animator"),Ne([m()],j0.prototype,"stateName");let Kc=j0;class hl extends I{constructor(){super(...arguments),a(this,"target")}getType(){}getDuration(){}}Ne([m(E)],hl.prototype,"target");class Zc extends I{constructor(){super(...arguments),a(this,"target")}}Ne([m(hl)],Zc.prototype,"target");class Jc extends hl{constructor(){super(...arguments),a(this,"type",1),a(this,"duration",1)}getType(){switch(this.type){case 1:return"hide";case 0:return"show"}}getDuration(){return this.duration}}Ne([m()],Jc.prototype,"type"),Ne([m()],Jc.prototype,"duration");class D0 extends Zc{}const W1=class wC{constructor(){a(this,"_quicklookButton"),a(this,"_arButton"),a(this,"_vrButton"),a(this,"_sendToQuestButton")}static create(){return new wC}static getOrCreate(){return this._instance||(this._instance=this.create()),this._instance}get isSecureConnection(){return window.location.protocol==="https:"}get quicklookButton(){return this._quicklookButton}get arButton(){return this._arButton}get vrButton(){return this._vrButton}get sendToQuestButton(){return this._sendToQuestButton}get qrButton(){return Co.getOrCreate().createQRCode()}createQuicklookButton(){if(this._quicklookButton)return this._quicklookButton;const e=document.createElement("button");this._quicklookButton=e,e.dataset.needle="quicklook-button";const t=Y.supportsQuickLookAR();e.innerText="View in AR",e.prepend(kt("view_in_ar"));let s=!1,n=null;return e.addEventListener("click",()=>{n=_c(gn),n||(s=!0,n=new gn),s&&(n.objectToExport=ee.Current.scene),n?(e.classList.add("this-mode-is-requested"),n.exportAndOpen().then(()=>{e.classList.remove("this-mode-is-requested")}).catch(r=>{e.classList.remove("this-mode-is-requested"),console.error(r)})):console.warn("No USDZExporter component found in the scene")}),this.hideElementDuringXRSession(e),e}createARButton(e){var t;if(this._arButton)return this._arButton;const s="immersive-ar",n=document.createElement("button");return this._arButton=n,n.classList.add("webxr-button"),n.dataset.needle="webxr-ar-button",n.innerText="Enter AR",n.prepend(kt("view_in_ar")),n.title="Click to start an AR session",n.addEventListener("click",()=>ne.start(s,e)),this.updateSessionSupported(n,s),this.listenToXRSessionState(n,s),this.hideElementDuringXRSession(n),this.isSecureConnection||(n.disabled=!0,n.title="WebXR requires a secure connection (HTTPS)"),Y.isMozillaXR()||(t=navigator.xr)==null||t.addEventListener("devicechange",()=>this.updateSessionSupported(n,s)),n}createVRButton(e){var t;if(this._vrButton)return this._vrButton;const s="immersive-vr",n=document.createElement("button");return this._vrButton=n,n.classList.add("webxr-button"),n.dataset.needle="webxr-vr-button",n.innerText="Enter VR",n.prepend(kt("panorama_photosphere")),n.title="Click to start a VR session",n.addEventListener("click",()=>ne.start(s,e)),this.updateSessionSupported(n,s),this.listenToXRSessionState(n,s),this.hideElementDuringXRSession(n),this.isSecureConnection||(n.disabled=!0,n.title="WebXR requires a secure connection (HTTPS)"),Y.isMozillaXR()||(t=navigator.xr)==null||t.addEventListener("devicechange",()=>this.updateSessionSupported(n,s)),n}createSendToQuestButton(){var e;if(this._sendToQuestButton)return this._sendToQuestButton;const t="https://oculus.com/open_url/?url=",s=document.createElement("button");return this._sendToQuestButton=s,s.dataset.needle="webxr-sendtoquest-button",s.innerText="Open on Quest",s.prepend(kt("share_windows")),s.title="Click to send this page to the Oculus Browser on your Quest",s.addEventListener("click",()=>{const n=encodeURIComponent(window.location.href),r=t+n;window.open(r)==null&&Be("This page doesn't allow popups. Please paste "+r+" into your browser.")}),this.listenToXRSessionState(s),this.hideElementDuringXRSession(s),Y.isMozillaXR()||(e=navigator.xr)==null||e.addEventListener("devicechange",()=>{var n;(n=navigator.xr)!=null&&n.isSessionSupported("immersive-vr")?s.style.display="none":s.style.display=""}),s}createQRCode(){return Co.getOrCreate().createQRCode()}updateSessionSupported(e,t){if(!("xr"in navigator)){e.style.display="none";return}ne.isSessionSupported(t).then(s=>{e.style.display=s?"":"none",F()&&!s&&console.log('[WebXR] "'+t+'" is not supported on this device \u2013 make sure your server runs using HTTPS and you have a device connected that supports '+t)})}hideElementDuringXRSession(e){Dd(t=>{e["previous-display"]=e.style.display,e.style.display="none"}),bg(t=>{e["previous-display"]!=null&&(e.style.display=e["previous-display"])})}listenToXRSessionState(e,t){t&&(ne.onSessionRequestStart(s=>{s.mode===t?e.classList.add("this-mode-is-requested"):(e["was-disabled"]=e.disabled,e.disabled=!0,e.classList.add("other-mode-is-requested"))}),ne.onSessionRequestEnd(s=>{e.classList.remove("this-mode-is-requested"),e.classList.remove("other-mode-is-requested"),e.disabled=e["was-disabled"]}))}};a(W1,"_instance");let dl=W1;var tA=Object.defineProperty,iA=Object.getOwnPropertyDescriptor,xt=(o,e,t,s)=>{for(var n=s>1?void 0:s?iA(e,t):e,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=(s?l(e,t,n):l(n))||n);return s&&n&&tA(e,t,n),n};const hp=C("debugspriterenderer"),sA=C("wireframe"),V1=class gv{static getOrCreateGeometry(e){if(e.__cached_geometry)return e.__cached_geometry;if(e.guid&&gv.cache[e.guid])return hp&&console.log("Take cached geometry for sprite",e.guid),gv.cache[e.guid];const t=new Vs;e.__cached_geometry=t;const s=new Float32Array(e.triangles.length*3),n=new Float32Array(e.triangles.length*2);for(let r=0;r<e.triangles.length;r+=1){const l=e.triangles[r];s[r*3]=-e.vertices[l].x,s[r*3+1]=e.vertices[l].y,s[r*3+2]=0;const c=e.uv[l];n[r*2]=c.x,n[r*2+1]=1-c.y}return t.setAttribute("position",new bt(s,3)),t.setAttribute("uv",new bt(n,2)),e.guid&&(this.cache[e.guid]=t),hp&&console.log("Built sprite geometry",e,t),t}};a(V1,"cache",{});let dp=V1;class nA{constructor(){a(this,"x"),a(this,"y")}}function H1(o){o&&(o.colorSpace!=Mn&&(o.colorSpace=Mn,o.needsUpdate=!0),o.minFilter==vd&&o.magFilter==vd&&(o.anisotropy=1,o.needsUpdate=!0))}let Qn=class{constructor(o){a(this,"guid"),a(this,"texture"),a(this,"triangles"),a(this,"uv"),a(this,"vertices"),a(this,"__cached_geometry"),a(this,"_mesh"),a(this,"_material"),o&&(this.texture=o,this.triangles=[0,1,2,0,2,3],this.uv=[{x:0,y:0},{x:1,y:0},{x:1,y:1},{x:0,y:1}],this.vertices=[{x:-.5,y:-.5},{x:.5,y:-.5},{x:.5,y:.5},{x:-.5,y:.5}])}get mesh(){return this._mesh||(this._mesh=new q(dp.getOrCreateGeometry(this),this.material)),this._mesh}get material(){return this._material||(this.texture&&H1(this.texture),this._material=new Me({map:this.texture,color:16777215,side:Ci,transparent:!0})),this._material}getGeometry(){return dp.getOrCreateGeometry(this)}};xt([m()],Qn.prototype,"guid",2),xt([m(De)],Qn.prototype,"texture",2),xt([Ir()],Qn.prototype,"triangles",2),xt([Ir()],Qn.prototype,"uv",2),xt([Ir()],Qn.prototype,"vertices",2);const B0=Symbol("spriteOwner");class ul{constructor(){a(this,"sprites"),this.sprites=[]}}xt([m(Qn)],ul.prototype,"sprites",2);const F0=class fv{constructor(){a(this,"spriteSheet"),a(this,"index",0)}static create(){const e=new fv;return e.spriteSheet=new ul,e}clone(){const e=new fv;return e.index=this.index,e.spriteSheet=this.spriteSheet,e}set sprite(e){e&&(this.spriteSheet?((this.index===null||this.index===void 0)&&(this.index=0),this.spriteSheet.sprites[this.index]=e):(this.spriteSheet=new ul,this.spriteSheet.sprites=[e],this.index=0))}get sprite(){if(this.spriteSheet)return this.spriteSheet.sprites[this.index]}update(e){if(!this.spriteSheet)return;const t=this.index;if(t<0||t>=this.spriteSheet.sprites.length)return;const s=this.spriteSheet.sprites[t],n=s?.texture;if(n&&(H1(n),!s.__hasLoadedProgressive)){s.__hasLoadedProgressive=!0;const r=n;Xe.assignTextureLOD(n,0).then(l=>{l instanceof De&&(s.texture=l,e?.map===r&&(e.map=l,e.needsUpdate=!0))})}}};xt([m(ul)],F0.prototype,"spriteSheet",2),xt([m()],F0.prototype,"index",2);let pl=F0;class mi extends I{constructor(){super(...arguments),a(this,"drawMode",0),a(this,"size",{x:1,y:1}),a(this,"color"),a(this,"sharedMaterial"),a(this,"transparent",!0),a(this,"cutoutThreshold",0),a(this,"castShadows",!1),a(this,"renderOrder",0),a(this,"toneMapped",!0),a(this,"_spriteSheet"),a(this,"_currentSprite")}set texture(e){var t;if(!this._spriteSheet)return;const s=(t=this._spriteSheet.spriteSheet)==null?void 0:t.sprites[this.spriteIndex];s&&(s.texture=e,this.updateSprite())}addSprite(e,t=!1){var s,n;if(this._spriteSheet||(this._spriteSheet=pl.create()),!this._spriteSheet.spriteSheet)return-1;(s=this._spriteSheet.spriteSheet)==null||s.sprites.push(e);const r=((n=this._spriteSheet.spriteSheet)==null?void 0:n.sprites.length)-1;return t&&(this.spriteIndex=r),r}get sprite(){return this._spriteSheet}set sprite(e){if(e!==this._spriteSheet)if(typeof e=="number"){const t=Math.floor(e);this.spriteIndex=t}else e instanceof Qn?(this._spriteSheet||(this._spriteSheet=pl.create()),this._spriteSheet.sprite!=e&&(this._spriteSheet.sprite=e),this.updateSprite()):e!=this._spriteSheet&&(this._spriteSheet=e,this.updateSprite())}set spriteIndex(e){this._spriteSheet&&(this._spriteSheet.index=e,this.updateSprite())}get spriteIndex(){var e;return((e=this._spriteSheet)==null?void 0:e.index)??0}get spriteFrames(){var e,t;return((t=(e=this._spriteSheet)==null?void 0:e.spriteSheet)==null?void 0:t.sprites.length)??0}awake(){this._currentSprite=void 0,this._spriteSheet?this._spriteSheet=this._spriteSheet.clone():this._spriteSheet=pl.create(),hp&&console.log("Awake",this.name,this,this.sprite)}start(){this._currentSprite?this.gameObject&&this.gameObject.add(this._currentSprite):this.updateSprite()}updateSprite(e=!1){var t;if(!this.__didAwake&&!e)return!1;const s=this._spriteSheet;if(!((t=s?.spriteSheet)!=null&&t.sprites))return console.warn("SpriteRenderer has no data or spritesheet assigned..."),!1;const n=s.spriteSheet.sprites[this.spriteIndex];if(!n)return hp&&console.warn("Sprite not found",this.spriteIndex,s.spriteSheet.sprites),!1;if(this._currentSprite)this._currentSprite.geometry=dp.getOrCreateGeometry(n),this._currentSprite.material.map=n.texture;else{const r=new Me({color:16777215,side:Ci});if(sA&&(r.wireframe=!0),this.color&&(r.color||(r.color=new ae),r.color.copy(this.color),r.opacity=this.color.alpha),r.transparent=!0,r.toneMapped=this.toneMapped,r.depthWrite=!1,n.texture&&!r.wireframe){let l=n.texture;l[B0]!==void 0&&l[B0]!==this&&this.spriteFrames>1&&(l=n.texture=l.clone()),l[B0]=this,r.map=l}this.sharedMaterial=r,this._currentSprite=new q(dp.getOrCreateGeometry(n),r),this._currentSprite.renderOrder=Math.round(this.renderOrder),Xe.assignTextureLOD(r,0)}return this._currentSprite.parent!==this.gameObject&&(this.drawMode===2&&this._currentSprite.scale.set(this.size.x,this.size.y,1),this.gameObject&&this.gameObject.add(this._currentSprite)),this._currentSprite&&this._currentSprite.layers.set(this.layer),this.sharedMaterial&&(this.sharedMaterial.alphaTest=this.cutoutThreshold,this.sharedMaterial.transparent=this.transparent),this._currentSprite.castShadow=this.castShadows,s?.update(this.sharedMaterial),!0}}xt([m()],mi.prototype,"drawMode",2),xt([m(nA)],mi.prototype,"size",2),xt([m(he)],mi.prototype,"color",2),xt([m(Pe)],mi.prototype,"sharedMaterial",2),xt([m()],mi.prototype,"transparent",2),xt([m()],mi.prototype,"cutoutThreshold",2),xt([m()],mi.prototype,"castShadows",2),xt([m()],mi.prototype,"renderOrder",2),xt([m()],mi.prototype,"toneMapped",2),xt([m(pl)],mi.prototype,"sprite",1);const $1=C("debugwebxr"),oA=new se().makeRotationY(Math.PI),U0=class sd extends I{constructor(){super(...arguments),a(this,"_arScale",1),a(this,"invertForward",!1),a(this,"customReticle"),a(this,"arTouchTransform",!0),a(this,"autoPlace",!1),a(this,"autoCenter",!1),a(this,"useXRAnchor",!1),a(this,"_isPlacing",!0),a(this,"_startOffset",new se),a(this,"_createdPlacementObject",null),a(this,"_reparentedComponents",[]),a(this,"_placementScene",new wi),a(this,"_reticle",[]),a(this,"_hits",[]),a(this,"_placementStartTime",-1),a(this,"_rigPlacementMatrix"),a(this,"_anchor",null),a(this,"userInput"),a(this,"onPlaceScene",e=>{var t;if(this._isPlacing==!1||e!=null&&e.used)return;let s=this._reticle[0];if(!s){console.warn("No reticle to place...");return}if(!s.visible&&!this.autoPlace){console.warn("Reticle is not visible (can not place)");return}if((t=ne.active)!=null&&t.isTrackingImages){console.warn("Scene Placement is disabled while images are being tracked");return}let n=this._hits[0];if(e&&e.origin instanceof _g){const r=this._reticle[e.origin.index];r&&(s=r,n=this._hits[e.origin.index])}if(e&&(e.stopImmediatePropagation(),e.stopPropagation(),e.use()),this._isPlacing=!1,this.context.input.removeEventListener("pointerup",this.onPlaceScene),this.onRevertSceneChanges(),s.position.copy(s.lastPos),s.quaternion.copy(s.lastQuat),this.onApplyPose(s),sd._hasPlaced=!0,this.useXRAnchor&&this.onCreateAnchor(ne.active,n),this.context.xr)for(const r of this.context.xr.controllers)r.cancelHitTestSource()}),a(this,"upVec",new x(0,1,0)),a(this,"lookPoint",new x),a(this,"worldUpVec",new x(0,1,0))}static onPlaced(e){const t="placed";return this._eventListeners[t]||(this._eventListeners[t]=[]),this._eventListeners[t].push(e),()=>{const s=this._eventListeners[t].indexOf(e);s>=0&&this._eventListeners[t].splice(s,1)}}static get hasPlaced(){return this._hasPlaced}get arScale(){return this._arScale}set arScale(e){this._arScale=Math.max(1e-6,e),this.onSetScale()}onEnable(){var e;(e=this.customReticle)==null||e.preload()}supportsXR(e){return e==="immersive-ar"}onEnterXR(e){$1&&console.log("ENTER WEBXR: SessionRoot start..."),this._anchor=null,sd._hasPlaced=!1,this.gameObject.updateMatrixWorld(),this._startOffset.copy(this.gameObject.matrixWorld);const t=new E;this._createdPlacementObject=t,t.name="AR Session Root",this._placementScene.name="AR Placement Scene",this._placementScene.children.length=0;for(let s=this.context.scene.children.length-1;s>=0;s--){const n=this.context.scene.children[s];this._placementScene.add(n)}if(this.context.scene.add(t),this.autoCenter){const s=ii(this._placementScene.children),n=s.getCenter(new x),r=s.getSize(new x),l=new se;l.makeTranslation(n.x,n.y-r.y*.5,n.z),this._startOffset.multiply(l)}this._reparentedComponents.length=0,this._reparentedComponents.push({comp:this,originalObject:this.gameObject}),P.addComponent(t,this);for(const s of this._reticle)Ei(s);this._reticle.length=0,this._isPlacing=!0,this.context.input.addEventListener("pointerup",this.onPlaceScene,{queue:ni.Early})}onLeaveXR(){this.context.input.removeEventListener("pointerup",this.onPlaceScene,{queue:ni.Early}),this.onRevertSceneChanges(),this._anchor=null,sd._hasPlaced=!1,this._rigPlacementMatrix=void 0}onUpdateXR(e){var t,s,n,r;if(e.xr.isTrackingImages){for(const l of this._reticle)l.visible=!1;return}if(this._isPlacing){const l=(t=e.xr.rig)==null?void 0:t.gameObject;l&&l.parent!==this.context.scene&&this.context.scene.add(l);let c=!1;if(e.xr.isPassThrough&&e.xr.controllers.length>0&&!this.autoPlace)for(const h of e.xr.controllers){const d=h.getHitTest();d&&(c=!0,this.updateReticleAndHits(e.xr,h.index,d,e.xr.rigScale))}if(!c){const h=e.xr.getHitTest();h&&this.updateReticleAndHits(e.xr,0,h,e.xr.rigScale)}}else{if(this._anchor&&e.xr.referenceSpace){const l=e.xr.frame.getPose(this._anchor.anchorSpace,e.xr.referenceSpace);if(l&&this.context.time.frame%20===0){const c=e.xr.convertSpace(l.transform),h=this._reticle[0];h&&(h.position.copy(c.position),h.quaternion.copy(c.quaternion),this.onApplyPose(h))}}if(this.arTouchTransform?(this.userInput||(this.userInput=new rA(this.context)),(s=this.userInput)==null||s.enable()):(n=this.userInput)==null||n.disable(),this.arTouchTransform&&(r=this.userInput)!=null&&r.hasChanged){if(e.xr.rig){const l=e.xr.rig.gameObject;this.userInput.applyMatrixTo(l.matrix,!0),l.matrix.decompose(l.position,l.quaternion,l.scale),this.userInput.factor=l.scale.x}this.userInput.reset()}}}updateReticleAndHits(e,t,s,n){this._hits[t]=s.hit;let r=this._reticle[t];if(!r){if(this.customReticle)if(this.customReticle.asset)r=Wa(this.customReticle.asset);else{this.customReticle.loadAssetAsync();return}else r=new q(new CP(.07,.09,32).rotateX(-Math.PI/2),new Me({side:Ci,depthTest:!1,depthWrite:!1,transparent:!0,opacity:1,color:15658734})),r.name="AR Placement Reticle";if($1){const l=new Si(1);l.position.y+=.01,r.add(l)}this._reticle[t]=r,r.matrixAutoUpdate=!1,r.visible=!1}if(r.lastPos=r.lastPos||s.position.clone(),r.lastQuat=r.lastQuat||s.quaternion.clone(),r.position.copy(r.lastPos.lerp(s.position,this.context.time.deltaTime/.1)),r.lastPos.copy(r.position),r.quaternion.copy(r.lastQuat.slerp(s.quaternion,this.context.time.deltaTime/.05)),r.lastQuat.copy(r.quaternion),r.scale.set(n,n,n),this.customReticle&&this.applyViewBasedTransform(r),r.updateMatrix(),r.visible=!0,r.parent!==this.context.scene&&this.context.scene.add(r),this._placementStartTime<0&&(this._placementStartTime=this.context.time.realtimeSinceStartup),this.autoPlace)if(this.upVec.set(0,1,0).applyQuaternion(r.quaternion),this.upVec.dot(X(0,1,0))>.9){let l=r["autoplace:timer"]||0;l>=1?(r.visible=!1,this.onPlaceScene(null)):(l+=this.context.time.deltaTime,r["autoplace:timer"]=l)}else r["autoplace:timer"]=0}onSetScale(){var e,t,s;if(!sd._hasPlaced)return;const n=(t=(e=ne.active)==null?void 0:e.rig)==null?void 0:t.gameObject;if(n){const r=((s=ne.active)==null?void 0:s.rigScale)||1,l=1/this._arScale*r,c=new se().makeScale(l,l,l).invert();n.matrix.premultiply(c),n.matrix.decompose(n.position,n.quaternion,n.scale)}}onRevertSceneChanges(){var e;for(const t of this._reticle)t&&(t.visible=!1,t?.removeFromParent());this._reticle.length=0;for(let t=this._placementScene.children.length-1;t>=0;t--){const s=this._placementScene.children[t];this.context.scene.add(s)}(e=this._createdPlacementObject)==null||e.removeFromParent();for(const t of this._reparentedComponents)P.addComponent(t.originalObject,t.comp)}async onCreateAnchor(e,t){if(t.createAnchor===void 0){console.warn("Hit does not support creating an anchor",t),F()&&be("Hit does not support creating an anchor");return}else{const s=await t.createAnchor(e.viewerPose.transform);e.running&&s&&(this._anchor=s)}}applyViewBasedTransform(e){const t=this.context.mainCamera,s=e,n=t.worldPosition,r=s.worldPosition;this.upVec.set(0,1,0).applyQuaternion(e.quaternion);const l=t.worldPosition;l&&e.position.clone().sub(l).angleTo(this.upVec)<Math.PI/2&&this.upVec.negate();const c=this.upVec.angleTo(this.worldUpVec)*180/Math.PI,h=30;c>h&&c<180-h||c<-h&&c>-180+h?(this.lookPoint.copy(e.position).add(this.upVec),this.lookPoint.y=e.position.y,e.lookAt(this.lookPoint)):(n.y=r.y,e.lookAt(n))}onApplyPose(e){var t,s,n;const r=(s=(t=ne.active)==null?void 0:t.rig)==null?void 0:s.gameObject;if(!r){console.warn("No rig object to place");return}const l=r.parent||this.context.scene;this._rigPlacementMatrix?(n=this._rigPlacementMatrix)==null||n.decompose(r.position,r.quaternion,r.scale):this._rigPlacementMatrix=r.matrix.clone(),this.applyViewBasedTransform(e),e.updateMatrix(),this.context.scene.add(e),e.attach(r),e.removeFromParent(),r.scale.set(this.arScale,this.arScale,this.arScale),r.position.multiplyScalar(this.arScale),r.updateMatrix(),this.invertForward&&r.matrix.premultiply(oA),r.matrix.premultiply(this._startOffset),r.matrix.decompose(r.position,r.quaternion,r.scale),l.add(r)}};a(U0,"_eventListeners",{}),a(U0,"_hasPlaced",!1);let Wo=U0;const up=class yv{constructor(e){a(this,"oneFingerDrag",!0),a(this,"twoFingerRotate",!0),a(this,"twoFingerScale",!0),a(this,"factor",1),a(this,"context"),a(this,"offset"),a(this,"plane"),a(this,"_scale",1),a(this,"_hasChanged",!1),a(this,"_enabled",!1),a(this,"currentlyUsedPointerIds",new Set),a(this,"currentlyUnusedPointerIds",new Set),a(this,"onPointerDownEarly",t=>{this.isActive&&t.stopPropagation()}),a(this,"onPointerDownLate",t=>{t.used?this.currentlyUsedPointerIds.add(t.pointerId):this.currentlyUsedPointerIds.size<=0&&this.currentlyUnusedPointerIds.add(t.pointerId)}),a(this,"onPointerUpEarly",t=>{this.currentlyUsedPointerIds.delete(t.pointerId),this.currentlyUnusedPointerIds.delete(t.pointerId)}),a(this,"prev",new Map),a(this,"_didMultitouch",!1),a(this,"touchStart",t=>{if(!t.defaultPrevented)for(let s=0;s<t.changedTouches.length;s++){const n=t.changedTouches[s],r=Y.isAndroidDevice()&&n.clientY<window.innerHeight*.1;this.prev.has(n.identifier)||this.prev.set(n.identifier,{ignore:r,x:0,z:0,screenx:0,screeny:0});const l=this.prev.get(n.identifier);if(l){const c=this.getPositionOnPlane(n.clientX,n.clientY);l.x=c.x,l.z=c.z,l.screenx=n.clientX,l.screeny=n.clientY}}}),a(this,"touchEnd",t=>{t.touches.length<=0&&(this._didMultitouch=!1);for(let s=0;s<t.changedTouches.length;s++){const n=t.changedTouches[s];this.prev.delete(n.identifier)}}),a(this,"touchMove",t=>{if(!t.defaultPrevented&&this.isActive){if(t.touches.length===1){if(this._didMultitouch)return;const s=t.touches[0],n=this.prev.get(s.identifier);if(!n||n.ignore)return;const r=this.getPositionOnPlane(s.clientX,s.clientY),l=r.x-n.x,c=r.z-n.z;if(l===0&&c===0)return;this.oneFingerDrag&&this.addMovement(l,c),n.x=r.x,n.z=r.z,n.screenx=s.clientX,n.screeny=s.clientY;return}else if(t.touches.length===2){this._didMultitouch=!0;const s=t.touches[0],n=t.touches[1],r=this.prev.get(s.identifier),l=this.prev.get(n.identifier);if(!r||!l)return;if(this.twoFingerRotate){const c=Math.atan2(s.clientY-n.clientY,s.clientX-n.clientX),h=Math.atan2(r.screeny-l.screeny,r.screenx-l.screenx),d=c-h;Math.abs(d)>.001&&this.addRotation(d)}if(this.twoFingerScale){const c=s.clientX-n.clientX,h=s.clientY-n.clientY,d=Math.sqrt(c*c+h*h),u=r.screenx-l.screenx,p=r.screeny-l.screeny,g=Math.sqrt(u*u+p*p),f=d-g;Math.abs(f)>2&&this.addScale(f)}r.screenx=s.clientX,r.screeny=s.clientY,l.screenx=n.clientX,l.screeny=n.clientY}}}),a(this,"_raycaster",new ud),a(this,"_intersection",new x),a(this,"_screenPos",new x),a(this,"_tempMatrix",new se),this.context=e,this.offset=new se,this.plane=new mr,this.plane.setFromNormalAndCoplanarPoint(yv.up,yv.zero)}get scale(){return this._scale}reset(){this._scale=1,this.offset.identity(),this._hasChanged=!0}get hasChanged(){return this._hasChanged}applyMatrixTo(e,t){this._hasChanged=!1,t?(this.offset.invert(),e.premultiply(this.offset)):e.multiply(this.offset)}get isActive(){return this.currentlyUsedPointerIds.size<=0&&this.currentlyUnusedPointerIds.size>0}enable(){this._enabled||(this._enabled=!0,this.context.input.addEventListener("pointerdown",this.onPointerDownEarly,{queue:ni.Early}),this.context.input.addEventListener("pointerdown",this.onPointerDownLate,{queue:ni.Late}),this.context.input.addEventListener("pointerup",this.onPointerUpEarly,{queue:ni.Early}),window.addEventListener("touchstart",this.touchStart,{passive:!1}),window.addEventListener("touchmove",this.touchMove,{passive:!1}),window.addEventListener("touchend",this.touchEnd,{passive:!1}))}disable(){this._enabled&&(this._enabled=!1,this.context.input.removeEventListener("pointerdown",this.onPointerDownEarly,{queue:ni.Early}),this.context.input.removeEventListener("pointerdown",this.onPointerDownLate,{queue:ni.Late}),this.context.input.removeEventListener("pointerup",this.onPointerUpEarly,{queue:ni.Early}),window.removeEventListener("touchstart",this.touchStart),window.removeEventListener("touchmove",this.touchMove),window.removeEventListener("touchend",this.touchEnd))}getPositionOnPlane(e,t){const s=this.context.mainCamera;return this._screenPos.x=e/window.innerWidth*2-1,this._screenPos.y=-(t/window.innerHeight)*2+1,this._screenPos.z=1,this._screenPos.unproject(s),this._raycaster.set(s.position,this._screenPos.sub(s.position)),this._raycaster.ray.intersectPlane(this.plane,this._intersection),this._intersection}addMovement(e,t){e/=this._scale,t/=this._scale,e*=this.factor,t*=this.factor,this.offset.elements[12]+=e,this.offset.elements[14]+=t,(e!==0||t!==0)&&(this._hasChanged=!0)}addScale(e){e/=window.innerWidth,e*=-1,this._scale*=1+e,this._tempMatrix.makeScale(1-e,1-e,1-e),this.offset.premultiply(this._tempMatrix),e!==0&&(this._hasChanged=!0)}addRotation(e){e*=-1,this._tempMatrix.makeRotationY(e),this.offset.premultiply(this._tempMatrix),e!==0&&(this._hasChanged=!0)}};a(up,"up",new x(0,1,0)),a(up,"zero",new x(0,0,0)),a(up,"one",new x(1,1,1));let rA=up;const Vo=C("debugautosync"),z0=Symbol("syncerId");class aA{constructor(){a(this,"_syncers",{})}getOrCreateSyncer(e){if(!e.guid)return null;if(this._syncers[e.guid])return this._syncers[e.guid];const t=new lA(e);return t[z0]=e.guid,this._syncers[t[z0]]=t,t}removeSyncer(e){delete this._syncers[e[z0]]}}const N0=new aA;class lA{constructor(e){a(this,"comp"),a(this,"hasChanges",!1),a(this,"changedProperties",{}),a(this,"_isReceiving",!1),a(this,"_isInit",!1),a(this,"onHandleSending",()=>{if(!this.hasChanges)return;this.hasChanges=!1;const t=this.comp.context.connection;if(!t||!t.isConnected||!t.isInRoom){for(const s in this.changedProperties)delete this.changedProperties[s];return}for(const s in this.changedProperties){const n=this.changedProperties[s];Vo&&console.log("SEND",this.comp.guid,this.networkingKey),t.send(this.networkingKey,{guid:this.comp.guid,property:s,data:n},xs.Queued),delete this.changedProperties[s]}}),a(this,"onHandleReceiving",t=>{if(Vo&&console.log("SYNCFIELD RECEIVE",this.comp.name,this.comp.guid,t),!!this._isInit&&this.comp&&t.guid===this.comp.guid)try{this._isReceiving=!0,this.comp[t.property]=t.data}catch(s){console.error(s)}finally{this._isReceiving=!1}}),this.comp=e}get networkingKey(){return this.comp.guid}init(e){if(this._isInit)return;this._isInit=!0,this.comp=e,this.comp.context.post_render_callbacks.push(this.onHandleSending),this.comp.context.connection.beginListen(this.networkingKey,this.onHandleReceiving);const t=this.comp.context.connection.tryGetState(this.comp.guid);t&&this.onHandleReceiving(t)}destroy(){this._isInit&&(this.comp.context.post_render_callbacks.splice(this.comp.context.post_render_callbacks.indexOf(this.onHandleSending),1),this.comp.context.connection.stopListen(this.networkingKey,this.onHandleReceiving),this.comp=null,this._isInit=!1)}notifyChanged(e,t){this._isReceiving||(Vo&&console.log("Property changed: "+e,t),this.hasChanges=!0,this.changedProperties[e]=t)}}function cA(o,e){let t=e!==o;return!t&&o&&e&&(Array.isArray(o)&&Array.isArray(e)||typeof o=="object"&&typeof e=="object")&&(t=!0),t}const eh=Symbol("AutoSyncHandler");function hA(o){if(o[eh])return o[eh];const e=N0.getOrCreateSyncer(o);return e?.init(o),o[eh]=e,e}function dA(o){const e=o[eh];e&&(N0.removeSyncer(e),e.destroy(),delete o[eh])}const W0=function(o=null){return function(e,t){var s;let n="";typeof t=="string"?n=t:n=t.name;let r=null,l;typeof o=="string"?l=e[o]:typeof o=="function"&&(l=o),l==null&&(F()||Vo)&&o!=null&&console.warn('syncField: no callback function found for property "'+n+'"','"'+o+'"');const c=e,h=c.__internalAwake;if(typeof h!="function"){(Vo||F())&&console.error('@syncField can currently only used on Needle Engine Components, custom object of type "'+((s=e?.constructor)==null?void 0:s.name)+'" is not supported',e);return}Vo&&console.log(n);const d=Symbol(n);c.__internalAwake=function(){if(this[d]!==void 0)return;this[d]=this[n],r=N0.getOrCreateSyncer(this);const p=Object.getOwnPropertyDescriptor(this,n);if(p?.set===void 0){let g=!1;Object.defineProperty(this,n,{set:function(f){var y;const b=this[d];if(this[d]=f,g){(F()||Vo)&&console.warn("Recursive call detected",n);return}g=!0;try{const v=cA(f,b);Vo&&console.log("SyncField assignment",n,"changed?",v,f,l),v&&l?.call(this,f,b)!==!1&&((y=hA(this))==null||y.notifyChanged(n,f))}finally{g=!1}},get:function(){return this[d]},configurable:!0,enumerable:!0})}r?.init(this),h.call(this)};const u=c.__internalDestroy;c.__internalDestroy=function(){dA(this),u.call(this)}}};var uA=Object.defineProperty,pp=(o,e,t,s)=>{for(var n=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=l(e,t,n)||n);return n&&uA(e,t,n),n};const Jt=C("debugplayersync"),mp=class xC extends I{constructor(){super(...arguments),a(this,"autoSync",!0),a(this,"asset"),a(this,"onPlayerSpawned"),a(this,"_localInstance"),a(this,"onJoinedRoom",()=>{Jt&&console.log("PlayerSync.joinedRoom. autoSync is set to "+this.autoSync),this.autoSync&&this.getInstance()}),a(this,"destroyInstance",()=>{var e;(e=this._localInstance)==null||e.then(t=>{Jt&&console.log("PlayerSync.destroyInstance",t),mc(t,this.context.connection,!0,{saveInRoom:!1})}),this._localInstance=void 0})}static async setupFrom(e,t){const s=ce.getOrCreateFromUrl(e);if(!s.asset){const l=await s.loadAssetAsync();l&&P.getOrAddComponent(l,Ms)}const n=new xC;n._internalInit(t),n.asset=s;const r=new E;return r.guid=e,P.addComponent(r,n),n}awake(){this.watchTabVisible(),this.onPlayerSpawned||(this.onPlayerSpawned=new xe)}onEnable(){this.context.connection.beginListen(ie.RoomStateSent,this.onJoinedRoom),this.context.connection.beginListen(ie.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(ie.LeftRoom,this.destroyInstance),this.context.connection.isInRoom&&this.onJoinedRoom()}onDisable(){this.context.connection.stopListen(ie.RoomStateSent,this.onJoinedRoom),this.context.connection.stopListen(ie.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(ie.LeftRoom,this.destroyInstance)}async getInstance(){var e,t,s,n,r,l;if(this._localInstance)return this._localInstance;if(Jt&&console.log("PlayerSync.createInstance",(e=this.asset)==null?void 0:e.url),!((t=this.asset)!=null&&t.asset)&&!((s=this.asset)!=null&&s.url))return console.error('PlayerSync: can not create an instance because "asset" is not set and or has no URL!'),null;this.gameObject.guid||console.warn("PlayerSync: gameObject has no guid! This might cause issues with syncing the player state."),this._localInstance=(n=this.asset)==null?void 0:n.instantiateSynced({parent:this.gameObject,deleteOnDisconnect:!0},!0);const c=await this._localInstance;if(c){const h=P.getComponentsInChildren(c,Ms);if(Jt&&console.log(`PlayerSync.createInstance: found ${h?.length} PlayerState components. Owner: ${this.context.connection.connectionId}`),h!=null&&h.length){for(const d of h)d.owner=this.context.connection.connectionId;(r=this.onPlayerSpawned)==null||r.invoke(c)}else this._localInstance=void 0,console.error("<strong>Failed finding PlayerState on "+((l=this.asset)==null?void 0:l.url)+"</strong>: please make sure the asset has a PlayerState component!"),P.destroySynced(c)}else this._localInstance=void 0,console.warn("PlayerSync: failed instantiating asset!");return this._localInstance}watchTabVisible(){window.addEventListener("visibilitychange",e=>{if(document.visibilityState==="visible")for(let t=Ms.all.length-1;t>=0;t--){const s=Ms.all[t];(!s.owner||!this.context.connection.userIsInRoom(s.owner))&&s.doDestroy()}})}};pp([m()],mp.prototype,"autoSync"),pp([m(ce)],mp.prototype,"asset"),pp([m(xe)],mp.prototype,"onPlayerSpawned");let V0=mp;var G1=(o=>(o.OwnerChanged="ownerChanged",o))(G1||{}),Ke;const H0=(Ke=class extends I{constructor(){super(...arguments),a(this,"onOwnerChangeEvent",new xe),a(this,"onFirstOwnerChangeEvent",new xe),a(this,"hasOwner",!1),a(this,"owner"),a(this,"dontDestroy",!1),a(this,"onUserLeftRoom",o=>{if(o.userId===this.owner){Jt&&console.log("PLAYERSYNC LEFT",this.owner),this.doDestroy();return}})}static get all(){return Ke._all}static get local(){return Ke._local}static getFor(o){if(o instanceof E)return P.getComponentInParent(o,Ke);if(o instanceof I)return P.getComponentInParent(o.gameObject,Ke)}static isLocalPlayer(o){const e=Ke.getFor(o);return e?.isLocalPlayer??!1}static addEventListener(o,e){return this._callbacks[o]||(this._callbacks[o]=[]),this._callbacks[o].push(e),e}static removeEventListener(o,e){if(!this._callbacks[o])return;const t=this._callbacks[o].indexOf(e);t>=0&&this._callbacks[o].splice(t,1)}static dispatchEvent(o,e){if(this._callbacks[o])for(const t of this._callbacks[o])t(e)}get isLocalPlayer(){return this.owner===this.context.connection.connectionId}onOwnerChange(o,e){var t,s;Jt&&console.log(`PlayerSync.onOwnerChange: ${e} \u2192 ${o} (me: ${this.context.connection.connectionId})`);const n=Ke._local.indexOf(this);n>=0&&Ke._local.splice(n,1);const r={playerState:this,oldValue:e,newValue:o};if(this.hasOwner||(this.hasOwner=!0,(t=this.onFirstOwnerChangeEvent)==null||t.invoke(r)),(s=this.onOwnerChangeEvent)==null||s.invoke(r),this.owner===this.context.connection.connectionId){Ke._local.push(this);const c=new CustomEvent("local-owner-changed",{detail:r});this.dispatchEvent(c)}const l=new CustomEvent("owner-changed",{detail:r});this.dispatchEvent(l),Ke.dispatchEvent("ownerChanged",l)}awake(){Ke.all.push(this),Jt&&console.log("Registered new PlayerState",this.guid,Ke.all.length-1,Ke.all),this.context.connection.beginListen(ie.UserLeftRoom,this.onUserLeftRoom)}async start(){Jt&&console.log("PLAYERSTATE.START, owner: "+this.owner,this.context.connection.usersInRoom([])),this.owner?(this.context.connection.isInRoom||await ys(300),this.context.connection.userIsInRoom(this.owner)==!1&&(Jt&&console.log(`PlayerSync.start \u2192 doDestroy "${this.name}" because user "${this.owner}" is not in room anymore...`,"Currently in room:",...this.context.connection.usersInRoom()),this.doDestroy())):this.owner||(Jt&&console.warn("PlayerState.start \u2192 owner is undefined!",this.name),setTimeout(()=>{!this.destroyed&&!this.owner?this.dontDestroy?Jt&&console.warn("PlayerState.start \u2192 owner is still undefined but dontDestroy is set to true",this.name):(Jt&&console.warn(`PlayerState.start \u2192 owner is still undefined: destroying "${this.name}" instance now`),this.doDestroy()):Jt&&console.log("PlayerState.start \u2192 owner is assigned",this.owner)},2e3))}doDestroy(){Jt&&console.log("PlayerSync.doDestroy \u2192 syncDestroy",this.name),mc(this.gameObject,this.context.connection,!0,{saveInRoom:!1})}onDestroy(){if(Jt&&console.warn("PlayerState.onDestroy",this.owner),this.context.connection.stopListen(ie.UserLeftRoom,this.onUserLeftRoom),Ke.all.splice(Ke.all.indexOf(this),1),this.isLocalPlayer){const o=Ke._local.indexOf(this);o>=0&&Ke._local.splice(o,1)}}},a(Ke,"_all",[]),a(Ke,"_local",[]),a(Ke,"_callbacks",{}),Ke);pp([W0(H0.prototype.onOwnerChange)],H0.prototype,"owner");let Ms=H0;var pA=Object.defineProperty,ml=(o,e,t,s)=>{for(var n=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=l(e,t,n)||n);return n&&pA(e,t,n),n};class un extends I{constructor(){super(...arguments),a(this,"position","bottom"),a(this,"showNeedleLogo",!1),a(this,"showSpatialMenu"),a(this,"createFullscreenButton"),a(this,"createMuteButton"),a(this,"createQRCodeButton")}onEnable(){this.applyOptions()}applyOptions(){this.context.menu.setPosition(this.position),this.context.menu.showNeedleLogo(this.showNeedleLogo),this.createFullscreenButton===!0&&this.context.menu.showFullscreenOption(!0),this.createMuteButton===!0&&this.context.menu.showAudioPlaybackOption(!0),this.showSpatialMenu===!0&&this.context.menu.showSpatialMenu(this.showSpatialMenu),this.createQRCodeButton===!0&&(Y.isMobileDevice()||this.context.menu.showQRCodeButton(!0))}}ml([m()],un.prototype,"position"),ml([m()],un.prototype,"showNeedleLogo"),ml([m()],un.prototype,"showSpatialMenu"),ml([m()],un.prototype,"createFullscreenButton"),ml([m()],un.prototype,"createMuteButton"),ml([m()],un.prototype,"createQRCodeButton");var mA=Object.defineProperty,$0=(o,e,t,s)=>{for(var n=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=l(e,t,n)||n);return n&&mA(e,t,n),n};const th=C("debugwebxr"),q1=new H().setFromAxisAngle(new x(0,1,0),Math.PI);class Ho extends I{constructor(){super(...arguments),a(this,"head"),a(this,"leftHand"),a(this,"rightHand"),a(this,"_leftHandMeshes"),a(this,"_rightHandMeshes"),a(this,"_syncTransforms")}async onEnterXR(e){if(!this.activeAndEnabled)return;th&&console.warn("AVATAR ENTER XR",this.guid,this.sourceId,this,this.activeAndEnabled),this._syncTransforms&&(this._syncTransforms.length=0),await this.prepareAvatar();const t=Ms.getFor(this);if(t!=null&&t.owner){const s=this.gameObject.addComponent(ci);s.avatar=this.gameObject,s.connectionId=t.owner}else this.context.connection.isConnected?console.error("No player state found for avatar",this):t&&!this.context.connection.isConnected&&(t.dontDestroy=!0)}onLeaveXR(e){const t=this.gameObject.getComponent(ci);t&&t.destroy()}onUpdateXR(e){var t,s;if(!this.activeAndEnabled)return;const n=Ms.isLocalPlayer(this);if(!n)return;const r=e.xr;if(r.rig&&r.rig.gameObject!==this.gameObject.parent&&(this.gameObject.position.set(0,0,0),this.gameObject.rotation.set(0,0,0),this.gameObject.scale.set(1,1,1),r.rig.gameObject.add(this.gameObject)),this._syncTransforms&&n)for(const u of this._syncTransforms)u.fastMode=!0,u.isOwned()||u.requestOwnership();if(this.head&&this.context.mainCamera){const u=this.head.asset;if(u.position.copy(this.context.mainCamera.position),u.position.x*=-1,u.position.z*=-1,u.quaternion.copy(this.context.mainCamera.quaternion),u.quaternion.x*=-1,this.context.time.frameCount%10===0&&this.head.asset){const p=P.getComponentsInChildren(this.head.asset,ns);for(const g of p)g.enabled=!1,g.gameObject.visible=!1}}const l=e.xr.leftController,c=(t=this.leftHand)==null?void 0:t.asset;l&&c?(c.position.copy(l.gripPosition),c.quaternion.copy(l.gripQuaternion),c.quaternion.multiply(q1),c.visible=l.isTracking,this.updateHandVisibility(l,c,this._leftHandMeshes)):c&&c.visible&&(c.visible=!1);const h=e.xr.rightController,d=(s=this.rightHand)==null?void 0:s.asset;h&&d?(d.position.copy(h.gripPosition),d.quaternion.copy(h.gripQuaternion),d.quaternion.multiply(q1),d.visible=h.isTracking,this.updateHandVisibility(h,d,this._rightHandMeshes)):d&&d.visible&&(d.visible=!1)}onBeforeRender(){this.context.xr&&this.context.time.frame%10===0&&this.updateRemoteAvatarVisibility()}updateHandVisibility(e,t,s){if(s){const n=e.model&&e.model.visible&&e.model!==t;s.forEach(r=>{Bn(r,!n)})}}updateRemoteAvatarVisibility(){var e,t,s;if(this.context.connection.isConnected){const n=Ms.getFor(this);if(n&&n.isLocalPlayer==!1){const r=ne.getXRSync(this.context);if(r&&r.hasState(n.owner)){this.tryFindAvatarObjectsIfMissing();const l=(e=this.leftHand)==null?void 0:e.asset;l&&(l.visible=r?.isTracking(n.owner,"left")??!1);const c=(t=this.rightHand)==null?void 0:t.asset;c&&(c.visible=r?.isTracking(n.owner,"right")??!1)}if((s=this.head)!=null&&s.asset){const l=P.getComponentsInChildren(this.head.asset,ns);for(const c of l)c.enabled=!1,c.gameObject.visible=!0}}}}tryFindAvatarObjectsIfMissing(){if(!this.head||!this.leftHand||!this.rightHand){const e={head:this.head,leftHand:this.leftHand,rightHand:this.rightHand};x_.tryFindAvatarObjects(this.gameObject,this.sourceId||"",e),e.head&&(this.head=e.head),e.leftHand&&(this.leftHand=e.leftHand),e.rightHand&&(this.rightHand=e.rightHand)}}async prepareAvatar(){var e,t;if(this.tryFindAvatarObjectsIfMissing(),this.head)this.head instanceof E&&(this.head=new ce("",this.sourceId,this.head));else{const s=new E;s.name="Head";const n=_o.createPrimitive(wr.Cube);s.add(n),this.gameObject.add(s),this.head=new ce("",this.sourceId,s),th&&console.log("Create head",s)}if(this.rightHand)this.rightHand instanceof E&&(this.rightHand=new ce("",this.sourceId,this.rightHand));else{const s=new E;s.name="Right Hand",this.gameObject.add(s),this.rightHand=new ce("",this.sourceId,s),th&&console.log("Create right hand",s)}if(this.leftHand)this.leftHand instanceof E&&(this.leftHand=new ce("",this.sourceId,this.leftHand));else{const s=new E;s.name="Left Hand",this.gameObject.add(s),this.leftHand=new ce("",this.sourceId,s),th&&console.log("Create left hand",s)}await this.loadAvatarObjects(this.head,this.leftHand,this.rightHand),this._leftHandMeshes=[],(e=this.leftHand.asset)==null||e.traverse(s=>{s!=null&&s.isMesh&&this._leftHandMeshes.push(s)}),this._rightHandMeshes=[],(t=this.rightHand.asset)==null||t.traverse(s=>{s!=null&&s.isMesh&&this._rightHandMeshes.push(s)}),Ms.isLocalPlayer(this.gameObject)&&(this._syncTransforms=P.getComponentsInChildren(this.gameObject,sn))}async loadAvatarObjects(e,t,s){const n=e.loadAssetAsync(),r=t.loadAssetAsync(),l=s.loadAssetAsync(),c=new Array;n&&c.push(n),r&&c.push(r),l&&c.push(l);const h=await Xm(c);th&&console.log("Avatar loaded results:",h)}}$0([m(ce)],Ho.prototype,"head"),$0([m(ce)],Ho.prototype,"leftHand"),$0([m(ce)],Ho.prototype,"rightHand");var gA=Object.defineProperty,gp=(o,e,t,s)=>{for(var n=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=l(e,t,n)||n);return n&&gA(e,t,n),n};const Yn=C("debugwebxr"),$o=new Array;class pn extends I{constructor(){super(...arguments),a(this,"createControllerModel",!0),a(this,"createHandModel",!0),a(this,"customLeftHand"),a(this,"customRightHand"),a(this,"_models",new Array)}supportsXR(e){return e==="immersive-vr"||e==="immersive-ar"}async onXRControllerAdded(e){var t;if(!(e.xr.isVR||e.xr.isPassThrough))return;const{controller:s}=e;if(Yn&&console.warn("Add Controller Model for",s.side,s.index),this.createControllerModel||this.createHandModel){if(s.hand){if(this.createHandModel){const n=await this.loadHandModel(this,s);if(!n||!s.connected||!s.isHand){n!=null&&n.handObject&&Na(n.handObject,!1),(t=n?.handObject)==null||t.destroy();return}this._models.push({controller:s,model:n.handObject,handmesh:n.handmesh}),this._models.sort((r,l)=>r.controller.index-l.controller.index),this.scene.add(n.handObject),s.model=n.handObject}}else if(this.createControllerModel){const n=await s.getModelUrl();if(n){const r=await this.loadModel(s,n);if(!r||!s.connected||s.isHand)return;this._models.push({controller:s,model:r}),this._models.sort((l,c)=>l.controller.index-c.controller.index),this.scene.add(r),r.traverse(l=>{l.layers.set(2),l.matrixAutoUpdate=!1,l.updateMatrix()}),s.model=r}else s.targetRayMode!=="transient-pointer"&&console.warn("XRControllerModel: no model found for "+s.side)}}}onXRControllerRemoved(e){console.debug("XR Controller Removed",e.controller.side,e.controller.index);const t=this._models.findIndex(n=>n.controller===e.controller),s=this._models[t];s&&(this._models.splice(t,1),s.model&&(Na(s.model,!1),s.model.destroy(),s.model=void 0))}onBeforeXR(e,t){this.createHandModel&&(this.customLeftHand||this.customRightHand)&&(t.optionalFeatures=t.optionalFeatures||[],t.optionalFeatures.includes("hand-tracking")||t.optionalFeatures.push("hand-tracking"))}onLeaveXR(e){for(const t of this._models)t&&(t.model&&(Na(t.model,!1),t.model.destroy(),t.model=void 0),t.controller.model===t.model&&(t.controller.model=null));this._models.length=0}onBeforeRender(){if(ne.active&&(Yn&&($o[0]=Date.now()),this.updateRendering(ne.active),Yn)){const e=Date.now()-$o[0];$o.push(e),$o.length>=30&&($o[0]=0,$o.reduce((t,s)=>t+s,0)/$o.length,$o.length=0)}}updateRendering(e){var t,s,n,r,l;for(let c=0;c<this._models.length;c++){const h=this._models[c];if(!h)continue;const d=h.controller;if(!d.connected){Yn&&console.warn("XRControllerModel.onUpdateXR: controller is not connected anymore",d.side,d.hand);continue}if(h.model&&!h.handmesh)h.model.matrixAutoUpdate=!1,h.model.matrix.copy(d.gripMatrix),h.model.visible=d.isTracking,(t=e.rig)==null||t.gameObject.add(h.model);else if(d.inputSource.hand&&h.handmesh){const u=e.referenceSpace,p=this.context.renderer.xr.getHand(d.index);if(u&&e.frame.getJointPose){for(const g of d.inputSource.hand.values()){const f=p.joints[g.jointName];if(f){const y=d.getHandJointPose(g);if(y){const b=y.transform.position,v=y.transform.orientation;f.position.copy(b),f.quaternion.copy(v),f.matrixAutoUpdate=!1}f.visible=y!=null}}h.model&&(h.model.visible=d.isTracking,h.model.visible&&h.model.parent!==((s=e.rig)==null?void 0:s.gameObject)&&((n=e.rig)==null||n.gameObject.add(h.model))),(r=h.model)!=null&&r.visible&&((l=h.handmesh)==null||l.updateMesh(),h.model.matrixAutoUpdate=!1,h.model.matrix.identity(),h.model.applyMatrix4(Ea))}}}}async loadModel(e,t){var s;if(!e.connected)return console.warn("XRControllerModel.onXRControllerAdded: controller is not connected anymore",e.side),null;const n=await ce.getOrCreate("",t).instantiate();return Na(n),(s=ne.active)!=null&&s.isPassThrough&&n.traverseVisible(r=>{this.makeOccluder(r)}),n}async loadHandModel(e,t){const s=this.context,n=s.renderer.xr.getHand(t.index);n||(Yn?G.DrawLabel(t.rayWorldPosition,"No hand found for index "+t.index,.05,5):console.warn("No hand found for index "+t.index));const r=new Rn;Tf(r,s),await Qu(r,s,this.sourceId??"");const l=u0(r);let c="";const h=t.side==="left"?this.customLeftHand:this.customRightHand;h?(c=h.url.split(".").slice(0,-1).join("."),r.setPath("")):(c=t.inputSource.handedness==="left"?"left":"right",r.setPath("https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles/generic-hand/"));const d=new E;Na(d);const u=new sO(d,n,r.path,c,r,p=>{var g;const f=l?.gltf;((g=f?.scene.children)==null?void 0:g.length)===0&&(f.scene.children[0]=p),l!=null&&l.gltf&&ws().createBuiltinComponents(e.context,e.sourceId||c,l.gltf,null,l),p.traverse(y=>{var b;y.layers.set(2),(b=ne.active)!=null&&b.isPassThrough&&!h&&this.makeOccluder(y),y instanceof q&&Xe.assignMeshLOD(y,0)}),t.connected||(Yn&&G.DrawLabel(t.rayWorldPosition,"Hand is loaded but not connected anymore",.05,5),p.removeFromParent())});if(Yn&&d.add(new Si(.5)),t.inputSource.hand){Yn&&console.log(t.inputSource.hand);for(const p of t.inputSource.hand.values())if(n.joints[p.jointName]===void 0){const g=new po;g.matrixAutoUpdate=!1,g.visible=!0,n.joints[p.jointName]=g,n.add(g)}}else Yn&&G.DrawLabel(t.rayWorldPosition,"No inputSource.hand found for index "+t.index,.05,5);return{handObject:d,handmesh:u}}makeOccluder(e){if(e instanceof q){let t=e.material;t instanceof Pe&&(t=e.material=t.clone(),t.depthWrite=!0,t.depthTest=!0,t.colorWrite=!1,e.receiveShadow=!1,e.renderOrder=-100)}}}a(pn,"factory",new iO),gp([m()],pn.prototype,"createControllerModel"),gp([m()],pn.prototype,"createHandModel"),gp([m(ce)],pn.prototype,"customLeftHand"),gp([m(ce)],pn.prototype,"customRightHand");class fp extends I{}var fA=Object.defineProperty,Go=(o,e,t,s)=>{for(var n=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=l(e,t,n)||n);return n&&fA(e,t,n),n};const G0=C("debugwebxr");class zi extends I{constructor(){super(...arguments),a(this,"movementSpeed",1.5),a(this,"rotationStep",30),a(this,"useTeleport",!0),a(this,"usePinchToTeleport",!0),a(this,"useTeleportTarget",!1),a(this,"useTeleportFade",!1),a(this,"showRays",!0),a(this,"showHits",!0),a(this,"isXRMovementHandler",!0),a(this,"xrSessionMode","immersive-vr"),a(this,"_didApplyRotation",!1),a(this,"_didTeleport",!1),a(this,"_teleportBuffer",new Array),a(this,"_plane",null),a(this,"_lines",[]),a(this,"_hitDiscs",[]),a(this,"_hitDistances",[]),a(this,"_lastHitDistances",[]),a(this,"hitPointRaycastFilter",e=>e.type==="SkinnedMesh"?"continue in children":!0)}onUpdateXR(e){const t=e.xr.rig;if(!(t!=null&&t.gameObject)||e.xr.isPassThrough)return;const s=e.xr.leftController,n=e.xr.rightController;s&&this.onHandleMovement(s,t.gameObject),n&&(this.onHandleRotation(n,t.gameObject),this.useTeleport&&this.onHandleTeleport(n,t.gameObject))}onLeaveXR(e){for(const t of this._lines)t.removeFromParent();for(const t of this._hitDiscs)t?.removeFromParent()}onBeforeRender(){var e;(e=this.context.xr)!=null&&e.running&&(this.showRays&&this.renderRays(this.context.xr),this.showHits&&this.renderHits(this.context.xr))}onHandleMovement(e,t){const s=e.getStick("xr-standard-thumbstick");if(s.x!=0||s.y!=0){const n=X(s.x,0,s.y);n.multiplyScalar(this.context.time.deltaTimeUnscaled*this.movementSpeed);const r=Ge(t);n.multiplyScalar(r.x),n.applyQuaternion(e.xr.poseOrientation),n.y=0,n.applyQuaternion(t.worldQuaternion),t.position.add(n),t.updateWorldMatrix(!1,!1);for(const l of t.children)l.updateWorldMatrix(!1,!1)}}onHandleRotation(e,t){if(e._isMxInk)return;const s=e.getStick("xr-standard-thumbstick").x;if(this._didApplyRotation)Math.abs(s)<.3&&(this._didApplyRotation=!1);else if(Math.abs(s)>.5){this._didApplyRotation=!0;const n=s>0?1:-1,r=te(this.context.mainCamera).clone();t.rotateY(n*W.toRadians(this.rotationStep));const l=te(this.context.mainCamera).clone().sub(r);l.y=0,t.position.sub(l)}}onHandleTeleport(e,t){var s,n,r,l,c;let h=0;if(e.hand&&this.usePinchToTeleport&&e.isTeleportGesture){const d=e.getPointerId("primary");if(d!=null&&this.context.input.getIsPointerIdInUse(d))return;const u=e.getGesture("pinch");u&&(h=u.value)}else h=(s=e.getStick("xr-standard-thumbstick"))==null?void 0:s.y;if(this._didTeleport)h>=0&&h<.4?this._didTeleport=!1:h<0&&h>-.4&&(this._didTeleport=!1);else if(h>.8){this._didTeleport=!0;const d=this.context.physics.raycastFromRay(e.ray)[0];if(d&&d.object instanceof Ca){const p=(n=d.normal)==null?void 0:n.dot(X(0,1,0));if(p!==void 0&&p<.4)return}let u=d?.point;if(!u&&!this.useTeleportTarget){this._plane||(this._plane=new mr(new x(0,1,0),0));const p=t.worldPosition;this._plane.setFromNormalAndCoplanarPoint(new x(0,1,0),p);const g=e.ray;u=p.clone(),this._plane.intersectLine(new PP(g.origin,X(g.direction).multiplyScalar(1e4).add(g.origin)),u),u.distanceTo(p)>t.scale.x*10&&(u=null)}if(u){if(this.useTeleportTarget&&!P.getComponentInParent(d.object,fp))return;const p=u.clone();if(G0&&G.DrawSphere(u,.025,16711680,5),(r=this.context.mainCamera)==null?void 0:r.position){const g=(l=this.context.xr)==null?void 0:l.getUserOffsetInRig();g&&(g.y=0,p.sub(g),G0&&G.DrawWireSphere(g.add(p),.025,65280,5))}this._teleportBuffer.push(t.matrix.clone()),this._teleportBuffer.length>10&&this._teleportBuffer.shift(),this.useTeleportFade?(c=e.xr.fadeTransition())==null||c.then(()=>{t.worldPosition=p}):t.worldPosition=p}}else if(h<-.8&&(this._didTeleport=!0,this._teleportBuffer.length>0)){const d=this._teleportBuffer.pop();d&&d.decompose(t.position,t.quaternion,t.scale)}}renderRays(e){var t;for(let s=0;s<this._lines.length;s++){const n=this._lines[s];n&&(n.visible=!1)}for(let s=0;s<e.controllers.length;s++){const n=e.controllers[s];let r=this._lines[s];if(!n.connected||!n.isTracking||!n.ray||n.targetRayMode==="transient-pointer"||!n.hasSelectEvent){r&&(r.visible=!1);continue}r||(r=this.createRayLineObject(),r.scale.z=.5,this._lines[s]=r),n.updateRayWorldPosition(),n.updateRayWorldQuaternion();const l=n.rayWorldPosition,c=n.rayWorldQuaternion;r.position.copy(l),r.quaternion.copy(c);const h=e.rigScale,d=this.usePinchToTeleport&&n.isTeleportGesture,u=this._lastHitDistances[s],p=this._hitDistances[s]!=null,g=u??h;r.scale.set(h,h,g),r.visible=!0,r.layers.disableAll(),r.layers.enable(2);let f=r.material.opacity;d?f=1:this.showHits&&g<e.rigScale*.5?f=0:(t=n.getButton("primary"))!=null&&t.pressed?f=.5:f=p?.2:.1,r.material.opacity=W.lerp(r.material.opacity,f,this.context.time.deltaTimeUnscaled/.1),r.parent!==this.context.scene&&this.context.scene.add(r)}}renderHits(e){var t;for(const s of this._hitDiscs){if(!s)continue;const n=s.controller;if(!n||!n.connected||!n.isTracking){s.visible=!1;continue}}for(let s=0;s<e.controllers.length;s++){const n=e.controllers[s];if(!n.connected||!n.isTracking||!n.ray||!n.hasSelectEvent)continue;let r=this._hitDiscs[s],l=!0;const c=n.getPointerId("primary");c!=null&&this.context.input.getIsPointerIdInUse(c)&&(r&&(r.visible=!1),this._hitDistances[s]=null,this._lastHitDistances[s]=0,l=!1);const h=this.context.time.smoothedFps>=59?1:10;if((this.context.time.frame+n.index)%h!==0&&(l=!1),!l){const p=this._hitDiscs[s];p&&p.visible&&p.hit&&this.updateHitPointerPosition(n,p,p.hit.distance);continue}const d=this.context.physics.raycastFromRay(n.ray,{testObject:this.hitPointRaycastFilter,precise:!1});let u=d.find(p=>this.usePinchToTeleport&&n.isTeleportGesture?!0:this.isObjectWithInteractiveComponent(p.object));if(u||(u=d[0]),r&&(r.controller=n,r.hit=u),this._hitDistances[s]=u?.distance||null,u){this._lastHitDistances[s]=u.distance;const p=e.rigScale??1;G0&&(G.DrawWireSphere(u.point,.025*p,16711680),G.DrawLabel(X(0,.2,0).add(u.point),u.object.name,.02,0)),r||(r=this.createHitPointObject(),this._hitDiscs[s]=r),r.hit=u,r.visible=u.distance>p*.05;let g=.01*(p+u.distance);const f=(t=n.getButton("primary"))==null?void 0:t.pressed;f&&(g*=1.1),r.scale.set(g,g,g),r.layers.set(2);let y=r.material.opacity;if(f?y=1:y=u.distance<.15*p?.2:.6,r.material.opacity=W.lerp(r.material.opacity,y,this.context.time.deltaTimeUnscaled/.1),r.visible){if(u.normal){this.updateHitPointerPosition(n,r,u.distance);const b=u.normal.applyQuaternion(Se(u.object));r.quaternion.setFromUnitVectors(yA,b)}else this.updateHitPointerPosition(n,r,u.distance);r.parent!==this.context.scene&&this.context.scene.add(r)}}else this._hitDiscs[s]&&(this._hitDiscs[s].visible=!1)}}isObjectWithInteractiveComponent(e,t=0){return Ou(e)||e.isUI===!0?!0:e.isScene?!1:e.parent?this.isObjectWithInteractiveComponent(e.parent,t+1):!1}updateHitPointerPosition(e,t,s){const n=X(e.rayWorldPosition);n.add(X(0,0,s-.01).applyQuaternion(e.rayWorldQuaternion)),t.position.lerp(n,this.context.time.deltaTimeUnscaled/.05)}createHitPointObject(){const e=new q(new dd(.3,6,6),new Me({color:15658734,opacity:.7,transparent:!0,depthTest:!1,depthWrite:!1,side:Ci}));return e.layers.disableAll(),e.layers.enable(2),e}createRayLineObject(){const e=new nO;e.layers.disableAll(),e.layers.enable(2);const t=new oO;e.geometry=t;const s=new Float32Array(9);s.set([0,0,.02,0,0,.4,0,0,1]),t.setPositions(s);const n=new Float32Array(9);n.set([1,1,1,.1,.1,.1,0,0,0]),t.setColors(n);const r=new rO({color:16777215,vertexColors:!0,worldUnits:!0,linewidth:.004,transparent:!0,depthWrite:!1,blending:Lv,dashed:!1});return e.material=r,e}}Go([m()],zi.prototype,"movementSpeed"),Go([m()],zi.prototype,"rotationStep"),Go([m()],zi.prototype,"useTeleport"),Go([m()],zi.prototype,"usePinchToTeleport"),Go([m()],zi.prototype,"useTeleportTarget"),Go([m()],zi.prototype,"useTeleportFade"),Go([m()],zi.prototype,"showRays"),Go([m()],zi.prototype,"showHits");const yA=new x(0,1,0);var vA=Object.defineProperty,St=(o,e,t,s)=>{for(var n=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=l(e,t,n)||n);return n&&vA(e,t,n),n};const ih=C("debugwebxr"),bA=C("debugusdz");var qo;const pt=(qo=class extends I{constructor(){super(...arguments),a(this,"createVRButton",!0),a(this,"createARButton",!0),a(this,"createSendToQuestButton",!0),a(this,"createQRCode",!0),a(this,"useDefaultControls",!0),a(this,"showControllerModels",!0),a(this,"showHandModels",!0),a(this,"usePlacementReticle",!0),a(this,"customARPlacementReticle"),a(this,"usePlacementAdjustment",!0),a(this,"arScale",1),a(this,"useXRAnchor",!1),a(this,"autoPlace",!1),a(this,"autoCenter",!1),a(this,"useQuicklookExport",!1),a(this,"useDepthSensing",!1),a(this,"useSpatialGrab",!0),a(this,"defaultAvatar"),a(this,"_playerSync"),a(this,"_createdComponentsInSession",[]),a(this,"_usdzExporter"),a(this,"_exitXRMenuButton"),a(this,"_previousXRState",0),a(this,"_spatialGrabRaycaster"),a(this,"_activeWebARSessionRoot",null),a(this,"onAvatarSpawned",o=>{ih&&console.log("WebXR.onAvatarSpawned",o),P.getComponentInChildren(o,Ho)??(i=P.addComponent(o,Ho))}),a(this,"_buttonFactory"),a(this,"_buttons",[])}awake(){ne.getXRSync(this.context)}onEnable(){var o,e;window.location.protocol!=="https:"&&be('<a href="https://developer.mozilla.org/en-US/docs/Web/API/WebXR_Device_API" target="_blank">WebXR</a> only works on secure connections (https).'),this.useQuicklookExport&&(P.findObjectOfType(gn)||(ih&&console.log("WebXR: Adding USDZExporter"),this._usdzExporter=P.addComponent(this.gameObject,gn),this._usdzExporter.objectToExport=this.context.scene,this._usdzExporter.autoExportAnimations=!0,this._usdzExporter.autoExportAudioSources=!0)),this.handleCreatingHTML(),this.handleOfferSession(),this.defaultAvatar===!0&&(ih&&console.warn("WebXR: No default avatar set, using static default avatar"),this.defaultAvatar=new ce("https://cdn.needle.tools/static/avatars/DefaultAvatar.glb")),this.defaultAvatar&&(this._playerSync=this.gameObject.getOrAddComponent(V0),this._playerSync.autoSync=!1),this._playerSync&&typeof this.defaultAvatar!="boolean"&&(this._playerSync.asset=this.defaultAvatar,(o=this._playerSync.onPlayerSpawned)==null||o.removeEventListener(this.onAvatarSpawned),(e=this._playerSync.onPlayerSpawned)==null||e.addEventListener(this.onAvatarSpawned))}onDisable(){var o;(o=this._usdzExporter)==null||o.destroy(),this.removeButtons()}async handleOfferSession(){return this.createVRButton&&await ne.isVRSupported()&&this.createVRButton?ne.offerSession("immersive-vr","default",this.context):this.createARButton&&await ne.isARSupported()&&this.createARButton?ne.offerSession("immersive-ar","default",this.context):!1}get session(){return ne.active??null}get sessionMode(){return ne.activeMode??null}get arSessionRoot(){return this._activeWebARSessionRoot}async enterVR(o){return ne.start("immersive-vr",o,this.context)}async enterAR(o){return ne.start("immersive-ar",o,this.context)}exitXR(){ne.stop()}get isActiveWebXR(){return!qo.activeWebXRComponent||qo.activeWebXRComponent===this}onBeforeXR(o,e){var t;if(!this.isActiveWebXR){console.warn(`WebXR: another WebXR component is already active (${(t=qo.activeWebXRComponent)==null?void 0:t.name}). This is ignored: ${this.name}`);return}qo.activeWebXRComponent=this,o=="immersive-ar"&&this.useDepthSensing&&(e.optionalFeatures=e.optionalFeatures||[],e.optionalFeatures.push("depth-sensing"))}async onEnterXR(o){if(!this.isActiveWebXR)return;ih&&console.log("WebXR onEnterXR"),this._previousXRState=ji.Global.Mask;const e=o.xr.isVR;if(ji.Global.Set(e?rn.VR:rn.AR),o.xr.isAR){let t=P.findObjectOfType(Wo);if(!t)if(this.usePlacementReticle){const s=new E;for(const n of this.context.scene.children)s.add(n);this.context.scene.add(s),t=P.addComponent(s,Wo),this._createdComponentsInSession.push(t)}else(ih||F())&&console.warn("WebXR: No WebARSessionRoot found in scene and usePlacementReticle is disabled in WebXR component.");this._activeWebARSessionRoot=t,t&&(t.customReticle=this.customARPlacementReticle,t.arScale=this.arScale,t.arTouchTransform=this.usePlacementAdjustment,t.autoPlace=this.autoPlace,t.autoCenter=this.autoCenter,t.useXRAnchor=this.useXRAnchor)}this.useDefaultControls&&this.setDefaultMovementEnabled(!0),(this.showControllerModels||this.showHandModels)&&this.setDefaultControllerRenderingEnabled(!0),this.useSpatialGrab&&(this._spatialGrabRaycaster=P.findObjectOfType(Lc)??void 0,this._spatialGrabRaycaster||(this._spatialGrabRaycaster=this.gameObject.addComponent(Lc))),this.createLocalAvatar(o.xr),o.xr.isScreenBasedAR||(this._exitXRMenuButton=this.context.menu.appendChild({label:"Quit XR",onClick:()=>this.exitXR(),icon:"exit_to_app",priority:2e4}))}onUpdateXR(o){this.isActiveWebXR&&this._spatialGrabRaycaster&&(this._spatialGrabRaycaster.enabled=this.useSpatialGrab)}onLeaveXR(o){var e,t;if((e=this._exitXRMenuButton)==null||e.remove(),!!this.isActiveWebXR){ji.Global.Set(this._previousXRState),(t=this._playerSync)==null||t.destroyInstance();for(const s of this._createdComponentsInSession)s.destroy();this._createdComponentsInSession.length=0,this._activeWebARSessionRoot=null,this.handleOfferSession(),Gl(1).then(()=>qo.activeWebXRComponent=null)}}setDefaultMovementEnabled(o){let e=this.gameObject.getComponent(zi);return!e&&o&&(e=this.gameObject.addComponent(zi),this._createdComponentsInSession.push(e)),e&&(e.enabled=o),e}setDefaultControllerRenderingEnabled(o){let e=this.gameObject.getComponent(pn);return!e&&o&&(e=this.gameObject.addComponent(pn),this._createdComponentsInSession.push(e),e.createControllerModel=this.showControllerModels,e.createHandModel==this.showHandModels),e&&(e.enabled=o),e}async createLocalAvatar(o){this._playerSync&&o.running&&typeof this.defaultAvatar!="boolean"&&(this._playerSync.asset=this.defaultAvatar,await this._playerSync.getInstance())}getButtonsContainer(){return this.getButtonsFactory()}getButtonsFactory(){return this._buttonFactory||(this._buttonFactory=dl.getOrCreate()),this._buttonFactory}handleCreatingHTML(){if(this.createARButton||this.createVRButton||this.useQuicklookExport){if((Y.isiOS()&&Y.isSafari()||bA)&&this.useQuicklookExport){const o=P.findObjectOfType(gn);if(!o||o&&o.allowCreateQuicklookButton){const e=this.getButtonsFactory().createQuicklookButton();this.addButton(e,50)}}if(this.createARButton){const o=this.getButtonsFactory().createARButton();this.addButton(o,50)}if(this.createVRButton){const o=this.getButtonsFactory().createVRButton();this.addButton(o,50)}}if(this.createSendToQuestButton&&!Y.isQuest()&&ne.isVRSupported().then(o=>{if(!o){const e=this.getButtonsFactory().createSendToQuestButton();this.addButton(e,50)}}),this.createQRCode){const o=_c(un);if(o&&o.createQRCodeButton===!1)F()&&console.warn("WebXR: QRCode button is disabled in the Needle Menu component");else if(!Y.isMobileDevice()){const e=Co.getOrCreate().createQRCode();this.addButton(e,50)}}}addButton(o,e){this._buttons.push(o),o.setAttribute("priority",e.toString()),this.context.menu.appendChild(o)}removeButtons(){for(const o of this._buttons)o.remove();this._buttons.length=0}},a(qo,"activeWebXRComponent",null),qo);St([m()],pt.prototype,"createVRButton"),St([m()],pt.prototype,"createARButton"),St([m()],pt.prototype,"createSendToQuestButton"),St([m()],pt.prototype,"createQRCode"),St([m()],pt.prototype,"useDefaultControls"),St([m()],pt.prototype,"showControllerModels"),St([m()],pt.prototype,"showHandModels"),St([m()],pt.prototype,"usePlacementReticle"),St([m(ce)],pt.prototype,"customARPlacementReticle"),St([m()],pt.prototype,"usePlacementAdjustment"),St([m()],pt.prototype,"arScale"),St([m()],pt.prototype,"useXRAnchor"),St([m()],pt.prototype,"autoPlace"),St([m()],pt.prototype,"autoCenter"),St([m()],pt.prototype,"useQuicklookExport"),St([m()],pt.prototype,"useDepthSensing"),St([m()],pt.prototype,"useSpatialGrab"),St([m(ce)],pt.prototype,"defaultAvatar");let yp=pt;const vp=C("debugusdzbehaviours");class q0{constructor(){a(this,"behaviours",[]),a(this,"behaviourComponents",[]),a(this,"behaviourComponentsCopy",[]),a(this,"audioClips",[]),a(this,"audioClipsCopy",[]),a(this,"targetUuids",new Set)}get extensionName(){return"Behaviour"}addBehavior(e){this.behaviours.push(e)}addAudioClip(e){if(!e||typeof e!="string")return"";const t="audio/"+ya.getName(e);return this.audioClips.push({clipUrl:e,filesKey:t}),t}getAllTargetUuids(){return this.targetUuids}onBeforeBuildDocument(e){if(!e.root)return Promise.resolve();const t=[];return e.root.traverse(s=>{P.foreachComponent(s,n=>{var r;const l=n;if(typeof l.createBehaviours=="function"||typeof l.beforeCreateDocument=="function"||typeof l.afterCreateDocument=="function"||typeof l.afterSerialize=="function"){this.behaviourComponents.push(l);const c=(r=l.beforeCreateDocument)==null?void 0:r.call(l,this,e);c instanceof Promise&&t.push(c)}},!1)}),vp&&console.log("onBeforeBuildDocument: all components",this.behaviourComponents),Promise.all(t)}onExportObject(e,t,s){var n;for(const r of this.behaviourComponents)(n=r.createBehaviours)==null||n.call(r,this,t,s)}onAfterBuildDocument(e){for(const p of this.behaviourComponents)typeof p.afterCreateDocument=="function"&&p.afterCreateDocument(this,e);this.behaviourComponentsCopy=this.behaviourComponents.slice(),this.behaviourComponents.length=0,this.audioClipsCopy=this.audioClips.slice(),this.audioClips.length=0;const t=new Set,s=new Set,n=new Set,r=new Set,l=vp;let c=`graph LR
1224
+ `,h="";function d(p){if(p instanceof zo){l&&(c+=`subgraph Group_${p.id}
1225
+ `);for(const g of p.actions)l&&(c+=`${p.id}[${p.id}] -- ${p.type},loops:${p.loops} --> ${g.id}[${g.id}]
1226
+ `),d(g);l&&(c+=`end
1227
+ `)}else if(p instanceof ks){p.tokenId==="StartAnimation"&&r.add(p);let g=p.tokenId;p.type!==void 0&&(g+=":"+p.type);const f=p.affectedObjects;if(f)if(Array.isArray(f))for(const b of f)s.add(b),l&&(h+=`${p.id}[${p.id}
1228
+ ${g}] -- ${g} --> ${b.uuid}(("${b.displayName||b.name||b.uuid}"))
1229
+ `);else typeof f=="object"?(s.add(f),l&&(h+=`${p.id}[${p.id}
1230
+ ${g}] -- ${g} --> ${f.uuid}(("${f.displayName||f.name||f.uuid}"))
1231
+ `)):typeof f=="string"&&s.add({uuid:f});const y=p.xFormTarget;y&&(typeof y=="object"?(s.add(y),l&&(h+=`${p.id}[${p.id}
1232
+ ${g}] -- ${g} --> ${y.uuid}(("${y.displayName||y.name||y.uuid}"))
1233
+ `)):typeof y=="string"&&s.add({uuid:y}))}}function u(p,g){if(Array.isArray(p))for(const f of p)u(f,g);else if(p instanceof ll){let f=p.tokenId;p.type!==void 0&&(f+=":"+p.type),typeof p.targetId=="object"&&(t.add(p.targetId),l&&(h+=`${p.targetId.uuid}(("${p.targetId.displayName}")) --> ${p.id}[${p.id}
1234
+ ${f}]
1235
+ `)),l&&(c+=`${p.id}((${p.id})) -- ${f} --> ${g.id}[${g.tokenId||g.id}]
1236
+ `)}}for(const p of this.behaviours)l&&(c+=`subgraph ${p.id}
1237
+ `),d(p.action),u(p.trigger,p.action),l&&(c+=`end
1238
+ `);l&&(c+=`
1239
+ `+h),l&&(console.log("All USDZ behaviours",this.behaviours),this.behaviours.length&&(console.warn("The Mermaid graph can be pasted into https://massive-mermaid.glitch.me/ or https://mermaid.live/edit. It should be in your clipboard already!"),console.log(c),navigator.clipboard.writeText(c)));{let p=`gantt
1240
+ title Animations
1241
+ dateFormat X
1242
+ axisFormat %s
1243
+ `;const g=Array.from(r),f=new Set;for(const _ of g)if(_.affectedObjects&&typeof _.affectedObjects!="string"){if(Array.isArray(_.affectedObjects))for(const w of _.affectedObjects)f.add(w);else f.add(_.affectedObjects);l&&(p+=`section ${_.animationName} (${_.id})
1244
+ `,p+=`${_.id} : ${_.start}, ${_.duration}s
1245
+ `)}l&&r.size&&console.log(p);const y=new Set;for(const _ of f){_.getPath||console.error("USDZExporter: Animation target object has no getPath method. This is likely a bug",_);let w=_.getPath();w.startsWith("<")&&(w=w.substring(1)),w.endsWith(">")&&(w=w.substring(0,w.length-1)),y.add({path:w,obj:_})}const b=Array.from(y).sort((_,w)=>_.path.length-w.path.length),v=new Array;for(let _=0;_<b.length;_++)for(let w=_+1;w<b.length;w++)if(b[w].path.startsWith(b[_].path)){const S=b[w],k=b[_];v.push({child:S.obj.displayName+" ("+S.path+")",parent:k.obj.displayName+" ("+k.path+")"})}v.length&&console.warn("USDZExporter: There are overlapping PlayAnimation actions. This can lead to undefined runtime behaviour when playing multiple animations. Please restructure the hierarchy so that animations don't overlap.",{overlappingTargets:v,playAnimationActions:r})}for(const p of new Set([...t,...s]))if(Array.isArray(p))for(const g of p)n.add(g.uuid);else n.add(p.uuid);vp&&console.log("All Behavior trigger sources and action targets",t,s,n),this.targetUuids=new Set(n)}onAfterHierarchy(e,t){var s;if((s=this.behaviours)!=null&&s.length){t.beginBlock('def Scope "Behaviors"');for(const n of this.behaviours)n.writeTo(this,e.document,t);t.closeBlock()}}async onAfterSerialize(e){vp&&console.log("onAfterSerialize behaviours",this.behaviourComponentsCopy);for(const t of this.behaviourComponentsCopy)typeof t.afterSerialize=="function"&&(t.afterSerialize.constructor.name==="AsyncFunction"?await t.afterSerialize(this,e):t.afterSerialize(this,e));for(const{clipUrl:t,filesKey:s}of this.audioClipsCopy){if(e.files[s])return;const n=await(await(await fetch(t)).blob()).arrayBuffer(),r=new Uint8Array(n);e.files[s]=r}this.behaviourComponentsCopy.length=0,this.audioClipsCopy.length=0}}class X0{get extensionName(){return"Physics"}onExportObject(e,t,s){const n=P.getComponents(e,dt).filter(h=>h.enabled),r=P.getComponents(e,di).filter(h=>h.enabled&&!h.isTrigger);let l=n.length>0?n[0]:null;const c=r.length>0?r[0]:null;c&&!l&&(l=new dt,l.isKinematic=!0),l&&t.addEventListener("serialize",(h,d)=>{var u,p,g;if(l){if(h.appendLine(),h.beginBlock('def RealityKitComponent "RigidBody"',"{",!0),l.useGravity||h.appendLine("bool gravityEnabled = 0"),h.appendLine('uniform token info:id = "RealityKit.RigidBody"'),l.isKinematic&&h.appendLine('token motionType = "Kinematic"'),h.beginBlock('def RealityKitStruct "massFrame"',"{",!0),h.appendLine(`float m_mass = ${l.mass}`),h.beginBlock('def RealityKitStruct "m_pose"',"{",!0),h.appendLine(`float3 position = (${l.centerOfMass.x}, ${l.centerOfMass.y}, ${l.centerOfMass.z})`),h.closeBlock("}"),h.closeBlock("}"),r.length>0){const f=r[0];h.beginBlock('def RealityKitStruct "material"',"{",!0);const y=f.sharedMaterial;y&&y.dynamicFriction!==void 0&&h.appendLine(`double dynamicFriction = ${(u=f.sharedMaterial)==null?void 0:u.dynamicFriction}`),y&&y.bounciness!==void 0&&h.appendLine(`double restitution = ${(p=f.sharedMaterial)==null?void 0:p.bounciness}`),y&&y.staticFriction!==void 0&&h.appendLine(`double staticFriction = ${(g=f.sharedMaterial)==null?void 0:g.staticFriction}`),h.closeBlock("}")}h.closeBlock("}")}}),c&&(t.addEventListener("serialize",(h,d)=>{var u;h.beginBlock('def RealityKitComponent "Collider"',"{",!0),h.appendLine("uint group = 1"),h.appendLine('uniform token info:id = "RealityKit.Collider"'),h.appendLine("uint mask = 4294967295");const p=c.isTrigger?"Trigger":"Default";if(h.appendLine(`token type = "${p}"`),h.beginBlock('def RealityKitStruct "Shape"',"{",!0),c instanceof Ka){const g=c;h.appendLine('token shapeType = "Sphere"'),h.appendLine(`float radius = ${g.radius}`)}else if(c instanceof Uu){const g=c;h.appendLine('token shapeType = "Box"'),h.appendLine(`float3 extent = (${g.size.x}, ${g.size.y}, ${g.size.z})`)}else if(c instanceof Wn){const g=c;h.appendLine('token shapeType = "Capsule"'),h.appendLine(`float radius = ${g.radius}`),h.appendLine(`float height = ${g.height}`)}else if(c instanceof Bo&&(u=c.sharedMesh)!=null&&u.geometry){const g=c.sharedMesh.geometry;g.boundingBox||g.computeBoundingBox();const f=c.sharedMesh.geometry.boundingBox;f&&(h.appendLine('token shapeType = "Box"'),h.appendLine(`float3 extent = (${f.max.x-f.min.x}, ${f.max.y-f.min.y}, ${f.max.z-f.min.z})`),console.log("[USDZ] Only Box, Sphere, and Capsule colliders are supported in visionOS/iOS. MeshCollider will be exported as Box",c))}else console.warn("[USDZ] Only Box, Sphere, and Capsule colliders are supported in visionOS/iOS. Ignoring collider:",c);h.beginBlock('def RealityKitStruct "pose"',"{",!0),h.closeBlock("}"),h.closeBlock("}"),h.closeBlock("}")}),r.length>1&&console.log("WARNING: Multiple colliders detected. visionOS / iOS can only support objects with a single collider, only exporting the first collider: ",c))}}const _A=C("debugshadowcomponents");Qv.prototype.interactable={get(){return this.interactive},set(o){this.interactable=o}};class hs extends I{constructor(){super(...arguments),a(this,"_shadowComponent",null),a(this,"_controlsChildLayout",!0),a(this,"_root"),a(this,"_parentComponent")}isRoot(){var e;return((e=this.Root)==null?void 0:e.gameObject)===this.gameObject}get canvas(){const e=this.Root;return e!=null&&e.isCanvas?e:null}get Canvas(){return this.canvas}markDirty(){ti.markUIDirty(this.context)}get shadowComponent(){return this._shadowComponent}set shadowComponent(e){this._shadowComponent=e}get controlsChildLayout(){return this._controlsChildLayout}set controlsChildLayout(e){this._controlsChildLayout=e,this.shadowComponent&&(this.shadowComponent.autoLayout=e)}get Root(){return this._root===void 0&&(this._root=P.getComponentInParent(this.gameObject,sh)),this._root}__internalNewInstanceCreated(e){return super.__internalNewInstanceCreated(e),this.shadowComponent=null,this._root=void 0,this._parentComponent=void 0,this}onEnable(){super.onEnable()}addShadowComponent(e,t){var s;if(!e)return;this.removeShadowComponent();const n=this.isRoot()?this.gameObject:this.gameObject.parent;if(this._parentComponent=P.getComponentInParent(n,hs),!this._parentComponent){console.warn(`Component "${this.name}" doesn't have a UI parent anywhere. Do you have an UI element outside a Canvas? UI components must be a child of a Canvas component`,this);return}e.name=this.name+" ("+(this.constructor.name??"UI")+")",e.autoLayout=this._parentComponent.controlsChildLayout,e[ki]=this,this.setShadowComponentOwner(e);let r=!1;if(((s=this.Root)==null?void 0:s.gameObject)===this.gameObject)this.gameObject.add(e);else{const l=this._parentComponent.shadowComponent;l&&(l?.add(e),r=!0)}this.shadowComponent=e,t&&t.shadowComponent&&this.shadowComponent&&t.shadowComponent.add(this.shadowComponent),gc&&e.add(new Si(.5)),this.onAfterAddedToScene(),r&&CO(),_A&&console.warn("Added shadow component",this.shadowComponent)}setShadowComponentOwner(e){if(e&&(e[ki]===void 0||e[ki]===this)&&(e[ki]=this,e.children))for(const t of e.children)this.setShadowComponentOwner(t)}traverseOwnedShadowComponents(e,t,s){if(e&&e[ki]===t){s(e);for(const n of e.children)this.traverseOwnedShadowComponents(n,t,s)}}removeShadowComponent(){this.shadowComponent&&this.shadowComponent.removeFromParent()}onAfterAddedToScene(){}setInteractable(e){this.shadowComponent&&(this.shadowComponent.interactable=e)}}class sh extends hs{awake(){super.awake()}}var wA=Object.defineProperty,xA=Object.getOwnPropertyDescriptor,nh=(o,e,t,s)=>{for(var n=s>1?void 0:s?xA(e,t):e,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=(s?l(e,t,n):l(n))||n);return s&&n&&wA(e,t,n),n};const Q0=C("debugui"),Y0=C("debuguilayout");class X1{constructor(){a(this,"width"),a(this,"height")}}class Q1{constructor(){a(this,"x"),a(this,"y"),a(this,"width"),a(this,"height")}}const Rs=new x,oh=new se,bp=new H,gl=class SC extends hs{constructor(){super(...arguments),a(this,"_anchoredPosition"),a(this,"sizeDelta",new le(100,100)),a(this,"pivot",new le(.5,.5)),a(this,"anchorMin",new le(0,0)),a(this,"anchorMax",new le(1,1)),a(this,"minWidth"),a(this,"minHeight"),a(this,"lastMatrix"),a(this,"rectBlock"),a(this,"_transformNeedsUpdate",!1),a(this,"_initialPosition"),a(this,"_parentRectTransform"),a(this,"_lastUpdateFrame",-1),a(this,"_lastAnchoring"),a(this,"_createdBlocks",[]),a(this,"_createdTextBlocks",[])}get parent(){return this._parentRectTransform}get translation(){return this.gameObject.position}get rotation(){return this.gameObject.quaternion}get scale(){return this.gameObject.scale}get anchoredPosition(){return this._anchoredPosition||(this._anchoredPosition=new le),this._anchoredPosition}set anchoredPosition(e){this._anchoredPosition=e}get width(){let e=this.sizeDelta.x;if(this.anchorMin.x!==this.anchorMax.x&&this._parentRectTransform){const t=this._parentRectTransform.width,s=this.anchorMax.x-this.anchorMin.x;e=t*s,e+=this.sizeDelta.x}return this.minWidth!==void 0&&e<this.minWidth?this.minWidth:e}get height(){let e=this.sizeDelta.y;if(this.anchorMin.y!==this.anchorMax.y&&this._parentRectTransform){const t=this._parentRectTransform.height,s=this.anchorMax.y-this.anchorMin.y;e=t*s,e+=this.sizeDelta.y}return this.minHeight!==void 0&&e<this.minHeight?this.minHeight:e}awake(){super.awake(),this._lastUpdateFrame=-1,this._parentRectTransform=void 0,this.rectBlock=new E,this.rectBlock.name=this.name,this.lastMatrix=new se,this._lastAnchoring=null,this._initialPosition=this.gameObject.position.clone(),this._initialPosition.z=0,this._anchoredPosition||(this._anchoredPosition=new le),Xa(this,"_anchoredPosition",()=>{this.markDirty()}),Xa(this,"sizeDelta",()=>{this.markDirty()}),Xa(this,"pivot",()=>{this.markDirty()}),Xa(this,"anchorMin",()=>{this.markDirty()}),Xa(this,"anchorMax",()=>{this.markDirty()})}onEnable(){var e;super.onEnable(),this.rectBlock||(this.rectBlock=new E),this.lastMatrix||(this.lastMatrix=new se),this._lastAnchoring||(this._lastAnchoring=new le),this._initialPosition||(this._initialPosition=new x),this._anchoredPosition||(this._anchoredPosition=new le),this.addShadowComponent(this.rectBlock),this._transformNeedsUpdate=!0,(e=this.canvas)==null||e.registerTransform(this)}onDisable(){var e;super.onDisable(),this.removeShadowComponent(),(e=this.canvas)==null||e.unregisterTransform(this)}onParentRectTransformChanged(e){this._transformNeedsUpdate||this.onApplyTransform(Y0?`${e.name} changed`:void 0)}get isDirty(){return this._transformNeedsUpdate||(this._transformNeedsUpdate=!this.lastMatrix.equals(this.gameObject.matrix)),this._transformNeedsUpdate}markDirty(){this._transformNeedsUpdate||(Y0&&console.warn("RectTransform markDirty()",this.name),this._transformNeedsUpdate=!0,this._lastUpdateFrame=-1)}updateTransform(){(this._transformNeedsUpdate||!this.lastMatrix.equals(this.gameObject.matrix))&&this.canUpdate()&&this.onApplyTransform(this._transformNeedsUpdate?"Marked dirty":"Matrix changed")}canUpdate(){return this._transformNeedsUpdate&&this.activeAndEnabled&&this._lastUpdateFrame!==this.context.time.frame}onApplyTransform(e){var t;if(this.context.time.frameCount===this._lastUpdateFrame)return;this._lastUpdateFrame=this.context.time.frameCount;const s=this.shadowComponent;if(!s)return;this.gameObject.parent?this._parentRectTransform=P.getComponentInParent(this.gameObject.parent,SC):this._parentRectTransform=void 0,this._transformNeedsUpdate=!1,Y0&&console.warn("RectTransform \u2192 ApplyTransform",this.name+" because "+e),this.isRoot()?this.Root.screenspace||(s.rotation.y=Math.PI):(s.matrix.identity(),s.matrixAutoUpdate=!1,Rs.set(0,0,0),this.applyPivot(Rs),s.matrix.setPosition(Rs.x,Rs.y,0),(this.gameObject.quaternion.x||this.gameObject.quaternion.y||this.gameObject.quaternion.z)&&(bp.copy(this.gameObject.quaternion),bp.x*=-1,bp.z*=-1,oh.makeRotationFromQuaternion(bp),s.matrix.premultiply(oh)),Rs.set(0,0,0),this.applyAnchoring(Rs),(t=this.canvas)!=null&&t.screenspace?Rs.z+=.1:Rs.z+=.01,oh.identity(),oh.setPosition(Rs.x,Rs.y,Rs.z),s.matrix.premultiply(oh),s.matrix.scale(this.gameObject.scale)),this.lastMatrix.copy(this.gameObject.matrix);const n=!0;for(const r of lu(this.gameObject,hs,n,1)){if(r===this||!r.activeAndEnabled)continue;const l=r;l.onParentRectTransformChanged&&l.onParentRectTransformChanged(this)}}applyAnchoring(e){this._lastAnchoring||(this._lastAnchoring=new le);const t=this._lastAnchoring.sub(this._anchoredPosition);this.gameObject.position.x+=t.x,this.gameObject.position.y+=t.y,this._lastAnchoring.copy(this._anchoredPosition),e.x+=this._initialPosition.x-this.gameObject.position.x,e.y+=this._initialPosition.y-this.gameObject.position.y,e.z+=this._initialPosition.z-this.gameObject.position.z;const s=this._parentRectTransform;if(s){let n=0;const r=1-this.anchorMax.y-this.anchorMin.y;n-=s.height*.5*r,e.y+=n;let l=0;const c=1-this.anchorMax.x-this.anchorMin.x;l-=s.width*.5*c,e.x+=l}}applyPivot(e){if(this.pivot&&!this.isRoot()){const t=this.pivot.x-.5;e.x-=t*this.sizeDelta.x*this.gameObject.scale.x;const s=this.pivot.y-.5;e.y-=s*this.sizeDelta.y*this.gameObject.scale.y}}getBasicOptions(){const e={width:this.sizeDelta.x,height:this.sizeDelta.y,offset:0,backgroundOpacity:0,borderWidth:0,borderRadius:0,borderOpacity:0,letterSpacing:-.03};return this.ensureValidSize(e),e}ensureValidSize(e,t=1e-4){return e.width<=0&&(e.width=t),e.height<=0&&(e.height=1e-4),e}createNewBlock(e){e={...this.getBasicOptions(),...e},Q0&&console.log(this.name,e);const t=new Qv(e);return this._createdBlocks.push(t),t}createNewText(e){Q0&&console.log(e),e={...this.getBasicOptions(),...e},Q0&&console.log(this.name,e);const t=new Xv(e);return this._createdTextBlocks.push(t),t}};nh([m(le)],gl.prototype,"anchoredPosition",1),nh([m(le)],gl.prototype,"sizeDelta",2),nh([m(le)],gl.prototype,"pivot",2),nh([m(le)],gl.prototype,"anchorMin",2),nh([m(le)],gl.prototype,"anchorMax",2);let Ts=gl;var SA=Object.defineProperty,Y1=(o,e,t,s)=>{for(var n=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=l(e,t,n)||n);return n&&SA(e,t,n),n};class fl extends I{constructor(){super(...arguments),a(this,"effectColor"),a(this,"effectDistance")}}Y1([m(he)],fl.prototype,"effectColor"),Y1([m(le)],fl.prototype,"effectDistance");var CA=Object.defineProperty,PA=Object.getOwnPropertyDescriptor,K1=(o,e,t,s)=>{for(var n=s>1?void 0:s?PA(e,t):e,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=(s?l(e,t,n):l(n))||n);return s&&n&&CA(e,t,n),n};const _p={backgroundColor:new ae(1,1,1),backgroundOpacity:1,borderColor:new ae(1,1,1),borderOpacity:1};var Gr;const K0=(Gr=class extends hs{constructor(){super(...arguments),a(this,"_alphaFactor",1),a(this,"sRGBColor",new ae(1,0,1)),a(this,"raycastTarget",!0),a(this,"uiObject",null),a(this,"_color",null),a(this,"_rect",null),a(this,"_stateManager",null),a(this,"_currentlyCreatingPanel",!1)}get isGraphic(){return!0}get color(){return this._color||(this._color=new he(1,1,1,1)),this._color}set color(o){(!this._color||this._color.r!==o.r||this._color.g!==o.g||this._color.b!==o.b||this._color.alpha!==o.alpha)&&(this._color||(this._color=new he(1,1,1,1)),this._color.copy(o),this.onColorChanged())}setAlphaFactor(o){this._alphaFactor=o,this.onColorChanged()}get alphaFactor(){return this._alphaFactor}onColorChanged(){this.uiObject&&(this.sRGBColor.copy(this._color),this.sRGBColor.convertLinearToSRGB(),_p.backgroundColor=this.sRGBColor,_p.backgroundOpacity=this._color.alpha*this._alphaFactor,this.applyEffects(_p,this._alphaFactor),this.uiObject.set(_p),this.markDirty())}get m_Color(){return this._color}get rectTransform(){if(this._rect||(this._rect=P.getComponent(this.gameObject,Ts)),!this._rect)throw new Error("Not Supported: Make sure to add a RectTransform component before adding a UI Graphic component.");return this._rect}onParentRectTransformChanged(){var o;(o=this.uiObject)==null||o.set({width:this.rectTransform.width,height:this.rectTransform.height}),this.markDirty()}__internalNewInstanceCreated(o){return super.__internalNewInstanceCreated(o),this._rect=null,this.uiObject=null,this._stateManager=null,this._color&&(this._color=this._color.clone()),this}setState(o){this.makePanel(),this.uiObject&&(this.uiObject.setState(o),this==null||this.markDirty())}setupState(o){this.makePanel(),this.uiObject&&(this._stateManager||(this._stateManager=new PO(this.uiObject)),this.uiObject.setupState(o.state,o.attributes))}setOptions(o){this.makePanel(),this.uiObject&&this.uiObject.set(o)}awake(){super.awake(),this.makePanel(),Xa(this,"_color",()=>PT(this,this.onColorChanged))}onEnable(){var o;super.onEnable(),this.uiObject&&((o=this.rectTransform.shadowComponent)==null||o.add(this.uiObject),this.addShadowComponent(this.uiObject,this.rectTransform))}onDisable(){super.onDisable(),this.uiObject&&this.removeShadowComponent()}makePanel(){if(this.uiObject||this._currentlyCreatingPanel)return;this._currentlyCreatingPanel=!0;const o={backgroundColor:this.color,backgroundOpacity:this.color.alpha,offset:.015};this.onBeforeCreate(o),this.applyEffects(o),this.onCreate(o),this.controlsChildLayout=!1,this._currentlyCreatingPanel=!1,this.onAfterCreated(),this.onColorChanged()}onBeforeCreate(o){}onCreate(o){this.uiObject=this.rectTransform.createNewBlock(o),this.uiObject.name=this.name}onAfterCreated(){}applyEffects(o,e=1){var t;const s=(t=this.gameObject)==null?void 0:t.getComponent(fl);s&&(s.effectDistance&&(o.borderWidth=Math.max(Math.abs(s.effectDistance.x),Math.abs(s.effectDistance.y))),s.effectColor&&(o.borderColor=s.effectColor,o.borderOpacity=s.effectColor.alpha*e))}async setTexture(o){if(this.setOptions({backgroundOpacity:0}),o){if(Gr.textureCache.has(o))o=Gr.textureCache.get(o);else if(!o.isRenderTargetTexture){const e=o.clone();e.colorSpace=On,Gr.textureCache.set(o,e),o=e}this.setOptions({backgroundImage:o,borderRadius:0,backgroundOpacity:this.color.alpha,backgroundSize:"stretch"}),Xe.assignTextureLOD(o,0).then(e=>{e instanceof De&&(o&&Gr.textureCache.set(o,e),this.setOptions({backgroundImage:e}),this.markDirty())})}else this.setOptions({backgroundImage:void 0,borderRadius:0,backgroundOpacity:this.color.alpha});this.markDirty()}onAfterAddedToScene(){super.onAfterAddedToScene(),this.shadowComponent&&(this.shadowComponent.offset=this.shadowComponent.position.z)}},a(Gr,"textureCache",new Map),Gr);K1([m(he)],K0.prototype,"color",1),K1([m()],K0.prototype,"raycastTarget",2);let rh=K0;class ah extends rh{constructor(){super(...arguments),a(this,"_flippedObject",!1)}onAfterCreated(){this.uiObject&&!this._flippedObject&&(this._flippedObject=!0,this.uiObject.scale.y*=-1)}}var OA=Object.defineProperty,kA=Object.getOwnPropertyDescriptor,Kn=(o,e,t,s)=>{for(var n=s>1?void 0:s?kA(e,t):e,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=(s?l(e,t,n):l(n))||n);return s&&n&&OA(e,t,n),n};const qr=C("debugtext");var mt=(o=>(o[o.UpperLeft=0]="UpperLeft",o[o.UpperCenter=1]="UpperCenter",o[o.UpperRight=2]="UpperRight",o[o.MiddleLeft=3]="MiddleLeft",o[o.MiddleCenter=4]="MiddleCenter",o[o.MiddleRight=5]="MiddleRight",o[o.LowerLeft=6]="LowerLeft",o[o.LowerCenter=7]="LowerCenter",o[o.LowerRight=8]="LowerRight",o))(mt||{}),Z1=(o=>(o[o.Normal=0]="Normal",o[o.Bold=1]="Bold",o[o.Italic=2]="Italic",o[o.BoldAndItalic=3]="BoldAndItalic",o))(Z1||{});class zt extends rh{constructor(){super(...arguments),a(this,"alignment",0),a(this,"verticalOverflow",0),a(this,"horizontalOverflow",0),a(this,"lineSpacing",1),a(this,"supportRichText",!1),a(this,"font"),a(this,"fontStyle",0),a(this,"sRGBTextColor",new ae(1,0,1)),a(this,"_text",""),a(this,"_fontSize",12),a(this,"_textMeshUi",null),a(this,"_didHandleTextRenderOnTop",!1)}setAlphaFactor(e){var t;super.setAlphaFactor(e),(t=this.uiObject)==null||t.set({fontOpacity:this.color.alpha*this.alphaFactor}),this.markDirty()}get text(){return this._text}set text(e){e!==this._text&&(this._text=e,this.feedText(this.text,this.supportRichText),this.markDirty())}set_text(e){this.text=e}get fontSize(){return this._fontSize}set fontSize(e){var t;this._fontSize=e,(t=this.uiObject)==null||t.set({fontSize:e})}onColorChanged(){var e;this.sRGBTextColor.copy(this.color),this.sRGBTextColor.convertLinearToSRGB(),(e=this.uiObject)==null||e.set({color:this.sRGBTextColor,fontOpacity:this.color.alpha})}onParentRectTransformChanged(){super.onParentRectTransformChanged(),this.uiObject&&this.updateOverflow()}onBeforeCanvasRender(e){this.updateOverflow()}updateOverflow(){var e;const t=(e=this.uiObject)==null?void 0:e._overflow;t&&(t._needsUpdate=!0)}onCreate(e){qr&&console.log(this),this.horizontalOverflow==1&&(e.whiteSpace="pre"),this.verticalOverflow==0&&(this.context.renderer.localClippingEnabled=!0,e.overflow="hidden"),this.horizontalOverflow==1&&this.verticalOverflow==0,e.lineHeight=this.lineSpacing,delete e.backgroundOpacity,delete e.backgroundColor,qr&&(e.backgroundColor=16750848,e.backgroundOpacity=.5);const t=this.rectTransform;e={...e,...this.getTextOpts()},this.getAlignment(e),qr&&(e.backgroundColor=Math.random()*16777215,e.backgroundOpacity=.1),this.uiObject=t.createNewText(e),this.feedText(this.text,this.supportRichText)}onAfterAddedToScene(){super.onAfterAddedToScene(),this.handleTextRenderOnTop()}getTextOpts(){const e=this.fontSize,t={color:this.color,fontOpacity:this.color.alpha,fontSize:e,fontKerning:"normal"};return this.setFont(t,this.fontStyle),t}onEnable(){var e;super.onEnable(),this._didHandleTextRenderOnTop=!1,this.uiObject&&this.uiObject.addAfterUpdate(()=>{this.setShadowComponentOwner(this.uiObject),this.markDirty()}),setTimeout(()=>this.markDirty(),10),(e=this.canvas)==null||e.registerEventReceiver(this)}onDisable(){var e;super.onDisable(),(e=this.canvas)==null||e.unregisterEventReceiver(this)}getAlignment(e){switch(e.flexDirection="column",this.alignment){case 0:case 3:case 6:e.textAlign="left";break;case 1:case 4:case 7:e.textAlign="center";break;case 2:case 5:case 8:e.textAlign="right";break}switch(this.alignment){default:case 0:case 1:case 2:e.alignItems="start";break;case 3:case 4:case 5:e.alignItems="center";break;case 6:case 7:case 8:e.alignItems="end";break}return e}feedText(e,t){var s,n,r;if(qr&&console.log("feedText",this.uiObject,e,t),!!this.uiObject)if(this._textMeshUi||(this._textMeshUi=[]),this.uiObject.children.length=0,!t||e.length===0)this.uiObject.textContent=e;else{let l=this.getNextTag(e);if(l){if(l.startIndex>0){for(let d=this.uiObject.children.length-1;d>=0;d--){const u=this.uiObject.children[d];u.isUI&&(this.uiObject.remove(u),u.clear())}const h=new Nm({textContent:e.substring(0,l.startIndex),color:"inherit"});this.uiObject.add(h)}}else{this.uiObject.textContent="",this.setOptions({textContent:e});return}const c=[];for(;l;){const h=this.getNextTag(e,l.endIndex),d={fontFamily:(s=this.uiObject)==null?void 0:s.get("fontFamily"),color:"inherit",textContent:""};if(h){d.textContent=this.getText(e,l,h),this.handleTag(l,d,c);const u=new Nm(d);(n=this.uiObject)==null||n.add(u)}else{d.textContent=e.substring(l.endIndex),this.handleTag(l,d,c);const u=new Nm(d);(r=this.uiObject)==null||r.add(u)}l=h}}}handleTextRenderOnTop(){this._didHandleTextRenderOnTop||(this._didHandleTextRenderOnTop=!0,this.startCoroutine(this.renderOnTopCoroutine()))}*renderOnTopCoroutine(){if(!this.canvas)return;const e=[],t=this.canvas,s={renderOnTop:t.renderOnTop,depthWrite:t.depthWrite,doubleSided:t.doubleSided};for(;;){let n=!1;if(this._textMeshUi)for(let r=0;r<this._textMeshUi.length;r++){if(e[r]===!0)continue;n=!0;const l=this._textMeshUi[r];l.textContent&&(Eu(l,s),e[r]=!0)}if(!n)break;yield}}handleTag(e,t,s){if(!e.isEndTag){if(e.type.includes("color")){const n=new Z0(e,{color:t.color});if(s.push(n),e.type.length>6){const r=parseInt("0x"+e.type.substring(7));t.color=r}else t.color=new ae(1,1,1)}else if(e.type=="b"){this.setFont(t,1);const n=new Z0(e,{fontWeight:700});s.push(n)}else if(e.type=="i"){this.setFont(t,2);const n=new Z0(e,{fontStyle:"italic"});s.push(n)}}}getText(e,t,s){return e.substring(t.endIndex,s.startIndex)}getNextTag(e,t=0){const s=e.indexOf("<",t),n=e.indexOf(">",s);if(s>=0&&n>=0){const r=e.substring(s+1,n);return{type:r,startIndex:s,endIndex:n+1,isEndTag:r.startsWith("/")}}return null}setFont(e,t){if(!this.font)return;const s=this.font,n=this.getFamilyNameWithCorrectSuffix(s,t);qr&&console.log("Selected font family:"+n);let r=Yv.getFontFamily(n);switch(r||(r=Yv.addFontFamily(n)),e.fontFamily=r,t){default:case 0:e.fontWeight=400,e.fontStyle="normal";break;case 1:e.fontWeight=700,e.fontStyle="normal";break;case 2:e.fontWeight=400,e.fontStyle="italic";break;case 3:e.fontStyle="italic",e.fontWeight=400}let l=r.getVariant(e.fontWeight,e.fontStyle);if(!l){let c=n;c!=null&&c.endsWith("-msdf.json")||(c+="-msdf.json");let h=n;h!=null&&h.endsWith(".png")||(h+=".png"),l=r.addVariant(e.fontWeight,e.fontStyle,c,h),l?.addEventListener("ready",()=>{this.markDirty()})}}getFamilyNameWithCorrectSuffix(e,t){var s;const n=e.lastIndexOf("-");if(n<0)return e;const r=(s=e.substring(n+1))==null?void 0:s.toLowerCase();if(MA.includes(r))return qr&&console.warn("Unsupported font style: "+r),e;const l=e.lastIndexOf("/");let c=e;l>=0&&(c=c.substring(l+1));const h=c[0]===c[0].toUpperCase(),d=e.substring(0,n);switch(qr&&console.log("Select font: ",e,Z1[t],c,h,d),t){case 0:return h?d+"-Regular":d+"-regular";case 1:return h?d+"-Bold":d+"-bold";case 2:return h?d+"-Italic":d+"-italic";case 3:return h?d+"-BoldItalic":d+"-bolditalic";default:return e}}}Kn([m()],zt.prototype,"alignment",2),Kn([m()],zt.prototype,"verticalOverflow",2),Kn([m()],zt.prototype,"horizontalOverflow",2),Kn([m()],zt.prototype,"lineSpacing",2),Kn([m()],zt.prototype,"supportRichText",2),Kn([m(URL)],zt.prototype,"font",2),Kn([m()],zt.prototype,"fontStyle",2),Kn([m()],zt.prototype,"text",1),Kn([m()],zt.prototype,"fontSize",1);class Z0{constructor(e,t){a(this,"tag"),a(this,"previousValues"),this.tag=e,this.previousValues=t}}const MA=["medium","mediumitalic","black","blackitalic","thin","thinitalic","extrabold","light","lightitalic","semibold"];class Xr{constructor(e){a(this,"id"),a(this,"content",""),a(this,"font",[]),a(this,"pointSize",144),a(this,"width"),a(this,"height"),a(this,"depth"),a(this,"wrapMode"),a(this,"horizontalAlignment"),a(this,"verticalAlignment"),a(this,"material"),this.id=e}static getId(){return this.global_id++}setDepth(e){return this.depth=e,this}setPointSize(e){return this.pointSize=e,this}setHorizontalAlignment(e){return this.horizontalAlignment=e,this}setVerticalAlignment(e){return this.verticalAlignment=e,this}writeTo(e,t){var s;t.beginBlock(`def Preliminary_Text "${this.id}"`,"(",!1),t.appendLine('prepend apiSchemas = ["MaterialBindingAPI"]'),t.closeBlock(")"),t.beginBlock(),this.content&&t.appendLine(`string content = "${this.content}"`),(!this.font||this.font.length<=0)&&(this.font||(this.font=[]),(s=this.font)==null||s.push("sans-serif"));const n=this.font.map(r=>`"${r}"`).join(", ");t.appendLine(`string[] font = [ ${n} ]`),t.appendLine(`double pointSize = ${this.pointSize}`),typeof this.width=="number"&&t.appendLine(`double width = ${this.width}`),typeof this.height=="number"&&t.appendLine(`double height = ${this.height}`),typeof this.depth=="number"&&t.appendLine(`double depth = ${this.depth}`),this.wrapMode&&t.appendLine(`token wrapMode = "${this.wrapMode}"`),this.horizontalAlignment&&t.appendLine(`token horizontalAlignment = "${this.horizontalAlignment}"`),this.verticalAlignment&&t.appendLine(`token verticalAlignment = "${this.verticalAlignment}"`),this.material!==void 0&&t.appendLine(`rel material:binding = </StageRoot/Materials/${P0(this.material)}>`),t.closeBlock()}}a(Xr,"global_id",0);class J0{static singleLine(e,t,s){const n=new Xr("text_"+Xr.getId());return n.content=e,t&&(n.pointSize=t),s&&(n.depth=s),n}static multiLine(e,t,s,n,r,l){const c=new Xr("text_"+Xr.getId());return c.content=e,c.width=t,c.height=s,c.horizontalAlignment=n,c.verticalAlignment=r,l!==void 0&&(c.wrapMode=l),c}}const RA=new se().makeRotationY(Math.PI),TA=new se().makeScale(-1,1,-1);class wp{get extensionName(){return"text"}exportText(e,t,s){const n=P.getComponent(e,zt);if(!n)return;const r=P.getComponent(e,Ts);let l=100,c=100;r&&(l=r.width,c=r.height);const h=RA.clone();r&&h.premultiply(TA),t.setMatrix(h);const d=n.color.clone();t.material=new vt({color:d,emissive:d}),t.addEventListener("serialize",(u,p)=>{let g=n.text;g=g.replace(/\r/g,""),g=g.replace(/\n/g,"\\n");const f=J0.multiLine(g,l,c,"center","bottom","flowing");this.setTextAlignment(f,n.alignment),this.setOverflow(f,n),t.material&&(f.material=t.material),f.pointSize=this.convertToTextSize(n.fontSize),f.depth=.001,f.writeTo(void 0,u)})}convertToTextSize(e){return 1/.0502*144*e}setOverflow(e,t){t.horizontalOverflow?e.wrapMode="singleLine":e.wrapMode="flowing"}setTextAlignment(e,t){switch(t){case mt.LowerLeft:case mt.MiddleLeft:case mt.UpperLeft:e.horizontalAlignment="left";break;case mt.LowerCenter:case mt.MiddleCenter:case mt.UpperCenter:e.horizontalAlignment="center";break;case mt.LowerRight:case mt.MiddleRight:case mt.UpperRight:e.horizontalAlignment="right";break}switch(t){case mt.LowerLeft:case mt.LowerCenter:case mt.LowerRight:e.verticalAlignment="bottom";break;case mt.MiddleLeft:case mt.MiddleCenter:case mt.MiddleRight:e.verticalAlignment="middle";break;case mt.UpperLeft:case mt.UpperCenter:case mt.UpperRight:e.verticalAlignment="top";break}}}var EA=Object.defineProperty,it=(o,e,t,s)=>{for(var n=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=l(e,t,n)||n);return n&&EA(e,t,n),n};const J1=C("debuguilayout");class Qr{constructor(){a(this,"left",0),a(this,"right",0),a(this,"top",0),a(this,"bottom",0)}get vertical(){return this.top+this.bottom}get horizontal(){return this.left+this.right}}it([m()],Qr.prototype,"left"),it([m()],Qr.prototype,"right"),it([m()],Qr.prototype,"top"),it([m()],Qr.prototype,"bottom");class Ni extends I{constructor(){super(...arguments),a(this,"_rectTransform",null),a(this,"_needsUpdate",!1),a(this,"childAlignment",0),a(this,"reverseArrangement",!1),a(this,"spacing",0),a(this,"padding"),a(this,"minWidth",0),a(this,"minHeight",0),a(this,"flexibleHeight",0),a(this,"flexibleWidth",0),a(this,"preferredHeight",0),a(this,"preferredWidth",0)}get rectTransform(){return this._rectTransform}onParentRectTransformChanged(e){this._needsUpdate=!0}get isDirty(){return this._needsUpdate}get isLayoutGroup(){return!0}updateLayout(){this._rectTransform&&(J1&&console.warn("Layout Update",this.context.time.frame,this.name),this._needsUpdate=!1,this.onCalculateLayout(this._rectTransform))}start(){this._needsUpdate=!0}onEnable(){J1&&console.log(this.name,this),this._rectTransform=this.gameObject.getComponent(Ts);const e=this.gameObject.getComponentInParent(yl);e&&e.registerLayoutGroup(this),this._needsUpdate=!0}onDisable(){const e=this.gameObject.getComponentInParent(yl);e&&e.unregisterLayoutGroup(this)}set m_Spacing(e){e!==this.spacing&&(this._needsUpdate=!0,this.spacing=e)}get m_Spacing(){return this.spacing}}it([m()],Ni.prototype,"childAlignment"),it([m()],Ni.prototype,"reverseArrangement"),it([m()],Ni.prototype,"spacing"),it([m(Qr)],Ni.prototype,"padding"),it([m()],Ni.prototype,"minWidth"),it([m()],Ni.prototype,"minHeight"),it([m()],Ni.prototype,"flexibleHeight"),it([m()],Ni.prototype,"flexibleWidth"),it([m()],Ni.prototype,"preferredHeight"),it([m()],Ni.prototype,"preferredWidth");class Xo extends Ni{constructor(){super(...arguments),a(this,"childControlHeight",!0),a(this,"childControlWidth",!0),a(this,"childForceExpandHeight",!1),a(this,"childForceExpandWidth",!1),a(this,"childScaleHeight",!1),a(this,"childScaleWidth",!1)}onCalculateLayout(e){var t;const s=this.primaryAxis,n=e.width;let r=n;const l=e.height;let c=l;r-=this.padding.horizontal,c-=this.padding.vertical,s==="x"?this.padding.horizontal:this.padding.vertical;const h=s==="x",d=h?"y":"x",u=h?this.childControlWidth:this.childControlHeight,p=h?this.childControlHeight:this.childControlWidth,g=h?this.childForceExpandWidth:this.childForceExpandHeight,f=h?this.childForceExpandHeight:this.childForceExpandWidth,y=h?c:r,b=h?n:l,v=.5*(h?this.childAlignment%3:Math.floor(this.childAlignment/3));let _=0;h?_+=this.padding.left:_+=this.padding.top;let w=0,S=0;for(let B=0;B<this.gameObject.children.length;B++){const z=this.gameObject.children[B],D=P.getComponent(z,Ts);D!=null&&D.activeAndEnabled&&(S+=1,h?w+=D.width:w+=D.height)}let k=0;const M=this.spacing*(S-1);if(g||u){let B=0;h?B=r-=M:B=c-=M,S>0&&(k=B/S)}let T=0;T+=this.padding.left,T-=this.padding.right,v!==0&&(_=b-w,_*=v,_-=M*v,h?(_-=this.padding.right*v,_+=this.padding.left*(1-v),_<this.padding.left&&(_=this.padding.left)):(_-=this.padding.bottom*v,_+=this.padding.top*(1-v),_<this.padding.top&&(_=this.padding.top)));let L=1;for(let B=0;B<this.gameObject.children.length;B++){const z=this.gameObject.children[B],D=P.getComponent(z,Ts);if(D!=null&&D.activeAndEnabled){(t=D.pivot)==null||t.set(.5,.5),D.anchorMin.set(0,1),D.anchorMax.set(0,1);const V=n*.5+T*.5;D.anchoredPosition.x!==V&&(D.anchoredPosition.x=V);const $=l*-.5;D.anchoredPosition.y!==$&&(D.anchoredPosition.y=$),f&&p&&D.sizeDelta[d]!==y&&(D.sizeDelta[d]=y),g&&u&&D.sizeDelta[s]!==k&&(D.sizeDelta[s]=k);const U=h?D.width:D.height,j=U*.5;if(_+=j,g){const J=k*L-k*.5;J>_&&(_=J-k*.5+U+this.padding.left,_-=j)}let Q=_;s==="y"&&(Q=-Q),D.anchoredPosition[s]!==Q&&(D.anchoredPosition[s]=Q),_+=j,_+=this.spacing,L+=1}}}}it([m()],Xo.prototype,"childControlHeight"),it([m()],Xo.prototype,"childControlWidth"),it([m()],Xo.prototype,"childForceExpandHeight"),it([m()],Xo.prototype,"childForceExpandWidth"),it([m()],Xo.prototype,"childScaleHeight"),it([m()],Xo.prototype,"childScaleWidth");class ey extends Xo{get primaryAxis(){return"y"}}class ty extends Xo{get primaryAxis(){return"x"}}class iy extends Ni{onCalculateLayout(){}}var AA=Object.defineProperty,IA=Object.getOwnPropertyDescriptor,mn=(o,e,t,s)=>{for(var n=s>1?void 0:s?IA(e,t):e,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=(s?l(e,t,n):l(n))||n);return s&&n&&AA(e,t,n),n},eS=(o=>(o[o.ScreenSpaceOverlay=0]="ScreenSpaceOverlay",o[o.ScreenSpaceCamera=1]="ScreenSpaceCamera",o[o.WorldSpace=2]="WorldSpace",o[o.Undefined=-1]="Undefined",o))(eS||{});const sy=C("debuguilayout"),rs=class CC extends sh{constructor(){super(...arguments),a(this,"_renderOnTop"),a(this,"_depthWrite",!1),a(this,"_doubleSided",!0),a(this,"_castShadows",!1),a(this,"_receiveShadows",!1),a(this,"_renderMode",-1),a(this,"_rootCanvas"),a(this,"_scaleFactor",1),a(this,"worldCamera"),a(this,"planeDistance",-1),a(this,"_boundRenderSettingsChanged",this.onRenderSettingsChanged.bind(this)),a(this,"previousParent",null),a(this,"_lastMatrixWorld",null),a(this,"_rectTransforms",[]),a(this,"_layoutGroups",new Map),a(this,"_receivers",[]),a(this,"onBeforeRenderRoutine",()=>{var e,t,s,n;if(this.previousParent=this.gameObject.parent,((e=this.context.xr)!=null&&e.isVR||(t=this.context.xr)!=null&&t.isPassThrough)&&this.screenspace){this.gameObject.visible=!1,this.gameObject.removeFromParent();return}this.renderOnTop||this.screenspace?this.gameObject.removeFromParent():(this.onUpdateRenderMode(),this.handleLayoutUpdates(),(s=this.shadowComponent)==null||s.updateMatrixWorld(!0),(n=this.shadowComponent)==null||n.updateWorldMatrix(!0,!0),this.invokeBeforeRenderEvents(),ti.ensureUpdateMeshUI(Kv,this.context))}),a(this,"onAfterRenderRoutine",()=>{var e,t,s,n,r;if(((e=this.context.xr)!=null&&e.isVR||(t=this.context.xr)!=null&&t.isPassThrough)&&this.screenspace){(s=this.previousParent)==null||s.add(this.gameObject);return}if((this.screenspace||this.renderOnTop)&&this.previousParent&&this.context.mainCamera){if(this.screenspace){const h=this.context.mainCamera;h?.add(this.gameObject)}else this.previousParent.add(this.gameObject);const l=this.context.renderer.autoClear,c=this.context.renderer.autoClearColor;this.context.renderer.autoClear=!1,this.context.renderer.autoClearColor=!1,this.context.renderer.clearDepth(),this.onUpdateRenderMode(!0),this.handleLayoutUpdates(),(n=this.shadowComponent)==null||n.updateMatrixWorld(!0),this.invokeBeforeRenderEvents(),ti.ensureUpdateMeshUI(Kv,this.context,!0),this.context.renderer.render(this.gameObject,this.context.mainCamera),this.context.renderer.autoClear=l,this.context.renderer.autoClearColor=c,this.previousParent.add(this.gameObject)}(r=this._lastMatrixWorld)==null||r.copy(this.gameObject.matrixWorld)}),a(this,"_updateRenderSettingsRoutine"),a(this,"_activeRenderMode",-1),a(this,"_lastWidth",-1),a(this,"_lastHeight",-1)}get isCanvas(){return!0}get screenspace(){return this.renderMode!==2}set renderOnTop(e){e!==this._renderOnTop&&(this._renderOnTop=e,this.onRenderSettingsChanged())}get renderOnTop(){return this._renderOnTop!==void 0?this._renderOnTop:!!(this.screenspace&&this._renderMode===0)}set depthWrite(e){this._depthWrite!==e&&(this._depthWrite=e,this.onRenderSettingsChanged())}get depthWrite(){return this._depthWrite}set doubleSided(e){this._doubleSided!==e&&(this._doubleSided=e,this.onRenderSettingsChanged())}get doubleSided(){return this._doubleSided}set castShadows(e){this._castShadows!==e&&(this._castShadows=e,this.onRenderSettingsChanged())}get castShadows(){return this._castShadows}set receiveShadows(e){this._receiveShadows!==e&&(this._receiveShadows=e,this.onRenderSettingsChanged())}get receiveShadows(){return this._receiveShadows}get renderMode(){return this._renderMode}set renderMode(e){this._renderMode!==e&&(this._renderMode=e,this.onRenderSettingsChanged())}set rootCanvas(e){this._rootCanvas instanceof CC||(this._rootCanvas=e)}get rootCanvas(){return this._rootCanvas}get scaleFactor(){return this._scaleFactor}set scaleFactor(e){this._scaleFactor=e}awake(){var e;this.shadowComponent=this.gameObject,this.previousParent=this.gameObject.parent,sy&&console.log("Canvas.Awake()",((e=this.previousParent)==null?void 0:e.name)+"/"+this.gameObject.name),super.awake()}start(){this.applyRenderSettings()}onEnable(){super.onEnable(),this._updateRenderSettingsRoutine=void 0,this._lastMatrixWorld=new se,this.applyRenderSettings(),document.addEventListener("resize",this._boundRenderSettingsChanged),this.context.pre_render_callbacks.push(this.onBeforeRenderRoutine),this.context.post_render_callbacks.push(this.onAfterRenderRoutine)}onDisable(){super.onDisable(),document.removeEventListener("resize",this._boundRenderSettingsChanged);const e=this.context.pre_render_callbacks.indexOf(this.onBeforeRenderRoutine);e!==-1&&this.context.pre_render_callbacks.splice(e,1);const t=this.context.post_render_callbacks.indexOf(this.onAfterRenderRoutine);t!==-1&&this.context.post_render_callbacks.splice(t,1)}registerTransform(e){this._rectTransforms.push(e)}unregisterTransform(e){const t=this._rectTransforms.indexOf(e);t!==-1&&this._rectTransforms.splice(t,1)}registerLayoutGroup(e){const t=e.gameObject;this._layoutGroups.set(t,e)}unregisterLayoutGroup(e){const t=e.gameObject;this._layoutGroups.delete(t)}registerEventReceiver(e){this._receivers.push(e)}unregisterEventReceiver(e){const t=this._receivers.indexOf(e);t!==-1&&this._receivers.splice(t,1)}async onEnterXR(e){this.screenspace?(e.xr.isVR||e.xr.isPassThrough)&&(this.gameObject.visible=!1):(this.gameObject.visible=!1,await Gl(1).then(()=>{this.gameObject.visible=!0}))}onLeaveXR(e){this.screenspace&&(e.xr.isVR||e.xr.isPassThrough)&&(this.gameObject.visible=!0)}invokeBeforeRenderEvents(){var e;for(const t of this._receivers)(e=t.onBeforeCanvasRender)==null||e.call(t,this)}handleLayoutUpdates(){this._lastMatrixWorld===null&&(this._lastMatrixWorld=new se);const e=!this._lastMatrixWorld.equals(this.gameObject.matrixWorld);sy&&e&&console.log("Canvas Layout changed",this.context.time.frameCount,this.name);for(const t of this._rectTransforms){e&&t.markDirty();let s=this._layoutGroups.get(t.gameObject);t.isDirty&&!s&&(s=t.gameObject.getComponentInParent(Ni)),(t.isDirty||s!=null&&s.isDirty)&&(sy&&console.log("CANVAS UPDATE ### "+t.name+" ##################################### "+this.context.time.frame),s?.updateLayout(),t.updateTransform())}}applyRenderSettings(){this.onRenderSettingsChanged()}onRenderSettingsChanged(){this._updateRenderSettingsRoutine||(this._updateRenderSettingsRoutine=this.startCoroutine(this._updateRenderSettingsDelayed(),Oe.OnBeforeRender))}*_updateRenderSettingsDelayed(){if(yield,this._updateRenderSettingsRoutine=void 0,this.shadowComponent){this.onUpdateRenderMode(),Eu(this.shadowComponent,this);for(const e of P.getComponentsInChildren(this.gameObject,hs))Eu(e.shadowComponent,this)}}onUpdateRenderMode(e=!1){if(!e&&this._renderMode===this._activeRenderMode&&this._lastWidth===this.context.domWidth&&this._lastHeight===this.context.domHeight)return;this._activeRenderMode=this._renderMode;let t=this.context.mainCameraComponent,s=10;switch(t&&t.nearClipPlane>0&&t.farClipPlane>0&&(s=W.lerp(t.nearClipPlane,t.farClipPlane,.01)),this._renderMode===1&&(this.worldCamera&&(t=this.worldCamera),this.planeDistance>0&&(s=this.planeDistance)),this._renderMode){case 0:case 1:if(this._lastWidth=this.context.domWidth,this._lastHeight=this.context.domHeight,!t)return;const n=s+.01;this.gameObject.position.x=0,this.gameObject.position.y=0,this.gameObject.position.z=-n,this.gameObject.quaternion.identity();const r=this.gameObject.getComponent(Ts);let l=!1;r.sizeDelta.x!==this.context.domWidth&&(l=!0),r.sizeDelta.y!==this.context.domHeight&&(l=!0);const c=t.fieldOfView*Math.PI/180,h=2*Math.tan(c/2)*Math.abs(n);this.gameObject.scale.x=h/this.context.domHeight,this.gameObject.scale.y=h/this.context.domHeight,this.gameObject.scale.z=.01,l&&(r.sizeDelta.x=this.context.domWidth,r.sizeDelta.y=this.context.domHeight,r?.markDirty());break;case 2:this._lastWidth=-1,this._lastHeight=-1;break}}};mn([m()],rs.prototype,"renderOnTop",1),mn([m()],rs.prototype,"depthWrite",1),mn([m()],rs.prototype,"doubleSided",1),mn([m()],rs.prototype,"castShadows",1),mn([m()],rs.prototype,"receiveShadows",1),mn([m()],rs.prototype,"renderMode",1),mn([m(rs)],rs.prototype,"rootCanvas",1),mn([m()],rs.prototype,"scaleFactor",1),mn([m(li)],rs.prototype,"worldCamera",2),mn([m()],rs.prototype,"planeDistance",2);let yl=rs;var LA=Object.defineProperty,jA=Object.getOwnPropertyDescriptor,ny=(o,e,t,s)=>{for(var n=s>1?void 0:s?jA(e,t):e,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=(s?l(e,t,n):l(n))||n);return s&&n&&LA(e,t,n),n};class Qo extends I{constructor(){super(...arguments),a(this,"_alpha",1),a(this,"interactable",!0),a(this,"blocksRaycasts",!0),a(this,"_isDirty",!1),a(this,"_buffer",[])}get alpha(){return this._alpha}set alpha(e){e!==this._alpha&&(this._alpha=e,this.markDirty())}get isCanvasGroup(){return!0}markDirty(){this._isDirty||(this._isDirty=!0,this.startCoroutine(this.applyChangesDelayed(),Oe.OnBeforeRender))}*applyChangesDelayed(){this._isDirty=!1,this.applyChangesNow()}applyChangesNow(){this._buffer.length=0;for(const e of P.getComponentsInChildren(this.gameObject,hs,this._buffer)){const t=e;t.setAlphaFactor&&t.setAlphaFactor(this._alpha)}}}ny([m()],Qo.prototype,"alpha",1),ny([m()],Qo.prototype,"interactable",2),ny([m()],Qo.prototype,"blocksRaycasts",2);class oy{get extensionName(){return"tmui"}onExportObject(e,t,s){const n=P.getComponent(e,yl);if(n&&n.enabled&&n.renderMode===eS.WorldSpace){const r=new wp,l=P.getComponent(e,Ts),c=P.getComponent(e,Qo),h=new Array;if(l){if(!P.isActiveSelf(e)){const p=P.isActiveSelf(e);P.setActive(e,!0),l.onEnable(),l.updateTransform(),h.push(()=>{l.onDisable(),P.setActive(e,p)})}e.traverse(p=>{if(!P.isActiveInHierarchy(p)){const g=P.isActiveSelf(p);P.setActive(p,!0);const f=P.getComponent(p,hs);f&&(f.onEnable(),h.push(()=>{f.onDisable()}));const y=P.getComponent(p,Ts);y&&(y.onEnable(),y.updateTransform(),y.onApplyTransform(),h.push(()=>{y.onDisable()}));const b=P.getComponent(p,zt);b&&(b.onEnable(),h.push(()=>{b.onDisable()})),h.push(()=>{P.setActive(p,g)})}}),l.width,l.height;const d=pi.createEmpty(),u=l.shadowComponent;if(t.add(d),u){const p=u.matrix;d.setMatrix(p);const g=new Map,f=new Map;g.set(u,d),f.set(u,c?c.alpha:1),u.traverse(y=>{if(y===u)return;const b=pi.createEmpty();b.setMatrix(y.matrix);const v=y.parent,_=!!v&&typeof v.textContent=="string"&&v.textContent.length>0;let w=f.get(v)||1;const S=P.getComponent(y,Qo);if(S&&(w*=S.alpha),y instanceof q&&_){const M=y[ki];M?r.exportText(M.gameObject,b,s):console.error("Error when exporting UI: shadow component owner not found. This is likely a bug.",y)}if(y instanceof q&&!_){const M=y.geometry.clone();M.scale(1,1,-1),this.flipWindingOrder(M),b.geometry=M;const T=new ae,L=y.material.opacity;T.copy(y.material.color),b.material=new Me({color:T,opacity:L*w,map:y.material.map,transparent:!0})}g.set(y,b),f.set(y,w);const k=g.get(v);if(!k){console.error("Error when exporting UI: shadow component parent not found!",y,y.parent);return}k.add(b)})}}for(const d of h)d()}}flipWindingOrder(e){const t=e.index.array;for(let s=0,n=t.length/3;s<n;s++){const r=t[s*3];t[s*3]=t[s*3+2],t[s*3+2]=r}e.index.needsUpdate=!0}}const lh=C("debugusdz");function DA(o,e){var t;const s=[],n=P.getComponentsInChildren(o,Mt),r=P.getComponentsInChildren(o,Bt),l=new Array,c=new Array;if(e.injectImplicitBehaviours)for(const h of n){if(!h||!h.runtimeAnimatorController||!h.enabled)continue;const d=h.runtimeAnimatorController.activeState;if(!d||!d.motion||!d.motion.clip||((t=d.motion.clip.tracks)==null?void 0:t.length)<1||l.includes(h))continue;const u=new Kc;u.animator=h,u.stateName=d.name,u.trigger="start",u.name="PlayAnimationOnClick_implicitAtStart_"+u.stateName;const p=new E;P.addComponent(p,u),c.push(p),l.push(h),o.add(p)}else for(const h of n){if(!h||!h.runtimeAnimatorController||!h.enabled)continue;lh&&console.log(h);const d=[];for(const u of h.runtimeAnimatorController.enumerateActions()){lh&&console.log(u);const p=u.getClip();d.includes(p)||d.push(p)}s.push({root:h.gameObject,clips:d})}if(e.injectImplicitBehaviours)for(const h of r){if(!h||!h.clip||!h.enabled||!h.playAutomatically||l.includes(h))continue;const d=new Kc;d.animation=h,d.stateName=h.clip.name,d.trigger="start",d.name="PlayAnimationOnClick_implicitAtStart_"+d.stateName;const u=new E;P.addComponent(u,d),c.push(u),l.push(h),o.add(u)}else for(const h of r){lh&&console.log(h);const d=[];for(const u of h.animations)d.includes(u)||d.push(u);s.push({root:h.gameObject,clips:d})}lh&&s?.length>0&&console.log("USDZ Animation Clips without behaviours",s);for(const h of s)for(const d of h.clips)e.registerAnimation(h.root,d);return c}function BA(o,e){const t=P.getComponentsInChildren(o,ss),s=P.getComponentsInChildren(o,No),n=new Array,r=new Array;lh&&console.log({audioSources:t,playAudioOnClicks:s});for(const l of s){if(!l.target)continue;const c=t.indexOf(l.target);c>-1&&t.splice(c,1)}for(const l of t){if(!l||!l.clip||l.volume<=0||n.includes(l))continue;const c=new No;c.target=l,c.name="PlayAudioOnClick_implicitAtStart_",c.trigger="start";const h=new E;P.addComponent(h,c),console.log("implicit PlayAudioOnStart",h,c),r.push(h),n.push(l),o.add(h)}return r}function FA(o){return new Zt("DisableAtStart",Et.sceneStartTrigger(),ve.fadeAction(o,0,!1))}function tS(o,e){const t=o.domElement.shadowRoot.querySelector("link[rel='ar']");if(t)return t;const s=document.createElement("div");s.classList.add("menu"),s.classList.add("quicklook-menu"),s.style.display="none",s.style.visibility="hidden";const n=document.createElement("button");n.id="open-in-ar",e?(n.innerText="View in AR",n.title="View this scene in AR. The scene will be exported to USDZ and opened with Apple's QuickLook."):(n.innerText="View in AR",n.title="Download this scene for AR. Open the downloaded USDZ file to view it in AR using Apple's QuickLook."),s.appendChild(n);const r=document.createElement("a");r.id="needle-usdz-link",r.style.display="none",r.rel="ar",r.href="",r.target="_blank",s.appendChild(r);const l=document.createElement("img");return l.id="button",r.appendChild(l),o.domElement.shadowRoot.appendChild(s),r}var UA=Object.defineProperty,At=(o,e,t,s)=>{for(var n=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=l(e,t,n)||n);return n&&UA(e,t,n),n};const Wi=C("debugusdz"),zA=C("debugusdzpruning");class Yr{constructor(){a(this,"callToAction"),a(this,"checkoutTitle"),a(this,"checkoutSubtitle"),a(this,"callToActionURL")}}At([m()],Yr.prototype,"callToAction"),At([m()],Yr.prototype,"checkoutTitle"),At([m()],Yr.prototype,"checkoutSubtitle"),At([m()],Yr.prototype,"callToActionURL");var vl;const gi=(vl=class extends I{constructor(){super(...arguments),a(this,"objectToExport"),a(this,"autoExportAnimations",!0),a(this,"autoExportAudioSources",!0),a(this,"exportFileName"),a(this,"customUsdzFile"),a(this,"customBranding"),a(this,"anchoringType","plane"),a(this,"maxTextureSize",2048),a(this,"planeAnchoringAlignment","horizontal"),a(this,"interactive",!0),a(this,"physics",!0),a(this,"allowCreateQuicklookButton",!0),a(this,"quickLookCompatible",!0),a(this,"extensions",[]),a(this,"link"),a(this,"button"),a(this,"onClickedOpenInARElement",o=>{o.preventDefault(),this.exportAndOpen()}),a(this,"_currentExportTasks",new Map),a(this,"_previousTimeScale",1),a(this,"lastCallback"),a(this,"_rootSessionRootWasAppliedTo",null),a(this,"_rootPositionBeforeExport",new x),a(this,"_rootRotationBeforeExport",new H),a(this,"_rootScaleBeforeExport",new x)}start(){var o,e,t;Wi&&(console.log("USDZExporter",this),console.log("Debug USDZ Mode. Press 'T' to export"),window.addEventListener("keydown",s=>{switch(s.key){case"t":this.exportAndOpen();break}})),this.objectToExport||(this.objectToExport=this.gameObject),!((e=(o=this.objectToExport)==null?void 0:o.children)!=null&&e.length)&&!((t=this.objectToExport)!=null&&t.isMesh)&&(this.objectToExport=this.context.scene)}onEnable(){var o;const e=Y.supportsQuickLookAR(),t=Y.isiOS()||Y.isiPad();!this.button&&(Wi||e||t)&&(this.allowCreateQuicklookButton&&(this.button=this.createQuicklookButton()),this.lastCallback=this.quicklookCallback.bind(this),this.link=tS(this.context,e),this.link.addEventListener("message",this.lastCallback)),Wi&&Be("USDZ Exporter enabled: "+this.name),(o=document.getElementById("open-in-ar"))==null||o.addEventListener("click",this.onClickedOpenInARElement),ac.registerExporter(this)}onDisable(){var o,e,t;(o=this.button)==null||o.remove(),(e=this.link)==null||e.removeEventListener("message",this.lastCallback),Wi&&Be("USDZ Exporter disabled: "+this.name),(t=document.getElementById("open-in-ar"))==null||t.removeEventListener("click",this.onClickedOpenInARElement),ac.unregisterExporter(this)}async exportAsync(){return this.exportAndOpen()}async exportAndOpen(){var o;let e=this.exportFileName??((o=this.objectToExport)==null?void 0:o.name)??this.name;if(e+="-"+g1(),Zs()||(e!==""&&(e+="-"),e+="MadeWithNeedle"),this.link||(this.link=tS(this.context,Y.supportsQuickLookAR())),this.customUsdzFile)return Wi&&console.log("Exporting custom usdz",this.customUsdzFile),this.openInQuickLook(this.customUsdzFile,e),null;if(!this.objectToExport)return console.warn("No object to export",this),null;const t=await this.export(this.objectToExport);return t?(Wi&&console.log("USDZ generation done. Downloading as "+e),this.openInQuickLook(t,e),t):(console.error("USDZ generation failed. Please report a bug",this),null)}async export(o){if(!o)return console.warn("No object to export"),null;const e=this._currentExportTasks.get(o);if(e)return e;const t=this.internalExport(o);return t instanceof Promise?(this._currentExportTasks.set(o,t),t.then(s=>(this._currentExportTasks.delete(o),s)).catch(s=>(this._currentExportTasks.delete(o),console.error("Error during USDZ export \u2013 please report a bug!",s),null))):t}async internalExport(o){de.start("export-usdz",{onProgress:S=>{this.dispatchEvent(new CustomEvent("export-progress",{detail:{progress:S}}))}}),de.report("export-usdz",{message:"Starting export",totalSteps:40,currentStep:0}),de.report("export-usdz",{message:"Load progressive textures",autoStep:5}),de.start("export-usdz-textures","export-usdz");const e=P.getComponentsInChildren(o,mi);for(const S of e)S&&S.enabled&&S.updateSprite(!0);const t=P.getComponentsInChildren(o,Fi),s=new Array;let n=0;for(const S of t){for(const k of S.sharedMeshes)if(k){const M=Xe.assignMeshLOD(k,0);M instanceof Promise&&s.push(new Promise((T,L)=>{M.then(()=>{n++,de.report("export-usdz-textures",{message:"Loaded progressive mesh",currentStep:n,totalSteps:s.length}),T()}).catch(B=>L(B))}))}for(const k of S.sharedMaterials)if(k){const M=Xe.assignTextureLOD(k,0);M instanceof Promise&&s.push(new Promise((T,L)=>{M.then(()=>{n++,de.report("export-usdz-textures",{message:"Loaded progressive texture",currentStep:n,totalSteps:s.length}),T()}).catch(B=>L(B))}))}}Wi&&Be("Progressive Loading: "+s.length),await Promise.all(s),Wi&&Be("Progressive Loading: done"),de.end("export-usdz-textures");const r=ji.Global.Mask;ji.Global.Set(rn.AR);const l=new w1,c=new ap(this.quickLookCompatible);let h;const d=[];this.interactive&&(d.push(new q0),d.push(new ya),globalThis.NEEDLE_USE_RAPIER&&P.getComponentsInChildren(o,dt).length>0&&(this.physics?(h=new X0,d.push(h)):F()&&console.warn("USDZExporter: Physics export is disabled, but there are active Rigidbody components in the scene. They will not be exported.")),d.push(new wp),d.push(new oy));const u=[c,...d,...this.extensions],p={self:this,exporter:l,extensions:u,object:o};de.report("export-usdz","Invoking before-export"),this.dispatchEvent(new CustomEvent("before-export",{detail:p})),this.applyWebARSessionRoot(),this._previousTimeScale=this.context.time.timeScale,this.context.time.timeScale=0,de.report("export-usdz","auto export animations and audio sources");const g=new Array;this.autoExportAnimations&&g.push(...DA(o,c)),u.find(S=>S.extensionName==="Audio")&&this.autoExportAudioSources&&g.push(...BA(o)),l.debug=Wi,l.pruneUnusedNodes=!zA;const f=Ku.instance.objs.map(S=>S.batchedMesh);l.keepObject=S=>{let k=!0;const M=P.getComponent(S,Fi);return M&&!M.enabled&&(k=!1),k&&f.includes(S)&&(k=!1),k&&P.getComponentInParent(S,Nc)&&(k=!1),k&&P.getComponentInParent(S,en)&&(k=!1),Wi&&!k&&console.log("USDZExporter: Discarding object",S),k},l.beforeWritingDocument=()=>{if(F()&&c&&h){const S=c.animatedRoots;for(const k of S){const M=P.getComponentsInChildren(k,dt).filter(L=>L.enabled),T=P.getComponents(k,di).filter(L=>L.enabled&&!L.isTrigger);(M.length>0||T.length>0)&&console.error("An animated object has physics components in its child hierarchy. This can lead to undefined behaviour due to a bug in Apple's QuickLook (FB15925487). Remove the physics components from child objects or verify that you get the expected results.",k)}}};const y=new Array;this.objectToExport&&this.quickLookCompatible&&this.interactive&&this.objectToExport.traverse(S=>{S.visible||y.push(S)});const b=u.find(S=>S.extensionName==="Behaviour");this.interactive&&b&&y.length>0&&b.addBehavior(FA(y));let v=!0;this.quickLookCompatible&&!this.interactive&&(v=!1),this.anchoringType!=="plane"&&this.anchoringType!=="none"&&this.anchoringType!=="image"&&this.anchoringType!=="face"&&(this.anchoringType="plane"),this.planeAnchoringAlignment!=="horizontal"&&this.planeAnchoringAlignment!=="vertical"&&this.planeAnchoringAlignment!=="any"&&(this.planeAnchoringAlignment="horizontal"),de.report("export-usdz","Invoking exporter.parse");const _=await l.parse(this.objectToExport,{ar:{anchoring:{type:this.anchoringType},planeAnchoring:{alignment:this.planeAnchoringAlignment}},extensions:u,quickLookCompatible:this.quickLookCompatible,maxTextureSize:this.maxTextureSize,exportInvisible:v}),w=new Blob([_],{type:"model/vnd.usdz+zip"});this.revertWebARSessionRoot(),this.context.time.timeScale=this._previousTimeScale,de.report("export-usdz","Invoking after-export"),this.dispatchEvent(new CustomEvent("after-export",{detail:p}));for(const S of g)P.destroy(S);return ji.Global.Set(r),de.end("export-usdz"),w}openInQuickLook(o,e){const t=o instanceof Blob?URL.createObjectURL(o):o,s=this.buildQuicklookOverlay();Wi&&console.log("QuickLook Overlay",s);const n=s.callToAction?encodeURIComponent(s.callToAction):"",r=s.checkoutTitle?encodeURIComponent(s.checkoutTitle):"",l=s.checkoutSubtitle?encodeURIComponent(s.checkoutSubtitle):"";this.link.href=t+`#callToAction=${n}&checkoutTitle=${r}&checkoutSubtitle=${l}&callToActionURL=${s.callToActionURL}`,this.lastCallback||(this.lastCallback=this.quicklookCallback.bind(this),this.link.addEventListener("message",this.lastCallback)),this.link.download=e+".usdz",this.link.click()}download(o,e){vl.save(o,e)}static save(o,e){const t=document.createElement("a");t.style.display="none",document.body.appendChild(t),typeof o=="string"?t.href=o:t.href=URL.createObjectURL(o),t.download=e,t.click(),t.remove()}quicklookCallback(o){if(o?.data=="_apple_ar_quicklook_button_tapped"){Wi&&be("Quicklook closed via call to action button");var e=new CustomEvent("quicklook-button-tapped",{detail:this});if(this.dispatchEvent(e),!e.defaultPrevented){const t=new URLSearchParams(this.link.href);if(t){const s=t.get("callToActionURL");Wi&&Be("Quicklook url: "+s),s&&(Zs()?globalThis.open(s,"_blank"):console.warn("Quicklook closed: custom redirects require a Needle Engine Pro license: https://needle.tools/pricing",s))}}}}buildQuicklookOverlay(){var o,e,t,s,n,r;const l={};return this.customBranding&&Object.assign(l,this.customBranding),Zs()||(console.log("Custom Quicklook banner text requires pro license: https://needle.tools/pricing"),l.callToAction="Close",l.checkoutTitle="\u{1F335} Made with Needle",l.checkoutSubtitle="_"),(((o=l.callToAction)==null?void 0:o.length)||((e=l.checkoutTitle)==null?void 0:e.length)||((t=l.checkoutSubtitle)==null?void 0:t.length))&&((s=l.callToAction)!=null&&s.length||(l.callToAction="\0"),(n=l.checkoutTitle)!=null&&n.length||(l.checkoutTitle="\0"),(r=l.checkoutSubtitle)!=null&&r.length||(l.checkoutSubtitle="\0")),this.dispatchEvent(new CustomEvent("quicklook-overlay",{detail:l})),l}getARScaleAndTarget(){if(!this.objectToExport)return{scale:1,_invertForward:!1,target:this.gameObject,sessionRoot:null};const o=P.findObjectOfType(yp);let e=P.getComponentInParent(this.objectToExport,Wo);e||(e=P.getComponentInChildren(this.objectToExport,Wo));let t=1,s=!1;const n=this.objectToExport;return o?t=o.arScale:e&&(t=e.arScale,s=e.invertForward),{scale:1/t,_invertForward:s,target:n,sessionRoot:e?.gameObject??null}}applyWebARSessionRoot(){if(!this.objectToExport)return;const{scale:o,_invertForward:e,target:t,sessionRoot:s}=this.getARScaleAndTarget(),n=s?.matrixWorld.clone().invert();this._rootSessionRootWasAppliedTo=t,this._rootPositionBeforeExport.copy(t.position),this._rootRotationBeforeExport.copy(t.quaternion),this._rootScaleBeforeExport.copy(t.scale),t.scale.multiplyScalar(o),e&&t.quaternion.multiply(vl.invertForwardQuaternion),t.updateMatrix(),t.updateMatrixWorld(!0),s&&n&&t.matrix.premultiply(n)}revertWebARSessionRoot(){if(!this.objectToExport||!this._rootSessionRootWasAppliedTo)return;const o=this._rootSessionRootWasAppliedTo;o.position.copy(this._rootPositionBeforeExport),o.quaternion.copy(this._rootRotationBeforeExport),o.scale.copy(this._rootScaleBeforeExport),o.updateMatrix(),o.updateMatrixWorld(!0),this._rootSessionRootWasAppliedTo=null}createQuicklookButton(){const o=dl.getOrCreate().createQuicklookButton();return o.parentNode||this.context.menu.appendChild(o),o}},a(vl,"invertForwardMatrix",new se().makeRotationY(Math.PI)),a(vl,"invertForwardQuaternion",new H().setFromEuler(new jt(0,Math.PI,0))),vl);At([m(E)],gi.prototype,"objectToExport"),At([m()],gi.prototype,"autoExportAnimations"),At([m()],gi.prototype,"autoExportAudioSources"),At([m()],gi.prototype,"exportFileName"),At([m(URL)],gi.prototype,"customUsdzFile"),At([m(Yr)],gi.prototype,"customBranding"),At([m()],gi.prototype,"anchoringType"),At([m()],gi.prototype,"maxTextureSize"),At([m()],gi.prototype,"planeAnchoringAlignment"),At([m()],gi.prototype,"interactive"),At([m()],gi.prototype,"physics"),At([m()],gi.prototype,"allowCreateQuicklookButton"),At([m()],gi.prototype,"quickLookCompatible");let gn=gi;var NA=Object.defineProperty,WA=Object.getOwnPropertyDescriptor,ry=(o,e,t,s)=>{for(var n=WA(e,t),r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=l(e,t,n)||n);return n&&NA(e,t,n),n};class bl extends I{constructor(){super(...arguments),a(this,"_fog")}get fog(){return this._fog||(this._fog=new Pv(0,0,50)),this._fog}get mode(){return 1}set near(e){this.fog.near=e}get near(){return this.fog.near}set far(e){this.fog.far=e}get far(){return this.fog.far}set color(e){this.fog.color.copy(e)}get color(){return this.fog.color}onEnable(){this.scene.fog=this.fog}onDisable(){this.scene.fog===this._fog&&(this.scene.fog=null)}}ry([m()],bl.prototype,"near"),ry([m()],bl.prototype,"far"),ry([m(ae)],bl.prototype,"color");var VA=Object.defineProperty,ay=(o,e,t,s)=>{for(var n=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=l(e,t,n)||n);return n&&VA(e,t,n),n};class Kr extends I{constructor(){super(...arguments),a(this,"objectBounds",!1),a(this,"color"),a(this,"isGizmo",!0),a(this,"_gizmoObject",null),a(this,"_boxHelper",null)}onEnable(){this.isGizmo&&!gc||(this._gizmoObject||(this.objectBounds?this._gizmoObject=new OP(this.gameObject,this.color??16776960):(this.objectBounds=!1,this._gizmoObject=Fg(this.color??16776960))),this.objectBounds?(this.scene.add(this._gizmoObject),this._boxHelper=this._gizmoObject,this.startCoroutine(this.syncObjectBounds(),Oe.OnBeforeRender)):this.gameObject.add(this._gizmoObject))}onDisable(){this._gizmoObject&&this.gameObject.remove(this._gizmoObject)}*syncObjectBounds(){for(var e;this._boxHelper;)(e=this._boxHelper)==null||e.update(),yield}}ay([m()],Kr.prototype,"objectBounds"),ay([m(ae)],Kr.prototype,"color"),ay([m()],Kr.prototype,"isGizmo");var HA=Object.defineProperty,ly=(o,e,t,s)=>{for(var n=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=l(e,t,n)||n);return n&&HA(e,t,n),n};class _l extends I{constructor(){super(...arguments),a(this,"isGizmo",!1),a(this,"color0"),a(this,"color1"),a(this,"gridHelper"),a(this,"size"),a(this,"divisions"),a(this,"offset")}onEnable(){if(this.isGizmo&&!gc)return;const e=this.size,t=this.divisions;this.gridHelper||(this.gridHelper=new Sm(e,t,this.color0??new ae(.4,.4,.4),this.color1??new ae(.6,.6,.6)),this.offset!==void 0&&(this.gridHelper.position.y+=this.offset)),this.gridHelper&&this.gameObject.add(this.gridHelper)}onDisable(){this.gridHelper&&(this.gameObject.remove(this.gridHelper),this.gridHelper=null)}}ly([m()],_l.prototype,"isGizmo"),ly([m(ae)],_l.prototype,"color0"),ly([m(ae)],_l.prototype,"color1");var $A=Object.defineProperty,cy=(o,e,t,s)=>{for(var n=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=l(e,t,n)||n);return n&&$A(e,t,n),n};class hy extends I{constructor(){super(...arguments),a(this,"connectedBody"),a(this,"_rigidBody",null)}get rigidBody(){return this._rigidBody}onEnable(){this._rigidBody||(this._rigidBody=this.gameObject.getComponent(dt)),this.rigidBody&&this.connectedBody&&this.startCoroutine(this.create())}*create(){yield,this.rigidBody&&this.connectedBody&&this.activeAndEnabled&&this.createJoint(this.rigidBody,this.connectedBody)}}cy([m(dt)],hy.prototype,"connectedBody");class dy extends hy{createJoint(e,t){var s;(s=this.context.physics.engine)==null||s.addFixedJoint(e,t)}}class ch extends hy{constructor(){super(...arguments),a(this,"anchor"),a(this,"axis")}createJoint(e,t){var s;this.axis&&this.anchor&&((s=this.context.physics.engine)==null||s.addHingeJoint(e,t,this.anchor,this.axis))}}cy([m(x)],ch.prototype,"anchor"),cy([m(x)],ch.prototype,"axis");var GA=Object.defineProperty,qA=Object.getOwnPropertyDescriptor,fn=(o,e,t,s)=>{for(var n=s>1?void 0:s?qA(e,t):e,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=(s?l(e,t,n):l(n))||n);return s&&n&&GA(e,t,n),n};function uy(o){return o*Math.PI/180}const iS=300,Yo=C("debuglights");class fi extends I{constructor(){super(...arguments),a(this,"type",0),a(this,"range",1),a(this,"spotAngle",1),a(this,"innerSpotAngle",1),a(this,"_color",new ae(16777215)),a(this,"_shadowNearPlane",.1),a(this,"_shadowBias",0),a(this,"_shadowNormalBias",0),a(this,"_overrideShadowBiasSettings",!1),a(this,"_shadows",1),a(this,"lightmapBakeType",4),a(this,"_intensity",-1),a(this,"_shadowDistance"),a(this,"shadowWidth"),a(this,"shadowHeight"),a(this,"_shadowResolution"),a(this,"light"),a(this,"_webXRStartedListener"),a(this,"_webXREndedListener"),a(this,"_webARRoot")}set color(e){this._color=e,this.light!==void 0&&(this.light.color=e)}get color(){return this.light?this.light.color:this._color}set shadowNearPlane(e){var t,s;if(e!==this._shadowNearPlane&&(this._shadowNearPlane=e,((s=(t=this.light)==null?void 0:t.shadow)==null?void 0:s.camera)!==void 0)){const n=this.light.shadow.camera;n.near=e}}get shadowNearPlane(){return this._shadowNearPlane}set shadowBias(e){var t,s;e!==this._shadowBias&&(this._shadowBias=e,((s=(t=this.light)==null?void 0:t.shadow)==null?void 0:s.bias)!==void 0&&(this.light.shadow.bias=e,this.light.shadow.needsUpdate=!0))}get shadowBias(){return this._shadowBias}set shadowNormalBias(e){var t,s;e!==this._shadowNormalBias&&(this._shadowNormalBias=e,((s=(t=this.light)==null?void 0:t.shadow)==null?void 0:s.normalBias)!==void 0&&(this.light.shadow.normalBias=e,this.light.shadow.needsUpdate=!0))}get shadowNormalBias(){return this._shadowNormalBias}set shadows(e){this._shadows=e,this.light&&(this.light.castShadow=e!==0,this.updateShadowSoftHard())}get shadows(){return this._shadows}set intensity(e){var t;if(this._intensity=e,this.light){let s=1;if(this.context.isInXR&&this._webARRoot){const n=(t=this._webARRoot)==null?void 0:t.arScale;typeof n=="number"&&n>0&&(s/=n)}this.light.intensity=e*s}Yo&&console.log("Set light intensity to "+this._intensity,e,this)}get intensity(){return this._intensity}get shadowDistance(){const e=this.light;return e!=null&&e.shadow?e.shadow.camera.far:-1}set shadowDistance(e){this._shadowDistance=e;const t=this.light;if(t!=null&&t.shadow){const s=t.shadow.camera;s.far=e,s.updateProjectionMatrix()}}get shadowResolution(){const e=this.light;return e!=null&&e.shadow?e.shadow.mapSize.x:-1}set shadowResolution(e){if(e===this._shadowResolution)return;this._shadowResolution=e;const t=this.light;t!=null&&t.shadow&&(t.shadow.mapSize.set(e,e),t.shadow.needsUpdate=!0)}get isBaked(){return this.lightmapBakeType===2}get selfIsLight(){if(this.gameObject.isLight===!0)return!0;switch(this.gameObject.type){case"SpotLight":case"PointLight":case"DirectionalLight":return!0}return!1}getWorldPosition(e){return this.light?this.type===1?this.light.getWorldPosition(e).multiplyScalar(1):this.light.getWorldPosition(e):e}awake(){this.color=new ae(this.color??16777215),Yo&&console.log(this.name,this)}onEnable(){Yo&&console.log("ENABLE LIGHT",this.name),this.createLight(),!this.isBaked&&(this.light&&(this.light.visible=!0,this.light.intensity=this._intensity,Yo&&console.log("Set light intensity to "+this.light.intensity,this.name),this.selfIsLight||this.light.parent!==this.gameObject&&this.gameObject.add(this.light)),this.type===1&&this.startCoroutine(this.updateMainLightRoutine(),Oe.LateUpdate))}onDisable(){Yo&&console.log("DISABLE LIGHT",this.name),this.light&&(this.selfIsLight?this.light.intensity=0:this.light.visible=!1)}onEnterXR(e){this._webARRoot=P.getComponentInParent(this.gameObject,Wo)??void 0}onLeaveXR(e){}createLight(){const e=this.selfIsLight;if(e&&!this.light)switch(this.light=this.gameObject,this.light.name=this.name,this._intensity=this.light.intensity,this.type){case 1:this.setDirectionalLight(this.light);break}else if(!this.light)switch(this.type){case 1:const t=new Cm(this.color,this.intensity*Math.PI);if(t.position.set(0,0,-iS*.5).applyQuaternion(this.gameObject.quaternion),this.gameObject.add(t.target),fr(t.target,0,0,0),this.light=t,this.gameObject.position.set(0,0,0),this.gameObject.rotation.set(0,0,0),Yo){const l=new MP(this.light,.2,this.color);this.context.scene.add(l)}break;case 0:const s=new kP(this.color,this.intensity*Math.PI,this.range,uy(this.spotAngle/2),1-uy(this.innerSpotAngle/2)/uy(this.spotAngle/2),2);s.position.set(0,0,0),s.rotation.set(0,0,0),this.light=s;const n=s.target;s.add(n),n.position.set(0,0,this.range),n.rotation.set(0,0,0);break;case 2:const r=new Pm(this.color,this.intensity*Math.PI,this.range);this.light=r;break}if(this.light){if(this._intensity>=0?this.light.intensity=this._intensity:this._intensity=this.light.intensity,this.shadows!==0?this.light.castShadow=!0:this.light.castShadow=!1,this.light.shadow){this._shadowResolution!==void 0&&this._shadowResolution>4?(this.light.shadow.mapSize.width=this._shadowResolution,this.light.shadow.mapSize.height=this._shadowResolution):(this.light.shadow.mapSize.width=2048,this.light.shadow.mapSize.height=2048),Yo&&console.log("Override shadow bias?",this._overrideShadowBiasSettings,this.shadowBias,this.shadowNormalBias),this.light.shadow.bias=this.shadowBias,this.light.shadow.normalBias=this.shadowNormalBias,this.updateShadowSoftHard();const t=this.light.shadow.camera;if(t.near=this.shadowNearPlane,this._shadowDistance!==void 0&&typeof this._shadowDistance=="number"?t.far=this._shadowDistance:t.far=iS*Math.abs(this.gameObject.scale.z),this.gameObject.scale.set(1,1,1),this.shadowWidth!==void 0)t.left=-this.shadowWidth/2,t.right=this.shadowWidth/2;else{const s=this.gameObject.scale.x;t.left*=s,t.right*=s}if(this.shadowHeight!==void 0)t.top=this.shadowHeight/2,t.bottom=-this.shadowHeight/2;else{const s=this.gameObject.scale.y;t.top*=s,t.bottom*=s}this.light.shadow.needsUpdate=!0,Yo&&this.context.scene.add(new RP(t))}this.isBaked?this.light.removeFromParent():e||this.gameObject.add(this.light)}}*updateMainLightRoutine(){for(;;){this.type===1&&((!this.context.mainLight||this.intensity>this.context.mainLight.intensity)&&(this.context.mainLight=this),yield);break}}updateShadowSoftHard(){this.light&&this.light.shadow&&(this.shadows===2||(this.light.shadow.radius=1,this.light.shadow.blurSamples=1))}setDirectionalLight(e){e.add(e.target),e.target.position.set(0,0,-1)}}a(fi,"allowChangingRendererShadowMapType",!0),fn([m()],fi.prototype,"type",2),fn([m(ae)],fi.prototype,"color",1),fn([m()],fi.prototype,"shadowNearPlane",1),fn([m()],fi.prototype,"shadowBias",1),fn([m()],fi.prototype,"shadowNormalBias",1),fn([m()],fi.prototype,"shadows",1),fn([m()],fi.prototype,"lightmapBakeType",2),fn([m()],fi.prototype,"intensity",1),fn([m()],fi.prototype,"shadowDistance",1),fn([m()],fi.prototype,"shadowResolution",1),new x(0,0,0);var XA=Object.defineProperty,hh=(o,e,t,s)=>{for(var n=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=l(e,t,n)||n);return n&&XA(e,t,n),n};const py=C("debuglods"),QA=C("nolods");class wl{constructor(){a(this,"screenRelativeTransitionHeight"),a(this,"distance"),a(this,"renderers")}}hh([m()],wl.prototype,"screenRelativeTransitionHeight"),hh([m()],wl.prototype,"distance"),hh([m(Fi)],wl.prototype,"renderers");class YA{constructor(e){a(this,"model"),this.model=e}get renderers(){return this.model.renderers}}class dh extends I{constructor(){super(...arguments),a(this,"fadeMode",0),a(this,"localReferencePoint"),a(this,"lodCount",0),a(this,"size",0),a(this,"animateCrossFading",!1),a(this,"lodModels"),a(this,"_lods",[]),a(this,"_settings",[]),a(this,"_lodsHandler"),a(this,"_distanceFactor",1)}start(){if(py&&console.log("LODGROUP",this.name,this.lodModels,this),!QA&&!this._lodsHandler&&this.gameObject&&this.lodModels&&Array.isArray(this.lodModels)){const e=[];for(const s of this.lodModels){const n=new YA(s);this._lods.push(n);for(const r of n.renderers)e.includes(r)||e.push(r)}this._lodsHandler=new Array;for(let s=0;s<e.length;s++){const n=new TP;this._lodsHandler.push(n),this.gameObject.add(n)}const t=new E;t.name="Cull "+this.name;for(let s=0;s<e.length;s++){const n=e[s],r=this._lodsHandler[s],l=n.gameObject;py&&console.log(s,l.name);for(const c of this._lods){const h=c.model.distance;let d=null;if(c.renderers.includes(n)?d=l:d=t,d.type==="Group"){console.warn(`LODGroup ${this.name}: Group or MultiMaterial object's are not supported as LOD object: ${d.name}`);continue}py&&console.log("LEVEL",d.name,h),r.autoUpdate=!1,this.onAddLodLevel(r,d,c.model.distance)}}}}onAfterRender(){if(!this.gameObject||!this._lodsHandler)return;const e=this.context.mainCamera;if(e)for(const t of this._lodsHandler){t.update(e);const s=t.getCurrentLevel(),n=t.levels[s];t.layers.mask=n.object.layers.mask}}onAddLodLevel(e,t,s){if(t===this.gameObject){console.warn("LODGroup component must be on parent object and not mesh directly at the moment",t.name,t);return}e.addLevel(t,s*this._distanceFactor,.01);const n={lod:e,levelIndex:e.levels.length-1,distance:s};this._settings.push(n)}distanceFactor(e){if(e!==this._distanceFactor){this._distanceFactor=e;for(const t of this._settings){const s=t.lod.levels[t.levelIndex];s.distance=t.distance*e}}}}hh([m(x)],dh.prototype,"localReferencePoint"),hh([m(wl)],dh.prototype,"lodModels");var KA=Object.defineProperty,ZA=(o,e,t,s)=>{for(var n=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=l(e,t,n)||n);return n&&KA(e,t,n),n};const xp=C("debugnestedgltf");class Sp extends I{constructor(){super(...arguments),a(this,"filePath"),a(this,"loadAssetInParent",!0),a(this,"_isLoadingOrDoneLoading",!1)}listenToProgress(e){var t;(t=this.filePath)==null||t.beginListenDownload(e)}preload(){var e;(e=this.filePath)==null||e.preload()}async start(){var e,t,s,n,r;if(this._isLoadingOrDoneLoading)return;xp&&console.log(this,this.guid);const l=this.gameObject.parent;if(l){this._isLoadingOrDoneLoading=!0;const c=new Fs;c.idProvider=new Lt(this.hash(this.guid)),c.parent=this.loadAssetInParent!==!1?l:this.gameObject,this.gameObject.updateMatrix();const h=this.gameObject.matrix;xp&&console.log("Load nested:",((e=this.filePath)==null?void 0:e.url)??this.filePath,this.gameObject.position);const d=await((s=(t=this.filePath)==null?void 0:t.instantiate)==null?void 0:s.call(this.filePath,c));xp&&console.log("Nested loaded:",((n=this.filePath)==null?void 0:n.url)??this.filePath,d),d&&this.loadAssetInParent!==!1&&(d.matrixAutoUpdate=!1,d.matrix.identity(),d.applyMatrix4(h),d.matrixAutoUpdate=!0,d.layers.disableAll(),d.layers.set(this.layer),this.dispatchEvent(new CustomEvent("loaded",{detail:{instance:d,assetReference:this.filePath}}))),xp&&console.log("Nested loading done:",((r=this.filePath)==null?void 0:r.url)??this.filePath,d)}}onDestroy(){var e;(e=this.filePath)==null||e.unload()}hash(e){let t=0;for(let s=0;s<e.length;s++)t=e.charCodeAt(s)+((t<<5)-t);return t}}ZA([m(ce)],Sp.prototype,"filePath");var JA=Object.defineProperty,my=(o,e,t,s)=>{for(var n=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=l(e,t,n)||n);return n&&JA(e,t,n),n};const e2=C("debugnet"),Cp=class vv extends I{constructor(){super(...arguments),a(this,"url",null),a(this,"urlParameterName",null),a(this,"localhost",null)}awake(){e2&&console.log(this),this.context.connection.registerProvider(this)}getWebsocketUrl(){let e=this.url?vv.GetUrl(this.url,this.localhost):null;if(this.urlParameterName){const s=C(this.urlParameterName);s&&typeof s=="string"&&(e=s)}if(!e)return null;const t=new RegExp("(((https?)|(?<socket_prefix>wss?))://)?(www.)?(?<url>.+)","gm").exec(e);return t!=null&&t.groups?t?.groups.socket_prefix?e:"wss://"+t?.groups.url:null}static GetUrl(e,t){let s=e;const n=vv.IsLocalNetwork()&&t;if(n&&(s=t),e!=null&&e.startsWith("/")){const r=n?s:window.location.origin;r!=null&&r.endsWith("/")&&e.startsWith("/")&&(e=e.substring(1)),s=r+e}return s}static IsLocalNetwork(e=window.location.hostname){return qt(e)}};my([m()],Cp.prototype,"url"),my([m()],Cp.prototype,"urlParameterName"),my([m()],Cp.prototype,"localhost");let gy=Cp;var t2=Object.defineProperty,Pp=(o,e,t,s)=>{for(var n=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=l(e,t,n)||n);return n&&t2(e,t,n),n};class Zr extends I{constructor(){super(...arguments),a(this,"referenceSpace"),a(this,"from"),a(this,"affectPosition",!1),a(this,"affectRotation",!1),a(this,"alignLookDirection",!1),a(this,"levelLookDirection",!1),a(this,"levelPosition",!1),a(this,"positionOffset",new x(0,0,0)),a(this,"rotationOffset",new x(0,0,0)),a(this,"offset",new x(0,0,0))}update(){if(!this.from)return;var e=te(this.from),t=Se(this.from);this.offset.copy(this.positionOffset);const s=this.offset.length();if(this.referenceSpace&&this.offset.transformDirection(this.referenceSpace.matrixWorld).multiplyScalar(s),e.add(this.offset),this.levelPosition&&this.referenceSpace){const c=new mr(this.gameObject.up,0),h=te(this.referenceSpace);c.setFromNormalAndCoplanarPoint(this.gameObject.up,h);const d=new x(0,0,0);c.projectPoint(e,d),e.copy(d)}this.affectPosition&&lt(this.gameObject,e);const n=new jt(this.rotationOffset.x,this.rotationOffset.y,this.rotationOffset.z),r=new H().setFromEuler(n);this.affectRotation&&Qi(this.gameObject,t.multiply(r));const l=new x;this.from.getWorldDirection(l).multiplyScalar(50),this.levelLookDirection&&(l.y=0),this.alignLookDirection&&this.gameObject.lookAt(l)}}Pp([m(P)],Zr.prototype,"referenceSpace"),Pp([m(P)],Zr.prototype,"from"),Pp([m(x)],Zr.prototype,"positionOffset"),Pp([m(x)],Zr.prototype,"rotationOffset");var i2=Object.defineProperty,Ko=(o,e,t,s)=>{for(var n=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=l(e,t,n)||n);return n&&i2(e,t,n),n};class yi{constructor(e=0,t=0){a(this,"time",0),a(this,"value",0),a(this,"inTangent",1/0),a(this,"inWeight"),a(this,"outTangent",1/0),a(this,"outWeight"),a(this,"weightedMode"),this.time=e,this.value=t}}Ko([m()],yi.prototype,"time"),Ko([m()],yi.prototype,"value"),Ko([m()],yi.prototype,"inTangent"),Ko([m()],yi.prototype,"inWeight"),Ko([m()],yi.prototype,"outTangent"),Ko([m()],yi.prototype,"outWeight"),Ko([m()],yi.prototype,"weightedMode");const sS=class nd{constructor(){a(this,"keys",[])}static linearFromTo(e,t,s){const n=new nd,r=new yi;r.time=0,r.value=e;const l=new yi;return l.time=s,l.value=t,n.keys.push(r,l),n}static constant(e){const t=new nd,s=new yi;return s.time=0,s.value=e,t.keys.push(s),t}clone(){var e;const t=new nd;return t.keys=((e=this.keys)==null?void 0:e.map(s=>{const n=new yi;return n.time=s.time,n.value=s.value,n.inTangent=s.inTangent,n.inWeight=s.inWeight,n.outTangent=s.outTangent,n.outWeight=s.outWeight,n.weightedMode=s.weightedMode,n}))||[],t}get duration(){return!this.keys||this.keys.length==0?0:this.keys[this.keys.length-1].time}evaluate(e){if(!this.keys||this.keys.length==0)return 0;if(this.keys.length===1)return this.keys[0].value;if(this.keys[0].time>=e)return this.keys[0].value;for(let t=0;t<this.keys.length;t++){const s=this.keys[t];if(s.time<=e)if(t+1<this.keys.length){const n=this.keys[t+1];if(n.time<e)continue;return!isFinite(s.outTangent)||!isFinite(n.inTangent)?s.value:nd.interpolateValue(e,s,n)}else return s.value}return this.keys[this.keys.length-1].value}static interpolateValue(e,t,s){const n=t.time,r=t.value,l=t.outTangent,c=s.time,h=s.value,d=s.inTangent,u=c-n,p=u*u,g=p*u,f=((l+d)*u-2*(h-r))/g,y=(3*(h-r)-(d+2*l)*u)/p,b=l,v=r,_=e-n,w=_*_,S=w*_;return f*S+y*w+b*_+v}};Ko([m(yi)],sS.prototype,"keys");let uh=sS;var s2=Object.defineProperty,O=(o,e,t,s)=>{for(var n=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=l(e,t,n)||n);return n&&s2(e,t,n),n};const Op=C("debugparticles");var Zn=(o=>(o[o.Billboard=0]="Billboard",o[o.Stretch=1]="Stretch",o[o.HorizontalBillboard=2]="HorizontalBillboard",o[o.VerticalBillboard=3]="VerticalBillboard",o[o.Mesh=4]="Mesh",o))(Zn||{});class Jr{constructor(){a(this,"alphaKeys",[]),a(this,"colorKeys",[])}get duration(){return 1}evaluate(e,t){let s,n=0,r=null,l=0;for(let c=0;c<this.alphaKeys.length;c++){const h=this.alphaKeys[c];(h.time<e||!s)&&(s=h,n=c)}for(let c=0;c<this.colorKeys.length;c++){const h=this.colorKeys[c];(h.time<e||!r)&&(r=h,l=c)}if(r)if(l+1<this.colorKeys.length){const c=this.colorKeys[l+1],h=W.remap(e,r.time,c.time,0,1);t.r=W.lerp(r.color.r,c.color.r,h),t.g=W.lerp(r.color.g,c.color.g,h),t.b=W.lerp(r.color.b,c.color.b,h)}else t.r=r.color.r,t.g=r.color.g,t.b=r.color.b;if(s)if(n+1<this.alphaKeys.length){const c=this.alphaKeys[n+1],h=W.remap(e,s.time,c.time,0,1);t.alpha=W.lerp(s.alpha,c.alpha,h)}else t.alpha=s.alpha;return t}}O([m()],Jr.prototype,"alphaKeys"),O([m()],Jr.prototype,"colorKeys");var ph=(o=>(o[o.Local=0]="Local",o[o.World=1]="World",o[o.Custom=2]="Custom",o))(ph||{}),kp=(o=>(o[o.Sphere=0]="Sphere",o[o.SphereShell=1]="SphereShell",o[o.Hemisphere=2]="Hemisphere",o[o.HemisphereShell=3]="HemisphereShell",o[o.Cone=4]="Cone",o[o.Box=5]="Box",o[o.Mesh=6]="Mesh",o[o.ConeShell=7]="ConeShell",o[o.ConeVolume=8]="ConeVolume",o[o.ConeVolumeShell=9]="ConeVolumeShell",o[o.Circle=10]="Circle",o[o.CircleEdge=11]="CircleEdge",o[o.SingleSidedEdge=12]="SingleSidedEdge",o[o.MeshRenderer=13]="MeshRenderer",o[o.SkinnedMeshRenderer=14]="SkinnedMeshRenderer",o[o.BoxShell=15]="BoxShell",o[o.BoxEdge=16]="BoxEdge",o[o.Donut=17]="Donut",o[o.Rectangle=18]="Rectangle",o[o.Sprite=19]="Sprite",o[o.SpriteRenderer=20]="SpriteRenderer",o))(kp||{});const Jn=class od{constructor(){a(this,"mode","Constant"),a(this,"constant"),a(this,"constantMin"),a(this,"constantMax"),a(this,"curve"),a(this,"curveMin"),a(this,"curveMax"),a(this,"curveMultiplier")}static constant(e){const t=new od;return t.setConstant(e),t}static betweenTwoConstants(e,t){const s=new od;return s.setMinMaxConstant(e,t),s}static curve(e,t=1){const s=new od;return s.setCurve(e,t),s}setConstant(e){this.mode=0,this.constant=e}setMinMaxConstant(e,t){this.mode=3,this.constantMin=e,this.constantMax=t}setCurve(e,t=1){this.mode=1,this.curve=e,this.curveMultiplier=t}clone(){var e,t,s;const n=new od;return n.mode=this.mode,n.constant=this.constant,n.constantMin=this.constantMin,n.constantMax=this.constantMax,n.curve=(e=this.curve)==null?void 0:e.clone(),n.curveMin=(t=this.curveMin)==null?void 0:t.clone(),n.curveMax=(s=this.curveMax)==null?void 0:s.clone(),n.curveMultiplier=this.curveMultiplier,n}evaluate(e,t){const s=t===void 0?Math.random():t;switch(this.mode){case 0:case"Constant":return this.constant;case 1:case"Curve":return e=W.clamp01(e),this.curve.evaluate(e)*this.curveMultiplier;case 2:case"TwoCurves":const n=e*this.curveMin.duration,r=e*this.curveMax.duration;return W.lerp(this.curveMin.evaluate(n),this.curveMax.evaluate(r),s%1)*this.curveMultiplier;case 3:case"TwoConstants":return W.lerp(this.constantMin,this.constantMax,s%1);default:this.curveMax.evaluate(e)*this.curveMultiplier;break}return 0}getMax(){switch(this.mode){case 0:case"Constant":return this.constant;case 1:case"Curve":return this.getMaxFromCurve(this.curve)*this.curveMultiplier;case 2:case"TwoCurves":return Math.max(this.getMaxFromCurve(this.curveMin),this.getMaxFromCurve(this.curveMax))*this.curveMultiplier;case 3:case"TwoConstants":return Math.max(this.constantMin,this.constantMax);default:return 0}}getMaxFromCurve(e){if(!e)return 0;let t=Number.MIN_VALUE;for(let s=0;s<e.keys.length;s++){const n=e.keys[s];n.value>t&&(t=n.value)}return t}};O([m()],Jn.prototype,"mode"),O([m()],Jn.prototype,"constant"),O([m()],Jn.prototype,"constantMin"),O([m()],Jn.prototype,"constantMax"),O([m(uh)],Jn.prototype,"curve"),O([m(uh)],Jn.prototype,"curveMin"),O([m(uh)],Jn.prototype,"curveMax"),O([m()],Jn.prototype,"curveMultiplier");let Z=Jn;var st;const Zo=(st=class{constructor(){a(this,"mode",0),a(this,"color"),a(this,"colorMin"),a(this,"colorMax"),a(this,"gradient"),a(this,"gradientMin"),a(this,"gradientMax")}static constant(o){const e=new st;return e.constant(o),e}static betweenTwoColors(o,e){const t=new st;return t.betweenTwoColors(o,e),t}constant(o){return this.mode=0,this.color=o,this}betweenTwoColors(o,e){return this.mode=2,this.colorMin=o,this.colorMax=e,this}evaluate(o,e){const t=e===void 0?Math.random():e;switch(this.mode){case 0:case"Color":return this.color;case 1:case"Gradient":return this.gradient.evaluate(o,st._temp),st._temp;case 2:case"TwoColors":return st._temp.lerpColors(this.colorMin,this.colorMax,t);case 3:case"TwoGradients":return this.gradientMin.evaluate(o,st._temp),this.gradientMax.evaluate(o,st._temp2),st._temp.lerp(st._temp2,t);case 4:case"RandomColor":const s=Math.random();return this.gradientMin.evaluate(o,st._temp),this.gradientMax.evaluate(o,st._temp2),st._temp.lerp(st._temp2,s)}return st._temp.set(16777215),st._temp.alpha=1,st._temp}},a(st,"_temp",new he(0,0,0,1)),a(st,"_temp2",new he(0,0,0,1)),st);O([m()],Zo.prototype,"mode"),O([m(he)],Zo.prototype,"color"),O([m(he)],Zo.prototype,"colorMin"),O([m(he)],Zo.prototype,"colorMax"),O([m(Jr)],Zo.prototype,"gradient"),O([m(Jr)],Zo.prototype,"gradientMin"),O([m(Jr)],Zo.prototype,"gradientMax");let ea=Zo;var fy=(o=>(o[o.Hierarchy=0]="Hierarchy",o[o.Local=1]="Local",o[o.Shape=2]="Shape",o))(fy||{});class Nt{constructor(){a(this,"cullingMode"),a(this,"duration"),a(this,"emitterVelocityMode"),a(this,"flipRotation"),a(this,"gravityModifier"),a(this,"gravityModifierMultiplier"),a(this,"loop"),a(this,"maxParticles"),a(this,"playOnAwake"),a(this,"prewarm"),a(this,"ringBufferLoopRange"),a(this,"ringBufferMode"),a(this,"scalingMode"),a(this,"simulationSpace"),a(this,"simulationSpeed"),a(this,"startColor"),a(this,"startDelay"),a(this,"startDelayMultiplier"),a(this,"startLifetime"),a(this,"startLifetimeMultiplier"),a(this,"startRotation"),a(this,"startRotationMultiplier"),a(this,"startRotation3D"),a(this,"startRotationX"),a(this,"startRotationXMultiplier"),a(this,"startRotationY"),a(this,"startRotationYMultiplier"),a(this,"startRotationZ"),a(this,"startRotationZMultiplier"),a(this,"startSize"),a(this,"startSize3D"),a(this,"startSizeMultiplier"),a(this,"startSizeX"),a(this,"startSizeXMultiplier"),a(this,"startSizeY"),a(this,"startSizeYMultiplier"),a(this,"startSizeZ"),a(this,"startSizeZMultiplier"),a(this,"startSpeed"),a(this,"startSpeedMultiplier"),a(this,"stopAction"),a(this,"useUnscaledTime")}}O([m(Z)],Nt.prototype,"gravityModifier"),O([m(ea)],Nt.prototype,"startColor"),O([m(Z)],Nt.prototype,"startDelay"),O([m(Z)],Nt.prototype,"startLifetime"),O([m(Z)],Nt.prototype,"startRotation"),O([m(Z)],Nt.prototype,"startRotationX"),O([m(Z)],Nt.prototype,"startRotationY"),O([m(Z)],Nt.prototype,"startRotationZ"),O([m(Z)],Nt.prototype,"startSize"),O([m(Z)],Nt.prototype,"startSizeX"),O([m(Z)],Nt.prototype,"startSizeY"),O([m(Z)],Nt.prototype,"startSizeZ"),O([m(Z)],Nt.prototype,"startSpeed");class Mp{constructor(){a(this,"cycleCount"),a(this,"maxCount"),a(this,"minCount"),a(this,"probability"),a(this,"repeatInterval"),a(this,"time"),a(this,"count"),a(this,"_performed",0)}reset(){this._performed=0}run(e){if(e<=this.time)return 0;let t=0;if(this.cycleCount===0||this._performed<this.cycleCount){const s=this.time+this.repeatInterval*this._performed;if(e>=s&&(this._performed+=1,Math.random()<this.probability))switch(this.count.mode){case 0:t=this.count.constant;break;case 3:t=W.lerp(this.count.constantMin,this.count.constantMax,Math.random());break;case 1:t=this.count.curve.evaluate(Math.random());break;case 2:const n=Math.random();t=W.lerp(this.count.curveMin.evaluate(n),this.count.curveMax.evaluate(n),Math.random());break}}return t}}class eo{constructor(){a(this,"enabled"),a(this,"bursts"),a(this,"rateOverTime"),a(this,"rateOverTimeMultiplier"),a(this,"rateOverDistance"),a(this,"rateOverDistanceMultiplier"),a(this,"system")}get burstCount(){var e;return((e=this.bursts)==null?void 0:e.length)??0}reset(){var e;(e=this.bursts)==null||e.forEach(t=>t.reset())}getBurst(){let e=0;if(this.burstCount>0)for(let t=0;t<this.burstCount;t++){const s=this.bursts[t];this.system.main.loop&&s.time>=this.system.time&&s.reset(),e+=Math.round(s.run(this.system.time))}return e}}O([m()],eo.prototype,"enabled"),O([m()],eo.prototype,"bursts"),O([m(Z)],eo.prototype,"rateOverTime"),O([m()],eo.prototype,"rateOverTimeMultiplier"),O([m(Z)],eo.prototype,"rateOverDistance"),O([m()],eo.prototype,"rateOverDistanceMultiplier");class Rp{constructor(){a(this,"enabled"),a(this,"color")}}O([m(ea)],Rp.prototype,"color");class ta{constructor(){a(this,"enabled"),a(this,"separateAxes"),a(this,"size"),a(this,"sizeMultiplier"),a(this,"x"),a(this,"xMultiplier"),a(this,"y"),a(this,"yMultiplier"),a(this,"z"),a(this,"zMultiplier"),a(this,"_time",0),a(this,"_temp",new x)}evaluate(e,t,s){if(t||(t=this._temp),!this.enabled)return t.x=t.y=t.z=1,t;if(this.separateAxes)t.x=this.x.evaluate(e,s)*this.xMultiplier,t.y=this.y.evaluate(e,s)*this.yMultiplier,t.z=this.z.evaluate(e,s)*this.zMultiplier;else{const n=this.size.evaluate(e,s)*this.sizeMultiplier;t.x=n}return t}}O([m(Z)],ta.prototype,"size"),O([m(Z)],ta.prototype,"x"),O([m(Z)],ta.prototype,"y"),O([m(Z)],ta.prototype,"z");var Jo;const nt=(Jo=class{constructor(){a(this,"shapeType",5),a(this,"enabled",!0),a(this,"alignToDirection",!1),a(this,"angle",0),a(this,"arc",360),a(this,"arcSpread"),a(this,"arcSpeedMultiplier"),a(this,"arcMode"),a(this,"boxThickness"),a(this,"position"),a(this,"rotation"),a(this,"_rotation",new jt),a(this,"scale"),a(this,"radius"),a(this,"radiusThickness"),a(this,"sphericalDirectionAmount"),a(this,"randomDirectionAmount"),a(this,"randomPositionAmount"),a(this,"meshShapeType"),a(this,"meshRenderer"),a(this,"_meshObj"),a(this,"_meshGeometry"),a(this,"system"),a(this,"_space"),a(this,"_worldSpaceMatrix",new se),a(this,"_worldSpaceMatrixInverse",new se),a(this,"_vector",new x(0,0,0)),a(this,"_temp",new x(0,0,0)),a(this,"_triangle",new EP),a(this,"_dir",new x),a(this,"_loopTime",0),a(this,"_loopDirection",1),Op&&console.log(this)}get type(){return kp[this.shapeType]}initialize(o){this.onInitialize(o),o.position.x=this._vector.x,o.position.y=this._vector.y,o.position.z=this._vector.z}toJSON(){return this}clone(){return new Jo}setMesh(o){this.meshRenderer=o,o?(this._meshObj=o.sharedMeshes[Math.floor(Math.random()*o.sharedMeshes.length)],this._meshGeometry=this._meshObj.geometry):(this._meshObj=void 0,this._meshGeometry=void 0)}update(o,e){}onUpdate(o,e,t,s){this.system=o,this._space=t,t===1&&(this._worldSpaceMatrix.copy(s.matrixWorld),this._worldSpaceMatrix.elements[0]=1,this._worldSpaceMatrix.elements[5]=1,this._worldSpaceMatrix.elements[10]=1,this._worldSpaceMatrixInverse.copy(this._worldSpaceMatrix).invert())}applyRotation(o){const e=this.rotation.x!==0||this.rotation.y!==0||this.rotation.z!==0;return e&&(this._rotation.x=W.toRadians(this.rotation.x),this._rotation.y=W.toRadians(this.rotation.y),this._rotation.z=W.toRadians(this.rotation.z),this._rotation.order="ZYX",o.applyEuler(this._rotation)),e}onInitialize(o){this._vector.set(0,0,0),o.mesh=void 0,o.mesh_geometry=void 0;const e=this._temp.copy(this.position),t=this._space===1;t&&e.applyQuaternion(this.system.worldQuaternion);let s=this.radius;if(t&&(s*=this.system.worldScale.x),this.enabled){switch(this.shapeType){case 5:Op&&G.DrawWireBox(this.position,this.scale,14540253,1),this._vector.x=Math.random()*this.scale.x-this.scale.x/2,this._vector.y=Math.random()*this.scale.y-this.scale.y/2,this._vector.z=Math.random()*this.scale.z-this.scale.z/2,this._vector.add(e);break;case 4:this.randomConePoint(this.position,this.angle,s,this.radiusThickness,this.arc,this.arcMode,this._vector);break;case 0:this.randomSpherePoint(this.position,s,this.radiusThickness,this.arc,this._vector);break;case 10:this.randomCirclePoint(this.position,s,this.radiusThickness,this.arc,this._vector);break;case 13:const n=this.meshRenderer;n?.destroyed==!1&&this.setMesh(n);const r=o.mesh=this._meshObj,l=o.mesh_geometry=this._meshGeometry;if(r&&l)switch(this.meshShapeType){case 0:{const c=l.getAttribute("position"),h=Math.floor(Math.random()*c.count);this._vector.fromBufferAttribute(c,h),this._vector.applyMatrix4(r.matrixWorld),o.mesh_normal=h}break;case 1:break;case 2:{const c=l.index;if(c){let h=Math.random(),d=Math.random();h+d>1&&(h=1-h,d=1-d);const u=Math.floor(Math.random()*(c.count/3));let p=u*3,g=u*3+1,f=u*3+2;p=c.getX(p),g=c.getX(g),f=c.getX(f);const y=l.getAttribute("position");this._triangle.a.fromBufferAttribute(y,p),this._triangle.b.fromBufferAttribute(y,g),this._triangle.c.fromBufferAttribute(y,f),this._vector.set(0,0,0).addScaledVector(this._triangle.a,h).addScaledVector(this._triangle.b,d).addScaledVector(this._triangle.c,1-(h+d)),this._vector.applyMatrix4(r.matrixWorld),o.mesh_normal=u}}break}break;default:this._vector.set(0,0,0),F()&&!globalThis.__particlesystem_shapetype_unsupported&&(console.warn("ParticleSystem ShapeType is not supported:",kp[this.shapeType]),globalThis.__particlesystem_shapetype_unsupported=!0);break}this.randomizePosition(this._vector,this.randomPositionAmount)}this.applyRotation(this._vector),t&&(this._vector.applyQuaternion(this.system.worldQuaternion),this._vector.add(this.system.worldPos)),Op&&G.DrawSphere(this._vector,.03,16711680,.5,!0)}getDirection(o,e){var t;if(!this.enabled)return this._dir.set(0,0,1),this._dir;switch(this.shapeType){case 5:this._dir.set(0,0,1);break;case 4:this._dir.set(0,0,1);break;case 10:case 0:const s=e.x,n=e.y,r=e.z;this._dir.set(s,n,r),(t=this.system)!=null&&t.worldspace?this._dir.sub(this.system.worldPos):this._dir.sub(this.position);break;case 13:const l=o.mesh,c=o.mesh_geometry;if(l&&c)switch(this.meshShapeType){case 0:{const h=c.getAttribute("normal"),d=o.mesh_normal;this._dir.fromBufferAttribute(h,d)}break;case 1:break;case 2:{const h=c.index;if(h){const d=o.mesh_normal,u=h.getX(d*3),p=h.getX(d*3+1),g=h.getX(d*3+2),f=c.getAttribute("position"),y=X(),b=X(),v=X();y.fromBufferAttribute(f,u),b.fromBufferAttribute(f,p),v.fromBufferAttribute(f,g),y.sub(b),v.sub(b),y.cross(v),this._dir.copy(y).multiplyScalar(-1);const _=Se(l);this._dir.applyQuaternion(_)}}break}break;default:this._dir.set(0,0,1);break}return this._space===1&&this._dir.applyQuaternion(this.system.worldQuaternion),this.applyRotation(this._dir),this._dir.normalize(),this.spherizeDirection(this._dir,this.sphericalDirectionAmount),this.randomizeDirection(this._dir,this.randomDirectionAmount),Op&&(G.DrawSphere(e,.01,8925952,.5,!0),G.DrawDirection(e,this._dir,8925952,.5,!0)),this._dir}randomizePosition(o,e){if(e<=0)return;const t=Jo._tempVec;t.set(Math.random()*2-1,Math.random()*2-1,Math.random()*2-1),t.x*=e*this.scale.x,t.y*=e*this.scale.y,t.z*=e*this.scale.z,o.add(t)}randomizeDirection(o,e){if(e===0)return;const t=Jo._randomQuat,s=Jo._tempVec;s.set(Math.random()-.5,Math.random()-.5,Math.random()-.5).normalize(),t.setFromAxisAngle(s,e*Math.random()*Math.PI),o.applyQuaternion(t)}spherizeDirection(o,e){if(e===0)return;const t=Math.random()*Math.PI*2,s=Math.acos(1-Math.random()*2),n=Math.sin(s)*Math.cos(t),r=Math.sin(s)*Math.sin(t),l=Math.cos(s),c=new x(n,r,l);o.lerp(c,e)}randomSpherePoint(o,e,t,s,n){const r=Math.random(),l=Math.random(),c=2*Math.PI*r*(s/360),h=Math.acos(2*l-1),d=W.lerp(1,1-Math.pow(1-Math.random(),Math.PI),t)*e,u=o.x+this.scale.x*(-d*Math.sin(h)*Math.cos(c)),p=o.y+this.scale.y*(d*Math.sin(h)*Math.sin(c)),g=o.z+this.scale.z*(d*Math.cos(h));n.x=u,n.y=p,n.z=g}randomCirclePoint(o,e,t,s,n){const r=Math.random(),l=2*Math.PI*r*(s/360),c=W.lerp(1,1-Math.pow(1-Math.random(),Math.PI),t)*e,h=o.x+this.scale.x*c*Math.cos(l),d=o.y+this.scale.y*c*Math.sin(l),u=o.z;n.x=h,n.y=d,n.z=u}randomConePoint(o,e,t,s,n,r,l){let c=0,h=0;switch(r){case 0:c=Math.random(),h=Math.random();break;case 2:this._loopTime>1&&(this._loopDirection=-1),this._loopTime<0&&(this._loopDirection=1);case 1:c=.5,h=Math.random(),this._loopTime+=this.system.deltaTime*this._loopDirection;break}let d=2*Math.PI*c*(n/360);switch(r){case 2:case 1:d+=Math.PI+.5,d+=this._loopTime*Math.PI*2,d%=W.toRadians(n);break}const u=Math.acos(2*h-1),p=W.lerp(1,1-Math.pow(1-Math.random(),Math.PI),s)*t,g=o.x+-p*Math.sin(u)*Math.cos(d),f=o.y+p*Math.sin(u)*Math.sin(d),y=o.z;l.x=g*this.scale.x,l.y=f*this.scale.y,l.z=y*this.scale.z}},a(Jo,"_randomQuat",new H),a(Jo,"_tempVec",new x),Jo);O([m()],nt.prototype,"shapeType"),O([m()],nt.prototype,"enabled"),O([m()],nt.prototype,"alignToDirection"),O([m()],nt.prototype,"angle"),O([m()],nt.prototype,"arc"),O([m()],nt.prototype,"arcSpread"),O([m()],nt.prototype,"arcSpeedMultiplier"),O([m()],nt.prototype,"arcMode"),O([m(x)],nt.prototype,"boxThickness"),O([m(x)],nt.prototype,"position"),O([m(x)],nt.prototype,"rotation"),O([m(x)],nt.prototype,"scale"),O([m()],nt.prototype,"radius"),O([m()],nt.prototype,"radiusThickness"),O([m()],nt.prototype,"sphericalDirectionAmount"),O([m()],nt.prototype,"randomDirectionAmount"),O([m()],nt.prototype,"randomPositionAmount"),O([m()],nt.prototype,"meshShapeType"),O([m(qc)],nt.prototype,"meshRenderer");let yy=nt;class Ce{constructor(){a(this,"damping"),a(this,"enabled"),a(this,"frequency"),a(this,"octaveCount"),a(this,"octaveMultiplier"),a(this,"octaveScale"),a(this,"positionAmount"),a(this,"quality"),a(this,"remap"),a(this,"remapEnabled"),a(this,"remapMultiplier"),a(this,"remapX"),a(this,"remapXMultiplier"),a(this,"remapY"),a(this,"remapYMultiplier"),a(this,"remapZ"),a(this,"remapZMultiplier"),a(this,"scrollSpeedMultiplier"),a(this,"separateAxes"),a(this,"strengthMultiplier"),a(this,"strengthX"),a(this,"strengthXMultiplier"),a(this,"strengthY"),a(this,"strengthYMultiplier"),a(this,"strengthZ"),a(this,"strengthZMultiplier"),a(this,"_noise"),a(this,"_time",0),a(this,"_temp",new x)}update(e){this._time+=e.time.deltaTime*this.scrollSpeedMultiplier}apply(e,t,s,n,r,l){if(!this.enabled)return;this._noise||(this._noise=fO(()=>0));const c=this._temp.set(t.x,t.y,t.z).multiplyScalar(this.frequency),h=this._noise(c.x,c.y,c.z,this._time),d=this._noise(c.x,c.y,c.z,this._time+1e3*this.frequency),u=this._noise(c.x,c.y,c.z,this._time+2e3*this.frequency);this._temp.set(h,d,u).normalize();const p=r/l;let g=this.positionAmount.evaluate(p);this.separateAxes?(this._temp.x*=g*this.strengthXMultiplier,this._temp.y*=g*this.strengthYMultiplier,this._temp.z*=g*this.strengthZMultiplier):(this.strengthX&&(g*=this.strengthX.evaluate(p)*1.5),this._temp.multiplyScalar(g)),s.x+=this._temp.x,s.y+=this._temp.y,s.z+=this._temp.z}}O([m()],Ce.prototype,"damping"),O([m()],Ce.prototype,"enabled"),O([m()],Ce.prototype,"frequency"),O([m()],Ce.prototype,"octaveCount"),O([m()],Ce.prototype,"octaveMultiplier"),O([m()],Ce.prototype,"octaveScale"),O([m(Z)],Ce.prototype,"positionAmount"),O([m()],Ce.prototype,"quality"),O([m(Z)],Ce.prototype,"remap"),O([m()],Ce.prototype,"remapEnabled"),O([m()],Ce.prototype,"remapMultiplier"),O([m(Z)],Ce.prototype,"remapX"),O([m()],Ce.prototype,"remapXMultiplier"),O([m(Z)],Ce.prototype,"remapY"),O([m()],Ce.prototype,"remapYMultiplier"),O([m(Z)],Ce.prototype,"remapZ"),O([m()],Ce.prototype,"remapZMultiplier"),O([m()],Ce.prototype,"scrollSpeedMultiplier"),O([m()],Ce.prototype,"separateAxes"),O([m()],Ce.prototype,"strengthMultiplier"),O([m(Z)],Ce.prototype,"strengthX"),O([m()],Ce.prototype,"strengthXMultiplier"),O([m(Z)],Ce.prototype,"strengthY"),O([m()],Ce.prototype,"strengthYMultiplier"),O([m(Z)],Ce.prototype,"strengthZ"),O([m()],Ce.prototype,"strengthZMultiplier");class We{constructor(){a(this,"enabled"),a(this,"attachRibbonToTransform",!1),a(this,"colorOverLifetime"),a(this,"colorOverTrail"),a(this,"dieWithParticles",!0),a(this,"inheritParticleColor",!0),a(this,"lifetime"),a(this,"lifetimeMultiplier"),a(this,"minVertexDistance",.2),a(this,"mode",0),a(this,"ratio",1),a(this,"ribbonCount",1),a(this,"shadowBias",0),a(this,"sizeAffectsLifetime",!1),a(this,"sizeAffectsWidth",!1),a(this,"splitSubEmitterRibbons",!1),a(this,"textureMode",0),a(this,"widthOverTrail"),a(this,"widthOverTrailMultiplier"),a(this,"worldSpace",!1)}getWidth(e,t,s,n){const r=this.widthOverTrail.evaluate(s,n);return e*=r,e}getColor(e,t,s){const n=this.colorOverTrail.evaluate(s),r=this.colorOverLifetime.evaluate(t);e.x*=n.r*r.r,e.y*=n.g*r.g,e.z*=n.b*r.b,"alpha"in n&&"alpha"in r&&(e.w*=n.alpha*r.alpha)}}O([m()],We.prototype,"enabled"),O([m()],We.prototype,"attachRibbonToTransform"),O([m(ea)],We.prototype,"colorOverLifetime"),O([m(ea)],We.prototype,"colorOverTrail"),O([m()],We.prototype,"dieWithParticles"),O([m()],We.prototype,"inheritParticleColor"),O([m(Z)],We.prototype,"lifetime"),O([m()],We.prototype,"lifetimeMultiplier"),O([m()],We.prototype,"minVertexDistance"),O([m()],We.prototype,"mode"),O([m()],We.prototype,"ratio"),O([m()],We.prototype,"ribbonCount"),O([m()],We.prototype,"shadowBias"),O([m()],We.prototype,"sizeAffectsLifetime"),O([m()],We.prototype,"sizeAffectsWidth"),O([m()],We.prototype,"splitSubEmitterRibbons"),O([m()],We.prototype,"textureMode"),O([m(Z)],We.prototype,"widthOverTrail"),O([m()],We.prototype,"widthOverTrailMultiplier"),O([m()],We.prototype,"worldSpace");class qe{constructor(){a(this,"enabled"),a(this,"space",0),a(this,"orbitalX"),a(this,"orbitalY"),a(this,"orbitalZ"),a(this,"orbitalXMultiplier"),a(this,"orbitalYMultiplier"),a(this,"orbitalZMultiplier"),a(this,"orbitalOffsetX"),a(this,"orbitalOffsetY"),a(this,"orbitalOffsetZ"),a(this,"speedModifier"),a(this,"speedModifierMultiplier"),a(this,"x"),a(this,"xMultiplier"),a(this,"y"),a(this,"yMultiplier"),a(this,"z"),a(this,"zMultiplier"),a(this,"_system"),a(this,"_temp",new x),a(this,"_temp2",new x),a(this,"_temp3",new x),a(this,"_hasOrbital",!1),a(this,"_index",0),a(this,"_orbitalMatrix",new se)}update(e){this._system=e}init(e){this._index==0&&(e.debug=!0),this._index+=1,e.orbitx=this.orbitalX.evaluate(Math.random()),e.orbity=this.orbitalY.evaluate(Math.random()),e.orbitz=this.orbitalZ.evaluate(Math.random()),this._hasOrbital=e.orbitx!=0||e.orbity!=0||e.orbitz!=0}apply(e,t,s,n,r,l,c){var h;if(!this.enabled)return;const d=l/c,u=this.speedModifier.evaluate(d)*this.speedModifierMultiplier,p=this.x.evaluate(d),g=this.y.evaluate(d),f=this.z.evaluate(d);if(this._temp.set(-p,g,f),this._system&&this._system.main.simulationSpace===1&&this._temp.applyQuaternion(this._system.worldQuaternion),this._hasOrbital&&((h=this._system)==null?void 0:h.worldPos)){const y=this._temp2.set(s.x,s.y,s.z),b=this.orbitalXMultiplier,v=this.orbitalYMultiplier,_=this.orbitalZMultiplier,w=u*Math.PI*2*10,S=Math.cos(w*b),k=Math.sin(w*b),M=Math.cos(w*v),T=Math.sin(w*v),L=Math.cos(w*_),B=Math.sin(w*_),z=y.x*(M*L)+y.y*(M*B)+y.z*-T,D=y.x*(k*T*L-S*B)+y.y*(k*T*B+S*L)+y.z*(k*M),V=y.x*(S*T*L+k*B)+y.y*(S*T*B-k*L)+y.z*(S*M),$=this._temp3.set(y.x-z,y.y-D,y.z-V);$.normalize(),$.multiplyScalar(.2/r*Math.max(this.orbitalXMultiplier,this.orbitalYMultiplier,this.orbitalZMultiplier)),n.x+=$.x,n.y+=$.y,n.z+=$.z}n.x+=this._temp.x,n.y+=this._temp.y,n.z+=this._temp.z,n.x*=u,n.y*=u,n.z*=u}}O([m()],qe.prototype,"enabled"),O([m()],qe.prototype,"space"),O([m(Z)],qe.prototype,"orbitalX"),O([m(Z)],qe.prototype,"orbitalY"),O([m(Z)],qe.prototype,"orbitalZ"),O([m()],qe.prototype,"orbitalXMultiplier"),O([m()],qe.prototype,"orbitalYMultiplier"),O([m()],qe.prototype,"orbitalZMultiplier"),O([m()],qe.prototype,"orbitalOffsetX"),O([m()],qe.prototype,"orbitalOffsetY"),O([m()],qe.prototype,"orbitalOffsetZ"),O([m(Z)],qe.prototype,"speedModifier"),O([m()],qe.prototype,"speedModifierMultiplier"),O([m(Z)],qe.prototype,"x"),O([m()],qe.prototype,"xMultiplier"),O([m(Z)],qe.prototype,"y"),O([m()],qe.prototype,"yMultiplier"),O([m(Z)],qe.prototype,"z"),O([m()],qe.prototype,"zMultiplier");class Wt{constructor(){a(this,"animation"),a(this,"enabled"),a(this,"cycleCount"),a(this,"frameOverTime"),a(this,"frameOverTimeMultiplier"),a(this,"numTilesX"),a(this,"numTilesY"),a(this,"startFrame"),a(this,"startFrameMultiplier"),a(this,"rowMode"),a(this,"rowIndex"),a(this,"spriteCount"),a(this,"timeMode")}sampleOnceAtStart(){if(this.timeMode===0)switch(this.frameOverTime.mode){case 0:case 3:case 2:case 1:return!0}return!1}getStartIndex(){return this.sampleOnceAtStart()?Math.random()*(this.numTilesX*this.numTilesY):0}evaluate(e){if(!this.sampleOnceAtStart())return this.getIndex(e)}getIndex(e){const t=this.numTilesX*this.numTilesY;e=e*this.cycleCount;let s=this.frameOverTime.evaluate(e%1);return s*=this.frameOverTimeMultiplier,s*=t,s=s%t,s=Math.floor(s),s}}O([m()],Wt.prototype,"animation"),O([m()],Wt.prototype,"enabled"),O([m()],Wt.prototype,"cycleCount"),O([m(Z)],Wt.prototype,"frameOverTime"),O([m()],Wt.prototype,"frameOverTimeMultiplier"),O([m()],Wt.prototype,"numTilesX"),O([m()],Wt.prototype,"numTilesY"),O([m(Z)],Wt.prototype,"startFrame"),O([m()],Wt.prototype,"startFrameMultiplier"),O([m()],Wt.prototype,"rowMode"),O([m()],Wt.prototype,"rowIndex"),O([m()],Wt.prototype,"spriteCount"),O([m()],Wt.prototype,"timeMode");class Es{constructor(){a(this,"enabled"),a(this,"separateAxes"),a(this,"x"),a(this,"xMultiplier"),a(this,"y"),a(this,"yMultiplier"),a(this,"z"),a(this,"zMultiplier")}evaluate(e,t){return this.enabled?this.separateAxes?0:this.z.evaluate(e,t)*-1:0}}O([m()],Es.prototype,"enabled"),O([m()],Es.prototype,"separateAxes"),O([m(Z)],Es.prototype,"x"),O([m()],Es.prototype,"xMultiplier"),O([m(Z)],Es.prototype,"y"),O([m()],Es.prototype,"yMultiplier"),O([m(Z)],Es.prototype,"z"),O([m()],Es.prototype,"zMultiplier");class as{constructor(){a(this,"enabled"),a(this,"range"),a(this,"separateAxes"),a(this,"x"),a(this,"xMultiplier"),a(this,"y"),a(this,"yMultiplier"),a(this,"z"),a(this,"zMultiplier")}evaluate(e,t){if(!this.enabled)return 0;if(!this.separateAxes){const s=W.lerp(this.range.x,this.range.y,t);return this.z.evaluate(s)*-1}return 0}}O([m()],as.prototype,"enabled"),O([m()],as.prototype,"range"),O([m()],as.prototype,"separateAxes"),O([m(Z)],as.prototype,"x"),O([m()],as.prototype,"xMultiplier"),O([m(Z)],as.prototype,"y"),O([m()],as.prototype,"yMultiplier"),O([m(Z)],as.prototype,"z"),O([m()],as.prototype,"zMultiplier");class gt{constructor(){a(this,"enabled"),a(this,"dampen"),a(this,"drag"),a(this,"dragMultiplier"),a(this,"limit"),a(this,"limitMultiplier"),a(this,"separateAxes"),a(this,"limitX"),a(this,"limitXMultiplier"),a(this,"limitY"),a(this,"limitYMultiplier"),a(this,"limitZ"),a(this,"limitZMultiplier"),a(this,"multiplyDragByParticleSize",!1),a(this,"multiplyDragByParticleVelocity",!1),a(this,"space"),a(this,"_temp",new x),a(this,"_temp2",new x)}apply(e,t,s,n,r,l,c){if(this.enabled){const h=this.limit.evaluate(r)*this.limitMultiplier;if(t.length()>h){this._temp.copy(t).normalize().multiplyScalar(h);const d=this.dampen*.5;t.x=W.lerp(t.x,this._temp.x,d),t.y=W.lerp(t.y,this._temp.y,d),t.z=W.lerp(t.z,this._temp.z,d),s.x=W.lerp(s.x,this._temp.x,d),s.y=W.lerp(s.y,this._temp.y,d),s.z=W.lerp(s.z,this._temp.z,d)}}}}O([m()],gt.prototype,"enabled"),O([m()],gt.prototype,"dampen"),O([m(Z)],gt.prototype,"drag"),O([m()],gt.prototype,"dragMultiplier"),O([m(Z)],gt.prototype,"limit"),O([m()],gt.prototype,"limitMultiplier"),O([m()],gt.prototype,"separateAxes"),O([m(Z)],gt.prototype,"limitX"),O([m()],gt.prototype,"limitXMultiplier"),O([m(Z)],gt.prototype,"limitY"),O([m()],gt.prototype,"limitYMultiplier"),O([m(Z)],gt.prototype,"limitZ"),O([m()],gt.prototype,"limitZMultiplier"),O([m()],gt.prototype,"multiplyDragByParticleSize"),O([m()],gt.prototype,"multiplyDragByParticleVelocity"),O([m()],gt.prototype,"space");const mh=class PC{constructor(){a(this,"enabled"),a(this,"curve"),a(this,"curveMultiplier"),a(this,"mode"),a(this,"system"),a(this,"_temp",new x),a(this,"_firstUpdate",!0),a(this,"_frames",0)}clone(){var e;const t=new PC;return t.enabled=this.enabled,t.curve=(e=this.curve)==null?void 0:e.clone(),t.curveMultiplier=this.curveMultiplier,t.mode=this.mode,t}get _lastWorldPosition(){return this.system._iv_lastWorldPosition||(this.system._iv_lastWorldPosition=new x),this.system._iv_lastWorldPosition}get _velocity(){return this.system._iv_velocity||(this.system._iv_velocity=new x),this.system._iv_velocity}awake(e){this.system=e,this.reset()}reset(){this._firstUpdate=!0}update(e){this.enabled&&this.system.worldspace!==!1&&(this._firstUpdate?(this._firstUpdate=!1,this._velocity.set(0,0,0),this._lastWorldPosition.copy(this.system.worldPos)):this._lastWorldPosition&&(this._velocity.copy(this.system.worldPos).sub(this._lastWorldPosition).multiplyScalar(1/this.system.deltaTime),this._lastWorldPosition.copy(this.system.worldPos)))}applyInitial(e){if(this.enabled&&this.system.worldspace!==!1&&this.mode===0){const t=this.curve.evaluate(Math.random(),Math.random());this._temp.copy(this._velocity).multiplyScalar(t),e.x+=this._temp.x,e.y+=this._temp.y,e.z+=this._temp.z}}applyCurrent(e,t,s){if(this.enabled&&this.system&&this.system.worldspace!==!1&&this.mode===1){const n=this.curve.evaluate(t,s);this._temp.copy(this._velocity).multiplyScalar(n),e.x+=this._temp.x,e.y+=this._temp.y,e.z+=this._temp.z}}};O([m()],mh.prototype,"enabled"),O([m(Z)],mh.prototype,"curve"),O([m()],mh.prototype,"curveMultiplier"),O([m()],mh.prototype,"mode");let vy=mh;class vi{constructor(){a(this,"enabled"),a(this,"range"),a(this,"separateAxes"),a(this,"size"),a(this,"sizeMultiplier"),a(this,"x"),a(this,"xMultiplier"),a(this,"y"),a(this,"yMultiplier"),a(this,"z"),a(this,"zMultiplier")}evaluate(e,t,s,n){const r=e.length(),l=W.remap(r,this.range.x,this.range.y,0,1),c=this.size.evaluate(l,s);return n.x*=c,n.y*=c,n.z*=c,n}}O([m()],vi.prototype,"enabled"),O([m(le)],vi.prototype,"range"),O([m()],vi.prototype,"separateAxes"),O([m(Z)],vi.prototype,"size"),O([m()],vi.prototype,"sizeMultiplier"),O([m(Z)],vi.prototype,"x"),O([m()],vi.prototype,"xMultiplier"),O([m(Z)],vi.prototype,"y"),O([m()],vi.prototype,"yMultiplier"),O([m(Z)],vi.prototype,"z"),O([m()],vi.prototype,"zMultiplier");class xl{constructor(){a(this,"enabled"),a(this,"range"),a(this,"color")}evaluate(e,t,s){const n=e.length(),r=W.remap(n,this.range.x,this.range.y,0,1),l=this.color.evaluate(r,t);s.x*=l.r,s.y*=l.g,s.z*=l.b,"alpha"in l&&(s.w*=l.alpha)}}O([m()],xl.prototype,"enabled"),O([m(le)],xl.prototype,"range"),O([m(ea)],xl.prototype,"color"),new x(1,1,1),new x(0,0,1);class by{constructor(e,t,s,n){a(this,"type","NeedleParticleSubEmitter"),a(this,"emitterType"),a(this,"emitterProbability"),a(this,"q_",new H),a(this,"v_",new x),a(this,"v2_",new x),a(this,"_emitterMatrix",new zm),a(this,"_circularBuffer"),this.system=e,this.particleSystem=t,this.subSystem=s,this.subParticleSystem=n,this.subParticleSystem&&this.subParticleSystem&&(this.subParticleSystem.onlyUsedByOther=!0);const r=1e3;this._circularBuffer=new Pi(()=>new zm,r)}clone(){throw new Error("Method not implemented.")}initialize(e){e.emissionState={burstIndex:0,burstWaveIndex:0,time:0,waitEmiting:0},this._emitterMatrix.copy(this.subSystem.matrixWorld).invert().premultiply(this.system.matrixWorld),this._emitterMatrix.setPosition(0,0,0),this.emitterType===_y.Birth&&this.run(e)}update(e,t){this.run(e)}frameUpdate(e){}toJSON(){}reset(){}run(e){if(this.subSystem.currentParticles>=this.subSystem.main.maxParticles||!this.subParticleSystem||!e.emissionState||this.emitterProbability&&Math.random()>this.emitterProbability)return;const t=this.system.deltaTime;if(this.emitterType===_y.Death){let n=e.life;if(e[Sl]!==void 0&&(n=e[Sl]),!(e.age+t*1.2>=n))return;const r=this.subSystem.main.maxParticles-this.subSystem.currentParticles;e.emissionState.waitEmiting=r}const s=new zm;s.set(1,0,0,e.position.x,0,1,0,e.position.y,0,0,1,e.position.z,0,0,0,1),this.particleSystem.worldSpace||s.multiplyMatrices(this._emitterMatrix,s),this.subParticleSystem.emit(t,e.emissionState,s)}}var n2=Object.defineProperty,Ve=(o,e,t,s)=>{for(var n=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=l(e,t,n)||n);return n&&n2(e,t,n),n};const er=C("debugparticles"),o2=C("noprogressive"),r2=C("debugprogressive");var _y=(o=>(o[o.Birth=0]="Birth",o[o.Collision=1]="Collision",o[o.Death=2]="Death",o[o.Trigger=3]="Trigger",o[o.Manual=4]="Manual",o))(_y||{});class ls extends I{constructor(){super(...arguments),a(this,"renderMode"),a(this,"particleMaterial"),a(this,"trailMaterial"),a(this,"particleMesh"),a(this,"maxParticleSize"),a(this,"minParticleSize"),a(this,"velocityScale"),a(this,"cameraVelocityScale"),a(this,"lengthScale")}start(){if(this.maxParticleSize!==.5&&this.minParticleSize!==0&&F()){const e=`ParticleSystem "${this.name}" has non-default min/max particle size. This may not render correctly. Please set min size to 0 and the max size to 0.5 and use the "StartSize" setting instead`;console.warn(e)}}get transparent(){var e;return((e=this.particleMaterial)==null?void 0:e.transparent)??!1}getMaterial(e=!1){let t=e===!0&&this.trailMaterial?this.trailMaterial:this.particleMaterial;if(t){if(t.type==="MeshStandardMaterial"){er&&console.debug("ParticleSystemRenderer.getMaterial: MeshStandardMaterial detected, converting to MeshBasicMaterial. See https://github.com/Alchemist0823/three.quarks/issues/101"),"map"in t&&t.map&&(t.map.colorSpace=On,t.map.premultiplyAlpha=!1);const s=new Me;s.copy(t),e?this.trailMaterial=s:this.particleMaterial=s}t.map&&(t.map.colorSpace=On,t.map.premultiplyAlpha=!1),e&&t.side===go&&(t=t.clone(),t.side=bd,e?this.trailMaterial=t:this.particleMaterial=t)}return t&&!o2&&t._didRequestTextureLOD===void 0&&(t._didRequestTextureLOD=0,r2&&console.log("Load material LOD",t.name),Xe.assignTextureLOD(t,0)),t}getMesh(e){let t=null;if(!t&&(this.particleMesh instanceof q&&(t=this.particleMesh.geometry),t===null)){t=new Ns(1,1);const s=t.attributes.uv;for(let n=0;n<s.count;n++)s.setX(n,1-s.getX(n))}return new q(t,this.getMaterial())}}Ve([m()],ls.prototype,"renderMode"),Ve([m(Pe)],ls.prototype,"particleMaterial"),Ve([m(Pe)],ls.prototype,"trailMaterial"),Ve([m()],ls.prototype,"maxParticleSize"),Ve([m()],ls.prototype,"minParticleSize"),Ve([m()],ls.prototype,"velocityScale"),Ve([m()],ls.prototype,"cameraVelocityScale"),Ve([m()],ls.prototype,"lengthScale");class Tp{constructor(e,t=1){a(this,"_curve"),a(this,"_factor"),a(this,"type","function"),this._curve=e,this._factor=t}startGen(e){}genValue(e,t){return this._curve.evaluate(t,Math.random())*this._factor}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}}class wy{constructor(e){a(this,"type","value"),a(this,"system"),this.system=e}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}startGen(e){}}class a2 extends wy{genValue(){return this.system.textureSheetAnimation.getStartIndex()}}class l2 extends wy{constructor(){super(...arguments),a(this,"_lastPosition",new x),a(this,"_lastDistance",0)}update(){const e=te(this.system.gameObject);this._lastDistance=this._lastPosition.distanceTo(e),this._lastPosition.copy(e)}genValue(){if(!this.system.isPlaying||!this.system.emission.enabled||this.system.currentParticles>=this.system.maxParticles)return 0;let e=this.system.emission.rateOverTime.evaluate(this.system.time/this.system.duration,Math.random());if(this.system.deltaTime>0){const n=this.system.emission.rateOverDistance.evaluate(this.system.time/this.system.duration,Math.random());let r=this._lastDistance/this.system.deltaTime*n;Number.isFinite(r)||(r=0),e+=r}const t=this.system.emission.getBurst();t>0&&(e+=t/this.system.deltaTime);const s=this.system.maxParticles-this.system.currentParticles;return W.clamp(e,0,s/this.system.deltaTime)}}class c2 extends wy{genValue(){return this.system.isPlaying,0}}class tr{constructor(e){a(this,"system"),a(this,"type"),this.type=Object.getPrototypeOf(this).constructor.name||"ParticleSystemBaseBehaviour",e&&(this.system=e)}get context(){return this.system.context}initialize(e){}update(e,t){}frameUpdate(e){}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}reset(){}}class h2 extends tr{constructor(){super(...arguments),a(this,"type","NeedleTextureSheet")}update(e,t){const s=this.system.textureSheetAnimation;if(s.enabled){const n=e.age/e.life,r=s.evaluate(n);r!==void 0&&(e.uvTile=r)}}}const nS=Symbol("particleRotation");class d2 extends tr{constructor(){super(...arguments),a(this,"type","NeedleRotation")}initialize(e){e[nS]=Math.random()}update(e,t){if(e.rotation===void 0)return;const s=e.age/e.life;if(typeof e.rotation=="number"&&(this.system.rotationOverLifetime.enabled?e.rotation+=this.system.rotationOverLifetime.evaluate(s,e[nS])*t:this.system.renderer.renderMode===Zn.Billboard&&(e.rotation=Math.PI),this.system.rotationBySpeed.enabled)){const n=e.velocity.length();e.rotation+=this.system.rotationBySpeed.evaluate(s,n)*t}}}const oS=Symbol("sizeLerpFactor"),u2=new x;class p2 extends tr{constructor(){super(...arguments),a(this,"type","NeedleSize"),a(this,"_minSize",0),a(this,"_maxSize",1)}initialize(e){e[oS]=Math.random(),this._minSize=this.system.renderer.minParticleSize,this._maxSize=this.system.renderer.maxParticleSize}update(e,t){const s=e.age/e.life;let n=1;this.system.sizeOverLifetime.enabled&&(n*=this.system.sizeOverLifetime.evaluate(s,void 0,e[oS]).x);let r=1;this.system.renderer.renderMode!==Zn.Mesh&&(r=this.system.worldScale.x/this.system.cameraScale);const l=X(e.startSize).multiplyScalar(n*r);if(e.size.set(l.x,l.y,l.z),this.system.localspace){const c=hS(this.system,u2);e.size.x*=c.x,e.size.y*=c.y,e.size.z*=c.z}}}const Sl=Symbol("particleLife"),xy=Symbol("trailLifetime"),rS=Symbol("trailStartLength"),Sy=Symbol("trailWidthRandom");class m2 extends tr{constructor(){super(...arguments),a(this,"type","NeedleTrail")}initialize(e){e instanceof qv&&(e[Sl]=e.life,this.system.trails.enabled&&this.system.trails.dieWithParticles===!1&&(e[xy]=this.system.trails.lifetime.evaluate(Math.random(),Math.random()),e.life+=e[xy]),e[rS]=e.length,e[Sy]=Math.random())}update(e){var t;if((t=this.system.trails)!=null&&t.enabled&&e instanceof qv){const s=e,n=e.age/e[Sl],r=e.previous.values(),l=e.previous.length;for(let c=0;c<l;c++){const h=r.next().value,d=1-c/(l-1),u=e.size;if(u.x<=0&&!this.system.trails.sizeAffectsWidth){const p=20*this.system.trails.widthOverTrail.evaluate(.5,s[Sy]);u.x=p,u.y=p,u.z=p}h.size=this.system.trails.getWidth(u.x,n,d,s[Sy]),h.color.copy(e.color),this.system.trails.getColor(h.color,n,d)}if(e.age>e[Sl]){e.velocity.set(0,0,0);const c=(e.age-e[Sl])/e[xy];s.length=W.lerp(e[rS],0,c)}}}}const Ep=Symbol("startVelocity"),aS=Symbol("gravityModifier"),Cy=Symbol("gravitySpeed"),Ap=Symbol("velocity lerp factor"),Py=new x;class g2 extends tr{constructor(){super(...arguments),a(this,"type","NeedleVelocity"),a(this,"_gravityDirection",new x)}initialize(e){var t,s;const n=this.system.main.simulationSpeed;e.startSpeed=this.system.main.startSpeed.evaluate(Math.random(),Math.random());const r=this.system.shape.getDirection(e,e.position);e.velocity.x=r.x*e.startSpeed,e.velocity.y=r.y*e.startSpeed,e.velocity.z=r.z*e.startSpeed,(t=this.system.inheritVelocity)!=null&&t.enabled&&this.system.inheritVelocity.applyInitial(e.velocity),e[Ep]?e[Ep].copy(e.velocity):e[Ep]=e.velocity.clone();const l=this.system.main.gravityModifier.evaluate(Math.random(),Math.random());e[aS]=l*n,e[Cy]=l*n*.5,e[Ap]=Math.random(),(s=this.system.velocityOverLifetime)==null||s.init(e),this._gravityDirection.set(0,-1,0),this.system.main.simulationSpace===ph.Local&&this._gravityDirection.applyQuaternion(this.system.worldQuaternionInverted).normalize()}update(e,t){var s;const n=e[Ep],r=e[aS];if(r!==0){const g=r*e[Cy];Py.copy(this._gravityDirection).multiplyScalar(g),e[Cy]+=t*.05,n.add(Py)}e.velocity.copy(n);const l=e.age/e.life;(s=this.system.inheritVelocity)!=null&&s.enabled&&this.system.inheritVelocity.applyCurrent(e.velocity,l,e[Ap]);const c=this.system.noise;c.enabled&&c.apply(0,e.position,e.velocity,t,e.age,e.life);const h=this.system.sizeBySpeed;h!=null&&h.enabled&&(e.size=h.evaluate(e.velocity,l,e[Ap],e.size));const d=this.system.colorBySpeed;d!=null&&d.enabled&&d.evaluate(e.velocity,e[Ap],e.color);const u=this.system.velocityOverLifetime;u.enabled&&u.apply(e,0,e.position,e.velocity,t,e.age,e.life);const p=this.system.limitVelocityOverLifetime;if(p.enabled&&p.apply(e.position,n,e.velocity,e.size,l,t,1),this.system.worldspace){const g=this.system.worldScale;e.velocity.x*=g.x,e.velocity.y*=g.y,e.velocity.z*=g.z}}}const lS=Symbol("colorLerpFactor"),cS=new he(1,1,1,1),ia=new he(1,1,1,1);class f2 extends tr{constructor(){super(...arguments),a(this,"type","NeedleColor")}initialize(e){}_init(e){const t=this.system.renderer.particleMaterial;ia.copy(this.system.main.startColor.evaluate(Math.random())),t!=null&&t.color&&(cS.copy(t.color),ia.multiply(cS)),ia.convertLinearToSRGB(),e.startColor.set(ia.r,ia.g,ia.b,ia.alpha),e.color.copy(e.startColor),e[lS]=Math.random()}update(e,t){if(e.age===0&&this._init(e),this.system.colorOverLifetime.enabled){const s=e.age/e.life,n=this.system.colorOverLifetime.color.evaluate(s,e[lS]);e.color.set(n.r,n.g,n.b,"alpha"in n?n.alpha:1).multiply(e.startColor)}else e.color.copy(e.startColor)}}class y2{constructor(e){a(this,"system"),a(this,"emission"),a(this,"autoDestroy"),a(this,"startLength"),a(this,"emissionBursts"),a(this,"onlyUsedByOther"),a(this,"behaviors",[]),a(this,"rendererEmitterSettings",{startLength:new wO(220),followLocalOrigin:!1}),a(this,"flatWhiteTexture"),a(this,"clonedTexture",{original:void 0,clone:void 0}),this.system=e,this.emission=new l2(this.system)}get anim(){return this.system.textureSheetAnimation}get prewarm(){return!1}get material(){return this.system.renderer.getMaterial(this.system.trails.enabled)}get layers(){return this.system.gameObject.layers}update(){this.emission.update()}get looping(){return this.system.main.loop}get duration(){return this.system.duration}get shape(){return this.system.shape}get startLife(){return new Tp(this.system.main.startLifetime)}get startSpeed(){return new Tp(this.system.main.startSpeed)}get startRotation(){return new Tp(this.system.main.startRotation)}get startSize(){return new Tp(this.system.main.startSize)}get startColor(){return new bO(new _O(1,1,1,1))}get emissionOverTime(){return this.emission}get emissionOverDistance(){return new c2(this.system)}get instancingGeometry(){return this.system.renderer.getMesh(this.system.renderer.renderMode).geometry}get renderMode(){if(this.system.trails.enabled===!0)return Tn.Trail;switch(this.system.renderer.renderMode){case Zn.Billboard:return Tn.BillBoard;case Zn.Stretch:return Tn.StretchedBillBoard;case Zn.HorizontalBillboard:return Tn.HorizontalBillBoard;case Zn.VerticalBillboard:return Tn.VerticalBillBoard;case Zn.Mesh:return Tn.Mesh}return Tn.BillBoard}get speedFactor(){var e;let t=this.system.main.simulationSpeed;return((e=this.system.renderer)==null?void 0:e.renderMode)===Zn.Stretch&&(t*=this.system.renderer.velocityScale??1),t}get texture(){const e=this.material;if(e&&e.map){const t=e.map;if(this.clonedTexture.original!==t||!this.clonedTexture.clone){const s=t.clone();s.premultiplyAlpha=!1,s.colorSpace=On,this.clonedTexture.original=t,this.clonedTexture.clone=s}return this.clonedTexture.clone}return this.flatWhiteTexture||(this.flatWhiteTexture=vf(new he(1,1,1,1),1)),this.flatWhiteTexture}get startTileIndex(){return new a2(this.system)}get uTileCount(){var e;return this.anim.enabled?(e=this.anim)==null?void 0:e.numTilesX:void 0}get vTileCount(){var e;return this.anim.enabled?(e=this.anim)==null?void 0:e.numTilesY:void 0}get renderOrder(){return 1}get blending(){var e;return((e=this.system.renderer.particleMaterial)==null?void 0:e.blending)??AP}get transparent(){return this.system.renderer.transparent}get worldSpace(){return this.system.main.simulationSpace===ph.World}}class v2{constructor(){a(this,"burstParticleIndex",0),a(this,"burstParticleCount",0),a(this,"isBursting",!1),a(this,"travelDistance",0),a(this,"previousWorldPos"),a(this,"burstIndex",0),a(this,"burstWaveIndex",0),a(this,"time",0),a(this,"waitEmiting",0)}}const Vt=class _m extends I{constructor(){super(...arguments),a(this,"_state"),a(this,"colorOverLifetime"),a(this,"main"),a(this,"emission"),a(this,"sizeOverLifetime"),a(this,"shape"),a(this,"noise"),a(this,"trails"),a(this,"velocityOverLifetime"),a(this,"limitVelocityOverLifetime"),a(this,"inheritVelocity"),a(this,"colorBySpeed"),a(this,"textureSheetAnimation"),a(this,"rotationOverLifetime"),a(this,"rotationBySpeed"),a(this,"sizeBySpeed"),a(this,"_cameraScale",1),a(this,"__worldQuaternion",new H),a(this,"_worldQuaternionInverted",new H),a(this,"_worldScale",new x),a(this,"_worldPositionFrame",-1),a(this,"_worldPos",new x),a(this,"_renderer"),a(this,"_batchSystem"),a(this,"_particleSystem"),a(this,"_interface"),a(this,"_container"),a(this,"_time",0),a(this,"_isPlaying",!0),a(this,"_isUsedAsSubsystem",!1),a(this,"_didPreWarm",!1),a(this,"_bursts"),a(this,"_subEmitterSystems"),a(this,"_lastBatchesCount",-1)}play(e=!1){var t;e&&P.foreachComponent(this.gameObject,s=>{s instanceof _m&&s!==this&&s.play(!1)},!0),this._isPlaying=!0,this._particleSystem&&(this._particleSystem.emissionState.time=0,this._particleSystem.emitEnded=!1),(t=this.emission)==null||t.reset()}pause(e=!0){e&&P.foreachComponent(this.gameObject,t=>{t instanceof _m&&t!==this&&t.pause(!1)},!0),this._isPlaying=!1}stop(e=!0,t=!1){e&&P.foreachComponent(this.gameObject,s=>{s instanceof _m&&s!==this&&s.stop(!1,t)},!0),this._isPlaying=!1,this._time=0,t&&this.reset()}reset(){var e;this._time=0,this._particleSystem&&(this._particleSystem.particleNum=0,this._particleSystem.emissionState.time=0,this._particleSystem.emitEnded=!1,(e=this.emission)==null||e.reset())}emit(e){if(this._particleSystem){this.onUpdate(),e=Math.min(e,this.maxParticles-this.currentParticles),this._state||(this._state=new v2),this._state.waitEmiting=e,this._state.time=0;const t=this._particleSystem.emitEnded;this._particleSystem.emitEnded=!1,this._particleSystem.emit(this.deltaTime,this._state,this._particleSystem.emitter.matrixWorld),this._particleSystem.emitEnded=t}}get playOnAwake(){return this.main.playOnAwake}set playOnAwake(e){this.main.playOnAwake=e}get renderer(){return this._renderer}get isPlaying(){return this._isPlaying}get currentParticles(){var e;return((e=this._particleSystem)==null?void 0:e.particleNum)??0}get maxParticles(){return this.main.maxParticles}get time(){return this._time}get duration(){return this.main.duration}get deltaTime(){return this.context.time.deltaTime*this.main.simulationSpeed}get scale(){return this.gameObject.scale.x}get cameraScale(){return this._cameraScale}get container(){return this._container}get worldspace(){return this.main.simulationSpace===ph.World}get localspace(){return this.main.simulationSpace===ph.Local}get worldQuaternion(){return this.__worldQuaternion}get worldQuaternionInverted(){return this._worldQuaternionInverted}get worldScale(){return this._worldScale}get worldPos(){return this._worldPositionFrame!==this.context.time.frame&&(this._worldPositionFrame=this.context.time.frame,te(this.gameObject,this._worldPos)),this._worldPos}get matrixWorld(){return this._container.matrixWorld}get isSubsystem(){return this._isUsedAsSubsystem}addBehaviour(e){return this._particleSystem?(e instanceof tr&&(e.system=this),er&&console.debug("Add custom ParticleSystem Behaviour",e),this._particleSystem.addBehavior(e),!0):!1}removeBehaviour(e){if(!this._particleSystem)return!1;const t=this._particleSystem.behaviors,s=t.indexOf(e);return s!==-1&&((F()||er)&&console.debug("Remove custom ParticleSystem Behaviour",s,e),t.splice(s,1)),!0}removeAllBehaviours(){return this._particleSystem?(this._particleSystem.behaviors.length=0,!0):!1}get behaviours(){return this._particleSystem?this._particleSystem.behaviors:null}get particleSystem(){return this._particleSystem??null}set bursts(e){for(let t=0;t<e.length;t++){const s=e[t];if(!(s instanceof Mp)){const n=new Mp;Fa(n,s),e[t]=n}}this._bursts=e}set subEmitterSystems(e){for(let t=0;t<e.length;t++){const s=e[t];if(!(s instanceof Ip)){const n=new Ip;Fa(n,s),e[t]=n}}er&&e.length>0&&console.log("SubEmitters: ",e,this),this._subEmitterSystems=e}onAfterDeserialize(e){if(this._subEmitterSystems&&Array.isArray(this._subEmitterSystems))for(const t of this._subEmitterSystems)t._deserialize(this.context,this.gameObject)}awake(){if(this._worldPositionFrame=-1,this._renderer=this.gameObject.getComponent(ls),!this.main)throw new Error("Not Supported: ParticleSystem needs a serialized MainModule. Creating new particle systems at runtime is currently not supported.");this._container=new E,this._container.matrixAutoUpdate=!1,this.context.scene.add(this._container),this._batchSystem=new yO,this._batchSystem.name=this.gameObject.name,this._container.add(this._batchSystem),this._interface=new y2(this),this._particleSystem=new vO(this._interface),this._particleSystem.addBehavior(new p2(this)),this._particleSystem.addBehavior(new f2(this)),this._particleSystem.addBehavior(new h2(this)),this._particleSystem.addBehavior(new d2(this)),this._particleSystem.addBehavior(new g2(this)),this._particleSystem.addBehavior(new m2(this)),this._batchSystem.addSystem(this._particleSystem);const e=this._particleSystem.emitter;this.context.scene.add(e),this.inheritVelocity.system&&this.inheritVelocity.system!==this&&(this.inheritVelocity=this.inheritVelocity.clone()),this.inheritVelocity.awake(this),er&&(console.log(this),this.gameObject.add(new Si(1)))}start(){this.addSubParticleSystems(),this.updateLayers(),this.renderer.particleMesh instanceof q&&this._interface.renderMode==Tn.Mesh&&Xe.assignMeshLOD(this.renderer.particleMesh,0).then(e=>{e&&this.particleSystem&&this._interface.renderMode==Tn.Mesh&&(this.particleSystem.instancingGeometry=e)})}onDestroy(){var e,t,s,n;(e=this._container)==null||e.removeFromParent(),(t=this._batchSystem)==null||t.removeFromParent(),(s=this._particleSystem)==null||s.emitter.removeFromParent(),(n=this._particleSystem)==null||n.dispose()}onEnable(){this.main&&(this.inheritVelocity&&(this.inheritVelocity.system=this),this._batchSystem&&(this._batchSystem.visible=!0),this.playOnAwake&&this.play(),this._isPlaying=this.playOnAwake)}onDisable(){this._batchSystem&&(this._batchSystem.visible=!1)}onBeforeRender(){var e;this.main&&(this._didPreWarm===!1&&((e=this.main)==null?void 0:e.prewarm)===!0&&(this._didPreWarm=!0,this.preWarm()),this.onUpdate(),this.onSimulate(this.deltaTime))}preWarm(){var e;if(!((e=this.emission)!=null&&e.enabled)||this.emission.rateOverTime.getMax()<=0)return;const t=1/60,s=this.main.duration,n=this.main.startLifetime.getMax(),r=Math.min(Math.max(s,n)/Math.max(.01,this.main.simulationSpeed),1e3),l=Math.ceil(r/t),c=Date.now();er&&console.log(`Particles ${this.name} - Prewarm for ${l} frames (${r} sec). Duration: ${s}, Lifetime: ${n}`);for(let h=0;h<l&&!(this.currentParticles>=this.maxParticles);h++){const d=Date.now()-c;if(d>2e3){console.warn(`Particles ${this.name} - Prewarm took too long. Aborting: ${d}`);break}this.onUpdate(),this.onSimulate(t)}}onSimulate(e){if(this._batchSystem){let t=this.context.time.frameCount%60===0;this._lastBatchesCount!==this._batchSystem.batches.length&&(this._lastBatchesCount=this._batchSystem.batches.length,t=!0),t&&this.updateLayers(),this._batchSystem.update(e)}this._time+=e,this._time>this.duration&&(this._time=0)}updateLayers(){if(this._batchSystem)for(let e=0;e<this._batchSystem.batches.length;e++){const t=this._batchSystem.batches[e];t.layers.disableAll();const s=this.layer;t.layers.mask=1<<s}}onUpdate(){var e,t;if(this._bursts&&(this.emission.bursts=this._bursts,delete this._bursts),!this._isPlaying)return;const s=this.context.mainCamera;if(s){const l=Ge(s);this._cameraScale=l.x}const n=!this.worldspace,r=this.gameObject;if(Se(r,this.__worldQuaternion),this._worldQuaternionInverted.copy(this.__worldQuaternion).invert(),Ge(this.gameObject,this._worldScale),n&&this._container&&(e=this.gameObject)!=null&&e.parent){const l=hS(this,Py);this._container.matrix.makeScale(l.x,l.y,l.z),this._container.matrix.makeRotationFromQuaternion(this.__worldQuaternion),this._container.matrix.setPosition(this.worldPos),this._container.matrix.scale(this.gameObject.scale)}this.emission.system=this,this._interface.update(),this.shape.onUpdate(this,this.context,this.main.simulationSpace,this.gameObject),this.noise.update(this.context),(t=this.inheritVelocity)==null||t.update(this.context),this.velocityOverLifetime.update(this)}addSubParticleSystems(){var e;if(this._subEmitterSystems&&this._particleSystem)for(const t of this._subEmitterSystems){t.particleSystem&&(t.particleSystem.__internalAwake?t.particleSystem.__internalAwake():F()&&console.warn("SubParticleSystem serialization issue(?)",t.particleSystem,t));const s=(e=t.particleSystem)==null?void 0:e._particleSystem;if(s){t.particleSystem._isUsedAsSubsystem=!0;const n=new by(this,this._particleSystem,t.particleSystem,s);n.emitterType=t.type,n.emitterProbability=t.emitProbability,this._particleSystem.addBehavior(n)}else er&&console.warn("Could not add SubParticleSystem",t,this)}}};Ve([m(Rp)],Vt.prototype,"colorOverLifetime"),Ve([m(Nt)],Vt.prototype,"main"),Ve([m(eo)],Vt.prototype,"emission"),Ve([m(ta)],Vt.prototype,"sizeOverLifetime"),Ve([m(yy)],Vt.prototype,"shape"),Ve([m(Ce)],Vt.prototype,"noise"),Ve([m(We)],Vt.prototype,"trails"),Ve([m(qe)],Vt.prototype,"velocityOverLifetime"),Ve([m(gt)],Vt.prototype,"limitVelocityOverLifetime"),Ve([m(vy)],Vt.prototype,"inheritVelocity"),Ve([m(xl)],Vt.prototype,"colorBySpeed"),Ve([m(Wt)],Vt.prototype,"textureSheetAnimation"),Ve([m(Es)],Vt.prototype,"rotationOverLifetime"),Ve([m(as)],Vt.prototype,"rotationBySpeed"),Ve([m(vi)],Vt.prototype,"sizeBySpeed");let gh=Vt;class Ip{constructor(){a(this,"particleSystem"),a(this,"emitProbability",1),a(this,"properties"),a(this,"type")}_deserialize(e,t){const s=this.particleSystem;if(s instanceof gh)return;let n="";s&&typeof s.guid=="string"&&(n=s.guid,this.particleSystem=P.findByGuid(n,t)),er&&!(this.particleSystem instanceof gh)&&console.warn("Could not find particle system for sub emitter",n,t,this)}}function hS(o,e){if(e.set(1,1,1),o.gameObject.parent&&o.localspace)switch(o.main.scalingMode){case fy.Local:e=Ge(o.gameObject.parent,e),e.x=1/e.x,e.y=1/e.y,e.z=1/e.z;break;default:if(!o.unsupported_scaling_mode){o.unsupported_scaling_mode=!0;const t="ParticleSystem scale mode "+fy[o.main.scalingMode]+" is not supported";F()&&be(t),console.warn(t,o.name,o)}e=Ge(o.gameObject,e);break}return e}class Fl extends I{constructor(){super(...arguments),a(this,"_didAssignPlayerColor",!1),a(this,"tryAssignColor",()=>{const e=P.getComponentInParent(this.gameObject,Ms);if(e&&e.owner)return this._didAssignPlayerColor=!0,this.assignUserColor(e.owner),!0;const t=P.getComponentInParent(this.gameObject,ci);return t!=null&&t.connectionId?(this._didAssignPlayerColor=!0,this.assignUserColor(t.connectionId),!0):!1})}onEnable(){this.context.connection.beginListen(ie.JoinedRoom,this.tryAssignColor),this._didAssignPlayerColor||this.startCoroutine(this.waitForConnection())}onDisable(){this.context.connection.stopListen(ie.JoinedRoom,this.tryAssignColor)}*waitForConnection(){for(;!this.destroyed&&this.activeAndEnabled&&(yield ff(.2),!this.tryAssignColor()););}assignUserColor(e){const t=Fl.hashCode(e),s=Fl.colorFromHashCode(t);if(this.gameObject.type==="Mesh"){const n=this.gameObject;this.assignColor(s,e,n)}else if(this.gameObject.children)for(const n of this.gameObject.children){const r=n;r.material&&r.material.color&&this.assignColor(s,e,r)}}assignColor(e,t,s){let n=s.material;n&&(n._playerMaterial!==t&&(n=n.clone(),n._playerMaterial=t,s.material=n),n.color=e)}static hashCode(e){var t=0,s,n;if(e.length===0)return t;for(s=0;s<e.length;s++)n=e.charCodeAt(s),t=(t<<5)-t+n,t|=0;return t}static colorFromHashCode(e){const t=(e&16711680)>>16,s=(e&65280)>>8,n=e&255;return new ae(t/255,s/255,n/255)}}const fh=C("debugpost");let Oy=null;function b2(o){Oy=o}function dS(o){let e=o.gameObject;for(;e;){for(const t of lu(e))if(t.isPostProcessingManager===!0)return t;e=e.parent}return null}function _2(o){let e=dS(o);if(!e)if(Oy){fh&&console.warn("Adding postprocessing manager to the scene.");const t=o.scene;e=Ti(t,Oy)}else F()&&console.warn("No post processing manager found");return e}const ft={AT_START:-1e4,NormalPass:0,DepthDownsamplingPass:10,SSAO:20,SMAA:30,TiltShift:40,DepthOfField:50,ChromaticAberration:60,Bloom:70,Vignette:80,Pixelation:90,ToneMapping:100,HueSaturation:110,BrightnessContrast:120,Sharpening:130,AT_END:1e4};let ot=null;function w2(o){fh==="verbose"&&console.debug("Before ordering effects",[...o]),ot||(ot=new Map,ot.set(A.POSTPROCESSING.MODULE.NormalPass,ft.NormalPass),ot.set(A.POSTPROCESSING.MODULE.DepthDownsamplingPass,ft.DepthDownsamplingPass),ot.set(A.POSTPROCESSING.MODULE.SMAAEffect,ft.SMAA),ot.set(A.POSTPROCESSING.MODULE.SSAOEffect,ft.SSAO),ot.set(A.POSTPROCESSING_AO.MODULE.N8AOPostPass,ft.SSAO),ot.set(A.POSTPROCESSING_AO.MODULE.N8AOPass,ft.SSAO),ot.set(A.POSTPROCESSING.MODULE.TiltShiftEffect,ft.TiltShift),ot.set(A.POSTPROCESSING.MODULE.DepthOfFieldEffect,ft.DepthOfField),ot.set(A.POSTPROCESSING.MODULE.ChromaticAberrationEffect,ft.ChromaticAberration),ot.set(A.POSTPROCESSING.MODULE.BloomEffect,ft.Bloom),ot.set(A.POSTPROCESSING.MODULE.SelectiveBloomEffect,ft.Bloom),ot.set(A.POSTPROCESSING.MODULE.VignetteEffect,ft.Vignette),ot.set(A.POSTPROCESSING.MODULE.PixelationEffect,ft.Pixelation),ot.set(A.POSTPROCESSING.MODULE.ToneMappingEffect,ft.ToneMapping),ot.set(A.POSTPROCESSING.MODULE.HueSaturationEffect,ft.HueSaturation),ot.set(A.POSTPROCESSING.MODULE.BrightnessContrastEffect,ft.BrightnessContrast)),o.sort((e,t)=>{const s=typeof e.priority=="number"?e.priority:ot.get(e.effect.constructor)??Number.NEGATIVE_INFINITY,n=typeof t.priority=="number"?t.priority:ot.get(t.effect.constructor)??Number.NEGATIVE_INFINITY;return s===Number.NEGATIVE_INFINITY?(fh&&console.warn("Unknown effect found: ",e.constructor.name,e),1):n===Number.NEGATIVE_INFINITY?(fh&&console.warn("Unknown effect found: ",t.constructor.name,t),-1):s-n}),fh==="verbose"&&console.debug("After ordering effects",[...o])}var x2=Object.defineProperty,S2=Object.getOwnPropertyDescriptor,uS=(o,e,t,s)=>{for(var n=S2(e,t),r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=l(e,t,n)||n);return n&&x2(e,t,n),n};const C2=C("debugpost");class N{constructor(e){a(this,"isVolumeParameter",!0),a(this,"_isInitialized",!1),a(this,"_active",!0),a(this,"_value"),a(this,"_valueRaw"),a(this,"_defaultValue"),a(this,"valueProcessor"),a(this,"onValueChanged"),e!==void 0&&this.initialize(e)}get isInitialized(){return this._isInitialized}initialize(e){e!==void 0&&(this._value=e,this._defaultValue=e,this._valueRaw=e,this._isInitialized=!0)}get overrideState(){return this._active}set overrideState(e){if(this._active===e)return;this._active=e;const t=e?this._valueRaw:this._defaultValue;this.processValue(t,!0)}get value(){return this._valueRaw}set value(e){this.isInitialized||this.initialize(e),this.processValue(e,!1)}set defaultValue(e){this._defaultValue=e}__init(){this.processValue(this._valueRaw,!0)}processValue(e,t){if(e==null||!t&&this.testIfValueChanged(e)===!1)return;const s=this._value;C2&&typeof s=="number"&&typeof e=="number"&&(s?.toFixed(4),e?.toFixed(4)),!this._active&&this._defaultValue!==void 0?(this._value=this._defaultValue,e=this._defaultValue,this._valueRaw=e):(this._valueRaw=e,this._active&&this.valueProcessor&&(e=this.valueProcessor(e)),this._value=e),this.onValueChanged&&this.onValueChanged(e,s,this)}testIfValueChanged(e){return this._valueRaw!==e}}uS([m()],N.prototype,"overrideState"),uS([m()],N.prototype,"value");class P2 extends Ji{constructor(){super([N])}onSerialize(e,t){}onDeserialize(e,t){const s=t.target,n=t.path;let r;if(s&&n&&(r=s[n]),(typeof r!="object"||typeof r=="object"&&r.isVolumeParameter!==!0)&&(r=new N),typeof e=="object"&&"value"in e){const l=e.value;r.initialize(l),r.overrideState=e.overrideState}else r.value=e;return r}}new P2;var O2=Object.defineProperty,k2=(o,e,t,s)=>{for(var n=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=l(e,t,n)||n);return n&&O2(e,t,n),n};const ky=C("debugpost");class rt extends I{constructor(e=void 0){if(super(),a(this,"order"),a(this,"active",!0),a(this,"_manager",null),a(this,"_result"),a(this,"_postprocessingContext",null),e)for(const t of Object.keys(e)){const s=e[t],n=this[t];n instanceof N?n.initialize(s):n!==void 0&&(this[t]=s)}}get isPostProcessingEffect(){return!0}onEnable(){super.onEnable(),ky&&console.warn("Enable",this.constructor.name+(this.__internalDidAwakeAndStart?"":" (awake)")),this.__internalDidAwakeAndStart&&(this.active=!0),this.onEffectEnabled()}onDisable(){var e;super.onDisable(),ky&&console.warn("Disable",this.constructor.name),(e=this._manager)==null||e.removeEffect(this),this.active=!1}onEffectEnabled(e){e&&e.isPostProcessingManager===!0?this._manager=e:this._manager||(this._manager=_2(this)),this._manager.addEffect(this),this._manager.dirty=!0}init(){}get postprocessingContext(){return this._postprocessingContext}apply(e){var t;return this._postprocessingContext=e,this._result||(this.initParameters(),this._result=(t=this.onCreateEffect)==null?void 0:t.call(this)),this._result&&this.initParameters(),this._result}unapply(){}dispose(){ky&&console.warn("DISPOSE",this),this._result&&(Array.isArray(this._result)?this._result.forEach(e=>e.dispose()):this._result.dispose()),this._result=void 0}initParameters(){const e=Object.keys(this);for(const t of e){const s=this[t];s instanceof N&&s.__init()}}onEditorModification(e){const t=e.propertyName;if(this[t]instanceof N){const s=e.value;return this[t].value=s,!0}}}k2([m()],rt.prototype,"active");var M2=Object.defineProperty,R2=(o,e,t,s)=>{for(var n=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=l(e,t,n)||n);return n&&M2(e,t,n),n};const T2=C("debugpost"),My={};function cs(o,e){My[o]=e}function E2(o){return o.__type in My?My[o.__type]:(T2&&o.__type&&console.warn("Unknown postprocessing type",o.__type,o),rt)}class Lp{constructor(){a(this,"components",[])}__init(e){var t;(t=this.components)==null||t.forEach(s=>{s.gameObject===void 0&&e.gameObject.addComponent(s),s.init()})}addEffect(e){this.components.push(e)}removeEffect(e){const t=this.components.indexOf(e);t>=0&&this.components.splice(t,1)}}R2([Ir([o=>E2(o),rt])],Lp.prototype,"components");var A2=Object.defineProperty,I2=(o,e,t,s)=>{for(var n=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=l(e,t,n)||n);return n&&A2(e,t,n),n};class yh extends rt{constructor(){super(...arguments),a(this,"preset",new N(2))}get typeName(){return"Antialiasing"}onCreateEffect(){const e=new A.POSTPROCESSING.MODULE.SMAAEffect({preset:A.POSTPROCESSING.MODULE.SMAAPreset.HIGH,edgeDetectionMode:A.POSTPROCESSING.MODULE.EdgeDetectionMode.LUMA});return this.preset.onValueChanged=t=>{e.applyPreset(t)},e}}I2([m(N)],yh.prototype,"preset"),cs("Antialiasing",yh);var L2=Object.defineProperty,Ry=(o,e,t,s)=>{for(var n=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=l(e,t,n)||n);return n&&L2(e,t,n),n},jp;const Dp=(jp=class extends rt{constructor(){super(...arguments),a(this,"threshold",new N(.9)),a(this,"intensity",new N(1)),a(this,"scatter",new N(.7)),a(this,"selectiveBloom")}get typeName(){return"Bloom"}init(){this.threshold.valueProcessor=o=>o,this.intensity.valueProcessor=o=>o,this.scatter.valueProcessor=o=>o}onCreateEffect(){let o;if(this.selectiveBloom==null&&(this.selectiveBloom=jp.useSelectiveBloom),this.selectiveBloom){const e=o=new A.POSTPROCESSING.MODULE.SelectiveBloomEffect(this.context.scene,this.context.mainCamera,{blendFunction:A.POSTPROCESSING.MODULE.BlendFunction.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,radius:.85,intensity:this.intensity.value});e.inverted=!0}else o=new A.POSTPROCESSING.MODULE.BloomEffect({blendFunction:A.POSTPROCESSING.MODULE.BlendFunction.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,radius:.85,intensity:this.intensity.value}),o.setAttributes(Zv.CONVOLUTION);return this.intensity.onValueChanged=e=>{o.intensity=e},this.threshold.onValueChanged=e=>{o.luminanceMaterial.threshold=Math.pow(e,2.2)},this.scatter.onValueChanged=e=>{o.luminancePass.enabled=!0,o.luminanceMaterial.smoothing=e,o.mipmapBlurPass&&(o.mipmapBlurPass.radius=Cn.lerp(.1,.9,e))},o}},a(jp,"useSelectiveBloom",!1),jp);Ry([m(N)],Dp.prototype,"threshold"),Ry([m(N)],Dp.prototype,"intensity"),Ry([m(N)],Dp.prototype,"scatter");let Bp=Dp;cs("Bloom",Bp);var j2=Object.defineProperty,D2=(o,e,t,s)=>{for(var n=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=l(e,t,n)||n);return n&&j2(e,t,n),n};class vh extends rt{constructor(){super(...arguments),a(this,"intensity",new N(0))}get typeName(){return"ChromaticAberration"}onCreateEffect(){const e=new A.POSTPROCESSING.MODULE.ChromaticAberrationEffect;return e.offset=new le(0,0),e.radialModulation=!0,e.modulationOffset=.15,this.intensity.valueProcessor=t=>t*.02,this.intensity.onValueChanged=t=>{e.offset.x=-t,e.offset.y=t},e}}D2([m(N)],vh.prototype,"intensity"),cs("ChromaticAberration",vh);var bh=(o=>(o[o.None=0]="None",o[o.Neutral=1]="Neutral",o[o.ACES=2]="ACES",o[o.AgX=3]="AgX",o[o.KhronosNeutral=4]="KhronosNeutral",o))(bh||{});const pS=new Map;function Ty(o){switch(o){case 0:return Lm;case 1:return Im;case 2:return fd;case 3:return gd;case 4:return xa;default:return pS.has(o)||(pS.set(o,!0),console.warn("[Postprocessing] Unknown tone mapping mode",o)),xa}}function B2(o){switch(o){case Lm:return 0;case fd:return 2;case gd:return 3;case xa:return 1;case Im:return 1;default:return 0}}function Fp(o){switch(o){case Lm:return A.POSTPROCESSING.MODULE.ToneMappingMode.LINEAR;case fd:return A.POSTPROCESSING.MODULE.ToneMappingMode.ACES_FILMIC;case gd:return A.POSTPROCESSING.MODULE.ToneMappingMode.AGX;case xa:return A.POSTPROCESSING.MODULE.ToneMappingMode.NEUTRAL;case Im:return A.POSTPROCESSING.MODULE.ToneMappingMode.REINHARD;default:return A.POSTPROCESSING.MODULE.ToneMappingMode.LINEAR}}var F2=Object.defineProperty,mS=(o,e,t,s)=>{for(var n=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=l(e,t,n)||n);return n&&F2(e,t,n),n};const Ey=C("debugpost");class ir extends rt{constructor(){super(...arguments),a(this,"mode",new N(void 0)),a(this,"exposure",new N(1)),a(this,"_tonemappingEffect",null)}get typeName(){return"ToneMapping"}setMode(e){const t=bh[e];return t===void 0?(console.error("[PostProcessing] Invalid ToneMapping mode",e),this):(this.mode.value=t,this)}get isToneMapping(){return!0}onEffectEnabled(){const e=dS(this);e&&super.onEffectEnabled(e)}onCreateEffect(){var e;if(this.mode.isInitialized==!1){const n=B2(this.context.renderer.toneMapping);Ey&&console.log("[PostProcessing] Initializing ToneMapping mode to renderer.toneMapping",this.context.renderer.toneMapping+" \u2192 "+n),this.mode.initialize(n)}(e=this._tonemappingEffect)==null||e.dispose();const t=Ty(this.mode.value),s=this._tonemappingEffect=new A.POSTPROCESSING.MODULE.ToneMappingEffect({mode:Fp(t)});return this.mode.onValueChanged=n=>{if(typeof n=="string")n=Ww(n),s.mode=Fp(n);else{const r=Ty(n);s.mode=Fp(r)}s.name="ToneMapping ("+bh[n]+")",Ey&&console.log("[PostProcessing] ToneMapping mode changed to",bh[n],t,s.mode)},Ey&&console.log("[PostProcessing] Use ToneMapping",bh[this.mode.value],t,s.mode,"renderer.tonemapping: "+this.context.renderer.toneMapping),s}onBeforeRender(){var e;if(this._tonemappingEffect&&(e=this.postprocessingContext)!=null&&e.handler.getEffectIsActive(this._tonemappingEffect)&&(this.mode.overrideState&&(this.context.renderer.toneMapping=Ty(this.mode.value)),this.exposure.overrideState&&this.exposure.value!==void 0)){const t=Math.max(.01,this.exposure.value);this.context.renderer.toneMappingExposure=t}}}mS([m(N)],ir.prototype,"mode"),mS([m(N)],ir.prototype,"exposure"),cs("Tonemapping",ir);var U2=Object.defineProperty,Up=(o,e,t,s)=>{for(var n=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=l(e,t,n)||n);return n&&U2(e,t,n),n};class sr extends rt{constructor(){super(...arguments),a(this,"remap",!0),a(this,"postExposure",new N(1)),a(this,"contrast",new N(0)),a(this,"hueShift",new N(0)),a(this,"saturation",new N(0))}get typeName(){return"ColorAdjustments"}init(){this.postExposure.valueProcessor=e=>(this.remap&&(e=Math.pow(2,e)),e),this.contrast.valueProcessor=e=>{if(!this.remap)return e;let t=1;return e>0?t=200:e<0&&(t=100),e/t},this.contrast.defaultValue=0,this.hueShift.valueProcessor=e=>this.remap?Math.PI*e/180:e,this.hueShift.defaultValue=0,this.saturation.valueProcessor=e=>this.remap?e<0?e/100:e/(100*Math.PI):e,this.saturation.defaultValue=0}onCreateEffect(){var e,t;const s=[];let n=(e=this.postprocessingContext)==null?void 0:e.components.find(c=>c instanceof ir);n||(n=new ir,(t=this.postprocessingContext)==null||t.components.push(n)),this.postExposure.onValueChanged=c=>{this.postExposure.overrideState&&n?n.exposure.value=c:console.warn("[PostProcessing] PostExposure is set to override but no ToneMappingEffect found in the postprocessing stack. Please add a ToneMappingEffect to your postprocessing stack to use PostExposure.")};const r=new A.POSTPROCESSING.MODULE.BrightnessContrastEffect;this.contrast.onValueChanged=c=>r.contrast=c;const l=new A.POSTPROCESSING.MODULE.HueSaturationEffect;return this.hueShift.onValueChanged=c=>l.hue=c,this.saturation.onValueChanged=c=>l.saturation=c,s.push(r),s.push(l),s}}Up([m(N)],sr.prototype,"postExposure"),Up([m(N)],sr.prototype,"contrast"),Up([m(N)],sr.prototype,"hueShift"),Up([m(N)],sr.prototype,"saturation"),cs("ColorAdjustments",sr);var z2=Object.defineProperty,sa=(o,e,t,s)=>{for(var n=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=l(e,t,n)||n);return n&&z2(e,t,n),n};const N2=C("debugpost");class As extends rt{constructor(){super(...arguments),a(this,"mode"),a(this,"focusDistance",new N(1)),a(this,"focalLength",new N(.2)),a(this,"aperture",new N(20)),a(this,"gaussianMaxRadius",new N),a(this,"resolutionScale",new N(1/window.devicePixelRatio)),a(this,"bokehScale",new N)}get typeName(){return"DepthOfField"}init(){this.focalLength.valueProcessor=t=>{const s=t/300;return W.lerp(2,.01,s)};const e=20;this.aperture.valueProcessor=t=>{const s=1-t/32;return W.lerp(1,e,s)}}onCreateEffect(){if(this.mode===0){N2&&console.warn("DepthOfField: Mode is set to Off");return}const e=new A.POSTPROCESSING.MODULE.DepthOfFieldEffect(this.context.mainCamera,{worldFocusRange:.2,focalLength:1,bokehScale:20,resolutionScale:this.resolutionScale.value});return this.focusDistance.onValueChanged=t=>{e.cocMaterial.worldFocusDistance=t},this.focalLength.onValueChanged=t=>e.cocMaterial.worldFocusRange=t,this.aperture.onValueChanged=t=>e.bokehScale=t,this.resolutionScale&&(this.resolutionScale.onValueChanged=t=>e.resolution.scale=t),[e]}unapply(){}}sa([m()],As.prototype,"mode"),sa([m(N)],As.prototype,"focusDistance"),sa([m(N)],As.prototype,"focalLength"),sa([m(N)],As.prototype,"aperture"),sa([m(N)],As.prototype,"gaussianMaxRadius"),sa([m(N)],As.prototype,"resolutionScale"),sa([m(N)],As.prototype,"bokehScale"),cs("DepthOfField",As);class _h extends rt{constructor(e){super(),a(this,"effect"),this.effect=e}get typeName(){return this.effect.constructor.name}onCreateEffect(){return this.effect}}var W2=Object.defineProperty,V2=(o,e,t,s)=>{for(var n=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=l(e,t,n)||n);return n&&W2(e,t,n),n};class wh extends rt{constructor(){super(...arguments),a(this,"granularity",new N(10))}get typeName(){return"PixelationEffect"}onCreateEffect(){const e=new A.POSTPROCESSING.MODULE.PixelationEffect;return this.granularity.onValueChanged=t=>{e.granularity=t},e}}V2([m(N)],wh.prototype,"granularity"),cs("PixelationEffect",wh);var H2=Object.defineProperty,xh=(o,e,t,s)=>{for(var n=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=l(e,t,n)||n);return n&&H2(e,t,n),n};class to extends rt{constructor(){super(...arguments),a(this,"intensity",new N(2)),a(this,"falloff",new N(1)),a(this,"samples",new N(9)),a(this,"color",new N(new ae(0,0,0))),a(this,"luminanceInfluence",new N(.7)),a(this,"_ssao")}get typeName(){return"ScreenSpaceAmbientOcclusion"}onBeforeRender(){if(this._ssao&&this.context.mainCamera instanceof we){const e=this.context.mainCamera.far-this.context.mainCamera.near;this._ssao.ssaoMaterial.worldDistanceFalloff=e*.01,this._ssao.ssaoMaterial.worldDistanceThreshold=this.context.mainCamera.far}}onCreateEffect(){const e=this.context.mainCamera,t=new A.POSTPROCESSING.MODULE.NormalPass(this.context.scene,e),s=new A.POSTPROCESSING.MODULE.DepthDownsamplingPass({normalBuffer:t.texture,resolutionScale:.5}),n=this._ssao=new A.POSTPROCESSING.MODULE.SSAOEffect(e,t.texture,{normalDepthBuffer:s.texture,worldDistanceThreshold:1,worldDistanceFalloff:1,worldProximityThreshold:.1,worldProximityFalloff:2,intensity:1,blendFunction:A.POSTPROCESSING.MODULE.BlendFunction.MULTIPLY,luminanceInfluence:.5});this.intensity.onValueChanged=l=>{n.intensity=l},this.falloff.onValueChanged=l=>{n.ssaoMaterial.radius=l*.1},this.samples.onValueChanged=l=>{n.ssaoMaterial.samples=l},this.color.onValueChanged=l=>{n.color||(n.color=new ae),n.color.copy(l)},this.luminanceInfluence.onValueChanged=l=>{n.luminanceInfluence=l};const r=new Array;return r.push(t),r.push(s),r.push(n),r}}xh([m(N)],to.prototype,"intensity"),xh([m(N)],to.prototype,"falloff"),xh([m(N)],to.prototype,"samples"),xh([m(N)],to.prototype,"color"),xh([m(N)],to.prototype,"luminanceInfluence"),cs("ScreenSpaceAmbientOcclusion",to);var $2=Object.defineProperty,na=(o,e,t,s)=>{for(var n=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=l(e,t,n)||n);return n&&$2(e,t,n),n};const G2=C("debugN8AO");var Ay=(o=>(o[o.Performance=0]="Performance",o[o.Low=1]="Low",o[o.Medium=2]="Medium",o[o.High=3]="High",o[o.Ultra=4]="Ultra",o))(Ay||{});class Is extends rt{constructor(){super(...arguments),a(this,"gammaCorrection",!0),a(this,"aoRadius",new N(1)),a(this,"falloff",new N(1)),a(this,"intensity",new N(1)),a(this,"color",new N(new ae(0,0,0))),a(this,"screenspaceRadius",!1),a(this,"quality",2),a(this,"_ssao")}get typeName(){return"ScreenSpaceAmbientOcclusionN8"}get pass(){return this._ssao}onValidate(){this._ssao&&(this._ssao.setQualityMode(Ay[this.quality]),this._ssao.configuration.gammaCorrection=this.gammaCorrection,this._ssao.configuration.screenSpaceRadius=this.screenspaceRadius)}onCreateEffect(){const e=this.context.mainCamera,t=this.context.domWidth,s=this.context.domHeight,n=this._ssao=new A.POSTPROCESSING_AO.MODULE.N8AOPostPass(this.context.scene,e,t,s);n.name="SSAO N8";const r=Ay[this.quality];n.setQualityMode(r),n.configuration.transparencyAware=!1;const l=new Hs(t,s);return n.configuration.beautyRenderTarget=l,n.configuration.autoRenderBeauty=!1,n.configuration.gammaCorrection=this.gammaCorrection,n.configuration.screenSpaceRadius=this.screenspaceRadius,G2&&(n.enableDebugMode(),console.log(n),setInterval(()=>{console.log("SSAO",n.lastTime)},1e3),setInterval(()=>{console.log("SSAO",n.enabled,{ssao:n,autoRenderBeauty:n.configuration.autoRenderBeauty})},4e3)),this.intensity.onValueChanged=c=>{n.configuration.intensity=c},this.falloff.onValueChanged=c=>{n.configuration.distanceFalloff=c},this.aoRadius.onValueChanged=c=>{n.configuration.aoRadius=c},this.color.onValueChanged=c=>{n.color||(n.color=new ae),n.configuration.color.copy(c)},n}}na([Rt(),m()],Is.prototype,"gammaCorrection"),na([m(N)],Is.prototype,"aoRadius"),na([m(N)],Is.prototype,"falloff"),na([m(N)],Is.prototype,"intensity"),na([m(N)],Is.prototype,"color"),na([Rt(),m()],Is.prototype,"screenspaceRadius"),na([Rt(),m()],Is.prototype,"quality"),cs("ScreenSpaceAmbientOcclusionN8",Is);var q2=Object.defineProperty,X2=Object.getOwnPropertyDescriptor,gS=(o,e,t,s)=>{for(var n=X2(e,t),r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=l(e,t,n)||n);return n&&q2(e,t,n),n};class Sh extends rt{constructor(){super(...arguments),a(this,"order",ft.Sharpening),a(this,"_effect"),a(this,"_amount",1),a(this,"_radius",1)}get typeName(){return"Sharpening"}onCreateEffect(){return this._effect??(this._effect=new(Q2())),this.effect}get effect(){return this._effect}set amount(e){this._amount=e,this._effect&&(this._effect.uniforms.get("amount").value=e)}get amount(){return this._effect?this._effect.uniforms.get("amount").value:this._amount}set radius(e){this._radius=e,this._effect&&(this._effect.uniforms.get("radius").value=e)}get radius(){return this._effect?this._effect.uniforms.get("radius").value:this._radius}}gS([m()],Sh.prototype,"amount"),gS([m()],Sh.prototype,"radius");function Q2(){const o=`
1246
+ void mainSupport() {
1247
+ vUv = uv;
1248
+ gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
1249
+ }
1250
+ `,e=`
1251
+ uniform sampler2D tDiffuse;
1252
+ uniform float amount;
1253
+ uniform float radius;
1254
+
1255
+ void mainImage(const in vec4 inputColor, const in vec2 uv, out vec4 outputColor) {
1256
+ float tx = 1.0 / resolution.x;
1257
+ float ty = 1.0 / resolution.y;
1258
+ vec2 texelSize = vec2(tx, ty);
1259
+
1260
+ vec4 blurred = vec4(0.0);
1261
+ float total = 0.0;
1262
+
1263
+ for (float x = -radius; x <= radius; x++) {
1264
+ for (float y = -radius; y <= radius; y++) {
1265
+ vec2 offset = vec2(x, y) * texelSize;
1266
+ vec4 diffuse = texture2D(tDiffuse, uv + offset);
1267
+ float weight = exp(-length(offset) * amount);
1268
+ blurred += diffuse * weight;
1269
+ total += weight;
1270
+ }
1271
+ }
1272
+
1273
+ if (total > 0.0) {
1274
+ blurred /= total;
1275
+ }
1276
+
1277
+ // Calculate the sharpened color using inputColor
1278
+ vec4 sharp = inputColor + clamp(inputColor - blurred, 0.0, 1.0) * amount;
1279
+ // Keep original alpha
1280
+ sharp.a = inputColor.a;
1281
+
1282
+ // Ensure the sharp color does not go below 0 or above 1
1283
+ // This means: sharpening must happen AFTER tonemapping.
1284
+ sharp = clamp(sharp, 0.0, 1.0);
1285
+
1286
+ outputColor = sharp;
1287
+ }
1288
+
1289
+ `;class t extends A.POSTPROCESSING.MODULE.Effect{constructor(){super("Sharpening",e,{vertexShader:o,blendFunction:A.POSTPROCESSING.MODULE.BlendFunction.NORMAL,uniforms:new Map([["amount",new Xi(1)],["radius",new Xi(1)]]),attributes:Zv.CONVOLUTION})}}return t}var Y2=Object.defineProperty,Cl=(o,e,t,s)=>{for(var n=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=l(e,t,n)||n);return n&&Y2(e,t,n),n};class yn extends rt{constructor(){super(...arguments),a(this,"offset",new N(0)),a(this,"rotation",new N(0)),a(this,"focusArea",new N(.4)),a(this,"feather",new N(.3)),a(this,"kernelSize",new N(2)),a(this,"resolutionScale",new N(1/window.devicePixelRatio))}get typeName(){return"TiltShiftEffect"}init(){this.offset.defaultValue=0,this.rotation.defaultValue=0,this.focusArea.defaultValue=.4,this.feather.defaultValue=.3,this.kernelSize.defaultValue=A.POSTPROCESSING.MODULE.KernelSize.MEDIUM,this.resolutionScale.defaultValue=1/window.devicePixelRatio}onCreateEffect(){const e=new A.POSTPROCESSING.MODULE.TiltShiftEffect({kernelSize:A.POSTPROCESSING.MODULE.KernelSize.VERY_LARGE,offset:this.offset.value,rotation:this.rotation.value,focusArea:this.focusArea.value,feather:this.feather.value});return this.offset.onValueChanged=t=>e.offset=t,this.rotation.onValueChanged=t=>e.rotation=t,this.focusArea.onValueChanged=t=>e.focusArea=t,this.feather.onValueChanged=t=>e.feather=t,this.kernelSize.onValueChanged=t=>e.blurPass.kernelSize=t,this.resolutionScale.onValueChanged=t=>e.resolution.scale=t/window.devicePixelRatio,e}}Cl([m(N)],yn.prototype,"offset"),Cl([m(N)],yn.prototype,"rotation"),Cl([m(N)],yn.prototype,"focusArea"),Cl([m(N)],yn.prototype,"feather"),Cl([m(N)],yn.prototype,"kernelSize"),Cl([m(N)],yn.prototype,"resolutionScale"),cs("TiltShiftEffect",yn);var K2=Object.defineProperty,Iy=(o,e,t,s)=>{for(var n=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=l(e,t,n)||n);return n&&K2(e,t,n),n};class oa extends rt{constructor(){super(...arguments),a(this,"color",new N({r:0,g:0,b:0,a:1})),a(this,"intensity",new N(0)),a(this,"center",new N({x:.5,y:.5}))}get typeName(){return"Vignette"}init(){this.color.defaultValue={r:0,g:0,b:0,a:1},this.intensity.defaultValue=0,this.center.defaultValue={x:.5,y:.5}}onCreateEffect(){const e=new A.POSTPROCESSING.MODULE.VignetteEffect;return this.intensity.onValueChanged=t=>{e.offset=t,this.updateDarkness(e)},this.color.onValueChanged=t=>{this.updateDarkness(e)},e}updateDarkness(e){const t=this.intensity.value;e.darkness=t}}Iy([m(N)],oa.prototype,"color"),Iy([m(N)],oa.prototype,"intensity"),Iy([m(N)],oa.prototype,"center"),cs("Vignette",oa),globalThis.NEEDLE_USE_POSTPROCESSING=globalThis.NEEDLE_USE_POSTPROCESSING!==void 0?globalThis.NEEDLE_USE_POSTPROCESSING:!0;const io=C("debugpost"),Ly=Symbol("needle:postprocessing-handler"),Ch=Symbol("needle:previous-autoclear-state"),Ph=Symbol("needle:previous-tone-mapping");class jy{constructor(e){a(this,"_composer",null),a(this,"_lastVolumeComponents"),a(this,"_effects",[]),a(this,"_isActive",!1),a(this,"context"),a(this,"_anyPassHasDepth",!1),a(this,"_anyPassHasNormal",!1),a(this,"_hasSmaaEffect",!1),a(this,"_customInputBuffer",null),a(this,"_customInputBufferId",0),a(this,"_multisampling",0),a(this,"_menuEntry",null),a(this,"_passIndices",null),this.context=e}getEffectIsActive(e){return e?this._isActive&&this._effects.some(t=>t.effect===e):!1}get isActive(){return this._isActive}get composer(){return this._composer}apply(e){return this._isActive=!0,this.onApply(this.context,e)}unapply(e=!0){var t,s;if(io&&console.log("Unapplying postprocessing effects"),this._isActive=!1,this._lastVolumeComponents){for(const r of this._lastVolumeComponents)r.unapply();this._lastVolumeComponents.length=0}const n=this.context;n[Ly]===this&&(delete n[Ly],typeof n.renderer[Ch]=="boolean"&&(n.renderer.autoClear=n.renderer[Ch]),typeof n.renderer[Ph]=="number"&&(n.renderer.toneMapping=n.renderer[Ph])),(t=this._composer)==null||t.removeAllPasses(),e&&((s=this._composer)==null||s.dispose()),n.composer===this._composer&&(n.composer=null)}dispose(){this.unapply(!0);for(const e of this._effects)e.effect.dispose();this._effects.length=0,this._composer=null}async onApply(e,t){if(!t)return;await Promise.all([A.POSTPROCESSING.load(),A.POSTPROCESSING_AO.load()]),e[Ly]=this,io&&console.log("Apply Postprocessing Effects",t),this._lastVolumeComponents=[...t],this._effects.length=0;const s={handler:this,components:this._lastVolumeComponents};for(let n=0;n<this._lastVolumeComponents.length;n++){const r=this._lastVolumeComponents[n];if(r.context=e,r.apply){if(r.active){if(!e.mainCameraComponent){console.error("No camera in scene found or available yet - can not create postprocessing effects");return}const l=r.apply(s);if(!l)continue;if(Array.isArray(l))for(const c of l)this._effects.push({effect:c,priority:r.order});else this._effects.push({effect:l,priority:r.order})}}else r.active&&be("Volume component is not a VolumeComponent: "+r.__type)}this.applyEffects(e)}get anyPassHasDepth(){return this._anyPassHasDepth}get anyPassHasNormal(){return this._anyPassHasNormal}get hasSmaaEffect(){return this._hasSmaaEffect}set multisampling(e){this._multisampling=e}get multisampling(){return this._multisampling}applyEffects(e){var t;if(this._anyPassHasDepth=!1,this._anyPassHasNormal=!1,this._hasSmaaEffect=!1,this._effects.length<=0)return;const s=e.mainCameraComponent,n=e.renderer,r=e.scene,l=s.threeCamera;if(typeof n[Ch]=="boolean"&&(n.autoClear=n[Ch]),n[Ch]=n.autoClear,typeof n[Ph]=="number"&&(n.toneMapping=n[Ph]),n[Ph]=n.toneMapping,n.toneMapping!=yd&&!this._effects.find(u=>u instanceof A.POSTPROCESSING.MODULE.ToneMappingEffect)){const u=new A.POSTPROCESSING.MODULE.ToneMappingEffect;u.name=`ToneMapping (${n.toneMapping})`,u.mode=Fp(n.toneMapping),this._effects.push({effect:u,priority:ft.ToneMapping})}this._composer||(this._composer=new A.POSTPROCESSING.MODULE.EffectComposer(n,{frameBufferType:jm,stencilBuffer:!0})),e.composer&&e.composer!==this._composer&&console.warn("There's already an active EffectComposer in your scene: replacing it with a new one. This might cause unexpected behaviour. Make sure to only use one PostprocessingManager/Volume in your scene."),e.composer=this._composer;const c=e.composer;c.setMainCamera(l),c.setRenderer(n),c.setMainScene(r),c.autoRenderToScreen=!0,c.multisampling=0;for(const u of c.passes)u.dispose();c.removeAllPasses();const h=new A.POSTPROCESSING.MODULE.RenderPass(r,l);h.name="RenderPass",h.mainScene=r,c.addPass(h);const d=h.render;(t=this._customInputBuffer)==null||t.dispose(),this._customInputBuffer=null,h.render=(u,p,g,f,y)=>{var b;p&&(p.samples=0,g&&(g.samples=0),(!this._customInputBuffer||this._customInputBuffer.width!==p.width||this._customInputBuffer.height!==p.height||this._customInputBuffer.samples!==this._multisampling||this._customInputBuffer.texture.format!==p.texture.format||this._customInputBuffer.texture.type!==jm)&&((b=this._customInputBuffer)==null||b.dispose(),this._customInputBuffer=new Hs(p.width,p.height,{format:p.texture.format,type:jm,depthBuffer:p.depthBuffer,depthTexture:p.depthTexture?new Rv(p.width,p.height):void 0,stencilBuffer:p.stencilBuffer,samples:Math.max(0,this._multisampling),minFilter:p.texture.minFilter??_d,magFilter:p.texture.magFilter??_d,generateMipmaps:p.texture.generateMipmaps}),this._customInputBufferId++,this._customInputBuffer.texture.name=`CustomInputBuffer-${this._customInputBufferId}`,this._customInputBuffer.depthTexture&&p.depthTexture&&(this._customInputBuffer.depthTexture.format=p.depthTexture.format,this._customInputBuffer.depthTexture.type=p.depthTexture.type),this._customInputBuffer.samples>0&&(this._customInputBuffer.ignoreDepthForMultisampleCopy=!1),io&&console.warn(`[PostProcessing] Input buffer created with size ${this._customInputBuffer.width}x${this._customInputBuffer.height} and samples ${this._customInputBuffer.samples}`)),d.call(h,u,this._customInputBuffer,g,f,y),Kl.blit(this._customInputBuffer.texture,p,{renderer:u,depthTexture:this._customInputBuffer.depthTexture,depthWrite:!0,depthTest:!0}))};try{w2(this._effects);let u=!1,p=null;for(let y=this._effects.length-1;y>=0;y--){const b=this._effects[y].effect;if(b instanceof A.POSTPROCESSING.MODULE.ToneMappingEffect){if(u){io&&console.warn(`[PostProcessing] Found multiple tonemapping effects in the scene: ${b.name} and ${p?.name}. Only the last one added will be used.`),this._effects.splice(y,1);continue}p=b,u=!0}}const g=[];let f=!1;for(const y of this._effects){const b=y.effect;if(b instanceof A.POSTPROCESSING.MODULE.SMAAEffect?this._hasSmaaEffect=!0:b instanceof A.POSTPROCESSING.MODULE.NormalPass&&(this._anyPassHasNormal=!0),!(b instanceof A.POSTPROCESSING.MODULE.ToneMappingEffect&&p!==b))if(b instanceof A.POSTPROCESSING.MODULE.Effect){const v=b.getAttributes(),_=A.POSTPROCESSING.MODULE.EffectAttribute.CONVOLUTION;v&_&&(io&&console.log("[PostProcessing] Convolution effect: "+b.name),f&&(io&&console.log("[PostProcessing] Merging effects with convolution",g.map(w=>w.name).join(", ")),this.createPassForMergeableEffects(g,c,l,r)),f=!0),g.push(b)}else b instanceof A.POSTPROCESSING.MODULE.Pass?(f=!1,this.createPassForMergeableEffects(g,c,l,r),b.renderToScreen=!1,c.addPass(b)):(f=!1,this.createPassForMergeableEffects(g,c,l,r),c.addPass(b))}this.createPassForMergeableEffects(g,c,l,r)}catch(u){console.error("Error while applying postprocessing effects",u),c.removeAllPasses()}for(let u=0;u<c.passes.length;u++){const p=c.passes[u],g=u===c.passes.length-1;p?.configuration!==void 0?p.configuration.gammaCorrection=g:"autosetGamma"in p&&(p.autosetGamma=g),this._anyPassHasDepth||(this._anyPassHasDepth=p.needsDepthTexture)}io&&console.log("[PostProcessing] Passes \u2192",[...c.passes],`
1290
+ ---------------------------------
1291
+ \u2022 `+c.passes.map(u=>u.name).join(`
1292
+ \u2022 `)+`
1293
+ `),io&&this._onCreateEffectsDebug(this._composer,l)}createPassForMergeableEffects(e,t,s,n){if(e.length>0){const r=new A.POSTPROCESSING.MODULE.EffectPass(s,...e);r.name=e.map(l=>l.name).join(", "),r.mainScene=n,r.enabled=!0,r.renderToScreen=!1,t.addPass(r),e.length=0}}_onCreateEffectsDebug(e,t){if(io==="passes"){const s=new A.POSTPROCESSING.MODULE.DepthEffect({blendFunction:A.POSTPROCESSING.MODULE.BlendFunction.NORMAL,inverted:!0});s.name="Depth Effect";const n=new A.POSTPROCESSING.MODULE.EffectPass(t,s);if(n.name="Depth Effect Pass",n.enabled=!1,e.passes.push(n),this._passIndices!==null){const l=[e.passes[0]];this._passIndices.length>0&&l.push(...this._passIndices.filter(c=>c!==0).map(c=>e.passes[c]).filter(c=>c)),l.length>0&&console.log("[PostProcessing] Passes (selected) \u2192",l),e.passes.length=0;for(const c of l)c.enabled=!0,c.renderToScreen=!1,e.addPass(c)}const r=this.context.menu;if(r&&this._passIndices===null){this._menuEntry&&this._menuEntry.remove();const l=document.createElement("select");l.multiple=!0;const c=document.createElement("option");c.innerText="Final Output",c.value="-1",l.appendChild(c);for(const h of e.passes){const d=document.createElement("option");d.innerText=h.name,d.value=`${e.passes.indexOf(h)}`,d.title=h.name,l.appendChild(d)}r.appendChild(l),this._menuEntry=l,l.addEventListener("change",()=>{const h=Array.from(l.selectedOptions).map(d=>parseInt(d.value));h.length===1&&h[0]===-1?this._passIndices=null:this._passIndices=h,this.applyEffects(this.context)})}}}}var Z2=Object.defineProperty,fS=(o,e,t,s)=>{for(var n=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=l(e,t,n)||n);return n&&Z2(e,t,n),n};const ra=C("debugpost");class Pl extends I{constructor(){super(...arguments),a(this,"sharedProfile"),a(this,"multisampling","auto"),a(this,"_postprocessing"),a(this,"_activeEffects",[]),a(this,"_effects",[]),a(this,"_componentEnabledTime",-1),a(this,"_multisampleAutoChangeTime",0),a(this,"_multisampleAutoDecreaseTime",0),a(this,"_lastApplyTime"),a(this,"_rapidApplyCount",0),a(this,"_isDirty",!1),a(this,"_modificationQueue"),a(this,"_recreateId",-1)}get isPostProcessingManager(){return!0}get effects(){return this._activeEffects}get dirty(){return this._isDirty}set dirty(e){this._isDirty=e}addEffect(e){let t=e;return t instanceof rt||(t=new _h(t)),t.gameObject===void 0&&this.gameObject.addComponent(t),this._effects.includes(t)||(this._effects.push(t),this._isDirty=!0),e}removeEffect(e){var t,s,n,r;let l=-1;if(e instanceof rt?l=this._effects.indexOf(e):l=this._effects.findIndex(c=>c instanceof _h&&c.effect===e),l!==-1)return this._effects.splice(l,1),this._isDirty=!0,e;if(e instanceof rt){const c=(s=(t=this.sharedProfile)==null?void 0:t.components)==null?void 0:s.indexOf(e);c!==void 0&&c!==-1&&(this._isDirty=!0,(r=(n=this.sharedProfile)==null?void 0:n.components)==null||r.splice(c,1))}return e}markDirty(){this._isDirty=!0}awake(){var e;ra&&(console.log("PostprocessingManager Awake",this),console.log("Press P to toggle post processing"),window.addEventListener("keydown",t=>{t.key==="p"&&(this.enabled=!this.enabled,Be("Toggle PostProcessing "+this.name+": Enabled="+this.enabled),this.markDirty())})),(e=this.sharedProfile)==null||e.__init(this)}onEnable(){this._componentEnabledTime=this.context.time.realtimeSinceStartup,this._isDirty=!0}onDisable(){var e;(e=this._postprocessing)==null||e.unapply(),this._isDirty=!1}onBeforeRender(){if(!this.context.isInXR&&(this.context.mainCamera&&this._isDirty&&this.apply(),this.context.composer&&this._postprocessing&&this._postprocessing.composer===this.context.composer)){if(this.context.renderer.getContext().isContextLost()&&this.context.renderer.forceContextRestore(),this.context.composer.getRenderer()!==this.context.renderer&&this.context.composer.setRenderer(this.context.renderer),this.context.composer.setMainScene(this.context.scene),this.multisampling==="auto")if(this._postprocessing&&this._postprocessing.hasSmaaEffect)this._postprocessing.multisampling!==0&&(this._postprocessing.multisampling=0,(ra||F())&&console.warn("[PostProcessing] Disabling multisampling you're using SMAA and have set the 'multisampling: auto' on your PostprocessingManager/Volume component. If you need anti-aliasing, consider adding an Antialiasing component or SMAA effect to the PostprocessingManager."));else{const e=this.context.time.realtimeSinceStartup-this._multisampleAutoChangeTime;if(this.context.time.realtimeSinceStartup-this._componentEnabledTime>2&&e>.5){const t=this._postprocessing.multisampling;if(this._postprocessing.multisampling>0&&this.context.time.smoothedFps<=50){this._multisampleAutoChangeTime=this.context.time.realtimeSinceStartup,this._multisampleAutoDecreaseTime=this.context.time.realtimeSinceStartup;let s=this._postprocessing.multisampling*.5;s=Math.floor(s),s!=this._postprocessing.multisampling&&(this._postprocessing.multisampling=s),ra&&console.debug(`[PostProcessing] Reduced multisampling from ${t} to ${this._postprocessing.multisampling}`)}else if(e>1&&this.context.time.smoothedFps>=59&&this._postprocessing.multisampling<this.context.renderer.capabilities.maxSamples&&this.context.time.realtimeSinceStartup-this._multisampleAutoDecreaseTime>10){this._multisampleAutoChangeTime=this.context.time.realtimeSinceStartup;let s=this._postprocessing.multisampling<=0?1:this._postprocessing.multisampling*2;s=Math.floor(s),s!==this._postprocessing.multisampling&&(this._postprocessing.multisampling=s),ra&&console.debug(`[PostProcessing] Increased multisampling from ${t} to ${this._postprocessing.multisampling}`)}}}else{const e=Math.max(0,Math.min(this.multisampling,this.context.renderer.capabilities.maxSamples));e!==this._postprocessing.multisampling&&(this._postprocessing.multisampling=e)}if(this.context.mainCamera){const e=this.context.composer.passes;for(const t of e)if(t.mainCamera&&t.mainCamera!==this.context.mainCamera){this.context.composer.setMainCamera(this.context.mainCamera);break}}}}onDestroy(){var e;(e=this._postprocessing)==null||e.dispose()}apply(){var e,t,s;if(ra&&console.log(`Apply PostProcessing "${this.name||"unnamed"}"`),F()&&(this._lastApplyTime!==void 0&&Date.now()-this._lastApplyTime<100&&(this._rapidApplyCount++,this._rapidApplyCount===5&&console.warn("Detected rapid post processing modifications - this might be a bug",this)),this._lastApplyTime=Date.now()),this._isDirty=!1,this._activeEffects.length=0,(e=this.sharedProfile)!=null&&e.components){const n=this.sharedProfile.components;for(const r of n)r.active&&r.enabled&&!this._activeEffects.includes(r)&&this._activeEffects.push(r)}for(const n of this._effects)n.active&&n.enabled&&!this._activeEffects.includes(n)&&this._activeEffects.push(n);this._activeEffects.length>0?(this._postprocessing||(this._postprocessing=new jy(this.context)),(t=this._postprocessing.apply(this._activeEffects))==null||t.then(()=>{this.activeAndEnabled&&(this._applyPostQueue(),this._postprocessing?(this.multisampling==="auto"?this._postprocessing.multisampling=Y.isMobileDevice()?2:4:this._postprocessing.multisampling=Math.max(0,Math.min(this.multisampling,this.context.renderer.capabilities.maxSamples)),ra&&console.debug(`[PostProcessing] Set multisampling to ${this._postprocessing.multisampling} (Is Mobile: ${Y.isMobileDevice()})`)):ra&&console.warn("[PostProcessing] No composer found"))})):(s=this._postprocessing)==null||s.unapply(!1)}_applyPostQueue(){if(this._modificationQueue){for(const e of this._modificationQueue.values())this.onEditorModification(e);this._modificationQueue.clear()}}onEditorModification(e){var t,s;if(e.propertyName.startsWith("postprocessing.")){if(!this._postprocessing)return this._modificationQueue||(this._modificationQueue=new Map),this._modificationQueue.set(e.propertyName,e),!0;if(!((t=this._activeEffects)!=null&&t.length))return;const n=e.propertyName.split(".");if(n.length===3||n.length===4){const r=n[1],l=n[2];for(const c of this._activeEffects)if(((s=c.typeName)==null?void 0:s.toLowerCase())===r.toLowerCase()){if(l==="active"){c.active=e.value,this.scheduleRecreate();return}if(!zp.has(r)){const h=new Array;zp.set(r,h);const d=Object.keys(c);for(const u of d)c[u]instanceof N&&h.push(u)}if(zp.has(r)){const h=l.toLowerCase(),d=zp.get(r);for(const u of d)if(u.toLowerCase()===h){const p=c[u];p instanceof N&&(n.length===4&&n[3]==="active"?(p.overrideState=e.value,this.scheduleRecreate()):p&&p.value!==void 0&&(p.value=e.value));return}}console.warn("Unknown modification",l);return}}return!0}return!1}scheduleRecreate(){const e=++this._recreateId;setTimeout(()=>{e===this._recreateId&&(this.onDisable(),this.onEnable())},200)}}fS([Ir(Lp)],Pl.prototype,"sharedProfile"),fS([Ir()],Pl.prototype,"multisampling");const zp=new Map;b2(Pl);async function Dy(o){const{NeedleEngineWebComponent:e}=await Promise.resolve().then(()=>kL);e.observedAttributes.includes(o)||e.observedAttributes.push(o)}var J2=Object.defineProperty,Ct=(o,e,t,s)=>{for(var n=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=l(e,t,n)||n);return n&&J2(e,t,n),n};const Ht=C("debugsceneswitcher"),eI=C("sceneswitcher:clearscene"),Np="scene";Dy(Np);const nr=Promise.resolve(!1);class Ze extends I{constructor(){super(...arguments),a(this,"autoLoadFirstScene",!0),a(this,"scenes",[]),a(this,"loadingScene"),a(this,"queryParameterName","scene"),a(this,"useSceneName",!0),a(this,"clamp",!0),a(this,"useHistory",!0),a(this,"useKeyboard",!0),a(this,"useSwipe",!0),a(this,"useSceneLighting",!0),a(this,"useSceneBackground",!0),a(this,"preloadNext",1),a(this,"preloadPrevious",1),a(this,"preloadConcurrent",2),a(this,"createMenuButtons",!1),a(this,"sceneLoadingStart",new xe),a(this,"sceneLoadingProgress",new xe),a(this,"sceneLoaded",new xe),a(this,"_currentIndex",-1),a(this,"_currentScene"),a(this,"_engineElementOverserver"),a(this,"_preloadScheduler"),a(this,"_menuButtons"),a(this,"onPopState",async e=>{if(!this.useHistory)return;const t=this.useHistory;try{this.useHistory=!1;let s=!1;if(this.queryParameterName&&(s=await this.tryLoadFromQueryParam()),!s){const n=e?.state;if(n&&n.startsWith(this.guid)){const r=n.substr(this.guid.length+2);Ht&&console.log("PopState",r),await this.trySelectSceneFromValue(r)}}}finally{this.useHistory=t}}),a(this,"normalizedSwipeThresholdX",.1),a(this,"_didSwipe",!1),a(this,"onInputPointerMove",e=>{if(this.useSwipe&&!this._didSwipe&&e.button===0&&e.pointerType==="touch"&&this.context.input.getPointerPressedCount()===1){const t=this.context.input.getPointerPositionDelta(e.button);if(t){const s=t.x/this.context.domWidth;s>=this.normalizedSwipeThresholdX?(this._didSwipe=!0,this.selectPrev()):s<=-this.normalizedSwipeThresholdX&&(this._didSwipe=!0,this.selectNext())}}}),a(this,"onInputPointerUp",e=>{e.button===0&&(this._didSwipe=!1)}),a(this,"onInputKeyDown",e=>{if(!this.useKeyboard||!this.scenes)return;const t=e.key.toLowerCase();if(!t)return;const s=parseInt(t)-1;if(s>=0){this.trySelectSceneFromValue(s);return}switch(t){case"arrowright":case"d":this.selectNext();break;case"arrowleft":case"a":this.selectPrev();break}}),a(this,"__lastSwitchScene"),a(this,"__lastSwitchScenePromise"),a(this,"_currentlyLoadingScene"),a(this,"_lastLoadingScene"),a(this,"_loadingScenePromise"),a(this,"_isCurrentlyLoading",!1),a(this,"_currentLoadingProgress")}get currentIndex(){return this._currentIndex}get currentLoadingProgress(){return this._currentLoadingProgress}get currentlyLoadingScene(){return this._currentlyLoadingScene}get currentlyLoadedScene(){return this._currentScene}awake(){this.scenes===void 0&&(this.scenes=[]);for(const e of this.scenes)e&&!e.hasUrl&&e.asset instanceof E?P.remove(e.asset):e instanceof E&&P.remove(e);Ht&&console.log("SceneSwitcher",this)}async onEnable(){if(globalThis.addEventListener("popstate",this.onPopState),this.context.input.addEventListener(Fe.KeyDown,this.onInputKeyDown),this.context.input.addEventListener(Fe.PointerMove,this.onInputPointerMove),this.context.input.addEventListener(Fe.PointerUp,this.onInputPointerUp),this._engineElementOverserver||(this._engineElementOverserver=new MutationObserver(e=>{for(const t of e)if(t.type==="attributes"&&t.attributeName===Np){const s=this.context.domElement.getAttribute(Np);s!==null&&this.trySelectSceneFromValue(s)}})),this._engineElementOverserver.observe(this.context.domElement,{attributes:!0}),this._preloadScheduler||(this._preloadScheduler=new tI(this)),this._preloadScheduler.maxLoadAhead=this.preloadNext,this._preloadScheduler.maxLoadBehind=this.preloadPrevious,this._preloadScheduler.maxConcurrent=this.preloadConcurrent,this._preloadScheduler.begin(2e3),this.autoLoadFirstScene&&this._currentIndex===-1&&!await this.tryLoadFromQueryParam()){const e=this.context.domElement.getAttribute(Np);try{(e===null||!await this.trySelectSceneFromValue(e))&&this._currentIndex===-1&&this.select(0)}finally{}}this.createMenuButtons&&(this._menuButtons??(this._menuButtons=[]),this._menuButtons.push(this.context.menu.appendChild({label:"Previous",icon:"arrow_back_ios",onClick:()=>this.selectPrev(),priority:-1005,class:"row2"})),this._menuButtons.push(this.context.menu.appendChild({label:"Next",icon:"arrow_forward_ios",iconSide:"right",onClick:()=>this.selectNext(),priority:-1e3,class:"row2"})))}onDisable(){var e;if(globalThis.removeEventListener("popstate",this.onPopState),this.context.input.removeEventListener(Fe.KeyDown,this.onInputKeyDown),this.context.input.removeEventListener(Fe.PointerMove,this.onInputPointerMove),this.context.input.removeEventListener(Fe.PointerUp,this.onInputPointerUp),(e=this._preloadScheduler)==null||e.stop(),this._menuButtons){for(const t of this._menuButtons)t.remove();this._menuButtons=void 0}}addScene(e){if(typeof e=="string"){let t=this.context.addressables.findAssetReference(e);return t||(t=new ce(e),this.context.addressables.registerAssetReference(t)),this.scenes.push(t),t}return this.scenes.push(e),e}selectNext(){return this.select(this._currentIndex+1)}selectPrev(){return this.select(this._currentIndex-1)}select(e){var t,s,n;if(Ht&&console.log("select",e),typeof e=="object"&&console.warn('Switching to "'+e+'" might not work. Please either use an index or a AssetReference (not a scene reference)'),typeof e=="string"){const l=(t=this.scenes)==null?void 0:t.find(c=>c.url===e);if(!l){const c=ce.getOrCreate(this.sourceId??"",e,this.context);return this.switchScene(c)}if(l)e=(s=this.scenes)==null?void 0:s.indexOf(l);else return nr}if(!((n=this.scenes)!=null&&n.length))return nr;if(e<0){if(this.clamp)return nr;e=this.scenes.length-1}else if(e>=this.scenes.length){if(this.clamp)return nr;e=0}const r=this.scenes[e];return this.switchScene(r)}unload(){return this.__lastSwitchScene=void 0,this.__lastSwitchScenePromise=void 0,this.__unloadCurrentScene()}async reload(){if(this.__lastSwitchScene){const e=this.__lastSwitchScene;return this.__lastSwitchScene=void 0,this.switchScene(e)}return!1}async switchScene(e){var t;if(!(e instanceof ce)){const s=typeof e;if(s==="string")return this.select(e);if(s==="number")return this.select(e);if(e&&e instanceof E){const n=(t=this.scenes)==null?void 0:t.indexOf(e);e=new ce(e.name,void 0,e),n>=0&&(this.scenes[n]=e)}else return console.warn(`[SceneSwitcher] Can't switch to scene of type ${s}`),!1}return e.url===this.sourceId?(console.warn("[SceneSwitcher] Can't load own scene - prevent recursive loading",this.sourceId),!1):this.__lastSwitchScene===e&&this.__lastSwitchScenePromise?this.__lastSwitchScenePromise:(this.__lastSwitchScene=e,this.__lastSwitchScenePromise=this.__internalSwitchScene(e),await this.__lastSwitchScenePromise)}async __unloadCurrentScene(){const e=this._currentScene;if(this._currentScene=void 0,e){Ht&&console.log("UNLOAD",e.url,"HasURL?: "+e.hasUrl);const t=this.tryGetSceneEventListener(e.asset);if(t!=null&&t.sceneClosing){const s=t.sceneClosing();s instanceof Promise&&await s}e.hasUrl?e.unload():e.asset instanceof E&&P.remove(e.asset)}}async __internalSwitchScene(e){var t,s,n,r,l;await this.__unloadCurrentScene();const c=this._currentIndex=((t=this.scenes)==null?void 0:t.indexOf(e))??-1;try{this._currentlyLoadingScene=e,this._currentLoadingProgress=new ProgressEvent("progress",{loaded:0,total:1});const h=new CustomEvent("loadscene-start",{detail:{scene:e,switcher:this,index:c}});this.dispatchEvent(h),(s=this.sceneLoadingStart)==null||s.invoke(h.detail),await this.onStartLoading(),await e.loadAssetAsync((u,p)=>{var g;if(Ht){const f=p.loaded/p.total,y="["+"=".repeat(Math.floor(f*20))+"-".repeat(20-Math.floor(f*20))+"]";console.debug(`[SceneSwitcher] Download ${(f*100).toFixed(1)} % ${y}`,e.url)}this._currentLoadingProgress=p,this.dispatchEvent(p),(g=this.sceneLoadingProgress)==null||g.invoke(p)}).catch(console.error),await this.onEndLoading();const d=new CustomEvent("loadscene-finished",{detail:{scene:e,switcher:this,index:c}});if(this.dispatchEvent(d),this._currentLoadingProgress=void 0,this._currentlyLoadingScene=void 0,d.defaultPrevented)return Ht&&console.warn("Adding loaded scene prevented:",e,d),!1;if(!e.asset)return Ht&&console.warn("Failed loading scene:",e),!1;if(this._currentIndex===c){if(Ht&&console.log("ADD",e.url),this._currentScene=e,eI){const g=((n=this.context.mainCameraComponent)==null?void 0:n.gameObject)||this.context.mainCamera;g?.removeFromParent();const f=this.gameObject.removeFromParent();Ei(this.context.scene,!0,!0),this.context.scene=new wi,this.context.scene.add(f),g&&this.context.scene.add(g)}if(P.add(e.asset,this.gameObject),this.useSceneLighting&&this.context.sceneLighting.enable(e),this.useSceneBackground){const g=this.context.lightmaps.tryGetSkybox(e.url);g?(g.mapping=kn,this.context.scene.background=g):Ht&&console.warn("SceneSwitcher: Can't find skybox for scene "+e.url)}if(this.useHistory&&c>=0){let g=c.toString();if(this.useSceneName&&(e instanceof E?g=e.name:e.url&&(g=yS(e.url))),(r=this.queryParameterName)!=null&&r.length)Hl(this.queryParameterName,g,this.useHistory);else{const f=history.state,y=this.guid+"::"+c;f!==y&&history.pushState(y,"unused",location.href)}}const u=this.tryGetSceneEventListener(e.asset);if(u!=null&&u.sceneOpened){const g=u.sceneOpened(this);g instanceof Promise&&await g}const p=new CustomEvent("scene-opened",{detail:{scene:e,switcher:this,index:c}});return this.dispatchEvent(p),(l=this.sceneLoaded)==null||l.invoke(this),!0}}catch(h){console.error(h)}return!1}preload(e){if(e>=0&&e<this.scenes.length){const t=this.scenes[e];if(t instanceof ce)return t.preload()}return nr}tryLoadFromQueryParam(){var e;if(!((e=this.queryParameterName)!=null&&e.length))return nr;const t=C(this.queryParameterName);return typeof t=="boolean"?nr:this.trySelectSceneFromValue(t)}trySelectSceneFromValue(e){if(typeof e=="string"){const t=parseInt(e);if(t>=0&&t<this.scenes.length)return this.select(t);{const s=e.toLowerCase();for(let n=0;n<this.scenes.length;n++){const r=this.scenes[n];if(!!r&&(r instanceof E?r.name:yS(r.url)).toLowerCase().includes(s))return this.select(n)}}}else if(typeof e=="number"&&e>=0&&e<this.scenes.length)return this.select(e);return qt()&&console.warn('Can not find scene: "'+e+'"',this),nr}async onStartLoading(){var e,t;if(this._isCurrentlyLoading=!0,this.loadingScene&&(this._lastLoadingScene!==this.loadingScene&&(this._loadingScenePromise=void 0),this._lastLoadingScene=this.loadingScene,this._loadingScenePromise||(this._loadingScenePromise=(e=this.loadingScene)==null?void 0:e.loadAssetAsync().then(s=>s!=null)),await this._loadingScenePromise,this._isCurrentlyLoading&&(t=this.loadingScene)!=null&&t.asset)){Ht&&console.log("Add loading scene",this.loadingScene.url,this.loadingScene.asset);const s=this.loadingScene.asset;P.add(s,this.gameObject);const n=this.tryGetSceneEventListener(s);if(n!=null&&n.sceneOpened){const r=n.sceneOpened(this);r instanceof Promise&&await r}}if(this._isCurrentlyLoading){const s=this.tryGetSceneEventListener(this.gameObject);if(s&&s.sceneOpened){const n=s.sceneOpened(this);n instanceof Promise&&await n}}}async onEndLoading(){var e;if(this._isCurrentlyLoading=!1,(e=this.loadingScene)!=null&&e.asset){Ht&&console.log("Remove loading scene",this.loadingScene.url);const t=this.loadingScene.asset,s=this.tryGetSceneEventListener(t);if(typeof s?.sceneClosing=="function"){const n=s.sceneClosing();n instanceof Promise&&await n}P.remove(t)}if(!this._isCurrentlyLoading){const t=this.tryGetSceneEventListener(this.gameObject);if(t&&t.sceneClosing){const s=t.sceneClosing();s instanceof Promise&&await s}}}tryGetSceneEventListener(e,t=0){if(!e)return null;const s=P.foreachComponent(e,n=>{const r=n;if(r.sceneClosing||r.sceneOpened)return r});if(t===0&&!s&&e.children.length)for(const n of e.children){const r=this.tryGetSceneEventListener(n,t+1);if(r)return r}return s||null}}Ct([m()],Ze.prototype,"autoLoadFirstScene"),Ct([m(ce)],Ze.prototype,"scenes"),Ct([m(ce)],Ze.prototype,"loadingScene"),Ct([m()],Ze.prototype,"queryParameterName"),Ct([m()],Ze.prototype,"useSceneName"),Ct([m()],Ze.prototype,"clamp"),Ct([m()],Ze.prototype,"useHistory"),Ct([m()],Ze.prototype,"useKeyboard"),Ct([m()],Ze.prototype,"useSwipe"),Ct([m()],Ze.prototype,"useSceneLighting"),Ct([m()],Ze.prototype,"useSceneBackground"),Ct([m()],Ze.prototype,"preloadNext"),Ct([m()],Ze.prototype,"preloadPrevious"),Ct([m()],Ze.prototype,"preloadConcurrent"),Ct([m()],Ze.prototype,"createMenuButtons"),Ct([m(xe)],Ze.prototype,"sceneLoadingStart"),Ct([m(xe)],Ze.prototype,"sceneLoadingProgress"),Ct([m(xe)],Ze.prototype,"sceneLoaded");function yS(o){const e=o.split("/").pop(),t=e?.split(".").shift();return t!=null&&t.length?t:o}class tI{constructor(e,t=1,s=1,n=2){a(this,"maxLoadAhead"),a(this,"maxLoadBehind"),a(this,"maxConcurrent"),a(this,"_isRunning",!1),a(this,"_switcher"),a(this,"_loadTasks",[]),a(this,"_maxConcurrentLoads",1),this._switcher=e,this.maxLoadAhead=t,this.maxLoadBehind=s,this.maxConcurrent=n}begin(e){if(this._isRunning)return;Ht&&console.log("Preload begin",{delay:e}),this._isRunning=!0;let t=-10,s,n;const r=this._switcher.scenes,l=Date.now()+e,c=setInterval(()=>{if(this.allLoaded()&&(Ht&&console.log("All scenes (pre-)loaded"),this.stop()),!this._isRunning){clearInterval(c);return}if(Date.now()<l||this.canLoadNewScene()===!1)return;(t===-10||t!==this._switcher.currentIndex)&&(t=this._switcher.currentIndex,n=0,s=0);const h=n%2===0;h&&(s+=1),n+=1;const d=h?this.maxLoadAhead:this.maxLoadBehind;if(s>d)return;const u=h?t+s:t-s;if(!(u<0)&&!(u<0||u>=r.length)&&!this._loadTasks.some(p=>p.index===u)){const p=r[u];Ht&&console.log("Preload scene",{roomIndex:u,searchForward:h,lastRoom:t,currentIndex:this._switcher.currentIndex,tasks:this._loadTasks.length},p?.url),new iI(u,p,this._loadTasks)}},200)}stop(){this._isRunning=!1}canLoadNewScene(){return this._loadTasks.length<this._maxConcurrentLoads}allLoaded(){if(this._switcher.scenes){for(const e of this._switcher.scenes)if(e!=null&&e.isLoaded&&e.isLoaded()===!1)return!1}return!0}}class iI{constructor(e,t,s){a(this,"index"),a(this,"asset"),a(this,"tasks"),this.index=e,this.asset=t,this.tasks=s,s.push(this),this.awaitLoading()}async awaitLoading(){this.asset&&!this.asset.isLoaded()&&(Ht&&console.log("Preload start: "+this.asset.url,this.index),await this.asset.preload(),Ht&&console.log("Preload finished: "+this.asset.url,this.index));const e=this.tasks.indexOf(this);e>=0&&this.tasks.splice(e,1)}}function sI(){return new Promise((o,e)=>{const t=()=>{t!=null&&(document.removeEventListener("pointerdown",t),document.removeEventListener("click",t),document.removeEventListener("dragstart",t),document.removeEventListener("touchstart",t),o())};document.addEventListener("pointerdown",t),document.addEventListener("click",t),document.addEventListener("dragstart",t),document.addEventListener("touchstart",t)})}async function nI(o){await sI(),o()}var oI=Object.defineProperty,rI=Object.getOwnPropertyDescriptor,Vi=(o,e,t,s)=>{for(var n=s>1?void 0:s?rI(e,t):e,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=(s?l(e,t,n):l(n))||n);return s&&n&&oI(e,t,n),n};const Pt=C("debugvideo");var vS=(o=>(o[o.None=0]="None",o[o.AdjustHeight=1]="AdjustHeight",o[o.AdjustWidth=2]="AdjustWidth",o))(vS||{}),bS=(o=>(o[o.VideoClip=0]="VideoClip",o[o.Url=1]="Url",o))(bS||{}),_S=(o=>(o[o.CameraFarPlane=0]="CameraFarPlane",o[o.CameraNearPlane=1]="CameraNearPlane",o[o.RenderTexture=2]="RenderTexture",o[o.MaterialOverride=3]="MaterialOverride",o))(_S||{});class yt extends I{constructor(){super(),a(this,"playOnAwake",!0),a(this,"aspectMode",0),a(this,"clip",null),a(this,"source",1),a(this,"_url",null),a(this,"renderMode"),a(this,"targetMaterialProperty"),a(this,"targetMaterialRenderer"),a(this,"targetTexture"),a(this,"time",0),a(this,"_playbackSpeed",1),a(this,"_isLooping",!1),a(this,"_muted",!1),a(this,"_audioOutputMode",2),a(this,"playInBackground",!0),a(this,"_crossOrigin","anonymous"),a(this,"_videoElement",null),a(this,"_videoTexture",null),a(this,"_videoMaterial",null),a(this,"_isPlaying",!1),a(this,"wasPlaying",!1),a(this,"visibilityChanged",e=>{switch(document.visibilityState){case"hidden":this.playInBackground||(this.wasPlaying=this._isPlaying,this.pause());break;case"visible":this.wasPlaying&&!this._isPlaying&&this.play();break}}),a(this,"_receivedInput",!1),a(this,"_overlay",null),a(this,"_targetObjects"),a(this,"_updateAspectRoutineId",-1),a(this,"_hls"),a(this,"onHlsAvailable",()=>{var e;Pt&&console.log("HLS: available",this.clip),!(!this.shouldUseM3U||!this.url)&&(this._hls||(this._hls=new Hls),this.videoElement.autoplay=!0,this._hls.loadSource(this.url),this._hls.attachMedia(this.videoElement),(e=this._videoElement)==null||e.play(),Pt&&console.log("HLS: loaded",this.clip))}),nI(()=>{this._receivedInput=!0,this.updateVideoElementSettings()}),this._targetObjects=[],C("videoscreenspace")&&window.addEventListener("keydown",e=>{e.key==="f"&&(this.screenspace=!this.screenspace)})}get url(){return this._url}set url(e){const t=this._url!==e;this.__didAwake?t&&this.setClipURL(e??""):this._url=e}get playbackSpeed(){var e;return((e=this._videoElement)==null?void 0:e.playbackRate)??this._playbackSpeed}set playbackSpeed(e){this._playbackSpeed=e,this._videoElement&&(this._videoElement.playbackRate=e)}get isLooping(){var e;return((e=this._videoElement)==null?void 0:e.loop)??this._isLooping}set isLooping(e){this._isLooping=e,this._videoElement&&(this._videoElement.loop=e)}get currentTime(){var e;return((e=this._videoElement)==null?void 0:e.currentTime)??this.time}set currentTime(e){this._videoElement?this._videoElement.currentTime=e:this.time=e}get isPlaying(){const e=this._videoElement;return!!(e&&(e.currentTime>0&&!e.paused&&!e.ended&&e.readyState>e.HAVE_CURRENT_DATA||e.srcObject&&e.srcObject.active))}get crossOrigin(){var e;return((e=this._videoElement)==null?void 0:e.crossOrigin)??this._crossOrigin}set crossOrigin(e){this._crossOrigin=e,this._videoElement&&(e!==null?this._videoElement.setAttribute("crossorigin",e):this._videoElement.removeAttribute("crossorigin"))}get videoMaterial(){return!this._videoMaterial&&!this.create(!1)?null:this._videoMaterial}get videoTexture(){return!this._videoTexture&&!this.create(!1)?null:this._videoTexture}get videoElement(){return!this._videoElement&&!this.create(!1)?null:this._videoElement}requestPictureInPicture(){return this._videoElement?this._videoElement.requestPictureInPicture():null}get muted(){var e;return((e=this._videoElement)==null?void 0:e.muted)??this._muted}set muted(e){this._muted=e,this._videoElement&&(this._videoElement.muted=e)}get currentVideo(){return this.clip}set audioOutputMode(e){e!==this._audioOutputMode&&(e===1&&F()&&console.warn("VideoAudioOutputMode.AudioSource is not yet implemented"),this._audioOutputMode=e,this.updateVideoElementSettings())}get audioOutputMode(){return this._audioOutputMode}preloadVideo(){Pt&&console.log("Video Preload: "+this.name,this.clip),this.create(!1)}preload(){this.preloadVideo()}setVideo(e){this.clip=e,this.source=0,this._videoElement?(this._videoElement.srcObject=e,this._isPlaying&&this.play(),this.updateAspect()):this.create(this.playOnAwake)}setClipURL(e){this._url!==e&&(this._url=e,this.source=1,Pt&&console.log("set url",e),this._videoElement?e.endsWith(".m3u8")||e.includes(".m3u")?this.ensureM3UCanBePlayed():(this._videoElement.src=e,this._isPlaying&&(this.stop(),this.play())):this.create(this.playOnAwake))}onEnable(){var e,t;Pt&&console.log("VideoPlayer.onEnable",bS[this.source],this.clip,this.url,this),window.addEventListener("visibilitychange",this.visibilityChanged),this.playOnAwake===!0?this.create(!0):this.preloadVideo(),this.screenspace?(e=this._overlay)==null||e.start():(t=this._overlay)==null||t.stop()}onDisable(){var e;window.removeEventListener("visibilitychange",this.visibilityChanged),(e=this._overlay)==null||e.stop(),this.pause()}onDestroy(){var e;this._videoElement&&((e=this.videoElement)==null||e.remove(),this._videoElement=null),this._videoTexture&&(this._videoTexture.dispose(),this._videoTexture=null)}play(){var e,t;if(this._videoElement||this.create(!1),!this._videoElement){Pt&&console.warn("Can not play: no video element found",this);return}if(!(this._isPlaying&&!((e=this._videoElement)!=null&&e.ended)&&!((t=this._videoElement)!=null&&t.paused))){if(this._isPlaying=!0,this._receivedInput||(this._videoElement.muted=!0),this.handleBeginPlaying(!1),this.shouldUseM3U){this.ensureM3UCanBePlayed();return}Pt&&console.log("Video Play()",this.clip,this._videoElement,this.time),this._videoElement.currentTime=this.time,this._videoElement.play().catch(s=>{var n;console.log(s),Pt&&console.error("Error playing video",s,"CODE="+s.code,(n=this.videoElement)==null?void 0:n.src,this),setTimeout(()=>{this._isPlaying&&!this.destroyed&&this.activeAndEnabled&&this.play()},1e3)}),Pt&&console.log("play",this._videoElement,this.time)}}stop(){this._isPlaying=!1,this.time=0,this._videoElement&&(this._videoElement.currentTime=0,this._videoElement.pause(),Pt&&console.log("STOP",this))}pause(){var e,t;this.time=((e=this._videoElement)==null?void 0:e.currentTime)??0,this._isPlaying=!1,(t=this._videoElement)==null||t.pause(),Pt&&console.log("PAUSE",this,this.currentTime)}create(e){let t;switch(this.source){case 0:t=this.clip;break;case 1:t=this.url,!(t!=null&&t.length)&&typeof this.clip=="string"&&(t=this.clip);break}return t?(this._videoElement||(Pt&&console.warn("Create VideoElement",this),this._videoElement=this.createVideoElement(),this.context.domElement.shadowRoot.prepend(this._videoElement),this.updateVideoElementStyles()),typeof t=="string"?(Pt&&console.log("Set Video src",t),this._videoElement.src=t):(Pt&&console.log("Set Video srcObject",t),this._videoElement.srcObject=t),this._videoTexture||(this._videoTexture=new IP(this._videoElement)),this._videoTexture.flipY=!1,this._videoTexture.colorSpace=Mn,e&&this.handleBeginPlaying(e),Pt&&console.log("Video: handle playing done...",t,e),!0):(Pt&&console.warn("No video source set",this),!1)}updateAspect(){this.aspectMode!==0&&this.startCoroutine(this.updateAspectImpl())}get screenspace(){var e;return((e=this._overlay)==null?void 0:e.enabled)??!1}set screenspace(e){var t;if(e){if(!this._videoTexture)return;this._overlay||(this._overlay=new aI(this.context)),this._overlay.add(this._videoTexture)}else(t=this._overlay)==null||t.remove(this._videoTexture);this._overlay&&(this._overlay.enabled=e)}createVideoElement(){const e=document.createElement("video");return this._crossOrigin&&e.setAttribute("crossorigin",this._crossOrigin),Pt&&console.log("created video element",e),e}handleBeginPlaying(e){var t,s;if(!this.activeAndEnabled||!this._videoElement)return;this._targetObjects.length=0;let n=this.gameObject;switch(this.renderMode){case 3:n=(t=this.targetMaterialRenderer)==null?void 0:t.gameObject,n||(n=(s=P.getComponent(this.gameObject,Fi))==null?void 0:s.gameObject);break;case 2:console.error("VideoPlayer renderTexture not implemented yet. Please use material override instead");return}if(!n){console.error("Missing target for video material renderer",this.name,_S[this.renderMode],this);return}const r=n.material;if(r){this._targetObjects.push(n),r!==this._videoMaterial&&(this._videoMaterial=r.clone(),n.material=this._videoMaterial);const l="map",c=this._videoMaterial;if(!this.targetMaterialProperty)c[l]=this._videoTexture;else switch(this.targetMaterialProperty){default:c[l]=this._videoTexture;break}}else{console.warn("Can not play video, no material found, this might be a multimaterial case which is not supported yet");return}this.updateVideoElementSettings(),this.updateVideoElementStyles(),e&&(this.shouldUseM3U&&this.ensureM3UCanBePlayed(),this.play())}updateVideoElementSettings(){if(!this._videoElement)return;this._videoElement.loop=this._isLooping,this._videoElement.currentTime=this.currentTime,this._videoElement.playbackRate=this._playbackSpeed,this._videoElement.playsInline=!0;let e=!this._receivedInput||this.audioOutputMode===0;!e&&this._muted&&(e=!0),this._videoElement.muted=e,this.playOnAwake&&(this._videoElement.autoplay=!0)}updateVideoElementStyles(){this._videoElement&&(this._videoElement.style.userSelect="none",this._videoElement.style.visibility="hidden",this._videoElement.style.display="none",this.updateAspect())}*updateAspectImpl(){const e=++this._updateAspectRoutineId,t=void 0,s=this.clip;for(;e===this._updateAspectRoutineId&&this.aspectMode!==0&&this.clip&&s===this.clip&&this._isPlaying;){if(!s||typeof s=="string")return;let n;for(const r of s.getVideoTracks()){const l=r.getSettings();if(l&&l.width&&l.height){n=l.width/l.height;break}else n=this.context.renderer.domElement.clientWidth/this.context.renderer.domElement.clientHeight}if(n===void 0){for(let r=0;r<10;r++)yield;if(!this.isPlaying)break;continue}if(t===n){yield;continue}for(const r of this._targetObjects){let l=1;if(r.parent){const c=Ge(r.parent);l=c.x/c.y}switch(this.aspectMode){case 1:r.scale.y=1/n*r.scale.x*l;break;case 2:r.scale.x=n*r.scale.y*l;break}}for(let r=0;r<3;r++)yield}}get shouldUseM3U(){return this.url!=null&&(this.url.endsWith(".m3u8")||this.url.endsWith(".m3u"))&&this.source===1}ensureM3UCanBePlayed(){if(!this.shouldUseM3U)return;let e=document.head.querySelector("script[data-hls_library]");e?globalThis.Hls?this.onHlsAvailable():e.addEventListener("load",this.onHlsAvailable):(Pt&&console.log("HLS: load script"),e=document.createElement("script"),e.dataset.hls_library="hls.js",e.src="https://cdn.jsdelivr.net/npm/hls.js@1",e.addEventListener("load",this.onHlsAvailable),document.head.append(e))}}Vi([m()],yt.prototype,"playOnAwake",2),Vi([m()],yt.prototype,"aspectMode",2),Vi([m(URL)],yt.prototype,"clip",2),Vi([m()],yt.prototype,"source",2),Vi([m(URL)],yt.prototype,"url",1),Vi([m()],yt.prototype,"renderMode",2),Vi([m()],yt.prototype,"targetMaterialProperty",2),Vi([m(Fi)],yt.prototype,"targetMaterialRenderer",2),Vi([m(De)],yt.prototype,"targetTexture",2),Vi([m()],yt.prototype,"time",2),Vi([m()],yt.prototype,"playbackSpeed",1),Vi([m()],yt.prototype,"isLooping",1),Vi([m()],yt.prototype,"audioOutputMode",1);class aI{constructor(e){a(this,"context"),a(this,"_videos",[]),a(this,"_screenspaceModeQuad"),a(this,"_isInScreenspaceMode",!1),a(this,"_input"),this.context=e,this._input=new lI(this)}get enabled(){return this._isInScreenspaceMode}set enabled(e){e?this.start():this.stop()}add(e){this._videos.indexOf(e)===-1&&this._videos.push(e)}remove(e){if(!e)return;const t=this._videos.indexOf(e);t>=0&&this._videos.splice(t,1)}start(){var e;if(this._isInScreenspaceMode||this._videos.length<0)return;const t=this._videos[this._videos.length-1];if(!t)return;if(this._isInScreenspaceMode=!0,!this._screenspaceModeQuad){if(this._screenspaceModeQuad=_o.createPrimitive(wr.Quad,{material:new cI(t)}),!this._screenspaceModeQuad)return;this._screenspaceModeQuad.geometry.scale(2,2,2)}const s=this._screenspaceModeQuad;this.context.scene.add(s),this.updateScreenspaceMaterialUniforms();const n=s.material;n?.reset(),(e=this._input)==null||e.enable(n)}stop(){var e;this._isInScreenspaceMode=!1,this._screenspaceModeQuad&&((e=this._input)==null||e.disable(),this._screenspaceModeQuad.removeFromParent())}updateScreenspaceMaterialUniforms(){var e;const t=(e=this._screenspaceModeQuad)==null?void 0:e.material;t&&(t.screenAspect=this.context.domElement.clientWidth/this.context.domElement.clientHeight)}}class lI{constructor(e){a(this,"_onResizeScreenFn"),a(this,"_onKeyUpFn"),a(this,"_onMouseWheelFn"),a(this,"context"),a(this,"overlay"),a(this,"_material"),a(this,"_isPinching",!1),a(this,"_lastPinch",0),this.overlay=e,this.context=e.context}enable(e){this._material=e,window.addEventListener("resize",this._onResizeScreenFn=()=>{this.overlay.updateScreenspaceMaterialUniforms()}),window.addEventListener("keyup",this._onKeyUpFn=n=>{n.key==="Escape"&&this.overlay.stop()}),window.addEventListener("wheel",this._onMouseWheelFn=n=>{this.overlay.enabled&&(e.zoom+=n.deltaY*5e-4,n.preventDefault())},{passive:!1});const t=new le;window.addEventListener("mousemove",n=>{if(this.overlay.enabled&&this.context.input.getPointerPressed(0)){const r=new le(n.movementX,n.movementY);r.x/=this.context.domElement.clientWidth,r.y/=this.context.domElement.clientHeight,t.set(r.x,r.y),t.multiplyScalar(e.zoom/-this.context.time.deltaTime*.01),e.offset=e.offset.add(t)}}),window.addEventListener("pointermove",n=>{this.overlay.enabled&&this.context.input.getPointerPressed(0)&&this.context.input.getTouchesPressedCount()===1&&(t.set(n.movementX,n.movementY),t.multiplyScalar(e.zoom*-this.context.time.deltaTime*.05),e.offset=e.offset.add(t))});let s=0;window.addEventListener("touchstart",n=>{if(n.touches.length<2){this.context.time.time-s<.3&&this.overlay.stop(),s=this.context.time.time;return}this._isPinching=!0,this._lastPinch=0}),window.addEventListener("touchmove",n=>{if(!this._isPinching||!this._material)return;const r=n.touches[0],l=n.touches[1],c=r.clientX-l.clientX,h=r.clientY-l.clientY,d=Math.sqrt(c*c+h*h);if(this._lastPinch!==0){const u=d-this._lastPinch;this._material.zoom-=u*.004}this._lastPinch=d}),window.addEventListener("touchend",()=>{this._isPinching=!1})}disable(){this._onResizeScreenFn&&(window.removeEventListener("resize",this._onResizeScreenFn),this._onResizeScreenFn=void 0),this._onKeyUpFn&&(window.removeEventListener("keyup",this._onKeyUpFn),this._onKeyUpFn=void 0),this._onMouseWheelFn&&(window.removeEventListener("wheel",this._onMouseWheelFn),this._onMouseWheelFn=void 0)}}class cI extends Ws{constructor(e){super(),a(this,"_offset",new le),this.uniforms={map:{value:e},screenAspect:{value:1},offsetScale:{value:new ye(0,0,1,1)}},this.vertexShader=`
1294
+ uniform sampler2D map;
1295
+ uniform float screenAspect;
1296
+ uniform vec4 offsetScale;
1297
+ varying vec2 vUv;
1298
+
1299
+ void main() {
1300
+
1301
+ gl_Position = vec4( position , 1.0 );
1302
+ vUv = uv;
1303
+ vUv.y = 1. - vUv.y;
1304
+
1305
+ // fit into screen
1306
+ ivec2 res = textureSize(map, 0);
1307
+ float videoAspect = float(res.x) / float(res.y);
1308
+ float aspect = videoAspect / screenAspect;
1309
+ if(aspect >= 1.0)
1310
+ {
1311
+ vUv.y = vUv.y * aspect;
1312
+ float offset = (1. - aspect) * .5;
1313
+ vUv.y = vUv.y + offset;
1314
+ }
1315
+ else
1316
+ {
1317
+ vUv.x = vUv.x / aspect;
1318
+ float offset = (1. - 1. / aspect) * .5;
1319
+ vUv.x = vUv.x + offset;
1320
+ }
1321
+
1322
+ vUv.x -= .5;
1323
+ vUv.y -= .5;
1324
+
1325
+ vUv.x *= offsetScale.z;
1326
+ vUv.y *= offsetScale.z;
1327
+ vUv.x += offsetScale.x;
1328
+ vUv.y += offsetScale.y;
1329
+
1330
+ vUv.x += .5;
1331
+ vUv.y += .5;
1332
+ }
1333
+
1334
+ `,this.fragmentShader=`
1335
+ uniform sampler2D map;
1336
+ varying vec2 vUv;
1337
+ void main() {
1338
+ if(vUv.x < 0. || vUv.x > 1. || vUv.y < 0. || vUv.y > 1.)
1339
+ gl_FragColor = vec4(0., 0., 0., 1.);
1340
+ else
1341
+ {
1342
+ vec4 texcolor = texture2D(map, vUv);
1343
+ gl_FragColor = texcolor;
1344
+ }
1345
+ }
1346
+ `}set screenAspect(e){this.uniforms.screenAspect.value=e,this.needsUpdate=!0}set offset(e){const t=this.uniforms.offsetScale.value;t.x=e.x,t.y=e.y,this.uniforms.offsetScale.value=t,this.needsUpdate=!0}get offset(){const e=this.uniforms.offsetScale.value;return this._offset.set(e.x,e.y),this._offset}set zoom(e){const t=this.uniforms.offsetScale.value;e<.001&&(e=.001),t.z=e,this.needsUpdate=!0}get zoom(){return this.uniforms.offsetScale.value.z}reset(){this.offset=this.offset.set(0,0),this.zoom=1,this.needsUpdate=!0}}var hI=Object.defineProperty,dI=Object.getOwnPropertyDescriptor,Oh=(o,e,t,s)=>{for(var n=s>1?void 0:s?dI(e,t):e,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=(s?l(e,t,n):l(n))||n);return s&&n&&hI(e,t,n),n};const It=C("debugscreensharing");var wS=(o=>(o[o.Screen=0]="Screen",o[o.Camera=1]="Camera",o[o.Canvas=2]="Canvas",o[o.Microphone=3]="Microphone",o))(wS||{});class or extends I{constructor(){super(...arguments),a(this,"allowStartOnClick",!0),a(this,"autoConnect",!1),a(this,"_videoPlayer"),a(this,"_audioSource"),a(this,"device","Screen"),a(this,"deviceName"),a(this,"deviceFilter"),a(this,"_net"),a(this,"_requestOpen",!1),a(this,"_currentStream",null),a(this,"_currentMode",0),a(this,"onJoinedRoom",async()=>{await ys(1e3),this.autoConnect&&!this.isSending&&!this.isReceiving&&this.context.connection.isInRoom&&this.share()}),a(this,"_activeShareRequest",null),a(this,"onReceiveStream",e=>{var t;((t=e.stream)==null?void 0:t.active)===!0&&this.setStream(e.stream,2)}),a(this,"onCallEnded",e=>{It&&console.log("CALL ENDED",this.isReceiving,this==null?void 0:this.screenspace),this.isReceiving&&(this.screenspace=!1)})}onPointerEnter(){this.context.connection.allowEditing!=!1&&this.allowStartOnClick&&this.context.input.setCursor("pointer")}onPointerExit(){this.context.connection.allowEditing!=!1&&this.allowStartOnClick&&this.context.input.unsetCursor("pointer")}onPointerClick(e){var t;if(this.context.connection.allowEditing!=!1&&this.allowStartOnClick&&!(e&&e.pointerId!==0)){if(this.isReceiving&&(t=this.videoPlayer)!=null&&t.isPlaying){this.videoPlayer&&(this.videoPlayer.screenspace=!this.videoPlayer.screenspace);return}if(this.isSending){this.close();return}this.share()}}set videoPlayer(e){this._videoPlayer&&(this.isSending||this.isReceiving)&&this._videoPlayer.stop(),this._videoPlayer=e,this._videoPlayer&&this._currentStream&&(this.isSending||this.isReceiving)&&this._videoPlayer.setVideo(this._currentStream)}get videoPlayer(){return this._videoPlayer}get screenspace(){var e;return((e=this.videoPlayer)==null?void 0:e.screenspace)??!1}set screenspace(e){this.videoPlayer&&(this.videoPlayer.screenspace=e)}get currentScream(){return this._currentStream}get currentMode(){return this._currentMode}get isSending(){var e;return((e=this._currentStream)==null?void 0:e.active)&&this._currentMode===1}get isReceiving(){if(this._currentMode===2){if(!this._currentStream||this._currentStream.active===!1)return!1;const e=this._currentStream.getTracks();for(const t of e)if(t.readyState==="live")return!0}return!1}get requiresVideoPlayer(){return this.device!=="Microphone"}awake(){typeof this.device=="number"&&(this.device=wS[this.device]),It&&console.log("Screensharing",this.name,this),ss.registerWaitForAllowAudio(()=>{this._videoPlayer&&this._currentStream&&this._currentMode===2&&(this._videoPlayer.playInBackground=!0,this._videoPlayer.setVideo(this._currentStream))}),this._net=new ld(this)}onEnable(){var e,t,s;(e=this._net)==null||e.enable(),(t=this._net)==null||t.addEventListener(nn.StreamReceived,this.onReceiveStream),(s=this._net)==null||s.addEventListener(nn.StreamEnded,this.onCallEnded),this.context.connection.beginListen(ie.JoinedRoom,this.onJoinedRoom),this.autoConnect&&ys(1e3).then(()=>(this.enabled&&this.autoConnect&&!this.isReceiving&&!this.isSending&&this.context.connection.isInRoom&&this.share(),0))}onDisable(){var e,t,s;(e=this._net)==null||e.removeEventListener(nn.StreamReceived,this.onReceiveStream),(t=this._net)==null||t.removeEventListener(nn.StreamEnded,this.onCallEnded),this.context.connection.stopListen(ie.JoinedRoom,this.onJoinedRoom),(s=this._net)==null||s.disable(),this.close()}_ensureVideoPlayer(){const e=new yt;e.aspectMode=vS.AdjustWidth,P.addComponent(this.gameObject,e),this._videoPlayer=e}async share(e){return this._activeShareRequest?this._activeShareRequest:(this._activeShareRequest=this.internalShare(e),this._activeShareRequest.then(()=>this._activeShareRequest=null))}async internalShare(e){if(this.context.connection.isInRoom===!1){console.warn("Can not start screensharing: requires network connection"),F()&&be("Can not start screensharing: requires network connection. Add a SyncedRoom component or join a room first.");return}if(e!=null&&e.device&&(this.device=e.device),!this.videoPlayer&&this.requiresVideoPlayer&&(this._videoPlayer||(this._videoPlayer=P.getComponent(this.gameObject,yt)??void 0),this.videoPlayer||this._ensureVideoPlayer(),!this.videoPlayer)){console.warn("Can not share video without a videoPlayer assigned");return}this._requestOpen=!0;try{const t=e?.constraints??{echoCancellation:!0,autoGainControl:!1},s={video:t,audio:t},n=s.video;switch(n!==void 0&&typeof n!="boolean"&&(n.width||(n.width={max:1920}),n.height||(n.height={max:1920}),n.aspectRatio||(n.aspectRatio={ideal:1.7777777778}),n.frameRate||(n.frameRate={ideal:24}),n.facingMode||(n.facingMode={ideal:"user"})),this.device){case"Camera":this.tryShareUserCamera(s,e);break;case"Screen":{if(!navigator.mediaDevices.getDisplayMedia){console.error("No getDisplayMedia support");return}const l=await navigator.mediaDevices.getDisplayMedia(s);this._requestOpen?this.setStream(l,1):on(l)}break;case"Canvas":const r=this.context.renderer.domElement.captureStream(0);this.setStream(r,1);break;case"Microphone":{if(!navigator.mediaDevices.getUserMedia){console.error("No getDisplayMedia support");return}s.video=!1;const l=await navigator.mediaDevices.getUserMedia(s);this._requestOpen?this.setStream(l,1):on(l)}break;default:console.error("Can not start screen sharing: Unknown device type",this.device)}}catch(t){if(t.name==="NotAllowedError"){console.log("Selection cancelled"),this._requestOpen=!1;return}console.error("Error opening video",t)}}close(){var e;this._requestOpen=!1,this._currentStream&&(It&&console.warn("Close current stream / disposing resources, stream was active?",this._currentStream.active),(e=this._net)==null||e.stopSendingStream(this._currentStream),on(this._currentStream),this._currentMode=0,this._currentStream=null)}setStream(e,t){var s,n,r;if(e===this._currentStream||(this.close(),!e))return;this._currentStream=e,this._requestOpen=!0,this._currentMode=t;const l=this.device!=="Microphone",c=t===1;l?(this._videoPlayer||this._ensureVideoPlayer(),this._videoPlayer?this._videoPlayer.setVideo(e):console.error("No video player assigned for video stream")):(this._audioSource||(this._audioSource=new ss,this._audioSource.spatialBlend=0,this._audioSource.volume=1,this.gameObject.addComponent(this._audioSource)),c||(It&&console.log("PLAY",e.getAudioTracks()),this._audioSource.volume=1,(s=this._audioSource)==null||s.play(e))),c&&((n=this._net)==null||n.startSendingStream(e)),c&&(this._videoPlayer&&(this._videoPlayer.muted=!0),(r=this._audioSource)==null||r.stop());for(const h of e.getTracks())h.addEventListener("ended",()=>{It&&console.log("Track ended",h),this.close()}),It&&h.kind==="video"&&console.log(c?"Video \u2192":"Video \u2190",h.getSettings())}async tryShareUserCamera(e,t){const s=(await navigator.mediaDevices.enumerateDevices()).filter(r=>r.kind==="videoinput");It&&console.log(`Request camera. These are your kind:videoinput devices:
1347
+ `,s);let n=!1;for(const r of s)try{if(!this._requestOpen){It&&console.log("Camera selection cancelled");break}if(r.kind!=="videoinput"){It&&console.log("Skipping non-video device",r);continue}const l=r.deviceId;if(t?.deviceId!=null||t?.deviceFilter!=null){if(t?.deviceId!==void 0&&l!==t.deviceId){It&&console.log("Skipping device due to options.deviceId: "+r.label+"; "+r.deviceId);continue}if(t!=null&&t.deviceFilter&&t.deviceFilter(r)===!1){It&&console.log("Skipping device due to options.deviceFilter: "+r.label+"; "+r.deviceId);continue}}else if(this.deviceFilter)if(this.deviceFilter(r)===!1){It&&console.log("Skipping device due to ScreenShare.deviceFilter: "+r.label+"; "+r.deviceId);continue}else It&&console.log("Selected device by filter",r);else if(this.deviceName){const h=r.label.toLowerCase(),d=this.deviceName.toLowerCase(),u=h.includes(d),p=r.deviceId===this.deviceName;if(!u&&!p){It&&console.log("Skipping device due to ScreenShare.deviceName: "+r.label+"; "+r.deviceId);continue}else It&&console.log("Selected device by name",r)}e.video!==!1&&((typeof e.video>"u"||typeof e.video=="boolean")&&(e.video={}),e.video.deviceId=l),n=!0;const c=await navigator.mediaDevices.getUserMedia(e).catch(h=>(console.error("Failed to get user media",h),null));if(c===null)continue;this._requestOpen?(this.setStream(c,1),It&&console.log("Selected camera",r)):(on(c),It&&console.log("Camera selection cancelled"));break}catch(l){if(l.message==="Failed to allocate videosource"||l.message==="Could not start video source"){be("Failed to start video: Try another camera (Code "+l.code+")"),console.warn(l);continue}else console.error("Failed to get user media",l.message,l.code,l)}!n&&F()&&(be("No camera found for sharing. Please connect a camera (see console for more information)"),console.warn("No camera found for sharing. Please connect a camera",s,this.deviceName,"Using deviceFilter? "+this.deviceFilter!=null,"Using options? "+t!=null,"Using deviceName? "+this.deviceName!=null,"Using options.deviceId? "+t?.deviceId!=null,"Using options.deviceFilter? "+t?.deviceFilter!=null))}}Oh([m()],or.prototype,"allowStartOnClick",2),Oh([m()],or.prototype,"autoConnect",2),Oh([m(yt)],or.prototype,"videoPlayer",1),Oh([m()],or.prototype,"device",2),Oh([m()],or.prototype,"deviceName",2);var uI=Object.defineProperty,xS=(o,e,t,s)=>{for(var n=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=l(e,t,n)||n);return n&&uI(e,t,n),n};class kh extends I{constructor(){super(...arguments),a(this,"mode",0),a(this,"shadowColor",new he(0,0,0,1)),a(this,"targetMesh")}start(){if(this.gameObject instanceof q)this.gameObject instanceof q&&this.gameObject.material&&(this.gameObject.material=this.gameObject.material.clone(),this.targetMesh=this.gameObject,this.targetMesh.receiveShadow=!0);else{const e=_o.createPrimitive(wr.Quad,{name:"ShadowCatcher",material:new vt({color:10066329,roughness:1,metalness:0,transparent:!0})});e.receiveShadow=!0,e.geometry.rotateX(-Math.PI/2),this.gameObject.add(e),this.targetMesh=e}if(!this.targetMesh){console.warn("ShadowCatcher: no mesh to apply shadow catching to. Groups are currently not supported.");return}switch(this.targetMesh.layers.set(2),this.mode){case 0:this.applyShadowMaterial();break;case 1:this.applyLightBlendMaterial();break;case 2:this.applyOccluderMaterial();break}}applyLightBlendMaterial(){if(!this.targetMesh)return;const e=this.targetMesh.material;e.blending=Lv,this.applyMaterialOptions(e),e.onBeforeCompile=t=>{t.fragmentShader=t.fragmentShader.replace("vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;",`vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;
1348
+ // diffuse-only lighting with overdrive to somewhat compensate
1349
+ // for the loss of indirect lighting and to make it more visible.
1350
+ vec3 direct = (reflectedLight.directDiffuse + reflectedLight.directSpecular) * 6.6;
1351
+ float max = max(direct.r, max(direct.g, direct.b));
1352
+
1353
+ // early out - we're simply returning direct lighting and some alpha based on it so it can
1354
+ // be blended onto the scene.
1355
+ gl_FragColor = vec4(direct, max);
1356
+ return;
1357
+ `)},e.userData.isLightBlendMaterial=!0}applyShadowMaterial(){if(this.targetMesh)if(this.targetMesh.material.type!=="ShadowMaterial"){const e=new xv;e.color=this.shadowColor,e.opacity=this.shadowColor.alpha,this.applyMaterialOptions(e),this.targetMesh.material=e,e.userData.isShadowCatcherMaterial=!0}else{const e=this.targetMesh.material;e.color=this.shadowColor,e.opacity=this.shadowColor.alpha,this.applyMaterialOptions(e),e.userData.isShadowCatcherMaterial=!0}}applyOccluderMaterial(){if(this.targetMesh){let e=this.targetMesh.material;if(!e){const t=new Me;this.targetMesh.material=t,e=t}e.depthWrite=!0,e.stencilWrite=!0,e.colorWrite=!1,this.gameObject.renderOrder=-100}}applyMaterialOptions(e){e&&(e.depthWrite=!1,e.stencilWrite=!1)}}xS([m()],kh.prototype,"mode"),xS([m(he)],kh.prototype,"shadowColor");var pI=Object.defineProperty,Mh=(o,e,t,s)=>{for(var n=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=l(e,t,n)||n);return n&&pI(e,t,n),n};const $t=C("debugskybox");Dy("skybox-image"),Dy("environment-image");function SS(o,e,t,s,n){const r=new Vp;r.allowDrop=!1,r.allowNetworking=!1,r.background=t,r.environment=s,P.addComponent(o.scene,r);const l=c=>{typeof c=="string"&&($t&&console.log(n,"CHANGED TO",c),r.setSkybox(c))};return cb(o.domElement,n,l),r.addEventListener("destroy",()=>{$t&&console.log("Destroyed attribute remote skybox",n),hb(o.domElement,n,l)}),r.setSkybox(e)}const Wp=new Array;pe.registerCallback(me.ContextCreationStart,o=>{var e;const t=o.context,s=t.domElement.getAttribute("skybox-image")||t.domElement.getAttribute("background-image"),n=t.domElement.getAttribute("environment-image");if(s){$t&&console.log("Creating remote skybox to load "+s),((e=t.mainCameraComponent)==null?void 0:e.clearFlags)!==Ao.Skybox&&console.warn('"skybox-image"/"background-image" attribute has no effect: camera clearflags are not set to "Skybox"');const r=SS(t,s,!0,!1,"skybox-image");Wp.push(r)}if(n){$t&&console.log("Creating remote environment to load "+n);const r=SS(t,n,!1,!0,"environment-image");Wp.push(r)}}),pe.registerCallback(me.ContextCreationStart,()=>Promise.all(Wp).finally(()=>{Wp.length=0}));function CS(){return globalThis.NEEDLE_ENGINE_SKYBOX_TEXTURES||(globalThis.NEEDLE_ENGINE_SKYBOX_TEXTURES=new Array),globalThis.NEEDLE_ENGINE_SKYBOX_TEXTURES}function PS(o){const e=CS().find(t=>t.src===o);return e?($t&&console.log("Skybox: Found previously loaded texture for "+o),e.texture):null}async function mI(o){const e=await o;Wg(e,!0),Te(e)}function gI(o,e){const t=CS();for(;t.length>5;){const s=t.shift();s&&mI(s.texture)}e.then(s=>Wg(s,!1)),t.push({src:o,texture:e})}const aa=class extends I{constructor(){super(...arguments),a(this,"url"),a(this,"allowDrop",!0),a(this,"background",!0),a(this,"environment",!0),a(this,"allowNetworking",!0),a(this,"_loader"),a(this,"_prevUrl"),a(this,"_prevLoadedEnvironment"),a(this,"_prevEnvironment",null),a(this,"_prevBackground",null),a(this,"validTextureTypes",[".ktx2",".hdr",".exr",".jpg",".jpeg",".png"]),a(this,"onDragOverEvent",o=>{if(this.allowDrop&&o.dataTransfer)for(const e of o.dataTransfer.types)(e==="text/uri-list"||e==="Files")&&o.preventDefault()}),a(this,"onDrop",o=>{var e,t,s,n;if(this.allowDrop&&o.dataTransfer){for(const r of o.dataTransfer.types)if($t&&console.log(r),r==="text/uri-list"){const l=o.dataTransfer.getData(r);$t&&console.log(r,l);let c=(t=(e=new RegExp(/polyhaven.com\/asset_img\/.+?\/(?<name>.+)\.png/).exec(l))==null?void 0:e.groups)==null?void 0:t.name;if(c||(c=(n=(s=new RegExp(/polyhaven\.com\/a\/(?<name>.+)/).exec(l))==null?void 0:s.groups)==null?void 0:n.name),$t&&console.log(c),c){const h="https://dl.polyhaven.org/file/ph-assets/HDRIs/exr/1k/"+c+"_1k.exr";console.log(`[Remote Skybox] Setting skybox from url: ${h}`),o.preventDefault(),this.setSkybox(h);break}else if(this.isValidTextureType(l)){console.log("[Remote Skybox] Setting skybox from url: "+l),o.preventDefault(),this.setSkybox(l);break}else{console.warn(`[RemoteSkybox] Unknown url ${l}. If you want to load a skybox from a url, make sure it is a valid image url. Url must end with${this.validTextureTypes.join(", ")}.`);const h=new CustomEvent("dropped-unknown-url",{detail:{sender:this,event:o,url:l,apply:d=>{o.preventDefault(),this.setSkybox(d)}}});this.dispatchEvent(h)}}else if(r=="Files"){const l=o.dataTransfer.files.item(0);if($t&&console.log(r,l),!l)continue;if(!this.isValidTextureType(l.name)){console.warn(`[RemoteSkybox]: File "${l.name}" is not supported. Supported files are ${this.validTextureTypes.join(", ")}`);return}if(PS(l.name)===null){const c=new Blob([l]),h=URL.createObjectURL(c);o.preventDefault(),this.setSkybox(h,l.name)}else o.preventDefault(),this.setSkybox(l.name);break}}})}onEnable(){this.setSkybox(this.url),this.registerDropEvents()}onDisable(){var o;this.context.scene.environment===this._prevLoadedEnvironment&&(this.context.scene.environment=this._prevEnvironment,li.backgroundShouldBeTransparent(this.context)||(this.context.scene.background=this._prevBackground),this._prevLoadedEnvironment=void 0),this.unregisterDropEvents(),(o=this.context.mainCameraComponent)==null||o.applyClearFlags()}urlChangedSyncField(){this.allowNetworking&&this.url&&(this.isRemoteTexture(this.url)?this.setSkybox(this.url):$t&&console.warn(`RemoteSkybox: Not setting skybox: ${this.url} is not a remote texture. If you want to set a local texture, set allowNetworking to false.`))}async setSkybox(o,e){var t;if(!this.activeAndEnabled||(o=fI(o,this.environment,this.background),!o))return!1;if(e??(e=o),this.isValidTextureType(e)||console.warn("Potentially invalid skybox url",e,"on",this.name),$t&&console.log("Set remote skybox url: "+o),this._prevUrl===o&&this._prevLoadedEnvironment)return this.apply(),!0;(t=this._prevLoadedEnvironment)==null||t.dispose(),this._prevLoadedEnvironment=void 0,this._prevUrl=o;const s=await this.loadTexture(o,e);if(!s)return $t&&console.warn("RemoteSkybox: Failed to load texture from url",o),!1;if(!this.enabled)return $t&&console.warn("RemoteSkybox: Component is not enabled, aborting setSkybox"),!1;if(this._prevUrl!==o)return $t&&console.warn("RemoteSkybox: URL changed while loading texture, aborting setSkybox"),!1;this.url=o;const n=o.lastIndexOf("/");return s.name=o.substring(n>=0?n+1:0),this._loader instanceof _a&&(s.colorSpace=Mn),this._prevLoadedEnvironment=s,this.apply(),!0}async loadTexture(o,e){var t,s,n,r,l;if(!o)return Promise.resolve(null);e??(e=o);const c=PS(e);if(c){const g=await c;if(((s=(t=g.source)==null?void 0:t.data)==null?void 0:s.length)>0||(l=(r=(n=g.source)==null?void 0:n.data)==null?void 0:r.data)!=null&&l.length)return g}const h=e.endsWith(".exr"),d=e.endsWith(".hdr"),u=e.endsWith(".ktx2");if(h)this._loader instanceof xd||(this._loader=new xd);else if(d)this._loader instanceof Bm||(this._loader=new Bm);else if(u){if(!(this._loader instanceof aO)){const{ktx2Loader:g}=Dm(this.context.renderer);this._loader=g}}else this._loader instanceof _a||(this._loader=new _a);$t&&console.log("Loading skybox: "+o);const p=this._loader.loadAsync(o);return gI(e,p),await p}apply(){var o;const e=this._prevLoadedEnvironment;e&&(e instanceof LP||e instanceof jP||(e.mapping=DP,e.needsUpdate=!0),this.context.scene.background!==e&&(this._prevBackground=this.context.scene.background),this.context.scene.environment!==e&&(this._prevEnvironment=this.context.scene.environment),$t&&console.log("Set remote skybox",this.url,!li.backgroundShouldBeTransparent(this.context)),this.environment&&(this.context.scene.environment=e),this.background&&!li.backgroundShouldBeTransparent(this.context)&&(this.context.scene.background=e),((o=this.context.mainCameraComponent)==null?void 0:o.backgroundBlurriness)!==void 0&&(this.context.scene.backgroundBlurriness=this.context.mainCameraComponent.backgroundBlurriness))}isRemoteTexture(o){return o.startsWith("http://")||o.startsWith("https://")}isValidTextureType(o){for(const e of this.validTextureTypes)if(o.endsWith(e))return!0;return!1}registerDropEvents(){this.unregisterDropEvents(),this.context.domElement.addEventListener("dragover",this.onDragOverEvent),this.context.domElement.addEventListener("drop",this.onDrop)}unregisterDropEvents(){this.context.domElement.removeEventListener("dragover",this.onDragOverEvent),this.context.domElement.removeEventListener("drop",this.onDrop)}};Mh([W0(aa.prototype.urlChangedSyncField),m(URL)],aa.prototype,"url"),Mh([m()],aa.prototype,"allowDrop"),Mh([m()],aa.prototype,"background"),Mh([m()],aa.prototype,"environment"),Mh([m()],aa.prototype,"allowNetworking");let Vp=aa;function fI(o,e,t){const s=e&&!t;switch(o?.toLowerCase()){case"studio":return s?"https://cdn.needle.tools/static/skybox/modelviewer-Neutral-small.hdr":"https://cdn.needle.tools/static/skybox/modelviewer-Neutral.hdr";case"blurred-skybox":return s?"https://cdn.needle.tools/static/skybox/blurred-skybox-small.exr":"https://cdn.needle.tools/static/skybox/blurred-skybox.exr";case"quicklook-ar":return s?"https://cdn.needle.tools/static/skybox/QuickLook-ARMode-small.exr":"https://cdn.needle.tools/static/skybox/QuickLook-ARMode.exr";case"quicklook":return s?"https://cdn.needle.tools/static/skybox/QuickLook-ObjectMode-small.exr":"https://cdn.needle.tools/static/skybox/QuickLook-ObjectMode.exr"}return o===void 0?null:o}var yI=Object.defineProperty,Hp=(o,e,t,s)=>{for(var n=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=l(e,t,n)||n);return n&&yI(e,t,n),n},$p;const Rh=($p=class extends I{constructor(){super(...arguments),a(this,"target",null),a(this,"followFactor",.1),a(this,"rotateFactor",.1),a(this,"positionAxes",$a.All),a(this,"flipForward",!1),a(this,"_firstUpdate",!0)}onBeforeRender(){this.updateNow(!1)}updateNow(o){if(!(!this.target||this.target===this.gameObject)){if(this.followFactor>0){const e=te(this.target),t=this._firstUpdate||o?1:W.clamp01(this.context.time.deltaTime*this.followFactor),s=this.worldPosition;this.positionAxes&$a.X&&(s.x=W.lerp(s.x,e.x,t)),this.positionAxes&$a.Y&&(s.y=W.lerp(s.y,e.y,t)),this.positionAxes&$a.Z&&(s.z=W.lerp(s.z,e.z,t)),this.worldPosition=s}if(this.rotateFactor>0){const e=Se(this.target);this.flipForward&&e.premultiply($p._invertForward);const t=this._firstUpdate||o?1:W.clamp01(this.context.time.deltaTime*this.rotateFactor);this.worldQuaternion=this.worldQuaternion.slerp(e,t)}this._firstUpdate=!1}}},a($p,"_invertForward",new H().setFromAxisAngle(new x(0,1,0),Math.PI)),$p);Hp([m(E)],Rh.prototype,"target"),Hp([m()],Rh.prototype,"followFactor"),Hp([m()],Rh.prototype,"rotateFactor"),Hp([m()],Rh.prototype,"positionAxes");let Gp=Rh;var vI=Object.defineProperty,Th=(o,e,t,s)=>{for(var n=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=l(e,t,n)||n);return n&&vI(e,t,n),n};const Eh=C("debugspatialtrigger"),OS=new ho,kS=new ho;function bI(o,e){return OS.mask=o,kS.mask=e,OS.test(kS)}class vn extends I{constructor(){super(...arguments),a(this,"triggerMask",0),a(this,"onEnter"),a(this,"onStay"),a(this,"onExit"),a(this,"currentIntersected",[]),a(this,"lastIntersected",[])}start(){Eh&&console.log(this.name,this.triggerMask,this)}update(){this.currentIntersected.length=0;for(const e of qp.triggers)bI(e.triggerMask,this.triggerMask)&&e.test(this.gameObject)&&this.currentIntersected.push(e);for(let e=this.lastIntersected.length-1;e>=0;e--){const t=this.lastIntersected[e];this.currentIntersected.indexOf(t)<0&&(this.onExitTrigger(t),this.lastIntersected.splice(e,1))}for(const e of this.currentIntersected)this.lastIntersected.indexOf(e)<0&&this.onEnterTrigger(e),this.onStayTrigger(e);this.lastIntersected.length=0,this.lastIntersected.push(...this.currentIntersected)}onEnterTrigger(e){var t;Eh&&console.log("ENTER TRIGGER",this.name,e.name,this,e),e.raiseOnEnterEvent(this),(t=this.onEnter)==null||t.invoke()}onExitTrigger(e){var t;Eh&&console.log("EXIT TRIGGER",this.name,e.name),e.raiseOnExitEvent(this),(t=this.onExit)==null||t.invoke()}onStayTrigger(e){var t;e.raiseOnStayEvent(this),(t=this.onStay)==null||t.invoke()}}Th([m()],vn.prototype,"triggerMask"),Th([m(xe)],vn.prototype,"onEnter"),Th([m(xe)],vn.prototype,"onStay"),Th([m(xe)],vn.prototype,"onExit");var Ol;const MS=(Ol=class extends I{constructor(){super(...arguments),a(this,"triggerMask"),a(this,"boxHelper")}start(){Eh&&console.log(this.name,this.triggerMask,this)}onEnable(){var o;Ol.triggers.push(this),this.boxHelper||(this.boxHelper=P.addComponent(this.gameObject,Do),(o=this.boxHelper)==null||o.showHelper(null,Eh))}onDisable(){Ol.triggers.splice(Ol.triggers.indexOf(this),1)}test(o){return this.boxHelper?this.boxHelper.isInBox(o)??!1:!1}raiseOnEnterEvent(o){P.foreachComponent(this.gameObject,e=>{e!==o&&e instanceof vn&&e.onEnterTrigger(this)},!1)}raiseOnStayEvent(o){P.foreachComponent(this.gameObject,e=>{e!==o&&e instanceof vn&&e.onStayTrigger(this)},!1)}raiseOnExitEvent(o){P.foreachComponent(this.gameObject,e=>{e!==o&&e instanceof vn&&e.onExitTrigger(this)},!1)}},a(Ol,"triggers",[]),Ol);Th([m()],MS.prototype,"triggerMask");let qp=MS;var _I=Object.defineProperty,wI=(o,e,t,s)=>{for(var n=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=l(e,t,n)||n);return n&&_I(e,t,n),n};const Hi=C("debugspectator");class Xp extends I{constructor(){super(...arguments),a(this,"cam",null),a(this,"useKeys",!0),a(this,"_mode",0),a(this,"orbit",null),a(this,"_handler"),a(this,"eventSub_WebXRRequestStartEvent",null),a(this,"eventSub_WebXRStartEvent",null),a(this,"eventSub_WebXREndEvent",null),a(this,"_debug"),a(this,"_networking")}get mode(){return this._mode}set mode(e){this._mode=e}get isSpectating(){var e;return((e=this._handler)==null?void 0:e.currentTarget)!==void 0}isSpectatingUser(e){var t;return((t=this.target)==null?void 0:t.userId)===e}isFollowedBy(e){var t;return(t=this.followers)==null?void 0:t.includes(e)}get followers(){return this._networking.followers}stopSpectating(){if(this.context.isInXR){this.followSelf();return}this.target=void 0}get localId(){return this.context.connection.connectionId??"local"}set target(e){var t;if(this._handler){const s=(t=this._handler.currentTarget)==null?void 0:t.userId,n=this.context.players.getPlayerView(this.localId);e===void 0||this.context.isInXR===!1&&n?.currentObject===e.currentObject?this._handler.currentTarget!==void 0&&(this._handler.disable(),P.setActive(this.gameObject,!1),this.orbit&&(this.orbit.enabled=!0),this._networking.onSpectatedObjectChanged(e,s)):this._handler.currentTarget!==e&&(this._handler.set(e),P.setActive(this.gameObject,!0),this.orbit&&(this.orbit.enabled=!1),this._networking.onSpectatedObjectChanged(e,s))}}get target(){var e;return(e=this._handler)==null?void 0:e.currentTarget}requestAllFollowMe(){this._networking.onRequestFollowMe()}get isSpectatingSelf(){var e,t;return this.isSpectating&&((e=this.target)==null?void 0:e.currentObject)===((t=this.context.players.getPlayerView(this.localId))==null?void 0:t.currentObject)}awake(){if(this._debug=new CI(this.context,this),this._networking=new kI(this.context,this),this._networking.awake(),P.setActive(this.gameObject,!1),this.cam=P.getComponent(this.gameObject,li),!this.cam){console.warn("SpectatorCamera: Spectator camera needs camera component on the same object.",this);return}!this._handler&&this.cam&&(this._handler=new xI(this.context,this.cam,this)),this.orbit=P.getComponent(this.context.mainCamera,_e)}onDestroy(){var e,t;this.stopSpectating(),(e=this._handler)==null||e.destroy(),(t=this._networking)==null||t.destroy()}isSupportedPlatform(){const e=window.navigator.userAgent,t=/Windows|MacOS/.test(e),s=/Windows NT/.test(e)&&/Edg/.test(e)&&!/Win64/.test(e);return t&&!s}onBeforeXR(e){this.isSupportedPlatform()&&P.setActive(this.gameObject,!0)}onEnterXR(e){this.isSupportedPlatform()&&(Hi&&console.log(this.context.mainCamera),this.context.mainCamera&&this.followSelf())}onLeaveXR(e){var t,s;this.context.removeCamera(this.cam),P.setActive(this.gameObject,!1),this.orbit&&(this.orbit.enabled=!0),(t=this._handler)==null||t.set(void 0),(s=this._handler)==null||s.disable(),this.isSpectatingSelf&&this.stopSpectating()}followSelf(){this.target=this.context.players.getPlayerView(this.context.connection.connectionId),this.target||(this.context.players.setPlayerView(this.localId,this.context.mainCamera,So.Headset),this.target=this.context.players.getPlayerView(this.localId)),Hi&&console.log("Follow self",this.target)}onAfterRender(){var e,t,s;if(!this.cam)return;const n=this.context.renderer,r=n.xr.enabled;if(!n.xr.isPresenting&&!((e=this._handler)!=null&&e.currentTarget))return;(t=this._handler)==null||t.update(this._mode);const l=n.getRenderTarget();let c=null;const h=n.state;if(!l){if(!n.state.bindFramebuffer||!h.bindXRFramebuffer)return;c=n._framebuffer,h.bindXRFramebuffer(null)}this.setAvatarFlagsBeforeRender();const d=this.context.mainCameraComponent;if(d){const g=d.backgroundColor;g&&n.setClearColor(g,g.alpha),this.cam.backgroundColor=g,this.cam.clearFlags=d.clearFlags,this.cam.nearClipPlane=d.nearClipPlane,this.cam.farClipPlane=d.farClipPlane}else n.setClearColor(new ae(1,1,1));n.setRenderTarget(null),n.xr.enabled=!1;const u=(s=this.cam)==null?void 0:s.threeCamera;this.context.updateAspect(u);const p=n.xr.isPresenting;n.xr.isPresenting=!1,n.setSize(this.context.domWidth,this.context.domHeight),n.render(this.context.scene,u),n.xr.isPresenting=p,n.xr.enabled=r,l?n.setRenderTarget(l):h.bindXRFramebuffer&&h.bindXRFramebuffer(c),this.resetAvatarFlags()}setAvatarFlagsBeforeRender(){const e=this._mode===0;for(const t of ci.instances)if(t.avatar&&"isLocalAvatar"in t.avatar&&"flags"in t.avatar){let s=rn.All;this.isSpectatingSelf&&(s=e&&t.avatar.isLocalAvatar?rn.FirstPerson:rn.ThirdPerson);const n=t.avatar.flags;if(!n)continue;for(const r of n)r.UpdateVisible(s)}}resetAvatarFlags(){var e;for(const t of ci.instances)if(t.avatar&&"flags"in t.avatar){const s=t.avatar.flags;if(!s)continue;for(const n of s)"isLocalAvatar"in t.avatar&&(e=t.avatar)!=null&&e.isLocalAvatar?n.UpdateVisible(rn.FirstPerson):n.UpdateVisible(rn.ThirdPerson)}}}wI([m()],Xp.prototype,"useKeys");class xI{constructor(e,t,s){a(this,"context"),a(this,"cam"),a(this,"spectator"),a(this,"follow"),a(this,"target"),a(this,"view"),a(this,"currentObject"),this.context=e,this.cam=t,this.spectator=s}get currentTarget(){return this.view}set(e){const t=e?.currentObject;if(!t){this.spectator.stopSpectating();return}t!==this.currentObject&&(this.currentObject=t,this.view=e,this.follow||(this.follow=P.addComponent(this.cam.gameObject,Gp)),this.target||(this.target=new E),t.add(this.target),this.follow.enabled=!0,this.follow.target=this.target,Hi&&console.log("FOLLOW",t),this.context.isInXR?this.context.removeCamera(this.cam):this.context.setCurrentCamera(this.cam))}disable(){Hi&&console.log("STOP FOLLOW",this.currentObject),this.view=void 0,this.currentObject=void 0,this.context.removeCamera(this.cam),this.follow&&(this.follow.enabled=!1)}destroy(){var e;(e=this.target)==null||e.removeFromParent(),this.follow&&P.destroy(this.follow)}update(e){var t,s,n,r,l,c;if(((t=this.currentTarget)==null?void 0:t.isConnected)===!1||((s=this.currentTarget)==null?void 0:s.removed)===!0){Hi&&console.log("Target disconnected or timeout",this.currentTarget),this.spectator.stopSpectating();return}this.currentTarget&&((n=this.currentTarget)==null?void 0:n.currentObject)!==this.currentObject&&(Hi&&console.log("Target changed",this.currentObject,"to",this.currentTarget.currentObject),this.set(this.currentTarget));const h=this.context.mainCamera;if(h){const u=this.cam.threeCamera;(u.near!==h.near||u.far!==h.far)&&(u.near=h.near,u.far=h.far,u.updateProjectionMatrix())}const d=(r=this.follow)==null?void 0:r.target;if(!(!d||!this.follow)){switch(e){case 0:((l=this.view)==null?void 0:l.viewDevice)!==So.Browser?(this.follow.followFactor=5,this.follow.rotateFactor=5):(this.follow.followFactor=50,this.follow.rotateFactor=50),d.position.set(0,0,0);break;case 1:this.follow.followFactor=3,this.follow.rotateFactor=2,d.position.set(0,.5,1.5);break}this.follow.flipForward=!1,((c=this.view)==null?void 0:c.viewDevice)!==So.Browser?d.quaternion.copy(SI):d.quaternion.identity()}}}const SI=new H().setFromAxisAngle(new x(0,1,0),Math.PI);class CI{constructor(e,t){a(this,"context"),a(this,"spectator"),this.context=e,this.spectator=t,console.log("[Spectator Camera] Click other avatars or cameras to follow them. Press ESC to exit spectator mode."),this.context.domElement.addEventListener("keydown",n=>{!this.spectator.useKeys||n.key==="Escape"&&this.spectator.stopSpectating()});let s=0;this.context.input.addEventListener(Fe.PointerDown,n=>{s=this.context.time.time}),this.context.input.addEventListener(Fe.PointerUp,n=>{const r=this.context.time.time-s;r>1?this.spectator.stopSpectating():this.context.input.getPointerClicked(0)&&r<.3&&this.trySelectObject()})}trySelectObject(){const e=new Qs;e.setMask(16777215);const t=this.context.physics.raycast(e);if(Hi&&console.log(...t),t!=null&&t.length)for(const s of t){if(s.distance<.2)continue;const n=s.object,r=P.getComponentInParent(n,ci),l=r?.connectionId;if(l){const c=this.context.players.getPlayerView(l);this.spectator.target=c,Hi&&console.log("spectate",l,r);break}}}}class PI{constructor(e,t,s){a(this,"guid"),a(this,"dontSave",!0),a(this,"targetUserId"),a(this,"stoppedFollowing"),this.guid=e,this.targetUserId=t,this.stoppedFollowing=s}}class OI{constructor(e,t){a(this,"guid"),a(this,"userId"),this.guid=e.guid,this.userId=t}}class kI{constructor(e,t){a(this,"followers",[]),a(this,"context"),a(this,"spectator"),a(this,"_followerEventMethod"),a(this,"_requestFollowMethod"),a(this,"_joinedRoomMethod"),a(this,"_lastRequestFollowUser"),a(this,"_enforceFollowInterval"),this.context=e,this.spectator=t,this._followerEventMethod=this.onFollowerEvent.bind(this),this._requestFollowMethod=this.onRequestFollowEvent.bind(this),this._joinedRoomMethod=this.onUserJoinedRoom.bind(this)}awake(){this.context.connection.beginListen("spectator-follower-changed",this._followerEventMethod),this.context.connection.beginListen("spectator-request-follow",this._requestFollowMethod),this.context.connection.beginListen(ie.JoinedRoom,this._joinedRoomMethod),this.context.domElement.addEventListener("keydown",e=>{this.spectator.useKeys&&(e.key==="f"?this.onRequestFollowMe():e.key==="Escape"&&this.onRequestFollowMe(!0))})}destroy(){this.context.connection.stopListen("spectator-follower-changed",this._followerEventMethod),this.context.connection.stopListen("spectator-request-follow",this._requestFollowMethod),this.context.connection.stopListen(ie.JoinedRoom,this._joinedRoomMethod)}onSpectatedObjectChanged(e,t){if(Hi&&console.log(this.context.connection.connectionId,"onSpectatedObjectChanged",e,t),this.context.connection.connectionId){const s=e?.userId===void 0,n=s?t:e?.userId,r=new PI(this.context.connection.connectionId,n,s);this.context.connection.send("spectator-follower-changed",r)}}onRequestFollowMe(e=!1){if(Hi&&console.log("Request follow",this.context.connection.connectionId),this.context.connection.connectionId){this.spectator.stopSpectating();const t=e?void 0:this.context.connection.connectionId,s=new OI(this.spectator,t);this.context.connection.send("spectator-request-follow",s)}}onUserJoinedRoom(){C("followme")&&this.onRequestFollowMe()}onFollowerEvent(e){const t=e.targetUserId,s=e.guid;if(Hi&&console.log(e),t===this.context.connection.connectionId)if(e.stoppedFollowing){const n=this.followers.indexOf(s);n!==-1&&(this.followers.splice(n,1),this.removeDisconnectedFollowers(),console.log(s,"unfollows you",this.followers.length))}else this.followers.includes(s)||(this.followers.push(s),this.removeDisconnectedFollowers(),console.log(s,"follows you",this.followers.length))}removeDisconnectedFollowers(){for(let e=this.followers.length-1;e>=0;e--){const t=this.followers[e];this.context.connection.userIsInRoom(t)===!1&&this.followers.splice(e,1)}}onRequestFollowEvent(e){if(this._lastRequestFollowUser=e,e.userId===this.context.connection.connectionId)this.spectator.stopSpectating();else if(e.userId===void 0)this.spectator.stopSpectating();else{const t=this.context.players.getPlayerView(e.userId);if(t)this.spectator.target=t;else return Hi&&console.warn("Could not find view",e.userId),this.enforceFollow(),!1}return!0}enforceFollow(){this._enforceFollowInterval||(this._enforceFollowInterval=setInterval(()=>{this._lastRequestFollowUser===void 0||this._lastRequestFollowUser.userId&&this.spectator.isFollowedBy(this._lastRequestFollowUser.userId)?(clearInterval(this._enforceFollowInterval),this._enforceFollowInterval=void 0):(Hi&&console.log("REQUEST FOLLOW AGAIN",this._lastRequestFollowUser.userId),this.onRequestFollowEvent(this._lastRequestFollowUser))},1e3))}}class Sn{constructor(){a(this,"bb",null),a(this,"bb_pos",0)}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsSyncedCameraModel(e,t){return(t||new Sn).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSyncedCameraModel(e,t){return e.setPosition(e.position()+Gv),(t||new Sn).__init(e.readInt32(e.position())+e.position(),e)}userId(e){const t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}guid(e){const t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__string(this.bb_pos+t,e):null}dontSave(){const e=this.bb.__offset(this.bb_pos,8);return e?!!this.bb.readInt8(this.bb_pos+e):!1}pos(e){const t=this.bb.__offset(this.bb_pos,10);return t?(e||new Dr).__init(this.bb_pos+t,this.bb):null}rot(e){const t=this.bb.__offset(this.bb_pos,12);return t?(e||new Dr).__init(this.bb_pos+t,this.bb):null}static startSyncedCameraModel(e){e.startObject(5)}static addUserId(e,t){e.addFieldOffset(0,t,0)}static addGuid(e,t){e.addFieldOffset(1,t,0)}static addDontSave(e,t){e.addFieldInt8(2,+t,0)}static addPos(e,t){e.addFieldStruct(3,t,0)}static addRot(e,t){e.addFieldStruct(4,t,0)}static endSyncedCameraModel(e){return e.endObject()}static finishSyncedCameraModelBuffer(e,t){e.finish(t)}static finishSizePrefixedSyncedCameraModelBuffer(e,t){e.finish(t,void 0,!0)}}var MI=Object.defineProperty,RI=(o,e,t,s)=>{for(var n=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=l(e,t,n)||n);return n&&MI(e,t,n),n};const Qp="SCAM";Pg(Qp,Sn.getRootAsSyncedCameraModel);const $i=new Um;class TI{constructor(e,t){a(this,"userId"),a(this,"guid"),this.guid=t,this.userId=e}send(e,t){if(e){$i.clear();const s=$i.createString(this.guid),n=$i.createString(this.userId);Sn.startSyncedCameraModel($i),Sn.addGuid($i,s),Sn.addUserId($i,n);const r=te(e),l=Td(e);Sn.addPos($i,Dr.createVec3($i,r.x,r.y,r.z)),Sn.addRot($i,Dr.createVec3($i,l.x,l.y,l.z));const c=Sn.endSyncedCameraModel($i);$i.finish(c,Qp),t.sendBinary($i.asUint8Array())}}}var Ah;const RS=(Ah=class extends I{constructor(){super(...arguments),a(this,"cameraPrefab",null),a(this,"_lastWorldPosition"),a(this,"_lastWorldQuaternion"),a(this,"_model",null),a(this,"_needsUpdate",!0),a(this,"_lastUpdateTime",0),a(this,"remoteCams",{}),a(this,"userToCamMap",{}),a(this,"_camTimeoutInSeconds",10),a(this,"_receiveCallback",null)}getCameraObject(o){const e=this.userToCamMap[o];return e?this.remoteCams[e].obj:null}async awake(){this._lastWorldPosition=this.worldPosition.clone(),this._lastWorldQuaternion=this.worldQuaternion.clone(),this.cameraPrefab&&("uri"in this.cameraPrefab&&(this.cameraPrefab=await this.cameraPrefab.instantiate(this.gameObject)),this.cameraPrefab&&"isObject3D"in this.cameraPrefab&&(this.cameraPrefab.visible=!1))}onEnable(){this._receiveCallback=this.context.connection.beginListenBinary(Qp,this.onReceivedRemoteCameraInfoBin.bind(this))}onDisable(){this.context.connection.stopListenBinary(Qp,this._receiveCallback)}update(){for(const s in this.remoteCams){const n=this.remoteCams[s],r=this.context.time.realtimeSinceStartup-n.lastUpdate;if(!n||r>this._camTimeoutInSeconds){F()&&console.log("Remote cam timeout",s),n!=null&&n.obj&&P.destroy(n.obj),delete this.remoteCams[s],n&&delete this.userToCamMap[n.userId],Ah.instances.push(n),this.context.players.removePlayerView(n.userId,So.Browser);continue}}if(this.context.isInXR)return;const o=this.context.mainCamera;if(o===null){this.enabled=!1;return}if(!this.context.connection.isConnected||this.context.connection.connectionId===null)return;this._model===null&&(this._model=new TI(this.context.connection.connectionId,this.context.connection.connectionId+"_camera"));const e=te(o),t=Se(o);(e.distanceTo(this._lastWorldPosition)>.001||t.angleTo(this._lastWorldQuaternion)>.01)&&(this._needsUpdate=!0),this._lastWorldPosition.copy(e),this._lastWorldQuaternion.copy(t),!((!this._needsUpdate||this.context.time.frameCount%2!==0)&&!(this.context.time.realtimeSinceStartup-this._lastUpdateTime>this._camTimeoutInSeconds*.5))&&(this._lastUpdateTime=this.context.time.realtimeSinceStartup,this._needsUpdate=!1,this._model.send(o,this.context.connection),this.context.isInXR||this.context.players.setPlayerView(this.context.connection.connectionId,o,So.Browser))}onReceivedRemoteCameraInfoBin(o){const e=o.guid();if(!e)return;const t=o.userId();if(!t||!this.context.connection.userIsInRoom(t)||!this.cameraPrefab)return;let s=this.remoteCams[e];if(!s)if("isObject3D"in this.cameraPrefab){const c=new Fs;c.context=this.context;const h=P.instantiate(this.cameraPrefab,c);s=this.remoteCams[e]={obj:h,lastUpdate:this.context.time.realtimeSinceStartup,userId:t},s.obj.visible=!0,this.gameObject.add(h),this.userToCamMap[t]=e,Ah.instances.push(s);const d=P.getOrAddComponent(h,ci);d.connectionId=t,d.avatar=h}else return;const n=s.obj;this.context.players.setPlayerView(t,n,So.Browser),s.lastUpdate=this.context.time.realtimeSinceStartup,ds.markDirty(n);const r=o.pos();r&&fr(n,r.x(),r.y(),r.z());const l=o.rot();l&&Yl(n,l.x(),l.y(),l.z())}},a(Ah,"instances",[]),Ah);RI([m([E,ce])],RS.prototype,"cameraPrefab");let By=RS;var EI=Object.defineProperty,AI=Object.getOwnPropertyDescriptor,rr=(o,e,t,s)=>{for(var n=s>1?void 0:s?AI(e,t):e,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=(s?l(e,t,n):l(n))||n);return s&&n&&EI(e,t,n),n};const Fy="view",Uy=C("debugsyncedroom");class Ls extends I{constructor(){super(...arguments),a(this,"roomName",""),a(this,"urlParameterName","room"),a(this,"joinRandomRoom"),a(this,"requireRoomParameter",!1),a(this,"autoRejoin",!0),a(this,"createJoinButton",!0),a(this,"createViewOnlyButton",!1),a(this,"_lastJoinedRoom"),a(this,"_roomPrefix",""),a(this,"_lastPingTime",0),a(this,"_lastRoomTime",-1),a(this,"_userWantsToBeInARoom",!1),a(this,"_roomButton"),a(this,"_roomButtonIconJoin"),a(this,"_roomButtonIconLeave"),a(this,"updateRoomButtonState",()=>{var e,t;this._roomButton&&(this.context.connection.isInRoom?(this._roomButton.title="Leave the networked room",this._roomButton.textContent="Leave Room",(e=this._roomButtonIconJoin)==null||e.remove(),this._roomButton.prepend(this._roomButtonIconLeave)):(this._roomButton.title="Create or join a networked room",this._roomButton.textContent="Join Room",(t=this._roomButtonIconLeave)==null||t.remove(),this._roomButton.prepend(this._roomButtonIconJoin)))}),a(this,"_viewOnlyButton"),a(this,"onCreateViewOnlyButton",()=>{if(!this._viewOnlyButton){const e=document.createElement("button");this._viewOnlyButton=e,e.classList.add("view-only-button"),e.setAttribute("priority","90"),e.onclick=()=>{var t;const s=this.getViewOnlyUrl();s!=null&&s.length?navigator.canShare({url:s})?(t=navigator.share({url:s}))==null||t.catch(n=>{console.warn(n)}):(navigator.clipboard.writeText(s),Be("View only URL copied to clipboard")):be("Could not create view only URL")},e.title="Copy the view only URL: A page accessed by the view only URL can not be modified by visiting users.",e.textContent="Share View URL",e.prepend(kt("visibility"))}this.context.menu.appendChild(this._viewOnlyButton)})}get currentRoomName(){return C(Fy)||C(this.urlParameterName)}set roomPrefix(e){this._roomPrefix=e}get roomPrefix(){return this._roomPrefix}awake(){var e;this.joinRandomRoom===void 0&&((e=this.roomName)==null?void 0:e.length)<=0&&(this.joinRandomRoom=!0),Uy&&console.log(`SyncedRoom roomName:${this.roomName}, urlParamName:${this.urlParameterName}, joinRandomRoom:${this.joinRandomRoom}`)}onEnable(){const e=C(Fy);if(e&&typeof e=="string"&&e.length>0){console.log("Join as viewer"),this.context.connection.joinRoom(e,!0);return}if(this.tryJoinRoom(),this.createJoinButton){const t=this.createRoomButton();this.context.menu.appendChild(t)}this.createViewOnlyButton&&this.onEnableViewOnlyButton()}onDisable(){var e;(e=this._roomButton)==null||e.remove(),this.onDisableViewOnlyButton(),this.roomName&&this.roomName.length>0&&this.context.connection.leaveRoom(this.roomName)}onDestroy(){this.destroyRoomButton()}tryJoinRandomRoom(){this.setRandomRoomUrlParameter(),this.tryJoinRoom()}tryJoinRoom(e=0){var t;e===void 0&&(e=0);let s=!1;if(((t=this.urlParameterName)==null?void 0:t.length)>0){const n=C(this.urlParameterName);if(n&&(typeof n=="string"||typeof n=="number")){s=!0;const r=ab(n.toString());this.roomName=r}else if(this.joinRandomRoom&&(console.log("No room name found in url, generating random one"),this.setRandomRoomUrlParameter(),e<1))return this.tryJoinRoom(e+1)}else this.joinRandomRoom&&(this.roomName===null||this.roomName===void 0||this.roomName.length<=0)&&(this.roomName=this.generateRoomName());return this.requireRoomParameter&&!s?((Uy||F())&&console.warn('[SyncedRoom] Missing required room parameter "'+this.urlParameterName+`" in url - will not connect.
1358
+ To allow joining a room without a query parameter you can set "requireRoomParameter" to false.`),!1):(this.context.connection.isConnected||this.context.connection.connect(),this._lastJoinedRoom=this.roomName,this._roomPrefix&&(this.roomName=this._roomPrefix+this.roomName),this.roomName.length<=0?(console.warn(`[SyncedRoom] Room name is not set so we can not join a networked room.
1359
+ Please choose one of the following options to fix this:
1360
+ A) Set a room name in the SyncedRoom component
1361
+ B) Set a room name in the URL parameter "?`+this.urlParameterName+`=my_room"
1362
+ C) Set "joinRandomRoom" to true`),!1):(Uy&&console.log("Join "+this.roomName),this._userWantsToBeInARoom=!0,this.context.connection.joinRoom(this.roomName),!0))}update(){this.context.connection.isConnected&&(this.context.time.time-this._lastPingTime>3&&(this._lastPingTime=this.context.time.time,this.context.connection.sendPing()),this.context.connection.isInRoom&&(this._lastRoomTime=this.context.time.time)),this._lastRoomTime>0&&this.context.time.time-this._lastRoomTime>.3&&(this._lastRoomTime=-1,this.autoRejoin?this._userWantsToBeInARoom&&(console.log("Disconnected from networking backend - attempt reconnecting now"),this.tryJoinRoom()):F()&&console.warn("You are not connected to a room anymore (possibly because the tab was inactive for too long and the server kicked you?)"))}getViewOnlyUrl(){if(this.context.connection.isConnected&&this.context.connection.currentRoomViewId){const e=window.location.search,t=new URLSearchParams(e);return t.has(this.urlParameterName)&&t.delete(this.urlParameterName),t.set(Fy,this.context.connection.currentRoomViewId),window.location.origin+window.location.pathname+"?"+t.toString()}return null}setRandomRoomUrlParameter(){const e=Vl(),t=this.generateRoomName();C(this.urlParameterName)?e.set(this.urlParameterName,t):e.append(this.urlParameterName,t),$m(t,e)}generateRoomName(){let e="";for(let t=0;t<6;t++)e+=Math.floor(Math.random()*10).toFixed(0);return e}createRoomButton(){if(this._roomButton)return this._roomButton;const e=document.createElement("button");return this._roomButton=e,e.classList.add("create-room-button"),e.setAttribute("priority","90"),e.onclick=()=>{if(this.context.connection.isInRoom)this.urlParameterName&&Hl(this.urlParameterName,null),this.context.connection.leaveRoom(),this._userWantsToBeInARoom=!1;else{if(this.urlParameterName){const t=C(this.urlParameterName);(!t||t===!0)&&(this._lastJoinedRoom?Hl(this.urlParameterName,this._lastJoinedRoom):this.setRandomRoomUrlParameter())}this.tryJoinRoom()}},this._roomButtonIconJoin=kt("group"),this._roomButtonIconLeave=kt("group_off"),this.updateRoomButtonState(),this.context.connection.beginListen(ie.JoinedRoom,this.updateRoomButtonState),this.context.connection.beginListen(ie.LeftRoom,this.updateRoomButtonState),e}destroyRoomButton(){this.context.connection.stopListen(ie.JoinedRoom,this.updateRoomButtonState),this.context.connection.stopListen(ie.LeftRoom,this.updateRoomButtonState)}onEnableViewOnlyButton(){this.context.connection.isConnected?this.onCreateViewOnlyButton():(this.context.connection.stopListen(ie.JoinedRoom,this.onCreateViewOnlyButton),this.context.connection.beginListen(ie.JoinedRoom,this.onCreateViewOnlyButton))}onDisableViewOnlyButton(){var e;this.context.connection.stopListen(ie.JoinedRoom,this.onCreateViewOnlyButton),(e=this._viewOnlyButton)==null||e.remove()}}rr([m()],Ls.prototype,"roomName",2),rr([m()],Ls.prototype,"urlParameterName",2),rr([m()],Ls.prototype,"joinRandomRoom",2),rr([m()],Ls.prototype,"requireRoomParameter",2),rr([m()],Ls.prototype,"autoRejoin",2),rr([m()],Ls.prototype,"createJoinButton",2),rr([m()],Ls.prototype,"createViewOnlyButton",2),rr([m()],Ls.prototype,"roomPrefix",1);function II(){const o=C("testwindowcount")||0;o&&o>0&&LI(o)}function LI(o){if(C("testwindow"))return null;const e=new URL(window.location.href);Hm(e.searchParams,zT,1),Hm(e.searchParams,"testwindow",1);const t=e.toString(),s=[];window.onbeforeunload=()=>{for(const h of s)h.close()};const n=.05,r=128;let l=0,c=0;for(let h=0;h<o;h++){l*r+r*.01>=window.innerWidth&&(c+=1,l=0);const d=l*(r*(1+n))+window.screenLeft,u=c*(r*(1+n))+window.screenTop+90+60*c;l+=1;const p=window.open(t,"test window "+h,`popup=yes width=${r} height=${r} top=${u} left=${d}`);if(!p){console.warn("Failed to open window");continue}s.push(p),p.onload=()=>{p.onbeforeunload=()=>{for(let g=0;g<s.length;g++){const f=s[g];f!==p&&f.close()}s.length=0}}}return s}class zy extends I{awake(){II()}}class Ny extends I{constructor(){super(...arguments),a(this,"transformsPerFrame",10),a(this,"interval",0),a(this,"useFlatbuffers",!0),a(this,"builder",null),a(this,"models",null)}awake(){if(this.useFlatbuffers)this.context.connection.beginListenBinary(Ac,e=>{});else{this.models=[];for(let e=0;e<this.transformsPerFrame;e++)this.models.push(new TS(this.context.connection.connectionId+"_simulatedTransform_"+e,this))}}update(){if(this.context.connection.isConnected){if(this.useFlatbuffers){if(!this.context.connection.connectionId||this.context.time.frameCount%this.interval!==0)return;this.builder===null&&(this.builder=new Um(1024));const e=this.builder;for(let t=0;t<this.transformsPerFrame;t++){e.clear();const s=vx(this.context.connection.connectionId,this);this.context.connection.sendBinary(s)}}else if(this.models)for(let e=0;e<this.models.length;e++){const t=this.models[e];t.dontSave=!0,t.update(this,null),this.context.connection.send("TestSimulateUserData-"+e,t)}}}}class TS{constructor(e,t){a(this,"guid"),a(this,"fast",!1),a(this,"position"),a(this,"rotation"),a(this,"velocity"),a(this,"dontSave"),this.guid=e,this.position={x:0,y:0,z:0},this.rotation={x:0,y:0,z:0,w:0},this.update(t,null)}isValid(){return this.fast!==void 0||this.position!==void 0||this.rotation!==void 0||this.velocity!==void 0}update(e,t){const s=e.worldPosition;this.position.x=s.x,this.position.y=s.y,this.position.z=s.z;const n=e.worldQuaternion;if(this.rotation.x=n.x,this.rotation.y=n.y,this.rotation.z=n.z,this.rotation.w=n.w,this.fast=!1,t){const r=t.getVelocity();this.velocity===void 0&&(this.velocity={x:0,y:0,z:0}),this.velocity.x=r.x,this.velocity.y=r.y,this.velocity.z=r.z}}}a(TS,"temp",new x);var jI=Object.defineProperty,Yp=(o,e,t,s)=>{for(var n=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=l(e,t,n)||n);return n&&jI(e,t,n),n};const DI=C("debugsignals");class Kp{constructor(){a(this,"guid")}}Yp([m()],Kp.prototype,"guid");class Ih{constructor(){a(this,"signal"),a(this,"reaction")}}Yp([m(Kp)],Ih.prototype,"signal"),Yp([m(xe)],Ih.prototype,"reaction");var js;const ES=(js=class extends I{constructor(){super(...arguments),a(this,"events")}static invoke(o){if(js.receivers[o]){const e=js.receivers[o];if(!e)return;for(const t of e)t.invoke(o)}}awake(){DI&&console.log("SignalReceiver awake",this)}onEnable(){if(this.events)for(const o of this.events)js.receivers[o.signal.guid]||(js.receivers[o.signal.guid]=[]),js.receivers[o.signal.guid].push(this)}onDisable(){if(this.events){for(const o of this.events)if(js.receivers[o.signal.guid]){const e=js.receivers[o.signal.guid].indexOf(this);e>=0&&js.receivers[o.signal.guid].splice(e,1)}}}invoke(o){if(!this.events||!Array.isArray(this.events))return;const e=typeof o=="object"?o.guid:o;for(const t of this.events)if(t.signal.guid===e)try{if(t.reaction){if(!t.reaction.invoke){console.warn("Missing invoke - possibly a serialization error",t,this);continue}}else{console.warn("Missing reaction for signal",t,this);continue}t.reaction.invoke()}catch(s){console.error(s)}}},a(js,"receivers",{}),js);Yp([m(Ih)],ES.prototype,"events");let Lh=ES;var Gi=(o=>(o.Activation="ActivationTrack",o.Animation="AnimationTrack",o.Audio="AudioTrack",o.Control="ControlTrack",o.Marker="MarkerTrack",o.Signal="SignalTrack",o))(Gi||{}),bn=(o=>(o[o.None=0]="None",o[o.Hold=1]="Hold",o[o.Loop=2]="Loop",o[o.PingPong=3]="PingPong",o[o.Continue=4]="Continue",o))(bn||{}),Wy=(o=>(o.Signal="SignalEmitter",o))(Wy||{});const _n=C("debugtimeline");class jh{constructor(){a(this,"director"),a(this,"track")}get muted(){return this.track.muted}set muted(e){var t;e!==this.track.muted&&(this.track.muted=e,(t=this.onMuteChanged)==null||t.call(this))}*forEachClip(e=!1){var t;if((t=this.track)!=null&&t.clips)if(e)for(let s=this.track.clips.length-1;s>=0;s--)yield this.track.clips[s];else for(const s of this.track.clips)yield s}getClipTime(e,t){return t.clipIn+(e-t.start)*t.timeScale}getClipTimeNormalized(e,t){return(e-t.start)/t.duration}evaluateWeight(e,t,s,n=!0){if(t<0||t>=s.length)return 0;const r=s[t];if(n||e>=r.start&&e<=r.end){let l=1;if(r.easeInDuration>0){const c=Math.min((e-r.start)/r.easeInDuration,1);l*=c}if(r.easeOutDuration>0){const c=Math.min((r.end-e)/r.easeOutDuration,1);l*=c}return l}return 0}}class BI{constructor(e){a(this,"clip"),a(this,"rootPositionOffset"),a(this,"rootQuaternionOffset"),a(this,"rootStartPosition"),a(this,"rootEndPosition"),a(this,"rootStartQuaternion"),a(this,"rootEndQuaternion");const t=e.getClip();this.clip=t;const s=e.getRoot(),n=s.name+".position",r=s.name+".quaternion";_n&&console.log(t.name,t.tracks,n);for(const l of t.tracks)if(!(l.times.length<=0)){if(l.name.endsWith(n))this.rootStartPosition=new x().fromArray(l.values,0),this.rootEndPosition=new x().fromArray(l.values,l.values.length-3),this.rootPositionOffset=this.rootEndPosition.clone().sub(this.rootStartPosition),_n&&console.log(this.rootPositionOffset);else if(l.name.endsWith(r)&&(this.rootStartQuaternion=new H().fromArray(l.values,0),this.rootEndQuaternion=new H().fromArray(l.values,l.values.length-4),this.rootQuaternionOffset=this.rootEndQuaternion.clone().multiply(this.rootStartQuaternion),_n)){const c=new jt().setFromQuaternion(this.rootQuaternionOffset);console.log("ROT",c)}}}get hasOffsets(){return this.rootPositionOffset!==void 0||this.rootQuaternionOffset!==void 0}}class Zp extends jh{constructor(){super(...arguments),a(this,"models",[]),a(this,"trackOffset"),a(this,"target"),a(this,"mixer"),a(this,"clips",[]),a(this,"actions",[]),a(this,"weight",1),a(this,"_actionOffsets",[]),a(this,"_didBind",!1),a(this,"_animator",null),a(this,"_useclipOffsets",!0),a(this,"_totalOffsetPosition",new x),a(this,"_totalOffsetRotation",new H),a(this,"_totalOffsetPosition2",new x),a(this,"_totalOffsetRotation2",new H),a(this,"_summedPos",new x),a(this,"_tempPos",new x),a(this,"_summedRot",new H),a(this,"_tempRot",new H),a(this,"_clipRotQuat",new H)}onDisable(){var e;(e=this.mixer)==null||e.stopAllAction()}onDestroy(){this.director.context.animations.unregisterAnimationMixer(this.mixer)}onStateChanged(){this._animator&&cx(this._animator.gameObject,this,this.director.isPlaying)}createHooks(e,t){var s,n;if(((s=t.tracks)==null?void 0:s.length)<=0){console.warn("No tracks in AnimationClip",t);return}const r=t.tracks[0].name.split("."),l=r[r.length-2],c=l+".position",h=l+".quaternion";let d=!1,u=!1;for(const p of t.tracks)p.name.endsWith(c)?(d=!0,this.createPositionInterpolant(t,e,p)):p.name.endsWith(h)&&(u=!0,this.createRotationInterpolant(t,e,p));if(!d||!u){const p=(n=this.mixer)==null?void 0:n.getRoot(),g=t.tracks[0],f=g.name.lastIndexOf("."),y=g.name.substring(0,f),b=y.substring(y.lastIndexOf(".")+1),v=p.getObjectByName(b);if(v)if(d){if(!u){const _=t.tracks[0].name.substring(0,f)+".quaternion";_n&&console.warn("Create quaternion track",b,v);const w=v.quaternion,S=new FP(_,[0,t.duration],[w.x,w.y,w.z,w.w,w.x,w.y,w.z,w.w]);t.tracks.push(S),this.createRotationInterpolant(t,e,S)}}else{const _=y+".position";_n&&console.warn("Create position track",b,v);const w=v.position,S=new BP(_,[0,t.duration],[w.x,w.y,w.z,w.x,w.y,w.z]);t.tracks.push(S),this.createPositionInterpolant(t,e,S)}}}bind(){if(!this._didBind){this._didBind=!0,_n&&console.log(this.models),this.mixer?this.target=this.mixer.getRoot():console.warn("No mixer was assigned to animation track");for(const e of this.actions){const t=new BI(e);this._actionOffsets.push(t)}this.target&&(this._animator=P.getComponent(this.target,Mt)??null,this._animator&&cx(this._animator.gameObject,this,!0));for(const e of this.models){const t=e.asset,s=t.position,n=t.rotation;s&&s.x!==void 0&&(s.isVector3||(t.position=new x(s.x,s.y,s.z)),n.isQuaternion||(t.rotation=new H(n.x,n.y,n.z,n.w)))}this.ensureTrackOffsets()}}ensureTrackOffsets(){if(this.trackOffset){const e=this.trackOffset.position;e&&(e.isVector3||(this.trackOffset.position=new x(e.x,e.y,e.z)));const t=this.trackOffset.rotation;t&&(t.isQuaternion||(this.trackOffset.rotation=new H(t.x,t.y,t.z,t.w)))}}evaluate(e){var t,s,n,r,l,c,h;if(this.track.muted||!this.mixer)return;this.bind(),this._totalOffsetPosition.set(0,0,0),this._totalOffsetRotation.set(0,0,0,1),this._totalOffsetPosition2.set(0,0,0),this._totalOffsetRotation2.set(0,0,0,1);let d=0,u=0,p=!1,g=!1,f=0;for(let y=0;y<this.clips.length;y++){const b=this.models[y],v=this.actions[y],_=b.asset;v.weight=0;const w=e>=b.start&&e<=b.end,S=b.preExtrapolationMode,k=b.postExtrapolationMode,M=y<this.clips.length-1?this.models[y+1]:null;let T=w,L=!1;if(!T&&!p&&b.end<e&&k!==bn.None?(!M||M.start>e)&&(T=!0,p=!0):y==0&&!T&&!g&&b.start>e&&S!==bn.None&&(!M||M.start<e)&&(T=!0,L=!0,g=!0),T){let B=this.weight;B*=this.evaluateWeight(e,y,this.models,T),B*=this.director.weight;let z=w;if(L)switch(S){case bn.Hold:break;case bn.Loop:e+=b.start,z=!0;break;default:e+=b.start,z=!0;break}let D=this.getClipTime(e,b),V=0;const $=_.duration;if(L&&S===bn.Hold&&(D=0),z){if(_.loop)for(V+=Math.floor(D/($+1e-6));D>$;)D-=$}else if(!w&&p)switch(k){case bn.Hold:D=this.getClipTime(b.end,b);break;case bn.Loop:D%=$;break;case bn.PingPong:const j=Math.floor(D/$)%2!==0;D%=$,j&&(D=$-D);break}b.reversed===!0?v.time=v.getClip().duration-D:v.time=D,v.timeScale=0;const U=Math.max(0,B);if(v.weight=U,f+=U,v.clampWhenFinished=!1,v.isRunning()||v.play(),this._useclipOffsets){const j=d==0?this._totalOffsetPosition:this._totalOffsetPosition2,Q=d==0?this._totalOffsetRotation:this._totalOffsetRotation2;d<1&&(u=1-B),d+=1;const J=this._summedPos.set(0,0,0),oe=this._tempPos.set(0,0,0),re=this._summedRot.identity(),ge=this._tempRot.identity(),je=_.rotation;je&&(this._clipRotQuat.identity(),this._clipRotQuat.slerp(je,B));const $e=this._actionOffsets[y];if($e.hasOffsets)for(let ms=0;ms<V;ms++)$e.rootPositionOffset?oe.copy($e.rootPositionOffset):oe.set(0,0,0),oe.applyQuaternion(re),this._clipRotQuat&&oe.applyQuaternion(this._clipRotQuat),$e.rootQuaternionOffset&&(ge.copy($e.rootQuaternionOffset),re.multiply(ge)),J.add(oe);this._clipRotQuat&&Q.multiply(this._clipRotQuat),Q.multiply(re),_.position&&J.add(_.position),j.add(J)}}}if(this._useclipOffsets&&(this._totalOffsetPosition.lerp(this._totalOffsetPosition2,u),this._totalOffsetRotation.slerp(this._totalOffsetRotation2,u)),this.__mixerError===void 0&&(_n||F())&&(s=(t=this._animator)==null?void 0:t.runtimeAnimatorController)!=null&&s.mixer&&this.mixer!==((r=(n=this._animator)==null?void 0:n.runtimeAnimatorController)==null?void 0:r.mixer)&&(this.__mixerError=!0,console.error("AnimationTrack mixer is not shared with the animator controller - this might result in the timeline to not animate properly. Please report a bug to the Needle Engine team!",this)),(l=this._animator)!=null&&l.runtimeAnimatorController){const y=Math.max(0,1-f);(h=(c=this._animator)==null?void 0:c.runtimeAnimatorController)==null||h.update(y)}else this.mixer.update(e)}createRotationInterpolant(e,t,s){var n;const r=s.createInterpolant.bind(s),l=new H;this.ensureTrackOffsets();const c=(n=this.trackOffset)==null?void 0:n.rotation;s.createInterpolant=()=>{const h=r(),d=h.evaluate.bind(h);return h.evaluate=u=>{var p;const g=d(u);if(l.set(g[0],g[1],g[2],g[3]),l.premultiply(this._totalOffsetRotation),c&&l.premultiply(c),this.director.animationCallbackReceivers)for(const f of this.director.animationCallbackReceivers)(p=f?.onTimelineRotation)==null||p.call(f,this.director,this.target,u,l);return g[0]=l.x,g[1]=l.y,g[2]=l.z,g[3]=l.w,g},h}}createPositionInterpolant(e,t,s){var n,r;const l=s.createInterpolant.bind(s),c=new x;this.ensureTrackOffsets();const h=(n=this.trackOffset)==null?void 0:n.rotation,d=(r=this.trackOffset)==null?void 0:r.position;let u;s.createInterpolant=()=>{const p=l(),g=p.evaluate.bind(p);return p.evaluate=f=>{var y,b,v;const _=g(f);if(c.set(_[0],_[1],_[2]),t.removeStartOffset&&(u===void 0?(u=null,u=(b=(y=this._actionOffsets.find(w=>w.clip===e))==null?void 0:y.rootStartPosition)==null?void 0:b.clone()):u!=null&&u.isVector3&&c.sub(u)),c.applyQuaternion(this._totalOffsetRotation),c.add(this._totalOffsetPosition),h&&c.applyQuaternion(h),d&&(c.x-=d.x,c.y+=d.y,c.z+=d.z),this.director.animationCallbackReceivers)for(const w of this.director.animationCallbackReceivers)(v=w?.onTimelinePosition)==null||v.call(w,this.director,this.target,f,c);return _[0]=c.x,_[1]=c.y,_[2]=c.z,_},p}}}const FI=C("mutetimeline"),AS=class rd extends jh{constructor(){super(...arguments),a(this,"models",[]),a(this,"listener"),a(this,"audio",[]),a(this,"audioContextTimeOffset",[]),a(this,"lastTime",0),a(this,"audioSource"),a(this,"_audioLoader",null),a(this,"_playableDirectorResumed",!1)}getAudioFilePath(e){const t=this.director.sourceId;return fo(t,e)}onAllowAudioChanged(e){for(let t=0;t<this.models.length;t++){const s=this.models[t];this.audio[t].setVolume(e?s.asset.volume:0)}}addModel(e){const t=new UP(this.listener);this.audio.push(t);const s=e;s._didTriggerPlay=!1,this.models.push(s)}onDisable(){for(const e of this.audio)e.isPlaying&&e.stop();for(const e of this.models)e._didTriggerPlay=!1}onDestroy(){for(const e of this.audio)e.source&&e?.disconnect();this.audio.length=0}onMuteChanged(){if(this.muted)for(let e=0;e<this.audio.length;e++){const t=this.audio[e];t!=null&&t.isPlaying&&t.stop()}}stop(){for(let e=0;e<this.audio.length;e++){const t=this.audio[e];t!=null&&t.isPlaying&&t.stop()}for(const e of this.models)e._didTriggerPlay=!1}onPauseChanged(){for(let e=0;e<this.audio.length;e++){const t=this.audio[e];t!=null&&t.isPlaying&&t.stop()}this._playableDirectorResumed=this.director.isPlaying}evaluate(e){if(FI||this.track.muted||this.director.speed<0)return;const t=this.director.context.application.muted,s=this._playableDirectorResumed;this._playableDirectorResumed=!1;const n=t?.1:0;for(let r=0;r<this.models.length;r++){const l=this.models[r],c=this.audio[r],h=l.asset;if((!c||!c.buffer)&&this.isInTimeRange(l,e-1,e+1)&&this.handleAudioLoading(l,c),ss.userInteractionRegistered!==!1&&!(c===null||!c.buffer))if(c.playbackRate=this.director.context.time.timeScale*this.director.speed,c.loop=h.loop,e>=l.start&&e<=l.end&&e<this.director.duration){if(!c.isPlaying||!this.director.isPlaying)(s||!l._didTriggerPlay&&this.lastTime<e)&&(l.duration*l.timeScale>.3?c.offset=l.clipIn+(e-l.start)*l.timeScale:c.offset=0,_n&&console.log("Timeline Audio ("+this.track.name+") play with offset "+c.offset+" - "+l.asset.clip),c.play(n),l._didTriggerPlay=!0);else{const u=l.clipIn+(e-l.start)*l.timeScale,p=c.context.currentTime-c._startedAt+c.offset;Math.abs(u-p)>.3&&(c.offset=u,c.stop(),c.play(n))}let d=h.volume;if(this.track.volume!==void 0&&(d*=this.track.volume),t&&(d=0),l.easeInDuration>0){const u=Math.min((e-l.start)/l.easeInDuration,1);d*=u}if(l.easeOutDuration>0){const u=Math.min((l.end-e)/l.easeOutDuration,1);d*=u}c.setVolume(d*this.director.weight)}else l._didTriggerPlay=!1,this.director.isPlaying&&c.isPlaying&&c.stop()}this.lastTime=e}loadAudio(e,t=0,s=0){let n=null;const r=e-s,l=e+t;for(const c of this.models)if(this.isInTimeRange(c,r,l)){const h=this.audio[this.models.indexOf(c)],d=this.handleAudioLoading(c,h);d!==null&&(n===null&&(n=[]),n.push(d))}return n!==null?Promise.all(n):null}isInTimeRange(e,t,s){return t<=e.start&&s>=e.end||t>=e.start&&t<=e.end||s>=e.start&&s<=e.end}static dispose(){rd._audioBuffers.clear()}handleAudioLoading(e,t){this._audioLoader||(this._audioLoader=new Tm);const s=this.getAudioFilePath(e.asset.clip);if(rd._audioBuffers.get(s)){const r=rd._audioBuffers.get(s);return r.then(l=>{l&&t.setBuffer(l)}),r}_n&&console.warn("LOAD audio track",s,this.director.sourceId);const n=new Promise((r,l)=>{this._audioLoader.load(s,c=>{t.setBuffer(c),r(c)},void 0,c=>{console.error("Error loading audio",c),r(null)})});return rd._audioBuffers.set(s,n),n}};a(AS,"_audioBuffers",new Map);let Jp=AS;class Dh extends jh{constructor(){super(...arguments),a(this,"models",[]),a(this,"didTrigger",[]),a(this,"receivers",[])}evaluate(e){var t;if(this.track.muted)return;const s=this.director.context.time.deltaTime*1.5;for(let n=0;n<this.models.length;n++){const r=this.models[n],l=this.didTrigger[n],c=r.time-e;let h=!1;if(r.retroActive)h=c<=1e-6;else{const d=Math.abs(c);(d===0||d>=1e-5&&d<s)&&(h=!0)}if(h){if(!l)if(_n&&console.log("Trigger signal",e,r.time,r),this.didTrigger[n]=!0,((t=this.receivers)==null?void 0:t.length)<=0)Lh.invoke(r.asset);else for(const d of this.receivers)d&&d.invoke(r.asset)}else r.emitOnce||(this.didTrigger[n]=!1)}}}class em extends jh{constructor(){super(...arguments),a(this,"models",[]),a(this,"timelines",[]),a(this,"_previousActiveModel",null)}resolveSourceObjects(e){for(let t=this.models.length-1;t>=0;t--){const s=this.models[t].asset;if(!s.sourceObject||typeof s.sourceObject!="object"){console.log("no source object, removing model",t,s),this.models.splice(t,1);continue}else{const n=P.getComponent(s.sourceObject,kl);this.timelines.push(n),n&&s.updateDirector&&(n.playOnAwake=!1)}}}evaluate(e){var t;this._previousActiveModel=null;for(let s=0;s<this.models.length;s++){const n=this.models[s],r=n.asset;if(e>=n.start&&e<=n.end){this._previousActiveModel=n;const l=this.getClipTime(e,n);if(r.controlActivation){const c=r.sourceObject;c.visible=!0}if(r.updateDirector){const c=this.timelines[s];c&&(c.isPlaying&&c.pause(),c.time=l,c.evaluate())}}else{const l=(t=this._previousActiveModel)==null?void 0:t.asset;if(r.controlActivation){const c=r.sourceObject;l?.sourceObject!==c&&(c.visible=!1)}}}}}var UI=Object.defineProperty,IS=(o,e,t,s)=>{for(var n=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=l(e,t,n)||n);return n&&UI(e,t,n),n};const so=C("debugtimeline");var Bh;const Vy=(Bh=class extends I{constructor(){super(...arguments),a(this,"playableAsset"),a(this,"playOnAwake"),a(this,"extrapolationMode",1),a(this,"waitForAudio",!0),a(this,"_visibilityChangeEvt"),a(this,"_clonedPlayableAsset",!1),a(this,"_speed",1),a(this,"_guidsMap"),a(this,"_isPlaying",!1),a(this,"_internalUpdateRoutine"),a(this,"_isPaused",!1),a(this,"_isStopping",!1),a(this,"_time",0),a(this,"_duration",0),a(this,"_weight",1),a(this,"_animationTracks",[]),a(this,"_audioTracks",[]),a(this,"_signalTracks",[]),a(this,"_controlTracks",[]),a(this,"_customTracks",[]),a(this,"_allTracks",[this._animationTracks,this._audioTracks,this._signalTracks,this._controlTracks,this._customTracks]),a(this,"animationCallbackReceivers",[])}static registerCreateTrack(o,e){this.createTrackFunctions[o]=e}get isPlaying(){return this._isPlaying}get isPaused(){return this._isPaused}get time(){return this._time}set time(o){typeof o=="number"&&!Number.isNaN(o)?this._time=o:(so||qt())&&console.error("INVALID TIMELINE.TIME VALUE",o,this.name)}get duration(){return this._duration}set duration(o){this._duration=o}get weight(){return this._weight}set weight(o){this._weight=o}get speed(){return this._speed}set speed(o){this._speed=o}awake(){var o,e,t,s,n;so&&console.log(this,(o=this.playableAsset)==null?void 0:o.tracks),this.rebuildGraph(),!this.isValid()&&(so||F())&&(so?console.warn("PlayableDirector is not valid","Asset?",this.playableAsset,"Tracks:",(e=this.playableAsset)==null?void 0:e.tracks,"IsArray?",Array.isArray((t=this.playableAsset)==null?void 0:t.tracks),this):(n=(s=this.playableAsset)==null?void 0:s.tracks)!=null&&n.length?console.warn("PlayableDirector is not valid"):console.warn("PlayableDirector has no tracks"))}onEnable(){var o,e,t;for(const s of this._audioTracks)(o=s.onEnable)==null||o.call(s);for(const s of this._customTracks)(e=s.onEnable)==null||e.call(s);for(const s of this._animationTracks)(t=s.onEnable)==null||t.call(s);this.playOnAwake&&this.play(),this._visibilityChangeEvt||(this._visibilityChangeEvt=()=>{switch(document.visibilityState){case"hidden":this.setAudioTracksAllowPlaying(!1);break;case"visible":this.setAudioTracksAllowPlaying(!0);break}}),window.addEventListener("visibilitychange",this._visibilityChangeEvt)}onDisable(){var o,e,t;this.stop();for(const s of this._audioTracks)(o=s.onDisable)==null||o.call(s);for(const s of this._customTracks)(e=s.onDisable)==null||e.call(s);for(const s of this._animationTracks)(t=s.onDisable)==null||t.call(s);this._visibilityChangeEvt&&window.removeEventListener("visibilitychange",this._visibilityChangeEvt)}onDestroy(){var o;for(const e of this._allTracks)for(const t of e)(o=t.onDestroy)==null||o.call(t)}rebuildGraph(){this.isValid()&&(this.resolveBindings(),this.updateTimelineDuration(),this.setupAndCreateTrackHandlers())}async play(){if(!this.isValid())return;const o=this._isPaused==!0;if(this._isPaused=!1,!this._isPlaying){if(this._isPlaying=!0,o&&this.invokePauseChangedMethodsOnTracks(),this.waitForAudio){const e=[];for(const t of this._audioTracks){const s=t.loadAudio(this._time,1,0);s&&e.push(s)}if(e.length>0&&(await Promise.all(e),!this._isPlaying))return;for(;this._audioTracks.length>0&&this._isPlaying&&!ss.userInteractionRegistered&&this.waitForAudio;)await ys(200)}this.invokeStateChangedMethodsOnTracks(),this._internalUpdateRoutine=this.startCoroutine(this.internalUpdate(),Oe.LateUpdate)}}pause(){this.isValid()&&(this._isPlaying=!1,!this._isPaused&&(this._isPaused=!0,this.internalEvaluate(),this.invokePauseChangedMethodsOnTracks(),this.invokeStateChangedMethodsOnTracks()))}stop(){this._isStopping=!0;for(const t of this._audioTracks)t.stop();const o=this._isPaused==!0,e=this._isPlaying;this._isPlaying&&(this._time=0,this._isPlaying=!1,this._isPaused=!1,this.internalEvaluate(),o&&this.invokePauseChangedMethodsOnTracks()),this._isPlaying=!1,this._isPaused=!1,o&&!e&&this.invokePauseChangedMethodsOnTracks(),e&&this.invokeStateChangedMethodsOnTracks(),this._internalUpdateRoutine&&this.stopCoroutine(this._internalUpdateRoutine),this._internalUpdateRoutine=null,this._isStopping=!1}evaluate(){this.internalEvaluate(!0)}isValid(){return this.playableAsset&&this.playableAsset.tracks&&Array.isArray(this.playableAsset.tracks)}*forEachTrack(){for(const o of this._allTracks)for(const e of o)yield e}get animationTracks(){return this._animationTracks}get audioTracks(){return this._audioTracks}resolveGuids(o){this._guidsMap=o}invokePauseChangedMethodsOnTracks(){var o;for(const e of this.forEachTrack())(o=e.onPauseChanged)==null||o.call(e)}invokeStateChangedMethodsOnTracks(){var o;for(const e of this.forEachTrack())(o=e.onStateChanged)==null||o.call(e,this._isPlaying)}*internalUpdate(){for(;this._isPlaying&&this.activeAndEnabled;)!this._isPaused&&this._isPlaying&&(this._time+=this.context.time.deltaTime*this.speed,this.internalEvaluate()),yield}internalEvaluate(o=!1){if(!this.isValid())return;let e=this._time;switch(this.extrapolationMode){case 0:this._speed>0?e=Math.min(e,this._duration):this._speed<0&&(e=Math.max(e,0)),this._time=e;break;case 1:e%=this._duration,this._time=e;break;case 2:if(e>this._duration){this.stop();return}break}const t=this._time;for(const s of this.playableAsset.tracks)if(!s.muted)switch(s.type){case Gi.Activation:if(!o&&!this._isPlaying)continue;for(let n=0;n<s.outputs.length;n++){const r=s.outputs[n];if(typeof r=="object"){let l=!1;if(s.clips)for(const h of s.clips)h.start<=t&&t<=h.end&&(l=!0);const c=r;c.visible!==void 0&&c.visible!==l&&(c.visible=l,so&&console.warn(this.name,"set ActivationTrack-"+n,c.name,l,t))}}break}if(!this._isStopping)for(const s of this._animationTracks)s.evaluate(t);for(const s of this._audioTracks)s.evaluate(t);for(const s of this._signalTracks)s.evaluate(t);for(const s of this._controlTracks)s.evaluate(t);for(const s of this._customTracks)s.evaluate(t)}resolveBindings(){if(this._clonedPlayableAsset||(this._clonedPlayableAsset=!0,this.playableAsset=$l(this.playableAsset)),!this.playableAsset||!this.playableAsset.tracks)return;const o=this.findRoot(this.gameObject);for(const e of this.playableAsset.tracks){for(let t=e.outputs.length-1;t>=0;t--){let s=e.outputs[t];if(typeof s=="string"){this._guidsMap&&this._guidsMap[s]&&(s=this._guidsMap[s]);const n=P.findByGuid(s,o);n===null||typeof n!="object"?(e.outputs.splice(t,1),console.warn("Failed to resolve binding",s,e.name,e.type)):(so&&console.log("Resolved binding",s,"to",n),e.outputs[t]=n)}else if(s===null){if(e.outputs.splice(t,1),Bh.createTrackFunctions[e.type])continue;e.type!==Gi.Audio&&e.type!==Gi.Control&&e.type!==Gi.Marker&&e.type!==Gi.Signal&&console.warn("Missing binding",s,e.name,e.type,this.name,this.playableAsset.name)}}if(e.type===Gi.Control&&e.clips)for(let t=0;t<e.clips.length;t++){const s=e.clips[t];let n=s.asset.sourceObject;if(typeof n=="string"){this._guidsMap&&this._guidsMap[n]&&(n=this._guidsMap[n]);const r=P.findByGuid(n,o);r===null||typeof r!="object"?console.warn("Failed to resolve sourceObject binding",n,e.name,s):(so&&console.log("Resolved binding",n,"to",r),s.asset.sourceObject=r)}}}}findRoot(o){return o.parent?this.findRoot(o.parent):o}updateTimelineDuration(){if(this._duration=0,!(!this.playableAsset||!this.playableAsset.tracks)){for(const o of this.playableAsset.tracks)if(o.muted!==!0){if(o.clips)for(const e of o.clips)e.end>this._duration&&(this._duration=e.end);if(o.markers)for(const e of o.markers)e.time>this._duration&&(this._duration=e.time+.001)}}}setupAndCreateTrackHandlers(){var o,e,t;if(this._animationTracks.length=0,this._audioTracks.length=0,this._signalTracks.length=0,!this.playableAsset)return;let s=P.findObjectOfType(zn,this.context);for(const n of this.playableAsset.tracks){const r=n.type,l=Bh.createTrackFunctions[r];if(l!=null){const c=l(this,n);if(typeof c.evaluate=="function"){c.director=this,c.track=n,this._customTracks.push(c);continue}}if(n.type===Gi.Animation){if(!n.clips||n.clips.length<=0){so&&console.warn("Animation track has no clips",n);continue}for(let c=n.outputs.length-1;c>=0;c--){let h=n.outputs[c];if(h instanceof E){const u=P.getOrAddComponent(h,Mt);u&&(h=u)}const d=(o=h?.gameObject)==null?void 0:o.animations;if(d){const u=new Zp;u.trackOffset=n.trackOffset,u.director=this,u.track=n;for(let p=0;p<n.clips.length;p++){const g=n.clips[p],f=g.asset;if(!f){console.error(`Timeline ${this.name}: clip #${p} on track "${n.name}" has no animation data`);continue}const y=f.clip;let b=y;if((typeof b=="string"||typeof b=="number")&&(b=d.find(_=>_.name===y)),so&&console.log(f,y,"\u2192",b),!b){console.warn("Could not find animationClip for model",g,n.name,this.name,(e=this.playableAsset)==null?void 0:e.name,d,h);continue}h instanceof Mt&&h.runtimeAnimatorController&&(h.__internalDidAwakeAndStart||h.initializeRuntimeAnimatorController(),h.runtimeAnimatorController.mixer||h.runtimeAnimatorController.bind(h),u.mixer=h.runtimeAnimatorController.mixer),u.mixer||(u.mixer=new Rm(h.gameObject),this.context.animations.registerAnimationMixer(u.mixer)),u.clips.push(b),u.mixer.uncacheAction(b),u.createHooks(g.asset,b);const v=u.mixer.clipAction(b);u.actions.push(v),u.models.push(g)}this._animationTracks.push(u)}}}else if(n.type===Gi.Audio){if(!n.clips||n.clips.length<=0)continue;const c=new Jp;c.director=this,c.track=n,c.audioSource=n.outputs.find(h=>h instanceof ss),this._audioTracks.push(c),s||(s=(t=this.context.mainCameraComponent)==null?void 0:t.gameObject.addComponent(zn)),c.listener=s.listener;for(let h=0;h<n.clips.length;h++){const d=n.clips[h];c.addModel(d)}}else if(n.type===Gi.Marker){const c=new Dh;if(c.director=this,c.track=n,n.markers)for(const h of n.markers)switch(h.type){case Wy.Signal:c.models.push(h),c.didTrigger.push(!1);break}if(c!==null&&c.models.length>0){const h=P.getComponent(this.gameObject,Lh);h&&(c.receivers.push(h),this._signalTracks.push(c))}}else if(n.type===Gi.Signal){const c=new Dh;if(c.director=this,c.track=n,n.markers)for(const h of n.markers)c.models.push(h),c.didTrigger.push(!1);for(const h of n.outputs)c.receivers.push(h);this._signalTracks.push(c)}else if(n.type===Gi.Control){const c=new em;if(c.director=this,c.track=n,n.clips)for(const h of n.clips)c.models.push(h);c.resolveSourceObjects(this.context),this._controlTracks.push(c)}}}setAudioTracksAllowPlaying(o){for(const e of this._audioTracks)e.onAllowAudioChanged(o)}registerAnimationCallback(o){this.animationCallbackReceivers.push(o)}unregisterAnimationCallback(o){const e=this.animationCallbackReceivers.indexOf(o);e!==-1&&this.animationCallbackReceivers.splice(e,1)}},a(Bh,"createTrackFunctions",{}),Bh);IS([m()],Vy.prototype,"playOnAwake"),IS([m()],Vy.prototype,"extrapolationMode");let kl=Vy;var zI=Object.defineProperty,tm=(o,e,t,s)=>{for(var n=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=l(e,t,n)||n);return n&&zI(e,t,n),n};class la extends I{constructor(){super(...arguments),a(this,"isGizmo",!1),a(this,"translationSnap",1),a(this,"rotationSnapAngle",15),a(this,"scaleSnap",.25),a(this,"_control"),a(this,"orbit"),a(this,"onControlChangedEvent",e=>{const t=this.orbit;if(t&&(t.enabled=!e.value),e.value){const s=P.getComponentInParent(this.gameObject,sn);s&&s.requestOwnership()}}),a(this,"windowKeyDownListener",e=>{if(this.enabled&&this._control)switch(e.keyCode){case 81:this._control.setSpace(this._control.space==="local"?"world":"local");break;case 16:this.enableSnapping();break;case 87:this._control.setMode("translate");break;case 69:this._control.setMode("rotate");break;case 82:this._control.setMode("scale");break;case 187:case 107:this._control.setSize(this._control.size+.1);break;case 189:case 109:this._control.setSize(Math.max(this._control.size-.1,.1));break;case 88:this._control.showX=!this._control.showX;break;case 89:this._control.showY=!this._control.showY;break;case 90:this._control.showZ=!this._control.showZ;break;case 32:this._control.enabled=!this._control.enabled;break}}),a(this,"windowKeyUpListener",e=>{if(this.enabled)switch(e.keyCode){case 16:this.disableSnapping();break}})}get control(){return this._control}onEnable(){var e;if(!(this.isGizmo&&!gc)&&this.context.mainCamera&&(this._control||(this._control=new lO(this.context.mainCamera,this.context.renderer.domElement),this._control.enabled=!0,this._control.getRaycaster().layers.set(2),this._control.size=1,("_root"in this._control?this._control._root:this._control).traverse(t=>{const s=t;if(s.layers.set(2),s){const n=s.material;n&&(n.opacity=.3)}}),this.orbit=P.getComponentInParent(this.context.mainCamera,_e)??void 0),this._control)){const t=this._control.getHelper();this.context.scene.add(t),this._control.attach(this.gameObject),(e=this._control)==null||e.addEventListener("dragging-changed",this.onControlChangedEvent),window.addEventListener("keydown",this.windowKeyDownListener),window.addEventListener("keyup",this.windowKeyUpListener)}}onDisable(){var e,t,s;(t=(e=this._control)==null?void 0:e.getHelper())==null||t.removeFromParent(),(s=this._control)==null||s.removeEventListener("dragging-changed",this.onControlChangedEvent),window.removeEventListener("keydown",this.windowKeyDownListener),window.removeEventListener("keyup",this.windowKeyUpListener)}enableSnapping(){this._control&&(this._control.setTranslationSnap(this.translationSnap),this._control.setRotationSnap(Cn.degToRad(this.rotationSnapAngle)),this._control.setScaleSnap(this.scaleSnap))}disableSnapping(){this._control&&(this._control.setTranslationSnap(null),this._control.setRotationSnap(null),this._control.setScaleSnap(null))}}tm([m()],la.prototype,"isGizmo"),tm([m()],la.prototype,"translationSnap"),tm([m()],la.prototype,"rotationSnapAngle"),tm([m()],la.prototype,"scaleSnap");var NI=Object.defineProperty,WI=Object.getOwnPropertyDescriptor,im=(o,e,t,s)=>{for(var n=s>1?void 0:s?WI(e,t):e,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=(s?l(e,t,n):l(n))||n);return s&&n&&NI(e,t,n),n};class Hy{constructor(){a(this,"texture",null),a(this,"rect")}}im([m(De)],Hy.prototype,"texture",2);let Ml=class extends ah{constructor(){super(...arguments),a(this,"_sprite"),a(this,"pixelsPerUnitMultiplier",1)}set image(o){this.sprite||(this.sprite=new Hy),this.sprite.texture=o,this.onAfterCreated()}get image(){return this.sprite?this.sprite.texture:null}get sprite(){return this._sprite}set sprite(o){this._sprite!==o&&(this._sprite=o,this.onAfterCreated())}isBuiltinSprite(){var o,e,t,s,n,r,l;const c=this.sprite;switch((o=c?.texture)==null?void 0:o.name){case"InputFieldBackground":case"UISprite":case"Background":case"Knob":return!0}return!((t=(e=c?.texture)==null?void 0:e.name)!=null&&t.length)&&((n=(s=c?.texture)==null?void 0:s.image)==null?void 0:n.width)===32&&((l=(r=c?.texture)==null?void 0:r.image)==null?void 0:l.height)===32}onBeforeCreate(o){var e,t;super.onBeforeCreate(o),this.isBuiltinSprite()&&(o.borderRadius=5/this.pixelsPerUnitMultiplier,((t=(e=this.sprite)==null?void 0:e.texture)==null?void 0:t.name)==="Knob"&&(o.borderRadius=999))}onAfterCreated(){var o;this.__didAwake&&(super.onAfterCreated(),!this.isBuiltinSprite()&&this.setTexture((o=this.sprite)==null?void 0:o.texture))}};im([m(Hy)],Ml.prototype,"sprite",1),im([m()],Ml.prototype,"pixelsPerUnitMultiplier",2);class sm extends ah{constructor(){super(...arguments),a(this,"_mainTexture")}get mainTexture(){return this._mainTexture}set mainTexture(e){this._mainTexture!==e&&(this._mainTexture=e,this.onAfterCreated())}onAfterCreated(){this.__didAwake&&(super.onAfterCreated(),this.setTexture(this.mainTexture))}}im([m(De)],sm.prototype,"mainTexture",1);var VI=Object.defineProperty,HI=Object.getOwnPropertyDescriptor,qi=(o,e,t,s)=>{for(var n=s>1?void 0:s?HI(e,t):e,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=(s?l(e,t,n):l(n))||n);return s&&n&&VI(e,t,n),n};const ca=C("debugbutton");class ar{constructor(){a(this,"colorMultiplier"),a(this,"disabledColor"),a(this,"fadeDuration"),a(this,"highlightedColor"),a(this,"normalColor"),a(this,"pressedColor"),a(this,"selectedColor")}}qi([m()],ar.prototype,"colorMultiplier",2),qi([m(he)],ar.prototype,"disabledColor",2),qi([m()],ar.prototype,"fadeDuration",2),qi([m(he)],ar.prototype,"highlightedColor",2),qi([m(he)],ar.prototype,"normalColor",2),qi([m(he)],ar.prototype,"pressedColor",2),qi([m(he)],ar.prototype,"selectedColor",2);class $I{constructor(){a(this,"disabledTrigger"),a(this,"highlightedTrigger"),a(this,"normalTrigger"),a(this,"pressedTrigger"),a(this,"selectedTrigger")}}class no extends I{constructor(){super(...arguments),a(this,"onClick",new xe),a(this,"_isHovered",0),a(this,"colors"),a(this,"transition"),a(this,"animationTriggers"),a(this,"animator"),a(this,"_interactable",!0),a(this,"_requestedAnimatorTrigger"),a(this,"_isInit",!1),a(this,"_image")}click(){var e;(e=this.onClick)==null||e.invoke()}onPointerEnter(e){var t,s;const n=e.event.pointerType==="mouse"&&e.button===0;n&&(this._isHovered+=1),ca&&console.warn("Button Enter",n,this._isHovered,(t=this.animationTriggers)==null?void 0:t.highlightedTrigger,this.animator),this.interactable&&(this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this.animationTriggers.highlightedTrigger):this.transition===1&&this.colors&&((s=this._image)==null||s.setState("hovered")),n&&this.context.input.setCursor("pointer"))}onPointerExit(){var e,t;this._isHovered-=1,this._isHovered<0&&(this._isHovered=0),ca&&console.log("Button Exit",this._isHovered,(e=this.animationTriggers)==null?void 0:e.highlightedTrigger,this.animator),this.interactable&&(this._isHovered>0||(this._isHovered=0,this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this.animationTriggers.normalTrigger):this.transition===1&&this.colors&&((t=this._image)==null||t.setState("normal")),this.context.input.unsetCursor("pointer")))}onPointerDown(e){var t,s;ca&&console.log("Button Down",(t=this.animationTriggers)==null?void 0:t.highlightedTrigger,this.animator),this.interactable&&(this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this.animationTriggers.pressedTrigger):this.transition===1&&this.colors&&((s=this._image)==null||s.setState("pressed")))}onPointerUp(e){var t,s;ca&&console.warn("Button Up",(t=this.animationTriggers)==null?void 0:t.highlightedTrigger,this.animator,this._isHovered),this.interactable&&(this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this._isHovered?this.animationTriggers.highlightedTrigger:this.animationTriggers.normalTrigger):this.transition===1&&this.colors&&((s=this._image)==null||s.setState(this._isHovered?"hovered":"normal")))}onPointerClick(e){if(this.interactable&&!(e.button!==0&&e.event.pointerType===Bd.Mouse)&&(ca&&(console.warn("Button Click",this.onClick),Be("CLICKED button "+this.name+" at "+this.context.time.frameCount)),this.onClick&&this.onClick.listenerCount>0&&(this.onClick.invoke(),e.use(),ca))){const t=this.gameObject.worldPosition;t.add(this.gameObject.worldUp.multiplyScalar(1+Math.random()*.5)),G.DrawLabel(t,"CLICK:"+Date.now(),.1,1+Math.random()*.5)}}set interactable(e){this._interactable=e,this._image&&(this._image.setInteractable(e),e?this._image.setState("normal"):this._image.setState("disabled"))}get interactable(){return this._interactable}set_interactable(e){this.interactable=e}awake(){super.awake(),ca&&console.log(this),this._isInit=!1,this.init()}start(){var e;(e=this._image)==null||e.setInteractable(this.interactable),this.gameObject.getComponentInParent(qa)||this.gameObject.addComponent(Tu)}onEnable(){super.onEnable()}onDestroy(){this._isHovered&&this.context.input.unsetCursor("pointer")}*setAnimatorTriggerAtEndOfFrame(e){var t;this._requestedAnimatorTrigger=e,yield,yield,this._requestedAnimatorTrigger==e&&((t=this.animator)==null||t.setTrigger(e))}init(){this._isInit||(this._isInit=!0,this._image=P.getComponent(this.gameObject,Ml),this._image&&(this.stateSetup(this._image),this.interactable?this._image.setState("normal"):this._image.setState("disabled")))}stateSetup(e){var t,s,n,r,l;e.setInteractable(this.interactable);const c=this.getFinalColor(e.color,(t=this.colors)==null?void 0:t.normalColor),h={state:"normal",attributes:{backgroundColor:c,backgroundOpacity:c.alpha}};e.setupState(h);const d=this.getFinalColor(e.color,(s=this.colors)==null?void 0:s.highlightedColor),u={state:"hovered",attributes:{backgroundColor:d,backgroundOpacity:d.alpha}};e.setupState(u);const p=this.getFinalColor(e.color,(n=this.colors)==null?void 0:n.pressedColor),g={state:"pressed",attributes:{backgroundColor:p,backgroundOpacity:p.alpha}};e.setupState(g);const f=this.getFinalColor(e.color,(r=this.colors)==null?void 0:r.selectedColor),y={state:"selected",attributes:{backgroundColor:f,backgroundOpacity:f.alpha}};e.setupState(y);const b=this.getFinalColor(e.color,(l=this.colors)==null?void 0:l.disabledColor),v={state:"disabled",attributes:{backgroundColor:b,backgroundOpacity:b.alpha}};e.setupState(v)}getFinalColor(e,t){return t?e.clone().multiply(t).convertLinearToSRGB():e.clone().convertLinearToSRGB()}}qi([m(xe)],no.prototype,"onClick",2),qi([m(ar)],no.prototype,"colors",2),qi([m()],no.prototype,"transition",2),qi([m($I)],no.prototype,"animationTriggers",2),qi([m(Mt)],no.prototype,"animator",2),qi([m()],no.prototype,"interactable",1);var GI=Object.defineProperty,nm=(o,e,t,s)=>{for(var n=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=l(e,t,n)||n);return n&&GI(e,t,n),n};const lr=C("debuginputfield");var K;const Fh=(K=class extends I{constructor(){super(...arguments),a(this,"textComponent"),a(this,"placeholder"),a(this,"onValueChanged"),a(this,"onEndEdit"),a(this,"inputEventFn"),a(this,"_iosEventFn")}get text(){var o;return((o=this.textComponent)==null?void 0:o.text)??""}set text(o){this.textComponent&&(this.textComponent.text=o,this.placeholder&&(o.length>0?this.placeholder.gameObject.visible=!1:this.placeholder.gameObject.visible=!0))}get isFocused(){return K.active===this}start(){lr&&console.log(this.name,this)}onEnable(){var o;K.htmlField||(K.htmlField=document.createElement("input"),K.htmlField.style.width="0px",K.htmlField.style.height="0px",K.htmlField.style.padding="0px",K.htmlField.style.border="none",K.htmlField.style.overflow="hidden",K.htmlField.style.caretColor="transparent",K.htmlField.style.outline="none",K.htmlField.classList.add("ar"),K.htmlField.onfocus=()=>K.htmlFieldFocused=!0,K.htmlField.onblur=()=>K.htmlFieldFocused=!1,document.body.append(K.htmlField)),this.inputEventFn||(this.inputEventFn=this.onInput.bind(this)),K.htmlField.addEventListener("keyup",this.inputEventFn),this.placeholder&&(o=this.textComponent)!=null&&o.text.length&&P.setActive(this.placeholder.gameObject,!1),Y.isiOS()&&(this._iosEventFn=this.processInputOniOS.bind(this),window.addEventListener("click",this._iosEventFn))}onDisable(){var o;(o=K.htmlField)==null||o.removeEventListener("keyup",this.inputEventFn),this.onDeselected(),this._iosEventFn&&window.removeEventListener("click",this._iosEventFn)}clear(){K.active===this&&K.htmlField?(K.htmlField.value="",this.setTextFromInputField()):(this.textComponent&&(this.textComponent.text=""),this.placeholder&&P.setActive(this.placeholder.gameObject,!0))}select(){this.onSelected()}deselect(){this.onDeselected()}onPointerEnter(o){o.event.pointerType==="mouse"&&o.button===0&&this.context.input.setCursor("text")}onPointerExit(o){this.context.input.unsetCursor("text")}onPointerClick(o){lr&&console.log("CLICK",o,K.active),K.activeTime=this.context.time.time,K.active!==this&&this.startCoroutine(this.activeLoop(),Oe.LateUpdate),this.selectInputField()}*activeLoop(){for(this.onSelected();K.active===this&&!(this.context.input.getPointerClicked(0)&&this.context.time.time-K.activeTime>.2);)this.setTextFromInputField(),yield;this.onDeselected()}onSelected(){var o,e,t,s;if(K.active!==this&&(lr&&console.log("Select",this.name,this,K.htmlField,this.context.isInXR,this.context.arOverlayElement,(o=this.textComponent)==null?void 0:o.text,(e=K.htmlField)==null?void 0:e.value),(t=K.active)==null||t.onDeselected(),K.active=this,this.placeholder&&P.setActive(this.placeholder.gameObject,!1),K.htmlField)){if(K.htmlField.value=((s=this.textComponent)==null?void 0:s.text)||"",lr&&console.log("set input field value",K.htmlField.value),this.context.isInXR){const n=this.context.arOverlayElement;n&&n.append(K.htmlField)}this.selectInputField()}}onDeselected(){var o;K.active===this&&(K.active=null,lr&&console.log("Deselect",this.name,this),K.htmlField&&(K.htmlField.blur(),document.body.append(K.htmlField)),this.placeholder&&(!this.textComponent||this.textComponent.text.length<=0)&&P.setActive(this.placeholder.gameObject,!0),K.htmlField&&((o=this.onEndEdit)==null||o.invoke(K.htmlField.value)))}update(){var o;K.active===this&&((o=this.textComponent)==null||o.markDirty())}onInput(o){var e,t;if(K.active===this){if(lr&&console.log(o.code,o,(e=K.htmlField)==null?void 0:e.value,(t=this.textComponent)==null?void 0:t.text),o.code==="Escape"||o.code==="Enter"){this.onDeselected();return}K.htmlField&&(this.textComponent&&(this.setTextFromInputField(),this.placeholder&&P.setActive(this.placeholder.gameObject,this.textComponent.text.length<=0)),this.selectInputField())}}setTextFromInputField(){var o;if(this.textComponent&&K.htmlField){const e=this.textComponent.text,t=K.htmlField.value,s=this.textComponent.text!==K.htmlField.value;this.textComponent.text=K.htmlField.value,s&&(lr&&console.log("[InputField] value changed:",t,e),(o=this.onValueChanged)==null||o.invoke(t,e))}}selectInputField(){K.htmlField&&(lr&&console.log("Focus Inputfield",K.htmlFieldFocused),K.htmlField.setSelectionRange(K.htmlField.value.length,K.htmlField.value.length),Y.isiOS()?K.htmlField.focus({preventScroll:!0}):setTimeout(()=>{var o;return(o=K.htmlField)==null?void 0:o.focus()},1))}processInputOniOS(){const o=this.context.physics.raycast();if(!o.length)return;const e=o[0].object,t=Df(e);(t?.gameObject===this.gameObject||t?.gameObject.parent===this.gameObject)&&this.selectInputField()}},a(K,"active",null),a(K,"activeTime",-1),a(K,"htmlField",null),a(K,"htmlFieldFocused",!1),K);nm([m(zt)],Fh.prototype,"textComponent"),nm([m(zt)],Fh.prototype,"placeholder"),nm([m(xe)],Fh.prototype,"onValueChanged"),nm([m(xe)],Fh.prototype,"onEndEdit");let $y=Fh;var qI=Object.defineProperty,LS=(o,e,t,s)=>{for(var n=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=l(e,t,n)||n);return n&&qI(e,t,n),n};class Uh extends I{constructor(){super(...arguments),a(this,"id",null),a(this,"keepAspect",!1),a(this,"_object",null)}onEnable(){if(this._object){this.gameObject.add(this._object);return}if(!this.id||!this.context.mainCamera)return;const e=document.getElementById(this.id);if(!e){console.warn('Could not find element with id "'+this.id+'"');return}e.style.display="block",e.style.visibility="hidden";const t=new cO;t.listenToPointerEvents(this.context.renderer,this.context.mainCamera),this.gameObject.add(t);const s=new hO(e);t.add(s),s.visible=!1;const n=s.material;n.transparent=!0,setTimeout(()=>{s.visible=!0;const r=Td(this.gameObject).clone();Yl(this.gameObject,0,0,0),this.gameObject.updateMatrixWorld();const l=new xi;l.setFromObject(t),this.setWorldRotation(r.x,r.y,r.z);const c=l.max.x-l.min.x,h=l.max.y-l.min.y;if(this.keepAspect){const u=c/h;c>h?s.scale.set(1/c,1/h/u,1):s.scale.set(1/c*u,1/h,1)}else s.scale.set(1/c,1/h,1);const d=this.gameObject.scale;s.scale.multiply(d)},1)}onDisable(){var e;(e=this._object)==null||e.removeFromParent()}}LS([m()],Uh.prototype,"id"),LS([m()],Uh.prototype,"keepAspect");/* @license
1363
+ * Copyright 2021 Google LLC. All Rights Reserved.
1364
+ * Licensed under the Apache License, Version 2.0 (the 'License');
1365
+ * you may not use this file except in compliance with the License.
1366
+ * You may obtain a copy of the License at
1367
+ *
1368
+ * http://www.apache.org/licenses/LICENSE-2.0
1369
+ *
1370
+ * Unless required by applicable law or agreed to in writing, software
1371
+ * distributed under the License is distributed on an 'AS IS' BASIS,
1372
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1373
+ * See the License for the specific language governing permissions and
1374
+ * limitations under the License.
1375
+ */const XI={topLight:{intensity:500,position:[.418,16.199,.3]},room:{position:[-.757,13.219,.717],scale:[31.713,28.305,28.591]},boxes:[{position:[-10.906,2.009,1.846],rotation:-.195,scale:[2.328,7.905,4.651]},{position:[-5.607,-.754,-.758],rotation:.994,scale:[1.97,1.534,3.955]},{position:[6.167,.857,7.803],rotation:.561,scale:[3.927,6.285,3.687]},{position:[-2.017,.018,6.124],rotation:.333,scale:[2.002,4.566,2.064]},{position:[2.291,-.756,-2.621],rotation:-.286,scale:[1.546,1.552,1.496]},{position:[-2.193,-.369,-5.547],rotation:.516,scale:[3.875,3.487,2.986]}],lights:[{intensity:50,position:[-16.116,14.37,8.208],scale:[.1,2.428,2.739]},{intensity:50,position:[-16.109,18.021,-8.207],scale:[.1,2.425,2.751]},{intensity:17,position:[14.904,12.198,-1.832],scale:[.15,4.265,6.331]},{intensity:43,position:[-.462,8.89,14.52],scale:[4.38,5.441,.088]},{intensity:20,position:[3.235,11.486,-12.541],scale:[2.5,2,.1]},{intensity:100,position:[0,20,0],scale:[1,.1,1]}]},QI={topLight:{intensity:400,position:[.5,14,.5]},room:{position:[0,13.2,0],scale:[31.5,28.5,31.5]},boxes:[{position:[-10.906,-1,1.846],rotation:-.195,scale:[2.328,7.905,4.651]},{position:[-5.607,-.754,-.758],rotation:.994,scale:[1.97,1.534,3.955]},{position:[6.167,-.16,7.803],rotation:.561,scale:[3.927,6.285,3.687]},{position:[-2.017,.018,6.124],rotation:.333,scale:[2.002,4.566,2.064]},{position:[2.291,-.756,-2.621],rotation:-.286,scale:[1.546,1.552,1.496]},{position:[-2.193,-.369,-5.547],rotation:.516,scale:[3.875,3.487,2.986]}],lights:[{intensity:80,position:[-14,10,8],scale:[.1,2.5,2.5]},{intensity:80,position:[-14,14,-4],scale:[.1,2.5,2.5]},{intensity:23,position:[14,12,0],scale:[.1,5,5]},{intensity:16,position:[0,9,14],scale:[5,5,.1]},{intensity:80,position:[7,8,-14],scale:[2.5,2.5,.1]},{intensity:80,position:[-7,16,-14],scale:[2.5,2.5,.1]},{intensity:1,position:[0,20,0],scale:[.1,.1,.1]}]};class om extends wi{constructor(e){super(),this.position.y=-3.5;const t=new ba;t.deleteAttribute("uv");const s=new vt({metalness:0,side:bd}),n=new vt({metalness:0}),r=e=="legacy"?XI:QI,l=new Pm(16777215,r.topLight.intensity,28,2);l.position.set(...r.topLight.position),this.add(l);const c=new q(t,s);c.position.set(...r.room.position),c.scale.set(...r.room.scale),this.add(c);for(const h of r.boxes){const d=new q(t,n);d.position.set(...h.position),d.rotation.set(0,h.rotation,0),d.scale.set(...h.scale),this.add(d)}for(const h of r.lights){const d=new q(t,this.createAreaLightMaterial(h.intensity));d.position.set(...h.position),d.scale.set(...h.scale),this.add(d)}}createAreaLightMaterial(e){const t=new Me;return t.color.setScalar(e),t}}var YI=Object.defineProperty,rm=(o,e,t,s)=>{for(var n=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=l(e,t,n)||n);return n&&YI(e,t,n),n},am;const zh=(am=class extends I{constructor(){super(...arguments),a(this,"target"),a(this,"invertForward",!1),a(this,"keepUpDirection",!0),a(this,"copyTargetRotation",!1)}onBeforeRender(){let o=this.target;if(o||(o=this.context.mainCamera),!o)return;let e=this.copyTargetRotation;(this.context.isInVR||this.context.isInPassThrough)&&(e=!1),Ql(this.gameObject,o,this.keepUpDirection,e),this.invertForward&&this.gameObject.quaternion.multiply(am.flipYQuat)}createBehaviours(o,e,t){if(e.uuid===this.gameObject.uuid){let s=e;if(this.keepUpDirection){const r=pi.createEmptyParent(e);s=r;const l=this.invertForward?-1:1;r.setMatrix(r.getMatrix().multiply(new se().makeRotationZ(Math.PI/2*l))),e.setMatrix(e.getMatrix().multiply(new se().makeRotationZ(-Math.PI/2*l)))}const n=new Zt("lookat "+this.name,Et.sceneStartTrigger(),ve.lookAtCameraAction(s,void 0,this.invertForward?ps.back:ps.forward,this.keepUpDirection?ps.up:ps.zero));o.addBehavior(n)}}},a(am,"flipYQuat",new H().setFromAxisAngle(new x(0,1,0),Math.PI)),am);rm([m(E)],zh.prototype,"target"),rm([m()],zh.prototype,"invertForward"),rm([m()],zh.prototype,"keepUpDirection"),rm([m()],zh.prototype,"copyTargetRotation");let Gy=zh;var KI=Object.defineProperty,qy=(o,e,t,s)=>{for(var n=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=l(e,t,n)||n);return n&&KI(e,t,n),n};class Rl extends I{constructor(){super(...arguments),a(this,"url"),a(this,"mode",0),a(this,"clickable",!0)}async open(){if(!this.url){console.warn("OpenURL: URL is not set, can't open.",this);return}this._validateUrl();let e=this.url;switch(!e.startsWith("mailto:")&&e.includes("@")&&(e="mailto:"+e),F()&&Be("Open URL: "+e),this.mode){case 0:Y.isSafari(),globalThis.open(e,"_blank");break;case 1:Y.isSafari()&&Y.isiOS()?globalThis.open(e,"_top"):globalThis.open(e,"_self");break;case 2:Y.isSafari()?globalThis.open(e,"_top"):globalThis.open(e,"_new");break}}start(){this.gameObject.getComponentInParent(Li)||this.gameObject.addComponent(Li)}onPointerEnter(e){!e.used&&this.clickable&&this.context.input.setCursor("pointer")}onPointerExit(){this.clickable&&this.context.input.unsetCursor("pointer")}onPointerClick(e){var t;this.clickable&&!e.used&&(t=this.url)!=null&&t.length&&this.open()}_validateUrl(){this.url&&this.url.startsWith("www.")&&(F()&&console.warn("URL is not valid, adding https:// to the start of the URL",this.url),this.url="https://"+this.url)}}qy([m()],Rl.prototype,"url"),qy([m()],Rl.prototype,"mode"),qy([m()],Rl.prototype,"clickable");var ZI=Object.defineProperty,Tl=(o,e,t,s)=>{for(var n=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=l(e,t,n)||n);return n&&ZI(e,t,n),n};class oo extends I{constructor(){super(...arguments),a(this,"side","none"),a(this,"controller",!0),a(this,"hands",!1),a(this,"controlVisibility",!0),a(this,"useGripSpace",!1),a(this,"resetTransformAfterXRSession",!0),a(this,"_startPosition",new x),a(this,"_startRotation",new H),a(this,"_startScale",new x)}get activeAndEnabled(){return!0}onEnterXR(e){this._startPosition.copy(this.gameObject.position),this._startRotation.copy(this.gameObject.quaternion),this._startScale.copy(this.gameObject.scale)}onUpdateXR(e){if(!this.enabled)return;const t=e.xr.getController(this.side);if(t){if(t.hand&&!this.hands){this.controlVisibility&&(this.gameObject.visible=!1);return}else if(!this.controller){this.controlVisibility&&(this.gameObject.visible=!1);return}this.controlVisibility&&(this.gameObject.visible=!0),this.useGripSpace||t.targetRayMode==="transient-pointer"?(this.gameObject.worldPosition=t.gripWorldPosition,this.gameObject.worldQuaternion=t.gripWorldQuaternion,this.gameObject.worldScale=X(t.xr.rigScale,t.xr.rigScale,t.xr.rigScale).multiply(this._startScale)):(this.gameObject.worldPosition=t.rayWorldPosition,this.gameObject.worldQuaternion=t.rayWorldQuaternion,this.gameObject.worldScale=X(t.xr.rigScale,t.xr.rigScale,t.xr.rigScale).multiply(this._startScale))}}onLeaveXR(e){this.resetTransformAfterXRSession&&(this.gameObject.position.copy(this._startPosition),this.gameObject.quaternion.copy(this._startRotation),this.gameObject.scale.copy(this._startScale))}}Tl([m()],oo.prototype,"side"),Tl([m()],oo.prototype,"controller"),Tl([m()],oo.prototype,"hands"),Tl([m()],oo.prototype,"controlVisibility"),Tl([m()],oo.prototype,"useGripSpace"),Tl([m()],oo.prototype,"resetTransformAfterXRSession");function jS(o,e){const t=o.xr.getFrame();if(!t)return console.warn("No XRFrame available"),!1;const s=t.session.enabledFeatures;if(s&&!s.some(r=>r==="camera-access"))return console.error(`No camera feed available - please request the 'camera-access' feature before starting WebXR or add the ARCameraBackground component to your scene.
1376
+
1377
+ Example to request camera-access in global scope:
1378
+ NeedleXRSession.onSessionRequestStart(evt => {
1379
+ evt.init.optionalFeatures = evt.init.optionalFeatures || [];
1380
+ evt.init.optionalFeatures.push('camera-access');
1381
+ });
1382
+ `),F()&&ec("No camera feed available - please request the 'camera-access' feature before starting WebXR or add the ARCameraBackground component to your scene"),!1;const n=t.getViewerPose(o.xr.getReferenceSpace());if(n)for(const r of n.views)if("camera"in r&&r.camera){let l=o.xr.getBinding();if(l||(l=new XRWebGLBinding(t.session,o.getContext())),l){let c=null;if("getCameraImage"in l){JI(o,e);const h=o.properties.get(e);if(h)return c=l.getCameraImage(r.camera),h.__webglTexture=c,!0;console.warn("No texture properties found for target texture")}}else console.error(r.camera,o.xr)}else console.error("NO CAMERA IN VIEW");else console.error(o.xr.getReferenceSpace(),t);return!1}const DS=new WeakMap;function JI(o,e){const t=DS.get(e)||new WeakSet;if(t.has(o))return;t.add(o),DS.set(e,t),console.debug("Initialize texture for camera feed");const s=new Me,n=new Ns,r=new wi;r.add(new q(n,s));const l=new we;s.map=e,o.render(r,l)}function eL(o,e,t,s="image/webp",n){return Xy({context:o,width:e,height:t,mimeType:s,camera:n})}function Xy(o){var e,t;o||(o={});const{transparent:s=!1}=o;let{mimeType:n,context:r,width:l,height:c,camera:h}=o;if(!r&&(r=pe.Current,!r))return console.error("Can not save screenshot: No needle-engine context found or provided."),null;if(!h&&(h=r.mainCamera,!h))return console.error("No camera found"),null;const d=r.renderer,u=d.xr.enabled&&d.xr.isPresenting;if(u&&r.currentFrameEvent!=Oe.EarlyUpdate)return console.warn("Screenshot: defer to access XR frame"),new Promise(B=>{jn(z=>{const D=Xy(o);B(D)},Oe.EarlyUpdate,{once:!0})});const p=d.domElement,g=p.width,f=p.height;l||(l=g),c||(c=f);const y=l,b=c;let v=window.devicePixelRatio||1,_=1;r.devicePixelRatio==="auto"||r.devicePixelRatio==="manual"?_=1:_=r.devicePixelRatio/window.devicePixelRatio,v*=_,l/=v,c/=v,l=Math.floor(l),c=Math.floor(c),d.xr.isPresenting&&d.xr.getFrame();const w=d.xr.enabled;d.xr.enabled=!1,d.xr.isPresenting=!1,p.style.width=`${l}px`,p.style.height=`${c}px`;const S=d.getRenderTarget(),k=d.getClearColor(new ae),M=d.getClearAlpha(),T=r.scene.background,L="aspect"in h?h.aspect:null;try{const B=o.render_events!==!1,z=new Array;B&&(Ua(r.scene,Fi,z),z.forEach(j=>{var Q;if(j?.onBeforeRender(),j.isInstancingActive&&j.instances)for(let J=0;J<((Q=j.instances)==null?void 0:Q.length);J++){const oe=j.instances[J];Bn(oe.object,!0)}})),s&&(r.scene.background=null,d.setClearColor(0,0)),o.background&&(r.scene.background=null,d.setClearColor(o.background),o.background instanceof he&&d.setClearAlpha(o.background.a)),s&&d.setClearAlpha(0),d.setSize(l,c,!1),"cam"in h&&(h=h.threeCamera),h instanceof we&&(h.aspect=l/c,h.updateProjectionMatrix());const D="type"in o&&o.type==="texture";let V=null;D&&(V=new Hs(l,c,{wrapS:Dv,wrapT:Dv,format:1023}),d.setRenderTarget(V));let $=p;if(u?(V&&console.error('Taking XR screenshots with { type: "texture" } is currently not supported.'),$=Wh.compositeWithCameraImage({width:y,height:b,scene:r.scene,camera:h,renderer:d})):r.renderNow(h||null),h instanceof we&&L!=null&&(h.aspect=L,h.updateProjectionMatrix()),B&&z.forEach(j=>j.onAfterRender()),!n&&"download_filename"in o&&o.download_filename)switch((e=o.download_filename.split(".").pop())==null?void 0:e.toLowerCase()){case"png":n="image/png";break;case"jpg":case"jpeg":n="image/jpeg";break;case"webp":n="image/webp";break}if(s&&o.trim===!0){const j=tL($);j&&($=j)}if("type"in o){if(o.type==="texture")return V?(o.target&&(o.target.image=V?.texture.image,o.target.needsUpdate=!0),V.texture.offset.set(0,-1),V.texture.needsUpdate=!0,V.texture):(console.error("No target texture found"),null);if(o.type==="blob")return new Promise((j,Q)=>{$.toBlob(J=>{j(J)},n)});if(o.type==="share")return new Promise((j,Q)=>{$.toBlob(J=>{if(J&&"share"in navigator){let oe="file_type"in o&&o.file_type||n;n||(oe="image/png");const re=oe?.split("/")[1]||"png",ge=new File([J],"filename"in o?o.filename||`screenshot.${re}`:`screenshot.${re}`,{type:oe});return navigator.share({title:"title"in o?o.title:void 0,text:"text"in o?o.text:void 0,url:"url"in o?o.url:void 0,files:[ge]}).catch(je=>{console.warn("User cancelled share",je.message)}).finally(()=>{j({blob:J,shared:!0})})}return{blob:J,shared:!1}},n)})}const U=$.toDataURL(n);if("download_filename"in o&&o.download_filename){let j=o.download_filename;if(Y.isMobileDevice()&&typeof window<"u"){const Q=j+"_screenshots",J=j.split("."),oe=(t=J.pop())==null?void 0:t.toLowerCase();let re=0;localStorage.getItem(Q)&&(re=parseInt(sessionStorage.getItem(Q)||"0")),re>0&&(j=`${J.join()}-${re}.${oe}`),re+=1,sessionStorage.setItem(Q,re.toString())}BS(U,j)}return U}finally{d.setRenderTarget(S),r.scene.background=T,d.setSize(g,f,!1),d.setClearColor(k,M),L!=null&&h instanceof we&&(h.aspect=L,h.updateProjectionMatrix()),d.xr.enabled=w,d.xr.isPresenting=u,u||r.updateSize(!0)}return null}function tL(o){if(!("document"in globalThis))return null;const e=document.createElement("canvas");e.width=o.width,e.height=o.height;const t=e.getContext("2d");if(!t)return null;t.drawImage(o,0,0);const s=e.width,n=e.height,r=t.getImageData(0,0,s,n).data;let l=n,c=s,h=0,d=0;for(let y=0;y<n;y++)for(let b=0;b<s;b++){const v=(y*s+b)*4;r[v+3]!==0&&(b<c&&(c=b),b>d&&(d=b),y<l&&(l=y),y>h&&(h=y))}const u=d-c+1,p=h-l+1,g=document.createElement("canvas"),f=g.getContext("2d");return f?(g.width=u,g.height=p,f.drawImage(e,c,l,u,p,0,0,u,p),g):null}let Nh=null;function BS(o,e){if(o){if(!o.startsWith("data:image")){console.error("Can not save image: Data url is not an image",o);return}Nh||(Nh=document.createElement("a")),Nh.href=o,Nh.download=e,Nh.click()}}var Wh;(o=>{let e=null,t=null,s=null,n=null,r=null;function l(d){const{renderer:u,width:p,height:g}=d,f=u.xr.enabled,y=u.getRenderTarget(),b=u.autoClear,v=p,_=g,w=p/g;(!s||s.width!==v||s.height!==_)&&(s??(s=new Hs(v,_,{colorSpace:Mn})),s.width=v,s.height=_,s.samples=4,s.texture.repeat.y=-1,s.texture.offset.y=1),(!r||r.width!==v||r.height!==_)&&(r=document.createElement("canvas"),r.width=v,r.height=_,r.style.position="fixed",r.style.top="0px",r.style.right="0px",r.style.width="300px",r.style.height=`${300/w}px`,r.style.zIndex="1000",r.style.pointerEvents="none",r.style.opacity="1.0",r.style.willChange="contents"),e||(e=h({defines:{DECODE_VIDEO_TEXTURE:!0}})),t||(t=h()),n||(n=new De),u.xr.updateCamera(d.camera),u.xr.enabled=!1,u.autoClear=!1,u.clear(),u.setSize(v,_),u.setRenderTarget(s),jS(d.renderer,n)||console.error("Could not update texture from XR frame");const S=P.findObjectOfType(Vh);return S?S.setTexture(n):(e.setTexture(n),u.render(e,d.camera)),u.clearDepth(),u.setSize(v,_),u.render(d.scene,d.camera),u.setRenderTarget(null),t.setTexture(s.texture),u.render(t,d.camera),r.getContext("2d",{alpha:!1}).drawImage(u.domElement,0,0,r.width,r.height),u.setRenderTarget(y),u.xr.enabled=f,u.autoClear=b,r}o.compositeWithCameraImage=l;const c=`
1383
+ uniform sampler2D t2D;
1384
+ varying vec2 vUv;
1385
+
1386
+ void main() {
1387
+
1388
+ vec4 texColor = texture2D( t2D, vUv );
1389
+
1390
+ #ifdef DECODE_VIDEO_TEXTURE
1391
+
1392
+ // inline sRGB decode (TODO: Remove this code when https://crbug.com/1256340 is solved)
1393
+ texColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w );
1394
+
1395
+ #endif
1396
+
1397
+ gl_FragColor = texColor;
1398
+ #include <tonemapping_fragment>
1399
+ #include <colorspace_fragment>
1400
+ }
1401
+ `;function h(d){const u=d?.material||new Ws({name:"BackgroundMaterial",uniforms:jv.clone(wd.background.uniforms),vertexShader:wd.background.vertexShader,fragmentShader:c,defines:d?.defines,side:go,depthTest:!1,depthWrite:!1,fog:!1});Object.defineProperty(u,"map",{get:function(){return this.threeTexture}});const p=new q(new Ns(2,2),u);return Md(p,!1),p.geometry.deleteAttribute("normal"),p.renderOrder=-1e6,p.setTexture=function(g){u.uniforms.t2D.value=g},p}o.makeFullscreenPlane=h})(Wh||(Wh={}));var iL=Object.defineProperty,sL=(o,e,t,s)=>{for(var n=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=l(e,t,n)||n);return n&&iL(e,t,n),n};const FS=C("debugarcamera");class Vh extends I{constructor(){super(...arguments),a(this,"backgroundTint",new he(1,1,1,1)),a(this,"backgroundPlane"),a(this,"threeTexture"),a(this,"forceTextureInitialization",function(){const e=new Me,t=new Ns,s=new wi;s.add(new q(t,e));const n=new we;return function(r,l){e.map=l,r.render(s,n),FS&&console.warn("Force texture initialization")}}()),a(this,"preRender",()=>{if(!(!this||!this.gameObject)&&this.context.renderer.xr.getFrame()){if(!this.threeTexture&&this.context.renderer&&(this.threeTexture=new De,this.forceTextureInitialization(this.context.renderer,this.threeTexture)),this.backgroundPlane===void 0){const e=this.backgroundTint;this.backgroundPlane=Wh.makeFullscreenPlane({material:new Ws({name:"BackgroundMaterial",uniforms:{...jv.clone(wd.background.uniforms),tint:{value:new ye(e.r,e.g,e.b,e.a)}},vertexShader:wd.background.vertexShader,fragmentShader:nL,side:Ci,depthTest:!1,depthWrite:!1,fog:!1})})}this.backgroundPlane.parent!==this.scene&&this.scene.add(this.backgroundPlane),this.backgroundPlane.material instanceof Ws&&this.backgroundPlane.material.uniforms.tint.value.set(this.backgroundTint.r,this.backgroundTint.g,this.backgroundTint.b,this.backgroundTint.a),this.updateFromFrame()}})}onBeforeXR(e,t){e==="immersive-ar"&&(t.optionalFeatures=t.optionalFeatures||[],t.optionalFeatures.push("camera-access"),FS&&console.warn("Requesting camera-access"))}onEnterXR(e){e.xr.mode==="immersive-ar"&&(this.backgroundPlane&&(this.context.scene.add(this.backgroundPlane),this.backgroundPlane.visible=!1),this.backgroundPlane&&this.context.scene.add(this.backgroundPlane),this.context.pre_render_callbacks.push(this.preRender))}onLeaveXR(e){this.backgroundPlane&&this.backgroundPlane.removeFromParent();const t=this.context.pre_render_callbacks.indexOf(this.preRender);t>=0&&this.context.pre_render_callbacks.splice(t,1)}get background(){return this.backgroundPlane}onBeforeRender(e){this.updateFromFrame()}updateFromFrame(){var e;this.threeTexture&&((e=this.context.xr)==null?void 0:e.mode)==="immersive-ar"&&(jS(this.context.renderer,this.threeTexture),this.setTexture(this.threeTexture))}setTexture(e){this.backgroundPlane&&(this.threeTexture=e,this.backgroundPlane.setTexture(this.threeTexture),this.backgroundPlane.visible=!0)}}sL([m(he)],Vh.prototype,"backgroundTint");const nL=`
1402
+ uniform sampler2D t2D;
1403
+ uniform vec4 tint;
1404
+
1405
+ varying vec2 vUv;
1406
+
1407
+ void main() {
1408
+
1409
+ vec4 texColor = texture2D( t2D, vUv );
1410
+ texColor.w = 1.0;
1411
+
1412
+ // inline sRGB decode
1413
+ texColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w );
1414
+
1415
+ gl_FragColor = texColor * tint;
1416
+
1417
+ #include <tonemapping_fragment>
1418
+ #include <colorspace_fragment>
1419
+ }
1420
+ `;var oL=Object.defineProperty,cr=(o,e,t,s)=>{for(var n=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=l(e,t,n)||n);return n&&oL(e,t,n),n};const US=C("debugimagetracking"),Qy=class bv{constructor(e,t,s,n,r,l){a(this,"measuredSize"),a(this,"state"),a(this,"_position"),a(this,"_rotation"),a(this,"_trackingComponent"),a(this,"_trackedImage"),a(this,"_bitmap"),a(this,"_pose"),this._trackingComponent=e,this._trackedImage=t,this._bitmap=s,this.measuredSize=n,this.state=r,this._pose=l}get url(){return this._trackedImage.image??""}get widthInMeters(){return this._trackedImage.widthInMeters??void 0}get bitmap(){return this._bitmap}get model(){return this._trackedImage}getPosition(e){return this.ensureTransformData(),e.copy(this._position),e}getQuaternion(e){return this.ensureTransformData(),e.copy(this._rotation),e}applyToObject(e,t=void 0){this.ensureTransformData();const s=e.position.distanceToSquared(this._position)/.05+e.quaternion.angleTo(this._rotation)/.05;t&&(t*=Math.max(1,s)),t===void 0||t>=1?(e.position.copy(this._position),e.quaternion.copy(this._rotation)):(t=Math.max(0,Math.min(1,t)),e.position.lerp(this._position,t),e.quaternion.slerp(this._rotation,t))}ensureTransformData(){if(!this._position){this._position=bv._positionBuffer.get(),this._rotation=bv._rotationBuffer.get();const e=this._pose.transform,t=ne.active.convertSpace(e);this._position.copy(t?.position),this._rotation.copy(t?.quaternion)}}};a(Qy,"_positionBuffer",new Pi(()=>new x,20)),a(Qy,"_rotationBuffer",new Pi(()=>new H,20));let Yy=Qy;class ro{constructor(){a(this,"image"),a(this,"widthInMeters",.25),a(this,"object"),a(this,"createObjectInstance",!1),a(this,"imageDoesNotMove",!1),a(this,"hideWhenTrackingIsLost",!0)}}cr([m(URL)],ro.prototype,"image"),cr([m()],ro.prototype,"widthInMeters"),cr([m(ce)],ro.prototype,"object"),cr([m()],ro.prototype,"createObjectInstance"),cr([m()],ro.prototype,"imageDoesNotMove"),cr([m()],ro.prototype,"hideWhenTrackingIsLost");class rL{constructor(e,t,s){a(this,"filename"),a(this,"widthInMeters"),a(this,"imageData"),this.filename=e,this.imageData=t,this.widthInMeters=s}get extensionName(){return"image-tracking"}onAfterHierarchy(e,t){const s=Y.getiOSVersion(),n=(s?parseInt(s.split(".")[0]):18)>=18?1:100;t.beginBlock('def Preliminary_ReferenceImage "AnchoringReferenceImage"'),t.appendLine("uniform asset image = @image_tracking/"+this.filename+"@"),t.appendLine("uniform double physicalWidth = "+(this.widthInMeters*n).toFixed(8)),t.closeBlock()}onBeforeBuildDocument(e){const t=P.findObjectOfType(Hh);!t||!t.trackedImages||t.trackedImages.length>1&&(F()&&be("USDZ: Only one tracked image is supported."),console.warn("USDZ: Only one tracked image is supported."))}onAfterSerialize(e){e.files["image_tracking/"+this.filename]=this.imageData}onExportObject(e,t,s){var n;const r=P.findObjectOfType(Hh);if(!(!r||!r.trackedImages)){for(const l of r.trackedImages)if(((n=l.object)==null?void 0:n.asset)===e){const c=P.findObjectOfType(gn);if(!c)continue;const{scale:h,target:d}=c.getARScaleAndTarget();let u=e;const p=new se;if(e!==d)for(;u.parent&&u.parent!==d;)u=u.parent,p.premultiply(u.matrix);const g=p.clone().invert();t.setMatrix(g.scale(new x(h,h,h)));break}}}}var ha;const Ky=(ha=class extends I{constructor(){super(...arguments),a(this,"trackedImages"),a(this,"smooth",!0),a(this,"trackedImageIndexMap",new Map),a(this,"_supported",!0),a(this,"imageToObjectMap",new Map),a(this,"currentImages",[]),a(this,"webXRIncubationsWarning",`Image tracking is currently not supported on this device. On Chrome for Android, you can enable the <a target="_blank" href="#" onclick="() => console.log('I')">chrome://flags/#webxr-incubations</a> flag.`),a(this,"onImageTrackingUpdate",o=>{const e=ne.active;if(e)for(const t of o){const s=t.model,n=t.state==="tracked";if(!s.object)continue;let r=this.imageToObjectMap.get(s);if(r===void 0)r={object:null,frames:0,lastTrackingTime:Date.now()},this.imageToObjectMap.set(s,r),s.object.loadAssetAsync().then(l=>{if(s.createObjectInstance&&l&&(l=P.instantiate(l)),l){r.object=l;for(const c of l.getComponentsInChildren(Fi))c.setInstancingEnabled(!1);e.rig?(e.rig.gameObject.add(l),t.applyToObject(l),l.activeSelf||P.setActive(l,!0)):console.warn("XRImageTracking: missing XRRig")}});else{if(r.frames++,n&&(r.lastTrackingTime=Date.now()),s.imageDoesNotMove&&r.frames>10||!r.object)continue;e.rig&&(e.rig.gameObject.add(r.object),t.applyToObject(r.object,this.smooth?this.context.time.deltaTimeUnscaled*3:void 0),r.object.activeSelf||P.setActive(r.object,!0))}}})}get supported(){return this._supported}awake(){if(US&&console.log(this),!!this.trackedImages){for(const o of this.trackedImages)if(o.image&&!ha._imageElements.has(o.image)){const e=o.image;ha._imageElements.set(e,null);const t=document.createElement("img");t.src=e,t.addEventListener("load",async()=>{const s=await createImageBitmap(t);ha._imageElements.set(e,s);const n=await k1(s);if(n){const r=await(await n.convertToBlob({type:"image/png"})).arrayBuffer(),l=P.findObjectOfType(gn);l&&this.trackedImages&&(l.extensions.push(new rL("marker.png",new Uint8Array(r),this.trackedImages[0].widthInMeters)),l.anchoringType="image")}})}}}onBeforeXR(o,e){var t;if(this.trackedImages){e.optionalFeatures=e.optionalFeatures||[],e.optionalFeatures.includes("image-tracking")||e.optionalFeatures.push("image-tracking"),e.trackedImages=[];for(const s of this.trackedImages)if((t=s.image)!=null&&t.length&&s.widthInMeters>0){const n=ha._imageElements.get(s.image);n&&(this.trackedImageIndexMap.set(e.trackedImages.length,s),e.trackedImages.push({image:n,widthInMeters:s.widthInMeters}))}}}onEnterXR(o){var e;if(this.trackedImages){for(const t of this.trackedImages)if((e=t.object)!=null&&e.asset){const s=t.object.asset;s.userData||(s.userData={});const n={visible:s.visible,parent:s.parent,matrix:s.matrix.clone()};s.userData["image-tracking"]=n}}for(const t of this.imageToObjectMap.values())t.frames=0}onLeaveXR(o){var e,t;if(!this.supported&&Y.isAndroidDevice()&&be(this.webXRIncubationsWarning),this.trackedImages){for(const s of this.trackedImages)if((e=s.object)!=null&&e.asset){const n=s.object.asset;if(n.userData){const r=n.userData["image-tracking"];r&&(n.visible=r.visible,(t=r.parent)==null||t.add(n),n.matrix.copy(r.matrix),n.matrix.decompose(n.position,n.quaternion,n.scale)),delete n.userData["image-tracking"]}}}}onUpdateXR(o){var e;this.currentImages.length=0;const t=o.xr.frame;if(!t)return;if("getImageTrackingResults"in t){if(((e=o.xr.session.enabledFeatures)==null?void 0:e.includes("image-tracking"))===!1)return;if(t.session&&typeof t.getImageTrackingResults=="function"){const n=t.getImageTrackingResults();if(n.length>0){const r=this.context.renderer.xr.getReferenceSpace();if(r){for(const l of n){const c=l.trackingState,h=l.index,d=this.trackedImageIndexMap.get(h);if(d){const u=t.getPose(l.imageSpace,r),p=new Yy(this,d,l.image,l.measuredSize,c,u);this.currentImages.push(p)}else US&&console.warn("No tracked image for index",h)}if(this.currentImages.length>0)try{this.dispatchEvent(new CustomEvent("image-tracking",{detail:this.currentImages})),this.onImageTrackingUpdate(this.currentImages)}catch(l){console.error(l)}}}}}else{this.didPrintWarning||(this.didPrintWarning=!0,console.log(this.webXRIncubationsWarning)),this._supported=!1,be(this.webXRIncubationsWarning);return}const s=1e3;for(const[n,r]of this.imageToObjectMap){if(!r.object||!n||n.hideWhenTrackingIsLost===!1)continue;let l=!1;for(const c of this.currentImages)if(c.model===n){const h=Date.now()-r.lastTrackingTime;if(n.imageDoesNotMove||c.state==="tracked"||h<=s){l=!0;break}}l||P.setActive(r.object,!1)}}},a(ha,"_imageElements",new Map),ha);cr([m(ro)],Ky.prototype,"trackedImages"),cr([m()],Ky.prototype,"smooth");let Hh=Ky;var aL=Object.defineProperty,El=(o,e,t,s)=>{for(var n=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=l(e,t,n)||n);return n&&aL(e,t,n),n};const da=C("debugplanetracking");class ao extends I{constructor(){super(...arguments),a(this,"dataTemplate"),a(this,"occluder",!0),a(this,"initiateRoomCaptureIfNoData",!0),a(this,"usePlaneData",!0),a(this,"useMeshData",!0),a(this,"runInVR",!0),a(this,"bounds",new xi),a(this,"center",new x),a(this,"labelOffset",new x),a(this,"_dataId",1),a(this,"_allPlanes",new Map),a(this,"_allMeshes",new Map),a(this,"firstTimeNoPlanesDetected",-100),a(this,"makeOccluder",(e,t,s=!1)=>{if(t){if(t instanceof Array){for(const n of t)this.makeOccluder(e,n,s);return}!s&&!t.name.toLowerCase().includes("occlu")||(t.colorWrite=!1,t.depthTest=!0,t.depthWrite=!0,t.transparent=!1,t.polygonOffset=!0,t.polygonOffsetFactor=1,t.polygonOffsetUnits=.1,e.renderOrder=-1e3)}}),a(this,"_flipForwardMatrix",new se().makeRotationY(Math.PI)),a(this,"_verticesCache",new Map)}get trackedPlanes(){return this._allPlanes.values()}get trackedMeshes(){return this._allMeshes.values()}onBeforeXR(e,t){e==="immersive-vr"&&!this.runInVR||(t.optionalFeatures=t.optionalFeatures||[],this.usePlaneData&&!t.optionalFeatures.includes("plane-detection")&&t.optionalFeatures.push("plane-detection"),this.useMeshData&&!t.optionalFeatures.includes("mesh-detection")&&t.optionalFeatures.push("mesh-detection"))}onEnterXR(e){for(const t of this._allPlanes.keys())this.removeData(t,this._allPlanes);for(const t of this._allMeshes.keys())this.removeData(t,this._allMeshes)}onLeaveXR(e){for(const t of this._allPlanes.keys())this.removeData(t,this._allPlanes);for(const t of this._allMeshes.keys())this.removeData(t,this._allMeshes)}onUpdateXR(e){if(!this.runInVR&&e.xr.isVR)return;const t=e.xr.rig;if(!t){console.warn("No XR rig found, cannot parent tracked planes to it");return}const s=e.xr.frame;if(!this.context.renderer.xr.getReferenceSpace())return;const n=s.detectedPlanes,r=s.detectedMeshes,l=n!==void 0&&n.size>0,c=r!==void 0&&r.size>0;if(this.initiateRoomCaptureIfNoData&&(!l&&!c&&this.firstTimeNoPlanesDetected<-10&&(this.firstTimeNoPlanesDetected=Date.now()),(l||c)&&(this.firstTimeNoPlanesDetected=-1),this.firstTimeNoPlanesDetected>0&&Date.now()-this.firstTimeNoPlanesDetected>2500&&"initiateRoomCapture"in s.session&&(s.session.initiateRoomCapture(),this.firstTimeNoPlanesDetected=-1)),n!==void 0&&this.processFrameData(e.xr,t.gameObject,s,n,this._allPlanes),r!==void 0&&this.processFrameData(e.xr,t.gameObject,s,r,this._allMeshes),da){const h=this.context.mainCameraComponent.gameObject.worldPosition;for(const d of this._allPlanes.values())!d.mesh||!d.mesh.visible||(this.bounds.makeEmpty(),d.mesh.traverse(u=>{u instanceof q&&this.bounds.expandByObject(u)}),this.bounds.getCenter(this.center),this.labelOffset.copy(h).sub(this.center).normalize().multiplyScalar(.1),G.DrawLabel(this.center.add(this.labelOffset),(d.xrData.semanticLabel||"plane").toUpperCase()+`
1421
+ `+d.xrData.lastChangedTime.toFixed(2),.02))}}removeData(e,t){const s=t.get(e);if(!s)return;t.delete(e),da&&console.log("Plane no longer tracked, id="+s.id),s.mesh&&(s.mesh.removeFromParent(),s.mesh.traverse(r=>{const l=r.userData.normalsHelper;l?(l.dispose(),l.removeFromParent()):da&&console.warn("No normals helper found for mesh",s.mesh)}),Ei(s.mesh,!0,!0));const n=new CustomEvent("plane-tracking",{detail:{type:"plane-removed",context:s}});this.dispatchEvent(n)}processFrameData(e,t,s,n,r){const l=this.context.renderer.xr.getReferenceSpace();if(l){for(const c of r.keys())n.has(c)||this.removeData(c,r);for(const c of n){const h="planeSpace"in c?c.planeSpace:"meshSpace"in c?c.meshSpace:void 0;if(!h)continue;const d=s.getPose(h,l);let u;if(r.has(c)){const p=r.get(c);if(u=p.mesh,p.timestamp<c.lastChangedTime){if(p.timestamp=c.lastChangedTime,p.mesh){const f=this.createGeometry(c);if(p.mesh instanceof q)p.mesh.geometry.dispose(),p.mesh.geometry=f,this.makeOccluder(p.mesh,p.mesh.material);else if(p.mesh instanceof po)for(const y of p.mesh.children)y instanceof q&&(y.geometry.dispose(),y.geometry=f,this.makeOccluder(y,y.material));if(p.collider){const y=p.mesh;p.collider.sharedMesh=y,p.collider.convex=this.checkIfContextShouldBeConvex(y,p.xrData),p.collider.onDisable(),p.collider.onEnable()}da&&(console.log("Plane updated, id="+p.id,p),p.mesh.traverse(y=>{if(!(y instanceof q))return;const b=y.userData.normalsHelper;b&&b.update()}))}const g=new CustomEvent("plane-tracking",{detail:{type:"plane-updated",context:p}});this.dispatchEvent(g)}}else{if(!this.dataTemplate){const p=new q;da?p.material=new zP:this.occluder?(p.material=new Me,this.makeOccluder(p,p.material,!0)):p.material=new Me({wireframe:!0,opacity:.5,transparent:!0,color:3355443}),this.dataTemplate=new ce("","",p)}if(!this.dataTemplate.asset)this.dataTemplate.loadAssetAsync();else{const p=P.instantiate(this.dataTemplate.asset);if(p.name="xr-tracked-plane",u=p,cg(p,!1),p instanceof q)Te(p.geometry),p.geometry=this.createGeometry(c),this.makeOccluder(p,p.material,this.occluder&&!this.dataTemplate);else if(p instanceof po)for(const y of p.children)y instanceof q&&(Te(y.geometry),y.geometry=this.createGeometry(c),this.makeOccluder(y,y.material,this.occluder&&!this.dataTemplate));const g=p.getComponent(Bo);if(g){const y=p;g.sharedMesh=y,g.convex=this.checkIfContextShouldBeConvex(y,c),g.onDisable(),g.onEnable()}p.matrixAutoUpdate=!1,p.matrixWorldNeedsUpdate=!0,t.add(p);const f={id:this._dataId++,xrData:c,timestamp:c.lastChangedTime,mesh:p,collider:g};r.set(c,f),da&&console.log("New plane detected, id="+f.id,f,{hasCollider:!!g,isGroup:p instanceof po});try{const y=new CustomEvent("plane-tracking",{detail:{type:"plane-added",context:f}});this.dispatchEvent(y)}catch(y){console.error(y)}}}u&&(d?(u.visible=!0,u.matrix.fromArray(d.transform.matrix),u.matrix.premultiply(this._flipForwardMatrix)):u.visible=!1,da&&u.traverse(p=>{if(p instanceof q)if(p.userData.normalsHelper)p.userData.normalsHelper.update();else{const g=new dO(p,.05,255);g.layers.disableAll(),g.layers.set(2),this.context.scene.add(g),p.userData.normalsHelper=g}}))}}}checkIfContextShouldBeConvex(e,t){if(!e)return!0;if(e){const s=new xi;s.expandByObject(e);const n=new x;s.getSize(n);let r=!0;return n.x>2&&n.y>2&&n.z>1.5&&(r=!1),r&&"semanticLabel"in t&&t.semanticLabel==="wall"&&(r=!0),r}return!0}createGeometry(e){return"polygon"in e?this.createPlaneGeometry(e.polygon):"vertices"in e&&"indices"in e?this.createMeshGeometry(e.vertices,e.indices):new Vs}createMeshGeometry(e,t){const s=e.toString()+"_"+t.toString();if(this._verticesCache.has(s))return this._verticesCache.get(s);const n=new Vs;n.setIndex(new bt(t,1)),n.setAttribute("position",new bt(e,3));const r=Array();for(let l=0;l<e.length;l+=3)r.push(e[l],e[l+2]);return n.setAttribute("uv",new bt(e,3)),n.computeVertexNormals(),this._verticesCache.set(s,n),n}createPlaneGeometry(e){const t=new Vs,s=[],n=[];e.forEach(g=>{s.push(g.x,g.y,g.z),n.push(g.x,g.z)});const r=new x(s[0],s[1],s[2]),l=new x(s[3],s[4],s[5]),c=new x(s[6],s[7],s[8]),h=new x,d=new x;h.subVectors(l,r),d.subVectors(c,r),h.cross(d),h.normalize();const u=[];for(let g=0;g<s.length/3;g++)u.push(h.x,h.y,h.z);const p=[];for(let g=2;g<e.length;++g)p.push(0,g-1,g);return t.setAttribute("position",new bt(new Float32Array(s),3)),t.setAttribute("uv",new bt(new Float32Array(n),2)),t.setAttribute("normal",new bt(new Float32Array(u),3)),t.setIndex(p),t.computeBoundingBox(),t.computeBoundingSphere(),t}}El([m(ce)],ao.prototype,"dataTemplate"),El([m()],ao.prototype,"occluder"),El([m()],ao.prototype,"initiateRoomCaptureIfNoData"),El([m()],ao.prototype,"usePlaneData"),El([m()],ao.prototype,"useMeshData"),El([m()],ao.prototype,"runInVR");var lL=Object.defineProperty,cL=(o,e,t,s)=>{for(var n=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(n=l(e,t,n)||n);return n&&lL(e,t,n),n};const zS=C("debugwebxr");class lm extends I{constructor(){super(...arguments),a(this,"priority",0),a(this,"_startScale")}get isActive(){return this.activeAndEnabled&&this.gameObject.visible}setAsActiveXRRig(){var e;(e=ne.active)==null||e.setRigActive(this)}setPriority(e){this.priority=e}awake(){if(zS){const e=new E;e.position.y+=.5,this.gameObject.add(e);const t=e.addNewComponent(Kr);t&&(t.isGizmo=!1);const s=new Si(.5);this.gameObject.add(s)}}isXRRig(){return!0}supportsXR(e){return!0}onEnterXR(e){this._startScale=this.gameObject.scale.clone(),e.xr.addRig(this),zS&&console.log("WebXR: add Rig",this.name,this.priority)}onLeaveXR(e){e.xr.removeRig(this),this._startScale&&this.gameObject&&this.gameObject.scale.copy(this._startScale)}}cL([m()],lm.prototype,"priority");class hL extends I{constructor(){super(...arguments),a(this,"toggleKey","KeyP")}update(){this.context.input.isKeyDown(this.toggleKey)&&this.context.domElement.classList.toggle("presentation-mode")}}R.add("AlignmentConstraint",Mc),R.add("Animation",Bt),R.add("Animator",Mt),R.add("AudioListener",zn),R.add("AudioSource",ss),R.add("Avatar_Brain_LookAt",Bc),R.add("Avatar_MouthShapes",Fc),R.add("Avatar_MustacheShake",Vf),R.add("AvatarBlink_Simple",Br),R.add("AvatarEyeLook_Rotation",Gf),R.add("AxesHelper",Ya),R.add("BasicIKConstraint",Xf),R.add("BoxHelperComponent",Do),R.add("Camera",li),R.add("CharacterController",Fr),R.add("CharacterControllerInput",Hn),R.add("Collider",di),R.add("SphereCollider",Ka),R.add("BoxCollider",Uu),R.add("MeshCollider",Bo),R.add("CapsuleCollider",Wn),R.add("ContactShadows",Nc),R.add("LogStats",Kf),R.add("DeleteBox",zu),R.add("Deletable",Jf),R.add("DeviceFlag",Nu),R.add("DragControls",Wr),R.add("DropListener",$n),R.add("Duplicatable",o0),R.add("EventListEvent",ku),R.add("EventTrigger",$u),R.add("GltfExportBox",v0),R.add("GltfExport",_0),R.add("VariantAction",T0),R.add("ChangeTransformOnClick",$r),R.add("ChangeMaterialOnClick",A0),R.add("SetActiveOnClick",I0),R.add("HideOnStart",cp),R.add("EmphasizeOnClick",cl),R.add("PlayAudioOnClick",No),R.add("PlayAnimationOnClick",Kc),R.add("PreliminaryAction",hl),R.add("PreliminaryTrigger",Zc),R.add("VisibilityAction",Jc),R.add("TapGestureTrigger",D0),R.add("USDZExporter",gn),R.add("Fog",bl),R.add("BoxGizmo",Kr),R.add("GridHelper",_l),R.add("GroundProjectedEnv",en),R.add("UsageMarker",Wc),R.add("Interactable",Zf),R.add("FixedJoint",dy),R.add("HingeJoint",ch),R.add("Light",fi),R.add("LODGroup",dh),R.add("LookAtConstraint",jr),R.add("NeedleMenu",un),R.add("NestedGltf",Sp),R.add("Networking",gy),R.add("OffsetConstraint",Zr),R.add("CameraTargetReachedEvent",Dc),R.add("OrbitControls",_e),R.add("ParticleSystemRenderer",ls),R.add("ParticleSystem",gh),R.add("PlayerColor",Fl),R.add("Antialiasing",yh),R.add("BloomEffect",Bp),R.add("ChromaticAberration",vh),R.add("ColorAdjustments",sr),R.add("DepthOfField",As),R.add("EffectWrapper",_h),R.add("PixelationEffect",wh),R.add("ScreenSpaceAmbientOcclusion",to),R.add("ScreenSpaceAmbientOcclusionN8",Is),R.add("SharpeningEffect",Sh),R.add("TiltShiftEffect",yn),R.add("ToneMappingEffect",ir),R.add("Vignette",oa),R.add("Volume",Pl),R.add("ReflectionProbe",$c),R.add("Renderer",Fi),R.add("MeshRenderer",qc),R.add("SkinnedMeshRenderer",y0),R.add("Rigidbody",dt),R.add("SceneSwitcher",Ze),R.add("ScreenCapture",or),R.add("ShadowCatcher",kh),R.add("RemoteSkybox",Vp),R.add("SmoothFollow",Gp),R.add("SpatialTriggerReceiver",vn),R.add("SpatialTrigger",qp),R.add("SpectatorCamera",Xp),R.add("SpriteRenderer",mi),R.add("SyncedCamera",By),R.add("SyncedRoom",Ls),R.add("SyncedTransform",sn),R.add("TestRunner",zy),R.add("TestSimulateUserData",Ny),R.add("PlayableDirector",kl),R.add("SignalReceiver",Lh),R.add("AnimationTrackHandler",Zp),R.add("AudioTrackHandler",Jp),R.add("SignalTrackHandler",Dh),R.add("ControlTrackHandler",em),R.add("TransformGizmo",la),R.add("BaseUIComponent",hs),R.add("UIRootComponent",sh),R.add("Button",no),R.add("Canvas",yl),R.add("CanvasGroup",Qo),R.add("EventSystem",ti),R.add("Graphic",rh),R.add("MaskableGraphic",ah),R.add("Image",Ml),R.add("RawImage",sm),R.add("InputField",$y),R.add("VerticalLayoutGroup",ey),R.add("HorizontalLayoutGroup",ty),R.add("GridLayoutGroup",iy),R.add("Outline",fl),R.add("ObjectRaycaster",Li),R.add("GraphicRaycaster",Tu),R.add("SpatialGrabRaycaster",Lc),R.add("RectTransform",Ts),R.add("SpatialHtml",Uh),R.add("Text",zt),R.add("EnvironmentScene",om),R.add("LookAt",Gy),R.add("OpenURL",Rl),R.add("VideoPlayer",yt),R.add("Voip",jo),R.add("Avatar",Ho),R.add("XRControllerFollow",oo),R.add("XRControllerModel",pn),R.add("XRControllerMovement",zi),R.add("TeleportTarget",fp),R.add("WebARCameraBackground",Vh),R.add("WebARSessionRoot",Wo),R.add("WebXR",yp),R.add("AvatarMarker",ci),R.add("WebXRImageTracking",Hh),R.add("WebXRPlaneTracking",ao),R.add("XRRig",lm),R.add("XRFlag",ns),R.add("PlayerSync",V0),R.add("PlayerState",Ms),R.add("PresentationMode",hL);const $h=_t,dL=C("debugtypestore");dL&&console.log(R);function uL(o,e){const t=iw(o,e);return t!==void 0?t:null}const pL=new HM,Zy=Symbol("deserialize-queue");async function mL(o,e,t,s=null,n){if(!t){console.debug("Can not create component instances: gltf is null");return}let r=s;typeof r=="number"&&(r=new Lt(s));const l=e.indexOf("?");e=l===-1?e:e.substring(0,l);const c=new rf(t.scene);c.gltfId=e,c.context=o,c.gltf=t,c.nodeToObject=n?.nodeToObjectMap,c.implementationInformation=pL;let h=o[Zy];if(h||(h=o[Zy]=[]),t.scenes)for(const d of t.scenes)await tv(c,d,h);if(t.children)for(const d of t.children)await tv(c,d,h);o.new_scripts_pre_setup_callbacks.push(()=>{const d=o[Zy];if(d){for(const u of d)gL(u,c);d.length=0}if(r){const u={},p=[];ev(t,r,u,p);for(const g of t.scenes)ev(g,r,u,p);for(const g of p)g.resolveGuids(u)}})}const Jy=Symbol("original-component-name"),Al=new Map;function ev(o,e,t,s){if(e===null||!o)return;const n=o.guid,r=o.guid;r!=null&&r.length&&(Al.has(r)||($h&&console.log('Creating InstanceIdProvider with key "'+r+'" for object '+o.name),Al.set(r,new Lt(r))));const l=r&&Al.get(r)||e;if(o.guid=l.generateUUID(),n&&n!=="invalid"&&(t[n]=o.guid),o&&o.userData&&o.userData.components)for(const c of o.userData.components){if(c===null)continue;const h=c.guid;h?Al.has(h)||($h&&console.log('Creating InstanceIdProvider with key "'+h+'" for component '+c[Jy]),Al.set(h,new Lt(h))):$h&&console.warn("Can not create IdProvider: component "+c[Jy]+" has no guid",c.guid);const d=Al.get(h)||e,u=c.guid;c.guid=d.generateUUID(),u&&u!=="invalid"&&(t[u]=c.guid),c.resolveGuids&&s.push(c)}if(o.children)for(const c of o.children)ev(c,e,t,s)}const Gh=[];async function tv(o,e,t,s){var n,r,l,c,h;if(!e)return;const d=e.userData;if(d){const u=d.builtin_components;if(u&&u.length>0)for(const p of u)try{if(p===null)continue;const g=R.get(p.name);if(g!=null){const f=new g;f.sourceId=o.gltfId,Fa(f,p,o.implementationInformation),f.context=o.context,"guid"in p&&(f[sc]=p.guid),f[Jy]=p.name,Pr(e,f,!1),t.push({instance:f,compData:p,obj:e}),f.isCamera&&o.context&&o.context.mainCamera===null&&f.tag==="MainCamera"&&o.context.setCurrentCamera(f),((l=(r=(n=o.context)==null?void 0:n.physics)==null?void 0:r.engine)==null?void 0:l.isInitialized)===!1&&(f.isCollider||f.isRigidbody)&&((h=(c=o.context)==null?void 0:c.physics.engine)==null||h.initialize())}else $h&&console.debug("unknown component: "+p.name),Gh.includes(p.name)||Gh.push(p.name)}catch(g){console.error(p.name+" - "+g.message,g)}if(Gh.length>0){const p=Gh.join(", ");console.warn("unknown components: "+p),Gh.length=0,qt()&&Be(`<strong>Unknown components in scene</strong>:
1422
+
1423
+ ${p}
1424
+
1425
+ This could mean you forgot to add a npmdef to your ExportInfo
1426
+ <a href="https://engine.needle.tools/docs/project_structure.html#creating-and-installing-a-npmdef" target="_blank">documentation</a>`,Oi.Warn)}}if(e.children)for(const u of e.children)await tv(o,u,t)}function gL(o,e){const{instance:t,compData:s,obj:n}=o;e.object=n,e.target=t,tu(t,s,e),$h&&console.debug("add "+s.name,s,t)}class NS{createBuiltinComponents(e,t,s,n,r){return mL(e,t,s,n,r)}writeBuiltinComponentData(e,t){return uL(e,t)}parseSync(e,t,s,n){return HS(e,t,s,n)}loadSync(e,t,s,n,r){return iv(e,t,s,n,r)}}fg(NS);const WS=C("printGltf")||C("printgltf"),fL=C("debugfileformat");async function VS(o,e){const t=await Hx(o,{useExtension:!0})||"unknown";fL&&console.debug(`Determined file type: '${t}' for url '${o}'`,{registeredModelLoaderCallbacks:Ja});for(const s of Ja){const{callback:n}=s,r=n({context:e,url:o,mimetype:t});if(r instanceof Promise&&await r,r)return console.debug(`Using custom loader (${s.name||"unnamed"}) for ${t} at '${o}'`),r}switch(t){case"unsupported":return null;default:case"unknown":{console.warn(`Unknown file type (${t}). Needle Engine will fallback to the GLTFLoader - To support more model formats please create a Needle loader plugin.
1427
+ Use import { NeedleEngineModelLoader } from "@needle-tools/engine" namespace to register your loader.`,o);const s=new Rn;return await Qu(s,e,o),s}case"model/fbx":case"model/vnd.autodesk.fbx":return new Wv;case"model/obj":return new Fm;case"model/vnd.usdz+zip":case"model/vnd.usd+zip":case"model/vnd.usda+zip":return console.warn(t.toUpperCase()+" files are not supported."),null;case"model/gltf+json":case"model/gltf-binary":case"model/vrm":{const s=new Rn;return await Qu(s,e,o),s}}}function yL(o,e){return iv(e?.context||ee.Current,o,o,e?.seed||null,e?.onprogress)}async function HS(o,e,t,s){typeof t!="string"&&(console.warn("Parse gltf binary without path, this might lead to errors in resolving extensions. Please provide the source path of the gltf/glb file",t,typeof t),t=""),WS&&console.log("Parse glTF",t);const n=await VS(t,o);if(!n)return;const{componentsExtension:r}=$S(n,o);if(n instanceof Fm){typeof e!="string"&&(e=new TextDecoder().decode(e));const l=n.parse(e);return await qh(n,o,t,l,s,r)}if(!(n instanceof Rn)){if(n.parse===void 0){console.error("Loader does not support parse");return}const l=n.parse(e,t);return await qh(n,o,t,l,s,r)}return new Promise((l,c)=>{try{let h=t.split("?")[0].trimEnd();const d=h.split("/");d.length>0&&d[d.length-1]!==""&&d.pop(),h=d.join("/"),h.endsWith("/")||(h+="/"),n.resourcePath=h,n.parse(e,"",async u=>{const p=await qh(n,o,t,u,s,r);l(p)},u=>{console.error('Loading asset at "'+t+`" failed
1428
+ `,u),l(void 0)})}catch(h){console.error(h),c(h)}})}async function iv(o,e,t,s,n){bL(e);const r=await VS(e,o);if(!r)return;const{componentsExtension:l}=$S(r,o);if(!(r instanceof Rn)){const c=await r.loadAsync(e,n);return await qh(r,o,e,c,s,l)}return new Promise((c,h)=>{try{r.load(e,async d=>{const u=await qh(r,o,t,d,s,l);c(u)},d=>{n?.call(r,d)},d=>{console.error('Loading asset at "'+e+`" failed
1429
+ `,d),c(void 0)})}catch(d){console.error(d),h(d)}})}function $S(o,e){const t=u0(o);return o instanceof Rn&&Tf(o,e),{componentsExtension:t}}async function qh(o,e,t,s,n,r){var l;if(WS&&console.warn("Loaded",t,s),s==null)return console.error(`Loaded model is null '${t}' - please make sure the loader is registered correctly`),{scene:new E,animations:[],scenes:[]};if(typeof s!="object")return console.error(`Loaded model is not an object '${t}' - please make sure the loader is registered correctly`),{scene:new E,animations:[],scenes:[]};if(s instanceof E)s={scene:s,animations:s.animations,scenes:[s]};else if(s instanceof Vs){const c=new vt({color:new ae(14540253)}),h=new q(s,c);s={scene:h,animations:[],scenes:[h]}}else Array.isArray(s.scenes)===!1&&console.error(`[Needle Engine] The loaded model object does not have a scenes property '${t}' - please make sure the loader is registered correctly and three.js is not imported multiple times.`);if(t.includes("?")&&(t=t.split("?")[0]),"scenes"in s)for(const c of s.scenes)c&&!((l=c.animations)!=null&&l.length)&&(c.animations=[...s.animations]);return _L(o,s),Px(s)&&(s1(t,s,e),await ws().createBuiltinComponents(e,t,s,n,r||void 0)),await vL(s.scene,e,e.mainCamera),s}async function vL(o,e,t){t||(t=e.mainCamera);try{t?await e.renderer.compileAsync(o,t,e.scene).catch(s=>{console.warn(s.message)}):RM(o,e)}catch(s){console.warn(s?.message||s)}}function bL(o){if(new URL(o,window.location.href).href.startsWith("file://")){const e=`Hi - it looks like you are trying to load a local file which will not work. You need to use a webserver to serve your files.
1430
+ Please refer to the documentation on <a href="https://fwd.needle.tools/needle-engine/docs/local-server">https://docs.needle.tools</a> or ask for help in our <a href="https://discord.needle.tools">discord community</a>`;Be(e),console.warn(e)}}function _L(o,e){if(o instanceof Wv||o instanceof Fm){let t=e;t instanceof E||(t=e.scene),t.traverse(s=>{const n=s;n!=null&&n.isMesh&&hg(n,n.material)})}}const Xh=C("debugoverlay"),GS="ar",wL="quit-ar";class xL{constructor(){a(this,"arContainer",null),a(this,"currentSession",null),a(this,"_createdAROnlyElements",[]),a(this,"_reparentedObjects",[]),a(this,"contentElement",null),a(this,"originalDomOverlayParent",null),a(this,"requestEndAR",()=>{this.onRequestedEndAR()})}get ARContainer(){return this.arContainer}onBegin(e,t,s){var n;if(this.currentSession=s,this.arContainer=t,Y.isMozillaXR()){const r=e.domElement.children;for(let l=0;l<r?.length;l++){const c=r[l];if(!c||c===this.arContainer)return;this._reparentedObjects.push({el:c,previousParent:c.parentElement}),(n=this.arContainer)==null||n.appendChild(c)}t?(this.originalDomOverlayParent=t.parentNode,this.originalDomOverlayParent&&(console.log("Reparent DOM Overlay to body",t,t.style.display),t.style.display="",t.style.visibility="",document.body.appendChild(t))):console.warn("WebXRViewer: No DOM Overlay found")}this.ensureQuitARButton(this.arContainer)}onEnd(e){var t;for(const s of this._createdAROnlyElements)s.remove&&s.remove();for(const s of this._reparentedObjects){const n=s.el;(t=s.previousParent)==null||t.appendChild(n)}this._reparentedObjects.length=0,Y.isMozillaXR()&&setTimeout(()=>{var s;const n=e.renderer.domElement;n&&((s=e.domElement.shadowRoot)==null||s.prepend(n));const r=document.querySelectorAll("*");for(var l=0;l<r.length;l++){const c=r[l];c&&c._displayChanged!==void 0&&c._displayWas!==void 0&&(c.style.display=c._displayWas)}},10)}createOverlayContainer(e){if(this.contentElement)return this.contentElement;Xh&&console.log("Setup overlay container");const t=e.shadowRoot.querySelector(".content");this.contentElement=t;const s=e.shadowRoot.querySelector(".overlay-content");return s&&t.appendChild(s),Xh&&!Y.isMobileDevice()&&this.ensureQuitARButton(t),t}onRequestedEndAR(){this.currentSession&&(this.currentSession.end(),this.currentSession=null)}ensureQuitARButton(e){const t=document.createElement("slot");t.setAttribute("name","quit-ar"),this.appendElement(t,e),this._createdAROnlyElements.push(t),t.style.pointerEvents="auto";const s=document.querySelector(`.${wL}`);if(s){s.addEventListener("click",this.requestEndAR),Xh&&s.addEventListener("click",()=>console.log("Clicked quit-ar button"));return}t.addEventListener("click",this.requestEndAR),Xh&&t.addEventListener("click",()=>console.log("Clicked fallback close button"));const n=document.createElement("div");n.style.cssText=`
1431
+ position: fixed;
1432
+ top: 0;
1433
+ right: 0;
1434
+ z-index: 600;
1435
+ pointer-events: all;
1436
+ `,this.appendElement(n,t);var r=document.createElementNS("http://www.w3.org/2000/svg","svg");r.classList.add("quit-ar-button"),r.setAttribute("width","40px"),r.setAttribute("height","40px"),r.style.cssText=`
1437
+ background: rgba(255, 255, 255, .4);
1438
+ -webkit-backdrop-filter: blur(8px);
1439
+ backdrop-filter: blur(8px);
1440
+ border-radius: 50%;
1441
+ box-shadow: 0 0 5px rgba(0,0,0,.3);
1442
+ outline: 1px solid rgba(255, 255, 255, .6);
1443
+ display: flex;
1444
+ justify-content: center;
1445
+ align-items: center;
1446
+ `,n.appendChild(r);var l=document.createElementNS("http://www.w3.org/2000/svg","path");l.setAttribute("d","M 12,12 L 28,28 M 28,12 12,28"),l.setAttribute("stroke","#000000"),l.setAttribute("stroke-width","2px"),l.style.cssText=`
1447
+ /**filter: drop-shadow(0 0px 1.2px rgba(0,0,0,.7));**/
1448
+ `,r.appendChild(l),Xh&&console.log("Created fallback close button",r,e)}appendElement(e,t){return t.shadowRoot?t.shadowRoot.appendChild(e):t.appendChild(e)}}const ua=C("debugloading"),Qh=C("debugloadingrendering"),qS=C("debuglicense");class SL{constructor(){a(this,"className"),a(this,"additionalClasses")}}let Yh=0,XS;function sv(o){ua&&console.log(o.progress.loaded.toFixed(0)+"/"+o.progress.total.toFixed(0),o);const e=o.count,t=o.progress.total;t===0||t===void 0?(XS!==o.name&&(Yh=0),XS=o.name,Yh+=(1-Yh)*.001,ua&&be("Loading "+o.name+" did not report total size")):Yh=o.progress.loaded/t;const s=o.index/e+Yh/e;return W.clamp01(s)}const QS=class _v{constructor(e,t){a(this,"loadingProgress",0),a(this,"_element"),a(this,"_progress",0),a(this,"_allowCustomLoadingElement",!0),a(this,"_loadingElement"),a(this,"_loadingTextContainer",null),a(this,"_loadingBar",null),a(this,"_messageContainer",null),a(this,"_loadingElementOptions"),a(this,"_progressLoop"),this._element=e,this._loadingElementOptions=t}async onLoadingBegin(e){const t=this._element.shadowRoot||this._element;if(ua&&console.warn("Begin Loading"),!this._loadingElement){for(let s=0;s<t.children.length;s++){const n=t.children[s];if(n.classList.contains(_v.LoadingContainerClassName)){if(!this._allowCustomLoadingElement){ua&&console.warn("Remove custom loading container"),t.removeChild(n);continue}this._loadingElement=this.createLoadingElement(n)}}this._loadingElement||(this._loadingElement=this.createLoadingElement())}this._progress=0,this.loadingProgress=0,this._loadingElement.style.display="flex",t.appendChild(this._loadingElement),this.smoothProgressLoop(),this.setMessage(e??"")}onLoadingUpdate(e,t){var s;if(!((s=this._loadingElement)!=null&&s.parentNode))return;let n=0;typeof e=="number"?n=e:("index"in e&&(n=sv(e)),!t&&"name"in e&&this.setMessage("loading "+e.name)),this.loadingProgress=n,t&&this.setMessage(t),this.updateDisplay()}onLoadingFinished(){ua&&console.warn("Finished Loading"),Qh||(this.loadingProgress=1,this.onDoneLoading())}setMessage(e){this._messageContainer&&(this._messageContainer.innerText=e)}smoothProgressLoop(){if(this._progressLoop)return;let e=1/12;Qh&&(e=1/500,typeof Qh=="number"&&(e*=Qh)),this._progressLoop=setInterval(()=>{this.loadingProgress>=.95&&!Qh&&(e=.9),this._progress=W.lerp(this._progress,this.loadingProgress,e*this.loadingProgress),this.updateDisplay()},e)}onDoneLoading(){this._loadingElement&&(ua&&console.log("Hiding loading element"),this._loadingElement.style.display="none",this._loadingElement.remove()),this._progressLoop&&clearInterval(this._progressLoop),this._progressLoop=null}updateDisplay(){const e=this._progress,t=(e*100).toFixed(0)+"%";this._loadingBar&&(this._loadingBar.style.width=e*100+"%"),this._loadingTextContainer&&(this._loadingTextContainer.textContent=t)}createLoadingElement(e){var t,s;ua&&!e&&console.log("Creating loading element"),this._loadingElement=e||document.createElement("div");let n=this._element.getAttribute("loading-style");(!n||n==="auto")&&(window.matchMedia("(prefers-color-scheme: dark)").matches?n="dark":n="light");const r=Zs();if(!e){this._loadingElement.style.position="absolute",this._loadingElement.style.width="100%",this._loadingElement.style.height="100%",this._loadingElement.style.left="0",this._loadingElement.style.top="0";const y=this._element.getAttribute("loading-background");y?this._loadingElement.style.background=y:this._loadingElement.style.backgroundColor="transparent",this._loadingElement.style.display="flex",this._loadingElement.style.alignItems="center",this._loadingElement.style.justifyContent="center",this._loadingElement.style.zIndex=Number.MAX_SAFE_INTEGER.toString(),this._loadingElement.style.flexDirection="column",this._loadingElement.style.pointerEvents="none",this._loadingElement.style.color="white",this._loadingElement.style.fontFamily='system-ui, Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol"',this._loadingElement.style.fontSize="1rem",n==="light"?this._loadingElement.style.color="rgba(0,0,0,.6)":this._loadingElement.style.color="rgba(255,255,255,.3)"}const l=((t=this._loadingElementOptions)==null?void 0:t.className)??_v.LoadingContainerClassName;if(this._loadingElement.classList.add(l),(s=this._loadingElementOptions)!=null&&s.additionalClasses)for(const y of this._loadingElementOptions.additionalClasses)this._loadingElement.classList.add(y);const c=document.createElement("div");this._loadingElement.appendChild(c);const h=document.createElement("img"),d=120;if(h.style.width=`${d}px`,h.style.height=`${d}px`,h.style.paddingTop="20px",h.style.paddingBottom="10px",h.style.margin="0px",h.style.userSelect="none",h.style.objectFit="contain",h.style.transition="transform 1.5s ease-out, opacity .3s ease-in-out",h.style.transform="translateY(30px)",h.style.opacity="0.05",setTimeout(()=>{h.style.opacity="1",h.style.transform="translateY(0px)"},1),h.src=eb,r&&this._element){const y=this._element.getAttribute("loading-logo-src");y&&(h.src=y)}c.appendChild(h);const u=document.createElement("div");u.style.cssText=`
1449
+ display: flex;
1450
+ flex-direction: column;
1451
+ align-items: center;
1452
+ justify-content: center;
1453
+ width: 100%;
1454
+ opacity: 0;
1455
+ transition: opacity 1s ease-in-out 4s;
1456
+ `,setTimeout(()=>{u.style.opacity="1"},1),this._loadingElement.appendChild(u);const p=document.createElement("div"),g=100;p.style.display="flex",p.style.width=g+"%",p.style.height="3px",p.style.position="absolute",p.style.left="0",p.style.bottom="0px",p.style.opacity="0",p.style.transition="opacity 1s ease-in-out 2s",setTimeout(()=>{p.style.opacity="1"},1),n==="light"?p.style.backgroundColor="rgba(0,0,0,.2)":p.style.backgroundColor="rgba(255,255,255,.2)",this._loadingElement.appendChild(p),this._loadingBar=document.createElement("div"),p.appendChild(this._loadingBar);const f=function(y){return W.lerp(0,g,y)+"%"};if(this._loadingBar.style.background="#66A22F",this._loadingBar.style.backgroundAttachment="fixed",this._loadingBar.style.width="0%",this._loadingBar.style.height="100%",r&&this._element){const y=this._element.getAttribute("primary-color"),b=this._element.getAttribute("secondary-color");y&&b?this._loadingBar.style.background=`linear-gradient(90deg, ${y} ${f(0)}, ${b} ${f(1)})`:y?this._loadingBar.style.background=y:b&&(this._loadingBar.style.background=b)}return this.handleRuntimeLicense(this._loadingElement),this._loadingElement}async handleRuntimeLicense(e){let t=Js();if(t)return;qS&&console.log("Loading UI has commercial license?",t);const s=document.createElement("div");s.style.paddingTop=".6em",s.style.fontSize=".8em",s.style.textTransform="uppercase",s.innerText=`NEEDLE ENGINE NON COMMERCIAL VERSION
1457
+ CLICK HERE TO GET A LICENSE`,s.style.cursor="pointer",s.style.userSelect="none",s.style.textAlign="center",s.style.pointerEvents="all",s.addEventListener("click",()=>window.open("https://needle.tools/pricing","_self")),s.style.opacity="0",e.appendChild(s),!F()&&Ar&&(qS&&console.log("Waiting for runtime license check"),await Ar,t=Js()),!t&&(s.style.transition="opacity .5s ease-in-out",s.style.opacity="1")}};a(QS,"LoadingContainerClassName","loading");let YS=QS;fg(NS);const Ie=C("debugwebcomponent"),KS="needle-engine",ZS="vr",JS="desktop",CL=[GS,ZS,JS],Kh="ar-session-active",Zh="desktop-session-active",PL=["public-key","version","hash","src","camera-controls","loadstart","progress","loadfinished","dracoDecoderPath","dracoDecoderType","ktx2DecoderPath","tone-mapping","tone-mapping-exposure","background-blurriness","background-color"];class nv extends HTMLElement{constructor(){super(),a(this,"_context"),a(this,"_overlay_ar"),a(this,"_loadingProgress01",0),a(this,"_loadingView"),a(this,"_previousSrc",null),a(this,"_didFullyLoad",!1),a(this,"_loadId",0),a(this,"_abortController",null),a(this,"_lastSourceFiles",null),a(this,"_createContextPromise",null),a(this,"onXRSessionStarted",()=>{var t;const s=this.context.xrSessionMode;s==="immersive-ar"?this.onEnterAR(this.context.xrSession):s==="immersive-vr"&&this.onEnterVR(this.context.xrSession),(t=this.context.xrSession)==null||t.addEventListener("end",()=>{this.dispatchEvent(new CustomEvent("xr-session-ended",{detail:{session:this.context.xrSession,context:this._context,sessionMode:s}})),s==="immersive-ar"?this.onExitAR(this.context.xrSession):s==="immersive-vr"&&this.onExitVR(this.context.xrSession)})}),a(this,"onReady",()=>{var t;return(t=this._loadingView)==null?void 0:t.onLoadingFinished()}),a(this,"onError",()=>{var t;return(t=this._loadingView)==null?void 0:t.setMessage("Loading failed!")}),a(this,"_previouslyRegisteredMap",new Map),this._overlay_ar=new xL,this.addEventListener("ready",this.onReady),$w(),this.attachShadow({mode:"open"});const e=document.createElement("template");e.innerHTML=`<style>
1458
+ @import url('https://fonts.googleapis.com/css2?family=Roboto+Flex:opsz,wght@8..144,100..1000&display=swap');
1459
+
1460
+ :host {
1461
+ position: absolute;
1462
+ display: block;
1463
+ width: max(600px, 100%);
1464
+ height: max(300px, 100%);
1465
+ touch-action: none;
1466
+
1467
+ -webkit-tap-highlight-color: transparent;
1468
+ }
1469
+
1470
+ @media (max-width: 600px) {
1471
+ :host {
1472
+ width: 100%;
1473
+ }
1474
+ }
1475
+ @media (max-height: 300px) {
1476
+ :host {
1477
+ height: 100%;
1478
+ }
1479
+ }
1480
+
1481
+ :host > div.canvas-wrapper {
1482
+ width: 100%;
1483
+ height: 100%;
1484
+ }
1485
+
1486
+ :host canvas {
1487
+ position: absolute;
1488
+ user-select: none;
1489
+ -webkit-user-select: none;
1490
+
1491
+ /** allow touch panning but no pinch zoom **/
1492
+ /** but this doesnt work yet:
1493
+ * touch-action: pan-x, pan-y;
1494
+ **/
1495
+
1496
+ -webkit-touch-callout: none;
1497
+ -webkit-user-drag: none;
1498
+ -webkit-user-modify: none;
1499
+
1500
+ left: 0;
1501
+ top: 0;
1502
+ }
1503
+ :host .content {
1504
+ position: absolute;
1505
+ top: 0;
1506
+ width: 100%;
1507
+ height: 100%;
1508
+ visibility: visible;
1509
+ z-index: 500; /* < must be less than the webxr buttons element */
1510
+ pointer-events: none;
1511
+ }
1512
+ :host .overlay-content {
1513
+ position: absolute;
1514
+ user-select: auto;
1515
+ pointer-events: all;
1516
+ }
1517
+ :host slot[name="quit-ar"]:hover {
1518
+ cursor: pointer;
1519
+ }
1520
+ :host .quit-ar-button {
1521
+ position: absolute;
1522
+ // top: env(titlebar-area-y); /** this doesnt work **/
1523
+ top: 60px; /** camera access needs a bit more space **/
1524
+ right: 20px;
1525
+ z-index: 9999;
1526
+ }
1527
+ </style>
1528
+ <div class="canvas-wrapper"> <!-- this wrapper is necessary for WebXR https://github.com/meta-quest/immersive-web-emulator/issues/55 -->
1529
+ <canvas></canvas>
1530
+ </div>
1531
+ <div class="content">
1532
+ <slot class="overlay-content"></slot>
1533
+ </div>
1534
+ `,this.shadowRoot&&this.shadowRoot.appendChild(e.content.cloneNode(!0)),this._context=new ee({domElement:this}),this.addEventListener("error",this.onError)}static get observedAttributes(){return PL}get loadingProgress01(){return this._loadingProgress01}get loadingFinished(){return this.loadingProgress01>.999}get cameraControls(){const e=this.getAttribute("camera-controls");return e==null?null:!(e===null||e==="False"||e==="false"||e==="0"||e==="none")}getContext(){return new Promise((e,t)=>{if(this._context&&this.loadingFinished)e(this._context);else{const s=()=>{this.removeEventListener("loadfinished",s),this._context&&this.loadingFinished&&e(this._context)};this.addEventListener("loadfinished",s)}})}get context(){return this._context}async connectedCallback(){if(Ie&&console.log("<needle-engine> connected"),this.setPublicKey(),this.setVersion(),this.addEventListener("xr-session-started",this.onXRSessionStarted),this.onSetupDesktop(),!this.getAttribute("src")){const t=globalThis["needle:codegen_files"];Ie&&console.log('src is null, trying to load from globalThis["needle:codegen_files"]',t),t&&(Ie&&console.log('globalThis["needle:codegen_files"]',t),this.setAttribute("src",t))}Ie&&console.log("src",this.getAttribute("src"));const e=this._loadId;setTimeout(()=>{this.isConnected!==!1&&e===this._loadId&&this.onLoad()},1)}disconnectedCallback(){var e;this.removeEventListener("xr-session-started",this.onXRSessionStarted),this._didFullyLoad=!1;const t=this.getAttribute("keep-alive"),s=t==null||t?.length>0&&t!=="true"&&t!=="1";Ie&&console.warn('<needle-engine> disconnected, keep-alive: "'+t+'"',typeof t,"Dispose=",s),s?(Ie&&console.warn("<needle-engine> dispose"),(e=this._context)==null||e.dispose(),this._context=null,this._lastSourceFiles=null,this._loadId+=1):Ie&&console.warn("<needle-engine> is not disposed because keep-alive is set")}attributeChangedCallback(e,t,s){switch(Ie&&console.log("attributeChangedCallback",e,t,s),e){case"src":Ie&&console.warn(`<needle-engine src>
1535
+ changed from "`,t,'" to "',s,'"'),this.onLoad();break;case"hash":this._context&&(this._context.hash=s);break;case"loadstart":case"progress":case"loadfinished":typeof s=="string"&&s.length>0&&(Ie&&console.log(e+" attribute changed",s),this.registerEventFromAttribute(e,s));break;case"dracoDecoderPath":Ie&&console.log("dracoDecoderPath",s),ex(s);break;case"dracoDecoderType":s==="wasm"||s==="js"?(Ie&&console.log("dracoDecoderType",s),tx(s)):console.error("Invalid dracoDecoderType",s,"expected js or wasm");break;case"ktx2DecoderPath":Ie&&console.log("ktx2DecoderPath",s),ix(s);break;case"tone-mapping":{this.applyAttributes();break}case"tone-mapping-exposure":{this.applyAttributes();break}case"background-blurriness":{const n=parseFloat(s);n!=null&&this._context&&(this._context.scene.backgroundBlurriness=n);break}case"background-color":{this.applyAttributes();break}case"public-key":{s!=Ma&&this.setPublicKey();break}case"version":{s!=_s&&this.setVersion();break}}}get toneMapping(){return this.getAttribute("tonemapping")||this.getAttribute("tone-mapping")}async onLoad(){var e,t;if(!this.isConnected)return;if(this._context||(Ie&&console.warn("Create new context"),this._context=new ee({domElement:this})),!this._context){console.error("Needle Engine: Context not initialized");return}const s=this.getSourceFiles();if(!this.checkIfSourceHasChanged(s,this._lastSourceFiles))return;this._abortController&&(Ie&&console.warn("Abort previous loading process"),this._abortController.abort(),this._abortController=null),this._lastSourceFiles=s;const n=++this._loadId;if((s==null||s.length<=0)&&(Ie&&console.warn("Clear scene",s),this._context.clear(),n!==this._loadId))return;const r=this.getAttribute("alias");this.classList.add("loading");const l=Js();this.ensureLoadStartIsRegistered();let c=this.dispatchEvent(new CustomEvent("loadstart",{detail:{context:this._context,alias:r},cancelable:!0}));if(l){const v=this.getAttribute("hide-loading-overlay");v!=null&&v!=="0"&&(c=!1)}c===!1&&!l&&(F()||(c=!0),console.warn("Needle Engine: You need a commercial license to override the default loading view. Visit https://needle.tools/pricing"),F()&&be('You need a <a target="_blank" href="https://needle.tools/pricing">commercial license</a> to override the default loading view. This will not work in production.')),!this._loadingView&&c&&(this._loadingView=new YS(this)),c&&(this._didFullyLoad!==!0?(e=this._loadingView)==null||e.onLoadingBegin("begin load"):setTimeout(()=>{this._loadingView&&this._loadingProgress01<.3&&this._loadId===n&&this._loadingView.onLoadingBegin("begin load")},300)),Ie&&console.warn(`--------------
1536
+ Needle Engine: Begin loading `+n+`
1537
+ `,s),this.onBeforeBeginLoading();const h=[],d={context:this._context,name:"",progress:{},index:0,count:s.length,totalProgress01:this._loadingProgress01},u=new CustomEvent("progress",{detail:d}),p=new Array,g=new AbortController;this._abortController=g;const f={files:s,abortSignal:g.signal,onLoadingProgress:v=>{var _;if(Ie&&console.debug("Loading progress: ",v),g.signal.aborted)return;const w=v.index;!p[w]&&v.name&&(p[w]=OL(v.name)),v.name=p[w],c&&((_=this._loadingView)==null||_.onLoadingUpdate(v)),d.name=v.name,d.progress=v.progress,this._loadingProgress01=sv(v),d.totalProgress01=this._loadingProgress01,this.dispatchEvent(u)},onLoadingFinished:(v,_,w)=>{Ie&&console.debug(`Finished loading "${_}" (aborted? ${g.signal.aborted})`),!g.signal.aborted&&w&&h.push({src:_,file:w})}},y=this.getAttribute("hash");y!=null&&(this._context.hash=y),this._context.alias=r,this._createContextPromise=this._context.create(f);const b=await this._createContextPromise;if(this.applyAttributes(),Ie&&console.warn(`--------------
1538
+ Needle Engine: finished loading `+n+`
1539
+ `,s,`Aborted? ${g.signal.aborted}`),g.signal.aborted){console.log("Loading finished but aborted...");return}if(this._loadId!==n){console.log("Load id changed during loading process");return}this._loadingProgress01=1,c&&b&&((t=this._loadingView)==null||t.onLoadingUpdate(1,"creating scene")),this._didFullyLoad=!0,this.classList.remove("loading"),this.classList.add("loading-finished"),this.dispatchEvent(new CustomEvent("loadfinished",{detail:{context:this._context,src:r,loadedFiles:h}}))}applyAttributes(){var e,t;if((e=this._context)!=null&&e.renderer){const r=Ww(this.toneMapping);r!==void 0&&(this._context.renderer.toneMapping=r);const l=this.getAttribute("tone-mapping-exposure");if(l!=null){const c=parseFloat(l);isNaN(c)||(this._context.renderer.toneMappingExposure=c)}}const s=this.getAttribute("background-blurriness");if(s!=null){const r=parseFloat(s);r!==void 0&&this._context&&(this._context.scene.backgroundBlurriness=r)}const n=this.getAttribute("background-color");if((t=this._context)!=null&&t.renderer&&typeof n=="string"&&n.length>0){const r=he.fromColorRepresentation(n);Ie&&console.debug("<needle-engine> background-color changed, str:",n,"\u2192",r),this._context.renderer.setClearColor(r,r.alpha),this.context.scene.background=null}}internalSetLoadingMessage(e){var t;(t=this._loadingView)==null||t.setMessage(e)}getSourceFiles(){const e=this.getAttribute("src");if(!e)return[];let t;Array.isArray(e)?t=e:e.startsWith("[")&&e.endsWith("]")?t=JSON.parse(e):e.includes(",")?t=e.split(","):t=[e];for(let s=t.length-1;s>=0;s--){const n=t[s];(n==="null"||n==="undefined"||n?.length<=0)&&t.splice(s,1)}return t}checkIfSourceHasChanged(e,t){if(e?.length!==t?.length||e==null&&t!==null||e!==null&&t==null)return!0;if(e!==null&&t!==null){for(let s=0;s<e?.length;s++)if(e[s]!==t[s])return!0}return!1}ensureLoadStartIsRegistered(){const e=this.getAttribute("loadstart");e&&this.registerEventFromAttribute("loadstart",e)}registerEventFromAttribute(e,t){const s=this._previouslyRegisteredMap.get(e);if(s&&(this._previouslyRegisteredMap.delete(e),this.removeEventListener(e,s)),typeof t=="string"&&t.length>0)try{const n=(0,eval)(t);typeof n=="function"&&(this._previouslyRegisteredMap.set(e,n),this.addEventListener(e,r=>n?.call(globalThis,this._context,r)))}catch(n){console.error("Error registering event "+e+'="'+t+`" failed with the following error:
1540
+ `,n)}}setPublicKey(){Ma&&Ma.length>0&&this.setAttribute("public-key",Ma)}setVersion(){_s.length>0&&this.setAttribute("version",_s)}getAROverlayContainer(){return this._overlay_ar.createOverlayContainer(this)}getVROverlayContainer(){for(let e=0;e<this.children.length;e++){const t=this.children[e];if(t.classList.contains("vr"))return t}return null}onEnterAR(e){var t;this.onSetupAR();const s=this.getAROverlayContainer();this._overlay_ar.onBegin(this._context,s,e),this.dispatchEvent(new CustomEvent("enter-ar",{detail:{session:e,context:this._context,htmlContainer:(t=this._overlay_ar)==null?void 0:t.ARContainer}}))}onExitAR(e){var t;this._overlay_ar.onEnd(this._context),this.onSetupDesktop(),this.dispatchEvent(new CustomEvent("exit-ar",{detail:{session:e,context:this._context,htmlContainer:(t=this._overlay_ar)==null?void 0:t.ARContainer}}))}onEnterVR(e){this.onSetupVR(),this.dispatchEvent(new CustomEvent("enter-vr",{detail:{session:e,context:this._context}}))}onExitVR(e){this.onSetupDesktop(),this.dispatchEvent(new CustomEvent("exit-vr",{detail:{session:e,context:this._context}}))}onSetupAR(){this.classList.add(Kh),this.classList.remove(Zh);const e=this.getAROverlayContainer();Ie&&console.warn("onSetupAR:",e),e&&(e.classList.add(Kh),e.classList.remove(Zh)),this.foreachHtmlElement(t=>this.setupElementsForMode(t,GS))}onSetupVR(){this.classList.remove(Kh),this.classList.remove(Zh),this.foreachHtmlElement(e=>this.setupElementsForMode(e,ZS))}onSetupDesktop(){this.classList.remove(Kh),this.classList.add(Zh);const e=this.getAROverlayContainer();e&&(e.classList.remove(Kh),e.classList.add(Zh)),this.foreachHtmlElement(t=>this.setupElementsForMode(t,JS))}setupElementsForMode(e,t,s=null){var n,r;if(!(e===((r=(n=this._context)==null?void 0:n.renderer)==null?void 0:r.domElement)||e.id==="VRButton"||e.id==="ARButton"))if(e.classList.contains(t))e.style.visibility="visible",e.style.display==="none"&&(e.style.display="block");else for(const l of CL)e.classList.contains(l)&&(e.style.visibility="hidden",e.style.display="none")}foreachHtmlElement(e){for(let t=0;t<this.children.length;t++){const s=this.children[t];s.style&&e(s)}}onBeforeBeginLoading(){const e=this.getAttribute("dracoDecoderPath");e&&(Ie&&console.log("using custom draco decoder path",e),ex(e));const t=this.getAttribute("dracoDecoderType");t&&(Ie&&console.log("using custom draco decoder type",t),tx(t));const s=this.getAttribute("ktx2DecoderPath");s&&(Ie&&console.log("using custom ktx2 decoder path",s),ix(s))}}typeof window<"u"&&!window.customElements.get(KS)&&window.customElements.define(KS,nv);function OL(o){if(o.startsWith("blob:"))return"blob";const e=o.split("/");let t=e[e.length-1];const s=t.indexOf("?");s>0&&(t=t.substring(0,s));const n=t.indexOf("=");n>0&&(t=t.substring(n));const r=t.split(".").pop(),l=r?["glb","gltf","usdz","usd","fbx","obj","mtl"].indexOf(r.toLowerCase()):-1;if(r&&l>=0&&(t=t.substring(0,t.length-r.length-1)),t=decodeURIComponent(t),t.length>3){let c="",h=!1;const d=["(",")","[","]","{","}",":",";",",",".","!","?"];for(let u=0;u<t.length;u++){let p=t[u];(p==="_"||p==="-")&&(p=" "),!(p===" "&&c.length<=0||d.includes(p)||(c.length===0&&(p=p.toUpperCase()),h&&p===" "))&&(h&&(p=p.toUpperCase()),h=!1,c+=p,p===" "&&(h=!0))}return F()&&t!==c&&console.debug('Generated display name: "'+t+'" \u2192 "'+c+'"'),c.trim()}return F()&&console.debug("Loading: use default name",t),t}const kL=Object.freeze(Object.defineProperty({__proto__:null,NeedleEngineWebComponent:nv},Symbol.toStringTag,{value:"Module"}));function ML(){Ln.registerWaitForInteraction(()=>{const o=NP.getContext();o.addEventListener("statechange",()=>{setTimeout(()=>{const e=o.state;(e==="suspended"||e==="interrupted")&&o.resume().then(()=>{console.log("AudioContext resumed successfully")}).catch(t=>{console.log("Failed to resume AudioContext: "+t)})},500)})})}setTimeout(ML,1e3);const at=C("debugphysics"),ov=C("debugcolliderplacement"),rv=C("debugcollisions"),RL=C("showcolliders"),av=C("debugraycasts"),bi=Symbol("needle component"),ei=Symbol("physics body"),eC=Symbol("rigidbody");globalThis.NEEDLE_USE_RAPIER=globalThis.NEEDLE_USE_RAPIER!==void 0?globalThis.NEEDLE_USE_RAPIER:!0,at&&console.log("Use Rapier",!0,globalThis.NEEDLE_USE_RAPIER),pe.registerCallback(me.ContextCreationStart,o=>{at&&console.log("Register rapier physics backend"),o.context.physics.engine=new tC(o.context)});const Jh=class wm{constructor(e){a(this,"debugRenderColliders",!1),a(this,"debugRenderRaycasts",!1),a(this,"context"),a(this,"_initializePromise"),a(this,"_isInitialized",!1),a(this,"rapierRay"),a(this,"raycastVectorsBuffer",new Pi(()=>new x,10)),a(this,"rapierSphere",null),a(this,"rapierColliderArray",[]),a(this,"rapierIdentityRotation",{x:0,y:0,z:0,w:1}),a(this,"rapierForwardVector",{x:0,y:0,z:1}),a(this,"enabled",!1),a(this,"_tempPosition",new x),a(this,"_tempQuaternion",new H),a(this,"_tempScale",new x),a(this,"_tempMatrix",new se),a(this,"_isUpdatingPhysicsWorld",!1),a(this,"_world"),a(this,"_hasCreatedWorld",!1),a(this,"eventQueue"),a(this,"collisionHandler"),a(this,"objects",[]),a(this,"bodies",[]),a(this,"_meshCache",new Map),a(this,"_gravity",{x:0,y:-9.81,z:0}),a(this,"lines"),a(this,"_tempCenterPos",new x),a(this,"_tempCenterVec",new x),a(this,"_tempCenterQuaternion",new H),this.context=e}removeBody(e){var t,s,n;if(!e)return;this.validate();const r=e[ei];if(e[ei]=null,r&&this.world){const l=this.objects.findIndex(c=>c===e);if(l>=0){const c=this.bodies[l];if(this.bodies.splice(l,1),this.objects.splice(l,1),c instanceof A.RAPIER_PHYSICS.MODULE.Collider){const h=c;(t=this.world)==null||t.removeCollider(h,!0);const d=h.parent();d&&d.numColliders()<=0&&(d[bi]||(s=this.world)==null||s.removeRigidBody(d))}else c instanceof A.RAPIER_PHYSICS.MODULE.RigidBody&&(c.numColliders()<=0?(n=this.world)==null||n.removeRigidBody(c):F()&&(c.did_log_removing||setTimeout(()=>{c.numColliders()>0&&(c.did_log_removing=!0,console.warn("RapierPhysics: removing rigidbody with colliders from the physics world is not possible right now, please remove the colliders first"))},1)))}}}updateBody(e,t,s){if(this.validate(),!!this.enabled&&!(e.destroyed||!e.gameObject)&&!(!t&&!s))if(e.isCollider===!0)console.warn("TODO: implement updating collider position");else{const n=e,r=n[ei];r&&this.syncPhysicsBody(n.gameObject,r,t,s)}}updateProperties(e){if(this.validate(),e.isCollider){const t=e,s=t[ei];s&&(this.internalUpdateColliderProperties(t,s),t.sharedMaterial&&this.updatePhysicsMaterial(t))}else{const t=e,s=this.internal_getRigidbody(t);s&&this.internalUpdateRigidbodyProperties(t,s)}}addForce(e,t,s){this.validate();const n=this.internal_getRigidbody(e);n?n.addForce(t,s):console.warn("Rigidbody doesn't exist: can not apply force (does your object with the Rigidbody have a collider?)")}addImpulse(e,t,s){this.validate();const n=this.internal_getRigidbody(e);n?n.applyImpulse(t,s):console.warn("Rigidbody doesn't exist: can not apply impulse (does your object with the Rigidbody have a collider?)")}getLinearVelocity(e){this.validate();const t=this.internal_getRigidbody(e);return t?t.linvel():null}getAngularVelocity(e){this.validate();const t=this.internal_getRigidbody(e);return t?t.angvel():null}resetForces(e,t){this.validate();const s=this.internal_getRigidbody(e);s?.resetForces(t)}resetTorques(e,t){this.validate();const s=this.internal_getRigidbody(e);s?.resetTorques(t)}applyImpulse(e,t,s){this.validate();const n=this.internal_getRigidbody(e);n?n.applyImpulse(t,s):console.warn("Rigidbody doesn't exist: can not apply impulse (does your object with the Rigidbody have a collider?)")}wakeup(e){this.validate();const t=this.internal_getRigidbody(e);t?t.wakeUp():console.warn("Rigidbody doesn't exist: can not wake up (does your object with the Rigidbody have a collider?)")}isSleeping(e){this.validate();const t=this.internal_getRigidbody(e);return t?.isSleeping()}setAngularVelocity(e,t,s){this.validate();const n=this.internal_getRigidbody(e);n?n.setAngvel(t,s):console.warn("Rigidbody doesn't exist: can not set angular velocity (does your object with the Rigidbody have a collider?)")}setLinearVelocity(e,t,s){this.validate();const n=this.internal_getRigidbody(e);n?n.setLinvel(t,s):console.warn("Rigidbody doesn't exist: can not set linear velocity (does your object with the Rigidbody have a collider?)")}get isInitialized(){return this._isInitialized}async initialize(){return this._initializePromise||(this._initializePromise=this.internalInitialization()),this._initializePromise}async internalInitialization(){return C("__nophysics")?(console.warn("Physics are disabled"),!1):(at&&console.log("Initialize rapier physics engine"),this._hasCreatedWorld?(console.error("Invalid call to create physics world: world is already created"),!0):(this._hasCreatedWorld=!0,A.RAPIER_PHYSICS.MAYBEMODULE==null&&(at&&console.trace("Loading rapier physics engine"),await(await A.RAPIER_PHYSICS.load()).init()),at&&console.log("Physics engine initialized, creating world..."),this._world=new A.RAPIER_PHYSICS.MODULE.World(this._gravity),this.rapierRay=new A.RAPIER_PHYSICS.MODULE.Ray({x:0,y:0,z:0},{x:0,y:0,z:1}),this.enabled=!0,this._isInitialized=!0,at&&console.log("Physics world created"),!0))}validate(){this._isInitialized||at&&(this._lastWarnTime=this._lastWarnTime??0,Date.now()-this._lastWarnTime>1e3&&(this._lastWarnTime=Date.now(),console.warn("Physics engine is not initialized")))}raycast(e,t,s){var n;if(!this._isInitialized)return console.log("Physics engine is not initialized"),null;let r=s?.maxDistance,l=s?.solid;r===void 0&&(r=1/0),l===void 0&&(l=!0);const c=this.getPhysicsRay(this.rapierRay,e,t);if(!c)return null;(this.debugRenderRaycasts||av)&&G.DrawRay(c.origin,c.dir,255,1);const h=(n=this.world)==null?void 0:n.castRay(c,r,l,s?.queryFilterFlags,s?.filterGroups,void 0,void 0,d=>{const u=d[bi];return s!=null&&s.filterPredicate?s.filterPredicate(u):s?.useIgnoreRaycastLayer!==!1?!(u!=null&&u.gameObject.layers.isEnabled(2)):!0});if(h){const d=c.pointAt(h.timeOfImpact),u=this.raycastVectorsBuffer.get();return u.set(d.x,d.y,d.z),{point:u,collider:h.collider[bi]}}return null}raycastAndGetNormal(e,t,s){var n;if(!this._isInitialized)return null;let r=s?.maxDistance,l=s?.solid;r===void 0&&(r=1/0),l===void 0&&(l=!0);const c=this.getPhysicsRay(this.rapierRay,e,t);if(!c)return null;(this.debugRenderRaycasts||av)&&G.DrawRay(c.origin,c.dir,255,1);const h=(n=this.world)==null?void 0:n.castRayAndGetNormal(c,r,l,s?.queryFilterFlags,s?.filterGroups,void 0,void 0,d=>{const u=d[bi];return s!=null&&s.filterPredicate?s.filterPredicate(u):s?.useIgnoreRaycastLayer!==!1?!(u!=null&&u.gameObject.layers.isEnabled(2)):!0});if(h){const d=c.pointAt(h.timeOfImpact),u=h.normal,p=this.raycastVectorsBuffer.get(),g=this.raycastVectorsBuffer.get();return p.set(d.x,d.y,d.z),g.set(u.x,u.y,u.z),{point:p,normal:g,collider:h.collider[bi]}}return null}getPhysicsRay(e,t,s){var n,r,l;const c=(n=this.context)==null?void 0:n.mainCamera;if(t===void 0){const u=(r=this.context)==null?void 0:r.input.getPointerPosition(0);if(u)t=u;else return null}if(t.z===void 0){if(!c)return console.error("Can not perform raycast from 2d point - no main camera found"),null;const u=this.raycastVectorsBuffer.get();u.x=t.x,u.y=t.y,u.z=0,(u.x>1||u.y>1||u.y<-1||u.x<-1)&&(at&&console.warn("Converting screenspace to raycast space",u),(l=this.context)==null||l.input.convertScreenspaceToRaycastSpace(u)),u.unproject(c),t=u}const h=t;e.origin.x=h.x,e.origin.y=h.y,e.origin.z=h.z;const d=this.raycastVectorsBuffer.get();if(s)d.set(s.x,s.y,s.z);else{if(!c)return console.error("Can not perform raycast - no camera found"),null;d.set(e.origin.x,e.origin.y,e.origin.z);const u=te(c);d.sub(u)}return d.normalize(),e.dir.x=d.x,e.dir.y=d.y,e.dir.z=d.z,e}sphereOverlap(e,t){return this.rapierColliderArray.length=0,this._isInitialized?this.world?(this.rapierSphere??(this.rapierSphere=new A.RAPIER_PHYSICS.MODULE.Ball(t)),this.rapierSphere.radius=t,(this.debugRenderRaycasts||av)&&G.DrawWireSphere(e,t,3359999,1),this.world.intersectionsWithShape(e,this.rapierIdentityRotation,this.rapierSphere,s=>{const n=s[bi],r=new Rx(n.gameObject,n);return this.rapierColliderArray.push(r),!0},void 0,void 0,void 0,void 0,s=>s.isSensor()?!1:s[bi].gameObject.layers.isEnabled(2)==!1),this.rapierColliderArray):this.rapierColliderArray:this.rapierColliderArray}get world(){return this._world}get isUpdating(){return this._isUpdatingPhysicsWorld}get gravity(){var e;return((e=this.world)==null?void 0:e.gravity)??this._gravity}set gravity(e){this.world?this.world.gravity=e:this._gravity=e}clearCaches(){var e,t,s,n;this._meshCache.clear(),(e=this.eventQueue)!=null&&e.raw&&((t=this.eventQueue)==null||t.free()),(s=this.world)!=null&&s.bodies&&((n=this.world)==null||n.free())}async addBoxCollider(e,t){if(this._isInitialized||await this.initialize(),!e.activeAndEnabled)return;if(!this.enabled){at&&console.warn("Physics are disabled");return}const s=e.gameObject,n=Ge(s,this._tempPosition).multiply(t);n.multiplyScalar(.5),n.x<0&&(n.x=Math.abs(n.x)),n.y<0&&(n.y=Math.abs(n.y)),n.z<0&&(n.z=Math.abs(n.z));const r=1e-7;n.x<r&&(n.x=r),n.y<r&&(n.y=r),n.z<r&&(n.z=r);const l=A.RAPIER_PHYSICS.MODULE.ColliderDesc.cuboid(n.x,n.y,n.z);this.createCollider(e,l)}async addSphereCollider(e){if(this._isInitialized||await this.initialize(),!e.activeAndEnabled)return;if(!this.enabled){at&&console.warn("Physics are disabled");return}const t=A.RAPIER_PHYSICS.MODULE.ColliderDesc.ball(.5);this.createCollider(e,t),this.updateProperties(e)}async addCapsuleCollider(e,t,s){if(this._isInitialized||await this.initialize(),!e.activeAndEnabled)return;if(!this.enabled){at&&console.warn("Physics are disabled");return}const n=e.gameObject,r=Ge(n,this._tempPosition);r.x=Math.abs(r.x),r.y=Math.abs(r.y);const l=s*r.x;t=Math.max(t,l*2);const c=W.clamp(t*.5*r.y-s*r.x,0,Number.MAX_SAFE_INTEGER),h=A.RAPIER_PHYSICS.MODULE.ColliderDesc.capsule(c,l);this.createCollider(e,h)}async addMeshCollider(e,t,s,n){var r,l,c;let h=t.geometry;if(!h){at&&console.warn("Missing mesh geometry",t.name);return}(l=(r=h.index)==null?void 0:r.array)!=null&&l.length||(console.warn(`Your MeshCollider is missing vertices or indices in the assined mesh "${t.name}". Consider providing an indexed geometry.`),h=uO(h));let d=null;const u=h.getAttribute("position");if(u instanceof Mv){const y=u.count;d=new Float32Array(y*3);for(let b=0;b<y;b++){const v=u.getX(b),_=u.getY(b),w=u.getZ(b);d[b*3]=v,d[b*3+1]=_,d[b*3+2]=w}}else d=u.array;if(await this.initialize(),!this.enabled){at&&console.warn("Physics are disabled");return}if(!e.activeAndEnabled)return;const p=(c=h.index)==null?void 0:c.array,g=e.gameObject.worldScale.clone();if(n&&g.multiply(n),Math.abs(g.x-1)>1e-4||Math.abs(g.y-1)>1e-4||Math.abs(g.z-1)>1e-4){const y=`${h.uuid}_${g.x}_${g.y}_${g.z}_${s}`;if(this._meshCache.has(y))at&&console.warn("Use cached mesh collider"),d=this._meshCache.get(y);else{(at||F())&&console.debug(`[Performance] Your MeshCollider "${e.name}" is scaled: consider applying the scale to the collider mesh instead (${g.x}, ${g.y}, ${g.z})`);const b=new Float32Array(d.length);for(let v=0;v<d.length;v+=3)b[v]=d[v]*g.x,b[v+1]=d[v+1]*g.y,b[v+2]=d[v+2]*g.z;d=b,this._meshCache.set(y,b)}}const f=s?A.RAPIER_PHYSICS.MODULE.ColliderDesc.convexHull(d):A.RAPIER_PHYSICS.MODULE.ColliderDesc.trimesh(d,p);f&&this.createCollider(e,f)}updatePhysicsMaterial(e){if(!e)return;const t=e.sharedMaterial,s=e[ei];if(s&&t){if(t.bounciness!==void 0&&s.setRestitution(t.bounciness),t.bounceCombine!==void 0)switch(t.bounceCombine){case wt.Average:s.setRestitutionCombineRule(A.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Average);break;case wt.Maximum:s.setRestitutionCombineRule(A.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Max);break;case wt.Minimum:s.setRestitutionCombineRule(A.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Min);break;case wt.Multiply:s.setRestitutionCombineRule(A.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Multiply);break}if(t.dynamicFriction!==void 0&&s.setFriction(t.dynamicFriction),t.frictionCombine!==void 0)switch(t.frictionCombine){case wt.Average:s.setFrictionCombineRule(A.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Average);break;case wt.Maximum:s.setFrictionCombineRule(A.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Max);break;case wt.Minimum:s.setFrictionCombineRule(A.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Min);break;case wt.Multiply:s.setFrictionCombineRule(A.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Multiply);break}}}getBody(e){return e?e[ei]:null}getComponent(e){return e?e[bi]:null}createCollider(e,t){var s;if(!this.world)throw new Error("Physics world not initialized");const n=this._tempMatrix;let r;e.attachedRigidbody?r=this.getRigidbody(e,this._tempMatrix):(at&&console.log("Create collider without rigidbody",e.name),n.makeRotationFromQuaternion(Se(e.gameObject)),n.setPosition(te(e.gameObject))),n.decompose(this._tempPosition,this._tempQuaternion,this._tempScale),this.tryApplyCenter(e,this._tempPosition),t.setTranslation(this._tempPosition.x,this._tempPosition.y,this._tempPosition.z),t.setRotation(this._tempQuaternion),t.setSensor(e.isTrigger);const l=e.sharedMaterial;if(l){if(l.bounciness!==void 0&&t.setRestitution(l.bounciness),l.bounceCombine!==void 0)switch(l.bounceCombine){case wt.Average:t.setRestitutionCombineRule(A.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Average);break;case wt.Maximum:t.setRestitutionCombineRule(A.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Max);break;case wt.Minimum:t.setRestitutionCombineRule(A.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Min);break;case wt.Multiply:t.setRestitutionCombineRule(A.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Multiply);break}if(l.dynamicFriction!==void 0&&t.setFriction(l.dynamicFriction),l.frictionCombine!==void 0)switch(l.frictionCombine){case wt.Average:t.setFrictionCombineRule(A.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Average);break;case wt.Maximum:t.setFrictionCombineRule(A.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Max);break;case wt.Minimum:t.setFrictionCombineRule(A.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Min);break;case wt.Multiply:t.setFrictionCombineRule(A.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Multiply);break}}((s=e.attachedRigidbody)==null?void 0:s.autoMass)===!1&&(t.setDensity(1e-6),t.setMass(1e-6));try{const c=this.world.createCollider(t,r);return c[bi]=e,e[ei]=c,c.setActiveEvents(A.RAPIER_PHYSICS.MODULE.ActiveEvents.COLLISION_EVENTS),c.setActiveCollisionTypes(A.RAPIER_PHYSICS.MODULE.ActiveCollisionTypes.ALL),this.objects.push(e),this.bodies.push(c),this.updateColliderCollisionGroups(e),c}catch(c){return console.error('Error creating collider "'+e.name+`"
1541
+ Error:`,c),null}}updateColliderCollisionGroups(e){const t=e[ei],s=e.membership;let n=0;if(s==null)n=65535;else for(let c=0;c<s.length;c++){const h=s[c];h>31?console.error(`Rapier only supports 32 layers, layer ${h} is not supported`):n|=1<<Math.floor(h)}const r=e.filter;let l=0;if(r==null)l=65535;else for(let c=0;c<r.length;c++){const h=r[c];h>31?console.error(`Rapier only supports 32 layers, layer ${h} is not supported`):l|=1<<Math.floor(h)}t.setCollisionGroups(n<<16|l)}getRigidbody(e,t){if(!this.world)throw new Error("Physics world not initialized");let s=null;if(e.attachedRigidbody){const n=e.attachedRigidbody;if(s=n[ei],!s){const r=n.isKinematic&&!ov;at&&console.log("Create rigidbody",r);const l=r?A.RAPIER_PHYSICS.MODULE.RigidBodyDesc.kinematicPositionBased():A.RAPIER_PHYSICS.MODULE.RigidBodyDesc.dynamic(),c=te(e.attachedRigidbody.gameObject);l.setTranslation(c.x,c.y,c.z),l.setRotation(Se(e.attachedRigidbody.gameObject)),l.centerOfMass=new A.RAPIER_PHYSICS.MODULE.Vector3(n.centerOfMass.x,n.centerOfMass.y,n.centerOfMass.z),s=this.world.createRigidBody(l),this.bodies.push(s),this.objects.push(n)}s[bi]=n,n[ei]=s,this.internalUpdateRigidbodyProperties(n,s),this.getRigidbodyRelativeMatrix(e.gameObject,n.gameObject,t),e[eC]=s}else{const n=A.RAPIER_PHYSICS.MODULE.RigidBodyDesc.kinematicPositionBased(),r=te(e.gameObject);n.setTranslation(r.x,r.y,r.z),n.setRotation(Se(e.gameObject)),s=this.world.createRigidBody(n),t.identity(),s[bi]=null}return s}internal_getRigidbody(e){return e.isCollider===!0?e[eC]:e[ei]}internalUpdateColliderProperties(e,t){const s=t.shape;let n=!1;switch(s.type){case A.RAPIER_PHYSICS.MODULE.ShapeType.Ball:{const g=s,f=e,y=e.gameObject,b=Ge(y,this._tempPosition),v=Math.abs(f.radius*b.x);n=g.radius!==v,g.radius=v,n&&t.setShape(g);break}case A.RAPIER_PHYSICS.MODULE.ShapeType.Cuboid:const r=s,l=e,c=e.gameObject,h=Ge(c,this._tempPosition),d=Math.abs(l.size.x*.5*h.x),u=Math.abs(l.size.y*.5*h.y),p=Math.abs(l.size.z*.5*h.z);n=r.halfExtents.x!==d||r.halfExtents.y!==u||r.halfExtents.z!==p,r.halfExtents.x=d,r.halfExtents.y=u,r.halfExtents.z=p,n&&t.setShape(r);break}if(n){const r=e.attachedRigidbody;if(r!=null&&r.autoMass){const l=this.getBody(r);l?.recomputeMassPropertiesFromColliders()}}this.updateColliderCollisionGroups(e),e.isTrigger!==t.isSensor()&&t.setSensor(e.isTrigger)}internalUpdateRigidbodyProperties(e,t){if(t.enableCcd(e.collisionDetectionMode!==Pu.Discrete),t.setLinearDamping(e.drag),t.setAngularDamping(e.angularDrag),t.setGravityScale(e.useGravity?e.gravityScale:0,!0),e.dominanceGroup<=127&&e.dominanceGroup>=-127?t.setDominanceGroup(Math.floor(e.dominanceGroup)):t.setDominanceGroup(0),e.autoMass){t.setAdditionalMass(0,!1);for(let s=0;s<t.numColliders();s++)t.collider(s).setDensity(1);t.recomputeMassPropertiesFromColliders()}else{t.setAdditionalMass(e.mass,!1);for(let s=0;s<t.numColliders();s++)t.collider(s).setDensity(1e-7);t.recomputeMassPropertiesFromColliders()}t.setEnabledRotations(!e.lockRotationX,!e.lockRotationY,!e.lockRotationZ,!1),t.setEnabledTranslations(!e.lockPositionX,!e.lockPositionY,!e.lockPositionZ,!1),e.isKinematic?t.setBodyType(A.RAPIER_PHYSICS.MODULE.RigidBodyType.KinematicPositionBased,!1):t.setBodyType(A.RAPIER_PHYSICS.MODULE.RigidBodyType.Dynamic,!1)}step(e){if(this.world&&this.enabled){if(this._isUpdatingPhysicsWorld=!0,this.eventQueue||(this.eventQueue=new A.RAPIER_PHYSICS.MODULE.EventQueue(!1)),e===void 0||e<=0){this._isUpdatingPhysicsWorld=!1;return}else e!==void 0&&(this.world.timestep=W.lerp(this.world.timestep,e,.8));try{this.world.step(this.eventQueue)}catch(t){console.warn("Error running physics step",t)}this._isUpdatingPhysicsWorld=!1}}postStep(){this.world&&this.enabled&&(this._isUpdatingPhysicsWorld=!0,this.syncObjects(),this._isUpdatingPhysicsWorld=!1,this.eventQueue&&!this.collisionHandler&&(this.collisionHandler=new TL(this.world,this.eventQueue)),this.collisionHandler&&(this.collisionHandler.handleCollisionEvents(),this.collisionHandler.update()),this.updateDebugRendering(this.world))}updateDebugRendering(e){var t,s,n,r;if(at||ov||RL||this.debugRenderColliders===!0){if(!this.lines){const c=new kv({color:7855479,fog:!1}),h=new Vs;this.lines=new Ov(h,c),this.lines.layers.disableAll(),this.lines.layers.enable(2)}this.lines.parent!==((t=this.context)==null?void 0:t.scene)&&((s=this.context)==null||s.scene.add(this.lines));const l=e.debugRender();this.lines.geometry.setAttribute("position",new bt(l.vertices,3)),this.lines.geometry.setAttribute("color",new bt(l.colors,4)),(this.context.time.frame%30===0||((n=this.lines.geometry.boundingSphere)==null?void 0:n.radius)===0)&&this.lines.geometry.computeBoundingSphere()}else this.lines&&((r=this.context)==null||r.scene.remove(this.lines))}syncObjects(){if(!ov)for(let e=0;e<this.bodies.length;e++){const t=this.objects[e],s=this.bodies[e],n=t;if(n?.isCollider===!0&&!n.attachedRigidbody){const h=s.parent();h?this.syncPhysicsBody(t.gameObject,h,!0,!0):this.syncPhysicsBody(t.gameObject,s,!0,!0);continue}const r=s.translation(),l=s.rotation();if(Number.isNaN(r.x)||Number.isNaN(l.x)){!n.__COLLIDER_NAN&&F()&&(console.warn("Collider has NaN values",n.name,n.gameObject,s),n.__COLLIDER_NAN=!0);continue}const c=t.center;if(c&&c.isVector3){this._tempQuaternion.set(l.x,l.y,l.z,l.w);const h=this._tempPosition.copy(c).applyQuaternion(this._tempQuaternion),d=Ge(t.gameObject);h.multiply(d),r.x-=h.x,r.y-=h.y,r.z-=h.z}fr(t.gameObject,r.x,r.y,r.z),rg(t.gameObject,l.x,l.y,l.z,l.w)}}syncPhysicsBody(e,t,s,n){if(t instanceof A.RAPIER_PHYSICS.MODULE.RigidBody){const r=te(e,this._tempPosition),l=Se(e,this._tempQuaternion);switch(t.bodyType()){case A.RAPIER_PHYSICS.MODULE.RigidBodyType.Fixed:case A.RAPIER_PHYSICS.MODULE.RigidBodyType.KinematicPositionBased:case A.RAPIER_PHYSICS.MODULE.RigidBodyType.KinematicVelocityBased:s&&t.setNextKinematicTranslation(r),n&&t.setNextKinematicRotation(l);break;default:s&&t.setTranslation(r,!1),n&&t.setRotation(l,!1);break}}else if(t instanceof A.RAPIER_PHYSICS.MODULE.Collider){e.matrixWorldNeedsUpdate&&e.updateWorldMatrix(!0,!1),e.matrixWorld.decompose(this._tempPosition,this._tempQuaternion,this._tempScale);const r=this._tempPosition,l=this._tempQuaternion,c=t[bi];if(this.tryApplyCenter(c,r),s){const h=t.translation();(h.x!==r.x||h.y!==r.y||h.z!==r.z)&&t.setTranslation(r)}if(n){const h=t.rotation();(h.x!==l.x||h.y!==l.y||h.z!==l.z||h.w!==l.w)&&t.setRotation(l)}}}tryApplyCenter(e,t){const s=e.center;s&&e.gameObject&&(s.x!==0||s.y!==0||s.z!==0)&&(this._tempCenterPos.x=s.x,this._tempCenterPos.y=s.y,this._tempCenterPos.z=s.z,Ge(e.gameObject,this._tempCenterVec),this._tempCenterPos.multiply(this._tempCenterVec),e.attachedRigidbody?this._tempCenterPos.applyQuaternion(e.gameObject.quaternion):(Se(e.gameObject,this._tempCenterQuaternion),this._tempCenterPos.applyQuaternion(this._tempCenterQuaternion)),t.x+=this._tempCenterPos.x,t.y+=this._tempCenterPos.y,t.z+=this._tempCenterPos.z)}getRigidbodyRelativeMatrix(e,t,s,n){if(n===void 0&&(n=wm._matricesBuffer,n.length=0),e===t){const r=Ge(e,this._tempPosition);s.makeScale(r.x,r.y,r.z);for(let l=n.length-1;l>=0;l--)s.multiply(n[l]);return s}return n.push(e.matrix),e.parent&&this.getRigidbodyRelativeMatrix(e.parent,t,s,n),s}addFixedJoint(e,t){if(!this.world){console.error("Physics world not initialized");return}const s=e[ei],n=t[ei];this.calculateJointRelativeMatrices(e.gameObject,t.gameObject,this._tempMatrix),this._tempMatrix.decompose(this._tempPosition,this._tempQuaternion,this._tempScale);const r=A.RAPIER_PHYSICS.MODULE.JointData.fixed(wm.centerConnectionPos,wm.centerConnectionRot,this._tempPosition,this._tempQuaternion),l=this.world.createImpulseJoint(r,s,n,!0);at&&console.log("ADD FIXED JOINT",l)}addHingeJoint(e,t,s,n){if(!this.world){console.error("Physics world not initialized");return}const r=e[ei],l=t[ei];this.calculateJointRelativeMatrices(e.gameObject,t.gameObject,this._tempMatrix),this._tempMatrix.decompose(this._tempPosition,this._tempQuaternion,this._tempScale);const c=A.RAPIER_PHYSICS.MODULE.JointData.revolute(s,this._tempPosition,n),h=this.world.createImpulseJoint(c,r,l,!0);at&&console.log("ADD HINGE JOINT",h)}calculateJointRelativeMatrices(e,t,s){e.updateWorldMatrix(!0,!1),t.updateWorldMatrix(!0,!1);const n=e.matrixWorld,r=t.matrixWorld;n.elements[0]=1,n.elements[5]=1,n.elements[10]=1,r.elements[0]=1,r.elements[5]=1,r.elements[10]=1,s.copy(r).premultiply(n.invert()).invert()}};a(Jh,"_didLoadPhysicsEngine",!1),a(Jh,"_matricesBuffer",[]),a(Jh,"centerConnectionPos",{x:0,y:0,z:0}),a(Jh,"centerConnectionRot",{x:0,y:0,z:0,w:1});let tC=Jh;class TL{constructor(e,t){a(this,"world"),a(this,"eventQueue"),a(this,"activeCollisions",[]),a(this,"activeCollisionsStay",[]),a(this,"activeTriggers",[]),this.world=e,this.eventQueue=t}handleCollisionEvents(){this.eventQueue&&this.world&&this.eventQueue.drainCollisionEvents((e,t,s)=>{const n=this.world.getCollider(e),r=this.world.getCollider(t);if(!n||!r)return;const l=n[bi],c=r[bi];rv&&console.log("EVT",l.name,c.name,s,n,r),l&&c&&(s?(this.onCollisionStarted(l,n,c,r),this.onCollisionStarted(c,r,l,n)):(this.onCollisionEnded(l,c),this.onCollisionEnded(c,l)))})}update(){this.onHandleCollisionStay()}onCollisionStarted(e,t,s,n){let r=null;if(e.isTrigger||s.isTrigger)Rr(e.gameObject,l=>{l.onTriggerEnter&&!l.destroyed&&l.onTriggerEnter(s),this.activeTriggers.push({collider:e,component:l,otherCollider:s})});else{const l=e.gameObject;this.world.contactPair(t,n,(c,h)=>{Rr(l,d=>{var u;if(d.destroyed)return;const p=d.onCollisionEnter||d.onCollisionStay||d.onCollisionExit;if(p||rv){if(!r){const g=[],f=c.normal();s instanceof Bo&&s.convex&&(f.x=-f.x,f.y=-f.y,f.z=-f.z);for(let y=0;y<c.numSolverContacts();y++){const b=c.solverContactPoint(y),v=c.contactImpulse(y);if(b){const _=c.contactDist(y),w=c.solverContactFriction(y),S=c.solverContactTangentVelocity(y),k=new kx(b,_,f,v,w,S);g.push(k),rv&&G.DrawDirection(b,f,16711680,3,!0)}}r=new Mx(l,s,g)}if(p){const g={collider:e,component:d,collision:r};this.activeCollisions.push(g),d.onCollisionStay&&this.activeCollisionsStay.push(g),(u=d.onCollisionEnter)==null||u.call(d,r)}}})})}}onHandleCollisionStay(){for(const e of this.activeCollisionsStay){const t=e.component;if(!t.destroyed&&t.activeAndEnabled&&t.onCollisionStay){if(e.collision.collider.destroyed)continue;const s=e.collision;t.onCollisionStay(s)}}for(const e of this.activeTriggers){const t=e.component;if(!t.destroyed&&t.activeAndEnabled&&t.onTriggerStay){const s=e.otherCollider;if(s.destroyed)continue;t.onTriggerStay(s)}}}onCollisionEnded(e,t){if(!(e.destroyed||t.destroyed)){for(let s=0;s<this.activeCollisions.length;s++){const n=this.activeCollisions[s],r=n.collider;if(r.destroyed||n.collision.collider.destroyed){this.activeCollisions.splice(s,1),s--;continue}if(r===e&&n.collision.collider===t){const l=n.component;if(this.activeCollisions.splice(s,1),s--,l.activeAndEnabled&&l.onCollisionExit){const c=n.collision;l.onCollisionExit(c)}}}for(let s=0;s<this.activeCollisionsStay.length;s++){const n=this.activeCollisionsStay[s],r=n.collider;if(r.destroyed||n.collision.collider.destroyed){this.activeCollisionsStay.splice(s,1),s--;continue}if(r===e&&n.collision.collider===t){const l=n.component;if(this.activeCollisionsStay.splice(s,1),s--,l.activeAndEnabled&&l.onCollisionExit){const c=n.collision;l.onCollisionExit(c)}}}for(let s=0;s<this.activeTriggers.length;s++){const n=this.activeTriggers[s],r=n.collider;if(r.destroyed||n.otherCollider.destroyed){this.activeTriggers.splice(s,1),s--;continue}if(r===e&&n.otherCollider===t){const l=n.component;if(this.activeTriggers.splice(s,1),s--,l.activeAndEnabled&&l.onTriggerExit){const c=n.otherCollider;l.onTriggerExit(c)}}}}}}class EL{static async createComparisonScene(e){const{files:t}=e,s=await Promise.all(t.map(y=>new ce(y).loadAssetAsync())),n=new wi;let r=0;for(const y of s)if(y instanceof E){y.position.y=r,n.add(y);const b=ii([y]);r+=b.getSize(new x).y,r+=.1}const l=new we(20);n.add(l);const c=e.environment||"https://dl.polyhaven.org/file/ph-assets/HDRIs/exr/1k/studio_small_09_1k.exr";{let y=null;if(c.endsWith(".hdr")){const b=(await import("./three-examples-DaDLBuy6.min.js").then(v=>v.RGBELoader$1)).RGBELoader;y=new b}else if(c.endsWith(".exr")){const b=(await import("./three-examples-DaDLBuy6.min.js").then(v=>v.EXRLoader$1)).EXRLoader;y=new b}if(y){const b=await y.loadAsync(c).catch(v=>(console.error(v),null));b&&(b.mapping=kn,b.needsUpdate=!0,n.background=b,n.environment=b,n.backgroundBlurriness=.75)}else console.warn("Unsupported environment map format",c)}const h=ii(n.children),d=h.getCenter(new x),u=h.getSize(new x),p=Math.max(u.x,u.y,u.z)/(2*Math.tan(Math.PI*l.fov/360));l.position.set(d.x,d.y,p),l.lookAt(d);const g=new Uv(l,e.domElement||document.body);g.target=d,g.update();const f=(e.domElement||document.body).getBoundingClientRect();return l.aspect=f.width/f.height,l.updateProjectionMatrix(),{scene:n,camera:l}}}let lv=0;function iC(o){o?lv++:lv--}function AL(){return lv>0}const IL={binary:!0,animations:!0};async function LL(o){if(!o.context)throw new Error("No context provided to exportAsGLTF");o.scene||(o.scene=o.context.scene);const e={...IL,...o},{context:t}=e,s=new zv;s.register(c=>new n1(c)),s.register(c=>new uE(c)),s.register(c=>new qx(c)),p0(s,e.context);const n={binary:e.binary,animations:DL(t,e.scene,[])},r=new jL;console.debug("Exporting GLTF",n),r.onBeforeExport(e),iC(!0);const l=await s.parseAsync(e.scene,n).catch(c=>(console.error(c),null));if(iC(!1),r.onAfterExport(e),!l)throw new Error("Failed to export GLTF");if(e.downloadAs!=null){let c=null;if(l instanceof ArrayBuffer?c=new Blob([l],{type:"application/octet-stream"}):console.error("Can not download GLTF as a blob",l),c){const h=URL.createObjectURL(c),d=document.createElement("a");d.href=h;let u=e.downloadAs;!u.endsWith(".glb")&&!u.endsWith(".gltf")&&(u+=e.binary?".glb":".gltf"),d.download=u,d.click()}}return l}const sC=Symbol("needle:weight");class jL{constructor(){a(this,"_undo",[])}onBeforeExport(e){e.context.animations.mixers.forEach(t=>{const s=Va.tryGetActionsFromMixer(t);if(s)for(let n=0;n<s.length;n++){const r=s[n];r[sC]=r.weight,r.weight=0,this._undo.push(()=>{r.weight=r[sC]})}t.update(0)}),e.context.scene.traverse(t=>{if(!l0(t)){const s=t.parent;s&&(t.removeFromParent(),this._undo.push(()=>s.add(t)))}})}onAfterExport(e){this._undo.forEach(t=>t()),this._undo.length=0}}function DL(o,e,t){o.animations.mixers.forEach(n=>{const r=Va.tryGetActionsFromMixer(n);if(r)for(let l=0;l<r.length;l++){const c=r[l].getClip();t.push(c)}}),Array.isArray(e)||(e=[e]);for(const n of e)Va.tryGetAnimationClipsFromObjectHierarchy(n,t);const s=new Set(t);return Array.from(s)}const nC="needle-button",cv=F();var pa,ma,ga,_i,Ds,Il,cm,oC,rC,hm;class hv extends HTMLElement{constructor(){super(),Us(this,cm),Us(this,pa),Us(this,ma),Us(this,ga),Us(this,_i),Us(this,Ds),Us(this,Il),Us(this,hm,e=>{cv&&console.log("Needle Button clicked"),!e.defaultPrevented&&fe(this,_i)&&fe(this,_i).click()}),this.removeEventListener("click",fe(this,hm)),this.addEventListener("click",fe(this,hm))}attributeChangedCallback(e,t,s){cd(this,cm,oC).call(this)}}pa=new WeakMap,ma=new WeakMap,ga=new WeakMap,_i=new WeakMap,Ds=new WeakMap,Il=new WeakMap,cm=new WeakSet,oC=function(){var o,e;if((o=fe(this,_i))==null||o.remove(),this.getAttribute("ar")!=null)fe(this,Ds)??zs(this,Ds,new dl),zs(this,_i,fe(this,Ds).createARButton());else if(this.getAttribute("vr")!=null)fe(this,Ds)??zs(this,Ds,new dl),zs(this,_i,fe(this,Ds).createVRButton());else if(this.getAttribute("quicklook")!=null)fe(this,Ds)??zs(this,Ds,new dl),zs(this,_i,fe(this,Ds).createQuicklookButton());else{cv?console.warn("No button type specified for <needle-button>. Use either ar, vr or quicklook attribute."):console.debug("No button type specified for <needle-button>. Use either ar, vr or quicklook attribute.");return}fe(this,pa)??zs(this,pa,this.attachShadow({mode:"open"})),fe(this,ma)??zs(this,ma,document.createElement("slot")),fe(this,ga)??zs(this,ga,document.createElement("style")),fe(this,ga).innerHTML=`
1542
+ button {
1543
+ all: initial;
1544
+ cursor: inherit;
1545
+ color: inherit;
1546
+ font-family: inherit;
1547
+ gap: inherit;
1548
+ white-space: nowrap;
1549
+ }
1550
+ `,this.getAttribute("unstyled")!=null||(fe(this,ga).innerHTML+=`
1551
+ :host {
1552
+ display: inline-block;
1553
+ background: rgba(255, 255, 255, .8);
1554
+ backdrop-filter: blur(10px);
1555
+ width: fit-content;
1556
+ transition: background .2s;
1557
+
1558
+ cursor: pointer;
1559
+ padding: 0.4rem .5rem;
1560
+ border-radius: 0.8rem;
1561
+ color: black;
1562
+ background: rgba(245, 245, 245, .8);
1563
+ outline: rgba(0,0,0,.05) 1px solid;
1564
+ }
1565
+ :host(:hover) {
1566
+ background: rgba(255, 255, 255, 1);
1567
+ transition: background .2s;
1568
+ }
1569
+ slot {
1570
+ display: flex;
1571
+ align-items: center;
1572
+ justify-content: center;
1573
+ gap: .5rem;
1574
+ }
1575
+ `),fe(this,ma).innerHTML=fe(this,_i).innerHTML,fe(this,ma).style.cssText="display: flex; align-items: center; justify-content: center;",fe(this,_i).innerHTML=fe(this,ma).outerHTML,fe(this,pa).innerHTML=fe(this,_i).outerHTML,fe(this,pa).prepend(fe(this,ga)),mu(xf,{element:fe(this,pa)}),(e=fe(this,Il))==null||e.disconnect(),fe(this,Il)??zs(this,Il,new MutationObserver(()=>cd(this,cm,rC).call(this))),fe(this,Il).observe(fe(this,_i),{attributes:!0}),cv&&console.log("Needle Button updated")},rC=function(){fe(this,_i)&&(fe(this,_i).style.display==="none"?this.style.display="none":this.style.display==="none"&&(this.style.display=""))},hm=new WeakMap,a(hv,"observedAttributes",["ar","vr","quicklook"]),typeof window<"u"&&!window.customElements.get(nC)&&window.customElements.define(nC,hv);const ed=C("debugavatar");class dv{constructor(e,t,s,n){a(this,"root"),a(this,"head"),a(this,"leftHand"),a(this,"rigthHand");var r;this.root=e,this.head=t,this.leftHand=s,this.rigthHand=n,(r=this.root)==null||r.traverse(l=>l.layers.set(2))}get isValid(){return this.head!==null&&this.head!==void 0}}class aC{constructor(){a(this,"avatarRegistryUrl",null)}async getOrCreateNewAvatarInstance(e,t){if(!t)return console.error("Can not create avatar: failed to provide id or root object"),null;let s=null;if(typeof t=="string"){if(s=await this.loadAvatar(e,t),!s){const r=new Fs;s=P.instantiate(Pa(t,e.scene),r)}}else s=t;if(!s)return null;const n=this.findAvatar(s);return n.isValid?(ed&&console.log("[Custom Avatar] valid config",t,ed?n:""),n):(console.warn("[Custom Avatar] config isn't valid",t,ed?n:""),null)}async loadAvatar(e,t){if(console.assert(t!=null&&typeof t=="string","Avatar id must not be null"),t.length<=0||!t)return null;if(ed&&console.log("[Custom Avatar] "+t+", loading..."),t.endsWith(".glb")||(t+=".glb"),this.avatarRegistryUrl===null){const n=await fetch("./"+t);let r=null;if(n.ok){const c=await n.blob();c&&(r=await c.arrayBuffer())}if(!r)return null;const l=await ws().parseSync(e,r,null,0);return l?.scene??null}const s=new Rn;return Tf(s,e),new Promise((n,r)=>{const l=this.avatarRegistryUrl+"/"+t;s.load(l,async c=>{await ws().createBuiltinComponents(e,l,c,null,void 0),n(c.scene)},c=>{ed&&console.log("[Custom Avatar] "+c.loaded/c.total*100+"% loaded of "+c.total/1024+"kB")},c=>{console.error("[Custom Avatar] Error when loading: "+c),n(null)})})}cacheModel(e,t){}findAvatar(e){const t=e;let s=t;s.children.length==1&&(s=e.children[0]);let n=this.findAvatarPart(s,["head"]);const r=this.findAvatarPart(s,["left","hand"]),l=this.findAvatarPart(s,["right","hand"]);if(!n){n=t;const c=new x;new xi().setFromObject(n).getSize(c);const h=Math.max(c.x,c.y,c.z);console.warn("[Custom Avatar] Normalizing head scale, it's too big: "+h+" meters! Should be < 0.3m"),h>.3&&n.scale.multiplyScalar(1/h*.3)}return new dv(t,n,r,l)}findAvatarPart(e,t){const s=e.name.toLowerCase();let n=!0;for(const r of t){if(!n)break;s.indexOf(r)===-1&&(n=!1)}if(n)return e;if(e.children)for(const r of e.children){const l=this.findAvatarPart(r,t);if(l)return l}return null}handleCustomAvatarErrors(e){if(!e.ok)throw Error(e.statusText);return e}}class lC{get extensionName(){return"DocumentExtension"}onAfterBuildDocument(e){}}class cC{}const BL=Object.freeze(Object.defineProperty({__proto__:null,ActionBuilder:ve,ActionCollection:z1,ActionModel:ks,AlignmentConstraint:Mc,Animation:Bt,AnimationCurve:uh,AnimationExtension:ap,AnimationTrackHandler:Zp,Animator:Mt,AnimatorController:us,Antialiasing:yh,AudioExtension:ya,AudioListener:zn,AudioSource:ss,AudioTrackHandler:Jp,Avatar:Ho,AvatarBlink_Simple:Br,AvatarEyeLook_Rotation:Gf,AvatarLoader:aC,AvatarMarker:ci,AvatarModel:dv,Avatar_Brain_LookAt:Bc,Avatar_MouthShapes:Fc,Avatar_MustacheShake:Vf,Avatar_POI:Nn,AxesHelper:Ya,BaseUIComponent:hs,BasicIKConstraint:Xf,BehaviorExtension:q0,BehaviorModel:Zt,BloomEffect:Bp,BoxCollider:Uu,BoxGizmo:Kr,BoxHelperComponent:Do,Button:no,CallInfo:Un,Camera:li,CameraTargetReachedEvent:Dc,Canvas:yl,CanvasGroup:Qo,CapsuleCollider:Wn,ChangeMaterialOnClick:A0,ChangeTransformOnClick:$r,CharacterController:Fr,CharacterControllerInput:Hn,ChromaticAberration:vh,Collider:di,ColorAdjustments:sr,ColorBySpeedModule:xl,ColorOverLifetimeModule:Rp,ContactShadows:Nc,ControlTrackHandler:em,CustomBranding:Yr,Deletable:Jf,DeleteBox:zu,DepthOfField:As,DeviceFlag:Nu,DocumentExtension:lC,DragControls:Wr,DropListener:$n,Duplicatable:o0,EffectWrapper:_h,EmissionModule:eo,EmphasizeOnClick:cl,EnvironmentScene:om,EventList:xe,EventListEvent:ku,EventSystem:ti,EventTrigger:$u,FieldWithDefault:p1,FixedJoint:dy,Fog:bl,GltfExport:_0,GltfExportBox:v0,Gradient:Jr,Graphic:rh,GraphicRaycaster:Tu,GridHelper:_l,GridLayoutGroup:iy,GroundProjectedEnv:en,GroupActionModel:zo,HideOnStart:cp,HingeJoint:ch,HorizontalLayoutGroup:ty,Image:Ml,InheritVelocityModule:vy,InputField:$y,InstanceHandle:f0,InstancingHandler:Ku,Interactable:Zf,Keyframe:yi,LODGroup:dh,LODModel:wl,Light:fi,LimitVelocityOverLifetimeModule:gt,LogStats:Kf,LookAt:Gy,LookAtConstraint:jr,MainModule:Nt,MaskableGraphic:ah,MeshCollider:Bo,MeshRenderer:qc,MinMaxCurve:Z,MinMaxGradient:ea,NeedleMenu:un,NestedGltf:Sp,Networking:gy,NoiseModule:Ce,ObjectRaycaster:Li,OffsetConstraint:Zr,OpenURL:Rl,OrbitControls:_e,Outline:fl,Padding:Qr,ParticleBurst:Mp,ParticleSubEmitter:by,ParticleSystem:gh,ParticleSystemRenderer:ls,PhysicsExtension:X0,PixelationEffect:wh,PlayAnimationOnClick:Kc,PlayAudioOnClick:No,PlayableDirector:kl,PlayerColor:Fl,PointerEventData:ad,PostProcessingHandler:jy,PreliminaryAction:hl,PreliminaryTrigger:Zc,RawImage:sm,Rect:Q1,RectTransform:Ts,ReflectionProbe:$c,RegisteredAnimationInfo:ur,RemoteSkybox:Vp,Renderer:Fi,RendererLightmap:Zu,Rigidbody:dt,RotationBySpeedModule:as,RotationOverLifetimeModule:Es,SceneSwitcher:Ze,ScreenCapture:or,ScreenSpaceAmbientOcclusion:to,ScreenSpaceAmbientOcclusionN8:Is,SetActiveOnClick:I0,ShadowCatcher:kh,ShapeModule:yy,SharpeningEffect:Sh,SignalAsset:Kp,SignalReceiver:Lh,SignalReceiverEvent:Ih,SignalTrackHandler:Dh,Size:X1,SizeBySpeedModule:vi,SizeOverLifetimeModule:ta,SkinnedMeshRenderer:y0,SmoothFollow:Gp,SpatialGrabRaycaster:Lc,SpatialHtml:Uh,SpatialTrigger:qp,SpatialTriggerReceiver:vn,SpectatorCamera:Xp,SphereCollider:Ka,Sprite:Qn,SpriteData:pl,SpriteRenderer:mi,SpriteSheet:ul,SubEmitterSystem:Ip,SyncedCamera:By,SyncedRoom:Ls,SyncedTransform:sn,TapGestureTrigger:D0,TeleportTarget:fp,TestRunner:zy,TestSimulateUserData:Ny,Text:zt,TextBuilder:J0,TextExtension:wp,TextureSheetAnimationModule:Wt,TiltShiftEffect:yn,ToneMappingEffect:ir,TrailModule:We,TransformData:ut,TransformGizmo:la,TriggerBuilder:Et,TriggerModel:ll,UIRaycastUtils:jf,UIRootComponent:sh,USDZExporter:gn,USDZText:Xr,USDZUIExtension:oy,UsageMarker:Wc,VariantAction:T0,VelocityOverLifetimeModule:qe,VerticalLayoutGroup:ey,VideoPlayer:yt,Vignette:oa,VisibilityAction:Jc,Voip:jo,Volume:Pl,VolumeParameter:N,VolumeProfile:Lp,WebARCameraBackground:Vh,WebARSessionRoot:Wo,WebXR:yp,WebXRImageTracking:Hh,WebXRImageTrackingModel:ro,WebXRPlaneTracking:ao,WebXRTrackedImage:Yy,XRControllerFollow:oo,XRControllerModel:pn,XRControllerMovement:zi,XRFlag:ns,XRRig:lm,XRState:ji,__Ignore:cC},Symbol.toStringTag,{value:"Module"})),dm=C("debugmissingcamera");pe.registerCallback(me.MissingCamera,o=>{var e,t,s,n;dm&&console.warn("Creating missing camera");const r=o.context.scene,l=new we;l.name="Default Fallback Camera",r.add(l);const c=new li;if(c.sourceId=((t=(e=o.files)==null?void 0:e[0])==null?void 0:t.src)??"unknown",c.fieldOfView=35,o.context.domElement.getAttribute("transparent")!=null)c.clearFlags=Ao.Uninitialized;else if((s=o.context.domElement.getAttribute("skybox-image"))!=null&&s.length||(n=o.context.domElement.getAttribute("background-image"))!=null&&n.length||o.context.lightmaps.tryGetSkybox(c.sourceId))c.clearFlags=Ao.Skybox,c.backgroundBlurriness=.2;else{if(c.clearFlags=Ao.SolidColor,!o.context.domElement.getAttribute("background-color")){let u="#efefef";typeof window!==void 0&&window.matchMedia("(prefers-color-scheme: dark)").matches&&(u="#1f1f1f"),r.background=new ae(u)}if(!r.environment){const u=new WP(o.context.renderer),p=new om("neutral");r.environment=u.fromScene(p,.025).texture}}const h=Pr(l,c,!0);l.position.x=0,l.position.y=1,l.position.z=2;const d=o.context.domElement;return d?.cameraControls!=!1&&hC(o.context,h),h}),pe.registerCallback(me.ContextCreated,o=>{if(!o.context.mainCamera){dm&&console.log("Will not auto-fit because a default camera exists");return}const e=o.context.domElement;if(e?.cameraControls==!0){const t=_b(o.context.mainCamera);if(t?.isCameraController==!0){dm&&console.log("Will not auto-fit because a camera controller exists");return}hC(o.context)}});function hC(o,e){e=e??o.mainCameraComponent;const t=e?.gameObject;if(dm&&console.log("Creating default camera controls",e?.name),t){const s=fc(t,_e);s.sourceId=e?.sourceId??"unknown";const n=o.domElement.getAttribute("auto-rotate");if(s.autoRotate=n!=null&&n!="0"&&n?.toLowerCase()!="false",s.autoRotateSpeed=.5,s.autoFit=!0,s.autoRotate&&n){const r=parseFloat(n);isNaN(r)||(s.autoRotateSpeed=r)}}else console.warn("Missing camera object, can not add orbit controls")}pe.registerCallback(me.ContextCreated,o=>{const e=o.context.domElement.getAttribute("autoplay");if(e!==void 0&&(e===""||e==="true"||e==="1")&&o.files)for(const t of o.files)P.foreachComponent(t.file.scene,s=>{if(s.enabled!==!1){if(s instanceof Bt&&s.playAutomatically||s instanceof Mt||s instanceof kl&&s.playOnAwake===!0)return!0;if(s instanceof Bt)return s.playAutomatically=!0,!0;if(s instanceof kl)return s.playOnAwake=!0,!0}},!0)!==!0&&Va.assignAnimationsFromFile(t.file,{createAnimationComponent:(s,n)=>Ti(s,Bt)})});class FL extends xO{constructor(){super(new Worker(new URL("/generateMeshBVH.worker-BaNp_Xtp.js",import.meta.url),{type:"module"})),this.name="GenerateMeshBVHWorker"}runTask(e,t,s={}){return new Promise((n,r)=>{if(t.getAttribute("position").isInterleavedBufferAttribute||t.index&&t.index.isInterleavedBufferAttribute)throw new Error("GenerateMeshBVHWorker: InterleavedBufferAttribute are not supported for the geometry attributes.");e.onerror=d=>{r(new Error(`[GenerateMeshBVHWorker] ${d.message||"Unknown error. Please check the server console. If you're using vite try adding 'three-mesh-bvh' to 'optimizeDeps.exclude' in your vite.config.js"}`))},e.onmessage=d=>{const{data:u}=d;if(u.error)r(new Error(u.error)),e.onmessage=null;else if(u.serialized){const{serialized:p,position:g}=u,f=SO.deserialize(p,t,{setIndex:!1}),y=Object.assign({setBoundingBox:!0},s);if(t.attributes.position.array=g,p.index)if(t.index)t.index.array=p.index;else{const b=new bt(p.index,1,!1);t.setIndex(b)}y.setBoundingBox&&(t.boundingBox=f.getBoundingBox(new xi)),s.onProgress&&s.onProgress(u.progress),n(f),e.onmessage=null}else s.onProgress&&s.onProgress(u.progress)};const l=t.index?t.index.array:null,c=t.attributes.position.array,h=[c];l&&h.push(l),e.postMessage({index:l,position:c,options:{...s,onProgress:null,includedProgressCallback:!!s.onProgress,groups:[...t.groups]}},h.map(d=>d.buffer).filter(d=>typeof SharedArrayBuffer>"u"||!(d instanceof SharedArrayBuffer)))})}}const UL=Object.freeze(Object.defineProperty({__proto__:null,GenerateMeshBVHWorker:FL},Symbol.toStringTag,{value:"Module"}));export{DT as $physicsKey,ve as ActionBuilder,z1 as ActionCollection,ks as ActionModel,Sw as Addressables,Mc as AlignmentConstraint,Ha as AmbientMode,Bt as Animation,uh as AnimationCurve,ap as AnimationExtension,Zp as AnimationTrackHandler,Va as AnimationUtils,Mt as Animator,ko as AnimatorConditionMode,us as AnimatorController,Af as AnimatorControllerParameterType,Rc as AnimatorStateInfo,yh as Antialiasing,Ln as Application,E_ as AssetDatabase,ce as AssetReference,ya as AudioExtension,zn as AudioListener,ss as AudioSource,Jp as AudioTrackHandler,Ho as Avatar,Br as AvatarBlink_Simple,Gf as AvatarEyeLook_Rotation,aC as AvatarLoader,ci as AvatarMarker,dv as AvatarModel,Bc as Avatar_Brain_LookAt,Fc as Avatar_MouthShapes,Vf as Avatar_MustacheShake,Nn as Avatar_POI,$a as Axes,Ya as AxesHelper,gg as BUILD_TIME,hs as BaseUIComponent,Xf as BasicIKConstraint,q0 as BehaviorExtension,Zt as BehaviorModel,Tr as BlobStorage,Bp as BloomEffect,Uu as BoxCollider,Kr as BoxGizmo,Do as BoxHelperComponent,no as Button,Co as ButtonsFactory,Ex as CallDirection,Un as CallInfo,li as Camera,Dc as CameraTargetReachedEvent,yl as Canvas,Qo as CanvasGroup,Wn as CapsuleCollider,A0 as ChangeMaterialOnClick,$r as ChangeTransformOnClick,Fr as CharacterController,Hn as CharacterControllerInput,vh as ChromaticAberration,Pi as CircularBuffer,Ao as ClearFlags,bn as ClipExtrapolation,di as Collider,Mx as Collision,Pu as CollisionDetectionMode,sr as ColorAdjustments,xl as ColorBySpeedModule,Rp as ColorOverLifetimeModule,zR as Component,I as Component$1,hc as ComponentLifecycleEvents,BL as Components,p_ as ConnectionEvents,kx as ContactPoint,Nc as ContactShadows,ee as Context,RR as ContextArgs,me as ContextEvent,pe as ContextRegistry,em as ControlTrackHandler,Yr as CustomBranding,t1 as CustomShader,uu as DefaultReflectionMode,Jf as Deletable,zu as DeleteBox,As as DepthOfField,Nu as DeviceFlag,Y as DeviceUtilities,lC as DocumentExtension,Wr as DragControls,t0 as DragMode,$n as DropListener,o0 as Duplicatable,_h as EffectWrapper,eo as EmissionModule,cl as EmphasizeOnClick,YS as EngineLoadingView,om as EnvironmentScene,xe as EventList,ku as EventListEvent,ti as EventSystem,$u as EventTrigger,p1 as FieldWithDefault,gf as FileReference,Mw as FileReferenceSerializer,oE as FileSpawnModel,Wx as File_Event,dy as FixedJoint,bl as Fog,Oe as FrameEvent,Id as GENERATOR,P as GameObject,G as Gizmos,_0 as GltfExport,v0 as GltfExportBox,Jr as Gradient,rh as Graphic,Tu as GraphicRaycaster,Kl as Graphics,_l as GridHelper,iy as GridLayoutGroup,en as GroundProjectedEnv,zo as GroupActionModel,Lu as HideFlags,cp as HideOnStart,ch as HingeJoint,ty as HorizontalLayoutGroup,AM as HostData,Ml as Image,mf as ImageReference,Ow as ImageReferenceSerializer,vy as InheritVelocityModule,e_ as Input,ni as InputEventQueue,Fe as InputEvents,$y as InputField,f0 as InstanceHandle,Ku as InstancingHandler,ds as InstancingUtil,H_ as InstantiateEvent,Lt as InstantiateIdProvider,Fs as InstantiateOptions,Zf as Interactable,Wh as InternalScreenshotUtils,sM as JoinedRoomResponse,Gk as KeyEventArgs,yi as Keyframe,dh as LODGroup,wl as LODModel,nM as LeftRoomResponse,fi as Light,Bw as LightData,gt as LimitVelocityOverLifetimeModule,SL as LoadingElementOptions,Kf as LogStats,Oi as LogType,Gy as LookAt,jr as LookAtConstraint,A as MODULES,Nt as MainModule,Wy as MarkerType,ah as MaskableGraphic,W as Mathf,Bo as MeshCollider,qc as MeshRenderer,Z as MinMaxCurve,ea as MinMaxGradient,nc as NEKeyboardEvent,An as NEPointerEvent,hv as NeedleButtonElement,s0 as NeedleEngineModelLoader,nv as NeedleEngineWebComponent,un as NeedleMenu,jd as NeedlePatchesKey,_g as NeedleXRController,ne as NeedleXRSession,f_ as NeedleXRSync,x_ as NeedleXRUtils,Sp as NestedGltf,g_ as NetworkConnection,nn as NetworkedStreamEvents,ld as NetworkedStreams,gy as Networking,G_ as NewInstanceModel,Ce as NoiseModule,Li as ObjectRaycaster,_o as ObjectUtils,Zr as OffsetConstraint,Od as OneEuroFilter,eg as OneEuroFilterXYZ,Rl as OpenURL,_e as OrbitControls,fl as Outline,m_ as OwnershipEvent,kg as OwnershipModel,Ma as PUBLIC_KEY,Qr as Padding,Mp as ParticleBurst,by as ParticleSubEmitter,gh as ParticleSystem,tr as ParticleSystemBaseBehaviour,ls as ParticleSystemRenderer,kp as ParticleSystemShapeType,ju as PeerHandle,d_ as PeerNetworking,Ng as Physics,X0 as PhysicsExtension,wt as PhysicsMaterialCombine,wh as PixelationEffect,Kc as PlayAnimationOnClick,No as PlayAudioOnClick,kl as PlayableDirector,Fl as PlayerColor,Ms as PlayerState,G1 as PlayerStateEvent,V0 as PlayerSync,Aw as PlayerView,Iw as PlayerViewManager,ad as PointerEventData,Bd as PointerType,rt as PostProcessingEffect,ft as PostProcessingEffectOrder,jy as PostProcessingHandler,hl as PreliminaryAction,Zc as PreliminaryTrigger,Uo as PreviewHelper,wr as PrimitiveType,de as Progress,Xm as PromiseAllWithErrors,qm as PromiseErrorResult,he as RGBAColor,tC as RapierPhysics,sm as RawImage,Qs as RaycastOptions,Q1 as Rect,Ts as RectTransform,$c as ReflectionProbe,ur as RegisteredAnimationInfo,Vp as RemoteSkybox,Tc as RenderTexture,_x as RenderTextureSerializer,Fi as Renderer,Dw as RendererData,Zu as RendererLightmap,dt as Rigidbody,Qe as RigidbodyConstraints,ie as RoomEvents,as as RotationBySpeedModule,Es as RotationOverLifetimeModule,qu as SceneLightSettings,Ze as SceneSwitcher,or as ScreenCapture,to as ScreenSpaceAmbientOcclusion,Is as ScreenSpaceAmbientOcclusionN8,xs as SendQueue,rf as SerializationContext,I0 as SetActiveOnClick,kh as ShadowCatcher,yy as ShapeModule,Sh as SharpeningEffect,Kp as SignalAsset,Lh as SignalReceiver,Ih as SignalReceiverEvent,Dh as SignalTrackHandler,X1 as Size,vi as SizeBySpeedModule,ta as SizeOverLifetimeModule,y0 as SkinnedMeshRenderer,Gp as SmoothFollow,Lc as SpatialGrabRaycaster,Uh as SpatialHtml,qp as SpatialTrigger,vn as SpatialTriggerReceiver,Xp as SpectatorCamera,Ka as SphereCollider,zg as SphereIntersection,Rx as SphereOverlapResult,Qn as Sprite,pl as SpriteData,mi as SpriteRenderer,ul as SpriteSheet,GR as StateMachineBehaviour,Nf as StreamEndedEvent,Tx as StreamReceivedEvent,Ip as SubEmitterSystem,By as SyncedCamera,Ls as SyncedRoom,sn as SyncedTransform,D0 as TapGestureTrigger,fp as TeleportTarget,zy as TestRunner,EL as TestSceneUtils,Ny as TestSimulateUserData,zt as Text,J0 as TextBuilder,wp as TextExtension,Wt as TextureSheetAnimationModule,yn as TiltShiftEffect,Uw as Time,ir as ToneMappingEffect,jh as TrackHandler,Gi as TrackType,We as TrailModule,ut as TransformData,la as TransformGizmo,Et as TriggerBuilder,ll as TriggerModel,R as TypeStore,jf as UIRaycastUtils,sh as UIRootComponent,w0 as USDDocument,pi as USDObject,_1 as USDWriter,gn as USDZExporter,w1 as USDZExporter$1,Xr as USDZText,oy as USDZUIExtension,wx as UriSerializer,Wc as UsageMarker,oM as UserJoinedOrLeftRoomModel,_s as VERSION,T0 as VariantAction,qe as VelocityOverLifetimeModule,ey as VerticalLayoutGroup,yt as VideoPlayer,So as ViewDevice,oa as Vignette,Jc as VisibilityAction,jo as Voip,Pl as Volume,N as VolumeParameter,Lp as VolumeProfile,aR as WaitForFrames,Rw as WaitForPromise,ff as WaitForSeconds,lo as Watch,Vh as WebARCameraBackground,Wo as WebARSessionRoot,yp as WebXR,dl as WebXRButtonFactory,Hh as WebXRImageTracking,ro as WebXRImageTrackingModel,ao as WebXRPlaneTracking,Yy as WebXRTrackedImage,oo as XRControllerFollow,pn as XRControllerModel,zi as XRControllerMovement,ns as XRFlag,lm as XRRig,ji as XRState,rn as XRStateFlag,cC as __Ignore,D_ as __internalNotifyObjectDestroyed,En as activeInHierarchyFieldName,cb as addAttributeChangeCallback,Ti as addComponent,kE as addCustomExtensionPlugin,Pr as addNewComponent,Ld as addPatch,su as apply,UR as applyHMRChanges,lw as applyPrototypeExtensions,$_ as beginListenDestroy,X_ as beginListenInstantiate,Cg as binaryIdentifierCasts,MR as build_scene_functions,br as builtinComponentKeyName,sv as calculateProgress01,rk as clearMessages,mT as colorSerializer,Z_ as compareAssociation,Mu as componentSerializer,Lb as copyTexture,hx as createMotion,oi as debugNet,oc as debugOwner,O1 as decompressGpuTexture,$l as deepClone,ys as delay,Gl as delayForFrames,tu as deserializeObject,Ei as destroy,uw as destroyComponentInstance,Vx as determineMimeTypeFromExtension,Te as disposeObjectResources,on as disposeStream,sc as editorGuidKeyName,vr as enableSpatialConsole,fT as euler,_T as eventListSerializer,LL as exportAsGLTF,hf as findByGuid,_c as findObjectOfType,gw as findObjectsOfType,Vg as findResourceUsers,Db as fitObjectIntoVolume,Rr as foreachComponent,lu as foreachComponentEnumerator,wk as forward,db as generateQRCode,q_ as generateSeed,ii as getBoundingBox,_b as getCameraController,Or as getComponent,vc as getComponentInChildren,bc as getComponentInParent,yc as getComponents,Ua as getComponentsInChildren,iu as getComponentsInParent,g1 as getFormattedDate,kt as getIconElement,wf as getIconTexture,ws as getLoader,fc as getOrAddComponent,C as getParam,Ck as getParentHierarchyPath,UO as getPath,Jk as getPeerOptions,c_ as getPeerjsInstance,SM as getResourceUserCount,Sb as getTempColor,vs as getTempQuaternion,X as getTempVector,Vl as getUrlParams,jb as getVisibleInCustomShadowRendering,kb as getWorldDirection,ag as getWorldEuler,te as getWorldPosition,Se as getWorldQuaternion,Td as getWorldRotation,Ge as getWorldScale,Js as hasCommercialLicense,Pc as hasIndieLicense,Ou as hasPointerEventComponent,Zs as hasProLicense,Nb as hideDebugConsole,k1 as imageToCanvas,Wa as instantiate,s1 as invokeLoadedImportPluginHooks,Jb as invokeXRSessionEnd,Zb as invokeXRSessionStart,fw as isActiveInHierarchy,za as isActiveSelf,$O as isAndroidDevice,Eb as isAnimationAction,Ox as isComponent,jO as isDebugMode,NO as isDesktop,Mr as isDestroyed,F as isDevEnvironment,wM as isDisposed,AL as isExporting,Px as isGLTFModel,Jv as isHostedOnGlitch,Ef as isHotReloadEnabled,BR as isHotReloading,VO as isIPad,Vw as isIconElement,qt as isLocalNetwork,qO as isMacOS,WO as isMobileDevice,GO as isMozillaXR,YO as isQuest,I_ as isResourceTrackingEnabled,QO as isSafari,ou as isUsingInstancing,XO as isiOS,HO as isiPad,yL as loadAsset,iv as loadSync,Ed as logHierarchy,pk as lookAtInverse,Ql as lookAtObject,mk as lookAtScreenPoint,BO as makeId,rb as makeIdFromRandomWords,Os as makeNameSafe,yw as markAsInstancedRendered,KO as microphonePermissionsGranted,LO as nameof,ib as nameofFactory,bx as objectSerializer,$k as offXRSessionEnd,Hk as offXRSessionStart,rT as onAfterRender,oT as onBeforeRender,sT as onClear,nT as onDestroy,mx as onInitialized,gx as onStart,fx as onUpdate,bg as onXRSessionEnd,Dd as onXRSessionStart,HS as parseSync,Bb as placeOnSurface,hg as postprocessFBXMaterials,lT as prefix,sb as pushState,FO as randomNumber,Pg as registerBinaryType,yu as registerComponent,u0 as registerComponentExtension,cs as registerCustomEffectType,p0 as registerExportExtensions,Qu as registerExtensions,nx as registerHotReloadType,fg as registerLoader,Y_ as registerPrefabProvider,cw as registerPrototypeExtensions,BM as registerType,lb as relativePathPrefix,hb as removeAttributeChangeCallback,cf as removeComponent,ME as removeCustomImportExtensionType,Wk as removePatch,fo as resolveUrl,ab as sanitizeString,BS as saveImage,eL as screenshot,Xy as screenshot2,Zg as sendDestroyed,m as serializable,iw as serializeObject,Ir as serializeable,wc as setActive,gb as setAllowBalloonMessages,ik as setAllowOverlayMessages,Md as setAutoFitEnabled,tg as setCameraController,bw as setDestroyed,Ak as setDevEnvironment,Wg as setDisposable,Na as setDontDestroy,Hm as setOrAddParamsToUrl,DO as setParam,Hl as setParamWithoutReload,eM as setPeerOptions,_M as setResourceTrackingEnabled,$m as setState,cg as setVisibleInCustomShadowRendering,lg as setWorldEuler,lt as setWorldPosition,fr as setWorldPositionXYZ,Qi as setWorldQuaternion,rg as setWorldQuaternionXYZW,Tb as setWorldRotation,Yl as setWorldRotationXYZ,ka as setWorldScale,ec as showBalloonError,Be as showBalloonMessage,be as showBalloonWarning,mg as showDebugConsole,uk as slerp,mc as syncDestroy,W0 as syncField,Jg as syncInstantiate,Pk as textureToCanvas,a_ as tryCastBinary,$x as tryDetermineMimetypeFromBinary,Hx as tryDetermineMimetypeFromURL,Pa as tryFindObject,l_ as tryGetGuid,ox as unregisterHotReloadType,Gm as unwatchWrite,wb as useForAutoFit,Rt as validate,Cd as watchWrite};