@needle-tools/engine 4.3.0-alpha → 4.3.0-alpha.1

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 (101) hide show
  1. package/CHANGELOG.md +3 -0
  2. package/dist/needle-engine.bundle.js +1467 -222
  3. package/dist/needle-engine.bundle.light.js +1467 -222
  4. package/dist/needle-engine.bundle.light.min.js +32 -32
  5. package/dist/needle-engine.bundle.light.umd.cjs +3 -3
  6. package/dist/needle-engine.bundle.min.js +3 -3
  7. package/dist/needle-engine.bundle.umd.cjs +3 -3
  8. package/dist/needle-engine.light.d.ts +9 -9
  9. package/lib/engine/engine_types.d.ts +162 -17
  10. package/lib/engine-components/Animator.d.ts +129 -21
  11. package/lib/engine-components/Animator.js +115 -21
  12. package/lib/engine-components/Animator.js.map +1 -1
  13. package/lib/engine-components/AnimatorController.d.ts +161 -32
  14. package/lib/engine-components/AnimatorController.js +176 -29
  15. package/lib/engine-components/AnimatorController.js.map +1 -1
  16. package/lib/engine-components/AudioListener.d.ts +16 -5
  17. package/lib/engine-components/AudioListener.js +16 -5
  18. package/lib/engine-components/AudioListener.js.map +1 -1
  19. package/lib/engine-components/AudioSource.d.ts +120 -28
  20. package/lib/engine-components/AudioSource.js +120 -37
  21. package/lib/engine-components/AudioSource.js.map +1 -1
  22. package/lib/engine-components/AvatarLoader.d.ts +61 -0
  23. package/lib/engine-components/AvatarLoader.js +61 -1
  24. package/lib/engine-components/AvatarLoader.js.map +1 -1
  25. package/lib/engine-components/AxesHelper.d.ts +19 -1
  26. package/lib/engine-components/AxesHelper.js +19 -1
  27. package/lib/engine-components/AxesHelper.js.map +1 -1
  28. package/lib/engine-components/BoxHelperComponent.d.ts +26 -0
  29. package/lib/engine-components/BoxHelperComponent.js +26 -0
  30. package/lib/engine-components/BoxHelperComponent.js.map +1 -1
  31. package/lib/engine-components/Camera.d.ts +126 -37
  32. package/lib/engine-components/Camera.js +139 -37
  33. package/lib/engine-components/Camera.js.map +1 -1
  34. package/lib/engine-components/CameraUtils.js +20 -0
  35. package/lib/engine-components/CameraUtils.js.map +1 -1
  36. package/lib/engine-components/Collider.d.ts +95 -21
  37. package/lib/engine-components/Collider.js +100 -23
  38. package/lib/engine-components/Collider.js.map +1 -1
  39. package/lib/engine-components/Component.d.ts +554 -106
  40. package/lib/engine-components/Component.js +352 -81
  41. package/lib/engine-components/Component.js.map +1 -1
  42. package/lib/engine-components/DragControls.d.ts +95 -21
  43. package/lib/engine-components/DragControls.js +126 -32
  44. package/lib/engine-components/DragControls.js.map +1 -1
  45. package/lib/engine-components/DropListener.d.ts +99 -16
  46. package/lib/engine-components/DropListener.js +119 -14
  47. package/lib/engine-components/DropListener.js.map +1 -1
  48. package/lib/engine-components/Light.d.ts +102 -5
  49. package/lib/engine-components/Light.js +102 -44
  50. package/lib/engine-components/Light.js.map +1 -1
  51. package/lib/engine-components/NeedleMenu.d.ts +28 -11
  52. package/lib/engine-components/NeedleMenu.js +28 -11
  53. package/lib/engine-components/NeedleMenu.js.map +1 -1
  54. package/lib/engine-components/Networking.d.ts +37 -5
  55. package/lib/engine-components/Networking.js +37 -5
  56. package/lib/engine-components/Networking.js.map +1 -1
  57. package/lib/engine-components/SceneSwitcher.js +44 -0
  58. package/lib/engine-components/SceneSwitcher.js.map +1 -1
  59. package/lib/engine-components/SpatialTrigger.d.ts +66 -1
  60. package/lib/engine-components/SpatialTrigger.js +74 -2
  61. package/lib/engine-components/SpatialTrigger.js.map +1 -1
  62. package/lib/engine-components/SpectatorCamera.d.ts +66 -4
  63. package/lib/engine-components/SpectatorCamera.js +132 -6
  64. package/lib/engine-components/SpectatorCamera.js.map +1 -1
  65. package/lib/engine-components/SyncedTransform.d.ts +45 -6
  66. package/lib/engine-components/SyncedTransform.js +45 -6
  67. package/lib/engine-components/SyncedTransform.js.map +1 -1
  68. package/lib/engine-components/TransformGizmo.d.ts +49 -3
  69. package/lib/engine-components/TransformGizmo.js +49 -3
  70. package/lib/engine-components/TransformGizmo.js.map +1 -1
  71. package/lib/engine-components/webxr/WebXR.d.ts +131 -22
  72. package/lib/engine-components/webxr/WebXR.js +132 -23
  73. package/lib/engine-components/webxr/WebXR.js.map +1 -1
  74. package/lib/engine-components-experimental/networking/PlayerSync.d.ts +82 -9
  75. package/lib/engine-components-experimental/networking/PlayerSync.js +76 -11
  76. package/lib/engine-components-experimental/networking/PlayerSync.js.map +1 -1
  77. package/package.json +1 -1
  78. package/src/engine/engine_types.ts +179 -18
  79. package/src/engine-components/Animator.ts +142 -22
  80. package/src/engine-components/AnimatorController.ts +184 -34
  81. package/src/engine-components/AudioListener.ts +16 -5
  82. package/src/engine-components/AudioSource.ts +126 -37
  83. package/src/engine-components/AvatarLoader.ts +61 -2
  84. package/src/engine-components/AxesHelper.ts +21 -1
  85. package/src/engine-components/BoxHelperComponent.ts +26 -0
  86. package/src/engine-components/Camera.ts +147 -41
  87. package/src/engine-components/CameraUtils.ts +20 -0
  88. package/src/engine-components/Collider.ts +102 -27
  89. package/src/engine-components/Component.ts +605 -129
  90. package/src/engine-components/DragControls.ts +134 -38
  91. package/src/engine-components/DropListener.ts +143 -23
  92. package/src/engine-components/Light.ts +105 -44
  93. package/src/engine-components/NeedleMenu.ts +29 -11
  94. package/src/engine-components/Networking.ts +37 -6
  95. package/src/engine-components/SceneSwitcher.ts +48 -1
  96. package/src/engine-components/SpatialTrigger.ts +80 -3
  97. package/src/engine-components/SpectatorCamera.ts +136 -18
  98. package/src/engine-components/SyncedTransform.ts +50 -7
  99. package/src/engine-components/TransformGizmo.ts +49 -4
  100. package/src/engine-components/webxr/WebXR.ts +144 -27
  101. package/src/engine-components-experimental/networking/PlayerSync.ts +85 -13
@@ -130,7 +130,7 @@ Open this page to get the console: `+t.toString())}const s=X.isMobileDevice()||X
130
130
  #__vconsole .vc-mask {
131
131
  overflow: hidden;
132
132
  }
133
- `,Qi?.prepend(n),s===!0&&Lm()<=0&&ob(),console.log("\u{1F335} Debug console has loaded")}},t.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.":"")),lc=!1,hi=null},t.src="https://unpkg.com/vconsole@latest/dist/vconsole.min.js",document.body.appendChild(t)}function fP(){if(!globalThis.VConsole)return;const s=new VConsole.VConsolePlugin("needle-console","\u{1F335} Inspect glTF"),t=()=>document.querySelector("#__vc_plug_"+s._id+" iframe");return s.on("renderTab",function(i){const n=globalThis["needle:codegen_files"];if(!n||n.length===0)return;let o=globalThis["needle:codegen_files"][0];const r=o.indexOf("?");r>-1&&(o=o.substring(0,r));const l=location.protocol+"//"+location.host+location.pathname+"/"+o,c=encodeURIComponent(l);s.fullUrl="https://viewer.needle.tools?inspect&file="+c;var h='<iframe src="" style="width: 100%; height: 99%; border: none;"></iframe>';i(h)}),s.on("show",function(){const i=t();i&&i.src!==s.fullUrl&&(i.src=s.fullUrl)}),s.on("hide",function(){const i=t();i&&(i.src="")}),s.on("addTopBar",function(i){var n=new Array;n.push({name:"Open in new window \u2197",onClick:function(o){window.open(s.fullUrl,"_blank"),hi?.hide()}}),n.push({name:"Reload",onClick:function(o){const r=t();r&&(r.src=s.fullUrl)}}),n.push({name:"Fullscreen",onClick:function(o){const r=t();r.requestFullscreen?r.requestFullscreen():r.webkitRequestFullscreen instanceof Function&&r.webkitRequestFullscreen()}}),i(n)}),s}function yP(){return document.querySelector("#__vconsole .vc-switch")||null}function vP(){return document.querySelector("#__vconsole")||null}const cb=O("debugdefines");po('if(!globalThis[""4.3.0-alpha""]) globalThis[""4.3.0-alpha""] = "0.0.0";'),po('if(!globalThis[""undefined""]) globalThis[""undefined""] = "unknown";'),po('if(!globalThis[""Fri Feb 28 2025 13:27:32 GMT+0100 (Central European Standard Time)""]) globalThis[""Fri Feb 28 2025 13:27:32 GMT+0100 (Central European Standard Time)""] = "unknown";'),po('if(!globalThis[""npk_74222a9fbd1b42572cdd3bf7f639eeb17a07d07f40a6185fac5f722e8fd34df9""]) globalThis[""npk_74222a9fbd1b42572cdd3bf7f639eeb17a07d07f40a6185fac5f722e8fd34df9""] = "unknown";'),po('globalThis["__NEEDLE_ENGINE_VERSION__"] = "4.3.0-alpha";'),po('globalThis["__NEEDLE_ENGINE_GENERATOR__"] = "undefined";'),po('globalThis["__NEEDLE_PROJECT_BUILD_TIME__"] = "Fri Feb 28 2025 13:27:32 GMT+0100 (Central European Standard Time)";'),po('globalThis["__NEEDLE_PUBLIC_KEY__"] = "npk_74222a9fbd1b42572cdd3bf7f639eeb17a07d07f40a6185fac5f722e8fd34df9";');const _s="4.3.0-alpha",Rd="undefined",tg="Fri Feb 28 2025 13:27:32 GMT+0100 (Central European Standard Time)";cb&&console.log(`Engine version: ${_s} (generator: ${Rd})
133
+ `,Qi?.prepend(n),s===!0&&Lm()<=0&&ob(),console.log("\u{1F335} Debug console has loaded")}},t.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.":"")),lc=!1,hi=null},t.src="https://unpkg.com/vconsole@latest/dist/vconsole.min.js",document.body.appendChild(t)}function fP(){if(!globalThis.VConsole)return;const s=new VConsole.VConsolePlugin("needle-console","\u{1F335} Inspect glTF"),t=()=>document.querySelector("#__vc_plug_"+s._id+" iframe");return s.on("renderTab",function(i){const n=globalThis["needle:codegen_files"];if(!n||n.length===0)return;let o=globalThis["needle:codegen_files"][0];const r=o.indexOf("?");r>-1&&(o=o.substring(0,r));const l=location.protocol+"//"+location.host+location.pathname+"/"+o,c=encodeURIComponent(l);s.fullUrl="https://viewer.needle.tools?inspect&file="+c;var h='<iframe src="" style="width: 100%; height: 99%; border: none;"></iframe>';i(h)}),s.on("show",function(){const i=t();i&&i.src!==s.fullUrl&&(i.src=s.fullUrl)}),s.on("hide",function(){const i=t();i&&(i.src="")}),s.on("addTopBar",function(i){var n=new Array;n.push({name:"Open in new window \u2197",onClick:function(o){window.open(s.fullUrl,"_blank"),hi?.hide()}}),n.push({name:"Reload",onClick:function(o){const r=t();r&&(r.src=s.fullUrl)}}),n.push({name:"Fullscreen",onClick:function(o){const r=t();r.requestFullscreen?r.requestFullscreen():r.webkitRequestFullscreen instanceof Function&&r.webkitRequestFullscreen()}}),i(n)}),s}function yP(){return document.querySelector("#__vconsole .vc-switch")||null}function vP(){return document.querySelector("#__vconsole")||null}const cb=O("debugdefines");po('if(!globalThis[""4.3.0-alpha.1""]) globalThis[""4.3.0-alpha.1""] = "0.0.0";'),po('if(!globalThis[""undefined""]) globalThis[""undefined""] = "unknown";'),po('if(!globalThis[""Mon Mar 03 2025 10:04:15 GMT+0100 (Central European Standard Time)""]) globalThis[""Mon Mar 03 2025 10:04:15 GMT+0100 (Central European Standard Time)""] = "unknown";'),po('if(!globalThis[""npk_74222a9fbd1b42572cdd3bf7f639eeb17a07d07f40a6185fac5f722e8fd34df9""]) globalThis[""npk_74222a9fbd1b42572cdd3bf7f639eeb17a07d07f40a6185fac5f722e8fd34df9""] = "unknown";'),po('globalThis["__NEEDLE_ENGINE_VERSION__"] = "4.3.0-alpha.1";'),po('globalThis["__NEEDLE_ENGINE_GENERATOR__"] = "undefined";'),po('globalThis["__NEEDLE_PROJECT_BUILD_TIME__"] = "Mon Mar 03 2025 10:04:15 GMT+0100 (Central European Standard Time)";'),po('globalThis["__NEEDLE_PUBLIC_KEY__"] = "npk_74222a9fbd1b42572cdd3bf7f639eeb17a07d07f40a6185fac5f722e8fd34df9";');const _s="4.3.0-alpha.1",Rd="undefined",tg="Mon Mar 03 2025 10:04:15 GMT+0100 (Central European Standard Time)";cb&&console.log(`Engine version: ${_s} (generator: ${Rd})
134
134
  Project built at ${tg}`);const hc="npk_74222a9fbd1b42572cdd3bf7f639eeb17a07d07f40a6185fac5f722e8fd34df9",Sn="needle_isActiveInHierarchy",_r="builtin_components",dc="needle_editor_guid";function po(s){try{(0,eval)(s)}catch(t){cb&&console.error(t)}}const bP='<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>',_P=btoa(bP),wP="data:image/svg+xml;base64,"+_P,xP=wP,SP=`<?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(SP);const CP='<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>',OP=btoa(CP),PP="data:image/svg+xml;charset=utf-8;base64,"+OP,kP=PP,MP=O("debugpatch");function Td(s,t,i,n){const o=MP===t;if(!i&&!n)return;const r=t+"___needle";TP(s,t,i,n);const l=Object.getOwnPropertyDescriptor(s,t),c=s[t];o&&console.log("Patch",s.constructor.name,t,l,c),l?(o&&console.log("Apply patch with existing descriptor",s.constructor.name,t,l),typeof l.value=="function"&&(s[t]=db(l.value,s,t))):(o&&console.log("Create patch with new property",s.constructor.name,t,l),Object.defineProperty(s,t,{set:function(h){if(typeof h=="function")this[r]=db(h,s,t);else{const d=this[r];ub(s,t,this,d,h),this[r]=h,pb(s,t,this,d,h)}},get:function(){const h=this[r];return typeof h=="function"&&h[r]?h[r]:h}}))}function RP(s,t,i){const n=sg(s,t);if(n)for(let o=n.length-1;o>=0;o--){const r=n[o];r.prefix===i&&(r.prefix=null),r.postfix===i&&(r.postfix=null),!r.prefix&&!r.postfix&&n.splice(o,1)}}const hb=Symbol("Needle:Patches:WrappedFunction");function db(s,t,i){if(s[hb])return s;const n=function(...o){ub(t,i,this,...o);const r=s.apply(this,o);return pb(t,i,this,r,...o),r};return n[hb]=!0,n}const Ed="Needle:Patches";function ig(){return globalThis[Ed]||(globalThis[Ed]=new WeakMap),globalThis[Ed]}function sg(s,t){const i=ig().get(s);return i?i.get(t):null}function TP(s,t,i,n){let o=ig().get(s);o||(o=new Map,ig().set(s,o));let r=o.get(t);r||(r=[],o.set(t,r)),r.push({prefix:i,postfix:n})}function ub(s,t,i,...n){var o;if(!i)return;const r=sg(s,t);if(r)for(const l of r)(o=l.prefix)==null||o.call(i,...n)}function pb(s,t,i,n,...o){var r;if(!i)return;const l=sg(s,t);if(l)for(const c of l)(r=c.postfix)==null||r.call(i,n,...o)}const ka=[];function Ad(s){ka.indexOf(s)===-1&&ka.push(s)}function EP(s){const t=ka.indexOf(s);t!==-1&&ka.splice(t,1)}const Ma=[];function ng(s){Ma.indexOf(s)===-1&&Ma.push(s)}function AP(s){const t=Ma.indexOf(s);t!==-1&&Ma.splice(t,1)}function mb(s){globalThis.dispatchEvent(new CustomEvent("needle-xrsession-start",{detail:s}));for(let t=0;t<ka.length;t++)ka[t](s)}function gb(s){globalThis.dispatchEvent(new CustomEvent("needle-xrsession-end",{detail:s}));for(let t=0;t<Ma.length;t++)Ma[t](s)}const ut=O("debuginput");var Id=(s=>(s.Mouse="mouse",s.Touch="touch",s.Controller="controller",s.Hand="hand",s))(Id||{}),Be=(s=>(s.PointerDown="pointerdown",s.PointerUp="pointerup",s.PointerMove="pointermove",s.KeyDown="keydown",s.KeyUp="keyup",s.KeyPressed="keypress",s))(Be||{});class Cn extends PointerEvent{constructor(t,i,n){super(t,n),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=n.clientZ,this._pointerid=n.pointerId,this._pointerType=n.pointerType,this._type=t,this.deviceIndex=n.deviceIndex,this.origin=n.origin,this.source=i,this.mode=n.mode,this._ray=n.ray,this.space=n.device}get isSpatial(){return this.mode!="screen"}get ray(){return this._ray||(this._ray=new oo(this.space.worldPosition.clone(),this.space.worldForward.clone())),this._ray}set ray(t){this._ray=t}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 t;this._immediatePropagationStopped=!0,super.stopImmediatePropagation(),(t=this.source)==null||t.stopImmediatePropagation()}stopPropagation(){var t;this._propagationStopped=!0,super.stopPropagation(),(t=this.source)==null||t.stopPropagation(),ut&&console.warn("Stop propagation...",this.pointerId,this.pointerType)}}class uc extends KeyboardEvent{constructor(t,i,n){super(t,n),a(this,"source"),this.source=i}stopImmediatePropagation(){var t;super.stopImmediatePropagation(),(t=this.source)==null||t.stopImmediatePropagation()}}class IP{constructor(t){a(this,"key"),a(this,"keyType"),a(this,"source"),this.key=t.key,this.keyType=t.type,this.source=t}}var Oi=(s=>(s[s.Early=-100]="Early",s[s.Default=0]="Default",s[s.Late=100]="Late",s))(Oi||{});class fb{constructor(t){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 oe]),a(this,"_pointerPositionsLastFrame",[new oe]),a(this,"_pointerPositionsDelta",[new oe]),a(this,"_pointerPositionsRC",[new oe]),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 i in this.keysPressed)this.keysPressed[i].pressed=!1}),a(this,"_receivedPointerMoveEventsThisFrame",new Array),a(this,"onEndOfFrame",()=>{this._receivedPointerMoveEventsThisFrame.length=0;for(let i=0;i<this._pointerUp.length;i++)this._pointerUp[i]=!1;for(let i=0;i<this._pointerDown.length;i++)this._pointerDown[i]=!1;for(let i=0;i<this._pointerClick.length;i++)this._pointerClick[i]=!1;for(let i=0;i<this._pointerDoubleClick.length;i++)this._pointerDoubleClick[i]=!1;for(const i of this._pointerPositionsDelta)i.set(0,0);for(let i=0;i<this._mouseWheelChanged.length;i++)this._mouseWheelChanged[i]=!1;for(let i=0;i<this._mouseWheelDeltaY.length;i++)this._mouseWheelDeltaY[i]=0}),a(this,"onContextMenu",i=>{this.canReceiveInput(i)!==!1&&i instanceof PointerEvent&&i.pointerType}),a(this,"keysPressed",{}),a(this,"onKeyDown",i=>{if(ut&&console.log(`key down ${i.code}, ${this.context.application.hasFocus}`,i),!this.context.application.hasFocus)return;const n=this.keysPressed[i.code];if(n&&n.pressed)return;this.keysPressed[i.code]={pressed:!0,frame:this.context.time.frameCount+1,startFrame:this.context.time.frameCount+1,key:i.key,code:i.code};const o=new uc("keydown",i,i);this.onDispatchEvent(o)}),a(this,"onKeyPressed",i=>{if(!this.context.application.hasFocus)return;const n=this.keysPressed[i.code];if(!n)return;n.pressed=!0,n.frame=this.context.time.frameCount+1;const o=new uc("keypress",i,i);this.onDispatchEvent(o)}),a(this,"onKeyUp",i=>{if(!this.context.application.hasFocus)return;const n=this.keysPressed[i.code];if(!n)return;n.pressed=!1,n.frame=this.context.time.frameCount+1;const o=new uc("keyup",i,i);this.onDispatchEvent(o)}),a(this,"onWheelWindow",i=>{document.pointerLockElement&&this.onMouseWheel(i)}),a(this,"onMouseWheel",i=>{if(this.canReceiveInput(i)===!1)return;this._mouseWheelDeltaY.length<=0&&this._mouseWheelDeltaY.push(0),this._mouseWheelChanged.length<=0&&this._mouseWheelChanged.push(!1),this._mouseWheelChanged[0]=!0;const n=this._mouseWheelDeltaY[0];this._mouseWheelDeltaY[0]=n+i.deltaY}),a(this,"onPointerDown",i=>{if(this.context.isInAR||this.canReceiveInput(i)===!1)return;i.target instanceof HTMLElement&&i.target.setPointerCapture(i.pointerId);const n=this.getPointerId(i);ut&&De(`pointer down #${n}, identifier:${i.pointerId}`);const o=this.getAndUpdateSpatialObjectForScreenPosition(n,i.clientX,i.clientY),r=new Cn("pointerdown",i,{origin:this,mode:"screen",deviceIndex:0,pointerId:n,button:i.button,clientX:i.clientX,clientY:i.clientY,pointerType:i.pointerType,buttonName:this.getButtonName(i),device:o,pressure:i.pressure});this.onDown(r)}),a(this,"onPointerMove",i=>{if(this.context.isInAR||this._receivedPointerMoveEventsThisFrame.includes(i.pointerId))return;this._receivedPointerMoveEventsThisFrame.push(i.pointerId);let n=i.button;i.pointerType==="mouse"&&(n=this.getFirstPressedButtonForPointer(0)??0);const o=this.getPointerId(i,n);n===-1&&(n=o);const r=this.getAndUpdateSpatialObjectForScreenPosition(o,i.clientX,i.clientY),l=new Cn("pointermove",i,{origin:this,mode:"screen",deviceIndex:0,pointerId:o,button:n,clientX:i.clientX,clientY:i.clientY,pointerType:i.pointerType,buttonName:this.getButtonName(i),device:r,pressure:i.pressure});this.onMove(l)}),a(this,"onPointerCancel",i=>{this.context.isInAR||(ut&&console.log("Pointer cancel",i),this.onPointerUp(i))}),a(this,"onPointerUp",i=>{if(this.context.isInAR)return;i.target instanceof HTMLElement&&i.target.releasePointerCapture(i.pointerId);const n=this.getPointerId(i),o=new Cn("pointerup",i,{origin:this,mode:"screen",deviceIndex:0,pointerId:n,button:i.button,clientX:i.clientX,clientY:i.clientY,pointerType:i.pointerType,buttonName:this.getButtonName(i),device:this.getAndUpdateSpatialObjectForScreenPosition(n,i.clientX,i.clientY),pressure:i.pressure});this.onUp(o),this._pointerIds[n]=-1,ut&&console.log("ID="+n,"PointerId="+i.pointerId,"ALL:",[...this._pointerIds])}),a(this,"onTouchStart",i=>{if(this.context.isInAR)for(let n=0;n<i.changedTouches.length;n++){const o=i.changedTouches[n],r=this.getPointerIndex(o.identifier),l=this.getAndUpdateSpatialObjectForScreenPosition(r,o.clientX,o.clientY),c=new Cn("pointerdown",i,{origin:this,mode:"screen",deviceIndex:0,pointerId:r,button:0,clientX:o.clientX,clientY:o.clientY,pointerType:"touch",buttonName:"unknown",device:l,pressure:o.force});this.onDown(c)}}),a(this,"onTouchMove",i=>{if(this.context.isInAR)for(let n=0;n<i.changedTouches.length;n++){const o=i.changedTouches[n],r=this.getPointerIndex(o.identifier),l=this.getAndUpdateSpatialObjectForScreenPosition(r,o.clientX,o.clientY),c=new Cn("pointermove",i,{origin:this,mode:"screen",deviceIndex:0,pointerId:r,button:0,clientX:o.clientX,clientY:o.clientY,pointerType:"touch",buttonName:"unknown",device:l,pressure:o.force});this.onMove(c)}}),a(this,"onTouchEnd",i=>{if(this.context.isInAR)for(let n=0;n<i.changedTouches.length;n++){const o=i.changedTouches[n],r=this.getPointerIndex(o.identifier),l=new Cn("pointerup",i,{origin:this,mode:"screen",deviceIndex:0,pointerId:r,button:0,clientX:o.clientX,clientY:o.clientY,pointerType:"touch",buttonName:"unknown",device:this.getAndUpdateSpatialObjectForScreenPosition(r,o.clientX,o.clientY),pressure:o.force});this.onUp(l),this._pointerIds[r]=-1}}),a(this,"tempNearPlaneVector",new x),a(this,"tempFarPlaneVector",new x),a(this,"tempLookMatrix",new ne),this.context=t,this.context.post_render_callbacks.push(this.onEndOfFrame)}addEventListener(t,i,n){if(this._eventListeners[t]||(this._eventListeners[t]=[]),!i||typeof i!="function"){console.error("Invalid call to addEventListener: callback is required and must be a function!");return}n?n={...n}:n={};let o=0;n?.queue!=null&&(o=n.queue);const r=this._eventListeners[t],l=r.find(c=>c.priority===o);l?l.listeners.push({callback:i,options:n}):(r.push({priority:o,listeners:[{callback:i,options:n}]}),r.sort((c,h)=>c.priority-h.priority))}removeEventListener(t,i,n){if(!this._eventListeners[t]||!i)return;const o=this._eventListeners[t];if(n?.queue!=null){const r=o.find(c=>c.priority===n.queue);if(!r)return;const l=r.listeners.findIndex(c=>c.callback===i);l>=0&&r.listeners.splice(l,1)}else for(const r of o){const l=r.listeners.findIndex(c=>c.callback===i);l>=0&&r.listeners.splice(l,1)}}dispatchEvent(t){var i,n,o,r;let l=!1;if(t instanceof uc){const c=this._eventListeners[t.type];if(c)for(const h of c)for(let d=0;d<h.listeners.length;d++){const u=h.listeners[d];if((n=(i=u.options)==null?void 0:i.signal)!=null&&n.aborted){h.listeners.splice(d,1),d--;continue}u.options.once&&(h.listeners.splice(d,1),d--),u.callback(t)}}if(t instanceof Cn){const c=this._eventListeners[t.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=(o=u.options)==null?void 0:o.signal)!=null&&r.aborted){h.listeners.splice(d,1),d--;continue}if(t.immediatePropagationStopped){l=!0,ut&&console.log("immediatePropagationStopped",t.type);break}else t.propagationStopped&&(l=!0,ut&&console.log("propagationStopped",t.type));u.options.once&&(h.listeners.splice(d,1),d--),u.callback(t)}}}}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]}setCursorPointer(){this.setCursor("pointer")}setCursorNormal(){this.unsetCursor("pointer")}setCursor(t){this._setCursorTypes.push(t),this._setCursorTypes.length>10&&this._setCursorTypes.shift(),this.updateCursor()}unsetCursor(t){for(let i=this._setCursorTypes.length-1;i>=0;i--)if(this._setCursorTypes[i]===t){this._setCursorTypes.splice(i,1),this.updateCursor();break}}updateCursor(){var t;((t=this._setCursorTypes)==null?void 0:t.length)==0?this.context.domElement.style.cursor="default":this.context.domElement.style.cursor=this._setCursorTypes[this._setCursorTypes.length-1]}getIsPointerIdInUse(t){for(const i of this._pointerEventsPressed)if(i.pointerId===t&&i.used)return!0;return!1}getPointerPressedCount(){let t=0;for(let i=0;i<this._pointerPressed.length;i++)this._pointerPressed[i]&&t++;return t}getPointerPosition(t){return t>=this._pointerPositions.length?null:this._pointerPositions[t]}getPointerPositionLastFrame(t){return t>=this._pointerPositionsLastFrame.length?null:this._pointerPositionsLastFrame[t]}getPointerPositionDelta(t){return t>=this._pointerPositionsDelta.length?null:this._pointerPositionsDelta[t]}getPointerPositionRC(t){return t>=this._pointerPositionsRC.length?null:this._pointerPositionsRC[t]}getPointerDown(t){return t>=this._pointerDown.length?!1:this._pointerDown[t]}getPointerUp(t){return t>=this._pointerUp.length?!1:this._pointerUp[t]}getPointerPressed(t){return t>=this._pointerPressed.length?!1:this._pointerPressed[t]}getPointerClicked(t){return t>=this._pointerClick.length?!1:this._pointerClick[t]}getPointerDoubleClicked(t){return t>=this._pointerDoubleClick.length?!1:this._pointerDoubleClick[t]}getPointerDownTime(t){return t>=this._pointerDownTime.length?-1:this._pointerDownTime[t]}getPointerUpTime(t){return t>=this._pointerUpTime.length?-1:this._pointerUpTime[t]}getPointerLongPress(t){return t>=this._pointerDownTime.length?!1:this.getPointerPressed(t)&&this.context.time.time-this._pointerDownTime[t]>this._longPressTimeThreshold}getIsMouse(t){return t<0||t>=this._pointerTypes.length?!1:this._pointerTypes[t]==="mouse"}getIsTouch(t){return t<0||t>=this._pointerTypes.length?!1:this._pointerTypes[t]==="touch"}getTouchesPressedCount(){let t=0;for(let i=0;i<this._pointerPressed.length;i++)this._pointerPressed[i]&&this.getIsTouch(i)&&t++;return t}getMouseWheelChanged(t=0){return t>=this._mouseWheelChanged.length?!1:this._mouseWheelChanged[t]}getMouseWheelDeltaY(t=0){return t>=this._mouseWheelDeltaY.length?0:this._mouseWheelDeltaY[t]}getPointerEvent(t){if(!(t>=this._pointerEvent.length))return this._pointerEvent[t]??void 0}*foreachPointerId(t){for(let i=0;i<this._pointerTypes.length;i++)if(this._pointerIsActive(i)){if(t!==void 0){const n=this._pointerTypes[i];if(Array.isArray(t)){let o=!1;for(const r of t)if(n===r){o=!0;break}if(!o)continue}else if(t!==n)continue}yield i}}*foreachTouchId(){for(let t=0;t<this._pointerTypes.length;t++)this._pointerTypes[t]==="touch"&&this._pointerIsActive[t]&&(yield t)}_pointerIsActive(t){return t<0?!1:this._pointerPressed[t]||this._pointerDown[t]||this._pointerUp[t]}onDownButton(t,i){let n=this._pressedStack.get(t);n||(n=[],this._pressedStack.set(t,n)),n.push(i)}onReleaseButton(t,i){const n=this._pressedStack.get(t);if(!n)return;const o=n.indexOf(i);o>=0&&n.splice(o,1)}getFirstPressedButtonForPointer(t){const i=this._pressedStack.get(t);if(i)return i[0]}getLatestPressedButtonForPointer(t){const i=this._pressedStack.get(t);if(i)return i[i.length-1]}getKeyDown(){for(const t in this.keysPressed){const i=this.keysPressed[t];if(i.startFrame===this.context.time.frameCount)return i.key}return null}getKeyPressed(){for(const t in this.keysPressed){const i=this.keysPressed[t];if(i.pressed)return i.key}return null}isKeyDown(t){var i;if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const n=this.getCodeForCommonKeyName(t);if(n!==null){for(const o of n)if(this.isKeyDown(o))return!0;return!1}return((i=this.keysPressed[t])==null?void 0:i.startFrame)===this.context.time.frameCount&&this.keysPressed[t].pressed}isKeyUp(t){var i;if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const n=this.getCodeForCommonKeyName(t);if(n!==null){for(const o of n)if(this.isKeyUp(o))return!0;return!1}return((i=this.keysPressed[t])==null?void 0:i.frame)===this.context.time.frameCount&&!this.keysPressed[t].pressed}isKeyPressed(t){var i;if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const n=this.getCodeForCommonKeyName(t);if(n!==null){for(const o of n)if(this.isKeyPressed(o))return!0;return!1}return(i=this.keysPressed[t])==null?void 0:i.pressed}getCodeForCommonKeyName(t){if(t.length===1){if(t>="0"&&t<="9")return["Digit"+t];if(t>="a"&&t<="z")return["Key"+t.toUpperCase()];if(t==" ")return["Space"]}switch(t){case"shift":case"Shift":return["ShiftLeft","ShiftRight"];case"control":case"Control":return["ControlLeft","ControlRight"];case"alt":case"Alt":return["AltLeft","AltRight"]}return null}createInputEvent(t){switch(t.type){case"pointerdown":ut&&De("Create Pointer down"),this.onDownButton(t.deviceIndex,t.button),this.onDown(t);break;case"pointermove":ut&&De("Create Pointer move"),this.onMove(t);break;case"pointerup":ut&&De("Create Pointer up"),this.onUp(t),this.onReleaseButton(t.deviceIndex,t.button);break}}convertScreenspaceToRaycastSpace(t){return t.x=(t.x-this.context.domX)/this.context.domWidth*2-1,t.y=-((t.y-this.context.domY)/this.context.domHeight)*2+1,t}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 t,i;window.removeEventListener("contextmenu",this.onContextMenu),(t=this._htmlEventSource)==null||t.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),(i=this._htmlEventSource)==null||i.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 t=this.context.post_render_callbacks.indexOf(this.onEndOfFrame);t>=0&&this.context.post_render_callbacks.splice(t,1),this.unbindEvents()}canReceiveInput(t){var i;return t.target===((i=this.context.renderer)==null?void 0:i.domElement)||t.target===this.context.domElement||this.context.isInAR||this.context.isInAR&&t.target===document.body&&X.isMozillaXR()?!0:(ut&&console.warn("CanReceiveInput:False for",t.target),!1)}getPointerId(t,i){return t.pointerType==="mouse"?0+(i??t.button):this.getPointerIndex(t.pointerId)}getButtonName(t){const i=t.button;if(t.pointerType==="mouse")switch(i){case 0:return"left";case 1:return"middle";case 2:return"right"}return"unknown"}getAndUpdateSpatialObjectForScreenPosition(t,i,n){let o=this._pointerSpace[t];o||(o=new I,this._pointerSpace[t]=o),this._pointerSpace[t]=o;const r=this.context.mainCamera;if(r){const l=this.tempNearPlaneVector.set(i,n,-1);this.convertScreenspaceToRaycastSpace(l);const c=this.tempFarPlaneVector.set(l.x,l.y,1);l.unproject(r),c.unproject(r);const h=r.worldUp||G(0,1,0).applyQuaternion(Oe(r));this.tempLookMatrix.lookAt(c,l,h),o.position.set(l.x,l.y,l.z),o.quaternion.setFromRotationMatrix(this.tempLookMatrix)}return o}isInRect(t){if(this.context.isInXR)return!0;const i=this.context.domElement.getBoundingClientRect(),n=t.clientX,o=t.clientY,r=n>=i.x&&n<=i.right&&o>=i.y&&o<=i.bottom;return ut&&!r&&console.log("Not in rect",i,n,o),r}onDown(t){const i=t.pointerId;if(this.getPointerPressed(i)&&console.warn(`Received pointerDown for pointerId that is already pressed: ${i}`,ut?t:""),ut&&console.log(t.pointerType,"DOWN",i),!!this.isInRect(t)){for(this.setPointerState(i,this._pointerPressed,!0),this.setPointerState(i,this._pointerDown,!0),this.setPointerStateT(i,this._pointerEvent,t.source);i>=this._pointerTypes.length;)this._pointerTypes.push(t.pointerType);for(this._pointerTypes[i]=t.pointerType;i>=this._pointerPositionDown.length;)this._pointerPositionDown.push(new x);for(this._pointerPositionDown[i].set(t.clientX,t.clientY,t.clientZ??0);i>=this._pointerPositions.length;)this._pointerPositions.push(new oe);this._pointerPositions[i].set(t.clientX,t.clientY),i>=this._pointerDownTime.length&&this._pointerDownTime.push(0),this._pointerDownTime[i]=this.context.time.realtimeSinceStartup,this.updatePointerPosition(t),this._pointerEventsPressed.push(t),this.onDispatchEvent(t)}}onMove(t){const i=t.pointerId,n=this.getPointerPressed(i);n===!1&&!this.isInRect(t)||t.pointerType==="touch"&&!n||(this.updatePointerPosition(t),this.setPointerStateT(i,this._pointerEvent,t.source),this.onDispatchEvent(t))}onUp(t){const i=t.pointerId;if(!this.getPointerPressed(i)){ut&&console.log(t.pointerType,"UP",i,"was not down");return}ut&&console.log(t.pointerType,"UP",i),this.setPointerState(i,this._pointerPressed,!1),this.setPointerStateT(i,this._pointerEvent,t.source),this.setPointerState(i,this._pointerUp,!0),this.updatePointerPosition(t);for(let c=this._pointerEventsPressed.length-1;c>=0;c--)if(this._pointerEventsPressed[c].pointerId===i){this._pointerEventsPressed.splice(c,1);break}if(!this._pointerPositionDown[i]){ut&&xe("Received pointer up event without matching down event for button: "+i),console.warn("Received pointer up event without matching down event for button: "+i);return}const n=this._pointerUpTime[i],o=this._pointerDownTime[i],r=this.context.time.realtimeSinceStartup,l=r-o;if(i>=this._pointerUpTime.length&&this._pointerUpTime.push(-99),this._pointerUpTime[i]=r,l<1){let c=t.clientX-this._pointerPositionDown[i].x,h=t.clientY-this._pointerPositionDown[i].y,d=0;if(t.isSpatial&&t.clientZ!=null&&(d=t.clientZ-this._pointerPositionDown[i].z,c*=200,h*=200,d*=200),Math.abs(c)<5&&Math.abs(h)<5&&Math.abs(d)<5){this.setPointerState(i,this._pointerClick,!0),t.isClick=!0;const u=r-n;ut&&console.log("CLICK",i,c,h,d,u),u<this._doubleClickTimeThreshold&&u>0&&(this.setPointerState(i,this._pointerDoubleClick,!0),t.isDoubleClick=!0)}}this.onDispatchEvent(t)}updatePointerPosition(t){const i=t.pointerId;for(;i>=this._pointerPositions.length;)this._pointerPositions.push(new oe);for(;i>=this._pointerPositionsLastFrame.length;)this._pointerPositionsLastFrame.push(new oe);for(;i>=this._pointerPositionsDelta.length;)this._pointerPositionsDelta.push(new oe);const n=this._pointerPositionsLastFrame[i];n.copy(this._pointerPositions[i]);const o=this._pointerPositionsDelta[i];let r=t.clientX-n.x,l=t.clientY-n.y;if(t.source instanceof MouseEvent||t.source instanceof TouchEvent){const u=t.source;r===0&&u.movementX!==0&&(r=u.movementX||0),l===0&&u.movementY!==0&&(l=u.movementY||0)}o.x+=r,o.y+=l,this._pointerPositions[i].x=t.clientX,this._pointerPositions[i].y=t.clientY;const c=t.clientX,h=t.clientY;for(;i>=this._pointerPositionsRC.length;)this._pointerPositionsRC.push(new oe);const d=this._pointerPositionsRC[i];d.set(c,h),this.convertScreenspaceToRaycastSpace(d)}getPointerIndex(t){let i=-1;for(let n=0;n<this._pointerIds.length;n++){if(this._pointerIds[n]===t)return n;i===-1&&this._pointerIds[n]===-1&&(i=n)}return i!==-1?(this._pointerIds[i]=t,i):(ut&&console.log("PUSH pointerId:",t),this._pointerIds.push(t),this._pointerIds.length-1)}setPointerState(t,i,n){i[t]=n}setPointerStateT(t,i,n){return i[t]=n,n}onDispatchEvent(t){const i=ee.Current;try{ee.Current=this.context,this.dispatchEvent(t)}finally{ee.Current=i}}}const Ra=new ne().makeRotationY(Math.PI),Yi=new V().setFromAxisAngle(new x(0,1,0),Math.PI),jP=O("debugwebxr");class LP{constructor(){if(a(this,"priority",-1e5),a(this,"gameObject"),this.gameObject=new I,this.gameObject.name="Implicit XR Rig",jP){const t=_g(16733661);t.position.y+=.5,this.gameObject.add(t)}}isXRRig(){return!0}get isActive(){return this.gameObject.visible}}const On=O("debugwebxr"),jd=O("debugcustomgesture"),DP="https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles",BP="generic-trigger",FP=new V().setFromEuler(new Ut(vn.degToRad(0),vn.degToRad(-90),vn.degToRad(-90))),zP=new x(.04,-.04,0);class og{constructor(t,i,n){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 ne),a(this,"_gripPosition",new x),a(this,"_gripQuaternion",new V),a(this,"_linearVelocity",new x),a(this,"_rayPositionRaw",new x),a(this,"_rayRotationRaw",new V),a(this,"_rayMatrix",new ne),a(this,"_rayPosition",new x),a(this,"_rayQuaternion",new V),a(this,"_gripWorldPosition",new x),a(this,"_gripWorldQuaternion",new V),a(this,"_rayWorldPosition",new x),a(this,"_rayWorldQuaternion",new V),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 wi(.15)),a(this,"_debugGripAxesHelper",new wi(.07)),a(this,"_debugRayAxesHelper",new wi(.07)),a(this,"_hitTestSourcePromise",null),a(this,"onPointerHits",o=>{}),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",o=>{var r,l,c,h;if(!this.emitPointerDownEvent||this.inputSource!==o.inputSource)return;this.onUpdateFrame(o.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),!jd&&(On&&q.DrawDirection(this.rayWorldPosition,G(0,.01,1).applyQuaternion(this.rayWorldQuaternion),16711680,10),this.emitPointerEvent(Be.PointerDown,this._selectButtonIndex||0,"xr-standard-trigger",!0,o))}),a(this,"onSelectEnd",o=>{this.emitPointerUpEvent&&(jd||this.inputSource===o.inputSource&&this.emitPointerEvent(Be.PointerUp,this._selectButtonIndex||0,"xr-standard-trigger",!0,o))}),a(this,"onSequeezeStart",o=>{var r,l,c;this.emitPointerDownEvent&&this.inputSource===o.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&&(On&&q.DrawDirection(this.rayWorldPosition,G(0,.01,1).applyQuaternion(this.rayWorldQuaternion),255,10),this.emitPointerEvent(Be.PointerDown,this._squeezeButtonIndex||0,"xr-standard-squeeze",!0,o)))}),a(this,"onSequeezeEnd",o=>{this.emitPointerUpEvent&&this.inputSource===o.inputSource&&this._squeezeButtonIndex!==void 0&&this.emitPointerEvent(Be.PointerUp,this._squeezeButtonIndex||0,"xr-standard-squeeze",!0,o)}),a(this,"states",{}),a(this,"_didMoveLastFrame",!1),a(this,"_lastPointerMovePosition",new x),a(this,"_lastPointerMoveQuaternion",new V),a(this,"pointerInit"),this.xr=t,this.inputSource=i,this.index=n,this._object=new I,this._object.name=`NeedleXRController_${n}`,On&&(this._object.add(this._debugAxesHelper),this._gripSpaceObject=new I,this._raySpaceObject=new I,this._gripSpaceObject.name=`NeedleXRController_${n}_gripSpace`,this._raySpaceObject.name=`NeedleXRController_${n}_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 oo,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(t,i){var n;if(i=i||this.xr.frame,!this.hand||!(i!=null&&i.getJointPose)||!this.xr.referenceSpace)return null;let o=(n=this._handJointPoses)==null?void 0:n.get(t);return o||(o=i.getJointPose(t,this.xr.referenceSpace),o&&this._handJointPoses.set(t,o),o)}get gripPosition(){return G(this._gripPosition)}get gripQuaternion(){return vs(this._gripQuaternion)}get gripMatrix(){return this._gripMatrix}get gripLinearVelocity(){return G(this._linearVelocity).applyQuaternion(Yi)}get rayPosition(){return G(this._rayPosition)}get rayQuaternion(){return vs(this._rayQuaternion)}get gripWorldPosition(){return G(this._gripWorldPosition)}get gripWorldQuaternion(){return vs(this._gripWorldQuaternion)}get rayWorldPosition(){return G(this._rayWorldPosition)}updateRayWorldPosition(){var t;const i=(t=this.xr.context.mainCamera)==null?void 0:t.parent;this._rayWorldPosition.copy(this._rayPositionRaw),i&&this._rayWorldPosition.applyMatrix4(i.matrixWorld)}get rayWorldQuaternion(){return vs(this._rayWorldQuaternion)}get pinchPosition(){return G(this._pinchPosition)}updateRayWorldQuaternion(){var t;const i=(t=this.xr.context.mainCamera)==null?void 0:t.parent,n=i?Oe(i):void 0;this._rayWorldQuaternion.copy(this._rayRotationRaw).multiply(Yi),n&&this._rayWorldQuaternion.premultiply(n)}get ray(){return this._ray.origin.copy(this.rayWorldPosition),this._ray.direction.copy(G(0,0,1).applyQuaternion(this.rayWorldQuaternion)),this._ray}get handWristDotUp(){var t;if(this._hand_wristDotUp!==void 0)return this._hand_wristDotUp;const i=(t=this.handObject)==null?void 0:t.joints.wrist;if(i){const n=G(0,1,0).applyQuaternion(i.quaternion),o=G(0,1,0).dot(n);return this._hand_wristDotUp=o}}get isHandUpsideDown(){return this.handWristDotUp!==void 0?this.handWristDotUp<-.7:!1}get isTeleportGesture(){var t;return this.isHandUpsideDown&&((t=this.getGesture("pinch"))==null?void 0:t.isDown)}get object(){return this._object}async getModelUrl(){var t;return(t=this.getMotionController)==null?void 0:t.then(i=>i?.assetUrl||null)}_requestHitTestSource(){var t;return this._hitTestSourcePromise?this._hitTestSourcePromise:this.xr.mode==="immersive-ar"&&this.inputSource.targetRayMode==="tracked-pointer"&&this.xr.session.requestHitTestSourceForTransientInput?this._hitTestSourcePromise=((t=this.xr.session.requestHitTestSourceForTransientInput({profile:this.inputSource.profiles[0],offsetRay:new XRRay}))==null?void 0:t.then(i=>(this._hitTestSourcePromise=null,this.connected?this._hitTestSource=i:(i.cancel(),null))))??null:null}onUpdate(t){performance.mark("NeedleXRController onUpdate start"),this.onUpdateFrame(t),this.updateInputEvents(),this.onUpdateMove(),performance.mark("NeedleXRController onUpdate end"),performance.measure("NeedleXRController onUpdate","NeedleXRController onUpdate start","NeedleXRController onUpdate end")}onRenderDebug(){var t;q.DrawSphere(this.rayWorldPosition,.003),q.DrawDirection(this.rayWorldPosition,G(0,0,10).applyQuaternion(this.rayWorldQuaternion));const i=(this.inputSource.gripSpace?this.gripWorldPosition:this.object.worldPosition).sub(this.object.worldForward.multiplyScalar(.1)),n=this.inputSource.profiles.join(`
135
135
  `);let o=`Controller[${this.index}] (${this.inputSource.targetRayMode}, ${this.side})
136
136
  C:${this.connected?"x":"-"} T:${this.isTracking?"x":"-"} Hand:${this.inputSource.hand?"x":"-"} Pen: ${this._isMxInk?"x":"-"}`;if(this.inputSource.hand&&(o+=`
@@ -150,13 +150,13 @@ or by using the once option like onStart(()=>{}, { once:true }).
150
150
  See https://engine.needle.tools/docs/scripting.html#special-lifecycle-hooks for more information.`))}}function mo(s,t){const i=Ea.get(t);if(i){for(let o=0;o<i.length;o++)if(i[o].method===s){i.splice(o,1);return}}const n=Ta.get(t);if(n){for(let o=0;o<n.length;o++)if(n[o].method===s){n.splice(o,1);return}}}function Ns(s,t){t===ye.ContextCreated&&rg.delete(s),_b(s,t)}function _b(s,t){t===Me.Start&&Ta.get(ye.ContextCreated)&&_b(s,ye.ContextCreated);const i=t===Me.Start||t===ye.ContextCreated,n=Ea.get(t);n&&n.length>0&&xb(s,n,i);const o=Ta.get(t);if(o&&o.length>0){const r=[...o];o.length=0,xb(s,r,i),r.length>0&&(Ea.has(t)||Ea.set(t,new Array),Ea.get(t).push(...r))}}const Ld=new Array,wb={context:null};function xb(s,t,i){var n,o;Ld.length=0;for(let l=0;l<t.length;l++)Ld.push(t[l]);let r=rg.get(s);for(let l=0;l<Ld.length;l++){const c=Ld[l];let h=!0;if(r&&r.has(c)&&(h=!1),h)try{wb.context=s,(n=c.method)==null||n.call(wb,s)}catch(d){console.error("Error in lifecycle method",d)}if((o=c.options)!=null&&o.once){for(let d=0;d<t.length;d++)if(t[d]===c){t.splice(d,1);break}}else i&&(r||(r=new Set,rg.set(s,r)),r.add(c))}}const rg=new WeakMap,ag={};function lg(s,t){ag[s]=t}function Sb(s){const t=s.getBufferIdentifier(),i=ag[t];return i(s)}function Cb(s){return typeof s.guid=="function"?s.guid():null}let cg;function UP(){return cg}function NP(s){cg=s}function Ob(s,t){return t||(t={}),t={...cg,...t},s?new dv(s,t):new dv(t)}async function Pb(){const s=await import("./vendor.light.min.js").then(t=>t.i);return console.log(s),s.default===void 0?s:s.default}class kb{constructor(){a(this,"_host"),a(this,"_client"),a(this,"_clientData"),this.onEnable()}get isHost(){return this._host!==void 0}onEnable(){const t="HOST-5980e65c-8438-453e-8b35-f13c736dcd81";this.trySetupHost(t)}async trySetupHost(t){const i=await Pb(),n=new i(t);n.on("error",o=>{console.error(o),this._host=void 0,this.trySetupClient(t)}),n.on("open",o=>{this._host=new VP(n)})}async trySetupClient(t){const i=await Pb();this._client=new i,this._client.on("error",n=>{console.error("Client error",n)}),this._client.on("open",n=>{console.log("client connected",n),this._clientData=this._client.connect(t,{metadata:{id:n}}),this._clientData.on("open",()=>{console.log("Connected to host")}),this._clientData.on("data",o=>{console.log("<<",o)})})}}class WP{constructor(t){a(this,"_peer"),this._peer=t}}class VP extends WP{constructor(t){var i;super(t),a(this,"_connections",[]),console.log("I AM THE HOST"),(i=this._peer)==null||i.on("connection",this.onConnection.bind(this)),this._peer.on("close",()=>{this.broadcast("BYE")}),setInterval(()=>{this.broadcast("HELLO")},2e3)}get isHost(){return!0}onConnection(t){console.log("host connection",t),t.on("open",()=>{this._connections.push(t),this.broadcastConnection(t)})}broadcastConnection(t){const i=this._connections.map(n=>{var o;return(o=n.metadata)==null?void 0:o.id}).filter(n=>n!==void 0);this.broadcast({type:"connection-list",connections:i})}broadcast(t){if(t!=null){console.log(">>",t);for(const i in this._peer.connections){const n=this._peer.connections[i];if(n)if(Array.isArray(n))for(const o of n)o&&o.send(t);else console.warn(n)}}}}var ws=(s=>(s[s.OnConnection=0]="OnConnection",s[s.OnRoomJoin=1]="OnRoomJoin",s[s.Queued=2]="Queued",s[s.Immediate=3]="Immediate",s))(ws||{});const Mb="https://urls.needle.tools/default-networking-backend/index";let Pi="wss://networking.needle.tools/socket";const di=!!O("debugnet"),pc=!!(di||O("debugowner")),hg=O("debugnetbin");var Rb=(s=>(s.ConnectionInfo="connection-start-info",s))(Rb||{}),ie=(s=>(s.Join="join-room",s.Leave="leave-room",s.JoinedRoom="joined-room",s.LeftRoom="left-room",s.UserJoinedRoom="user-joined-room",s.UserLeftRoom="user-left-room",s.RoomStateSent="room-state-sent",s))(ie||{});class HP{constructor(){a(this,"room"),a(this,"viewId"),a(this,"allowEditing"),a(this,"inRoom")}}class $P{constructor(){a(this,"room")}}class qP{constructor(){a(this,"userId")}}var Tb=(s=>(s.RequestHasOwner="request-has-owner",s.ResponseHasOwner="response-has-owner",s.RequestIsOwner="request-is-owner",s.ResponseIsOwner="response-is-owner",s.RequestOwnership="request-ownership",s.GainedOwnership="gained-ownership",s.RemoveOwnership="remove-ownership",s.LostOwnership="lost-ownership",s.GainedOwnershipBroadcast="gained-ownership-broadcast",s.LostOwnershipBroadcast="lost-ownership-broadcast",s))(Tb||{});class dg{constructor(t,i){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=t,this.guid=i,this._gainSubscription=this.onGainedOwnership.bind(this),this._lostSubscription=this.onLostOwnership.bind(this),t.beginListen("lost-ownership",this._lostSubscription),t.beginListen("gained-ownership-broadcast",this._gainSubscription),this._hasOwnerResponse=this.onHasOwnerResponse.bind(this),t.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(t){t.guid===this.guid&&(this._isOwned=t.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(t){t.guid===this.guid&&(this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this._isOwned=t.value,t.value||(pc&&console.log("request ownership",this.guid),this.requestOwnership()))}requestOwnershipAsync(){return new Promise((t,i)=>{this.requestOwnership();let n=0;const o=()=>{if(n++>10)return i("Timeout");setTimeout(()=>{this.hasOwnership?t(this):o()},100)};o()})}requestOwnership(){return pc&&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(t){t.guid===this.guid&&(this._isOwned=!0,this.connection.connectionId===t.owner?(pc&&console.log("GAINED OWNERSHIP",this.guid),this._hasOwnership=!0):this._hasOwnership=!1)}onLostOwnership(t){t===this.guid&&(pc&&console.log("LOST OWNERSHIP",this.guid),this._hasOwnership=!1,this._isOwned=!1)}}class Eb{constructor(t){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=t}get peer(){return this._peer||(this._peer=new kb),this._peer}tryGetState(t){return t==="invalid"?null:this._state[t]}get connectionId(){return this._connectionId}get isDebugEnabled(){return di}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 t=new URL(window.location.href);return t.searchParams.set("view",this.currentRoomViewId),t.href}get isInRoom(){return this._isInRoom}get currentLatency(){return this._currentDelay}get currentServerUrl(){var t;return((t=this._ws)==null?void 0:t.url)??null}sendPing(){this.send("ping",{time:this.context.time.time})}userIsInRoom(t){return this._currentInRoom.indexOf(t)!==-1}usersInRoom(t=null){t||(t=this._usersInRoomCopy),t.length=0;for(const i of this._currentInRoom)t.push(i);return t}joinRoom(t,i=!1){return t?t.length>1024?(console.error('Room name too long, can not join: "'+t+'". Max length is 1024 characters.'),!1):(this.connect(),di&&console.log("join: "+t),this.send("join-room",{room:t,viewOnly:i},ws.OnConnection),!0):(console.error('Missing room name, can not join: "'+t+'"'),!1)}leaveRoom(t=null){return t||(t=this.currentRoomName),t?(this.send("leave-room",{room:t}),!0):(console.error('Missing room name, can not join: "'+t+'"'),!1)}send(t,i=null,n=ws.Queued){if(i===null&&(i={}),n===ws.Queued){this._defaultMessagesBuffer.push({key:t,value:i});return}return this.sendWithWebsocket(t,i,n)}sendDeleteRemoteState(t){this.send("delete-state",{guid:t,dontSave:!0}),delete this._state[t]}sendDeleteRemoteStateAll(){this.send("delete-all-state"),this._state={}}sendBinary(t){var i;hg&&console.log("<< send binary",this.context.time.frame,t.length/1024+" KB"),(i=this._ws)==null||i.send(t)}sendBufferedMessagesNow(){var t;if(!this._ws)return;this._defaultMessagesBufferArray.length=0;const i=Object.keys(this._defaultMessagesBuffer).length;for(const o in this._defaultMessagesBuffer){const r=this._defaultMessagesBuffer[o];if(i<=1){this.sendWithWebsocket(r.key,r.value,ws.Immediate);break}const l=this.toMessage(r.key,r.value);this._defaultMessagesBufferArray.push(l)}if(this._defaultMessagesBuffer.length=0,this._defaultMessagesBufferArray.length>0&&di&&console.log("SEND BUFFERED",this._defaultMessagesBufferArray.length),this._defaultMessagesBufferArray.length<=0)return;const n=JSON.stringify(this._defaultMessagesBufferArray);(t=this._ws)==null||t.send(n)}beginListen(t,i){return this._listeners[t]||(this._listeners[t]=[]),this._listeners[t].push(i),i}stopListening(t,i){return this.stopListen(t,i)}stopListen(t,i){if(!i||!this._listeners[t])return;const n=this._listeners[t].indexOf(i);n>=0&&this._listeners[t].splice(n,1)}beginListenBinary(t,i){return this._listenersBinary[t]||(this._listenersBinary[t]=[]),this._listenersBinary[t].push(i),i}stopListenBinary(t,i){if(!this._listenersBinary[t])return;const n=this._listenersBinary[t].indexOf(i);n>=0&&this._listenersBinary[t].splice(n,1)}registerProvider(t){this.netWebSocketUrlProvider=t}async connect(t){var i;if(this.connected&&t&&t!==Pi)return Promise.reject("Can not connect to different server url. Please disconnect first.");if(this.connected)return Promise.resolve(!0);t&&console.debug("Connecting to user provided url "+t);const n=t||((i=this.netWebSocketUrlProvider)==null?void 0:i.getWebsocketUrl());return n?Pi=n:xv()&&(Pi="wss://"+window.location.host+"/socket"),this.connectWebsocket()}disconnect(){var t;(t=this._ws)==null||t.close(),this._ws=void 0,Pi=void 0}connectWebsocket(){return this._connectingToWebsocketPromise?this._connectingToWebsocketPromise:this._connectingToWebsocketPromise=new Promise(async(t,i)=>{var n,o;let r=!1;const l=p=>{r||(r=!0,t(p))};if(Pi===void 0&&(console.log("Fetch default backend url: "+Mb),Pi=await(await fetch(Mb)).text()),Pi===void 0){l(!1);return}console.debug(`\u22A1 Connecting to networking backend on
151
151
  `+Pi);const c=await import("./vendor.light.min.js").then(p=>p.j),h=((n=c.default)==null?void 0:n.WebsocketBuilder)??c.WebsocketBuilder,d=((o=c.default)==null?void 0:o.ExponentialBackoff)??c.ExponentialBackoff,u=new h(Pi).withMaxRetries(10).withBackoff(new d(2e3,4)).onOpen(()=>{this._connectingToWebsocketPromise=null,this._ws=u,this.connected=!0,F()||di?console.log(`\u229E Connected to networking backend
152
152
  `+Pi):console.debug("\u229E Connected to networking backend",Pi),l(!0),this.onSendQueued(ws.OnConnection)}).onClose(p=>{this._connectingToWebsocketPromise=null,this.connected=!1,this._isInRoom=!1,l(!1);let g="Websocket connection closed...";Pi!=null&&Pi.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(t,i){const n=i.data;try{if(typeof n!="string"){n.size&&this.handleIncomingBinaryMessage(n);return}const o=JSON.parse(n);if(Array.isArray(o))for(const r of o)this.handleIncomingStringMessage(r);else this.handleIncomingStringMessage(o);return}catch(o){di&&n==="pong"?console.log("<<",n):F()&&console.error("Failed to parse message",o)}}async handleIncomingBinaryMessage(t){hg&&console.log("<< bin",this.context.time.frame);const i=await t.arrayBuffer();var n=new Uint8Array(i);const o=new ZC(n),r=o.getBufferIdentifier(),l=this._listenersBinary[r],c=Sb(o),h=Cb(c);if(h&&typeof h=="string"&&(this._state[h]=c),!l)return;const d=c??o;for(const u of l)u(d)}handleIncomingStringMessage(t){var i,n;if(di&&console.log("<<",t.key??t),t.key)switch(t.key){case"connection-start-info":if(t.data){const c=t.data;c&&(console.assert(c.id!==void 0&&c.id!==null&&c.id.length>0,"server did not send connection id",c.id),console.debug("Your id is: "+c.id,this.context.alias??""),this._connectionId=c.id)}else console.warn("Expected connection id in "+t.key);break;case"joined-room":if(di&&console.log(t),t){this._isInRoom=!0;const c=t;this._currentRoomName=c.room,this._currentRoomViewId=c.viewId,this._currentRoomAllowEditing=c.allowEditing??!0,this._currentInRoom.length=0,this._currentInRoom.push(...c.inRoom),(hg||F())&&console.debug("Joined Needle Engine Room: "+c.room);const h=new URL(window.location.href);h.searchParams.has("room")&&h.searchParams.delete("room"),h.searchParams.set("view",this._currentRoomViewId),console.debug(`Room view id: ${this._currentRoomViewId}
153
- ${h.href}`)}this.onSendQueued(ws.OnRoomJoin);break;case"left-room":t.room===this.currentRoomName&&(this._isInRoom=!1,this._currentRoomName=null,this._currentInRoom.length=0);break;case"user-joined-room":if(t.data){const c=t.data;this._currentInRoom.push(c.userId),di&&console.log(c.userId+" joined","now in room:",this._currentInRoom)}break;case"user-left-room":if(t.data){const c=t.data,h=this._currentInRoom.indexOf(c.userId);h>=0&&(di&&console.log(c.userId+" left","now in room:",this._currentInRoom),this._currentInRoom.splice(h,1)),c.userId===this.connectionId&&console.log("you left the room")}break;case"all-room-state-deleted":di&&console.log("RECEIVED all-room-state-deleted"),this._state={};break;case"ping":case"pong":const l=(i=t.data)==null?void 0:i.time;l&&(this._currentDelay=this.context.time.time-l),di&&console.log("Current latency: "+this._currentDelay.toFixed(4)+" sec","Clients in room: "+((n=this._currentInRoom)==null?void 0:n.length));break}const o=t.data;o&&(this._state[o.guid]=o);let r=this._listeners[t.key];if(r){r=[...r];for(const l of r)try{l(t.data)}catch(c){console.error('Error invoking callback for "'+t.key+'"',c)}}}toMessage(t,i){return{key:t,data:i}}sendWithWebsocket(t,i,n=ws.OnRoomJoin){if(!this._ws){const r=this._waitingForSocket[n]||[];r.push(()=>this.sendWithWebsocket(t,i,n)),this._waitingForSocket[n]=r;return}const o=JSON.stringify(this.toMessage(t,i));di&&console.log(">>",t),this._ws.send(o)}onSendQueued(t){const i=this._waitingForSocket[t];if(i){for(const n of i)n();i.length=0}}}const mc=O("debugwebxr");class ug{constructor(t,i){a(this,"controllerStates",[]),a(this,"userId"),a(this,"context"),a(this,"userStateEvtName"),a(this,"onReceivedControllerState",n=>{mc&&console.log(`XRSync: Received change for ${this.userId}: ${n.type} ${n.handedness}; tracked=${n.isTracking}`);let o=!1;for(let r=0;r<this.controllerStates.length;r++)if(this.controllerStates[r].index===n.index){this.controllerStates[r]=n,o=!0;break}o||this.controllerStates.push(n)}),this.userId=t,this.context=i,this.userStateEvtName="xr-sync-user-state-"+t,this.context.connection.beginListen(this.userStateEvtName,this.onReceivedControllerState)}dispose(){this.context.connection.stopListen(this.userStateEvtName,this.onReceivedControllerState)}update(t){if(this.context.connection.isConnected!=!1){for(let i=this.controllerStates.length-1;i>=0;i--){const n=this.controllerStates[i];let o=!1;for(let r=0;r<t.controllers.length;r++)t.controllers[r].index===n.index&&(o=!0);o||(mc&&console.log(`XRSync: ${n.type} ${n.handedness} removed`,n.index),this.controllerStates.splice(i,1),this.sendControllerRemoved(n))}for(const i of t.controllers)this.updateControllerStates(i)}}onExitXR(t){for(const i of this.controllerStates)this.sendControllerRemoved(i);this.controllerStates.length=0}sendControllerRemoved(t){t.isTracking=!1,t.guid="",this.context.connection.send(this.userStateEvtName,t),this.context.connection.sendDeleteRemoteState(t.guid)}updateControllerStates(t){const i=this.controllerStates.find(n=>n.index===t.index);if(i){let n=!1;n||(n=i.isTracking!=t.isTracking),n&&(i.isTracking=t.isTracking,this.context.connection.send(this.userStateEvtName,i))}else{const n={guid:this.userId+"-"+t.index,isTracking:t.isTracking,handedness:t.side,index:t.index,type:t.hand?"hand":"controller"};this.controllerStates.push(n),this.context.connection.send(this.userStateEvtName,n),mc&&console.log(`XRSync: ${n.type} ${n.handedness} added`,n.index)}}}class Ab{constructor(t){a(this,"context"),a(this,"onJoinedRoom",()=>{if(this.context.connection.connectionId){this._states.has(this.context.connection.connectionId)||(mc&&console.log("XRSync: Local user joined room",this.context.connection.connectionId),this._states.set(this.context.connection.connectionId,new ug(this.context.connection.connectionId,this.context)));for(const i of this.context.connection.usersInRoom())this._states.has(i)||this._states.set(i,new ug(i,this.context))}}),a(this,"onLeftRoom",()=>{if(this.context.connection.connectionId&&!this._states.has(this.context.connection.connectionId)){const i=this._states.get(this.context.connection.connectionId);i?.dispose(),this._states.delete(this.context.connection.connectionId)}}),a(this,"onOtherUserJoinedRoom",i=>{const n=i.userId;this._states.has(n)||(mc&&console.log("XRSync: Remote user joined room",n),this._states.set(n,new ug(n,this.context)))}),a(this,"onOtherUserLeftRoom",i=>{const n=i.userId;if(!this._states.has(n)){const o=this._states.get(n);o?.dispose(),this._states.delete(n)}}),a(this,"_states",new Map),this.context=t,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(t){return t?this._states.has(t):!1}isTracking(t,i){if(!t)return;const n=this._states.get(t);if(!n)return;const o=n.controllerStates.find(r=>r.handedness===i);return o?.isTracking||!1}getDeviceType(t,i){if(!t)return;const n=this._states.get(t);if(!n)return;const o=n.controllerStates.find(r=>r.handedness===i);return o?.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(t){if(this.context.connection.isConnected&&this.context.connection.connectionId){const i=this._states.get(this.context.connection.connectionId);i?.update(t)}}onExitXR(t){if(this.context.connection.isConnected&&this.context.connection.connectionId){const i=this._states.get(this.context.connection.connectionId);i?.onExitXR(t)}}}class Ib{constructor(){a(this,"_fadeToColorQuad"),a(this,"_fadeToColorMaterial"),a(this,"_requestedFadeValue",0),a(this,"_transitionPromise",null),a(this,"_transitionResolve",null),this._fadeToColorMaterial=new Re({color:0,transparent:!0,depthTest:!1,fog:!1,side:xi}),this._fadeToColorQuad=new K(new Fs(10,10),this._fadeToColorMaterial)}dispose(){this._fadeToColorQuad.geometry.dispose(),this._fadeToColorMaterial.dispose()}update(t,i){const n=this._fadeToColorQuad,o=this._fadeToColorMaterial;n.parent!==t&&o.opacity>0?t.add(n):o.opacity===0&&n.removeFromParent(),n.layers.set(2),n.material=this._fadeToColorMaterial,n.position.z=-1,n.renderOrder=1/0;const r=this._requestedFadeValue;o.opacity=W.lerp(o.opacity,r,i/.03),Math.abs(o.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 t=new Promise(i=>{this._transitionResolve=i});return this._transitionPromise=t,t}}var wr=(s=>(s[s.Quad=0]="Quad",s[s.Cube=1]="Cube",s[s.Sphere=2]="Sphere",s[s.RoundedCube=10]="RoundedCube",s))(wr||{}),Dd,pg;class go{static createText(t,i){let n=null;const o=i?.font||XP(i?.familyFamily||null);o instanceof TC?n=va(this,Dd,pg).call(this,t,o,i):n==null&&(n=new bn);const r=i?.color||16777215,l=new K(n,i?.material??new li({color:r}));return this.applyDefaultObjectOptions(l,i),o instanceof Promise?o.then(c=>{l.geometry=va(this,Dd,pg).call(this,t,c,i),i!=null&&i.onGeometry&&i.onGeometry(l)}):i!=null&&i.onGeometry&&i.onGeometry(l),l}static createOccluder(t){const i=new Re({colorWrite:!1,depthWrite:!0,side:xi});return this.createPrimitive(t,{material:i})}static createPrimitive(t,i){let n;const o=i?.color||16777215;switch(t){case"Quad":case 0:{const r=new Fs(1,1,1,1),l=i?.material??new li({color:o});i!=null&&i.texture&&"map"in l&&(l.map=i.texture),n=new K(r,l),n.name="Quad"}break;case"Cube":case 1:{const r=new Gl(1,1,1),l=i?.material??new li({color:o});i!=null&&i.texture&&"map"in l&&(l.map=i.texture),n=new K(r,l),n.name="Cube"}break;case 10:case"RoundedCube":{const r=GP(1,1,1,.1,2),l=i?.material??new li({color:o});i!=null&&i.texture&&"map"in l&&(l.map=i.texture),n=new K(r,l),n.name="RoundedCube"}break;case"Sphere":case 2:{const r=new hd(.5,16,16),l=i?.material??new li({color:o});i!=null&&i.texture&&"map"in l&&(l.map=i.texture),n=new K(r,l),n.name="Sphere"}break;case"ShaderBall":n=new ro,n.name="ShaderBall",QP(n,i);break}return this.applyDefaultObjectOptions(n,i),n}static createSprite(t){const i=new dS({color:16777215});t!=null&&t.texture&&"map"in i&&(i.map=t.texture);const n=new uS(i);return this.applyDefaultObjectOptions(n,t),n}static applyDefaultObjectOptions(t,i){t.receiveShadow=!0,t.castShadow=!0,i!=null&&i.name&&(t.name=i.name),i!=null&&i.position&&(Array.isArray(i.position)?t.position.set(i.position[0],i.position[1],i.position[2]):t.position.set(i.position.x,i.position.y,i.position.z)),i!=null&&i.rotation&&(Array.isArray(i.rotation)?t.rotation.set(i.rotation[0],i.rotation[1],i.rotation[2]):t.rotation.set(i.rotation.x,i.rotation.y,i.rotation.z)),i!=null&&i.scale&&(typeof i.scale=="number"?t.scale.set(i.scale,i.scale,i.scale):t.scale.set(i.scale.x,i.scale.y,i.scale.z)),i?.receiveShadow!=null&&(t.receiveShadow=i.receiveShadow),i?.castShadow!=null&&(t.castShadow=i.castShadow),i!=null&&i.parent&&i.parent.add(t)}}Dd=new WeakSet,pg=function(s,t,i){const n=i?.depth||.1;return new EC(s,{font:t,size:1,depth:n,height:n,bevelEnabled:i?.bevel||!1,bevelThickness:.01,bevelOffset:.01,bevelSize:.01})},$i(go,Dd);function GP(s,t,i,n,o){const r=new pS,l=1e-5,c=n-l;r.absarc(l,l,l,-Math.PI/2,-Math.PI,!0),r.absarc(l,t-c*2,l,Math.PI,Math.PI/2,!0),r.absarc(s-c*2,t-c*2,l,Math.PI/2,0,!0),r.absarc(s-c*2,l,l,0,-Math.PI/2,!0);const h=new mS(r,{bevelEnabled:!0,bevelSegments:o*2,steps:1,bevelSize:c,bevelThickness:n,curveSegments:o});return h.scale(1,1,1-n),h.center(),h.computeVertexNormals(),h}const Bd=new Map;function XP(s){let t="";switch(s){default:case"OpenSans":t="https://cdn.needle.tools/static/fonts/facetype/Open Sans_Regular_ascii.json";break;case"Helvetiker":t="https://raw.githubusercontent.com/mrdoob/three.js/master/examples/fonts/helvetiker_regular.typeface.json";break}if(Bd.has(t)){const o=Bd.get(t);if(o)return o}const i=new AC,n=new Promise((o,r)=>{i.load(t,l=>{Bd.set(t,l),o(l)},void 0,r)});return Bd.set(t,n),n}let mg=!1,gg=null;function QP(s,t){if(gg===null){const i="https://cdn.needle.tools/static/models/shaderball.glb",n=new gr,o=wm(null);n.setDRACOLoader(o.dracoLoader),n.setKTX2Loader(o.ktx2Loader),mg=!0,gg=n.loadAsync(i).then(r=>{const l=r.scene;return l.position.y-=.5,l}).catch(r=>(console.warn("Failed to load shaderball mesh: "+r.message),Lb())).finally(()=>{mg=!1})}if(mg){const i=Lb();i.name="ShaderBall-Placeholder";const n=i.children[0];n?.type==="Mesh"&&jb(n,t),s.add(i)}gg.then(i=>{s.children.forEach(r=>{r.name==="ShaderBall-Placeholder"&&s.remove(r)});const n=i.clone(),o=n.children[0];o?.type==="Mesh"&&jb(o,t),s.add(n)})}function jb(s,t){var i;if(t?.color||t?.material||t?.texture){const n=t?.material??((i=s.material)==null?void 0:i.clone())??new li;t.color&&"color"in n&&n.color instanceof re&&n.color.set(t.color),t!=null&&t.texture&&"map"in n&&(n.map=t.texture),s.material=n}}function Lb(){return new ro().add(go.createPrimitive("Sphere",{material:new Re({transparent:!0,opacity:.1})}))}const Db=class{constructor(s,t,i){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,o)=>{const r=n-this._lastTime;this.update(n,r),this._camera.parent!==this._scene&&this._scene.add(this._camera),this._renderer.render(this._scene,this._camera)}),a(this,"_objects",[]),this._mode=s,this._init=t,this._session=i,this._session.addEventListener("end",this.onEnd),this._renderer=new ur({alpha:!0}),this._renderer.setAnimationLoop(this.onFrame),this._renderer.xr.setSession(i),this._renderer.xr.enabled=!0,this._camera=new we,this._scene=new qi,this._scene.fog=new $y(4473924,10,250),this._scene.add(this._camera),this.setupScene()}static get active(){return this._active}static async start(s,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 i=await navigator.xr.requestSession(s,t);return i.addEventListener("end",()=>{this._active=null}),this._requestInFlight?(this._requestInFlight=!1,this._active=new Db(s,t,i),this._active):(i.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 s={session:this._session,mode:this._mode,init:this._init};return await this.onBeforeHandoff(),this.onEnd(),this._session=null,s}async onBeforeHandoff(){await ys(1e3),this._scene.clear()}setupScene(){this._scene.background=new re(0),this._scene.add(new cm(5,10,1118481,1118481));const s=new hm(16777215,1);s.position.set(0,20,0),s.castShadow=!1,this._scene.add(s);const t=new hm(16777215,1);t.position.set(0,-1,0),t.castShadow=!1,this._scene.add(t);const i=new qy(16777215,1,100,1);i.position.set(0,2,0),i.castShadow=!1,i.distance=200,this._scene.add(i);const n=50;for(let o=0;o<100;o++){const r=new li({color:2236962,metalness:1,roughness:.8});this.isAR&&(r.emissive=new re(Math.random(),Math.random(),Math.random()),r.emissiveIntensity=Math.random());const l=W.random(0,1)>.5?wr.Sphere:wr.Cube,c=go.createPrimitive(l,{material:r});c.position.x=W.random(-n,n),c.position.y=W.random(-2,n),c.position.z=W.random(-n,n),c.rotation.x=W.random(0,Math.PI*2),c.rotation.y=W.random(0,Math.PI*2),c.rotation.z=W.random(0,Math.PI*2),c.scale.multiplyScalar(.5+Math.random()*10);const h=c.position.distanceTo(this._camera.position)-c.scale.x;h<1&&c.position.multiplyScalar(1+1/h),this._objects.push(c),this._scene.add(c)}}update(s,t){const i=s*4e-4;for(let n=0;n<this._objects.length;n++){const o=this._objects[n];o.position.y+=Math.sin(i+n*.5)*.005,o.rotateY(.002)}}};let Aa=Db;a(Aa,"_active",null),a(Aa,"_requestInFlight",!1);var gc;(s=>{const t=[];function i(){if(!(t!=null&&t.length))return!1;for(const r of t)r.exportAndOpen();return!0}s.exportAndOpen=i;function n(r){t.push(r)}s.registerExporter=n;function o(r){if(!t)return;const l=t.indexOf(r);l>=0&&t.splice(l,1)}s.unregisterExporter=o})(gc||(gc={}));const Bb="NeedleXRSession onStart",Fb="NeedleXRSession onEnd",yt=O("debugwebxr"),zb=O("stats");let fg=0;function YP(s){let t=null;const i=s;return i.getAROverlayContainer?t=i.getAROverlayContainer():t=s,t}KP();async function KP(){var s;if(O("debugasap")){let t=globalThis["needle:XRSession"];if(t instanceof Promise){delete globalThis["needle:XRSession"],ge.addContextCreatedCallback(async i=>{if(!t)return;br(!0);const n=await t;if(n){const o=J.getDefaultSessionInit("immersive-vr");J.setSession("immersive-vr",n,o,i.context)}else console.error("NeedleXRSession: ASAP session was rejected");t=void 0});return}}if("xr"in navigator){if(/WebXRViewer\//i.test(navigator.userAgent)){console.warn("WebXRViewer does not support addEventListener");return}(s=navigator.xr)==null||s.addEventListener("sessiongranted",async()=>{br(!0),console.log("Received Session Granted..."),await ys(100);const t=sessionStorage.getItem("needle_xr_session_mode"),i=sessionStorage.getItem("needle_xr_session_init")??null,n=i?JSON.parse(i):null;let o=null;if(Ub()&&(await Aa.start(t||"immersive-vr",n||J.getDefaultSessionInit("immersive-vr")),await e2(),o=await Aa.handoff()),o)J.setSession(o.mode,o.session,o.init,ee.Current);else if(t&&i){console.log("Session Granted: Restore last session");const r=JSON.parse(i);J.start(t,r).catch(l=>console.warn(l))}else J.start("immersive-vr").catch(r=>console.warn("Session Granted failed:",r))},{once:!0})}}function ZP(s,t){sessionStorage.setItem("needle_xr_session_mode",s),sessionStorage.setItem("needle_xr_session_init",JSON.stringify(t))}function JP(){sessionStorage.removeItem("needle_xr_session_mode"),sessionStorage.removeItem("needle_xr_session_init")}const yg=new Set;ge.registerCallback(ye.ContextCreationStart,async s=>{yg.add(s.context)}),ge.registerCallback(ye.ContextCreated,async s=>{yg.delete(s.context)});function Ub(){return yg.size>0}function e2(){return new Promise(s=>{const t=Date.now(),i=setInterval(()=>{(!Ub()||Date.now()-t>6e4)&&(clearInterval(i),s())},100)})}X.isDesktop()&&F()&&window.addEventListener("keydown",s=>{(s.key==="x"||s.key==="Escape")&&J.active&&J.stop()});const fo=class{constructor(s,t,i,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 l;this.running&&(this.context.renderer.xr.enabled=!0,this.context.renderer.xr.updateCamera(this.context.mainCamera),(l=this.context.mainCameraComponent)==null||l.applyClearFlags())}),a(this,"onInputSourceAdded",l=>{if(l.targetRayMode==="screen")return;let c=0;for(let d=0;d<this.session.inputSources.length;d++)if(this.session.inputSources[d]===l){c=d;break}if(this.controllers.find(d=>d.inputSource===l)){console.debug("Controller already exists for input source",c);return}else if(this._newControllers.find(d=>d.inputSource===l)){console.debug("Controller already registered for input source",c);return}const h=new og(this,l,c);this._newControllers.push(h)}),a(this,"_ended",!1),a(this,"_newControllers",[]),a(this,"onEnd",l=>{var c,h,d;if(this._ended)return;this._ended=!0,console.debug("XR Session ended"),JP(),this.onAfterRender(),this.revertCustomForward(),this._didStart=!1,this._previousCameraParent=null,mo(this.onBefore,Me.LateUpdate);const u=this.context.pre_render_callbacks.indexOf(this.onBeforeRender);u>=0&&this.context.pre_render_callbacks.splice(u,1);const p=this.context.post_render_callbacks.indexOf(this.onAfterRender);p>=0&&this.context.post_render_callbacks.splice(p,1),this.context.xr=null,this.context.renderer.xr.enabled=!1,this.context.pre_update_oneshot_callbacks.push(()=>{var y,f;(y=this.context.mainCameraComponent)==null||y.applyClearFlags(),(f=this.context.mainCameraComponent)==null||f.applyClippingPlane()}),gb({session:this});for(const y of fo._xrEndListeners)y({xr:this});const g=[...this.controllers];for(let y=0;y<g.length;y++)this.disconnectInputSource(g[y].inputSource);this._newControllers.length=0,this.controllers.length=0;for(const y of this._xr_scripts)(c=y?.onLeaveXR)==null||c.call(y,{xr:this});(h=this.sync)==null||h.onExitXR(this),this.context.mainCamera&&((d=this._originalCameraParent)==null||d.add(this.context.mainCamera),this._originalCameraWorldPosition&&dt(this.context.mainCamera,this._originalCameraWorldPosition),this._originalCameraWorldRotation&&Gi(this.context.mainCamera,this._originalCameraWorldRotation),this._originalCameraWorldScale&&Pa(this.context.mainCamera,this._originalCameraWorldScale)),this.context.requestSizeUpdate(),this._defaultRig.gameObject.removeFromParent(),br(!1),performance.mark(Fb),performance.measure("NeedleXRSession",Bb,Fb)}),a(this,"_didStart",!1),a(this,"onBefore",l=>{var c,h,d,u,p,g,y,f;const v=l.xrFrame;if(!v)return;performance.mark("NeedleXRSession onBefore start"),this.context.xr=this,this.context.mainCameraComponent&&this.context.mainCameraComponent!==this._mainCamera&&(this._mainCamera=this.context.mainCameraComponent),((c=this.rig)==null?void 0:c.isActive)==!1&&(yt&&console.warn("Latest rig is not active - trying to activate a different rig",this.rig),this.updateActiveXRRig()),this.rig&&(h=this._mainCamera)!=null&&h.gameObject&&((u=(d=this._mainCamera)==null?void 0:d.gameObject)==null?void 0:u.parent)!==this.rig.gameObject&&this.rig.gameObject.add((p=this._mainCamera)==null?void 0:p.gameObject),this.internalUpdateState(),this.applyCustomForward();const b={xr:this};if(this._didStart){if(this.context.new_scripts_xr.length>0){const w=[...this.context.new_scripts_xr];for(let _=0;_<w.length;_++){const C=this.context.new_scripts_xr[_];if(!C||C.destroyed||((g=C.supportsXR)==null?void 0:g.call(C,this.mode))==!1){this.context.new_scripts_xr.splice(_,1);continue}if(!C.activeAndEnabled){this.context.new_scripts_xr.splice(_,1),this.markInactive(C);continue}if(this.addScript(C)){this.invokeCallback_EnterXR(C);for(const R of this.controllers)this.invokeCallback_ControllerAdded(C,R)}}}}else{if(this._didStart=!0,this.mode==="immersive-vr"){const _=ci(this.context.scene.children);if(_){const C=_.getSize(G());if(C.length()>0){const R=this._defaultRig.gameObject;R.position.set(_.min.x+C.x*.5,_.min.y,_.max.z+C.z*.5+1.5);const M=_.getCenter(G());M.y=R.position.y,R.lookAt(M)}}}mb({session:this});for(const _ of fo._xrStartListeners)_(b);const w=[...this._xr_scripts];yt&&console.log("NeedleXRSession start, handle scripts:",w);for(const _ of w){if(_.destroyed){this._script_to_remove.push(_);continue}if(!_.activeAndEnabled){this.markInactive(_);continue}this.invokeCallback_EnterXR(_);for(const C of this.controllers)this.invokeCallback_ControllerAdded(_,C)}}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 _ of w){if(!_.connected){console.warn("New controller is not connected",_);continue}this.controllers.push(_);for(const C of this._xr_scripts){if(C.destroyed){this._script_to_remove.push(C);continue}C.activeAndEnabled!==!1&&this.invokeCallback_ControllerAdded(C,_)}}this.controllers.sort((_,C)=>_.index-C.index)}yt&&this.context.time.frame%30===0&&this.controllers.length<=0&&this.session.inputSources.length>0&&(br(!0),console.error("XRControllers are not added but inputSources are present")),performance.mark("NeedleXRSession update scripts start");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(b)}if(performance.mark("NeedleXRSession update scripts end"),performance.measure("NeedleXRSession update scripts","NeedleXRSession update scripts start","NeedleXRSession update scripts end"),this.handleInactiveScripts(),this._script_to_remove.length>0){const w=[...new Set(this._script_to_remove)];this._script_to_remove.length=0;for(const _ of w)!_.destroyed&&this.running&&((y=_.onLeaveXR)==null||y.call(_,b)),this.removeScript(_)}(f=this.sync)==null||f.onUpdate(this),this.onRenderDebug(),performance.mark("NeedleXRSession onBefore end"),performance.measure("NE XR frame","NeedleXRSession onBefore start","NeedleXRSession onBefore end")}),a(this,"onBeforeRender",()=>{this.context.mainCamera&&this.updateFade(this.context.mainCamera)}),a(this,"onAfterRender",()=>{if(this.onUpdateFade_PostRender(),X.isDesktop()||!this._renderOnceOnDevice){const l=this.context.renderer;if(l.xr.isPresenting&&this.context.mainCamera){this._renderOnceOnDevice=!0;const c=l.xr.enabled,h=l.getRenderTarget(),d=this.context.scene.background;l.xr.enabled=!1,l.setRenderTarget(null),this.isPassThrough&&(this.context.scene.background=null),this.context.composer?this.context.composer.render(this.context.time.deltaTime):l.render(this.context.scene,this.context.mainCamera),l.xr.enabled=c,l.setRenderTarget(h),this.context.scene.background=d}}}),a(this,"_script_to_remove",[]),a(this,"_camera"),a(this,"_cameraRenderParent",new I().rotateY(Math.PI)),a(this,"_previousCameraParent"),a(this,"_customforward",!0),a(this,"originalCameraNearPlane"),a(this,"_viewerPose"),a(this,"_transformOrientation",new V),a(this,"_transformPosition",new x),a(this,"_transition");var o,r;performance.mark(Bb),ZP(s,n.init),this.session=t,this.mode=s,this.context=i,(yt||O("console"))&&br(!0),this._xr_scripts=[...n.scripts],this._xr_update_scripts=this._xr_scripts.filter(l=>typeof l.onUpdateXR=="function"),this._controllerAdded=n.controller_added,this._controllerRemoved=n.controller_removed,Pn(this.onBefore,Me.LateUpdate),this.context.pre_render_callbacks.push(this.onBeforeRender),this.context.post_render_callbacks.push(this.onAfterRender),((o=n.init.optionalFeatures)!=null&&o.includes("hit-test")||(r=n.init.requiredFeatures)!=null&&r.includes("hit-test"))&&t.requestReferenceSpace("viewer").then(l=>{var c,h;return(h=(c=t.requestHitTestSource)==null?void 0:c.call(t,{space:l}))==null?void 0:h.then(d=>this._viewerHitTestSource=d).catch(d=>console.error(d))}).catch(l=>console.error(l)),this.context.mainCamera&&(this._originalCameraWorldPosition=te(this.context.mainCamera,new x),this._originalCameraWorldRotation=Oe(this.context.mainCamera,new V),this._originalCameraWorldScale=Je(this.context.mainCamera,new x),this._originalCameraParent=this.context.mainCamera.parent),this._defaultRig=new LP,this.context.scene.add(this._defaultRig.gameObject),this.addRig(this._defaultRig);for(let l=0;l<t.inputSources.length;l++){const c=t.inputSources[l];if(!c.handedness){console.warn("Input source in xr session has no handedness - ignoring",l);continue}this.onInputSourceAdded(c)}this.session.addEventListener("end",this.onEnd),this.session.addEventListener("inputsourceschange",l=>{for(const c of l.removed)this.disconnectInputSource(c);for(const c of l.added)this.onInputSourceAdded(c)}),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):yt&&console.warn("controllerAutoUpdate is not available in three.js - cannot disable it")}static getXRSync(s){return this._sync||(this._sync=new Ab(s)),this._sync}static get currentSessionRequest(){return this._currentSessionRequestMode}static get active(){return this._activeSession}static get activeMode(){var s;return((s=this._activeSession)==null?void 0:s.mode)??null}static get xrSystem(){return"xr"in navigator?navigator.xr:void 0}static isXRSupported(){return Promise.all([this.isVRSupported(),this.isARSupported()]).then(s=>s.some(t=>t)).catch(()=>!1)}static isVRSupported(){return this.isSessionSupported("immersive-vr")}static isARSupported(){return this.isSessionSupported("immersive-ar")}static isSessionSupported(s){var t;return((t=this.xrSystem)==null?void 0:t.isSessionSupported(s).catch(i=>(yt&&console.error(i),!1)))??Promise.resolve(!1)}static onSessionRequestStart(s){this._sessionRequestStartListeners.push(s)}static offSessionRequestStart(s){const t=this._sessionRequestStartListeners.indexOf(s);t>=0&&this._sessionRequestStartListeners.splice(t,1)}static onSessionRequestEnd(s){this._sessionRequestEndListeners.push(s)}static offSessionRequestEnd(s){const t=this._sessionRequestEndListeners.indexOf(s);t>=0&&this._sessionRequestEndListeners.splice(t,1)}static onXRSessionStart(s){this._xrStartListeners.push(s)}static offXRSessionStart(s){const t=this._xrStartListeners.indexOf(s);t>=0&&this._xrStartListeners.splice(t,1)}static onXRSessionEnd(s){this._xrEndListeners.push(s)}static offXRSessionEnd(s){const t=this._xrEndListeners.indexOf(s);t>=0&&this._xrEndListeners.splice(t,1)}static onControllerAdded(s){this._controllerAddedListeners.push(s)}static offControllerAdded(s){const t=this._controllerAddedListeners.indexOf(s);t>=0&&this._controllerAddedListeners.splice(t,1)}static onControllerRemoved(s){this._controllerRemovedListeners.push(s)}static offControllerRemoved(s){const t=this._controllerRemovedListeners.indexOf(s);t>=0&&this._controllerRemovedListeners.splice(t,1)}static offerSession(s,t,i){return"xr"in navigator&&navigator.xr&&"offerSession"in navigator.xr?(typeof navigator.xr.offerSession=="function"&&(console.log("WebXR offerSession is available - requesting mode: "+s),t=="default"&&(t=this.getDefaultSessionInit(s)),navigator.xr.offerSession(s,{...t}).then(n=>fo.setSession(s,n,t,i)).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(s){switch(s){case"immersive-ar":const t=["anchors","local-floor","layers","dom-overlay","hit-test","unbounded"];return X.isVisionOS()||t.push("hand-tracking"),{optionalFeatures:t};case"immersive-vr":const i=["local-floor","bounded-floor","high-fixed-foveation-level","layers"];return X.isVisionOS()||i.push("hand-tracking"),{optionalFeatures:i};default:return console.warn("No default session init for mode",s),{}}}static async start(s,t,i){var n,o,r,l;if(X.isiOS()){if(s==="ar")if(await this.isARSupported())s="immersive-ar";else return gc.exportAndOpen(),null}else s=="ar"&&(s="immersive-ar");if(F()&&O("debugxrpreroom"))return console.warn("Debug: Starting temporary XR session"),await Aa.start(s,t||fo.getDefaultSessionInit(s)),null;if(this._currentSessionRequest)return console.warn("A XRSession is already being requested"),(yt||F())&&xe("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(i||(i=ee.Current),i||(i=ge.All[0]),!i)throw new Error("No Needle Engine Context found");switch(performance.mark("NeedleXRSession start"),t||(t={}),s){case"immersive-ar":{if(await((n=this.xrSystem)==null?void 0:n.isSessionSupported("immersive-ar"))!==!0)return console.error(s+" is not supported by this browser."),null;const u=this.getDefaultSessionInit(s),p=YP(i.domElement);p&&!X.isQuest()&&(u.domOverlay={root:p},u.optionalFeatures.push("dom-overlay")),t={...u,...t}}break;case"immersive-vr":{if(await((o=this.xrSystem)==null?void 0:o.isSessionSupported("immersive-vr"))!==!0)return console.error(s+" is not supported by this browser."),null;t={...this.getDefaultSessionInit(s),...t}}break;default:console.warn("No default session init for mode",s);break}t.optionalFeatures??(t.optionalFeatures=[]),t.requiredFeatures??(t.requiredFeatures=[]),await Aa.stop();const c=s=="immersive-ar"?i.scripts_immersive_ar:i.scripts_immersive_vr;yt?console.log(`%cRequesting ${s} session`,"font-weight:bold;",t,c):console.log(`%cRequesting ${s} session`,"font-weight:bold;");for(const u of c)u.onBeforeXR&&u.onBeforeXR(s,t);for(const u of this._sessionRequestStartListeners)u({mode:s,init:t});yt&&De("Requesting "+s+" session ("+Date.now()+")"),this._currentSessionRequest=(r=navigator.xr)==null?void 0:r.requestSession(s,t),this._currentSessionRequestMode=s;const h=await((l=this._currentSessionRequest)==null?void 0:l.catch(u=>{console.error(u,"Code: "+u.code),u.code===9&&xe("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:"&&xe("XR requires a secure connection (HTTPS)")}));this._currentSessionRequest=void 0,this._currentSessionRequestMode=null;for(const u of this._sessionRequestEndListeners)u({mode:s,init:t,newSession:h||null});if(!h)return console.warn("XR Session request was rejected"),null;const d=this.setSession(s,h,t,i);return performance.mark("NeedleXRSession end"),performance.measure("NeedleXRSession Startup","NeedleXRSession start","NeedleXRSession end"),d}static setSession(s,t,i,n){if(this._activeSession)return console.error("A XRSession is already running"),this._activeSession;const o=s=="immersive-ar"?n.scripts_immersive_ar:n.scripts_immersive_vr;return this._activeSession=new fo(s,t,n,{scripts:o,controller_added:this._controllerAddedListeners,controller_removed:this._controllerRemovedListeners,init:i}),t.addEventListener("end",this.onEnd),yt?console.log(`%cStarted ${s} session`,"font-weight:bold;",o):console.log(`%cStarted ${s} session`,"font-weight:bold;"),this._activeSession}static stop(){var s;(s=this._activeSession)==null||s.end()}get sync(){return fo._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(s=>s.side==="left")}get rightController(){return this.controllers.find(s=>s.side==="right")}getController(s){return typeof s=="number"?this.controllers[s]||null:this.controllers.find(t=>t.side===s)||null}get isPassThrough(){return!!(this.environmentBlendMode!=="opaque"&&this.interactionMode==="world-space"||this.mode==="immersive-ar"&&this.environmentBlendMode!=="opaque"&&this.controllers.some(s=>s.inputSource.targetRayMode==="tracked-pointer")||F()&&X.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 s=this.frame.getImageTrackingResults();for(const t of s)if(t.trackingState==="tracked")return!0}catch{return!1}return!1}get rig(){const s=this._rigs[0]??null;return s!=null&&s.gameObject&&kr(s.gameObject)||s?.isActive===!1?(this.updateActiveXRRig(),this._rigs[0]??null):s}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(s){this._rigs.indexOf(s)>=0||(s.priority===void 0&&(s.priority=0),this._rigs.push(s),this.updateActiveXRRig())}removeRig(s){const t=this._rigs.indexOf(s);t!==-1&&(this._rigs.splice(t,1),this.updateActiveXRRig())}setRigActive(s){const t=this._rigs.indexOf(s),i=this._rigs[0];this._rigs.splice(t,1),this._rigs.unshift(s),s.priority=i?.priority??0,this.updateActiveXRRig()}getUserOffsetInRig(){var s;const t=(s=this.context.mainCamera)==null?void 0:s.position;if(!t||!this.rig)return G(0,0,0);const i=G(t);return i.x*=-1,i.z*=-1,i.applyQuaternion(vs(this.rig.gameObject.quaternion)),i}updateActiveXRRig(){const s=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 i=1;i<this._rigs.length;i++){const n=this._rigs[i];if(n.isActive){if(kr(n.gameObject)){this._rigs.splice(i,1),i--;continue}(!t||t.isActive===!1||n.priority!==void 0&&n.priority>t.priority)&&(t=n)}}if(s!==t){const i=this._rigs.indexOf(t);i>=0&&this._rigs.splice(i,1),this._rigs.unshift(t)}yt&&(s===t?console.log("Updated Active XR Rig:",t,"prev:",s):console.log("Updated Active XRRig:",t," (the same as before)"))}getHitTest(s){if(s)return this.getControllerHitTest(s);if(!this._viewerHitTestSource)return null;const t=this._viewerHitTestSource,i=this.frame.getHitTestResults(t);if(i.length>0){const n=i[0];return this.convertHitTestResult(n)}return null}getControllerHitTest(s){const t=s.getHitTestSource();if(!t)return null;const i=this.frame.getHitTestResultsForTransientInput(t);for(const n of i)if(n.inputSource===s.inputSource)for(const o of n.results)return this.convertHitTestResult(o);return null}convertHitTestResult(s){const t=this.context.renderer.xr.getReferenceSpace(),i=t&&s.getPose(t);if(i){const n=G(i.transform.position),o=vs(i.transform.orientation),r=this.context.mainCamera;if(r?.parent!==this._cameraRenderParent&&n.applyMatrix4(Ra),r!=null&&r.parent){n.applyMatrix4(r.parent.matrixWorld),o.multiply(Yi);const l=Oe(r.parent);l.premultiply(Yi),o.premultiply(l)}return{hit:s,position:n,quaternion:o}}return null}convertSpace(s){const t=G(s.position);t.applyMatrix4(Ra);const i=vs(s.orientation);return i.premultiply(Yi),{position:t,quaternion:i}}disconnectInputSource(s){const t=(i,n,o)=>{if(i.inputSource===s){yt&&console.log("Disconnecting controller",i.index),this.controllers.splice(o,1),this.invokeControllerEvent(i,this._controllerRemoved,"removed");const r={xr:this,controller:i,change:"removed"};for(const l of this._xr_scripts)l.onXRControllerRemoved&&l.onXRControllerRemoved(r);i.onDisconnected()}};for(let i=this.controllers.length-1;i>=0;i--){const n=this.controllers[i];t(n,this.controllers,i)}for(let i=this._newControllers.length-1;i>=0;i--){const n=this._newControllers[i];t(n,this._newControllers,i)}}end(){this._ended||this.session.end().catch(s=>console.warn(s))}onRenderDebug(){if(yt)for(const s of this.controllers)s.onRenderDebug();if((yt||zb)&&this.rig&&(fg++,fg>=20)){const s=this.rig.gameObject.worldPosition,t=this.rig.gameObject.worldForward;s.add(t.multiplyScalar(1.5));const i=this.rig.gameObject.worldUp;s.add(i.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()}`,yt||zb)for(const o of this.controllers)n+=`
154
- ${o.hand?"hand":"ctrl"} ${o.inputSource.handedness}[${o.index}] con:${o.connected} tr:${o.isTracking} hts:${o.hasHitTestSource?"yes":"no"}`;fg=0,q.DrawLabel(s,n,void 0,1/60*20)}}addScript(s){return this._xr_scripts.includes(s)?!1:(yt&&console.log("Register new XRScript",s),this._xr_scripts.push(s),typeof s.onUpdateXR=="function"&&this._xr_update_scripts.push(s),!0)}markInactive(s){if(!(this._inactive_scripts.indexOf(s)>=0)){this.removeScript(s,!1),this._inactive_scripts.push(s);for(const t of this.controllers)this.invokeCallback_ControllerRemoved(s,t);this.invokeCallback_LeaveXR(s)}}handleInactiveScripts(){if(this._inactive_scripts.length>0)for(let s=this._inactive_scripts.length-1;s>=0;s--){const t=this._inactive_scripts[s];if(t.activeAndEnabled){this._inactive_scripts.splice(s,1),this.addScript(t),this.invokeCallback_EnterXR(t);for(const i of this.controllers)this.invokeCallback_ControllerAdded(t,i)}}}removeScript(s,t=!0){yt&&console.log("Remove XRScript",s);const i=this._xr_scripts.indexOf(s);i>=0&&this._xr_scripts.splice(i,1);const n=this._xr_update_scripts.indexOf(s);if(n>=0&&this._xr_update_scripts.splice(n,1),t){const o=this._inactive_scripts.indexOf(s);o>=0&&this._inactive_scripts.splice(o,1)}}invokeCallback_EnterXR(s){s.onEnterXR&&s.onEnterXR({xr:this})}invokeCallback_ControllerAdded(s,t){s.onXRControllerAdded&&s.onXRControllerAdded({xr:this,controller:t,change:"added"})}invokeCallback_ControllerRemoved(s,t){s.onXRControllerRemoved&&s.onXRControllerRemoved({xr:this,controller:t,change:"removed"})}invokeCallback_LeaveXR(s){s.onLeaveXR&&!s.destroyed&&s.onLeaveXR({xr:this})}syncCameraCullingMask(){var s;const t=this.context.xrCamera,i=(s=this.context.mainCameraComponent)==null?void 0:s.cullingMask;if(t&&i!==void 0){for(const n of t.cameras)n.layers.mask=i;t.layers.mask=i}else if(t){for(const n of t.cameras)n.layers.enableAll();t.layers.enableAll()}}invokeControllerEvent(s,t,i){for(let n=t.length-1;n>=0;n--){const o=t[n];if(o)try{o({xr:this,controller:s,change:i})}catch(r){console.error(r)}}}applyCustomForward(){var s;if(this.context.mainCamera&&this._customforward){this._camera=this.context.mainCamera,this._camera.parent!==this._cameraRenderParent&&(this._previousCameraParent=this._camera.parent,(s=this._previousCameraParent)==null||s.add(this._cameraRenderParent)),this._cameraRenderParent.name="XR Camera Render Parent",this._cameraRenderParent.add(this._camera);let t=.02;if(this.rig){const i=Je(this.rig.gameObject);t*=i.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 s=this.context.renderer.xr.getReferenceSpace();if(!s){this._viewerPose=void 0;return}if(this._viewerPose=this.frame.getViewerPose(s),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 Ib),this._transition}fadeTransition(){return this._transition||(this._transition=new Ib),this._transition.fadeTransition()}updateFade(s){this._transition&&s instanceof we&&this._transition.update(s,this.context.time.deltaTime)}onUpdateFade_PostRender(){var s;(s=this._transition)==null||s.remove()}};let J=fo;a(J,"_sync",null),a(J,"_currentSessionRequestMode",null),a(J,"_currentSessionRequest"),a(J,"_activeSession"),a(J,"_sessionRequestStartListeners",[]),a(J,"_sessionRequestEndListeners",[]),a(J,"_xrStartListeners",[]),a(J,"_xrEndListeners",[]),a(J,"_controllerAddedListeners",[]),a(J,"_controllerRemovedListeners",[]),a(J,"onEnd",()=>{yt&&console.log("XR Session ended"),fo._activeSession=null});const vg=O("debugwebxr");class Nb{static tryFindAvatarObjects(t,i,n){if(n.head&&n.leftHand&&n.rightHand)return;const o=t.name.toLocaleLowerCase();!n.head&&o.includes("head")&&(vg&&console.log("FOUND AVATAR HEAD",t.name),n.head=new ae("",i,t)),o.includes("hand")&&(!n.leftHand&&o.includes("left")&&(vg&&console.log("FOUND AVATAR LEFT HAND",t.name),n.leftHand=new ae("",i,t)),!n.rightHand&&o.includes("right")&&(vg&&console.log("FOUND AVATAR RIGHT HAND",t.name),n.rightHand=new ae("",i,t)));for(let r=0;r<t.children.length;r++){if(n.head&&n.leftHand&&n.rightHand)return;const l=t.children[r];this.tryFindAvatarObjects(l,i,n)}}}const Nt=new x,Wb=new x,Vb=new V,t2=O("debuggizmos"),xs=8947848,bg=32,Ss=class{constructor(){}static isGizmo(s){return s[wg]!==void 0}static DrawLabel(s,t,i=.05,n=0,o,r,l){var c;if(!Ss.enabled)return null;o||(o=xs);const h=((c=J.active)==null?void 0:c.rigScale)??1,d=Ae.getTextLabel(n,t,i*h,o,r);return l instanceof I&&l.add(d),d.position.x=s.x,d.position.y=s.y,d.position.z=s.z,d}static DrawRay(s,t,i=xs,n=0,o=!0){if(!Ss.enabled)return;const r=Ae.getLine(n),l=r.geometry.getAttribute("position");l.setXYZ(0,s.x,s.y,s.z),Nt.set(t.x,t.y,t.z).multiplyScalar(999999999),l.setXYZ(1,s.x+Nt.x,s.y+Nt.y,s.z+Nt.z),l.needsUpdate=!0,r.material.color.set(i),r.material.depthTest=o,r.material.depthWrite=!1}static DrawDirection(s,t,i=xs,n=0,o=!0,r=1){if(!Ss.enabled)return;const l=Ae.getLine(n),c=l.geometry.getAttribute("position");c.setXYZ(0,s.x,s.y,s.z),t.w!==void 0?(Nt.set(0,0,-r),Vb.set(t.x,t.y,t.z,t.w),Nt.applyQuaternion(Vb)):(Nt.set(t.x,t.y,t.z),Nt.multiplyScalar(r)),c.setXYZ(1,s.x+Nt.x,s.y+Nt.y,s.z+Nt.z),c.needsUpdate=!0,l.material.color.set(i),l.material.depthTest=o,l.material.depthWrite=!1}static DrawLine(s,t,i=xs,n=0,o=!0){if(!Ss.enabled)return;const r=Ae.getLine(n),l=r.geometry.getAttribute("position");l.setXYZ(0,s.x,s.y,s.z),l.setXYZ(1,t.x,t.y,t.z),l.needsUpdate=!0,r.material.color.set(i),r.material.depthTest=o,r.material.depthWrite=!1,r.material.fog=!1}static DrawCircle(s,t,i,n=xs,o=0,r=!0){if(!Ss.enabled)return;const l=Ae.getCircle(o);l.position.set(s.x,s.y,s.z),l.scale.set(i,i,i),l.quaternion.setFromUnitVectors(this._up,Nt.set(t.x,t.y,t.z).normalize()),l.material.color.set(n),l.material.depthTest=r,l.material.depthWrite=!1,l.material.fog=!1}static DrawWireSphere(s,t,i=xs,n=0,o=!0){if(!Ss.enabled)return;const r=Ae.getSphere(t,n,!0);yr(r,s.x,s.y,s.z),r.material.color.set(i),r.material.depthTest=o,r.material.depthWrite=!1,r.material.fog=!1}static DrawSphere(s,t,i=xs,n=0,o=!0){if(!Ss.enabled)return;const r=Ae.getSphere(t,n,!1);yr(r,s.x,s.y,s.z),r.material.color.set(i),r.material.depthTest=o,r.material.depthWrite=!1}static DrawWireBox(s,t,i=xs,n=0,o=!0){if(!Ss.enabled)return;const r=Ae.getBox(n);r.position.set(s.x,s.y,s.z),r.scale.set(t.x,t.y,t.z),r.material.color.set(i),r.material.depthTest=o,r.material.wireframe=!0,r.material.depthWrite=!1,r.material.fog=!1}static DrawWireBox3(s,t=xs,i=0,n=!0){if(!Ss.enabled)return;const o=Ae.getBox(i);o.position.copy(s.getCenter(Nt)),o.scale.copy(s.getSize(Nt)),o.material.color.set(t),o.material.depthTest=n,o.material.wireframe=!0,o.material.depthWrite=!1,o.material.fog=!1}static DrawArrow(s,t,i=xs,n=0,o=!0,r=!1){if(!Ss.enabled)return;const l=Ae.getArrowHead(n);l.position.set(t.x,t.y,t.z),l.quaternion.setFromUnitVectors(this._up.set(0,1,0),Nt.set(t.x,t.y,t.z).sub(Wb.set(s.x,s.y,s.z)).normalize());const c=Nt.set(t.x,t.y,t.z).sub(Wb.set(s.x,s.y,s.z)).length()*.1;l.scale.set(c,c,c),l.material.color.set(i),l.material.depthTest=o,l.material.wireframe=r,this.DrawLine(s,t,i,n,o)}static DrawWireMesh(s){const t=Ae.getMesh(s.duration??0);"mesh"in s?(t.geometry=s.mesh.geometry,t.matrix.copy(s.mesh.matrixWorld)):(t.geometry=s.geometry,t.matrix.copy(s.matrix)),t.matrixAutoUpdate=!1,t.matrixWorldAutoUpdate=!1,t.material.color.set(s.color??xs),t.material.depthTest=s.depthTest??!0,t.material.wireframe=!0}static setVisible(s){for(const t of Ae.timedObjectsBuffer)t.visible=s}};let q=Ss;a(q,"enabled",!0),a(q,"_up",new x(0,1,0));const i2=new Gl(1,1,1);function _g(s=null){const t=new re(s??14540253),i=new fS(i2);return new Gy(i,new Xy({color:t}))}const wg=Symbol("GizmoCache");class Ae{static ensureFont(){let t=Te.FontLibrary.getFontFamily(this.familyName);if(!t){t=Te.FontLibrary.addFontFamily(this.familyName);const i=t.addVariant("normal","normal","https://uploads.needle.tools/include/font-msdf.json","https://uploads.needle.tools/include/font.png");i?.addEventListener("ready",()=>{Te.update()})}}static getTextLabel(t,i,n,o,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),t2&&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:n,color:o,lineHeight:1,backgroundColor:r??void 0,backgroundOpacity:c,textContent:i,borderRadius:.5*n,padding:.8*n,whiteSpace:"pre",offset:.05*n};if(l)l.set(h);else{l=new fv(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,t,this.textLabelCache),l}static getBox(t){let i=this.boxesCache.pop();if(!i){const n=new Gl(1,1,1);i=new K(n)}return this.registerTimedObject(ee.Current,i,t,this.boxesCache),i}static getLine(t){let i=this.linesCache.pop();if(!i){i=new Xl;let n=i.geometry.getAttribute("position");n||(n=new ft(new Float32Array(2*3),3),i.geometry.setAttribute("position",n))}return i.frustumCulled=!1,this.registerTimedObject(ee.Current,i,t,this.linesCache),i}static getCircle(t){let i=this.circlesCache.pop();if(!i){i=new Xl;let n=i.geometry.getAttribute("position");if(!n){n=new ft(new Float32Array(bg*3),3),i.geometry.setAttribute("position",n);const o=G(0,1,0),r=G(0,0,1),l=G(r);l.cross(o).normalize();const c=G(l),h=Math.PI*2/(bg-1);for(let d=0;d<bg+1;d++){const u=h*d;o.copy(c).multiplyScalar(Math.cos(u)*1),l.copy(r).multiplyScalar(Math.sin(u)*1);const p=o.add(l);n.setXYZ(d,p.x,p.y,p.z)}}}return i.frustumCulled=!1,this.registerTimedObject(ee.Current,i,t,this.circlesCache),i}static getSphere(t,i,n){let o=this.spheresCache.pop();return o||(o=new K(new hd(1,8,8))),o.scale.set(t,t,t),o.material.wireframe=n,this.registerTimedObject(ee.Current,o,i,this.spheresCache),o}static getArrowHead(t){let i=this.arrowHeadsCache.pop();return i||(i=new K(new gS(0,.5,1,8))),this.registerTimedObject(ee.Current,i,t,this.arrowHeadsCache),i}static getMesh(t){let i=this.mesh.pop();return i||(i=new K,i.material=new Re),this.registerTimedObject(ee.Current,i,t,this.mesh),i}static registerTimedObject(t,i,n,o){if(!t){console.error("No Needle Engine context available. Did you call a Gizmos function in global scope?");return}const r=this.contextBeforeRenderCallbacks.get(t),l=this.contextPostRenderCallbacks.get(t);if(r){if(t.pre_render_callbacks[t.pre_render_callbacks.length-1]!==r){const c=t.pre_render_callbacks.indexOf(r);c>=0&&t.pre_render_callbacks.splice(c,1),t.pre_render_callbacks.push(r)}}else{const c=()=>{this.onBeforeRender(t,this.timedObjectsBuffer)};this.contextBeforeRenderCallbacks.set(t,c),t.pre_render_callbacks.push(c)}if(l){if(t.post_render_callbacks[t.post_render_callbacks.length-1]!==l){const c=t.post_render_callbacks.indexOf(l);c>=0&&t.post_render_callbacks.splice(c,1),t.post_render_callbacks.push(l)}}else{const c=()=>{this.onPostRender(t,this.timedObjectsBuffer,this.timesBuffer)};this.contextPostRenderCallbacks.set(t,c),t.post_render_callbacks.push(c)}i.traverse(c=>{c.layers.disableAll(),c.layers.enable(2)}),i.renderOrder=999999,i[wg]=o,i.castShadow=!1,i.receiveShadow=!1,i.isGizmo=!0,this.timedObjectsBuffer.push(i),this.timesBuffer.push(ee.Current.time.realtimeSinceStartup+n),t.scene.add(i)}static onBeforeRender(t,i){this.tmuiNeedsUpdate&&(this.tmuiNeedsUpdate=!1,Te.update());for(let n=0;n<i.length;n++){const o=i[n];if(t.mainCamera&&o instanceof Te.MeshUIBaseElement){if(kr(o))continue;const r=t.isInVR,l=!1,c=!r;ic(o,t.mainCamera,l,c)}}}static onPostRender(t,i,n){const o=t.time.realtimeSinceStartup;for(let r=i.length-1;r>=0;r--){const l=i[r];o>=n[r]-1e-6&&(i.splice(r,1),n.splice(r,1),l.removeFromParent(),kr(l)!=!0&&l[wg].push(l))}}}a(Ae,"familyName","needle-gizmos"),a(Ae,"linesCache",[]),a(Ae,"circlesCache",[]),a(Ae,"spheresCache",[]),a(Ae,"boxesCache",[]),a(Ae,"arrowHeadsCache",[]),a(Ae,"mesh",[]),a(Ae,"textLabelCache",[]),a(Ae,"timedObjectsBuffer",new Array),a(Ae,"timesBuffer",new Array),a(Ae,"contextPostRenderCallbacks",new Map),a(Ae,"contextBeforeRenderCallbacks",new Map),a(Ae,"tmuiNeedsUpdate",!1);const ki=O("debugphysics"),Hb=new no;class Ws{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(t,i){this.screenPoint===void 0&&(this.screenPoint=new oe),this.screenPoint.x=t/window.innerWidth*2-1,this.screenPoint.y=-(i/window.innerHeight)*2+1}setLayer(t){Hb.set(t),this.layerMask=Hb}setMask(t){this.layerMask||(this.layerMask=new no);const i=this.layerMask;i?i.mask=t:this.layerMask=t}}a(Ws,"AllLayers",4294967295);class xg{constructor(t,i,n){a(this,"distance"),a(this,"point"),a(this,"object"),this.object=t,this.distance=i,this.point=n}}const Sg=class{constructor(s){a(this,"context"),a(this,"engine"),a(this,"raycaster",new ud),a(this,"defaultRaycastOptions",new Ws),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 no),a(this,"sphere",new dd),a(this,"tempBoundingBox",new _i),this.context=s}static get raycasting(){return this._raycasting>0}raycastPhysicsFast(s,t=void 0,i=1/0,n=!0){var o;return((o=this.context.physics.engine)==null?void 0:o.raycast(s,t,{maxDistance:i,solid:n}))??null}raycastPhysicsFastAndGetNormal(s,t=void 0,i=1/0,n=!0){var o;return((o=this.context.physics.engine)==null?void 0:o.raycastAndGetNormal(s,t,{maxDistance:i,solid:n}))??null}sphereOverlapPhysics(s,t){var i;return((i=this.context.physics.engine)==null?void 0:i.sphereOverlap(s,t))??null}sphereOverlap(s,t,i=!0,n=!1,o=null){if(this.sphereResults.length=0,!this.context.scene)return this.sphereResults;const r=this.sphereMask;r.enableAll(),r.disable(2);for(const l of this.context.scene.children)this.intersectSphere(l,s,t,r,this.sphereResults,i,n,o);return this.sphereResults.sort((l,c)=>l.distance-c.distance)}raycastFromRay(s,t=null){const i=t??this.defaultRaycastOptions;i.ray=s;const n=this.raycast(i);return i===this.defaultRaycastOptions&&(i.ray=void 0),n}raycast(s=null){ki&&performance.mark("raycast.start"),s||(s=this.defaultRaycastOptions);const t=s.screenPoint??this.context.input.mousePositionRC,i=s.raycaster??this.raycaster;if(i.near=s.minDistance??0,i.far=s.maxDistance??1/0,i.params=this.defaultThresholds,s.lineThreshold===void 0&&(s.lineThreshold=-1),i.params.Line={threshold:s.lineThreshold},s.ray)i.ray.copy(s.ray);else{const l=s.cam??this.context.mainCamera;if(!l)return ki&&console.error("Can not perform raycast - no main camera found"),this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),this.defaultRaycastOptions.results??[];const c=this.context.xrCamera;this.context.isInXR&&c instanceof yS&&c.cameras.length>0?i.setFromCamera(t,c.cameras[0]):i.setFromCamera(t,l)}let n=s.targets;n||(n=this.targetBuffer,n.length=1,n[0]=this.context.scene);let o=s.results;this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),o||(this.defaultRaycastOptions.results||(this.defaultRaycastOptions.results=new Array),o=this.defaultRaycastOptions.results),s.layerMask!==void 0?s.layerMask instanceof no?i.layers.mask=s.layerMask.mask:i.layers.mask=s.layerMask:(i.layers.enableAll(),i.layers.disable(2)),ki&&console.time("raycast"),o.length=0,Sg._raycasting++,this.intersect(this.raycaster,n,o,s),o.sort((l,c)=>l.distance-c.distance);const r=s.ignore;return r!==void 0&&r.length>0&&(o=o.filter(l=>!r.includes(l.object))),Sg._raycasting--,ki&&(console.timeEnd("raycast"),console.warn("#"+this.context.time.frame+", hits:",o!=null&&o.length?[...o]:"nothing"),performance.mark("raycast.end"),performance.measure("raycast","raycast.start","raycast.end")),o}intersect(s,t,i,n){var o,r,l;for(const c of t){if(!c||c.visible===!1||q.isGizmo(c)||n.lineThreshold!==void 0&&n.lineThreshold<0&&c instanceof Xl)continue;let h=!0;const d=c,u=d.geometry;if(n.testObject){const p=(o=n.testObject)==null?void 0:o.call(n,c);if(p===!1)continue;p==="continue in children"&&(h=!1)}if(h&&(u&&$b(u)||(h=!1)),h){const p=ov(c);p&&(d.geometry=p);const g=i.length;let y=!0;if(n.precise===!1&&(y=!1),y||(y=((l=(r=u.getAttribute("position"))==null?void 0:r.array)==null?void 0:l.length)<64),d instanceof Sa&&(y=!1),!y&&n2(d,s,i)||(n.useAcceleratedRaycast!==!1?Ud.runMeshBVHRaycast(s,d,i,this.context):s.intersectObject(d,!1,i)),ki&&i.length!=g){const f=i[i.length-1],v=p?8969557:7798784;q.DrawWireSphere(f.point,.1,v,1,!1),q.DrawWireMesh({mesh:c,depthTest:!1,duration:.2,color:v})}d.geometry=u}n.recursive!==!1&&this.intersect(s,c.children,i,n)}return i}intersectSphere(s,t,i,n,o,r,l,c){let h=s&&s.isMesh&&s.layers.test(n)&&!q.isGizmo(s);h&&(h=s.visible),h&&(h=!(s instanceof Xl)),h&&(h=!(s instanceof Sa));const d=s,u=d.geometry;if(h&&c){const p=c(s);if(p===!1)return;p==="continue in children"&&(h=!1)}if(u&&$b(u)||(h=!1),h){if(l){const p=this.sphere;p.center.copy(t),p.radius=i;const g=o.length;if(Ud.runMeshBVHRaycast(this.sphere,d,o,this.context),g!=o.length&&!r)return}else if(u.boundingBox||u.computeBoundingBox(),u.boundingBox){d.matrixWorldNeedsUpdate&&d.updateWorldMatrix(!1,!1);const p=this.tempBoundingBox.copy(u.boundingBox).applyMatrix4(d.matrixWorld),g=this.sphere;if(g.center.copy(t),g.radius=i,g.intersectsBox(p)){const y=te(s),f=y.distanceTo(g.center),v=new xg(s,f,y);if(o.push(v),!r)return}}}if(s.children)for(const p of s.children){const g=o.length;if(this.intersectSphere(p,t,i,n,o,r,l,c),g!=o.length&&!r)return}}};let Fd=Sg;a(Fd,"_raycasting",0);function $b(s){return!(s.index&&s.index.array.length<3)}const xr=new dd,zd=new pr,s2=new Hy;function n2(s,t,i){const n=s._computeIntersections;if(!n)return!1;let o=s["_computeIntersections:Needle"];return o||(o=s["_computeIntersections:Needle"]=function(r,l,c){const h=this,d=h.geometry.boundingSphere;if(d){if(h instanceof Sa){zd.setFromNormalAndCoplanarPoint(G(0,1,0),G(0,-h.position.y,0)),zd.applyMatrix4(h.matrixWorld,s2);const p=r.ray.intersectPlane(zd,G());if(p){xr.copy(d),xr.applyMatrix4(h.matrixWorld);const g=G(p).sub(r.ray.origin).length(),y=xr.radius*.5;g<y&&l.push({distance:g,point:p,object:h,normal:zd.normal.clone()})}return}xr.copy(d),xr.applyMatrix4(h.matrixWorld);const u=r.ray.intersectSphere(xr,G());if(u){const p=G(u).sub(r.ray.origin),g=p.length();if(g>xr.radius){const y=p.clone().normalize();l.push({distance:g,point:u,object:h,normal:y})}}}}),s._computeIntersections=o,t.intersectObject(s,!1,i),s._computeIntersections=n,!0}var Ud;(s=>{function t(w,_,C,R){var M,T,j;if(!_.geometry||!_.geometry.hasAttribute("position"))return!1;const D=_.geometry;if(_!=null&&_.isSkinnedMesh){const U=_,B=U.bvhNeedsUpdate;if(!U.staticGenerator)c(),r&&(U.staticGenerator=new r(_),U.staticGenerator.applyWorldTransforms=!1,U.staticGeometry=U.staticGenerator.generate(),D.boundsTree=l?.call(U.staticGeometry),U.staticGeometryLastUpdate=performance.now()+Math.random()*200,U.autoUpdateMeshBVH===void 0&&(U.autoUpdateMeshBVH=!1));else if(D.boundsTree&&(U.autoUpdateMeshBVH===!0||B===!0)){const Y=performance.now(),$=Y-U.staticGeometryLastUpdate;(B||$>100)&&(U.bvhNeedsUpdate=!1,U.staticGeometryLastUpdate=Y,(M=U.staticGenerator)==null||M.generate(U.staticGeometry),D.boundsTree.refit())}}else if(!D.boundsTree){d||b();let U=!0;if((R.xr||D[y]===!1||(T=D.getAttribute("position"))!=null&&T.isInterleavedBufferAttribute||D.index&&(j=D.index)!=null&&j.isInterleavedBufferAttribute)&&(U=!1),U&&p){if(D[g]===void 0){let B=null;if(v.length>0){const Y=v.shift();Y&&!Y.running&&(B=Y)}if(!B&&f.length<3&&(B=new p,f.push(B)),B!=null&&!B.running){const Y=_.name;ki&&console.log("<<<< worker start",Y,B),D[g]="queued",performance.mark("bvh.create.start");const $=D.clone();try{B.generate($).then(E=>{D[g]="done",D.boundsTree=E}).catch(E=>{D[g]="failed - "+E?.message,D[y]=!1,ki&&console.error("Failed to generate mesh bvh on worker",E)}).finally(()=>{ki&&console.log(">>>>> worker done",Y,{hasBoundsTre:D.boundsTree!=null}),v.push(B),$.dispose(),performance.mark("bvh.create.end"),performance.measure("bvh.create (worker)","bvh.create.start","bvh.create.end")})}catch(E){console.error("Failed to generate mesh bvh on worker",E)}}else ki&&console.warn("No worker available")}}else(!u||!U)&&(c(),o&&(performance.mark("bvh.create.start"),D.boundsTree=new o(D),performance.mark("bvh.create.end"),performance.measure("bvh.create","bvh.create.start","bvh.create.end")))}if(w instanceof ud){const U=w,B=_.raycast;D.boundsTree?(c(),n&&(_.acceleratedRaycast||(_.acceleratedRaycast=n.bind(_),ki&&console.debug(`Physics: bind acceleratedRaycast fn to "${_.name}"`)),_.raycast=_.acceleratedRaycast)):ki&&console.warn("No bounds tree found for mesh",_.name,{workerTask:D[g],hasAcceleratedRaycast:n!=null});const Y=U.firstHitOnly;return U.firstHitOnly=!1,U.intersectObject(_,!1,C),U.firstHitOnly=Y,_.raycast=B,!0}else if(w instanceof dd){const U=D.boundsTree;if(U){const B=w;if(h.copy(_.matrixWorld).invert(),B.applyMatrix4(h),U.intersectsSphere(B)){const Y=te(_),$=Y.distanceTo(B.center),E=new xg(_,$,Y);C.push(E)}}return!0}return!1}s.runMeshBVHRaycast=t;let i=!1,n=null,o=null,r=null,l=null;function c(){i||(i=!0,import("./vendor.light.min.js").then(w=>w.k).then(w=>{n=w.acceleratedRaycast,o=w.MeshBVH,r=w.StaticGeometryGenerator,l=w.computeBoundsTree}).catch(w=>{(ki||F())&&console.error("Failed to load BVH library...",w.message)}))}const h=new ne;let d=!1,u=!1,p=null;const g=Symbol("Needle:MeshBVH-Worker"),y=Symbol("Needle:MeshBVH-CanUseWorker"),f=[],v=[];function b(){d=!0,u=!0,Promise.resolve().then(()=>Xj).then(w=>{p=w.GenerateMeshBVHWorker}).catch(w=>{(ki||F())&&console.warn("Failed to setup mesh bvh worker")}).finally(()=>{u=!1})}})(Ud||(Ud={}));const qb=Symbol("gltf-loader-internal-usage-tracker"),o2=O("debugusers"),Nd=class{constructor(s){a(this,"parser"),a(this,"_getDependency"),a(this,"_loadingId"),a(this,"_loadedObjects",new Set),this.parser=s,this._getDependency=this.parser.getDependency,this._loadingId=Date.now().toString()}get name(){return"NEEDLE_internal_usage_tracker"}static isLoading(s){return Nd._loadingProcesses>0}beforeRoot(){Nd._loadingProcesses++;const s=this,t=this._getDependency;return this.parser.getDependency=function(i,n){const o=t.call(this,i,n);return o.then(r=>(r&&(s._loadedObjects.add(r),r[qb]=s._loadingId),r)),o},null}afterRoot(s){Nd._loadingProcesses--,this.parser.getDependency=this._getDependency;for(const t of this._loadedObjects)delete t[qb],t instanceof I&&(t.parent||t instanceof K&&setTimeout(()=>{o2&&console.warn("> GLTF LOADER: Mesh not used in scene!",t),t.material=null,t.geometry=null},1e3));return null}};let Cg=Nd;a(Cg,"_loadingProcesses",0);class Gb{constructor(){window.addEventListener("unhandledrejection",t=>{var i;if(t.defaultPrevented)return;const n=(i=t?.reason)==null?void 0:i.path;if(n){const o=n[0];o&&o.tagName==="IMG"&&(console.warn(`Could not load image:
155
- `+o.src),t.preventDefault())}})}}const Wd=O("trackresources");function Xb(){return Wd==="dispose"}let Sr=!0;Wd===0&&(Sr=!1);function r2(s){Sr=s}function Qb(){return Sr}const Yb=Symbol("disposable");function Og(s,t){s&&(s[Yb]=t,Cr&&console.warn("Set disposable",t,s))}const Kb=Symbol("disposed");function a2(s){return s[Kb]===!0}function Ee(s){var t;if(s){if(s[Yb]===!1){Cr&&console.warn("Object is marked as not disposable",s);return}if(s[Kb]=!0,s instanceof qi)Ee(s.environment),Ee(s.background),Ee(s.customDepthMaterial),Ee(s.customDistanceMaterial);else if(s instanceof _n)Ee(s.geometry),Ee(s.material),Ee(s.skeleton),Ee(s.bindMatrix),Ee(s.bindMatrixInverse),Ee(s.customDepthMaterial),Ee(s.customDistanceMaterial),s.geometry=null,s.material=null,s.visible=!1;else if(s instanceof K)Ee(s.geometry),Ee(s.material),Ee(s.customDepthMaterial),Ee(s.customDistanceMaterial),s.geometry=null,s.material=null,s.visible=!1;else if(s instanceof bn){Ia(s);for(const i of Object.keys(s.attributes)){const n=s.attributes[i];Ee(n)}}else if(s instanceof ft||s instanceof Qy)Cr&&console.warn("BufferAttribute dispose not supported",s.count);else if(s instanceof Array)for(const i of s)i instanceof ke&&Ee(i);else if(s instanceof ke){Ia(s);for(const n of Object.keys(s)){const o=s[n];o instanceof Le&&(Ee(o),s[n]=null)}const i=s.uniforms;if(i)for(const n of Object.keys(i)){const o=i[n];o instanceof Le?(Ee(o),i[n]=null):o instanceof so&&(Ee(o.value),o.value=null)}}else s instanceof Le?(Ia(s),Ia(s.source),((t=s.source)==null?void 0:t.data)instanceof ImageBitmap&&Ia(s.source.data)):s instanceof vS?(Ia(s.boneTexture),s.boneTexture=null):s instanceof bS||!(s instanceof I)&&Cr&&console.warn("Unknown object type",s)}}function Ia(s){s&&((Cr||Xb()||Wd)&&console.warn("\u{1F9E8} FREE",s),s instanceof ImageBitmap?s.close():s instanceof _S?s.data=null:s.dispose())}function Zb(s){(s instanceof K||s instanceof _n)&&(s.material=null,s.geometry=null)}const l2=new Set;function Pg(s,t,i=null,n){if(n||(n=l2,n.clear()),!s)return n;const o=s[fc];if(o)for(const r of o)n.has(r)||i?.call(null,r)!==!1&&(n.add(r),t&&Pg(r,!0,i,n));return n}function c2(s){return s[yc]}const Cr=O("debugresourceusers")||O("debugmemory"),fc=Symbol("needle-resource-users"),yc=Symbol("needle-resource-users-count");function Xt(s,t){Td(s,t,function(i,n){Sr&&!Fd.raycasting&&(Vd(fc,this,i,!1),Vd(fc,this,n,!0))})}Sr&&(Xt(K.prototype,"material"),Xt(K.prototype,"geometry"),Xt(ke.prototype,"map"),Xt(ke.prototype,"bumpMap"),Xt(ke.prototype,"alphaMap"),Xt(ke.prototype,"normalMap"),Xt(ke.prototype,"displacementMap"),Xt(ke.prototype,"roughnessMap"),Xt(ke.prototype,"metalnessMap"),Xt(ke.prototype,"emissiveMap"),Xt(ke.prototype,"specularMap"),Xt(ke.prototype,"envMap"),Xt(ke.prototype,"lightMap"),Xt(ke.prototype,"aoMap"),Xt(ke.prototype,"gradientMap"));function h2(s){if(Sr===!1)return;const t=s[fc];if(t)for(const i of t)Vd(fc,i,s,!1)}Sr&&Td(ke.prototype,"dispose",function(){h2(this)});let kg=0;function Vd(s,t,i,n){if(kg>0)return;if(Array.isArray(i)){for(const r of i)Vd(s,t,r,n);return}if(!i)return;let o=i[s];if(o||(o=new Set),n){if(t&&!o.has(t)){o.add(t);let r=i[yc]||0;r+=1,i[yc]=r,Cr&&console.warn(`\u{1F7E2} Added user of "${i.type}"`,t,i,r,"users:",o)}}else if(t&&o.has(t)){o.delete(t);let r=i[yc]||0;r>0&&(r-=1,i[yc]=r),Cr&&console.warn(`\u{1F534} Removed user of "${i.type}"`,t,i,r,"users:",o),r<=0&&(Cg.isLoading(i)||(Wd&&console.warn(`\u{1F534} Removed all user of "${i.type}"`,i),Xb()&&Ee(i)))}i[s]=o}try{Td(ur.prototype,"render",function(){kg++},function(){kg--})}catch(s){console.warn("Could not wrap WebGLRenderer.render",s)}const Jb=O("debugcomponentevents");class vc{static addComponentLifecylceEventListener(t,i){this.eventListeners.has(t)&&this.eventListeners.set(t,[]);let n=this.eventListeners.get(t);n||(n=[]),n.push(i),this.eventListeners.set(t,n),Jb&&console.log("Added event listener for "+t,this.eventListeners)}static removeComponentLifecylceEventListener(t,i){const n=this.eventListeners.get(t);if(!n)return;const o=n.indexOf(i);o<0||n.splice(o,1)}static dispatchComponentLifecycleEvent(t,i){const n=this.eventListeners.get(t);if(Jb&&console.log("Dispatching event "+t,n),!!n)for(const o of n)o(i)}}a(vc,"eventListeners",new Map);const bc=Symbol("NEEDLE_NEED_UPDATE_INSTANCE"),e_=Symbol("isUsingInstancing"),t_=Symbol("instancingRenderer"),_c=Symbol("instancingAutoUpdateBounds");class cs{static isUsingInstancing(t){return t[e_]===!0}static getRenderer(t){return t[t_]||null}setAutoUpdateBounds(t,i){const n=cs.getRenderer(t);n&&(n[_c]=i)}static markDirty(t,i=!0){if(t&&(this.isUsingInstancing(t)&&(t[bc]=!0,t.matrixWorldNeedsUpdate=!0),i))for(const n of t.children)cs.markDirty(n,!0)}}function ja(s,t){try{t?s(t):s()}catch(i){return console.error(i),!1}return!0}const Mg=O("debugnewscripts"),d2=O("debughierarchy"),Fe=[];function u2(){return Fe.length>0}function Hd(s){if(!(s.new_scripts.length<=0)){if(Mg&&console.log("Register new components",s.new_scripts.length,[...s.new_scripts],s.alias?"element: "+s.alias:s.hash,s),s.new_scripts_pre_setup_callbacks.length>0){for(const t of s.new_scripts_pre_setup_callbacks)t&&t();s.new_scripts_pre_setup_callbacks.length=0}Fe.length=0,s.new_scripts.length>0&&Fe.push(...s.new_scripts),s.new_scripts.length=0;for(let t=0;t<Fe.length;t++)try{const i=Fe[t];if(i.isComponent!==!0){(F()||Mg)&&console.error(`Registered script is not a Needle Engine component.
153
+ ${h.href}`)}this.onSendQueued(ws.OnRoomJoin);break;case"left-room":t.room===this.currentRoomName&&(this._isInRoom=!1,this._currentRoomName=null,this._currentInRoom.length=0);break;case"user-joined-room":if(t.data){const c=t.data;this._currentInRoom.push(c.userId),di&&console.log(c.userId+" joined","now in room:",this._currentInRoom)}break;case"user-left-room":if(t.data){const c=t.data,h=this._currentInRoom.indexOf(c.userId);h>=0&&(di&&console.log(c.userId+" left","now in room:",this._currentInRoom),this._currentInRoom.splice(h,1)),c.userId===this.connectionId&&console.log("you left the room")}break;case"all-room-state-deleted":di&&console.log("RECEIVED all-room-state-deleted"),this._state={};break;case"ping":case"pong":const l=(i=t.data)==null?void 0:i.time;l&&(this._currentDelay=this.context.time.time-l),di&&console.log("Current latency: "+this._currentDelay.toFixed(4)+" sec","Clients in room: "+((n=this._currentInRoom)==null?void 0:n.length));break}const o=t.data;o&&(this._state[o.guid]=o);let r=this._listeners[t.key];if(r){r=[...r];for(const l of r)try{l(t.data)}catch(c){console.error('Error invoking callback for "'+t.key+'"',c)}}}toMessage(t,i){return{key:t,data:i}}sendWithWebsocket(t,i,n=ws.OnRoomJoin){if(!this._ws){const r=this._waitingForSocket[n]||[];r.push(()=>this.sendWithWebsocket(t,i,n)),this._waitingForSocket[n]=r;return}const o=JSON.stringify(this.toMessage(t,i));di&&console.log(">>",t),this._ws.send(o)}onSendQueued(t){const i=this._waitingForSocket[t];if(i){for(const n of i)n();i.length=0}}}const mc=O("debugwebxr");class ug{constructor(t,i){a(this,"controllerStates",[]),a(this,"userId"),a(this,"context"),a(this,"userStateEvtName"),a(this,"onReceivedControllerState",n=>{mc&&console.log(`XRSync: Received change for ${this.userId}: ${n.type} ${n.handedness}; tracked=${n.isTracking}`);let o=!1;for(let r=0;r<this.controllerStates.length;r++)if(this.controllerStates[r].index===n.index){this.controllerStates[r]=n,o=!0;break}o||this.controllerStates.push(n)}),this.userId=t,this.context=i,this.userStateEvtName="xr-sync-user-state-"+t,this.context.connection.beginListen(this.userStateEvtName,this.onReceivedControllerState)}dispose(){this.context.connection.stopListen(this.userStateEvtName,this.onReceivedControllerState)}update(t){if(this.context.connection.isConnected!=!1){for(let i=this.controllerStates.length-1;i>=0;i--){const n=this.controllerStates[i];let o=!1;for(let r=0;r<t.controllers.length;r++)t.controllers[r].index===n.index&&(o=!0);o||(mc&&console.log(`XRSync: ${n.type} ${n.handedness} removed`,n.index),this.controllerStates.splice(i,1),this.sendControllerRemoved(n))}for(const i of t.controllers)this.updateControllerStates(i)}}onExitXR(t){for(const i of this.controllerStates)this.sendControllerRemoved(i);this.controllerStates.length=0}sendControllerRemoved(t){t.isTracking=!1,t.guid="",this.context.connection.send(this.userStateEvtName,t),this.context.connection.sendDeleteRemoteState(t.guid)}updateControllerStates(t){const i=this.controllerStates.find(n=>n.index===t.index);if(i){let n=!1;n||(n=i.isTracking!=t.isTracking),n&&(i.isTracking=t.isTracking,this.context.connection.send(this.userStateEvtName,i))}else{const n={guid:this.userId+"-"+t.index,isTracking:t.isTracking,handedness:t.side,index:t.index,type:t.hand?"hand":"controller"};this.controllerStates.push(n),this.context.connection.send(this.userStateEvtName,n),mc&&console.log(`XRSync: ${n.type} ${n.handedness} added`,n.index)}}}class Ab{constructor(t){a(this,"context"),a(this,"onJoinedRoom",()=>{if(this.context.connection.connectionId){this._states.has(this.context.connection.connectionId)||(mc&&console.log("XRSync: Local user joined room",this.context.connection.connectionId),this._states.set(this.context.connection.connectionId,new ug(this.context.connection.connectionId,this.context)));for(const i of this.context.connection.usersInRoom())this._states.has(i)||this._states.set(i,new ug(i,this.context))}}),a(this,"onLeftRoom",()=>{if(this.context.connection.connectionId&&!this._states.has(this.context.connection.connectionId)){const i=this._states.get(this.context.connection.connectionId);i?.dispose(),this._states.delete(this.context.connection.connectionId)}}),a(this,"onOtherUserJoinedRoom",i=>{const n=i.userId;this._states.has(n)||(mc&&console.log("XRSync: Remote user joined room",n),this._states.set(n,new ug(n,this.context)))}),a(this,"onOtherUserLeftRoom",i=>{const n=i.userId;if(!this._states.has(n)){const o=this._states.get(n);o?.dispose(),this._states.delete(n)}}),a(this,"_states",new Map),this.context=t,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(t){return t?this._states.has(t):!1}isTracking(t,i){if(!t)return;const n=this._states.get(t);if(!n)return;const o=n.controllerStates.find(r=>r.handedness===i);return o?.isTracking||!1}getDeviceType(t,i){if(!t)return;const n=this._states.get(t);if(!n)return;const o=n.controllerStates.find(r=>r.handedness===i);return o?.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(t){if(this.context.connection.isConnected&&this.context.connection.connectionId){const i=this._states.get(this.context.connection.connectionId);i?.update(t)}}onExitXR(t){if(this.context.connection.isConnected&&this.context.connection.connectionId){const i=this._states.get(this.context.connection.connectionId);i?.onExitXR(t)}}}class Ib{constructor(){a(this,"_fadeToColorQuad"),a(this,"_fadeToColorMaterial"),a(this,"_requestedFadeValue",0),a(this,"_transitionPromise",null),a(this,"_transitionResolve",null),this._fadeToColorMaterial=new Re({color:0,transparent:!0,depthTest:!1,fog:!1,side:xi}),this._fadeToColorQuad=new K(new Fs(10,10),this._fadeToColorMaterial)}dispose(){this._fadeToColorQuad.geometry.dispose(),this._fadeToColorMaterial.dispose()}update(t,i){const n=this._fadeToColorQuad,o=this._fadeToColorMaterial;n.parent!==t&&o.opacity>0?t.add(n):o.opacity===0&&n.removeFromParent(),n.layers.set(2),n.material=this._fadeToColorMaterial,n.position.z=-1,n.renderOrder=1/0;const r=this._requestedFadeValue;o.opacity=W.lerp(o.opacity,r,i/.03),Math.abs(o.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 t=new Promise(i=>{this._transitionResolve=i});return this._transitionPromise=t,t}}var wr=(s=>(s[s.Quad=0]="Quad",s[s.Cube=1]="Cube",s[s.Sphere=2]="Sphere",s[s.RoundedCube=10]="RoundedCube",s))(wr||{}),Dd,pg;class go{static createText(t,i){let n=null;const o=i?.font||XP(i?.familyFamily||null);o instanceof TC?n=va(this,Dd,pg).call(this,t,o,i):n==null&&(n=new bn);const r=i?.color||16777215,l=new K(n,i?.material??new li({color:r}));return this.applyDefaultObjectOptions(l,i),o instanceof Promise?o.then(c=>{l.geometry=va(this,Dd,pg).call(this,t,c,i),i!=null&&i.onGeometry&&i.onGeometry(l)}):i!=null&&i.onGeometry&&i.onGeometry(l),l}static createOccluder(t){const i=new Re({colorWrite:!1,depthWrite:!0,side:xi});return this.createPrimitive(t,{material:i})}static createPrimitive(t,i){let n;const o=i?.color||16777215;switch(t){case"Quad":case 0:{const r=new Fs(1,1,1,1),l=i?.material??new li({color:o});i!=null&&i.texture&&"map"in l&&(l.map=i.texture),n=new K(r,l),n.name="Quad"}break;case"Cube":case 1:{const r=new Gl(1,1,1),l=i?.material??new li({color:o});i!=null&&i.texture&&"map"in l&&(l.map=i.texture),n=new K(r,l),n.name="Cube"}break;case 10:case"RoundedCube":{const r=GP(1,1,1,.1,2),l=i?.material??new li({color:o});i!=null&&i.texture&&"map"in l&&(l.map=i.texture),n=new K(r,l),n.name="RoundedCube"}break;case"Sphere":case 2:{const r=new hd(.5,16,16),l=i?.material??new li({color:o});i!=null&&i.texture&&"map"in l&&(l.map=i.texture),n=new K(r,l),n.name="Sphere"}break;case"ShaderBall":n=new ro,n.name="ShaderBall",QP(n,i);break}return this.applyDefaultObjectOptions(n,i),n}static createSprite(t){const i=new dS({color:16777215});t!=null&&t.texture&&"map"in i&&(i.map=t.texture);const n=new uS(i);return this.applyDefaultObjectOptions(n,t),n}static applyDefaultObjectOptions(t,i){t.receiveShadow=!0,t.castShadow=!0,i!=null&&i.name&&(t.name=i.name),i!=null&&i.position&&(Array.isArray(i.position)?t.position.set(i.position[0],i.position[1],i.position[2]):t.position.set(i.position.x,i.position.y,i.position.z)),i!=null&&i.rotation&&(Array.isArray(i.rotation)?t.rotation.set(i.rotation[0],i.rotation[1],i.rotation[2]):t.rotation.set(i.rotation.x,i.rotation.y,i.rotation.z)),i!=null&&i.scale&&(typeof i.scale=="number"?t.scale.set(i.scale,i.scale,i.scale):t.scale.set(i.scale.x,i.scale.y,i.scale.z)),i?.receiveShadow!=null&&(t.receiveShadow=i.receiveShadow),i?.castShadow!=null&&(t.castShadow=i.castShadow),i!=null&&i.parent&&i.parent.add(t)}}Dd=new WeakSet,pg=function(s,t,i){const n=i?.depth||.1;return new EC(s,{font:t,size:1,depth:n,height:n,bevelEnabled:i?.bevel||!1,bevelThickness:.01,bevelOffset:.01,bevelSize:.01})},$i(go,Dd);function GP(s,t,i,n,o){const r=new pS,l=1e-5,c=n-l;r.absarc(l,l,l,-Math.PI/2,-Math.PI,!0),r.absarc(l,t-c*2,l,Math.PI,Math.PI/2,!0),r.absarc(s-c*2,t-c*2,l,Math.PI/2,0,!0),r.absarc(s-c*2,l,l,0,-Math.PI/2,!0);const h=new mS(r,{bevelEnabled:!0,bevelSegments:o*2,steps:1,bevelSize:c,bevelThickness:n,curveSegments:o});return h.scale(1,1,1-n),h.center(),h.computeVertexNormals(),h}const Bd=new Map;function XP(s){let t="";switch(s){default:case"OpenSans":t="https://cdn.needle.tools/static/fonts/facetype/Open Sans_Regular_ascii.json";break;case"Helvetiker":t="https://raw.githubusercontent.com/mrdoob/three.js/master/examples/fonts/helvetiker_regular.typeface.json";break}if(Bd.has(t)){const o=Bd.get(t);if(o)return o}const i=new AC,n=new Promise((o,r)=>{i.load(t,l=>{Bd.set(t,l),o(l)},void 0,r)});return Bd.set(t,n),n}let mg=!1,gg=null;function QP(s,t){if(gg===null){const i="https://cdn.needle.tools/static/models/shaderball.glb",n=new gr,o=wm(null);n.setDRACOLoader(o.dracoLoader),n.setKTX2Loader(o.ktx2Loader),mg=!0,gg=n.loadAsync(i).then(r=>{const l=r.scene;return l.position.y-=.5,l}).catch(r=>(console.warn("Failed to load shaderball mesh: "+r.message),Lb())).finally(()=>{mg=!1})}if(mg){const i=Lb();i.name="ShaderBall-Placeholder";const n=i.children[0];n?.type==="Mesh"&&jb(n,t),s.add(i)}gg.then(i=>{s.children.forEach(r=>{r.name==="ShaderBall-Placeholder"&&s.remove(r)});const n=i.clone(),o=n.children[0];o?.type==="Mesh"&&jb(o,t),s.add(n)})}function jb(s,t){var i;if(t?.color||t?.material||t?.texture){const n=t?.material??((i=s.material)==null?void 0:i.clone())??new li;t.color&&"color"in n&&n.color instanceof re&&n.color.set(t.color),t!=null&&t.texture&&"map"in n&&(n.map=t.texture),s.material=n}}function Lb(){return new ro().add(go.createPrimitive("Sphere",{material:new Re({transparent:!0,opacity:.1})}))}const Db=class{constructor(s,t,i){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,o)=>{const r=n-this._lastTime;this.update(n,r),this._camera.parent!==this._scene&&this._scene.add(this._camera),this._renderer.render(this._scene,this._camera)}),a(this,"_objects",[]),this._mode=s,this._init=t,this._session=i,this._session.addEventListener("end",this.onEnd),this._renderer=new ur({alpha:!0}),this._renderer.setAnimationLoop(this.onFrame),this._renderer.xr.setSession(i),this._renderer.xr.enabled=!0,this._camera=new we,this._scene=new qi,this._scene.fog=new $y(4473924,10,250),this._scene.add(this._camera),this.setupScene()}static get active(){return this._active}static async start(s,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 i=await navigator.xr.requestSession(s,t);return i.addEventListener("end",()=>{this._active=null}),this._requestInFlight?(this._requestInFlight=!1,this._active=new Db(s,t,i),this._active):(i.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 s={session:this._session,mode:this._mode,init:this._init};return await this.onBeforeHandoff(),this.onEnd(),this._session=null,s}async onBeforeHandoff(){await ys(1e3),this._scene.clear()}setupScene(){this._scene.background=new re(0),this._scene.add(new cm(5,10,1118481,1118481));const s=new hm(16777215,1);s.position.set(0,20,0),s.castShadow=!1,this._scene.add(s);const t=new hm(16777215,1);t.position.set(0,-1,0),t.castShadow=!1,this._scene.add(t);const i=new qy(16777215,1,100,1);i.position.set(0,2,0),i.castShadow=!1,i.distance=200,this._scene.add(i);const n=50;for(let o=0;o<100;o++){const r=new li({color:2236962,metalness:1,roughness:.8});this.isAR&&(r.emissive=new re(Math.random(),Math.random(),Math.random()),r.emissiveIntensity=Math.random());const l=W.random(0,1)>.5?wr.Sphere:wr.Cube,c=go.createPrimitive(l,{material:r});c.position.x=W.random(-n,n),c.position.y=W.random(-2,n),c.position.z=W.random(-n,n),c.rotation.x=W.random(0,Math.PI*2),c.rotation.y=W.random(0,Math.PI*2),c.rotation.z=W.random(0,Math.PI*2),c.scale.multiplyScalar(.5+Math.random()*10);const h=c.position.distanceTo(this._camera.position)-c.scale.x;h<1&&c.position.multiplyScalar(1+1/h),this._objects.push(c),this._scene.add(c)}}update(s,t){const i=s*4e-4;for(let n=0;n<this._objects.length;n++){const o=this._objects[n];o.position.y+=Math.sin(i+n*.5)*.005,o.rotateY(.002)}}};let Aa=Db;a(Aa,"_active",null),a(Aa,"_requestInFlight",!1);var gc;(s=>{const t=[];function i(){if(!(t!=null&&t.length))return!1;for(const r of t)r.exportAndOpen();return!0}s.exportAndOpen=i;function n(r){t.push(r)}s.registerExporter=n;function o(r){if(!t)return;const l=t.indexOf(r);l>=0&&t.splice(l,1)}s.unregisterExporter=o})(gc||(gc={}));const Bb="NeedleXRSession onStart",Fb="NeedleXRSession onEnd",yt=O("debugwebxr"),zb=O("stats");let fg=0;function YP(s){let t=null;const i=s;return i.getAROverlayContainer?t=i.getAROverlayContainer():t=s,t}KP();async function KP(){var s;if(O("debugasap")){let t=globalThis["needle:XRSession"];if(t instanceof Promise){delete globalThis["needle:XRSession"],ge.addContextCreatedCallback(async i=>{if(!t)return;br(!0);const n=await t;if(n){const o=J.getDefaultSessionInit("immersive-vr");J.setSession("immersive-vr",n,o,i.context)}else console.error("NeedleXRSession: ASAP session was rejected");t=void 0});return}}if("xr"in navigator){if(/WebXRViewer\//i.test(navigator.userAgent)){console.warn("WebXRViewer does not support addEventListener");return}(s=navigator.xr)==null||s.addEventListener("sessiongranted",async()=>{br(!0),console.log("Received Session Granted..."),await ys(100);const t=sessionStorage.getItem("needle_xr_session_mode"),i=sessionStorage.getItem("needle_xr_session_init")??null,n=i?JSON.parse(i):null;let o=null;if(Ub()&&(await Aa.start(t||"immersive-vr",n||J.getDefaultSessionInit("immersive-vr")),await ek(),o=await Aa.handoff()),o)J.setSession(o.mode,o.session,o.init,ee.Current);else if(t&&i){console.log("Session Granted: Restore last session");const r=JSON.parse(i);J.start(t,r).catch(l=>console.warn(l))}else J.start("immersive-vr").catch(r=>console.warn("Session Granted failed:",r))},{once:!0})}}function ZP(s,t){sessionStorage.setItem("needle_xr_session_mode",s),sessionStorage.setItem("needle_xr_session_init",JSON.stringify(t))}function JP(){sessionStorage.removeItem("needle_xr_session_mode"),sessionStorage.removeItem("needle_xr_session_init")}const yg=new Set;ge.registerCallback(ye.ContextCreationStart,async s=>{yg.add(s.context)}),ge.registerCallback(ye.ContextCreated,async s=>{yg.delete(s.context)});function Ub(){return yg.size>0}function ek(){return new Promise(s=>{const t=Date.now(),i=setInterval(()=>{(!Ub()||Date.now()-t>6e4)&&(clearInterval(i),s())},100)})}X.isDesktop()&&F()&&window.addEventListener("keydown",s=>{(s.key==="x"||s.key==="Escape")&&J.active&&J.stop()});const fo=class{constructor(s,t,i,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 l;this.running&&(this.context.renderer.xr.enabled=!0,this.context.renderer.xr.updateCamera(this.context.mainCamera),(l=this.context.mainCameraComponent)==null||l.applyClearFlags())}),a(this,"onInputSourceAdded",l=>{if(l.targetRayMode==="screen")return;let c=0;for(let d=0;d<this.session.inputSources.length;d++)if(this.session.inputSources[d]===l){c=d;break}if(this.controllers.find(d=>d.inputSource===l)){console.debug("Controller already exists for input source",c);return}else if(this._newControllers.find(d=>d.inputSource===l)){console.debug("Controller already registered for input source",c);return}const h=new og(this,l,c);this._newControllers.push(h)}),a(this,"_ended",!1),a(this,"_newControllers",[]),a(this,"onEnd",l=>{var c,h,d;if(this._ended)return;this._ended=!0,console.debug("XR Session ended"),JP(),this.onAfterRender(),this.revertCustomForward(),this._didStart=!1,this._previousCameraParent=null,mo(this.onBefore,Me.LateUpdate);const u=this.context.pre_render_callbacks.indexOf(this.onBeforeRender);u>=0&&this.context.pre_render_callbacks.splice(u,1);const p=this.context.post_render_callbacks.indexOf(this.onAfterRender);p>=0&&this.context.post_render_callbacks.splice(p,1),this.context.xr=null,this.context.renderer.xr.enabled=!1,this.context.pre_update_oneshot_callbacks.push(()=>{var y,f;(y=this.context.mainCameraComponent)==null||y.applyClearFlags(),(f=this.context.mainCameraComponent)==null||f.applyClippingPlane()}),gb({session:this});for(const y of fo._xrEndListeners)y({xr:this});const g=[...this.controllers];for(let y=0;y<g.length;y++)this.disconnectInputSource(g[y].inputSource);this._newControllers.length=0,this.controllers.length=0;for(const y of this._xr_scripts)(c=y?.onLeaveXR)==null||c.call(y,{xr:this});(h=this.sync)==null||h.onExitXR(this),this.context.mainCamera&&((d=this._originalCameraParent)==null||d.add(this.context.mainCamera),this._originalCameraWorldPosition&&dt(this.context.mainCamera,this._originalCameraWorldPosition),this._originalCameraWorldRotation&&Gi(this.context.mainCamera,this._originalCameraWorldRotation),this._originalCameraWorldScale&&Pa(this.context.mainCamera,this._originalCameraWorldScale)),this.context.requestSizeUpdate(),this._defaultRig.gameObject.removeFromParent(),br(!1),performance.mark(Fb),performance.measure("NeedleXRSession",Bb,Fb)}),a(this,"_didStart",!1),a(this,"onBefore",l=>{var c,h,d,u,p,g,y,f;const v=l.xrFrame;if(!v)return;performance.mark("NeedleXRSession onBefore start"),this.context.xr=this,this.context.mainCameraComponent&&this.context.mainCameraComponent!==this._mainCamera&&(this._mainCamera=this.context.mainCameraComponent),((c=this.rig)==null?void 0:c.isActive)==!1&&(yt&&console.warn("Latest rig is not active - trying to activate a different rig",this.rig),this.updateActiveXRRig()),this.rig&&(h=this._mainCamera)!=null&&h.gameObject&&((u=(d=this._mainCamera)==null?void 0:d.gameObject)==null?void 0:u.parent)!==this.rig.gameObject&&this.rig.gameObject.add((p=this._mainCamera)==null?void 0:p.gameObject),this.internalUpdateState(),this.applyCustomForward();const b={xr:this};if(this._didStart){if(this.context.new_scripts_xr.length>0){const w=[...this.context.new_scripts_xr];for(let _=0;_<w.length;_++){const C=this.context.new_scripts_xr[_];if(!C||C.destroyed||((g=C.supportsXR)==null?void 0:g.call(C,this.mode))==!1){this.context.new_scripts_xr.splice(_,1);continue}if(!C.activeAndEnabled){this.context.new_scripts_xr.splice(_,1),this.markInactive(C);continue}if(this.addScript(C)){this.invokeCallback_EnterXR(C);for(const R of this.controllers)this.invokeCallback_ControllerAdded(C,R)}}}}else{if(this._didStart=!0,this.mode==="immersive-vr"){const _=ci(this.context.scene.children);if(_){const C=_.getSize(G());if(C.length()>0){const R=this._defaultRig.gameObject;R.position.set(_.min.x+C.x*.5,_.min.y,_.max.z+C.z*.5+1.5);const M=_.getCenter(G());M.y=R.position.y,R.lookAt(M)}}}mb({session:this});for(const _ of fo._xrStartListeners)_(b);const w=[...this._xr_scripts];yt&&console.log("NeedleXRSession start, handle scripts:",w);for(const _ of w){if(_.destroyed){this._script_to_remove.push(_);continue}if(!_.activeAndEnabled){this.markInactive(_);continue}this.invokeCallback_EnterXR(_);for(const C of this.controllers)this.invokeCallback_ControllerAdded(_,C)}}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 _ of w){if(!_.connected){console.warn("New controller is not connected",_);continue}this.controllers.push(_);for(const C of this._xr_scripts){if(C.destroyed){this._script_to_remove.push(C);continue}C.activeAndEnabled!==!1&&this.invokeCallback_ControllerAdded(C,_)}}this.controllers.sort((_,C)=>_.index-C.index)}yt&&this.context.time.frame%30===0&&this.controllers.length<=0&&this.session.inputSources.length>0&&(br(!0),console.error("XRControllers are not added but inputSources are present")),performance.mark("NeedleXRSession update scripts start");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(b)}if(performance.mark("NeedleXRSession update scripts end"),performance.measure("NeedleXRSession update scripts","NeedleXRSession update scripts start","NeedleXRSession update scripts end"),this.handleInactiveScripts(),this._script_to_remove.length>0){const w=[...new Set(this._script_to_remove)];this._script_to_remove.length=0;for(const _ of w)!_.destroyed&&this.running&&((y=_.onLeaveXR)==null||y.call(_,b)),this.removeScript(_)}(f=this.sync)==null||f.onUpdate(this),this.onRenderDebug(),performance.mark("NeedleXRSession onBefore end"),performance.measure("NE XR frame","NeedleXRSession onBefore start","NeedleXRSession onBefore end")}),a(this,"onBeforeRender",()=>{this.context.mainCamera&&this.updateFade(this.context.mainCamera)}),a(this,"onAfterRender",()=>{if(this.onUpdateFade_PostRender(),X.isDesktop()||!this._renderOnceOnDevice){const l=this.context.renderer;if(l.xr.isPresenting&&this.context.mainCamera){this._renderOnceOnDevice=!0;const c=l.xr.enabled,h=l.getRenderTarget(),d=this.context.scene.background;l.xr.enabled=!1,l.setRenderTarget(null),this.isPassThrough&&(this.context.scene.background=null),this.context.composer?this.context.composer.render(this.context.time.deltaTime):l.render(this.context.scene,this.context.mainCamera),l.xr.enabled=c,l.setRenderTarget(h),this.context.scene.background=d}}}),a(this,"_script_to_remove",[]),a(this,"_camera"),a(this,"_cameraRenderParent",new I().rotateY(Math.PI)),a(this,"_previousCameraParent"),a(this,"_customforward",!0),a(this,"originalCameraNearPlane"),a(this,"_viewerPose"),a(this,"_transformOrientation",new V),a(this,"_transformPosition",new x),a(this,"_transition");var o,r;performance.mark(Bb),ZP(s,n.init),this.session=t,this.mode=s,this.context=i,(yt||O("console"))&&br(!0),this._xr_scripts=[...n.scripts],this._xr_update_scripts=this._xr_scripts.filter(l=>typeof l.onUpdateXR=="function"),this._controllerAdded=n.controller_added,this._controllerRemoved=n.controller_removed,Pn(this.onBefore,Me.LateUpdate),this.context.pre_render_callbacks.push(this.onBeforeRender),this.context.post_render_callbacks.push(this.onAfterRender),((o=n.init.optionalFeatures)!=null&&o.includes("hit-test")||(r=n.init.requiredFeatures)!=null&&r.includes("hit-test"))&&t.requestReferenceSpace("viewer").then(l=>{var c,h;return(h=(c=t.requestHitTestSource)==null?void 0:c.call(t,{space:l}))==null?void 0:h.then(d=>this._viewerHitTestSource=d).catch(d=>console.error(d))}).catch(l=>console.error(l)),this.context.mainCamera&&(this._originalCameraWorldPosition=te(this.context.mainCamera,new x),this._originalCameraWorldRotation=Oe(this.context.mainCamera,new V),this._originalCameraWorldScale=Je(this.context.mainCamera,new x),this._originalCameraParent=this.context.mainCamera.parent),this._defaultRig=new LP,this.context.scene.add(this._defaultRig.gameObject),this.addRig(this._defaultRig);for(let l=0;l<t.inputSources.length;l++){const c=t.inputSources[l];if(!c.handedness){console.warn("Input source in xr session has no handedness - ignoring",l);continue}this.onInputSourceAdded(c)}this.session.addEventListener("end",this.onEnd),this.session.addEventListener("inputsourceschange",l=>{for(const c of l.removed)this.disconnectInputSource(c);for(const c of l.added)this.onInputSourceAdded(c)}),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):yt&&console.warn("controllerAutoUpdate is not available in three.js - cannot disable it")}static getXRSync(s){return this._sync||(this._sync=new Ab(s)),this._sync}static get currentSessionRequest(){return this._currentSessionRequestMode}static get active(){return this._activeSession}static get activeMode(){var s;return((s=this._activeSession)==null?void 0:s.mode)??null}static get xrSystem(){return"xr"in navigator?navigator.xr:void 0}static isXRSupported(){return Promise.all([this.isVRSupported(),this.isARSupported()]).then(s=>s.some(t=>t)).catch(()=>!1)}static isVRSupported(){return this.isSessionSupported("immersive-vr")}static isARSupported(){return this.isSessionSupported("immersive-ar")}static isSessionSupported(s){var t;return((t=this.xrSystem)==null?void 0:t.isSessionSupported(s).catch(i=>(yt&&console.error(i),!1)))??Promise.resolve(!1)}static onSessionRequestStart(s){this._sessionRequestStartListeners.push(s)}static offSessionRequestStart(s){const t=this._sessionRequestStartListeners.indexOf(s);t>=0&&this._sessionRequestStartListeners.splice(t,1)}static onSessionRequestEnd(s){this._sessionRequestEndListeners.push(s)}static offSessionRequestEnd(s){const t=this._sessionRequestEndListeners.indexOf(s);t>=0&&this._sessionRequestEndListeners.splice(t,1)}static onXRSessionStart(s){this._xrStartListeners.push(s)}static offXRSessionStart(s){const t=this._xrStartListeners.indexOf(s);t>=0&&this._xrStartListeners.splice(t,1)}static onXRSessionEnd(s){this._xrEndListeners.push(s)}static offXRSessionEnd(s){const t=this._xrEndListeners.indexOf(s);t>=0&&this._xrEndListeners.splice(t,1)}static onControllerAdded(s){this._controllerAddedListeners.push(s)}static offControllerAdded(s){const t=this._controllerAddedListeners.indexOf(s);t>=0&&this._controllerAddedListeners.splice(t,1)}static onControllerRemoved(s){this._controllerRemovedListeners.push(s)}static offControllerRemoved(s){const t=this._controllerRemovedListeners.indexOf(s);t>=0&&this._controllerRemovedListeners.splice(t,1)}static offerSession(s,t,i){return"xr"in navigator&&navigator.xr&&"offerSession"in navigator.xr?(typeof navigator.xr.offerSession=="function"&&(console.log("WebXR offerSession is available - requesting mode: "+s),t=="default"&&(t=this.getDefaultSessionInit(s)),navigator.xr.offerSession(s,{...t}).then(n=>fo.setSession(s,n,t,i)).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(s){switch(s){case"immersive-ar":const t=["anchors","local-floor","layers","dom-overlay","hit-test","unbounded"];return X.isVisionOS()||t.push("hand-tracking"),{optionalFeatures:t};case"immersive-vr":const i=["local-floor","bounded-floor","high-fixed-foveation-level","layers"];return X.isVisionOS()||i.push("hand-tracking"),{optionalFeatures:i};default:return console.warn("No default session init for mode",s),{}}}static async start(s,t,i){var n,o,r,l;if(X.isiOS()){if(s==="ar")if(await this.isARSupported())s="immersive-ar";else return gc.exportAndOpen(),null}else s=="ar"&&(s="immersive-ar");if(F()&&O("debugxrpreroom"))return console.warn("Debug: Starting temporary XR session"),await Aa.start(s,t||fo.getDefaultSessionInit(s)),null;if(this._currentSessionRequest)return console.warn("A XRSession is already being requested"),(yt||F())&&xe("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(i||(i=ee.Current),i||(i=ge.All[0]),!i)throw new Error("No Needle Engine Context found");switch(performance.mark("NeedleXRSession start"),t||(t={}),s){case"immersive-ar":{if(await((n=this.xrSystem)==null?void 0:n.isSessionSupported("immersive-ar"))!==!0)return console.error(s+" is not supported by this browser."),null;const u=this.getDefaultSessionInit(s),p=YP(i.domElement);p&&!X.isQuest()&&(u.domOverlay={root:p},u.optionalFeatures.push("dom-overlay")),t={...u,...t}}break;case"immersive-vr":{if(await((o=this.xrSystem)==null?void 0:o.isSessionSupported("immersive-vr"))!==!0)return console.error(s+" is not supported by this browser."),null;t={...this.getDefaultSessionInit(s),...t}}break;default:console.warn("No default session init for mode",s);break}t.optionalFeatures??(t.optionalFeatures=[]),t.requiredFeatures??(t.requiredFeatures=[]),await Aa.stop();const c=s=="immersive-ar"?i.scripts_immersive_ar:i.scripts_immersive_vr;yt?console.log(`%cRequesting ${s} session`,"font-weight:bold;",t,c):console.log(`%cRequesting ${s} session`,"font-weight:bold;");for(const u of c)u.onBeforeXR&&u.onBeforeXR(s,t);for(const u of this._sessionRequestStartListeners)u({mode:s,init:t});yt&&De("Requesting "+s+" session ("+Date.now()+")"),this._currentSessionRequest=(r=navigator.xr)==null?void 0:r.requestSession(s,t),this._currentSessionRequestMode=s;const h=await((l=this._currentSessionRequest)==null?void 0:l.catch(u=>{console.error(u,"Code: "+u.code),u.code===9&&xe("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:"&&xe("XR requires a secure connection (HTTPS)")}));this._currentSessionRequest=void 0,this._currentSessionRequestMode=null;for(const u of this._sessionRequestEndListeners)u({mode:s,init:t,newSession:h||null});if(!h)return console.warn("XR Session request was rejected"),null;const d=this.setSession(s,h,t,i);return performance.mark("NeedleXRSession end"),performance.measure("NeedleXRSession Startup","NeedleXRSession start","NeedleXRSession end"),d}static setSession(s,t,i,n){if(this._activeSession)return console.error("A XRSession is already running"),this._activeSession;const o=s=="immersive-ar"?n.scripts_immersive_ar:n.scripts_immersive_vr;return this._activeSession=new fo(s,t,n,{scripts:o,controller_added:this._controllerAddedListeners,controller_removed:this._controllerRemovedListeners,init:i}),t.addEventListener("end",this.onEnd),yt?console.log(`%cStarted ${s} session`,"font-weight:bold;",o):console.log(`%cStarted ${s} session`,"font-weight:bold;"),this._activeSession}static stop(){var s;(s=this._activeSession)==null||s.end()}get sync(){return fo._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(s=>s.side==="left")}get rightController(){return this.controllers.find(s=>s.side==="right")}getController(s){return typeof s=="number"?this.controllers[s]||null:this.controllers.find(t=>t.side===s)||null}get isPassThrough(){return!!(this.environmentBlendMode!=="opaque"&&this.interactionMode==="world-space"||this.mode==="immersive-ar"&&this.environmentBlendMode!=="opaque"&&this.controllers.some(s=>s.inputSource.targetRayMode==="tracked-pointer")||F()&&X.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 s=this.frame.getImageTrackingResults();for(const t of s)if(t.trackingState==="tracked")return!0}catch{return!1}return!1}get rig(){const s=this._rigs[0]??null;return s!=null&&s.gameObject&&kr(s.gameObject)||s?.isActive===!1?(this.updateActiveXRRig(),this._rigs[0]??null):s}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(s){this._rigs.indexOf(s)>=0||(s.priority===void 0&&(s.priority=0),this._rigs.push(s),this.updateActiveXRRig())}removeRig(s){const t=this._rigs.indexOf(s);t!==-1&&(this._rigs.splice(t,1),this.updateActiveXRRig())}setRigActive(s){const t=this._rigs.indexOf(s),i=this._rigs[0];this._rigs.splice(t,1),this._rigs.unshift(s),s.priority=i?.priority??0,this.updateActiveXRRig()}getUserOffsetInRig(){var s;const t=(s=this.context.mainCamera)==null?void 0:s.position;if(!t||!this.rig)return G(0,0,0);const i=G(t);return i.x*=-1,i.z*=-1,i.applyQuaternion(vs(this.rig.gameObject.quaternion)),i}updateActiveXRRig(){const s=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 i=1;i<this._rigs.length;i++){const n=this._rigs[i];if(n.isActive){if(kr(n.gameObject)){this._rigs.splice(i,1),i--;continue}(!t||t.isActive===!1||n.priority!==void 0&&n.priority>t.priority)&&(t=n)}}if(s!==t){const i=this._rigs.indexOf(t);i>=0&&this._rigs.splice(i,1),this._rigs.unshift(t)}yt&&(s===t?console.log("Updated Active XR Rig:",t,"prev:",s):console.log("Updated Active XRRig:",t," (the same as before)"))}getHitTest(s){if(s)return this.getControllerHitTest(s);if(!this._viewerHitTestSource)return null;const t=this._viewerHitTestSource,i=this.frame.getHitTestResults(t);if(i.length>0){const n=i[0];return this.convertHitTestResult(n)}return null}getControllerHitTest(s){const t=s.getHitTestSource();if(!t)return null;const i=this.frame.getHitTestResultsForTransientInput(t);for(const n of i)if(n.inputSource===s.inputSource)for(const o of n.results)return this.convertHitTestResult(o);return null}convertHitTestResult(s){const t=this.context.renderer.xr.getReferenceSpace(),i=t&&s.getPose(t);if(i){const n=G(i.transform.position),o=vs(i.transform.orientation),r=this.context.mainCamera;if(r?.parent!==this._cameraRenderParent&&n.applyMatrix4(Ra),r!=null&&r.parent){n.applyMatrix4(r.parent.matrixWorld),o.multiply(Yi);const l=Oe(r.parent);l.premultiply(Yi),o.premultiply(l)}return{hit:s,position:n,quaternion:o}}return null}convertSpace(s){const t=G(s.position);t.applyMatrix4(Ra);const i=vs(s.orientation);return i.premultiply(Yi),{position:t,quaternion:i}}disconnectInputSource(s){const t=(i,n,o)=>{if(i.inputSource===s){yt&&console.log("Disconnecting controller",i.index),this.controllers.splice(o,1),this.invokeControllerEvent(i,this._controllerRemoved,"removed");const r={xr:this,controller:i,change:"removed"};for(const l of this._xr_scripts)l.onXRControllerRemoved&&l.onXRControllerRemoved(r);i.onDisconnected()}};for(let i=this.controllers.length-1;i>=0;i--){const n=this.controllers[i];t(n,this.controllers,i)}for(let i=this._newControllers.length-1;i>=0;i--){const n=this._newControllers[i];t(n,this._newControllers,i)}}end(){this._ended||this.session.end().catch(s=>console.warn(s))}onRenderDebug(){if(yt)for(const s of this.controllers)s.onRenderDebug();if((yt||zb)&&this.rig&&(fg++,fg>=20)){const s=this.rig.gameObject.worldPosition,t=this.rig.gameObject.worldForward;s.add(t.multiplyScalar(1.5));const i=this.rig.gameObject.worldUp;s.add(i.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()}`,yt||zb)for(const o of this.controllers)n+=`
154
+ ${o.hand?"hand":"ctrl"} ${o.inputSource.handedness}[${o.index}] con:${o.connected} tr:${o.isTracking} hts:${o.hasHitTestSource?"yes":"no"}`;fg=0,q.DrawLabel(s,n,void 0,1/60*20)}}addScript(s){return this._xr_scripts.includes(s)?!1:(yt&&console.log("Register new XRScript",s),this._xr_scripts.push(s),typeof s.onUpdateXR=="function"&&this._xr_update_scripts.push(s),!0)}markInactive(s){if(!(this._inactive_scripts.indexOf(s)>=0)){this.removeScript(s,!1),this._inactive_scripts.push(s);for(const t of this.controllers)this.invokeCallback_ControllerRemoved(s,t);this.invokeCallback_LeaveXR(s)}}handleInactiveScripts(){if(this._inactive_scripts.length>0)for(let s=this._inactive_scripts.length-1;s>=0;s--){const t=this._inactive_scripts[s];if(t.activeAndEnabled){this._inactive_scripts.splice(s,1),this.addScript(t),this.invokeCallback_EnterXR(t);for(const i of this.controllers)this.invokeCallback_ControllerAdded(t,i)}}}removeScript(s,t=!0){yt&&console.log("Remove XRScript",s);const i=this._xr_scripts.indexOf(s);i>=0&&this._xr_scripts.splice(i,1);const n=this._xr_update_scripts.indexOf(s);if(n>=0&&this._xr_update_scripts.splice(n,1),t){const o=this._inactive_scripts.indexOf(s);o>=0&&this._inactive_scripts.splice(o,1)}}invokeCallback_EnterXR(s){s.onEnterXR&&s.onEnterXR({xr:this})}invokeCallback_ControllerAdded(s,t){s.onXRControllerAdded&&s.onXRControllerAdded({xr:this,controller:t,change:"added"})}invokeCallback_ControllerRemoved(s,t){s.onXRControllerRemoved&&s.onXRControllerRemoved({xr:this,controller:t,change:"removed"})}invokeCallback_LeaveXR(s){s.onLeaveXR&&!s.destroyed&&s.onLeaveXR({xr:this})}syncCameraCullingMask(){var s;const t=this.context.xrCamera,i=(s=this.context.mainCameraComponent)==null?void 0:s.cullingMask;if(t&&i!==void 0){for(const n of t.cameras)n.layers.mask=i;t.layers.mask=i}else if(t){for(const n of t.cameras)n.layers.enableAll();t.layers.enableAll()}}invokeControllerEvent(s,t,i){for(let n=t.length-1;n>=0;n--){const o=t[n];if(o)try{o({xr:this,controller:s,change:i})}catch(r){console.error(r)}}}applyCustomForward(){var s;if(this.context.mainCamera&&this._customforward){this._camera=this.context.mainCamera,this._camera.parent!==this._cameraRenderParent&&(this._previousCameraParent=this._camera.parent,(s=this._previousCameraParent)==null||s.add(this._cameraRenderParent)),this._cameraRenderParent.name="XR Camera Render Parent",this._cameraRenderParent.add(this._camera);let t=.02;if(this.rig){const i=Je(this.rig.gameObject);t*=i.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 s=this.context.renderer.xr.getReferenceSpace();if(!s){this._viewerPose=void 0;return}if(this._viewerPose=this.frame.getViewerPose(s),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 Ib),this._transition}fadeTransition(){return this._transition||(this._transition=new Ib),this._transition.fadeTransition()}updateFade(s){this._transition&&s instanceof we&&this._transition.update(s,this.context.time.deltaTime)}onUpdateFade_PostRender(){var s;(s=this._transition)==null||s.remove()}};let J=fo;a(J,"_sync",null),a(J,"_currentSessionRequestMode",null),a(J,"_currentSessionRequest"),a(J,"_activeSession"),a(J,"_sessionRequestStartListeners",[]),a(J,"_sessionRequestEndListeners",[]),a(J,"_xrStartListeners",[]),a(J,"_xrEndListeners",[]),a(J,"_controllerAddedListeners",[]),a(J,"_controllerRemovedListeners",[]),a(J,"onEnd",()=>{yt&&console.log("XR Session ended"),fo._activeSession=null});const vg=O("debugwebxr");class Nb{static tryFindAvatarObjects(t,i,n){if(n.head&&n.leftHand&&n.rightHand)return;const o=t.name.toLocaleLowerCase();!n.head&&o.includes("head")&&(vg&&console.log("FOUND AVATAR HEAD",t.name),n.head=new ae("",i,t)),o.includes("hand")&&(!n.leftHand&&o.includes("left")&&(vg&&console.log("FOUND AVATAR LEFT HAND",t.name),n.leftHand=new ae("",i,t)),!n.rightHand&&o.includes("right")&&(vg&&console.log("FOUND AVATAR RIGHT HAND",t.name),n.rightHand=new ae("",i,t)));for(let r=0;r<t.children.length;r++){if(n.head&&n.leftHand&&n.rightHand)return;const l=t.children[r];this.tryFindAvatarObjects(l,i,n)}}}const Nt=new x,Wb=new x,Vb=new V,tk=O("debuggizmos"),xs=8947848,bg=32,Ss=class{constructor(){}static isGizmo(s){return s[wg]!==void 0}static DrawLabel(s,t,i=.05,n=0,o,r,l){var c;if(!Ss.enabled)return null;o||(o=xs);const h=((c=J.active)==null?void 0:c.rigScale)??1,d=Ae.getTextLabel(n,t,i*h,o,r);return l instanceof I&&l.add(d),d.position.x=s.x,d.position.y=s.y,d.position.z=s.z,d}static DrawRay(s,t,i=xs,n=0,o=!0){if(!Ss.enabled)return;const r=Ae.getLine(n),l=r.geometry.getAttribute("position");l.setXYZ(0,s.x,s.y,s.z),Nt.set(t.x,t.y,t.z).multiplyScalar(999999999),l.setXYZ(1,s.x+Nt.x,s.y+Nt.y,s.z+Nt.z),l.needsUpdate=!0,r.material.color.set(i),r.material.depthTest=o,r.material.depthWrite=!1}static DrawDirection(s,t,i=xs,n=0,o=!0,r=1){if(!Ss.enabled)return;const l=Ae.getLine(n),c=l.geometry.getAttribute("position");c.setXYZ(0,s.x,s.y,s.z),t.w!==void 0?(Nt.set(0,0,-r),Vb.set(t.x,t.y,t.z,t.w),Nt.applyQuaternion(Vb)):(Nt.set(t.x,t.y,t.z),Nt.multiplyScalar(r)),c.setXYZ(1,s.x+Nt.x,s.y+Nt.y,s.z+Nt.z),c.needsUpdate=!0,l.material.color.set(i),l.material.depthTest=o,l.material.depthWrite=!1}static DrawLine(s,t,i=xs,n=0,o=!0){if(!Ss.enabled)return;const r=Ae.getLine(n),l=r.geometry.getAttribute("position");l.setXYZ(0,s.x,s.y,s.z),l.setXYZ(1,t.x,t.y,t.z),l.needsUpdate=!0,r.material.color.set(i),r.material.depthTest=o,r.material.depthWrite=!1,r.material.fog=!1}static DrawCircle(s,t,i,n=xs,o=0,r=!0){if(!Ss.enabled)return;const l=Ae.getCircle(o);l.position.set(s.x,s.y,s.z),l.scale.set(i,i,i),l.quaternion.setFromUnitVectors(this._up,Nt.set(t.x,t.y,t.z).normalize()),l.material.color.set(n),l.material.depthTest=r,l.material.depthWrite=!1,l.material.fog=!1}static DrawWireSphere(s,t,i=xs,n=0,o=!0){if(!Ss.enabled)return;const r=Ae.getSphere(t,n,!0);yr(r,s.x,s.y,s.z),r.material.color.set(i),r.material.depthTest=o,r.material.depthWrite=!1,r.material.fog=!1}static DrawSphere(s,t,i=xs,n=0,o=!0){if(!Ss.enabled)return;const r=Ae.getSphere(t,n,!1);yr(r,s.x,s.y,s.z),r.material.color.set(i),r.material.depthTest=o,r.material.depthWrite=!1}static DrawWireBox(s,t,i=xs,n=0,o=!0){if(!Ss.enabled)return;const r=Ae.getBox(n);r.position.set(s.x,s.y,s.z),r.scale.set(t.x,t.y,t.z),r.material.color.set(i),r.material.depthTest=o,r.material.wireframe=!0,r.material.depthWrite=!1,r.material.fog=!1}static DrawWireBox3(s,t=xs,i=0,n=!0){if(!Ss.enabled)return;const o=Ae.getBox(i);o.position.copy(s.getCenter(Nt)),o.scale.copy(s.getSize(Nt)),o.material.color.set(t),o.material.depthTest=n,o.material.wireframe=!0,o.material.depthWrite=!1,o.material.fog=!1}static DrawArrow(s,t,i=xs,n=0,o=!0,r=!1){if(!Ss.enabled)return;const l=Ae.getArrowHead(n);l.position.set(t.x,t.y,t.z),l.quaternion.setFromUnitVectors(this._up.set(0,1,0),Nt.set(t.x,t.y,t.z).sub(Wb.set(s.x,s.y,s.z)).normalize());const c=Nt.set(t.x,t.y,t.z).sub(Wb.set(s.x,s.y,s.z)).length()*.1;l.scale.set(c,c,c),l.material.color.set(i),l.material.depthTest=o,l.material.wireframe=r,this.DrawLine(s,t,i,n,o)}static DrawWireMesh(s){const t=Ae.getMesh(s.duration??0);"mesh"in s?(t.geometry=s.mesh.geometry,t.matrix.copy(s.mesh.matrixWorld)):(t.geometry=s.geometry,t.matrix.copy(s.matrix)),t.matrixAutoUpdate=!1,t.matrixWorldAutoUpdate=!1,t.material.color.set(s.color??xs),t.material.depthTest=s.depthTest??!0,t.material.wireframe=!0}static setVisible(s){for(const t of Ae.timedObjectsBuffer)t.visible=s}};let q=Ss;a(q,"enabled",!0),a(q,"_up",new x(0,1,0));const ik=new Gl(1,1,1);function _g(s=null){const t=new re(s??14540253),i=new fS(ik);return new Gy(i,new Xy({color:t}))}const wg=Symbol("GizmoCache");class Ae{static ensureFont(){let t=Te.FontLibrary.getFontFamily(this.familyName);if(!t){t=Te.FontLibrary.addFontFamily(this.familyName);const i=t.addVariant("normal","normal","https://uploads.needle.tools/include/font-msdf.json","https://uploads.needle.tools/include/font.png");i?.addEventListener("ready",()=>{Te.update()})}}static getTextLabel(t,i,n,o,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),tk&&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:n,color:o,lineHeight:1,backgroundColor:r??void 0,backgroundOpacity:c,textContent:i,borderRadius:.5*n,padding:.8*n,whiteSpace:"pre",offset:.05*n};if(l)l.set(h);else{l=new fv(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,t,this.textLabelCache),l}static getBox(t){let i=this.boxesCache.pop();if(!i){const n=new Gl(1,1,1);i=new K(n)}return this.registerTimedObject(ee.Current,i,t,this.boxesCache),i}static getLine(t){let i=this.linesCache.pop();if(!i){i=new Xl;let n=i.geometry.getAttribute("position");n||(n=new ft(new Float32Array(2*3),3),i.geometry.setAttribute("position",n))}return i.frustumCulled=!1,this.registerTimedObject(ee.Current,i,t,this.linesCache),i}static getCircle(t){let i=this.circlesCache.pop();if(!i){i=new Xl;let n=i.geometry.getAttribute("position");if(!n){n=new ft(new Float32Array(bg*3),3),i.geometry.setAttribute("position",n);const o=G(0,1,0),r=G(0,0,1),l=G(r);l.cross(o).normalize();const c=G(l),h=Math.PI*2/(bg-1);for(let d=0;d<bg+1;d++){const u=h*d;o.copy(c).multiplyScalar(Math.cos(u)*1),l.copy(r).multiplyScalar(Math.sin(u)*1);const p=o.add(l);n.setXYZ(d,p.x,p.y,p.z)}}}return i.frustumCulled=!1,this.registerTimedObject(ee.Current,i,t,this.circlesCache),i}static getSphere(t,i,n){let o=this.spheresCache.pop();return o||(o=new K(new hd(1,8,8))),o.scale.set(t,t,t),o.material.wireframe=n,this.registerTimedObject(ee.Current,o,i,this.spheresCache),o}static getArrowHead(t){let i=this.arrowHeadsCache.pop();return i||(i=new K(new gS(0,.5,1,8))),this.registerTimedObject(ee.Current,i,t,this.arrowHeadsCache),i}static getMesh(t){let i=this.mesh.pop();return i||(i=new K,i.material=new Re),this.registerTimedObject(ee.Current,i,t,this.mesh),i}static registerTimedObject(t,i,n,o){if(!t){console.error("No Needle Engine context available. Did you call a Gizmos function in global scope?");return}const r=this.contextBeforeRenderCallbacks.get(t),l=this.contextPostRenderCallbacks.get(t);if(r){if(t.pre_render_callbacks[t.pre_render_callbacks.length-1]!==r){const c=t.pre_render_callbacks.indexOf(r);c>=0&&t.pre_render_callbacks.splice(c,1),t.pre_render_callbacks.push(r)}}else{const c=()=>{this.onBeforeRender(t,this.timedObjectsBuffer)};this.contextBeforeRenderCallbacks.set(t,c),t.pre_render_callbacks.push(c)}if(l){if(t.post_render_callbacks[t.post_render_callbacks.length-1]!==l){const c=t.post_render_callbacks.indexOf(l);c>=0&&t.post_render_callbacks.splice(c,1),t.post_render_callbacks.push(l)}}else{const c=()=>{this.onPostRender(t,this.timedObjectsBuffer,this.timesBuffer)};this.contextPostRenderCallbacks.set(t,c),t.post_render_callbacks.push(c)}i.traverse(c=>{c.layers.disableAll(),c.layers.enable(2)}),i.renderOrder=999999,i[wg]=o,i.castShadow=!1,i.receiveShadow=!1,i.isGizmo=!0,this.timedObjectsBuffer.push(i),this.timesBuffer.push(ee.Current.time.realtimeSinceStartup+n),t.scene.add(i)}static onBeforeRender(t,i){this.tmuiNeedsUpdate&&(this.tmuiNeedsUpdate=!1,Te.update());for(let n=0;n<i.length;n++){const o=i[n];if(t.mainCamera&&o instanceof Te.MeshUIBaseElement){if(kr(o))continue;const r=t.isInVR,l=!1,c=!r;ic(o,t.mainCamera,l,c)}}}static onPostRender(t,i,n){const o=t.time.realtimeSinceStartup;for(let r=i.length-1;r>=0;r--){const l=i[r];o>=n[r]-1e-6&&(i.splice(r,1),n.splice(r,1),l.removeFromParent(),kr(l)!=!0&&l[wg].push(l))}}}a(Ae,"familyName","needle-gizmos"),a(Ae,"linesCache",[]),a(Ae,"circlesCache",[]),a(Ae,"spheresCache",[]),a(Ae,"boxesCache",[]),a(Ae,"arrowHeadsCache",[]),a(Ae,"mesh",[]),a(Ae,"textLabelCache",[]),a(Ae,"timedObjectsBuffer",new Array),a(Ae,"timesBuffer",new Array),a(Ae,"contextPostRenderCallbacks",new Map),a(Ae,"contextBeforeRenderCallbacks",new Map),a(Ae,"tmuiNeedsUpdate",!1);const ki=O("debugphysics"),Hb=new no;class Ws{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(t,i){this.screenPoint===void 0&&(this.screenPoint=new oe),this.screenPoint.x=t/window.innerWidth*2-1,this.screenPoint.y=-(i/window.innerHeight)*2+1}setLayer(t){Hb.set(t),this.layerMask=Hb}setMask(t){this.layerMask||(this.layerMask=new no);const i=this.layerMask;i?i.mask=t:this.layerMask=t}}a(Ws,"AllLayers",4294967295);class xg{constructor(t,i,n){a(this,"distance"),a(this,"point"),a(this,"object"),this.object=t,this.distance=i,this.point=n}}const Sg=class{constructor(s){a(this,"context"),a(this,"engine"),a(this,"raycaster",new ud),a(this,"defaultRaycastOptions",new Ws),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 no),a(this,"sphere",new dd),a(this,"tempBoundingBox",new _i),this.context=s}static get raycasting(){return this._raycasting>0}raycastPhysicsFast(s,t=void 0,i=1/0,n=!0){var o;return((o=this.context.physics.engine)==null?void 0:o.raycast(s,t,{maxDistance:i,solid:n}))??null}raycastPhysicsFastAndGetNormal(s,t=void 0,i=1/0,n=!0){var o;return((o=this.context.physics.engine)==null?void 0:o.raycastAndGetNormal(s,t,{maxDistance:i,solid:n}))??null}sphereOverlapPhysics(s,t){var i;return((i=this.context.physics.engine)==null?void 0:i.sphereOverlap(s,t))??null}sphereOverlap(s,t,i=!0,n=!1,o=null){if(this.sphereResults.length=0,!this.context.scene)return this.sphereResults;const r=this.sphereMask;r.enableAll(),r.disable(2);for(const l of this.context.scene.children)this.intersectSphere(l,s,t,r,this.sphereResults,i,n,o);return this.sphereResults.sort((l,c)=>l.distance-c.distance)}raycastFromRay(s,t=null){const i=t??this.defaultRaycastOptions;i.ray=s;const n=this.raycast(i);return i===this.defaultRaycastOptions&&(i.ray=void 0),n}raycast(s=null){ki&&performance.mark("raycast.start"),s||(s=this.defaultRaycastOptions);const t=s.screenPoint??this.context.input.mousePositionRC,i=s.raycaster??this.raycaster;if(i.near=s.minDistance??0,i.far=s.maxDistance??1/0,i.params=this.defaultThresholds,s.lineThreshold===void 0&&(s.lineThreshold=-1),i.params.Line={threshold:s.lineThreshold},s.ray)i.ray.copy(s.ray);else{const l=s.cam??this.context.mainCamera;if(!l)return ki&&console.error("Can not perform raycast - no main camera found"),this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),this.defaultRaycastOptions.results??[];const c=this.context.xrCamera;this.context.isInXR&&c instanceof yS&&c.cameras.length>0?i.setFromCamera(t,c.cameras[0]):i.setFromCamera(t,l)}let n=s.targets;n||(n=this.targetBuffer,n.length=1,n[0]=this.context.scene);let o=s.results;this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),o||(this.defaultRaycastOptions.results||(this.defaultRaycastOptions.results=new Array),o=this.defaultRaycastOptions.results),s.layerMask!==void 0?s.layerMask instanceof no?i.layers.mask=s.layerMask.mask:i.layers.mask=s.layerMask:(i.layers.enableAll(),i.layers.disable(2)),ki&&console.time("raycast"),o.length=0,Sg._raycasting++,this.intersect(this.raycaster,n,o,s),o.sort((l,c)=>l.distance-c.distance);const r=s.ignore;return r!==void 0&&r.length>0&&(o=o.filter(l=>!r.includes(l.object))),Sg._raycasting--,ki&&(console.timeEnd("raycast"),console.warn("#"+this.context.time.frame+", hits:",o!=null&&o.length?[...o]:"nothing"),performance.mark("raycast.end"),performance.measure("raycast","raycast.start","raycast.end")),o}intersect(s,t,i,n){var o,r,l;for(const c of t){if(!c||c.visible===!1||q.isGizmo(c)||n.lineThreshold!==void 0&&n.lineThreshold<0&&c instanceof Xl)continue;let h=!0;const d=c,u=d.geometry;if(n.testObject){const p=(o=n.testObject)==null?void 0:o.call(n,c);if(p===!1)continue;p==="continue in children"&&(h=!1)}if(h&&(u&&$b(u)||(h=!1)),h){const p=ov(c);p&&(d.geometry=p);const g=i.length;let y=!0;if(n.precise===!1&&(y=!1),y||(y=((l=(r=u.getAttribute("position"))==null?void 0:r.array)==null?void 0:l.length)<64),d instanceof Sa&&(y=!1),!y&&nk(d,s,i)||(n.useAcceleratedRaycast!==!1?Ud.runMeshBVHRaycast(s,d,i,this.context):s.intersectObject(d,!1,i)),ki&&i.length!=g){const f=i[i.length-1],v=p?8969557:7798784;q.DrawWireSphere(f.point,.1,v,1,!1),q.DrawWireMesh({mesh:c,depthTest:!1,duration:.2,color:v})}d.geometry=u}n.recursive!==!1&&this.intersect(s,c.children,i,n)}return i}intersectSphere(s,t,i,n,o,r,l,c){let h=s&&s.isMesh&&s.layers.test(n)&&!q.isGizmo(s);h&&(h=s.visible),h&&(h=!(s instanceof Xl)),h&&(h=!(s instanceof Sa));const d=s,u=d.geometry;if(h&&c){const p=c(s);if(p===!1)return;p==="continue in children"&&(h=!1)}if(u&&$b(u)||(h=!1),h){if(l){const p=this.sphere;p.center.copy(t),p.radius=i;const g=o.length;if(Ud.runMeshBVHRaycast(this.sphere,d,o,this.context),g!=o.length&&!r)return}else if(u.boundingBox||u.computeBoundingBox(),u.boundingBox){d.matrixWorldNeedsUpdate&&d.updateWorldMatrix(!1,!1);const p=this.tempBoundingBox.copy(u.boundingBox).applyMatrix4(d.matrixWorld),g=this.sphere;if(g.center.copy(t),g.radius=i,g.intersectsBox(p)){const y=te(s),f=y.distanceTo(g.center),v=new xg(s,f,y);if(o.push(v),!r)return}}}if(s.children)for(const p of s.children){const g=o.length;if(this.intersectSphere(p,t,i,n,o,r,l,c),g!=o.length&&!r)return}}};let Fd=Sg;a(Fd,"_raycasting",0);function $b(s){return!(s.index&&s.index.array.length<3)}const xr=new dd,zd=new pr,sk=new Hy;function nk(s,t,i){const n=s._computeIntersections;if(!n)return!1;let o=s["_computeIntersections:Needle"];return o||(o=s["_computeIntersections:Needle"]=function(r,l,c){const h=this,d=h.geometry.boundingSphere;if(d){if(h instanceof Sa){zd.setFromNormalAndCoplanarPoint(G(0,1,0),G(0,-h.position.y,0)),zd.applyMatrix4(h.matrixWorld,sk);const p=r.ray.intersectPlane(zd,G());if(p){xr.copy(d),xr.applyMatrix4(h.matrixWorld);const g=G(p).sub(r.ray.origin).length(),y=xr.radius*.5;g<y&&l.push({distance:g,point:p,object:h,normal:zd.normal.clone()})}return}xr.copy(d),xr.applyMatrix4(h.matrixWorld);const u=r.ray.intersectSphere(xr,G());if(u){const p=G(u).sub(r.ray.origin),g=p.length();if(g>xr.radius){const y=p.clone().normalize();l.push({distance:g,point:u,object:h,normal:y})}}}}),s._computeIntersections=o,t.intersectObject(s,!1,i),s._computeIntersections=n,!0}var Ud;(s=>{function t(w,_,C,R){var M,T,j;if(!_.geometry||!_.geometry.hasAttribute("position"))return!1;const D=_.geometry;if(_!=null&&_.isSkinnedMesh){const U=_,B=U.bvhNeedsUpdate;if(!U.staticGenerator)c(),r&&(U.staticGenerator=new r(_),U.staticGenerator.applyWorldTransforms=!1,U.staticGeometry=U.staticGenerator.generate(),D.boundsTree=l?.call(U.staticGeometry),U.staticGeometryLastUpdate=performance.now()+Math.random()*200,U.autoUpdateMeshBVH===void 0&&(U.autoUpdateMeshBVH=!1));else if(D.boundsTree&&(U.autoUpdateMeshBVH===!0||B===!0)){const Y=performance.now(),$=Y-U.staticGeometryLastUpdate;(B||$>100)&&(U.bvhNeedsUpdate=!1,U.staticGeometryLastUpdate=Y,(M=U.staticGenerator)==null||M.generate(U.staticGeometry),D.boundsTree.refit())}}else if(!D.boundsTree){d||b();let U=!0;if((R.xr||D[y]===!1||(T=D.getAttribute("position"))!=null&&T.isInterleavedBufferAttribute||D.index&&(j=D.index)!=null&&j.isInterleavedBufferAttribute)&&(U=!1),U&&p){if(D[g]===void 0){let B=null;if(v.length>0){const Y=v.shift();Y&&!Y.running&&(B=Y)}if(!B&&f.length<3&&(B=new p,f.push(B)),B!=null&&!B.running){const Y=_.name;ki&&console.log("<<<< worker start",Y,B),D[g]="queued",performance.mark("bvh.create.start");const $=D.clone();try{B.generate($).then(E=>{D[g]="done",D.boundsTree=E}).catch(E=>{D[g]="failed - "+E?.message,D[y]=!1,ki&&console.error("Failed to generate mesh bvh on worker",E)}).finally(()=>{ki&&console.log(">>>>> worker done",Y,{hasBoundsTre:D.boundsTree!=null}),v.push(B),$.dispose(),performance.mark("bvh.create.end"),performance.measure("bvh.create (worker)","bvh.create.start","bvh.create.end")})}catch(E){console.error("Failed to generate mesh bvh on worker",E)}}else ki&&console.warn("No worker available")}}else(!u||!U)&&(c(),o&&(performance.mark("bvh.create.start"),D.boundsTree=new o(D),performance.mark("bvh.create.end"),performance.measure("bvh.create","bvh.create.start","bvh.create.end")))}if(w instanceof ud){const U=w,B=_.raycast;D.boundsTree?(c(),n&&(_.acceleratedRaycast||(_.acceleratedRaycast=n.bind(_),ki&&console.debug(`Physics: bind acceleratedRaycast fn to "${_.name}"`)),_.raycast=_.acceleratedRaycast)):ki&&console.warn("No bounds tree found for mesh",_.name,{workerTask:D[g],hasAcceleratedRaycast:n!=null});const Y=U.firstHitOnly;return U.firstHitOnly=!1,U.intersectObject(_,!1,C),U.firstHitOnly=Y,_.raycast=B,!0}else if(w instanceof dd){const U=D.boundsTree;if(U){const B=w;if(h.copy(_.matrixWorld).invert(),B.applyMatrix4(h),U.intersectsSphere(B)){const Y=te(_),$=Y.distanceTo(B.center),E=new xg(_,$,Y);C.push(E)}}return!0}return!1}s.runMeshBVHRaycast=t;let i=!1,n=null,o=null,r=null,l=null;function c(){i||(i=!0,import("./vendor.light.min.js").then(w=>w.k).then(w=>{n=w.acceleratedRaycast,o=w.MeshBVH,r=w.StaticGeometryGenerator,l=w.computeBoundsTree}).catch(w=>{(ki||F())&&console.error("Failed to load BVH library...",w.message)}))}const h=new ne;let d=!1,u=!1,p=null;const g=Symbol("Needle:MeshBVH-Worker"),y=Symbol("Needle:MeshBVH-CanUseWorker"),f=[],v=[];function b(){d=!0,u=!0,Promise.resolve().then(()=>Xj).then(w=>{p=w.GenerateMeshBVHWorker}).catch(w=>{(ki||F())&&console.warn("Failed to setup mesh bvh worker")}).finally(()=>{u=!1})}})(Ud||(Ud={}));const qb=Symbol("gltf-loader-internal-usage-tracker"),ok=O("debugusers"),Nd=class{constructor(s){a(this,"parser"),a(this,"_getDependency"),a(this,"_loadingId"),a(this,"_loadedObjects",new Set),this.parser=s,this._getDependency=this.parser.getDependency,this._loadingId=Date.now().toString()}get name(){return"NEEDLE_internal_usage_tracker"}static isLoading(s){return Nd._loadingProcesses>0}beforeRoot(){Nd._loadingProcesses++;const s=this,t=this._getDependency;return this.parser.getDependency=function(i,n){const o=t.call(this,i,n);return o.then(r=>(r&&(s._loadedObjects.add(r),r[qb]=s._loadingId),r)),o},null}afterRoot(s){Nd._loadingProcesses--,this.parser.getDependency=this._getDependency;for(const t of this._loadedObjects)delete t[qb],t instanceof I&&(t.parent||t instanceof K&&setTimeout(()=>{ok&&console.warn("> GLTF LOADER: Mesh not used in scene!",t),t.material=null,t.geometry=null},1e3));return null}};let Cg=Nd;a(Cg,"_loadingProcesses",0);class Gb{constructor(){window.addEventListener("unhandledrejection",t=>{var i;if(t.defaultPrevented)return;const n=(i=t?.reason)==null?void 0:i.path;if(n){const o=n[0];o&&o.tagName==="IMG"&&(console.warn(`Could not load image:
155
+ `+o.src),t.preventDefault())}})}}const Wd=O("trackresources");function Xb(){return Wd==="dispose"}let Sr=!0;Wd===0&&(Sr=!1);function rk(s){Sr=s}function Qb(){return Sr}const Yb=Symbol("disposable");function Og(s,t){s&&(s[Yb]=t,Cr&&console.warn("Set disposable",t,s))}const Kb=Symbol("disposed");function ak(s){return s[Kb]===!0}function Ee(s){var t;if(s){if(s[Yb]===!1){Cr&&console.warn("Object is marked as not disposable",s);return}if(s[Kb]=!0,s instanceof qi)Ee(s.environment),Ee(s.background),Ee(s.customDepthMaterial),Ee(s.customDistanceMaterial);else if(s instanceof _n)Ee(s.geometry),Ee(s.material),Ee(s.skeleton),Ee(s.bindMatrix),Ee(s.bindMatrixInverse),Ee(s.customDepthMaterial),Ee(s.customDistanceMaterial),s.geometry=null,s.material=null,s.visible=!1;else if(s instanceof K)Ee(s.geometry),Ee(s.material),Ee(s.customDepthMaterial),Ee(s.customDistanceMaterial),s.geometry=null,s.material=null,s.visible=!1;else if(s instanceof bn){Ia(s);for(const i of Object.keys(s.attributes)){const n=s.attributes[i];Ee(n)}}else if(s instanceof ft||s instanceof Qy)Cr&&console.warn("BufferAttribute dispose not supported",s.count);else if(s instanceof Array)for(const i of s)i instanceof ke&&Ee(i);else if(s instanceof ke){Ia(s);for(const n of Object.keys(s)){const o=s[n];o instanceof Le&&(Ee(o),s[n]=null)}const i=s.uniforms;if(i)for(const n of Object.keys(i)){const o=i[n];o instanceof Le?(Ee(o),i[n]=null):o instanceof so&&(Ee(o.value),o.value=null)}}else s instanceof Le?(Ia(s),Ia(s.source),((t=s.source)==null?void 0:t.data)instanceof ImageBitmap&&Ia(s.source.data)):s instanceof vS?(Ia(s.boneTexture),s.boneTexture=null):s instanceof bS||!(s instanceof I)&&Cr&&console.warn("Unknown object type",s)}}function Ia(s){s&&((Cr||Xb()||Wd)&&console.warn("\u{1F9E8} FREE",s),s instanceof ImageBitmap?s.close():s instanceof _S?s.data=null:s.dispose())}function Zb(s){(s instanceof K||s instanceof _n)&&(s.material=null,s.geometry=null)}const lk=new Set;function Pg(s,t,i=null,n){if(n||(n=lk,n.clear()),!s)return n;const o=s[fc];if(o)for(const r of o)n.has(r)||i?.call(null,r)!==!1&&(n.add(r),t&&Pg(r,!0,i,n));return n}function ck(s){return s[yc]}const Cr=O("debugresourceusers")||O("debugmemory"),fc=Symbol("needle-resource-users"),yc=Symbol("needle-resource-users-count");function Xt(s,t){Td(s,t,function(i,n){Sr&&!Fd.raycasting&&(Vd(fc,this,i,!1),Vd(fc,this,n,!0))})}Sr&&(Xt(K.prototype,"material"),Xt(K.prototype,"geometry"),Xt(ke.prototype,"map"),Xt(ke.prototype,"bumpMap"),Xt(ke.prototype,"alphaMap"),Xt(ke.prototype,"normalMap"),Xt(ke.prototype,"displacementMap"),Xt(ke.prototype,"roughnessMap"),Xt(ke.prototype,"metalnessMap"),Xt(ke.prototype,"emissiveMap"),Xt(ke.prototype,"specularMap"),Xt(ke.prototype,"envMap"),Xt(ke.prototype,"lightMap"),Xt(ke.prototype,"aoMap"),Xt(ke.prototype,"gradientMap"));function hk(s){if(Sr===!1)return;const t=s[fc];if(t)for(const i of t)Vd(fc,i,s,!1)}Sr&&Td(ke.prototype,"dispose",function(){hk(this)});let kg=0;function Vd(s,t,i,n){if(kg>0)return;if(Array.isArray(i)){for(const r of i)Vd(s,t,r,n);return}if(!i)return;let o=i[s];if(o||(o=new Set),n){if(t&&!o.has(t)){o.add(t);let r=i[yc]||0;r+=1,i[yc]=r,Cr&&console.warn(`\u{1F7E2} Added user of "${i.type}"`,t,i,r,"users:",o)}}else if(t&&o.has(t)){o.delete(t);let r=i[yc]||0;r>0&&(r-=1,i[yc]=r),Cr&&console.warn(`\u{1F534} Removed user of "${i.type}"`,t,i,r,"users:",o),r<=0&&(Cg.isLoading(i)||(Wd&&console.warn(`\u{1F534} Removed all user of "${i.type}"`,i),Xb()&&Ee(i)))}i[s]=o}try{Td(ur.prototype,"render",function(){kg++},function(){kg--})}catch(s){console.warn("Could not wrap WebGLRenderer.render",s)}const Jb=O("debugcomponentevents");class vc{static addComponentLifecylceEventListener(t,i){this.eventListeners.has(t)&&this.eventListeners.set(t,[]);let n=this.eventListeners.get(t);n||(n=[]),n.push(i),this.eventListeners.set(t,n),Jb&&console.log("Added event listener for "+t,this.eventListeners)}static removeComponentLifecylceEventListener(t,i){const n=this.eventListeners.get(t);if(!n)return;const o=n.indexOf(i);o<0||n.splice(o,1)}static dispatchComponentLifecycleEvent(t,i){const n=this.eventListeners.get(t);if(Jb&&console.log("Dispatching event "+t,n),!!n)for(const o of n)o(i)}}a(vc,"eventListeners",new Map);const bc=Symbol("NEEDLE_NEED_UPDATE_INSTANCE"),e_=Symbol("isUsingInstancing"),t_=Symbol("instancingRenderer"),_c=Symbol("instancingAutoUpdateBounds");class cs{static isUsingInstancing(t){return t[e_]===!0}static getRenderer(t){return t[t_]||null}setAutoUpdateBounds(t,i){const n=cs.getRenderer(t);n&&(n[_c]=i)}static markDirty(t,i=!0){if(t&&(this.isUsingInstancing(t)&&(t[bc]=!0,t.matrixWorldNeedsUpdate=!0),i))for(const n of t.children)cs.markDirty(n,!0)}}function ja(s,t){try{t?s(t):s()}catch(i){return console.error(i),!1}return!0}const Mg=O("debugnewscripts"),dk=O("debughierarchy"),Fe=[];function uk(){return Fe.length>0}function Hd(s){if(!(s.new_scripts.length<=0)){if(Mg&&console.log("Register new components",s.new_scripts.length,[...s.new_scripts],s.alias?"element: "+s.alias:s.hash,s),s.new_scripts_pre_setup_callbacks.length>0){for(const t of s.new_scripts_pre_setup_callbacks)t&&t();s.new_scripts_pre_setup_callbacks.length=0}Fe.length=0,s.new_scripts.length>0&&Fe.push(...s.new_scripts),s.new_scripts.length=0;for(let t=0;t<Fe.length;t++)try{const i=Fe[t];if(i.isComponent!==!0){(F()||Mg)&&console.error(`Registered script is not a Needle Engine component.
156
156
  The script will be ignored. Please make sure your component extends "Behaviour" imported from "@needle-tools/engine"
157
157
  `,i),Fe.splice(t,1),t--;continue}if(i.destroyed)continue;if(!i.gameObject){console.warn(`Component can not be initialized: no GameObject assigned.
158
- Did you add and remove a component in the same frame?`),Fe.splice(t,1),t--;continue}i.context=s,wc(i.gameObject),Rg(i,s)}catch(i){console.error(i),kn(Fe[t],s),Fe.splice(t,1),t--}for(let t=0;t<Fe.length;t++)try{const i=Fe[t];if(i.destroyed){kn(Fe[t],s),Fe.splice(t,1),t--;continue}if(i.registering)try{i.registering()}catch(n){console.error(n)}i.__internalAwake!==void 0&&(i.gameObject||console.error("Calling awake for a component without a GameObject",i,i.gameObject),wc(i.gameObject),i.activeAndEnabled&&ja(i.__internalAwake.bind(i)))}catch(i){console.error(i),kn(Fe[t],s),Fe.splice(t,1),t--}for(let t=0;t<Fe.length;t++)try{const i=Fe[t];if(i.destroyed||i.enabled===!1||(wc(i.gameObject),i.activeAndEnabled===!1))continue;i.__internalEnable!==void 0&&(i.enabled=!0,ja(i.__internalEnable.bind(i)))}catch(i){console.error(i),kn(Fe[t],s),Fe.splice(t,1),t--}for(let t=0;t<Fe.length;t++)try{const i=Fe[t];if(i.destroyed||!i.gameObject)continue;s.new_script_start.push(i)}catch(i){console.error(i),kn(Fe[t],s),Fe.splice(t,1),t--}Fe.length=0;for(const t of s.new_scripts_post_setup_callbacks)t&&t();s.new_scripts_post_setup_callbacks.length=0}}function p2(s){s&&(s.__internalDisable(!0),kn(s,s.context))}function i_(s,t){for(let i=0;i<s.new_script_start.length;i++)try{const n=s.new_script_start[i];if(t!==void 0&&n.gameObject!==t||n.destroyed||n.activeAndEnabled===!1)continue;ja(n.__internalAwake.bind(n)),n.enabled&&(ja(n.__internalEnable.bind(n)),ja(n.__internalStart.bind(n)),s.new_script_start.splice(i,1),i--)}catch(n){console.error(n),kn(s.new_script_start[i],s),s.new_script_start.splice(i,1),i--}}function Rg(s,t){t.scripts.indexOf(s)===-1&&(t.scripts.push(s),s.earlyUpdate&&t.scripts_earlyUpdate.push(s),s.update&&t.scripts_update.push(s),s.lateUpdate&&t.scripts_lateUpdate.push(s),s.onBeforeRender&&t.scripts_onBeforeRender.push(s),s.onAfterRender&&t.scripts_onAfterRender.push(s),s.onPausedChanged&&t.scripts_pausedChanged.push(s),Tg(s,null)&&t.new_scripts_xr.push(s),Tg(s,"immersive-vr")&&t.scripts_immersive_vr.push(s),Tg(s,"immersive-ar")&&t.scripts_immersive_ar.push(s))}function kn(s,t){Ki(s,t.new_scripts),Ki(s,t.new_script_start),Ki(s,t.scripts),Ki(s,t.scripts_earlyUpdate),Ki(s,t.scripts_update),Ki(s,t.scripts_lateUpdate),Ki(s,t.scripts_onBeforeRender),Ki(s,t.scripts_onAfterRender),Ki(s,t.scripts_pausedChanged),Ki(s,t.new_scripts_xr),Ki(s,t.scripts_immersive_vr),Ki(s,t.scripts_immersive_ar),t.stopAllCoroutinesFrom(s)}function Ki(s,t){const i=t.indexOf(s);i>=0&&t.splice(i,1)}function Tg(s,t){var i;if(s){const n=s;if(n.onBeforeXR||n.onEnterXR||n.onUpdateXR||n.onLeaveXR||n.onXRControllerAdded||n.onXRControllerRemoved)return!(t!=null&&((i=n.supportsXR)==null?void 0:i.call(n,t))===!1)}return!1}function $d(s){if(s||(s=ge.Current.scene),!s){console.trace("Invalid call - no current context.");return}const t=Fa(s);s_(s,t,!0)||(Mg||F()?console.error(`Error updating hierarchy
159
- Do you have circular references in your project? <a target="_blank" href="https://docs.needle.tools/circular-reference"> Click here for more information.`,s):console.error('Failed to update active state in hierarchy of "'+s.name+'"',s),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 s_(s,t,i,n=0){if(n>1e3)return console.warn("Hierarchy is too deep (> 1000 level) - will abort updating active state"),!1;const o=Fa(s);if(t&&(t=o,t&&s.parent)){const c=s.parent;t=c[Sn],t===void 0&&(c instanceof qi||(t=!0))}const r=s[Sn]!==t;s[Sn]=t,r&&(d2&&console.warn("ACTIVE CHANGE",s.name,o,s.visible,t,"changed?"+r,s),i&&m2(s,c=>{t?c.enabled&&(ja(c.__internalAwake.bind(c)),c.enabled&&(c.__didEnable=!0,c.onEnable())):c.__didAwake&&c.enabled&&(c.__didEnable=!1,c.onDisable())}));let l=!0;if(s.children){const c=n+1;for(const h of s.children)s_(h,t,i,c)===!1&&(l=!1)}return l}function wc(s){let t=!0,i=s,n=!1;for(;i&&i;){if(i.type==="Scene"&&(n=!0),!Fa(i)){t=!1;break}i=i.parent}if(!s){console.error("GO is null");return}s[Sn]=t&&n}function m2(s,t){var i;if((i=s.userData)!=null&&i.components)for(const n of s.userData.components)t(n)}const qd=new Map,n_=Symbol("prewarmFlag"),Eg=Symbol("waitingForPrewarm"),Ag=O("debugprewarm");function g2(s,t){!s||s[n_]===!0||s[Eg]===!0||(qd.has(t)||qd.set(t,[]),s[Eg]=!0,qd.get(t).push(s),Ag&&console.debug("register prewarm",s.name))}let Ig=null,jg=null;function f2(s){if(!s)return;const t=qd.get(s);if(!(t!=null&&t.length))return;const i=s.mainCamera;if(i){Ag&&console.log("prewarm",t.length,"objects",[...t]);const n=s.renderer;if(n.compile){const o=s.scene;n.compile(o,i),Ig??(Ig=new wS(64)),jg??(jg=new xS(.001,9999999,Ig)),jg.update(n,o);for(const r of t)r[n_]=!0,r[Eg]=!1;t.length=0,Ag&&console.log("prewarm done")}}}ge.registerCallback(ye.ContextCreated,s=>{const t=s.context;h_(t),a_(t)});const Gd=O("debugcomponents"),o_="eff8ba80-635d-11ec-90d6-0242ac120003";class zt{constructor(t){a(this,"_originalSeed"),a(this,"_seed"),typeof t=="string"&&(t=zt.hash(t)),this._originalSeed=t,this._seed=t}get seed(){return this._seed}set seed(t){this._seed=t}reset(){this._seed=this._originalSeed}generateUUID(t){if(typeof t=="string")return uv(t,o_);const i=this._seed;return this._seed-=1,uv(i.toString(),o_)}initialize(t){typeof t=="string"?this._seed=zt.hash(t):this._seed=t}static createFromString(t){return new zt(this.hash(t))}static hash(t){let i=0;for(let n=0;n<t.length;n++)i=t.charCodeAt(n)+((i<<5)-i);return i}}var r_=(s=>(s.NewInstanceCreated="new-instance-created",s.InstanceDestroyed="instance-destroyed",s))(r_||{});class y2{constructor(t){a(this,"guid"),a(this,"dontSave"),this.guid=t}}function xc(s,t,i=!0,n){if(!s)return;const o=s;if(Ri(s,i),!t){console.warn("Can not send destroy: No networking connection provided",s.guid);return}if(!t.isConnected){F()&&console.debug("Can not send destroy: not connected",s.guid);return}let r=s.guid;if(!r&&o.uuid&&(r=o.uuid),!r){console.warn("Can not send destroy: failed to find guid",s);return}Lg(r,t,n)}function Lg(s,t,i){const n=new y2(s);i?.saveInRoom===!1&&(n.dontSave=!0),t.send("instance-destroyed",n,ws.Queued)}function a_(s){s.connection.beginListen("instance-destroyed",t=>{Gd&&console.log("[Remote] Destroyed",s.scene,t);const i=qg(t.guid,s.scene);i&&Ri(i)})}class v2{constructor(t,i,n){a(this,"filename"),a(this,"hash"),a(this,"size"),this.filename=t,this.hash=i,this.size=n}}class l_{constructor(t,i){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=t,this.guid=i}}function Dg(s,t,i,n){var o,r;const l=s;if(!l.guid)return console.warn("Can not instantiate: No guid",l),null;if(t.context||(t.context=ee.Current),!t.context)return console.error("Missing network instantiate options / reference to network connection in sync instantiate"),null;const c=t?{...t}:null,{instance:h,seed:d}=b2(l,t);if(h){const u=h;if(u.guid){Gd&&console.log("[Local] new instance","gameobject:",h?.guid);const p=new l_(l.guid,u.guid);p.seed=d,t.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=i,n===!1&&(p.dontSave=!0),!((o=t?.context)!=null&&o.connection)&&F()&&console.debug("Object will be instantiated but it will not be synced: not connected",l.guid),t.context.connection.isInRoom&&La.push(new WeakRef(u)),(r=t?.context)==null||r.connection.send("new-instance-created",p)}else console.warn("Missing guid, can not send new instance event",u)}return h}function c_(){return Math.random()*9999999}const La=new Array;function h_(s){s.connection.beginListen("new-instance-created",async t=>{const i=await _2(t.originalGuid,s.scene);if(t.preventCreation===!0)return;if(!i){console.warn("could not find object that was instantiated: "+t.guid);return}const n=new Ds;t.position&&(n.position=new x(t.position.x,t.position.y,t.position.z)),t.rotation&&(n.rotation=new V(t.rotation.x,t.rotation.y,t.rotation.z,t.rotation.w)),t.scale&&(n.scale=new x(t.scale.x,t.scale.y,t.scale.z)),n.parent=t.parent,t.seed&&(n.idProvider=new zt(t.seed)),n.visible=t.visible,n.context=s,Gd&&s.alias&&console.log("[Remote] instantiate in: "+s.alias);const o=Ua(i,n);La.push(new WeakRef(o)),o&&(t.parent==="scene"&&s.scene.add(o),Gd&&console.log("[Remote] new instance","gameobject:",o?.guid,i))}),s.connection.beginListen("left-room",()=>{La.length>0&&console.debug(`Left networking room, cleaning up ${La.length} instantiated objects`);for(const t of La){const i=t.deref();i&&i.destroy()}La.length=0})}function b2(s,t){const i=c_(),n=t??new Ds;n.idProvider=new zt(i);const o=Ua(s,n);return{seed:i,instance:o}}const d_={};function u_(s,t){d_[s]=t}async function _2(s,t){const i=d_[s];if(i!=null){const n=await i(s);if(n)return n}return p_(s,t)}function p_(s,t){if(t===null||!s)return null;if(t.guid===s)return t;if(t.children)for(const i of t.children){const n=p_(s,i);if(n)return n}return null}const Sc=O("gizmos"),vt=O("debugextension"),Bg=O("debugtypes");class w2{constructor(){a(this,"_types",new Map),Bg&&console.warn("TypeStore: Created",this)}add(t,i){Bg&&console.warn("ADD TYPE",t);const n=this._types.get(t);n?Bg&&n!==i&&console.warn("Type name exists multiple times in your project and may lead to runtime errors:",t):this._types.set(t,i)}get(t){return this._types.get(t)||null}getKey(t){for(const[i,n]of this._types)if(n===t)return i;return null}}const x2=Symbol("BuiltInType"),S=new w2,S2=function(s){S.get(s.name)||S.add(s.name,s)},Fg=O("debugresolvedependencies"),C2=["/extensions/","extensions/"],O2=[{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 zg(s,t){Fg&&console.log(s,t);const i=[];Ug(O2,s,t,i);const n=await Promise.all(i);return typeof t=="string"&&n.length===1?n[0]:n}function m_(s,t){return!s||!t?!1:s["needle:identifier"]!=null&&t["needle:identifier"]!=null?s["needle:identifier"]===t["needle:identifier"]:!1}function P2(s,t){s["needle:identifier"]=t}function Ug(s,t,i,n){if(typeof i=="object"&&i!==void 0&&i!==null)for(const o of Object.keys(i)){const r=i[o];if(typeof r=="string"){const l=g_(t,r);if(l!=null)typeof l.then=="function"?n.push(l.then(c=>i[o]=c)):i[o]=l;else{const c=f_(s,t,r);if(c){n.push(c.then(h=>(i[o]=h,h)));continue}}}else if(Array.isArray(r))for(let l=0;l<r.length;l++){const c=r[l],h=g_(t,c);if(h!==null){typeof h.then=="function"?n.push(h.then(d=>r[l]=d)):r[l]=h;continue}for(const d of s){const u=y_(d.prefix,c);if(u>=0){Fg&&console.log(d,u,d.dependencyName),n.push(t.getDependency(d.dependencyName,u).then(p=>r[l]=p));break}}typeof c=="object"&&Ug(s,t,c,n)}else typeof r=="object"&&Ug(s,t,r,n)}else if(typeof i=="string"){const o=f_(s,t,i);o&&n.push(o)}}function g_(s,t){if(s&&s.plugins&&typeof t=="string"){for(const i of C2)if(t.startsWith(i)){let n=t.substring(i.length);const o=n.indexOf("/");o>=0&&(n=n.substring(0,o));const r=s.plugins[n];if(vt&&console.log(n,r),typeof r?.resolve=="function"){const l=t.substring(i.length+n.length+1);return r.resolve(s,l)}break}}return null}function f_(s,t,i){for(const n of s){const o=y_(n.prefix,i);if(o>=0)return Fg&&console.warn("GET DEPENDENCY",n,o,n.dependencyName),t.getDependency(n.dependencyName,o)}return null}function y_(s,t){if(typeof t=="string"&&t.startsWith(s)){const i=t.substring(s.length),n=Number.parseInt(i);if(n>=0)return n}return-1}const Ng="NEEDLE_persistent_assets";function k2(s){return s?.___persistentAsset===!0}class M2{constructor(t){a(this,"parser"),this.parser=t}get name(){return Ng}async afterRoot(t){var i,n;if(!((n=(i=this.parser)==null?void 0:i.json)!=null&&n.extensions))return;const o=this.parser.json.extensions[Ng];if(!o)return;vt&&console.log(o);const r=new Array;for(const l of o?.assets){const c=zg(this.parser,l);c&&r.push(c)}await Promise.all(r)}resolve(t,i){const n=Number.parseInt(i);if(n>=0){vt&&console.log(i);const o=t.json.extensions[Ng];if(o){const r=o?.assets[n];if(r&&typeof r=="object"){r.___persistentAsset=!0;const l=r.__type;l&&S.get(l)}return r}}return null}}const Vs=O("debugserializer");class R2{constructor(){a(this,"typeMap",new Map)}register(t,i){if(this.typeMap.has(t)){const n=this.typeMap.get(t);if(n===i)return;Vs&&console.warn("Type: "+t+" is already registered",i,n)}Vs&&console.log("Register type serializer",i.name,i,t),this.typeMap.set(t,i)}getSerializer(t){if(t)return this.typeMap.get(t)}getSerializerForConstructor(t,i=0){if(i>20)return;if(!t||!t.constructor){Vs&&console.log("invalid type");return}const n=t.name,o=this.getSerializer(t);if(o!==void 0)return Vs&&console.log("FOUND SERIALIZER",o?.name,t.name,t.constructor.name,"for type: "+n,o,t,this.typeMap),o;const r=Object.getPrototypeOf(t);if(r&&r!==t){const l=this.getSerializerForConstructor(r,++i);if(l){const c=r.constructor||r.prototype;Vs&&console.log("FOUND SERIALIZER(in constructor) "+c.constructor.name,c.name,c,l),this.register(c,l)}return l}Vs&&console.warn("No serializer found for "+n,t,t.name,t.constructor.name)}}const Xd=new R2;class Zi{constructor(t,i){if(a(this,"name"),this.name=i,Array.isArray(t))for(const n of t)Xd.register(n,this);else Xd.register(t,this)}}class T2{constructor(){a(this,"isDevMode",Gt()),a(this,"cache",{})}registerDefinedKeys(t,i){if(this.isDevMode&&this.cache[t]===void 0){this.cache[t]=Object.keys(i);const n=i;n.$serializedTypes&&Object.keys(n.$serializedTypes)&&this.cache[t].push(...Object.keys(n.$serializedTypes)),Vs&&console.log("registerDefinedKeys for "+t,this.cache[t],i)}}getDefinedKey(t,i){return this.cache[t]===void 0?!1:this.cache[t].includes(i)}}class Wg{constructor(t){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=t}}function v_(s,t){const i=s.$serializedTypes;if(i===void 0)return null;const n={};for(const r in i){const l=s[r];if(l!=null&&typeof l=="object"){const c=Xd.getSerializerForConstructor(l);if(c){n[r]=c.onSerialize(l,t);continue}}n[r]=l}function o(r){const l=S._types;for(const[c,h]of l)if(h===s.constructor)return c;return r.__name||r.constructor.name}return n.name=o(s),typeof s.guid=="string"&&(n.guid=s.guid),n}const Qd=[];function b_(s,t){if(!s)return t;typeof s.$serializedTypes=="object"&&(t||(t={}),Object.assign(t,s.$serializedTypes));const i=Object.getPrototypeOf(s);return b_(i,t)}function Yd(s,t,i){if(!s)return!1;if(i.target=s,s.onBeforeDeserialize!==void 0){const o=s.onBeforeDeserialize(t,i);if(typeof o=="boolean")return o}const n=b_(s);if(t){if(typeof t.guid=="string"&&(s.guid=t.guid),n)for(const o in n){let r=function(h){const d=h.type;return d?Vg(c,d,i,void 0,s[o]):Vg(c,h,i,void 0,s[o])};const l=n[o],c=t[o];if(Vs&&console.log(o,c,s,l),!(s[o]!==void 0&&c===void 0)&&(i.type=void 0,i.path=o,i.serializable=l,!(s.onBeforeDeserializeMember!==void 0&&s.onBeforeDeserializeMember(o,c,i)===!0))){if(l===null)s[o]=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){s[o]=u;break}}else s[o]=r(l);Qd.length=0}s.onAfterDeserializeMember!==void 0&&s.onAfterDeserializeMember(o,c,i)}}I2(s,t)}return A2(s,t,i.implementationInformation),s.onAfterDeserialize!==void 0&&s.onAfterDeserialize(t,i),!0}const E2=O("noerrors");function A2(s,t,i){var n,o;if(E2||!t||!Gt()||!s||s.constructor&&s.constructor[x2]===!0)return;const r=(n=s.constructor)==null?void 0:n.name,l=Object.getOwnPropertyNames(t);for(const c of l){if(c==="sourceId")continue;const h=s[c];if(h==null)continue;const d=t[c];if(i?.getDefinedKey(r,c)===!1){const u=c.charAt(0).toUpperCase()+c.slice(1);i.getDefinedKey(r,u)&&(zs(Ci.Warn,'<strong>Please rename</strong> "'+u+'" to "'+c+'" in '+r),console.warn('Please use lowercase for field: "'+u+'" in '+r,d,s));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)){zs(Ci.Warn,`<strong>Missing serialization for object reference!</strong>
158
+ Did you add and remove a component in the same frame?`),Fe.splice(t,1),t--;continue}i.context=s,wc(i.gameObject),Rg(i,s)}catch(i){console.error(i),kn(Fe[t],s),Fe.splice(t,1),t--}for(let t=0;t<Fe.length;t++)try{const i=Fe[t];if(i.destroyed){kn(Fe[t],s),Fe.splice(t,1),t--;continue}if(i.registering)try{i.registering()}catch(n){console.error(n)}i.__internalAwake!==void 0&&(i.gameObject||console.error("Calling awake for a component without a GameObject",i,i.gameObject),wc(i.gameObject),i.activeAndEnabled&&ja(i.__internalAwake.bind(i)))}catch(i){console.error(i),kn(Fe[t],s),Fe.splice(t,1),t--}for(let t=0;t<Fe.length;t++)try{const i=Fe[t];if(i.destroyed||i.enabled===!1||(wc(i.gameObject),i.activeAndEnabled===!1))continue;i.__internalEnable!==void 0&&(i.enabled=!0,ja(i.__internalEnable.bind(i)))}catch(i){console.error(i),kn(Fe[t],s),Fe.splice(t,1),t--}for(let t=0;t<Fe.length;t++)try{const i=Fe[t];if(i.destroyed||!i.gameObject)continue;s.new_script_start.push(i)}catch(i){console.error(i),kn(Fe[t],s),Fe.splice(t,1),t--}Fe.length=0;for(const t of s.new_scripts_post_setup_callbacks)t&&t();s.new_scripts_post_setup_callbacks.length=0}}function pk(s){s&&(s.__internalDisable(!0),kn(s,s.context))}function i_(s,t){for(let i=0;i<s.new_script_start.length;i++)try{const n=s.new_script_start[i];if(t!==void 0&&n.gameObject!==t||n.destroyed||n.activeAndEnabled===!1)continue;ja(n.__internalAwake.bind(n)),n.enabled&&(ja(n.__internalEnable.bind(n)),ja(n.__internalStart.bind(n)),s.new_script_start.splice(i,1),i--)}catch(n){console.error(n),kn(s.new_script_start[i],s),s.new_script_start.splice(i,1),i--}}function Rg(s,t){t.scripts.indexOf(s)===-1&&(t.scripts.push(s),s.earlyUpdate&&t.scripts_earlyUpdate.push(s),s.update&&t.scripts_update.push(s),s.lateUpdate&&t.scripts_lateUpdate.push(s),s.onBeforeRender&&t.scripts_onBeforeRender.push(s),s.onAfterRender&&t.scripts_onAfterRender.push(s),s.onPausedChanged&&t.scripts_pausedChanged.push(s),Tg(s,null)&&t.new_scripts_xr.push(s),Tg(s,"immersive-vr")&&t.scripts_immersive_vr.push(s),Tg(s,"immersive-ar")&&t.scripts_immersive_ar.push(s))}function kn(s,t){Ki(s,t.new_scripts),Ki(s,t.new_script_start),Ki(s,t.scripts),Ki(s,t.scripts_earlyUpdate),Ki(s,t.scripts_update),Ki(s,t.scripts_lateUpdate),Ki(s,t.scripts_onBeforeRender),Ki(s,t.scripts_onAfterRender),Ki(s,t.scripts_pausedChanged),Ki(s,t.new_scripts_xr),Ki(s,t.scripts_immersive_vr),Ki(s,t.scripts_immersive_ar),t.stopAllCoroutinesFrom(s)}function Ki(s,t){const i=t.indexOf(s);i>=0&&t.splice(i,1)}function Tg(s,t){var i;if(s){const n=s;if(n.onBeforeXR||n.onEnterXR||n.onUpdateXR||n.onLeaveXR||n.onXRControllerAdded||n.onXRControllerRemoved)return!(t!=null&&((i=n.supportsXR)==null?void 0:i.call(n,t))===!1)}return!1}function $d(s){if(s||(s=ge.Current.scene),!s){console.trace("Invalid call - no current context.");return}const t=Fa(s);s_(s,t,!0)||(Mg||F()?console.error(`Error updating hierarchy
159
+ Do you have circular references in your project? <a target="_blank" href="https://docs.needle.tools/circular-reference"> Click here for more information.`,s):console.error('Failed to update active state in hierarchy of "'+s.name+'"',s),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 s_(s,t,i,n=0){if(n>1e3)return console.warn("Hierarchy is too deep (> 1000 level) - will abort updating active state"),!1;const o=Fa(s);if(t&&(t=o,t&&s.parent)){const c=s.parent;t=c[Sn],t===void 0&&(c instanceof qi||(t=!0))}const r=s[Sn]!==t;s[Sn]=t,r&&(dk&&console.warn("ACTIVE CHANGE",s.name,o,s.visible,t,"changed?"+r,s),i&&mk(s,c=>{t?c.enabled&&(ja(c.__internalAwake.bind(c)),c.enabled&&(c.__didEnable=!0,c.onEnable())):c.__didAwake&&c.enabled&&(c.__didEnable=!1,c.onDisable())}));let l=!0;if(s.children){const c=n+1;for(const h of s.children)s_(h,t,i,c)===!1&&(l=!1)}return l}function wc(s){let t=!0,i=s,n=!1;for(;i&&i;){if(i.type==="Scene"&&(n=!0),!Fa(i)){t=!1;break}i=i.parent}if(!s){console.error("GO is null");return}s[Sn]=t&&n}function mk(s,t){var i;if((i=s.userData)!=null&&i.components)for(const n of s.userData.components)t(n)}const qd=new Map,n_=Symbol("prewarmFlag"),Eg=Symbol("waitingForPrewarm"),Ag=O("debugprewarm");function gk(s,t){!s||s[n_]===!0||s[Eg]===!0||(qd.has(t)||qd.set(t,[]),s[Eg]=!0,qd.get(t).push(s),Ag&&console.debug("register prewarm",s.name))}let Ig=null,jg=null;function fk(s){if(!s)return;const t=qd.get(s);if(!(t!=null&&t.length))return;const i=s.mainCamera;if(i){Ag&&console.log("prewarm",t.length,"objects",[...t]);const n=s.renderer;if(n.compile){const o=s.scene;n.compile(o,i),Ig??(Ig=new wS(64)),jg??(jg=new xS(.001,9999999,Ig)),jg.update(n,o);for(const r of t)r[n_]=!0,r[Eg]=!1;t.length=0,Ag&&console.log("prewarm done")}}}ge.registerCallback(ye.ContextCreated,s=>{const t=s.context;h_(t),a_(t)});const Gd=O("debugcomponents"),o_="eff8ba80-635d-11ec-90d6-0242ac120003";class zt{constructor(t){a(this,"_originalSeed"),a(this,"_seed"),typeof t=="string"&&(t=zt.hash(t)),this._originalSeed=t,this._seed=t}get seed(){return this._seed}set seed(t){this._seed=t}reset(){this._seed=this._originalSeed}generateUUID(t){if(typeof t=="string")return uv(t,o_);const i=this._seed;return this._seed-=1,uv(i.toString(),o_)}initialize(t){typeof t=="string"?this._seed=zt.hash(t):this._seed=t}static createFromString(t){return new zt(this.hash(t))}static hash(t){let i=0;for(let n=0;n<t.length;n++)i=t.charCodeAt(n)+((i<<5)-i);return i}}var r_=(s=>(s.NewInstanceCreated="new-instance-created",s.InstanceDestroyed="instance-destroyed",s))(r_||{});class yk{constructor(t){a(this,"guid"),a(this,"dontSave"),this.guid=t}}function xc(s,t,i=!0,n){if(!s)return;const o=s;if(Ri(s,i),!t){console.warn("Can not send destroy: No networking connection provided",s.guid);return}if(!t.isConnected){F()&&console.debug("Can not send destroy: not connected",s.guid);return}let r=s.guid;if(!r&&o.uuid&&(r=o.uuid),!r){console.warn("Can not send destroy: failed to find guid",s);return}Lg(r,t,n)}function Lg(s,t,i){const n=new yk(s);i?.saveInRoom===!1&&(n.dontSave=!0),t.send("instance-destroyed",n,ws.Queued)}function a_(s){s.connection.beginListen("instance-destroyed",t=>{Gd&&console.log("[Remote] Destroyed",s.scene,t);const i=qg(t.guid,s.scene);i&&Ri(i)})}class vk{constructor(t,i,n){a(this,"filename"),a(this,"hash"),a(this,"size"),this.filename=t,this.hash=i,this.size=n}}class l_{constructor(t,i){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=t,this.guid=i}}function Dg(s,t,i,n){var o,r;const l=s;if(!l.guid)return console.warn("Can not instantiate: No guid",l),null;if(t.context||(t.context=ee.Current),!t.context)return console.error("Missing network instantiate options / reference to network connection in sync instantiate"),null;const c=t?{...t}:null,{instance:h,seed:d}=bk(l,t);if(h){const u=h;if(u.guid){Gd&&console.log("[Local] new instance","gameobject:",h?.guid);const p=new l_(l.guid,u.guid);p.seed=d,t.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=i,n===!1&&(p.dontSave=!0),!((o=t?.context)!=null&&o.connection)&&F()&&console.debug("Object will be instantiated but it will not be synced: not connected",l.guid),t.context.connection.isInRoom&&La.push(new WeakRef(u)),(r=t?.context)==null||r.connection.send("new-instance-created",p)}else console.warn("Missing guid, can not send new instance event",u)}return h}function c_(){return Math.random()*9999999}const La=new Array;function h_(s){s.connection.beginListen("new-instance-created",async t=>{const i=await _k(t.originalGuid,s.scene);if(t.preventCreation===!0)return;if(!i){console.warn("could not find object that was instantiated: "+t.guid);return}const n=new Ds;t.position&&(n.position=new x(t.position.x,t.position.y,t.position.z)),t.rotation&&(n.rotation=new V(t.rotation.x,t.rotation.y,t.rotation.z,t.rotation.w)),t.scale&&(n.scale=new x(t.scale.x,t.scale.y,t.scale.z)),n.parent=t.parent,t.seed&&(n.idProvider=new zt(t.seed)),n.visible=t.visible,n.context=s,Gd&&s.alias&&console.log("[Remote] instantiate in: "+s.alias);const o=Ua(i,n);La.push(new WeakRef(o)),o&&(t.parent==="scene"&&s.scene.add(o),Gd&&console.log("[Remote] new instance","gameobject:",o?.guid,i))}),s.connection.beginListen("left-room",()=>{La.length>0&&console.debug(`Left networking room, cleaning up ${La.length} instantiated objects`);for(const t of La){const i=t.deref();i&&i.destroy()}La.length=0})}function bk(s,t){const i=c_(),n=t??new Ds;n.idProvider=new zt(i);const o=Ua(s,n);return{seed:i,instance:o}}const d_={};function u_(s,t){d_[s]=t}async function _k(s,t){const i=d_[s];if(i!=null){const n=await i(s);if(n)return n}return p_(s,t)}function p_(s,t){if(t===null||!s)return null;if(t.guid===s)return t;if(t.children)for(const i of t.children){const n=p_(s,i);if(n)return n}return null}const Sc=O("gizmos"),vt=O("debugextension"),Bg=O("debugtypes");class wk{constructor(){a(this,"_types",new Map),Bg&&console.warn("TypeStore: Created",this)}add(t,i){Bg&&console.warn("ADD TYPE",t);const n=this._types.get(t);n?Bg&&n!==i&&console.warn("Type name exists multiple times in your project and may lead to runtime errors:",t):this._types.set(t,i)}get(t){return this._types.get(t)||null}getKey(t){for(const[i,n]of this._types)if(n===t)return i;return null}}const xk=Symbol("BuiltInType"),S=new wk,Sk=function(s){S.get(s.name)||S.add(s.name,s)},Fg=O("debugresolvedependencies"),Ck=["/extensions/","extensions/"],Ok=[{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 zg(s,t){Fg&&console.log(s,t);const i=[];Ug(Ok,s,t,i);const n=await Promise.all(i);return typeof t=="string"&&n.length===1?n[0]:n}function m_(s,t){return!s||!t?!1:s["needle:identifier"]!=null&&t["needle:identifier"]!=null?s["needle:identifier"]===t["needle:identifier"]:!1}function Pk(s,t){s["needle:identifier"]=t}function Ug(s,t,i,n){if(typeof i=="object"&&i!==void 0&&i!==null)for(const o of Object.keys(i)){const r=i[o];if(typeof r=="string"){const l=g_(t,r);if(l!=null)typeof l.then=="function"?n.push(l.then(c=>i[o]=c)):i[o]=l;else{const c=f_(s,t,r);if(c){n.push(c.then(h=>(i[o]=h,h)));continue}}}else if(Array.isArray(r))for(let l=0;l<r.length;l++){const c=r[l],h=g_(t,c);if(h!==null){typeof h.then=="function"?n.push(h.then(d=>r[l]=d)):r[l]=h;continue}for(const d of s){const u=y_(d.prefix,c);if(u>=0){Fg&&console.log(d,u,d.dependencyName),n.push(t.getDependency(d.dependencyName,u).then(p=>r[l]=p));break}}typeof c=="object"&&Ug(s,t,c,n)}else typeof r=="object"&&Ug(s,t,r,n)}else if(typeof i=="string"){const o=f_(s,t,i);o&&n.push(o)}}function g_(s,t){if(s&&s.plugins&&typeof t=="string"){for(const i of Ck)if(t.startsWith(i)){let n=t.substring(i.length);const o=n.indexOf("/");o>=0&&(n=n.substring(0,o));const r=s.plugins[n];if(vt&&console.log(n,r),typeof r?.resolve=="function"){const l=t.substring(i.length+n.length+1);return r.resolve(s,l)}break}}return null}function f_(s,t,i){for(const n of s){const o=y_(n.prefix,i);if(o>=0)return Fg&&console.warn("GET DEPENDENCY",n,o,n.dependencyName),t.getDependency(n.dependencyName,o)}return null}function y_(s,t){if(typeof t=="string"&&t.startsWith(s)){const i=t.substring(s.length),n=Number.parseInt(i);if(n>=0)return n}return-1}const Ng="NEEDLE_persistent_assets";function kk(s){return s?.___persistentAsset===!0}class Mk{constructor(t){a(this,"parser"),this.parser=t}get name(){return Ng}async afterRoot(t){var i,n;if(!((n=(i=this.parser)==null?void 0:i.json)!=null&&n.extensions))return;const o=this.parser.json.extensions[Ng];if(!o)return;vt&&console.log(o);const r=new Array;for(const l of o?.assets){const c=zg(this.parser,l);c&&r.push(c)}await Promise.all(r)}resolve(t,i){const n=Number.parseInt(i);if(n>=0){vt&&console.log(i);const o=t.json.extensions[Ng];if(o){const r=o?.assets[n];if(r&&typeof r=="object"){r.___persistentAsset=!0;const l=r.__type;l&&S.get(l)}return r}}return null}}const Vs=O("debugserializer");class Rk{constructor(){a(this,"typeMap",new Map)}register(t,i){if(this.typeMap.has(t)){const n=this.typeMap.get(t);if(n===i)return;Vs&&console.warn("Type: "+t+" is already registered",i,n)}Vs&&console.log("Register type serializer",i.name,i,t),this.typeMap.set(t,i)}getSerializer(t){if(t)return this.typeMap.get(t)}getSerializerForConstructor(t,i=0){if(i>20)return;if(!t||!t.constructor){Vs&&console.log("invalid type");return}const n=t.name,o=this.getSerializer(t);if(o!==void 0)return Vs&&console.log("FOUND SERIALIZER",o?.name,t.name,t.constructor.name,"for type: "+n,o,t,this.typeMap),o;const r=Object.getPrototypeOf(t);if(r&&r!==t){const l=this.getSerializerForConstructor(r,++i);if(l){const c=r.constructor||r.prototype;Vs&&console.log("FOUND SERIALIZER(in constructor) "+c.constructor.name,c.name,c,l),this.register(c,l)}return l}Vs&&console.warn("No serializer found for "+n,t,t.name,t.constructor.name)}}const Xd=new Rk;class Zi{constructor(t,i){if(a(this,"name"),this.name=i,Array.isArray(t))for(const n of t)Xd.register(n,this);else Xd.register(t,this)}}class Tk{constructor(){a(this,"isDevMode",Gt()),a(this,"cache",{})}registerDefinedKeys(t,i){if(this.isDevMode&&this.cache[t]===void 0){this.cache[t]=Object.keys(i);const n=i;n.$serializedTypes&&Object.keys(n.$serializedTypes)&&this.cache[t].push(...Object.keys(n.$serializedTypes)),Vs&&console.log("registerDefinedKeys for "+t,this.cache[t],i)}}getDefinedKey(t,i){return this.cache[t]===void 0?!1:this.cache[t].includes(i)}}class Wg{constructor(t){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=t}}function v_(s,t){const i=s.$serializedTypes;if(i===void 0)return null;const n={};for(const r in i){const l=s[r];if(l!=null&&typeof l=="object"){const c=Xd.getSerializerForConstructor(l);if(c){n[r]=c.onSerialize(l,t);continue}}n[r]=l}function o(r){const l=S._types;for(const[c,h]of l)if(h===s.constructor)return c;return r.__name||r.constructor.name}return n.name=o(s),typeof s.guid=="string"&&(n.guid=s.guid),n}const Qd=[];function b_(s,t){if(!s)return t;typeof s.$serializedTypes=="object"&&(t||(t={}),Object.assign(t,s.$serializedTypes));const i=Object.getPrototypeOf(s);return b_(i,t)}function Yd(s,t,i){if(!s)return!1;if(i.target=s,s.onBeforeDeserialize!==void 0){const o=s.onBeforeDeserialize(t,i);if(typeof o=="boolean")return o}const n=b_(s);if(t){if(typeof t.guid=="string"&&(s.guid=t.guid),n)for(const o in n){let r=function(h){const d=h.type;return d?Vg(c,d,i,void 0,s[o]):Vg(c,h,i,void 0,s[o])};const l=n[o],c=t[o];if(Vs&&console.log(o,c,s,l),!(s[o]!==void 0&&c===void 0)&&(i.type=void 0,i.path=o,i.serializable=l,!(s.onBeforeDeserializeMember!==void 0&&s.onBeforeDeserializeMember(o,c,i)===!0))){if(l===null)s[o]=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){s[o]=u;break}}else s[o]=r(l);Qd.length=0}s.onAfterDeserializeMember!==void 0&&s.onAfterDeserializeMember(o,c,i)}}Ik(s,t)}return Ak(s,t,i.implementationInformation),s.onAfterDeserialize!==void 0&&s.onAfterDeserialize(t,i),!0}const Ek=O("noerrors");function Ak(s,t,i){var n,o;if(Ek||!t||!Gt()||!s||s.constructor&&s.constructor[xk]===!0)return;const r=(n=s.constructor)==null?void 0:n.name,l=Object.getOwnPropertyNames(t);for(const c of l){if(c==="sourceId")continue;const h=s[c];if(h==null)continue;const d=t[c];if(i?.getDefinedKey(r,c)===!1){const u=c.charAt(0).toUpperCase()+c.slice(1);i.getDefinedKey(r,u)&&(zs(Ci.Warn,'<strong>Please rename</strong> "'+u+'" to "'+c+'" in '+r),console.warn('Please use lowercase for field: "'+u+'" in '+r,d,s));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)){zs(Ci.Warn,`<strong>Missing serialization for object reference!</strong>
160
160
 
161
161
  Please change to:
162
162
  @serializable(Object3D)
@@ -171,12 +171,12 @@ Please change to:
171
171
  ${c}? : AssetReference;
172
172
 
173
173
  in script ${r}.ts
174
- <a href="https://docs.needle.tools/serializable" target="_blank">documentation</a>`),console.warn(r,c,s[c],s);continue}}}}function I2(s,t){for(const i of Object.keys(t)){const n=t[i];if(typeof n=="object"&&n!==null&&n!==void 0){const o=s[i];if(!o){Vs&&console.log(i,"is undefined on",s);continue}for(const r of Object.keys(n))if(o[r]===void 0&&__(n[r])&&!__(o)){const l=j2(o,r);if(l&&(l?.writable===void 0||l?.writable===!1)&&l.set===void 0){Vs&&console.warn('Property is not writable "'+r+'"',o,l,n[r],o[r]);continue}o[r]=n[r]}}}}function j2(s,t){for(;s;){const i=Object.getOwnPropertyDescriptor(s,t);if(i)return i;s=Object.getPrototypeOf(s)}}function __(s){switch(typeof s){case"number":case"string":case"boolean":return!0}return!1}function Vg(s,t,i,n,o){let r=typeof t=="function"&&t.prototype===void 0,l=t;if(r)try{if(l=t?.call(t,o),r=!1,l==null)return}catch(u){console.error("Error in callback",u,s)}if(i.type=l,!r&&o&&(o instanceof ke||o instanceof Le||o instanceof K||o instanceof bn||o instanceof ao))return o;if(n||(n={serializer:Xd.getSerializerForConstructor(l)}),o&&typeof o=="object"&&k2(o)){if(o.__concreteInstance)return o.__concreteInstance;const u=o;if(!u.$serializedTypes&&l.prototype.$serializedTypes&&(u.$serializedTypes=l.prototype.$serializedTypes),u.$serializedTypes&&Yd(u,s,i),o&&l!==void 0)try{let p=null;n.serializer&&(p=n.serializer.onDeserialize(s,i)),p||(p=new l,vt&&console.log("Create concrete instance for persistent asset",o,"instance:",p),Da(p,o)),o.__concreteInstance=p,o=p}catch(p){console.error("Error creating instance or creating values on instance",p,o,l)}return o}if(Array.isArray(s)){const u=[];for(let p=0;p<s.length;p++){const g=s[p],y=Vg(g,t,i,n,g);u.push(y)}return u}const c=n?.serializer;if(c)return c.onDeserialize(s,i);let h;if(s&&(s.isMaterial||s.isTexture||s.isObject3D||s instanceof ao))h=s;else{if(s===void 0)return;if(s===null&&(l===ke||l===Le||l===K||l===ao))return null;try{h=new l(...L2(s))}catch(u){console.error("Error creating "+i.path,i.target,u);return}}const d=h;return d.$serializedTypes&&Yd(d,s,i),h}function L2(s){if(Qd.length=0,typeof s=="object"&&s!==null&&s!==void 0)for(const t of Object.keys(s))Qd.push(s[t]);return Qd}const Hg=Symbol("assigned component properties");function Da(s,t,i){var n;if(t==null||s==null)return;s[Hg]=!0;const o=((n=s.constructor)==null?void 0:n.name)??"unknown";i?.registerDefinedKeys(o,s);for(const r of Object.keys(t)){const l=D2(s,r);typeof l?.value!="function"&&(!l||l.writable===!0||l?.set!==void 0)&&(s[r]=t[r])}delete s[Hg]}function D2(s,t){let i;do i=Object.getOwnPropertyDescriptor(s,t);while(!i&&(s=Object.getPrototypeOf(s)));return i}const w_=Symbol("customVisibilityFlag");function Mn(s,t){s.layers[w_]=t}const x_=Symbol("DidPatchLayers");function B2(){const s=no.prototype;if(s[x_])return;s[x_]=!0;const t=s.test;s.test=function(i){return this[w_]===!1?!1:t.call(this,i)}}B2(),Object.defineProperty(we.prototype,"fov",{get:function(){return this._fov},set:function(s){const t=s!==this._fov;this._fov=s,t&&this.view!==void 0&&this.updateProjectionMatrix()},configurable:!0}),Object.defineProperty(we.prototype,"near",{get:function(){return this._near},set:function(s){const t=s!==this._near;this._near=s,t&&this.view!==void 0&&this.updateProjectionMatrix()},configurable:!0}),Object.defineProperty(we.prototype,"far",{get:function(){return this._far},set:function(s){const t=s!==this._far;this._far=s,t&&this.view!==void 0&&this.updateProjectionMatrix()},configurable:!0});const S_=new Map;function C_(s,t){if(!s)return;if(!t){console.warn("No prototype found",s,s.prototype,s.constructor);return}const i=S_.get(t);i&&i.apply(s)}function O_(s){const t=F2(s.prototype);S_.set(s,t)}function F2(s){return new z2(s)}class z2{constructor(t){a(this,"$symbol"),a(this,"extensions"),a(this,"descriptors"),this.$symbol=Symbol("prototype-extension"),this.extensions=Object.keys(t),this.descriptors=new Array;for(let i=0;i<this.extensions.length;i++){const n=this.extensions[i],o=Object.getOwnPropertyDescriptor(t,n);o&&this.descriptors.push(o)}}apply(t){if(!t[this.$symbol]){t[this.$symbol]=!0;for(let i=0;i<this.extensions.length;i++){const n=this.extensions[i],o=this.descriptors[i];o&&Object.defineProperty(t,n,o)}}}}const U2=O("debuggetcomponent"),P_=()=>U2||globalThis.NEEDLE_DEBUG_GETCOMPONENT===!0;function N2(s){return s==null||s.isObject3D?s:s.object&&s.object.isObject3D?s.object:s}function $g(s,t){if(!s||!s.userData.components)return t;const i=s.userData.components.indexOf(t);return i<0||(vc.dispatchComponentLifecycleEvent("removing-component",t),t.gameObject=null,s.userData.components.splice(i,1)),t}function Cc(s,t,i){return Pr(s,t)||Mi(s,t,i)}const k_=new zt("addComponentIdProvider");function Or(s,t,i=!0){s.userData||(s.userData={}),s.userData.components||(s.userData.components=[]),s.userData.components.push(t),t.gameObject=s,(t.guid===void 0||t.guid==="invalid")&&(t.guid=k_.generateUUID()),Jd(s),wu(t,t.context);try{i&&t.__internalAwake&&(wc(s),t.activeAndEnabled&&t.__internalAwake()),vc.dispatchComponentLifecycleEvent("component-added",t)}catch(n){console.error(n)}return t}function Mi(s,t,i,n){if(typeof t=="function"){const o=new t;i&&o.__internalNewInstanceCreated(i);let r=!0;return n?.callAwake!=null&&(r=n.callAwake),Or(s,o,r)}if(t.destroyed)return console.warn("Can not move/add a destroyed component",t),t;if(t.gameObject===s)return t;if(t.gameObject&&t.gameObject.userData.components){const o=t.gameObject.userData.components.indexOf(t);t.gameObject.userData.components.splice(o,1)}if(!s.userData.components)s.userData.components=[];else if(s.userData.components.includes(t))return t;return s.userData.components.push(t),t.gameObject=s,(t.guid===void 0||t.guid==="invalid")&&(t.guid=k_.generateUUID()),i&&t._internalInit(i),wu(t,t.context),t}function M_(s){if(s.gameObject&&s.gameObject.userData.components){const t=s.gameObject.userData.components.indexOf(s);s.gameObject.userData.components.splice(t,1)}s.__internalDisable&&s.__internalDisable(),kn(s,s.context??ee.Current),s.destroy(),s.gameObject=null}let R_=!1;function T_(s,t,i){var n;if(s==null)return null;if(!s.isObject3D)return console.error("Object is not object3D"),null;if(!((n=s?.userData)!=null&&n.components)||(typeof t=="string"&&(R_||(R_=!0,console.warn(`Accessing components by name is not supported.
174
+ <a href="https://docs.needle.tools/serializable" target="_blank">documentation</a>`),console.warn(r,c,s[c],s);continue}}}}function Ik(s,t){for(const i of Object.keys(t)){const n=t[i];if(typeof n=="object"&&n!==null&&n!==void 0){const o=s[i];if(!o){Vs&&console.log(i,"is undefined on",s);continue}for(const r of Object.keys(n))if(o[r]===void 0&&__(n[r])&&!__(o)){const l=jk(o,r);if(l&&(l?.writable===void 0||l?.writable===!1)&&l.set===void 0){Vs&&console.warn('Property is not writable "'+r+'"',o,l,n[r],o[r]);continue}o[r]=n[r]}}}}function jk(s,t){for(;s;){const i=Object.getOwnPropertyDescriptor(s,t);if(i)return i;s=Object.getPrototypeOf(s)}}function __(s){switch(typeof s){case"number":case"string":case"boolean":return!0}return!1}function Vg(s,t,i,n,o){let r=typeof t=="function"&&t.prototype===void 0,l=t;if(r)try{if(l=t?.call(t,o),r=!1,l==null)return}catch(u){console.error("Error in callback",u,s)}if(i.type=l,!r&&o&&(o instanceof ke||o instanceof Le||o instanceof K||o instanceof bn||o instanceof ao))return o;if(n||(n={serializer:Xd.getSerializerForConstructor(l)}),o&&typeof o=="object"&&kk(o)){if(o.__concreteInstance)return o.__concreteInstance;const u=o;if(!u.$serializedTypes&&l.prototype.$serializedTypes&&(u.$serializedTypes=l.prototype.$serializedTypes),u.$serializedTypes&&Yd(u,s,i),o&&l!==void 0)try{let p=null;n.serializer&&(p=n.serializer.onDeserialize(s,i)),p||(p=new l,vt&&console.log("Create concrete instance for persistent asset",o,"instance:",p),Da(p,o)),o.__concreteInstance=p,o=p}catch(p){console.error("Error creating instance or creating values on instance",p,o,l)}return o}if(Array.isArray(s)){const u=[];for(let p=0;p<s.length;p++){const g=s[p],y=Vg(g,t,i,n,g);u.push(y)}return u}const c=n?.serializer;if(c)return c.onDeserialize(s,i);let h;if(s&&(s.isMaterial||s.isTexture||s.isObject3D||s instanceof ao))h=s;else{if(s===void 0)return;if(s===null&&(l===ke||l===Le||l===K||l===ao))return null;try{h=new l(...Lk(s))}catch(u){console.error("Error creating "+i.path,i.target,u);return}}const d=h;return d.$serializedTypes&&Yd(d,s,i),h}function Lk(s){if(Qd.length=0,typeof s=="object"&&s!==null&&s!==void 0)for(const t of Object.keys(s))Qd.push(s[t]);return Qd}const Hg=Symbol("assigned component properties");function Da(s,t,i){var n;if(t==null||s==null)return;s[Hg]=!0;const o=((n=s.constructor)==null?void 0:n.name)??"unknown";i?.registerDefinedKeys(o,s);for(const r of Object.keys(t)){const l=Dk(s,r);typeof l?.value!="function"&&(!l||l.writable===!0||l?.set!==void 0)&&(s[r]=t[r])}delete s[Hg]}function Dk(s,t){let i;do i=Object.getOwnPropertyDescriptor(s,t);while(!i&&(s=Object.getPrototypeOf(s)));return i}const w_=Symbol("customVisibilityFlag");function Mn(s,t){s.layers[w_]=t}const x_=Symbol("DidPatchLayers");function Bk(){const s=no.prototype;if(s[x_])return;s[x_]=!0;const t=s.test;s.test=function(i){return this[w_]===!1?!1:t.call(this,i)}}Bk(),Object.defineProperty(we.prototype,"fov",{get:function(){return this._fov},set:function(s){const t=s!==this._fov;this._fov=s,t&&this.view!==void 0&&this.updateProjectionMatrix()},configurable:!0}),Object.defineProperty(we.prototype,"near",{get:function(){return this._near},set:function(s){const t=s!==this._near;this._near=s,t&&this.view!==void 0&&this.updateProjectionMatrix()},configurable:!0}),Object.defineProperty(we.prototype,"far",{get:function(){return this._far},set:function(s){const t=s!==this._far;this._far=s,t&&this.view!==void 0&&this.updateProjectionMatrix()},configurable:!0});const S_=new Map;function C_(s,t){if(!s)return;if(!t){console.warn("No prototype found",s,s.prototype,s.constructor);return}const i=S_.get(t);i&&i.apply(s)}function O_(s){const t=Fk(s.prototype);S_.set(s,t)}function Fk(s){return new zk(s)}class zk{constructor(t){a(this,"$symbol"),a(this,"extensions"),a(this,"descriptors"),this.$symbol=Symbol("prototype-extension"),this.extensions=Object.keys(t),this.descriptors=new Array;for(let i=0;i<this.extensions.length;i++){const n=this.extensions[i],o=Object.getOwnPropertyDescriptor(t,n);o&&this.descriptors.push(o)}}apply(t){if(!t[this.$symbol]){t[this.$symbol]=!0;for(let i=0;i<this.extensions.length;i++){const n=this.extensions[i],o=this.descriptors[i];o&&Object.defineProperty(t,n,o)}}}}const Uk=O("debuggetcomponent"),P_=()=>Uk||globalThis.NEEDLE_DEBUG_GETCOMPONENT===!0;function Nk(s){return s==null||s.isObject3D?s:s.object&&s.object.isObject3D?s.object:s}function $g(s,t){if(!s||!s.userData.components)return t;const i=s.userData.components.indexOf(t);return i<0||(vc.dispatchComponentLifecycleEvent("removing-component",t),t.gameObject=null,s.userData.components.splice(i,1)),t}function Cc(s,t,i){return Pr(s,t)||Mi(s,t,i)}const k_=new zt("addComponentIdProvider");function Or(s,t,i=!0){s.userData||(s.userData={}),s.userData.components||(s.userData.components=[]),s.userData.components.push(t),t.gameObject=s,(t.guid===void 0||t.guid==="invalid")&&(t.guid=k_.generateUUID()),Jd(s),wu(t,t.context);try{i&&t.__internalAwake&&(wc(s),t.activeAndEnabled&&t.__internalAwake()),vc.dispatchComponentLifecycleEvent("component-added",t)}catch(n){console.error(n)}return t}function Mi(s,t,i,n){if(typeof t=="function"){const o=new t;i&&o.__internalNewInstanceCreated(i);let r=!0;return n?.callAwake!=null&&(r=n.callAwake),Or(s,o,r)}if(t.destroyed)return console.warn("Can not move/add a destroyed component",t),t;if(t.gameObject===s)return t;if(t.gameObject&&t.gameObject.userData.components){const o=t.gameObject.userData.components.indexOf(t);t.gameObject.userData.components.splice(o,1)}if(!s.userData.components)s.userData.components=[];else if(s.userData.components.includes(t))return t;return s.userData.components.push(t),t.gameObject=s,(t.guid===void 0||t.guid==="invalid")&&(t.guid=k_.generateUUID()),i&&t._internalInit(i),wu(t,t.context),t}function M_(s){if(s.gameObject&&s.gameObject.userData.components){const t=s.gameObject.userData.components.indexOf(s);s.gameObject.userData.components.splice(t,1)}s.__internalDisable&&s.__internalDisable(),kn(s,s.context??ee.Current),s.destroy(),s.gameObject=null}let R_=!1;function T_(s,t,i){var n;if(s==null)return null;if(!s.isObject3D)return console.error("Object is not object3D"),null;if(!((n=s?.userData)!=null&&n.components)||(typeof t=="string"&&(R_||(R_=!0,console.warn(`Accessing components by name is not supported.
175
175
  Please use the component type instead. This may keep working in local development but it will fail when bundling your application.
176
176
 
177
177
  You can import other modules your main module to get access to types
178
178
  or if you use npmdefs you can make types available globally using globalThis:
179
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis`,t))),P_()&&console.log("[onGetComponent] FIND",t),t==null))return null;for(let o=0;o<s.userData.components.length;o++){const r=s.userData.components[o];let l=Object.getPrototypeOf(r);for(;l;){if(l===t.prototype)if(P_()&&console.log("[onGetComponent] MATCH BY PROTOYPE",l),i)i.push(r);else return r;l=Object.getPrototypeOf(l)}}return i||null}function Pr(s,t){const i=T_(s,t);return i?Array.isArray(i)?i[0]:i:null}function Oc(s,t,i,n=!0){return i||(i=[]),n&&(i.length=0),T_(s,t,i),i}function Pc(s,t,i){var n;const o=Pr(s,t);if(i===!1&&o?.enabled===!1)return null;if(o)return o;for(let r=0;r<((n=s?.children)==null?void 0:n.length);r++){const l=Pc(s.children[r],t);if(l)return l}return null}function Ba(s,t,i,n=!0){var o;i||(i=[]),n&&(i.length=0),Oc(s,t,i,!1);for(let r=0;r<((o=s?.children)==null?void 0:o.length);r++)Ba(s.children[r],t,i,!1);return i}function kc(s,t){if(!s)return null;if(Array.isArray(s)){for(let n=0;n<s.length;n++){const o=N2(s[n]),r=kc(o,t);if(r)return r}return null}return Pr(s,t)||(s.parent?kc(s.parent,t):null)}function Kd(s,t,i,n=!0){return i||(i=[]),n&&(i.length=0),s?(Oc(s,t,i,!1),s.parent?Kd(s.parent,t,i,!1):i):i}function Zd(s,t=void 0,i=!0){if(!s)return null;if(!t&&(t=ee.Current,!t))return console.error("Can not search object without any needle context or scene!!!"),null;let n=t;if(n.isScene||(n=t?.scene),!n)return null;for(const o in n.children){const r=n.children[o];if(i===!1&&r[Sn]===!1)continue;const l=Pc(r,s);if(l)return l}return null}function E_(s,t,i=void 0){if(!s)return t??[];if(t||(t=[]),t.length=0,!i&&(i=ee.Current,!i))return console.error("Can not search object without any needle context or scene!!!"),t;"scene"in i&&(i=i.scene);const n=i;if(!n)return t;for(const o in n.children){const r=n.children[o];Ba(r,s,t,!1)}return t}function Jd(s){s&&s.isObject3D===!0&&C_(s,I)}I.prototype.SetActive=function(s){this.visible=s},I.prototype.setActive=function(s){this.visible=s},I.prototype.destroy=function(){Ri(this)},I.prototype.addComponent=function(s,t){return Mi(this,s,t)},I.prototype.addNewComponent=function(s,t){return Mi(this,s,t)},I.prototype.removeComponent=function(s){return $g(this,s)},I.prototype.getOrAddComponent=function(s,t){return Cc(this,s,t)},I.prototype.getComponent=function(s){return Pr(this,s)},I.prototype.getComponents=function(s,t){return Oc(this,s,t)},I.prototype.getComponentInChildren=function(s){return Pc(this,s)},I.prototype.getComponentsInChildren=function(s,t){return Ba(this,s,t)},I.prototype.getComponentInParent=function(s){return kc(this,s)},I.prototype.getComponentsInParent=function(s,t){return Kd(this,s,t)},Object.getOwnPropertyDescriptor(I.prototype,"activeSelf")||Object.defineProperty(I.prototype,"activeSelf",{get:function(){return Fa(this)},set:function(s){Mc(this,s)}}),Object.getOwnPropertyDescriptor(I.prototype,"worldPosition")||Object.defineProperty(I.prototype,"worldPosition",{get:function(){return this instanceof rv?te(this.object):te(this)},set:function(s){dt(this,s)}}),Object.getOwnPropertyDescriptor(I.prototype,"worldQuaternion")||Object.defineProperty(I.prototype,"worldQuaternion",{get:function(){return this instanceof rv?Oe(this.object):Oe(this)},set:function(s){Gi(this,s)}}),Object.getOwnPropertyDescriptor(I.prototype,"worldRotation")||Object.defineProperty(I.prototype,"worldRotation",{get:function(){return sc(this)},set:function(s){Xm(this,s)}}),Object.getOwnPropertyDescriptor(I.prototype,"worldScale")||Object.defineProperty(I.prototype,"worldScale",{get:function(){return Je(this)},set:function(s){Pa(this,s)}}),Object.getOwnPropertyDescriptor(I.prototype,"worldForward")||Object.defineProperty(I.prototype,"worldForward",{get:function(){return G().set(0,0,1).applyQuaternion(Oe(this))}}),Object.getOwnPropertyDescriptor(I.prototype,"worldRight")||Object.defineProperty(I.prototype,"worldRight",{get:function(){return G().set(1,0,0).applyQuaternion(Oe(this))}}),Object.getOwnPropertyDescriptor(I.prototype,"worldUp")||Object.defineProperty(I.prototype,"worldUp",{get:function(){return G().set(0,1,0).applyQuaternion(Oe(this))}}),O_(I);class Se extends re{constructor(t,i,n,o){var r=(...l)=>{super(...l),a(this,"alpha",1)};i!=null&&n!=null?(r(t,i,n),this.alpha=o):(r(t),this.alpha=1)}get isRGBAColor(){return!0}set a(t){this.alpha=t}get a(){return this.alpha}clone(){const t=super.clone();return t.alpha=this.alpha,t}copy(t){return this.r=t.r,this.g=t.g,this.b=t.b,"alpha"in t&&typeof t.alpha=="number"?this.alpha=t.alpha:typeof t.a=="number"&&(this.alpha=t.a),this}lerp(t,i){const n=t;return n.alpha!=null&&(this.alpha=W.lerp(this.alpha,n.alpha,i)),super.lerp(t,i)}lerpColors(t,i,n){const o=t,r=i;return o.alpha!=null&&r.alpha!=null&&(this.alpha=W.lerp(o.alpha,r.alpha,n)),super.lerpColors(t,i,n)}multiply(t){const i=t;return i.alpha!=null&&(this.alpha=this.alpha*i.alpha),super.multiply(t)}fromArray(t,i=0){return this.alpha=t[i+3],super.fromArray(t,i)}}const eu=O("debuggetcomponent"),tu=O("debuginstantiate");class Ds{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 t,i,n;const o=new Ds;return o.idProvider=this.idProvider,o.parent=this.parent,o.keepWorldPosition=this.keepWorldPosition,o.position=(t=this.position)==null?void 0:t.clone(),o.rotation=(i=this.rotation)==null?void 0:i.clone(),o.scale=(n=this.scale)==null?void 0:n.clone(),o.visible=this.visible,o.context=this.context,o.components=this.components,o}cloneAssign(t){var i,n,o;this.idProvider=t.idProvider,this.parent=t.parent,this.keepWorldPosition=t.keepWorldPosition,this.position=(i=t.position)==null?void 0:i.clone(),this.rotation=(n=t.rotation)==null?void 0:n.clone(),this.scale=(o=t.scale)==null?void 0:o.clone(),this.visible=t.visible,this.context=t.context,this.components=t.components}}function Fa(s){return s.visible}function Mc(s,t){return typeof t=="number"&&(t=t>.5),s.visible=t,s.visible}function A_(s){return s[Sn]||iu(s)}function I_(s,t){s[e_]=t}function iu(s){return cs.isUsingInstancing(s)}function qg(s,t){return Ca(s,t,!0,!0)}const j_=Symbol("isDestroyed");function kr(s){return s[j_]}function L_(s,t){s[j_]=t}const Gg=Symbol("isDontDestroy");function za(s,t=!0){s[Gg]=t}const su=[],nu=[];function Ri(s,t=!0,i=!1){su.length=0,nu.length=0,Xg(s,t,!0);for(const n of su)n.gameObject=null,n.context=null;for(const n of nu)L_(n,!0),i&&Ee(n),Zb(n);nu.length=0,su.length=0}function Xg(s,t=!0,i=!0){var n;if(s==null)return;const o=s;if(o.isComponent){if(o[Gg])return;su.push(o);const c=o.gameObject;o.__internalDisable(),o.__internalDestroy(),o.gameObject=c;return}if(s[Gg])return;const r=s;eu&&console.log(r),nu.push(r);const l=(n=r.userData)==null?void 0:n.components;if(l!=null&&Array.isArray(l)){let c=l.length;for(let h=0;h<l.length;h++){const d=l[h];Xg(d,t,!1),l.length<c&&(c=l.length,h--)}}if(t&&r.children)for(const c of r.children)Xg(c,t,!1);i&&r.removeFromParent()}function Mr(s,t,i=!0){return D_(s,t,i)}function*ou(s,t,i=!1,n=999,o=0){if(s!=null&&s.userData.components&&!(o>n)){for(const r of s.userData.components)t&&r?.isComponent===!0&&r instanceof t?yield r:yield r;if(i===!0)for(const r of s.children)yield*ou(r,t,!0,n,o+1)}}function D_(s,t,i,n=0){var o;if(s){if(s.isObject3D,n>1e3){console.warn("Failed to iterate components: too many levels");return}if((o=s.userData)!=null&&o.components)for(let r=0;r<s.userData.components.length;r++){const l=s.userData.components[r];if(l?.isComponent===!0){const c=t(l);if(c!==void 0)return c}}if(i&&s.children){const r=n+1;for(let l=0;l<s.children.length;l++){const c=s.children[l];if(!c)continue;const h=D_(c,t,i,r);if(h!==void 0)return h}}}}function Ua(s,t){if("isAssetReference"in s)return s.instantiate(t??void 0);let i=null;t!=null&&(t.x!==void 0?(i=new Ds,i.position=t):i=t);let n=ee.Current;i!=null&&i.context&&(n=i.context),eu&&n.alias&&console.log("context",n.alias),i&&!i.idProvider&&(i.idProvider=new zt(Date.now()));const o=[],r={},l={},c=B_(n,s,i,o,r,l);c&&(V2(r),W2(l,r)),eu&&(kd(s,!0),kd(c,!0));const h={};if(i?.components!==!1){for(const d in o){const u=o[d],p=u.guid;i&&i.idProvider&&(u.guid=i.idProvider.generateUUID(),h[p]=u.guid,eu&&console.log(u.name,u.guid)),wu(u,n),u.__internalNewInstanceCreated&&u.__internalNewInstanceCreated()}for(const d in o){const u=o[d];u.resolveGuids&&u.resolveGuids(h),u.enabled!==!1&&(u.enabled=!0)}Hd(n)}return c}function B_(s,t,i,n,o,r){var l;if(!t)return null;const c=t.userData;t.userData={};const h=t.children;t.children=[];const d=t.clone(!1);if(Jd(d),t.userData=c,t.children=h,o[t.uuid]={original:t,clone:d},tu&&console.log("ADD",t,d),t.type==="SkinnedMesh"&&(r[t.uuid]={original:t,clone:d}),i?.visible!==void 0&&(d.visible=i.visible),i!=null&&i.idProvider){d.uuid=i.idProvider.generateUUID();const p=d;p&&(p.guid=d.uuid)}t.animations&&t.animations.length>0&&(d.animations=[...t.animations]);const u=t.parent;if(u&&u.add(d),i!=null&&i.position?dt(d,i.position):d.position.copy(t.position),i!=null&&i.rotation?Gi(d,i.rotation):d.quaternion.copy(t.quaternion),i!=null&&i.scale?d.scale.copy(i.scale):d.scale.copy(t.scale),i!=null&&i.parent&&i.parent!=="scene"){let p=null;if(typeof i.parent=="string"?p=Ca(i.parent,s.scene,!0):p=i.parent,p){const g=i.keepWorldPosition===!0?p.attach:p.add;g?g.call(p,d):console.error("Invalid parent object",p,"received when instantiating:",t)}else console.warn("could not find parent:",i.parent)}for(const[p,g]of Object.entries(t.userData))p!=="components"&&(d.userData[p]=g);if((l=t.userData)!=null&&l.components){const p=t.userData.components,g=[];d.userData.components=g;for(let y=0;y<p.length;y++){const f=p[y],v=new f.constructor;Da(v,f),f[dc]!==void 0&&(v[dc]=f[dc]),g.push(v),v.gameObject=d,n.push(v),o[f.guid]={original:f,clone:v},vc.dispatchComponentLifecycleEvent("component-added",v)}}i&&(i.position=void 0,i.rotation=void 0,i.scale=void 0,i.parent=void 0);for(const p in t.children){const g=t.children[p],y=B_(s,g,i,n,o,r);y&&d.add(y)}return d}function W2(s,t){for(const i in s){const n=s[i],o=n.original,r=o.skeleton,l=n.clone;if(!r){console.warn("Skinned mesh has no skeleton?",n);continue}const c=r.bones,h=l.skeleton.clone();l.skeleton=h,l.bindMatrix.clone().copy(o.bindMatrix),l.bindMatrixInverse.copy(o.bindMatrixInverse);const d=[];h.bones=d;for(let u=0;u<c.length;u++){const p=c[u],g=t[p.uuid].clone;d.push(g)}}for(const i in s){const n=s[i].clone;n.skeleton.update(),n.bind(n.skeleton,n.bindMatrix),n.updateMatrixWorld(!0)}}function V2(s){var t;for(const i in s){const n=s[i].clone;if(n!=null&&n.isObject3D&&(t=n?.userData)!=null&&t.components)for(let o=0;o<n.userData.components.length;o++){const r=n.userData.components[o],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=F_(r,c,p,s);g!==void 0?d.push(g):d.push(p)}}else if(typeof h=="object"){const d=F_(r,c,h,s);d!==void 0&&(r[c]=d)}}}}function F_(s,t,i,n){var o,r;if(i!=null)if(i.isComponent===!0){const l=i.gameObject;if(l){const c=l.uuid,h=(o=n[c])==null?void 0:o.clone;if(!h){tu&&console.log("reference did not change",t,s,i);return}const d=l.userData.components.indexOf(i);if(d>=0&&h.isObject3D)return tu&&console.log(t,c),h.userData.components[d];console.warn("could not find component",t,i)}}else if(i.isObject3D===!0){if(t==="gameObject")return;const l=i;if(l){const c=l.uuid,h=(r=n[c])==null?void 0:r.clone;if(h)return tu&&console.log(t,"old",i,"new",h),h}}else{if(i.isVector4||i.isVector3||i.isVector2||i.isQuaternion||i.isEuler||i.isColor===!0)return i.clone();if(i.isEventList===!0)return i.__internalOnInstantiate(n)}}var Rr;(s=>{s.baseUrl="https://networking.needle.tools";function t(h){return pv(new Uint8Array(h))}s.hashMD5=t;function i(h){const d=pv(new Uint8Array(h),{encoding:"binary",asBytes:!0});return btoa(String.fromCharCode(...d))}s.hashMD5_Base64=i;function n(h){const d=new Uint8Array(h);return crypto.subtle.digest("SHA-256",d).then(u=>btoa(String.fromCharCode(...new Uint8Array(u))))}s.hashSha256=n;function o(h){const d=h.filesize/1024/1024;return Os()?d<50:d<5}s.canUpload=o;async function r(h,d){var u;const p=s.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 y=g.byteLength,f=y/1024/1024;if(f>50)return d?.silent!==!0&&xe(`File (${f.toFixed(1)}MB) is too large for uploading (see console for details)`),console.warn(`Your file is too large for uploading (${f.toFixed(1)}MB). Max allowed size is 50MB`),null;if(!Os()&&f>5)return d?.silent!==!0&&xe('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 (${f.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(y<1)return console.warn(`Your file is too small for uploading (${f.toFixed(1)}MB). Min size is 1 byte`),null;const v=i(g),b={filename:h.name,"Content-Md5":v,"Content-Type":h.type||"application/octet-stream",FileSize:y.toString(),"Content-Disposition":`attachment; filename="${h.name}"`,"x-amz-server-side-encryption":"AES256"},w=await fetch(p+"/api/needle/blob",{method:"POST",headers:b,signal:d?.abort}).then(_=>_.json()).catch(_=>(console.error(_),null));if(w==null)return console.warn("Upload failed..."),null;if("error"in w)return console.error(w.error),null;if("upload"in w&&w.upload){let _=function(M){var T;return(T=d?.onProgress)==null||T.call(null,{progress01:0,state:"inprogress"}),fetch(M,{method:"PUT",headers:b,body:g,signal:d?.abort}).then(j=>{var D;return(D=d?.onProgress)==null||D.call(null,{progress01:1,state:"finished"}),j}).catch(j=>j)};console.debug("Uploading file",w.upload);let C=!1,R=null;for(let M=0;M<3;M++)try{if(C)break;if((u=d?.abort)!=null&&u.aborted)return console.debug("Aborted upload"),null;const T=await _(w.upload);T instanceof Error?(R=T,await ys(1e3*M)):T.ok&&(console.debug("File uploaded successfully"),C=!0)}catch(T){console.error(T)}if(!C)return console.error(R?.message||"Failed to upload file"),null}if("download"in w){const _=p+w.download;return console.debug("File found in blob storage",_),{key:w.key,success:!0,download_url:_}}return null}s.upload=r;function l(h){return`${s.baseUrl}/api/needle/blob/${h}`}s.getBlobUrlForKey=l;async function c(h,d){var u;const p=await fetch(h),g=(u=p.body)==null?void 0:u.getReader(),y=p.headers.get("Content-Length"),f=y?parseInt(y):0;if(!g)return null;let v=0;const b=[];for(;;){const{done:C,value:R}=await g.read();if(R&&(b.push(R),v+=R.length,d?.call(null,new ProgressEvent("progress",{loaded:v,total:f}))),C)break}const w=new Uint8Array(v);let _=0;for(const C of b)w.set(C,_),_+=C.length;return w}s.download=c})(Rr||(Rr={}));const yo=O("debugaddressables");class z_{constructor(t){a(this,"_context"),a(this,"_assetReferences",{}),a(this,"preUpdate",()=>{}),this._context=t,this._context.pre_update_callbacks.push(this.preUpdate)}dispose(){const t=this._context.pre_update_callbacks.indexOf(this.preUpdate);t>=0&&this._context.pre_update_callbacks.splice(t,1);for(const i in this._assetReferences){const n=this._assetReferences[i];n?.unload()}this._assetReferences={}}findAssetReference(t){return this._assetReferences[t]||null}registerAssetReference(t){return t.url&&(this._assetReferences[t.url]?console.warn("Asset reference already registered",t):this._assetReferences[t.url]=t),t}unregisterAssetReference(t){t.url&&delete this._assetReferences[t.url]}}const Qg=Symbol("assetReference"),Na=class{constructor(s,t,i=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=s;const n=s.lastIndexOf("/");if(n>=0){this._urlName=s.substring(n+1);const o=this._urlName.lastIndexOf(".");o>=0&&(this._urlName=this._urlName.substring(0,o))}else this._urlName=s;this._hash=t,s.includes("?v=")?this._hashedUri=s:this._hashedUri=t?s+"?v="+t:s,i!==null&&(this.asset=i),u_(this._url,this.onResolvePrefab.bind(this))}static getOrCreateFromUrl(s,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 i=t.addressables,n=i.findAssetReference(s);if(n)return n;const o=new Na(s,t.hash);return i.registerAssetReference(o),o}static getOrCreate(s,t,i){if(typeof s=="string"){if(!i&&(i=ee.Current,!i))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 i=s.context,s=s.sourceId;const n=ho(s,t);yo&&console.log("GetOrCreate Addressable from",s,t,"FinalPath=",n);const o=i.addressables,r=o.findAssetReference(n);if(r)return r;const l=new Na(n,i.hash);return o.registerAssetReference(l),l}get isAssetReference(){return!0}get asset(){return this._glbRoot??this._asset}set asset(s){this._asset=s}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(s){return s===this.url&&(this.mustLoad&&await this.loadAssetAsync(),this.asset)?this.asset:null}get mustLoad(){return!this.asset||this.asset.__destroyed===!0||kr(this.asset)===!0}isLoaded(){return this._rawBinary||this.asset!==void 0}unload(){this.asset&&(yo&&console.log("Unload",this.asset),"scene"in this.asset&&this.asset.scene&&Ri(this.asset.scene,!0,!0),Ri(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,yo&&console.log("Preload",this._hashedUri);const s=await Rr.download(this._hashedUri,t=>{this.raiseProgressEvent(t)});return this._rawBinary=s?.buffer??null,this._isLoadingRawBinary=!1,this._rawBinary}async loadAssetAsync(s){if(yo&&console.log("loadAssetAsync",this.url),!this.mustLoad)return this.asset;if(s&&this._progressListeners.push(s),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=fs().parseSync(t,this._rawBinary,this.url,null),this.raiseProgressEvent(new ProgressEvent("progress",{loaded:this._rawBinary.byteLength,total:this._rawBinary.byteLength}))}else yo&&console.log("Load async",this.url),this._loading=fs().loadSync(t,this._hashedUri,this.url,null,n=>{this.raiseProgressEvent(n)});const i=await this._loading;return this._progressListeners.length=0,this._glbRoot=this.tryGetActualGameObjectRoot(i),this._loading=void 0,i?(i[Qg]=this,this._glbRoot&&(this._glbRoot[Qg]=this),this.asset&&(this.asset[Qg]=this),Hd(t),i.scene!==void 0&&(this.asset=i),this.asset):null}async instantiate(s){return this.onInstantiate(s,!1)}async instantiateSynced(s,t=!0){return this.onInstantiate(s,!0,t)}beginListenDownload(s){this._progressListeners.indexOf(s)<0&&this._progressListeners.push(s)}endListenDownload(s){const t=this._progressListeners.indexOf(s);t>=0&&this._progressListeners.splice(t,1)}raiseProgressEvent(s){for(const t of this._progressListeners)t(this,s)}async onInstantiate(s,t=!1,i){const n=ee.Current,o=new Ds;if(s instanceof I?o.parent=s:s&&(Object.assign(o,s),o.cloneAssign(s)),o.parent||(o.parent=n.scene),this.mustLoad&&await this.loadAssetAsync(),yo&&console.log("Instantiate",this.url,"parent:",s),this.asset){yo&&console.log("Add to scene",this.asset);let r=Na.currentlyInstantiating.get(this.url);if(r!==void 0&&r>=1e4)return console.error("Recursive or too many instantiations of "+this.url+" in the same frame ("+r+")"),null;try{if(r===void 0&&(r=0),r+=1,Na.currentlyInstantiating.set(this.url,r),t){o.context=n;const l=this.asset;l.guid=this.url;const c=Dg(l,o,void 0,i);if(c)return c}else{const l=Ua(this.asset,o);if(l)return l}}finally{n.post_render_callbacks.push(()=>{r===void 0||r<0?r=0:r-=1,Na.currentlyInstantiating.set(this.url,r)})}}else yo&&console.warn("Failed to load asset",this.url);return null}tryGetActualGameObjectRoot(s){if(s&&s.scene){const t=s.scene;return t.isGroup&&t.children.length===1&&t.children[0].name+"glb"===t.name?t.children[0]:t}return null}};let ae=Na;a(ae,"currentlyInstantiating",new Map);class H2 extends Zi{constructor(){super([ae],"AssetReferenceSerializer")}onSerialize(t,i){if(t&&t.uri!==void 0&&typeof t.uri=="string")return t.uri}onDeserialize(t,i){if(typeof t=="string")return i.context?i.gltfId?ae.getOrCreate(i.gltfId,t,i.context):(console.error("Missing source id"),null):(console.error("Missing context"),null);if(t instanceof I){if(!i.context)return console.error("Missing context"),null;if(!i.gltfId)return console.error("Missing source id"),null;const n=t,o=i.context,r=n.guid??n.uuid,l=o.addressables.findAssetReference(r);if(l)return l;const c=new ae(r,void 0,n);return o.addressables.registerAssetReference(c),c}return null}}new H2;const $2=Promise.resolve(null),ru=class{constructor(s){a(this,"url"),a(this,"_bitmap"),a(this,"_bitmapObject"),a(this,"loader",null),this.url=s}static getOrCreate(s){let t=ru.imageReferences.get(s);return t||(t=new ru(s),ru.imageReferences.set(s,t)),t}dispose(){this._bitmapObject&&this._bitmapObject.close(),this._bitmap=void 0}createHTMLImage(){const s=new Image;return s.src=this.url,s}createTexture(){return this.url?(this.loader||(this.loader=new ba),this.loader.setCrossOrigin("anonymous"),this.loader.loadAsync(this.url)):$2}getBitmap(){return this._bitmap?this._bitmap:(this._bitmap=new Promise((s,t)=>{const i=document.createElement("img");i.addEventListener("load",()=>{this._bitmap=createImageBitmap(i).then(n=>(this._bitmapObject=n,s(n),n))}),i.addEventListener("error",n=>{console.error("Failed to load image:"+this.url,n),s(null)}),i.src=this.url}),this._bitmap)}};let au=ru;a(au,"imageReferences",new Map);class U_ extends Zi{constructor(){super([au],"ImageReferenceSerializer")}onSerialize(t,i){return null}onDeserialize(t,i){if(typeof t=="string"){const n=ho(i.gltfId,t);return au.getOrCreate(n)}}}new U_;const lu=class{constructor(s){a(this,"url"),a(this,"res"),this.url=s}static getOrCreate(s){let t=lu.cache.get(s);return t||(t=new lu(s),lu.cache.set(s,t)),t}async loadRaw(){return this.res||(this.res=fetch(this.url)),this.res.then(s=>s.blob())}async loadText(){return this.res||(this.res=fetch(this.url)),this.res.then(s=>s.text())}};let cu=lu;a(cu,"cache",new Map);class N_ extends Zi{constructor(){super([cu],"FileReferenceSerializer")}onSerialize(t,i){return null}onDeserialize(t,i){if(typeof t=="string"){const n=ho(i.gltfId,t);return cu.getOrCreate(n)}}}new N_;class q2{constructor(t){a(this,"context"),a(this,"mixers",[]),this.context=t}onDestroy(){this.mixers.forEach(t=>t.stopAllAction()),this.mixers.length=0}registerAnimationMixer(t){if(!t){console.warn("AnimationsRegistry.registerAnimationMixer called with null or undefined mixer");return}this.mixers.includes(t)||this.mixers.push(t)}unregisterAnimationMixer(t){if(!t){console.warn("AnimationsRegistry.unregisterAnimationMixer called with null or undefined mixer");return}const i=this.mixers.indexOf(t);i!==-1&&this.mixers.splice(i,1)}}class Wa{static tryGetActionsFromMixer(t){return t._actions||null}static tryGetAnimationClipsFromObjectHierarchy(t,i){if(i||(i=new Array),t)t.animations&&i.push(...t.animations);else return i;if(t.children)for(const n of t.children)this.tryGetAnimationClipsFromObjectHierarchy(n,i);return i}static assignAnimationsFromFile(t,i){if(!t||!t.animations){console.debug("No animations found in file");return}for(let o=0;o<t.animations.length;o++){const r=t.animations[o];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=_a.parseTrackName(c.name);let d=_a.findNode(t.scene,h.nodeName);if(!d){const p=c.__objectName??c.name.substring(0,c.name.indexOf("."));if(d=t.scene.getObjectByProperty("uuid",p),!d)continue}let u=n(d);if(!u){if(!(i!=null&&i.createAnimationComponent)){console.warn("No AnimationComponent found in parent hierarchy of object and no 'createAnimationComponent' callback was provided in options.");continue}u=i.createAnimationComponent(t.scene,r)}u.addClip&&u.addClip(r)}}function n(o){var r;if(!o)return null;const l=(r=o.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 o}return n(o.parent)}}}var hu=(s=>(s.Visible="application-visible",s.Hidden="application-hidden",s.MuteChanged="application-mutechanged",s))(hu||{});let du=!1;const Va=[];function Tr(){if(du)return;F()&&console.debug("User interaction registered: audio can now be played"),du=!0;const s=[...Va];Va.length=0,s.forEach(t=>t())}document.addEventListener("mousedown",Tr),document.addEventListener("pointerup",Tr),document.addEventListener("click",Tr),document.addEventListener("dragstart",Tr),document.addEventListener("touchend",Tr),document.addEventListener("keydown",Tr),J.onXRSessionStart(()=>{Tr()});const W_=class extends EventTarget{constructor(s){super(),a(this,"_mute",!1),a(this,"context"),a(this,"_isVisible",!0),this.context=s,window.addEventListener("visibilitychange",this.onVisiblityChanged.bind(this),!1)}static get userInteractionRegistered(){return du}static registerWaitForInteraction(s){if(s!==null){if(du){s();return}Va.indexOf(s)===-1&&Va.push(s)}}static unregisterWaitForInteraction(s){const t=Va.indexOf(s);t!==-1&&Va.splice(t,1)}get muted(){return this._mute}set muted(s){s!==this._mute&&(this._mute=s,this.dispatchEvent(new Event("application-mutechanged")))}get hasFocus(){return document.hasFocus()}get isVisible(){return this._isVisible}onVisiblityChanged(s){switch(s.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}}};let Rn=W_;a(Rn,"registerWaitForAllowAudio",W_.registerWaitForInteraction);function*V_(s,t=null){const i=t?t.time:ee.Current.time,n=i.time;for(;i.time-n<s;)yield}function*G2(s){for(let t=0;t<s;t++)yield}function*H_(s){let t=!0;for(s.then(()=>t=!1),s.catch(()=>t=!1);t;)yield}const $_="NEEDLE_lightmaps",Rc=O("debuglightmapsextension")||O("debuglightmaps");var vo=(s=>(s[s.Lightmap=0]="Lightmap",s[s.Skybox=1]="Skybox",s[s.Reflection=2]="Reflection",s))(vo||{});class X2{constructor(t,i,n){a(this,"parser"),a(this,"registry"),a(this,"source"),this.parser=t,this.registry=i,this.source=n}get name(){return $_}afterRoot(t){const i=this.parser.json.extensions;if(i){const n=i[$_];if(n){const o=n.textures;return o!=null&&o.length?(Rc&&console.log(n),new Promise(async(r,l)=>{const c=[];for(const d of o)if(d.pointer){Rc&&console.log(d);let u=null;if(d.pointer.startsWith("/textures/"))Rc&&console.log("Load texture from gltf",d.pointer),u=zg(this.parser,d.pointer).then(p=>this.resolveTexture(d,p));else if(typeof d.pointer=="string"){Rc&&console.log("Load texture from path",d.pointer);const p=ho(this.source,d.pointer);let g;p.endsWith(".exr")?g=new vd(this.parser.options.manager):p.endsWith(".hdr")?g=new xm(this.parser.options.manager):g=new ba(this.parser.options.manager),u=g.loadAsync(p,void 0).then(y=>this.resolveTexture(d,y))}else d.pointer;u&&c.push(u)}const h=await wd(c);h!=null&&h.anyFailed&&F()&&console.error("Failed to load lightmap extension",h),r()})):null}}return null}resolveTexture(t,i){const n=i;Rc&&console.log("Lightmap loaded:",n),n!=null&&n.isTexture&&(this.registry?(n.colorSpace=mr,this.registry.registerTexture(this.source,t.type,n,t.index)):console.log(vo[t.type],t.pointer,n))}}const q_=!!O("debuglightmaps");class Q2{constructor(t){a(this,"_context"),a(this,"_lightmaps",new Map),this._context=t}clear(){this._lightmaps.clear()}registerTexture(t,i,n,o){q_&&console.log("Registering ",vo[i]+' "'+t+'"',n),this._lightmaps.has(t)||this._lightmaps.set(t,new Map);const r=this._lightmaps.get(t),l=r?.get(i)??[];l.length<o&&(l.length=o+1),l[o]=n,r?.set(i,l)}tryGetLightmap(t,i=0){return this.tryGet(t,vo.Lightmap,i)}tryGetSkybox(t){return this.tryGet(t,vo.Skybox,0)}tryGetReflection(t){return this.tryGet(t,vo.Reflection,0)}tryGet(t,i,n){if(!t)return q_&&console.warn("Missing source id"),null;const o=this._lightmaps.get(t);if(!o)return null;const r=o.get(i);return r===void 0||!(r!=null&&r.length)||r.length<=n?null:r[n]}}qt.lights_fragment_maps=qt.lights_fragment_maps.replace("vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );",`
179
+ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis`,t))),P_()&&console.log("[onGetComponent] FIND",t),t==null))return null;for(let o=0;o<s.userData.components.length;o++){const r=s.userData.components[o];let l=Object.getPrototypeOf(r);for(;l;){if(l===t.prototype)if(P_()&&console.log("[onGetComponent] MATCH BY PROTOYPE",l),i)i.push(r);else return r;l=Object.getPrototypeOf(l)}}return i||null}function Pr(s,t){const i=T_(s,t);return i?Array.isArray(i)?i[0]:i:null}function Oc(s,t,i,n=!0){return i||(i=[]),n&&(i.length=0),T_(s,t,i),i}function Pc(s,t,i){var n;const o=Pr(s,t);if(i===!1&&o?.enabled===!1)return null;if(o)return o;for(let r=0;r<((n=s?.children)==null?void 0:n.length);r++){const l=Pc(s.children[r],t);if(l)return l}return null}function Ba(s,t,i,n=!0){var o;i||(i=[]),n&&(i.length=0),Oc(s,t,i,!1);for(let r=0;r<((o=s?.children)==null?void 0:o.length);r++)Ba(s.children[r],t,i,!1);return i}function kc(s,t){if(!s)return null;if(Array.isArray(s)){for(let n=0;n<s.length;n++){const o=Nk(s[n]),r=kc(o,t);if(r)return r}return null}return Pr(s,t)||(s.parent?kc(s.parent,t):null)}function Kd(s,t,i,n=!0){return i||(i=[]),n&&(i.length=0),s?(Oc(s,t,i,!1),s.parent?Kd(s.parent,t,i,!1):i):i}function Zd(s,t=void 0,i=!0){if(!s)return null;if(!t&&(t=ee.Current,!t))return console.error("Can not search object without any needle context or scene!!!"),null;let n=t;if(n.isScene||(n=t?.scene),!n)return null;for(const o in n.children){const r=n.children[o];if(i===!1&&r[Sn]===!1)continue;const l=Pc(r,s);if(l)return l}return null}function E_(s,t,i=void 0){if(!s)return t??[];if(t||(t=[]),t.length=0,!i&&(i=ee.Current,!i))return console.error("Can not search object without any needle context or scene!!!"),t;"scene"in i&&(i=i.scene);const n=i;if(!n)return t;for(const o in n.children){const r=n.children[o];Ba(r,s,t,!1)}return t}function Jd(s){s&&s.isObject3D===!0&&C_(s,I)}I.prototype.SetActive=function(s){this.visible=s},I.prototype.setActive=function(s){this.visible=s},I.prototype.destroy=function(){Ri(this)},I.prototype.addComponent=function(s,t){return Mi(this,s,t)},I.prototype.addNewComponent=function(s,t){return Mi(this,s,t)},I.prototype.removeComponent=function(s){return $g(this,s)},I.prototype.getOrAddComponent=function(s,t){return Cc(this,s,t)},I.prototype.getComponent=function(s){return Pr(this,s)},I.prototype.getComponents=function(s,t){return Oc(this,s,t)},I.prototype.getComponentInChildren=function(s){return Pc(this,s)},I.prototype.getComponentsInChildren=function(s,t){return Ba(this,s,t)},I.prototype.getComponentInParent=function(s){return kc(this,s)},I.prototype.getComponentsInParent=function(s,t){return Kd(this,s,t)},Object.getOwnPropertyDescriptor(I.prototype,"activeSelf")||Object.defineProperty(I.prototype,"activeSelf",{get:function(){return Fa(this)},set:function(s){Mc(this,s)}}),Object.getOwnPropertyDescriptor(I.prototype,"worldPosition")||Object.defineProperty(I.prototype,"worldPosition",{get:function(){return this instanceof rv?te(this.object):te(this)},set:function(s){dt(this,s)}}),Object.getOwnPropertyDescriptor(I.prototype,"worldQuaternion")||Object.defineProperty(I.prototype,"worldQuaternion",{get:function(){return this instanceof rv?Oe(this.object):Oe(this)},set:function(s){Gi(this,s)}}),Object.getOwnPropertyDescriptor(I.prototype,"worldRotation")||Object.defineProperty(I.prototype,"worldRotation",{get:function(){return sc(this)},set:function(s){Xm(this,s)}}),Object.getOwnPropertyDescriptor(I.prototype,"worldScale")||Object.defineProperty(I.prototype,"worldScale",{get:function(){return Je(this)},set:function(s){Pa(this,s)}}),Object.getOwnPropertyDescriptor(I.prototype,"worldForward")||Object.defineProperty(I.prototype,"worldForward",{get:function(){return G().set(0,0,1).applyQuaternion(Oe(this))}}),Object.getOwnPropertyDescriptor(I.prototype,"worldRight")||Object.defineProperty(I.prototype,"worldRight",{get:function(){return G().set(1,0,0).applyQuaternion(Oe(this))}}),Object.getOwnPropertyDescriptor(I.prototype,"worldUp")||Object.defineProperty(I.prototype,"worldUp",{get:function(){return G().set(0,1,0).applyQuaternion(Oe(this))}}),O_(I);class Se extends re{constructor(t,i,n,o){var r=(...l)=>{super(...l),a(this,"alpha",1)};i!=null&&n!=null?(r(t,i,n),this.alpha=o):(r(t),this.alpha=1)}get isRGBAColor(){return!0}set a(t){this.alpha=t}get a(){return this.alpha}clone(){const t=super.clone();return t.alpha=this.alpha,t}copy(t){return this.r=t.r,this.g=t.g,this.b=t.b,"alpha"in t&&typeof t.alpha=="number"?this.alpha=t.alpha:typeof t.a=="number"&&(this.alpha=t.a),this}lerp(t,i){const n=t;return n.alpha!=null&&(this.alpha=W.lerp(this.alpha,n.alpha,i)),super.lerp(t,i)}lerpColors(t,i,n){const o=t,r=i;return o.alpha!=null&&r.alpha!=null&&(this.alpha=W.lerp(o.alpha,r.alpha,n)),super.lerpColors(t,i,n)}multiply(t){const i=t;return i.alpha!=null&&(this.alpha=this.alpha*i.alpha),super.multiply(t)}fromArray(t,i=0){return this.alpha=t[i+3],super.fromArray(t,i)}}const eu=O("debuggetcomponent"),tu=O("debuginstantiate");class Ds{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 t,i,n;const o=new Ds;return o.idProvider=this.idProvider,o.parent=this.parent,o.keepWorldPosition=this.keepWorldPosition,o.position=(t=this.position)==null?void 0:t.clone(),o.rotation=(i=this.rotation)==null?void 0:i.clone(),o.scale=(n=this.scale)==null?void 0:n.clone(),o.visible=this.visible,o.context=this.context,o.components=this.components,o}cloneAssign(t){var i,n,o;this.idProvider=t.idProvider,this.parent=t.parent,this.keepWorldPosition=t.keepWorldPosition,this.position=(i=t.position)==null?void 0:i.clone(),this.rotation=(n=t.rotation)==null?void 0:n.clone(),this.scale=(o=t.scale)==null?void 0:o.clone(),this.visible=t.visible,this.context=t.context,this.components=t.components}}function Fa(s){return s.visible}function Mc(s,t){return typeof t=="number"&&(t=t>.5),s.visible=t,s.visible}function A_(s){return s[Sn]||iu(s)}function I_(s,t){s[e_]=t}function iu(s){return cs.isUsingInstancing(s)}function qg(s,t){return Ca(s,t,!0,!0)}const j_=Symbol("isDestroyed");function kr(s){return s[j_]}function L_(s,t){s[j_]=t}const Gg=Symbol("isDontDestroy");function za(s,t=!0){s[Gg]=t}const su=[],nu=[];function Ri(s,t=!0,i=!1){su.length=0,nu.length=0,Xg(s,t,!0);for(const n of su)n.gameObject=null,n.context=null;for(const n of nu)L_(n,!0),i&&Ee(n),Zb(n);nu.length=0,su.length=0}function Xg(s,t=!0,i=!0){var n;if(s==null)return;const o=s;if(o.isComponent){if(o[Gg])return;su.push(o);const c=o.gameObject;o.__internalDisable(),o.__internalDestroy(),o.gameObject=c;return}if(s[Gg])return;const r=s;eu&&console.log(r),nu.push(r);const l=(n=r.userData)==null?void 0:n.components;if(l!=null&&Array.isArray(l)){let c=l.length;for(let h=0;h<l.length;h++){const d=l[h];Xg(d,t,!1),l.length<c&&(c=l.length,h--)}}if(t&&r.children)for(const c of r.children)Xg(c,t,!1);i&&r.removeFromParent()}function Mr(s,t,i=!0){return D_(s,t,i)}function*ou(s,t,i=!1,n=999,o=0){if(s!=null&&s.userData.components&&!(o>n)){for(const r of s.userData.components)t&&r?.isComponent===!0&&r instanceof t?yield r:yield r;if(i===!0)for(const r of s.children)yield*ou(r,t,!0,n,o+1)}}function D_(s,t,i,n=0){var o;if(s){if(s.isObject3D,n>1e3){console.warn("Failed to iterate components: too many levels");return}if((o=s.userData)!=null&&o.components)for(let r=0;r<s.userData.components.length;r++){const l=s.userData.components[r];if(l?.isComponent===!0){const c=t(l);if(c!==void 0)return c}}if(i&&s.children){const r=n+1;for(let l=0;l<s.children.length;l++){const c=s.children[l];if(!c)continue;const h=D_(c,t,i,r);if(h!==void 0)return h}}}}function Ua(s,t){if("isAssetReference"in s)return s.instantiate(t??void 0);let i=null;t!=null&&(t.x!==void 0?(i=new Ds,i.position=t):i=t);let n=ee.Current;i!=null&&i.context&&(n=i.context),eu&&n.alias&&console.log("context",n.alias),i&&!i.idProvider&&(i.idProvider=new zt(Date.now()));const o=[],r={},l={},c=B_(n,s,i,o,r,l);c&&(Vk(r),Wk(l,r)),eu&&(kd(s,!0),kd(c,!0));const h={};if(i?.components!==!1){for(const d in o){const u=o[d],p=u.guid;i&&i.idProvider&&(u.guid=i.idProvider.generateUUID(),h[p]=u.guid,eu&&console.log(u.name,u.guid)),wu(u,n),u.__internalNewInstanceCreated&&u.__internalNewInstanceCreated()}for(const d in o){const u=o[d];u.resolveGuids&&u.resolveGuids(h),u.enabled!==!1&&(u.enabled=!0)}Hd(n)}return c}function B_(s,t,i,n,o,r){var l;if(!t)return null;const c=t.userData;t.userData={};const h=t.children;t.children=[];const d=t.clone(!1);if(Jd(d),t.userData=c,t.children=h,o[t.uuid]={original:t,clone:d},tu&&console.log("ADD",t,d),t.type==="SkinnedMesh"&&(r[t.uuid]={original:t,clone:d}),i?.visible!==void 0&&(d.visible=i.visible),i!=null&&i.idProvider){d.uuid=i.idProvider.generateUUID();const p=d;p&&(p.guid=d.uuid)}t.animations&&t.animations.length>0&&(d.animations=[...t.animations]);const u=t.parent;if(u&&u.add(d),i!=null&&i.position?dt(d,i.position):d.position.copy(t.position),i!=null&&i.rotation?Gi(d,i.rotation):d.quaternion.copy(t.quaternion),i!=null&&i.scale?d.scale.copy(i.scale):d.scale.copy(t.scale),i!=null&&i.parent&&i.parent!=="scene"){let p=null;if(typeof i.parent=="string"?p=Ca(i.parent,s.scene,!0):p=i.parent,p){const g=i.keepWorldPosition===!0?p.attach:p.add;g?g.call(p,d):console.error("Invalid parent object",p,"received when instantiating:",t)}else console.warn("could not find parent:",i.parent)}for(const[p,g]of Object.entries(t.userData))p!=="components"&&(d.userData[p]=g);if((l=t.userData)!=null&&l.components){const p=t.userData.components,g=[];d.userData.components=g;for(let y=0;y<p.length;y++){const f=p[y],v=new f.constructor;Da(v,f),f[dc]!==void 0&&(v[dc]=f[dc]),g.push(v),v.gameObject=d,n.push(v),o[f.guid]={original:f,clone:v},vc.dispatchComponentLifecycleEvent("component-added",v)}}i&&(i.position=void 0,i.rotation=void 0,i.scale=void 0,i.parent=void 0);for(const p in t.children){const g=t.children[p],y=B_(s,g,i,n,o,r);y&&d.add(y)}return d}function Wk(s,t){for(const i in s){const n=s[i],o=n.original,r=o.skeleton,l=n.clone;if(!r){console.warn("Skinned mesh has no skeleton?",n);continue}const c=r.bones,h=l.skeleton.clone();l.skeleton=h,l.bindMatrix.clone().copy(o.bindMatrix),l.bindMatrixInverse.copy(o.bindMatrixInverse);const d=[];h.bones=d;for(let u=0;u<c.length;u++){const p=c[u],g=t[p.uuid].clone;d.push(g)}}for(const i in s){const n=s[i].clone;n.skeleton.update(),n.bind(n.skeleton,n.bindMatrix),n.updateMatrixWorld(!0)}}function Vk(s){var t;for(const i in s){const n=s[i].clone;if(n!=null&&n.isObject3D&&(t=n?.userData)!=null&&t.components)for(let o=0;o<n.userData.components.length;o++){const r=n.userData.components[o],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=F_(r,c,p,s);g!==void 0?d.push(g):d.push(p)}}else if(typeof h=="object"){const d=F_(r,c,h,s);d!==void 0&&(r[c]=d)}}}}function F_(s,t,i,n){var o,r;if(i!=null)if(i.isComponent===!0){const l=i.gameObject;if(l){const c=l.uuid,h=(o=n[c])==null?void 0:o.clone;if(!h){tu&&console.log("reference did not change",t,s,i);return}const d=l.userData.components.indexOf(i);if(d>=0&&h.isObject3D)return tu&&console.log(t,c),h.userData.components[d];console.warn("could not find component",t,i)}}else if(i.isObject3D===!0){if(t==="gameObject")return;const l=i;if(l){const c=l.uuid,h=(r=n[c])==null?void 0:r.clone;if(h)return tu&&console.log(t,"old",i,"new",h),h}}else{if(i.isVector4||i.isVector3||i.isVector2||i.isQuaternion||i.isEuler||i.isColor===!0)return i.clone();if(i.isEventList===!0)return i.__internalOnInstantiate(n)}}var Rr;(s=>{s.baseUrl="https://networking.needle.tools";function t(h){return pv(new Uint8Array(h))}s.hashMD5=t;function i(h){const d=pv(new Uint8Array(h),{encoding:"binary",asBytes:!0});return btoa(String.fromCharCode(...d))}s.hashMD5_Base64=i;function n(h){const d=new Uint8Array(h);return crypto.subtle.digest("SHA-256",d).then(u=>btoa(String.fromCharCode(...new Uint8Array(u))))}s.hashSha256=n;function o(h){const d=h.filesize/1024/1024;return Os()?d<50:d<5}s.canUpload=o;async function r(h,d){var u;const p=s.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 y=g.byteLength,f=y/1024/1024;if(f>50)return d?.silent!==!0&&xe(`File (${f.toFixed(1)}MB) is too large for uploading (see console for details)`),console.warn(`Your file is too large for uploading (${f.toFixed(1)}MB). Max allowed size is 50MB`),null;if(!Os()&&f>5)return d?.silent!==!0&&xe('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 (${f.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(y<1)return console.warn(`Your file is too small for uploading (${f.toFixed(1)}MB). Min size is 1 byte`),null;const v=i(g),b={filename:h.name,"Content-Md5":v,"Content-Type":h.type||"application/octet-stream",FileSize:y.toString(),"Content-Disposition":`attachment; filename="${h.name}"`,"x-amz-server-side-encryption":"AES256"},w=await fetch(p+"/api/needle/blob",{method:"POST",headers:b,signal:d?.abort}).then(_=>_.json()).catch(_=>(console.error(_),null));if(w==null)return console.warn("Upload failed..."),null;if("error"in w)return console.error(w.error),null;if("upload"in w&&w.upload){let _=function(M){var T;return(T=d?.onProgress)==null||T.call(null,{progress01:0,state:"inprogress"}),fetch(M,{method:"PUT",headers:b,body:g,signal:d?.abort}).then(j=>{var D;return(D=d?.onProgress)==null||D.call(null,{progress01:1,state:"finished"}),j}).catch(j=>j)};console.debug("Uploading file",w.upload);let C=!1,R=null;for(let M=0;M<3;M++)try{if(C)break;if((u=d?.abort)!=null&&u.aborted)return console.debug("Aborted upload"),null;const T=await _(w.upload);T instanceof Error?(R=T,await ys(1e3*M)):T.ok&&(console.debug("File uploaded successfully"),C=!0)}catch(T){console.error(T)}if(!C)return console.error(R?.message||"Failed to upload file"),null}if("download"in w){const _=p+w.download;return console.debug("File found in blob storage",_),{key:w.key,success:!0,download_url:_}}return null}s.upload=r;function l(h){return`${s.baseUrl}/api/needle/blob/${h}`}s.getBlobUrlForKey=l;async function c(h,d){var u;const p=await fetch(h),g=(u=p.body)==null?void 0:u.getReader(),y=p.headers.get("Content-Length"),f=y?parseInt(y):0;if(!g)return null;let v=0;const b=[];for(;;){const{done:C,value:R}=await g.read();if(R&&(b.push(R),v+=R.length,d?.call(null,new ProgressEvent("progress",{loaded:v,total:f}))),C)break}const w=new Uint8Array(v);let _=0;for(const C of b)w.set(C,_),_+=C.length;return w}s.download=c})(Rr||(Rr={}));const yo=O("debugaddressables");class z_{constructor(t){a(this,"_context"),a(this,"_assetReferences",{}),a(this,"preUpdate",()=>{}),this._context=t,this._context.pre_update_callbacks.push(this.preUpdate)}dispose(){const t=this._context.pre_update_callbacks.indexOf(this.preUpdate);t>=0&&this._context.pre_update_callbacks.splice(t,1);for(const i in this._assetReferences){const n=this._assetReferences[i];n?.unload()}this._assetReferences={}}findAssetReference(t){return this._assetReferences[t]||null}registerAssetReference(t){return t.url&&(this._assetReferences[t.url]?console.warn("Asset reference already registered",t):this._assetReferences[t.url]=t),t}unregisterAssetReference(t){t.url&&delete this._assetReferences[t.url]}}const Qg=Symbol("assetReference"),Na=class{constructor(s,t,i=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=s;const n=s.lastIndexOf("/");if(n>=0){this._urlName=s.substring(n+1);const o=this._urlName.lastIndexOf(".");o>=0&&(this._urlName=this._urlName.substring(0,o))}else this._urlName=s;this._hash=t,s.includes("?v=")?this._hashedUri=s:this._hashedUri=t?s+"?v="+t:s,i!==null&&(this.asset=i),u_(this._url,this.onResolvePrefab.bind(this))}static getOrCreateFromUrl(s,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 i=t.addressables,n=i.findAssetReference(s);if(n)return n;const o=new Na(s,t.hash);return i.registerAssetReference(o),o}static getOrCreate(s,t,i){if(typeof s=="string"){if(!i&&(i=ee.Current,!i))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 i=s.context,s=s.sourceId;const n=ho(s,t);yo&&console.log("GetOrCreate Addressable from",s,t,"FinalPath=",n);const o=i.addressables,r=o.findAssetReference(n);if(r)return r;const l=new Na(n,i.hash);return o.registerAssetReference(l),l}get isAssetReference(){return!0}get asset(){return this._glbRoot??this._asset}set asset(s){this._asset=s}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(s){return s===this.url&&(this.mustLoad&&await this.loadAssetAsync(),this.asset)?this.asset:null}get mustLoad(){return!this.asset||this.asset.__destroyed===!0||kr(this.asset)===!0}isLoaded(){return this._rawBinary||this.asset!==void 0}unload(){this.asset&&(yo&&console.log("Unload",this.asset),"scene"in this.asset&&this.asset.scene&&Ri(this.asset.scene,!0,!0),Ri(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,yo&&console.log("Preload",this._hashedUri);const s=await Rr.download(this._hashedUri,t=>{this.raiseProgressEvent(t)});return this._rawBinary=s?.buffer??null,this._isLoadingRawBinary=!1,this._rawBinary}async loadAssetAsync(s){if(yo&&console.log("loadAssetAsync",this.url),!this.mustLoad)return this.asset;if(s&&this._progressListeners.push(s),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=fs().parseSync(t,this._rawBinary,this.url,null),this.raiseProgressEvent(new ProgressEvent("progress",{loaded:this._rawBinary.byteLength,total:this._rawBinary.byteLength}))}else yo&&console.log("Load async",this.url),this._loading=fs().loadSync(t,this._hashedUri,this.url,null,n=>{this.raiseProgressEvent(n)});const i=await this._loading;return this._progressListeners.length=0,this._glbRoot=this.tryGetActualGameObjectRoot(i),this._loading=void 0,i?(i[Qg]=this,this._glbRoot&&(this._glbRoot[Qg]=this),this.asset&&(this.asset[Qg]=this),Hd(t),i.scene!==void 0&&(this.asset=i),this.asset):null}async instantiate(s){return this.onInstantiate(s,!1)}async instantiateSynced(s,t=!0){return this.onInstantiate(s,!0,t)}beginListenDownload(s){this._progressListeners.indexOf(s)<0&&this._progressListeners.push(s)}endListenDownload(s){const t=this._progressListeners.indexOf(s);t>=0&&this._progressListeners.splice(t,1)}raiseProgressEvent(s){for(const t of this._progressListeners)t(this,s)}async onInstantiate(s,t=!1,i){const n=ee.Current,o=new Ds;if(s instanceof I?o.parent=s:s&&(Object.assign(o,s),o.cloneAssign(s)),o.parent||(o.parent=n.scene),this.mustLoad&&await this.loadAssetAsync(),yo&&console.log("Instantiate",this.url,"parent:",s),this.asset){yo&&console.log("Add to scene",this.asset);let r=Na.currentlyInstantiating.get(this.url);if(r!==void 0&&r>=1e4)return console.error("Recursive or too many instantiations of "+this.url+" in the same frame ("+r+")"),null;try{if(r===void 0&&(r=0),r+=1,Na.currentlyInstantiating.set(this.url,r),t){o.context=n;const l=this.asset;l.guid=this.url;const c=Dg(l,o,void 0,i);if(c)return c}else{const l=Ua(this.asset,o);if(l)return l}}finally{n.post_render_callbacks.push(()=>{r===void 0||r<0?r=0:r-=1,Na.currentlyInstantiating.set(this.url,r)})}}else yo&&console.warn("Failed to load asset",this.url);return null}tryGetActualGameObjectRoot(s){if(s&&s.scene){const t=s.scene;return t.isGroup&&t.children.length===1&&t.children[0].name+"glb"===t.name?t.children[0]:t}return null}};let ae=Na;a(ae,"currentlyInstantiating",new Map);class Hk extends Zi{constructor(){super([ae],"AssetReferenceSerializer")}onSerialize(t,i){if(t&&t.uri!==void 0&&typeof t.uri=="string")return t.uri}onDeserialize(t,i){if(typeof t=="string")return i.context?i.gltfId?ae.getOrCreate(i.gltfId,t,i.context):(console.error("Missing source id"),null):(console.error("Missing context"),null);if(t instanceof I){if(!i.context)return console.error("Missing context"),null;if(!i.gltfId)return console.error("Missing source id"),null;const n=t,o=i.context,r=n.guid??n.uuid,l=o.addressables.findAssetReference(r);if(l)return l;const c=new ae(r,void 0,n);return o.addressables.registerAssetReference(c),c}return null}}new Hk;const $k=Promise.resolve(null),ru=class{constructor(s){a(this,"url"),a(this,"_bitmap"),a(this,"_bitmapObject"),a(this,"loader",null),this.url=s}static getOrCreate(s){let t=ru.imageReferences.get(s);return t||(t=new ru(s),ru.imageReferences.set(s,t)),t}dispose(){this._bitmapObject&&this._bitmapObject.close(),this._bitmap=void 0}createHTMLImage(){const s=new Image;return s.src=this.url,s}createTexture(){return this.url?(this.loader||(this.loader=new ba),this.loader.setCrossOrigin("anonymous"),this.loader.loadAsync(this.url)):$k}getBitmap(){return this._bitmap?this._bitmap:(this._bitmap=new Promise((s,t)=>{const i=document.createElement("img");i.addEventListener("load",()=>{this._bitmap=createImageBitmap(i).then(n=>(this._bitmapObject=n,s(n),n))}),i.addEventListener("error",n=>{console.error("Failed to load image:"+this.url,n),s(null)}),i.src=this.url}),this._bitmap)}};let au=ru;a(au,"imageReferences",new Map);class U_ extends Zi{constructor(){super([au],"ImageReferenceSerializer")}onSerialize(t,i){return null}onDeserialize(t,i){if(typeof t=="string"){const n=ho(i.gltfId,t);return au.getOrCreate(n)}}}new U_;const lu=class{constructor(s){a(this,"url"),a(this,"res"),this.url=s}static getOrCreate(s){let t=lu.cache.get(s);return t||(t=new lu(s),lu.cache.set(s,t)),t}async loadRaw(){return this.res||(this.res=fetch(this.url)),this.res.then(s=>s.blob())}async loadText(){return this.res||(this.res=fetch(this.url)),this.res.then(s=>s.text())}};let cu=lu;a(cu,"cache",new Map);class N_ extends Zi{constructor(){super([cu],"FileReferenceSerializer")}onSerialize(t,i){return null}onDeserialize(t,i){if(typeof t=="string"){const n=ho(i.gltfId,t);return cu.getOrCreate(n)}}}new N_;class qk{constructor(t){a(this,"context"),a(this,"mixers",[]),this.context=t}onDestroy(){this.mixers.forEach(t=>t.stopAllAction()),this.mixers.length=0}registerAnimationMixer(t){if(!t){console.warn("AnimationsRegistry.registerAnimationMixer called with null or undefined mixer");return}this.mixers.includes(t)||this.mixers.push(t)}unregisterAnimationMixer(t){if(!t){console.warn("AnimationsRegistry.unregisterAnimationMixer called with null or undefined mixer");return}const i=this.mixers.indexOf(t);i!==-1&&this.mixers.splice(i,1)}}class Wa{static tryGetActionsFromMixer(t){return t._actions||null}static tryGetAnimationClipsFromObjectHierarchy(t,i){if(i||(i=new Array),t)t.animations&&i.push(...t.animations);else return i;if(t.children)for(const n of t.children)this.tryGetAnimationClipsFromObjectHierarchy(n,i);return i}static assignAnimationsFromFile(t,i){if(!t||!t.animations){console.debug("No animations found in file");return}for(let o=0;o<t.animations.length;o++){const r=t.animations[o];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=_a.parseTrackName(c.name);let d=_a.findNode(t.scene,h.nodeName);if(!d){const p=c.__objectName??c.name.substring(0,c.name.indexOf("."));if(d=t.scene.getObjectByProperty("uuid",p),!d)continue}let u=n(d);if(!u){if(!(i!=null&&i.createAnimationComponent)){console.warn("No AnimationComponent found in parent hierarchy of object and no 'createAnimationComponent' callback was provided in options.");continue}u=i.createAnimationComponent(t.scene,r)}u.addClip&&u.addClip(r)}}function n(o){var r;if(!o)return null;const l=(r=o.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 o}return n(o.parent)}}}var hu=(s=>(s.Visible="application-visible",s.Hidden="application-hidden",s.MuteChanged="application-mutechanged",s))(hu||{});let du=!1;const Va=[];function Tr(){if(du)return;F()&&console.debug("User interaction registered: audio can now be played"),du=!0;const s=[...Va];Va.length=0,s.forEach(t=>t())}document.addEventListener("mousedown",Tr),document.addEventListener("pointerup",Tr),document.addEventListener("click",Tr),document.addEventListener("dragstart",Tr),document.addEventListener("touchend",Tr),document.addEventListener("keydown",Tr),J.onXRSessionStart(()=>{Tr()});const W_=class extends EventTarget{constructor(s){super(),a(this,"_mute",!1),a(this,"context"),a(this,"_isVisible",!0),this.context=s,window.addEventListener("visibilitychange",this.onVisiblityChanged.bind(this),!1)}static get userInteractionRegistered(){return du}static registerWaitForInteraction(s){if(s!==null){if(du){s();return}Va.indexOf(s)===-1&&Va.push(s)}}static unregisterWaitForInteraction(s){const t=Va.indexOf(s);t!==-1&&Va.splice(t,1)}get muted(){return this._mute}set muted(s){s!==this._mute&&(this._mute=s,this.dispatchEvent(new Event("application-mutechanged")))}get hasFocus(){return document.hasFocus()}get isVisible(){return this._isVisible}onVisiblityChanged(s){switch(s.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}}};let Rn=W_;a(Rn,"registerWaitForAllowAudio",W_.registerWaitForInteraction);function*V_(s,t=null){const i=t?t.time:ee.Current.time,n=i.time;for(;i.time-n<s;)yield}function*Gk(s){for(let t=0;t<s;t++)yield}function*H_(s){let t=!0;for(s.then(()=>t=!1),s.catch(()=>t=!1);t;)yield}const $_="NEEDLE_lightmaps",Rc=O("debuglightmapsextension")||O("debuglightmaps");var vo=(s=>(s[s.Lightmap=0]="Lightmap",s[s.Skybox=1]="Skybox",s[s.Reflection=2]="Reflection",s))(vo||{});class Xk{constructor(t,i,n){a(this,"parser"),a(this,"registry"),a(this,"source"),this.parser=t,this.registry=i,this.source=n}get name(){return $_}afterRoot(t){const i=this.parser.json.extensions;if(i){const n=i[$_];if(n){const o=n.textures;return o!=null&&o.length?(Rc&&console.log(n),new Promise(async(r,l)=>{const c=[];for(const d of o)if(d.pointer){Rc&&console.log(d);let u=null;if(d.pointer.startsWith("/textures/"))Rc&&console.log("Load texture from gltf",d.pointer),u=zg(this.parser,d.pointer).then(p=>this.resolveTexture(d,p));else if(typeof d.pointer=="string"){Rc&&console.log("Load texture from path",d.pointer);const p=ho(this.source,d.pointer);let g;p.endsWith(".exr")?g=new vd(this.parser.options.manager):p.endsWith(".hdr")?g=new xm(this.parser.options.manager):g=new ba(this.parser.options.manager),u=g.loadAsync(p,void 0).then(y=>this.resolveTexture(d,y))}else d.pointer;u&&c.push(u)}const h=await wd(c);h!=null&&h.anyFailed&&F()&&console.error("Failed to load lightmap extension",h),r()})):null}}return null}resolveTexture(t,i){const n=i;Rc&&console.log("Lightmap loaded:",n),n!=null&&n.isTexture&&(this.registry?(n.colorSpace=mr,this.registry.registerTexture(this.source,t.type,n,t.index)):console.log(vo[t.type],t.pointer,n))}}const q_=!!O("debuglightmaps");class Qk{constructor(t){a(this,"_context"),a(this,"_lightmaps",new Map),this._context=t}clear(){this._lightmaps.clear()}registerTexture(t,i,n,o){q_&&console.log("Registering ",vo[i]+' "'+t+'"',n),this._lightmaps.has(t)||this._lightmaps.set(t,new Map);const r=this._lightmaps.get(t),l=r?.get(i)??[];l.length<o&&(l.length=o+1),l[o]=n,r?.set(i,l)}tryGetLightmap(t,i=0){return this.tryGet(t,vo.Lightmap,i)}tryGetSkybox(t){return this.tryGet(t,vo.Skybox,0)}tryGetReflection(t){return this.tryGet(t,vo.Reflection,0)}tryGet(t,i,n){if(!t)return q_&&console.warn("Missing source id"),null;const o=this._lightmaps.get(t);if(!o)return null;const r=o.get(i);return r===void 0||!(r!=null&&r.length)||r.length<=n?null:r[n]}}qt.lights_fragment_maps=qt.lights_fragment_maps.replace("vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );",`
180
180
  vec2 lUv = vLightMapUv.xy * lightmapScaleOffset.xy + vec2(lightmapScaleOffset.z, (1. - (lightmapScaleOffset.y + lightmapScaleOffset.w)));
181
181
  vec4 lightMapTexel = texture2D( lightMap, lUv);
182
182
  // 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.
@@ -199,13 +199,13 @@ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects
199
199
  irradiance += 0.;
200
200
  #else
201
201
  irradiance += getLightProbeIrradiance( lightProbe, geometry.normal );
202
- #endif`),SS.lightmap.lightmapScaleOffset={value:new me(1,1,0,0)};const Yg=O("debugprogressive"),uu=new _i,pu=new dd;class Y2{constructor(t){a(this,"context"),a(this,"_lodsManager"),this.context=t}get manager(){return this._lodsManager}get targetTriangleDensity(){var t;return((t=this._lodsManager)==null?void 0:t.targetTriangleDensity)??-1}set targetTriangleDensity(t){this._lodsManager&&(this._lodsManager.targetTriangleDensity=t)}setRenderer(t){var i;(i=this._lodsManager)==null||i.disable(),xa.removePlugin(this),xa.addPlugin(this),xa.debugDrawLine=q.DrawLine,this._lodsManager=xa.get(t),this._lodsManager.enable()}disable(){var t;(t=this._lodsManager)==null||t.disable(),xa.removePlugin(this)}onAfterUpdatedLOD(t,i,n,o,r){Yg&&this.onRenderDebug(n,o,r)}onRenderDebug(t,i,n){var o,r,l;if(!i.geometry||!it.hasLODLevelAvailable(i.geometry)&&!it.hasLODLevelAvailable(i.material))return;const c=xa.getObjectLODState(i);if(!c)return;let h=n.mesh_lod;const d=n.mesh_lod!=c.lastLodLevel_Mesh||n.texture_lod!=c.lastLodLevel_Texture;if(Yg&&i.geometry.boundingSphere){const u=i.geometry.boundingSphere;pu.copy(u),pu.applyMatrix4(i.matrixWorld);const p=pu.center,g=pu.radius,y=["#76c43e","#bcc43e","#c4ac3e","#c4673e","#ff3e3e"];if(d)q.DrawWireSphere(p,g,y[h],.1);else{const f=((o=i.geometry.index)==null?void 0:o.count)??0,v=(r=it.getMeshLODInformation(i.geometry))==null?void 0:r.lods;h=v?Math.min(v?.length-1,h):0;let b="";if(v&&c.lastScreenCoverage>0)for(let C=0;C<v.length;C++){const R=v[C].density,M=C==v.length-1;b+=R.toFixed(0)+">"+(R/c.lastScreenCoverage).toFixed(0)+(M?"":",")}const w=v?(l=v[h])==null?void 0:l.density:-1;let _="LOD "+n.mesh_lod+`
202
+ #endif`),SS.lightmap.lightmapScaleOffset={value:new me(1,1,0,0)};const Yg=O("debugprogressive"),uu=new _i,pu=new dd;class Yk{constructor(t){a(this,"context"),a(this,"_lodsManager"),this.context=t}get manager(){return this._lodsManager}get targetTriangleDensity(){var t;return((t=this._lodsManager)==null?void 0:t.targetTriangleDensity)??-1}set targetTriangleDensity(t){this._lodsManager&&(this._lodsManager.targetTriangleDensity=t)}setRenderer(t){var i;(i=this._lodsManager)==null||i.disable(),xa.removePlugin(this),xa.addPlugin(this),xa.debugDrawLine=q.DrawLine,this._lodsManager=xa.get(t),this._lodsManager.enable()}disable(){var t;(t=this._lodsManager)==null||t.disable(),xa.removePlugin(this)}onAfterUpdatedLOD(t,i,n,o,r){Yg&&this.onRenderDebug(n,o,r)}onRenderDebug(t,i,n){var o,r,l;if(!i.geometry||!it.hasLODLevelAvailable(i.geometry)&&!it.hasLODLevelAvailable(i.material))return;const c=xa.getObjectLODState(i);if(!c)return;let h=n.mesh_lod;const d=n.mesh_lod!=c.lastLodLevel_Mesh||n.texture_lod!=c.lastLodLevel_Texture;if(Yg&&i.geometry.boundingSphere){const u=i.geometry.boundingSphere;pu.copy(u),pu.applyMatrix4(i.matrixWorld);const p=pu.center,g=pu.radius,y=["#76c43e","#bcc43e","#c4ac3e","#c4673e","#ff3e3e"];if(d)q.DrawWireSphere(p,g,y[h],.1);else{const f=((o=i.geometry.index)==null?void 0:o.count)??0,v=(r=it.getMeshLODInformation(i.geometry))==null?void 0:r.lods;h=v?Math.min(v?.length-1,h):0;let b="";if(v&&c.lastScreenCoverage>0)for(let C=0;C<v.length;C++){const R=v[C].density,M=C==v.length-1;b+=R.toFixed(0)+">"+(R/c.lastScreenCoverage).toFixed(0)+(M?"":",")}const w=v?(l=v[h])==null?void 0:l.density:-1;let _="LOD "+n.mesh_lod+`
203
203
  TEX `+n.texture_lod;if(Yg=="density"&&(_+=`
204
204
  `+f+` tris
205
205
  `+(w/c.lastScreenCoverage).toFixed(0)+` dens
206
206
  `+(c.lastScreenCoverage*100).toFixed(1)+`% cov
207
207
  `+(c.lastCentrality*100).toFixed(1)+`% centr
208
- `+(uu.min.x.toFixed(2)+"-"+uu.max.x.toFixed(2)+"x"+uu.min.y.toFixed(2)+"-"+uu.max.y.toFixed(2))+" scr"),c.lastScreenCoverage>.1){const C=t,R=C.worldForward,M=C.worldPosition,T=G(R).multiplyScalar(g*.7).add(p),j=T.distanceTo(M),D=y[Math.min(y.length-1,Math.max(0,h))]+"88",U=this.context.domHeight>0?screen.height/this.context.domHeight:1,B=t.isPerspectiveCamera?Math.tan(t.fov*Math.PI/180/2):1;q.DrawLabel(T,_,j*.012*U*B,void 0,16777215,D)}}}}}const K2=O("debugplayerview");var bo=(s=>(s.Browser="browser",s.Headset="headset",s.Handheld="handheld",s))(bo||{});class G_{constructor(t,i){a(this,"userId"),a(this,"context"),a(this,"viewDevice","browser"),a(this,"removed",!1),a(this,"_object"),this.userId=t,this.context=i}get currentObject(){return this._object}set currentObject(t){this._object=t}get isConnected(){return this.context.connection.userIsInRoom(this.userId)}}class X_{constructor(t){a(this,"context"),a(this,"playerViews",new Map),this.context=t}setPlayerView(t,i,n){let o=this.playerViews.get(t);o||(o=new G_(t,this.context),this.playerViews.set(t,o)),o.viewDevice=n,o.currentObject=i,o.removed=!1}getPlayerView(t){if(!!t){if(!this.context.connection.userIsInRoom(t)){this.playerViews.delete(t);return}return this.playerViews.get(t)}}removePlayerView(t,i){const n=this.playerViews.get(t);n?.viewDevice===i&&(K2&&console.log("REMOVE",t),n.removed=!0,this.playerViews.delete(t))}}new Yy;const Tc=new Uint8Array(4);Tc[0]=255,Tc[1]=255,Tc[2]=255,Tc[3]=255;const Z2=new dm(Tc,1,1,pd);function Kg(s,t=1){const i="alpha"in s,n=t*t,o=new Uint8Array(4*n),r=Math.floor(s.r*255),l=Math.floor(s.g*255),c=Math.floor(s.b*255);for(let d=0;d<n;d++){const u=d*4;o[u+0]=r,o[u+1]=l,o[u+2]=c,i?o[u+3]=Math.floor(s.alpha*255):o[u+3]=255}const h=new dm(o,t,t);return h.needsUpdate=!0,h}function J2(s,t,i,n=1,o=3){const r=n*o,l=[s,t,i],c=l.length,h=new Uint8Array(4*c*r),d=new re;for(let p=0;p<o;p++){const g=Math.floor(p/o*c),y=W.clamp(g+1,0,c-1),f=l[g],v=l[y],b=p/o*c%1;d.lerpColors(f,v,b);const w=Math.floor(d.r*255),_=Math.floor(d.g*255),C=Math.floor(d.b*255);for(let R=0;R<n;R++){const M=(p*n+R)*4;h[M+0]=w,h[M+1]=_,h[M+2]=C,h[M+3]=255}}const u=new dm(h,n,o);return u.needsUpdate=!0,u}function mu(s,t){const i=s.elements;t||(t=[]),t.length=0;for(let n=0;n<16;n+=4){const o=i[n],r=i[n+1],l=i[n+2],c=i[n+3],h=new me(o,r,l,c);t.push(h)}return t}const Zg=[],Q_=[];function ek(s,t){if(Zg.length===0)for(let i=0;i<27;i++)Zg.push(0);t||(t=Zg);for(let i=0;i<27;i++)Q_[i]=t[i];t=Q_,s.unity_SHAr={value:new me(t[9],t[3],t[6],t[0])},s.unity_SHBr={value:new me(t[12],t[15],t[18],t[21])},s.unity_SHAg={value:new me(t[10],t[4],t[7],t[1])},s.unity_SHBg={value:new me(t[13],t[16],t[19],t[22])},s.unity_SHAb={value:new me(t[11],t[5],t[8],t[2])},s.unity_SHBb={value:new me(t[14],t[17],t[20],t[23])},s.unity_SHC={value:new me(t[24],t[25],t[26],1)}}class tk{constructor(t,i,n){a(this,"vertexShader"),a(this,"fragmentShader"),a(this,"technique"),this.vertexShader=t,this.fragmentShader=i,this.technique=n}}async function ik(s,t){if(!s)return console.error("Can not find technique: no shader data"),null;const i=s.programs[t],n=i.vertexShader,o=i.fragmentShader;if(n!==void 0&&o!==void 0){const r=s.shaders[n],l=s.shaders[o];if(r.uri&&l.uri||r.code&&l.code){if(!r.code&&r.uri&&await Y_(r),!l.code&&l.uri&&await Y_(l),!r.code||!l.code)return null;const c=s.techniques[t];return new tk(r.code,l.code,c)}}return console.error("Shader technique not found",t),null}async function Y_(s){const t=s.uri;if(t)if(t.endsWith(".glsl")){const i=await new Yy().loadAsync(t);s.code=i.toString()}else s.code=sk(s.uri)}function sk(s){return decodeURIComponent(Array.prototype.map.call(atob(s),function(t){return"%"+("00"+t.charCodeAt(0).toString(16)).slice(-2)}).join(""))}const Cs=O("debugenvlight");var Ha=(s=>(s[s.Skybox=0]="Skybox",s[s.Trilight=1]="Trilight",s[s.Flat=3]="Flat",s[s.Custom=4]="Custom",s))(Ha||{}),gu=(s=>(s[s.Skybox=0]="Skybox",s[s.Custom=1]="Custom",s))(gu||{});class K_{constructor(t){a(this,"context"),a(this,"_currentLightSettingsId"),a(this,"_sceneLightSettings"),a(this,"_timevec4",new me),a(this,"__currentReflectionId",null),a(this,"_lighting",{}),this.context=t,this.context.pre_update_callbacks.push(this.preUpdate.bind(this))}preUpdate(){const t=this.context.time;this._timevec4.x=t.time,this._timevec4.y=Math.sin(t.time),this._timevec4.z=Math.cos(t.time),this._timevec4.w=t.deltaTime}get timeVec4(){return this._timevec4}get environmentIntensity(){if(!this._sceneLightSettings||!this._currentLightSettingsId)return 1;const t=this._sceneLightSettings.get(this._currentLightSettingsId);return t?t.ambientIntensity:1}get sceneLightSettings(){var t;return(t=this._sceneLightSettings)==null?void 0:t.values()}enable(t){var i;t instanceof ae&&(t=t.url);const n=(i=this._sceneLightSettings)==null?void 0:i.get(t);return n?(Cs&&console.log("Enable scene light settings",t,n),t!==this._currentLightSettingsId&&this._currentLightSettingsId&&this.disable(this._currentLightSettingsId),this._currentLightSettingsId=t,n.enabled=!0,!0):(Cs&&console.warn("No light settings found for",t),!1)}disable(t){var i;if(t instanceof ae&&(t=t.url),t==null)return!1;const n=(i=this._sceneLightSettings)==null?void 0:i.get(t);return n?(Cs&&console.log("Disable scene light settings",t,n),n.enabled=!1,!0):!1}disableCurrent(){if(this._currentLightSettingsId){const t=this._currentLightSettingsId;return this.disable(this._currentLightSettingsId),t}return null}internalRegisterSceneLightSettings(t){const i=t.sourceId;if(!i){console.error("Missing source id for scene light settings, can not register:",t);return}Cs&&console.log("Register "+t?.sourceId+" lighting",t),this._sceneLightSettings||(this._sceneLightSettings=new Map),this._sceneLightSettings.set(i,t)}internalUnregisterSceneLightSettings(t){const i=t.sourceId;if(!i){console.error("Missing source id for scene light settings, can not unregister:",t);return}Cs&&console.log("Unregister "+t?.sourceId+" lighting",t),this._sceneLightSettings&&this._sceneLightSettings.delete(i)}internalRegisterReflection(t,i){Cs&&console.log("Register reflection",t,i);const n=new Z_(this.context,i,1);this._lighting[t]=n}internalGetReflection(t){return this._lighting[t]}internalEnableReflection(t){var i;this.__currentReflectionId=t;const n=(i=this._sceneLightSettings)==null?void 0:i.get(t);switch(Cs&&console.log("Enable reflection",t,n?Ha[n.ambientMode]:"Unknown ambient mode",n),n?.ambientMode){case 0:case 4:const o=this.internalGetReflection(t);if(o&&o.Source){Cs&&console.log("Setting environment reflection",o);const r=this.context.scene,l=o.Source;l.mapping=wn,r.environment=l;return}else Cs&&console.warn("Could not find reflection for source",t);break}if(n?.environmentReflectionSource===1)switch(n?.ambientMode){case 1:if(n.ambientTrilight){const o=n.ambientTrilight,r=J2(o[0],o[1],o[2],64,64);r.colorSpace=gs,r.mapping=wn,this.context.scene.environment=r}else console.error("Missing ambient trilight",n.sourceId);return;case 3:if(n.ambientLight){const o=Kg(n.ambientLight,64);o.colorSpace=gs,o.mapping=wn,this.context.scene.environment=o}else console.error("Missing ambientlight",n.sourceId);return;default:return}}internalDisableReflection(t){if(t&&t!==this.__currentReflectionId){Cs&&console.log("Not disabling reflection for",t,"because it is not the current light settings id",this.__currentReflectionId);return}Cs&&console.log("Disable reflection",t);const i=this.context.scene;i.environment=null}}class Z_{constructor(t,i,n=1){a(this,"_source"),this._source=i,i.mapping=wn}get Source(){return this._source}}const J_=O("timescale");let Jg=1;typeof J_=="number"&&(Jg=J_);class ew{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 CS),a(this,"_smoothedFps",0),a(this,"_smoothedDeltaTime",0),a(this,"_fpsSamples",[]),a(this,"_fpsSampleIndex",0),typeof Jg=="number"&&(this.timeScale=Jg)}get time(){return this._time}set time(t){this._time=t}get deltaTime(){return this._deltaTime}set deltaTime(t){this._deltaTime=t}get deltaTimeUnscaled(){return this._deltaTimeUnscaled}get frame(){return this._frame}set frame(t){this._frame=t}get frameCount(){return this.frame}get realtimeSinceStartup(){return this.clock.elapsedTime}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 t=0;for(let i=0;i<this._fpsSamples.length;i++)t+=this._fpsSamples[i];this._smoothedDeltaTime=t/this._fpsSamples.length,this._smoothedFps=1/this._smoothedDeltaTime}}let tw=!1;function iw(s){tw||(tw=!0,nk(),ok())}iw();function nk(){const s=`
208
+ `+(uu.min.x.toFixed(2)+"-"+uu.max.x.toFixed(2)+"x"+uu.min.y.toFixed(2)+"-"+uu.max.y.toFixed(2))+" scr"),c.lastScreenCoverage>.1){const C=t,R=C.worldForward,M=C.worldPosition,T=G(R).multiplyScalar(g*.7).add(p),j=T.distanceTo(M),D=y[Math.min(y.length-1,Math.max(0,h))]+"88",U=this.context.domHeight>0?screen.height/this.context.domHeight:1,B=t.isPerspectiveCamera?Math.tan(t.fov*Math.PI/180/2):1;q.DrawLabel(T,_,j*.012*U*B,void 0,16777215,D)}}}}}const Kk=O("debugplayerview");var bo=(s=>(s.Browser="browser",s.Headset="headset",s.Handheld="handheld",s))(bo||{});class G_{constructor(t,i){a(this,"userId"),a(this,"context"),a(this,"viewDevice","browser"),a(this,"removed",!1),a(this,"_object"),this.userId=t,this.context=i}get currentObject(){return this._object}set currentObject(t){this._object=t}get isConnected(){return this.context.connection.userIsInRoom(this.userId)}}class X_{constructor(t){a(this,"context"),a(this,"playerViews",new Map),this.context=t}setPlayerView(t,i,n){let o=this.playerViews.get(t);o||(o=new G_(t,this.context),this.playerViews.set(t,o)),o.viewDevice=n,o.currentObject=i,o.removed=!1}getPlayerView(t){if(!!t){if(!this.context.connection.userIsInRoom(t)){this.playerViews.delete(t);return}return this.playerViews.get(t)}}removePlayerView(t,i){const n=this.playerViews.get(t);n?.viewDevice===i&&(Kk&&console.log("REMOVE",t),n.removed=!0,this.playerViews.delete(t))}}new Yy;const Tc=new Uint8Array(4);Tc[0]=255,Tc[1]=255,Tc[2]=255,Tc[3]=255;const Zk=new dm(Tc,1,1,pd);function Kg(s,t=1){const i="alpha"in s,n=t*t,o=new Uint8Array(4*n),r=Math.floor(s.r*255),l=Math.floor(s.g*255),c=Math.floor(s.b*255);for(let d=0;d<n;d++){const u=d*4;o[u+0]=r,o[u+1]=l,o[u+2]=c,i?o[u+3]=Math.floor(s.alpha*255):o[u+3]=255}const h=new dm(o,t,t);return h.needsUpdate=!0,h}function Jk(s,t,i,n=1,o=3){const r=n*o,l=[s,t,i],c=l.length,h=new Uint8Array(4*c*r),d=new re;for(let p=0;p<o;p++){const g=Math.floor(p/o*c),y=W.clamp(g+1,0,c-1),f=l[g],v=l[y],b=p/o*c%1;d.lerpColors(f,v,b);const w=Math.floor(d.r*255),_=Math.floor(d.g*255),C=Math.floor(d.b*255);for(let R=0;R<n;R++){const M=(p*n+R)*4;h[M+0]=w,h[M+1]=_,h[M+2]=C,h[M+3]=255}}const u=new dm(h,n,o);return u.needsUpdate=!0,u}function mu(s,t){const i=s.elements;t||(t=[]),t.length=0;for(let n=0;n<16;n+=4){const o=i[n],r=i[n+1],l=i[n+2],c=i[n+3],h=new me(o,r,l,c);t.push(h)}return t}const Zg=[],Q_=[];function e2(s,t){if(Zg.length===0)for(let i=0;i<27;i++)Zg.push(0);t||(t=Zg);for(let i=0;i<27;i++)Q_[i]=t[i];t=Q_,s.unity_SHAr={value:new me(t[9],t[3],t[6],t[0])},s.unity_SHBr={value:new me(t[12],t[15],t[18],t[21])},s.unity_SHAg={value:new me(t[10],t[4],t[7],t[1])},s.unity_SHBg={value:new me(t[13],t[16],t[19],t[22])},s.unity_SHAb={value:new me(t[11],t[5],t[8],t[2])},s.unity_SHBb={value:new me(t[14],t[17],t[20],t[23])},s.unity_SHC={value:new me(t[24],t[25],t[26],1)}}class t2{constructor(t,i,n){a(this,"vertexShader"),a(this,"fragmentShader"),a(this,"technique"),this.vertexShader=t,this.fragmentShader=i,this.technique=n}}async function i2(s,t){if(!s)return console.error("Can not find technique: no shader data"),null;const i=s.programs[t],n=i.vertexShader,o=i.fragmentShader;if(n!==void 0&&o!==void 0){const r=s.shaders[n],l=s.shaders[o];if(r.uri&&l.uri||r.code&&l.code){if(!r.code&&r.uri&&await Y_(r),!l.code&&l.uri&&await Y_(l),!r.code||!l.code)return null;const c=s.techniques[t];return new t2(r.code,l.code,c)}}return console.error("Shader technique not found",t),null}async function Y_(s){const t=s.uri;if(t)if(t.endsWith(".glsl")){const i=await new Yy().loadAsync(t);s.code=i.toString()}else s.code=s2(s.uri)}function s2(s){return decodeURIComponent(Array.prototype.map.call(atob(s),function(t){return"%"+("00"+t.charCodeAt(0).toString(16)).slice(-2)}).join(""))}const Cs=O("debugenvlight");var Ha=(s=>(s[s.Skybox=0]="Skybox",s[s.Trilight=1]="Trilight",s[s.Flat=3]="Flat",s[s.Custom=4]="Custom",s))(Ha||{}),gu=(s=>(s[s.Skybox=0]="Skybox",s[s.Custom=1]="Custom",s))(gu||{});class K_{constructor(t){a(this,"context"),a(this,"_currentLightSettingsId"),a(this,"_sceneLightSettings"),a(this,"_timevec4",new me),a(this,"__currentReflectionId",null),a(this,"_lighting",{}),this.context=t,this.context.pre_update_callbacks.push(this.preUpdate.bind(this))}preUpdate(){const t=this.context.time;this._timevec4.x=t.time,this._timevec4.y=Math.sin(t.time),this._timevec4.z=Math.cos(t.time),this._timevec4.w=t.deltaTime}get timeVec4(){return this._timevec4}get environmentIntensity(){if(!this._sceneLightSettings||!this._currentLightSettingsId)return 1;const t=this._sceneLightSettings.get(this._currentLightSettingsId);return t?t.ambientIntensity:1}get sceneLightSettings(){var t;return(t=this._sceneLightSettings)==null?void 0:t.values()}enable(t){var i;t instanceof ae&&(t=t.url);const n=(i=this._sceneLightSettings)==null?void 0:i.get(t);return n?(Cs&&console.log("Enable scene light settings",t,n),t!==this._currentLightSettingsId&&this._currentLightSettingsId&&this.disable(this._currentLightSettingsId),this._currentLightSettingsId=t,n.enabled=!0,!0):(Cs&&console.warn("No light settings found for",t),!1)}disable(t){var i;if(t instanceof ae&&(t=t.url),t==null)return!1;const n=(i=this._sceneLightSettings)==null?void 0:i.get(t);return n?(Cs&&console.log("Disable scene light settings",t,n),n.enabled=!1,!0):!1}disableCurrent(){if(this._currentLightSettingsId){const t=this._currentLightSettingsId;return this.disable(this._currentLightSettingsId),t}return null}internalRegisterSceneLightSettings(t){const i=t.sourceId;if(!i){console.error("Missing source id for scene light settings, can not register:",t);return}Cs&&console.log("Register "+t?.sourceId+" lighting",t),this._sceneLightSettings||(this._sceneLightSettings=new Map),this._sceneLightSettings.set(i,t)}internalUnregisterSceneLightSettings(t){const i=t.sourceId;if(!i){console.error("Missing source id for scene light settings, can not unregister:",t);return}Cs&&console.log("Unregister "+t?.sourceId+" lighting",t),this._sceneLightSettings&&this._sceneLightSettings.delete(i)}internalRegisterReflection(t,i){Cs&&console.log("Register reflection",t,i);const n=new Z_(this.context,i,1);this._lighting[t]=n}internalGetReflection(t){return this._lighting[t]}internalEnableReflection(t){var i;this.__currentReflectionId=t;const n=(i=this._sceneLightSettings)==null?void 0:i.get(t);switch(Cs&&console.log("Enable reflection",t,n?Ha[n.ambientMode]:"Unknown ambient mode",n),n?.ambientMode){case 0:case 4:const o=this.internalGetReflection(t);if(o&&o.Source){Cs&&console.log("Setting environment reflection",o);const r=this.context.scene,l=o.Source;l.mapping=wn,r.environment=l;return}else Cs&&console.warn("Could not find reflection for source",t);break}if(n?.environmentReflectionSource===1)switch(n?.ambientMode){case 1:if(n.ambientTrilight){const o=n.ambientTrilight,r=Jk(o[0],o[1],o[2],64,64);r.colorSpace=gs,r.mapping=wn,this.context.scene.environment=r}else console.error("Missing ambient trilight",n.sourceId);return;case 3:if(n.ambientLight){const o=Kg(n.ambientLight,64);o.colorSpace=gs,o.mapping=wn,this.context.scene.environment=o}else console.error("Missing ambientlight",n.sourceId);return;default:return}}internalDisableReflection(t){if(t&&t!==this.__currentReflectionId){Cs&&console.log("Not disabling reflection for",t,"because it is not the current light settings id",this.__currentReflectionId);return}Cs&&console.log("Disable reflection",t);const i=this.context.scene;i.environment=null}}class Z_{constructor(t,i,n=1){a(this,"_source"),this._source=i,i.mapping=wn}get Source(){return this._source}}const J_=O("timescale");let Jg=1;typeof J_=="number"&&(Jg=J_);class ew{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 CS),a(this,"_smoothedFps",0),a(this,"_smoothedDeltaTime",0),a(this,"_fpsSamples",[]),a(this,"_fpsSampleIndex",0),typeof Jg=="number"&&(this.timeScale=Jg)}get time(){return this._time}set time(t){this._time=t}get deltaTime(){return this._deltaTime}set deltaTime(t){this._deltaTime=t}get deltaTimeUnscaled(){return this._deltaTimeUnscaled}get frame(){return this._frame}set frame(t){this._frame=t}get frameCount(){return this.frame}get realtimeSinceStartup(){return this.clock.elapsedTime}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 t=0;for(let i=0;i<this._fpsSamples.length;i++)t+=this._fpsSamples[i];this._smoothedDeltaTime=t/this._fpsSamples.length,this._smoothedFps=1/this._smoothedDeltaTime}}let tw=!1;function iw(s){tw||(tw=!0,n2(),o2())}iw();function n2(){const s=`
209
209
  float startCompression = 0.8;
210
210
  float desaturation = 0.5;
211
211
  // Patched tonemapping function
@@ -226,7 +226,7 @@ vec3 NeutralToneMapping( vec3 color ) {
226
226
  return mix(color, vec3(1, 1, 1), g);
227
227
  }
228
228
  `,t="vec3 NeutralToneMapping( vec3 color ) {",i=`return mix( color, vec3( newPeak ), g );
229
- }`,n=qt.tonemapping_pars_fragment.indexOf(t),o=qt.tonemapping_pars_fragment.indexOf(i,n);if(n>=0&&o>=0){const r=qt.tonemapping_pars_fragment.substring(n,o+i.length);qt.tonemapping_pars_fragment=qt.tonemapping_pars_fragment.replace(r,s)}else F()&&console.error("Couldn't find NeutralToneMapping in ShaderChunk.tonemapping_pars_fragment")}function ok(){const s=`
229
+ }`,n=qt.tonemapping_pars_fragment.indexOf(t),o=qt.tonemapping_pars_fragment.indexOf(i,n);if(n>=0&&o>=0){const r=qt.tonemapping_pars_fragment.substring(n,o+i.length);qt.tonemapping_pars_fragment=qt.tonemapping_pars_fragment.replace(r,s)}else F()&&console.error("Couldn't find NeutralToneMapping in ShaderChunk.tonemapping_pars_fragment")}function o2(){const s=`
230
230
  // 0: Default, 1: Golden, 2: Punchy
231
231
  #define AGX_LOOK 0
232
232
 
@@ -376,7 +376,7 @@ vec3 AgXToneMapping( vec3 color ) {
376
376
  <div class="wrapper">
377
377
  <img class="logo" src=${kP} />
378
378
  </div>
379
- `,this._root.appendChild(t.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 vu}static create(){return document.createElement(vu)}setLogoVisible(t){this.logoElement.style.display=t?"block":"none"}}customElements.get(vu)||customElements.define(vu,ow);const nf=O("debugspatialmenu");class rk{constructor(t,i){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}nf&&X.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 I),a(this,"positionFilter",new zm(90,.5)),a(this,"familyName","Needle Spatial Menu"),a(this,"menu"),a(this,"_poweredByNeedleElement");var n;this._context=t,this._context.pre_render_callbacks.push(this.preRender),this.needleMenu=i;const o=(n=this.needleMenu.shadowRoot)==null?void 0:n.querySelector(".options");o?new MutationObserver(r=>{if(this.enabled&&!(this._context.isInXR==!1&&!nf))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(),Te.update())}))}).observe(o,{childList:!0}):console.error("Could not find options container in needle menu")}setEnabled(t){var i;this.enabled=t,t||(i=this.menu)==null||i.removeFromParent()}setDisplay(t){return this.enabled?(this.userRequestedMenu=t,!0):!1}onDestroy(){const t=this._context.pre_render_callbacks.indexOf(this.preRender);t>-1&&this._context.pre_render_callbacks.splice(t,1)}markDirty(){this.uiisDirty=!0}showNeedleLogo(t){this._showNeedleLogo=t}onEnterXR(){var t;const i=(t=this.needleMenu.shadowRoot)==null?void 0:t.querySelector(".options");i&&i.childNodes.forEach(n=>{this.createButtonFromHTMLNode(n)})}onExitXR(){var t;(t=this.menu)==null||t.removeFromParent()}createButtonFromHTMLNode(t){const i=this.getMenu(),n=this.htmlButtonsMap.get(t);if(n){n.add();return}if(t instanceof HTMLButtonElement){const o=this.createButton(i,t);this.htmlButtonsMap.set(t,o),o.add()}else t instanceof HTMLSlotElement&&t.assignedNodes().forEach(o=>{this.createButtonFromHTMLNode(o)})}updateMenu(){var t,i;performance.mark("NeedleSpatialMenu updateMenu start");const n=this.getMenu();this.handleNeedleWatermark(),this._context.scene.add(n);const o=this._context.mainCamera,r=this._context.xr,l=r?.rigScale||1;if(o){const c=o.worldPosition,h=o.worldForward.multiplyScalar(-1),d=h.y>.6,u=h.y>.4,p=(n.visible?u:d)||this.userRequestedMenu,g=!n.visible&&p;n.visible=p||X.isDesktop()&&nf,h.multiplyScalar(3*l),c.add(h),g&&(n.position.copy(this._menuTarget.position),n.position.y+=.25,this._menuTarget.position.copy(n.position),this.positionFilter.reset(n.position),n.quaternion.copy(this._menuTarget.quaternion),this.markDirty());const y=this._menuTarget.position.distanceTo(c);(g||y>1.5*l)&&(this.ensureRenderOnTop(this.menu),this._menuTarget.position.copy(c),this._context.scene.add(this._menuTarget),ic(this._menuTarget,this._context.mainCamera,!0,!0),this._menuTarget.removeFromParent()),this.positionFilter.filter(this._menuTarget.position,n.position,this._context.time.time);const f=5;(t=this.menu)==null||t.quaternion.slerp(this._menuTarget.quaternion,this._context.time.deltaTime*f),(i=this.menu)==null||i.scale.setScalar(l)}this.uiisDirty&&(performance.mark("SpatialMenu.update.uiisDirty.start"),this.uiisDirty=!1,Te.update(),performance.mark("SpatialMenu.update.uiisDirty.end"),performance.measure("SpatialMenu.update.uiisDirty","SpatialMenu.update.uiisDirty.start","SpatialMenu.update.uiisDirty.end")),performance.mark("NeedleSpatialMenu updateMenu end"),performance.measure("SpatialMenu.update","NeedleSpatialMenu updateMenu start","NeedleSpatialMenu updateMenu end")}ensureRenderOnTop(t,i=0){t instanceof K&&(t.material.depthTest=!1,t.material.depthWrite=!1),t.renderOrder=1e3+i*2;for(const n of t.children)this.ensureRenderOnTop(n,i+1)}get isVisible(){var t;return(t=this.menu)==null?void 0:t.visible}getMenu(){if(this.menu)return this.menu;this.ensureFont(),this.menu=new Te.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 me(0,.05,0,.05),borderColor:0,borderOpacity:.05,borderWidth:.005});const t=S.get("ObjectRaycaster");return t&&Or(this.menu,new t),this.menu}handleNeedleWatermark(){var t;if(!this._poweredByNeedleElement){this._poweredByNeedleElement=new Te.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 i=new rw(this._context,()=>globalThis.open("https://needle.tools","_self"));Or(this._poweredByNeedleElement,i);const n=new Te.Text({textContent:"Powered by",width:"auto",height:"auto"}),o=new Te.Text({textContent:"needle",width:"auto",height:"auto",fontSize:.07,margin:new me(0,0,0,.02)});this._poweredByNeedleElement.add(n),this._poweredByNeedleElement.add(o),(t=this.menu)==null||t.add(this._poweredByNeedleElement),this.markDirty(),new ba().load("./include/needle/poweredbyneedle.webp",r=>{var l;i.allowModifyUI=!1,n.removeFromParent(),o.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 i=this.menu.children.indexOf(this._poweredByNeedleElement);if(!this._showNeedleLogo&&_o())i>=0&&(this._poweredByNeedleElement.removeFromParent(),this.markDirty());else{this._poweredByNeedleElement.visible=!0,this.menu.add(this._poweredByNeedleElement);const n=this.menu.children.indexOf(this._poweredByNeedleElement);i!==n&&this.markDirty()}}}ensureFont(){let t=Te.FontLibrary.getFontFamily(this.familyName);if(!t){t=Te.FontLibrary.addFontFamily(this.familyName);const i=t.addVariant("normal","normal","./include/needle/arial-msdf.json","./include/needle/arial.png");i?.addEventListener("ready",()=>{this.markDirty()})}}createButton(t,i){const n=new Te.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}),o=new Te.Text({textContent:"",width:"auto",justifyContent:"center",alignItems:"center",backgroundOpacity:0,backgroundColor:16777215,fontFamily:this.familyName,color:0,borderRadius:.02,padding:.01});n.add(o),n["needle:use_eventsystem"]=!0;const r=new rw(this._context,()=>i.click());return Or(n,r),new ak(this,t,i,n,o)}}class ak{constructor(t,i,n,o,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=t,this.root=i,this.htmlbutton=n,this.spatialContainer=o,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(n,{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 t=this.spatialContainer.visible;this.spatialContainer.visible=this.htmlbutton.style.display!=="none",t!==this.spatialContainer.visible&&this.menu.markDirty()}updateText(){let t="",i="";this.htmlbutton.childNodes.forEach(n=>{n.nodeType===Node.TEXT_NODE?t+=n.textContent:n instanceof HTMLElement&&sw(n)&&n.textContent&&(i=n.textContent)}),this._lastText!==t&&(this._lastText=t,this.spatialText.name=t,this.spatialText.set({textContent:t}),this.menu.markDirty()),t.length<=0?this.spatialText.parent&&(this.spatialText.removeFromParent(),this.menu.markDirty()):this.spatialText.parent||(this.spatialContainer.add(this.spatialText),this.menu.markDirty()),i&&this.createIcon(i)}async createIcon(t){var i;if(!this.spatialIcon){const o=await ef(t);if(o&&!this.spatialIcon){const r=new Te.Block({width:.08,height:.08,backgroundColor:16777215,backgroundImage:o,backgroundOpacity:1,margin:new me(0,.005,0,0)});this.spatialIcon=r,this.spatialContainer.add(r),this.menu.markDirty()}}if(t!=this._lastTexture){this._lastTexture=t;const o=await ef(t);o&&((i=this.spatialIcon)==null||i.set({backgroundImage:o}),this.menu.markDirty())}const n=this.spatialContainer.children.indexOf(this.spatialIcon);n>0&&(this.spatialContainer.children.splice(n,1),this.spatialContainer.children.unshift(this.spatialIcon),this.menu.markDirty())}}class rw{constructor(t,i){a(this,"isComponent",!0),a(this,"enabled",!0),a(this,"gameObject"),a(this,"allowModifyUI",!0),a(this,"context"),a(this,"onclick"),this.context=t,this.onclick=i}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}),Te.update())}onPointerExit(){this.context.input.unsetCursor("pointer"),this.allowModifyUI&&(this.element.set({backgroundOpacity:0}),Te.update())}onPointerDown(t){t.use()}onPointerUp(t){t.use()}onPointerClick(t){t.use(),this.onclick()}}const Er="needle-menu",Ec=O("debugmenu"),aw=O("debugnoncommercial");let lk=class{constructor(s){a(this,"_context"),a(this,"_menu"),a(this,"_spatialMenu"),a(this,"onPostMessage",t=>{if(t.origin===globalThis.location.origin&&typeof t.data=="object"){const i=t.data,n=i.type;if(n==="needle:menu"){const o=i.button;if(o){if(!o.label)return console.error("NeedleMenu: buttoninfo.label is required");if(!o.onclick)return console.error("NeedleMenu: buttoninfo.onclick is required");const r=document.createElement("button");if(r.textContent=o.label,o.icon){const l=Pt(o.icon);r.prepend(l)}o.priority&&r.setAttribute("priority",o.priority.toString()),r.onclick=()=>{if(o.onclick){const l=o.onclick.startsWith("http")||o.onclick.startsWith("www."),c=o.target||"_blank";l?globalThis.open(o.onclick,c):console.error("NeedleMenu: onclick is not a valid link",o.onclick)}},this._menu.appendChild(r)}else Ec&&console.error("NeedleMenu: unknown postMessage event",i)}else Ec&&console.warn("NeedleMenu: unknown postMessage type",n,i)}}),a(this,"onStartXR",t=>{t.session.isScreenBasedAR&&(this._menu.previousParent=this._menu.parentNode,this._context.arOverlayElement.appendChild(this._menu),t.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=cw.getOrCreate(s.domElement,s),this._context=s,this._spatialMenu=new rk(s,this._menu),window.addEventListener("message",this.onPostMessage),Ad(this.onStartXR)}onDestroy(){window.removeEventListener("message",this.onPostMessage),this._menu.remove(),this._spatialMenu.onDestroy()}setPosition(s){this._menu.setPosition(s)}setVisible(s){this._menu.setVisible(s)}showNeedleLogo(s){var t;this._menu.showNeedleLogo(s),(t=this._spatialMenu)==null||t.showNeedleLogo(s)}showSpatialMenu(s){this._spatialMenu.setEnabled(s)}setSpatialMenuVisible(s){this._spatialMenu.setDisplay(s)}get spatialMenuIsVisible(){return this._spatialMenu.isVisible}showQRCodeButton(s){if(s==="desktop-only"&&(s=!X.isMobileDevice()),s){const t=Tn.getOrCreate().createQRCode();return t.style.display="",this._menu.appendChild(t),t}else{const t=Tn.getOrCreate().qrButton;return t&&(t.style.display="none"),t??null}}showAudioPlaybackOption(s){var t;if(!s){(t=this._muteButton)==null||t.remove();return}this._muteButton=Tn.getOrCreate().createMuteButton(this._context),this._muteButton.setAttribute("priority","100"),this._menu.appendChild(this._muteButton)}showFullscreenOption(s){var t;if(!s){(t=this._fullscreenButton)==null||t.remove();return}this._fullscreenButton=Tn.getOrCreate().createFullscreenButton(this._context),this._fullscreenButton&&(this._fullscreenButton.setAttribute("priority","150"),this._menu.appendChild(this._fullscreenButton))}appendChild(s){return this._menu.appendChild(s)}};var bu,_u,of;const lw=class extends HTMLElement{constructor(){var s,t,i,n,o,r;super(),$i(this,_u),a(this,"_domElement",null),a(this,"_context",null),a(this,"_sizeChangeInterval"),$i(this,bu,f=>{if(!f.defaultPrevented&&f.target==this._domElement&&f instanceof PointerEvent&&f.button===0&&this.root.classList.contains("open")){const v=this.foldout.getBoundingClientRect(),b=f;b.clientX>v.left&&b.clientX<v.right&&b.clientY>v.top&&b.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",(f,v)=>{if(!this._domElement)return;const b=this._domElement.clientWidth;if(b<100){clearTimeout(this._timeoutHandle),this.root.classList.add("compact"),this.foldout.classList.add("floating-panel-style");return}const w=20*2,_=b-w;if(!v&&Math.abs(_-this._lastAvailableWidthChange)<1)return;this._lastAvailableWidthChange=_,clearTimeout(this._timeoutHandle),this._timeoutHandle=setTimeout(()=>{const M=R();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"),R()<0&&(this.root.classList.add("compact"),this.foldout.classList.add("floating-panel-style")))},5);const C=()=>this.options.clientWidth+this.logoContainer.clientWidth,R=()=>_-C()});const l=document.createElement("template");l.innerHTML=`<style>
379
+ `,this._root.appendChild(t.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 vu}static create(){return document.createElement(vu)}setLogoVisible(t){this.logoElement.style.display=t?"block":"none"}}customElements.get(vu)||customElements.define(vu,ow);const nf=O("debugspatialmenu");class r2{constructor(t,i){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}nf&&X.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 I),a(this,"positionFilter",new zm(90,.5)),a(this,"familyName","Needle Spatial Menu"),a(this,"menu"),a(this,"_poweredByNeedleElement");var n;this._context=t,this._context.pre_render_callbacks.push(this.preRender),this.needleMenu=i;const o=(n=this.needleMenu.shadowRoot)==null?void 0:n.querySelector(".options");o?new MutationObserver(r=>{if(this.enabled&&!(this._context.isInXR==!1&&!nf))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(),Te.update())}))}).observe(o,{childList:!0}):console.error("Could not find options container in needle menu")}setEnabled(t){var i;this.enabled=t,t||(i=this.menu)==null||i.removeFromParent()}setDisplay(t){return this.enabled?(this.userRequestedMenu=t,!0):!1}onDestroy(){const t=this._context.pre_render_callbacks.indexOf(this.preRender);t>-1&&this._context.pre_render_callbacks.splice(t,1)}markDirty(){this.uiisDirty=!0}showNeedleLogo(t){this._showNeedleLogo=t}onEnterXR(){var t;const i=(t=this.needleMenu.shadowRoot)==null?void 0:t.querySelector(".options");i&&i.childNodes.forEach(n=>{this.createButtonFromHTMLNode(n)})}onExitXR(){var t;(t=this.menu)==null||t.removeFromParent()}createButtonFromHTMLNode(t){const i=this.getMenu(),n=this.htmlButtonsMap.get(t);if(n){n.add();return}if(t instanceof HTMLButtonElement){const o=this.createButton(i,t);this.htmlButtonsMap.set(t,o),o.add()}else t instanceof HTMLSlotElement&&t.assignedNodes().forEach(o=>{this.createButtonFromHTMLNode(o)})}updateMenu(){var t,i;performance.mark("NeedleSpatialMenu updateMenu start");const n=this.getMenu();this.handleNeedleWatermark(),this._context.scene.add(n);const o=this._context.mainCamera,r=this._context.xr,l=r?.rigScale||1;if(o){const c=o.worldPosition,h=o.worldForward.multiplyScalar(-1),d=h.y>.6,u=h.y>.4,p=(n.visible?u:d)||this.userRequestedMenu,g=!n.visible&&p;n.visible=p||X.isDesktop()&&nf,h.multiplyScalar(3*l),c.add(h),g&&(n.position.copy(this._menuTarget.position),n.position.y+=.25,this._menuTarget.position.copy(n.position),this.positionFilter.reset(n.position),n.quaternion.copy(this._menuTarget.quaternion),this.markDirty());const y=this._menuTarget.position.distanceTo(c);(g||y>1.5*l)&&(this.ensureRenderOnTop(this.menu),this._menuTarget.position.copy(c),this._context.scene.add(this._menuTarget),ic(this._menuTarget,this._context.mainCamera,!0,!0),this._menuTarget.removeFromParent()),this.positionFilter.filter(this._menuTarget.position,n.position,this._context.time.time);const f=5;(t=this.menu)==null||t.quaternion.slerp(this._menuTarget.quaternion,this._context.time.deltaTime*f),(i=this.menu)==null||i.scale.setScalar(l)}this.uiisDirty&&(performance.mark("SpatialMenu.update.uiisDirty.start"),this.uiisDirty=!1,Te.update(),performance.mark("SpatialMenu.update.uiisDirty.end"),performance.measure("SpatialMenu.update.uiisDirty","SpatialMenu.update.uiisDirty.start","SpatialMenu.update.uiisDirty.end")),performance.mark("NeedleSpatialMenu updateMenu end"),performance.measure("SpatialMenu.update","NeedleSpatialMenu updateMenu start","NeedleSpatialMenu updateMenu end")}ensureRenderOnTop(t,i=0){t instanceof K&&(t.material.depthTest=!1,t.material.depthWrite=!1),t.renderOrder=1e3+i*2;for(const n of t.children)this.ensureRenderOnTop(n,i+1)}get isVisible(){var t;return(t=this.menu)==null?void 0:t.visible}getMenu(){if(this.menu)return this.menu;this.ensureFont(),this.menu=new Te.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 me(0,.05,0,.05),borderColor:0,borderOpacity:.05,borderWidth:.005});const t=S.get("ObjectRaycaster");return t&&Or(this.menu,new t),this.menu}handleNeedleWatermark(){var t;if(!this._poweredByNeedleElement){this._poweredByNeedleElement=new Te.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 i=new rw(this._context,()=>globalThis.open("https://needle.tools","_self"));Or(this._poweredByNeedleElement,i);const n=new Te.Text({textContent:"Powered by",width:"auto",height:"auto"}),o=new Te.Text({textContent:"needle",width:"auto",height:"auto",fontSize:.07,margin:new me(0,0,0,.02)});this._poweredByNeedleElement.add(n),this._poweredByNeedleElement.add(o),(t=this.menu)==null||t.add(this._poweredByNeedleElement),this.markDirty(),new ba().load("./include/needle/poweredbyneedle.webp",r=>{var l;i.allowModifyUI=!1,n.removeFromParent(),o.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 i=this.menu.children.indexOf(this._poweredByNeedleElement);if(!this._showNeedleLogo&&_o())i>=0&&(this._poweredByNeedleElement.removeFromParent(),this.markDirty());else{this._poweredByNeedleElement.visible=!0,this.menu.add(this._poweredByNeedleElement);const n=this.menu.children.indexOf(this._poweredByNeedleElement);i!==n&&this.markDirty()}}}ensureFont(){let t=Te.FontLibrary.getFontFamily(this.familyName);if(!t){t=Te.FontLibrary.addFontFamily(this.familyName);const i=t.addVariant("normal","normal","./include/needle/arial-msdf.json","./include/needle/arial.png");i?.addEventListener("ready",()=>{this.markDirty()})}}createButton(t,i){const n=new Te.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}),o=new Te.Text({textContent:"",width:"auto",justifyContent:"center",alignItems:"center",backgroundOpacity:0,backgroundColor:16777215,fontFamily:this.familyName,color:0,borderRadius:.02,padding:.01});n.add(o),n["needle:use_eventsystem"]=!0;const r=new rw(this._context,()=>i.click());return Or(n,r),new a2(this,t,i,n,o)}}class a2{constructor(t,i,n,o,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=t,this.root=i,this.htmlbutton=n,this.spatialContainer=o,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(n,{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 t=this.spatialContainer.visible;this.spatialContainer.visible=this.htmlbutton.style.display!=="none",t!==this.spatialContainer.visible&&this.menu.markDirty()}updateText(){let t="",i="";this.htmlbutton.childNodes.forEach(n=>{n.nodeType===Node.TEXT_NODE?t+=n.textContent:n instanceof HTMLElement&&sw(n)&&n.textContent&&(i=n.textContent)}),this._lastText!==t&&(this._lastText=t,this.spatialText.name=t,this.spatialText.set({textContent:t}),this.menu.markDirty()),t.length<=0?this.spatialText.parent&&(this.spatialText.removeFromParent(),this.menu.markDirty()):this.spatialText.parent||(this.spatialContainer.add(this.spatialText),this.menu.markDirty()),i&&this.createIcon(i)}async createIcon(t){var i;if(!this.spatialIcon){const o=await ef(t);if(o&&!this.spatialIcon){const r=new Te.Block({width:.08,height:.08,backgroundColor:16777215,backgroundImage:o,backgroundOpacity:1,margin:new me(0,.005,0,0)});this.spatialIcon=r,this.spatialContainer.add(r),this.menu.markDirty()}}if(t!=this._lastTexture){this._lastTexture=t;const o=await ef(t);o&&((i=this.spatialIcon)==null||i.set({backgroundImage:o}),this.menu.markDirty())}const n=this.spatialContainer.children.indexOf(this.spatialIcon);n>0&&(this.spatialContainer.children.splice(n,1),this.spatialContainer.children.unshift(this.spatialIcon),this.menu.markDirty())}}class rw{constructor(t,i){a(this,"isComponent",!0),a(this,"enabled",!0),a(this,"gameObject"),a(this,"allowModifyUI",!0),a(this,"context"),a(this,"onclick"),this.context=t,this.onclick=i}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}),Te.update())}onPointerExit(){this.context.input.unsetCursor("pointer"),this.allowModifyUI&&(this.element.set({backgroundOpacity:0}),Te.update())}onPointerDown(t){t.use()}onPointerUp(t){t.use()}onPointerClick(t){t.use(),this.onclick()}}const Er="needle-menu",Ec=O("debugmenu"),aw=O("debugnoncommercial");let l2=class{constructor(s){a(this,"_context"),a(this,"_menu"),a(this,"_spatialMenu"),a(this,"onPostMessage",t=>{if(t.origin===globalThis.location.origin&&typeof t.data=="object"){const i=t.data,n=i.type;if(n==="needle:menu"){const o=i.button;if(o){if(!o.label)return console.error("NeedleMenu: buttoninfo.label is required");if(!o.onclick)return console.error("NeedleMenu: buttoninfo.onclick is required");const r=document.createElement("button");if(r.textContent=o.label,o.icon){const l=Pt(o.icon);r.prepend(l)}o.priority&&r.setAttribute("priority",o.priority.toString()),r.onclick=()=>{if(o.onclick){const l=o.onclick.startsWith("http")||o.onclick.startsWith("www."),c=o.target||"_blank";l?globalThis.open(o.onclick,c):console.error("NeedleMenu: onclick is not a valid link",o.onclick)}},this._menu.appendChild(r)}else Ec&&console.error("NeedleMenu: unknown postMessage event",i)}else Ec&&console.warn("NeedleMenu: unknown postMessage type",n,i)}}),a(this,"onStartXR",t=>{t.session.isScreenBasedAR&&(this._menu.previousParent=this._menu.parentNode,this._context.arOverlayElement.appendChild(this._menu),t.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=cw.getOrCreate(s.domElement,s),this._context=s,this._spatialMenu=new r2(s,this._menu),window.addEventListener("message",this.onPostMessage),Ad(this.onStartXR)}onDestroy(){window.removeEventListener("message",this.onPostMessage),this._menu.remove(),this._spatialMenu.onDestroy()}setPosition(s){this._menu.setPosition(s)}setVisible(s){this._menu.setVisible(s)}showNeedleLogo(s){var t;this._menu.showNeedleLogo(s),(t=this._spatialMenu)==null||t.showNeedleLogo(s)}showSpatialMenu(s){this._spatialMenu.setEnabled(s)}setSpatialMenuVisible(s){this._spatialMenu.setDisplay(s)}get spatialMenuIsVisible(){return this._spatialMenu.isVisible}showQRCodeButton(s){if(s==="desktop-only"&&(s=!X.isMobileDevice()),s){const t=Tn.getOrCreate().createQRCode();return t.style.display="",this._menu.appendChild(t),t}else{const t=Tn.getOrCreate().qrButton;return t&&(t.style.display="none"),t??null}}showAudioPlaybackOption(s){var t;if(!s){(t=this._muteButton)==null||t.remove();return}this._muteButton=Tn.getOrCreate().createMuteButton(this._context),this._muteButton.setAttribute("priority","100"),this._menu.appendChild(this._muteButton)}showFullscreenOption(s){var t;if(!s){(t=this._fullscreenButton)==null||t.remove();return}this._fullscreenButton=Tn.getOrCreate().createFullscreenButton(this._context),this._fullscreenButton&&(this._fullscreenButton.setAttribute("priority","150"),this._menu.appendChild(this._fullscreenButton))}appendChild(s){return this._menu.appendChild(s)}};var bu,_u,of;const lw=class extends HTMLElement{constructor(){var s,t,i,n,o,r;super(),$i(this,_u),a(this,"_domElement",null),a(this,"_context",null),a(this,"_sizeChangeInterval"),$i(this,bu,f=>{if(!f.defaultPrevented&&f.target==this._domElement&&f instanceof PointerEvent&&f.button===0&&this.root.classList.contains("open")){const v=this.foldout.getBoundingClientRect(),b=f;b.clientX>v.left&&b.clientX<v.right&&b.clientY>v.top&&b.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",(f,v)=>{if(!this._domElement)return;const b=this._domElement.clientWidth;if(b<100){clearTimeout(this._timeoutHandle),this.root.classList.add("compact"),this.foldout.classList.add("floating-panel-style");return}const w=20*2,_=b-w;if(!v&&Math.abs(_-this._lastAvailableWidthChange)<1)return;this._lastAvailableWidthChange=_,clearTimeout(this._timeoutHandle),this._timeoutHandle=setTimeout(()=>{const M=R();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"),R()<0&&(this.root.classList.add("compact"),this.foldout.classList.add("floating-panel-style")))},5);const C=()=>this.options.clientWidth+this.logoContainer.clientWidth,R=()=>_-C()});const l=document.createElement("template");l.innerHTML=`<style>
380
380
 
381
381
  #root {
382
382
  position: absolute;
@@ -749,20 +749,20 @@ vec3 AgXToneMapping( vec3 color ) {
749
749
  <div class="expanded-click-area"></div>
750
750
  </button>
751
751
  </div>
752
- `;const c=this.attachShadow({mode:"open"});nw(),yu(sf,{loadedCallback:()=>{this.handleSizeChange()}}),yu(sf,{element:c});const h=l.content.cloneNode(!0);c?.appendChild(h),this.root=c.querySelector("#root"),this.wrapper=(s=this.root)==null?void 0:s.querySelector(".wrapper"),this.options=(t=this.root)==null?void 0:t.querySelector(".options"),this.logoContainer=(i=this.root)==null?void 0:i.querySelector(".logo"),this.compactMenuButton=(n=this.root)==null?void 0:n.querySelector(".compact-menu-button"),this.compactMenuButton.append(Pt("more_vert")),this.foldout=(o=this.root)==null?void 0:o.querySelector(".foldout"),(r=this.root)==null||r.appendChild(this.wrapper),this.wrapper.classList.add("wrapper");const d=ow.create();d.style.minHeight="1rem",this.logoContainer.append(d),this.logoContainer.addEventListener("click",()=>{globalThis.open("https://needle.tools","_blank")});try{window.requestAnimationFrame(()=>gk(f=>{if(f==!0&&Os()&&!aw){let v=this._userRequestedLogoVisible;v===void 0&&(v=!1),va(this,_u,of).call(this,v)}}))}catch(f){console.error("[Needle Menu] License check failed.",f)}this.compactMenuButton.addEventListener("click",f=>{f.preventDefault(),this.root.classList.toggle("open")});let u=this._context;setTimeout(()=>u=this._context);let p=0;const g=(f,v)=>{var b,w,_;Ec&&console.log("Set menu visible",v),u!=null&&u.isInAR&&u.arOverlayElement?f!=u.arOverlayElement&&u.arOverlayElement.appendChild(this):this.parentNode!=((b=this._domElement)==null?void 0:b.shadowRoot)&&((_=(w=this._domElement)==null?void 0:w.shadowRoot)==null||_.appendChild(this)),this.style.display=v?"flex":"none",this.style.visibility="visible",this.style.opacity="1"};let y=!1;new MutationObserver(f=>{var v;if(!y)try{y=!0,this.onChangeDetected(f);const b=this==null?void 0:this.parentNode;if((this.style.display!="flex"||this.style.visibility!="visible"||this.style.opacity!="1"||b!=((v=this._domElement)==null?void 0:v.shadowRoot))&&!Os()){const w=p++;Gt()&&this._userRequestedMenuVisible===!1?(w===0&&g(b,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?g(b,!0):setTimeout(()=>g(b,!0),5)}}finally{y=!1}}).observe(this.root,{childList:!0,subtree:!0,attributes:!0}),Ec&&this.___insertDebugOptions()}static create(){return document.createElement(Er,{is:Er})}static getOrCreate(s,t){let i=s.querySelector(Er);return!i&&s.shadowRoot&&(i=s.shadowRoot.querySelector(Er)),i||(i=window.document.body.querySelector(Er)),i||(i=lw.create(),s.shadowRoot?s.shadowRoot.appendChild(i):s.appendChild(i)),i._domElement=s,i._context=t,i}connectedCallback(){window.addEventListener("resize",this.handleSizeChange),this.handleMenuVisible(),this._sizeChangeInterval=setInterval(()=>this.handleSizeChange(void 0,!0),5e3),setTimeout(()=>{var s,t;(s=this._domElement)==null||s.addEventListener("resize",this.handleSizeChange),(t=this._domElement)==null||t.addEventListener("click",pe(this,bu))},1)}disconnectedCallback(){var s,t;window.removeEventListener("resize",this.handleSizeChange),clearInterval(this._sizeChangeInterval),(s=this._domElement)==null||s.removeEventListener("resize",this.handleSizeChange),(t=this._context)==null||t.domElement.removeEventListener("click",pe(this,bu))}showNeedleLogo(s){this._userRequestedLogoVisible=s,!(!s&&(!Os()||aw)&&(console.warn("Needle Menu: You need a PRO license to hide the Needle Engine logo."),!Gt()))&&va(this,_u,of).call(this,s)}setPosition(s){if(s!=="top"&&s!=="bottom")return console.error("NeedleMenu.setPosition: invalid position",s);this.root.classList.remove("top","bottom"),this.root.classList.add(s)}setVisible(s){this._userRequestedMenuVisible=s,this.style.display=s?"flex":"none"}closeFoldout(){this.root.classList.remove("open")}append(...s){for(const t of s)if(typeof t=="string"){const i=document.createTextNode(t);this.options.appendChild(i)}else this.options.appendChild(t)}appendChild(s){var t;if(!(s instanceof Node)){const i=document.createElement("button");if(i.textContent=s.label,i.onclick=s.onClick,i.setAttribute("priority",((t=s.priority)==null?void 0:t.toString())??"0"),s.title&&(i.title=s.title),s.icon){const n=Pt(s.icon);s.iconSide==="right"?i.appendChild(n):i.prepend(n)}s.class&&i.classList.add(s.class),s=i}return this.options.appendChild(s)}prepend(...s){for(const t of s)if(typeof t=="string"){const i=document.createTextNode(t);this.options.prepend(i)}else this.options.prepend(t)}onChangeDetected(s){if(!this._isHandlingChange){this._isHandlingChange=!0;try{this.handleMenuVisible();for(const t of s)t.target==this.options&&this.onOptionsChildrenChanged(t)}finally{this._isHandlingChange=!1}}}onOptionsChildrenChanged(s){if(this.root.classList.toggle("has-options",this.hasAnyVisibleOptions),this.root.classList.toggle("has-no-options",!this.hasAnyVisibleOptions),this.handleSizeChange(void 0,!0),s.type==="childList"&&s.addedNodes.length>0){const t=Array.from(this.options.children);t.sort((n,o)=>{const r=parseInt(n.getAttribute("priority")||"0"),l=parseInt(o.getAttribute("priority")||"0");return r-l});let i=!1;for(let n=0;n<t.length;n++){const o=this.options.children[n],r=t[n];if(o!==r){i=!0;break}}if(i)for(const n of t)this.options.appendChild(n)}}handleMenuVisible(){Ec&&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 s=0;s<this.options.children.length;s++){const t=this.options.children[s];if(t.tagName==="SLOT"){const i=t.assignedNodes();for(const n of i)if(n instanceof HTMLElement&&n.style.display!="none")return!0}else if(t.style.display!="none")return!0}return!1}___insertDebugOptions(){window.addEventListener("keydown",i=>{i.key==="p"&&this.setPosition(this.root.classList.contains("top")?"bottom":"top")});const s=document.createElement("button");s.textContent="Hide Buttons",s.onclick=()=>{const i=new Array(this.options.children.length);for(let n=0;n<this.options.children.length;n++)i[n]=this.options.children[n];for(const n of i)this.options.removeChild(n);setTimeout(()=>{for(const n of i)this.options.appendChild(n)},1e3)},this.appendChild(s);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)}};let cw=lw;bu=new WeakMap,_u=new WeakSet,of=function(s){this.logoContainer.style.display="",this.logoContainer.style.opacity="1",this.logoContainer.style.visibility="visible",s?(this.root.classList.remove("logo-hidden"),this.root.classList.add("logo-visible")):(this.root.classList.remove("logo-visible"),this.root.classList.add("logo-hidden"))},customElements.get(Er)||customElements.define(Er,cw);const rt=O("debugcontext"),ck=O("stats"),hk=O("debugactive"),dk=O("debugframerate"),uk=O("debugcoroutine"),pk={};class mk{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 Me=(s=>(s[s.Start=-1]="Start",s[s.EarlyUpdate=0]="EarlyUpdate",s[s.Update=1]="Update",s[s.LateUpdate=2]="LateUpdate",s[s.OnBeforeRender=3]="OnBeforeRender",s[s.OnAfterRender=4]="OnAfterRender",s[s.PrePhysicsStep=9]="PrePhysicsStep",s[s.PostPhysicsStep=10]="PostPhysicsStep",s[s.Undefined=-1]="Undefined",s))(Me||{});function wu(s,t){if(!s)return;if(!s.isComponent){(F()||rt)&&console.error(`Registered script is not a Needle Engine component.
752
+ `;const c=this.attachShadow({mode:"open"});nw(),yu(sf,{loadedCallback:()=>{this.handleSizeChange()}}),yu(sf,{element:c});const h=l.content.cloneNode(!0);c?.appendChild(h),this.root=c.querySelector("#root"),this.wrapper=(s=this.root)==null?void 0:s.querySelector(".wrapper"),this.options=(t=this.root)==null?void 0:t.querySelector(".options"),this.logoContainer=(i=this.root)==null?void 0:i.querySelector(".logo"),this.compactMenuButton=(n=this.root)==null?void 0:n.querySelector(".compact-menu-button"),this.compactMenuButton.append(Pt("more_vert")),this.foldout=(o=this.root)==null?void 0:o.querySelector(".foldout"),(r=this.root)==null||r.appendChild(this.wrapper),this.wrapper.classList.add("wrapper");const d=ow.create();d.style.minHeight="1rem",this.logoContainer.append(d),this.logoContainer.addEventListener("click",()=>{globalThis.open("https://needle.tools","_blank")});try{window.requestAnimationFrame(()=>g2(f=>{if(f==!0&&Os()&&!aw){let v=this._userRequestedLogoVisible;v===void 0&&(v=!1),va(this,_u,of).call(this,v)}}))}catch(f){console.error("[Needle Menu] License check failed.",f)}this.compactMenuButton.addEventListener("click",f=>{f.preventDefault(),this.root.classList.toggle("open")});let u=this._context;setTimeout(()=>u=this._context);let p=0;const g=(f,v)=>{var b,w,_;Ec&&console.log("Set menu visible",v),u!=null&&u.isInAR&&u.arOverlayElement?f!=u.arOverlayElement&&u.arOverlayElement.appendChild(this):this.parentNode!=((b=this._domElement)==null?void 0:b.shadowRoot)&&((_=(w=this._domElement)==null?void 0:w.shadowRoot)==null||_.appendChild(this)),this.style.display=v?"flex":"none",this.style.visibility="visible",this.style.opacity="1"};let y=!1;new MutationObserver(f=>{var v;if(!y)try{y=!0,this.onChangeDetected(f);const b=this==null?void 0:this.parentNode;if((this.style.display!="flex"||this.style.visibility!="visible"||this.style.opacity!="1"||b!=((v=this._domElement)==null?void 0:v.shadowRoot))&&!Os()){const w=p++;Gt()&&this._userRequestedMenuVisible===!1?(w===0&&g(b,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?g(b,!0):setTimeout(()=>g(b,!0),5)}}finally{y=!1}}).observe(this.root,{childList:!0,subtree:!0,attributes:!0}),Ec&&this.___insertDebugOptions()}static create(){return document.createElement(Er,{is:Er})}static getOrCreate(s,t){let i=s.querySelector(Er);return!i&&s.shadowRoot&&(i=s.shadowRoot.querySelector(Er)),i||(i=window.document.body.querySelector(Er)),i||(i=lw.create(),s.shadowRoot?s.shadowRoot.appendChild(i):s.appendChild(i)),i._domElement=s,i._context=t,i}connectedCallback(){window.addEventListener("resize",this.handleSizeChange),this.handleMenuVisible(),this._sizeChangeInterval=setInterval(()=>this.handleSizeChange(void 0,!0),5e3),setTimeout(()=>{var s,t;(s=this._domElement)==null||s.addEventListener("resize",this.handleSizeChange),(t=this._domElement)==null||t.addEventListener("click",pe(this,bu))},1)}disconnectedCallback(){var s,t;window.removeEventListener("resize",this.handleSizeChange),clearInterval(this._sizeChangeInterval),(s=this._domElement)==null||s.removeEventListener("resize",this.handleSizeChange),(t=this._context)==null||t.domElement.removeEventListener("click",pe(this,bu))}showNeedleLogo(s){this._userRequestedLogoVisible=s,!(!s&&(!Os()||aw)&&(console.warn("Needle Menu: You need a PRO license to hide the Needle Engine logo."),!Gt()))&&va(this,_u,of).call(this,s)}setPosition(s){if(s!=="top"&&s!=="bottom")return console.error("NeedleMenu.setPosition: invalid position",s);this.root.classList.remove("top","bottom"),this.root.classList.add(s)}setVisible(s){this._userRequestedMenuVisible=s,this.style.display=s?"flex":"none"}closeFoldout(){this.root.classList.remove("open")}append(...s){for(const t of s)if(typeof t=="string"){const i=document.createTextNode(t);this.options.appendChild(i)}else this.options.appendChild(t)}appendChild(s){var t;if(!(s instanceof Node)){const i=document.createElement("button");if(i.textContent=s.label,i.onclick=s.onClick,i.setAttribute("priority",((t=s.priority)==null?void 0:t.toString())??"0"),s.title&&(i.title=s.title),s.icon){const n=Pt(s.icon);s.iconSide==="right"?i.appendChild(n):i.prepend(n)}s.class&&i.classList.add(s.class),s=i}return this.options.appendChild(s)}prepend(...s){for(const t of s)if(typeof t=="string"){const i=document.createTextNode(t);this.options.prepend(i)}else this.options.prepend(t)}onChangeDetected(s){if(!this._isHandlingChange){this._isHandlingChange=!0;try{this.handleMenuVisible();for(const t of s)t.target==this.options&&this.onOptionsChildrenChanged(t)}finally{this._isHandlingChange=!1}}}onOptionsChildrenChanged(s){if(this.root.classList.toggle("has-options",this.hasAnyVisibleOptions),this.root.classList.toggle("has-no-options",!this.hasAnyVisibleOptions),this.handleSizeChange(void 0,!0),s.type==="childList"&&s.addedNodes.length>0){const t=Array.from(this.options.children);t.sort((n,o)=>{const r=parseInt(n.getAttribute("priority")||"0"),l=parseInt(o.getAttribute("priority")||"0");return r-l});let i=!1;for(let n=0;n<t.length;n++){const o=this.options.children[n],r=t[n];if(o!==r){i=!0;break}}if(i)for(const n of t)this.options.appendChild(n)}}handleMenuVisible(){Ec&&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 s=0;s<this.options.children.length;s++){const t=this.options.children[s];if(t.tagName==="SLOT"){const i=t.assignedNodes();for(const n of i)if(n instanceof HTMLElement&&n.style.display!="none")return!0}else if(t.style.display!="none")return!0}return!1}___insertDebugOptions(){window.addEventListener("keydown",i=>{i.key==="p"&&this.setPosition(this.root.classList.contains("top")?"bottom":"top")});const s=document.createElement("button");s.textContent="Hide Buttons",s.onclick=()=>{const i=new Array(this.options.children.length);for(let n=0;n<this.options.children.length;n++)i[n]=this.options.children[n];for(const n of i)this.options.removeChild(n);setTimeout(()=>{for(const n of i)this.options.appendChild(n)},1e3)},this.appendChild(s);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)}};let cw=lw;bu=new WeakMap,_u=new WeakSet,of=function(s){this.logoContainer.style.display="",this.logoContainer.style.opacity="1",this.logoContainer.style.visibility="visible",s?(this.root.classList.remove("logo-hidden"),this.root.classList.add("logo-visible")):(this.root.classList.remove("logo-visible"),this.root.classList.add("logo-hidden"))},customElements.get(Er)||customElements.define(Er,cw);const rt=O("debugcontext"),c2=O("stats"),h2=O("debugactive"),d2=O("debugframerate"),u2=O("debugcoroutine"),p2={};class m2{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 Me=(s=>(s[s.Start=-1]="Start",s[s.EarlyUpdate=0]="EarlyUpdate",s[s.Update=1]="Update",s[s.LateUpdate=2]="LateUpdate",s[s.OnBeforeRender=3]="OnBeforeRender",s[s.OnAfterRender=4]="OnAfterRender",s[s.PrePhysicsStep=9]="PrePhysicsStep",s[s.PostPhysicsStep=10]="PostPhysicsStep",s[s.Undefined=-1]="Undefined",s))(Me||{});function wu(s,t){if(!s)return;if(!s.isComponent){(F()||rt)&&console.error(`Registered script is not a Needle Engine component.
753
753
  The script will be ignored. Please make sure your component extends "Behaviour" imported from "@needle-tools/engine"
754
- `,s);return}t||(t=ee.Current,rt&&console.warn("> Registering component without context"));const i=t?.new_scripts;i.includes(s)||i.push(s)}const Ie=class{constructor(s){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,"_sizeChanged",!1),a(this,"_isCreated",!1),a(this,"_isCreating",!1),a(this,"_isVisible",!1),a(this,"_stats",ck?new IC:null),a(this,"_intersectionObserver",null),a(this,"_disposeCallbacks",[]),a(this,"maxRenderResolution"),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,"_contextRestoreTries",0),a(this,"_wasPaused",!1),this.name=s?.name||"",this.alias=s?.alias,this.domElement=s?.domElement||document.body,this.hash=s?.hash,s!=null&&s.renderer&&(this.renderer=s.renderer,this.isManagedExternally=!0),s?.runInBackground!==void 0&&(this.runInBackground=s.runInBackground),s!=null&&s.scene?this.scene=s.scene:this.scene=new qi,s!=null&&s.camera&&(this._mainCamera=s.camera),this.application=new Rn(this),this.time=new ew,this.input=new fb(this),this.physics=new Fd(this),this.connection=new Eb(this),this.assets=new Gb,this.sceneLighting=new K_(this),this.addressables=new z_(this),this.lightmaps=new Q2(this),this.players=new X_(this),this.menu=new lk(this),this.lodsManager=new Y2(this),this.animations=new q2(this);const t=()=>this._sizeChanged=!0;window.addEventListener("resize",t),this._disposeCallbacks.push(()=>window.removeEventListener("resize",t));const i=new ResizeObserver(n=>this._sizeChanged=!0);i.observe(this.domElement),this._disposeCallbacks.push(()=>i.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()}),ge.register(this)}static get DefaultTargetFrameRate(){return Ie._defaultTargetFramerate.value}static set DefaultTargetFrameRate(s){Ie._defaultTargetFramerate.value=s}static get DefaultWebGLRendererParameters(){return Ie._defaultWebglRendererParameters}get version(){return _s}static get Current(){return ge.Current}static set Current(s){ge.Current=s}appendHTMLElement(s){return this.domElement.shadowRoot?this.domElement.shadowRoot.appendChild(s):this.domElement.appendChild(s)}get resolutionScaleFactor(){return this._resolutionScaleFactor}set resolutionScaleFactor(s){if(s!==this._resolutionScaleFactor&&typeof s=="number"){if(s<=0){console.error("Invalid resolution scale factor",s);return}this._resolutionScaleFactor=s,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 s,t;return((t=(s=this.renderer)==null?void 0:s.xr)==null?void 0:t.isPresenting)||!1}get xrSessionMode(){var s;return(s=this.xr)==null?void 0:s.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 s,t;return(t=(s=this.renderer)==null?void 0:s.xr)==null?void 0:t.getSession()}get xrFrame(){return this._xrFrame}get xrCamera(){var s,t;return this.renderer.xr.isPresenting?(t=(s=this.renderer)==null?void 0:s.xr)==null?void 0:t.getCamera():void 0}get arOverlayElement(){const s=this.domElement;return typeof s.getAROverlayContainer=="function"?s.getAROverlayContainer():this.domElement}get currentFrameEvent(){return this._currentFrameEvent}get mainCamera(){if(this._mainCamera)return this._mainCamera;if(this.mainCameraComponent){const s=this.mainCameraComponent;return s.threeCamera||s.buildCamera(),s.threeCamera}return this._fallbackCamera||(this._fallbackCamera=new we(75,this.domWidth/this.domHeight,.1,1e3)),this._fallbackCamera}set mainCamera(s){this._mainCamera=s}get rendererData(){return this.sceneLighting}get isCreated(){return this._isCreated}createNewRenderer(s){var t,i,n;if((t=this.renderer)==null||t.dispose(),s={...Ie.DefaultWebGLRendererParameters,...s},!s.canvas){const o=(n=(i=this.domElement)==null?void 0:i.shadowRoot)==null?void 0:n.querySelector("canvas");o&&(s.canvas=o,rt&&console.log("Using canvas from shadow root",o))}rt&&console.log("Using Renderer Parameters:",s,this.domElement),this.renderer=new ur(s),this.renderer.debug.checkShaderErrors=F()||O("checkshadererrors")===!0,this.renderer.toneMappingExposure=1,this.renderer.toneMapping=wa,this.renderer.setClearColor(new re("lightgrey"),0),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=OS,this.renderer.setSize(this.domWidth,this.domHeight),this.renderer.outputColorSpace=gs,this.renderer.nodes={library:new PS,modelViewMatrix:null,modelNormalViewMatrix:null},this.lodsManager.setRenderer(this.renderer),this.input.bindEvents()}internalOnUpdateVisible(){var s,t;(s=this._intersectionObserver)==null||s.disconnect(),(t=this._intersectionObserver)==null||t.observe(this.domElement)}requestSizeUpdate(){this._sizeChanged=!0}updateSize(s=!1){var t,i,n;if(s||!this.isManagedExternally&&((t=this.renderer.xr)==null?void 0:t.isPresenting)===!1){this._sizeChanged=!1;const o=this.resolutionScaleFactor;let r=this.domWidth*o,l=this.domHeight*o;this.maxRenderResolution&&(this.maxRenderResolution.x=Math.max(1,this.maxRenderResolution.x),r=Math.min(this.maxRenderResolution.x,r),this.maxRenderResolution.y=Math.max(1,this.maxRenderResolution.y),l=Math.min(this.maxRenderResolution.y,l));const c=this.mainCamera;this.updateAspect(c),this.renderer.setSize(r,l,!0),this.renderer.setPixelRatio(window.devicePixelRatio),this.renderer.domElement.style.width="100%",this.renderer.domElement.style.height="100%",this.composer&&((i=this.composer.setSize)==null||i.call(this.composer,r,l),"setPixelRatio"in this.composer&&typeof this.composer.setPixelRatio=="function"&&((n=this.composer.setPixelRatio)==null||n.call(this.composer,window.devicePixelRatio)))}}updateAspect(s,t,i){if(!s)return;t===void 0&&(t=this.domWidth),i===void 0&&(i=this.domHeight);const n=t/i;if(s.isPerspectiveCamera){const o=s,r=o.aspect;o.aspect=n,r!==o.aspect&&s.updateProjectionMatrix()}else if(s.isOrthographicCamera){const o=s,r=o.top-o.bottom,l=r*n/2,c=r/2;(o.left!=-l||o.top!=c)&&(o.left=-l,o.right=l,o.top=c,o.bottom=-c,s.updateProjectionMatrix())}}recreate(){this.clear(),this.create(this._originalCreationArgs)}async onCreate(s){return this.create(s)}async create(s){try{this._isCreating=!0,s!==this._originalCreationArgs&&(this._originalCreationArgs=Zl(s)),window.addEventListener("unhandledrejection",this.onUnhandledRejection);const t=await this.internalOnCreate(s);return this._isCreated=t,t}finally{window.removeEventListener("unhandledrejection",this.onUnhandledRejection),this._isCreating=!1}}onError(s){this.domElement.dispatchEvent(new CustomEvent("error",{detail:s}))}clear(){var s,t,i,n;ge.dispatchCallback(ye.ContextClearing,this),Ns(this,ye.ContextClearing),Ri(this.scene,!0,!0),this.scene=new qi,(s=this.addressables)==null||s.dispose(),(t=this.lightmaps)==null||t.clear(),(n=(i=this.physics)==null?void 0:i.engine)==null||n.clearCaches(),this.lodsManager.disable(),this.isManagedExternally||this.renderer&&(this.renderer.renderLists.dispose(),this.renderer.state.reset(),this.renderer.resetState()),ge.dispatchCallback(ye.ContextCleared,this)}dispose(){this.internalOnDestroy()}onDestroy(){this.internalOnDestroy()}internalOnDestroy(){var s,t;Ie.Current=this,ge.dispatchCallback(ye.ContextDestroying,this),Ns(this,ye.ContextDestroying),this.clear(),(s=this.renderer)==null||s.setAnimationLoop(null),this.renderer&&(this.renderer.setClearAlpha(0),this.renderer.clear(),this.isManagedExternally||(rt&&console.log("Disposing renderer"),this.renderer.dispose())),this.scene=null,this.renderer=null,this.input.dispose(),this.menu.onDestroy(),this.animations.onDestroy();for(const i of this._disposeCallbacks)try{i()}catch(n){console.error("Error in on dispose callback:",n,i)}(t=this.domElement)!=null&&t.parentElement&&this.domElement.parentElement.removeChild(this.domElement),this._isCreated=!1,ge.dispatchCallback(ye.ContextDestroyed,this),Ns(this,ye.ContextDestroyed),ge.unregister(this),Ie.Current===this&&(Ie.Current=null)}registerCoroutineUpdate(s,t,i){return typeof t?.next!="function"?(console.error("Registered invalid coroutine function from "+s.name+`
754
+ `,s);return}t||(t=ee.Current,rt&&console.warn("> Registering component without context"));const i=t?.new_scripts;i.includes(s)||i.push(s)}const Ie=class{constructor(s){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,"_sizeChanged",!1),a(this,"_isCreated",!1),a(this,"_isCreating",!1),a(this,"_isVisible",!1),a(this,"_stats",c2?new IC:null),a(this,"_intersectionObserver",null),a(this,"_disposeCallbacks",[]),a(this,"maxRenderResolution"),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,"_contextRestoreTries",0),a(this,"_wasPaused",!1),this.name=s?.name||"",this.alias=s?.alias,this.domElement=s?.domElement||document.body,this.hash=s?.hash,s!=null&&s.renderer&&(this.renderer=s.renderer,this.isManagedExternally=!0),s?.runInBackground!==void 0&&(this.runInBackground=s.runInBackground),s!=null&&s.scene?this.scene=s.scene:this.scene=new qi,s!=null&&s.camera&&(this._mainCamera=s.camera),this.application=new Rn(this),this.time=new ew,this.input=new fb(this),this.physics=new Fd(this),this.connection=new Eb(this),this.assets=new Gb,this.sceneLighting=new K_(this),this.addressables=new z_(this),this.lightmaps=new Qk(this),this.players=new X_(this),this.menu=new l2(this),this.lodsManager=new Yk(this),this.animations=new qk(this);const t=()=>this._sizeChanged=!0;window.addEventListener("resize",t),this._disposeCallbacks.push(()=>window.removeEventListener("resize",t));const i=new ResizeObserver(n=>this._sizeChanged=!0);i.observe(this.domElement),this._disposeCallbacks.push(()=>i.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()}),ge.register(this)}static get DefaultTargetFrameRate(){return Ie._defaultTargetFramerate.value}static set DefaultTargetFrameRate(s){Ie._defaultTargetFramerate.value=s}static get DefaultWebGLRendererParameters(){return Ie._defaultWebglRendererParameters}get version(){return _s}static get Current(){return ge.Current}static set Current(s){ge.Current=s}appendHTMLElement(s){return this.domElement.shadowRoot?this.domElement.shadowRoot.appendChild(s):this.domElement.appendChild(s)}get resolutionScaleFactor(){return this._resolutionScaleFactor}set resolutionScaleFactor(s){if(s!==this._resolutionScaleFactor&&typeof s=="number"){if(s<=0){console.error("Invalid resolution scale factor",s);return}this._resolutionScaleFactor=s,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 s,t;return((t=(s=this.renderer)==null?void 0:s.xr)==null?void 0:t.isPresenting)||!1}get xrSessionMode(){var s;return(s=this.xr)==null?void 0:s.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 s,t;return(t=(s=this.renderer)==null?void 0:s.xr)==null?void 0:t.getSession()}get xrFrame(){return this._xrFrame}get xrCamera(){var s,t;return this.renderer.xr.isPresenting?(t=(s=this.renderer)==null?void 0:s.xr)==null?void 0:t.getCamera():void 0}get arOverlayElement(){const s=this.domElement;return typeof s.getAROverlayContainer=="function"?s.getAROverlayContainer():this.domElement}get currentFrameEvent(){return this._currentFrameEvent}get mainCamera(){if(this._mainCamera)return this._mainCamera;if(this.mainCameraComponent){const s=this.mainCameraComponent;return s.threeCamera||s.buildCamera(),s.threeCamera}return this._fallbackCamera||(this._fallbackCamera=new we(75,this.domWidth/this.domHeight,.1,1e3)),this._fallbackCamera}set mainCamera(s){this._mainCamera=s}get rendererData(){return this.sceneLighting}get isCreated(){return this._isCreated}createNewRenderer(s){var t,i,n;if((t=this.renderer)==null||t.dispose(),s={...Ie.DefaultWebGLRendererParameters,...s},!s.canvas){const o=(n=(i=this.domElement)==null?void 0:i.shadowRoot)==null?void 0:n.querySelector("canvas");o&&(s.canvas=o,rt&&console.log("Using canvas from shadow root",o))}rt&&console.log("Using Renderer Parameters:",s,this.domElement),this.renderer=new ur(s),this.renderer.debug.checkShaderErrors=F()||O("checkshadererrors")===!0,this.renderer.toneMappingExposure=1,this.renderer.toneMapping=wa,this.renderer.setClearColor(new re("lightgrey"),0),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=OS,this.renderer.setSize(this.domWidth,this.domHeight),this.renderer.outputColorSpace=gs,this.renderer.nodes={library:new PS,modelViewMatrix:null,modelNormalViewMatrix:null},this.lodsManager.setRenderer(this.renderer),this.input.bindEvents()}internalOnUpdateVisible(){var s,t;(s=this._intersectionObserver)==null||s.disconnect(),(t=this._intersectionObserver)==null||t.observe(this.domElement)}requestSizeUpdate(){this._sizeChanged=!0}updateSize(s=!1){var t,i,n;if(s||!this.isManagedExternally&&((t=this.renderer.xr)==null?void 0:t.isPresenting)===!1){this._sizeChanged=!1;const o=this.resolutionScaleFactor;let r=this.domWidth*o,l=this.domHeight*o;this.maxRenderResolution&&(this.maxRenderResolution.x=Math.max(1,this.maxRenderResolution.x),r=Math.min(this.maxRenderResolution.x,r),this.maxRenderResolution.y=Math.max(1,this.maxRenderResolution.y),l=Math.min(this.maxRenderResolution.y,l));const c=this.mainCamera;this.updateAspect(c),this.renderer.setSize(r,l,!0),this.renderer.setPixelRatio(window.devicePixelRatio),this.renderer.domElement.style.width="100%",this.renderer.domElement.style.height="100%",this.composer&&((i=this.composer.setSize)==null||i.call(this.composer,r,l),"setPixelRatio"in this.composer&&typeof this.composer.setPixelRatio=="function"&&((n=this.composer.setPixelRatio)==null||n.call(this.composer,window.devicePixelRatio)))}}updateAspect(s,t,i){if(!s)return;t===void 0&&(t=this.domWidth),i===void 0&&(i=this.domHeight);const n=t/i;if(s.isPerspectiveCamera){const o=s,r=o.aspect;o.aspect=n,r!==o.aspect&&s.updateProjectionMatrix()}else if(s.isOrthographicCamera){const o=s,r=o.top-o.bottom,l=r*n/2,c=r/2;(o.left!=-l||o.top!=c)&&(o.left=-l,o.right=l,o.top=c,o.bottom=-c,s.updateProjectionMatrix())}}recreate(){this.clear(),this.create(this._originalCreationArgs)}async onCreate(s){return this.create(s)}async create(s){try{this._isCreating=!0,s!==this._originalCreationArgs&&(this._originalCreationArgs=Zl(s)),window.addEventListener("unhandledrejection",this.onUnhandledRejection);const t=await this.internalOnCreate(s);return this._isCreated=t,t}finally{window.removeEventListener("unhandledrejection",this.onUnhandledRejection),this._isCreating=!1}}onError(s){this.domElement.dispatchEvent(new CustomEvent("error",{detail:s}))}clear(){var s,t,i,n;ge.dispatchCallback(ye.ContextClearing,this),Ns(this,ye.ContextClearing),Ri(this.scene,!0,!0),this.scene=new qi,(s=this.addressables)==null||s.dispose(),(t=this.lightmaps)==null||t.clear(),(n=(i=this.physics)==null?void 0:i.engine)==null||n.clearCaches(),this.lodsManager.disable(),this.isManagedExternally||this.renderer&&(this.renderer.renderLists.dispose(),this.renderer.state.reset(),this.renderer.resetState()),ge.dispatchCallback(ye.ContextCleared,this)}dispose(){this.internalOnDestroy()}onDestroy(){this.internalOnDestroy()}internalOnDestroy(){var s,t;Ie.Current=this,ge.dispatchCallback(ye.ContextDestroying,this),Ns(this,ye.ContextDestroying),this.clear(),(s=this.renderer)==null||s.setAnimationLoop(null),this.renderer&&(this.renderer.setClearAlpha(0),this.renderer.clear(),this.isManagedExternally||(rt&&console.log("Disposing renderer"),this.renderer.dispose())),this.scene=null,this.renderer=null,this.input.dispose(),this.menu.onDestroy(),this.animations.onDestroy();for(const i of this._disposeCallbacks)try{i()}catch(n){console.error("Error in on dispose callback:",n,i)}(t=this.domElement)!=null&&t.parentElement&&this.domElement.parentElement.removeChild(this.domElement),this._isCreated=!1,ge.dispatchCallback(ye.ContextDestroyed,this),Ns(this,ye.ContextDestroyed),ge.unregister(this),Ie.Current===this&&(Ie.Current=null)}registerCoroutineUpdate(s,t,i){return typeof t?.next!="function"?(console.error("Registered invalid coroutine function from "+s.name+`
755
755
  Coroutine functions must be generators: "*myCoroutine() {...}"
756
756
  Start a coroutine from a component by calling "this.startCoroutine(myCoroutine())"`),t):(this.coroutines[i]||(this.coroutines[i]=[]),this.coroutines[i].push({comp:s,main:t}),t)}unregisterCoroutineUpdate(s,t){if(!this.coroutines[t])return;const i=this.coroutines[t].findIndex(n=>n.main===s);i>=0&&this.coroutines[t].splice(i,1)}stopAllCoroutinesFrom(s){for(const t in this.coroutines){const i=this.coroutines[t];for(let n=i.length-1;n>=0;n--)i[n].comp===s&&i.splice(n,1)}}setCurrentCamera(s){var t;if(!s)return;if(s.threeCamera||s.buildCamera(),!s.threeCamera){console.warn("Camera component is missing camera",s);return}const i=this._cameraStack.indexOf(s);i>=0&&this._cameraStack.splice(i,1),this._cameraStack.push(s),this.mainCameraComponent=s;const n=s.threeCamera;n.isPerspectiveCamera&&this.updateAspect(n),(t=this.mainCameraComponent)==null||t.applyClearFlagsIfIsActiveCamera()}removeCamera(s){if(!s)return;const t=this._cameraStack.indexOf(s);if(t>=0&&this._cameraStack.splice(t,1),this.mainCameraComponent===s&&(this.mainCameraComponent=void 0,this._cameraStack.length>0)){const i=this._cameraStack[this._cameraStack.length-1];this.setCurrentCamera(i)}}addBeforeRenderListener(s,t){this._onBeforeRenderListeners.has(s.uuid)||(this._onBeforeRenderListeners.set(s.uuid,[]),s.onBeforeRender=this._createRenderCallbackWrapper(s,this._onBeforeRenderListeners)),this._onBeforeRenderListeners.get(s.uuid).push(t)}removeBeforeRenderListener(s,t){if(this._onBeforeRenderListeners.has(s.uuid)){const i=this._onBeforeRenderListeners.get(s.uuid),n=i.indexOf(t);n>=0&&i.splice(n,1)}}addAfterRenderListener(s,t){var i;this._onAfterRenderListeners.has(s.uuid)||(this._onAfterRenderListeners.set(s.uuid,[]),s.onAfterRender=this._createRenderCallbackWrapper(s,this._onAfterRenderListeners)),(i=this._onAfterRenderListeners.get(s.uuid))==null||i.push(t)}removeAfterRenderListener(s,t){if(this._onAfterRenderListeners.has(s.uuid)){const i=this._onAfterRenderListeners.get(s.uuid),n=i.indexOf(t);n>=0&&i.splice(n,1)}}_createRenderCallbackWrapper(s,t){return(i,n,o,r,l,c)=>{const h=t.get(s.uuid);if(h)for(let d=0;d<h.length;d++){const u=h[d];u(i,n,o,r,l,c)}}}get isRendering(){return this._isRendering}setRequireDepth(s){this._requireDepthTexture=s}setRequireColor(s){this._requireColorTexture=s}get depthTexture(){var s;return((s=this._renderTarget)==null?void 0:s.depthTexture)||null}get opaqueColorTexture(){var s;return((s=this._renderTarget)==null?void 0:s.texture)||null}get isVisibleToUser(){if(this.isInXR)return!0;if(!this._isVisible)return!1;const s=getComputedStyle(this.domElement);return s.visibility!=="hidden"&&s.display!=="none"&&s.opacity!=="0"}async internalOnCreate(s){var t,i,n,o,r,l,c,h;const d=++this._createId;rt&&console.log("Creating context",this.name,s);const u=globalThis["needle:dependencies:ready"];u instanceof Promise&&(rt&&console.log("Waiting for dependencies to be ready"),await u.catch(f=>{if(rt||F()){if(ac("Needle Engine dependencies failed to load. Please check the console for more details"),f instanceof ReferenceError){let v="YourComponentName";const b=f.message.indexOf("'");if(b>0){const w=f.message.indexOf("'",b+1);if(w>0){const _=f.message.substring(b+1,w);_.length>3&&(v=_)}}console.error(`Needle Engine dependencies failed to load:
757
757
 
758
758
  # Make sure you don't have circular imports in your scripts!
759
759
  \u2192 Possible solution: Replace @serializable(${v}) in your script with @serializable(Behaviour)
760
760
 
761
- ---`,f);return}console.error("Needle Engine dependencies failed to load",f)}}).then(()=>{rt&&console.log("Needle Engine dependencies are ready")})),this.clear(),this.isManagedExternally===!1&&(this.createNewRenderer(),(t=this.renderer)==null||t.setAnimationLoop(null)),await ys(1),Ie.Current=this,await ge.dispatchCallback(ye.ContextCreationStart,this);let p=!0,g;try{Ie.Current=this,s?g=await this.internalLoadInitialContent(d,s):g=[]}catch(f){console.error(f),p=!1}if(!p)return this.onError("Failed to load initial content"),!1;if(d!==this._createId||(i=s?.abortSignal)!=null&&i.aborted)return!1;if(this.internalOnUpdateVisible(),!this.renderer)return rt&&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),Ie.Current=this,Ie.Current=this;for(let f=0;f<this.new_scripts.length;f++){const v=this.new_scripts[f];if(v.gameObject!==void 0&&v.gameObject!==null){v.gameObject.userData===void 0&&(v.gameObject.userData={}),v.gameObject.userData.components===void 0&&(v.gameObject.userData.components=[]);const b=v.gameObject.userData.components;b.includes(v)||b.push(v)}}if(this.post_setup_callbacks)for(let f=0;f<this.post_setup_callbacks.length;f++)Ie.Current=this,await this.post_setup_callbacks[f](this);if(!this._mainCamera){Ie.Current=this;let f=null;Mr(this.scene,v=>{const b=v;if(b!=null&&b.isCamera){if(wc(b.gameObject),!b.activeAndEnabled)return;if(b.tag==="MainCamera")return f=b,!0;f=b}}),f?this.setCurrentCamera(f):!ge.dispatchCallback(ye.MissingCamera,this,{files:g})&&!this.mainCamera&&!this.isManagedExternally&&console.warn("Missing camera in main scene",this)}this.input.bindEvents(),Ie.Current=this,Hd(this),this.physics.engine&&((n=this.physics.engine)==null||n.step(0),(o=this.physics.engine)==null||o.postStep()),!this.isManagedExternally&&this.composer&&this.mainCamera,this._sizeChanged=!0,this._stats&&(this._stats.showPanel(0),this._stats.dom.style.position="absolute",(r=this.domElement.shadowRoot)==null||r.appendChild(this._stats.dom)),rt&&kd(this.scene,!0),this.targetFrameRate===void 0?(rt&&console.warn("No target framerate set, using default",Ie.DefaultTargetFrameRate),this.targetFrameRate=Ie._defaultTargetFramerate):rt&&console.log("Target framerate set to",this.targetFrameRate),this._dispatchReadyAfterFrame=!0;const y=ge.dispatchCallback(ye.ContextCreated,this,{files:g});return y&&("internalSetLoadingMessage"in this.domElement&&typeof this.domElement.internalSetLoadingMessage=="function"&&((l=this.domElement)==null||l.internalSetLoadingMessage("finish loading")),await y),(c=s?.abortSignal)!=null&&c.aborted?!1:(Ns(this,ye.ContextCreated),rt&&console.log("Context Created...",this.renderer,this.renderer.domElement),this._isCreating=!1,!this.isManagedExternally&&!((h=s?.abortSignal)!=null&&h.aborted)&&this.restartRenderLoop(),!0)}async internalLoadInitialContent(s,t){var i,n,o,r;const l=new Array;if(t.files.length===0)return l;const c=[...t.files],h={name:"",progress:null,index:0,count:c.length},d=fs(),u=0;for(let p=0;p<c.length;p++){if((i=t.abortSignal)!=null&&i.aborted){rt&&console.log("Aborting loading because of abort signal");break}if(s!==this._createId){rt&&console.log("Aborting loading because create id changed",s,this._createId);break}const g=c[p];(n=t?.onLoadingStart)==null||n.call(this,p,g),rt&&console.log("Context Load "+g);const y=await d.loadSync(this,g,g,u,f=>{var v,b;(v=t.abortSignal)!=null&&v.aborted||(h.name=g,h.progress=f,h.index=p,h.count=c.length,(b=t.onLoadingProgress)==null||b.call(this,h))});(o=t?.onLoadingFinished)==null||o.call(this,p,g,y??null),y?l.push({src:g,file:y}):console.warn("Could not load file: "+g)}if(s!==this._createId||(r=t.abortSignal)!=null&&r.aborted){rt&&console.log("Aborting loading because create id changed or abort signal was set",s,this._createId);for(const p of l)if(p&&p.file)for(const g of p.file.scenes)Ri(g,!0,!0)}else{let p=!1;for(const g of l)g&&g.file&&(g.file.scene?(p=!0,this.scene.add(g.file.scene)):console.warn("No scene found in loaded file"));if(!p){for(const g of l)if(g&&g.file&&"parser"in g.file){let y=0;if(!Array.isArray(g.file.parser.json.materials))continue;for(let f=0;f<g.file.parser.json.materials.length;f++){const v=await g.file.parser.getDependency("material",f),b=new I;b.position.x=f*1.1,b.position.y=y,this.scene.add(b),go.createPrimitive("ShaderBall",{parent:b,material:v})}y+=1}}}return l}restartRenderLoop(){return this.renderer?this._isCreating?(console.warn("Can not start render loop while creating context"),!1):(this.renderer.setAnimationLoop((s,t)=>{this.isManagedExternally||this.update(s,t)}),!0):(console.error("Can not start render loop without renderer"),!1)}update(s,t){if(t===void 0&&(t=null),F()||rt||u2())try{performance.mark("update.start"),this.internalStep(s,t),this._renderlooperrors=0,performance.mark("update.end"),performance.measure("NE Frame","update.start","update.end")}catch(i){this._renderlooperrors+=1,(F()||rt)&&(i instanceof Error||i instanceof TypeError)&&De("Caught unhandled exception during render-loop - see console for details.",Ci.Error),console.error("Frame #"+this.time.frame+`
762
- `,i),this._renderlooperrors>=3&&(console.warn("Stopping render loop due to error"),this.renderer.setAnimationLoop(null)),this.domElement.dispatchEvent(new CustomEvent("error",{detail:i}))}else this.internalStep(s,t)}updatePhysics(s){this.internalUpdatePhysics(s)}internalStep(s,t){this.internalOnBeforeRender(s,t)!==!1&&(this.internalOnRender(),this.internalOnAfterRender())}internalOnBeforeRender(s,t){var i;this.renderer.info.autoReset=!0;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=s),this._accumulatedTime+=(s-this._lastTimestamp)/1e3,this._lastTimestamp=s;let o=this.targetFrameRate;if(typeof o=="object"&&(o=o.value),this._accumulatedTime<1/(o+1))return!1;this._accumulatedTime=0}if((i=this._stats)==null||i.begin(),Ie.Current=this,this.onHandlePaused())return!1;for(Ie.Current=this,this.time.update(),dk&&console.log("FPS",this.time.smoothedFps.toFixed(0)),Hd(this),$d(this.scene),i_(this),Ns(this,-1);this._cameraStack.length>0&&(!this.mainCameraComponent||this.mainCameraComponent.destroyed);){this._cameraStack.splice(this._cameraStack.length-1,1);const o=this._cameraStack[this._cameraStack.length-1];this.setCurrentCamera(o)}if(this.pre_update_oneshot_callbacks){for(const o in this.pre_update_oneshot_callbacks)this.pre_update_oneshot_callbacks[o]();this.pre_update_oneshot_callbacks.length=0}if(this.pre_update_callbacks)for(const o in this.pre_update_callbacks)this.pre_update_callbacks[o]();this._currentFrameEvent=0;for(let o=0;o<this.scripts_earlyUpdate.length;o++){const r=this.scripts_earlyUpdate[o];r.activeAndEnabled&&r.earlyUpdate!==void 0&&(Ie.Current=this,r.earlyUpdate())}if(this.executeCoroutines(0),Ns(this,0),this.onHandlePaused())return!1;this._currentFrameEvent=1;for(let o=0;o<this.scripts_update.length;o++){const r=this.scripts_update[o];r.activeAndEnabled&&r.update!==void 0&&(Ie.Current=this,r.update())}if(this.executeCoroutines(1),Ns(this,1),this.onHandlePaused())return!1;this._currentFrameEvent=2;for(let o=0;o<this.scripts_lateUpdate.length;o++){const r=this.scripts_lateUpdate[o];r.activeAndEnabled&&r.lateUpdate!==void 0&&(Ie.Current=this,r.lateUpdate())}if(this.executeCoroutines(2),Ns(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 o=0;o<this.scripts_onBeforeRender.length;o++){const r=this.scripts_onBeforeRender[o];r.activeAndEnabled&&r.onBeforeRender!==void 0&&(Ie.Current=this,r.onBeforeRender(t))}if(this.executeCoroutines(3),Ns(this,3),this._sizeChanged&&this.updateSize(),this.pre_render_callbacks)for(const o in this.pre_render_callbacks)this.pre_render_callbacks[o](t)}return!0}internalUpdatePhysics(s){if(!this.physics.engine)return!1;const t=s,i=this.time.deltaTime/t;for(let n=0;n<t;n++)this._currentFrameEvent=9,this.executeCoroutines(9),this.physics.engine.step(i),this._currentFrameEvent=10,this.executeCoroutines(10);return this.physics.engine.postStep(),!0}internalOnRender(){this.isManagedExternally||(f2(this),this._currentFrameEvent=-1,jC.update(),this.renderNow(),this._currentFrameEvent=4)}internalOnAfterRender(){if(this.isVisibleToUser||this.runInBackground){for(let s=0;s<this.scripts_onAfterRender.length;s++){const t=this.scripts_onAfterRender[s];t.activeAndEnabled&&t.onAfterRender!==void 0&&(Ie.Current=this,t.onAfterRender())}if(this.executeCoroutines(4),Ns(this,4),this.post_render_callbacks)for(const s in this.post_render_callbacks)this.post_render_callbacks[s]()}this._currentFrameEvent=-1,this.connection.sendBufferedMessagesNow(),this._stats&&(this._stats.end(),this.time.frameCount%150===0&&console.log(this.renderer.info.render.calls+" DrawCalls",`
761
+ ---`,f);return}console.error("Needle Engine dependencies failed to load",f)}}).then(()=>{rt&&console.log("Needle Engine dependencies are ready")})),this.clear(),this.isManagedExternally===!1&&(this.createNewRenderer(),(t=this.renderer)==null||t.setAnimationLoop(null)),await ys(1),Ie.Current=this,await ge.dispatchCallback(ye.ContextCreationStart,this);let p=!0,g;try{Ie.Current=this,s?g=await this.internalLoadInitialContent(d,s):g=[]}catch(f){console.error(f),p=!1}if(!p)return this.onError("Failed to load initial content"),!1;if(d!==this._createId||(i=s?.abortSignal)!=null&&i.aborted)return!1;if(this.internalOnUpdateVisible(),!this.renderer)return rt&&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),Ie.Current=this,Ie.Current=this;for(let f=0;f<this.new_scripts.length;f++){const v=this.new_scripts[f];if(v.gameObject!==void 0&&v.gameObject!==null){v.gameObject.userData===void 0&&(v.gameObject.userData={}),v.gameObject.userData.components===void 0&&(v.gameObject.userData.components=[]);const b=v.gameObject.userData.components;b.includes(v)||b.push(v)}}if(this.post_setup_callbacks)for(let f=0;f<this.post_setup_callbacks.length;f++)Ie.Current=this,await this.post_setup_callbacks[f](this);if(!this._mainCamera){Ie.Current=this;let f=null;Mr(this.scene,v=>{const b=v;if(b!=null&&b.isCamera){if(wc(b.gameObject),!b.activeAndEnabled)return;if(b.tag==="MainCamera")return f=b,!0;f=b}}),f?this.setCurrentCamera(f):!ge.dispatchCallback(ye.MissingCamera,this,{files:g})&&!this.mainCamera&&!this.isManagedExternally&&console.warn("Missing camera in main scene",this)}this.input.bindEvents(),Ie.Current=this,Hd(this),this.physics.engine&&((n=this.physics.engine)==null||n.step(0),(o=this.physics.engine)==null||o.postStep()),!this.isManagedExternally&&this.composer&&this.mainCamera,this._sizeChanged=!0,this._stats&&(this._stats.showPanel(0),this._stats.dom.style.position="absolute",(r=this.domElement.shadowRoot)==null||r.appendChild(this._stats.dom)),rt&&kd(this.scene,!0),this.targetFrameRate===void 0?(rt&&console.warn("No target framerate set, using default",Ie.DefaultTargetFrameRate),this.targetFrameRate=Ie._defaultTargetFramerate):rt&&console.log("Target framerate set to",this.targetFrameRate),this._dispatchReadyAfterFrame=!0;const y=ge.dispatchCallback(ye.ContextCreated,this,{files:g});return y&&("internalSetLoadingMessage"in this.domElement&&typeof this.domElement.internalSetLoadingMessage=="function"&&((l=this.domElement)==null||l.internalSetLoadingMessage("finish loading")),await y),(c=s?.abortSignal)!=null&&c.aborted?!1:(Ns(this,ye.ContextCreated),rt&&console.log("Context Created...",this.renderer,this.renderer.domElement),this._isCreating=!1,!this.isManagedExternally&&!((h=s?.abortSignal)!=null&&h.aborted)&&this.restartRenderLoop(),!0)}async internalLoadInitialContent(s,t){var i,n,o,r;const l=new Array;if(t.files.length===0)return l;const c=[...t.files],h={name:"",progress:null,index:0,count:c.length},d=fs(),u=0;for(let p=0;p<c.length;p++){if((i=t.abortSignal)!=null&&i.aborted){rt&&console.log("Aborting loading because of abort signal");break}if(s!==this._createId){rt&&console.log("Aborting loading because create id changed",s,this._createId);break}const g=c[p];(n=t?.onLoadingStart)==null||n.call(this,p,g),rt&&console.log("Context Load "+g);const y=await d.loadSync(this,g,g,u,f=>{var v,b;(v=t.abortSignal)!=null&&v.aborted||(h.name=g,h.progress=f,h.index=p,h.count=c.length,(b=t.onLoadingProgress)==null||b.call(this,h))});(o=t?.onLoadingFinished)==null||o.call(this,p,g,y??null),y?l.push({src:g,file:y}):console.warn("Could not load file: "+g)}if(s!==this._createId||(r=t.abortSignal)!=null&&r.aborted){rt&&console.log("Aborting loading because create id changed or abort signal was set",s,this._createId);for(const p of l)if(p&&p.file)for(const g of p.file.scenes)Ri(g,!0,!0)}else{let p=!1;for(const g of l)g&&g.file&&(g.file.scene?(p=!0,this.scene.add(g.file.scene)):console.warn("No scene found in loaded file"));if(!p){for(const g of l)if(g&&g.file&&"parser"in g.file){let y=0;if(!Array.isArray(g.file.parser.json.materials))continue;for(let f=0;f<g.file.parser.json.materials.length;f++){const v=await g.file.parser.getDependency("material",f),b=new I;b.position.x=f*1.1,b.position.y=y,this.scene.add(b),go.createPrimitive("ShaderBall",{parent:b,material:v})}y+=1}}}return l}restartRenderLoop(){return this.renderer?this._isCreating?(console.warn("Can not start render loop while creating context"),!1):(this.renderer.setAnimationLoop((s,t)=>{this.isManagedExternally||this.update(s,t)}),!0):(console.error("Can not start render loop without renderer"),!1)}update(s,t){if(t===void 0&&(t=null),F()||rt||uk())try{performance.mark("update.start"),this.internalStep(s,t),this._renderlooperrors=0,performance.mark("update.end"),performance.measure("NE Frame","update.start","update.end")}catch(i){this._renderlooperrors+=1,(F()||rt)&&(i instanceof Error||i instanceof TypeError)&&De("Caught unhandled exception during render-loop - see console for details.",Ci.Error),console.error("Frame #"+this.time.frame+`
762
+ `,i),this._renderlooperrors>=3&&(console.warn("Stopping render loop due to error"),this.renderer.setAnimationLoop(null)),this.domElement.dispatchEvent(new CustomEvent("error",{detail:i}))}else this.internalStep(s,t)}updatePhysics(s){this.internalUpdatePhysics(s)}internalStep(s,t){this.internalOnBeforeRender(s,t)!==!1&&(this.internalOnRender(),this.internalOnAfterRender())}internalOnBeforeRender(s,t){var i;this.renderer.info.autoReset=!0;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=s),this._accumulatedTime+=(s-this._lastTimestamp)/1e3,this._lastTimestamp=s;let o=this.targetFrameRate;if(typeof o=="object"&&(o=o.value),this._accumulatedTime<1/(o+1))return!1;this._accumulatedTime=0}if((i=this._stats)==null||i.begin(),Ie.Current=this,this.onHandlePaused())return!1;for(Ie.Current=this,this.time.update(),d2&&console.log("FPS",this.time.smoothedFps.toFixed(0)),Hd(this),$d(this.scene),i_(this),Ns(this,-1);this._cameraStack.length>0&&(!this.mainCameraComponent||this.mainCameraComponent.destroyed);){this._cameraStack.splice(this._cameraStack.length-1,1);const o=this._cameraStack[this._cameraStack.length-1];this.setCurrentCamera(o)}if(this.pre_update_oneshot_callbacks){for(const o in this.pre_update_oneshot_callbacks)this.pre_update_oneshot_callbacks[o]();this.pre_update_oneshot_callbacks.length=0}if(this.pre_update_callbacks)for(const o in this.pre_update_callbacks)this.pre_update_callbacks[o]();this._currentFrameEvent=0;for(let o=0;o<this.scripts_earlyUpdate.length;o++){const r=this.scripts_earlyUpdate[o];r.activeAndEnabled&&r.earlyUpdate!==void 0&&(Ie.Current=this,r.earlyUpdate())}if(this.executeCoroutines(0),Ns(this,0),this.onHandlePaused())return!1;this._currentFrameEvent=1;for(let o=0;o<this.scripts_update.length;o++){const r=this.scripts_update[o];r.activeAndEnabled&&r.update!==void 0&&(Ie.Current=this,r.update())}if(this.executeCoroutines(1),Ns(this,1),this.onHandlePaused())return!1;this._currentFrameEvent=2;for(let o=0;o<this.scripts_lateUpdate.length;o++){const r=this.scripts_lateUpdate[o];r.activeAndEnabled&&r.lateUpdate!==void 0&&(Ie.Current=this,r.lateUpdate())}if(this.executeCoroutines(2),Ns(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 o=0;o<this.scripts_onBeforeRender.length;o++){const r=this.scripts_onBeforeRender[o];r.activeAndEnabled&&r.onBeforeRender!==void 0&&(Ie.Current=this,r.onBeforeRender(t))}if(this.executeCoroutines(3),Ns(this,3),this._sizeChanged&&this.updateSize(),this.pre_render_callbacks)for(const o in this.pre_render_callbacks)this.pre_render_callbacks[o](t)}return!0}internalUpdatePhysics(s){if(!this.physics.engine)return!1;const t=s,i=this.time.deltaTime/t;for(let n=0;n<t;n++)this._currentFrameEvent=9,this.executeCoroutines(9),this.physics.engine.step(i),this._currentFrameEvent=10,this.executeCoroutines(10);return this.physics.engine.postStep(),!0}internalOnRender(){this.isManagedExternally||(fk(this),this._currentFrameEvent=-1,jC.update(),this.renderNow(),this._currentFrameEvent=4)}internalOnAfterRender(){if(this.isVisibleToUser||this.runInBackground){for(let s=0;s<this.scripts_onAfterRender.length;s++){const t=this.scripts_onAfterRender[s];t.activeAndEnabled&&t.onAfterRender!==void 0&&(Ie.Current=this,t.onAfterRender())}if(this.executeCoroutines(4),Ns(this,4),this.post_render_callbacks)for(const s in this.post_render_callbacks)this.post_render_callbacks[s]()}this._currentFrameEvent=-1,this.connection.sendBufferedMessagesNow(),this._stats&&(this._stats.end(),this.time.frameCount%150===0&&console.log(this.renderer.info.render.calls+" DrawCalls",`
763
763
  Render:`,{...this.renderer.info.render},`
764
764
  Memory:`,{...this.renderer.info.memory},`
765
- Target Framerate: `+this.targetFrameRate)),this._dispatchReadyAfterFrame&&(this._dispatchReadyAfterFrame=!1,this.domElement.dispatchEvent(new CustomEvent("ready")),ge.dispatchCallback(ye.ContextFirstFrameRendered,this))}renderNow(s){var t;return!s&&(s=this.mainCamera,!s)?!1:(this.handleRendererContextLost(),this._isRendering=!0,this.renderRequiredTextures(),this.renderer.toneMapping!==wa&&iw(),this.composer&&!this.isInXR?(s&&((t=this.composer.passes[0])==null?void 0:t.mainCamera)!=s&&this.composer.setMainCamera(s),this.composer.render(this.time.deltaTime)):s&&(this.isInXR&&X.isMacOS()&&this.renderer.clearDepth(),this.renderer.render(this.scene,s)),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 s=this.evaluatePaused();if(this._wasPaused!==s){hk&&console.log("Paused?",s,"context:"+this.alias);for(let t=0;t<this.scripts_pausedChanged.length;t++){const i=this.scripts_pausedChanged[t];i.activeAndEnabled&&i.onPausedChanged!==void 0&&(Ie.Current=this,i.onPausedChanged(s,this._wasPaused))}}return this._wasPaused=s,s}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 lo(this.domWidth,this.domHeight),this._requireDepthTexture){const i=new kS(this.domWidth,this.domHeight);this._renderTarget.depthTexture=i}this._requireColorTexture&&(this._renderTarget.texture=new Le,this._renderTarget.texture.generateMipmaps=!1,this._renderTarget.texture.minFilter=md,this._renderTarget.texture.magFilter=md,this._renderTarget.texture.format=pd)}const s=this._renderTarget;s.texture&&(s.texture.colorSpace=this.renderer.outputColorSpace);const t=this.renderer.getRenderTarget();this.renderer.setRenderTarget(s),this.renderer.render(this.scene,this.mainCamera),this.renderer.setRenderTarget(t)}executeCoroutines(s){var t;if(this.coroutines[s]){const n=this.coroutines[s];for(let o=0;o<n.length;o++)try{const r=n[o];if(!r.comp||r.comp.destroyed||!r.main||r.comp.enabled===!1){uk&&console.log("Removing coroutine",r.comp,r.comp.enabled),n.splice(o,1),--o;continue}const l=r.chained;if(l&&l.length>0){const d=l[l.length-1].next();if(d.done&&l.pop(),i(d)&&(r.chained||(r.chained=[]),r.chained.push(d.value)),!d.done)continue}const c=r.main.next();if(c.done===!0){n.splice(o,1),--o;continue}const h=c.value;if(i(h)){if(h.next().done)continue;r.chained||(r.chained=[]),r.chained.push(h)}else if(h instanceof Promise){const d=h;r.chained||(r.chained=[]);const u=H_(d);(t=r.chained)==null||t.push(u);continue}}catch(r){console.error(r)}}function i(n){return!!(n&&n.next&&n.return)}}};let ee=Ie;a(ee,"_defaultTargetFramerate",{value:90,toString(){return this.value}}),a(ee,"_defaultWebglRendererParameters",{antialias:!0,alpha:!1,powerPreference:X.isiOS()||X.isMacOS()?"default":"high-performance",stencil:!0});const Ji=O("debuglicense"),hw=[];let Ar="basic";Ji&&console.log("License Type: "+Ar);function _o(){switch(Ar){case"pro":case"enterprise":return!0}return!1}function rf(){switch(Ar){case"indie":return!0}return!1}function Os(){return _o()||rf()}function gk(s){if(_o()||rf())return s(!0);hw.push(s)}function fk(s){for(const t of hw)try{t(s)}catch{}}ge.registerCallback(ye.ContextRegistered,s=>{bk(s.context),wk(),vk(s.context)});let Ir,af=!1,xu="";async function yk(){if(Ir)return Ir;if(Ar==="basic")try{const s="https://engine.needle.tools/licensing/check?location="+encodeURIComponent(window.location.href)+"&version="+_s+"&generator="+encodeURIComponent(Rd),t=await fetch(s,{method:"GET"}).catch(i=>{Ji&&console.error("License check failed",i)});t?.status===200?(af=!1,Ji&&console.log("License check succeeded"),Ar="pro",fk(!0)):t?.status===403?(af=!0,xu=await t.text()):Ji&&console.log("License check failed with status "+t?.status)}catch(s){Ji&&console.error("License check failed",s)}else Ji&&console.log('Runtime license check is skipped because license is already applied as "'+Ar+'"')}Ir=yk();async function vk(s){function t(){const o=document.createElement("div");o.className="needle-forbidden",o.style.cssText=`
765
+ Target Framerate: `+this.targetFrameRate)),this._dispatchReadyAfterFrame&&(this._dispatchReadyAfterFrame=!1,this.domElement.dispatchEvent(new CustomEvent("ready")),ge.dispatchCallback(ye.ContextFirstFrameRendered,this))}renderNow(s){var t;return!s&&(s=this.mainCamera,!s)?!1:(this.handleRendererContextLost(),this._isRendering=!0,this.renderRequiredTextures(),this.renderer.toneMapping!==wa&&iw(),this.composer&&!this.isInXR?(s&&((t=this.composer.passes[0])==null?void 0:t.mainCamera)!=s&&this.composer.setMainCamera(s),this.composer.render(this.time.deltaTime)):s&&(this.isInXR&&X.isMacOS()&&this.renderer.clearDepth(),this.renderer.render(this.scene,s)),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 s=this.evaluatePaused();if(this._wasPaused!==s){h2&&console.log("Paused?",s,"context:"+this.alias);for(let t=0;t<this.scripts_pausedChanged.length;t++){const i=this.scripts_pausedChanged[t];i.activeAndEnabled&&i.onPausedChanged!==void 0&&(Ie.Current=this,i.onPausedChanged(s,this._wasPaused))}}return this._wasPaused=s,s}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 lo(this.domWidth,this.domHeight),this._requireDepthTexture){const i=new kS(this.domWidth,this.domHeight);this._renderTarget.depthTexture=i}this._requireColorTexture&&(this._renderTarget.texture=new Le,this._renderTarget.texture.generateMipmaps=!1,this._renderTarget.texture.minFilter=md,this._renderTarget.texture.magFilter=md,this._renderTarget.texture.format=pd)}const s=this._renderTarget;s.texture&&(s.texture.colorSpace=this.renderer.outputColorSpace);const t=this.renderer.getRenderTarget();this.renderer.setRenderTarget(s),this.renderer.render(this.scene,this.mainCamera),this.renderer.setRenderTarget(t)}executeCoroutines(s){var t;if(this.coroutines[s]){const n=this.coroutines[s];for(let o=0;o<n.length;o++)try{const r=n[o];if(!r.comp||r.comp.destroyed||!r.main||r.comp.enabled===!1){u2&&console.log("Removing coroutine",r.comp,r.comp.enabled),n.splice(o,1),--o;continue}const l=r.chained;if(l&&l.length>0){const d=l[l.length-1].next();if(d.done&&l.pop(),i(d)&&(r.chained||(r.chained=[]),r.chained.push(d.value)),!d.done)continue}const c=r.main.next();if(c.done===!0){n.splice(o,1),--o;continue}const h=c.value;if(i(h)){if(h.next().done)continue;r.chained||(r.chained=[]),r.chained.push(h)}else if(h instanceof Promise){const d=h;r.chained||(r.chained=[]);const u=H_(d);(t=r.chained)==null||t.push(u);continue}}catch(r){console.error(r)}}function i(n){return!!(n&&n.next&&n.return)}}};let ee=Ie;a(ee,"_defaultTargetFramerate",{value:90,toString(){return this.value}}),a(ee,"_defaultWebglRendererParameters",{antialias:!0,alpha:!1,powerPreference:X.isiOS()||X.isMacOS()?"default":"high-performance",stencil:!0});const Ji=O("debuglicense"),hw=[];let Ar="basic";Ji&&console.log("License Type: "+Ar);function _o(){switch(Ar){case"pro":case"enterprise":return!0}return!1}function rf(){switch(Ar){case"indie":return!0}return!1}function Os(){return _o()||rf()}function g2(s){if(_o()||rf())return s(!0);hw.push(s)}function f2(s){for(const t of hw)try{t(s)}catch{}}ge.registerCallback(ye.ContextRegistered,s=>{b2(s.context),w2(),v2(s.context)});let Ir,af=!1,xu="";async function y2(){if(Ir)return Ir;if(Ar==="basic")try{const s="https://engine.needle.tools/licensing/check?location="+encodeURIComponent(window.location.href)+"&version="+_s+"&generator="+encodeURIComponent(Rd),t=await fetch(s,{method:"GET"}).catch(i=>{Ji&&console.error("License check failed",i)});t?.status===200?(af=!1,Ji&&console.log("License check succeeded"),Ar="pro",f2(!0)):t?.status===403?(af=!0,xu=await t.text()):Ji&&console.log("License check failed with status "+t?.status)}catch(s){Ji&&console.error("License check failed",s)}else Ji&&console.log('Runtime license check is skipped because license is already applied as "'+Ar+'"')}Ir=y2();async function v2(s){function t(){const o=document.createElement("div");o.className="needle-forbidden",o.style.cssText=`
766
766
  position: fixed;
767
767
  top: 0;
768
768
  left: 0;
@@ -790,7 +790,7 @@ Target Framerate: `+this.targetFrameRate)),this._dispatchReadyAfterFrame&&(this.
790
790
  align-items: center;
791
791
  background-color: rgba(0,0,0,.3);
792
792
  text-shadow: 0 0 2px black;
793
- `;const c=l.style.cssText,h=xu?.length>1?xu:"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!==o&&o.appendChild(l),o.style.cssText!==r&&(o.style.cssText=r),l.style.cssText!==c&&(l.style.cssText=c)},500),o}let i=t();const n=i.style.cssText;setInterval(()=>{var o;af===!0&&(i.style.cssText!==n&&(i=t()),s.domElement.shadowRoot?i.parentNode!==s.domElement.shadowRoot&&((o=s.domElement.shadowRoot)==null||o.appendChild(i)):i.parentNode!=document.body&&document.body.appendChild(i))},500)}async function bk(s){try{if(Os()!==!0)return lf(s)}catch(t){return Ji&&console.log("License check failed",t),lf(s)}Ji&&lf(s)}async function lf(s){s.domElement.addEventListener("ready",()=>!0),await Ir?.catch(()=>{}),!Os()&&_k()}let dw=0;async function _k(s){var t;const i=Date.now();if(i-dw<2e3)return;dw=i;const n=`
793
+ `;const c=l.style.cssText,h=xu?.length>1?xu:"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!==o&&o.appendChild(l),o.style.cssText!==r&&(o.style.cssText=r),l.style.cssText!==c&&(l.style.cssText=c)},500),o}let i=t();const n=i.style.cssText;setInterval(()=>{var o;af===!0&&(i.style.cssText!==n&&(i=t()),s.domElement.shadowRoot?i.parentNode!==s.domElement.shadowRoot&&((o=s.domElement.shadowRoot)==null||o.appendChild(i)):i.parentNode!=document.body&&document.body.appendChild(i))},500)}async function b2(s){try{if(Os()!==!0)return lf(s)}catch(t){return Ji&&console.log("License check failed",t),lf(s)}Ji&&lf(s)}async function lf(s){s.domElement.addEventListener("ready",()=>!0),await Ir?.catch(()=>{}),!Os()&&_2()}let dw=0;async function _2(s){var t;const i=Date.now();if(i-dw<2e3)return;dw=i;const n=`
794
794
  position: relative;
795
795
  display: block;
796
796
  font-size: 18px;
@@ -806,7 +806,7 @@ Target Framerate: `+this.targetFrameRate)),this._dispatchReadyAfterFrame&&(this.
806
806
  padding-left: 25px;
807
807
  border-radius: .5em;
808
808
  border: 2px solid rgba(160,160,160,.3);
809
- `,o=`Needle Engine \u2014 No license active, commercial use is not allowed. Visit https://needle.tools/pricing for more information and licensing options! v${_s}`;(t=ee.Current)!=null&&t.xr?console.log(o):console.log("%c "+o,n)}async function wk(){var s;if(!window.crossOriginIsolated)try{const t="https://needle-engine-analytics-v2-r26roub2hq-lz.a.run.app";if(t){Ji&&console.log("Analytics backend url",t);const i=window.location.href.split("?")[0];let n="api/v2/new/request";t.endsWith("/")||(n="/"+n);const o=Ar,r=`${t}${n}`;Ji&&console.log("Sending non-commercial usage message to analytics backend",r);const l={license:o,url:i,hostname:window.location.hostname,pathname:window.location.pathname,version:_s,generator:Rd,build_time:tg,public_key:hc},c=(s=navigator.sendBeacon)==null?void 0:s.call(navigator,r,JSON.stringify(l));Ji&&console.log("Send beacon result",c)}}catch(t){Ji&&console.log("Failed to send non-commercial usage message to analytics backend",t)}}const jr=O("debugloading"),Ac=O("debugloadingrendering"),uw=O("debuglicense");class xk{constructor(){a(this,"className"),a(this,"additionalClasses")}}let Ic=0,pw;function cf(s){jr&&console.log(s.progress.loaded.toFixed(0)+"/"+s.progress.total.toFixed(0),s);const t=s.count,i=s.progress.total;i===0||i===void 0?(pw!==s.name&&(Ic=0),pw=s.name,Ic+=(1-Ic)*.001,jr&&xe("Loading "+s.name+" did not report total size")):Ic=s.progress.loaded/i;const n=s.index/t+Ic/t;return W.clamp01(n)}const hf=class{constructor(s,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=s,this._loadingElementOptions=t}async onLoadingBegin(s){const t=this._element.shadowRoot||this._element;if(jr&&console.warn("Begin Loading"),!this._loadingElement){for(let i=0;i<t.children.length;i++){const n=t.children[i];if(n.classList.contains(hf.LoadingContainerClassName)){if(!this._allowCustomLoadingElement){jr&&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(s??"")}onLoadingUpdate(s,t){var i;if(!((i=this._loadingElement)!=null&&i.parentNode))return;let n=0;typeof s=="number"?n=s:("index"in s&&(n=cf(s)),!t&&"name"in s&&this.setMessage("loading "+s.name)),this.loadingProgress=n,t&&this.setMessage(t),this.updateDisplay()}onLoadingFinished(){jr&&console.warn("Finished Loading"),Ac||(this.loadingProgress=1,this.onDoneLoading())}setMessage(s){this._messageContainer&&(this._messageContainer.innerText=s)}smoothProgressLoop(){if(this._progressLoop)return;let s=1/12;Ac&&(s=1/500,typeof Ac=="number"&&(s*=Ac)),this._progressLoop=setInterval(()=>{this.loadingProgress>=.95&&!Ac&&(s=.9),this._progress=W.lerp(this._progress,this.loadingProgress,s*this.loadingProgress),this.updateDisplay()},s)}onDoneLoading(){this._loadingElement&&(jr&&console.log("Hiding loading element"),this._loadingElement.style.display="none",this._loadingElement.remove()),this._progressLoop&&clearInterval(this._progressLoop),this._progressLoop=null}updateDisplay(){const s=this._progress,t=(s*100).toFixed(0)+"%";this._loadingBar&&(this._loadingBar.style.width=s*100+"%"),this._loadingTextContainer&&(this._loadingTextContainer.textContent=t)}createLoadingElement(s){var t,i;jr&&!s&&console.log("Creating loading element"),this._loadingElement=s||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 o=_o();if(!s&&(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",n==="light"?this._loadingElement.style.backgroundColor="#ddd":this._loadingElement.style.backgroundColor="#222",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)",o&&this._element)){const f=this._element.getAttribute("loading-background-color");f&&(this._loadingElement.style.backgroundColor=f);const v=this._element.getAttribute("loading-text-color");v&&(this._loadingElement.style.color=v)}const r=((t=this._loadingElementOptions)==null?void 0:t.className)??hf.LoadingContainerClassName;if(this._loadingElement.classList.add(r),(i=this._loadingElementOptions)!=null&&i.additionalClasses)for(const f of this._loadingElementOptions.additionalClasses)this._loadingElement.classList.add(f);const l=document.createElement("div");this._loadingElement.appendChild(l);const c=document.createElement("img"),h=120;if(c.style.width=`${h}px`,c.style.height=`${h}px`,c.style.paddingTop="20px",c.style.paddingBottom="10px",c.style.margin="0px",c.style.userSelect="none",c.style.objectFit="contain",c.style.transition="transform 1.5s ease-out, opacity .3s ease-in-out",c.style.transform="translateY(30px)",c.style.opacity="0.05",setTimeout(()=>{c.style.opacity="1",c.style.transform="translateY(0px)"},1),c.src=xP,o&&this._element){const f=this._element.getAttribute("loading-logo-src");f&&(c.src=f)}l.appendChild(c);const d=document.createElement("div");d.style.cssText=`
809
+ `,o=`Needle Engine \u2014 No license active, commercial use is not allowed. Visit https://needle.tools/pricing for more information and licensing options! v${_s}`;(t=ee.Current)!=null&&t.xr?console.log(o):console.log("%c "+o,n)}async function w2(){var s;if(!window.crossOriginIsolated)try{const t="https://needle-engine-analytics-v2-r26roub2hq-lz.a.run.app";if(t){Ji&&console.log("Analytics backend url",t);const i=window.location.href.split("?")[0];let n="api/v2/new/request";t.endsWith("/")||(n="/"+n);const o=Ar,r=`${t}${n}`;Ji&&console.log("Sending non-commercial usage message to analytics backend",r);const l={license:o,url:i,hostname:window.location.hostname,pathname:window.location.pathname,version:_s,generator:Rd,build_time:tg,public_key:hc},c=(s=navigator.sendBeacon)==null?void 0:s.call(navigator,r,JSON.stringify(l));Ji&&console.log("Send beacon result",c)}}catch(t){Ji&&console.log("Failed to send non-commercial usage message to analytics backend",t)}}const jr=O("debugloading"),Ac=O("debugloadingrendering"),uw=O("debuglicense");class x2{constructor(){a(this,"className"),a(this,"additionalClasses")}}let Ic=0,pw;function cf(s){jr&&console.log(s.progress.loaded.toFixed(0)+"/"+s.progress.total.toFixed(0),s);const t=s.count,i=s.progress.total;i===0||i===void 0?(pw!==s.name&&(Ic=0),pw=s.name,Ic+=(1-Ic)*.001,jr&&xe("Loading "+s.name+" did not report total size")):Ic=s.progress.loaded/i;const n=s.index/t+Ic/t;return W.clamp01(n)}const hf=class{constructor(s,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=s,this._loadingElementOptions=t}async onLoadingBegin(s){const t=this._element.shadowRoot||this._element;if(jr&&console.warn("Begin Loading"),!this._loadingElement){for(let i=0;i<t.children.length;i++){const n=t.children[i];if(n.classList.contains(hf.LoadingContainerClassName)){if(!this._allowCustomLoadingElement){jr&&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(s??"")}onLoadingUpdate(s,t){var i;if(!((i=this._loadingElement)!=null&&i.parentNode))return;let n=0;typeof s=="number"?n=s:("index"in s&&(n=cf(s)),!t&&"name"in s&&this.setMessage("loading "+s.name)),this.loadingProgress=n,t&&this.setMessage(t),this.updateDisplay()}onLoadingFinished(){jr&&console.warn("Finished Loading"),Ac||(this.loadingProgress=1,this.onDoneLoading())}setMessage(s){this._messageContainer&&(this._messageContainer.innerText=s)}smoothProgressLoop(){if(this._progressLoop)return;let s=1/12;Ac&&(s=1/500,typeof Ac=="number"&&(s*=Ac)),this._progressLoop=setInterval(()=>{this.loadingProgress>=.95&&!Ac&&(s=.9),this._progress=W.lerp(this._progress,this.loadingProgress,s*this.loadingProgress),this.updateDisplay()},s)}onDoneLoading(){this._loadingElement&&(jr&&console.log("Hiding loading element"),this._loadingElement.style.display="none",this._loadingElement.remove()),this._progressLoop&&clearInterval(this._progressLoop),this._progressLoop=null}updateDisplay(){const s=this._progress,t=(s*100).toFixed(0)+"%";this._loadingBar&&(this._loadingBar.style.width=s*100+"%"),this._loadingTextContainer&&(this._loadingTextContainer.textContent=t)}createLoadingElement(s){var t,i;jr&&!s&&console.log("Creating loading element"),this._loadingElement=s||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 o=_o();if(!s&&(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",n==="light"?this._loadingElement.style.backgroundColor="#ddd":this._loadingElement.style.backgroundColor="#222",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)",o&&this._element)){const f=this._element.getAttribute("loading-background-color");f&&(this._loadingElement.style.backgroundColor=f);const v=this._element.getAttribute("loading-text-color");v&&(this._loadingElement.style.color=v)}const r=((t=this._loadingElementOptions)==null?void 0:t.className)??hf.LoadingContainerClassName;if(this._loadingElement.classList.add(r),(i=this._loadingElementOptions)!=null&&i.additionalClasses)for(const f of this._loadingElementOptions.additionalClasses)this._loadingElement.classList.add(f);const l=document.createElement("div");this._loadingElement.appendChild(l);const c=document.createElement("img"),h=120;if(c.style.width=`${h}px`,c.style.height=`${h}px`,c.style.paddingTop="20px",c.style.paddingBottom="10px",c.style.margin="0px",c.style.userSelect="none",c.style.objectFit="contain",c.style.transition="transform 1.5s ease-out, opacity .3s ease-in-out",c.style.transform="translateY(30px)",c.style.opacity="0.05",setTimeout(()=>{c.style.opacity="1",c.style.transform="translateY(0px)"},1),c.src=xP,o&&this._element){const f=this._element.getAttribute("loading-logo-src");f&&(c.src=f)}l.appendChild(c);const d=document.createElement("div");d.style.cssText=`
810
810
  display: flex;
811
811
  flex-direction: column;
812
812
  align-items: center;
@@ -815,7 +815,7 @@ Target Framerate: `+this.targetFrameRate)),this._dispatchReadyAfterFrame&&(this.
815
815
  opacity: 0;
816
816
  transition: opacity 1s ease-in-out 4s;
817
817
  `,setTimeout(()=>{d.style.opacity="1"},1),this._loadingElement.appendChild(d);const u=document.createElement("div"),p=100;u.style.display="flex",u.style.width=p+"%",u.style.height="3px",u.style.position="absolute",u.style.left="0",u.style.bottom="0px",u.style.opacity="0",u.style.transition="opacity 1s ease-in-out 2s",setTimeout(()=>{u.style.opacity="1"},1),n==="light"?u.style.backgroundColor="rgba(0,0,0,.2)":u.style.backgroundColor="rgba(255,255,255,.2)",this._loadingElement.appendChild(u),this._loadingBar=document.createElement("div"),u.appendChild(this._loadingBar);const g=function(f){return W.lerp(0,p,f)+"%"};if(this._loadingBar.style.background=`linear-gradient(90deg, #204f49 ${g(0)}, #0BA398 ${g(.3)}, #66A22F ${g(.6)}, #D7DB0A ${g(1)})`,this._loadingBar.style.backgroundAttachment="fixed",this._loadingBar.style.width="0%",this._loadingBar.style.height="100%",o&&this._element){const f=this._element.getAttribute("primary-color"),v=this._element.getAttribute("secondary-color");f&&v?this._loadingBar.style.background=`linear-gradient(90deg, ${f} ${g(0)}, ${v} ${g(1)})`:f?this._loadingBar.style.background=f:v&&(this._loadingBar.style.background=v)}this._loadingTextContainer=document.createElement("div"),this._loadingTextContainer.style.display="flex",this._loadingTextContainer.style.justifyContent="center",this._loadingTextContainer.style.marginTop=".2rem",d.appendChild(this._loadingTextContainer);const y=document.createElement("div");if(this._messageContainer=y,y.style.display="flex",y.style.fontSize=".8rem",y.style.paddingTop=".1rem",y.style.justifyContent="center",d.appendChild(y),o&&this._element){const f=this._element.getAttribute("loading-text-color");f&&(y.style.color=f)}return this.handleRuntimeLicense(this._loadingElement),this._loadingElement}async handleRuntimeLicense(s){let t=Os();if(t)return;uw&&console.log("Loading UI has commercial license?",t);const i=document.createElement("div");i.style.paddingTop=".6em",i.style.fontSize=".8em",i.style.textTransform="uppercase",i.innerText=`NEEDLE ENGINE NON COMMERCIAL VERSION
818
- CLICK HERE TO GET A LICENSE`,i.style.cursor="pointer",i.style.userSelect="none",i.style.textAlign="center",i.style.pointerEvents="all",i.addEventListener("click",()=>window.open("https://needle.tools/pricing","_self")),i.style.opacity="0",s.appendChild(i),!F()&&Ir&&(uw&&console.log("Waiting for runtime license check"),await Ir,t=Os()),!t&&(i.style.transition="opacity .5s ease-in-out",i.style.opacity="1")}};let df=hf;a(df,"LoadingContainerClassName","loading");const jc=O("debugoverlay"),mw="ar",Sk="quit-ar";class Ck{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(t,i,n){var o;if(this.currentSession=n,this.arContainer=i,X.isMozillaXR()){const r=t.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}),(o=this.arContainer)==null||o.appendChild(c)}i?(this.originalDomOverlayParent=i.parentNode,this.originalDomOverlayParent&&(console.log("Reparent DOM Overlay to body",i,i.style.display),i.style.display="",i.style.visibility="",document.body.appendChild(i))):console.warn("WebXRViewer: No DOM Overlay found")}this.ensureQuitARButton(this.arContainer)}onEnd(t){var i;for(const n of this._createdAROnlyElements)n.remove&&n.remove();for(const n of this._reparentedObjects){const o=n.el;(i=n.previousParent)==null||i.appendChild(o)}this._reparentedObjects.length=0,X.isMozillaXR()&&setTimeout(()=>{var n;const o=t.renderer.domElement;o&&((n=t.domElement.shadowRoot)==null||n.prepend(o));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(t){if(this.contentElement)return this.contentElement;jc&&console.log("Setup overlay container");const i=t.shadowRoot.querySelector(".content");this.contentElement=i;const n=t.shadowRoot.querySelector(".overlay-content");return n&&i.appendChild(n),jc&&!X.isMobileDevice()&&this.ensureQuitARButton(i),i}onRequestedEndAR(){this.currentSession&&(this.currentSession.end(),this.currentSession=null)}ensureQuitARButton(t){const i=document.createElement("slot");i.setAttribute("name","quit-ar"),this.appendElement(i,t),this._createdAROnlyElements.push(i),i.style.pointerEvents="auto";const n=document.querySelector(`.${Sk}`);if(n){n.addEventListener("click",this.requestEndAR),jc&&n.addEventListener("click",()=>console.log("Clicked quit-ar button"));return}i.addEventListener("click",this.requestEndAR),jc&&i.addEventListener("click",()=>console.log("Clicked fallback close button"));const o=document.createElement("div");o.style.cssText=`
818
+ CLICK HERE TO GET A LICENSE`,i.style.cursor="pointer",i.style.userSelect="none",i.style.textAlign="center",i.style.pointerEvents="all",i.addEventListener("click",()=>window.open("https://needle.tools/pricing","_self")),i.style.opacity="0",s.appendChild(i),!F()&&Ir&&(uw&&console.log("Waiting for runtime license check"),await Ir,t=Os()),!t&&(i.style.transition="opacity .5s ease-in-out",i.style.opacity="1")}};let df=hf;a(df,"LoadingContainerClassName","loading");const jc=O("debugoverlay"),mw="ar",S2="quit-ar";class C2{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(t,i,n){var o;if(this.currentSession=n,this.arContainer=i,X.isMozillaXR()){const r=t.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}),(o=this.arContainer)==null||o.appendChild(c)}i?(this.originalDomOverlayParent=i.parentNode,this.originalDomOverlayParent&&(console.log("Reparent DOM Overlay to body",i,i.style.display),i.style.display="",i.style.visibility="",document.body.appendChild(i))):console.warn("WebXRViewer: No DOM Overlay found")}this.ensureQuitARButton(this.arContainer)}onEnd(t){var i;for(const n of this._createdAROnlyElements)n.remove&&n.remove();for(const n of this._reparentedObjects){const o=n.el;(i=n.previousParent)==null||i.appendChild(o)}this._reparentedObjects.length=0,X.isMozillaXR()&&setTimeout(()=>{var n;const o=t.renderer.domElement;o&&((n=t.domElement.shadowRoot)==null||n.prepend(o));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(t){if(this.contentElement)return this.contentElement;jc&&console.log("Setup overlay container");const i=t.shadowRoot.querySelector(".content");this.contentElement=i;const n=t.shadowRoot.querySelector(".overlay-content");return n&&i.appendChild(n),jc&&!X.isMobileDevice()&&this.ensureQuitARButton(i),i}onRequestedEndAR(){this.currentSession&&(this.currentSession.end(),this.currentSession=null)}ensureQuitARButton(t){const i=document.createElement("slot");i.setAttribute("name","quit-ar"),this.appendElement(i,t),this._createdAROnlyElements.push(i),i.style.pointerEvents="auto";const n=document.querySelector(`.${S2}`);if(n){n.addEventListener("click",this.requestEndAR),jc&&n.addEventListener("click",()=>console.log("Clicked quit-ar button"));return}i.addEventListener("click",this.requestEndAR),jc&&i.addEventListener("click",()=>console.log("Clicked fallback close button"));const o=document.createElement("div");o.style.cssText=`
819
819
  position: fixed;
820
820
  top: 0;
821
821
  right: 0;
@@ -833,17 +833,17 @@ CLICK HERE TO GET A LICENSE`,i.style.cursor="pointer",i.style.userSelect="none",
833
833
  align-items: center;
834
834
  `,o.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=`
835
835
  /**filter: drop-shadow(0 0px 1.2px rgba(0,0,0,.7));**/
836
- `,r.appendChild(l),jc&&console.log("Created fallback close button",r,t)}appendElement(t,i){return i.shadowRoot?i.shadowRoot.appendChild(t):i.appendChild(t)}}const Ok=O("debugdecoders");let uf=null;function gw(){if(!uf){const s=wm(null);uf={dracoLoader:s.dracoLoader,ktx2Loader:s.ktx2Loader,meshoptDecoder:s.meshoptDecoder}}return uf}function fw(s){s!==void 0&&typeof s=="string"&&MC(s)}function yw(s){if(s!==void 0&&typeof s=="string"&&s!=="js"){const t=gw();Ok&&console.log("Setting draco decoder type to",s),t.dracoLoader.setDecoderConfig({type:s})}}function vw(s){s!==void 0&&typeof s=="string"&&RC(s)}function Su(s,t){const i=gw();return t.renderer?i.ktx2Loader.detectSupport(t.renderer):console.warn("No renderer provided to detect ktx2 support - loading KTX2 textures will probably fail"),PC(s),s.dracoLoader||s.setDRACOLoader(i.dracoLoader),s.ktx2Loader||s.setKTX2Loader(i.ktx2Loader),s.meshoptDecoder||s.setMeshoptDecoder(i.meshoptDecoder),kC(s,{progressive:!0}),s}const $a=function(s){return m(s)},m=function(s){if(s===void 0&&(s=null),!Array.isArray(s))s=bw(s);else for(let t=0;t<s.length;t++){const i=s[t];s[t]=bw(i)}return function(t,i){typeof i!="string"&&(i=i.name),Object.getOwnPropertyDescriptor(t,"$serializedTypes")||(t.$serializedTypes={});const n=t.$serializedTypes=t.$serializedTypes||{};n[i]=s}};function bw(s){var t,i;switch((i=(t=s?.prototype)==null?void 0:t.constructor)==null?void 0:i.name){case"Number":case"String":case"Boolean":return null}return s}class P extends I{constructor(){super(...arguments),a(this,"guid")}static isDestroyed(t){return kr(t)}static setActive(t,i,n=!0){t&&(Mc(t,i),$d(t),i&&n&&i_(ee.Current,t))}static isActiveSelf(t){return Fa(t)}static isActiveInHierarchy(t){return A_(t)}static markAsInstancedRendered(t,i){I_(t,i)}static isUsingInstancing(t){return iu(t)}static foreachComponent(t,i,n=!0){return Mr(t,i,n)}static instantiateSynced(t,i){return t?Dg(t,i):null}static instantiate(t,i=null){return"isAssetReference"in t,Ua(t,i)}static destroySynced(t,i,n=!0){if(!t)return;const o=t;i=i??ee.Current,xc(o,i.connection,n)}static destroy(t,i=!0){return Ri(t,i)}static add(t,i,n){if(!(!t||!i)){if(t===i){console.warn("Can not add object to self",t);return}n||(n=ee.Current),i.add(t),Mc(t,!0),$d(t),n?P.foreachComponent(t,o=>{Rg(o,n),!o.__internalDidAwakeAndStart&&n.new_script_start.includes(o)===!1&&n.new_script_start.push(o)},!0):console.warn("Missing context")}}static remove(t){var i;t&&((i=t.parent)==null||i.remove(t),Mc(t,!1),$d(t),P.foreachComponent(t,n=>{p2(n)},!0))}static invokeOnChildren(t,i,...n){this.invoke(t,i,!0,n)}static invoke(t,i,n=!1,...o){t&&this.foreachComponent(t,r=>{const l=r[i];l&&typeof l=="function"&&l?.call(r,...o)},n)}static addNewComponent(t,i,n,o=!0){return Mi(t,i,n,{callAwake:o})}static addComponent(t,i,n,o){return Mi(t,i,n,o)}static moveComponent(t,i){return Mi(t,i)}static removeComponent(t){return $g(t.gameObject,t),t}static getOrAddComponent(t,i){return Cc(t,i)}static getComponent(t,i){return t===null?null:Pr(t,i)}static getComponents(t,i,n=null){return t===null?n??[]:Oc(t,i,n)}static findByGuid(t,i){return qg(t,i)}static findObjectOfType(t,i,n=!0){return Zd(t,i??ee.Current,n)}static findObjectsOfType(t,i){const n=[];return E_(t,n,i),n}static getComponentInChildren(t,i){return Pc(t,i)}static getComponentsInChildren(t,i,n=null){return Ba(t,i,n??void 0)}static getComponentInParent(t,i){return kc(t,i)}static getComponentsInParent(t,i,n=null){return Kd(t,i,n)}static getAllComponents(t){var i;const n=(i=t.userData)==null?void 0:i.components;return n?[...n]:[]}static*iterateComponents(t){var i;const n=(i=t?.userData)==null?void 0:i.components;if(n&&Array.isArray(n))for(let o=0;o<n.length;o++)yield n[o]}}const Cu=class{constructor(s){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(s)}get isComponent(){return!0}get context(){return this.__context??ee.Current}set context(s){this.__context=s}get scene(){return this.context.scene}get layer(){var s,t;return(t=(s=this.gameObject)==null?void 0:s.userData)==null?void 0:t.layer}get name(){var s,t;return(s=this.gameObject)!=null&&s.name?this.gameObject.name:(t=this.gameObject)==null?void 0:t.userData.name}set name(s){this.gameObject?(this.gameObject.userData||(this.gameObject.userData={}),this.gameObject.userData.name=s,this.__name=s):this.__name=s}get tag(){var s;return(s=this.gameObject)==null?void 0:s.userData.tag}set tag(s){this.gameObject&&(this.gameObject.userData||(this.gameObject.userData={}),this.gameObject.userData.tag=s)}get static(){var s;return(s=this.gameObject)==null?void 0:s.userData.static}set static(s){this.gameObject&&(this.gameObject.userData||(this.gameObject.userData={}),this.gameObject.userData.static=s)}get activeAndEnabled(){return!(this.destroyed||this.__isEnabled===!1||!this.__isActiveInHierarchy)}get __isActive(){return this.gameObject.visible}get __isActiveInHierarchy(){if(!this.gameObject)return!1;const s=this.gameObject[Sn];return s===void 0?!0:s}set __isActiveInHierarchy(s){this.gameObject&&(this.gameObject[Sn]=s)}awake(){}onEnable(){}onDisable(){}onDestroy(){this.__destroyed=!0}startCoroutine(s,t=Me.Update){return this.context.registerCoroutineUpdate(this,s,t)}stopCoroutine(s,t=Me.Update){this.context.unregisterCoroutineUpdate(s,t)}get destroyed(){return this.__destroyed}destroy(){this.__destroyed||this.__internalDestroy()}get __internalDidAwakeAndStart(){return this.__didAwake&&this.__didStart}__internalNewInstanceCreated(s){return this.__didAwake=!1,this.__didStart=!1,this.__didEnable=!1,this.__isEnabled=void 0,this.__destroyed=!1,this._internalInit(s),this}_internalInit(s){if(typeof s=="object")for(const t of Object.keys(s)){const i=s[t];typeof i!="function"&&(this[t]=i)}}__internalAwake(){this.__didAwake||(this.__didAwake=!0,this.awake())}__internalStart(){this.__didStart||(this.__didStart=!0,this.start&&this.start())}__internalEnable(s){return this.__destroyed?(F()&&console.warn("[Needle Engine Dev] Trying to enable destroyed component"),!1):this.__didAwake?this.__didEnable?(s!==!0&&(this.__isEnabled=!0),!1):(this.__didEnable=!0,this.__isEnabled=!0,this.onEnable(),!0):!1}__internalDisable(s){if(this.__didAwake){if(!this.__didEnable){s!==!0&&(this.__isEnabled=!1);return}this.__didEnable=!1,this.__isEnabled=!1,this.onDisable()}}__internalDestroy(){var s;this.__destroyed||(this.__destroyed=!0,this.__didAwake&&((s=this.onDestroy)==null||s.call(this),this.dispatchEvent(new CustomEvent("destroyed",{detail:this}))),M_(this))}get enabled(){return typeof this.__isEnabled=="boolean"?this.__isEnabled:!0}set enabled(s){if(this.__destroyed){F()&&console.warn(`[Needle Engine Dev] Trying to ${s?"enable":"disable"} destroyed component`);return}if(typeof s=="number"&&(s>=.5?s=!0:s=!1),!this.__didAwake){this.__isEnabled=s;return}s?this.__internalEnable():this.__internalDisable()}get worldPosition(){return te(this.gameObject)}set worldPosition(s){dt(this.gameObject,s)}setWorldPosition(s,t,i){yr(this.gameObject,s,t,i)}get worldQuaternion(){return Oe(this.gameObject)}set worldQuaternion(s){Gi(this.gameObject,s)}setWorldQuaternion(s,t,i,n){$m(this.gameObject,s,t,i,n)}get worldEuler(){return qm(this.gameObject)}set worldEuler(s){Gm(this.gameObject,s)}get worldRotation(){return this.gameObject.worldRotation}set worldRotation(s){this.setWorldRotation(s.x,s.y,s.z,!0)}setWorldRotation(s,t,i,n=!0){nc(this.gameObject,s,t,i,n)}get forward(){return Cu._forward.set(0,0,-1).applyQuaternion(this.worldQuaternion)}get right(){return Cu._right.set(1,0,0).applyQuaternion(this.worldQuaternion)}get up(){return Cu._up.set(0,1,0).applyQuaternion(this.worldQuaternion)}addEventListener(s,t){this._eventListeners[s]=this._eventListeners[s]||[],this._eventListeners[s].push(t)}removeEventListener(s,t){if(!this._eventListeners[s])return;const i=this._eventListeners[s].indexOf(t);i>=0&&this._eventListeners[s].splice(i,1)}dispatchEvent(s){if(!s||!this._eventListeners[s.type])return!1;const t=this._eventListeners[s.type];for(let i=0;i<t.length;i++)t[i](s);return!1}};let A=Cu;a(A,"_forward",new x),a(A,"_right",new x),a(A,"_up",new x);const Pk=Object.freeze(Object.defineProperty({__proto__:null,Behaviour:A,Component:A,GameObject:P},Symbol.toStringTag,{value:"Module"}));var kk=Object.defineProperty,Mk=Object.getOwnPropertyDescriptor,_w=(s,t,i,n)=>{for(var o=n>1?void 0:n?Mk(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&kk(t,i,o),o};class Lc extends A{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 t=te(this.from).clone(),i=te(this.to).clone(),n=t.distanceTo(i);this._centerPos.copy(t),this._centerPos.add(i),this._centerPos.multiplyScalar(.5),dt(this.gameObject,this.centered?this._centerPos:t),this.gameObject.lookAt(te(this.to).clone()),this.gameObject.scale.set(this.width,this.width,n)}}_w([m(P)],Lc.prototype,"from",2),_w([m(P)],Lc.prototype,"to",2);var Rk=Object.defineProperty,Tk=Object.getOwnPropertyDescriptor,Lr=(s,t,i,n)=>{for(var o=n>1?void 0:n?Tk(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&Rk(t,i,o),o};const wo=O("debuganimation");let ww=class{constructor(){a(this,"x"),a(this,"y")}};class Wt extends A{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(t){this.animations||(this.animations=[]),this.animations.push(t)}get time(){if(this.actions){for(const t of this.actions)if(t.isRunning())return t.time}return 0}set time(t){if(this.actions)for(const i of this.actions)i.time=t}get clip(){var t;return(t=this.animations)!=null&&t.length?this.animations[0]:null}set clip(t){if(!this.__didAwake){wo&&console.warn("Assign clip during serialization",t),this._tempAnimationClipBeforeGameObjectExisted=t;return}t&&(this.gameObject.animations||(this.gameObject.animations=[]),!this.animations.includes(t)&&(this.animations.length>0?this.animations.splice(0,0,t):this.animations.push(t)))}set clips(t){this.animations=t}set animations(t){t==null||!Array.isArray(t)||(this.gameObject?this.gameObject.animations=t:this._tempAnimationsArray=t)}get animations(){return this.gameObject.animations||this._tempAnimationsArray||[]}get actions(){return this._actions}set actions(t){this._actions=t}awake(){this.mixer=void 0,wo&&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 t;if(this.playAutomatically&&((t=this.animations)==null?void 0:t.length)>0){const i=Math.floor(Math.random()*this.animations.length),n=this.animations[i];this.play(i,{exclusive:!0,fadeDuration:0,startTime:this.randomStartTime?Math.random()*n.duration:0,loop:this.loop,clampWhenFinished:this.clampWhenFinished})}}update(){this.mixer&&(this.mixer.update(this.context.time.deltaTime),this._handles.forEach(t=>t.update()))}onDisable(){this.mixer&&this.mixer.stopAllAction()}onDestroy(){this.context.animations.unregisterAnimationMixer(this.mixer)}getAction(t){var i;return((i=this.actions)==null?void 0:i.find(n=>n.getClip().name===t))||null}get isPlaying(){if(this.actions){for(let t=0;t<this.actions.length;t++)if(this.actions[t].isRunning())return!0}return!1}stopAll(t){if(this.actions)for(const i of this.actions)t!=null&&t.fadeDuration?i.fadeOut(t.fadeDuration):i.stop()}stop(t,i){if(t===void 0){this.stopAll();return}else if(typeof t=="number"){if(t>=this.animations.length){wo&&console.log("No animation at index",t);return}t=this.animations[t]}else typeof t=="string"&&(t=this.animations.find(o=>o.name===t));if(!t){console.error("Could not find clip",t);return}const n=this.actions.find(o=>o.getClip()===t);if(!n){console.error("Could not find action",t);return}i!=null&&i.fadeDuration?n.fadeOut(i.fadeDuration):n.stop()}pause(t,i=!1){if(t===void 0){for(const o of this.actions)o.paused=!i;return}else if(typeof t=="number"){if(t>=this.animations.length){wo&&console.log("No animation at index",t);return}t=this.animations[t]}else typeof t=="string"&&(t=this.animations.find(o=>o.name===t));if(!t){console.error("Could not find clip",t);return}const n=this.actions.find(o=>o.getClip()===t);if(!n){console.error("Could not find action",t);return}n.paused=!i}resume(){for(const t of this.actions)t.paused=!1}play(t=0,i){if(wo&&console.log("PLAY",t),this.ensureMixer(),!this.mixer){wo&&console.warn("Missing mixer",this);return}t===void 0&&(t=0);let n=t;if(typeof t=="number"){if(t>=this.animations.length){wo&&console.log("No animation at index",t);return}n=this.animations[t]}else typeof t=="string"&&(n=this.animations.find(r=>r.name===t));if(!n){console.error("Could not find clip",t);return}i||(i={});for(const r of this.actions)if(r.getClip()===n)return this.internalOnPlay(r,i);if(!n.tracks){console.warn("Clip is no AnimationClip",n);return}const o=this.mixer.clipAction(n);return this.actions.push(o),this.internalOnPlay(o,i)}internalOnPlay(t,i){var n=this.actions.find(r=>r===t);if(n===t&&n.isRunning()&&n.time<n.getClip().duration){const r=this.tryFindHandle(t);if(n.paused&&(n.paused=!1),r)return r.waitForFinish()}if(i.loop===void 0&&(i.loop=this.loop),i.clampWhenFinished===void 0&&(i.clampWhenFinished=this.clampWhenFinished),i.minMaxOffsetNormalized===void 0&&this.randomStartTime&&(i.minMaxOffsetNormalized=this.minMaxOffsetNormalized),i.minMaxSpeed===void 0&&(i.minMaxSpeed=this.minMaxSpeed),i?.exclusive??!0)for(const r of this.actions)r!=n&&(i.fadeDuration?r.fadeOut(i.fadeDuration):r.stop());if(i!=null&&i.fadeDuration&&t.fadeIn(i.fadeDuration),t.enabled=!0,i?.startTime!=null)t.time=i.startTime;else if(i!=null&&i.minMaxOffsetNormalized&&i.minMaxOffsetNormalized.x!=0&&i.minMaxOffsetNormalized.y!=0){const r=t.getClip();t.time=W.lerp(i.minMaxOffsetNormalized.x,i.minMaxOffsetNormalized.y,Math.random())*r.duration}else t.time>=t.getClip().duration&&(t.time=0);i!=null&&i.minMaxSpeed?t.timeScale=W.lerp(i.minMaxSpeed.x,i.minMaxSpeed.y,Math.random()):t.timeScale=i?.speed??1,i?.loop!=null?t.loop=i.loop?MS:um:t.loop=um,i!=null&&i.clampWhenFinished&&(t.clampWhenFinished=!0),t.paused=!1,t.play(),wo&&console.log("PLAY",t.getClip().name,t);const o=new Ek(t,this.mixer,i,r=>{this._handles.splice(this._handles.indexOf(o),1)});return this._handles.push(o),o.waitForFinish()}tryFindHandle(t){for(const i of this._handles)if(i.action===t)return i}ensureMixer(){if(!this.mixer){const t="animationMixer";this.gameObject[t]&&(this.mixer=this.gameObject[t]),(!this.mixer||!this.mixer.clipAction)&&(this.mixer=new pm(this.gameObject),this.gameObject[t]=this.mixer)}this.context.animations.registerAnimationMixer(this.mixer)}}Lr([m()],Wt.prototype,"playAutomatically",2),Lr([m()],Wt.prototype,"randomStartTime",2),Lr([m(ww)],Wt.prototype,"minMaxSpeed",2),Lr([m(ww)],Wt.prototype,"minMaxOffsetNormalized",2),Lr([m()],Wt.prototype,"loop",2),Lr([m()],Wt.prototype,"clampWhenFinished",2),Lr([m(ao)],Wt.prototype,"clips",1);class Ek{constructor(t,i,n,o){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=t,this.mixer=i,this._resolvedOrRejectedCallback=o,this._options=n}waitForFinish(){return this.promise?this.promise:(this.promise=new Promise(t=>{this._resolveCallback=t}),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 t,i;this.dispose(),(t=this._resolvedOrRejectedCallback)==null||t.call(this,this),(i=this._resolveCallback)==null||i.call(this,this.action)}dispose(){this.mixer.removeEventListener("finished",this.onFinished)}}var Ak=Object.defineProperty,Ik=Object.getOwnPropertyDescriptor,xo=(s,t,i,n)=>{for(var o=n>1?void 0:n?Ik(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&Ak(t,i,o),o};class Qt{constructor(t=0,i=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=t,this.value=i}}xo([m()],Qt.prototype,"time",2),xo([m()],Qt.prototype,"value",2),xo([m()],Qt.prototype,"inTangent",2),xo([m()],Qt.prototype,"inWeight",2),xo([m()],Qt.prototype,"outTangent",2),xo([m()],Qt.prototype,"outWeight",2),xo([m()],Qt.prototype,"weightedMode",2);const Dc=class{constructor(){a(this,"keys",[])}static linearFromTo(s,t,i){const n=new Dc,o=new Qt;o.time=0,o.value=s;const r=new Qt;return r.time=i,r.value=t,n.keys.push(o,r),n}static constant(s){const t=new Dc,i=new Qt;return i.time=0,i.value=s,t.keys.push(i),t}clone(){var s;const t=new Dc;return t.keys=((s=this.keys)==null?void 0:s.map(i=>{const n=new Qt;return n.time=i.time,n.value=i.value,n.inTangent=i.inTangent,n.inWeight=i.inWeight,n.outTangent=i.outTangent,n.outWeight=i.outWeight,n.weightedMode=i.weightedMode,n}))||[],t}get duration(){return!this.keys||this.keys.length==0?0:this.keys[this.keys.length-1].time}evaluate(s){if(!this.keys||this.keys.length==0)return 0;if(this.keys.length===1)return this.keys[0].value;if(this.keys[0].time>=s)return this.keys[0].value;for(let t=0;t<this.keys.length;t++){const i=this.keys[t];if(i.time<=s)if(t+1<this.keys.length){const n=this.keys[t+1];if(n.time<s)continue;return!isFinite(i.outTangent)||!isFinite(n.inTangent)?i.value:Dc.interpolateValue(s,i,n)}else return i.value}return this.keys[this.keys.length-1].value}static interpolateValue(s,t,i){const n=t.time,o=t.value,r=t.outTangent,l=i.time,c=i.value,h=i.inTangent,d=l-n,u=d*d,p=u*d,g=((r+h)*d-2*(c-o))/p,y=(3*(c-o)-(h+2*r)*d)/u,f=r,v=o,b=s-n,w=b*b,_=w*b;return g*_+y*w+f*b+v}};let Dr=Dc;xo([m(Qt)],Dr.prototype,"keys",2);const Ou=Symbol("objectIsAnimatedData");function xw(s,t,i){if(!s)return;if(s[Ou]===void 0){if(!i)return;s[Ou]=new Set}const n=s[Ou];i?n.add(t):n.has(t)&&n.delete(t)}function jk(s){if(!s)return!1;const t=s[Ou];return t!==void 0&&t.size>0}class Lk{constructor(){a(this,"_context")}get context(){return this._context??ee.Current}get isStateMachineBehaviour(){return!0}}class Bc{constructor(t,i,n,o){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=t.name,this.nameHash=t.hash,this.normalizedTime=i,this.length=n,this.speed=o,this.action=t.motion.action||null,this.hasTransitions=((r=t.transitions)==null?void 0:r.length)>0||!1}}function Sw(s,t){return{name:"Empty",isLooping:!1,guid:t?.generateUUID()??vn.generateUUID(),index:-1,clip:new ao(s,0,[])}}var So=(s=>(s[s.If=1]="If",s[s.IfNot=2]="IfNot",s[s.Greater=3]="Greater",s[s.Less=4]="Less",s[s.Equals=6]="Equals",s[s.NotEqual=7]="NotEqual",s))(So||{}),pf=(s=>(s[s.Float=1]="Float",s[s.Int=3]="Int",s[s.Bool=4]="Bool",s[s.Trigger=9]="Trigger",s))(pf||{});const pt=O("debuganimatorcontroller"),Pu=O("debugrootmotion");class Hi{constructor(t){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=t,pt&&console.log(this)}static createFromClips(t,i={looping:!1,autoTransition:!0,transitionDuration:0}){const n=[];for(let r=0;r<t.length;r++){const l=t[r],c=[];if(i.autoTransition!==!1){const d=i.transitionDuration??0,u=d/l.duration;let p=r;(i.autoTransition===void 0||i.autoTransition===!0)&&(p=(r+1)%t.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:i?.looping??!1},transitions:c,behaviours:[]};n.push(h)}const o={name:"AnimatorController",guid:new zt(Date.now()).generateUUID(),parameters:[],layers:[{name:"Base Layer",stateMachine:{defaultState:0,states:n}}]};return new Hi(o)}play(t,i=-1,n=Number.NEGATIVE_INFINITY,o=0){if(i<0)i=0;else if(i>=this.model.layers.length){console.warn("invalid layer");return}const r=this.model.layers[i].stateMachine;for(const l of r.states)if(l.name===t||l.hash===t){pt&&console.log("transition to ",l),this.transitionTo(l,o,n);return}console.warn("Could not find "+t+" to play")}reset(){this.setStartTransition()}setBool(t,i){var n,o;const r=typeof t=="string"?"name":"hash";return(o=(n=this.model)==null?void 0:n.parameters)==null?void 0:o.filter(l=>l[r]===t).forEach(l=>l.value=i)}getBool(t){var i,n,o;const r=typeof t=="string"?"name":"hash";return((o=(n=(i=this.model)==null?void 0:i.parameters)==null?void 0:n.find(l=>l[r]===t))==null?void 0:o.value)??!1}setFloat(t,i){var n,o;const r=typeof t=="string"?"name":"hash",l=(o=(n=this.model)==null?void 0:n.parameters)==null?void 0:o.filter(c=>c[r]===t);return l.forEach(c=>c.value=i),l?.length>0}getFloat(t){var i,n,o;const r=typeof t=="string"?"name":"hash";return((o=(n=(i=this.model)==null?void 0:i.parameters)==null?void 0:n.find(l=>l[r]===t))==null?void 0:o.value)??0}setInteger(t,i){var n,o;const r=typeof t=="string"?"name":"hash";return(o=(n=this.model)==null?void 0:n.parameters)==null?void 0:o.filter(l=>l[r]===t).forEach(l=>l.value=i)}getInteger(t){var i,n,o;const r=typeof t=="string"?"name":"hash";return((o=(n=(i=this.model)==null?void 0:i.parameters)==null?void 0:n.find(l=>l[r]===t))==null?void 0:o.value)??0}setTrigger(t){var i,n;pt&&console.log("SET TRIGGER",t);const o=typeof t=="string"?"name":"hash";return(n=(i=this.model)==null?void 0:i.parameters)==null?void 0:n.filter(r=>r[o]===t).forEach(r=>r.value=!0)}resetTrigger(t){var i,n;const o=typeof t=="string"?"name":"hash";return(n=(i=this.model)==null?void 0:i.parameters)==null?void 0:n.filter(r=>r[o]===t).forEach(r=>r.value=!1)}getTrigger(t){var i,n,o;const r=typeof t=="string"?"name":"hash";return((o=(n=(i=this.model)==null?void 0:i.parameters)==null?void 0:n.find(l=>l[r]===t))==null?void 0:o.value)??!1}isInTransition(){return this._activeStates.length>1}setSpeed(t){this._speed=t}FindState(t){return this.findState(t)}findState(t){if(!t)return null;if(Array.isArray(this.model.layers)){for(const i of this.model.layers)for(const n of i.stateMachine.states)if(n.name===t||n.hash==t)return n}return null}getCurrentStateInfo(){if(!this._activeState)return null;const t=this._activeState.motion.action;if(!t)return null;const i=this._activeState.motion.clip.duration,n=i<=0?0:Math.abs(t.time/i);return new Bc(this._activeState,n,i,this._speed)}get currentAction(){return this._activeState&&this._activeState.motion.action||null}get context(){var t;return(t=this.animator)==null?void 0:t.context}get mixer(){return this._mixer}dispose(){var t;if(this._mixer.stopAllAction(),this.animator){this._mixer.uncacheRoot(this.animator.gameObject);for(const i of this._activeStates)i.motion.clip&&this.mixer.uncacheAction(i.motion.clip,this.animator.gameObject)}(t=this.context)==null||t.animations.unregisterAnimationMixer(this._mixer)}bind(t){var i,n;t?this.animator!==t&&(this._mixer&&(this._mixer.stopAllAction(),(i=this.context)==null||i.animations.unregisterAnimationMixer(this._mixer)),this.animator=t,this._mixer=new pm(this.animator.gameObject),(n=this.context)==null||n.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;pt&&console.warn("AnimatorController clone()",this.model);const t=Zl(this.model,(i,n,o)=>o==null?!0:!(o.type==="Object3D"||o.isObject3D===!0||Kv(o)||o.tracks!==void 0||o instanceof Hi));return console.assert(t!==this.model),new Hi(t)}update(t){var i,n;if(!this.animator)return;this.evaluateTransitions(),this.updateActiveStates(t);const o=this.animator.context.time.deltaTime;this.animator.applyRootMotion&&((i=this.rootMotionHandler)==null||i.onBeforeUpdate(t)),this._mixer.update(o),this.animator.applyRootMotion&&((n=this.rootMotionHandler)==null||n.onAfterUpdate(t))}get activeState(){return this._activeState}updateActiveStates(t){for(let i=0;i<this._activeStates.length;i++){const n=this._activeStates[i],o=n.motion;if(!o.action)this._activeStates.splice(i,1),i--;else{const r=o.action;r.weight=t,r.getEffectiveWeight()<=0&&!r.isRunning()&&(pt&&console.debug("REMOVE",n.name,r.getEffectiveWeight(),r.isRunning(),r.isScheduled()),this._activeStates.splice(i,1),i--)}}}setStartTransition(){var t;this.model.layers.length>1&&(pt||F())&&console.warn("Multiple layers are not supported yet "+((t=this.animator)==null?void 0:t.name));for(const i of this.model.layers){const n=i.stateMachine;n.defaultState===void 0&&(pt&&console.warn("AnimatorController default state is undefined, will assign state 0 as default",i),n.defaultState=0);const o=n.states[n.defaultState];this.transitionTo(o,0,this.normalizedStartOffset);break}}evaluateTransitions(){var t;let i=!1;if(!this._activeState){if(this.setStartTransition(),!this._activeState)return;i=!0}const n=this._activeState,o=n.motion.action;for(const l of n.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(o){const h=n.motion.clip.duration,d=h<=0?1:Math.abs(o.time/h);let u=l.exitTime;o.timeScale<0&&(u=1-u);let p=!1;if(l.hasExitTime?o.timeScale>0?p=d>=l.exitTime:o.timeScale<0&&(p=1-d>=l.exitTime):p=!0,p){for(const g of l.conditions){const y=this.model.parameters.find(f=>f.name===g.parameter);y?.type===pf.Trigger&&y.value&&(y.value=!1)}if(o.clampWhenFinished=!0,pt){const g=this.getState(l.destinationState,0);console.log(`Transition to ${l.destinationState} / ${g?.name}`,l,`
836
+ `,r.appendChild(l),jc&&console.log("Created fallback close button",r,t)}appendElement(t,i){return i.shadowRoot?i.shadowRoot.appendChild(t):i.appendChild(t)}}const O2=O("debugdecoders");let uf=null;function gw(){if(!uf){const s=wm(null);uf={dracoLoader:s.dracoLoader,ktx2Loader:s.ktx2Loader,meshoptDecoder:s.meshoptDecoder}}return uf}function fw(s){s!==void 0&&typeof s=="string"&&MC(s)}function yw(s){if(s!==void 0&&typeof s=="string"&&s!=="js"){const t=gw();O2&&console.log("Setting draco decoder type to",s),t.dracoLoader.setDecoderConfig({type:s})}}function vw(s){s!==void 0&&typeof s=="string"&&RC(s)}function Su(s,t){const i=gw();return t.renderer?i.ktx2Loader.detectSupport(t.renderer):console.warn("No renderer provided to detect ktx2 support - loading KTX2 textures will probably fail"),PC(s),s.dracoLoader||s.setDRACOLoader(i.dracoLoader),s.ktx2Loader||s.setKTX2Loader(i.ktx2Loader),s.meshoptDecoder||s.setMeshoptDecoder(i.meshoptDecoder),kC(s,{progressive:!0}),s}const $a=function(s){return m(s)},m=function(s){if(s===void 0&&(s=null),!Array.isArray(s))s=bw(s);else for(let t=0;t<s.length;t++){const i=s[t];s[t]=bw(i)}return function(t,i){typeof i!="string"&&(i=i.name),Object.getOwnPropertyDescriptor(t,"$serializedTypes")||(t.$serializedTypes={});const n=t.$serializedTypes=t.$serializedTypes||{};n[i]=s}};function bw(s){var t,i;switch((i=(t=s?.prototype)==null?void 0:t.constructor)==null?void 0:i.name){case"Number":case"String":case"Boolean":return null}return s}class P extends I{constructor(){super(...arguments),a(this,"guid")}static isDestroyed(t){return kr(t)}static setActive(t,i,n=!0){t&&(Mc(t,i),$d(t),i&&n&&i_(ee.Current,t))}static isActiveSelf(t){return Fa(t)}static isActiveInHierarchy(t){return A_(t)}static markAsInstancedRendered(t,i){I_(t,i)}static isUsingInstancing(t){return iu(t)}static foreachComponent(t,i,n=!0){return Mr(t,i,n)}static instantiateSynced(t,i){return t?Dg(t,i):null}static instantiate(t,i=null){return"isAssetReference"in t,Ua(t,i)}static destroySynced(t,i,n=!0){if(!t)return;const o=t;i=i??ee.Current,xc(o,i.connection,n)}static destroy(t,i=!0){return Ri(t,i)}static add(t,i,n){if(!(!t||!i)){if(t===i){console.warn("Can not add object to self",t);return}n||(n=ee.Current),i.add(t),Mc(t,!0),$d(t),n?P.foreachComponent(t,o=>{Rg(o,n),!o.__internalDidAwakeAndStart&&n.new_script_start.includes(o)===!1&&n.new_script_start.push(o)},!0):console.warn("Missing context")}}static remove(t){var i;t&&((i=t.parent)==null||i.remove(t),Mc(t,!1),$d(t),P.foreachComponent(t,n=>{pk(n)},!0))}static invokeOnChildren(t,i,...n){this.invoke(t,i,!0,n)}static invoke(t,i,n=!1,...o){t&&this.foreachComponent(t,r=>{const l=r[i];l&&typeof l=="function"&&l?.call(r,...o)},n)}static addNewComponent(t,i,n,o=!0){return Mi(t,i,n,{callAwake:o})}static addComponent(t,i,n,o){return Mi(t,i,n,o)}static moveComponent(t,i){return Mi(t,i)}static removeComponent(t){return $g(t.gameObject,t),t}static getOrAddComponent(t,i){return Cc(t,i)}static getComponent(t,i){return t===null?null:Pr(t,i)}static getComponents(t,i,n=null){return t===null?n??[]:Oc(t,i,n)}static findByGuid(t,i){return qg(t,i)}static findObjectOfType(t,i,n=!0){return Zd(t,i??ee.Current,n)}static findObjectsOfType(t,i){const n=[];return E_(t,n,i),n}static getComponentInChildren(t,i){return Pc(t,i)}static getComponentsInChildren(t,i,n=null){return Ba(t,i,n??void 0)}static getComponentInParent(t,i){return kc(t,i)}static getComponentsInParent(t,i,n=null){return Kd(t,i,n)}static getAllComponents(t){var i;const n=(i=t.userData)==null?void 0:i.components;return n?[...n]:[]}static*iterateComponents(t){var i;const n=(i=t?.userData)==null?void 0:i.components;if(n&&Array.isArray(n))for(let o=0;o<n.length;o++)yield n[o]}}const Cu=class{constructor(s){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(s)}get isComponent(){return!0}get context(){return this.__context??ee.Current}set context(s){this.__context=s}get scene(){return this.context.scene}get layer(){var s,t;return(t=(s=this.gameObject)==null?void 0:s.userData)==null?void 0:t.layer}get name(){var s,t;return(s=this.gameObject)!=null&&s.name?this.gameObject.name:(t=this.gameObject)==null?void 0:t.userData.name}set name(s){this.gameObject?(this.gameObject.userData||(this.gameObject.userData={}),this.gameObject.userData.name=s,this.__name=s):this.__name=s}get tag(){var s;return(s=this.gameObject)==null?void 0:s.userData.tag}set tag(s){this.gameObject&&(this.gameObject.userData||(this.gameObject.userData={}),this.gameObject.userData.tag=s)}get static(){var s;return(s=this.gameObject)==null?void 0:s.userData.static}set static(s){this.gameObject&&(this.gameObject.userData||(this.gameObject.userData={}),this.gameObject.userData.static=s)}get activeAndEnabled(){return!(this.destroyed||this.__isEnabled===!1||!this.__isActiveInHierarchy)}get __isActive(){return this.gameObject.visible}get __isActiveInHierarchy(){if(!this.gameObject)return!1;const s=this.gameObject[Sn];return s===void 0?!0:s}set __isActiveInHierarchy(s){this.gameObject&&(this.gameObject[Sn]=s)}awake(){}onEnable(){}onDisable(){}onDestroy(){this.__destroyed=!0}startCoroutine(s,t=Me.Update){return this.context.registerCoroutineUpdate(this,s,t)}stopCoroutine(s,t=Me.Update){this.context.unregisterCoroutineUpdate(s,t)}get destroyed(){return this.__destroyed}destroy(){this.__destroyed||this.__internalDestroy()}get __internalDidAwakeAndStart(){return this.__didAwake&&this.__didStart}__internalNewInstanceCreated(s){return this.__didAwake=!1,this.__didStart=!1,this.__didEnable=!1,this.__isEnabled=void 0,this.__destroyed=!1,this._internalInit(s),this}_internalInit(s){if(typeof s=="object")for(const t of Object.keys(s)){const i=s[t];typeof i!="function"&&(this[t]=i)}}__internalAwake(){this.__didAwake||(this.__didAwake=!0,this.awake())}__internalStart(){this.__didStart||(this.__didStart=!0,this.start&&this.start())}__internalEnable(s){return this.__destroyed?(F()&&console.warn("[Needle Engine Dev] Trying to enable destroyed component"),!1):this.__didAwake?this.__didEnable?(s!==!0&&(this.__isEnabled=!0),!1):(this.__didEnable=!0,this.__isEnabled=!0,this.onEnable(),!0):!1}__internalDisable(s){if(this.__didAwake){if(!this.__didEnable){s!==!0&&(this.__isEnabled=!1);return}this.__didEnable=!1,this.__isEnabled=!1,this.onDisable()}}__internalDestroy(){var s;this.__destroyed||(this.__destroyed=!0,this.__didAwake&&((s=this.onDestroy)==null||s.call(this),this.dispatchEvent(new CustomEvent("destroyed",{detail:this}))),M_(this))}get enabled(){return typeof this.__isEnabled=="boolean"?this.__isEnabled:!0}set enabled(s){if(this.__destroyed){F()&&console.warn(`[Needle Engine Dev] Trying to ${s?"enable":"disable"} destroyed component`);return}if(typeof s=="number"&&(s>=.5?s=!0:s=!1),!this.__didAwake){this.__isEnabled=s;return}s?this.__internalEnable():this.__internalDisable()}get worldPosition(){return te(this.gameObject)}set worldPosition(s){dt(this.gameObject,s)}setWorldPosition(s,t,i){yr(this.gameObject,s,t,i)}get worldQuaternion(){return Oe(this.gameObject)}set worldQuaternion(s){Gi(this.gameObject,s)}setWorldQuaternion(s,t,i,n){$m(this.gameObject,s,t,i,n)}get worldEuler(){return qm(this.gameObject)}set worldEuler(s){Gm(this.gameObject,s)}get worldRotation(){return this.gameObject.worldRotation}set worldRotation(s){this.setWorldRotation(s.x,s.y,s.z,!0)}setWorldRotation(s,t,i,n=!0){nc(this.gameObject,s,t,i,n)}get forward(){return Cu._forward.set(0,0,-1).applyQuaternion(this.worldQuaternion)}get right(){return Cu._right.set(1,0,0).applyQuaternion(this.worldQuaternion)}get up(){return Cu._up.set(0,1,0).applyQuaternion(this.worldQuaternion)}addEventListener(s,t){this._eventListeners[s]=this._eventListeners[s]||[],this._eventListeners[s].push(t)}removeEventListener(s,t){if(!this._eventListeners[s])return;const i=this._eventListeners[s].indexOf(t);i>=0&&this._eventListeners[s].splice(i,1)}dispatchEvent(s){if(!s||!this._eventListeners[s.type])return!1;const t=this._eventListeners[s.type];for(let i=0;i<t.length;i++)t[i](s);return!1}};let A=Cu;a(A,"_forward",new x),a(A,"_right",new x),a(A,"_up",new x);const P2=Object.freeze(Object.defineProperty({__proto__:null,Behaviour:A,Component:A,GameObject:P},Symbol.toStringTag,{value:"Module"}));var k2=Object.defineProperty,M2=Object.getOwnPropertyDescriptor,_w=(s,t,i,n)=>{for(var o=n>1?void 0:n?M2(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&k2(t,i,o),o};class Lc extends A{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 t=te(this.from).clone(),i=te(this.to).clone(),n=t.distanceTo(i);this._centerPos.copy(t),this._centerPos.add(i),this._centerPos.multiplyScalar(.5),dt(this.gameObject,this.centered?this._centerPos:t),this.gameObject.lookAt(te(this.to).clone()),this.gameObject.scale.set(this.width,this.width,n)}}_w([m(P)],Lc.prototype,"from",2),_w([m(P)],Lc.prototype,"to",2);var R2=Object.defineProperty,T2=Object.getOwnPropertyDescriptor,Lr=(s,t,i,n)=>{for(var o=n>1?void 0:n?T2(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&R2(t,i,o),o};const wo=O("debuganimation");let ww=class{constructor(){a(this,"x"),a(this,"y")}};class Wt extends A{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(t){this.animations||(this.animations=[]),this.animations.push(t)}get time(){if(this.actions){for(const t of this.actions)if(t.isRunning())return t.time}return 0}set time(t){if(this.actions)for(const i of this.actions)i.time=t}get clip(){var t;return(t=this.animations)!=null&&t.length?this.animations[0]:null}set clip(t){if(!this.__didAwake){wo&&console.warn("Assign clip during serialization",t),this._tempAnimationClipBeforeGameObjectExisted=t;return}t&&(this.gameObject.animations||(this.gameObject.animations=[]),!this.animations.includes(t)&&(this.animations.length>0?this.animations.splice(0,0,t):this.animations.push(t)))}set clips(t){this.animations=t}set animations(t){t==null||!Array.isArray(t)||(this.gameObject?this.gameObject.animations=t:this._tempAnimationsArray=t)}get animations(){return this.gameObject.animations||this._tempAnimationsArray||[]}get actions(){return this._actions}set actions(t){this._actions=t}awake(){this.mixer=void 0,wo&&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 t;if(this.playAutomatically&&((t=this.animations)==null?void 0:t.length)>0){const i=Math.floor(Math.random()*this.animations.length),n=this.animations[i];this.play(i,{exclusive:!0,fadeDuration:0,startTime:this.randomStartTime?Math.random()*n.duration:0,loop:this.loop,clampWhenFinished:this.clampWhenFinished})}}update(){this.mixer&&(this.mixer.update(this.context.time.deltaTime),this._handles.forEach(t=>t.update()))}onDisable(){this.mixer&&this.mixer.stopAllAction()}onDestroy(){this.context.animations.unregisterAnimationMixer(this.mixer)}getAction(t){var i;return((i=this.actions)==null?void 0:i.find(n=>n.getClip().name===t))||null}get isPlaying(){if(this.actions){for(let t=0;t<this.actions.length;t++)if(this.actions[t].isRunning())return!0}return!1}stopAll(t){if(this.actions)for(const i of this.actions)t!=null&&t.fadeDuration?i.fadeOut(t.fadeDuration):i.stop()}stop(t,i){if(t===void 0){this.stopAll();return}else if(typeof t=="number"){if(t>=this.animations.length){wo&&console.log("No animation at index",t);return}t=this.animations[t]}else typeof t=="string"&&(t=this.animations.find(o=>o.name===t));if(!t){console.error("Could not find clip",t);return}const n=this.actions.find(o=>o.getClip()===t);if(!n){console.error("Could not find action",t);return}i!=null&&i.fadeDuration?n.fadeOut(i.fadeDuration):n.stop()}pause(t,i=!1){if(t===void 0){for(const o of this.actions)o.paused=!i;return}else if(typeof t=="number"){if(t>=this.animations.length){wo&&console.log("No animation at index",t);return}t=this.animations[t]}else typeof t=="string"&&(t=this.animations.find(o=>o.name===t));if(!t){console.error("Could not find clip",t);return}const n=this.actions.find(o=>o.getClip()===t);if(!n){console.error("Could not find action",t);return}n.paused=!i}resume(){for(const t of this.actions)t.paused=!1}play(t=0,i){if(wo&&console.log("PLAY",t),this.ensureMixer(),!this.mixer){wo&&console.warn("Missing mixer",this);return}t===void 0&&(t=0);let n=t;if(typeof t=="number"){if(t>=this.animations.length){wo&&console.log("No animation at index",t);return}n=this.animations[t]}else typeof t=="string"&&(n=this.animations.find(r=>r.name===t));if(!n){console.error("Could not find clip",t);return}i||(i={});for(const r of this.actions)if(r.getClip()===n)return this.internalOnPlay(r,i);if(!n.tracks){console.warn("Clip is no AnimationClip",n);return}const o=this.mixer.clipAction(n);return this.actions.push(o),this.internalOnPlay(o,i)}internalOnPlay(t,i){var n=this.actions.find(r=>r===t);if(n===t&&n.isRunning()&&n.time<n.getClip().duration){const r=this.tryFindHandle(t);if(n.paused&&(n.paused=!1),r)return r.waitForFinish()}if(i.loop===void 0&&(i.loop=this.loop),i.clampWhenFinished===void 0&&(i.clampWhenFinished=this.clampWhenFinished),i.minMaxOffsetNormalized===void 0&&this.randomStartTime&&(i.minMaxOffsetNormalized=this.minMaxOffsetNormalized),i.minMaxSpeed===void 0&&(i.minMaxSpeed=this.minMaxSpeed),i?.exclusive??!0)for(const r of this.actions)r!=n&&(i.fadeDuration?r.fadeOut(i.fadeDuration):r.stop());if(i!=null&&i.fadeDuration&&t.fadeIn(i.fadeDuration),t.enabled=!0,i?.startTime!=null)t.time=i.startTime;else if(i!=null&&i.minMaxOffsetNormalized&&i.minMaxOffsetNormalized.x!=0&&i.minMaxOffsetNormalized.y!=0){const r=t.getClip();t.time=W.lerp(i.minMaxOffsetNormalized.x,i.minMaxOffsetNormalized.y,Math.random())*r.duration}else t.time>=t.getClip().duration&&(t.time=0);i!=null&&i.minMaxSpeed?t.timeScale=W.lerp(i.minMaxSpeed.x,i.minMaxSpeed.y,Math.random()):t.timeScale=i?.speed??1,i?.loop!=null?t.loop=i.loop?MS:um:t.loop=um,i!=null&&i.clampWhenFinished&&(t.clampWhenFinished=!0),t.paused=!1,t.play(),wo&&console.log("PLAY",t.getClip().name,t);const o=new E2(t,this.mixer,i,r=>{this._handles.splice(this._handles.indexOf(o),1)});return this._handles.push(o),o.waitForFinish()}tryFindHandle(t){for(const i of this._handles)if(i.action===t)return i}ensureMixer(){if(!this.mixer){const t="animationMixer";this.gameObject[t]&&(this.mixer=this.gameObject[t]),(!this.mixer||!this.mixer.clipAction)&&(this.mixer=new pm(this.gameObject),this.gameObject[t]=this.mixer)}this.context.animations.registerAnimationMixer(this.mixer)}}Lr([m()],Wt.prototype,"playAutomatically",2),Lr([m()],Wt.prototype,"randomStartTime",2),Lr([m(ww)],Wt.prototype,"minMaxSpeed",2),Lr([m(ww)],Wt.prototype,"minMaxOffsetNormalized",2),Lr([m()],Wt.prototype,"loop",2),Lr([m()],Wt.prototype,"clampWhenFinished",2),Lr([m(ao)],Wt.prototype,"clips",1);class E2{constructor(t,i,n,o){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=t,this.mixer=i,this._resolvedOrRejectedCallback=o,this._options=n}waitForFinish(){return this.promise?this.promise:(this.promise=new Promise(t=>{this._resolveCallback=t}),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 t,i;this.dispose(),(t=this._resolvedOrRejectedCallback)==null||t.call(this,this),(i=this._resolveCallback)==null||i.call(this,this.action)}dispose(){this.mixer.removeEventListener("finished",this.onFinished)}}var A2=Object.defineProperty,I2=Object.getOwnPropertyDescriptor,xo=(s,t,i,n)=>{for(var o=n>1?void 0:n?I2(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&A2(t,i,o),o};class Qt{constructor(t=0,i=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=t,this.value=i}}xo([m()],Qt.prototype,"time",2),xo([m()],Qt.prototype,"value",2),xo([m()],Qt.prototype,"inTangent",2),xo([m()],Qt.prototype,"inWeight",2),xo([m()],Qt.prototype,"outTangent",2),xo([m()],Qt.prototype,"outWeight",2),xo([m()],Qt.prototype,"weightedMode",2);const Dc=class{constructor(){a(this,"keys",[])}static linearFromTo(s,t,i){const n=new Dc,o=new Qt;o.time=0,o.value=s;const r=new Qt;return r.time=i,r.value=t,n.keys.push(o,r),n}static constant(s){const t=new Dc,i=new Qt;return i.time=0,i.value=s,t.keys.push(i),t}clone(){var s;const t=new Dc;return t.keys=((s=this.keys)==null?void 0:s.map(i=>{const n=new Qt;return n.time=i.time,n.value=i.value,n.inTangent=i.inTangent,n.inWeight=i.inWeight,n.outTangent=i.outTangent,n.outWeight=i.outWeight,n.weightedMode=i.weightedMode,n}))||[],t}get duration(){return!this.keys||this.keys.length==0?0:this.keys[this.keys.length-1].time}evaluate(s){if(!this.keys||this.keys.length==0)return 0;if(this.keys.length===1)return this.keys[0].value;if(this.keys[0].time>=s)return this.keys[0].value;for(let t=0;t<this.keys.length;t++){const i=this.keys[t];if(i.time<=s)if(t+1<this.keys.length){const n=this.keys[t+1];if(n.time<s)continue;return!isFinite(i.outTangent)||!isFinite(n.inTangent)?i.value:Dc.interpolateValue(s,i,n)}else return i.value}return this.keys[this.keys.length-1].value}static interpolateValue(s,t,i){const n=t.time,o=t.value,r=t.outTangent,l=i.time,c=i.value,h=i.inTangent,d=l-n,u=d*d,p=u*d,g=((r+h)*d-2*(c-o))/p,y=(3*(c-o)-(h+2*r)*d)/u,f=r,v=o,b=s-n,w=b*b,_=w*b;return g*_+y*w+f*b+v}};let Dr=Dc;xo([m(Qt)],Dr.prototype,"keys",2);const Ou=Symbol("objectIsAnimatedData");function xw(s,t,i){if(!s)return;if(s[Ou]===void 0){if(!i)return;s[Ou]=new Set}const n=s[Ou];i?n.add(t):n.has(t)&&n.delete(t)}function j2(s){if(!s)return!1;const t=s[Ou];return t!==void 0&&t.size>0}class L2{constructor(){a(this,"_context")}get context(){return this._context??ee.Current}get isStateMachineBehaviour(){return!0}}class Bc{constructor(t,i,n,o){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=t.name,this.nameHash=t.hash,this.normalizedTime=i,this.length=n,this.speed=o,this.action=t.motion.action||null,this.hasTransitions=((r=t.transitions)==null?void 0:r.length)>0||!1}}function Sw(s,t){return{name:"Empty",isLooping:!1,guid:t?.generateUUID()??vn.generateUUID(),index:-1,clip:new ao(s,0,[])}}var So=(s=>(s[s.If=1]="If",s[s.IfNot=2]="IfNot",s[s.Greater=3]="Greater",s[s.Less=4]="Less",s[s.Equals=6]="Equals",s[s.NotEqual=7]="NotEqual",s))(So||{}),pf=(s=>(s[s.Float=1]="Float",s[s.Int=3]="Int",s[s.Bool=4]="Bool",s[s.Trigger=9]="Trigger",s))(pf||{});const pt=O("debuganimatorcontroller"),Pu=O("debugrootmotion");class Hi{constructor(t){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=t,pt&&console.log(this)}static createFromClips(t,i={looping:!1,autoTransition:!0,transitionDuration:0}){const n=[];for(let r=0;r<t.length;r++){const l=t[r],c=[];if(i.autoTransition!==!1){const d=i.transitionDuration??0,u=d/l.duration;let p=r;(i.autoTransition===void 0||i.autoTransition===!0)&&(p=(r+1)%t.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:i?.looping??!1},transitions:c,behaviours:[]};n.push(h)}const o={name:"AnimatorController",guid:new zt(Date.now()).generateUUID(),parameters:[],layers:[{name:"Base Layer",stateMachine:{defaultState:0,states:n}}]};return new Hi(o)}play(t,i=-1,n=Number.NEGATIVE_INFINITY,o=0){if(i<0)i=0;else if(i>=this.model.layers.length){console.warn("invalid layer");return}const r=this.model.layers[i].stateMachine;for(const l of r.states)if(l.name===t||l.hash===t){pt&&console.log("transition to ",l),this.transitionTo(l,o,n);return}console.warn("Could not find "+t+" to play")}reset(){this.setStartTransition()}setBool(t,i){var n,o;const r=typeof t=="string"?"name":"hash";return(o=(n=this.model)==null?void 0:n.parameters)==null?void 0:o.filter(l=>l[r]===t).forEach(l=>l.value=i)}getBool(t){var i,n,o;const r=typeof t=="string"?"name":"hash";return((o=(n=(i=this.model)==null?void 0:i.parameters)==null?void 0:n.find(l=>l[r]===t))==null?void 0:o.value)??!1}setFloat(t,i){var n,o;const r=typeof t=="string"?"name":"hash",l=(o=(n=this.model)==null?void 0:n.parameters)==null?void 0:o.filter(c=>c[r]===t);return l.forEach(c=>c.value=i),l?.length>0}getFloat(t){var i,n,o;const r=typeof t=="string"?"name":"hash";return((o=(n=(i=this.model)==null?void 0:i.parameters)==null?void 0:n.find(l=>l[r]===t))==null?void 0:o.value)??0}setInteger(t,i){var n,o;const r=typeof t=="string"?"name":"hash";return(o=(n=this.model)==null?void 0:n.parameters)==null?void 0:o.filter(l=>l[r]===t).forEach(l=>l.value=i)}getInteger(t){var i,n,o;const r=typeof t=="string"?"name":"hash";return((o=(n=(i=this.model)==null?void 0:i.parameters)==null?void 0:n.find(l=>l[r]===t))==null?void 0:o.value)??0}setTrigger(t){var i,n;pt&&console.log("SET TRIGGER",t);const o=typeof t=="string"?"name":"hash";return(n=(i=this.model)==null?void 0:i.parameters)==null?void 0:n.filter(r=>r[o]===t).forEach(r=>r.value=!0)}resetTrigger(t){var i,n;const o=typeof t=="string"?"name":"hash";return(n=(i=this.model)==null?void 0:i.parameters)==null?void 0:n.filter(r=>r[o]===t).forEach(r=>r.value=!1)}getTrigger(t){var i,n,o;const r=typeof t=="string"?"name":"hash";return((o=(n=(i=this.model)==null?void 0:i.parameters)==null?void 0:n.find(l=>l[r]===t))==null?void 0:o.value)??!1}isInTransition(){return this._activeStates.length>1}setSpeed(t){this._speed=t}FindState(t){return this.findState(t)}findState(t){if(!t)return null;if(Array.isArray(this.model.layers)){for(const i of this.model.layers)for(const n of i.stateMachine.states)if(n.name===t||n.hash==t)return n}return null}getCurrentStateInfo(){if(!this._activeState)return null;const t=this._activeState.motion.action;if(!t)return null;const i=this._activeState.motion.clip.duration,n=i<=0?0:Math.abs(t.time/i);return new Bc(this._activeState,n,i,this._speed)}get currentAction(){return this._activeState&&this._activeState.motion.action||null}get context(){var t;return(t=this.animator)==null?void 0:t.context}get mixer(){return this._mixer}dispose(){var t;if(this._mixer.stopAllAction(),this.animator){this._mixer.uncacheRoot(this.animator.gameObject);for(const i of this._activeStates)i.motion.clip&&this.mixer.uncacheAction(i.motion.clip,this.animator.gameObject)}(t=this.context)==null||t.animations.unregisterAnimationMixer(this._mixer)}bind(t){var i,n;t?this.animator!==t&&(this._mixer&&(this._mixer.stopAllAction(),(i=this.context)==null||i.animations.unregisterAnimationMixer(this._mixer)),this.animator=t,this._mixer=new pm(this.animator.gameObject),(n=this.context)==null||n.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;pt&&console.warn("AnimatorController clone()",this.model);const t=Zl(this.model,(i,n,o)=>o==null?!0:!(o.type==="Object3D"||o.isObject3D===!0||Kv(o)||o.tracks!==void 0||o instanceof Hi));return console.assert(t!==this.model),new Hi(t)}update(t){var i,n;if(!this.animator)return;this.evaluateTransitions(),this.updateActiveStates(t);const o=this.animator.context.time.deltaTime;this.animator.applyRootMotion&&((i=this.rootMotionHandler)==null||i.onBeforeUpdate(t)),this._mixer.update(o),this.animator.applyRootMotion&&((n=this.rootMotionHandler)==null||n.onAfterUpdate(t))}get activeState(){return this._activeState}updateActiveStates(t){for(let i=0;i<this._activeStates.length;i++){const n=this._activeStates[i],o=n.motion;if(!o.action)this._activeStates.splice(i,1),i--;else{const r=o.action;r.weight=t,r.getEffectiveWeight()<=0&&!r.isRunning()&&(pt&&console.debug("REMOVE",n.name,r.getEffectiveWeight(),r.isRunning(),r.isScheduled()),this._activeStates.splice(i,1),i--)}}}setStartTransition(){var t;this.model.layers.length>1&&(pt||F())&&console.warn("Multiple layers are not supported yet "+((t=this.animator)==null?void 0:t.name));for(const i of this.model.layers){const n=i.stateMachine;n.defaultState===void 0&&(pt&&console.warn("AnimatorController default state is undefined, will assign state 0 as default",i),n.defaultState=0);const o=n.states[n.defaultState];this.transitionTo(o,0,this.normalizedStartOffset);break}}evaluateTransitions(){var t;let i=!1;if(!this._activeState){if(this.setStartTransition(),!this._activeState)return;i=!0}const n=this._activeState,o=n.motion.action;for(const l of n.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(o){const h=n.motion.clip.duration,d=h<=0?1:Math.abs(o.time/h);let u=l.exitTime;o.timeScale<0&&(u=1-u);let p=!1;if(l.hasExitTime?o.timeScale>0?p=d>=l.exitTime:o.timeScale<0&&(p=1-d>=l.exitTime):p=!0,p){for(const g of l.conditions){const y=this.model.parameters.find(f=>f.name===g.parameter);y?.type===pf.Trigger&&y.value&&(y.value=!1)}if(o.clampWhenFinished=!0,pt){const g=this.getState(l.destinationState,0);console.log(`Transition to ${l.destinationState} / ${g?.name}`,l,`
837
837
  Timescale: `+o.timeScale,`
838
838
  Normalized time: `+d.toFixed(3),`
839
- Exit Time: `+u,l.hasExitTime)}this.transitionTo(l.destinationState,l.duration,l.offset);return}}else{this.transitionTo(l.destinationState,l.duration,l.offset);return}}o&&this.setTimescale(o,n);let r=!1;if(n.motion.isLooping&&o&&(o.time>=o.getClip().duration?(r=!0,o.reset(),o.time=0,o.play()):o.time<=0&&o.timeScale<0&&(r=!0,o.reset(),o.time=o.getClip().duration,o.play())),!r&&n&&!i&&o&&this.animator&&n.behaviours){const l=o?.getClip().duration,c=o.time/l,h=new Bc(this._activeState,c,l,this._speed);for(const d of n.behaviours)d.instance&&((t=d.instance.onStateUpdate)==null||t.call(d.instance,this.animator,h,0))}}setTimescale(t,i){let n=i.speed??1;i.speedParameter&&(n*=this.getFloat(i.speedParameter)),n!==void 0&&(t.timeScale=n*this._speed)}getState(t,i){return typeof t=="number"&&(t==-1&&(t=this.model.layers[i].stateMachine.defaultState,t===void 0&&(pt&&console.warn("AnimatorController default state is undefined: ",this.model,"Layer: "+i),t=0)),t=this.model.layers[i].stateMachine.states[t]),t}releaseHeldActions(t){for(const i of this._heldActions)i.fadeOut(t);this._heldActions.length=0}transitionTo(t,i,n){var o,r,l,c,h,d,u,p;if(!this.animator)return;const g=0;if(t=this.getState(t,g),!(t!=null&&t.motion)||!t.motion.clip||!(t.motion.clip instanceof ao))return;const y=this._activeState===t;if(y){const _=t.motion;if(!_.action_loopback&&_.clip){const C=this.rootMotionHandler?this.animator.gameObject.matrix.clone():null;this._mixer.uncacheAction(_.clip,this.animator.gameObject),C&&C.decompose(this.animator.gameObject.position,this.animator.gameObject.quaternion,this.animator.gameObject.scale),_.action_loopback=this.createAction(_.clip)}}if((o=this._activeState)!=null&&o.behaviours&&this._activeState.motion.action){const _=(r=this._activeState)==null?void 0:r.motion.clip.duration,C=this._activeState.motion.action.time/_,R=new Bc(this._activeState,C,_,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,R,g)}const f=(h=this._activeState)==null?void 0:h.motion.action;y&&(t.motion.action=t.motion.action_loopback,t.motion.action_loopback=f);const v=this._activeState;this._activeState=t;const b=(d=t.motion)==null?void 0:d.action,w=t.motion.clip;if(w?.duration<=0&&w.tracks.length<=0?f&&this._heldActions.push(f):f&&(f.fadeOut(i),this.releaseHeldActions(i)),b){if(n=Math.max(0,Math.min(1,n)),t.cycleOffsetParameter){let C=this.getFloat(t.cycleOffsetParameter);typeof C=="number"?(C<0&&(C+=1),n+=C,n%=1):pt&&console.warn("AnimatorController cycle offset parameter is not a number",t.cycleOffsetParameter)}else typeof t.cycleOffset=="number"&&(n+=t.cycleOffset,n%=1);b.isRunning()&&b.stop(),b.reset(),b.enabled=!0,this.setTimescale(b,t);const _=t.motion.clip.duration;if(b.time=y?0:n*_,b.timeScale<0&&(b.time=_-b.time),b.clampWhenFinished=!0,b.setLoop(um,0),i>0?b.fadeIn(i):b.weight=1,b.play(),this.rootMotionHandler&&this.rootMotionHandler.onStart(b),this._activeStates.includes(t)||this._activeStates.push(t),this._activeState.behaviours){const C=new Bc(t,n,_,this._speed);for(const R of this._activeState.behaviours)(p=(u=R.instance)==null?void 0:u.onStateEnter)==null||p.call(R.instance,this.animator,C,g)}}else pt&&(t.__warned_no_motion||(t.__warned_no_motion=!0,console.warn("No action",t.motion,this)));pt&&console.log("TRANSITION FROM "+v?.name+" TO "+t.name,i,f,b,b?.getEffectiveTimeScale(),b?.getEffectiveWeight(),b?.isRunning(),b?.isScheduled(),b?.paused)}createAction(t){var i,n;if(this._mixer.existingAction(t)&&this._mixer.uncacheAction(t,(i=this.animator)==null?void 0:i.gameObject),(n=this.animator)!=null&&n.applyRootMotion){this.rootMotionHandler||(this.rootMotionHandler=new Dk(this));const o=this.animator.gameObject;return this.rootMotionHandler.createClip(this._mixer,o,t)}else return this._mixer.clipAction(t)}evaluateCondition(t){const i=this.model.parameters.find(n=>n.name===t.parameter);if(!i)return!1;switch(t.mode){case So.If:return i.value===!0;case So.IfNot:return i.value===!1;case So.Greater:return i.value>t.threshold;case So.Less:return i.value<t.threshold;case So.Equals:return i.value===t.threshold;case So.NotEqual:return i.value!==t.threshold}return!1}createActions(t){var i,n,o,r;pt&&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||(pt&&console.warn("No motion",d),d.motion=Sw(d.name)),this.animator&&d.motion.clips){const u=(i=d.motion.clips)==null?void 0:i.find(p=>{var g,y;return p.node.name===((y=(g=this.animator)==null?void 0:g.gameObject)==null?void 0:y.name)});u?d.motion.clip=u.clip:(pt||F())&&console.warn('Could not find clip for animator "'+((o=(n=this.animator)==null?void 0:n.gameObject)==null?void 0:o.name)+'"',d.motion.clips.map(p=>p.node.name))}if(!d.motion.clip){pt&&console.warn("No clip assigned to state",d);const u=new ao(void 0,void 0,[]);d.motion.clip=u}if((r=d.motion)!=null&&r.clip){const u=d.motion.clip;if(u instanceof ao){const p=this.createAction(u);d.motion.action=p}else(pt||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=S.get(u.typeName);if(p){const g=new p;g.isStateMachineBehaviour&&(g._context=this.context??void 0,Da(g,u.properties),u.instance=g),pt&&console.log("Created animator controller behaviour",d.name,u.typeName,u.properties,g)}else(pt||F())&&console.warn("Could not find AnimatorBehaviour type: "+u.typeName)}}}}*enumerateActions(){if(this.model.layers)for(const t of this.model.layers){const i=t.stateMachine;for(let n=0;n<i.states.length;n++){const o=i.states[n];o!=null&&o.motion&&(o.motion.action&&(yield o.motion.action),o.motion.action_loopback&&(yield o.motion.action_loopback))}}}}class Cw{constructor(t,i){a(this,"track"),a(this,"createdInterpolant"),a(this,"originalEvaluate"),a(this,"customEvaluate"),this.track=t;const n=t,o=n.createInterpolant.bind(t);n.createInterpolant=()=>(n.createInterpolant=o,this.createdInterpolant=o(),this.originalEvaluate=this.createdInterpolant.evaluate.bind(this.createdInterpolant),this.customEvaluate=r=>{if(!this.originalEvaluate)return;const l=this.originalEvaluate(r);return i(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 bt=class{constructor(s,t,i,n,o){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 V),a(this,"_prevTime",0),this.context=s,this.root=t,this.clip=i,bt.firstKeyframeRotation[this.cacheId]||(bt.firstKeyframeRotation[this.cacheId]=new V),o){const r=o.values;bt.firstKeyframeRotation[this.cacheId].set(r[0],r[1],r[2],r[3])}bt.spaceRotation[this.cacheId]||(bt.spaceRotation[this.cacheId]=new V),bt.effectiveSpaceRotation[this.cacheId]||(bt.effectiveSpaceRotation[this.cacheId]=new V),bt.clipOffsetRotation[this.cacheId]=new V,o&&bt.clipOffsetRotation[this.cacheId].set(o.values[0],o.values[1],o.values[2],o.values[3]).invert(),this.handlePosition(i,n),this.handleRotation(i,o)}set action(s){this._action=s}get action(){return this._action}get cacheId(){return this.root.uuid}onStart(s){if(s.getClip()!==this.clip)return;bt.lastObjRotation[this.cacheId]||(bt.lastObjRotation[this.cacheId]=this.root.quaternion.clone());const t=bt.lastObjRotation[this.cacheId];if(bt.spaceRotation[this.cacheId].copy(t),Pu){const i=new Ut().setFromQuaternion(t);console.log("START",this.clip.name,W.toDegrees(i.y),this.root.position.z)}}getClipRotationOffset(){return bt.clipOffsetRotation[this.cacheId]}handlePosition(s,t){if(t){const i=this.root;Pu&&i.add(new wi),bt.lastObjPosition[this.cacheId]||(bt.lastObjPosition[this.cacheId]=this.root.position.clone());const n=new x,o=new x;this.positionWrapper=new Cw(t,(r,l)=>{const c=this.action.getEffectiveWeight();return Pu&&i.position.length()>8&&i.position.set(0,i.position.y,0),r>this._prevTime&&(n.set(l[0],l[1],l[2]),n.sub(o),n.multiplyScalar(c),n.applyQuaternion(this.getClipRotationOffset()),n.applyQuaternion(i.quaternion),this.positionChange.copy(n)),o.fromArray(l),this._prevTime=r,l[0]=0,l[1]=0,l[2]=0,l})}}handleRotation(s,t){if(t){if(Pu){const r=t.values,l=new Ut().setFromQuaternion(new V(r[0],r[1],r[2],r[3]));console.log(s.name,t.name,"FIRST ROTATION IN TRACK",W.toDegrees(l.y));const c=t.values.length-4,h=new V().set(r[c],r[c+1],r[c+2],r[c+3]),d=new Ut().setFromQuaternion(h);console.log(s.name,t.name,"LAST ROTATION IN TRACK",W.toDegrees(d.y))}let i=0;const n=new V,o=new V;this.rotationWrapper=new Cw(t,(r,l)=>(r>i&&(o.set(l[0],l[1],l[2],l[3]),n.invert(),o.multiply(n),this.rotationChange.copy(o)),n.fromArray(l),i=r,l[0]=0,l[1]=0,l[2]=0,l[3]=1,l))}}onBeforeUpdate(s){this.positionChange.set(0,0,0),this.rotationChange.set(0,0,0,1)}onAfterUpdate(s){return!this.action||(s*=this.action.getEffectiveWeight(),s<=0)?!1:(this.positionChange.multiplyScalar(s),this.rotationChange.slerp(bt.identityQuaternion,1-s),!0)}};let Co=bt;a(Co,"lastObjPosition",{}),a(Co,"lastObjRotation",{}),a(Co,"firstKeyframeRotation",{}),a(Co,"spaceRotation",{}),a(Co,"effectiveSpaceRotation",{}),a(Co,"clipOffsetRotation",{}),a(Co,"identityQuaternion",new V);class Dk{constructor(t){a(this,"controller"),a(this,"handler",[]),a(this,"root"),a(this,"basePosition",new x),a(this,"baseQuaternion",new V),a(this,"baseRotation",new Ut),a(this,"summedPosition",new x),a(this,"summedRotation",new V),this.controller=t}createClip(t,i,n){this.root=i,i&&"name"in i&&i.name;const o=this.findRootTrack(n,".position"),r=this.findRootTrack(n,".quaternion"),l=new Co(this.controller.context,i,n,o,r);this.handler.push(l);const c=t.clipAction(n);return l.action=c,c}onStart(t){for(const i of this.handler)i.onStart(t)}onBeforeUpdate(t){this.basePosition.copy(this.root.position),this.baseQuaternion.copy(this.root.quaternion);for(const i of this.handler)i.onBeforeUpdate(t)}onAfterUpdate(t){if(!(t<=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 i of this.handler)i.onAfterUpdate(t)&&(this.summedPosition.add(i.positionChange),this.summedRotation.multiply(i.rotationChange));this.root.position.add(this.summedPosition),this.root.quaternion.multiply(this.summedRotation)}}findRootTrack(t,i){const n=t.tracks;if(!n)return null;for(const o of n)if(o.name.endsWith(i))return o;return null}}class Bk extends Zi{onSerialize(t,i){}onDeserialize(t,i){if(i.type===Hi&&t?.__type==="AnimatorController")return new Hi(t)}}new Bk(Hi);var Fk=Object.defineProperty,zk=Object.getOwnPropertyDescriptor,ku=(s,t,i,n)=>{for(var o=n>1?void 0:n?zk(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&Fk(t,i,o),o};const es=O("debuganimator");class kt extends A{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(t){var i;this._animatorController&&this._animatorController.model===t||(t?t instanceof Hi?(t.animator&&t.animator!==this&&(console.warn("AnimatorController can not be bound to multiple animators",(i=t.model)==null?void 0:i.name),t.model||console.error("AnimatorController has no model"),t=new Hi(t.model)),this._animatorController=t,this._animatorController.bind(this)):(es&&console.log("Assign animator controller",t,this),this._animatorController=new Hi(t),this.__didAwake&&this._animatorController.bind(this)):this._animatorController=null)}get runtimeAnimatorController(){return this._animatorController}getCurrentStateInfo(){var t;return(t=this.runtimeAnimatorController)==null?void 0:t.getCurrentStateInfo()}get currentAction(){var t;return((t=this.runtimeAnimatorController)==null?void 0:t.currentAction)||null}get parametersAreDirty(){return this._parametersAreDirty}get isDirty(){return this._isDirty}Play(t,i=-1,n=Number.NEGATIVE_INFINITY,o=0){this.play(t,i,n,o)}play(t,i=-1,n=Number.NEGATIVE_INFINITY,o=0){var r;(r=this.runtimeAnimatorController)==null||r.play(t,i,n,o),this._isDirty=!0}Reset(){this.reset()}reset(){var t;(t=this._animatorController)==null||t.reset(),this._isDirty=!0}SetBool(t,i){this.setBool(t,i)}setBool(t,i){var n,o;es&&console.log("setBool",t,i),((n=this.runtimeAnimatorController)==null?void 0:n.getBool(t))!==i&&(this._parametersAreDirty=!0),(o=this.runtimeAnimatorController)==null||o.setBool(t,i)}GetBool(t){return this.getBool(t)}getBool(t){var i;const n=((i=this.runtimeAnimatorController)==null?void 0:i.getBool(t))??!1;return es&&console.log("getBool",t,n),n}toggleBool(t){this.setBool(t,!this.getBool(t))}SetFloat(t,i){this.setFloat(t,i)}setFloat(t,i){var n,o;((n=this.runtimeAnimatorController)==null?void 0:n.getFloat(t))!==i&&(this._parametersAreDirty=!0),es&&console.log("setFloat",t,i),(o=this.runtimeAnimatorController)==null||o.setFloat(t,i)}GetFloat(t){return this.getFloat(t)}getFloat(t){var i;const n=((i=this.runtimeAnimatorController)==null?void 0:i.getFloat(t))??-1;return es&&console.log("getFloat",t,n),n}SetInteger(t,i){this.setInteger(t,i)}setInteger(t,i){var n,o;((n=this.runtimeAnimatorController)==null?void 0:n.getInteger(t))!==i&&(this._parametersAreDirty=!0),es&&console.log("setInteger",t,i),(o=this.runtimeAnimatorController)==null||o.setInteger(t,i)}GetInteger(t){return this.getInteger(t)}getInteger(t){var i;const n=((i=this.runtimeAnimatorController)==null?void 0:i.getInteger(t))??-1;return es&&console.log("getInteger",t,n),n}SetTrigger(t){this.setTrigger(t)}setTrigger(t){var i;this._parametersAreDirty=!0,es&&console.log("setTrigger",t),(i=this.runtimeAnimatorController)==null||i.setTrigger(t)}ResetTrigger(t){this.resetTrigger(t)}resetTrigger(t){var i;this._parametersAreDirty=!0,es&&console.log("resetTrigger",t),(i=this.runtimeAnimatorController)==null||i.resetTrigger(t)}GetTrigger(t){this.getTrigger(t)}getTrigger(t){var i;const n=(i=this.runtimeAnimatorController)==null?void 0:i.getTrigger(t);return es&&console.log("getTrigger",t,n),n}IsInTransition(){return this.isInTransition()}isInTransition(){var t;return((t=this.runtimeAnimatorController)==null?void 0:t.isInTransition())??!1}SetSpeed(t){return this.setSpeed(t)}setSpeed(t){var i;t!==this._speed&&(es&&console.log("setSpeed",t),this._speed=t,((i=this._animatorController)==null?void 0:i.animator)==this&&this._animatorController.setSpeed(t))}set minMaxSpeed(t){var i;this._speed=W.lerp(t.x,t.y,Math.random()),((i=this._animatorController)==null?void 0:i.animator)==this&&this._animatorController.setSpeed(this._speed)}set minMaxOffsetNormalized(t){var i;this._normalizedStartOffset=W.lerp(t.x,t.y,Math.random()),((i=this.runtimeAnimatorController)==null?void 0:i.animator)==this&&(this.runtimeAnimatorController.normalizedStartOffset=this._normalizedStartOffset)}awake(){es&&console.log("ANIMATOR",this.name,this),this.gameObject&&this.initializeRuntimeAnimatorController()}initializeRuntimeAnimatorController(t=!1){const i=t||this.runtimeAnimatorController!==this._initializeWithRuntimeAnimatorController;if(this.runtimeAnimatorController&&i){const n=this.runtimeAnimatorController.clone();this._initializeWithRuntimeAnimatorController=n,n?(console.assert(this.runtimeAnimatorController!==n),this.runtimeAnimatorController=n,console.assert(this.runtimeAnimatorController===n),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 t;this.keepAnimatorControllerStateOnDisable||(t=this._animatorController)==null||t.reset()}onBeforeRender(){this._isDirty=!1,this._parametersAreDirty=!1,!jk(this.gameObject)&&this._animatorController&&this._animatorController.update(1)}}ku([m()],kt.prototype,"applyRootMotion",2),ku([m()],kt.prototype,"hasRootMotion",2),ku([m()],kt.prototype,"keepAnimatorControllerStateOnDisable",2),ku([m()],kt.prototype,"runtimeAnimatorController",1);const Ow=Symbol("previous-visibility"),Fc=class extends lo{render(s,t,i){if("addPass"in i)this._unsupported_effectcomposer_warning||(console.warn("RenderTexture.render() does not yet support EffectComposer"),this._unsupported_effectcomposer_warning=!0);else if(i instanceof ur){this.onBeforeRender();const n=i.getRenderTarget(),o=i.xr.enabled;i.xr.enabled=!1,i.setRenderTarget(this),i.clear(!0,!0,!0),i.render(s,t),i.setRenderTarget(n),i.xr.enabled=o,this.onAfterRender()}}onBeforeRender(){Fc._userSet.clear();const s=Pg(this.texture,!0,null,Fc._userSet);for(const t of s)t instanceof K&&(t[Ow]=t.visible,t.visible=!1)}onAfterRender(){for(const s of Fc._userSet)s instanceof K&&(s.visible=s[Ow]);Fc._userSet.clear()}};let qa=Fc;a(qa,"_userSet",new Set);var Uk=Object.defineProperty,Nk=Object.getOwnPropertyDescriptor,zc=(s,t,i,n)=>{for(var o=n>1?void 0:n?Nk(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&Uk(t,i,o),o};const Mu=O("debuggroundprojection");class Hs extends A{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(t){this._radius=t,this._projection&&this.updateProjection()}get radius(){return this._radius}set height(t){this._height=t,this._projection&&this.updateProjection()}get height(){return this._height}set arBlending(t){this._arblending=t,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 eo(this.context.scene,"background"),this._watcher.subscribeWrite(t=>{Mu&&console.log("Background changed",this.context.scene.background),this._needsTextureUpdate=!0}))}onDisable(){var t,i;(t=this._watcher)==null||t.revoke(),(i=this._projection)==null||i.removeFromParent()}onEnterXR(){this.activeAndEnabled&&(this._needsTextureUpdate=!0,this.updateProjection())}async onLeaveXR(){this.activeAndEnabled&&(await Jl(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 Le&&this.updateBlurriness(this.context.scene.background,this.context.scene.backgroundBlurriness)}updateAndCreate(){var t;this.updateProjection(),(t=this._watcher)==null||t.apply()}updateProjection(){var t,i,n,o,r,l;if(!this.context.scene.background){(t=this._projection)==null||t.removeFromParent();return}const c=this.context.scene.background;if(!(c instanceof Le)){(i=this._projection)==null||i.removeFromParent();return}if(((n=this.context.xr)!=null&&n.isPassThrough||(o=this.context.xr)!=null&&o.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){Mu&&console.log("Create/Update Ground Projection",c.name),(l=this._projection)==null||l.removeFromParent();try{this._projection=new Sa(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",Qm(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=ci(this.context.scene.children,[this._projection]),g=p.min.y;if(g<1/0){const y=G();y.x=p.min.x+(p.max.x-p.min.x)*.5;const f=Je(this.gameObject).x;y.y=g+this._height*f-d,y.z=p.min.z+(p.max.z-p.min.z)*.5,dt(this._projection,y)}Mu&&q.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(t,i){var n;if(this._projection){if(!t)return}else return;this._needsTextureUpdate=!1,Mu&&console.log("Update Blurriness",i),this._blurrynessShader??(this._blurrynessShader=new ms({name:"GroundProjectionBlurriness",uniforms:{map:{value:t},blurriness:{value:i},blending:{value:0},alphaFactor:{value:1}},vertexShader:Wk,fragmentShader:Vk})),this._blurrynessShader.depthWrite=!1,this._blurrynessShader.uniforms.map.value=t,this._blurrynessShader.uniforms.blurriness.value=1,this._lastBlurriness=i,t.needsUpdate=!0;const o=this._projection.material.transparent;this._projection.material.transparent=(((n=this.context.xr)==null?void 0:n.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,o!==this._projection.material.transparent&&(this._projection.material.needsUpdate=!0),this._projection.material.map=Xi.copyTexture(t,this._blurrynessShader),this._projection.material.depthTest=!0,this._projection.material.depthWrite=!1}}zc([m()],Hs.prototype,"applyOnAwake",2),zc([m()],Hs.prototype,"autoFit",2),zc([m()],Hs.prototype,"radius",1),zc([m()],Hs.prototype,"height",1),zc([m()],Hs.prototype,"arBlending",1);const Wk=`
839
+ Exit Time: `+u,l.hasExitTime)}this.transitionTo(l.destinationState,l.duration,l.offset);return}}else{this.transitionTo(l.destinationState,l.duration,l.offset);return}}o&&this.setTimescale(o,n);let r=!1;if(n.motion.isLooping&&o&&(o.time>=o.getClip().duration?(r=!0,o.reset(),o.time=0,o.play()):o.time<=0&&o.timeScale<0&&(r=!0,o.reset(),o.time=o.getClip().duration,o.play())),!r&&n&&!i&&o&&this.animator&&n.behaviours){const l=o?.getClip().duration,c=o.time/l,h=new Bc(this._activeState,c,l,this._speed);for(const d of n.behaviours)d.instance&&((t=d.instance.onStateUpdate)==null||t.call(d.instance,this.animator,h,0))}}setTimescale(t,i){let n=i.speed??1;i.speedParameter&&(n*=this.getFloat(i.speedParameter)),n!==void 0&&(t.timeScale=n*this._speed)}getState(t,i){return typeof t=="number"&&(t==-1&&(t=this.model.layers[i].stateMachine.defaultState,t===void 0&&(pt&&console.warn("AnimatorController default state is undefined: ",this.model,"Layer: "+i),t=0)),t=this.model.layers[i].stateMachine.states[t]),t}releaseHeldActions(t){for(const i of this._heldActions)i.fadeOut(t);this._heldActions.length=0}transitionTo(t,i,n){var o,r,l,c,h,d,u,p;if(!this.animator)return;const g=0;if(t=this.getState(t,g),!(t!=null&&t.motion)||!t.motion.clip||!(t.motion.clip instanceof ao))return;const y=this._activeState===t;if(y){const _=t.motion;if(!_.action_loopback&&_.clip){const C=this.rootMotionHandler?this.animator.gameObject.matrix.clone():null;this._mixer.uncacheAction(_.clip,this.animator.gameObject),C&&C.decompose(this.animator.gameObject.position,this.animator.gameObject.quaternion,this.animator.gameObject.scale),_.action_loopback=this.createAction(_.clip)}}if((o=this._activeState)!=null&&o.behaviours&&this._activeState.motion.action){const _=(r=this._activeState)==null?void 0:r.motion.clip.duration,C=this._activeState.motion.action.time/_,R=new Bc(this._activeState,C,_,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,R,g)}const f=(h=this._activeState)==null?void 0:h.motion.action;y&&(t.motion.action=t.motion.action_loopback,t.motion.action_loopback=f);const v=this._activeState;this._activeState=t;const b=(d=t.motion)==null?void 0:d.action,w=t.motion.clip;if(w?.duration<=0&&w.tracks.length<=0?f&&this._heldActions.push(f):f&&(f.fadeOut(i),this.releaseHeldActions(i)),b){if(n=Math.max(0,Math.min(1,n)),t.cycleOffsetParameter){let C=this.getFloat(t.cycleOffsetParameter);typeof C=="number"?(C<0&&(C+=1),n+=C,n%=1):pt&&console.warn("AnimatorController cycle offset parameter is not a number",t.cycleOffsetParameter)}else typeof t.cycleOffset=="number"&&(n+=t.cycleOffset,n%=1);b.isRunning()&&b.stop(),b.reset(),b.enabled=!0,this.setTimescale(b,t);const _=t.motion.clip.duration;if(b.time=y?0:n*_,b.timeScale<0&&(b.time=_-b.time),b.clampWhenFinished=!0,b.setLoop(um,0),i>0?b.fadeIn(i):b.weight=1,b.play(),this.rootMotionHandler&&this.rootMotionHandler.onStart(b),this._activeStates.includes(t)||this._activeStates.push(t),this._activeState.behaviours){const C=new Bc(t,n,_,this._speed);for(const R of this._activeState.behaviours)(p=(u=R.instance)==null?void 0:u.onStateEnter)==null||p.call(R.instance,this.animator,C,g)}}else pt&&(t.__warned_no_motion||(t.__warned_no_motion=!0,console.warn("No action",t.motion,this)));pt&&console.log("TRANSITION FROM "+v?.name+" TO "+t.name,i,f,b,b?.getEffectiveTimeScale(),b?.getEffectiveWeight(),b?.isRunning(),b?.isScheduled(),b?.paused)}createAction(t){var i,n;if(this._mixer.existingAction(t)&&this._mixer.uncacheAction(t,(i=this.animator)==null?void 0:i.gameObject),(n=this.animator)!=null&&n.applyRootMotion){this.rootMotionHandler||(this.rootMotionHandler=new D2(this));const o=this.animator.gameObject;return this.rootMotionHandler.createClip(this._mixer,o,t)}else return this._mixer.clipAction(t)}evaluateCondition(t){const i=this.model.parameters.find(n=>n.name===t.parameter);if(!i)return!1;switch(t.mode){case So.If:return i.value===!0;case So.IfNot:return i.value===!1;case So.Greater:return i.value>t.threshold;case So.Less:return i.value<t.threshold;case So.Equals:return i.value===t.threshold;case So.NotEqual:return i.value!==t.threshold}return!1}createActions(t){var i,n,o,r;pt&&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||(pt&&console.warn("No motion",d),d.motion=Sw(d.name)),this.animator&&d.motion.clips){const u=(i=d.motion.clips)==null?void 0:i.find(p=>{var g,y;return p.node.name===((y=(g=this.animator)==null?void 0:g.gameObject)==null?void 0:y.name)});u?d.motion.clip=u.clip:(pt||F())&&console.warn('Could not find clip for animator "'+((o=(n=this.animator)==null?void 0:n.gameObject)==null?void 0:o.name)+'"',d.motion.clips.map(p=>p.node.name))}if(!d.motion.clip){pt&&console.warn("No clip assigned to state",d);const u=new ao(void 0,void 0,[]);d.motion.clip=u}if((r=d.motion)!=null&&r.clip){const u=d.motion.clip;if(u instanceof ao){const p=this.createAction(u);d.motion.action=p}else(pt||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=S.get(u.typeName);if(p){const g=new p;g.isStateMachineBehaviour&&(g._context=this.context??void 0,Da(g,u.properties),u.instance=g),pt&&console.log("Created animator controller behaviour",d.name,u.typeName,u.properties,g)}else(pt||F())&&console.warn("Could not find AnimatorBehaviour type: "+u.typeName)}}}}*enumerateActions(){if(this.model.layers)for(const t of this.model.layers){const i=t.stateMachine;for(let n=0;n<i.states.length;n++){const o=i.states[n];o!=null&&o.motion&&(o.motion.action&&(yield o.motion.action),o.motion.action_loopback&&(yield o.motion.action_loopback))}}}}class Cw{constructor(t,i){a(this,"track"),a(this,"createdInterpolant"),a(this,"originalEvaluate"),a(this,"customEvaluate"),this.track=t;const n=t,o=n.createInterpolant.bind(t);n.createInterpolant=()=>(n.createInterpolant=o,this.createdInterpolant=o(),this.originalEvaluate=this.createdInterpolant.evaluate.bind(this.createdInterpolant),this.customEvaluate=r=>{if(!this.originalEvaluate)return;const l=this.originalEvaluate(r);return i(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 bt=class{constructor(s,t,i,n,o){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 V),a(this,"_prevTime",0),this.context=s,this.root=t,this.clip=i,bt.firstKeyframeRotation[this.cacheId]||(bt.firstKeyframeRotation[this.cacheId]=new V),o){const r=o.values;bt.firstKeyframeRotation[this.cacheId].set(r[0],r[1],r[2],r[3])}bt.spaceRotation[this.cacheId]||(bt.spaceRotation[this.cacheId]=new V),bt.effectiveSpaceRotation[this.cacheId]||(bt.effectiveSpaceRotation[this.cacheId]=new V),bt.clipOffsetRotation[this.cacheId]=new V,o&&bt.clipOffsetRotation[this.cacheId].set(o.values[0],o.values[1],o.values[2],o.values[3]).invert(),this.handlePosition(i,n),this.handleRotation(i,o)}set action(s){this._action=s}get action(){return this._action}get cacheId(){return this.root.uuid}onStart(s){if(s.getClip()!==this.clip)return;bt.lastObjRotation[this.cacheId]||(bt.lastObjRotation[this.cacheId]=this.root.quaternion.clone());const t=bt.lastObjRotation[this.cacheId];if(bt.spaceRotation[this.cacheId].copy(t),Pu){const i=new Ut().setFromQuaternion(t);console.log("START",this.clip.name,W.toDegrees(i.y),this.root.position.z)}}getClipRotationOffset(){return bt.clipOffsetRotation[this.cacheId]}handlePosition(s,t){if(t){const i=this.root;Pu&&i.add(new wi),bt.lastObjPosition[this.cacheId]||(bt.lastObjPosition[this.cacheId]=this.root.position.clone());const n=new x,o=new x;this.positionWrapper=new Cw(t,(r,l)=>{const c=this.action.getEffectiveWeight();return Pu&&i.position.length()>8&&i.position.set(0,i.position.y,0),r>this._prevTime&&(n.set(l[0],l[1],l[2]),n.sub(o),n.multiplyScalar(c),n.applyQuaternion(this.getClipRotationOffset()),n.applyQuaternion(i.quaternion),this.positionChange.copy(n)),o.fromArray(l),this._prevTime=r,l[0]=0,l[1]=0,l[2]=0,l})}}handleRotation(s,t){if(t){if(Pu){const r=t.values,l=new Ut().setFromQuaternion(new V(r[0],r[1],r[2],r[3]));console.log(s.name,t.name,"FIRST ROTATION IN TRACK",W.toDegrees(l.y));const c=t.values.length-4,h=new V().set(r[c],r[c+1],r[c+2],r[c+3]),d=new Ut().setFromQuaternion(h);console.log(s.name,t.name,"LAST ROTATION IN TRACK",W.toDegrees(d.y))}let i=0;const n=new V,o=new V;this.rotationWrapper=new Cw(t,(r,l)=>(r>i&&(o.set(l[0],l[1],l[2],l[3]),n.invert(),o.multiply(n),this.rotationChange.copy(o)),n.fromArray(l),i=r,l[0]=0,l[1]=0,l[2]=0,l[3]=1,l))}}onBeforeUpdate(s){this.positionChange.set(0,0,0),this.rotationChange.set(0,0,0,1)}onAfterUpdate(s){return!this.action||(s*=this.action.getEffectiveWeight(),s<=0)?!1:(this.positionChange.multiplyScalar(s),this.rotationChange.slerp(bt.identityQuaternion,1-s),!0)}};let Co=bt;a(Co,"lastObjPosition",{}),a(Co,"lastObjRotation",{}),a(Co,"firstKeyframeRotation",{}),a(Co,"spaceRotation",{}),a(Co,"effectiveSpaceRotation",{}),a(Co,"clipOffsetRotation",{}),a(Co,"identityQuaternion",new V);class D2{constructor(t){a(this,"controller"),a(this,"handler",[]),a(this,"root"),a(this,"basePosition",new x),a(this,"baseQuaternion",new V),a(this,"baseRotation",new Ut),a(this,"summedPosition",new x),a(this,"summedRotation",new V),this.controller=t}createClip(t,i,n){this.root=i,i&&"name"in i&&i.name;const o=this.findRootTrack(n,".position"),r=this.findRootTrack(n,".quaternion"),l=new Co(this.controller.context,i,n,o,r);this.handler.push(l);const c=t.clipAction(n);return l.action=c,c}onStart(t){for(const i of this.handler)i.onStart(t)}onBeforeUpdate(t){this.basePosition.copy(this.root.position),this.baseQuaternion.copy(this.root.quaternion);for(const i of this.handler)i.onBeforeUpdate(t)}onAfterUpdate(t){if(!(t<=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 i of this.handler)i.onAfterUpdate(t)&&(this.summedPosition.add(i.positionChange),this.summedRotation.multiply(i.rotationChange));this.root.position.add(this.summedPosition),this.root.quaternion.multiply(this.summedRotation)}}findRootTrack(t,i){const n=t.tracks;if(!n)return null;for(const o of n)if(o.name.endsWith(i))return o;return null}}class B2 extends Zi{onSerialize(t,i){}onDeserialize(t,i){if(i.type===Hi&&t?.__type==="AnimatorController")return new Hi(t)}}new B2(Hi);var F2=Object.defineProperty,z2=Object.getOwnPropertyDescriptor,ku=(s,t,i,n)=>{for(var o=n>1?void 0:n?z2(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&F2(t,i,o),o};const es=O("debuganimator");class kt extends A{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(t){var i;this._animatorController&&this._animatorController.model===t||(t?t instanceof Hi?(t.animator&&t.animator!==this&&(console.warn("AnimatorController can not be bound to multiple animators",(i=t.model)==null?void 0:i.name),t.model||console.error("AnimatorController has no model"),t=new Hi(t.model)),this._animatorController=t,this._animatorController.bind(this)):(es&&console.log("Assign animator controller",t,this),this._animatorController=new Hi(t),this.__didAwake&&this._animatorController.bind(this)):this._animatorController=null)}get runtimeAnimatorController(){return this._animatorController}getCurrentStateInfo(){var t;return(t=this.runtimeAnimatorController)==null?void 0:t.getCurrentStateInfo()}get currentAction(){var t;return((t=this.runtimeAnimatorController)==null?void 0:t.currentAction)||null}get parametersAreDirty(){return this._parametersAreDirty}get isDirty(){return this._isDirty}Play(t,i=-1,n=Number.NEGATIVE_INFINITY,o=0){this.play(t,i,n,o)}play(t,i=-1,n=Number.NEGATIVE_INFINITY,o=0){var r;(r=this.runtimeAnimatorController)==null||r.play(t,i,n,o),this._isDirty=!0}Reset(){this.reset()}reset(){var t;(t=this._animatorController)==null||t.reset(),this._isDirty=!0}SetBool(t,i){this.setBool(t,i)}setBool(t,i){var n,o;es&&console.log("setBool",t,i),((n=this.runtimeAnimatorController)==null?void 0:n.getBool(t))!==i&&(this._parametersAreDirty=!0),(o=this.runtimeAnimatorController)==null||o.setBool(t,i)}GetBool(t){return this.getBool(t)}getBool(t){var i;const n=((i=this.runtimeAnimatorController)==null?void 0:i.getBool(t))??!1;return es&&console.log("getBool",t,n),n}toggleBool(t){this.setBool(t,!this.getBool(t))}SetFloat(t,i){this.setFloat(t,i)}setFloat(t,i){var n,o;((n=this.runtimeAnimatorController)==null?void 0:n.getFloat(t))!==i&&(this._parametersAreDirty=!0),es&&console.log("setFloat",t,i),(o=this.runtimeAnimatorController)==null||o.setFloat(t,i)}GetFloat(t){return this.getFloat(t)}getFloat(t){var i;const n=((i=this.runtimeAnimatorController)==null?void 0:i.getFloat(t))??-1;return es&&console.log("getFloat",t,n),n}SetInteger(t,i){this.setInteger(t,i)}setInteger(t,i){var n,o;((n=this.runtimeAnimatorController)==null?void 0:n.getInteger(t))!==i&&(this._parametersAreDirty=!0),es&&console.log("setInteger",t,i),(o=this.runtimeAnimatorController)==null||o.setInteger(t,i)}GetInteger(t){return this.getInteger(t)}getInteger(t){var i;const n=((i=this.runtimeAnimatorController)==null?void 0:i.getInteger(t))??-1;return es&&console.log("getInteger",t,n),n}SetTrigger(t){this.setTrigger(t)}setTrigger(t){var i;this._parametersAreDirty=!0,es&&console.log("setTrigger",t),(i=this.runtimeAnimatorController)==null||i.setTrigger(t)}ResetTrigger(t){this.resetTrigger(t)}resetTrigger(t){var i;this._parametersAreDirty=!0,es&&console.log("resetTrigger",t),(i=this.runtimeAnimatorController)==null||i.resetTrigger(t)}GetTrigger(t){this.getTrigger(t)}getTrigger(t){var i;const n=(i=this.runtimeAnimatorController)==null?void 0:i.getTrigger(t);return es&&console.log("getTrigger",t,n),n}IsInTransition(){return this.isInTransition()}isInTransition(){var t;return((t=this.runtimeAnimatorController)==null?void 0:t.isInTransition())??!1}SetSpeed(t){return this.setSpeed(t)}setSpeed(t){var i;t!==this._speed&&(es&&console.log("setSpeed",t),this._speed=t,((i=this._animatorController)==null?void 0:i.animator)==this&&this._animatorController.setSpeed(t))}set minMaxSpeed(t){var i;this._speed=W.lerp(t.x,t.y,Math.random()),((i=this._animatorController)==null?void 0:i.animator)==this&&this._animatorController.setSpeed(this._speed)}set minMaxOffsetNormalized(t){var i;this._normalizedStartOffset=W.lerp(t.x,t.y,Math.random()),((i=this.runtimeAnimatorController)==null?void 0:i.animator)==this&&(this.runtimeAnimatorController.normalizedStartOffset=this._normalizedStartOffset)}awake(){es&&console.log("ANIMATOR",this.name,this),this.gameObject&&this.initializeRuntimeAnimatorController()}initializeRuntimeAnimatorController(t=!1){const i=t||this.runtimeAnimatorController!==this._initializeWithRuntimeAnimatorController;if(this.runtimeAnimatorController&&i){const n=this.runtimeAnimatorController.clone();this._initializeWithRuntimeAnimatorController=n,n?(console.assert(this.runtimeAnimatorController!==n),this.runtimeAnimatorController=n,console.assert(this.runtimeAnimatorController===n),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 t;this.keepAnimatorControllerStateOnDisable||(t=this._animatorController)==null||t.reset()}onBeforeRender(){this._isDirty=!1,this._parametersAreDirty=!1,!j2(this.gameObject)&&this._animatorController&&this._animatorController.update(1)}}ku([m()],kt.prototype,"applyRootMotion",2),ku([m()],kt.prototype,"hasRootMotion",2),ku([m()],kt.prototype,"keepAnimatorControllerStateOnDisable",2),ku([m()],kt.prototype,"runtimeAnimatorController",1);const Ow=Symbol("previous-visibility"),Fc=class extends lo{render(s,t,i){if("addPass"in i)this._unsupported_effectcomposer_warning||(console.warn("RenderTexture.render() does not yet support EffectComposer"),this._unsupported_effectcomposer_warning=!0);else if(i instanceof ur){this.onBeforeRender();const n=i.getRenderTarget(),o=i.xr.enabled;i.xr.enabled=!1,i.setRenderTarget(this),i.clear(!0,!0,!0),i.render(s,t),i.setRenderTarget(n),i.xr.enabled=o,this.onAfterRender()}}onBeforeRender(){Fc._userSet.clear();const s=Pg(this.texture,!0,null,Fc._userSet);for(const t of s)t instanceof K&&(t[Ow]=t.visible,t.visible=!1)}onAfterRender(){for(const s of Fc._userSet)s instanceof K&&(s.visible=s[Ow]);Fc._userSet.clear()}};let qa=Fc;a(qa,"_userSet",new Set);var U2=Object.defineProperty,N2=Object.getOwnPropertyDescriptor,zc=(s,t,i,n)=>{for(var o=n>1?void 0:n?N2(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&U2(t,i,o),o};const Mu=O("debuggroundprojection");class Hs extends A{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(t){this._radius=t,this._projection&&this.updateProjection()}get radius(){return this._radius}set height(t){this._height=t,this._projection&&this.updateProjection()}get height(){return this._height}set arBlending(t){this._arblending=t,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 eo(this.context.scene,"background"),this._watcher.subscribeWrite(t=>{Mu&&console.log("Background changed",this.context.scene.background),this._needsTextureUpdate=!0}))}onDisable(){var t,i;(t=this._watcher)==null||t.revoke(),(i=this._projection)==null||i.removeFromParent()}onEnterXR(){this.activeAndEnabled&&(this._needsTextureUpdate=!0,this.updateProjection())}async onLeaveXR(){this.activeAndEnabled&&(await Jl(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 Le&&this.updateBlurriness(this.context.scene.background,this.context.scene.backgroundBlurriness)}updateAndCreate(){var t;this.updateProjection(),(t=this._watcher)==null||t.apply()}updateProjection(){var t,i,n,o,r,l;if(!this.context.scene.background){(t=this._projection)==null||t.removeFromParent();return}const c=this.context.scene.background;if(!(c instanceof Le)){(i=this._projection)==null||i.removeFromParent();return}if(((n=this.context.xr)!=null&&n.isPassThrough||(o=this.context.xr)!=null&&o.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){Mu&&console.log("Create/Update Ground Projection",c.name),(l=this._projection)==null||l.removeFromParent();try{this._projection=new Sa(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",Qm(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=ci(this.context.scene.children,[this._projection]),g=p.min.y;if(g<1/0){const y=G();y.x=p.min.x+(p.max.x-p.min.x)*.5;const f=Je(this.gameObject).x;y.y=g+this._height*f-d,y.z=p.min.z+(p.max.z-p.min.z)*.5,dt(this._projection,y)}Mu&&q.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(t,i){var n;if(this._projection){if(!t)return}else return;this._needsTextureUpdate=!1,Mu&&console.log("Update Blurriness",i),this._blurrynessShader??(this._blurrynessShader=new ms({name:"GroundProjectionBlurriness",uniforms:{map:{value:t},blurriness:{value:i},blending:{value:0},alphaFactor:{value:1}},vertexShader:W2,fragmentShader:V2})),this._blurrynessShader.depthWrite=!1,this._blurrynessShader.uniforms.map.value=t,this._blurrynessShader.uniforms.blurriness.value=1,this._lastBlurriness=i,t.needsUpdate=!0;const o=this._projection.material.transparent;this._projection.material.transparent=(((n=this.context.xr)==null?void 0:n.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,o!==this._projection.material.transparent&&(this._projection.material.needsUpdate=!0),this._projection.material.map=Xi.copyTexture(t,this._blurrynessShader),this._projection.material.depthTest=!0,this._projection.material.depthWrite=!1}}zc([m()],Hs.prototype,"applyOnAwake",2),zc([m()],Hs.prototype,"autoFit",2),zc([m()],Hs.prototype,"radius",1),zc([m()],Hs.prototype,"height",1),zc([m()],Hs.prototype,"arBlending",1);const W2=`
840
840
  varying vec2 vUv;
841
841
 
842
842
  void main() {
843
843
  vUv = uv;
844
844
  gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
845
845
  }
846
- `,Vk=`
846
+ `,V2=`
847
847
  uniform sampler2D map;
848
848
  uniform float blurriness;
849
849
  uniform float alphaFactor;
@@ -905,7 +905,7 @@ Exit Time: `+u,l.hasExitTime)}this.transitionTo(l.destinationState,l.duration,l.
905
905
  // Uncomment to visualize blur amount
906
906
  // gl_FragColor = vec4(blurAmount, 0.0, 0.0, 1.0);
907
907
  }
908
- `;var Hk=Object.defineProperty,$k=Object.getOwnPropertyDescriptor,mf=(s,t,i,n)=>{for(var o=n>1?void 0:n?$k(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&Hk(t,i,o),o};class Br extends A{constructor(){super(...arguments),a(this,"constraintActive",!0),a(this,"locked",!1),a(this,"sources",[])}}mf([m()],Br.prototype,"constraintActive",2),mf([m()],Br.prototype,"locked",2),mf([m(I)],Br.prototype,"sources",2);function Pw(s,t){return Pn(s,ye.ContextCreated,t),()=>mo(s,ye.ContextCreated)}function qk(s,t){return Pn(s,ye.ContextClearing,t),()=>mo(s,ye.ContextClearing)}function Gk(s,t){return Pn(s,ye.ContextDestroying,t),()=>mo(s,ye.ContextDestroying)}function kw(s,t){return Pn(s,Me.Start,t),()=>mo(s,Me.Start)}function Mw(s,t){return Pn(s,Me.Update,t),()=>mo(s,Me.Update)}function Xk(s,t){return Pn(s,Me.OnBeforeRender,t),()=>mo(s,Me.OnBeforeRender)}function Qk(s,t){return Pn(s,Me.OnAfterRender,t),()=>mo(s,Me.OnAfterRender)}let Fr=class{constructor(){a(this,"bb",null),a(this,"bb_pos",0)}__init(s,t){return this.bb_pos=s,this.bb=t,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(s,t,i,n){return s.prep(4,12),s.writeFloat32(n),s.writeFloat32(i),s.writeFloat32(t),s.offset()}};class Rw{constructor(){a(this,"bb",null),a(this,"bb_pos",0)}__init(t,i){return this.bb_pos=t,this.bb=i,this}position(t){return(t||new Fr).__init(this.bb_pos,this.bb)}rotation(t){return(t||new Fr).__init(this.bb_pos+12,this.bb)}scale(t){return(t||new Fr).__init(this.bb_pos+24,this.bb)}static sizeOf(){return 36}static createTransform(t,i,n,o,r,l,c,h,d,u){return t.prep(4,36),t.prep(4,12),t.writeFloat32(u),t.writeFloat32(d),t.writeFloat32(h),t.prep(4,12),t.writeFloat32(c),t.writeFloat32(l),t.writeFloat32(r),t.prep(4,12),t.writeFloat32(o),t.writeFloat32(n),t.writeFloat32(i),t.offset()}}class to{constructor(){a(this,"bb",null),a(this,"bb_pos",0)}__init(t,i){return this.bb_pos=t,this.bb=i,this}static getRootAsSyncedTransformModel(t,i){return(i||new to).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsSyncedTransformModel(t,i){return t.setPosition(t.position()+mv),(i||new to).__init(t.readInt32(t.position())+t.position(),t)}guid(t){const i=this.bb.__offset(this.bb_pos,4);return i?this.bb.__string(this.bb_pos+i,t):null}fast(){const t=this.bb.__offset(this.bb_pos,6);return t?!!this.bb.readInt8(this.bb_pos+t):!1}transform(t){const i=this.bb.__offset(this.bb_pos,8);return i?(t||new Rw).__init(this.bb_pos+i,this.bb):null}dontSave(){const t=this.bb.__offset(this.bb_pos,10);return t?!!this.bb.readInt8(this.bb_pos+t):!1}static startSyncedTransformModel(t){t.startObject(4)}static addGuid(t,i){t.addFieldOffset(0,i,0)}static addFast(t,i){t.addFieldInt8(1,+i,0)}static addTransform(t,i){t.addFieldStruct(2,i,0)}static addDontSave(t,i){t.addFieldInt8(3,+i,0)}static endSyncedTransformModel(t){return t.endObject()}static finishSyncedTransformModelBuffer(t,i){t.finish(i)}static finishSizePrefixedSyncedTransformModelBuffer(t,i){t.finish(i,void 0,!0)}}var L;(s=>{(t=>{t.MAYBEMODULE=null;const i=[];function n(){return t.MODULE?Promise.resolve(t.MODULE):new Promise(r=>{i.push(r)})}t.ready=n;async function o(){if(t.MODULE)return t.MODULE;const r=await import("./rapier.light.min.js");return t.MODULE=r,t.MAYBEMODULE=r,i.forEach(l=>l(r)),i.length=0,r}t.load=o})(s.RAPIER_PHYSICS||(s.RAPIER_PHYSICS={})),(t=>{t.MAYBEMODULE=null;const i=[];function n(){return t.MODULE?Promise.resolve(t.MODULE):new Promise(r=>{i.push(r)})}t.ready=n;async function o(){if(t.MODULE)return t.MODULE;const r=await import("./postprocessing.light.min.js").then(l=>l.i);return t.MODULE=r,t.MAYBEMODULE=r,i.forEach(l=>l(r)),i.length=0,r}t.load=o})(s.POSTPROCESSING||(s.POSTPROCESSING={})),(t=>{t.MAYBEMODULE=null;const i=[];function n(){return t.MODULE?Promise.resolve(t.MODULE):new Promise(r=>{i.push(r)})}t.ready=n;async function o(){if(t.MODULE)return t.MODULE;const r=await import("./postprocessing.light.min.js").then(l=>l.N);return t.MODULE=r,t.MAYBEMODULE=r,i.forEach(l=>l(r)),i.length=0,r}t.load=o})(s.POSTPROCESSING_AO||(s.POSTPROCESSING_AO={}))})(L||(L={}));var _t=(s=>(s[s.Average=0]="Average",s[s.Multiply=1]="Multiply",s[s.Minimum=2]="Minimum",s[s.Maximum=3]="Maximum",s))(_t||{}),Ru=(s=>(s[s.Discrete=0]="Discrete",s[s.Continuous=1]="Continuous",s))(Ru||{}),st=(s=>(s[s.None=0]="None",s[s.FreezePositionX=2]="FreezePositionX",s[s.FreezePositionY=4]="FreezePositionY",s[s.FreezePositionZ=8]="FreezePositionZ",s[s.FreezePosition=14]="FreezePosition",s[s.FreezeRotationX=16]="FreezeRotationX",s[s.FreezeRotationY=32]="FreezeRotationY",s[s.FreezeRotationZ=64]="FreezeRotationZ",s[s.FreezeRotation=112]="FreezeRotation",s[s.FreezeAll=126]="FreezeAll",s))(st||{}),Ga=(s=>(s[s.None=0]="None",s[s.X=2]="X",s[s.Y=4]="Y",s[s.Z=8]="Z",s[s.All=-1]="All",s))(Ga||{});const Mt=function(s,t){return function(i,n,o){Yk(i,n,o,s,t)}};function Yk(s,t,i,n,o){if(!o&&!n&&!s.onValidate)return;if(i!==void 0){console.error("Invalid usage of validate decorator. Only fields can be validated.",s,t,i),De("Invalid usage of validate decorator. Only fields can be validated. Property: "+t,Ci.Error);return}let r="";if(typeof t=="string"?r=t:r=t.name,s.__internalAwake){const l=Symbol(r),c=s.__internalAwake;s.__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=s.constructor)==null?void 0:h.name)+'"');return}if(this[l]===void 0){this[l]=this[r];const d=this[r];if(d instanceof oe||d instanceof x||d instanceof me||d instanceof V){const u=this[r];_d(u,()=>{this.onValidate(r)})}Object.defineProperty(this,r,{set:function(u){var p;if(this[Hg]===!0)this[l]=u;else{n?.call(this,u);const g=this[l];this[l]=u,(p=this.onValidate)==null||p.call(this,r,g)}},get:function(){return o?.call(this),this[l]}})}c.call(this)}}}const Kk=function(s){return function(t,i,n){let o="";typeof i=="string"?o=i:o=i.name;const r=s.prototype,l=Object.getOwnPropertyDescriptor(r,o);if(!(l!=null&&l.value)){console.warn("Can not apply prefix: type does not have method named",i,s);return}const c=l.value,h=t[o];Object.defineProperty(r,o,{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 Zk=Object.defineProperty,Jk=Object.getOwnPropertyDescriptor,Ti=(s,t,i,n)=>{for(var o=n>1?void 0:n?Jk(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&Zk(t,i,o),o};class eM{constructor(t,i){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=i,this.obj=t}get isDirty(){return this.positionChanged||this.rotationChanged}reset(t=!1){if(this.positionChanged=!1,this.rotationChanged=!1,this.mute=!1,t){if(this.position)for(const i of this._positionKeys)delete this.position[i];if(this.quaternion)for(const i of this._quaternionKeys)delete this.quaternion[i]}}syncValues(){for(const t of this._positionKeys)this.position[t]=this.obj.position[t];for(const t of this._quaternionKeys)this.quaternion[t]=this.obj.quaternion[t]}applyValues(){if(this.positionChanged&&this.position)for(const t of this._positionKeys){const i=this.position[t];i!==void 0&&(this.obj.position[t]=i)}if(this.rotationChanged&&this.quaternion)for(const t of this._quaternionKeys){const i=this.quaternion[t];i!==void 0&&(this.obj.quaternion[t]=i)}}start(t,i){this.reset(),t&&(this._positionWatch||(this._positionWatch=new eo(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)})),i&&(this._rotationWatch||(this._rotationWatch=new eo(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 n=this.obj.matrixWorld.multiplyMatrices.bind(this.obj.matrixWorld),o=new ne;this.obj.matrixWorld.multiplyMatrices=(r,l)=>{var c;return(c=this.context.physics.engine)!=null&&c.isUpdating||this.mute||o.equals(r)||(this.positionChanged=!0,this.rotationChanged=!0,o.copy(r)),n(r,l)}}stop(){var t,i;(t=this._positionWatch)==null||t.revoke(),(i=this._rotationWatch)==null||i.revoke()}}var gf;const ff=(gf=class extends A{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",st.None),a(this,"isKinematic",!1),a(this,"drag",0),a(this,"angularDrag",1),a(this,"detectCollisions",!0),a(this,"sleepThreshold",.01),a(this,"collisionDetectionMode",Ru.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(s){s!==this._mass&&(this._mass=s,this._propertiesChanged=!0,this.__didAwake&&(this.autoMass=!1))}get mass(){var s,t;return this.autoMass?((t=(s=this.context.physics.engine)==null?void 0:s.getBody(this))==null?void 0:t.mass())??-1:this._mass}get lockPositionX(){return(this.constraints&st.FreezePositionX)!==0}get lockPositionY(){return(this.constraints&st.FreezePositionY)!==0}get lockPositionZ(){return(this.constraints&st.FreezePositionZ)!==0}get lockRotationX(){return(this.constraints&st.FreezeRotationX)!==0}get lockRotationY(){return(this.constraints&st.FreezeRotationY)!==0}get lockRotationZ(){return(this.constraints&st.FreezeRotationZ)!==0}set lockPositionX(s){s?this.constraints|=st.FreezePositionX:this.constraints&=~st.FreezePositionX}set lockPositionY(s){s?this.constraints|=st.FreezePositionY:this.constraints&=~st.FreezePositionY}set lockPositionZ(s){s?this.constraints|=st.FreezePositionZ:this.constraints&=~st.FreezePositionZ}set lockRotationX(s){s?this.constraints|=st.FreezeRotationX:this.constraints&=~st.FreezeRotationX}set lockRotationY(s){s?this.constraints|=st.FreezeRotationY:this.constraints&=~st.FreezeRotationY}set lockRotationZ(s){s?this.constraints|=st.FreezeRotationZ:this.constraints&=~st.FreezeRotationZ}set gravityScale(s){this._gravityScale=s}get gravityScale(){return this._gravityScale}awake(){this._watch=void 0,this._propertiesChanged=!1}onEnable(){this._watch||(this._watch=new eM(this.gameObject,this.context)),this._watch.start(!0,!0),this.startCoroutine(this.beforePhysics(),Me.LateUpdate),F()&&(globalThis.false?L.RAPIER_PHYSICS.ready().then(async()=>{var s;await Jl(3),(s=this.context.physics.engine)!=null&&s.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 s,t;(s=this._watch)==null||s.stop(),(t=this.context.physics.engine)==null||t.removeBody(this)}onDestroy(){var s;(s=this.context.physics.engine)==null||s.removeBody(this)}onValidate(){this._propertiesChanged=!0}*beforePhysics(){for(var s,t,i,n;;)this._propertiesChanged&&(this._propertiesChanged=!1,(s=this.context.physics.engine)==null||s.updateProperties(this)),(t=this._watch)!=null&&t.isDirty?(this._watch.mute=!0,this._watch.applyValues(),(i=this.context.physics.engine)==null||i.updateBody(this,this._watch.positionChanged,this._watch.rotationChanged),this._watch.reset()):(n=this._watch)==null||n.syncValues(),this.captureVelocity(),yield}teleport(s,t=!0){var i;(i=this._watch)==null||i.reset(!0),t?this.gameObject.position.set(s.x,s.y,s.z):this.setWorldPosition(s.x,s.y,s.z),this.resetForcesAndTorques(),this.resetVelocities()}resetForces(s=!0){var t;(t=this.context.physics.engine)==null||t.resetForces(this,s)}resetTorques(s=!0){var t;(t=this.context.physics.engine)==null||t.resetTorques(this,s)}resetVelocities(){this.setVelocity(0,0,0),this.setAngularVelocity(0,0,0)}resetForcesAndTorques(){this.resetForces(),this.resetTorques()}wakeUp(){var s;(s=this.context.physics.engine)==null||s.wakeup(this)}get isSleeping(){var s;return(s=this.context.physics.engine)==null?void 0:s.isSleeping(this)}updateProperties(){var s;return this._propertiesChanged=!1,(s=this.context.physics.engine)==null?void 0:s.updateProperties(this)}applyForce(s,t,i=!0){var n;this._propertiesChanged&&this.updateProperties(),(n=this.context.physics.engine)==null||n.addForce(this,s,i)}applyImpulse(s,t=!0){var i;this._propertiesChanged&&this.updateProperties(),(i=this.context.physics.engine)==null||i.applyImpulse(this,s,t)}setForce(s,t,i,n=!0){var o,r,l;(o=this.context.physics.engine)==null||o.resetForces(this,n),typeof s=="number"?(t??(t=0),i??(i=0),(r=this.context.physics.engine)==null||r.addForce(this,{x:s,y:t,z:i},n)):(l=this.context.physics.engine)==null||l.addForce(this,s,n)}getVelocity(){var s;const t=(s=this.context.physics.engine)==null?void 0:s.getLinearVelocity(this);return t?(this._currentVelocity.x=t.x,this._currentVelocity.y=t.y,this._currentVelocity.z=t.z,this._currentVelocity):this._currentVelocity.set(0,0,0)}setVelocity(s,t,i,n=!0){var o,r;if(s instanceof x){const l=s;(o=this.context.physics.engine)==null||o.setLinearVelocity(this,l,n);return}t===void 0||i===void 0||(r=this.context.physics.engine)==null||r.setLinearVelocity(this,{x:s,y:t,z:i},n)}getAngularVelocity(){var s;const t=(s=this.context.physics.engine)==null?void 0:s.getAngularVelocity(this);return t?(this._currentVelocity.x=t.x,this._currentVelocity.y=t.y,this._currentVelocity.z=t.z,this._currentVelocity):this._currentVelocity.set(0,0,0)}setAngularVelocity(s,t,i,n=!0){var o,r;if(typeof s=="object"){const l=s;(o=this.context.physics.engine)==null||o.setAngularVelocity(this,l,n);return}if(t===void 0||i===void 0||typeof t=="boolean"){console.warn("setAngularVelocity expects either a Vec3 or 3 numbers");return}(r=this.context.physics.engine)==null||r.setAngularVelocity(this,{x:s,y:t,z:i},n)}setTorque(s,t,i){typeof s=="number"?this.setAngularVelocity(s,t,i):this.setAngularVelocity(s)}get smoothedVelocity(){return this._smoothedVelocityGetter.copy(this._smoothedVelocity),this._smoothedVelocityGetter.multiplyScalar(1/this.context.time.deltaTime)}setBodyFromGameObject(s=null){}captureVelocity(){const s=te(this.gameObject);this.gameObject.matrixWorld.decompose(ff.tempPosition,tM,iM);const t=s.sub(this._lastPosition);this._lastPosition.copy(ff.tempPosition),this._smoothedVelocity.lerp(t,this.context.time.deltaTime/.1)}},a(gf,"tempPosition",new x),gf);let ve=ff;Ti([Mt()],ve.prototype,"autoMass",2),Ti([m()],ve.prototype,"mass",1),Ti([Mt(),m()],ve.prototype,"useGravity",2),Ti([m(x)],ve.prototype,"centerOfMass",2),Ti([Mt(),m()],ve.prototype,"constraints",2),Ti([Mt(),m()],ve.prototype,"isKinematic",2),Ti([Mt(),m()],ve.prototype,"drag",2),Ti([Mt(),m()],ve.prototype,"angularDrag",2),Ti([Mt(),m()],ve.prototype,"detectCollisions",2),Ti([Mt(),m()],ve.prototype,"sleepThreshold",2),Ti([Mt(),m()],ve.prototype,"collisionDetectionMode",2),Ti([Mt()],ve.prototype,"_gravityScale",2),Ti([Mt()],ve.prototype,"dominanceGroup",2),new x;const tM=new V,iM=new x,Oo=O("debugsync"),Uc="STRS";lg(Uc,to.getRootAsSyncedTransformModel);const $s=new Cm;function Tw(s,t,i=!0){$s.clear();const n=$s.createString(s);to.startSyncedTransformModel($s),to.addGuid($s,n),to.addFast($s,i);const o=t.worldPosition,r=t.worldEuler,l=t.gameObject.scale;to.addTransform($s,Rw.createTransform($s,o.x,o.y,o.z,r.x,r.y,r.z,l.x,l.y,l.z));const c=to.endSyncedTransformModel($s);return $s.finish(c,Uc),$s.asUint8Array()}let yf=0,Nc=0;Mw(s=>{var t;const i=(t=s.connection.currentServerUrl)!=null&&t.includes("glitch")?10:40;Nc=Math.floor(yf/i),yf=0,Oo&&Nc>0&&console.log("Sync Transform Fast Interval",Nc)});class qs extends A{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 Ut),a(this,"receivedUpdate",!1),a(this,"lastWorldPos"),a(this,"lastWorldRotation")}requestOwnership(){Oo&&console.log("Request ownership"),this._model?this._model.requestOwnership():(this._shouldRequestOwnership=!0,this._needsUpdate=!0)}hasOwnership(){var t;return((t=this._model)==null?void 0:t.hasOwnership)??void 0}isOwned(){var t;return(t=this._model)==null?void 0:t.isOwned}awake(){Oo&&console.log("new instance",this.guid,this),this._receivedDataBefore=!1,this._targetPosition=new x,this._targetRotation=new V,this.lastWorldPos=new x,this.lastWorldRotation=new V,this.rb=P.getComponentInChildren(this.gameObject,ve),this.rb&&(this._wasKinematic=this.rb.isKinematic),this.receivedUpdate=!0,this._model=new dg(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(Uc,this.receivedDataCallback)}onDestroy(){this.syncDestroy&&Lg(this.guid,this.context.connection),this._model=null,this.context.connection.stopListen(ie.JoinedRoom,this.joinedRoomCallback),this.context.connection.stopListenBinary(Uc,this.receivedDataCallback)}tryGetLastState(){const t=this.context.connection.tryGetState(this.guid);t&&this.onReceivedData(t)}onReceivedData(t){var i;if(!this.destroyed&&typeof t.guid=="function"&&t.guid()===this.guid){Oo&&console.log("new data",this.context.connection.connectionId,this.context.time.frameCount,this.guid,t),this.receivedUpdate=!0,this._receivedFastUpdate=t.fast();const n=t.transform();if(n){cs.markDirty(this.gameObject,!0);const o=n.position();o&&(this.interpolatePosition&&((i=this._targetPosition)==null||i.set(o.x(),o.y(),o.z())),(!this.interpolatePosition||!this._receivedDataBefore)&&this.setWorldPosition(o.x(),o.y(),o.z()));const r=n.rotation();r&&(this.tempEuler.set(r.x(),r.y(),r.z()),this.interpolateRotation&&this._targetRotation.setFromEuler(this.tempEuler),(!this.interpolateRotation||!this._receivedDataBefore)&&Gm(this.gameObject,this.tempEuler))}this._receivedDataBefore=!0}}onEnable(){this.lastWorldPos.copy(this.worldPosition),this.lastWorldRotation.copy(this.worldQuaternion),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){Oo&&console.log("no model or room",this.name,this.guid,this.context.connection.isInRoom);return}this._shouldRequestOwnership&&(this._shouldRequestOwnership=!1,this._model.requestOwnership());const t=this.worldPosition,i=this.worldQuaternion;if(this._model.isOwned&&!this.receivedUpdate){const r=t.distanceTo(this.lastWorldPos),l=i.angleTo(this.lastWorldRotation),c=this._model.hasOwnership||this.fastMode?1e-4:.001;(r>c||l>c)&&(this._model.hasOwnership?this._needsUpdate=!0:(Oo&&console.log(this.guid,"reset because not owned but",this.gameObject.name,this.lastWorldPos),this.worldPosition=this.lastWorldPos,t.copy(this.lastWorldPos),this.worldQuaternion=this.lastWorldRotation,i.copy(this.lastWorldRotation),cs.markDirty(this.gameObject,!0),this._needsUpdate=!1))}if(this._model&&!this._model.hasOwnership&&this._model.isOwned&&this._receivedDataBefore){const r=this._receivedFastUpdate||this.fastMode?.5:.3;let l=!1;if(this.interpolatePosition&&this._targetPosition){const c=this.worldPosition;c.lerp(this._targetPosition,r),this.worldPosition=c,l=!0}if(this.interpolateRotation&&this._targetRotation){const c=this.worldQuaternion;c.slerp(this._targetRotation,r),this.worldQuaternion=c,l=!0}l&&cs.markDirty(this.gameObject,!0)}if(this.receivedUpdate=!1,this.lastWorldPos.copy(t),this.lastWorldRotation.copy(i),!this._model||!this._model||this._model.hasOwnership===void 0||!this._model.hasOwnership)return;this.rb&&this.overridePhysics&&this._wasKinematic!==void 0&&(Oo&&console.log("reset kinematic",this.rb.name,this._wasKinematic),this.rb.isKinematic=this._wasKinematic);const n=10,o=this.rb||this.fastMode;if(this._needsUpdate&&(this.context.time.frameCount%n===0||o)){if(yf++,o&&Nc>0&&this.context.time.frameCount%Nc!==0)return;Oo&&console.log("send update",this.context.connection.connectionId,this.guid,this.gameObject.name,this.gameObject.guid),this._needsUpdate=!1;const r=Tw(this.guid,this,!!o);this.context.connection.sendBinary(r)}}}const sM=O("debugshadowcomponents");yv.prototype.interactable={get(){return this.interactive},set(s){this.interactable=s}};const ts=Symbol("shadowDomOwner");class ls extends A{constructor(){super(...arguments),a(this,"_shadowComponent",null),a(this,"_controlsChildLayout",!0),a(this,"_root"),a(this,"_parentComponent")}isRoot(){var t;return((t=this.Root)==null?void 0:t.gameObject)===this.gameObject}get canvas(){const t=this.Root;return t!=null&&t.isCanvas?t:null}get Canvas(){return this.canvas}markDirty(){ai.markUIDirty(this.context)}get shadowComponent(){return this._shadowComponent}set shadowComponent(t){this._shadowComponent=t}get controlsChildLayout(){return this._controlsChildLayout}set controlsChildLayout(t){this._controlsChildLayout=t,this.shadowComponent&&(this.shadowComponent.autoLayout=t)}get Root(){return this._root===void 0&&(this._root=P.getComponentInParent(this.gameObject,Wc)),this._root}__internalNewInstanceCreated(t){return super.__internalNewInstanceCreated(t),this.shadowComponent=null,this._root=void 0,this._parentComponent=void 0,this}onEnable(){super.onEnable()}addShadowComponent(t,i){var n;if(!t)return;this.removeShadowComponent();const o=this.isRoot()?this.gameObject:this.gameObject.parent;if(this._parentComponent=P.getComponentInParent(o,ls),!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}t.name=this.name+" ("+(this.constructor.name??"UI")+")",t.autoLayout=this._parentComponent.controlsChildLayout,t[ts]=this,this.setShadowComponentOwner(t);let r=!1;if(((n=this.Root)==null?void 0:n.gameObject)===this.gameObject)this.gameObject.add(t);else{const l=this._parentComponent.shadowComponent;l&&(l?.add(t),r=!0)}this.shadowComponent=t,i&&i.shadowComponent&&this.shadowComponent&&i.shadowComponent.add(this.shadowComponent),Sc&&t.add(new wi(.5)),this.onAfterAddedToScene(),r&&lO(),sM&&console.warn("Added shadow component",this.shadowComponent)}setShadowComponentOwner(t){if(t&&(t[ts]===void 0||t[ts]===this)&&(t[ts]=this,t.children))for(const i of t.children)this.setShadowComponentOwner(i)}traverseOwnedShadowComponents(t,i,n){if(t&&t[ts]===i){n(t);for(const o of t.children)this.traverseOwnedShadowComponents(o,i,n)}}removeShadowComponent(){this.shadowComponent&&this.shadowComponent.removeFromParent()}onAfterAddedToScene(){}setInteractable(t){this.shadowComponent&&(this.shadowComponent.interactable=t)}}class Wc extends ls{awake(){super.awake()}}class Wl{constructor(t,i){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=i,this.input=t,this.button=i.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 t=new Wl(this.input,this.event);return Object.assign(t,this),t}Use(){this.use()}StopPropagation(){this.event.stopImmediatePropagation()}}function Tu(s,t){return P.foreachComponent(s,i=>{if(!i.enabled)return;const n=i;if(t)switch(t){case"pointerdown":if(n.onPointerDown)return!0;break;case"pointerup":if(n.onPointerUp||n.onPointerClick)return!0;break;case"pointermove":if(n.onPointerEnter||n.onPointerExit||n.onPointerMove)return!0;break}else if(n.onPointerDown||n.onPointerUp||n.onPointerEnter||n.onPointerExit||n.onPointerClick)return!0},!1)===!0}const En=new Array;class Gs{constructor(t,i,n,o){a(this,"enabled",!0),a(this,"target"),a(this,"methodName"),a(this,"arguments"),this.target=t,this.methodName=i||null,this.arguments=n,o!=null&&(this.enabled=o)}get canClone(){return this.target instanceof Object}invoke(...t){if(this.enabled!==!1){if(typeof this.target=="function")this.arguments?(En.length=0,t!==void 0&&t.length>0&&En.push(...t),En.push(...this.arguments),this.target(...this.arguments),En.length=0):this.target(...t);else if(this.methodName!=null){const i=this.target[this.methodName];typeof i=="function"?this.arguments?(En.length=0,t!==void 0&&t.length>0&&En.push(...t),En.push(...this.arguments),i.call(this.target,...En),En.length=0):i.call(this.target,...t):this.arguments?this.target[this.methodName]=this.arguments[0]||t[0]:this.target[this.methodName]=t[0]}}}}const nM=s=>/^[A-Z]*$/.test(s);class Eu extends Event{constructor(){super(...arguments),a(this,"args")}}class _e{constructor(t){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(t))for(const i of t)i instanceof Gs?this.methods.push(i):typeof i=="function"&&this.methods.push(new Gs(i));else typeof t=="function"&&this.methods.push(new Gs(t))}__internalOnInstantiate(t){var i;const n=new Array;for(let o=0;o<this.methods.length;o++){const r=this.methods[o];if(!(r.target instanceof Function)){const l=r.target;let c=l?.uuid;if(l&&(c=l.guid),c){const h=t[c];if(h){const d=(i=r.arguments)==null?void 0:i.map(u=>u instanceof Object&&u.uuid?t[u.uuid]:u!=null&&u.isComponent?t[u.guid]:u);n.push(new Gs(h.clone,r.methodName,d,r.enabled))}else F()&&console.warn("Could not find target for event listener")}}}return new _e(n)}setEventTarget(t,i){if(this.key=t,this.target=i,this.key!==void 0){let n="",o=!1;for(const r of this.key)o&&nM(r)&&(n+="-"),o=!0,n+=r.toLowerCase();this.key=n}}get listenerCount(){var t;return((t=this.methods)==null?void 0:t.length)??0}get isInvoking(){return this._isInvoking}static from(...t){return new _e(t)}invoke(...t){var i;if(this._isInvoking)return console.warn("Circular event invocation detected. Please check your event listeners for circular references.",this),!1;if(((i=this.methods)==null?void 0:i.length)<=0)return!1;this._isInvoking=!0;try{this._methodsCopy.length=0,this._methodsCopy.push(...this.methods);for(const n of this._methodsCopy)n.invoke(...t);if(typeof this.target=="object"&&typeof this.key=="string"){const n=this.target.dispatchEvent;if(typeof n=="function"){const o=new Eu(this.key);o.args=t,n.call(this.target,o)}}}finally{this._isInvoking=!1,this._methodsCopy.length=0}return!0}addEventListener(t){return this.methods.push(new Gs(t)),t}removeEventListener(t){if(t)for(let i=this.methods.length-1;i>=0;i--)this.methods[i].target===t&&(this.methods[i].enabled=!1,this.methods.splice(i,1))}removeAllEventListeners(){this.methods.length=0}}class oM extends Zi{constructor(){super([re,Se],"ColorSerializer")}onDeserialize(t){if(t!=null)return t.a!==void 0?new Se(t.r,t.g,t.b,t.a):t.alpha!==void 0?new Se(t.r,t.g,t.b,t.alpha):new re(t.r,t.g,t.b)}onSerialize(t){if(t!=null)return t.a!==void 0?{r:t.r,g:t.g,b:t.b,a:t.a}:{r:t.r,g:t.g,b:t.b}}}const rM=new oM;class aM extends Zi{constructor(){super([Ut],"EulerSerializer")}onDeserialize(t,i){if(t!=null){if(t.order)return new Ut(t.x,t.y,t.z,t.order);if(t.x!=null)return new Ut(t.x,t.y,t.z)}}onSerialize(t,i){return{x:t.x,y:t.y,z:t.z,order:t.order}}}const lM=new aM;class cM extends Zi{constructor(){super(I,"ObjectSerializer")}onSerialize(t,i){if(i.objectToNode!==void 0&&t.uuid){const n=i.objectToNode[t.uuid];return vt&&console.log(n,t.name,t.uuid),{node:n}}}onDeserialize(t,i){var n,o,r;if(typeof t=="string"){if(t.endsWith(".glb")||t.endsWith(".gltf")){if(i.serializable instanceof Array&&i.serializable.includes(ae))return;F()&&xe("Detected wrong usage of @serializable with Object3D or GameObject. Instead you should use AssetReference here! Please see the console for details.");const l=(o=(n=i.target)==null?void 0:n.constructor)==null?void 0:o.name;console.warn(`Wrong usage of @serializable detected in your script "${l}"
908
+ `;var H2=Object.defineProperty,$2=Object.getOwnPropertyDescriptor,mf=(s,t,i,n)=>{for(var o=n>1?void 0:n?$2(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&H2(t,i,o),o};class Br extends A{constructor(){super(...arguments),a(this,"constraintActive",!0),a(this,"locked",!1),a(this,"sources",[])}}mf([m()],Br.prototype,"constraintActive",2),mf([m()],Br.prototype,"locked",2),mf([m(I)],Br.prototype,"sources",2);function Pw(s,t){return Pn(s,ye.ContextCreated,t),()=>mo(s,ye.ContextCreated)}function q2(s,t){return Pn(s,ye.ContextClearing,t),()=>mo(s,ye.ContextClearing)}function G2(s,t){return Pn(s,ye.ContextDestroying,t),()=>mo(s,ye.ContextDestroying)}function kw(s,t){return Pn(s,Me.Start,t),()=>mo(s,Me.Start)}function Mw(s,t){return Pn(s,Me.Update,t),()=>mo(s,Me.Update)}function X2(s,t){return Pn(s,Me.OnBeforeRender,t),()=>mo(s,Me.OnBeforeRender)}function Q2(s,t){return Pn(s,Me.OnAfterRender,t),()=>mo(s,Me.OnAfterRender)}let Fr=class{constructor(){a(this,"bb",null),a(this,"bb_pos",0)}__init(s,t){return this.bb_pos=s,this.bb=t,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(s,t,i,n){return s.prep(4,12),s.writeFloat32(n),s.writeFloat32(i),s.writeFloat32(t),s.offset()}};class Rw{constructor(){a(this,"bb",null),a(this,"bb_pos",0)}__init(t,i){return this.bb_pos=t,this.bb=i,this}position(t){return(t||new Fr).__init(this.bb_pos,this.bb)}rotation(t){return(t||new Fr).__init(this.bb_pos+12,this.bb)}scale(t){return(t||new Fr).__init(this.bb_pos+24,this.bb)}static sizeOf(){return 36}static createTransform(t,i,n,o,r,l,c,h,d,u){return t.prep(4,36),t.prep(4,12),t.writeFloat32(u),t.writeFloat32(d),t.writeFloat32(h),t.prep(4,12),t.writeFloat32(c),t.writeFloat32(l),t.writeFloat32(r),t.prep(4,12),t.writeFloat32(o),t.writeFloat32(n),t.writeFloat32(i),t.offset()}}class to{constructor(){a(this,"bb",null),a(this,"bb_pos",0)}__init(t,i){return this.bb_pos=t,this.bb=i,this}static getRootAsSyncedTransformModel(t,i){return(i||new to).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsSyncedTransformModel(t,i){return t.setPosition(t.position()+mv),(i||new to).__init(t.readInt32(t.position())+t.position(),t)}guid(t){const i=this.bb.__offset(this.bb_pos,4);return i?this.bb.__string(this.bb_pos+i,t):null}fast(){const t=this.bb.__offset(this.bb_pos,6);return t?!!this.bb.readInt8(this.bb_pos+t):!1}transform(t){const i=this.bb.__offset(this.bb_pos,8);return i?(t||new Rw).__init(this.bb_pos+i,this.bb):null}dontSave(){const t=this.bb.__offset(this.bb_pos,10);return t?!!this.bb.readInt8(this.bb_pos+t):!1}static startSyncedTransformModel(t){t.startObject(4)}static addGuid(t,i){t.addFieldOffset(0,i,0)}static addFast(t,i){t.addFieldInt8(1,+i,0)}static addTransform(t,i){t.addFieldStruct(2,i,0)}static addDontSave(t,i){t.addFieldInt8(3,+i,0)}static endSyncedTransformModel(t){return t.endObject()}static finishSyncedTransformModelBuffer(t,i){t.finish(i)}static finishSizePrefixedSyncedTransformModelBuffer(t,i){t.finish(i,void 0,!0)}}var L;(s=>{(t=>{t.MAYBEMODULE=null;const i=[];function n(){return t.MODULE?Promise.resolve(t.MODULE):new Promise(r=>{i.push(r)})}t.ready=n;async function o(){if(t.MODULE)return t.MODULE;const r=await import("./rapier.light.min.js");return t.MODULE=r,t.MAYBEMODULE=r,i.forEach(l=>l(r)),i.length=0,r}t.load=o})(s.RAPIER_PHYSICS||(s.RAPIER_PHYSICS={})),(t=>{t.MAYBEMODULE=null;const i=[];function n(){return t.MODULE?Promise.resolve(t.MODULE):new Promise(r=>{i.push(r)})}t.ready=n;async function o(){if(t.MODULE)return t.MODULE;const r=await import("./postprocessing.light.min.js").then(l=>l.i);return t.MODULE=r,t.MAYBEMODULE=r,i.forEach(l=>l(r)),i.length=0,r}t.load=o})(s.POSTPROCESSING||(s.POSTPROCESSING={})),(t=>{t.MAYBEMODULE=null;const i=[];function n(){return t.MODULE?Promise.resolve(t.MODULE):new Promise(r=>{i.push(r)})}t.ready=n;async function o(){if(t.MODULE)return t.MODULE;const r=await import("./postprocessing.light.min.js").then(l=>l.N);return t.MODULE=r,t.MAYBEMODULE=r,i.forEach(l=>l(r)),i.length=0,r}t.load=o})(s.POSTPROCESSING_AO||(s.POSTPROCESSING_AO={}))})(L||(L={}));var _t=(s=>(s[s.Average=0]="Average",s[s.Multiply=1]="Multiply",s[s.Minimum=2]="Minimum",s[s.Maximum=3]="Maximum",s))(_t||{}),Ru=(s=>(s[s.Discrete=0]="Discrete",s[s.Continuous=1]="Continuous",s))(Ru||{}),st=(s=>(s[s.None=0]="None",s[s.FreezePositionX=2]="FreezePositionX",s[s.FreezePositionY=4]="FreezePositionY",s[s.FreezePositionZ=8]="FreezePositionZ",s[s.FreezePosition=14]="FreezePosition",s[s.FreezeRotationX=16]="FreezeRotationX",s[s.FreezeRotationY=32]="FreezeRotationY",s[s.FreezeRotationZ=64]="FreezeRotationZ",s[s.FreezeRotation=112]="FreezeRotation",s[s.FreezeAll=126]="FreezeAll",s))(st||{}),Ga=(s=>(s[s.None=0]="None",s[s.X=2]="X",s[s.Y=4]="Y",s[s.Z=8]="Z",s[s.All=-1]="All",s))(Ga||{});const Mt=function(s,t){return function(i,n,o){Y2(i,n,o,s,t)}};function Y2(s,t,i,n,o){if(!o&&!n&&!s.onValidate)return;if(i!==void 0){console.error("Invalid usage of validate decorator. Only fields can be validated.",s,t,i),De("Invalid usage of validate decorator. Only fields can be validated. Property: "+t,Ci.Error);return}let r="";if(typeof t=="string"?r=t:r=t.name,s.__internalAwake){const l=Symbol(r),c=s.__internalAwake;s.__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=s.constructor)==null?void 0:h.name)+'"');return}if(this[l]===void 0){this[l]=this[r];const d=this[r];if(d instanceof oe||d instanceof x||d instanceof me||d instanceof V){const u=this[r];_d(u,()=>{this.onValidate(r)})}Object.defineProperty(this,r,{set:function(u){var p;if(this[Hg]===!0)this[l]=u;else{n?.call(this,u);const g=this[l];this[l]=u,(p=this.onValidate)==null||p.call(this,r,g)}},get:function(){return o?.call(this),this[l]}})}c.call(this)}}}const K2=function(s){return function(t,i,n){let o="";typeof i=="string"?o=i:o=i.name;const r=s.prototype,l=Object.getOwnPropertyDescriptor(r,o);if(!(l!=null&&l.value)){console.warn("Can not apply prefix: type does not have method named",i,s);return}const c=l.value,h=t[o];Object.defineProperty(r,o,{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 Z2=Object.defineProperty,J2=Object.getOwnPropertyDescriptor,Ti=(s,t,i,n)=>{for(var o=n>1?void 0:n?J2(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&Z2(t,i,o),o};class eM{constructor(t,i){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=i,this.obj=t}get isDirty(){return this.positionChanged||this.rotationChanged}reset(t=!1){if(this.positionChanged=!1,this.rotationChanged=!1,this.mute=!1,t){if(this.position)for(const i of this._positionKeys)delete this.position[i];if(this.quaternion)for(const i of this._quaternionKeys)delete this.quaternion[i]}}syncValues(){for(const t of this._positionKeys)this.position[t]=this.obj.position[t];for(const t of this._quaternionKeys)this.quaternion[t]=this.obj.quaternion[t]}applyValues(){if(this.positionChanged&&this.position)for(const t of this._positionKeys){const i=this.position[t];i!==void 0&&(this.obj.position[t]=i)}if(this.rotationChanged&&this.quaternion)for(const t of this._quaternionKeys){const i=this.quaternion[t];i!==void 0&&(this.obj.quaternion[t]=i)}}start(t,i){this.reset(),t&&(this._positionWatch||(this._positionWatch=new eo(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)})),i&&(this._rotationWatch||(this._rotationWatch=new eo(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 n=this.obj.matrixWorld.multiplyMatrices.bind(this.obj.matrixWorld),o=new ne;this.obj.matrixWorld.multiplyMatrices=(r,l)=>{var c;return(c=this.context.physics.engine)!=null&&c.isUpdating||this.mute||o.equals(r)||(this.positionChanged=!0,this.rotationChanged=!0,o.copy(r)),n(r,l)}}stop(){var t,i;(t=this._positionWatch)==null||t.revoke(),(i=this._rotationWatch)==null||i.revoke()}}var gf;const ff=(gf=class extends A{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",st.None),a(this,"isKinematic",!1),a(this,"drag",0),a(this,"angularDrag",1),a(this,"detectCollisions",!0),a(this,"sleepThreshold",.01),a(this,"collisionDetectionMode",Ru.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(s){s!==this._mass&&(this._mass=s,this._propertiesChanged=!0,this.__didAwake&&(this.autoMass=!1))}get mass(){var s,t;return this.autoMass?((t=(s=this.context.physics.engine)==null?void 0:s.getBody(this))==null?void 0:t.mass())??-1:this._mass}get lockPositionX(){return(this.constraints&st.FreezePositionX)!==0}get lockPositionY(){return(this.constraints&st.FreezePositionY)!==0}get lockPositionZ(){return(this.constraints&st.FreezePositionZ)!==0}get lockRotationX(){return(this.constraints&st.FreezeRotationX)!==0}get lockRotationY(){return(this.constraints&st.FreezeRotationY)!==0}get lockRotationZ(){return(this.constraints&st.FreezeRotationZ)!==0}set lockPositionX(s){s?this.constraints|=st.FreezePositionX:this.constraints&=~st.FreezePositionX}set lockPositionY(s){s?this.constraints|=st.FreezePositionY:this.constraints&=~st.FreezePositionY}set lockPositionZ(s){s?this.constraints|=st.FreezePositionZ:this.constraints&=~st.FreezePositionZ}set lockRotationX(s){s?this.constraints|=st.FreezeRotationX:this.constraints&=~st.FreezeRotationX}set lockRotationY(s){s?this.constraints|=st.FreezeRotationY:this.constraints&=~st.FreezeRotationY}set lockRotationZ(s){s?this.constraints|=st.FreezeRotationZ:this.constraints&=~st.FreezeRotationZ}set gravityScale(s){this._gravityScale=s}get gravityScale(){return this._gravityScale}awake(){this._watch=void 0,this._propertiesChanged=!1}onEnable(){this._watch||(this._watch=new eM(this.gameObject,this.context)),this._watch.start(!0,!0),this.startCoroutine(this.beforePhysics(),Me.LateUpdate),F()&&(globalThis.false?L.RAPIER_PHYSICS.ready().then(async()=>{var s;await Jl(3),(s=this.context.physics.engine)!=null&&s.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 s,t;(s=this._watch)==null||s.stop(),(t=this.context.physics.engine)==null||t.removeBody(this)}onDestroy(){var s;(s=this.context.physics.engine)==null||s.removeBody(this)}onValidate(){this._propertiesChanged=!0}*beforePhysics(){for(var s,t,i,n;;)this._propertiesChanged&&(this._propertiesChanged=!1,(s=this.context.physics.engine)==null||s.updateProperties(this)),(t=this._watch)!=null&&t.isDirty?(this._watch.mute=!0,this._watch.applyValues(),(i=this.context.physics.engine)==null||i.updateBody(this,this._watch.positionChanged,this._watch.rotationChanged),this._watch.reset()):(n=this._watch)==null||n.syncValues(),this.captureVelocity(),yield}teleport(s,t=!0){var i;(i=this._watch)==null||i.reset(!0),t?this.gameObject.position.set(s.x,s.y,s.z):this.setWorldPosition(s.x,s.y,s.z),this.resetForcesAndTorques(),this.resetVelocities()}resetForces(s=!0){var t;(t=this.context.physics.engine)==null||t.resetForces(this,s)}resetTorques(s=!0){var t;(t=this.context.physics.engine)==null||t.resetTorques(this,s)}resetVelocities(){this.setVelocity(0,0,0),this.setAngularVelocity(0,0,0)}resetForcesAndTorques(){this.resetForces(),this.resetTorques()}wakeUp(){var s;(s=this.context.physics.engine)==null||s.wakeup(this)}get isSleeping(){var s;return(s=this.context.physics.engine)==null?void 0:s.isSleeping(this)}updateProperties(){var s;return this._propertiesChanged=!1,(s=this.context.physics.engine)==null?void 0:s.updateProperties(this)}applyForce(s,t,i=!0){var n;this._propertiesChanged&&this.updateProperties(),(n=this.context.physics.engine)==null||n.addForce(this,s,i)}applyImpulse(s,t=!0){var i;this._propertiesChanged&&this.updateProperties(),(i=this.context.physics.engine)==null||i.applyImpulse(this,s,t)}setForce(s,t,i,n=!0){var o,r,l;(o=this.context.physics.engine)==null||o.resetForces(this,n),typeof s=="number"?(t??(t=0),i??(i=0),(r=this.context.physics.engine)==null||r.addForce(this,{x:s,y:t,z:i},n)):(l=this.context.physics.engine)==null||l.addForce(this,s,n)}getVelocity(){var s;const t=(s=this.context.physics.engine)==null?void 0:s.getLinearVelocity(this);return t?(this._currentVelocity.x=t.x,this._currentVelocity.y=t.y,this._currentVelocity.z=t.z,this._currentVelocity):this._currentVelocity.set(0,0,0)}setVelocity(s,t,i,n=!0){var o,r;if(s instanceof x){const l=s;(o=this.context.physics.engine)==null||o.setLinearVelocity(this,l,n);return}t===void 0||i===void 0||(r=this.context.physics.engine)==null||r.setLinearVelocity(this,{x:s,y:t,z:i},n)}getAngularVelocity(){var s;const t=(s=this.context.physics.engine)==null?void 0:s.getAngularVelocity(this);return t?(this._currentVelocity.x=t.x,this._currentVelocity.y=t.y,this._currentVelocity.z=t.z,this._currentVelocity):this._currentVelocity.set(0,0,0)}setAngularVelocity(s,t,i,n=!0){var o,r;if(typeof s=="object"){const l=s;(o=this.context.physics.engine)==null||o.setAngularVelocity(this,l,n);return}if(t===void 0||i===void 0||typeof t=="boolean"){console.warn("setAngularVelocity expects either a Vec3 or 3 numbers");return}(r=this.context.physics.engine)==null||r.setAngularVelocity(this,{x:s,y:t,z:i},n)}setTorque(s,t,i){typeof s=="number"?this.setAngularVelocity(s,t,i):this.setAngularVelocity(s)}get smoothedVelocity(){return this._smoothedVelocityGetter.copy(this._smoothedVelocity),this._smoothedVelocityGetter.multiplyScalar(1/this.context.time.deltaTime)}setBodyFromGameObject(s=null){}captureVelocity(){const s=te(this.gameObject);this.gameObject.matrixWorld.decompose(ff.tempPosition,tM,iM);const t=s.sub(this._lastPosition);this._lastPosition.copy(ff.tempPosition),this._smoothedVelocity.lerp(t,this.context.time.deltaTime/.1)}},a(gf,"tempPosition",new x),gf);let ve=ff;Ti([Mt()],ve.prototype,"autoMass",2),Ti([m()],ve.prototype,"mass",1),Ti([Mt(),m()],ve.prototype,"useGravity",2),Ti([m(x)],ve.prototype,"centerOfMass",2),Ti([Mt(),m()],ve.prototype,"constraints",2),Ti([Mt(),m()],ve.prototype,"isKinematic",2),Ti([Mt(),m()],ve.prototype,"drag",2),Ti([Mt(),m()],ve.prototype,"angularDrag",2),Ti([Mt(),m()],ve.prototype,"detectCollisions",2),Ti([Mt(),m()],ve.prototype,"sleepThreshold",2),Ti([Mt(),m()],ve.prototype,"collisionDetectionMode",2),Ti([Mt()],ve.prototype,"_gravityScale",2),Ti([Mt()],ve.prototype,"dominanceGroup",2),new x;const tM=new V,iM=new x,Oo=O("debugsync"),Uc="STRS";lg(Uc,to.getRootAsSyncedTransformModel);const $s=new Cm;function Tw(s,t,i=!0){$s.clear();const n=$s.createString(s);to.startSyncedTransformModel($s),to.addGuid($s,n),to.addFast($s,i);const o=t.worldPosition,r=t.worldEuler,l=t.gameObject.scale;to.addTransform($s,Rw.createTransform($s,o.x,o.y,o.z,r.x,r.y,r.z,l.x,l.y,l.z));const c=to.endSyncedTransformModel($s);return $s.finish(c,Uc),$s.asUint8Array()}let yf=0,Nc=0;Mw(s=>{var t;const i=(t=s.connection.currentServerUrl)!=null&&t.includes("glitch")?10:40;Nc=Math.floor(yf/i),yf=0,Oo&&Nc>0&&console.log("Sync Transform Fast Interval",Nc)});class qs extends A{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 Ut),a(this,"receivedUpdate",!1),a(this,"lastWorldPos"),a(this,"lastWorldRotation")}requestOwnership(){Oo&&console.log("Request ownership"),this._model?this._model.requestOwnership():(this._shouldRequestOwnership=!0,this._needsUpdate=!0)}hasOwnership(){var t;return((t=this._model)==null?void 0:t.hasOwnership)??void 0}isOwned(){var t;return(t=this._model)==null?void 0:t.isOwned}awake(){Oo&&console.log("new instance",this.guid,this),this._receivedDataBefore=!1,this._targetPosition=new x,this._targetRotation=new V,this.lastWorldPos=new x,this.lastWorldRotation=new V,this.rb=P.getComponentInChildren(this.gameObject,ve),this.rb&&(this._wasKinematic=this.rb.isKinematic),this.receivedUpdate=!0,this._model=new dg(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(Uc,this.receivedDataCallback)}onDestroy(){this.syncDestroy&&Lg(this.guid,this.context.connection),this._model=null,this.context.connection.stopListen(ie.JoinedRoom,this.joinedRoomCallback),this.context.connection.stopListenBinary(Uc,this.receivedDataCallback)}tryGetLastState(){const t=this.context.connection.tryGetState(this.guid);t&&this.onReceivedData(t)}onReceivedData(t){var i;if(!this.destroyed&&typeof t.guid=="function"&&t.guid()===this.guid){Oo&&console.log("new data",this.context.connection.connectionId,this.context.time.frameCount,this.guid,t),this.receivedUpdate=!0,this._receivedFastUpdate=t.fast();const n=t.transform();if(n){cs.markDirty(this.gameObject,!0);const o=n.position();o&&(this.interpolatePosition&&((i=this._targetPosition)==null||i.set(o.x(),o.y(),o.z())),(!this.interpolatePosition||!this._receivedDataBefore)&&this.setWorldPosition(o.x(),o.y(),o.z()));const r=n.rotation();r&&(this.tempEuler.set(r.x(),r.y(),r.z()),this.interpolateRotation&&this._targetRotation.setFromEuler(this.tempEuler),(!this.interpolateRotation||!this._receivedDataBefore)&&Gm(this.gameObject,this.tempEuler))}this._receivedDataBefore=!0}}onEnable(){this.lastWorldPos.copy(this.worldPosition),this.lastWorldRotation.copy(this.worldQuaternion),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){Oo&&console.log("no model or room",this.name,this.guid,this.context.connection.isInRoom);return}this._shouldRequestOwnership&&(this._shouldRequestOwnership=!1,this._model.requestOwnership());const t=this.worldPosition,i=this.worldQuaternion;if(this._model.isOwned&&!this.receivedUpdate){const r=t.distanceTo(this.lastWorldPos),l=i.angleTo(this.lastWorldRotation),c=this._model.hasOwnership||this.fastMode?1e-4:.001;(r>c||l>c)&&(this._model.hasOwnership?this._needsUpdate=!0:(Oo&&console.log(this.guid,"reset because not owned but",this.gameObject.name,this.lastWorldPos),this.worldPosition=this.lastWorldPos,t.copy(this.lastWorldPos),this.worldQuaternion=this.lastWorldRotation,i.copy(this.lastWorldRotation),cs.markDirty(this.gameObject,!0),this._needsUpdate=!1))}if(this._model&&!this._model.hasOwnership&&this._model.isOwned&&this._receivedDataBefore){const r=this._receivedFastUpdate||this.fastMode?.5:.3;let l=!1;if(this.interpolatePosition&&this._targetPosition){const c=this.worldPosition;c.lerp(this._targetPosition,r),this.worldPosition=c,l=!0}if(this.interpolateRotation&&this._targetRotation){const c=this.worldQuaternion;c.slerp(this._targetRotation,r),this.worldQuaternion=c,l=!0}l&&cs.markDirty(this.gameObject,!0)}if(this.receivedUpdate=!1,this.lastWorldPos.copy(t),this.lastWorldRotation.copy(i),!this._model||!this._model||this._model.hasOwnership===void 0||!this._model.hasOwnership)return;this.rb&&this.overridePhysics&&this._wasKinematic!==void 0&&(Oo&&console.log("reset kinematic",this.rb.name,this._wasKinematic),this.rb.isKinematic=this._wasKinematic);const n=10,o=this.rb||this.fastMode;if(this._needsUpdate&&(this.context.time.frameCount%n===0||o)){if(yf++,o&&Nc>0&&this.context.time.frameCount%Nc!==0)return;Oo&&console.log("send update",this.context.connection.connectionId,this.guid,this.gameObject.name,this.gameObject.guid),this._needsUpdate=!1;const r=Tw(this.guid,this,!!o);this.context.connection.sendBinary(r)}}}const sM=O("debugshadowcomponents");yv.prototype.interactable={get(){return this.interactive},set(s){this.interactable=s}};const ts=Symbol("shadowDomOwner");class ls extends A{constructor(){super(...arguments),a(this,"_shadowComponent",null),a(this,"_controlsChildLayout",!0),a(this,"_root"),a(this,"_parentComponent")}isRoot(){var t;return((t=this.Root)==null?void 0:t.gameObject)===this.gameObject}get canvas(){const t=this.Root;return t!=null&&t.isCanvas?t:null}get Canvas(){return this.canvas}markDirty(){ai.markUIDirty(this.context)}get shadowComponent(){return this._shadowComponent}set shadowComponent(t){this._shadowComponent=t}get controlsChildLayout(){return this._controlsChildLayout}set controlsChildLayout(t){this._controlsChildLayout=t,this.shadowComponent&&(this.shadowComponent.autoLayout=t)}get Root(){return this._root===void 0&&(this._root=P.getComponentInParent(this.gameObject,Wc)),this._root}__internalNewInstanceCreated(t){return super.__internalNewInstanceCreated(t),this.shadowComponent=null,this._root=void 0,this._parentComponent=void 0,this}onEnable(){super.onEnable()}addShadowComponent(t,i){var n;if(!t)return;this.removeShadowComponent();const o=this.isRoot()?this.gameObject:this.gameObject.parent;if(this._parentComponent=P.getComponentInParent(o,ls),!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}t.name=this.name+" ("+(this.constructor.name??"UI")+")",t.autoLayout=this._parentComponent.controlsChildLayout,t[ts]=this,this.setShadowComponentOwner(t);let r=!1;if(((n=this.Root)==null?void 0:n.gameObject)===this.gameObject)this.gameObject.add(t);else{const l=this._parentComponent.shadowComponent;l&&(l?.add(t),r=!0)}this.shadowComponent=t,i&&i.shadowComponent&&this.shadowComponent&&i.shadowComponent.add(this.shadowComponent),Sc&&t.add(new wi(.5)),this.onAfterAddedToScene(),r&&lO(),sM&&console.warn("Added shadow component",this.shadowComponent)}setShadowComponentOwner(t){if(t&&(t[ts]===void 0||t[ts]===this)&&(t[ts]=this,t.children))for(const i of t.children)this.setShadowComponentOwner(i)}traverseOwnedShadowComponents(t,i,n){if(t&&t[ts]===i){n(t);for(const o of t.children)this.traverseOwnedShadowComponents(o,i,n)}}removeShadowComponent(){this.shadowComponent&&this.shadowComponent.removeFromParent()}onAfterAddedToScene(){}setInteractable(t){this.shadowComponent&&(this.shadowComponent.interactable=t)}}class Wc extends ls{awake(){super.awake()}}class Wl{constructor(t,i){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=i,this.input=t,this.button=i.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 t=new Wl(this.input,this.event);return Object.assign(t,this),t}Use(){this.use()}StopPropagation(){this.event.stopImmediatePropagation()}}function Tu(s,t){return P.foreachComponent(s,i=>{if(!i.enabled)return;const n=i;if(t)switch(t){case"pointerdown":if(n.onPointerDown)return!0;break;case"pointerup":if(n.onPointerUp||n.onPointerClick)return!0;break;case"pointermove":if(n.onPointerEnter||n.onPointerExit||n.onPointerMove)return!0;break}else if(n.onPointerDown||n.onPointerUp||n.onPointerEnter||n.onPointerExit||n.onPointerClick)return!0},!1)===!0}const En=new Array;class Gs{constructor(t,i,n,o){a(this,"enabled",!0),a(this,"target"),a(this,"methodName"),a(this,"arguments"),this.target=t,this.methodName=i||null,this.arguments=n,o!=null&&(this.enabled=o)}get canClone(){return this.target instanceof Object}invoke(...t){if(this.enabled!==!1){if(typeof this.target=="function")this.arguments?(En.length=0,t!==void 0&&t.length>0&&En.push(...t),En.push(...this.arguments),this.target(...this.arguments),En.length=0):this.target(...t);else if(this.methodName!=null){const i=this.target[this.methodName];typeof i=="function"?this.arguments?(En.length=0,t!==void 0&&t.length>0&&En.push(...t),En.push(...this.arguments),i.call(this.target,...En),En.length=0):i.call(this.target,...t):this.arguments?this.target[this.methodName]=this.arguments[0]||t[0]:this.target[this.methodName]=t[0]}}}}const nM=s=>/^[A-Z]*$/.test(s);class Eu extends Event{constructor(){super(...arguments),a(this,"args")}}class _e{constructor(t){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(t))for(const i of t)i instanceof Gs?this.methods.push(i):typeof i=="function"&&this.methods.push(new Gs(i));else typeof t=="function"&&this.methods.push(new Gs(t))}__internalOnInstantiate(t){var i;const n=new Array;for(let o=0;o<this.methods.length;o++){const r=this.methods[o];if(!(r.target instanceof Function)){const l=r.target;let c=l?.uuid;if(l&&(c=l.guid),c){const h=t[c];if(h){const d=(i=r.arguments)==null?void 0:i.map(u=>u instanceof Object&&u.uuid?t[u.uuid]:u!=null&&u.isComponent?t[u.guid]:u);n.push(new Gs(h.clone,r.methodName,d,r.enabled))}else F()&&console.warn("Could not find target for event listener")}}}return new _e(n)}setEventTarget(t,i){if(this.key=t,this.target=i,this.key!==void 0){let n="",o=!1;for(const r of this.key)o&&nM(r)&&(n+="-"),o=!0,n+=r.toLowerCase();this.key=n}}get listenerCount(){var t;return((t=this.methods)==null?void 0:t.length)??0}get isInvoking(){return this._isInvoking}static from(...t){return new _e(t)}invoke(...t){var i;if(this._isInvoking)return console.warn("Circular event invocation detected. Please check your event listeners for circular references.",this),!1;if(((i=this.methods)==null?void 0:i.length)<=0)return!1;this._isInvoking=!0;try{this._methodsCopy.length=0,this._methodsCopy.push(...this.methods);for(const n of this._methodsCopy)n.invoke(...t);if(typeof this.target=="object"&&typeof this.key=="string"){const n=this.target.dispatchEvent;if(typeof n=="function"){const o=new Eu(this.key);o.args=t,n.call(this.target,o)}}}finally{this._isInvoking=!1,this._methodsCopy.length=0}return!0}addEventListener(t){return this.methods.push(new Gs(t)),t}removeEventListener(t){if(t)for(let i=this.methods.length-1;i>=0;i--)this.methods[i].target===t&&(this.methods[i].enabled=!1,this.methods.splice(i,1))}removeAllEventListeners(){this.methods.length=0}}class oM extends Zi{constructor(){super([re,Se],"ColorSerializer")}onDeserialize(t){if(t!=null)return t.a!==void 0?new Se(t.r,t.g,t.b,t.a):t.alpha!==void 0?new Se(t.r,t.g,t.b,t.alpha):new re(t.r,t.g,t.b)}onSerialize(t){if(t!=null)return t.a!==void 0?{r:t.r,g:t.g,b:t.b,a:t.a}:{r:t.r,g:t.g,b:t.b}}}const rM=new oM;class aM extends Zi{constructor(){super([Ut],"EulerSerializer")}onDeserialize(t,i){if(t!=null){if(t.order)return new Ut(t.x,t.y,t.z,t.order);if(t.x!=null)return new Ut(t.x,t.y,t.z)}}onSerialize(t,i){return{x:t.x,y:t.y,z:t.z,order:t.order}}}const lM=new aM;class cM extends Zi{constructor(){super(I,"ObjectSerializer")}onSerialize(t,i){if(i.objectToNode!==void 0&&t.uuid){const n=i.objectToNode[t.uuid];return vt&&console.log(n,t.name,t.uuid),{node:n}}}onDeserialize(t,i){var n,o,r;if(typeof t=="string"){if(t.endsWith(".glb")||t.endsWith(".gltf")){if(i.serializable instanceof Array&&i.serializable.includes(ae))return;F()&&xe("Detected wrong usage of @serializable with Object3D or GameObject. Instead you should use AssetReference here! Please see the console for details.");const l=(o=(n=i.target)==null?void 0:n.constructor)==null?void 0:o.name;console.warn(`Wrong usage of @serializable detected in your script "${l}"
909
909
 
910
910
  It looks like you used @serializable(Object3D) or @serializable(GameObject) for a prefab or scene reference which is exported to a separate glTF file.
911
911
 
@@ -922,7 +922,7 @@ Using the assigned clip instead:`,this.clip),s=this.clip);let o=!this.sound||s&&
922
922
  Audio:`,r.getAudioTracks(),`
923
923
  Video:`,r.getVideoTracks()),this._stream=r,n==="incoming"){const l=new Nw(t,r,this);this.dispatchEvent(l)}}),i.on("close",()=>{this.dispatchEvent(new Sf(t,n))})}get stream(){return this._stream}close(){this._isDisposed||(this._isDisposed=!0,this.call.close(),Ks(this._stream))}get isOpen(){var t;return((t=this.call.peerConnection)==null?void 0:t.connectionState)==="connected"}get isOpening(){var t;return((t=this.call.peerConnection)==null?void 0:t.connectionState)==="connecting"}get isClosed(){return!this.isOpen||this._isDisposed}}function Vw(s){return s=s.replace("a=fmtp:111 minptime=10;useinbandfec=1","a=fmtp:111 ptime=5;useinbandfec=1;stereo=1;maxplaybackrate=48000;maxaveragebitrat=128000;sprop-stereo=1"),s}const qc=class extends fm{constructor(s,t){super(),a(this,"updateCalls",()=>{var i;for(let n=this._incomingCalls.length-1;n>=0;n--){const o=this._incomingCalls[n];o.isClosed&&!o.isOpening&&this._incomingCalls.splice(n,1)}for(let n=this._outgoingCalls.length-1;n>=0;n--){const o=this._outgoingCalls[n];let r=!1;o.isClosed&&!o.isOpening&&((i=o.stream)!=null&&i.active?nt&&console.warn("!!! Stream is still active, don't remove call",o.userId,"Your id: "+this.context.connection.connectionId):(nt&&console.warn("!!! Remove closed call",o.userId),r=!0)),this.context.connection.userIsInRoom(o.userId)===!1&&(nt&&console.warn("!!! User is not in room anymore, remove call",o.userId),r=!0),r&&(o.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",i=>{if(nt&&console.log("PEER opened as",i),i===null){console.error("Peer connection failed",i);return}this.context.connection.send("peer-user-connected",new EM(this,i))}),a(this,"onPeerClose",()=>{nt&&console.log("PEER closed"),this.updateCalls()}),a(this,"onPeerDisconnected",()=>{nt&&console.log("PEER disconnected"),this.updateCalls()}),a(this,"onPeerError",i=>{nt&&console.error("PEER error",i)}),a(this,"onPeerReceivingCall",i=>{i.answer(void 0,{sdpTransform:n=>Vw(n)}),this.registerCall(i,"incoming",null)}),this.context=s,this.id=t,this.setupPeer(),navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia}static getOrCreate(s,t){if(qc.instances.has(t))return qc.instances.get(t);const i=new qc(s,t);return qc.instances.set(t,i),i}getMyPeerId(){if(this.context.connection.connectionId)return this.getPeerIdFromUserId(this.context.connection.connectionId)}getPeerIdFromUserId(s){return this.id+"-"+s}getUserIdFromPeerId(s){return s.substring(this.id.length+1)}makeCall(s,t){var i;if(!(t!=null&&t.id)){nt?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:r=>Vw(r)},o=(i=this._peer)==null?void 0:i.call(s,t,n);if(o){const r=this.registerCall(o,"outgoing",t);return nt&&console.warn(`\u{1F4DE} CALL ${s}`,`
924
924
  Outgoing:`,this._outgoingCalls,`
925
- Incoming:`,this._incomingCalls),r}else nt&&console.error("Failed to make call",s,t,this._peer)}closeAll(){for(const s of this._incomingCalls)s.close();for(const s of this._outgoingCalls)s.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 s=this.getMyPeerId();s?this._peer=Ob(s):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(s,t,i){const n=s.metadata;(!n||!n.userId)&&console.error("Missing call metadata",s);const o=n.userId;t==="incoming"&&nt?console.warn("\u2190 Receive call from",s.metadata,s.connectionId):nt&&console.warn("\u2192 Make call to",s.metadata);const r=t==="incoming"?this._incomingCalls:this._outgoingCalls,l=new AM(o,s,t,i);return r.push(l),s.on("error",c=>{console.error("Call error",c)}),s.on("close",()=>{nt&&console.log("Call ended",s.metadata);const c=r.indexOf(l);c!==-1&&r.splice(c,1),l.close(),this.dispatchEvent(new Sf(o,t))}),l.addEventListener("call-ended",c=>{this.dispatchEvent(c)}),t==="incoming"&&(l.addEventListener("receive-stream",c=>{this.dispatchEvent(c)}),s.on("stream",()=>{nt&&console.log("Received stream for call",s.metadata);let c=0;const h=setInterval(()=>{const d=c===0;!l.isOpen&&d&&(nt&&console.warn("Close call because stream is not active",s.metadata),c+=1,clearInterval(h),l.close())},2e3)})),l}};let Gc=qc;a(Gc,"instances",new Map);class cd extends fm{constructor(t,i){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",n=>{this._sendingStreams.size>0&&(this.debug&&console.warn(`${n!=null&&n.userId?`User ${n.userId}`:"You"} joined room`,n,this._sendingStreams.size),this.updateSendingCalls())}),a(this,"onLeftRoom",n=>{this.debug&&console.warn(`${n?.userId||"You"} left room`,n),this.stopCallsToUsersThatAreNotInTheRoomAnymore(),this.peer.closeAll()}),a(this,"onCallStreamReceived",n=>{this.debug&&console.log("Call with "+n.userId+" started"),this.dispatchEvent({type:"receive-stream",target:this,stream:n.stream,userId:n.userId}),this.debug&&this.debugLogCurrentState()}),a(this,"onCallEnded",n=>{this.debug&&console.log("Call with "+n.userId+" ended"),this.dispatchEvent(n),this.debug&&this.debugLogCurrentState()}),a(this,"onUserConnected",n=>{if(this.peer.id===n.guid){this.debug&&console.log("PEER USER CONNECTED",n.guid,n,this._sendingStreams.size);const o=this._sendingStreams.keys().next().value;this.peer.makeCall(n.peerId,o)}else nt&&console.log("Unknown user connected",n.guid,n.peerId)}),a(this,"onUserLeft",n=>{this.debug&&console.log("User left room: "+n.userId),this.stopCallsToUsersThatAreNotInTheRoomAnymore()}),Bw(t)){const n=t;t=n.context,i=Gc.getOrCreate(n.context,n.guid)}else typeof i=="string"&&(i=Gc.getOrCreate(t,i));if(t){if(!(t 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(!i)throw new Error("Failed to create NetworkedStreams because peer is undefined");this.context=t,this.peer=i,nt&&(this.debug=!0)}static create(t,i){const n=Gc.getOrCreate(t.context,i||t.context.connection.connectionId||t.guid);return new cd(t.context,n)}startSendingStream(t){this._sendingStreams.has(t)?console.warn("Received start sending stream with stream that is already being sent"):(this._sendingStreams.set(t,[]),this.updateSendingCalls())}stopSendingStream(t){if(t){const i=this._sendingStreams.get(t);if(i){for(const n of i)n.close();i.length=0}this._sendingStreams.delete(t),i&&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 t=this.context.connection.connectionId;for(const i of this._sendingStreams.keys()){const n=this._sendingStreams.get(i)||[];for(const o of this.context.connection.usersInRoom()){if(o===t)continue;const r=this.peer.getPeerIdFromUserId(o);if(n.find(l=>{var c;return l.peerId===r&&l.direction==="outgoing"&&!l.isClosed&&((c=l.stream)==null?void 0:c.active)}))nt&&console.debug("Already have a call with user "+o+" / peer "+r);else{const l=this.peer.makeCall(r,i);l&&n.push(l)}}this._sendingStreams.set(i,n)}this.stopCallsToUsersThatAreNotInTheRoomAnymore()}stopCallsToUsersThatAreNotInTheRoomAnymore(){for(const t of this._sendingStreams.keys()){const i=this._sendingStreams.get(t);if(i)for(let n=i.length-1;n>=0;n--){const o=i[n];this.context.connection.userIsInRoom(o.userId)?nt&&(this.context.connection.connectionId===o.userId?console.warn(`You are still in the room [${n}] ${o.userId}`):console.log(`User is still in room [${n}] ${o.userId}`)):(nt&&console.log(`Remove call ${[n]} to user that is not in room anymore ${o.userId}`),o.close(),i.splice(n,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(t=>t.userId).join(", ")})`,this.peer.incomingCalls)}}function Ks(s){if(s&&s instanceof MediaStream)for(const t of s.getTracks())t.stop()}var IM=Object.defineProperty,jM=Object.getOwnPropertyDescriptor,Cf=(s,t,i,n)=>{for(var o=n>1?void 0:n?jM(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&IM(t,i,o),o};const LM="noVoip",DM=O("debugvoip");class Ao extends A{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 t of this._incomingStreams.values())Ks(t.srcObject);this._incomingStreams.clear()}),a(this,"_incomingStreams",new Map),a(this,"onReceiveStream",t=>{const i=t.target.userId,n=t.stream;let o=this._incomingStreams.get(i);o||(o=new Audio,this._incomingStreams.set(i,o)),o.srcObject=n,o.setAttribute("autoplay","true"),Rn.registerWaitForInteraction(()=>{o?.play().catch(r=>{console.error("VOIP: Failed to play audio",r)})})}),a(this,"onStreamEnded",t=>{const i=this._incomingStreams.get(t.userId);Ks(i?.srcObject),this._incomingStreams.delete(t.userId)}),a(this,"onEnabledChanged",()=>{for(const t of this._incomingStreams){const i=t[1];i.muted=!this.enabled}}),a(this,"onVisibilityChanged",()=>{if(this.runInBackground)return;const t=document.visibilityState!=="visible";this.setMuted(t);for(const i of this._incomingStreams){const n=i[1];n.muted=t}})}awake(){DM&&(this.debug=!0),this.debug&&(console.log("VOIP debugging: press 'v' to toggle mute or 'c' to toggle connect/disconnect"),window.addEventListener("keydown",async t=>{switch(t.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=cd.create(this)),this.debug&&(this._net.debug=!0),this._net.addEventListener(Ys.StreamReceived,this.onReceiveStream),this._net.addEventListener(Ys.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 t;this._net&&(this._net.stopSendingStream(this._outputStream),this._net.removeEventListener(Ys.StreamReceived,this.onReceiveStream),this._net.removeEventListener(Ys.StreamEnded,this.onStreamEnded),(t=this._net)==null||t.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 t;(t=this._menubutton)==null||t.remove(),this._menubutton=void 0}get isSending(){return this._outputStream!=null&&this._outputStream.active}async connect(t){var i,n;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 X.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,(i=this._net)==null||i.stopSendingStream(this._outputStream),Ks(this._outputStream),this._outputStream=await this.getAudioStream(t),this._outputStream?(this.debug&&console.log("VOIP: Got audio stream"),(n=this._net)==null||n.startSendingStream(this._outputStream),this.updateButton(),!0):(this.updateButton(),await X.microphonePermissionsGranted()?console.error("VOIP: Could not get audio stream - please make sure to connect an audio device and grant microphone permissions"):ac("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(t){var i;t!=null&&t.remember&&(this._allowSending=!1),(i=this._net)==null||i.stopSendingStream(this._outputStream),Ks(this._outputStream),this._outputStream=null,this.updateButton()}setMuted(t){var i;const n=(i=this._outputStream)==null?void 0:i.getAudioTracks();if(n)for(const o of n)o.enabled=!t}get isMuted(){var t;if(this._outputStream===null)return!1;const i=(t=this._outputStream)==null?void 0:t.getAudioTracks();if(i){for(const n of i)if(!n.enabled)return!0}return!1}async updateButton(){var t;if(this.createMenuButton){if(this._menubutton||(this._menubutton=document.createElement("button"),this._menubutton.addEventListener("click",()=>{this.isSending?this.disconnect({remember:!0}):this.connect(),X.microphonePermissionsGranted().then(i=>{i||xe("<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 i=(this.isSending,""),n=this.isSending?"mic":"mic_off";await X.microphonePermissionsGranted()||(i="No Permission",n="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=i,this._menubutton.prepend(Pt(n)),this.context.connection.isConnected==!1?this._menubutton.setAttribute("disabled",""):this._menubutton.removeAttribute("disabled")}}else this.activeAndEnabled||(t=this._menubutton)==null||t.remove()}getFrequency(t){return this.unsupported_getfrequency||(this.unsupported_getfrequency=!0,F()&&xe("VOIP: getFrequency is currently not supported"),console.warn("VOIP: getFrequency is currently not supported")),null}async getAudioStream(t){if(!navigator.mediaDevices.getUserMedia)return console.error("No getDisplayMedia support"),null;const i=async o=>await navigator.mediaDevices.getUserMedia({audio:o??!0,video:!1}).catch(r=>(console.warn("VOIP failed getting audio stream",r),null)),n=await i(t);if(!n)return null;if(X.isiOS()&&t?.deviceId===void 0){const o=(await navigator.mediaDevices.enumerateDevices()).find(r=>(r.kind==="audioinput"||r.kind==="audiooutput")&&!r.label.includes("iPhone"));if(o){const r=Object.assign({},t);return r.deviceId=o.deviceId,await i(r)}}return n}}Cf([m()],Ao.prototype,"autoConnect",2),Cf([m()],Ao.prototype,"runInBackground",2),Cf([m()],Ao.prototype,"createMenuButton",2);var BM=Object.defineProperty,FM=Object.getOwnPropertyDescriptor,Hw=(s,t,i,n)=>{for(var o=n>1?void 0:n?FM(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&BM(t,i,o),o};const zM=O("debugmouth");class Xc extends A{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(Ao,this.context),this.marker||(this.marker=P.getComponentInParent(this.gameObject,Rt))},3e3)}update(){var t;if(!this.voip||this.context.time.frameCount%10!==0)return;let i=((t=this.marker)==null?void 0:t.connectionId)??null;if(!i){zM&&(i=null);return}const n=this.voip.getFrequency(i)??0;this.updateLips(n)}updateLips(t){if(this.context.time.time-this.lastMouthChangeTime>this.mouthChangeLength){if(this.mouthChangeLength=.05+Math.random()*.1,this.talking&&this.talking.length>0&&t>30){this.lastMouthChangeTime=this.context.time.time;const i=Math.floor(Math.random()*this.talking.length);this.setMouthShapeActive(this.talking,i)}else if(this.idle.length>0&&this.context.time.time-this.lastMouthChangeTime>.5){this.lastMouthChangeTime=this.context.time.time;const i=Math.floor(Math.random()*this.idle.length);this.setMouthShapeActive(this.idle,i)}}}setMouthShapeActive(t,i){if(t){t!=this.idle?this.idle.map(n=>n.visible=!1):this.talking.map(n=>n.visible=!1);for(let n=0;n<t.length;n++){const o=t[n];o&&(o.visible=n===i)}}}}Hw([m(I)],Xc.prototype,"idle",2),Hw([m(I)],Xc.prototype,"talking",2);class Of extends A{constructor(){super(...arguments),a(this,"voip",null),a(this,"marker",null),a(this,"_startPosition",null)}awake(){this.voip=P.findObjectOfType(Ao,this.context),this.marker=P.getComponentInParent(this.gameObject,Rt)}update(){if(!this.voip||!this.marker||this.context.time.frameCount%10!==0)return;const t=this.marker.connectionId,i=this.voip.getFrequency(t);if(i==null)return;this._startPosition||(this._startPosition=this.gameObject.position.clone());const n=i/100;this.gameObject.position.y=this._startPosition.y+n*.07}}var UM=Object.defineProperty,NM=Object.getOwnPropertyDescriptor,WM=(s,t,i,n)=>{for(var o=n>1?void 0:n?NM(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&UM(t,i,o),o};const Za=O("debugxrflags"),$w=O("disablexrflags");$w&&console.warn("XRFlags are disabled");var Zs=(s=>(s[s.Never=0]="Never",s[s.Browser=1]="Browser",s[s.AR=2]="AR",s[s.VR=4]="VR",s[s.FirstPerson=8]="FirstPerson",s[s.ThirdPerson=16]="ThirdPerson",s[s.All=4294967295]="All",s))(Zs||{});const qw=class{constructor(){a(this,"Mask",17)}Has(s){return(this.Mask&s)!==0}Set(s){Za&&console.warn("Set XR flag state to",s),this.Mask=s,Ai.Apply()}Enable(s){this.Mask|=s,Ai.Apply()}Disable(s){this.Mask&=~s,Ai.Apply()}Toggle(s){this.Mask^=s,Ai.Apply()}EnableAll(){this.Mask=-1,Ai.Apply()}DisableAll(){this.Mask=0,Ai.Apply()}};let Kt=qw;a(Kt,"Global",new qw);var Qc;const An=(Qc=class extends A{constructor(){super(...arguments),a(this,"visibleIn")}static Apply(){for(const s of this.registry)s.UpdateVisible(Kt.Global)}awake(){An.registry.push(this)}onEnable(){An.firstApply?this.UpdateVisible(Kt.Global):(An.firstApply=!0,An.Apply())}onDestroy(){const s=An.registry.indexOf(this);s>=0&&An.registry.splice(s,1)}get isOn(){return this.gameObject.visible}UpdateVisible(s=null){if($w)return;let t;const i=s;if(i&&typeof i=="number"&&(console.assert(typeof i=="number","XRFlag.UpdateVisible: state must be a number",i),Za&&console.log(i),An.buffer.Mask=i,s=An.buffer),s instanceof Kt?(Za&&console.warn(this.name,"use passed in mask",s.Mask,this.visibleIn),t=s.Has(this.visibleIn)):(Za&&console.log(this.name,"use global mask"),Kt.Global.Has(this.visibleIn)),t!==void 0)if(t)Za&&console.log(this.name,"is visible",this.gameObject.uuid),P.setActive(this.gameObject,!0);else{if(Za&&console.log(this.name,"is not visible",this.gameObject.uuid),!this.gameObject.visible)return;this.gameObject.visible=!1}}},a(Qc,"registry",[]),a(Qc,"firstApply"),a(Qc,"buffer",new Kt),Qc);let Ai=An;WM([m()],Ai.prototype,"visibleIn",2);var VM=Object.defineProperty,HM=Object.getOwnPropertyDescriptor,Nu=(s,t,i,n)=>{for(var o=n>1?void 0:n?HM(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&VM(t,i,o),o};class zr extends A{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,Ai)}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 t of this.eyes)t&&(t.visible=this.eyesOpen)}}}Nu([m(I)],zr.prototype,"eyes",2),Nu([m()],zr.prototype,"lastBlinkTime",2),Nu([m()],zr.prototype,"blinkLength",2),Nu([m()],zr.prototype,"eyesOpen",2);var $M=Object.defineProperty,qM=Object.getOwnPropertyDescriptor,Pf=(s,t,i,n)=>{for(var o=n>1?void 0:n?qM(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&$M(t,i,o),o},kf;const Gw=(kf=class extends A{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,$c)),this.brain||(this.brain=P.addComponent(this.gameObject,$c)),this.brain&&this.target&&(this.brain.controlledTarget=this.target)}update(){const s=this.target;if(s&&this.head){const t=this.eyes;if(t){const i=te(s);this.currentTargetPoint.lerp(i,this.context.time.deltaTime/.1);const n=te(this.head),o=this.vec.copy(this.currentTargetPoint).sub(n).normalize();if(o.length()<.1)return;const r=Gw.forward;if(r.set(0,0,1),r.applyQuaternion(Oe(this.head)),r.dot(o)>.45)for(let l=0;l<t.length;l++)t[l].lookAt(this.currentTargetPoint)}}}},a(kf,"forward",new x(0,0,1)),kf);let Ja=Gw;Pf([m(I)],Ja.prototype,"head",2),Pf([m(I)],Ja.prototype,"eyes",2),Pf([m(I)],Ja.prototype,"target",2);const Yc=O("debugavatar");class Wu{constructor(t,i,n,o){a(this,"root"),a(this,"head"),a(this,"leftHand"),a(this,"rigthHand");var r;this.root=t,this.head=i,this.leftHand=n,this.rigthHand=o,(r=this.root)==null||r.traverse(l=>l.layers.set(2))}get isValid(){return this.head!==null&&this.head!==void 0}}class Mf{constructor(){a(this,"avatarRegistryUrl",null)}async getOrCreateNewAvatarInstance(t,i){if(!i)return console.error("Can not create avatar: failed to provide id or root object"),null;let n=null;if(typeof i=="string"){if(n=await this.loadAvatar(t,i),!n){const r=new Ds;n=P.instantiate(Ca(i,t.scene),r)}}else n=i;if(!n)return null;const o=this.findAvatar(n);return o.isValid?(Yc&&console.log("[Custom Avatar] valid config",i,Yc?o:""),o):(console.warn("[Custom Avatar] config isn't valid",i,Yc?o:""),null)}async loadAvatar(t,i){if(console.assert(i!=null&&typeof i=="string","Avatar id must not be null"),i.length<=0||!i)return null;if(Yc&&console.log("[Custom Avatar] "+i+", loading..."),i.endsWith(".glb")||(i+=".glb"),this.avatarRegistryUrl===null){const o=await fetch("./"+i);let r=null;if(o.ok){const c=await o.blob();c&&(r=await c.arrayBuffer())}if(!r)return null;const l=await fs().parseSync(t,r,null,0);return l?.scene??null}const n=new gr;return Su(n,t),new Promise((o,r)=>{const l=this.avatarRegistryUrl+"/"+i;n.load(l,async c=>{await fs().createBuiltinComponents(t,l,c,null,void 0),o(c.scene)},c=>{Yc&&console.log("[Custom Avatar] "+c.loaded/c.total*100+"% loaded of "+c.total/1024+"kB")},c=>{console.error("[Custom Avatar] Error when loading: "+c),o(null)})})}cacheModel(t,i){}findAvatar(t){const i=t;let n=i;n.children.length==1&&(n=t.children[0]);let o=this.findAvatarPart(n,["head"]);const r=this.findAvatarPart(n,["left","hand"]),l=this.findAvatarPart(n,["right","hand"]);if(!o){o=i;const c=new x;new _i().setFromObject(o).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&&o.scale.multiplyScalar(1/h*.3)}return new Wu(i,o,r,l)}findAvatarPart(t,i){const n=t.name.toLowerCase();let o=!0;for(const r of i){if(!o)break;n.indexOf(r)===-1&&(o=!1)}if(o)return t;if(t.children)for(const r of t.children){const l=this.findAvatarPart(r,i);if(l)return l}return null}handleCustomAvatarErrors(t){if(!t.ok)throw Error(t.statusText);return t}}var GM=Object.defineProperty,XM=Object.getOwnPropertyDescriptor,Rf=(s,t,i,n)=>{for(var o=n>1?void 0:n?XM(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&GM(t,i,o),o};class el extends A{constructor(){super(...arguments),a(this,"length",1),a(this,"depthTest",!0),a(this,"isGizmo",!1),a(this,"_axes",null)}onEnable(){if(this.isGizmo&&!Sc)return;this._axes||(this._axes=new wi(this.length)),this._axes.layers.disableAll(),this._axes.layers.set(this.layer),this.gameObject.add(this._axes);const t=this._axes.material;t&&t.depthTest!==void 0&&(t.depthTest=this.depthTest)}onDisable(){this._axes&&this.gameObject.remove(this._axes)}}Rf([m()],el.prototype,"length",2),Rf([m()],el.prototype,"depthTest",2),Rf([m()],el.prototype,"isGizmo",2);class Tf extends A{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 t=te(this.to).clone(),i=te(this.from).clone(),n=t.distanceTo(i),o=t.clone();o.sub(i);const r=i.clone();r.add(t),r.multiplyScalar(.5);const l=te(this.hint).clone();l.sub(r);const c=new x;c.crossVectors(l,o),c.crossVectors(o,c),c.normalize();const h=n*.5,d=Math.max(this.desiredDistance,h),u=Math.sqrt(d*d-h*h),p=c.clone();p.multiplyScalar(u),p.add(r),dt(this.gameObject,p);const g=r.clone();g.sub(c),this.gameObject.lookAt(g)}}const QM=O("gizmos"),YM=O("debugboxhelper"),Js=class extends A{constructor(){super(...arguments),a(this,"box",null),a(this,"_lastMatrixUpdateFrame",-1),a(this,"_helper",null),a(this,"_color",null)}isInBox(s){var t;if(!s)return;if(this.box||(this.box=new _i),ci([s],void 0,void 0,Js.testBox),Js.testBox.isEmpty()){const n=te(s,Js._position);Js.testBox.setFromCenterAndSize(n,Js._emptyObjectSize)}this.updateBox();const i=(t=this.box)==null?void 0:t.intersectsBox(Js.testBox);return i&&YM&&q.DrawWireBox3(Js.testBox,16711680,5),i}intersects(s){return s?this.updateBox(!1).intersectsBox(s):!1}updateBox(s=!1){if(this.box||(this.box=new _i),s||this.context.time.frameCount!=this._lastMatrixUpdateFrame){const t=this._lastMatrixUpdateFrame<0;this._lastMatrixUpdateFrame=this.context.time.frameCount;const i=t,n=te(this.gameObject,Js._position,i),o=Je(this.gameObject,Js._size);this.box.setFromCenterAndSize(n,o)}return this.box}awake(){this._helper=null,this._color=null,this.box=null}showHelper(s=null,t=!1){var i;if(!(!QM&&!t)){if(this._helper){s&&((i=this._color)==null||i.set(s)),this.gameObject.add(this._helper);return}this._helper=_g(s),this.gameObject.add(this._helper)}}};let is=Js;a(is,"testBox",new _i),a(is,"_position",new x),a(is,"_size",new x(.01,.01,.01)),a(is,"_emptyObjectSize",new x(.01,.01,.01));var KM=Object.defineProperty,ZM=Object.getOwnPropertyDescriptor,ui=(s,t,i,n)=>{for(var o=n>1?void 0:n?ZM(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&KM(t,i,o),o};class pi extends A{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 t;(t=this.context.physics.engine)==null||t.updateProperties(this)})}get isCollider(){return!0}awake(){super.awake(),this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(ve))}start(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(ve))}onEnable(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(ve))}onDisable(){var t;(t=this.context.physics.engine)==null||t.removeBody(this)}get body(){var t;return(t=this.context.physics.engine)==null?void 0:t.getBody(this)}updatePhysicsMaterial(){var t;(t=this.context.physics.engine)==null||t.updatePhysicsMaterial(this)}}ui([m(ve)],pi.prototype,"attachedRigidbody",2),ui([m()],pi.prototype,"isTrigger",2),ui([m()],pi.prototype,"sharedMaterial",2),ui([m()],pi.prototype,"membership",2),ui([m()],pi.prototype,"filter",2);class tl extends pi{constructor(){super(...arguments),a(this,"radius",.5),a(this,"center",new x(0,0,0))}onEnable(){var t;super.onEnable(),(t=this.context.physics.engine)==null||t.addSphereCollider(this),_d(this.gameObject.scale,this.updateProperties)}onDisable(){super.onDisable(),Am(this.gameObject.scale,this.updateProperties)}onValidate(){this.updateProperties()}}ui([Mt(),m()],tl.prototype,"radius",2),ui([m(x)],tl.prototype,"center",2);const Xw=class extends pi{constructor(){super(...arguments),a(this,"size",new x(1,1,1)),a(this,"center",new x(0,0,0))}static add(s,t){const i=Mi(s,Xw);return i.autoFit(),t?.rigidbody===!0&&Mi(s,ve,{isKinematic:!1}),i}onEnable(){var s;super.onEnable(),(s=this.context.physics.engine)==null||s.addBoxCollider(this,this.size),_d(this.gameObject.scale,this.updateProperties)}onDisable(){super.onDisable(),Am(this.gameObject.scale,this.updateProperties)}onValidate(){this.updateProperties()}autoFit(s){const t=this.gameObject,i=t.position.clone(),n=t.quaternion.clone(),o=t.scale.clone(),r=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 l=ci([t]);t.position.copy(i),t.quaternion.copy(n),t.scale.copy(o),t.parent=r,s?.debug===!0&&q.DrawWireBox3(l,16768256,20),this.size=l.getSize(new x)||new x(1,1,1),this.center=l.getCenter(new x)||new x(0,0,0),this.size.length()<=0&&this.size.set(.01,.01,.01)}};let il=Xw;ui([Mt(),m(x)],il.prototype,"size",2),ui([m(x)],il.prototype,"center",2);class Io extends pi{constructor(){super(...arguments),a(this,"sharedMesh"),a(this,"convex",!1)}onEnable(){var t,i,n;if(super.onEnable(),!this.context.physics.engine)return;(t=this.sharedMesh)!=null&&t.isMesh||(this.gameObject instanceof K||this.gameObject instanceof ro)&&(this.sharedMesh=this.gameObject);const o=0;if((i=this.sharedMesh)!=null&&i.isMesh)this.context.physics.engine.addMeshCollider(this,this.sharedMesh,this.convex),it.assignMeshLOD(this.sharedMesh,o).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 "${((n=this.sharedMesh)==null?void 0:n.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(it.assignMeshLOD(h,o)))}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 K;for(const p of c)p&&this.activeAndEnabled&&(u.geometry=p,(d=this.context.physics.engine)==null||d.addMeshCollider(this,u,this.convex))})}else console.warn("A MeshCollider mesh is assigned, but it's neither a Mesh nor a Group. Please report a bug!",this,this.sharedMesh)}}}ui([m(K)],Io.prototype,"sharedMesh",2),ui([m()],Io.prototype,"convex",2);class In extends pi{constructor(){super(...arguments),a(this,"center",new x(0,0,0)),a(this,"radius",.5),a(this,"height",2)}onEnable(){var t;super.onEnable(),(t=this.context.physics.engine)==null||t.addCapsuleCollider(this,this.height,this.radius)}}ui([m(x)],In.prototype,"center",2),ui([m()],In.prototype,"radius",2),ui([m()],In.prototype,"height",2);var JM=Object.defineProperty,eR=Object.getOwnPropertyDescriptor,jn=(s,t,i,n)=>{for(var o=n>1?void 0:n?eR(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&JM(t,i,o),o};const Qw=O("debugcharactercontroller");class Ur extends A{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(ve),this._rigidbody||(this._rigidbody=this.gameObject.addComponent(ve)),this.rigidbody)}awake(){this._activeGroundCollisions=new Set}onEnable(){const t=this.rigidbody;let i=this.gameObject.getComponent(In);i||(i=this.gameObject.addComponent(In)),i.center.copy(this.center),i.radius=this.radius,i.height=this.height;const n=new x(0,0,1),o=new x(1,0,0),r=new x(0,1,0),l=this.gameObject.getWorldDirection(new x);l.y=0;const c=o.dot(l)<0?-1:1,h=n.angleTo(l)*c;this.gameObject.setRotationFromAxisAngle(r,h),t.lockRotationX=!0,t.lockRotationY=!0,t.lockRotationZ=!0}move(t){this.gameObject.position.add(t)}onCollisionEnter(t){(t.contacts.length==0||t.contacts.some(i=>i.normal.y>.2))&&(this._activeGroundCollisions.add(t),Qw&&console.log(`Collision(${this._activeGroundCollisions.size}): ${t.contacts.map(i=>i.normal.y.toFixed(2)).join(", ")} - ${this.isGrounded}`))}onCollisionExit(t){this._activeGroundCollisions.delete(t),Qw&&console.log(`Collision(${this._activeGroundCollisions.size}) - ${this.isGrounded}`)}get isGrounded(){return this._activeGroundCollisions.size>0}get contactVelocity(){var t;this._contactVelocity.set(0,0,0);for(const i of this._activeGroundCollisions){const n=(t=this.context.physics.engine)==null?void 0:t.getLinearVelocity(i.collider);n&&(this._contactVelocity.x+=n.x,this._contactVelocity.y+=n.y,this._contactVelocity.z+=n.z)}return this._contactVelocity}}jn([m(x)],Ur.prototype,"center",2),jn([m()],Ur.prototype,"radius",2),jn([m()],Ur.prototype,"height",2);class Ln extends A{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 oe(0,0)),a(this,"moveInput",new oe(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 Ws)}awake(){this._currentRotation=new V}update(){const t=this.context.input;t.isKeyPressed("KeyW")?this.moveInput.y+=1:t.isKeyPressed("KeyS")&&(this.moveInput.y-=1),t.isKeyPressed("KeyD")?this.lookInput.x+=1:t.isKeyPressed("KeyA")&&(this.lookInput.x-=1),this.jumpInput||(this.jumpInput=t.isKeyDown("Space"))}move(t){this.moveInput.add(t)}look(t){this.lookInput.add(t)}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(t,i,n){var o,r,l,c,h,d,u,p,g,y,f;if((o=this.controller)!=null&&o.isGrounded&&(this._jumpCount=0,this.doubleJumpForce>0&&((r=this.animator)==null||r.setBool("doubleJump",!1))),this._currentSpeed.z+=t.y*this.movementSpeed*this.context.time.deltaTime,(l=this.animator)==null||l.setBool("running",t.length()>.01),(h=this.animator)==null||h.setBool("jumping",((c=this.controller)==null?void 0:c.isGrounded)===!0&&n),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(-i.x*this.rotationSpeed)*this.context.time.deltaTime,this.lookForward&&Math.abs(this._currentAngularSpeed.y)<.01){const v=this.context.mainCameraComponent.forward;v.y=0,v.normalize(),this._currentRotation.setFromUnitVectors(new x(0,0,1),v),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&&n&&this.jumpForce>0){let v=(d=this.controller)==null?void 0:d.isGrounded;if(this.doubleJumpForce>0&&!((u=this.controller)!=null&&u.isGrounded)&&this._jumpCount===1&&(v=!0,(p=this.animator)==null||p.setBool("doubleJump",!0)),v){this._jumpCount+=1;const b=this.controller.rigidbody,w=this._jumpCount===2?this.doubleJumpForce:this.jumpForce;b.applyImpulse(new x(0,1,0).multiplyScalar(w))}}if(this.controller){const v=(g=this.controller)==null?void 0:g.rigidbody.getVelocity().y;if(v<-1){this._raycastOptions.ray||(this._raycastOptions.ray=new oo),this._raycastOptions.ray.origin.copy(te(this.gameObject)),this._raycastOptions.ray.direction.set(0,-1,0);const b=this.layer;this.gameObject.layers.disableAll(),this.gameObject.layers.set(2);const w=this.context.physics.raycast(this._raycastOptions);this.gameObject.layers.set(b),(w.length&&w[0].distance>2||v<-10)&&((y=this.animator)==null||y.setBool("falling",!0))}else(f=this.animator)==null||f.setBool("falling",!1)}}}jn([m(Ur)],Ln.prototype,"controller",2),jn([m()],Ln.prototype,"movementSpeed",2),jn([m()],Ln.prototype,"rotationSpeed",2),jn([m()],Ln.prototype,"jumpForce",2),jn([m()],Ln.prototype,"doubleJumpForce",2),jn([m(kt)],Ln.prototype,"animator",2);var tR=Object.defineProperty,iR=Object.getOwnPropertyDescriptor,sl=(s,t,i,n)=>{for(var o=n>1?void 0:n?iR(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&tR(t,i,o),o};const Kc=O("debugcontactshadows");kw(s=>{const t=s.domElement.getAttribute("contactshadows");t!=null&&t!="0"&&t!="false"&&ks.auto(s)});var Ef;const Zc=(Ef=class extends A{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,"shadowsRoot",new I),a(this,"shadowCamera"),a(this,"shadowGroup",new ro),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(s){if(s||(s=ee.Current),!s)throw new Error("No context provided and no current context set.");let t=this._instances.get(s);if(!t||t.destroyed){const i=new I;t=Mi(i,Zc,{autoFit:!1,occludeBelowGround:!1}),this._instances.set(s,t)}return s.scene.add(t.gameObject),t.fitShadows(),t}fitShadows(){Kc&&console.warn("Fitting shadows to scene"),Od(this.shadowsRoot,!1);const s=ci(this.context.scene.children,[this.shadowsRoot]),t=Math.max(1,this.blur/32),i=s.max.x-s.min.x,n=s.max.z-s.min.z;s.expandByVector(new x(t*i,0,t*n)),Kc&&q.DrawWireBox3(s,16776960,60),this.gameObject.parent&&s.applyMatrix4(this.gameObject.parent.matrixWorld.clone().invert());const o=s.min,r=Math.max(1e-5,(s.max.y-o.y)*.002);s.max.y+=r,this.shadowsRoot.position.set((o.x+s.max.x)/2,o.y-r,(o.z+s.max.z)/2),this.shadowsRoot.scale.set(s.max.x-o.x,s.max.y-o.y,s.max.z-o.z),this.applyMinSize(),this.shadowsRoot.matrixWorldNeedsUpdate=!0,Kc&&console.log("Fitted shadows to scene",this.shadowsRoot.scale.clone())}awake(){Zc._instances.set(this.context,this),this.shadowsRoot.hideFlags=Uu.DontExport,Od(this.shadowsRoot,!1)}start(){Kc&&console.log("Create ContactShadows on "+this.gameObject.name,this),this.gameObject.add(this.shadowsRoot),this.shadowsRoot.add(this.shadowGroup),this.renderTarget=new lo(this.textureSize,this.textureSize),this.renderTarget.texture.generateMipmaps=!1,this.renderTargetBlur=new lo(this.textureSize,this.textureSize),this.renderTargetBlur.texture.generateMipmaps=!1;const s=new Fs(1,1).rotateX(Math.PI/2);this.gameObject instanceof K&&(console.warn("ContactShadows can not be added to a Mesh. Please add it to a Group or an empty Object"),Mn(this.gameObject,!1));const t=new Re({map:this.renderTarget.texture,opacity:this.opacity,color:0,transparent:!0,depthWrite:!1,side:co});this.plane=new K(s,t),this.plane.scale.y=-1,this.plane.layers.set(2),this.shadowsRoot.add(this.plane),this.plane&&(this.plane.renderOrder=1),this.occluderMesh=new K(this.plane.geometry,new Re({depthWrite:!0,stencilWrite:!0,colorWrite:!1,side:ym})).translateY(-1e-4),this.occluderMesh.renderOrder=-100,this.occluderMesh.layers.set(2),this.shadowsRoot.add(this.occluderMesh),this.blurPlane=new K(s),this.blurPlane.visible=!1,this.shadowGroup.add(this.blurPlane);const i=0,n=1;this.shadowCamera=new mm(-1/2,1/2,1/2,-1/2,i,n),this.shadowCamera.layers.enableAll(),this.shadowCamera.rotation.x=Math.PI/2,this.shadowGroup.add(this.shadowCamera),this.depthMaterial=new AS,this.depthMaterial.userData.darkness={value:this.darkness},this.depthMaterial.blending=IS,this.depthMaterial.blendEquation=jS,this.depthMaterial.onBeforeCompile=o=>{this.depthMaterial&&(o.uniforms.darkness=this.depthMaterial.userData.darkness,o.fragmentShader=`
925
+ Incoming:`,this._incomingCalls),r}else nt&&console.error("Failed to make call",s,t,this._peer)}closeAll(){for(const s of this._incomingCalls)s.close();for(const s of this._outgoingCalls)s.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 s=this.getMyPeerId();s?this._peer=Ob(s):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(s,t,i){const n=s.metadata;(!n||!n.userId)&&console.error("Missing call metadata",s);const o=n.userId;t==="incoming"&&nt?console.warn("\u2190 Receive call from",s.metadata,s.connectionId):nt&&console.warn("\u2192 Make call to",s.metadata);const r=t==="incoming"?this._incomingCalls:this._outgoingCalls,l=new AM(o,s,t,i);return r.push(l),s.on("error",c=>{console.error("Call error",c)}),s.on("close",()=>{nt&&console.log("Call ended",s.metadata);const c=r.indexOf(l);c!==-1&&r.splice(c,1),l.close(),this.dispatchEvent(new Sf(o,t))}),l.addEventListener("call-ended",c=>{this.dispatchEvent(c)}),t==="incoming"&&(l.addEventListener("receive-stream",c=>{this.dispatchEvent(c)}),s.on("stream",()=>{nt&&console.log("Received stream for call",s.metadata);let c=0;const h=setInterval(()=>{const d=c===0;!l.isOpen&&d&&(nt&&console.warn("Close call because stream is not active",s.metadata),c+=1,clearInterval(h),l.close())},2e3)})),l}};let Gc=qc;a(Gc,"instances",new Map);class cd extends fm{constructor(t,i){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",n=>{this._sendingStreams.size>0&&(this.debug&&console.warn(`${n!=null&&n.userId?`User ${n.userId}`:"You"} joined room`,n,this._sendingStreams.size),this.updateSendingCalls())}),a(this,"onLeftRoom",n=>{this.debug&&console.warn(`${n?.userId||"You"} left room`,n),this.stopCallsToUsersThatAreNotInTheRoomAnymore(),this.peer.closeAll()}),a(this,"onCallStreamReceived",n=>{this.debug&&console.log("Call with "+n.userId+" started"),this.dispatchEvent({type:"receive-stream",target:this,stream:n.stream,userId:n.userId}),this.debug&&this.debugLogCurrentState()}),a(this,"onCallEnded",n=>{this.debug&&console.log("Call with "+n.userId+" ended"),this.dispatchEvent(n),this.debug&&this.debugLogCurrentState()}),a(this,"onUserConnected",n=>{if(this.peer.id===n.guid){this.debug&&console.log("PEER USER CONNECTED",n.guid,n,this._sendingStreams.size);const o=this._sendingStreams.keys().next().value;this.peer.makeCall(n.peerId,o)}else nt&&console.log("Unknown user connected",n.guid,n.peerId)}),a(this,"onUserLeft",n=>{this.debug&&console.log("User left room: "+n.userId),this.stopCallsToUsersThatAreNotInTheRoomAnymore()}),Bw(t)){const n=t;t=n.context,i=Gc.getOrCreate(n.context,n.guid)}else typeof i=="string"&&(i=Gc.getOrCreate(t,i));if(t){if(!(t 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(!i)throw new Error("Failed to create NetworkedStreams because peer is undefined");this.context=t,this.peer=i,nt&&(this.debug=!0)}static create(t,i){const n=Gc.getOrCreate(t.context,i||t.context.connection.connectionId||t.guid);return new cd(t.context,n)}startSendingStream(t){this._sendingStreams.has(t)?console.warn("Received start sending stream with stream that is already being sent"):(this._sendingStreams.set(t,[]),this.updateSendingCalls())}stopSendingStream(t){if(t){const i=this._sendingStreams.get(t);if(i){for(const n of i)n.close();i.length=0}this._sendingStreams.delete(t),i&&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 t=this.context.connection.connectionId;for(const i of this._sendingStreams.keys()){const n=this._sendingStreams.get(i)||[];for(const o of this.context.connection.usersInRoom()){if(o===t)continue;const r=this.peer.getPeerIdFromUserId(o);if(n.find(l=>{var c;return l.peerId===r&&l.direction==="outgoing"&&!l.isClosed&&((c=l.stream)==null?void 0:c.active)}))nt&&console.debug("Already have a call with user "+o+" / peer "+r);else{const l=this.peer.makeCall(r,i);l&&n.push(l)}}this._sendingStreams.set(i,n)}this.stopCallsToUsersThatAreNotInTheRoomAnymore()}stopCallsToUsersThatAreNotInTheRoomAnymore(){for(const t of this._sendingStreams.keys()){const i=this._sendingStreams.get(t);if(i)for(let n=i.length-1;n>=0;n--){const o=i[n];this.context.connection.userIsInRoom(o.userId)?nt&&(this.context.connection.connectionId===o.userId?console.warn(`You are still in the room [${n}] ${o.userId}`):console.log(`User is still in room [${n}] ${o.userId}`)):(nt&&console.log(`Remove call ${[n]} to user that is not in room anymore ${o.userId}`),o.close(),i.splice(n,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(t=>t.userId).join(", ")})`,this.peer.incomingCalls)}}function Ks(s){if(s&&s instanceof MediaStream)for(const t of s.getTracks())t.stop()}var IM=Object.defineProperty,jM=Object.getOwnPropertyDescriptor,Cf=(s,t,i,n)=>{for(var o=n>1?void 0:n?jM(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&IM(t,i,o),o};const LM="noVoip",DM=O("debugvoip");class Ao extends A{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 t of this._incomingStreams.values())Ks(t.srcObject);this._incomingStreams.clear()}),a(this,"_incomingStreams",new Map),a(this,"onReceiveStream",t=>{const i=t.target.userId,n=t.stream;let o=this._incomingStreams.get(i);o||(o=new Audio,this._incomingStreams.set(i,o)),o.srcObject=n,o.setAttribute("autoplay","true"),Rn.registerWaitForInteraction(()=>{o?.play().catch(r=>{console.error("VOIP: Failed to play audio",r)})})}),a(this,"onStreamEnded",t=>{const i=this._incomingStreams.get(t.userId);Ks(i?.srcObject),this._incomingStreams.delete(t.userId)}),a(this,"onEnabledChanged",()=>{for(const t of this._incomingStreams){const i=t[1];i.muted=!this.enabled}}),a(this,"onVisibilityChanged",()=>{if(this.runInBackground)return;const t=document.visibilityState!=="visible";this.setMuted(t);for(const i of this._incomingStreams){const n=i[1];n.muted=t}})}awake(){DM&&(this.debug=!0),this.debug&&(console.log("VOIP debugging: press 'v' to toggle mute or 'c' to toggle connect/disconnect"),window.addEventListener("keydown",async t=>{switch(t.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=cd.create(this)),this.debug&&(this._net.debug=!0),this._net.addEventListener(Ys.StreamReceived,this.onReceiveStream),this._net.addEventListener(Ys.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 t;this._net&&(this._net.stopSendingStream(this._outputStream),this._net.removeEventListener(Ys.StreamReceived,this.onReceiveStream),this._net.removeEventListener(Ys.StreamEnded,this.onStreamEnded),(t=this._net)==null||t.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 t;(t=this._menubutton)==null||t.remove(),this._menubutton=void 0}get isSending(){return this._outputStream!=null&&this._outputStream.active}async connect(t){var i,n;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 X.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,(i=this._net)==null||i.stopSendingStream(this._outputStream),Ks(this._outputStream),this._outputStream=await this.getAudioStream(t),this._outputStream?(this.debug&&console.log("VOIP: Got audio stream"),(n=this._net)==null||n.startSendingStream(this._outputStream),this.updateButton(),!0):(this.updateButton(),await X.microphonePermissionsGranted()?console.error("VOIP: Could not get audio stream - please make sure to connect an audio device and grant microphone permissions"):ac("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(t){var i;t!=null&&t.remember&&(this._allowSending=!1),(i=this._net)==null||i.stopSendingStream(this._outputStream),Ks(this._outputStream),this._outputStream=null,this.updateButton()}setMuted(t){var i;const n=(i=this._outputStream)==null?void 0:i.getAudioTracks();if(n)for(const o of n)o.enabled=!t}get isMuted(){var t;if(this._outputStream===null)return!1;const i=(t=this._outputStream)==null?void 0:t.getAudioTracks();if(i){for(const n of i)if(!n.enabled)return!0}return!1}async updateButton(){var t;if(this.createMenuButton){if(this._menubutton||(this._menubutton=document.createElement("button"),this._menubutton.addEventListener("click",()=>{this.isSending?this.disconnect({remember:!0}):this.connect(),X.microphonePermissionsGranted().then(i=>{i||xe("<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 i=(this.isSending,""),n=this.isSending?"mic":"mic_off";await X.microphonePermissionsGranted()||(i="No Permission",n="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=i,this._menubutton.prepend(Pt(n)),this.context.connection.isConnected==!1?this._menubutton.setAttribute("disabled",""):this._menubutton.removeAttribute("disabled")}}else this.activeAndEnabled||(t=this._menubutton)==null||t.remove()}getFrequency(t){return this.unsupported_getfrequency||(this.unsupported_getfrequency=!0,F()&&xe("VOIP: getFrequency is currently not supported"),console.warn("VOIP: getFrequency is currently not supported")),null}async getAudioStream(t){if(!navigator.mediaDevices.getUserMedia)return console.error("No getDisplayMedia support"),null;const i=async o=>await navigator.mediaDevices.getUserMedia({audio:o??!0,video:!1}).catch(r=>(console.warn("VOIP failed getting audio stream",r),null)),n=await i(t);if(!n)return null;if(X.isiOS()&&t?.deviceId===void 0){const o=(await navigator.mediaDevices.enumerateDevices()).find(r=>(r.kind==="audioinput"||r.kind==="audiooutput")&&!r.label.includes("iPhone"));if(o){const r=Object.assign({},t);return r.deviceId=o.deviceId,await i(r)}}return n}}Cf([m()],Ao.prototype,"autoConnect",2),Cf([m()],Ao.prototype,"runInBackground",2),Cf([m()],Ao.prototype,"createMenuButton",2);var BM=Object.defineProperty,FM=Object.getOwnPropertyDescriptor,Hw=(s,t,i,n)=>{for(var o=n>1?void 0:n?FM(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&BM(t,i,o),o};const zM=O("debugmouth");class Xc extends A{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(Ao,this.context),this.marker||(this.marker=P.getComponentInParent(this.gameObject,Rt))},3e3)}update(){var t;if(!this.voip||this.context.time.frameCount%10!==0)return;let i=((t=this.marker)==null?void 0:t.connectionId)??null;if(!i){zM&&(i=null);return}const n=this.voip.getFrequency(i)??0;this.updateLips(n)}updateLips(t){if(this.context.time.time-this.lastMouthChangeTime>this.mouthChangeLength){if(this.mouthChangeLength=.05+Math.random()*.1,this.talking&&this.talking.length>0&&t>30){this.lastMouthChangeTime=this.context.time.time;const i=Math.floor(Math.random()*this.talking.length);this.setMouthShapeActive(this.talking,i)}else if(this.idle.length>0&&this.context.time.time-this.lastMouthChangeTime>.5){this.lastMouthChangeTime=this.context.time.time;const i=Math.floor(Math.random()*this.idle.length);this.setMouthShapeActive(this.idle,i)}}}setMouthShapeActive(t,i){if(t){t!=this.idle?this.idle.map(n=>n.visible=!1):this.talking.map(n=>n.visible=!1);for(let n=0;n<t.length;n++){const o=t[n];o&&(o.visible=n===i)}}}}Hw([m(I)],Xc.prototype,"idle",2),Hw([m(I)],Xc.prototype,"talking",2);class Of extends A{constructor(){super(...arguments),a(this,"voip",null),a(this,"marker",null),a(this,"_startPosition",null)}awake(){this.voip=P.findObjectOfType(Ao,this.context),this.marker=P.getComponentInParent(this.gameObject,Rt)}update(){if(!this.voip||!this.marker||this.context.time.frameCount%10!==0)return;const t=this.marker.connectionId,i=this.voip.getFrequency(t);if(i==null)return;this._startPosition||(this._startPosition=this.gameObject.position.clone());const n=i/100;this.gameObject.position.y=this._startPosition.y+n*.07}}var UM=Object.defineProperty,NM=Object.getOwnPropertyDescriptor,WM=(s,t,i,n)=>{for(var o=n>1?void 0:n?NM(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&UM(t,i,o),o};const Za=O("debugxrflags"),$w=O("disablexrflags");$w&&console.warn("XRFlags are disabled");var Zs=(s=>(s[s.Never=0]="Never",s[s.Browser=1]="Browser",s[s.AR=2]="AR",s[s.VR=4]="VR",s[s.FirstPerson=8]="FirstPerson",s[s.ThirdPerson=16]="ThirdPerson",s[s.All=4294967295]="All",s))(Zs||{});const qw=class{constructor(){a(this,"Mask",17)}Has(s){return(this.Mask&s)!==0}Set(s){Za&&console.warn("Set XR flag state to",s),this.Mask=s,Ai.Apply()}Enable(s){this.Mask|=s,Ai.Apply()}Disable(s){this.Mask&=~s,Ai.Apply()}Toggle(s){this.Mask^=s,Ai.Apply()}EnableAll(){this.Mask=-1,Ai.Apply()}DisableAll(){this.Mask=0,Ai.Apply()}};let Kt=qw;a(Kt,"Global",new qw);var Qc;const An=(Qc=class extends A{constructor(){super(...arguments),a(this,"visibleIn")}static Apply(){for(const s of this.registry)s.UpdateVisible(Kt.Global)}awake(){An.registry.push(this)}onEnable(){An.firstApply?this.UpdateVisible(Kt.Global):(An.firstApply=!0,An.Apply())}onDestroy(){const s=An.registry.indexOf(this);s>=0&&An.registry.splice(s,1)}get isOn(){return this.gameObject.visible}UpdateVisible(s=null){if($w)return;let t;const i=s;if(i&&typeof i=="number"&&(console.assert(typeof i=="number","XRFlag.UpdateVisible: state must be a number",i),Za&&console.log(i),An.buffer.Mask=i,s=An.buffer),s instanceof Kt?(Za&&console.warn(this.name,"use passed in mask",s.Mask,this.visibleIn),t=s.Has(this.visibleIn)):(Za&&console.log(this.name,"use global mask"),Kt.Global.Has(this.visibleIn)),t!==void 0)if(t)Za&&console.log(this.name,"is visible",this.gameObject.uuid),P.setActive(this.gameObject,!0);else{if(Za&&console.log(this.name,"is not visible",this.gameObject.uuid),!this.gameObject.visible)return;this.gameObject.visible=!1}}},a(Qc,"registry",[]),a(Qc,"firstApply"),a(Qc,"buffer",new Kt),Qc);let Ai=An;WM([m()],Ai.prototype,"visibleIn",2);var VM=Object.defineProperty,HM=Object.getOwnPropertyDescriptor,Nu=(s,t,i,n)=>{for(var o=n>1?void 0:n?HM(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&VM(t,i,o),o};class zr extends A{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,Ai)}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 t of this.eyes)t&&(t.visible=this.eyesOpen)}}}Nu([m(I)],zr.prototype,"eyes",2),Nu([m()],zr.prototype,"lastBlinkTime",2),Nu([m()],zr.prototype,"blinkLength",2),Nu([m()],zr.prototype,"eyesOpen",2);var $M=Object.defineProperty,qM=Object.getOwnPropertyDescriptor,Pf=(s,t,i,n)=>{for(var o=n>1?void 0:n?qM(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&$M(t,i,o),o},kf;const Gw=(kf=class extends A{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,$c)),this.brain||(this.brain=P.addComponent(this.gameObject,$c)),this.brain&&this.target&&(this.brain.controlledTarget=this.target)}update(){const s=this.target;if(s&&this.head){const t=this.eyes;if(t){const i=te(s);this.currentTargetPoint.lerp(i,this.context.time.deltaTime/.1);const n=te(this.head),o=this.vec.copy(this.currentTargetPoint).sub(n).normalize();if(o.length()<.1)return;const r=Gw.forward;if(r.set(0,0,1),r.applyQuaternion(Oe(this.head)),r.dot(o)>.45)for(let l=0;l<t.length;l++)t[l].lookAt(this.currentTargetPoint)}}}},a(kf,"forward",new x(0,0,1)),kf);let Ja=Gw;Pf([m(I)],Ja.prototype,"head",2),Pf([m(I)],Ja.prototype,"eyes",2),Pf([m(I)],Ja.prototype,"target",2);const Yc=O("debugavatar");class Wu{constructor(t,i,n,o){a(this,"root"),a(this,"head"),a(this,"leftHand"),a(this,"rigthHand");var r;this.root=t,this.head=i,this.leftHand=n,this.rigthHand=o,(r=this.root)==null||r.traverse(l=>l.layers.set(2))}get isValid(){return this.head!==null&&this.head!==void 0}}class Mf{constructor(){a(this,"avatarRegistryUrl",null)}async getOrCreateNewAvatarInstance(t,i){if(!i)return console.error("Can not create avatar: failed to provide id or root object"),null;let n=null;if(typeof i=="string"){if(n=await this.loadAvatar(t,i),!n){const r=new Ds;n=P.instantiate(Ca(i,t.scene),r)}}else n=i;if(!n)return null;const o=this.findAvatar(n);return o.isValid?(Yc&&console.log("[Custom Avatar] valid config",i,Yc?o:""),o):(console.warn("[Custom Avatar] config isn't valid",i,Yc?o:""),null)}async loadAvatar(t,i){if(console.assert(i!=null&&typeof i=="string","Avatar id must not be null"),i.length<=0||!i)return null;if(Yc&&console.log("[Custom Avatar] "+i+", loading..."),i.endsWith(".glb")||(i+=".glb"),this.avatarRegistryUrl===null){const o=await fetch("./"+i);let r=null;if(o.ok){const c=await o.blob();c&&(r=await c.arrayBuffer())}if(!r)return null;const l=await fs().parseSync(t,r,null,0);return l?.scene??null}const n=new gr;return Su(n,t),new Promise((o,r)=>{const l=this.avatarRegistryUrl+"/"+i;n.load(l,async c=>{await fs().createBuiltinComponents(t,l,c,null,void 0),o(c.scene)},c=>{Yc&&console.log("[Custom Avatar] "+c.loaded/c.total*100+"% loaded of "+c.total/1024+"kB")},c=>{console.error("[Custom Avatar] Error when loading: "+c),o(null)})})}cacheModel(t,i){}findAvatar(t){const i=t;let n=i;n.children.length==1&&(n=t.children[0]);let o=this.findAvatarPart(n,["head"]);const r=this.findAvatarPart(n,["left","hand"]),l=this.findAvatarPart(n,["right","hand"]);if(!o){o=i;const c=new x;new _i().setFromObject(o).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&&o.scale.multiplyScalar(1/h*.3)}return new Wu(i,o,r,l)}findAvatarPart(t,i){const n=t.name.toLowerCase();let o=!0;for(const r of i){if(!o)break;n.indexOf(r)===-1&&(o=!1)}if(o)return t;if(t.children)for(const r of t.children){const l=this.findAvatarPart(r,i);if(l)return l}return null}handleCustomAvatarErrors(t){if(!t.ok)throw Error(t.statusText);return t}}var GM=Object.defineProperty,XM=Object.getOwnPropertyDescriptor,Rf=(s,t,i,n)=>{for(var o=n>1?void 0:n?XM(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&GM(t,i,o),o};class el extends A{constructor(){super(...arguments),a(this,"length",1),a(this,"depthTest",!0),a(this,"isGizmo",!1),a(this,"_axes",null)}onEnable(){if(this.isGizmo&&!Sc)return;this._axes||(this._axes=new wi(this.length)),this._axes.layers.disableAll(),this._axes.layers.set(this.layer),this.gameObject.add(this._axes);const t=this._axes.material;t&&t.depthTest!==void 0&&(t.depthTest=this.depthTest)}onDisable(){this._axes&&this.gameObject.remove(this._axes)}}Rf([m()],el.prototype,"length",2),Rf([m()],el.prototype,"depthTest",2),Rf([m()],el.prototype,"isGizmo",2);class Tf extends A{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 t=te(this.to).clone(),i=te(this.from).clone(),n=t.distanceTo(i),o=t.clone();o.sub(i);const r=i.clone();r.add(t),r.multiplyScalar(.5);const l=te(this.hint).clone();l.sub(r);const c=new x;c.crossVectors(l,o),c.crossVectors(o,c),c.normalize();const h=n*.5,d=Math.max(this.desiredDistance,h),u=Math.sqrt(d*d-h*h),p=c.clone();p.multiplyScalar(u),p.add(r),dt(this.gameObject,p);const g=r.clone();g.sub(c),this.gameObject.lookAt(g)}}const QM=O("gizmos"),YM=O("debugboxhelper"),Js=class extends A{constructor(){super(...arguments),a(this,"box",null),a(this,"_lastMatrixUpdateFrame",-1),a(this,"_helper",null),a(this,"_color",null)}isInBox(s){var t;if(!s)return;if(this.box||(this.box=new _i),ci([s],void 0,void 0,Js.testBox),Js.testBox.isEmpty()){const n=te(s,Js._position);Js.testBox.setFromCenterAndSize(n,Js._emptyObjectSize)}this.updateBox();const i=(t=this.box)==null?void 0:t.intersectsBox(Js.testBox);return i&&YM&&q.DrawWireBox3(Js.testBox,16711680,5),i}intersects(s){return s?this.updateBox(!1).intersectsBox(s):!1}updateBox(s=!1){if(this.box||(this.box=new _i),s||this.context.time.frameCount!=this._lastMatrixUpdateFrame){const t=this._lastMatrixUpdateFrame<0;this._lastMatrixUpdateFrame=this.context.time.frameCount;const i=t,n=te(this.gameObject,Js._position,i),o=Je(this.gameObject,Js._size);this.box.setFromCenterAndSize(n,o)}return this.box}awake(){this._helper=null,this._color=null,this.box=null}showHelper(s=null,t=!1){var i;if(!(!QM&&!t)){if(this._helper){s&&((i=this._color)==null||i.set(s)),this.gameObject.add(this._helper);return}this._helper=_g(s),this.gameObject.add(this._helper)}}};let is=Js;a(is,"testBox",new _i),a(is,"_position",new x),a(is,"_size",new x(.01,.01,.01)),a(is,"_emptyObjectSize",new x(.01,.01,.01));var KM=Object.defineProperty,ZM=Object.getOwnPropertyDescriptor,ui=(s,t,i,n)=>{for(var o=n>1?void 0:n?ZM(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&KM(t,i,o),o};class pi extends A{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 t;(t=this.context.physics.engine)==null||t.updateProperties(this)})}get isCollider(){return!0}awake(){super.awake(),this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(ve))}start(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(ve))}onEnable(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(ve))}onDisable(){var t;(t=this.context.physics.engine)==null||t.removeBody(this)}get body(){var t;return(t=this.context.physics.engine)==null?void 0:t.getBody(this)}updatePhysicsMaterial(){var t;(t=this.context.physics.engine)==null||t.updatePhysicsMaterial(this)}}ui([m(ve)],pi.prototype,"attachedRigidbody",2),ui([m()],pi.prototype,"isTrigger",2),ui([m()],pi.prototype,"sharedMaterial",2),ui([m()],pi.prototype,"membership",2),ui([m()],pi.prototype,"filter",2);class tl extends pi{constructor(){super(...arguments),a(this,"radius",.5),a(this,"center",new x(0,0,0))}onEnable(){var t;super.onEnable(),(t=this.context.physics.engine)==null||t.addSphereCollider(this),_d(this.gameObject.scale,this.updateProperties)}onDisable(){super.onDisable(),Am(this.gameObject.scale,this.updateProperties)}onValidate(){this.updateProperties()}}ui([Mt(),m()],tl.prototype,"radius",2),ui([m(x)],tl.prototype,"center",2);const Xw=class extends pi{constructor(){super(...arguments),a(this,"size",new x(1,1,1)),a(this,"center",new x(0,0,0))}static add(s,t){const i=Mi(s,Xw);return i.autoFit(),t?.rigidbody===!0&&Mi(s,ve,{isKinematic:!1}),i}onEnable(){var s;super.onEnable(),(s=this.context.physics.engine)==null||s.addBoxCollider(this,this.size),_d(this.gameObject.scale,this.updateProperties)}onDisable(){super.onDisable(),Am(this.gameObject.scale,this.updateProperties)}onValidate(){this.updateProperties()}autoFit(s){const t=this.gameObject,i=t.position.clone(),n=t.quaternion.clone(),o=t.scale.clone(),r=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 l=ci([t]);t.position.copy(i),t.quaternion.copy(n),t.scale.copy(o),t.parent=r,s?.debug===!0&&q.DrawWireBox3(l,16768256,20),this.size=l.getSize(new x)||new x(1,1,1),this.center=l.getCenter(new x)||new x(0,0,0),this.size.length()<=0&&this.size.set(.01,.01,.01)}};let il=Xw;ui([Mt(),m(x)],il.prototype,"size",2),ui([m(x)],il.prototype,"center",2);class Io extends pi{constructor(){super(...arguments),a(this,"sharedMesh"),a(this,"convex",!1)}onEnable(){var t,i,n;if(super.onEnable(),!this.context.physics.engine)return;(t=this.sharedMesh)!=null&&t.isMesh||(this.gameObject instanceof K||this.gameObject instanceof ro)&&(this.sharedMesh=this.gameObject);const o=0;if((i=this.sharedMesh)!=null&&i.isMesh)this.context.physics.engine.addMeshCollider(this,this.sharedMesh,this.convex),it.assignMeshLOD(this.sharedMesh,o).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 "${((n=this.sharedMesh)==null?void 0:n.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(it.assignMeshLOD(h,o)))}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 K;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()||O("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)}}}ui([m(K)],Io.prototype,"sharedMesh",2),ui([m()],Io.prototype,"convex",2);class In extends pi{constructor(){super(...arguments),a(this,"center",new x(0,0,0)),a(this,"radius",.5),a(this,"height",2)}onEnable(){var t;super.onEnable(),(t=this.context.physics.engine)==null||t.addCapsuleCollider(this,this.height,this.radius)}}ui([m(x)],In.prototype,"center",2),ui([m()],In.prototype,"radius",2),ui([m()],In.prototype,"height",2);var JM=Object.defineProperty,eR=Object.getOwnPropertyDescriptor,jn=(s,t,i,n)=>{for(var o=n>1?void 0:n?eR(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&JM(t,i,o),o};const Qw=O("debugcharactercontroller");class Ur extends A{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(ve),this._rigidbody||(this._rigidbody=this.gameObject.addComponent(ve)),this.rigidbody)}awake(){this._activeGroundCollisions=new Set}onEnable(){const t=this.rigidbody;let i=this.gameObject.getComponent(In);i||(i=this.gameObject.addComponent(In)),i.center.copy(this.center),i.radius=this.radius,i.height=this.height;const n=new x(0,0,1),o=new x(1,0,0),r=new x(0,1,0),l=this.gameObject.getWorldDirection(new x);l.y=0;const c=o.dot(l)<0?-1:1,h=n.angleTo(l)*c;this.gameObject.setRotationFromAxisAngle(r,h),t.lockRotationX=!0,t.lockRotationY=!0,t.lockRotationZ=!0}move(t){this.gameObject.position.add(t)}onCollisionEnter(t){(t.contacts.length==0||t.contacts.some(i=>i.normal.y>.2))&&(this._activeGroundCollisions.add(t),Qw&&console.log(`Collision(${this._activeGroundCollisions.size}): ${t.contacts.map(i=>i.normal.y.toFixed(2)).join(", ")} - ${this.isGrounded}`))}onCollisionExit(t){this._activeGroundCollisions.delete(t),Qw&&console.log(`Collision(${this._activeGroundCollisions.size}) - ${this.isGrounded}`)}get isGrounded(){return this._activeGroundCollisions.size>0}get contactVelocity(){var t;this._contactVelocity.set(0,0,0);for(const i of this._activeGroundCollisions){const n=(t=this.context.physics.engine)==null?void 0:t.getLinearVelocity(i.collider);n&&(this._contactVelocity.x+=n.x,this._contactVelocity.y+=n.y,this._contactVelocity.z+=n.z)}return this._contactVelocity}}jn([m(x)],Ur.prototype,"center",2),jn([m()],Ur.prototype,"radius",2),jn([m()],Ur.prototype,"height",2);class Ln extends A{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 oe(0,0)),a(this,"moveInput",new oe(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 Ws)}awake(){this._currentRotation=new V}update(){const t=this.context.input;t.isKeyPressed("KeyW")?this.moveInput.y+=1:t.isKeyPressed("KeyS")&&(this.moveInput.y-=1),t.isKeyPressed("KeyD")?this.lookInput.x+=1:t.isKeyPressed("KeyA")&&(this.lookInput.x-=1),this.jumpInput||(this.jumpInput=t.isKeyDown("Space"))}move(t){this.moveInput.add(t)}look(t){this.lookInput.add(t)}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(t,i,n){var o,r,l,c,h,d,u,p,g,y,f;if((o=this.controller)!=null&&o.isGrounded&&(this._jumpCount=0,this.doubleJumpForce>0&&((r=this.animator)==null||r.setBool("doubleJump",!1))),this._currentSpeed.z+=t.y*this.movementSpeed*this.context.time.deltaTime,(l=this.animator)==null||l.setBool("running",t.length()>.01),(h=this.animator)==null||h.setBool("jumping",((c=this.controller)==null?void 0:c.isGrounded)===!0&&n),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(-i.x*this.rotationSpeed)*this.context.time.deltaTime,this.lookForward&&Math.abs(this._currentAngularSpeed.y)<.01){const v=this.context.mainCameraComponent.forward;v.y=0,v.normalize(),this._currentRotation.setFromUnitVectors(new x(0,0,1),v),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&&n&&this.jumpForce>0){let v=(d=this.controller)==null?void 0:d.isGrounded;if(this.doubleJumpForce>0&&!((u=this.controller)!=null&&u.isGrounded)&&this._jumpCount===1&&(v=!0,(p=this.animator)==null||p.setBool("doubleJump",!0)),v){this._jumpCount+=1;const b=this.controller.rigidbody,w=this._jumpCount===2?this.doubleJumpForce:this.jumpForce;b.applyImpulse(new x(0,1,0).multiplyScalar(w))}}if(this.controller){const v=(g=this.controller)==null?void 0:g.rigidbody.getVelocity().y;if(v<-1){this._raycastOptions.ray||(this._raycastOptions.ray=new oo),this._raycastOptions.ray.origin.copy(te(this.gameObject)),this._raycastOptions.ray.direction.set(0,-1,0);const b=this.layer;this.gameObject.layers.disableAll(),this.gameObject.layers.set(2);const w=this.context.physics.raycast(this._raycastOptions);this.gameObject.layers.set(b),(w.length&&w[0].distance>2||v<-10)&&((y=this.animator)==null||y.setBool("falling",!0))}else(f=this.animator)==null||f.setBool("falling",!1)}}}jn([m(Ur)],Ln.prototype,"controller",2),jn([m()],Ln.prototype,"movementSpeed",2),jn([m()],Ln.prototype,"rotationSpeed",2),jn([m()],Ln.prototype,"jumpForce",2),jn([m()],Ln.prototype,"doubleJumpForce",2),jn([m(kt)],Ln.prototype,"animator",2);var tR=Object.defineProperty,iR=Object.getOwnPropertyDescriptor,sl=(s,t,i,n)=>{for(var o=n>1?void 0:n?iR(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&tR(t,i,o),o};const Kc=O("debugcontactshadows");kw(s=>{const t=s.domElement.getAttribute("contactshadows");t!=null&&t!="0"&&t!="false"&&ks.auto(s)});var Ef;const Zc=(Ef=class extends A{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,"shadowsRoot",new I),a(this,"shadowCamera"),a(this,"shadowGroup",new ro),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(s){if(s||(s=ee.Current),!s)throw new Error("No context provided and no current context set.");let t=this._instances.get(s);if(!t||t.destroyed){const i=new I;t=Mi(i,Zc,{autoFit:!1,occludeBelowGround:!1}),this._instances.set(s,t)}return s.scene.add(t.gameObject),t.fitShadows(),t}fitShadows(){Kc&&console.warn("Fitting shadows to scene"),Od(this.shadowsRoot,!1);const s=ci(this.context.scene.children,[this.shadowsRoot]),t=Math.max(1,this.blur/32),i=s.max.x-s.min.x,n=s.max.z-s.min.z;s.expandByVector(new x(t*i,0,t*n)),Kc&&q.DrawWireBox3(s,16776960,60),this.gameObject.parent&&s.applyMatrix4(this.gameObject.parent.matrixWorld.clone().invert());const o=s.min,r=Math.max(1e-5,(s.max.y-o.y)*.002);s.max.y+=r,this.shadowsRoot.position.set((o.x+s.max.x)/2,o.y-r,(o.z+s.max.z)/2),this.shadowsRoot.scale.set(s.max.x-o.x,s.max.y-o.y,s.max.z-o.z),this.applyMinSize(),this.shadowsRoot.matrixWorldNeedsUpdate=!0,Kc&&console.log("Fitted shadows to scene",this.shadowsRoot.scale.clone())}awake(){Zc._instances.set(this.context,this),this.shadowsRoot.hideFlags=Uu.DontExport,Od(this.shadowsRoot,!1)}start(){Kc&&console.log("Create ContactShadows on "+this.gameObject.name,this),this.gameObject.add(this.shadowsRoot),this.shadowsRoot.add(this.shadowGroup),this.renderTarget=new lo(this.textureSize,this.textureSize),this.renderTarget.texture.generateMipmaps=!1,this.renderTargetBlur=new lo(this.textureSize,this.textureSize),this.renderTargetBlur.texture.generateMipmaps=!1;const s=new Fs(1,1).rotateX(Math.PI/2);this.gameObject instanceof K&&(console.warn("ContactShadows can not be added to a Mesh. Please add it to a Group or an empty Object"),Mn(this.gameObject,!1));const t=new Re({map:this.renderTarget.texture,opacity:this.opacity,color:0,transparent:!0,depthWrite:!1,side:co});this.plane=new K(s,t),this.plane.scale.y=-1,this.plane.layers.set(2),this.shadowsRoot.add(this.plane),this.plane&&(this.plane.renderOrder=1),this.occluderMesh=new K(this.plane.geometry,new Re({depthWrite:!0,stencilWrite:!0,colorWrite:!1,side:ym})).translateY(-1e-4),this.occluderMesh.renderOrder=-100,this.occluderMesh.layers.set(2),this.shadowsRoot.add(this.occluderMesh),this.blurPlane=new K(s),this.blurPlane.visible=!1,this.shadowGroup.add(this.blurPlane);const i=0,n=1;this.shadowCamera=new mm(-1/2,1/2,1/2,-1/2,i,n),this.shadowCamera.layers.enableAll(),this.shadowCamera.rotation.x=Math.PI/2,this.shadowGroup.add(this.shadowCamera),this.depthMaterial=new AS,this.depthMaterial.userData.darkness={value:this.darkness},this.depthMaterial.blending=IS,this.depthMaterial.blendEquation=jS,this.depthMaterial.onBeforeCompile=o=>{this.depthMaterial&&(o.uniforms.darkness=this.depthMaterial.userData.darkness,o.fragmentShader=`
926
926
  uniform float darkness;
927
927
  ${o.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) );")}
928
928
  `)},this.depthMaterial.depthTest=!1,this.depthMaterial.depthWrite=!1,this.horizontalBlurMaterial=new ms(DC),this.horizontalBlurMaterial.depthTest=!1,this.verticalBlurMaterial=new ms(BC),this.verticalBlurMaterial.depthTest=!1,this.shadowGroup.visible=!1,this.autoFit?this.fitShadows():this.applyMinSize()}onDestroy(){var s,t,i,n,o,r,l,c;Zc._instances.get(this.context)===this&&Zc._instances.delete(this.context),(s=this.renderTarget)==null||s.dispose(),(t=this.renderTargetBlur)==null||t.dispose(),(i=this.depthMaterial)==null||i.dispose(),(n=this.horizontalBlurMaterial)==null||n.dispose(),(o=this.verticalBlurMaterial)==null||o.dispose(),(r=this.blurPlane)==null||r.geometry.dispose(),(l=this.plane)==null||l.geometry.dispose(),(c=this.occluderMesh)==null||c.geometry.dispose()}onBeforeRender(s){if(!this.renderTarget||!this.renderTargetBlur||!this.depthMaterial||!this.shadowCamera||!this.blurPlane||!this.shadowGroup||!this.plane||!this.horizontalBlurMaterial||!this.verticalBlurMaterial){Kc&&console.error("ContactShadows: not initialized yet");return}const t=this.context.scene,i=this.context.renderer,n=i.getRenderTarget();this.shadowGroup.visible=!0,this.occluderMesh&&(this.occluderMesh.visible=!1);const o=this.plane.visible;this.plane.visible=!1,this.gameObject instanceof K&&Mn(this.gameObject,!1);const r=t.background;t.background=null,t.overrideMaterial=this.depthMaterial,this.backfaceShadows?this.depthMaterial.side=xi:this.depthMaterial.side=co;const l=i.getClearAlpha();i.setClearAlpha(0);const c=i.xr.enabled;i.xr.enabled=!1;const h=this.context.scene.matrixWorldAutoUpdate;this.context.scene.matrixWorldAutoUpdate=!1;const d=i.renderLists.get(t,0),u=d.transparent;Yw.length=0,d.transparent=Yw,Af.length=0;for(const g of d.opaque){if(!g.object.visible)continue;const y=g.material;let f=g.material.colorWrite==!1||y.wireframe===!0||Jv(g.object)===!1;!f&&g.material.isLineMaterial&&(f=!0),!f&&g.material.isPointsMaterial&&(f=!0),f&&(Af.push(g.object),g.object["needle:visible"]=g.object.visible,g.object.visible=!1)}i.setRenderTarget(this.renderTarget),i.clear(),i.render(t,this.shadowCamera),d.transparent=u;for(const g of Af)g["needle:visible"]!=null&&(g.visible=g["needle:visible"]);t.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=o,i.setRenderTarget(n),i.setClearAlpha(l),t.background=r,i.xr.enabled=c,this.context.scene.matrixWorldAutoUpdate=h}blurShadow(s){if(!this.blurPlane||!this.shadowCamera||!this.renderTarget||!this.renderTargetBlur||!this.horizontalBlurMaterial||!this.verticalBlurMaterial)return;this.blurPlane.visible=!0;const t=this.shadowsRoot.worldScale,i=(t.x+t.z)/2,n=t.z/i,o=t.x/i;this.blurPlane.material=this.horizontalBlurMaterial,this.blurPlane.material.uniforms.tDiffuse.value=this.renderTarget.texture,this.horizontalBlurMaterial.uniforms.h.value=s*1/this.textureSize*n;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=s*1/this.textureSize*o,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(Ef,"_instances",new Map),Ef);let ks=Zc;sl([m()],ks.prototype,"autoFit",2),sl([m()],ks.prototype,"darkness",2),sl([m()],ks.prototype,"opacity",2),sl([m()],ks.prototype,"blur",2),sl([m()],ks.prototype,"occludeBelowGround",2),sl([m()],ks.prototype,"backfaceShadows",2);const Yw=[],Af=new Array,sR=O("logstats");class If extends A{onEnable(){console.log(this),sR&&this.startCoroutine(this.run(),Me.OnAfterRender)}*run(){for(;this.enabled;){const t=this.context.renderer.info;console.log(t.memory,t.render,t.programs),yield}}}class Jc extends A{constructor(){super(...arguments),a(this,"isUsed",!0),a(this,"usedBy",null)}}class jf extends A{}const Kw=O("debugdeletable"),Vu=class extends is{onEnable(){Vu._instances.push(this)}onDisable(){const s=Vu._instances.indexOf(this);s>=0&&Vu._instances.splice(s,1)}};let eh=Vu;a(eh,"_instances",[]);class Lf extends A{update(){for(const t of eh._instances){const i=this.gameObject;if(t.isInBox(i)===!0){const n=P.getComponentInParent(this.gameObject,Jc);if(n)Kw&&console.warn("DeleteBox: Not deleting object with usage marker",this.guid,n);else{if(Kw)try{if(t.box){const o=t.box,r=is.testBox;q.DrawWireBox3(o,16711680,5),q.DrawWireBox3(r,255,5),console.log("DeleteBox: Destroying",this.gameObject,{deleteBoxArea:o,deletedObjectArea:r})}else console.log("DeleteBox: Destroying",this.gameObject)}catch{}xc(this.gameObject,this.context.connection)}}}}}var nR=Object.defineProperty,oR=Object.getOwnPropertyDescriptor,rR=(s,t,i,n)=>{for(var o=n>1?void 0:n?oR(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&nR(t,i,o),o};class Hu extends A{constructor(){super(...arguments),a(this,"visibleOn")}onEnable(){this.apply()}apply(){this.test()||P.setActive(this.gameObject,!1)}test(){return this.visibleOn<0?!0:X.isMobileDevice()?(this.visibleOn&2)!==0:(this.visibleOn&1)!==0}}rR([m()],Hu.prototype,"visibleOn",2);var aR=Object.defineProperty,lR=Object.getOwnPropertyDescriptor,Nr=(s,t,i,n)=>{for(var o=n>1?void 0:n?lR(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&aR(t,i,o),o};const en=O("debugdrag"),Df=[];var Bf=(s=>(s[s.XZPlane=0]="XZPlane",s[s.Attached=1]="Attached",s[s.HitNormal=2]="HitNormal",s[s.DynamicViewAngle=3]="DynamicViewAngle",s[s.SnapToSurfaces=4]="SnapToSurfaces",s[s.None=5]="None",s))(Bf||{}),th;const ss=(th=class extends A{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(){Df.length=0;for(const s of this._instances)s._isDragging&&Df.push(s);return Df}get draggedObject(){return this._targetObject}setTargetObject(s){var t,i;this._targetObject=s;for(const o of this._dragHandlers.values())o.setTargetObject(s);const n="_rigidbody-was-kinematic";((t=this._rigidbody)==null?void 0:t[n])===!1&&(this._rigidbody.isKinematic=!1,this._rigidbody[n]=void 0),this._rigidbody=null,s&&(this._rigidbody=P.getComponentInChildren(s,ve),((i=this._rigidbody)==null?void 0:i.isKinematic)===!1&&(this._rigidbody.isKinematic=!0,this._rigidbody[n]=!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(Ei)||this.gameObject.addComponent(Ei)}onEnable(){ss._instances.push(this)}onDisable(){ss._instances=ss._instances.filter(s=>s!==this)}allowEdit(s=null){return this.context.connection.allowEditing}onPointerEnter(s){if(!this.allowEdit(this.gameObject)||s.mode!=="screen"||(s.event.mode==="tracked-pointer"||s.event.mode==="transient-pointer"?this.xrDragMode:this.dragMode)===5)return;const t=P.getComponentInParent(s.object,ss);!t||t!==this||(ss.lastHovered=s.object,this.context.domElement.style.cursor="pointer")}onPointerMove(s){(this._isDragging||this._potentialDragStartEvt!==null)&&s.use()}onPointerExit(s){this.allowEdit(this.gameObject)&&s.mode==="screen"&&ss.lastHovered===s.object&&(this.context.domElement.style.cursor="auto")}onPointerDown(s){if(!(!this.allowEdit(this.gameObject)||s.used||(s.mode==="tracked-pointer"||s.mode==="transient-pointer"?this.xrDragMode:this.dragMode)===5)&&(ss.lastHovered=s.object,s.button===0)){this._dragHandlers.size===0&&(this._didDrag=!1,this._totalMovement.set(0,0,0),this._potentialDragStartEvt=s),this._targetObject||this.setTargetObject(this.gameObject),ss._active+=1;const t=new Ff(this,this._targetObject);if(this._dragHandlers.set(s.event.space,t),t.onDragStart(s),this._dragHandlers.size===2){const i=this._dragHandlers.values(),n=i.next().value,o=i.next().value;if(n instanceof Ff&&o instanceof Ff){const r=new cR(this,this._targetObject,n,o);this._dragHandlers.set(this.gameObject,r),r.onDragStart(s)}else console.error("Attempting to construct a MultiTouchDragHandler with invalid DragPointerHandlers. This is likely a bug.",{a:n,b:o})}s.use()}}onPointerUp(s){if(en&&q.DrawLabel(s.point??this.gameObject.worldPosition,"POINTERUP:"+s.pointerId+", "+s.button,.03,3),!this.allowEdit(this.gameObject)||s.button!==0)return;this._potentialDragStartEvt=null;const t=this._dragHandlers.get(s.event.space),i=this._dragHandlers.get(this.gameObject);i&&(i.handlerA===t||i.handlerB===t)&&(this._dragHandlers.delete(this.gameObject),i.onDragEnd(s)),t&&(ss._active>0&&(ss._active-=1),this.setTargetObject(null),t.onDragEnd&&t.onDragEnd(s),this._dragHandlers.delete(s.event.space),this._dragHandlers.size===0&&this.onLastDragEnd(s),s.use())}update(){for(const s of this._dragHandlers.values())s.collectMovementInfo&&s.collectMovementInfo(),s.getTotalMovement&&this._totalMovement.add(s.getTotalMovement());if(this._potentialDragStartEvt){if(!this._didDrag)if(this._totalMovement.length()>3e-4)this._didDrag=!0;else return;const s=this._potentialDragStartEvt;this._potentialDragStartEvt=null,this.onFirstDragStart(s)}for(const s of this._dragHandlers.values())s.onDragUpdate&&s.onDragUpdate(this._dragHandlers.size);this._dragHelper&&this._dragHelper.hasSelected&&this.onAnyDragUpdate()}onFirstDragStart(s){if(!s||!s.object)return;const t=P.getComponentInParent(s.object,ss);if(!t||t!==this&&t._isDragging)return;const i=this._targetObject||this.gameObject;if(!i)return;this._isDragging=!0;const n=P.getComponentInChildren(i,qs);en&&console.log("DRAG START",n,i),n&&(n.fastMode=!0,n?.requestOwnership()),this._marker=P.addComponent(i,Jc),this._draggingRigidbodies.length=0;const o=P.getComponentsInChildren(i,ve);o&&this._draggingRigidbodies.push(...o)}onAnyDragUpdate(){if(!this._dragHelper)return;this._dragHelper.showGizmo=this.showGizmo,this._dragHelper.onUpdate(this.context);for(const t of this._draggingRigidbodies)t.wakeUp(),t.resetVelocities(),t.resetForcesAndTorques();const s=this._targetObject||this.gameObject;cs.markDirty(s)}onLastDragEnd(s){if(!this||!this._isDragging)return;this._isDragging=!1;for(const i of this._draggingRigidbodies)i.setVelocity(i.smoothedVelocity);if(this._draggingRigidbodies.length=0,this._targetObject=null,s!=null&&s.object){const i=P.getComponentInChildren(s.object,qs);i&&(i.fastMode=!1)}if(this._marker&&this._marker.destroy(),!this._dragHelper)return;const t=this._dragHelper.selected;en&&console.log("DRAG END",t,t?.visible),this._dragHelper.setSelected(null,this.context)}},a(th,"_active",0),a(th,"_instances",[]),a(th,"lastHovered"),th);let mi=ss;Nr([m()],mi.prototype,"dragMode",2),Nr([m()],mi.prototype,"snapGridResolution",2),Nr([m()],mi.prototype,"keepRotation",2),Nr([m()],mi.prototype,"xrDragMode",2),Nr([m()],mi.prototype,"xrKeepRotation",2),Nr([m()],mi.prototype,"xrDistanceDragFactor",2),Nr([m()],mi.prototype,"showGizmo",2);class cR{constructor(t,i,n,o){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 V),a(this,"_manipulatorPosOffset",new x),a(this,"_manipulatorRotOffset",new V),a(this,"_manipulatorScaleOffset",new x),a(this,"_tempVec1",new x),a(this,"_tempVec2",new x),a(this,"_tempVec3",new x),a(this,"tempLookMatrix",new ne),a(this,"_initialScale",new x),a(this,"_initialDistance",0);var r,l;this.context=t.context,this.settings=t,this.gameObject=i,this.handlerA=n,this.handlerB=o,this._followObject=new I,this._manipulatorObject=new I,this.context.scene.add(this._manipulatorObject);const c=(l=(r=J.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?(en&&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(i.scale),en){this._followObject.add(new wi(2)),this._manipulatorObject.add(new wi(5));const h=d=>`${d.x.toFixed(2)}, ${d.y.toFixed(2)}, ${d.z.toFixed(2)}`;q.DrawLine(this._tempVec1,this._tempVec2,65535,0,!1),q.DrawLabel(this._tempVec3,"A:B "+this._initialDistance.toFixed(2)+`
@@ -935,8 +935,8 @@ Incoming:`,this._incomingCalls),r}else nt&&console.error("Failed to make call",s
935
935
 
936
936
  Device: ${this._deviceMode}
937
937
 
938
- `,.03);const R=this._bottomCenter.clone(),M=this._backCenter.clone(),T=this._backBottomCenter.clone();i.localToWorld(R),i.localToWorld(M),i.localToWorld(T),q.DrawSphere(R,.01,65280,0,!1),q.DrawSphere(M,.01,255,0,!1),q.DrawSphere(T,.01,16711935,0,!1),q.DrawLine(R,T,65535,0,!1),q.DrawLine(T,M,65535,0,!1)}}onDragEnd(t){console.assert(this._followObject.parent===t.event.space,"Drag end: _followObject is not parented to the space object"),this._followObject.removeFromParent(),this._followObject.destroy(),this._lastDragPosRigSpace=void 0}setPlaneViewAligned(t,i){if(!this._followObject.parent)return!1;const n=this._followObject.parent.worldForward,o=G(0,1,0),r=n,l=o.angleTo(r),c=.5;return i&&(l>Math.PI/2+c||l<Math.PI/2-c)?this._dragPlane.setFromNormalAndCoplanarPoint(o,t):this._dragPlane.setFromNormalAndCoplanarPoint(n,t),!0}}const Zw=class{constructor(s){a(this,"showGizmo",!0),a(this,"useViewAngle",!0),a(this,"_selected",null),a(this,"_context",null),a(this,"_camera"),a(this,"_cameraPlane",new pr),a(this,"_hasGroundPlane",!1),a(this,"_groundPlane",new pr),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 ne),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=s;const t=new Xl(Zw.geometry),i=t.material;i.color=new re(.4,.4,.4),t.layers.set(2),t.name="line",t.scale.y=1,this._groundLine=t;const n=new hd(.5,22,22),o=new Re({color:i.color}),r=new K(n,o);r.visible=!1,r.layers.set(2),this._groundMarker=r}get hasSelected(){return this._selected!==null&&this._selected!==void 0}get selected(){return this._selected}setSelected(s,t){if(this._selected&&t)for(const i of this._rbs)i.wakeUp(),i.setVelocity(0,0,0);if(this._selected&&Qs.Remove(t,this._selected),this._selected=s,this._context=t,this._rbs.length=0,s?(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}Qs.Add(t,this._selected,null),this._groundOffsetFactor=0,this._hasGroundPlane=!0,this._groundOffset.set(0,0,0),this._requireUpdateGroundPlane=!0,this.onUpdateScreenSpacePlane()}}onUpdate(s){this._selected}onUpdateWorldPosition(s,t,i){if(this._selected){if(i){const n=te(this._selected);n.y=s.y,s=n}if(dt(this._selected,s),dt(this._groundLine,s),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),dt(this._groundMarker,t)}}}onUpdateScreenSpacePlane(){if(!this._selected||!this._context)return;const s=this._context.input.getPointerPositionRC(0);s&&(this._raycaster.setFromCamera(s,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 s=te(this._selected),t=new oo(G(0,.1,0).add(s),G(0,-1,0)),i=new Ws;i.testObject=o=>o!==this._selected;const n=this._context.physics.raycastFromRay(t,i);for(let o=0;o<n.length;o++){const r=n[o];if(!r.face||this.contains(this._selected,r.object))continue;const l=G(0,1,0);this._groundPlane.setFromNormalAndCoplanarPoint(l,r.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(s),this._groundOffset.copy(this._intersection).sub(s)}contains(s,t){if(s===t)return!0;if(s.children){for(const i of s.children)if(this.contains(i,t))return!0}return!1}};let hR=Zw;a(hR,"geometry",new bn().setFromPoints([new x(0,0,0),new x(0,-1,0)]));var Jw=(s=>(s.File_Spawned="file-spawned",s))(Jw||{});class dR{constructor(t,i,n,o,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=i,this.guid=n,this.file_name=o,this.file_hash=r,this.file_size=l,this.position=c,this.scale=h,this.sender=t,this.downloadUrl=d}}var jo;(s=>{const t=new Map;function i(o){var r;t.has(o.guid)&&n(o.guid);const l=new I;t.set(o.guid,l);const c=new I;c.position.y=-.5,l.add(c);const h=new K(new Gl(1,1,1,1,1,1),new Re({color:14540253,wireframe:!0,transparent:!0,opacity:.3}));h.position.y=.5,c.add(h);const d=new I;c.add(d);const u=new K(new Gl(1,1,1,1,1,1),new Re({color:12307660,transparent:!0,opacity:.4}));u.position.y=.5,d.scale.y=.01,d.add(u);const p=new K(new Fs(1,1,1,1),new Re({color:34,transparent:!0,opacity:.05,depthTest:!1}));return p.rotateX(-Math.PI/2),p.position.y=.51,u.add(p),o.parent.add(l),l.rotateY(Math.PI/2),o.position&&((r=l.position)==null||r.copy(o.position)),o.size&&(l.worldScale=new x().copy(o.size)),l.position.y=l.scale.y/2,{object:l,onProgress:g=>{d instanceof I&&d.scale.set(1,g,1)}}}s.addPreview=i;function n(o){const r=t.get(o);r&&(t.delete(o),r.removeFromParent())}s.removePreview=n})(jo||(jo={}));var uR=Object.defineProperty,pR=Object.getOwnPropertyDescriptor,nl=(s,t,i,n)=>{for(var o=n>1?void 0:n?pR(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&uR(t,i,o),o};const Ms=O("debugdroplistener");class mR extends CustomEvent{constructor(t){super("object-added",{detail:t})}}const gR="blob";class Dn extends A{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 _e),a(this,"onNetworkEvent",t=>{var i;if(!this.useNetworking){Ms&&console.debug("[DropListener] Ignoring networked event because networking is disabled",t);return}if((i=t.guid)!=null&&i.startsWith(this.guid)){const n=t.url;if(console.debug("[DropListener] Received networked event",t),n)if(Array.isArray(n))for(const o of n)this.addFromUrl(o,{screenposition:new oe,point:t.point,size:t.size},!0);else this.addFromUrl(n,{screenposition:new oe,point:t.point,size:t.size},!0)}}),a(this,"handlePaste",t=>{this.context.connection.allowEditing===!1||t.defaultPrevented||navigator.clipboard.readText().then(i=>{if(i&&(i.startsWith("http")||i.startsWith("https")||i.startsWith("blob"))){const n={screenposition:new oe(this.context.input.mousePosition.x,this.context.input.mousePosition.y)};this.testIfIsInDropArea(n)&&this.addFromUrl(i,n,!1)}}).catch(console.warn)}),a(this,"onDrag",t=>{this.context.connection.allowEditing!==!1&&t.preventDefault()}),a(this,"onDrop",async t=>{if(this.context.connection.allowEditing===!1||(Ms&&console.log(t),!(t!=null&&t.dataTransfer))||t["droplistener:handled"])return;t.preventDefault();const i={screenposition:new oe(t.offsetX,t.offsetY)};if(this.dropArea&&this.testIfIsInDropArea(i)===!1)return;t["droplistener:handled"]=!0;const n=t.dataTransfer.items;if(!n)return;const o=[];for(const r in n){const l=n[r];if(l.kind==="file"){const c=l.getAsFile();if(!c)continue;o.push(c)}else l.kind==="string"&&l.type=="text/plain"&&l.getAsString(c=>{this.addFromUrl(c,i,!1)})}o.length>0&&await this.addDroppedFiles(o,i)}),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(t,i){this.addFromUrl(t,{screenposition:new oe,point:i?.point,size:i?.size},!0)}forgetObjects(){this.removePreviouslyAddedObjects(!1)}async addFromUrl(t,i,n){Ms&&console.log("dropped url",t);try{if(t.startsWith("https://github.com/")){const l=t.split("/"),c=l[3],h=l[4],d=l[6],u=l.slice(7).join("/");t=`https://raw.githubusercontent.com/${c}/${h}/${d}/${u}`}else t.startsWith("https://polyhaven.com/a")&&(t=fR(t));if(!t)return null;const o=t.toLowerCase();if(o.endsWith(".hdr")||o.endsWith(".hdri")||o.endsWith(".exr")||o.endsWith(".png")||o.endsWith(".jpg")||o.endsWith(".jpeg"))return null;this.removePreviouslyAddedObjects();const r=await $u.loadFileFromURL(new URL(t),{guid:this.guid,context:this.context,parent:this.gameObject,point:i.point,size:i.size});if(r&&this._addedObjects.length<=0)return i.url=t,this.addObject(r,i,n)}catch{console.warn("String is not a valid URL",t)}return null}async addDroppedFiles(t,i){var n,o;if(Ms&&console.log("Add files",t),!!Array.isArray(t)&&t.length){this.deleteDropEvent(),this.removePreviouslyAddedObjects(),Kl(gR,null),(n=this._abort)==null||n.abort("New files dropped"),this._abort=new AbortController;for(const r of t){if(!r)continue;console.debug("Load file "+r.name);const l=await $u.loadFile(r,this.context,{guid:this.guid});if(l){this.dispatchEvent(new CustomEvent("file-dropped",{detail:r})),i.file=r;const c=this.addObject(l,i,!1);c&&this.context.connection.isConnected&&this.useNetworking&&(console.debug("Uploading dropped file to blob storage"),Rr.upload(r,{abort:(o=this._abort)==null?void 0:o.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(t=!0){if(t)for(const i of this._addedObjects)i.parent===this.gameObject&&Ri(i,!0,!0);this._addedObjects.length=0,this._addedModels.length=0}addObject(t,i,n){var o,r;const{model:l,contentMD5:c}=t;if(Ms&&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 _i().setFromCenterAndSize(new x(0,this.fitVolumeSize.y*.5,0).add(this.gameObject.worldPosition),this.fitVolumeSize);if(Ms&&q.DrawWireBox3(d,255,5),this.fitIntoVolume&&eb(h,d,{position:!this.placeAtHitPosition}),this.placeAtHitPosition&&i&&i.screenposition){h.visible=!1;const p=this.context.physics.raycast({screenPoint:this.context.input.convertScreenspaceToRaycastSpace(i.screenposition.clone())});if(h.visible=!0,p&&p.length>0)for(const g of p){const y=g.point.clone();Ms&&console.log("Place object at hit",g),tb(h,y);break}}Wa.assignAnimationsFromFile(l,{createAnimationComponent:p=>Mi(p,Wt)});const u=new mR({sender:this,gltf:l,model:l,object:h,contentMD5:c,dropped:i.file||(i.url?new URL(i.url):void 0)});return this.dispatchEvent(u),(o=this.onDropped)==null||o.invoke(u.detail),!n&&(r=i.url)!=null&&r.startsWith("http")&&this.context.connection.isConnected&&h&&this.sendDropEvent(i.url,h,c),h}async sendDropEvent(t,i,n){if(!this.useNetworking){Ms&&console.debug("[DropListener] Ignoring networked event because networking is disabled",t);return}if(this.context.connection.isConnected){console.debug('Sending drop event "'+i.name+'"',t);const o=ci([i]),r={name:i.name,guid:this.guid,url:t,point:i.worldPosition.clone(),size:o.getSize(new x),contentMD5:n};this.context.connection.send("droplistener",r)}}deleteDropEvent(){this.context.connection.sendDeleteRemoteState(this.guid)}testIfIsInDropArea(t){if(this.dropArea){const i=this.context.input.convertScreenspaceToRaycastSpace(t.screenposition.clone());if(!this.context.physics.raycast({targets:[this.dropArea],screenPoint:i,recursive:!0,testObject:n=>!this._addedObjects.includes(n)}).length)return F()&&console.log(`Dropped outside of drop area for DropListener "${this.name}".`),!1}return!0}}nl([m()],Dn.prototype,"useNetworking",2),nl([m(I)],Dn.prototype,"dropArea",2),nl([m()],Dn.prototype,"fitIntoVolume",2),nl([m(x)],Dn.prototype,"fitVolumeSize",2),nl([m()],Dn.prototype,"placeAtHitPosition",2),nl([m(_e)],Dn.prototype,"onDropped",2);function fR(s){if(!s.startsWith("https://polyhaven.com/"))return s;const t="https://dl.polyhaven.org/file/ph-assets/Models/gltf/4k/",i=new URL(s).pathname.split("/").pop(),n=`${t}${i}/${i}_4k.gltf`;return console.log("Resolved polyhaven asset url",s,"\u2192",n),n}var $u;(s=>{async function t(n,o,r){const l=n.name.toLowerCase();return l.endsWith(".gltf")||l.endsWith(".glb")||l.endsWith(".fbx")||l.endsWith(".obj")||l.endsWith(".usdz")||l.endsWith(".vrm")||n.type==="model/gltf+json"||n.type==="model/gltf-binary"?new Promise((c,h)=>{const d=new FileReader;d.readAsArrayBuffer(n),d.onloadend=async u=>{const p=d.result,g=r.guid,y=new zt(g),f=await fs().parseSync(o,p,n.name,y);if(f){const v=Rr.hashMD5(p);c({model:f,contentMD5:v})}}}):(console.warn("Unsupported file type: "+l,n.type),null)}s.loadFile=t;async function i(n,o){return new Promise(async(r,l)=>{const c=new zt(o.guid),h=n.toString();Ms&&q.DrawWireSphere(o.point,.1,16711680,3);const d=jo.addPreview({guid:o.guid,parent:o.parent,position:o?.point,size:o?.size}),u=await fs().loadSync(o.context,h,h,c,p=>{d.onProgress(p.loaded/p.total)}).catch(console.warn);if(u){const p=await fetch(h).then(y=>y.arrayBuffer()),g=Rr.hashMD5(p);Ms?setTimeout(()=>jo.removePreview(o.guid),3e3):jo.removePreview(o.guid),r({model:u,contentMD5:g})}else Ms?setTimeout(()=>jo.removePreview(o.guid),3e3):jo.removePreview(o.guid),console.warn("Unsupported file type: "+n.toString())})}s.loadFileFromURL=i})($u||($u={}));var yR=Object.defineProperty,vR=Object.getOwnPropertyDescriptor,qu=(s,t,i,n)=>{for(var o=n>1?void 0:n?vR(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&yR(t,i,o),o};const ex=class extends A{constructor(){super(...arguments),a(this,"parent",null),a(this,"object",null),a(this,"limitCount",10),a(this,"limitInterval",60),a(this,"_currentCount",0),a(this,"_startPosition",null),a(this,"_startQuaternion",null),a(this,"_forwardPointerEvents",new Map)}start(){var s,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 zt(this.guid);this.object=P.instantiate(this.object,{idProvider:n,keepWorldPosition:!1});const o=P.getComponent(this.object,ex);o?.destroy();let r=this.object.getComponentInChildren(mi);r||(r=this.object.addComponent(mi,{dragMode:Bf.SnapToSurfaces}),r.guid=n.generateUUID());let l=P.getComponent(r.gameObject,qs);l||(l=r.gameObject.addComponent(qs),l.guid=n.generateUUID())}this.object.visible=!1;const i=this.gameObject.getComponent(mi);i&&(i.enabled=!1),this._startPosition=((s=this.object.position)==null?void 0:s.clone())??new x(0,0,0),this._startQuaternion=((t=this.object.quaternion)==null?void 0:t.clone())??new V(0,0,0,1)}this.gameObject.getComponentInParent(Ei)||this.gameObject.addComponent(Ei),this.cloneLimitIntervalFn()}onPointerEnter(s){s.used||this.object&&this.context.connection.allowEditing&&s.button===0&&this.context.input.setCursor("pointer")}onPointerExit(s){s.used||this.object&&this.context.connection.allowEditing&&s.button===0&&this.context.input.unsetCursor("pointer")}onPointerDown(s){if(s.used||!this.object||!this.context.connection.allowEditing||s.button!==0)return;const t=this.handleDuplication();if(t){const i=P.getComponent(t,mi);i?(i.onPointerDown(s),this._forwardPointerEvents.set(s.event.space,i)):console.warn("Duplicated object does not have DragControls",t)}else console.warn("Could not duplicate object. Has the target object been destroyed?",this)}onPointerUp(s){if(s.used)return;const t=this._forwardPointerEvents.get(s.event.space);t&&(t.onPointerUp(s),this._forwardPointerEvents.delete(s.event.space))}cloneLimitIntervalFn(){this.destroyed||(this._currentCount>0&&(this._currentCount-=1),setTimeout(()=>{this.cloneLimitIntervalFn()},this.limitInterval/this.limitCount*1e3))}handleDuplication(){var s;if(!this.object||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 Ds;this.parent||(this.parent=this.gameObject.parent),this.parent&&(t.parent=this.parent.guid??((s=this.parent.userData)==null?void 0:s.guid),t.keepWorldPosition=!0),t.position=this.worldPosition,t.rotation=this.worldQuaternion,t.context=this.context,this._currentCount+=1;const i=P.instantiateSynced(this.object,t);return console.assert(i!==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),i}};let Wr=ex;qu([m(I)],Wr.prototype,"parent",2),qu([m(I)],Wr.prototype,"object",2),qu([m()],Wr.prototype,"limitCount",2),qu([m()],Wr.prototype,"limitInterval",2);var Bn=(s=>(s[s.PointerEnter=0]="PointerEnter",s[s.PointerExit=1]="PointerExit",s[s.PointerDown=2]="PointerDown",s[s.PointerUp=3]="PointerUp",s[s.PointerClick=4]="PointerClick",s[s.Drag=5]="Drag",s[s.Drop=6]="Drop",s[s.Scroll=7]="Scroll",s[s.UpdateSelected=8]="UpdateSelected",s[s.Select=9]="Select",s[s.Deselect=10]="Deselect",s[s.Move=11]="Move",s[s.InitializePotentialDrag=12]="InitializePotentialDrag",s[s.BeginDrag=13]="BeginDrag",s[s.EndDrag=14]="EndDrag",s[s.Submit=15]="Submit",s[s.Cancel=16]="Cancel",s))(Bn||{}),bR=Object.defineProperty,_R=Object.getOwnPropertyDescriptor,zf=(s,t,i,n)=>{for(var o=n>1?void 0:n?_R(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&bR(t,i,o),o};class Uf{constructor(){a(this,"eventID"),a(this,"callback",new _e)}}zf([m()],Uf.prototype,"eventID",2),zf([m(_e)],Uf.prototype,"callback",2);class Gu extends A{constructor(){super(...arguments),a(this,"triggers",[])}invoke(t){var i;if(this.triggers)for(const n of this.triggers)n.eventID===t&&((i=n.callback)==null||i.invoke())}hasTrigger(t){var i;return((i=this.triggers)==null?void 0:i.some(n=>n.eventID===t))??!1}shouldChangeCursor(){return this.hasTrigger(Bn.PointerClick)||this.hasTrigger(Bn.PointerDown)||this.hasTrigger(Bn.PointerUp)}onPointerClick(t){this.invoke(Bn.PointerClick)}onPointerEnter(t){this.shouldChangeCursor()&&this.context.input.setCursor("pointer"),this.invoke(Bn.PointerEnter)}onPointerExit(t){this.shouldChangeCursor()&&this.context.input.unsetCursor("pointer"),this.invoke(Bn.PointerExit)}onPointerDown(t){this.invoke(Bn.PointerDown)}onPointerUp(t){this.invoke(Bn.PointerUp)}}zf([m(Uf)],Gu.prototype,"triggers",2);class tx{constructor(t){a(this,"writer"),this.writer=t}writeNode(t){}}class wR extends tx{beforeWriteNode(t,i){q.isGizmo(t)&&(i.keep=!1)}}class ix extends tx{beforeWriteTexture(t,i){t.isRenderTargetTexture&&(i.newTexture=Kg(new Se(1,1,1,0)))}}function Nf(s){const t=Uu.DontExport;return!(s.hideFlags&t)}const Wf=O("debugexr");class xR{constructor(t){a(this,"parser"),this.parser=t,Wf&&console.log(t)}get name(){return"EXT_texture_exr"}loadTexture(t){const i=this.name,n=this.parser,o=n.json.textures[t];if(Wf&&console.log("EXT_texture_exr.loadTexture",t,o),!o.extensions||!o.extensions[i])return null;const r=o.extensions[i],l=new vd(n.options.manager);return Wf&&console.log("EXT_texture_exr.loadTexture",r),n.loadTextureImage(t,r.source,l)}}typeof window<"u"&&window.addEventListener("unhandledrejection",s=>{});const Fn=vt,Xu="$___Export_Components",SR="NEEDLE_components";var sx;class CR{constructor(){a(this,sx)}}sx=_r;class OR{constructor(t,i,n){a(this,"node"),a(this,"nodeIndex"),a(this,"nodeDef"),this.node=t,this.nodeIndex=i,this.nodeDef=n}}class nx{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 SR}registerExport(t){t.register(i=>{if("serializeUserData"in i){const n=i.serializeUserData.bind(i);this.writer=i,i.serializeUserData=(o,r)=>{try{this.serializeUserData(o,r)&&(i.extensionsUsed[this.name]=!0),n(o,r)}finally{this.afterSerializeUserData(o,r)}}}return this})}beforeParse(){this.exportContext={},this.objectToNodeMap={}}serializeUserData(t,i){var n;const o=(n=t.userData)==null?void 0:n.components;return!o||o.length<=0?!1:(delete t.userData.components,t[Xu]=o,!0)}afterSerializeUserData(t,i){if(t.type==="Scene"&&Fn&&console.log("DONE",JSON.stringify(i)),t[Xu]===void 0)return;const n=t[Xu];delete t[Xu],n!==null&&(t.userData.components=n)}writeNode(t,i){const n=this.writer.json.nodes.length;Fn&&console.log(t.name,n,t.uuid);const o=new OR(t,n,i);this.exportContext[n]=o,this.objectToNodeMap[t.uuid]=n}afterParse(t){var i;Fn&&console.log("AFTER",t);for(const n in this.exportContext){const o=this.exportContext[n],r=o.node,l=o.nodeDef,c=o.nodeIndex,h=(i=r.userData)==null?void 0:i.components;if(!h||h.length<=0)continue;const d=new CR;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=fs().writeBuiltinComponentData(p,this.context);g!==null&&u.push(g)}u.length>0&&(d[_r]=u,Fn&&console.log("DID WRITE",r,"nodeIndex",c,u))}}beforeRoot(){return Fn&&console.log("BEGIN LOAD"),this.nodeToObjectMap={},null}async afterRoot(t){this.gltf=t;const i=t.parser,n=i?.extensions;if(!n)return;const o=n[this.name];Fn&&console.log("After root",t,this.parser,n);const r=[];if(o===!0){const l=i.json.nodes;if(l){for(let c=0;c<l.length;c++){const h=await i.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;Fn&&console.log("NODE",h);const g=this.nodeToObjectMap[d];if(!g){console.error("Could not find object for node index: "+d,h,i);continue}Jd(g),r.push(this.createComponents(g,p))}}}await Promise.all(r);for(const l of i.associations.keys()){const c=i.associations.get(l);if(c?.materials!=null){const h="/materials/"+c.materials;P2(l,h)}}}async createComponents(t,i){if(!i)return;const n=i[_r];if(n){const o=new Array;Fn&&console.log(t.name,n);for(const r in n){const l=n[r];Fn&&console.log("Serialized data",JSON.parse(JSON.stringify(l))),l&&this.parser&&o.push(zg(this.parser,l).catch(c=>console.error(`Error while resolving references (see console for details)
939
- `,c,t,l))),t.userData=t.userData||{},t.userData[_r]=t.userData[_r]||[],t.userData[_r].push(l)}await Promise.all(o).catch(r=>{console.error("Error while loading components",r)})}}}const ox="NEEDLE_gameobject_data";class PR{constructor(t){a(this,"parser"),this.parser=t}get name(){return ox}afterRoot(t){var i;const n=[];for(let o=0;o<((i=this.parser.json.nodes)==null?void 0:i.length);o++){const r=this.parser.json.nodes[o];if(r&&r.extensions){const l=r.extensions[ox];if(l){const c=this.findAndApplyExtensionData(o,l);n.push(c)}}}return Promise.all(n).then(()=>null)}async findAndApplyExtensionData(t,i){const n=await this.parser.getDependency("node",t);n&&this.applyExtensionData(n,i)}applyExtensionData(t,i){i.layers===void 0&&(i.layers=0),t.userData.layer=i.layers,t.layers.disableAll(),t.layers.set(i.layers),t.userData.tag=i.tag??"none",t.hideFlags=0,t.userData.static=i.static??!1,t.visible=i.activeSelf??!0,t.guid=i.guid}}const rx="NEEDLE_lighting_settings",ol=O("debugenvlight");class kR{constructor(t,i,n){a(this,"parser"),a(this,"sourceId"),a(this,"context"),this.parser=t,this.sourceId=i,this.context=n}get name(){return rx}afterRoot(t){const i=this.parser.json.extensions;if(i){const n=i[rx];if(n){ol&&console.log('Loaded "'+this.name+'", src: "'+this.sourceId+'"',n);let o;if(t.scene.children.length===1){const r=t.scene.children[0];o=P.addComponent(r,Qu,{},{callAwake:!1})}else{const r=new I;r.name="LightSettings "+this.sourceId,t.scene.add(r),o=P.addComponent(r,Qu,{},{callAwake:!1})}o.sourceId=this.sourceId,o.ambientIntensity=n.ambientIntensity,o.ambientLight=new re().fromArray(n.ambientLight),Array.isArray(n.ambientTrilight)&&(o.ambientTrilight=n.ambientTrilight.map(r=>new re().fromArray(r))),o.ambientMode=n.ambientMode,o.environmentReflectionSource=n.environmentReflectionSource}}return null}}ge.registerCallback(ye.ContextCreated,s=>{const t=s.context,i=P.findObjectOfType(Qu,t);i!=null&&i.sourceId&&(i.enabled=!0)});class Qu extends A{constructor(){super(...arguments),a(this,"ambientMode",Ha.Skybox),a(this,"ambientLight"),a(this,"ambientTrilight"),a(this,"ambientIntensity",1),a(this,"environmentReflectionSource",gu.Skybox),a(this,"_hasReflection",!1),a(this,"_ambientLightObj"),a(this,"_hemisphereLightObj")}awake(){var t;if(this.sourceId){const n=this.environmentReflectionSource===gu.Skybox?vo.Skybox:vo.Reflection,o=this.context.lightmaps.tryGet(this.sourceId,n,0);this._hasReflection=o!=null,o&&this.context.sceneLighting.internalRegisterReflection(this.sourceId,o)}this.enabled=!1,this.context.sceneLighting.internalRegisterSceneLightSettings(this),ol&&window.addEventListener("keydown",n=>{if(!this.destroyed)switch(n.key){case"l":this.enabled=!this.enabled;break}});const i=(t=this.gameObject.userData)==null?void 0:t.components;if(i){const n=i.indexOf(this);i.splice(n,1),i.push(this)}}onDestroy(){this.context.sceneLighting.internalUnregisterSceneLightSettings(this)}calculateIntensityFactor(t){const i=Math.max(t.r,t.g,t.b);return 2.2*W.lerp(0,1.33,i)}onEnable(){if(ol&&console.warn("\u{1F4A1}\u{1F7E1} >>> Enable lighting",this.sourceId,this.enabled,this),this.ambientMode==Ha.Flat){if(this.ambientLight&&!this._ambientLightObj){const t=this.calculateIntensityFactor(this.ambientLight);this._ambientLightObj=new LS(this.ambientLight,this.ambientIntensity*t),ol&&console.log("Created ambient light",this.sourceId,this._ambientLightObj,this.ambientIntensity,t)}this._ambientLightObj&&this.gameObject.add(this._ambientLightObj)}else if(this.ambientMode===Ha.Trilight){if(this.ambientTrilight){const t=this.ambientTrilight[0],i=this.ambientTrilight[this.ambientTrilight.length-1],n=this.calculateIntensityFactor(i);this._hemisphereLightObj=new DS(i,t,this.ambientIntensity*n),this.gameObject.add(this._hemisphereLightObj),ol&&console.log("Created hemisphere ambient light",this.sourceId,this._hemisphereLightObj,this.ambientIntensity,n)}}else this._ambientLightObj&&this._ambientLightObj.removeFromParent(),this._hemisphereLightObj&&this._hemisphereLightObj.removeFromParent();this.sourceId&&this.context.sceneLighting.internalEnableReflection(this.sourceId)}onDisable(){ol&&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 Vf=O("debugstencil");function MR(s,t){return(s&1<<t.layer)!=0}const RR=Symbol("stencils"),rl=class{constructor(s,t){a(this,"parser"),a(this,"source"),this.parser=s,this.source=t}get name(){return"NEEDLE_render_objects"}static applyStencil(s){if(!s)return;const t=s.sourceId;if(Vf&&console.log(t,rl.stencils),!t)return;const i=rl.stencils[t];if(i)for(let n=i.length-1;n>=0;n--){const o=i[n];if(MR(o.layer,s)){Vf&&console.log(o),setTimeout(()=>{Gt()&&iu(s.gameObject)&&(xe("Stencil not supported on instanced objects"),console.warn("Stencil not supported on instanced objects",s))},500);for(let r=0;r<s.sharedMaterials.length;r++){let l=s.sharedMaterials[r];l&&(l=l.clone(),l[RR]=!0,l.stencilWrite=!0,l.stencilWriteMask=255,l.stencilFuncMask=255,l.stencilRef=o.value,l.stencilFunc=o.compareFunc,l.stencilZPass=o.passOp,l.stencilFail=o.failOp,l.stencilZFail=o.zFailOp,s.sharedMaterials[r]=l)}s.gameObject.renderOrder=o.event*1e3+o.index*50;break}}}afterRoot(s){const t=this.parser.json.extensions;if(t){const i=t[ER];if(i){Vf&&console.log(i);const n=i.stencil;if(n&&Array.isArray(n))for(const o of n){const r={...o};r.compareFunc=TR(r.compareFunc),r.passOp=$f(r.passOp),r.failOp=$f(r.failOp),r.zFailOp=$f(r.zFailOp),rl.stencils[this.source]||(rl.stencils[this.source]=[]),rl.stencils[this.source].push(r)}}}return null}};let Hf=rl;a(Hf,"stencils",{});function $f(s){switch(s){case 0:return HS;case 1:return VS;case 2:return WS;case 3:return NS;case 4:return US;case 6:return zS;case 7:return FS;case 5:return BS}return 0}function TR(s){switch(s){case 1:return Zy;case 2:return KS;case 3:return YS;case 4:return QS;case 5:return XS;case 6:return GS;case 7:return qS;case 8:return $S}return Zy}const ER="NEEDLE_render_objects";var ax=(s=>(s[s.INT=5124]="INT",s[s.FLOAT=5126]="FLOAT",s[s.FLOAT_VEC2=35664]="FLOAT_VEC2",s[s.FLOAT_VEC3=35665]="FLOAT_VEC3",s[s.FLOAT_VEC4=35666]="FLOAT_VEC4",s[s.INT_VEC2=35667]="INT_VEC2",s[s.INT_VEC3=35668]="INT_VEC3",s[s.INT_VEC4=35669]="INT_VEC4",s[s.BOOL=35670]="BOOL",s[s.BOOL_VEC2=35671]="BOOL_VEC2",s[s.BOOL_VEC3=35672]="BOOL_VEC3",s[s.BOOL_VEC4=35673]="BOOL_VEC4",s[s.FLOAT_MAT2=35674]="FLOAT_MAT2",s[s.FLOAT_MAT3=35675]="FLOAT_MAT3",s[s.FLOAT_MAT4=35676]="FLOAT_MAT4",s[s.SAMPLER_2D=35678]="SAMPLER_2D",s[s.SAMPLER_3D=35680]="SAMPLER_3D",s[s.SAMPLER_CUBE=35681]="SAMPLER_CUBE",s[s.UNKNOWN=0]="UNKNOWN",s))(ax||{});const tn=O("debugcustomshader"),al="NEEDLE_techniques_webgl";class AR{constructor(){a(this,"objectToWorldMatrix",new ne),a(this,"worldToObjectMatrix",new ne),a(this,"objectToWorld",new Array),a(this,"worldToObject",new Array)}updateFrom(t){this.objectToWorldMatrix.copy(t.matrixWorld),mu(this.objectToWorldMatrix,this.objectToWorld),this.worldToObjectMatrix.copy(t.matrixWorld).invert(),mu(this.worldToObjectMatrix,this.worldToObject)}}const Ve=class extends Jy{constructor(s,...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 AR),this.identifier=s,tn&&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 s=super.clone();return lx(s),s}dispose(){super.dispose();const s=ee.Current.pre_render_callbacks.indexOf(this.onBeforeRenderSceneCallback);s>=0&&ee.Current.pre_render_callbacks.splice(s,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(s,t,i,n,o,r){n.attributes.tangent||n.computeTangents(),this.onUpdateUniforms(i,o)}onUpdateUniforms(s,t){const i=ee.Current;if(s&&(Ve.viewProjection&&this.uniforms[this._viewProjectionName]&&(Ve.viewProjection.copy(s.projectionMatrix).multiply(s.matrixWorldInverse),mu(Ve.viewProjection,Ve._viewProjectionValues)),Ve.viewMatrix&&this.uniforms[this._viewMatrixName]&&(Ve.viewMatrix.copy(s.matrixWorldInverse),mu(Ve.viewMatrix,Ve._viewMatrixValues)),this.uniforms[Ve._worldSpaceCameraPosName]&&Ve._worldSpaceCameraPos.setFromMatrixPosition(s.matrixWorld)),this.uniforms._TimeParameters&&(this.uniforms._TimeParameters.value=i.sceneLighting.timeVec4),this.uniforms._Time){const l=this.uniforms._Time.value;l.x=i.sceneLighting.timeVec4.x/20,l.y=i.sceneLighting.timeVec4.x,l.z=i.sceneLighting.timeVec4.x*2,l.w=i.sceneLighting.timeVec4.x*3}if(this.uniforms._SinTime){const l=this.uniforms._SinTime.value;l.x=Math.sin(i.sceneLighting.timeVec4.x/8),l.y=Math.sin(i.sceneLighting.timeVec4.x/4),l.z=Math.sin(i.sceneLighting.timeVec4.x/2),l.w=Math.sin(i.sceneLighting.timeVec4.x)}if(this.uniforms._CosTime){const l=this.uniforms._CosTime.value;l.x=Math.cos(i.sceneLighting.timeVec4.x/8),l.y=Math.cos(i.sceneLighting.timeVec4.x/4),l.z=Math.cos(i.sceneLighting.timeVec4.x/2),l.w=Math.cos(i.sceneLighting.timeVec4.x)}if(this.uniforms.unity_DeltaTime){const l=this.uniforms.unity_DeltaTime.value;l.x=i.time.deltaTime,l.y=1/i.time.deltaTime,l.z=i.time.smoothedDeltaTime,l.w=1/i.time.smoothedDeltaTime}const n=i.mainLight;if(n){const l=te(n.gameObject,Ve._mainLightPosition);this.uniforms._MainLightPosition={value:l.normalize()},Ve._mainLightColor.set(n.color.r,n.color.g,n.color.b,0),this.uniforms._MainLightColor={value:Ve._mainLightColor};const c=n.intensity;Ve._lightData.z=c,this.uniforms.unity_LightData={value:Ve._lightData}}if(s&&(Ve.viewProjection&&this.uniforms[this._viewProjectionName]&&(this.uniforms[this._viewProjectionName].value=Ve._viewProjectionValues),Ve.viewMatrix&&this.uniforms[this._viewMatrixName]&&(this.uniforms[this._viewMatrixName].value=Ve._viewMatrixValues),this.uniforms[Ve._worldSpaceCameraPosName]&&(this.uniforms[Ve._worldSpaceCameraPosName]={value:Ve._worldSpaceCameraPos}),i.mainCameraComponent)){if(this.uniforms._ProjectionParams){const l=this.uniforms._ProjectionParams.value;l.x=1,l.y=i.mainCameraComponent.nearClipPlane,l.z=i.mainCameraComponent.farClipPlane,l.w=1/l.z,this.uniforms._ProjectionParams.value=l}if(this.uniforms._ZBufferParams){const l=this.uniforms._ZBufferParams.value,c=i.mainCameraComponent;l.x=1-c.farClipPlane/c.nearClipPlane,l.y=c.farClipPlane/c.nearClipPlane,l.z=l.x/c.farClipPlane,l.w=l.y/c.farClipPlane,this.uniforms._ZBufferParams.value=l}if(this.uniforms._ScreenParams){const l=this.uniforms._ScreenParams.value;l.x=i.domWidth,l.y=i.domHeight,l.z=1+1/l.x,l.w=1+1/l.y,this.uniforms._ScreenParams.value=l}if(this.uniforms._ScaledScreenParams){const l=this.uniforms._ScaledScreenParams.value;l.x=i.domWidth,l.y=i.domHeight,l.z=1+1/l.x,l.w=1+1/l.y,this.uniforms._ScaledScreenParams.value=l}}const o=this.depthTextureUniform;o&&(o.value=i.depthTexture);const r=this.opaqueTextureUniform;if(r&&(r.value=i.opaqueColorTexture),t){const l=this._rendererData;l.updateFrom(t),this.uniforms[this._worldToObjectName].value=l.worldToObject,this.uniforms[this._objToWorldName].value=l.objectToWorld}this.uniformsNeedUpdate=!0}};let Rs=Ve;a(Rs,"viewProjection",new ne),a(Rs,"_viewProjectionValues",[]),a(Rs,"viewMatrix",new ne),a(Rs,"_viewMatrixValues",[]),a(Rs,"_worldSpaceCameraPosName","_WorldSpaceCameraPos"),a(Rs,"_worldSpaceCameraPos",new x),a(Rs,"_mainLightColor",new me),a(Rs,"_mainLightPosition",new x),a(Rs,"_lightData",new me);class IR{constructor(t,i){a(this,"parser"),a(this,"identifier"),this.parser=t,this.identifier=i}get name(){return al}loadMaterial(t){const i=this.parser.json.materials[t];if(!i)return tn&&console.log(t,this.parser.json.materials),null;if(!i.extensions||!i.extensions[al])return tn&&console.log(`Material ${t} does not use NEEDLE_techniques_webgl`),null;tn&&console.log(`Material ${t} uses NEEDLE_techniques_webgl`,i);const n=i.extensions[al].technique;if(n<0)return console.debug(`Material ${t} does not have a valid technique index`),null;const o=this.parser.json.extensions[al];if(!o)return tn?console.error("Missing shader data",this.parser.json.extensions):console.debug("Missing custom shader data in parser.json.extensions"),null;tn&&console.log(o);const r=o.techniques[n];return r?new Promise(async(l,c)=>{var h,d,u;const p=await ik(o,r.program),g=p?.fragmentShader,y=p?.vertexShader;if(!g||!y)return c();tn&&console.log("loadMaterial",i,p);const f={},v=r.uniforms;(y.includes("_Time")||g.includes("_Time"))&&(f._Time={value:new me(0,0,0,0)}),(y.includes("_SinTime")||g.includes("_SinTime"))&&(f._SinTime={value:new me(0,0,0,0)}),(y.includes("_CosTime")||g.includes("_CosTime"))&&(f._CosTime={value:new me(0,0,0,0)}),(y.includes("unity_DeltaTime")||g.includes("unity_DeltaTime"))&&(f.unity_DeltaTime={value:new me(0,0,0,0)});for(const _ in v){const C=_;switch(C){case"_TimeParameters":const R=new me;f[C]={value:R};break;case"hlslcc_mtx4x4unity_MatrixV":case"hlslcc_mtx4x4unity_MatrixVP":f[C]={value:[]};break;case"_MainLightPosition":case"_MainLightColor":case"_WorldSpaceCameraPos":f[C]={value:[0,0,0,1]};break;case"unity_OrthoParams":break;case"unity_SpecCube0":f[C]={value:null};break;default:case"_ScreenParams":case"_ZBufferParams":case"_ProjectionParams":f[C]={value:[0,0,0,0]};break;case"_CameraOpaqueTexture":case"_CameraDepthTexture":f[C]={value:null};break}}let b=!1;if(i.extensions&&i.extensions[al]){const _=i.extensions[al];if(_.technique===n){tn&&console.log(i.name,"Material Properties",_);for(const C in _.values){const R=_.values[C];if(typeof R=="string"){if(R.startsWith("/textures/")){const M=R.substring(10),T=Number.parseInt(M);if(T>=0){const j=await this.parser.getDependency("texture",T);j instanceof Le&&(j.colorSpace=mr,j.needsUpdate=!0),f[C]={value:j};continue}}switch(C){case"alphaMode":R==="BLEND"&&(b=!0);continue}}if(Array.isArray(R)&&R.length===4){f[C]={value:new me(R[0],R[1],R[2],R[3])};continue}f[C]={value:R}}}}const w=new Rs(this.identifier,{name:i.name??"",uniforms:f,vertexShader:y,fragmentShader:g,lights:!1});switch(w.glslVersion=ZS,w.vertexShader=w.vertexShader.replace("#version 300 es",""),w.fragmentShader=w.fragmentShader.replace("#version 300 es",""),(h=f._Cull)==null?void 0:h.value){case 0:w.side=xi;break;case 1:w.side=ym;break;case 2:w.side=co;break;default:w.side=co;break}switch((d=f._ZTest)==null?void 0:d.value){case 3:w.depthTest=!0,w.depthFunc=oC;break;case 6:w.depthTest=!0,w.depthFunc=nC;break;case 2:w.depthTest=!0,w.depthFunc=sC;break;case 4:w.depthTest=!0,w.depthFunc=iC;break;case 5:w.depthTest=!0,w.depthFunc=tC;break;case 7:w.depthTest=!0,w.depthFunc=eC;break;case 8:w.depthTest=!1,w.depthFunc=JS;break}w.transparent=b,b&&(w.depthWrite=!1),ek(f),w.onUpdateUniforms();for(const _ in v){const C=_,R=v[_].type;if(((u=f[C])==null?void 0:u.value)===void 0)switch(R){case ax.SAMPLER_2D:f[C]={value:Z2},console.warn("Missing/unassigned texture, fallback to white: "+C);break;default:C==="unity_OrthoParams"||console.warn("TODO: EXPECTED UNIFORM / fallback NOT SET: "+C,v[_]);break}}tn&&console.log(w.uuid,f),lx(w),l(w)}):null}}function lx(s){if(s.uniforms){tn&&console.log("Uniforms:",s.uniforms);for(const i in s.uniforms)switch(t(i,i),i){case"_Color":t("color",i);break}}function t(i,n){Object.getOwnPropertyDescriptor(s,i)||Object.defineProperty(s,i,{get:()=>s.uniforms[n].value,set:o=>{s.uniforms[n].value=o,s.needsUpdate=!0}})}}const jR=O("debugextensions");let Yu;const LR=import("./three-examples.light.min.js").then(s=>s.r).then(async s=>(Yu=s.GLTFAnimationPointerExtension,Yu)).catch(s=>{console.warn("Failed to import GLTFLoaderAnimationPointer. Please use @needle-tools/three for full KHR_animation support",s)}),Vr=new Array;function DR(s){Vr.includes(s)||Vr.push(s)}function BR(s){const t=Vr.indexOf(s);t>=0&&Vr.splice(t,1)}function Ku(s){const t=new nx;return s.register(i=>(t.parser=i,t)),t}class FR{resolvePath(t){return t.includes("/extensions/builtin_components/")?t.replace("/extensions/builtin_components/","/userData/components/"):t.includes("extensions/builtin_components/")?t.replace("extensions/builtin_components/","/userData/components/"):t}}async function Zu(s,t,i){const n=i.indexOf("?");n>=0&&(i=i.substring(0,n)),s.register(o=>new PR(o)),s.register(o=>new M2(o)),s.register(o=>new X2(o,t.lightmaps,i)),s.register(o=>new kR(o,i,t)),s.register(o=>new IR(o,i)),s.register(o=>new Hf(o,i)),s.register(o=>new it(o,i)),s.register(o=>new xR(o)),Qb()&&s.register(o=>new Cg(o)),await LR.catch(o=>{}),s.register(o=>{if(Yu){const r=new Yu(o);return r.setAnimationPointerResolver.bind(r)(new FR),r}else return(jR||F())&&console.error("Missing KHR_animation_pointer extension..."),{name:"KHR_animation_pointer_NOT_AVAILABLE"}});for(const o of Vr)o.onImport&&o.onImport(s,i,t)}function qf(s,t){for(const i of Vr)i.onExport&&i.onExport(s,t)}function Gf(s,t,i){for(const n of Vr)n.onLoaded&&n.onLoaded(s,t,i)}class cx{constructor(t){this.writer=t,this.name="EXT_mesh_gpu_instancing"}writeNode(t,i){if(t.constructor.name!=="InstancedMesh")return;const n=this.writer,o=n.extensionsUsed,r={};i.extensions=i.extensions||{},i.extensions[this.name]=r;let l=new ne;const c=new Array,h=new Array,d=new Array;for(let y=0;y<t.count;y++){t.getMatrixAt(y,l);let f=new x,v=new V,b=new x;l.decompose(f,v,b),c.push(f.x,f.y,f.z),h.push(v.x,v.y,v.z,v.w),d.push(b.x,b.y,b.z)}const u=new Float32Array(c),p=new Float32Array(h),g=new Float32Array(d);r.attributes={TRANSLATION:n.processAccessor(new ft(u,3)),ROTATION:n.processAccessor(new ft(p,4)),SCALE:n.processAccessor(new ft(g,3))},o[this.name]=!0}}var zR=Object.defineProperty,UR=Object.getOwnPropertyDescriptor,hx=(s,t,i,n)=>{for(var o=n>1?void 0:n?UR(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&zR(t,i,o),o};const Ju=O("debugreflectionprobe"),dx=O("noreflectionprobe"),NR=Symbol("reflectionProbeKey"),WR=Symbol("original material");var ep;const zn=(ep=class extends A{constructor(){var s;super(),a(this,"_texture"),a(this,"center"),a(this,"size"),a(this,"_boxHelper"),zn._probes.has(this.context)||zn._probes.set(this.context,[]),(s=zn._probes.get(this.context))==null||s.push(this)}static get(s,t,i,n){if(!s||s.isObject3D!==!0||dx)return null;const o=zn._probes.get(t);if(o){for(const r of o)if(r.__didAwake||r.__internalAwake(),r.enabled&&n&&r.gameObject===n)return r}return Ju&&console.debug("Did not find reflection probe",s.name,i,s),null}set texture(s){if(s&&!(s instanceof Le)){console.error("ReflectionProbe.texture must be a Texture",s);return}this._texture=s,s&&(s.mapping=wn,s.colorSpace=gs,s.needsUpdate=!0)}get texture(){return this._texture}isInBox(s){var t;return(t=this._boxHelper)==null?void 0:t.isInBox(s)}awake(){this._boxHelper=this.gameObject.addComponent(is),this._boxHelper.updateBox(!0),Ju&&this._boxHelper.showHelper(5592320,!0),this.texture&&(this.texture.mapping=wn,this.texture.colorSpace=gs,this.texture.needsUpdate=!0)}onDestroy(){const s=zn._probes.get(this.context);if(s){const t=s.indexOf(this);t>=0&&s.splice(t,1)}}onSet(s){var t;if(dx||!this.enabled||((t=s.sharedMaterials)==null?void 0:t.length)<=0||!this.texture)return;let i=zn._rendererMaterialsCache.get(s);i||(i=[],zn._rendererMaterialsCache.set(s,i));for(let n=0;n<s.sharedMaterials.length;n++){const o=s.sharedMaterials[n];if(!o||o.envMap===void 0||o instanceof Re)continue;let r=i[n];const l=o===r?.copy,c=!r||r.material.uuid!==o.uuid||r.copy.version!==o.version;if(!l&&c){if(Ju){let u="";r?r.material!==o?u="reference changed; cached instance?: "+l:r.copy.version!==o.version&&(u="version changed"):u="not cached",console.warn("Cloning material",o.name,o.version,"Reason:",u,`
938
+ `,.03);const R=this._bottomCenter.clone(),M=this._backCenter.clone(),T=this._backBottomCenter.clone();i.localToWorld(R),i.localToWorld(M),i.localToWorld(T),q.DrawSphere(R,.01,65280,0,!1),q.DrawSphere(M,.01,255,0,!1),q.DrawSphere(T,.01,16711935,0,!1),q.DrawLine(R,T,65535,0,!1),q.DrawLine(T,M,65535,0,!1)}}onDragEnd(t){console.assert(this._followObject.parent===t.event.space,"Drag end: _followObject is not parented to the space object"),this._followObject.removeFromParent(),this._followObject.destroy(),this._lastDragPosRigSpace=void 0}setPlaneViewAligned(t,i){if(!this._followObject.parent)return!1;const n=this._followObject.parent.worldForward,o=G(0,1,0),r=n,l=o.angleTo(r),c=.5;return i&&(l>Math.PI/2+c||l<Math.PI/2-c)?this._dragPlane.setFromNormalAndCoplanarPoint(o,t):this._dragPlane.setFromNormalAndCoplanarPoint(n,t),!0}}const Zw=class{constructor(s){a(this,"showGizmo",!0),a(this,"useViewAngle",!0),a(this,"_selected",null),a(this,"_context",null),a(this,"_camera"),a(this,"_cameraPlane",new pr),a(this,"_hasGroundPlane",!1),a(this,"_groundPlane",new pr),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 ne),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=s;const t=new Xl(Zw.geometry),i=t.material;i.color=new re(.4,.4,.4),t.layers.set(2),t.name="line",t.scale.y=1,this._groundLine=t;const n=new hd(.5,22,22),o=new Re({color:i.color}),r=new K(n,o);r.visible=!1,r.layers.set(2),this._groundMarker=r}get hasSelected(){return this._selected!==null&&this._selected!==void 0}get selected(){return this._selected}setSelected(s,t){if(this._selected&&t)for(const i of this._rbs)i.wakeUp(),i.setVelocity(0,0,0);if(this._selected&&Qs.Remove(t,this._selected),this._selected=s,this._context=t,this._rbs.length=0,s?(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}Qs.Add(t,this._selected,null),this._groundOffsetFactor=0,this._hasGroundPlane=!0,this._groundOffset.set(0,0,0),this._requireUpdateGroundPlane=!0,this.onUpdateScreenSpacePlane()}}onUpdate(s){this._selected}onUpdateWorldPosition(s,t,i){if(this._selected){if(i){const n=te(this._selected);n.y=s.y,s=n}if(dt(this._selected,s),dt(this._groundLine,s),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),dt(this._groundMarker,t)}}}onUpdateScreenSpacePlane(){if(!this._selected||!this._context)return;const s=this._context.input.getPointerPositionRC(0);s&&(this._raycaster.setFromCamera(s,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 s=te(this._selected),t=new oo(G(0,.1,0).add(s),G(0,-1,0)),i=new Ws;i.testObject=o=>o!==this._selected;const n=this._context.physics.raycastFromRay(t,i);for(let o=0;o<n.length;o++){const r=n[o];if(!r.face||this.contains(this._selected,r.object))continue;const l=G(0,1,0);this._groundPlane.setFromNormalAndCoplanarPoint(l,r.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(s),this._groundOffset.copy(this._intersection).sub(s)}contains(s,t){if(s===t)return!0;if(s.children){for(const i of s.children)if(this.contains(i,t))return!0}return!1}};let hR=Zw;a(hR,"geometry",new bn().setFromPoints([new x(0,0,0),new x(0,-1,0)]));var Jw=(s=>(s.File_Spawned="file-spawned",s))(Jw||{});class dR{constructor(t,i,n,o,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=i,this.guid=n,this.file_name=o,this.file_hash=r,this.file_size=l,this.position=c,this.scale=h,this.sender=t,this.downloadUrl=d}}var jo;(s=>{const t=new Map;function i(o){var r;t.has(o.guid)&&n(o.guid);const l=new I;t.set(o.guid,l);const c=new I;c.position.y=-.5,l.add(c);const h=new K(new Gl(1,1,1,1,1,1),new Re({color:14540253,wireframe:!0,transparent:!0,opacity:.3}));h.position.y=.5,c.add(h);const d=new I;c.add(d);const u=new K(new Gl(1,1,1,1,1,1),new Re({color:12307660,transparent:!0,opacity:.4}));u.position.y=.5,d.scale.y=.01,d.add(u);const p=new K(new Fs(1,1,1,1),new Re({color:34,transparent:!0,opacity:.05,depthTest:!1}));return p.rotateX(-Math.PI/2),p.position.y=.51,u.add(p),o.parent.add(l),l.rotateY(Math.PI/2),o.position&&((r=l.position)==null||r.copy(o.position)),o.size&&(l.worldScale=new x().copy(o.size)),l.position.y=l.scale.y/2,{object:l,onProgress:g=>{d instanceof I&&d.scale.set(1,g,1)}}}s.addPreview=i;function n(o){const r=t.get(o);r&&(t.delete(o),r.removeFromParent())}s.removePreview=n})(jo||(jo={}));var uR=Object.defineProperty,pR=Object.getOwnPropertyDescriptor,nl=(s,t,i,n)=>{for(var o=n>1?void 0:n?pR(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&uR(t,i,o),o};const Ms=O("debugdroplistener");class mR extends CustomEvent{constructor(t){super("object-added",{detail:t})}}const gR="blob";class Dn extends A{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 _e),a(this,"onNetworkEvent",t=>{var i;if(!this.useNetworking){Ms&&console.debug("[DropListener] Ignoring networked event because networking is disabled",t);return}if((i=t.guid)!=null&&i.startsWith(this.guid)){const n=t.url;if(console.debug("[DropListener] Received networked event",t),n)if(Array.isArray(n))for(const o of n)this.addFromUrl(o,{screenposition:new oe,point:t.point,size:t.size},!0);else this.addFromUrl(n,{screenposition:new oe,point:t.point,size:t.size},!0)}}),a(this,"handlePaste",t=>{this.context.connection.allowEditing===!1||t.defaultPrevented||navigator.clipboard.readText().then(i=>{if(i&&(i.startsWith("http")||i.startsWith("https")||i.startsWith("blob"))){const n={screenposition:new oe(this.context.input.mousePosition.x,this.context.input.mousePosition.y)};this.testIfIsInDropArea(n)&&this.addFromUrl(i,n,!1)}}).catch(console.warn)}),a(this,"onDrag",t=>{this.context.connection.allowEditing!==!1&&t.preventDefault()}),a(this,"onDrop",async t=>{if(this.context.connection.allowEditing===!1||(Ms&&console.log(t),!(t!=null&&t.dataTransfer))||t["droplistener:handled"])return;t.preventDefault();const i={screenposition:new oe(t.offsetX,t.offsetY)};if(this.dropArea&&this.testIfIsInDropArea(i)===!1)return;t["droplistener:handled"]=!0;const n=t.dataTransfer.items;if(!n)return;const o=[];for(const r in n){const l=n[r];if(l.kind==="file"){const c=l.getAsFile();if(!c)continue;o.push(c)}else l.kind==="string"&&l.type=="text/plain"&&l.getAsString(c=>{this.addFromUrl(c,i,!1)})}o.length>0&&await this.addDroppedFiles(o,i)}),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(t,i){this.addFromUrl(t,{screenposition:new oe,point:i?.point,size:i?.size},!0)}forgetObjects(){this.removePreviouslyAddedObjects(!1)}async addFromUrl(t,i,n){Ms&&console.log("dropped url",t);try{if(t.startsWith("https://github.com/")){const l=t.split("/"),c=l[3],h=l[4],d=l[6],u=l.slice(7).join("/");t=`https://raw.githubusercontent.com/${c}/${h}/${d}/${u}`}else t.startsWith("https://polyhaven.com/a")&&(t=fR(t));if(!t)return null;const o=t.toLowerCase();if(o.endsWith(".hdr")||o.endsWith(".hdri")||o.endsWith(".exr")||o.endsWith(".png")||o.endsWith(".jpg")||o.endsWith(".jpeg"))return null;this.removePreviouslyAddedObjects();const r=await $u.loadFileFromURL(new URL(t),{guid:this.guid,context:this.context,parent:this.gameObject,point:i.point,size:i.size});if(r&&this._addedObjects.length<=0)return i.url=t,this.addObject(r,i,n)}catch{console.warn("String is not a valid URL",t)}return null}async addDroppedFiles(t,i){var n,o;if(Ms&&console.log("Add files",t),!!Array.isArray(t)&&t.length){this.deleteDropEvent(),this.removePreviouslyAddedObjects(),Kl(gR,null),(n=this._abort)==null||n.abort("New files dropped"),this._abort=new AbortController;for(const r of t){if(!r)continue;console.debug("Load file "+r.name);const l=await $u.loadFile(r,this.context,{guid:this.guid});if(l){this.dispatchEvent(new CustomEvent("file-dropped",{detail:r})),i.file=r;const c=this.addObject(l,i,!1);c&&this.context.connection.isConnected&&this.useNetworking&&(console.debug("Uploading dropped file to blob storage"),Rr.upload(r,{abort:(o=this._abort)==null?void 0:o.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(t=!0){if(t)for(const i of this._addedObjects)i.parent===this.gameObject&&Ri(i,!0,!0);this._addedObjects.length=0,this._addedModels.length=0}addObject(t,i,n){var o,r;const{model:l,contentMD5:c}=t;if(Ms&&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 _i().setFromCenterAndSize(new x(0,this.fitVolumeSize.y*.5,0).add(this.gameObject.worldPosition),this.fitVolumeSize);if(Ms&&q.DrawWireBox3(d,255,5),this.fitIntoVolume&&eb(h,d,{position:!this.placeAtHitPosition}),this.placeAtHitPosition&&i&&i.screenposition){h.visible=!1;const p=this.context.physics.raycast({screenPoint:this.context.input.convertScreenspaceToRaycastSpace(i.screenposition.clone())});if(h.visible=!0,p&&p.length>0)for(const g of p){const y=g.point.clone();Ms&&console.log("Place object at hit",g),tb(h,y);break}}Wa.assignAnimationsFromFile(l,{createAnimationComponent:p=>Mi(p,Wt)});const u=new mR({sender:this,gltf:l,model:l,object:h,contentMD5:c,dropped:i.file||(i.url?new URL(i.url):void 0)});return this.dispatchEvent(u),(o=this.onDropped)==null||o.invoke(u.detail),!n&&(r=i.url)!=null&&r.startsWith("http")&&this.context.connection.isConnected&&h&&this.sendDropEvent(i.url,h,c),h}async sendDropEvent(t,i,n){if(!this.useNetworking){Ms&&console.debug("[DropListener] Ignoring networked event because networking is disabled",t);return}if(this.context.connection.isConnected){console.debug('Sending drop event "'+i.name+'"',t);const o=ci([i]),r={name:i.name,guid:this.guid,url:t,point:i.worldPosition.clone(),size:o.getSize(new x),contentMD5:n};this.context.connection.send("droplistener",r)}}deleteDropEvent(){this.context.connection.sendDeleteRemoteState(this.guid)}testIfIsInDropArea(t){if(this.dropArea){const i=this.context.input.convertScreenspaceToRaycastSpace(t.screenposition.clone());if(!this.context.physics.raycast({targets:[this.dropArea],screenPoint:i,recursive:!0,testObject:n=>!this._addedObjects.includes(n)}).length)return F()&&console.log(`Dropped outside of drop area for DropListener "${this.name}".`),!1}return!0}}nl([m()],Dn.prototype,"useNetworking",2),nl([m(I)],Dn.prototype,"dropArea",2),nl([m()],Dn.prototype,"fitIntoVolume",2),nl([m(x)],Dn.prototype,"fitVolumeSize",2),nl([m()],Dn.prototype,"placeAtHitPosition",2),nl([m(_e)],Dn.prototype,"onDropped",2);function fR(s){if(!s.startsWith("https://polyhaven.com/"))return s;const t="https://dl.polyhaven.org/file/ph-assets/Models/gltf/4k/",i=new URL(s).pathname.split("/").pop(),n=`${t}${i}/${i}_4k.gltf`;return console.log("Resolved polyhaven asset url",s,"\u2192",n),n}var $u;(s=>{async function t(n,o,r){const l=n.name.toLowerCase();return l.endsWith(".gltf")||l.endsWith(".glb")||l.endsWith(".fbx")||l.endsWith(".obj")||l.endsWith(".usdz")||l.endsWith(".vrm")||n.type==="model/gltf+json"||n.type==="model/gltf-binary"?new Promise((c,h)=>{const d=new FileReader;d.readAsArrayBuffer(n),d.onloadend=async u=>{const p=d.result,g=r.guid,y=new zt(g),f=await fs().parseSync(o,p,n.name,y);if(f){const v=Rr.hashMD5(p);c({model:f,contentMD5:v})}}}):(console.warn("Unsupported file type: "+l,n.type),null)}s.loadFile=t;async function i(n,o){return new Promise(async(r,l)=>{const c=new zt(o.guid),h=n.toString();Ms&&q.DrawWireSphere(o.point,.1,16711680,3);const d=jo.addPreview({guid:o.guid,parent:o.parent,position:o?.point,size:o?.size}),u=await fs().loadSync(o.context,h,h,c,p=>{d.onProgress(p.loaded/p.total)}).catch(console.warn);if(u){const p=await fetch(h).then(y=>y.arrayBuffer()),g=Rr.hashMD5(p);Ms?setTimeout(()=>jo.removePreview(o.guid),3e3):jo.removePreview(o.guid),r({model:u,contentMD5:g})}else Ms?setTimeout(()=>jo.removePreview(o.guid),3e3):jo.removePreview(o.guid),console.warn("Unsupported file type: "+n.toString())})}s.loadFileFromURL=i})($u||($u={}));var yR=Object.defineProperty,vR=Object.getOwnPropertyDescriptor,qu=(s,t,i,n)=>{for(var o=n>1?void 0:n?vR(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&yR(t,i,o),o};const ex=class extends A{constructor(){super(...arguments),a(this,"parent",null),a(this,"object",null),a(this,"limitCount",10),a(this,"limitInterval",60),a(this,"_currentCount",0),a(this,"_startPosition",null),a(this,"_startQuaternion",null),a(this,"_forwardPointerEvents",new Map)}start(){var s,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 zt(this.guid);this.object=P.instantiate(this.object,{idProvider:n,keepWorldPosition:!1});const o=P.getComponent(this.object,ex);o?.destroy();let r=this.object.getComponentInChildren(mi);r||(r=this.object.addComponent(mi,{dragMode:Bf.SnapToSurfaces}),r.guid=n.generateUUID());let l=P.getComponent(r.gameObject,qs);l||(l=r.gameObject.addComponent(qs),l.guid=n.generateUUID())}this.object.visible=!1;const i=this.gameObject.getComponent(mi);i&&(i.enabled=!1),this._startPosition=((s=this.object.position)==null?void 0:s.clone())??new x(0,0,0),this._startQuaternion=((t=this.object.quaternion)==null?void 0:t.clone())??new V(0,0,0,1)}this.gameObject.getComponentInParent(Ei)||this.gameObject.addComponent(Ei),this.cloneLimitIntervalFn()}onPointerEnter(s){s.used||this.object&&this.context.connection.allowEditing&&s.button===0&&this.context.input.setCursor("pointer")}onPointerExit(s){s.used||this.object&&this.context.connection.allowEditing&&s.button===0&&this.context.input.unsetCursor("pointer")}onPointerDown(s){if(s.used||!this.object||!this.context.connection.allowEditing||s.button!==0)return;const t=this.handleDuplication();if(t){const i=P.getComponent(t,mi);i?(i.onPointerDown(s),this._forwardPointerEvents.set(s.event.space,i)):console.warn("Duplicated object does not have DragControls",t)}else console.warn("Could not duplicate object. Has the target object been destroyed?",this)}onPointerUp(s){if(s.used)return;const t=this._forwardPointerEvents.get(s.event.space);t&&(t.onPointerUp(s),this._forwardPointerEvents.delete(s.event.space))}cloneLimitIntervalFn(){this.destroyed||(this._currentCount>0&&(this._currentCount-=1),setTimeout(()=>{this.cloneLimitIntervalFn()},this.limitInterval/this.limitCount*1e3))}handleDuplication(){var s;if(!this.object||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 Ds;this.parent||(this.parent=this.gameObject.parent),this.parent&&(t.parent=this.parent.guid??((s=this.parent.userData)==null?void 0:s.guid),t.keepWorldPosition=!0),t.position=this.worldPosition,t.rotation=this.worldQuaternion,t.context=this.context,this._currentCount+=1;const i=P.instantiateSynced(this.object,t);return console.assert(i!==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),i}};let Wr=ex;qu([m(I)],Wr.prototype,"parent",2),qu([m(I)],Wr.prototype,"object",2),qu([m()],Wr.prototype,"limitCount",2),qu([m()],Wr.prototype,"limitInterval",2);var Bn=(s=>(s[s.PointerEnter=0]="PointerEnter",s[s.PointerExit=1]="PointerExit",s[s.PointerDown=2]="PointerDown",s[s.PointerUp=3]="PointerUp",s[s.PointerClick=4]="PointerClick",s[s.Drag=5]="Drag",s[s.Drop=6]="Drop",s[s.Scroll=7]="Scroll",s[s.UpdateSelected=8]="UpdateSelected",s[s.Select=9]="Select",s[s.Deselect=10]="Deselect",s[s.Move=11]="Move",s[s.InitializePotentialDrag=12]="InitializePotentialDrag",s[s.BeginDrag=13]="BeginDrag",s[s.EndDrag=14]="EndDrag",s[s.Submit=15]="Submit",s[s.Cancel=16]="Cancel",s))(Bn||{}),bR=Object.defineProperty,_R=Object.getOwnPropertyDescriptor,zf=(s,t,i,n)=>{for(var o=n>1?void 0:n?_R(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&bR(t,i,o),o};class Uf{constructor(){a(this,"eventID"),a(this,"callback",new _e)}}zf([m()],Uf.prototype,"eventID",2),zf([m(_e)],Uf.prototype,"callback",2);class Gu extends A{constructor(){super(...arguments),a(this,"triggers",[])}invoke(t){var i;if(this.triggers)for(const n of this.triggers)n.eventID===t&&((i=n.callback)==null||i.invoke())}hasTrigger(t){var i;return((i=this.triggers)==null?void 0:i.some(n=>n.eventID===t))??!1}shouldChangeCursor(){return this.hasTrigger(Bn.PointerClick)||this.hasTrigger(Bn.PointerDown)||this.hasTrigger(Bn.PointerUp)}onPointerClick(t){this.invoke(Bn.PointerClick)}onPointerEnter(t){this.shouldChangeCursor()&&this.context.input.setCursor("pointer"),this.invoke(Bn.PointerEnter)}onPointerExit(t){this.shouldChangeCursor()&&this.context.input.unsetCursor("pointer"),this.invoke(Bn.PointerExit)}onPointerDown(t){this.invoke(Bn.PointerDown)}onPointerUp(t){this.invoke(Bn.PointerUp)}}zf([m(Uf)],Gu.prototype,"triggers",2);class tx{constructor(t){a(this,"writer"),this.writer=t}writeNode(t){}}class wR extends tx{beforeWriteNode(t,i){q.isGizmo(t)&&(i.keep=!1)}}class ix extends tx{beforeWriteTexture(t,i){t.isRenderTargetTexture&&(i.newTexture=Kg(new Se(1,1,1,0)))}}function Nf(s){const t=Uu.DontExport;return!(s.hideFlags&t)}const Wf=O("debugexr");class xR{constructor(t){a(this,"parser"),this.parser=t,Wf&&console.log(t)}get name(){return"EXT_texture_exr"}loadTexture(t){const i=this.name,n=this.parser,o=n.json.textures[t];if(Wf&&console.log("EXT_texture_exr.loadTexture",t,o),!o.extensions||!o.extensions[i])return null;const r=o.extensions[i],l=new vd(n.options.manager);return Wf&&console.log("EXT_texture_exr.loadTexture",r),n.loadTextureImage(t,r.source,l)}}typeof window<"u"&&window.addEventListener("unhandledrejection",s=>{});const Fn=vt,Xu="$___Export_Components",SR="NEEDLE_components";var sx;class CR{constructor(){a(this,sx)}}sx=_r;class OR{constructor(t,i,n){a(this,"node"),a(this,"nodeIndex"),a(this,"nodeDef"),this.node=t,this.nodeIndex=i,this.nodeDef=n}}class nx{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 SR}registerExport(t){t.register(i=>{if("serializeUserData"in i){const n=i.serializeUserData.bind(i);this.writer=i,i.serializeUserData=(o,r)=>{try{this.serializeUserData(o,r)&&(i.extensionsUsed[this.name]=!0),n(o,r)}finally{this.afterSerializeUserData(o,r)}}}return this})}beforeParse(){this.exportContext={},this.objectToNodeMap={}}serializeUserData(t,i){var n;const o=(n=t.userData)==null?void 0:n.components;return!o||o.length<=0?!1:(delete t.userData.components,t[Xu]=o,!0)}afterSerializeUserData(t,i){if(t.type==="Scene"&&Fn&&console.log("DONE",JSON.stringify(i)),t[Xu]===void 0)return;const n=t[Xu];delete t[Xu],n!==null&&(t.userData.components=n)}writeNode(t,i){const n=this.writer.json.nodes.length;Fn&&console.log(t.name,n,t.uuid);const o=new OR(t,n,i);this.exportContext[n]=o,this.objectToNodeMap[t.uuid]=n}afterParse(t){var i;Fn&&console.log("AFTER",t);for(const n in this.exportContext){const o=this.exportContext[n],r=o.node,l=o.nodeDef,c=o.nodeIndex,h=(i=r.userData)==null?void 0:i.components;if(!h||h.length<=0)continue;const d=new CR;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=fs().writeBuiltinComponentData(p,this.context);g!==null&&u.push(g)}u.length>0&&(d[_r]=u,Fn&&console.log("DID WRITE",r,"nodeIndex",c,u))}}beforeRoot(){return Fn&&console.log("BEGIN LOAD"),this.nodeToObjectMap={},null}async afterRoot(t){this.gltf=t;const i=t.parser,n=i?.extensions;if(!n)return;const o=n[this.name];Fn&&console.log("After root",t,this.parser,n);const r=[];if(o===!0){const l=i.json.nodes;if(l){for(let c=0;c<l.length;c++){const h=await i.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;Fn&&console.log("NODE",h);const g=this.nodeToObjectMap[d];if(!g){console.error("Could not find object for node index: "+d,h,i);continue}Jd(g),r.push(this.createComponents(g,p))}}}await Promise.all(r);for(const l of i.associations.keys()){const c=i.associations.get(l);if(c?.materials!=null){const h="/materials/"+c.materials;Pk(l,h)}}}async createComponents(t,i){if(!i)return;const n=i[_r];if(n){const o=new Array;Fn&&console.log(t.name,n);for(const r in n){const l=n[r];Fn&&console.log("Serialized data",JSON.parse(JSON.stringify(l))),l&&this.parser&&o.push(zg(this.parser,l).catch(c=>console.error(`Error while resolving references (see console for details)
939
+ `,c,t,l))),t.userData=t.userData||{},t.userData[_r]=t.userData[_r]||[],t.userData[_r].push(l)}await Promise.all(o).catch(r=>{console.error("Error while loading components",r)})}}}const ox="NEEDLE_gameobject_data";class PR{constructor(t){a(this,"parser"),this.parser=t}get name(){return ox}afterRoot(t){var i;const n=[];for(let o=0;o<((i=this.parser.json.nodes)==null?void 0:i.length);o++){const r=this.parser.json.nodes[o];if(r&&r.extensions){const l=r.extensions[ox];if(l){const c=this.findAndApplyExtensionData(o,l);n.push(c)}}}return Promise.all(n).then(()=>null)}async findAndApplyExtensionData(t,i){const n=await this.parser.getDependency("node",t);n&&this.applyExtensionData(n,i)}applyExtensionData(t,i){i.layers===void 0&&(i.layers=0),t.userData.layer=i.layers,t.layers.disableAll(),t.layers.set(i.layers),t.userData.tag=i.tag??"none",t.hideFlags=0,t.userData.static=i.static??!1,t.visible=i.activeSelf??!0,t.guid=i.guid}}const rx="NEEDLE_lighting_settings",ol=O("debugenvlight");class kR{constructor(t,i,n){a(this,"parser"),a(this,"sourceId"),a(this,"context"),this.parser=t,this.sourceId=i,this.context=n}get name(){return rx}afterRoot(t){const i=this.parser.json.extensions;if(i){const n=i[rx];if(n){ol&&console.log('Loaded "'+this.name+'", src: "'+this.sourceId+'"',n);let o;if(t.scene.children.length===1){const r=t.scene.children[0];o=P.addComponent(r,Qu,{},{callAwake:!1})}else{const r=new I;r.name="LightSettings "+this.sourceId,t.scene.add(r),o=P.addComponent(r,Qu,{},{callAwake:!1})}o.sourceId=this.sourceId,o.ambientIntensity=n.ambientIntensity,o.ambientLight=new re().fromArray(n.ambientLight),Array.isArray(n.ambientTrilight)&&(o.ambientTrilight=n.ambientTrilight.map(r=>new re().fromArray(r))),o.ambientMode=n.ambientMode,o.environmentReflectionSource=n.environmentReflectionSource}}return null}}ge.registerCallback(ye.ContextCreated,s=>{const t=s.context,i=P.findObjectOfType(Qu,t);i!=null&&i.sourceId&&(i.enabled=!0)});class Qu extends A{constructor(){super(...arguments),a(this,"ambientMode",Ha.Skybox),a(this,"ambientLight"),a(this,"ambientTrilight"),a(this,"ambientIntensity",1),a(this,"environmentReflectionSource",gu.Skybox),a(this,"_hasReflection",!1),a(this,"_ambientLightObj"),a(this,"_hemisphereLightObj")}awake(){var t;if(this.sourceId){const n=this.environmentReflectionSource===gu.Skybox?vo.Skybox:vo.Reflection,o=this.context.lightmaps.tryGet(this.sourceId,n,0);this._hasReflection=o!=null,o&&this.context.sceneLighting.internalRegisterReflection(this.sourceId,o)}this.enabled=!1,this.context.sceneLighting.internalRegisterSceneLightSettings(this),ol&&window.addEventListener("keydown",n=>{if(!this.destroyed)switch(n.key){case"l":this.enabled=!this.enabled;break}});const i=(t=this.gameObject.userData)==null?void 0:t.components;if(i){const n=i.indexOf(this);i.splice(n,1),i.push(this)}}onDestroy(){this.context.sceneLighting.internalUnregisterSceneLightSettings(this)}calculateIntensityFactor(t){const i=Math.max(t.r,t.g,t.b);return 2.2*W.lerp(0,1.33,i)}onEnable(){if(ol&&console.warn("\u{1F4A1}\u{1F7E1} >>> Enable lighting",this.sourceId,this.enabled,this),this.ambientMode==Ha.Flat){if(this.ambientLight&&!this._ambientLightObj){const t=this.calculateIntensityFactor(this.ambientLight);this._ambientLightObj=new LS(this.ambientLight,this.ambientIntensity*t),ol&&console.log("Created ambient light",this.sourceId,this._ambientLightObj,this.ambientIntensity,t)}this._ambientLightObj&&this.gameObject.add(this._ambientLightObj)}else if(this.ambientMode===Ha.Trilight){if(this.ambientTrilight){const t=this.ambientTrilight[0],i=this.ambientTrilight[this.ambientTrilight.length-1],n=this.calculateIntensityFactor(i);this._hemisphereLightObj=new DS(i,t,this.ambientIntensity*n),this.gameObject.add(this._hemisphereLightObj),ol&&console.log("Created hemisphere ambient light",this.sourceId,this._hemisphereLightObj,this.ambientIntensity,n)}}else this._ambientLightObj&&this._ambientLightObj.removeFromParent(),this._hemisphereLightObj&&this._hemisphereLightObj.removeFromParent();this.sourceId&&this.context.sceneLighting.internalEnableReflection(this.sourceId)}onDisable(){ol&&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 Vf=O("debugstencil");function MR(s,t){return(s&1<<t.layer)!=0}const RR=Symbol("stencils"),rl=class{constructor(s,t){a(this,"parser"),a(this,"source"),this.parser=s,this.source=t}get name(){return"NEEDLE_render_objects"}static applyStencil(s){if(!s)return;const t=s.sourceId;if(Vf&&console.log(t,rl.stencils),!t)return;const i=rl.stencils[t];if(i)for(let n=i.length-1;n>=0;n--){const o=i[n];if(MR(o.layer,s)){Vf&&console.log(o),setTimeout(()=>{Gt()&&iu(s.gameObject)&&(xe("Stencil not supported on instanced objects"),console.warn("Stencil not supported on instanced objects",s))},500);for(let r=0;r<s.sharedMaterials.length;r++){let l=s.sharedMaterials[r];l&&(l=l.clone(),l[RR]=!0,l.stencilWrite=!0,l.stencilWriteMask=255,l.stencilFuncMask=255,l.stencilRef=o.value,l.stencilFunc=o.compareFunc,l.stencilZPass=o.passOp,l.stencilFail=o.failOp,l.stencilZFail=o.zFailOp,s.sharedMaterials[r]=l)}s.gameObject.renderOrder=o.event*1e3+o.index*50;break}}}afterRoot(s){const t=this.parser.json.extensions;if(t){const i=t[ER];if(i){Vf&&console.log(i);const n=i.stencil;if(n&&Array.isArray(n))for(const o of n){const r={...o};r.compareFunc=TR(r.compareFunc),r.passOp=$f(r.passOp),r.failOp=$f(r.failOp),r.zFailOp=$f(r.zFailOp),rl.stencils[this.source]||(rl.stencils[this.source]=[]),rl.stencils[this.source].push(r)}}}return null}};let Hf=rl;a(Hf,"stencils",{});function $f(s){switch(s){case 0:return HS;case 1:return VS;case 2:return WS;case 3:return NS;case 4:return US;case 6:return zS;case 7:return FS;case 5:return BS}return 0}function TR(s){switch(s){case 1:return Zy;case 2:return KS;case 3:return YS;case 4:return QS;case 5:return XS;case 6:return GS;case 7:return qS;case 8:return $S}return Zy}const ER="NEEDLE_render_objects";var ax=(s=>(s[s.INT=5124]="INT",s[s.FLOAT=5126]="FLOAT",s[s.FLOAT_VEC2=35664]="FLOAT_VEC2",s[s.FLOAT_VEC3=35665]="FLOAT_VEC3",s[s.FLOAT_VEC4=35666]="FLOAT_VEC4",s[s.INT_VEC2=35667]="INT_VEC2",s[s.INT_VEC3=35668]="INT_VEC3",s[s.INT_VEC4=35669]="INT_VEC4",s[s.BOOL=35670]="BOOL",s[s.BOOL_VEC2=35671]="BOOL_VEC2",s[s.BOOL_VEC3=35672]="BOOL_VEC3",s[s.BOOL_VEC4=35673]="BOOL_VEC4",s[s.FLOAT_MAT2=35674]="FLOAT_MAT2",s[s.FLOAT_MAT3=35675]="FLOAT_MAT3",s[s.FLOAT_MAT4=35676]="FLOAT_MAT4",s[s.SAMPLER_2D=35678]="SAMPLER_2D",s[s.SAMPLER_3D=35680]="SAMPLER_3D",s[s.SAMPLER_CUBE=35681]="SAMPLER_CUBE",s[s.UNKNOWN=0]="UNKNOWN",s))(ax||{});const tn=O("debugcustomshader"),al="NEEDLE_techniques_webgl";class AR{constructor(){a(this,"objectToWorldMatrix",new ne),a(this,"worldToObjectMatrix",new ne),a(this,"objectToWorld",new Array),a(this,"worldToObject",new Array)}updateFrom(t){this.objectToWorldMatrix.copy(t.matrixWorld),mu(this.objectToWorldMatrix,this.objectToWorld),this.worldToObjectMatrix.copy(t.matrixWorld).invert(),mu(this.worldToObjectMatrix,this.worldToObject)}}const Ve=class extends Jy{constructor(s,...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 AR),this.identifier=s,tn&&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 s=super.clone();return lx(s),s}dispose(){super.dispose();const s=ee.Current.pre_render_callbacks.indexOf(this.onBeforeRenderSceneCallback);s>=0&&ee.Current.pre_render_callbacks.splice(s,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(s,t,i,n,o,r){n.attributes.tangent||n.computeTangents(),this.onUpdateUniforms(i,o)}onUpdateUniforms(s,t){const i=ee.Current;if(s&&(Ve.viewProjection&&this.uniforms[this._viewProjectionName]&&(Ve.viewProjection.copy(s.projectionMatrix).multiply(s.matrixWorldInverse),mu(Ve.viewProjection,Ve._viewProjectionValues)),Ve.viewMatrix&&this.uniforms[this._viewMatrixName]&&(Ve.viewMatrix.copy(s.matrixWorldInverse),mu(Ve.viewMatrix,Ve._viewMatrixValues)),this.uniforms[Ve._worldSpaceCameraPosName]&&Ve._worldSpaceCameraPos.setFromMatrixPosition(s.matrixWorld)),this.uniforms._TimeParameters&&(this.uniforms._TimeParameters.value=i.sceneLighting.timeVec4),this.uniforms._Time){const l=this.uniforms._Time.value;l.x=i.sceneLighting.timeVec4.x/20,l.y=i.sceneLighting.timeVec4.x,l.z=i.sceneLighting.timeVec4.x*2,l.w=i.sceneLighting.timeVec4.x*3}if(this.uniforms._SinTime){const l=this.uniforms._SinTime.value;l.x=Math.sin(i.sceneLighting.timeVec4.x/8),l.y=Math.sin(i.sceneLighting.timeVec4.x/4),l.z=Math.sin(i.sceneLighting.timeVec4.x/2),l.w=Math.sin(i.sceneLighting.timeVec4.x)}if(this.uniforms._CosTime){const l=this.uniforms._CosTime.value;l.x=Math.cos(i.sceneLighting.timeVec4.x/8),l.y=Math.cos(i.sceneLighting.timeVec4.x/4),l.z=Math.cos(i.sceneLighting.timeVec4.x/2),l.w=Math.cos(i.sceneLighting.timeVec4.x)}if(this.uniforms.unity_DeltaTime){const l=this.uniforms.unity_DeltaTime.value;l.x=i.time.deltaTime,l.y=1/i.time.deltaTime,l.z=i.time.smoothedDeltaTime,l.w=1/i.time.smoothedDeltaTime}const n=i.mainLight;if(n){const l=te(n.gameObject,Ve._mainLightPosition);this.uniforms._MainLightPosition={value:l.normalize()},Ve._mainLightColor.set(n.color.r,n.color.g,n.color.b,0),this.uniforms._MainLightColor={value:Ve._mainLightColor};const c=n.intensity;Ve._lightData.z=c,this.uniforms.unity_LightData={value:Ve._lightData}}if(s&&(Ve.viewProjection&&this.uniforms[this._viewProjectionName]&&(this.uniforms[this._viewProjectionName].value=Ve._viewProjectionValues),Ve.viewMatrix&&this.uniforms[this._viewMatrixName]&&(this.uniforms[this._viewMatrixName].value=Ve._viewMatrixValues),this.uniforms[Ve._worldSpaceCameraPosName]&&(this.uniforms[Ve._worldSpaceCameraPosName]={value:Ve._worldSpaceCameraPos}),i.mainCameraComponent)){if(this.uniforms._ProjectionParams){const l=this.uniforms._ProjectionParams.value;l.x=1,l.y=i.mainCameraComponent.nearClipPlane,l.z=i.mainCameraComponent.farClipPlane,l.w=1/l.z,this.uniforms._ProjectionParams.value=l}if(this.uniforms._ZBufferParams){const l=this.uniforms._ZBufferParams.value,c=i.mainCameraComponent;l.x=1-c.farClipPlane/c.nearClipPlane,l.y=c.farClipPlane/c.nearClipPlane,l.z=l.x/c.farClipPlane,l.w=l.y/c.farClipPlane,this.uniforms._ZBufferParams.value=l}if(this.uniforms._ScreenParams){const l=this.uniforms._ScreenParams.value;l.x=i.domWidth,l.y=i.domHeight,l.z=1+1/l.x,l.w=1+1/l.y,this.uniforms._ScreenParams.value=l}if(this.uniforms._ScaledScreenParams){const l=this.uniforms._ScaledScreenParams.value;l.x=i.domWidth,l.y=i.domHeight,l.z=1+1/l.x,l.w=1+1/l.y,this.uniforms._ScaledScreenParams.value=l}}const o=this.depthTextureUniform;o&&(o.value=i.depthTexture);const r=this.opaqueTextureUniform;if(r&&(r.value=i.opaqueColorTexture),t){const l=this._rendererData;l.updateFrom(t),this.uniforms[this._worldToObjectName].value=l.worldToObject,this.uniforms[this._objToWorldName].value=l.objectToWorld}this.uniformsNeedUpdate=!0}};let Rs=Ve;a(Rs,"viewProjection",new ne),a(Rs,"_viewProjectionValues",[]),a(Rs,"viewMatrix",new ne),a(Rs,"_viewMatrixValues",[]),a(Rs,"_worldSpaceCameraPosName","_WorldSpaceCameraPos"),a(Rs,"_worldSpaceCameraPos",new x),a(Rs,"_mainLightColor",new me),a(Rs,"_mainLightPosition",new x),a(Rs,"_lightData",new me);class IR{constructor(t,i){a(this,"parser"),a(this,"identifier"),this.parser=t,this.identifier=i}get name(){return al}loadMaterial(t){const i=this.parser.json.materials[t];if(!i)return tn&&console.log(t,this.parser.json.materials),null;if(!i.extensions||!i.extensions[al])return tn&&console.log(`Material ${t} does not use NEEDLE_techniques_webgl`),null;tn&&console.log(`Material ${t} uses NEEDLE_techniques_webgl`,i);const n=i.extensions[al].technique;if(n<0)return console.debug(`Material ${t} does not have a valid technique index`),null;const o=this.parser.json.extensions[al];if(!o)return tn?console.error("Missing shader data",this.parser.json.extensions):console.debug("Missing custom shader data in parser.json.extensions"),null;tn&&console.log(o);const r=o.techniques[n];return r?new Promise(async(l,c)=>{var h,d,u;const p=await i2(o,r.program),g=p?.fragmentShader,y=p?.vertexShader;if(!g||!y)return c();tn&&console.log("loadMaterial",i,p);const f={},v=r.uniforms;(y.includes("_Time")||g.includes("_Time"))&&(f._Time={value:new me(0,0,0,0)}),(y.includes("_SinTime")||g.includes("_SinTime"))&&(f._SinTime={value:new me(0,0,0,0)}),(y.includes("_CosTime")||g.includes("_CosTime"))&&(f._CosTime={value:new me(0,0,0,0)}),(y.includes("unity_DeltaTime")||g.includes("unity_DeltaTime"))&&(f.unity_DeltaTime={value:new me(0,0,0,0)});for(const _ in v){const C=_;switch(C){case"_TimeParameters":const R=new me;f[C]={value:R};break;case"hlslcc_mtx4x4unity_MatrixV":case"hlslcc_mtx4x4unity_MatrixVP":f[C]={value:[]};break;case"_MainLightPosition":case"_MainLightColor":case"_WorldSpaceCameraPos":f[C]={value:[0,0,0,1]};break;case"unity_OrthoParams":break;case"unity_SpecCube0":f[C]={value:null};break;default:case"_ScreenParams":case"_ZBufferParams":case"_ProjectionParams":f[C]={value:[0,0,0,0]};break;case"_CameraOpaqueTexture":case"_CameraDepthTexture":f[C]={value:null};break}}let b=!1;if(i.extensions&&i.extensions[al]){const _=i.extensions[al];if(_.technique===n){tn&&console.log(i.name,"Material Properties",_);for(const C in _.values){const R=_.values[C];if(typeof R=="string"){if(R.startsWith("/textures/")){const M=R.substring(10),T=Number.parseInt(M);if(T>=0){const j=await this.parser.getDependency("texture",T);j instanceof Le&&(j.colorSpace=mr,j.needsUpdate=!0),f[C]={value:j};continue}}switch(C){case"alphaMode":R==="BLEND"&&(b=!0);continue}}if(Array.isArray(R)&&R.length===4){f[C]={value:new me(R[0],R[1],R[2],R[3])};continue}f[C]={value:R}}}}const w=new Rs(this.identifier,{name:i.name??"",uniforms:f,vertexShader:y,fragmentShader:g,lights:!1});switch(w.glslVersion=ZS,w.vertexShader=w.vertexShader.replace("#version 300 es",""),w.fragmentShader=w.fragmentShader.replace("#version 300 es",""),(h=f._Cull)==null?void 0:h.value){case 0:w.side=xi;break;case 1:w.side=ym;break;case 2:w.side=co;break;default:w.side=co;break}switch((d=f._ZTest)==null?void 0:d.value){case 3:w.depthTest=!0,w.depthFunc=oC;break;case 6:w.depthTest=!0,w.depthFunc=nC;break;case 2:w.depthTest=!0,w.depthFunc=sC;break;case 4:w.depthTest=!0,w.depthFunc=iC;break;case 5:w.depthTest=!0,w.depthFunc=tC;break;case 7:w.depthTest=!0,w.depthFunc=eC;break;case 8:w.depthTest=!1,w.depthFunc=JS;break}w.transparent=b,b&&(w.depthWrite=!1),e2(f),w.onUpdateUniforms();for(const _ in v){const C=_,R=v[_].type;if(((u=f[C])==null?void 0:u.value)===void 0)switch(R){case ax.SAMPLER_2D:f[C]={value:Zk},console.warn("Missing/unassigned texture, fallback to white: "+C);break;default:C==="unity_OrthoParams"||console.warn("TODO: EXPECTED UNIFORM / fallback NOT SET: "+C,v[_]);break}}tn&&console.log(w.uuid,f),lx(w),l(w)}):null}}function lx(s){if(s.uniforms){tn&&console.log("Uniforms:",s.uniforms);for(const i in s.uniforms)switch(t(i,i),i){case"_Color":t("color",i);break}}function t(i,n){Object.getOwnPropertyDescriptor(s,i)||Object.defineProperty(s,i,{get:()=>s.uniforms[n].value,set:o=>{s.uniforms[n].value=o,s.needsUpdate=!0}})}}const jR=O("debugextensions");let Yu;const LR=import("./three-examples.light.min.js").then(s=>s.r).then(async s=>(Yu=s.GLTFAnimationPointerExtension,Yu)).catch(s=>{console.warn("Failed to import GLTFLoaderAnimationPointer. Please use @needle-tools/three for full KHR_animation support",s)}),Vr=new Array;function DR(s){Vr.includes(s)||Vr.push(s)}function BR(s){const t=Vr.indexOf(s);t>=0&&Vr.splice(t,1)}function Ku(s){const t=new nx;return s.register(i=>(t.parser=i,t)),t}class FR{resolvePath(t){return t.includes("/extensions/builtin_components/")?t.replace("/extensions/builtin_components/","/userData/components/"):t.includes("extensions/builtin_components/")?t.replace("extensions/builtin_components/","/userData/components/"):t}}async function Zu(s,t,i){const n=i.indexOf("?");n>=0&&(i=i.substring(0,n)),s.register(o=>new PR(o)),s.register(o=>new Mk(o)),s.register(o=>new Xk(o,t.lightmaps,i)),s.register(o=>new kR(o,i,t)),s.register(o=>new IR(o,i)),s.register(o=>new Hf(o,i)),s.register(o=>new it(o,i)),s.register(o=>new xR(o)),Qb()&&s.register(o=>new Cg(o)),await LR.catch(o=>{}),s.register(o=>{if(Yu){const r=new Yu(o);return r.setAnimationPointerResolver.bind(r)(new FR),r}else return(jR||F())&&console.error("Missing KHR_animation_pointer extension..."),{name:"KHR_animation_pointer_NOT_AVAILABLE"}});for(const o of Vr)o.onImport&&o.onImport(s,i,t)}function qf(s,t){for(const i of Vr)i.onExport&&i.onExport(s,t)}function Gf(s,t,i){for(const n of Vr)n.onLoaded&&n.onLoaded(s,t,i)}class cx{constructor(t){this.writer=t,this.name="EXT_mesh_gpu_instancing"}writeNode(t,i){if(t.constructor.name!=="InstancedMesh")return;const n=this.writer,o=n.extensionsUsed,r={};i.extensions=i.extensions||{},i.extensions[this.name]=r;let l=new ne;const c=new Array,h=new Array,d=new Array;for(let y=0;y<t.count;y++){t.getMatrixAt(y,l);let f=new x,v=new V,b=new x;l.decompose(f,v,b),c.push(f.x,f.y,f.z),h.push(v.x,v.y,v.z,v.w),d.push(b.x,b.y,b.z)}const u=new Float32Array(c),p=new Float32Array(h),g=new Float32Array(d);r.attributes={TRANSLATION:n.processAccessor(new ft(u,3)),ROTATION:n.processAccessor(new ft(p,4)),SCALE:n.processAccessor(new ft(g,3))},o[this.name]=!0}}var zR=Object.defineProperty,UR=Object.getOwnPropertyDescriptor,hx=(s,t,i,n)=>{for(var o=n>1?void 0:n?UR(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&zR(t,i,o),o};const Ju=O("debugreflectionprobe"),dx=O("noreflectionprobe"),NR=Symbol("reflectionProbeKey"),WR=Symbol("original material");var ep;const zn=(ep=class extends A{constructor(){var s;super(),a(this,"_texture"),a(this,"center"),a(this,"size"),a(this,"_boxHelper"),zn._probes.has(this.context)||zn._probes.set(this.context,[]),(s=zn._probes.get(this.context))==null||s.push(this)}static get(s,t,i,n){if(!s||s.isObject3D!==!0||dx)return null;const o=zn._probes.get(t);if(o){for(const r of o)if(r.__didAwake||r.__internalAwake(),r.enabled&&n&&r.gameObject===n)return r}return Ju&&console.debug("Did not find reflection probe",s.name,i,s),null}set texture(s){if(s&&!(s instanceof Le)){console.error("ReflectionProbe.texture must be a Texture",s);return}this._texture=s,s&&(s.mapping=wn,s.colorSpace=gs,s.needsUpdate=!0)}get texture(){return this._texture}isInBox(s){var t;return(t=this._boxHelper)==null?void 0:t.isInBox(s)}awake(){this._boxHelper=this.gameObject.addComponent(is),this._boxHelper.updateBox(!0),Ju&&this._boxHelper.showHelper(5592320,!0),this.texture&&(this.texture.mapping=wn,this.texture.colorSpace=gs,this.texture.needsUpdate=!0)}onDestroy(){const s=zn._probes.get(this.context);if(s){const t=s.indexOf(this);t>=0&&s.splice(t,1)}}onSet(s){var t;if(dx||!this.enabled||((t=s.sharedMaterials)==null?void 0:t.length)<=0||!this.texture)return;let i=zn._rendererMaterialsCache.get(s);i||(i=[],zn._rendererMaterialsCache.set(s,i));for(let n=0;n<s.sharedMaterials.length;n++){const o=s.sharedMaterials[n];if(!o||o.envMap===void 0||o instanceof Re)continue;let r=i[n];const l=o===r?.copy,c=!r||r.material.uuid!==o.uuid||r.copy.version!==o.version;if(!l&&c){if(Ju){let u="";r?r.material!==o?u="reference changed; cached instance?: "+l:r.copy.version!==o.version&&(u="version changed"):u="not cached",console.warn("Cloning material",o.name,o.version,"Reason:",u,`
940
940
  `,o.uuid,`
941
941
  `,r?.copy.uuid,`
942
942
  `,s.name)}const d=o.clone();d.version=o.version,r?(r.copy=d,r.material=o):(r={material:o,copy:d},i.push(r)),d[NR]=this,d[WR]=o,Ju&&console.log("Set reflection",s.name,s.guid)}r&&r.copy&&(r.copy.onBeforeCompile=o.onBeforeCompile);const h=r?.copy;h.envMap=this.texture,s.sharedMaterials[n]=h}}onUnset(s){const t=zn._rendererMaterialsCache.get(s);if(t)for(let i=0;i<t.length;i++){const n=t[i];s.sharedMaterials[i]=n.material}}},a(ep,"_probes",new Map),a(ep,"_rendererMaterialsCache",new Map),ep);let ll=zn;hx([m(x)],ll.prototype,"center",2),hx([m(x)],ll.prototype,"size",2);const gi=O("debuginstancing"),Xf=class{constructor(){a(this,"objs",[])}setup(s,t,i,n,o,r=0){s.applySettings(t);const l=this.tryCreateOrAddInstance(t,i,o);if(l){n===null&&(n=[]),n.push(l),it.assignTextureLOD(l.renderer.material,0);for(let c=0;c<s.sharedMeshes.length;c++){const h=s.sharedMeshes[c],d=h.geometry;it.assignMeshLOD(h,0).then(u=>{u&&s.activeAndEnabled&&d!=u&&l.setGeometry(u)})}}else if(r<=0&&t.type!=="Mesh"){const c=r+1;for(const h of t.children)n=this.setup(s,h,i,n,o,c)}return r===0&&o.useMatrixWorldAutoUpdate&&n&&n.length>=0&&this.autoUpdateInstanceMatrix(t),n}tryCreateOrAddInstance(s,t,i){if(s.type==="Mesh"){const n=i.foundMeshes;if(i.foundMeshes+=1,!i.rend.enableInstancing)return null;if(i.rend.enableInstancing!==!0){if(n>=i.rend.enableInstancing.length)return gi&&console.error("Something is wrong with instance setup",s,i.rend.enableInstancing,n),null;if(!i.rend.enableInstancing[n])return null}const o=s,r=o.material;for(const d of this.objs)if(!!d.canAdd(o.geometry,r))return d.addInstance(o);let l=Xf.getStartInstanceCount(s);(!l||l<0)&&(l=4);let c=s.name;c!=null&&c.length||(c=kv());const h=new ux(c,o.geometry,r,l,t);return this.objs.push(h),h.addInstance(o)}return null}autoUpdateInstanceMatrix(s){const t=s.matrixWorld.multiplyMatrices.bind(s.matrixWorld),i=s.matrixWorld.clone(),n=(o,r)=>{const l=t(o,r);return(s[bc]||i.equals(l)===!1)&&(i.copy(l),s[bc]=!0),l};s.matrixWorld.multiplyMatrices=n}};let Hr=Xf;a(Hr,"instance",new Xf),a(Hr,"getStartInstanceCount",s=>4);const tp=class{constructor(s,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=s,this.renderer=t,s[t_]=t,this.meshInformation=$r(s.geometry),tp.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 s=$r(this.object.geometry),t=this.meshInformation.vertexCount,i=this.meshInformation.indexCount;return Object.assign(this.meshInformation,s),t!==this.meshInformation.vertexCount||i!==this.meshInformation.indexCount}updateInstanceMatrix(s=!1,t=!0){this.__instanceIndex<0||(t&&this.object.updateWorldMatrix(!0,s),this.renderer.updateInstance(this.object.matrixWorld,this.__instanceIndex))}setMatrix(s){this.__instanceIndex<0||this.renderer.updateInstance(s,this.__instanceIndex)}setGeometry(s){if(this.__geometryIndex<0)return!1;const t=this;if(this.vertexCount>this.__reservedVertexRange)return i(`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 i(`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(s,this.__geometryIndex);function i(n){return t.updateMeshInformation()&&(t.renderer.remove(t,!0),t.renderer.add(t))?!0:((F()||gi)&&console.error(n),!1)}}add(){this.__instanceIndex>=0||(this.renderer.add(this),P.markAsInstancedRendered(this.object,!0))}remove(s){if(!(this.__instanceIndex<0)&&(this.renderer.remove(this,s),P.markAsInstancedRendered(this.object,!1),s)){const t=tp.all.indexOf(this);t>=0&&tp.all.splice(t,1)}}};let ih=tp;a(ih,"all",[]);class ux{constructor(t,i,n,o,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[_c]===!0&&(gi&&console.log("Update instancing bounds",this.name,this._batchedMesh.matrixWorldNeedsUpdate),this.updateBounds())}),a(this,"onAfterRender",()=>{this._batchedMesh.layers.disableAll()}),a(this,"_availableBuckets",new Array),a(this,"_usedBuckets",new Array),this.name=t,this.geometry=i,this.material=n,this._context=r,this._maxInstanceCount=Math.max(2,o),gi&&(this._debugMaterial=px());const l=this.tryEstimateVertexCountSize(this._maxInstanceCount,[i],o);this._maxVertexCount=l.vertexCount,this._maxIndexCount=l.indexCount,this._batchedMesh=new ev(this._maxInstanceCount,this._maxVertexCount,this._maxIndexCount,this._debugMaterial??this.material),this._batchedMesh[_c]=!0,this._batchedMesh.visible=!0,this._context.scene.add(this._batchedMesh),n instanceof Jy&&(n.defines.USE_INSTANCING=!0,n.needsUpdate=!0),r.pre_render_callbacks.push(this.onBeforeRender),r.post_render_callbacks.push(this.onAfterRender),gi&&console.log(`Instanced renderer created with ${this._maxInstanceCount} instances, ${this._maxVertexCount} max vertices and ${this._maxIndexCount} max indices for "${t}"`)}get batchedMesh(){return this._batchedMesh}get visible(){return this._batchedMesh.visible}set visible(t){this._batchedMesh.visible=t}get castShadow(){return this._batchedMesh.castShadow}set castShadow(t){this._batchedMesh.castShadow=t}set receiveShadow(t){this._batchedMesh.receiveShadow=t}get count(){return this._currentInstanceCount}updateBounds(t=!0,i=!0){this._needUpdateBounds=!1,t&&this._batchedMesh.computeBoundingBox(),i&&this._batchedMesh.computeBoundingSphere()}canAdd(t,i){return this._maxVertexCount>1e7||i!==this.material||!this.validateGeometry(t)?!1:!!(!this.mustGrow(t)||this.allowResize)}dispose(){gi&&console.warn("Dispose instanced renderer",this.name),this._context.scene.remove(this._batchedMesh),this._batchedMesh.dispose(),this._batchedMesh=null,this._handles=[]}addInstance(t){const i=new ih(t,this);t.castShadow===!0&&this._batchedMesh.castShadow===!1&&(this._batchedMesh.castShadow=!0),t.receiveShadow===!0&&this._batchedMesh.receiveShadow===!1&&(this._batchedMesh.receiveShadow=!0);try{this.add(i)}catch(n){if(console.error(`Failed adding mesh to instancing (object name: "${t.name}", instances: ${this._currentInstanceCount.toLocaleString()}/${this._maxInstanceCount.toLocaleString()}, vertices: ${this._currentVertexCount.toLocaleString()}/${this._maxVertexCount.toLocaleString()}, indices: ${this._currentIndexCount.toLocaleString()}/${this._maxIndexCount.toLocaleString()})
@@ -1202,7 +1202,7 @@ dateFormat X
1202
1202
  axisFormat %s
1203
1203
  `;const g=Array.from(r),y=new Set;for(const w of g)if(w.affectedObjects&&typeof w.affectedObjects!="string"){if(Array.isArray(w.affectedObjects))for(const _ of w.affectedObjects)y.add(_);else y.add(w.affectedObjects);l&&(p+=`section ${w.animationName} (${w.id})
1204
1204
  `,p+=`${w.id} : ${w.start}, ${w.duration}s
1205
- `)}l&&r.size&&console.log(p);const f=new Set;for(const w of y){w.getPath||console.error("USDZExporter: Animation target object has no getPath method. This is likely a bug",w);let _=w.getPath();_.startsWith("<")&&(_=_.substring(1)),_.endsWith(">")&&(_=_.substring(0,_.length-1)),f.add({path:_,obj:w})}const v=Array.from(f).sort((w,_)=>w.path.length-_.path.length),b=new Array;for(let w=0;w<v.length;w++)for(let _=w+1;_<v.length;_++)if(v[_].path.startsWith(v[w].path)){const C=v[_],R=v[w];b.push({child:C.obj.displayName+" ("+C.path+")",parent:R.obj.displayName+" ("+R.path+")"})}b.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:b,playAnimationActions:r})}for(const p of new Set([...i,...n]))if(Array.isArray(p))for(const g of p)o.add(g.uuid);else o.add(p.uuid);dp&&console.log("All Behavior trigger sources and action targets",i,n,o),this.targetUuids=new Set(o)}onAfterHierarchy(t,i){var n;if((n=this.behaviours)!=null&&n.length){i.beginBlock('def Scope "Behaviors"');for(const o of this.behaviours)o.writeTo(this,t.document,i);i.closeBlock()}}async onAfterSerialize(t){dp&&console.log("onAfterSerialize behaviours",this.behaviourComponentsCopy);for(const i of this.behaviourComponentsCopy)typeof i.afterSerialize=="function"&&(i.afterSerialize.constructor.name==="AsyncFunction"?await i.afterSerialize(this,t):i.afterSerialize(this,t));for(const{clipUrl:i,filesKey:n}of this.audioClipsCopy){if(t.files[n])return;const o=await(await(await fetch(i)).blob()).arrayBuffer(),r=new Uint8Array(o);t.files[n]=r}this.behaviourComponentsCopy.length=0,this.audioClipsCopy.length=0}}var mT=Object.defineProperty,gT=Object.getOwnPropertyDescriptor,$e=(s,t,i,n)=>{for(var o=n>1?void 0:n?gT(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&mT(t,i,o),o};const Ux=O("debugusdzbehaviours");function ch(s){s&&(s.getComponentInParent(Xa)||(F()&&console.debug('Raycaster on "'+s.name+'" was automatically added, because no raycaster was found in the parent hierarchy.'),s.addComponent(Ei)))}class qr extends A{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 V),a(this,"targetScale",new x)}start(){ch(this.gameObject)}onPointerClick(t){t.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 t=te(this.object).clone(),i=te(this.target).clone(),n=Oe(this.object).clone(),o=Oe(this.target).clone(),r=Je(this.object).clone(),l=Je(this.target).clone(),c=t.distanceTo(i),h=n.angleTo(o),d=r.distanceTo(l);if(c<.01&&h<.01&&d<.01){dt(this.object,i),Gi(this.object,o),Pa(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(t,i,p),this.targetRot.slerpQuaternions(n,o,p),this.targetScale.lerpVectors(r,l,p),dt(this.object,this.targetPos),Gi(this.object,this.targetRot),Pa(this.object,this.targetScale),yield;this.coroutine=null}*moveRelative(){if(!this.target||!this.object)return;const t=this.object.position.clone(),i=this.object.quaternion.clone(),n=this.object.scale.clone(),o=this.target.position.clone(),r=this.target.quaternion.clone(),l=this.target.scale.clone();o.applyQuaternion(this.object.quaternion),this.targetPos.copy(this.object.position).add(o),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(t,this.targetPos,h),this.object.quaternion.slerpQuaternions(i,this.targetRot,h),this.object.scale.lerpVectors(n,this.targetScale,h),yield;this.coroutine=null}beforeCreateDocument(t){var i;if(this.target&&this.object&&this.gameObject){const n=new Tt("Move to "+((i=this.target)==null?void 0:i.name),wt.tapTrigger(this.gameObject),fe.transformAction(this.object,this.target,this.duration,this.relativeMotion?"relative":"absolute"));t.addBehavior(n)}}}$e([m(I)],qr.prototype,"object",2),$e([m(I)],qr.prototype,"target",2),$e([m()],qr.prototype,"duration",2),$e([m()],qr.prototype,"relativeMotion",2);var fl;const ti=(fl=class extends A{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 s;this._objectsWithThisMaterial=this.objectsWithThisMaterial,ch(this.gameObject),F()&&this._objectsWithThisMaterial.length<=0&&console.warn('ChangeMaterialOnClick: No objects found with material "'+((s=this.materialToSwitch)==null?void 0:s.name)+'"')}onPointerEnter(s){this.context.input.setCursor("pointer")}onPointerExit(s){this.context.input.unsetCursor("pointer")}onPointerClick(s){if(s.use(),!!this.variantMaterial)for(let t=0;t<this.objectsWithThisMaterial.length;t++){const i=this.objectsWithThisMaterial[t];i.material=this.variantMaterial}}get objectsWithThisMaterial(){return this._objectsWithThisMaterial!=null?this._objectsWithThisMaterial:(this._objectsWithThisMaterial=[],this.variantMaterial&&this.materialToSwitch&&this.context.scene.traverse(s=>{if(s instanceof K)if(Array.isArray(s.material)){for(const t of s.material)if(t===this.materialToSwitch){this.objectsWithThisMaterial.push(s);break}}else s.material===this.materialToSwitch?this.objectsWithThisMaterial.push(s):m_(s.material,this.materialToSwitch)&&this.objectsWithThisMaterial.push(s)}),this._objectsWithThisMaterial)}async beforeCreateDocument(s,t){this.targetModels=[],ti._materialTriggersPerId={},ti.variantSwitchIndex=0,this.materialToSwitch&&await it.assignTextureLOD(this.materialToSwitch,0),this.variantMaterial&&await it.assignTextureLOD(this.variantMaterial,0)}createBehaviours(s,t,i){this.objectsWithThisMaterial.find(n=>n.uuid===t.uuid)&&this.targetModels.push(t),this.gameObject.uuid===t.uuid&&(this.selfModel=t,this.materialToSwitch&&(ti._materialTriggersPerId[this.materialToSwitch.uuid]||(ti._materialTriggersPerId[this.materialToSwitch.uuid]=[]),ti._materialTriggersPerId[this.materialToSwitch.uuid].push(this)))}afterCreateDocument(s,t){if(!this.materialToSwitch)return;const i=ti._materialTriggersPerId[this.materialToSwitch.uuid];if(i){const n={};for(const o of i){const r=o.createVariants();r&&r.length>0&&(n[o.selfModel.uuid]=r)}for(const o of i){const r=[];for(const l in n)l!==o.selfModel.uuid&&r.push(...n[l]);o.createAndAttachBehaviors(s,n[o.selfModel.uuid],r)}}delete ti._materialTriggersPerId[this.materialToSwitch.uuid]}createAndAttachBehaviors(s,t,i){const n=[],o=Math.max(0,this.fadeDuration);n.push(fe.fadeAction([...this.targetModels,...i],o,!1)),n.push(fe.fadeAction(t,o,!0)),s.addBehavior(new Tt("Select_"+this.selfModel.name,wt.tapTrigger(this.selfModel),fe.parallel(...n))),ti._parallelStartHiddenActions.push(...t),ti._startHiddenBehaviour||(ti._startHiddenBehaviour=new Tt("StartHidden_"+this.selfModel.name,wt.sceneStartTrigger(),fe.fadeAction(ti._parallelStartHiddenActions,o,!1)),s.addBehavior(ti._startHiddenBehaviour))}static getMaterialName(s){return Ts(s.name||"Material")+"_"+s.id}createVariants(){if(!this.variantMaterial)return null;const s=[];for(const t of this.targetModels){const i=t.clone();i.name+="_Variant_"+ti.variantSwitchIndex+++"_"+ti.getMaterialName(this.variantMaterial),i.displayName=i.displayName+": Variant with material "+this.variantMaterial.name,i.material=this.variantMaterial,i.geometry=t.geometry,i.transform=t.transform,(!t.parent||!t.parent.isEmpty())&&Zt.createEmptyParent(t),t.parent&&t.parent.add(i),s.push(i)}return s}},a(fl,"_materialTriggersPerId",{}),a(fl,"_startHiddenBehaviour",null),a(fl,"_parallelStartHiddenActions",[]),a(fl,"variantSwitchIndex",0),fl);let yl=ti;$e([m(ke)],yl.prototype,"materialToSwitch",2),$e([m(ke)],yl.prototype,"variantMaterial",2),$e([m()],yl.prototype,"fadeDuration",2);var vl;const qe=(vl=class extends A{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(){ch(this.gameObject)}onPointerClick(s){s.use(),!this.toggleOnClick&&this.hideSelf&&(this.gameObject.visible=!1),this.target&&(this.target.visible=this.toggleOnClick?!this.target.visible:this.targetState)}createBehaviours(s,t,i){t.uuid===this.gameObject.uuid&&(this.selfModel=t,this.selfModelClone=t.clone())}beforeCreateDocument(){this.target&&(this.gameObject[qe.wasVisible]===void 0&&(this.gameObject[qe.wasVisible]=this.gameObject.activeSelf),this.target[qe.wasVisible]===void 0&&(this.target[qe.wasVisible]=this.target.activeSelf),this.stateBeforeCreatingDocument=this.gameObject[qe.wasVisible],this.targetStateBeforeCreatingDocument=this.target[qe.wasVisible],this.gameObject.visible=!0,this.target.visible=!0)}afterCreateDocument(s,t){if(!this.target)return;this.targetModel=t.document.findById(this.target.uuid);const i=this.selfModel;if(this.selfModel&&this.targetModel){let n=this.selfModel,o=this.targetState;if(this.toggleOnClick)if(o=!this.targetStateBeforeCreatingDocument,!this.selfModelClone.geometry)(!this.selfModel.parent||this.selfModel.parent.isEmpty())&&Zf.createEmptyParent(this.selfModel),this.toggleModel=this.selfModel.deepClone(),this.toggleModel.name+="_toggle",this.selfModel.parent.add(this.toggleModel);else{if(!this.gameObject[qe.toggleClone]){const c=this.selfModelClone.clone();c.setMatrix(new ne),c.name+="_toggle"+qe.clonedToggleIndex++,i.add(c),this.gameObject[qe.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[qe.toggleClone];if(!this.gameObject[qe.reverseToggleClone]){const c=this.selfModelClone.clone();c.setMatrix(new ne),c.name+="_toggleReverse"+qe.clonedToggleIndex++,i.add(c),this.gameObject[qe.reverseToggleClone]=c}this.toggleModel=this.gameObject[qe.reverseToggleClone],(!this.toggleModel.geometry||!l.geometry)&&console.error("triggers without childs and without geometry won't work!",this,i.geometry),n=l,i.geometry=null,i.material=null}if(this.toggleModel){if(this.toggleOnClick){const l=[];l.push(fe.fadeAction(n,0,!1)),l.push(fe.fadeAction(this.toggleModel,0,!0)),l.push(fe.fadeAction(this.targetModel,0,o)),s.addBehavior(new Tt("Toggle_"+n.name+"_ToggleTo"+(o?"On":"Off"),wt.tapTrigger(n),fe.parallel(...l)));const c=[];c.push(fe.fadeAction(this.toggleModel,0,!1)),c.push(fe.fadeAction(n,0,!0)),c.push(fe.fadeAction(this.targetModel,0,!o)),s.addBehavior(new Tt("Toggle_"+n.name+"_ToggleTo"+(o?"Off":"On"),wt.tapTrigger(this.toggleModel),fe.parallel(...c)))}}else{const l=[];this.hideSelf&&l.push(fe.fadeAction(n,0,!1)),l.push(fe.fadeAction(this.targetModel,0,o)),s.addBehavior(new Tt("Toggle_"+n.name+"_ToggleTo"+(o?"On":"Off"),wt.tapTrigger(n),l.length>1?fe.parallel(...l):l[0]))}const r=new Array;this.targetStateBeforeCreatingDocument||r.push(this.targetModel),this.stateBeforeCreatingDocument||r.push(i),this.toggleModel&&r.push(this.toggleModel),bl.add(r,s)}}afterSerialize(s,t){this.gameObject[qe.wasVisible]!==void 0&&(this.gameObject.visible=this.gameObject[qe.wasVisible],delete this.gameObject[qe.wasVisible]),this.target&&this.target[qe.wasVisible]!==void 0&&(this.target.visible=this.target[qe.wasVisible],delete this.target[qe.wasVisible]),delete this.gameObject[qe.toggleClone],delete this.gameObject[qe.reverseToggleClone]}},a(vl,"clonedToggleIndex",0),a(vl,"wasVisible",Symbol("usdz_SetActiveOnClick_wasVisible")),a(vl,"toggleClone",Symbol("clone for toggling")),a(vl,"reverseToggleClone",Symbol("clone for reverse toggling")),vl);let Gr=qe;$e([m(I)],Gr.prototype,"target",2),$e([m()],Gr.prototype,"toggleOnClick",2),$e([m()],Gr.prototype,"targetState",2),$e([m()],Gr.prototype,"hideSelf",2);const Do=class extends A{constructor(){super(...arguments),a(this,"wasVisible",!1)}static add(s,t){const i=Array.isArray(s)?s:[s];for(const n of i)Do._fadeObjects.includes(n)||(console.log("adding hide on start",n),Do._fadeObjects.push(n));Do._fadeBehaviour===void 0&&(Do._fadeBehaviour=new Tt("HideOnStart",wt.sceneStartTrigger(),fe.fadeAction(Do._fadeObjects,0,!1)),t.addBehavior(Do._fadeBehaviour))}start(){P.setActive(this.gameObject,!1)}createBehaviours(s,t,i){t.uuid===this.gameObject.uuid&&(this.wasVisible||Do.add(t,s))}beforeCreateDocument(){this.wasVisible=P.isActiveSelf(this.gameObject)}};let bl=Do;a(bl,"_fadeBehaviour"),a(bl,"_fadeObjects",[]);class _l extends A{constructor(){super(...arguments),a(this,"target"),a(this,"duration",.5),a(this,"motionType","bounce")}beforeCreateDocument(){}createBehaviours(t,i,n){if(this.target&&i.uuid===this.gameObject.uuid){const o=new Tt("emphasize "+this.name,wt.tapTrigger(this.gameObject),fe.emphasize(this.target,this.duration,this.motionType,void 0,"basic"));t.addBehavior(o)}}afterCreateDocument(t,i){}}$e([m()],_l.prototype,"target",2),$e([m()],_l.prototype,"duration",2),$e([m()],_l.prototype,"motionType",2);class Bo extends A{constructor(){super(...arguments),a(this,"target"),a(this,"clip",""),a(this,"toggleOnClick",!1),a(this,"trigger","tap")}start(){ch(this.gameObject)}ensureAudioSource(){if(!this.target){const t=this.gameObject.addComponent(We);t&&(this.target=t,t.spatialBlend=1,t.volume=1,t.loop=!1,t.preload=!0)}}onPointerClick(t){var i;t.use(),!(!((i=this.target)!=null&&i.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(t,i,n){if(!(!this.target&&!this.clip)&&i.uuid===this.gameObject.uuid){const o=this.clip?this.clip:this.target?this.target.clip:void 0;if(!o||typeof o!="string")return;const r=this.target?this.target.gameObject:this.gameObject;dr.getName(o);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 K&&g.visible&&(h=!0)}),h=!0;const d=t.addAudioClip(o);let u=fe.playAudioAction(r,d,"play",l,c);this.target&&this.target.loop&&(u=fe.sequence(u).makeLooping());const p=this.name?"_"+this.name:"";if(h&&this.trigger==="tap"){this.toggleOnClick&&(u.multiplePerformOperation="stop");const g=new Tt("playAudio"+p,wt.tapTrigger(i),u);t.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 Tt("playAudioOnStart"+p,wt.sceneStartTrigger(),u);t.addBehavior(g)}}}}$e([m(We)],Bo.prototype,"target",2),$e([m(URL)],Bo.prototype,"clip",2),$e([m()],Bo.prototype,"toggleOnClick",2);var pp;const nn=(pp=class extends A{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 s,t;return((s=this.animator)==null?void 0:s.gameObject)||((t=this.animation)==null?void 0:t.gameObject)}start(){ch(this.gameObject)}onPointerClick(s){var t;s.use(),this.target&&this.stateName&&((t=this.animator)==null||t.play(this.stateName,0,0,.1))}createBehaviours(s,t,i){t.uuid===this.gameObject.uuid&&(this.selfModel=t)}afterSerialize(){if(nn.rootsWithExclusivePlayback.size>1){const s='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()&&xe(s),console.warn(s,...nn.rootsWithExclusivePlayback)}nn.animationActions=[],nn.rootsWithExclusivePlayback=new Set}afterCreateDocument(s,t){if(this.animationSequence===void 0&&this.animationLoopAfterSequence===void 0||!this.stateAnimationModel||!this.target)return;const i=t.document,n=t.extensions.find(l=>l instanceof lh);if(!n)return;const o=n.getClipCount(this.target)>1;o&&(F()&&console.warn("Setting exclusive playback for "+this.target.name+"@"+this.stateName+" because it has "+n.getClipCount(this.target)+" animations. This works around QuickLook bug FB13410767."),nn.rootsWithExclusivePlayback.add(this.target));const r=this.name?this.name:"";i.traverse(l=>{var c,h;if(l.uuid===((c=this.target)==null?void 0:c.uuid)){const d=nn.getActionForSequences(i,l,this.animationSequence,this.animationLoopAfterSequence,this.randomOffsetNormalized),u=new Tt(this.trigger+"_"+r+"_toPlayAnimation_"+this.stateName+"_on_"+((h=this.target)==null?void 0:h.name),this.trigger=="tap"?wt.tapTrigger(this.selfModel):wt.sceneStartTrigger(),d);o&&u.makeExclusive(!0),s.addBehavior(u)}})}static getActionForSequences(s,t,i,n,o){const r=(c,h)=>{let d=nn.animationActions.find(u=>u.affectedObjects==c&&u.start==h.start&&u.duration==h.duration&&u.animationSpeed==h.speed);return d||(d=fe.startAnimationAction(c,h),nn.animationActions.push(d)),d},l=fe.sequence();if(i&&i.length>0)for(const c of i)l.addAction(r(t,c));if(n&&n.length>0){const c=l.actions.length==0?l:fe.sequence();for(const h of n)c.addAction(r(t,h));c.makeLooping(),l!==c&&l.addAction(c)}return o&&o>0&&l.actions.unshift(fe.waitAction(o)),l}static getAndRegisterAnimationSequences(s,t,i){var n,o,r,l,c,h,d,u;if(!t)return;const p=t.getComponent(kt),g=t.getComponent(Wt);if(!p&&!g)return;if(p&&!i)throw new Error("PlayAnimationOnClick: No stateName specified for animator "+p.name+" on "+t.name);let y=[],f=[];if(g){const M=s.registerAnimation(t,g.clip);M&&(g.loop?f.push(M):y.push(M));let T=0;if(g.minMaxOffsetNormalized){const j=g.minMaxOffsetNormalized.x,D=g.minMaxOffsetNormalized.y;T=(((n=g.clip)==null?void 0:n.duration)||1)*(j+Math.random()*(D-j))}return{animationSequence:y,animationLoopAfterSequence:f,randomTimeOffset:T}}const v=p?.runtimeAnimatorController;let b=v?.findState(i),w=[],_=[];if(v&&b){const M=new Array;M.push(b);let T=!1;for(;M.length<100;){if(!b||b===null||!b.transitions||b.transitions.length===0){(o=b.motion)!=null&&o.isLooping&&(T=!0);break}const j=b.transitions.find(U=>U.conditions.length===0),D=j?v.getState(j.destinationState,0):null;if(D&&M.includes(D)){b=D,T=!0;break}else if(j){if(b=D,!b)break;M.push(b)}else{T=((r=b.motion)==null?void 0:r.isLooping)??!1;break}}if(T&&b){const j=M.indexOf(b);w=M.slice(0,j),_=M.slice(j),Ux&&console.log("found loop from "+i,"states until loop",w,"states looping",_)}else w=M,_=[],Ux&&console.log("found no loop from "+i,"states",w);if(!_.length){const j=w[w.length-1],D=(l=j.motion)==null?void 0:l.clip;if(D){let U;if(s.holdClipMap.has(D))U=s.holdClipMap.get(D);else{const B=j.name+"_hold";U=D.clone(),U.duration=1,U.name=B;const Y=D.duration;U.tracks=D.tracks.map($=>{const E=$.clone();E.times=new Float32Array([0,Y]);const z=$.values.length,H=$.getValueSize(),se=$.values.slice(z-H,z);return E.values=new Float32Array(2*H),E.values.set(se,0),E.values.set(se,H),E}),U.name=B,s.holdClipMap.set(D,U)}if(U){const B={name:U.name,motion:{clip:U,isLooping:!1,name:U.name},speed:1,transitions:[],behaviours:[],hash:j.hash+1};_.push(B)}}}}if(w.length===1&&(!((c=w[0].motion)!=null&&c.clip)||((d=(h=w[0].motion)==null?void 0:h.clip.tracks)==null?void 0:d.length)===0)){y=new Array;const M=s.registerAnimation(t,null);M&&y.push(M);return}if(w=w.filter(M=>{var T,j,D;return((T=M.motion)==null?void 0:T.clip)&&((D=(j=M.motion)==null?void 0:j.clip.tracks)==null?void 0:D.length)>0}),_=_.filter(M=>{var T,j,D;return((T=M.motion)==null?void 0:T.clip)&&((D=(j=M.motion)==null?void 0:j.clip.tracks)==null?void 0:D.length)>0}),w.length===0&&_.length===0){console.warn("No clips found for state "+i+" on "+p?.name+", can't export animation data");return}const C=(M,T)=>{if(!t)return;const j=s.registerAnimation(t,M.motion.clip??null);j?(j.speed=M.speed,T.push(j)):console.warn("Couldn't register animation for state "+M.name+" on "+p?.name)};if(w.length>0){y=new Array;for(const M of w)C(M,y)}if(_.length>0){f=new Array;for(const M of _)C(M,f)}let R=0;if(p&&v&&p.minMaxOffsetNormalized){const M=p.minMaxOffsetNormalized.x,T=p.minMaxOffsetNormalized.y,j=w.length?w[0]:_.length?_[0]:null;R=(((u=j?.motion.clip)==null?void 0:u.duration)||1)*(M+Math.random()*(T-M))}return{animationSequence:y,animationLoopAfterSequence:f,randomTimeOffset:R}}createAnimation(s,t,i){if(!this.target||!this.animator&&!this.animation)return;const n=nn.getAndRegisterAnimationSequences(s,this.target,this.stateName);n&&(this.animationSequence=n.animationSequence,this.animationLoopAfterSequence=n.animationLoopAfterSequence,this.randomOffsetNormalized=n.randomTimeOffset,this.stateAnimationModel=t)}},a(pp,"animationActions",[]),a(pp,"rootsWithExclusivePlayback",new Set),pp);let Xr=nn;$e([m(kt)],Xr.prototype,"animator",2),$e([m()],Xr.prototype,"stateName",2);class wl extends A{constructor(){super(...arguments),a(this,"target")}getType(){}getDuration(){}}$e([m(I)],wl.prototype,"target",2);class hh extends A{constructor(){super(...arguments),a(this,"target")}}$e([m(wl)],hh.prototype,"target",2);class dh extends wl{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}}$e([m()],dh.prototype,"type",2),$e([m()],dh.prototype,"duration",2);class d0 extends hh{}class mp{get extensionName(){return"Physics"}onExportObject(t,i,n){const o=P.getComponents(t,ve).filter(h=>h.enabled),r=P.getComponents(t,pi).filter(h=>h.enabled&&!h.isTrigger);let l=o.length>0?o[0]:null;const c=r.length>0?r[0]:null;c&&!l&&(l=new ve,l.isKinematic=!0),l&&i.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 y=r[0];h.beginBlock('def RealityKitStruct "material"',"{",!0);const f=y.sharedMaterial;f&&f.dynamicFriction!==void 0&&h.appendLine(`double dynamicFriction = ${(u=y.sharedMaterial)==null?void 0:u.dynamicFriction}`),f&&f.bounciness!==void 0&&h.appendLine(`double restitution = ${(p=y.sharedMaterial)==null?void 0:p.bounciness}`),f&&f.staticFriction!==void 0&&h.appendLine(`double staticFriction = ${(g=y.sharedMaterial)==null?void 0:g.staticFriction}`),h.closeBlock("}")}h.closeBlock("}")}}),c&&(i.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 tl){const g=c;h.appendLine('token shapeType = "Sphere"'),h.appendLine(`float radius = ${g.radius}`)}else if(c instanceof il){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 In){const g=c;h.appendLine('token shapeType = "Capsule"'),h.appendLine(`float radius = ${g.radius}`),h.appendLine(`float height = ${g.height}`)}else if(c instanceof Io&&(u=c.sharedMesh)!=null&&u.geometry){const g=c.sharedMesh.geometry;g.boundingBox||g.computeBoundingBox();const y=c.sharedMesh.geometry.boundingBox;y&&(h.appendLine('token shapeType = "Box"'),h.appendLine(`float3 extent = (${y.max.x-y.min.x}, ${y.max.y-y.min.y}, ${y.max.z-y.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))}}class u0{get extensionName(){return"DocumentExtension"}onAfterBuildDocument(t){}}var fT=Object.defineProperty,yT=Object.getOwnPropertyDescriptor,uh=(s,t,i,n)=>{for(var o=n>1?void 0:n?yT(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&fT(t,i,o),o};const p0=O("debugui"),m0=O("debuguilayout");class g0{constructor(){a(this,"width"),a(this,"height")}}class f0{constructor(){a(this,"x"),a(this,"y"),a(this,"width"),a(this,"height")}}const Es=new x,ph=new ne,gp=new V,Nx=class extends ls{constructor(){super(...arguments),a(this,"_anchoredPosition"),a(this,"sizeDelta",new oe(100,100)),a(this,"pivot",new oe(.5,.5)),a(this,"anchorMin",new oe(0,0)),a(this,"anchorMax",new oe(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 oe),this._anchoredPosition}set anchoredPosition(s){this._anchoredPosition=s}get width(){let s=this.sizeDelta.x;if(this.anchorMin.x!==this.anchorMax.x&&this._parentRectTransform){const t=this._parentRectTransform.width,i=this.anchorMax.x-this.anchorMin.x;s=t*i,s+=this.sizeDelta.x}return this.minWidth!==void 0&&s<this.minWidth?this.minWidth:s}get height(){let s=this.sizeDelta.y;if(this.anchorMin.y!==this.anchorMax.y&&this._parentRectTransform){const t=this._parentRectTransform.height,i=this.anchorMax.y-this.anchorMin.y;s=t*i,s+=this.sizeDelta.y}return this.minHeight!==void 0&&s<this.minHeight?this.minHeight:s}awake(){super.awake(),this._anchoredPosition||(this._anchoredPosition=new oe),this.lastMatrix=new ne,this.rectBlock=new I,this.rectBlock.name=this.name,this._initialPosition=this.gameObject.position.clone(),this._initialPosition.z=0,Ya(this,"_anchoredPosition",()=>{this.markDirty()}),Ya(this,"sizeDelta",()=>{this.markDirty()}),Ya(this,"pivot",()=>{this.markDirty()}),Ya(this,"anchorMin",()=>{this.markDirty()}),Ya(this,"anchorMax",()=>{this.markDirty()})}onEnable(){var s;super.onEnable(),this.rectBlock||(this.rectBlock=new I),this.lastMatrix||(this.lastMatrix=new ne),this._lastAnchoring||(this._lastAnchoring=new oe),this._initialPosition||(this._initialPosition=new x),this._anchoredPosition||(this._anchoredPosition=new oe),this.addShadowComponent(this.rectBlock),this._transformNeedsUpdate=!0,(s=this.canvas)==null||s.registerTransform(this)}onDisable(){var s;super.onDisable(),this.removeShadowComponent(),(s=this.canvas)==null||s.unregisterTransform(this)}onParentRectTransformChanged(s){this._transformNeedsUpdate||this.onApplyTransform(m0?`${s.name} changed`:void 0)}get isDirty(){return this._transformNeedsUpdate||(this._transformNeedsUpdate=!this.lastMatrix.equals(this.gameObject.matrix)),this._transformNeedsUpdate}markDirty(){this._transformNeedsUpdate||(m0&&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(s){var t;if(this.context.time.frameCount===this._lastUpdateFrame)return;this._lastUpdateFrame=this.context.time.frameCount;const i=this.shadowComponent;if(!i)return;this.gameObject.parent?this._parentRectTransform=P.getComponentInParent(this.gameObject.parent,Nx):this._parentRectTransform=void 0,this._transformNeedsUpdate=!1,m0&&console.warn("RectTransform \u2192 ApplyTransform",this.name+" because "+s),this.isRoot()?this.Root.screenspace||(i.rotation.y=Math.PI):(i.matrix.identity(),i.matrixAutoUpdate=!1,Es.set(0,0,0),this.applyPivot(Es),i.matrix.setPosition(Es.x,Es.y,0),(this.gameObject.quaternion.x||this.gameObject.quaternion.y||this.gameObject.quaternion.z)&&(gp.copy(this.gameObject.quaternion),gp.x*=-1,gp.z*=-1,ph.makeRotationFromQuaternion(gp),i.matrix.premultiply(ph)),Es.set(0,0,0),this.applyAnchoring(Es),(t=this.canvas)!=null&&t.screenspace?Es.z+=.1:Es.z+=.01,ph.identity(),ph.setPosition(Es.x,Es.y,Es.z),i.matrix.premultiply(ph),i.matrix.scale(this.gameObject.scale)),this.lastMatrix.copy(this.gameObject.matrix);const n=!0;for(const o of ou(this.gameObject,ls,n,1)){if(o===this||!o.activeAndEnabled)continue;const r=o;r.onParentRectTransformChanged&&r.onParentRectTransformChanged(this)}}applyAnchoring(s){this._lastAnchoring||(this._lastAnchoring=new oe);const t=this._lastAnchoring.sub(this._anchoredPosition);this.gameObject.position.x+=t.x,this.gameObject.position.y+=t.y,this._lastAnchoring.copy(this._anchoredPosition),s.x+=this._initialPosition.x-this.gameObject.position.x,s.y+=this._initialPosition.y-this.gameObject.position.y,s.z+=this._initialPosition.z-this.gameObject.position.z;const i=this._parentRectTransform;if(i){let n=0;const o=1-this.anchorMax.y-this.anchorMin.y;n-=i.height*.5*o,s.y+=n;let r=0;const l=1-this.anchorMax.x-this.anchorMin.x;r-=i.width*.5*l,s.x+=r}}applyPivot(s){if(this.pivot&&!this.isRoot()){const t=this.pivot.x-.5;s.x-=t*this.sizeDelta.x*this.gameObject.scale.x;const i=this.pivot.y-.5;s.y-=i*this.sizeDelta.y*this.gameObject.scale.y}}getBasicOptions(){const s={width:this.sizeDelta.x,height:this.sizeDelta.y,offset:0,backgroundOpacity:0,borderWidth:0,borderRadius:0,borderOpacity:0,letterSpacing:-.03};return this.ensureValidSize(s),s}ensureValidSize(s,t=1e-4){return s.width<=0&&(s.width=t),s.height<=0&&(s.height=1e-4),s}createNewBlock(s){s={...this.getBasicOptions(),...s},p0&&console.log(this.name,s);const t=new yv(s);return this._createdBlocks.push(t),t}createNewText(s){p0&&console.log(s),s={...this.getBasicOptions(),...s},p0&&console.log(this.name,s);const t=new fv(s);return this._createdTextBlocks.push(t),t}};let Ht=Nx;uh([m(oe)],Ht.prototype,"anchoredPosition",1),uh([m(oe)],Ht.prototype,"sizeDelta",2),uh([m(oe)],Ht.prototype,"pivot",2),uh([m(oe)],Ht.prototype,"anchorMin",2),uh([m(oe)],Ht.prototype,"anchorMax",2);var vT=Object.defineProperty,bT=Object.getOwnPropertyDescriptor,Wx=(s,t,i,n)=>{for(var o=n>1?void 0:n?bT(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&vT(t,i,o),o};class xl extends A{constructor(){super(...arguments),a(this,"effectColor"),a(this,"effectDistance")}}Wx([m(Se)],xl.prototype,"effectColor",2),Wx([m(oe)],xl.prototype,"effectDistance",2);var _T=Object.defineProperty,wT=Object.getOwnPropertyDescriptor,Vx=(s,t,i,n)=>{for(var o=n>1?void 0:n?wT(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&_T(t,i,o),o};const fp={backgroundColor:new re(1,1,1),backgroundOpacity:1,borderColor:new re(1,1,1),borderOpacity:1};var y0;const mh=(y0=class extends ls{constructor(){super(...arguments),a(this,"_alphaFactor",1),a(this,"sRGBColor",new re(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 Se(1,1,1,1)),this._color}set color(s){(!this._color||this._color.r!==s.r||this._color.g!==s.g||this._color.b!==s.b||this._color.alpha!==s.alpha)&&(this._color||(this._color=new Se(1,1,1,1)),this._color.copy(s),this.onColorChanged())}setAlphaFactor(s){this._alphaFactor=s,this.onColorChanged()}get alphaFactor(){return this._alphaFactor}onColorChanged(){this.uiObject&&(this.sRGBColor.copy(this._color),this.sRGBColor.convertLinearToSRGB(),fp.backgroundColor=this.sRGBColor,fp.backgroundOpacity=this._color.alpha*this._alphaFactor,this.applyEffects(fp,this._alphaFactor),this.uiObject.set(fp),this.markDirty())}get m_Color(){return this._color}get rectTransform(){if(this._rect||(this._rect=P.getComponent(this.gameObject,Ht)),!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 s;(s=this.uiObject)==null||s.set({width:this.rectTransform.width,height:this.rectTransform.height}),this.markDirty()}__internalNewInstanceCreated(s){return super.__internalNewInstanceCreated(s),this._rect=null,this.uiObject=null,this._color&&(this._color=this._color.clone()),this}setState(s){this.makePanel(),this.uiObject&&(this.uiObject.setState(s),this==null||this.markDirty())}setupState(s){this.makePanel(),this.uiObject&&(this._stateManager||(this._stateManager=new cO(this.uiObject)),this.uiObject.setupState(s.state,s.attributes))}setOptions(s){this.makePanel(),this.uiObject&&this.uiObject.set(s)}awake(){super.awake(),this.makePanel(),Ya(this,"_color",()=>vM(this,this.onColorChanged))}onEnable(){var s;super.onEnable(),this.uiObject&&((s=this.rectTransform.shadowComponent)==null||s.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 s=.015,t={backgroundColor:this.color,backgroundOpacity:this.color.alpha,offset:s};this.onBeforeCreate(t),this.applyEffects(t),this.onCreate(t),this.controlsChildLayout=!1,this._currentlyCreatingPanel=!1,this.onAfterCreated(),this.onColorChanged()}onBeforeCreate(s){}onCreate(s){this.uiObject=this.rectTransform.createNewBlock(s),this.uiObject.name=this.name}onAfterCreated(){}applyEffects(s,t=1){var i;const n=(i=this.gameObject)==null?void 0:i.getComponent(xl);n&&(n.effectDistance&&(s.borderWidth=Math.max(Math.abs(n.effectDistance.x),Math.abs(n.effectDistance.y))),n.effectColor&&(s.borderColor=n.effectColor,s.borderOpacity=n.effectColor.alpha*t))}async setTexture(s){if(this.setOptions({backgroundOpacity:0}),s){if(mh.textureCache.has(s))s=mh.textureCache.get(s);else if(!s.isRenderTargetTexture){const t=s.clone();t.colorSpace=mr,mh.textureCache.set(s,t),s=t}this.setOptions({backgroundImage:s,borderRadius:0,backgroundOpacity:this.color.alpha,backgroundSize:"stretch"}),it.assignTextureLOD(s,0).then(t=>{t instanceof Le&&(s&&mh.textureCache.set(s,t),this.setOptions({backgroundImage:t}),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(y0,"textureCache",new Map),y0);let Qr=mh;Vx([m(Se)],Qr.prototype,"color",1),Vx([m()],Qr.prototype,"raycastTarget",2);class gh extends Qr{constructor(){super(...arguments),a(this,"_flippedObject",!1)}onAfterCreated(){this.uiObject&&!this._flippedObject&&(this._flippedObject=!0,this.uiObject.scale.y*=-1)}}var xT=Object.defineProperty,ST=Object.getOwnPropertyDescriptor,Wn=(s,t,i,n)=>{for(var o=n>1?void 0:n?ST(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&xT(t,i,o),o};const Yr=O("debugtext");var mt=(s=>(s[s.UpperLeft=0]="UpperLeft",s[s.UpperCenter=1]="UpperCenter",s[s.UpperRight=2]="UpperRight",s[s.MiddleLeft=3]="MiddleLeft",s[s.MiddleCenter=4]="MiddleCenter",s[s.MiddleRight=5]="MiddleRight",s[s.LowerLeft=6]="LowerLeft",s[s.LowerCenter=7]="LowerCenter",s[s.LowerRight=8]="LowerRight",s))(mt||{}),Hx=(s=>(s[s.Normal=0]="Normal",s[s.Bold=1]="Bold",s[s.Italic=2]="Italic",s[s.BoldAndItalic=3]="BoldAndItalic",s))(Hx||{});class $t extends Qr{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 re(1,0,1)),a(this,"_text",""),a(this,"_fontSize",12),a(this,"_textMeshUi",null),a(this,"_didHandleTextRenderOnTop",!1)}setAlphaFactor(t){var i;super.setAlphaFactor(t),(i=this.uiObject)==null||i.set({fontOpacity:this.color.alpha*this.alphaFactor}),this.markDirty()}get text(){return this._text}set text(t){t!==this._text&&(this._text=t,this.feedText(this.text,this.supportRichText),this.markDirty())}set_text(t){this.text=t}get fontSize(){return this._fontSize}set fontSize(t){var i;this._fontSize=t,(i=this.uiObject)==null||i.set({fontSize:t})}onColorChanged(){var t;this.sRGBTextColor.copy(this.color),this.sRGBTextColor.convertLinearToSRGB(),(t=this.uiObject)==null||t.set({color:this.sRGBTextColor,fontOpacity:this.color.alpha})}onParentRectTransformChanged(){super.onParentRectTransformChanged(),this.uiObject&&this.updateOverflow()}onBeforeCanvasRender(t){this.updateOverflow()}updateOverflow(){var t;const i=(t=this.uiObject)==null?void 0:t._overflow;i&&(i._needsUpdate=!0)}onCreate(t){Yr&&console.log(this),this.horizontalOverflow==1&&(t.whiteSpace="pre"),this.verticalOverflow==0&&(this.context.renderer.localClippingEnabled=!0,t.overflow="hidden"),this.horizontalOverflow==1&&this.verticalOverflow==0,t.lineHeight=this.lineSpacing,delete t.backgroundOpacity,delete t.backgroundColor,Yr&&(t.backgroundColor=16750848,t.backgroundOpacity=.5);const i=this.rectTransform;t={...t,...this.getTextOpts()},this.getAlignment(t),Yr&&(t.backgroundColor=Math.random()*16777215,t.backgroundOpacity=.1),this.uiObject=i.createNewText(t),this.feedText(this.text,this.supportRichText)}onAfterAddedToScene(){super.onAfterAddedToScene(),this.handleTextRenderOnTop()}getTextOpts(){const t=this.fontSize,i={color:this.color,fontOpacity:this.color.alpha,fontSize:t,fontKerning:"normal"};return this.setFont(i,this.fontStyle),i}onEnable(){var t;super.onEnable(),this._didHandleTextRenderOnTop=!1,this.uiObject&&this.uiObject.addAfterUpdate(()=>{this.setShadowComponentOwner(this.uiObject),this.markDirty()}),setTimeout(()=>this.markDirty(),10),(t=this.canvas)==null||t.registerEventReceiver(this)}onDisable(){var t;super.onDisable(),(t=this.canvas)==null||t.unregisterEventReceiver(this)}getAlignment(t){switch(t.flexDirection="column",this.alignment){case 0:case 3:case 6:t.textAlign="left";break;case 1:case 4:case 7:t.textAlign="center";break;case 2:case 5:case 8:t.textAlign="right";break}switch(this.alignment){default:case 0:case 1:case 2:t.alignItems="start";break;case 3:case 4:case 5:t.alignItems="center";break;case 6:case 7:case 8:t.alignItems="end";break}return t}feedText(t,i){var n,o,r;if(Yr&&console.log("feedText",this.uiObject,t,i),!!this.uiObject)if(this._textMeshUi||(this._textMeshUi=[]),this.uiObject.children.length=0,!i||t.length===0)this.uiObject.textContent=t;else{let l=this.getNextTag(t);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 Pm({textContent:t.substring(0,l.startIndex),color:"inherit"});this.uiObject.add(h)}}else{this.uiObject.textContent="",this.setOptions({textContent:t});return}const c=[];for(;l;){const h=this.getNextTag(t,l.endIndex),d={fontFamily:(n=this.uiObject)==null?void 0:n.get("fontFamily"),color:"inherit",textContent:""};if(h){d.textContent=this.getText(t,l,h),this.handleTag(l,d,c);const u=new Pm(d);(o=this.uiObject)==null||o.add(u)}else{d.textContent=t.substring(l.endIndex),this.handleTag(l,d,c);const u=new Pm(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 t=[],i=this.canvas,n={renderOnTop:i.renderOnTop,depthWrite:i.depthWrite,doubleSided:i.doubleSided};for(;;){let o=!1;if(this._textMeshUi)for(let r=0;r<this._textMeshUi.length;r++){if(t[r]===!0)continue;o=!0;const l=this._textMeshUi[r];l.textContent&&(Du(l,n),t[r]=!0)}if(!o)break;yield}}handleTag(t,i,n){if(!t.isEndTag){if(t.type.includes("color")){const o=new v0(t,{color:i.color});if(n.push(o),t.type.length>6){const r=parseInt("0x"+t.type.substring(7));i.color=r}else i.color=new re(1,1,1)}else if(t.type=="b"){this.setFont(i,1);const o=new v0(t,{fontWeight:700});n.push(o)}else if(t.type=="i"){this.setFont(i,2);const o=new v0(t,{fontStyle:"italic"});n.push(o)}}}getText(t,i,n){return t.substring(i.endIndex,n.startIndex)}getNextTag(t,i=0){const n=t.indexOf("<",i),o=t.indexOf(">",n);if(n>=0&&o>=0){const r=t.substring(n+1,o);return{type:r,startIndex:n,endIndex:o+1,isEndTag:r.startsWith("/")}}return null}setFont(t,i){if(!this.font)return;const n=this.font,o=this.getFamilyNameWithCorrectSuffix(n,i);Yr&&console.log("Selected font family:"+o);let r=vv.getFontFamily(o);switch(r||(r=vv.addFontFamily(o)),t.fontFamily=r,i){default:case 0:t.fontWeight=400,t.fontStyle="normal";break;case 1:t.fontWeight=700,t.fontStyle="normal";break;case 2:t.fontWeight=400,t.fontStyle="italic";break;case 3:t.fontStyle="italic",t.fontWeight=400}let l=r.getVariant(t.fontWeight,t.fontStyle);if(!l){let c=o;c!=null&&c.endsWith("-msdf.json")||(c+="-msdf.json");let h=o;h!=null&&h.endsWith(".png")||(h+=".png"),l=r.addVariant(t.fontWeight,t.fontStyle,c,h),l?.addEventListener("ready",()=>{this.markDirty()})}}getFamilyNameWithCorrectSuffix(t,i){var n;const o=t.lastIndexOf("-");if(o<0)return t;const r=(n=t.substring(o+1))==null?void 0:n.toLowerCase();if(CT.includes(r))return Yr&&console.warn("Unsupported font style: "+r),t;const l=t.lastIndexOf("/");let c=t;l>=0&&(c=c.substring(l+1));const h=c[0]===c[0].toUpperCase(),d=t.substring(0,o);switch(Yr&&console.log("Select font: ",t,Hx[i],c,h,d),i){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 t}}}Wn([m()],$t.prototype,"alignment",2),Wn([m()],$t.prototype,"verticalOverflow",2),Wn([m()],$t.prototype,"horizontalOverflow",2),Wn([m()],$t.prototype,"lineSpacing",2),Wn([m()],$t.prototype,"supportRichText",2),Wn([m(URL)],$t.prototype,"font",2),Wn([m()],$t.prototype,"fontStyle",2),Wn([m()],$t.prototype,"text",1),Wn([m()],$t.prototype,"fontSize",1);class v0{constructor(t,i){a(this,"tag"),a(this,"previousValues"),this.tag=t,this.previousValues=i}}const CT=["medium","mediumitalic","black","blackitalic","thin","thinitalic","extrabold","light","lightitalic","semibold"];class Fo{constructor(t){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=t}static getId(){return this.global_id++}setDepth(t){return this.depth=t,this}setPointSize(t){return this.pointSize=t,this}setHorizontalAlignment(t){return this.horizontalAlignment=t,this}setVerticalAlignment(t){return this.verticalAlignment=t,this}writeTo(t,i){var n;i.beginBlock(`def Preliminary_Text "${this.id}"`,"(",!1),i.appendLine('prepend apiSchemas = ["MaterialBindingAPI"]'),i.closeBlock(")"),i.beginBlock(),this.content&&i.appendLine(`string content = "${this.content}"`),(!this.font||this.font.length<=0)&&(this.font||(this.font=[]),(n=this.font)==null||n.push("sans-serif"));const o=this.font.map(r=>`"${r}"`).join(", ");i.appendLine(`string[] font = [ ${o} ]`),i.appendLine(`double pointSize = ${this.pointSize}`),typeof this.width=="number"&&i.appendLine(`double width = ${this.width}`),typeof this.height=="number"&&i.appendLine(`double height = ${this.height}`),typeof this.depth=="number"&&i.appendLine(`double depth = ${this.depth}`),this.wrapMode&&i.appendLine(`token wrapMode = "${this.wrapMode}"`),this.horizontalAlignment&&i.appendLine(`token horizontalAlignment = "${this.horizontalAlignment}"`),this.verticalAlignment&&i.appendLine(`token verticalAlignment = "${this.verticalAlignment}"`),this.material!==void 0&&i.appendLine(`rel material:binding = </StageRoot/Materials/${i0(this.material)}>`),i.closeBlock()}}a(Fo,"global_id",0);class yp{static singleLine(t,i,n){const o=new Fo("text_"+Fo.getId());return o.content=t,i&&(o.pointSize=i),n&&(o.depth=n),o}static multiLine(t,i,n,o,r,l){const c=new Fo("text_"+Fo.getId());return c.content=t,c.width=i,c.height=n,c.horizontalAlignment=o,c.verticalAlignment=r,l!==void 0&&(c.wrapMode=l),c}}const OT=new ne().makeRotationY(Math.PI),PT=new ne().makeScale(-1,1,-1);class fh{get extensionName(){return"text"}exportText(t,i,n){const o=P.getComponent(t,$t);if(!o)return;const r=P.getComponent(t,Ht);let l=100,c=100;r&&(l=r.width,c=r.height);const h=OT.clone();r&&h.premultiply(PT),i.setMatrix(h);const d=o.color.clone();i.material=new li({color:d,emissive:d}),i.addEventListener("serialize",(u,p)=>{let g=o.text;g=g.replace(/\r/g,""),g=g.replace(/\n/g,"\\n");const y=yp.multiLine(g,l,c,"center","bottom","flowing");this.setTextAlignment(y,o.alignment),this.setOverflow(y,o),i.material&&(y.material=i.material),y.pointSize=this.convertToTextSize(o.fontSize),y.depth=.001,y.writeTo(void 0,u)})}convertToTextSize(t){return 1/.0502*144*t}setOverflow(t,i){i.horizontalOverflow?t.wrapMode="singleLine":t.wrapMode="flowing"}setTextAlignment(t,i){switch(i){case mt.LowerLeft:case mt.MiddleLeft:case mt.UpperLeft:t.horizontalAlignment="left";break;case mt.LowerCenter:case mt.MiddleCenter:case mt.UpperCenter:t.horizontalAlignment="center";break;case mt.LowerRight:case mt.MiddleRight:case mt.UpperRight:t.horizontalAlignment="right";break}switch(i){case mt.LowerLeft:case mt.LowerCenter:case mt.LowerRight:t.verticalAlignment="bottom";break;case mt.MiddleLeft:case mt.MiddleCenter:case mt.MiddleRight:t.verticalAlignment="middle";break;case mt.UpperLeft:case mt.UpperCenter:case mt.UpperRight:t.verticalAlignment="top";break}}}var kT=Object.defineProperty,MT=Object.getOwnPropertyDescriptor,at=(s,t,i,n)=>{for(var o=n>1?void 0:n?MT(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&kT(t,i,o),o};const $x=O("debuguilayout");class zo{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}}at([m()],zo.prototype,"left",2),at([m()],zo.prototype,"right",2),at([m()],zo.prototype,"top",2),at([m()],zo.prototype,"bottom",2);class ji extends A{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(t){this._needsUpdate=!0}get isDirty(){return this._needsUpdate}get isLayoutGroup(){return!0}updateLayout(){this._rectTransform&&($x&&console.warn("Layout Update",this.context.time.frame,this.name),this._needsUpdate=!1,this.onCalculateLayout(this._rectTransform))}start(){this._needsUpdate=!0}onEnable(){$x&&console.log(this.name,this),this._rectTransform=this.gameObject.getComponent(Ht);const t=this.gameObject.getComponentInParent(Et);t&&t.registerLayoutGroup(this),this._needsUpdate=!0}onDisable(){const t=this.gameObject.getComponentInParent(Et);t&&t.unregisterLayoutGroup(this)}set m_Spacing(t){t!==this.spacing&&(this._needsUpdate=!0,this.spacing=t)}get m_Spacing(){return this.spacing}}at([m()],ji.prototype,"childAlignment",2),at([m()],ji.prototype,"reverseArrangement",2),at([m()],ji.prototype,"spacing",2),at([m(zo)],ji.prototype,"padding",2),at([m()],ji.prototype,"minWidth",2),at([m()],ji.prototype,"minHeight",2),at([m()],ji.prototype,"flexibleHeight",2),at([m()],ji.prototype,"flexibleWidth",2),at([m()],ji.prototype,"preferredHeight",2),at([m()],ji.prototype,"preferredWidth",2);class Uo extends ji{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(t){var i;const n=this.primaryAxis,o=t.width;let r=o;const l=t.height;let c=l;r-=this.padding.horizontal,c-=this.padding.vertical,n==="x"?this.padding.horizontal:this.padding.vertical;const h=n==="x",d=h?"y":"x",u=h?this.childControlWidth:this.childControlHeight,p=h?this.childControlHeight:this.childControlWidth,g=h?this.childForceExpandWidth:this.childForceExpandHeight,y=h?this.childForceExpandHeight:this.childForceExpandWidth,f=h?c:r,v=h?o:l,b=.5*(h?this.childAlignment%3:Math.floor(this.childAlignment/3));let w=0;h?w+=this.padding.left:w+=this.padding.top;let _=0,C=0;for(let D=0;D<this.gameObject.children.length;D++){const U=this.gameObject.children[D],B=P.getComponent(U,Ht);B!=null&&B.activeAndEnabled&&(C+=1,h?_+=B.width:_+=B.height)}let R=0;const M=this.spacing*(C-1);if(g||u){let D=0;h?D=r-=M:D=c-=M,C>0&&(R=D/C)}let T=0;T+=this.padding.left,T-=this.padding.right,b!==0&&(w=v-_,w*=b,w-=M*b,h?(w-=this.padding.right*b,w+=this.padding.left*(1-b),w<this.padding.left&&(w=this.padding.left)):(w-=this.padding.bottom*b,w+=this.padding.top*(1-b),w<this.padding.top&&(w=this.padding.top)));let j=1;for(let D=0;D<this.gameObject.children.length;D++){const U=this.gameObject.children[D],B=P.getComponent(U,Ht);if(B!=null&&B.activeAndEnabled){(i=B.pivot)==null||i.set(.5,.5),B.anchorMin.set(0,1),B.anchorMax.set(0,1);const Y=o*.5+T*.5;B.anchoredPosition.x!==Y&&(B.anchoredPosition.x=Y);const $=l*-.5;B.anchoredPosition.y!==$&&(B.anchoredPosition.y=$),y&&p&&B.sizeDelta[d]!==f&&(B.sizeDelta[d]=f),g&&u&&B.sizeDelta[n]!==R&&(B.sizeDelta[n]=R);const E=h?B.width:B.height,z=E*.5;if(w+=z,g){const se=R*j-R*.5;se>w&&(w=se-R*.5+E+this.padding.left,w-=z)}let H=w;n==="y"&&(H=-H),B.anchoredPosition[n]!==H&&(B.anchoredPosition[n]=H),w+=z,w+=this.spacing,j+=1}}}}at([m()],Uo.prototype,"childControlHeight",2),at([m()],Uo.prototype,"childControlWidth",2),at([m()],Uo.prototype,"childForceExpandHeight",2),at([m()],Uo.prototype,"childForceExpandWidth",2),at([m()],Uo.prototype,"childScaleHeight",2),at([m()],Uo.prototype,"childScaleWidth",2);class b0 extends Uo{get primaryAxis(){return"y"}}class _0 extends Uo{get primaryAxis(){return"x"}}class w0 extends ji{onCalculateLayout(){}}var RT=Object.defineProperty,TT=Object.getOwnPropertyDescriptor,on=(s,t,i,n)=>{for(var o=n>1?void 0:n?TT(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&RT(t,i,o),o},qx=(s=>(s[s.ScreenSpaceOverlay=0]="ScreenSpaceOverlay",s[s.ScreenSpaceCamera=1]="ScreenSpaceCamera",s[s.WorldSpace=2]="WorldSpace",s[s.Undefined=-1]="Undefined",s))(qx||{});const x0=O("debuguilayout"),Gx=class extends Wc{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 s,t,i,n;if(this.previousParent=this.gameObject.parent,((s=this.context.xr)!=null&&s.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(),(i=this.shadowComponent)==null||i.updateMatrixWorld(!0),(n=this.shadowComponent)==null||n.updateWorldMatrix(!0,!0),this.invokeBeforeRenderEvents(),ai.ensureUpdateMeshUI(bv,this.context))}),a(this,"onAfterRenderRoutine",()=>{var s,t,i,n,o;if(((s=this.context.xr)!=null&&s.isVR||(t=this.context.xr)!=null&&t.isPassThrough)&&this.screenspace){(i=this.previousParent)==null||i.add(this.gameObject);return}if((this.screenspace||this.renderOnTop)&&this.previousParent&&this.context.mainCamera){if(this.screenspace){const c=this.context.mainCamera;c?.add(this.gameObject)}else this.previousParent.add(this.gameObject);const r=this.context.renderer.autoClear,l=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(),ai.ensureUpdateMeshUI(bv,this.context,!0),this.context.renderer.render(this.gameObject,this.context.mainCamera),this.context.renderer.autoClear=r,this.context.renderer.autoClearColor=l,this.previousParent.add(this.gameObject)}(o=this._lastMatrixWorld)==null||o.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(s){s!==this._renderOnTop&&(this._renderOnTop=s,this.onRenderSettingsChanged())}get renderOnTop(){return this._renderOnTop!==void 0?this._renderOnTop:!!(this.screenspace&&this._renderMode===0)}set depthWrite(s){this._depthWrite!==s&&(this._depthWrite=s,this.onRenderSettingsChanged())}get depthWrite(){return this._depthWrite}set doubleSided(s){this._doubleSided!==s&&(this._doubleSided=s,this.onRenderSettingsChanged())}get doubleSided(){return this._doubleSided}set castShadows(s){this._castShadows!==s&&(this._castShadows=s,this.onRenderSettingsChanged())}get castShadows(){return this._castShadows}set receiveShadows(s){this._receiveShadows!==s&&(this._receiveShadows=s,this.onRenderSettingsChanged())}get receiveShadows(){return this._receiveShadows}get renderMode(){return this._renderMode}set renderMode(s){this._renderMode!==s&&(this._renderMode=s,this.onRenderSettingsChanged())}set rootCanvas(s){this._rootCanvas instanceof Gx||(this._rootCanvas=s)}get rootCanvas(){return this._rootCanvas}get scaleFactor(){return this._scaleFactor}set scaleFactor(s){this._scaleFactor=s}awake(){var s;this.shadowComponent=this.gameObject,this.previousParent=this.gameObject.parent,x0&&console.log("Canvas.Awake()",((s=this.previousParent)==null?void 0:s.name)+"/"+this.gameObject.name),super.awake()}start(){this.onUpdateRenderMode()}onEnable(){super.onEnable(),this._updateRenderSettingsRoutine=void 0,this._lastMatrixWorld=new ne,this.onUpdateRenderMode(),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 s=this.context.pre_render_callbacks.indexOf(this.onBeforeRenderRoutine);s!==-1&&this.context.pre_render_callbacks.splice(s,1);const t=this.context.post_render_callbacks.indexOf(this.onAfterRenderRoutine);t!==-1&&this.context.post_render_callbacks.splice(t,1)}registerTransform(s){this._rectTransforms.push(s)}unregisterTransform(s){const t=this._rectTransforms.indexOf(s);t!==-1&&this._rectTransforms.splice(t,1)}registerLayoutGroup(s){const t=s.gameObject;this._layoutGroups.set(t,s)}unregisterLayoutGroup(s){const t=s.gameObject;this._layoutGroups.delete(t)}registerEventReceiver(s){this._receivers.push(s)}unregisterEventReceiver(s){const t=this._receivers.indexOf(s);t!==-1&&this._receivers.splice(t,1)}async onEnterXR(s){this.screenspace?(s.xr.isVR||s.xr.isPassThrough)&&(this.gameObject.visible=!1):(this.gameObject.visible=!1,await Jl(1).then(()=>{this.gameObject.visible=!0}))}onLeaveXR(s){this.screenspace&&(s.xr.isVR||s.xr.isPassThrough)&&(this.gameObject.visible=!0)}invokeBeforeRenderEvents(){var s;for(const t of this._receivers)(s=t.onBeforeCanvasRender)==null||s.call(t,this)}handleLayoutUpdates(){this._lastMatrixWorld===null&&(this._lastMatrixWorld=new ne);const s=!this._lastMatrixWorld.equals(this.gameObject.matrixWorld);x0&&s&&console.log("Canvas Layout changed",this.context.time.frameCount,this.name);const t=!1;for(const i of this._rectTransforms){s&&i.markDirty();let n=this._layoutGroups.get(i.gameObject);i.isDirty&&!n&&(n=i.gameObject.getComponentInParent(ji)),(i.isDirty||n!=null&&n.isDirty)&&(x0&&!t&&console.log("CANVAS UPDATE ### "+i.name+" ##################################### "+this.context.time.frame),n?.updateLayout(),i.updateTransform())}}applyRenderSettings(){this.onRenderSettingsChanged()}onRenderSettingsChanged(){this._updateRenderSettingsRoutine||(this._updateRenderSettingsRoutine=this.startCoroutine(this._updateRenderSettingsDelayed(),Me.OnBeforeRender))}*_updateRenderSettingsDelayed(){if(yield,this._updateRenderSettingsRoutine=void 0,this.shadowComponent){this.onUpdateRenderMode(),Du(this.shadowComponent,this);for(const s of P.getComponentsInChildren(this.gameObject,ls))Du(s.shadowComponent,this)}}onUpdateRenderMode(s=!1){if(!s&&this._renderMode===this._activeRenderMode&&this._lastWidth===this.context.domWidth&&this._lastHeight===this.context.domHeight)return;this._activeRenderMode=this._renderMode;let t=this.context.mainCameraComponent,i=10;switch(t&&t.nearClipPlane>0&&t.farClipPlane>0&&(i=W.lerp(t.nearClipPlane,t.farClipPlane,.01)),this._renderMode===1&&(this.worldCamera&&(t=this.worldCamera),this.planeDistance>0&&(i=this.planeDistance)),this._renderMode){case 0:case 1:if(this._lastWidth=this.context.domWidth,this._lastHeight=this.context.domHeight,!t)return;const n=i+.01;this.gameObject.position.x=0,this.gameObject.position.y=0,this.gameObject.position.z=-n,this.gameObject.quaternion.identity();const o=this.gameObject.getComponent(Ht);let r=!1;o.sizeDelta.x!==this.context.domWidth&&(r=!0),o.sizeDelta.y!==this.context.domHeight&&(r=!0);const l=t.fieldOfView*Math.PI/180,c=2*Math.tan(l/2)*Math.abs(n);this.gameObject.scale.x=c/this.context.domHeight,this.gameObject.scale.y=c/this.context.domHeight,this.gameObject.scale.z=.01,r&&(o.sizeDelta.x=this.context.domWidth,o.sizeDelta.y=this.context.domHeight,o?.markDirty());break;case 2:this._lastWidth=-1,this._lastHeight=-1;break}}};let Et=Gx;on([m()],Et.prototype,"renderOnTop",1),on([m()],Et.prototype,"depthWrite",1),on([m()],Et.prototype,"doubleSided",1),on([m()],Et.prototype,"castShadows",1),on([m()],Et.prototype,"receiveShadows",1),on([m()],Et.prototype,"renderMode",1),on([m(Et)],Et.prototype,"rootCanvas",1),on([m()],Et.prototype,"scaleFactor",1),on([m(Pe)],Et.prototype,"worldCamera",2),on([m()],Et.prototype,"planeDistance",2);var ET=Object.defineProperty,AT=Object.getOwnPropertyDescriptor,S0=(s,t,i,n)=>{for(var o=n>1?void 0:n?AT(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&ET(t,i,o),o};class No extends A{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(t){t!==this._alpha&&(this._alpha=t,this.markDirty())}get isCanvasGroup(){return!0}markDirty(){this._isDirty||(this._isDirty=!0,this.startCoroutine(this.applyChangesDelayed(),Me.OnBeforeRender))}*applyChangesDelayed(){this._isDirty=!1,this.applyChangesNow()}applyChangesNow(){this._buffer.length=0;for(const t of P.getComponentsInChildren(this.gameObject,ls,this._buffer)){const i=t;i.setAlphaFactor&&i.setAlphaFactor(this._alpha)}}}S0([m()],No.prototype,"alpha",1),S0([m()],No.prototype,"interactable",2),S0([m()],No.prototype,"blocksRaycasts",2);class vp{get extensionName(){return"tmui"}onExportObject(t,i,n){const o=P.getComponent(t,Et);if(o&&o.enabled&&o.renderMode===qx.WorldSpace){const r=new fh,l=P.getComponent(t,Ht),c=P.getComponent(t,No),h=new Array;if(l){if(!P.isActiveSelf(t)){const p=P.isActiveSelf(t);P.setActive(t,!0),l.onEnable(),l.updateTransform(),h.push(()=>{l.onDisable(),P.setActive(t,p)})}t.traverse(p=>{if(!P.isActiveInHierarchy(p)){const g=P.isActiveSelf(p);P.setActive(p,!0);const y=P.getComponent(p,ls);y&&(y.onEnable(),h.push(()=>{y.onDisable()}));const f=P.getComponent(p,Ht);f&&(f.onEnable(),f.updateTransform(),f.onApplyTransform(),h.push(()=>{f.onDisable()}));const v=P.getComponent(p,$t);v&&(v.onEnable(),h.push(()=>{v.onDisable()})),h.push(()=>{P.setActive(p,g)})}}),l.width,l.height;const d=Zt.createEmpty(),u=l.shadowComponent;if(i.add(d),u){const p=u.matrix;d.setMatrix(p);const g=new Map,y=new Map;g.set(u,d),y.set(u,c?c.alpha:1),u.traverse(f=>{if(f===u)return;const v=Zt.createEmpty();v.setMatrix(f.matrix);const b=f.parent,w=!!b&&typeof b.textContent=="string"&&b.textContent.length>0;let _=y.get(b)||1;const C=P.getComponent(f,No);if(C&&(_*=C.alpha),f instanceof K&&w){const M=f[ts];M?r.exportText(M.gameObject,v,n):console.error("Error when exporting UI: shadow component owner not found. This is likely a bug.",f)}if(f instanceof K&&!w){const M=f.geometry.clone();M.scale(1,1,-1),this.flipWindingOrder(M),v.geometry=M;const T=new re,j=f.material.opacity;T.copy(f.material.color),v.material=new Re({color:T,opacity:j*_,map:f.material.map,transparent:!0})}g.set(f,v),y.set(f,_);const R=g.get(b);if(!R){console.error("Error when exporting UI: shadow component parent not found!",f,f.parent);return}R.add(v)})}}for(const d of h)d()}}flipWindingOrder(t){const i=t.index.array;for(let n=0,o=i.length/3;n<o;n++){const r=i[n*3];i[n*3]=i[n*3+2],i[n*3+2]=r}t.index.needsUpdate=!0}}const Xx=class{constructor(){a(this,"_quicklookButton"),a(this,"_arButton"),a(this,"_vrButton"),a(this,"_sendToQuestButton")}static create(){return new Xx}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 Tn.getOrCreate().createQRCode()}createQuicklookButton(){if(this._quicklookButton)return this._quicklookButton;const s=document.createElement("button");this._quicklookButton=s,s.dataset.needle="quicklook-button";const t=X.supportsQuickLookAR();s.innerText="View in AR",s.prepend(Pt("view_in_ar"));let i=!1,n=null;return s.addEventListener("click",()=>{n=Zd(Ge),n||(i=!0,n=new Ge),i&&(n.objectToExport=ee.Current.scene),n?(s.classList.add("this-mode-is-requested"),n.exportAndOpen().then(()=>{s.classList.remove("this-mode-is-requested")}).catch(o=>{s.classList.remove("this-mode-is-requested"),console.error(o)})):console.warn("No USDZExporter component found in the scene")}),this.hideElementDuringXRSession(s),s}createARButton(s){var t;if(this._arButton)return this._arButton;const i="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(Pt("view_in_ar")),n.title="Click to start an AR session",n.addEventListener("click",()=>J.start(i,s)),this.updateSessionSupported(n,i),this.listenToXRSessionState(n,i),this.hideElementDuringXRSession(n),this.isSecureConnection||(n.disabled=!0,n.title="WebXR requires a secure connection (HTTPS)"),X.isMozillaXR()||(t=navigator.xr)==null||t.addEventListener("devicechange",()=>this.updateSessionSupported(n,i)),n}createVRButton(s){var t;if(this._vrButton)return this._vrButton;const i="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(Pt("panorama_photosphere")),n.title="Click to start a VR session",n.addEventListener("click",()=>J.start(i,s)),this.updateSessionSupported(n,i),this.listenToXRSessionState(n,i),this.hideElementDuringXRSession(n),this.isSecureConnection||(n.disabled=!0,n.title="WebXR requires a secure connection (HTTPS)"),X.isMozillaXR()||(t=navigator.xr)==null||t.addEventListener("devicechange",()=>this.updateSessionSupported(n,i)),n}createSendToQuestButton(){var s;if(this._sendToQuestButton)return this._sendToQuestButton;const t="https://oculus.com/open_url/?url=",i=document.createElement("button");return this._sendToQuestButton=i,i.dataset.needle="webxr-sendtoquest-button",i.innerText="Open on Quest",i.prepend(Pt("share_windows")),i.title="Click to send this page to the Oculus Browser on your Quest",i.addEventListener("click",()=>{const n=encodeURIComponent(window.location.href),o=t+n;window.open(o)==null&&De("This page doesn't allow popups. Please paste "+o+" into your browser.")}),this.listenToXRSessionState(i),this.hideElementDuringXRSession(i),X.isMozillaXR()||(s=navigator.xr)==null||s.addEventListener("devicechange",()=>{var n;(n=navigator.xr)!=null&&n.isSessionSupported("immersive-vr")?i.style.display="none":i.style.display=""}),i}createQRCode(){return Tn.getOrCreate().createQRCode()}updateSessionSupported(s,t){if(!("xr"in navigator)){s.style.display="none";return}J.isSessionSupported(t).then(i=>{s.style.display=i?"":"none",F()&&!i&&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(s){Ad(t=>{s["previous-display"]=s.style.display,s.style.display="none"}),ng(t=>{s["previous-display"]!=null&&(s.style.display=s["previous-display"])})}listenToXRSessionState(s,t){t&&(J.onSessionRequestStart(i=>{i.mode===t?s.classList.add("this-mode-is-requested"):(s["was-disabled"]=s.disabled,s.disabled=!0,s.classList.add("other-mode-is-requested"))}),J.onSessionRequestEnd(i=>{s.classList.remove("this-mode-is-requested"),s.classList.remove("other-mode-is-requested"),s.disabled=s["was-disabled"]}))}};let Kr=Xx;a(Kr,"_instance");var IT=Object.defineProperty,jT=Object.getOwnPropertyDescriptor,xt=(s,t,i,n)=>{for(var o=n>1?void 0:n?jT(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&IT(t,i,o),o};const bp=O("debugspriterenderer"),LT=O("wireframe"),C0=class{static getOrCreateGeometry(s){if(s.__cached_geometry)return s.__cached_geometry;if(s.guid&&C0.cache[s.guid])return bp&&console.log("Take cached geometry for sprite",s.guid),C0.cache[s.guid];const t=new bn;s.__cached_geometry=t;const i=new Float32Array(s.triangles.length*3),n=new Float32Array(s.triangles.length*2);for(let o=0;o<s.triangles.length;o+=1){const r=s.triangles[o];i[o*3]=-s.vertices[r].x,i[o*3+1]=s.vertices[r].y,i[o*3+2]=0;const l=s.uv[r];n[o*2]=l.x,n[o*2+1]=1-l.y}return t.setAttribute("position",new ft(i,3)),t.setAttribute("uv",new ft(n,2)),s.guid&&(this.cache[s.guid]=t),bp&&console.log("Built sprite geometry",s,t),t}};let yh=C0;a(yh,"cache",{});class DT{constructor(){a(this,"x"),a(this,"y")}}function Qx(s){s&&(s.colorSpace!=gs&&(s.colorSpace=gs,s.needsUpdate=!0),s.minFilter==md&&s.magFilter==md&&(s.anisotropy=1,s.needsUpdate=!0))}let rn=class{constructor(s){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"),s&&(this.texture=s,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 K(yh.getOrCreateGeometry(this),this.material)),this._mesh}get material(){return this._material||(this.texture&&Qx(this.texture),this._material=new Re({map:this.texture,color:16777215,side:xi,transparent:!0})),this._material}getGeometry(){return yh.getOrCreateGeometry(this)}};xt([m()],rn.prototype,"guid",2),xt([m(Le)],rn.prototype,"texture",2),xt([$a()],rn.prototype,"triangles",2),xt([$a()],rn.prototype,"uv",2),xt([$a()],rn.prototype,"vertices",2);const O0=Symbol("spriteOwner");class Wo{constructor(){a(this,"sprites")}}xt([m(rn)],Wo.prototype,"sprites",2);const Yx=class{constructor(){a(this,"spriteSheet"),a(this,"index",0)}static create(){const s=new Yx;return s.spriteSheet=new Wo,s}set sprite(s){s&&(this.spriteSheet?((this.index===null||this.index===void 0)&&(this.index=0),this.spriteSheet.sprites[this.index]=s):(this.spriteSheet=new Wo,this.spriteSheet.sprites=[s],this.index=0))}get sprite(){if(this.spriteSheet)return this.spriteSheet.sprites[this.index]}update(s){if(!this.spriteSheet)return;const t=this.index;if(t<0||t>=this.spriteSheet.sprites.length)return;const i=this.spriteSheet.sprites[t],n=i?.texture;if(n&&(Qx(n),!i.__hasLoadedProgressive)){i.__hasLoadedProgressive=!0;const o=n;it.assignTextureLOD(n,0).then(r=>{r instanceof Le&&(i.texture=r,s?.map===o&&(s.map=r,s.needsUpdate=!0))})}}};let Vn=Yx;xt([m(Wo)],Vn.prototype,"spriteSheet",2),xt([m()],Vn.prototype,"index",2);class fi extends A{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(t){var i;if(!this._spriteSheet)return;const n=(i=this._spriteSheet.spriteSheet)==null?void 0:i.sprites[this.spriteIndex];n&&(n.texture=t,this.updateSprite())}addSprite(t,i=!1){var n,o;if(this._spriteSheet||(this._spriteSheet=Vn.create()),!this._spriteSheet.spriteSheet)return-1;(n=this._spriteSheet.spriteSheet)==null||n.sprites.push(t);const r=((o=this._spriteSheet.spriteSheet)==null?void 0:o.sprites.length)-1;return i&&(this.spriteIndex=r),r}get sprite(){return this._spriteSheet}set sprite(t){if(t!==this._spriteSheet)if(typeof t=="number"){const i=Math.floor(t);this.spriteIndex=i;return}else t instanceof rn?(this._spriteSheet||(this._spriteSheet=Vn.create()),this._spriteSheet.sprite!=t&&(this._spriteSheet.sprite=t,this.updateSprite())):t!=this._spriteSheet&&(this._spriteSheet=t,this.updateSprite())}set spriteIndex(t){this._spriteSheet&&t!==this.spriteIndex&&(this._spriteSheet.index=t,this.updateSprite())}get spriteIndex(){var t;return((t=this._spriteSheet)==null?void 0:t.index)??0}get spriteFrames(){var t,i;return((i=(t=this._spriteSheet)==null?void 0:t.spriteSheet)==null?void 0:i.sprites.length)??0}awake(){this._currentSprite=void 0,this._spriteSheet||(this._spriteSheet=new Vn,this._spriteSheet.spriteSheet=new Wo),bp&&console.log("Awake",this.name,this,this.sprite)}start(){this._currentSprite?this.gameObject&&this.gameObject.add(this._currentSprite):this.updateSprite()}updateSprite(t=!1){var i;if(!this.__didAwake&&!t)return!1;const n=this._spriteSheet;if(!((i=n?.spriteSheet)!=null&&i.sprites))return console.warn("SpriteRenderer has no data or spritesheet assigned..."),!1;const o=n.spriteSheet.sprites[this.spriteIndex];if(!o)return bp&&console.warn("Sprite not found",this.spriteIndex,n.spriteSheet.sprites),!1;if(this._currentSprite)this._currentSprite.geometry=yh.getOrCreateGeometry(o),this._currentSprite.material.map=o.texture;else{const r=new Re({color:16777215,side:xi});if(LT&&(r.wireframe=!0),this.color&&(r.color||(r.color=new re),r.color.copy(this.color),r.opacity=this.color.alpha),r.transparent=!0,r.toneMapped=this.toneMapped,o.texture&&!r.wireframe){let l=o.texture;l[O0]!==void 0&&l[O0]!==this&&this.spriteFrames>1&&(l=o.texture=l.clone()),l[O0]=this,r.map=l}this.sharedMaterial=r,this._currentSprite=new K(yh.getOrCreateGeometry(o),r),this._currentSprite.renderOrder=Math.round(this.renderOrder),it.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,n?.update(this.sharedMaterial),!0}}xt([m()],fi.prototype,"drawMode",2),xt([m(DT)],fi.prototype,"size",2),xt([m(Se)],fi.prototype,"color",2),xt([m(ke)],fi.prototype,"sharedMaterial",2),xt([m()],fi.prototype,"transparent",2),xt([m()],fi.prototype,"cutoutThreshold",2),xt([m()],fi.prototype,"castShadows",2),xt([m()],fi.prototype,"renderOrder",2),xt([m()],fi.prototype,"toneMapped",2),xt([m(Vn)],fi.prototype,"sprite",1);const Kx=O("debugwebxr"),BT=new ne().makeRotationY(Math.PI);class Hn extends A{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 ne),a(this,"_createdPlacementObject",null),a(this,"_reparentedComponents",[]),a(this,"_placementScene",new qi),a(this,"_reticle",[]),a(this,"_hits",[]),a(this,"_placementStartTime",-1),a(this,"_rigPlacementMatrix"),a(this,"_anchor",null),a(this,"userInput"),a(this,"onPlaceScene",t=>{var i;if(this._isPlacing==!1||t!=null&&t.used)return;let n=this._reticle[0];if(!n){console.warn("No reticle to place...");return}if(!n.visible&&!this.autoPlace){console.warn("Reticle is not visible (can not place)");return}if((i=J.active)!=null&&i.isTrackingImages){console.warn("Scene Placement is disabled while images are being tracked");return}let o=this._hits[0];if(t&&t.origin instanceof og){const r=this._reticle[t.origin.index];r&&(n=r,o=this._hits[t.origin.index])}if(t&&(t.stopImmediatePropagation(),t.stopPropagation(),t.use()),this._isPlacing=!1,this.context.input.removeEventListener("pointerup",this.onPlaceScene),this.onRevertSceneChanges(),n.position.copy(n.lastPos),n.quaternion.copy(n.lastQuat),this.onApplyPose(n),this.useXRAnchor&&this.onCreateAnchor(J.active,o),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(t){const i="placed";return this._eventListeners[i]||(this._eventListeners[i]=[]),this._eventListeners[i].push(t),()=>{const n=this._eventListeners[i].indexOf(t);n>=0&&this._eventListeners[i].splice(n,1)}}get arScale(){return this._arScale}set arScale(t){t!==this._arScale&&(this._arScale=t,this.onScaleChanged())}onEnable(){var t;(t=this.customReticle)==null||t.preload()}supportsXR(t){return t==="immersive-ar"}onEnterXR(t){Kx&&console.log("ENTER WEBXR: SessionRoot start..."),this._anchor=null,this.gameObject.updateMatrixWorld(),this._startOffset.copy(this.gameObject.matrixWorld);const i=new I;this._createdPlacementObject=i,i.name="AR Session Root",this._placementScene.name="AR Placement Scene",this._placementScene.children.length=0;for(let n=this.context.scene.children.length-1;n>=0;n--){const o=this.context.scene.children[n];this._placementScene.add(o)}if(this.context.scene.add(i),this.autoCenter){const n=ci(this._placementScene.children),o=n.getCenter(new x),r=n.getSize(new x),l=new ne;l.makeTranslation(o.x,o.y-r.y*.5,o.z),this._startOffset.multiply(l)}this._reparentedComponents.length=0,this._reparentedComponents.push({comp:this,originalObject:this.gameObject}),P.addComponent(i,this);for(const n of this._reticle)Ri(n);this._reticle.length=0,this._isPlacing=!0,this.context.input.addEventListener("pointerup",this.onPlaceScene,{queue:Oi.Early})}onLeaveXR(){this.context.input.removeEventListener("pointerup",this.onPlaceScene,{queue:Oi.Early}),this.onRevertSceneChanges(),this._anchor=null,this._rigPlacementMatrix=void 0}onUpdateXR(t){var i,n,o,r;if(t.xr.isTrackingImages){for(const l of this._reticle)l.visible=!1;return}if(this._isPlacing){const l=(i=t.xr.rig)==null?void 0:i.gameObject;l&&l.parent!==this.context.scene&&this.context.scene.add(l);let c=!1;if(t.xr.isPassThrough&&t.xr.controllers.length>0&&!this.autoPlace)for(const h of t.xr.controllers){const d=h.getHitTest();d&&(c=!0,this.updateReticleAndHits(t.xr,h.index,d,t.xr.rigScale))}if(!c){const h=t.xr.getHitTest();h&&this.updateReticleAndHits(t.xr,0,h,t.xr.rigScale)}}else{if(this._anchor&&t.xr.referenceSpace){const l=t.xr.frame.getPose(this._anchor.anchorSpace,t.xr.referenceSpace);if(l&&this.context.time.frame%20===0){const c=t.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 _p(this.context)),(n=this.userInput)==null||n.enable()):(o=this.userInput)==null||o.disable(),this.arTouchTransform&&(r=this.userInput)!=null&&r.hasChanged){if(t.xr.rig){const l=t.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(t,i,n,o){this._hits[i]=n.hit;let r=this._reticle[i];if(!r){if(this.customReticle)if(this.customReticle.asset)r=Ua(this.customReticle.asset);else{this.customReticle.loadAssetAsync();return}else r=new K(new aC(.07,.09,32).rotateX(-Math.PI/2),new Re({side:xi,depthTest:!1,depthWrite:!1,transparent:!0,opacity:1,color:15658734})),r.name="AR Placement Reticle";if(Kx){const l=new wi(1);l.position.y+=.01,r.add(l)}this._reticle[i]=r,r.matrixAutoUpdate=!1,r.visible=!1}if(r.lastPos=r.lastPos||n.position.clone(),r.lastQuat=r.lastQuat||n.quaternion.clone(),r.position.copy(r.lastPos.lerp(n.position,this.context.time.deltaTime/.1)),r.lastPos.copy(r.position),r.quaternion.copy(r.lastQuat.slerp(n.quaternion,this.context.time.deltaTime/.05)),r.lastQuat.copy(r.quaternion),r.scale.set(o,o,o),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(G(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}onScaleChanged(){}onRevertSceneChanges(){var t;for(const i of this._reticle)i&&(i.visible=!1,i?.removeFromParent());this._reticle.length=0;for(let i=this._placementScene.children.length-1;i>=0;i--){const n=this._placementScene.children[i];this.context.scene.add(n)}(t=this._createdPlacementObject)==null||t.removeFromParent();for(const i of this._reparentedComponents)P.addComponent(i.originalObject,i.comp)}async onCreateAnchor(t,i){if(i.createAnchor===void 0){console.warn("Hit does not support creating an anchor",i),F()&&xe("Hit does not support creating an anchor");return}else{const n=await i.createAnchor(t.viewerPose.transform);t.running&&n&&(this._anchor=n)}}applyViewBasedTransform(t){const i=this.context.mainCamera,n=t,o=i.worldPosition,r=n.worldPosition;this.upVec.set(0,1,0).applyQuaternion(t.quaternion);const l=i.worldPosition;l&&t.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(t.position).add(this.upVec),this.lookPoint.y=t.position.y,t.lookAt(this.lookPoint)):(o.y=r.y,t.lookAt(o))}onApplyPose(t){var i,n,o,r;const l=(n=(i=J.active)==null?void 0:i.rig)==null?void 0:n.gameObject;if(!l){console.warn("No rig object to place");return}(o=J.active)!=null&&o.rigScale;const c=l.parent||this.context.scene;this._rigPlacementMatrix?(r=this._rigPlacementMatrix)==null||r.decompose(l.position,l.quaternion,l.scale):this._rigPlacementMatrix=l.matrix.clone(),this.applyViewBasedTransform(t),t.updateMatrix(),this.context.scene.add(t),t.attach(l),t.removeFromParent(),l.scale.set(this.arScale,this.arScale,this.arScale),l.position.multiplyScalar(this.arScale),l.updateMatrix(),this.invertForward&&l.matrix.premultiply(BT),l.matrix.premultiply(this._startOffset),l.matrix.decompose(l.position,l.quaternion,l.scale),c.add(l)}}a(Hn,"_eventListeners",{});const P0=class{constructor(s){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 i=0;i<t.changedTouches.length;i++){const n=t.changedTouches[i],o=X.isAndroidDevice()&&n.clientY<window.innerHeight*.1;this.prev.has(n.identifier)||this.prev.set(n.identifier,{ignore:o,x:0,z:0,screenx:0,screeny:0});const r=this.prev.get(n.identifier);if(r){const l=this.getPositionOnPlane(n.clientX,n.clientY);r.x=l.x,r.z=l.z,r.screenx=n.clientX,r.screeny=n.clientY}}}),a(this,"touchEnd",t=>{t.touches.length<=0&&(this._didMultitouch=!1);for(let i=0;i<t.changedTouches.length;i++){const n=t.changedTouches[i];this.prev.delete(n.identifier)}}),a(this,"touchMove",t=>{if(!t.defaultPrevented&&this.isActive){if(t.touches.length===1){if(this._didMultitouch)return;const i=t.touches[0],n=this.prev.get(i.identifier);if(!n||n.ignore)return;const o=this.getPositionOnPlane(i.clientX,i.clientY),r=o.x-n.x,l=o.z-n.z;if(r===0&&l===0)return;this.oneFingerDrag&&this.addMovement(r,l),n.x=o.x,n.z=o.z,n.screenx=i.clientX,n.screeny=i.clientY;return}else if(t.touches.length===2){this._didMultitouch=!0;const i=t.touches[0],n=t.touches[1],o=this.prev.get(i.identifier),r=this.prev.get(n.identifier);if(!o||!r)return;if(this.twoFingerRotate){const l=Math.atan2(i.clientY-n.clientY,i.clientX-n.clientX),c=Math.atan2(o.screeny-r.screeny,o.screenx-r.screenx),h=l-c;Math.abs(h)>.001&&this.addRotation(h)}if(this.twoFingerScale){const l=i.clientX-n.clientX,c=i.clientY-n.clientY,h=Math.sqrt(l*l+c*c),d=o.screenx-r.screenx,u=o.screeny-r.screeny,p=Math.sqrt(d*d+u*u),g=h-p;Math.abs(g)>2&&this.addScale(g)}o.screenx=i.clientX,o.screeny=i.clientY,r.screenx=n.clientX,r.screeny=n.clientY}}}),a(this,"_raycaster",new ud),a(this,"_intersection",new x),a(this,"_screenPos",new x),a(this,"_tempMatrix",new ne),this.context=s,this.offset=new ne,this.plane=new pr,this.plane.setFromNormalAndCoplanarPoint(P0.up,P0.zero)}reset(){this._scale=1,this.offset.identity()}get hasChanged(){return this._hasChanged}applyMatrixTo(s,t){this._hasChanged=!1,t?(this.offset.invert(),s.premultiply(this.offset)):s.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:Oi.Early}),this.context.input.addEventListener("pointerdown",this.onPointerDownLate,{queue:Oi.Late}),this.context.input.addEventListener("pointerup",this.onPointerUpEarly,{queue:Oi.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:Oi.Early}),this.context.input.removeEventListener("pointerdown",this.onPointerDownLate,{queue:Oi.Late}),this.context.input.removeEventListener("pointerup",this.onPointerUpEarly,{queue:Oi.Early}),window.removeEventListener("touchstart",this.touchStart),window.removeEventListener("touchmove",this.touchMove),window.removeEventListener("touchend",this.touchEnd))}getPositionOnPlane(s,t){const i=this.context.mainCamera;return this._screenPos.x=s/window.innerWidth*2-1,this._screenPos.y=-(t/window.innerHeight)*2+1,this._screenPos.z=1,this._screenPos.unproject(i),this._raycaster.set(i.position,this._screenPos.sub(i.position)),this._raycaster.ray.intersectPlane(this.plane,this._intersection),this._intersection}addMovement(s,t){s/=this._scale,t/=this._scale,s*=this.factor,t*=this.factor,this.offset.elements[12]+=s,this.offset.elements[14]+=t,(s!==0||t!==0)&&(this._hasChanged=!0)}addScale(s){s/=window.innerWidth,s*=-1,this._scale*=1+s,this._tempMatrix.makeScale(1-s,1-s,1-s),this.offset.premultiply(this._tempMatrix),s!==0&&(this._hasChanged=!0)}addRotation(s){s*=-1,this._tempMatrix.makeRotationY(s),this.offset.premultiply(this._tempMatrix),s!==0&&(this._hasChanged=!0)}};let _p=P0;a(_p,"up",new x(0,1,0)),a(_p,"zero",new x(0,0,0)),a(_p,"one",new x(1,1,1));const Vo=O("debugautosync"),k0=Symbol("syncerId");class FT{constructor(){a(this,"_syncers",{})}getOrCreateSyncer(t){if(!t.guid)return null;if(this._syncers[t.guid])return this._syncers[t.guid];const i=new zT(t);return i[k0]=t.guid,this._syncers[i[k0]]=i,i}removeSyncer(t){delete this._syncers[t[k0]]}}const M0=new FT;class zT{constructor(t){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 i=this.comp.context.connection;if(!i||!i.isConnected||!i.isInRoom){for(const n in this.changedProperties)delete this.changedProperties[n];return}for(const n in this.changedProperties){const o=this.changedProperties[n];Vo&&console.log("SEND",this.comp.guid,this.networkingKey),i.send(this.networkingKey,{guid:this.comp.guid,property:n,data:o},ws.Queued),delete this.changedProperties[n]}}),a(this,"onHandleReceiving",i=>{if(Vo&&console.log("SYNCFIELD RECEIVE",this.comp.name,this.comp.guid,i),!!this._isInit&&this.comp&&i.guid===this.comp.guid)try{this._isReceiving=!0,this.comp[i.property]=i.data}catch(n){console.error(n)}finally{this._isReceiving=!1}}),this.comp=t}get networkingKey(){return this.comp.guid}init(t){if(this._isInit)return;this._isInit=!0,this.comp=t,this.comp.context.post_render_callbacks.push(this.onHandleSending),this.comp.context.connection.beginListen(this.networkingKey,this.onHandleReceiving);const i=this.comp.context.connection.tryGetState(this.comp.guid);i&&this.onHandleReceiving(i)}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(t,i){this._isReceiving||(Vo&&console.log("Property changed: "+t,i),this.hasChanges=!0,this.changedProperties[t]=i)}}function UT(s,t){let i=t!==s;return!i&&s&&t&&(Array.isArray(s)&&Array.isArray(t)||typeof s=="object"&&typeof t=="object")&&(i=!0),i}const vh=Symbol("AutoSyncHandler");function NT(s){if(s[vh])return s[vh];const t=M0.getOrCreateSyncer(s);return t?.init(s),s[vh]=t,t}function WT(s){const t=s[vh];t&&(M0.removeSyncer(t),t.destroy(),delete s[vh])}const R0=function(s=null){return function(t,i){var n;let o="";typeof i=="string"?o=i:o=i.name;let r=null,l;typeof s=="string"?l=t[s]:typeof s=="function"&&(l=s),l==null&&(F()||Vo)&&s!=null&&console.warn('syncField: no callback function found for property "'+o+'"','"'+s+'"');const c=t,h=c.__internalAwake;if(typeof h!="function"){(Vo||F())&&console.error('@syncField can currently only used on Needle Engine Components, custom object of type "'+((n=t?.constructor)==null?void 0:n.name)+'" is not supported',t);return}Vo&&console.log(o);const d=Symbol(o);c.__internalAwake=function(){if(this[d]!==void 0)return;this[d]=this[o],r=M0.getOrCreateSyncer(this);const p=Object.getOwnPropertyDescriptor(this,o);if(p?.set===void 0){let g=!1;Object.defineProperty(this,o,{set:function(y){var f;const v=this[d];if(this[d]=y,g){(F()||Vo)&&console.warn("Recursive call detected",o);return}g=!0;try{const b=UT(y,v);Vo&&console.log("SyncField assignment",o,"changed?",b,y,l),b&&l?.call(this,y,v)!==!1&&((f=NT(this))==null||f.notifyChanged(o,y))}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(){WT(this),u.call(this)}}};var VT=Object.defineProperty,HT=Object.getOwnPropertyDescriptor,wp=(s,t,i,n)=>{for(var o=n>1?void 0:n?HT(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&VT(t,i,o),o};const ii=O("debugplayersync"),Zx=class extends A{constructor(){super(...arguments),a(this,"autoSync",!0),a(this,"asset"),a(this,"onPlayerSpawned"),a(this,"_localInstance"),a(this,"onJoinedRoom",()=>{ii&&console.log("PlayerSync.joinedRoom. autoSync is set to "+this.autoSync),this.autoSync&&this.getInstance()}),a(this,"destroyInstance",()=>{var s;(s=this._localInstance)==null||s.then(t=>{ii&&console.log("PlayerSync.destroyInstance",t),xc(t,this.context.connection,!0,{saveInRoom:!1})}),this._localInstance=void 0})}static async setupFrom(s,t){const i=ae.getOrCreateFromUrl(s);if(!i.asset){const r=await i.loadAssetAsync();r&&P.getOrAddComponent(r,Li)}const n=new Zx;n._internalInit(t),n.asset=i;const o=new I;return o.guid=s,P.addComponent(o,n),n}awake(){this.watchTabVisible(),this.onPlayerSpawned||(this.onPlayerSpawned=new _e)}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 s,t,i,n,o,r;if(this._localInstance)return this._localInstance;if(ii&&console.log("PlayerSync.createInstance",(s=this.asset)==null?void 0:s.url),!((t=this.asset)!=null&&t.asset)&&!((i=this.asset)!=null&&i.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 l=await this._localInstance;if(l){const c=P.getComponentsInChildren(l,Li);if(ii&&console.log(`PlayerSync.createInstance: found ${c?.length} PlayerState components. Owner: ${this.context.connection.connectionId}`),c!=null&&c.length){for(const h of c)h.owner=this.context.connection.connectionId;(o=this.onPlayerSpawned)==null||o.invoke(l)}else this._localInstance=void 0,console.error("<strong>Failed finding PlayerState on "+((r=this.asset)==null?void 0:r.url)+"</strong>: please make sure the asset has a PlayerState component!"),P.destroySynced(l)}else this._localInstance=void 0,console.warn("PlayerSync: failed instantiating asset!");return this._localInstance}watchTabVisible(){window.addEventListener("visibilitychange",s=>{if(document.visibilityState==="visible")for(let t=Li.all.length-1;t>=0;t--){const i=Li.all[t];(!i.owner||!this.context.connection.userIsInRoom(i.owner))&&i.doDestroy()}})}};let Sl=Zx;wp([m()],Sl.prototype,"autoSync",2),wp([m(ae)],Sl.prototype,"asset",2),wp([m(_e)],Sl.prototype,"onPlayerSpawned",2);var Jx=(s=>(s.OwnerChanged="ownerChanged",s))(Jx||{}),bh;const At=(bh=class extends A{constructor(){super(...arguments),a(this,"onOwnerChangeEvent",new _e),a(this,"onFirstOwnerChangeEvent",new _e),a(this,"hasOwner",!1),a(this,"owner"),a(this,"dontDestroy",!1),a(this,"onUserLeftRoom",s=>{if(s.userId===this.owner){ii&&console.log("PLAYERSYNC LEFT",this.owner),this.doDestroy();return}})}static get all(){return At._all}static get local(){return At._local}static getFor(s){if(s instanceof I)return P.getComponentInParent(s,At);if(s instanceof A)return P.getComponentInParent(s.gameObject,At)}static isLocalPlayer(s){const t=At.getFor(s);return t?.isLocalPlayer??!1}static addEventListener(s,t){return this._callbacks[s]||(this._callbacks[s]=[]),this._callbacks[s].push(t),t}static removeEventListener(s,t){if(!this._callbacks[s])return;const i=this._callbacks[s].indexOf(t);i>=0&&this._callbacks[s].splice(i,1)}static dispatchEvent(s,t){if(this._callbacks[s])for(const i of this._callbacks[s])i(t)}get isLocalPlayer(){return this.owner===this.context.connection.connectionId}onOwnerChange(s,t){var i,n;ii&&console.log(`PlayerSync.onOwnerChange: ${t} \u2192 ${s} (me: ${this.context.connection.connectionId})`);const o=At._local.indexOf(this);o>=0&&At._local.splice(o,1);const r={playerState:this,oldValue:t,newValue:s};if(this.hasOwner||(this.hasOwner=!0,(i=this.onFirstOwnerChangeEvent)==null||i.invoke(r)),(n=this.onOwnerChangeEvent)==null||n.invoke(r),this.owner===this.context.connection.connectionId){At._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),At.dispatchEvent("ownerChanged",l)}awake(){At.all.push(this),ii&&console.log("Registered new PlayerState",this.guid,At.all.length-1,At.all),this.context.connection.beginListen(ie.UserLeftRoom,this.onUserLeftRoom)}async start(){ii&&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&&(ii&&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||(ii&&console.warn("PlayerState.start \u2192 owner is undefined!",this.name),setTimeout(()=>{!this.destroyed&&!this.owner?this.dontDestroy?ii&&console.warn("PlayerState.start \u2192 owner is still undefined but dontDestroy is set to true",this.name):(ii&&console.warn(`PlayerState.start \u2192 owner is still undefined: destroying "${this.name}" instance now`),this.doDestroy()):ii&&console.log("PlayerState.start \u2192 owner is assigned",this.owner)},2e3))}doDestroy(){ii&&console.log("PlayerSync.doDestroy \u2192 syncDestroy",this.name),xc(this.gameObject,this.context.connection,!0,{saveInRoom:!1})}onDestroy(){if(ii&&console.warn("PlayerState.onDestroy",this.owner),this.context.connection.stopListen(ie.UserLeftRoom,this.onUserLeftRoom),At.all.splice(At.all.indexOf(this),1),this.isLocalPlayer){const s=At._local.indexOf(this);s>=0&&At._local.splice(s,1)}}},a(bh,"_all",[]),a(bh,"_local",[]),a(bh,"_callbacks",{}),bh);let Li=At;wp([R0(Li.prototype.onOwnerChange)],Li.prototype,"owner",2);var $T=Object.defineProperty,qT=Object.getOwnPropertyDescriptor,Cl=(s,t,i,n)=>{for(var o=n>1?void 0:n?qT(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&$T(t,i,o),o};class an extends A{constructor(){super(...arguments),a(this,"position","bottom"),a(this,"showNeedleLogo",!0),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&&(X.isMobileDevice()||this.context.menu.showQRCodeButton(!0))}}Cl([m()],an.prototype,"position",2),Cl([m()],an.prototype,"showNeedleLogo",2),Cl([m()],an.prototype,"showSpatialMenu",2),Cl([m()],an.prototype,"createFullscreenButton",2),Cl([m()],an.prototype,"createMuteButton",2),Cl([m()],an.prototype,"createQRCodeButton",2);var GT=Object.defineProperty,XT=Object.getOwnPropertyDescriptor,T0=(s,t,i,n)=>{for(var o=n>1?void 0:n?XT(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&GT(t,i,o),o};const _h=O("debugwebxr"),e1=new V().setFromAxisAngle(new x(0,1,0),Math.PI);class Ho extends A{constructor(){super(...arguments),a(this,"head"),a(this,"leftHand"),a(this,"rightHand"),a(this,"_leftHandMeshes"),a(this,"_rightHandMeshes"),a(this,"_syncTransforms")}async onEnterXR(t){if(!this.activeAndEnabled)return;_h&&console.warn("AVATAR ENTER XR",this.guid,this.sourceId,this,this.activeAndEnabled),this._syncTransforms&&(this._syncTransforms.length=0),await this.prepareAvatar();const i=Li.getFor(this);if(i!=null&&i.owner){const n=this.gameObject.addComponent(Rt);n.avatar=this.gameObject,n.connectionId=i.owner}else this.context.connection.isConnected?console.error("No player state found for avatar",this):i&&!this.context.connection.isConnected&&(i.dontDestroy=!0)}onLeaveXR(t){const i=this.gameObject.getComponent(Rt);i&&i.destroy()}onUpdateXR(t){var i,n;if(!this.activeAndEnabled)return;const o=Li.isLocalPlayer(this);if(!o)return;const r=t.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&&o)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,Ai);for(const g of p)g.enabled=!1,g.gameObject.visible=!1}}const l=t.xr.leftController,c=(i=this.leftHand)==null?void 0:i.asset;l&&c?(c.position.copy(l.gripPosition),c.quaternion.copy(l.gripQuaternion),c.quaternion.multiply(e1),c.visible=l.isTracking,this.updateHandVisibility(l,c,this._leftHandMeshes)):c&&c.visible&&(c.visible=!1);const h=t.xr.rightController,d=(n=this.rightHand)==null?void 0:n.asset;h&&d?(d.position.copy(h.gripPosition),d.quaternion.copy(h.gripQuaternion),d.quaternion.multiply(e1),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(t,i,n){if(n){const o=t.model&&t.model.visible&&t.model!==i;n.forEach(r=>{Mn(r,!o)})}}updateRemoteAvatarVisibility(){var t,i,n;if(this.context.connection.isConnected){const o=Li.getFor(this);if(o&&o.isLocalPlayer==!1){const r=J.getXRSync(this.context);if(r&&r.hasState(o.owner)){this.tryFindAvatarObjectsIfMissing();const l=(t=this.leftHand)==null?void 0:t.asset;l&&(l.visible=r?.isTracking(o.owner,"left")??!1);const c=(i=this.rightHand)==null?void 0:i.asset;c&&(c.visible=r?.isTracking(o.owner,"right")??!1)}if((n=this.head)!=null&&n.asset){const l=P.getComponentsInChildren(this.head.asset,Ai);for(const c of l)c.enabled=!1,c.gameObject.visible=!0}}}}tryFindAvatarObjectsIfMissing(){if(!this.head||!this.leftHand||!this.rightHand){const t={head:this.head,leftHand:this.leftHand,rightHand:this.rightHand};Nb.tryFindAvatarObjects(this.gameObject,this.sourceId||"",t),t.head&&(this.head=t.head),t.leftHand&&(this.leftHand=t.leftHand),t.rightHand&&(this.rightHand=t.rightHand)}}async prepareAvatar(){var t,i;if(this.tryFindAvatarObjectsIfMissing(),this.head)this.head instanceof I&&(this.head=new ae("",this.sourceId,this.head));else{const n=new I;n.name="Head";const o=go.createPrimitive(wr.Cube);n.add(o),this.gameObject.add(n),this.head=new ae("",this.sourceId,n),_h&&console.log("Create head",n)}if(this.rightHand)this.rightHand instanceof I&&(this.rightHand=new ae("",this.sourceId,this.rightHand));else{const n=new I;n.name="Right Hand",this.gameObject.add(n),this.rightHand=new ae("",this.sourceId,n),_h&&console.log("Create right hand",n)}if(this.leftHand)this.leftHand instanceof I&&(this.leftHand=new ae("",this.sourceId,this.leftHand));else{const n=new I;n.name="Left Hand",this.gameObject.add(n),this.leftHand=new ae("",this.sourceId,n),_h&&console.log("Create left hand",n)}await this.loadAvatarObjects(this.head,this.leftHand,this.rightHand),this._leftHandMeshes=[],(t=this.leftHand.asset)==null||t.traverse(n=>{n!=null&&n.isMesh&&this._leftHandMeshes.push(n)}),this._rightHandMeshes=[],(i=this.rightHand.asset)==null||i.traverse(n=>{n!=null&&n.isMesh&&this._rightHandMeshes.push(n)}),Li.isLocalPlayer(this.gameObject)&&(this._syncTransforms=P.getComponentsInChildren(this.gameObject,qs))}async loadAvatarObjects(t,i,n){const o=t.loadAssetAsync(),r=i.loadAssetAsync(),l=n.loadAssetAsync(),c=new Array;o&&c.push(o),r&&c.push(r),l&&c.push(l);const h=await wd(c);_h&&console.log("Avatar loaded results:",h)}}T0([m(ae)],Ho.prototype,"head",2),T0([m(ae)],Ho.prototype,"leftHand",2),T0([m(ae)],Ho.prototype,"rightHand",2);var QT=Object.defineProperty,YT=Object.getOwnPropertyDescriptor,xp=(s,t,i,n)=>{for(var o=n>1?void 0:n?YT(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&QT(t,i,o),o};const $n=O("debugwebxr"),$o=new Array;class ln extends A{constructor(){super(...arguments),a(this,"createControllerModel",!0),a(this,"createHandModel",!0),a(this,"customLeftHand"),a(this,"customRightHand"),a(this,"_models",new Array)}supportsXR(t){return t==="immersive-vr"||t==="immersive-ar"}async onXRControllerAdded(t){var i;if(!(t.xr.isVR||t.xr.isPassThrough))return;const{controller:n}=t;if($n&&console.warn("Add Controller Model for",n.side,n.index),this.createControllerModel||this.createHandModel){if(n.hand){if(this.createHandModel){const o=await this.loadHandModel(this,n);if(!o||!n.connected||!n.isHand){o!=null&&o.handObject&&za(o.handObject,!1),(i=o?.handObject)==null||i.destroy();return}this._models.push({controller:n,model:o.handObject,handmesh:o.handmesh}),this._models.sort((r,l)=>r.controller.index-l.controller.index),this.scene.add(o.handObject),n.model=o.handObject}}else if(this.createControllerModel){const o=await n.getModelUrl();if(o){const r=await this.loadModel(n,o);if(!r||!n.connected||n.isHand)return;this._models.push({controller:n,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()}),n.model=r}else n.targetRayMode!=="transient-pointer"&&console.warn("XRControllerModel: no model found for "+n.side)}}}onXRControllerRemoved(t){console.debug("XR Controller Removed",t.controller.side,t.controller.index);const i=this._models.findIndex(o=>o.controller===t.controller),n=this._models[i];n&&(this._models.splice(i,1),n.model&&(za(n.model,!1),n.model.destroy(),n.model=void 0))}onBeforeXR(t,i){this.createHandModel&&(this.customLeftHand||this.customRightHand)&&(i.optionalFeatures=i.optionalFeatures||[],i.optionalFeatures.includes("hand-tracking")||i.optionalFeatures.push("hand-tracking"))}onLeaveXR(t){for(const i of this._models)i&&(i.model&&(za(i.model,!1),i.model.destroy(),i.model=void 0),i.controller.model===i.model&&(i.controller.model=null));this._models.length=0}onBeforeRender(){if(J.active&&($n&&($o[0]=Date.now()),this.updateRendering(J.active),$n)){const t=Date.now()-$o[0];$o.push(t),$o.length>=30&&($o[0]=0,$o.reduce((i,n)=>i+n,0)/$o.length,$o.length=0)}}updateRendering(t){var i,n,o,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){$n&&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,(i=t.rig)==null||i.gameObject.add(h.model);else if(d.inputSource.hand&&h.handmesh){const u=t.referenceSpace,p=this.context.renderer.xr.getHand(d.index);if(u&&t.frame.getJointPose){for(const g of d.inputSource.hand.values()){const y=p.joints[g.jointName];if(y){const f=d.getHandJointPose(g);if(f){const v=f.transform.position,b=f.transform.orientation;y.position.copy(v),y.quaternion.copy(b),y.matrixAutoUpdate=!1}y.visible=f!=null}}h.model&&(h.model.visible=d.isTracking,h.model.visible&&h.model.parent!==((n=t.rig)==null?void 0:n.gameObject)&&((o=t.rig)==null||o.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(Ra))}}}}async loadModel(t,i){var n;if(!t.connected)return console.warn("XRControllerModel.onXRControllerAdded: controller is not connected anymore",t.side),null;const o=await ae.getOrCreate("",i).instantiate();return za(o),(n=J.active)!=null&&n.isPassThrough&&o.traverseVisible(r=>{this.makeOccluder(r)}),o}async loadHandModel(t,i){const n=this.context,o=n.renderer.xr.getHand(i.index);o||($n?q.DrawLabel(i.rayWorldPosition,"No hand found for index "+i.index,.05,5):console.warn("No hand found for index "+i.index));const r=new gr;Su(r,n),await Zu(r,n,this.sourceId??"");const l=Ku(r);let c="";const h=i.side==="left"?this.customLeftHand:this.customRightHand;h?(c=h.url.split(".").slice(0,-1).join("."),r.setPath("")):(c=i.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 I;za(d);const u=new UC(d,o,r.path,c,r,p=>{var g;const y=l.gltf;((g=y?.scene.children)==null?void 0:g.length)===0&&(y.scene.children[0]=p),fs().createBuiltinComponents(t.context,t.sourceId||c,l.gltf,null,l),p.traverse(f=>{var v;f.layers.set(2),(v=J.active)!=null&&v.isPassThrough&&!h&&this.makeOccluder(f),f instanceof K&&it.assignMeshLOD(f,0)}),i.connected||($n&&q.DrawLabel(i.rayWorldPosition,"Hand is loaded but not connected anymore",.05,5),p.removeFromParent())});if($n&&d.add(new wi(.5)),i.inputSource.hand){$n&&console.log(i.inputSource.hand);for(const p of i.inputSource.hand.values())if(o.joints[p.jointName]===void 0){const g=new ro;g.matrixAutoUpdate=!1,g.visible=!0,o.joints[p.jointName]=g,o.add(g)}}else $n&&q.DrawLabel(i.rayWorldPosition,"No inputSource.hand found for index "+i.index,.05,5);return{handObject:d,handmesh:u}}makeOccluder(t){if(t instanceof K){let i=t.material;i instanceof ke&&(i=t.material=i.clone(),i.depthWrite=!0,i.depthTest=!0,i.colorWrite=!1,t.receiveShadow=!1,t.renderOrder=-100)}}}a(ln,"factory",new zC),xp([m()],ln.prototype,"createControllerModel",2),xp([m()],ln.prototype,"createHandModel",2),xp([m(ae)],ln.prototype,"customLeftHand",2),xp([m(ae)],ln.prototype,"customRightHand",2);class Sp extends A{}var KT=Object.defineProperty,ZT=Object.getOwnPropertyDescriptor,qo=(s,t,i,n)=>{for(var o=n>1?void 0:n?ZT(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&KT(t,i,o),o};const E0=O("debugwebxr");class Di extends A{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",t=>t.type==="SkinnedMesh"?"continue in children":!0)}onUpdateXR(t){const i=t.xr.rig;if(!(i!=null&&i.gameObject)||t.xr.isPassThrough)return;const n=t.xr.leftController,o=t.xr.rightController;n&&this.onHandleMovement(n,i.gameObject),o&&(this.onHandleRotation(o,i.gameObject),this.useTeleport&&this.onHandleTeleport(o,i.gameObject))}onLeaveXR(t){for(const i of this._lines)i.removeFromParent();for(const i of this._hitDiscs)i?.removeFromParent()}onBeforeRender(){var t;(t=this.context.xr)!=null&&t.running&&(this.showRays&&this.renderRays(this.context.xr),this.showHits&&this.renderHits(this.context.xr))}onHandleMovement(t,i){const n=t.getStick("xr-standard-thumbstick");if(n.x!=0||n.y!=0){const o=G(n.x,0,n.y);o.multiplyScalar(this.context.time.deltaTimeUnscaled*this.movementSpeed);const r=Je(i);o.multiplyScalar(r.x),o.applyQuaternion(t.xr.poseOrientation),o.y=0,o.applyQuaternion(i.worldQuaternion),i.position.add(o),i.updateWorldMatrix(!1,!1);for(const l of i.children)l.updateWorldMatrix(!1,!1)}}onHandleRotation(t,i){if(t._isMxInk)return;const n=t.getStick("xr-standard-thumbstick").x;if(this._didApplyRotation)Math.abs(n)<.3&&(this._didApplyRotation=!1);else if(Math.abs(n)>.5){this._didApplyRotation=!0;const o=n>0?1:-1,r=te(this.context.mainCamera).clone();i.rotateY(o*W.toRadians(this.rotationStep));const l=te(this.context.mainCamera).clone().sub(r);l.y=0,i.position.sub(l)}}onHandleTeleport(t,i){var n,o,r,l,c;let h=0;if(t.hand&&this.usePinchToTeleport&&t.isTeleportGesture){const d=t.getPointerId("primary");if(d!=null&&this.context.input.getIsPointerIdInUse(d))return;const u=t.getGesture("pinch");u&&(h=u.value)}else h=(n=t.getStick("xr-standard-thumbstick"))==null?void 0:n.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(t.ray)[0];if(d&&d.object instanceof Sa){const p=(o=d.normal)==null?void 0:o.dot(G(0,1,0));if(p!==void 0&&p<.4)return}let u=d?.point;if(!u&&!this.useTeleportTarget){this._plane||(this._plane=new pr(new x(0,1,0),0));const p=i.worldPosition;this._plane.setFromNormalAndCoplanarPoint(new x(0,1,0),p);const g=t.ray;u=p.clone(),this._plane.intersectLine(new lC(g.origin,G(g.direction).multiplyScalar(1e4).add(g.origin)),u),u.distanceTo(p)>i.scale.x*10&&(u=null)}if(u){if(this.useTeleportTarget&&!P.getComponentInParent(d.object,Sp))return;const p=u.clone();if(E0&&q.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),E0&&q.DrawWireSphere(g.add(p),.025,65280,5))}this._teleportBuffer.push(i.matrix.clone()),this._teleportBuffer.length>10&&this._teleportBuffer.shift(),this.useTeleportFade?(c=t.xr.fadeTransition())==null||c.then(()=>{i.worldPosition=p}):i.worldPosition=p}}else if(h<-.8&&(this._didTeleport=!0,this._teleportBuffer.length>0)){const d=this._teleportBuffer.pop();d&&d.decompose(i.position,i.quaternion,i.scale)}}renderRays(t){var i;for(let n=0;n<this._lines.length;n++){const o=this._lines[n];o&&(o.visible=!1)}for(let n=0;n<t.controllers.length;n++){const o=t.controllers[n];let r=this._lines[n];if(!o.connected||!o.isTracking||!o.ray||o.targetRayMode==="transient-pointer"||!o.hasSelectEvent){r&&(r.visible=!1);continue}r||(r=this.createRayLineObject(),r.scale.z=.5,this._lines[n]=r),o.updateRayWorldPosition(),o.updateRayWorldQuaternion();const l=o.rayWorldPosition,c=o.rayWorldQuaternion;r.position.copy(l),r.quaternion.copy(c);const h=t.rigScale,d=this.usePinchToTeleport&&o.isTeleportGesture,u=this._lastHitDistances[n],p=this._hitDistances[n]!=null,g=u??h;r.scale.set(h,h,g),r.visible=!0,r.layers.disableAll(),r.layers.enable(2);let y=r.material.opacity;d?y=1:this.showHits&&g<t.rigScale*.5?y=0:(i=o.getButton("primary"))!=null&&i.pressed?y=.5:y=p?.2:.1,r.material.opacity=W.lerp(r.material.opacity,y,this.context.time.deltaTimeUnscaled/.1),r.parent!==this.context.scene&&this.context.scene.add(r)}}renderHits(t){var i;for(const n of this._hitDiscs){if(!n)continue;const o=n.controller;if(!o||!o.connected||!o.isTracking){n.visible=!1;continue}}for(let n=0;n<t.controllers.length;n++){const o=t.controllers[n];if(!o.connected||!o.isTracking||!o.ray||!o.hasSelectEvent)continue;let r=this._hitDiscs[n],l=!0;const c=o.getPointerId("primary");c!=null&&this.context.input.getIsPointerIdInUse(c)&&(r&&(r.visible=!1),this._hitDistances[n]=null,this._lastHitDistances[n]=0,l=!1);const h=this.context.time.smoothedFps>=59?1:10;if((this.context.time.frame+o.index)%h!==0&&(l=!1),!l){const p=this._hitDiscs[n];p&&p.visible&&p.hit&&this.updateHitPointerPosition(o,p,p.hit.distance);continue}const d=this.context.physics.raycastFromRay(o.ray,{testObject:this.hitPointRaycastFilter,precise:!1});let u=d.find(p=>this.usePinchToTeleport&&o.isTeleportGesture?!0:this.isObjectWithInteractiveComponent(p.object));if(u||(u=d[0]),r&&(r.controller=o,r.hit=u),this._hitDistances[n]=u?.distance||null,u){this._lastHitDistances[n]=u.distance;const p=t.rigScale??1;E0&&(q.DrawWireSphere(u.point,.025*p,16711680),q.DrawLabel(G(0,.2,0).add(u.point),u.object.name,.02,0)),r||(r=this.createHitPointObject(),this._hitDiscs[n]=r),r.hit=u,r.visible=u.distance>p*.05;let g=.01*(p+u.distance);const y=(i=o.getButton("primary"))==null?void 0:i.pressed;y&&(g*=1.1),r.scale.set(g,g,g),r.layers.set(2);let f=r.material.opacity;if(y?f=1:f=u.distance<.15*p?.2:.6,r.material.opacity=W.lerp(r.material.opacity,f,this.context.time.deltaTimeUnscaled/.1),r.visible){if(u.normal){this.updateHitPointerPosition(o,r,u.distance);const v=u.normal.applyQuaternion(Oe(u.object));r.quaternion.setFromUnitVectors(JT,v)}else this.updateHitPointerPosition(o,r,u.distance);r.parent!==this.context.scene&&this.context.scene.add(r)}}else this._hitDiscs[n]&&(this._hitDiscs[n].visible=!1)}}isObjectWithInteractiveComponent(t,i=0){return Tu(t)||t.isUI===!0?!0:t.isScene?!1:t.parent?this.isObjectWithInteractiveComponent(t.parent,i+1):!1}updateHitPointerPosition(t,i,n){const o=G(t.rayWorldPosition);o.add(G(0,0,n-.01).applyQuaternion(t.rayWorldQuaternion)),i.position.lerp(o,this.context.time.deltaTimeUnscaled/.05)}createHitPointObject(){const t=new K(new hd(.3,6,6),new Re({color:15658734,opacity:.7,transparent:!0,depthTest:!1,depthWrite:!1,side:xi}));return t.layers.disableAll(),t.layers.enable(2),t}createRayLineObject(){const t=new NC;t.layers.disableAll(),t.layers.enable(2);const i=new WC;t.geometry=i;const n=new Float32Array(9);n.set([0,0,.02,0,0,.4,0,0,1]),i.setPositions(n);const o=new Float32Array(9);o.set([1,1,1,.1,.1,.1,0,0,0]),i.setColors(o);const r=new VC({color:16777215,vertexColors:!0,worldUnits:!0,linewidth:.004,transparent:!0,depthWrite:!1,blending:iv,dashed:!1});return t.material=r,t}}qo([m()],Di.prototype,"movementSpeed",2),qo([m()],Di.prototype,"rotationStep",2),qo([m()],Di.prototype,"useTeleport",2),qo([m()],Di.prototype,"usePinchToTeleport",2),qo([m()],Di.prototype,"useTeleportTarget",2),qo([m()],Di.prototype,"useTeleportFade",2),qo([m()],Di.prototype,"showRays",2),qo([m()],Di.prototype,"showHits",2);const JT=new x(0,1,0);var eE=Object.defineProperty,tE=Object.getOwnPropertyDescriptor,St=(s,t,i,n)=>{for(var o=n>1?void 0:n?tE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&eE(t,i,o),o};const wh=O("debugwebxr"),iE=O("debugusdz");var A0;const Ol=(A0=class extends A{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",!0),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,"onAvatarSpawned",s=>{wh&&console.log("WebXR.onAvatarSpawned",s),P.getComponentInChildren(s,Ho)??(e=P.addComponent(s,Ho))}),a(this,"_buttonFactory"),a(this,"_buttons",[])}awake(){J.getXRSync(this.context)}onEnable(){var s,t;window.location.protocol!=="https:"&&xe('<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(Ge)||(wh&&console.log("WebXR: Adding USDZExporter"),this._usdzExporter=P.addComponent(this.gameObject,Ge),this._usdzExporter.objectToExport=this.context.scene,this._usdzExporter.autoExportAnimations=!0,this._usdzExporter.autoExportAudioSources=!0)),this.handleCreatingHTML(),this.handleOfferSession(),this.defaultAvatar===!0&&(wh&&console.warn("WebXR: No default avatar set, using static default avatar"),this.defaultAvatar=new ae("https://cdn.needle.tools/static/avatars/DefaultAvatar.glb")),this.defaultAvatar&&(this._playerSync=this.gameObject.getOrAddComponent(Sl),this._playerSync.autoSync=!1),this._playerSync&&typeof this.defaultAvatar!="boolean"&&(this._playerSync.asset=this.defaultAvatar,(s=this._playerSync.onPlayerSpawned)==null||s.removeEventListener(this.onAvatarSpawned),(t=this._playerSync.onPlayerSpawned)==null||t.addEventListener(this.onAvatarSpawned))}onDisable(){var s;(s=this._usdzExporter)==null||s.destroy(),this.removeButtons()}async handleOfferSession(){return this.createVRButton&&await J.isVRSupported()&&this.createVRButton?J.offerSession("immersive-vr","default",this.context):this.createARButton&&await J.isARSupported()&&this.createARButton?J.offerSession("immersive-ar","default",this.context):!1}get session(){return J.active??null}get sessionMode(){return J.activeMode??null}async enterVR(s){return J.start("immersive-vr",s,this.context)}async enterAR(s){return J.start("immersive-ar",s,this.context)}exitXR(){J.stop()}get isActiveWebXR(){return!Ol.activeWebXRComponent||Ol.activeWebXRComponent===this}onBeforeXR(s,t){var i;if(!this.isActiveWebXR){console.warn(`WebXR: another WebXR component is already active (${(i=Ol.activeWebXRComponent)==null?void 0:i.name}). This is ignored: ${this.name}`);return}Ol.activeWebXRComponent=this,s=="immersive-ar"&&this.useDepthSensing&&(t.optionalFeatures=t.optionalFeatures||[],t.optionalFeatures.push("depth-sensing"))}async onEnterXR(s){if(!this.isActiveWebXR)return;wh&&console.log("WebXR onEnterXR"),this._previousXRState=Kt.Global.Mask;const t=s.xr.isVR;if(Kt.Global.Set(t?Zs.VR:Zs.AR),s.xr.isAR){let i=P.findObjectOfType(Hn);if(!i)if(this.usePlacementReticle){const n=new I;for(const o of this.context.scene.children)n.add(o);this.context.scene.add(n),i=P.addComponent(n,Hn),this._createdComponentsInSession.push(i)}else(wh||F())&&console.warn("WebXR: No WebARSessionRoot found in scene and usePlacementReticle is disabled in WebXR component.");i&&(i.customReticle=this.customARPlacementReticle,i.arScale=this.arScale,i.arTouchTransform=this.usePlacementAdjustment,i.autoPlace=this.autoPlace,i.autoCenter=this.autoCenter,i.useXRAnchor=this.useXRAnchor)}this.useDefaultControls&&this.setDefaultMovementEnabled(!0),(this.showControllerModels||this.showHandModels)&&this.setDefaultControllerRenderingEnabled(!0),this.useSpatialGrab&&(this._spatialGrabRaycaster=P.findObjectOfType(Qa)??void 0,this._spatialGrabRaycaster||(this._spatialGrabRaycaster=this.gameObject.addComponent(Qa))),this.createLocalAvatar(s.xr),s.xr.isScreenBasedAR||(this._exitXRMenuButton=this.context.menu.appendChild({label:"Quit XR",onClick:()=>this.exitXR(),icon:"exit_to_app",priority:2e4}))}onUpdateXR(s){this.isActiveWebXR&&this._spatialGrabRaycaster&&(this._spatialGrabRaycaster.enabled=this.useSpatialGrab)}onLeaveXR(s){var t,i;if((t=this._exitXRMenuButton)==null||t.remove(),!!this.isActiveWebXR){Kt.Global.Set(this._previousXRState),(i=this._playerSync)==null||i.destroyInstance();for(const n of this._createdComponentsInSession)n.destroy();this._createdComponentsInSession.length=0,this.handleOfferSession(),Jl(1).then(()=>Ol.activeWebXRComponent=null)}}setDefaultMovementEnabled(s){let t=this.gameObject.getComponent(Di);return!t&&s&&(t=this.gameObject.addComponent(Di),this._createdComponentsInSession.push(t)),t&&(t.enabled=s),t}setDefaultControllerRenderingEnabled(s){let t=this.gameObject.getComponent(ln);return!t&&s&&(t=this.gameObject.addComponent(ln),this._createdComponentsInSession.push(t),t.createControllerModel=this.showControllerModels,t.createHandModel==this.showHandModels),t&&(t.enabled=s),t}async createLocalAvatar(s){this._playerSync&&s.running&&typeof this.defaultAvatar!="boolean"&&(this._playerSync.asset=this.defaultAvatar,await this._playerSync.getInstance())}getButtonsContainer(){return this.getButtonsFactory()}getButtonsFactory(){return this._buttonFactory||(this._buttonFactory=Kr.getOrCreate()),this._buttonFactory}handleCreatingHTML(){if(this.createARButton||this.createVRButton||this.useQuicklookExport){if((X.isiOS()&&X.isSafari()||iE)&&this.useQuicklookExport){const s=P.findObjectOfType(Ge);if(!s||s&&s.allowCreateQuicklookButton){const t=this.getButtonsFactory().createQuicklookButton();this.addButton(t,50)}}if(this.createARButton){const s=this.getButtonsFactory().createARButton();this.addButton(s,50)}if(this.createVRButton){const s=this.getButtonsFactory().createVRButton();this.addButton(s,50)}}if(this.createSendToQuestButton&&!X.isQuest()&&J.isVRSupported().then(s=>{if(!s){const t=this.getButtonsFactory().createSendToQuestButton();this.addButton(t,50)}}),this.createQRCode){const s=Zd(an);if(s&&s.createQRCodeButton===!1)F()&&console.warn("WebXR: QRCode button is disabled in the Needle Menu component");else if(!X.isMobileDevice()){const t=Tn.getOrCreate().createQRCode();this.addButton(t,50)}}}addButton(s,t){this._buttons.push(s),s.setAttribute("priority",t.toString()),this.context.menu.appendChild(s)}removeButtons(){for(const s of this._buttons)s.remove();this._buttons.length=0}},a(A0,"activeWebXRComponent",null),A0);let tt=Ol;St([m()],tt.prototype,"createVRButton",2),St([m()],tt.prototype,"createARButton",2),St([m()],tt.prototype,"createSendToQuestButton",2),St([m()],tt.prototype,"createQRCode",2),St([m()],tt.prototype,"useDefaultControls",2),St([m()],tt.prototype,"showControllerModels",2),St([m()],tt.prototype,"showHandModels",2),St([m()],tt.prototype,"usePlacementReticle",2),St([m(ae)],tt.prototype,"customARPlacementReticle",2),St([m()],tt.prototype,"usePlacementAdjustment",2),St([m()],tt.prototype,"arScale",2),St([m()],tt.prototype,"useXRAnchor",2),St([m()],tt.prototype,"autoPlace",2),St([m()],tt.prototype,"autoCenter",2),St([m()],tt.prototype,"useQuicklookExport",2),St([m()],tt.prototype,"useDepthSensing",2),St([m()],tt.prototype,"useSpatialGrab",2),St([m(ae)],tt.prototype,"defaultAvatar",2);const xh=O("debugusdz");function sE(s,t){var i;const n=[],o=P.getComponentsInChildren(s,kt),r=P.getComponentsInChildren(s,Wt),l=new Array,c=new Array;if(t.injectImplicitBehaviours)for(const h of o){if(!h||!h.runtimeAnimatorController||!h.enabled)continue;const d=h.runtimeAnimatorController.activeState;if(!d||!d.motion||!d.motion.clip||((i=d.motion.clip.tracks)==null?void 0:i.length)<1||l.includes(h))continue;const u=new Xr;u.animator=h,u.stateName=d.name,u.trigger="start",u.name="PlayAnimationOnClick_implicitAtStart_"+u.stateName;const p=new I;P.addComponent(p,u),c.push(p),l.push(h),s.add(p)}else for(const h of o){if(!h||!h.runtimeAnimatorController||!h.enabled)continue;xh&&console.log(h);const d=[];for(const u of h.runtimeAnimatorController.enumerateActions()){xh&&console.log(u);const p=u.getClip();d.includes(p)||d.push(p)}n.push({root:h.gameObject,clips:d})}if(t.injectImplicitBehaviours)for(const h of r){if(!h||!h.clip||!h.enabled||!h.playAutomatically||l.includes(h))continue;const d=new Xr;d.animation=h,d.stateName=h.clip.name,d.trigger="start",d.name="PlayAnimationOnClick_implicitAtStart_"+d.stateName;const u=new I;P.addComponent(u,d),c.push(u),l.push(h),s.add(u)}else for(const h of r){xh&&console.log(h);const d=[];for(const u of h.animations)d.includes(u)||d.push(u);n.push({root:h.gameObject,clips:d})}xh&&n?.length>0&&console.log("USDZ Animation Clips without behaviours",n);for(const h of n)for(const d of h.clips)t.registerAnimation(h.root,d);return c}function nE(s,t){const i=P.getComponentsInChildren(s,We),n=P.getComponentsInChildren(s,Bo),o=new Array,r=new Array;xh&&console.log({audioSources:i,playAudioOnClicks:n});for(const l of n){if(!l.target)continue;const c=i.indexOf(l.target);c>-1&&i.splice(c,1)}for(const l of i){if(!l||!l.clip||l.volume<=0||o.includes(l))continue;const c=new Bo;c.target=l,c.name="PlayAudioOnClick_implicitAtStart_",c.trigger="start";const h=new I;P.addComponent(h,c),console.log("implicit PlayAudioOnStart",h,c),r.push(h),o.push(l),s.add(h)}return r}function oE(s){return new Tt("DisableAtStart",wt.sceneStartTrigger(),fe.fadeAction(s,0,!1))}function t1(s,t){const i=s.domElement.shadowRoot.querySelector("link[rel='ar']");if(i)return i;const n=document.createElement("div");n.classList.add("menu"),n.classList.add("quicklook-menu"),n.style.display="none",n.style.visibility="hidden";const o=document.createElement("button");o.id="open-in-ar",t?(o.innerText="View in AR",o.title="View this scene in AR. The scene will be exported to USDZ and opened with Apple's QuickLook."):(o.innerText="View in AR",o.title="Download this scene for AR. Open the downloaded USDZ file to view it in AR using Apple's QuickLook."),n.appendChild(o);const r=document.createElement("a");r.id="needle-usdz-link",r.style.display="none",r.rel="ar",r.href="",r.target="_blank",n.appendChild(r);const l=document.createElement("img");return l.id="button",r.appendChild(l),s.domElement.shadowRoot.appendChild(n),r}var rE=Object.defineProperty,aE=Object.getOwnPropertyDescriptor,It=(s,t,i,n)=>{for(var o=n>1?void 0:n?aE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&rE(t,i,o),o};const Bi=O("debugusdz"),lE=O("debugusdzpruning");class Go{constructor(){a(this,"callToAction"),a(this,"checkoutTitle"),a(this,"checkoutSubtitle"),a(this,"callToActionURL")}}It([m()],Go.prototype,"callToAction",2),It([m()],Go.prototype,"checkoutTitle",2),It([m()],Go.prototype,"checkoutSubtitle",2),It([m()],Go.prototype,"callToActionURL",2);var Cp;const I0=(Cp=class extends A{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",s=>{s.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 V),a(this,"_rootScaleBeforeExport",new x)}start(){var s,t,i;Bi&&(console.log("USDZExporter",this),console.log("Debug USDZ Mode. Press 'T' to export"),window.addEventListener("keydown",n=>{switch(n.key){case"t":this.exportAndOpen();break}})),this.objectToExport||(this.objectToExport=this.gameObject),!((t=(s=this.objectToExport)==null?void 0:s.children)!=null&&t.length)&&!((i=this.objectToExport)!=null&&i.isMesh)&&(this.objectToExport=this.context.scene)}onEnable(){var s;const t=X.supportsQuickLookAR(),i=X.isiOS()||X.isiPad();!this.button&&(Bi||t||i)&&(this.allowCreateQuicklookButton&&(this.button=this.createQuicklookButton()),this.lastCallback=this.quicklookCallback.bind(this),this.link=t1(this.context,t),this.link.addEventListener("message",this.lastCallback)),Bi&&De("USDZ Exporter enabled: "+this.name),(s=document.getElementById("open-in-ar"))==null||s.addEventListener("click",this.onClickedOpenInARElement),gc.registerExporter(this)}onDisable(){var s,t,i;(s=this.button)==null||s.remove(),(t=this.link)==null||t.removeEventListener("message",this.lastCallback),Bi&&De("USDZ Exporter disabled: "+this.name),(i=document.getElementById("open-in-ar"))==null||i.removeEventListener("click",this.onClickedOpenInARElement),gc.unregisterExporter(this)}async exportAsync(){return this.exportAndOpen()}async exportAndOpen(){var s;let t=this.exportFileName??((s=this.objectToExport)==null?void 0:s.name)??this.name;if(t+="-"+yx(),_o()||(t!==""&&(t+="-"),t+="MadeWithNeedle"),this.link||(this.link=t1(this.context,X.supportsQuickLookAR())),this.customUsdzFile)return Bi&&console.log("Exporting custom usdz",this.customUsdzFile),this.openInQuickLook(this.customUsdzFile,t),null;if(!this.objectToExport)return console.warn("No object to export",this),null;const i=await this.export(this.objectToExport);return i?(Bi&&console.log("USDZ generation done. Downloading as "+t),this.openInQuickLook(i,t),i):(console.error("USDZ generation failed. Please report a bug",this),null)}async export(s){if(!s)return console.warn("No object to export"),null;const t=this._currentExportTasks.get(s);if(t)return t;const i=this.internalExport(s);return i instanceof Promise?(this._currentExportTasks.set(s,i),i.then(n=>(this._currentExportTasks.delete(s),n)).catch(n=>(this._currentExportTasks.delete(s),console.error("Error during USDZ export \u2013 please report a bug!",n),null))):i}async internalExport(s){ce.start("export-usdz",{onProgress:C=>{this.dispatchEvent(new CustomEvent("export-progress",{detail:{progress:C}}))}}),ce.report("export-usdz",{message:"Starting export",totalSteps:40,currentStep:0}),ce.report("export-usdz",{message:"Load progressive textures",autoStep:5}),ce.start("export-usdz-textures","export-usdz");const t=P.getComponentsInChildren(s,fi);for(const C of t)C&&C.enabled&&C.updateSprite(!0);const i=P.getComponentsInChildren(s,et),n=new Array;let o=0;for(const C of i){for(const R of C.sharedMeshes)if(R){const M=it.assignMeshLOD(R,0);M instanceof Promise&&n.push(new Promise((T,j)=>{M.then(()=>{o++,ce.report("export-usdz-textures",{message:"Loaded progressive mesh",currentStep:o,totalSteps:n.length}),T()}).catch(D=>j(D))}))}for(const R of C.sharedMaterials)if(R){const M=it.assignTextureLOD(R,0);M instanceof Promise&&n.push(new Promise((T,j)=>{M.then(()=>{o++,ce.report("export-usdz-textures",{message:"Loaded progressive texture",currentStep:o,totalSteps:n.length}),T()}).catch(D=>j(D))}))}}Bi&&De("Progressive Loading: "+n.length),await Promise.all(n),Bi&&De("Progressive Loading: done"),ce.end("export-usdz-textures");const r=Kt.Global.Mask;Kt.Global.Set(Zs.AR);const l=new xx,c=new lh(this.quickLookCompatible);let h;const d=[];this.interactive&&(d.push(new up),d.push(new dr),globalThis.false&&P.getComponentsInChildren(s,ve).length>0&&(this.physics?(h=new mp,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 fh),d.push(new vp));const u=[c,...d,...this.extensions],p={self:this,exporter:l,extensions:u,object:s};ce.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,ce.report("export-usdz","auto export animations and audio sources");const g=new Array;this.autoExportAnimations&&g.push(...sE(s,c)),u.find(C=>C.extensionName==="Audio")&&this.autoExportAudioSources&&g.push(...nE(s)),l.debug=Bi,l.pruneUnusedNodes=!lE;const y=Hr.instance.objs.map(C=>C.batchedMesh);l.keepObject=C=>{let R=!0;const M=P.getComponent(C,et);return M&&!M.enabled&&(R=!1),R&&y.includes(C)&&(R=!1),R&&P.getComponentInParent(C,ks)&&(R=!1),R&&P.getComponentInParent(C,Hs)&&(R=!1),Bi&&!R&&console.log("USDZExporter: Discarding object",C),R},l.beforeWritingDocument=()=>{if(F()&&c&&h){const C=c.animatedRoots;for(const R of C){const M=P.getComponentsInChildren(R,ve).filter(j=>j.enabled),T=P.getComponents(R,pi).filter(j=>j.enabled&&!j.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.",R)}}};const f=new Array;this.objectToExport&&this.quickLookCompatible&&this.interactive&&this.objectToExport.traverse(C=>{C.visible||f.push(C)});const v=u.find(C=>C.extensionName==="Behaviour");this.interactive&&v&&f.length>0&&v.addBehavior(oE(f));let b=!0;this.quickLookCompatible&&!this.interactive&&(b=!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"),ce.report("export-usdz","Invoking exporter.parse");const w=await l.parse(this.objectToExport,{ar:{anchoring:{type:this.anchoringType},planeAnchoring:{alignment:this.planeAnchoringAlignment}},extensions:u,quickLookCompatible:this.quickLookCompatible,maxTextureSize:this.maxTextureSize,exportInvisible:b}),_=new Blob([w],{type:"model/vnd.usdz+zip"});this.revertWebARSessionRoot(),this.context.time.timeScale=this._previousTimeScale,ce.report("export-usdz","Invoking after-export"),this.dispatchEvent(new CustomEvent("after-export",{detail:p}));for(const C of g)P.destroy(C);return Kt.Global.Set(r),ce.end("export-usdz"),_}openInQuickLook(s,t){const i=s instanceof Blob?URL.createObjectURL(s):s,n=this.buildQuicklookOverlay();Bi&&console.log("QuickLook Overlay",n);const o=n.callToAction?encodeURIComponent(n.callToAction):"",r=n.checkoutTitle?encodeURIComponent(n.checkoutTitle):"",l=n.checkoutSubtitle?encodeURIComponent(n.checkoutSubtitle):"";this.link.href=i+`#callToAction=${o}&checkoutTitle=${r}&checkoutSubtitle=${l}&callToActionURL=${n.callToActionURL}`,this.lastCallback||(this.lastCallback=this.quicklookCallback.bind(this),this.link.addEventListener("message",this.lastCallback)),this.link.download=t+".usdz",this.link.click()}download(s,t){I0.save(s,t)}static save(s,t){const i=document.createElement("a");i.style.display="none",document.body.appendChild(i),typeof s=="string"?i.href=s:i.href=URL.createObjectURL(s),i.download=t,i.click(),i.remove()}quicklookCallback(s){if(s?.data=="_apple_ar_quicklook_button_tapped"){Bi&&xe("Quicklook closed via call to action button");var t=new CustomEvent("quicklook-button-tapped",{detail:this});if(this.dispatchEvent(t),!t.defaultPrevented){const i=new URLSearchParams(this.link.href);if(i){const n=i.get("callToActionURL");Bi&&De("Quicklook url: "+n),n&&(_o()?globalThis.open(n,"_blank"):console.warn("Quicklook closed: custom redirects require a Needle Engine Pro license: https://needle.tools/pricing",n))}}}}buildQuicklookOverlay(){var s,t,i,n,o,r;const l={};return this.customBranding&&Object.assign(l,this.customBranding),_o()||(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="_"),(((s=l.callToAction)==null?void 0:s.length)||((t=l.checkoutTitle)==null?void 0:t.length)||((i=l.checkoutSubtitle)==null?void 0:i.length))&&((n=l.callToAction)!=null&&n.length||(l.callToAction="\0"),(o=l.checkoutTitle)!=null&&o.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 s=P.findObjectOfType(tt);let t=P.getComponentInParent(this.objectToExport,Hn);t||(t=P.getComponentInChildren(this.objectToExport,Hn));let i=1,n=!1;const o=this.objectToExport;return s?i=s.arScale:t&&(i=t.arScale,n=t.invertForward),{scale:1/i,_invertForward:n,target:o,sessionRoot:t?.gameObject??null}}applyWebARSessionRoot(){if(!this.objectToExport)return;const{scale:s,_invertForward:t,target:i,sessionRoot:n}=this.getARScaleAndTarget(),o=n?.matrixWorld.clone().invert();this._rootSessionRootWasAppliedTo=i,this._rootPositionBeforeExport.copy(i.position),this._rootRotationBeforeExport.copy(i.quaternion),this._rootScaleBeforeExport.copy(i.scale),i.scale.multiplyScalar(s),t&&i.quaternion.multiply(I0.invertForwardQuaternion),i.updateMatrix(),i.updateMatrixWorld(!0),n&&o&&i.matrix.premultiply(o)}revertWebARSessionRoot(){if(!this.objectToExport||!this._rootSessionRootWasAppliedTo)return;const s=this._rootSessionRootWasAppliedTo;s.position.copy(this._rootPositionBeforeExport),s.quaternion.copy(this._rootRotationBeforeExport),s.scale.copy(this._rootScaleBeforeExport),s.updateMatrix(),s.updateMatrixWorld(!0),this._rootSessionRootWasAppliedTo=null}createQuicklookButton(){const s=Kr.getOrCreate().createQuicklookButton();return s.parentNode||this.context.menu.appendChild(s),s}},a(Cp,"invertForwardMatrix",new ne().makeRotationY(Math.PI)),a(Cp,"invertForwardQuaternion",new V().setFromEuler(new Ut(0,Math.PI,0))),Cp);let Ge=I0;It([m(I)],Ge.prototype,"objectToExport",2),It([m()],Ge.prototype,"autoExportAnimations",2),It([m()],Ge.prototype,"autoExportAudioSources",2),It([m()],Ge.prototype,"exportFileName",2),It([m(URL)],Ge.prototype,"customUsdzFile",2),It([m(Go)],Ge.prototype,"customBranding",2),It([m()],Ge.prototype,"anchoringType",2),It([m()],Ge.prototype,"maxTextureSize",2),It([m()],Ge.prototype,"planeAnchoringAlignment",2),It([m()],Ge.prototype,"interactive",2),It([m()],Ge.prototype,"physics",2),It([m()],Ge.prototype,"allowCreateQuicklookButton",2),It([m()],Ge.prototype,"quickLookCompatible",2);var cE=Object.defineProperty,hE=Object.getOwnPropertyDescriptor,j0=(s,t,i,n)=>{for(var o=n>1?void 0:n?hE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&cE(t,i,o),o};class Pl extends A{constructor(){super(...arguments),a(this,"_fog")}get fog(){return this._fog||(this._fog=new $y(0,0,50)),this._fog}get mode(){return 1}set near(t){this.fog.near=t}get near(){return this.fog.near}set far(t){this.fog.far=t}get far(){return this.fog.far}set color(t){this.fog.color.copy(t)}get color(){return this.fog.color}onEnable(){this.scene.fog=this.fog}onDisable(){this.scene.fog===this._fog&&(this.scene.fog=null)}}j0([m()],Pl.prototype,"near",1),j0([m()],Pl.prototype,"far",1),j0([m(re)],Pl.prototype,"color",1);var dE=Object.defineProperty,uE=Object.getOwnPropertyDescriptor,L0=(s,t,i,n)=>{for(var o=n>1?void 0:n?uE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&dE(t,i,o),o};class Zr extends A{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&&!Sc||(this._gizmoObject||(this.objectBounds?this._gizmoObject=new cC(this.gameObject,this.color??16776960):(this.objectBounds=!1,this._gizmoObject=_g(this.color??16776960))),this.objectBounds?(this.scene.add(this._gizmoObject),this._boxHelper=this._gizmoObject,this.startCoroutine(this.syncObjectBounds(),Me.OnBeforeRender)):this.gameObject.add(this._gizmoObject))}onDisable(){this._gizmoObject&&this.gameObject.remove(this._gizmoObject)}*syncObjectBounds(){for(var t;this._boxHelper;)(t=this._boxHelper)==null||t.update(),yield}}L0([m()],Zr.prototype,"objectBounds",2),L0([m(re)],Zr.prototype,"color",2),L0([m()],Zr.prototype,"isGizmo",2);var pE=Object.defineProperty,mE=Object.getOwnPropertyDescriptor,D0=(s,t,i,n)=>{for(var o=n>1?void 0:n?mE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&pE(t,i,o),o};class kl extends A{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&&!Sc)return;const t=this.size,i=this.divisions;this.gridHelper||(this.gridHelper=new cm(t,i,this.color0??new re(.4,.4,.4),this.color1??new re(.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)}}D0([m()],kl.prototype,"isGizmo",2),D0([m(re)],kl.prototype,"color0",2),D0([m(re)],kl.prototype,"color1",2);var gE=Object.defineProperty,fE=Object.getOwnPropertyDescriptor,B0=(s,t,i,n)=>{for(var o=n>1?void 0:n?fE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&gE(t,i,o),o};class F0 extends A{constructor(){super(...arguments),a(this,"connectedBody"),a(this,"_rigidBody",null)}get rigidBody(){return this._rigidBody}onEnable(){this._rigidBody||(this._rigidBody=this.gameObject.getComponent(ve)),this.rigidBody&&this.connectedBody&&this.startCoroutine(this.create())}*create(){yield,this.rigidBody&&this.connectedBody&&this.activeAndEnabled&&this.createJoint(this.rigidBody,this.connectedBody)}}B0([m(ve)],F0.prototype,"connectedBody",2);class z0 extends F0{createJoint(t,i){var n;(n=this.context.physics.engine)==null||n.addFixedJoint(t,i)}}class Sh extends F0{constructor(){super(...arguments),a(this,"anchor"),a(this,"axis")}createJoint(t,i){var n;this.axis&&this.anchor&&((n=this.context.physics.engine)==null||n.addHingeJoint(t,i,this.anchor,this.axis))}}B0([m(x)],Sh.prototype,"anchor",2),B0([m(x)],Sh.prototype,"axis",2);var yE=Object.defineProperty,vE=Object.getOwnPropertyDescriptor,cn=(s,t,i,n)=>{for(var o=n>1?void 0:n?vE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&yE(t,i,o),o};function U0(s){return s*Math.PI/180}const i1=300,Xo=O("debuglights");class yi extends A{constructor(){super(...arguments),a(this,"type",0),a(this,"range",1),a(this,"spotAngle",1),a(this,"innerSpotAngle",1),a(this,"_color",new re(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(t){this._color=t,this.light!==void 0&&(this.light.color=t)}get color(){return this.light?this.light.color:this._color}set shadowNearPlane(t){var i,n;if(t!==this._shadowNearPlane&&(this._shadowNearPlane=t,((n=(i=this.light)==null?void 0:i.shadow)==null?void 0:n.camera)!==void 0)){const o=this.light.shadow.camera;o.near=t}}get shadowNearPlane(){return this._shadowNearPlane}set shadowBias(t){var i,n;t!==this._shadowBias&&(this._shadowBias=t,((n=(i=this.light)==null?void 0:i.shadow)==null?void 0:n.bias)!==void 0&&(this.light.shadow.bias=t,this.light.shadow.needsUpdate=!0))}get shadowBias(){return this._shadowBias}set shadowNormalBias(t){var i,n;t!==this._shadowNormalBias&&(this._shadowNormalBias=t,((n=(i=this.light)==null?void 0:i.shadow)==null?void 0:n.normalBias)!==void 0&&(this.light.shadow.normalBias=t,this.light.shadow.needsUpdate=!0))}get shadowNormalBias(){return this._shadowNormalBias}set shadows(t){this._shadows=t,this.light&&(this.light.castShadow=t!==0,this.updateShadowSoftHard())}get shadows(){return this._shadows}set intensity(t){var i;if(this._intensity=t,this.light){let n=1;if(this.context.isInXR&&this._webARRoot){const o=(i=this._webARRoot)==null?void 0:i.arScale;typeof o=="number"&&o>0&&(n/=o)}this.light.intensity=t*n}Xo&&console.log("Set light intensity to "+this._intensity,t,this)}get intensity(){return this._intensity}get shadowDistance(){const t=this.light;return t!=null&&t.shadow?t.shadow.camera.far:-1}set shadowDistance(t){this._shadowDistance=t;const i=this.light;if(i!=null&&i.shadow){const n=i.shadow.camera;n.far=t,n.updateProjectionMatrix()}}get shadowResolution(){const t=this.light;return t!=null&&t.shadow?t.shadow.mapSize.x:-1}set shadowResolution(t){if(t===this._shadowResolution)return;this._shadowResolution=t;const i=this.light;i!=null&&i.shadow&&(i.shadow.mapSize.set(t,t),i.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(t){return this.light?this.type===1?this.light.getWorldPosition(t).multiplyScalar(1):this.light.getWorldPosition(t):t}awake(){this.color=new re(this.color??16777215),Xo&&console.log(this.name,this)}onEnable(){Xo&&console.log("ENABLE LIGHT",this.name),this.createLight(),!this.isBaked&&(this.light&&(this.light.visible=!0,this.light.intensity=this._intensity,Xo&&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(),Me.LateUpdate))}onDisable(){Xo&&console.log("DISABLE LIGHT",this.name),this.light&&(this.selfIsLight?this.light.intensity=0:this.light.visible=!1)}onEnterXR(t){this._webARRoot=P.getComponentInParent(this.gameObject,Hn)??void 0}onLeaveXR(t){}createLight(){const t=this.selfIsLight;if(t&&!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 i=new hm(this.color,this.intensity*Math.PI);if(i.position.set(0,0,-i1*.5).applyQuaternion(this.gameObject.quaternion),this.gameObject.add(i.target),yr(i.target,0,0,0),this.light=i,this.gameObject.position.set(0,0,0),this.gameObject.rotation.set(0,0,0),Xo){const l=new dC(this.light,.2,this.color);this.context.scene.add(l)}break;case 0:const n=new hC(this.color,this.intensity*Math.PI,this.range,U0(this.spotAngle/2),1-U0(this.innerSpotAngle/2)/U0(this.spotAngle/2),2);n.position.set(0,0,0),n.rotation.set(0,0,0),this.light=n;const o=n.target;n.add(o),o.position.set(0,0,this.range),o.rotation.set(0,0,0);break;case 2:const r=new qy(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),Xo&&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 i=this.light.shadow.camera;if(i.near=this.shadowNearPlane,this._shadowDistance!==void 0&&typeof this._shadowDistance=="number"?i.far=this._shadowDistance:i.far=i1*Math.abs(this.gameObject.scale.z),this.gameObject.scale.set(1,1,1),this.shadowWidth!==void 0)i.left=-this.shadowWidth/2,i.right=this.shadowWidth/2;else{const n=this.gameObject.scale.x;i.left*=n,i.right*=n}if(this.shadowHeight!==void 0)i.top=this.shadowHeight/2,i.bottom=-this.shadowHeight/2;else{const n=this.gameObject.scale.y;i.top*=n,i.bottom*=n}this.light.shadow.needsUpdate=!0,Xo&&this.context.scene.add(new uC(i))}this.isBaked?this.light.removeFromParent():t||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(t){t.add(t.target),t.target.position.set(0,0,-1)}}a(yi,"allowChangingRendererShadowMapType",!0),cn([m()],yi.prototype,"type",2),cn([m(re)],yi.prototype,"color",1),cn([m()],yi.prototype,"shadowNearPlane",1),cn([m()],yi.prototype,"shadowBias",1),cn([m()],yi.prototype,"shadowNormalBias",1),cn([m()],yi.prototype,"shadows",1),cn([m()],yi.prototype,"lightmapBakeType",2),cn([m()],yi.prototype,"intensity",1),cn([m()],yi.prototype,"shadowDistance",1),cn([m()],yi.prototype,"shadowResolution",1),new x(0,0,0);var bE=Object.defineProperty,_E=Object.getOwnPropertyDescriptor,Ch=(s,t,i,n)=>{for(var o=n>1?void 0:n?_E(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&bE(t,i,o),o};const N0=O("debuglods"),wE=O("nolods");class Jr{constructor(){a(this,"screenRelativeTransitionHeight"),a(this,"distance"),a(this,"renderers")}}Ch([m()],Jr.prototype,"screenRelativeTransitionHeight",2),Ch([m()],Jr.prototype,"distance",2),Ch([m(et)],Jr.prototype,"renderers",2);class xE{constructor(t){a(this,"model"),this.model=t}get renderers(){return this.model.renderers}}class Oh extends A{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(N0&&console.log("LODGROUP",this.name,this.lodModels,this),!wE&&!this._lodsHandler&&this.gameObject&&this.lodModels&&Array.isArray(this.lodModels)){const t=[];for(const n of this.lodModels){const o=new xE(n);this._lods.push(o);for(const r of o.renderers)t.includes(r)||t.push(r)}this._lodsHandler=new Array;for(let n=0;n<t.length;n++){const o=new pC;this._lodsHandler.push(o),this.gameObject.add(o)}const i=new I;i.name="Cull "+this.name;for(let n=0;n<t.length;n++){const o=t[n],r=this._lodsHandler[n],l=o.gameObject;N0&&console.log(n,l.name);for(const c of this._lods){const h=c.model.distance;let d=null;if(c.renderers.includes(o)?d=l:d=i,d.type==="Group"){console.warn(`LODGroup ${this.name}: Group or MultiMaterial object's are not supported as LOD object: ${d.name}`);continue}N0&&console.log("LEVEL",d.name,h),r.autoUpdate=!1,this.onAddLodLevel(r,d,c.model.distance)}}}}onAfterRender(){if(!this.gameObject||!this._lodsHandler)return;const t=this.context.mainCamera;if(t)for(const i of this._lodsHandler){i.update(t);const n=i.getCurrentLevel(),o=i.levels[n];i.layers.mask=o.object.layers.mask}}onAddLodLevel(t,i,n){if(i===this.gameObject){console.warn("LODGroup component must be on parent object and not mesh directly at the moment",i.name,i);return}t.addLevel(i,n*this._distanceFactor,.01);const o={lod:t,levelIndex:t.levels.length-1,distance:n};this._settings.push(o)}distanceFactor(t){if(t!==this._distanceFactor){this._distanceFactor=t;for(const i of this._settings){const n=i.lod.levels[i.levelIndex];n.distance=i.distance*t}}}}Ch([m(x)],Oh.prototype,"localReferencePoint",2),Ch([m(Jr)],Oh.prototype,"lodModels",2);var SE=Object.defineProperty,CE=Object.getOwnPropertyDescriptor,OE=(s,t,i,n)=>{for(var o=n>1?void 0:n?CE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&SE(t,i,o),o};const Op=O("debugnestedgltf");class Pp extends A{constructor(){super(...arguments),a(this,"filePath"),a(this,"loadAssetInParent",!0),a(this,"_isLoadingOrDoneLoading",!1)}listenToProgress(t){var i;(i=this.filePath)==null||i.beginListenDownload(t)}preload(){var t;(t=this.filePath)==null||t.preload()}async start(){var t,i,n,o,r;if(this._isLoadingOrDoneLoading)return;Op&&console.log(this,this.guid);const l=this.gameObject.parent;if(l){this._isLoadingOrDoneLoading=!0;const c=new Ds;c.idProvider=new zt(this.hash(this.guid)),c.parent=this.loadAssetInParent!==!1?l:this.gameObject,this.gameObject.updateMatrix();const h=this.gameObject.matrix;Op&&console.log("Load nested:",((t=this.filePath)==null?void 0:t.url)??this.filePath,this.gameObject.position);const d=await((n=(i=this.filePath)==null?void 0:i.instantiate)==null?void 0:n.call(this.filePath,c));Op&&console.log("Nested loaded:",((o=this.filePath)==null?void 0:o.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}}))),Op&&console.log("Nested loading done:",((r=this.filePath)==null?void 0:r.url)??this.filePath,d)}}onDestroy(){var t;(t=this.filePath)==null||t.unload()}hash(t){let i=0;for(let n=0;n<t.length;n++)i=t.charCodeAt(n)+((i<<5)-i);return i}}OE([m(ae)],Pp.prototype,"filePath",2);var PE=Object.defineProperty,kE=Object.getOwnPropertyDescriptor,W0=(s,t,i,n)=>{for(var o=n>1?void 0:n?kE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&PE(t,i,o),o};const ME=O("debugnet"),V0=class extends A{constructor(){super(...arguments),a(this,"url",null),a(this,"urlParameterName",null),a(this,"localhost",null)}awake(){ME&&console.log(this),this.context.connection.registerProvider(this)}getWebsocketUrl(){let s=this.url?V0.GetUrl(this.url,this.localhost):null;if(this.urlParameterName){const i=O(this.urlParameterName);i&&typeof i=="string"&&(s=i)}if(!s)return null;const t=new RegExp("(((https?)|(?<socket_prefix>wss?))://)?(www.)?(?<url>.+)","gm").exec(s);return t!=null&&t.groups?t?.groups.socket_prefix?s:"wss://"+t?.groups.url:null}static GetUrl(s,t){let i=s;const n=V0.IsLocalNetwork()&&t;if(n&&(i=t),s!=null&&s.startsWith("/")){const o=n?i:window.location.origin;o!=null&&o.endsWith("/")&&s.startsWith("/")&&(s=s.substring(1)),i=o+s}return i}static IsLocalNetwork(s=window.location.hostname){return Gt(s)}};let Ml=V0;W0([m()],Ml.prototype,"url",2),W0([m()],Ml.prototype,"urlParameterName",2),W0([m()],Ml.prototype,"localhost",2);var RE=Object.defineProperty,TE=Object.getOwnPropertyDescriptor,kp=(s,t,i,n)=>{for(var o=n>1?void 0:n?TE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&RE(t,i,o),o};class ea extends A{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 t=te(this.from),i=Oe(this.from);this.offset.copy(this.positionOffset);const n=this.offset.length();if(this.referenceSpace&&this.offset.transformDirection(this.referenceSpace.matrixWorld).multiplyScalar(n),t.add(this.offset),this.levelPosition&&this.referenceSpace){const c=new pr(this.gameObject.up,0),h=te(this.referenceSpace);c.setFromNormalAndCoplanarPoint(this.gameObject.up,h);const d=new x(0,0,0);c.projectPoint(t,d),t.copy(d)}this.affectPosition&&dt(this.gameObject,t);const o=new Ut(this.rotationOffset.x,this.rotationOffset.y,this.rotationOffset.z),r=new V().setFromEuler(o);this.affectRotation&&Gi(this.gameObject,i.multiply(r));const l=new x;this.from.getWorldDirection(l).multiplyScalar(50),this.levelLookDirection&&(l.y=0),this.alignLookDirection&&this.gameObject.lookAt(l)}}kp([m(P)],ea.prototype,"referenceSpace",2),kp([m(P)],ea.prototype,"from",2),kp([m(x)],ea.prototype,"positionOffset",2),kp([m(x)],ea.prototype,"rotationOffset",2);var EE=Object.defineProperty,AE=Object.getOwnPropertyDescriptor,k=(s,t,i,n)=>{for(var o=n>1?void 0:n?AE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&EE(t,i,o),o};const Mp=O("debugparticles");var qn=(s=>(s[s.Billboard=0]="Billboard",s[s.Stretch=1]="Stretch",s[s.HorizontalBillboard=2]="HorizontalBillboard",s[s.VerticalBillboard=3]="VerticalBillboard",s[s.Mesh=4]="Mesh",s))(qn||{});class Qo{constructor(){a(this,"alphaKeys",[]),a(this,"colorKeys",[])}get duration(){return 1}evaluate(t,i){let n,o=0,r=null,l=0;for(let c=0;c<this.alphaKeys.length;c++){const h=this.alphaKeys[c];(h.time<t||!n)&&(n=h,o=c)}for(let c=0;c<this.colorKeys.length;c++){const h=this.colorKeys[c];(h.time<t||!r)&&(r=h,l=c)}if(r)if(l+1<this.colorKeys.length){const c=this.colorKeys[l+1],h=W.remap(t,r.time,c.time,0,1);i.r=W.lerp(r.color.r,c.color.r,h),i.g=W.lerp(r.color.g,c.color.g,h),i.b=W.lerp(r.color.b,c.color.b,h)}else i.r=r.color.r,i.g=r.color.g,i.b=r.color.b;if(n)if(o+1<this.alphaKeys.length){const c=this.alphaKeys[o+1],h=W.remap(t,n.time,c.time,0,1);i.alpha=W.lerp(n.alpha,c.alpha,h)}else i.alpha=n.alpha;return i}}k([m()],Qo.prototype,"alphaKeys",2),k([m()],Qo.prototype,"colorKeys",2);var Ph=(s=>(s[s.Local=0]="Local",s[s.World=1]="World",s[s.Custom=2]="Custom",s))(Ph||{}),Rp=(s=>(s[s.Sphere=0]="Sphere",s[s.SphereShell=1]="SphereShell",s[s.Hemisphere=2]="Hemisphere",s[s.HemisphereShell=3]="HemisphereShell",s[s.Cone=4]="Cone",s[s.Box=5]="Box",s[s.Mesh=6]="Mesh",s[s.ConeShell=7]="ConeShell",s[s.ConeVolume=8]="ConeVolume",s[s.ConeVolumeShell=9]="ConeVolumeShell",s[s.Circle=10]="Circle",s[s.CircleEdge=11]="CircleEdge",s[s.SingleSidedEdge=12]="SingleSidedEdge",s[s.MeshRenderer=13]="MeshRenderer",s[s.SkinnedMeshRenderer=14]="SkinnedMeshRenderer",s[s.BoxShell=15]="BoxShell",s[s.BoxEdge=16]="BoxEdge",s[s.Donut=17]="Donut",s[s.Rectangle=18]="Rectangle",s[s.Sprite=19]="Sprite",s[s.SpriteRenderer=20]="SpriteRenderer",s))(Rp||{});const kh=class{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(s){const t=new kh;return t.setConstant(s),t}static betweenTwoConstants(s,t){const i=new kh;return i.setMinMaxConstant(s,t),i}static curve(s,t=1){const i=new kh;return i.setCurve(s,t),i}setConstant(s){this.mode=0,this.constant=s}setMinMaxConstant(s,t){this.mode=3,this.constantMin=s,this.constantMax=t}setCurve(s,t=1){this.mode=1,this.curve=s,this.curveMultiplier=t}clone(){var s,t,i;const n=new kh;return n.mode=this.mode,n.constant=this.constant,n.constantMin=this.constantMin,n.constantMax=this.constantMax,n.curve=(s=this.curve)==null?void 0:s.clone(),n.curveMin=(t=this.curveMin)==null?void 0:t.clone(),n.curveMax=(i=this.curveMax)==null?void 0:i.clone(),n.curveMultiplier=this.curveMultiplier,n}evaluate(s,t){const i=t===void 0?Math.random():t;switch(this.mode){case 0:case"Constant":return this.constant;case 1:case"Curve":return s=W.clamp01(s),this.curve.evaluate(s)*this.curveMultiplier;case 2:case"TwoCurves":const n=s*this.curveMin.duration,o=s*this.curveMax.duration;return W.lerp(this.curveMin.evaluate(n),this.curveMax.evaluate(o),i%1)*this.curveMultiplier;case 3:case"TwoConstants":return W.lerp(this.constantMin,this.constantMax,i%1);default:this.curveMax.evaluate(s)*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(s){if(!s)return 0;let t=Number.MIN_VALUE;for(let i=0;i<s.keys.length;i++){const n=s.keys[i];n.value>t&&(t=n.value)}return t}};let Q=kh;k([m()],Q.prototype,"mode",2),k([m()],Q.prototype,"constant",2),k([m()],Q.prototype,"constantMin",2),k([m()],Q.prototype,"constantMax",2),k([m(Dr)],Q.prototype,"curve",2),k([m(Dr)],Q.prototype,"curveMin",2),k([m(Dr)],Q.prototype,"curveMax",2),k([m()],Q.prototype,"curveMultiplier",2);var Tp;const jt=(Tp=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(s){const t=new jt;return t.constant(s),t}static betweenTwoColors(s,t){const i=new jt;return i.betweenTwoColors(s,t),i}constant(s){return this.mode=0,this.color=s,this}betweenTwoColors(s,t){return this.mode=2,this.colorMin=s,this.colorMax=t,this}evaluate(s,t){const i=t===void 0?Math.random():t;switch(this.mode){case 0:case"Color":return this.color;case 1:case"Gradient":return this.gradient.evaluate(s,jt._temp),jt._temp;case 2:case"TwoColors":return jt._temp.lerpColors(this.colorMin,this.colorMax,i);case 3:case"TwoGradients":return this.gradientMin.evaluate(s,jt._temp),this.gradientMax.evaluate(s,jt._temp2),jt._temp.lerp(jt._temp2,i);case 4:case"RandomColor":const n=Math.random();return this.gradientMin.evaluate(s,jt._temp),this.gradientMax.evaluate(s,jt._temp2),jt._temp.lerp(jt._temp2,n)}return jt._temp.set(16777215),jt._temp.alpha=1,jt._temp}},a(Tp,"_temp",new Se(0,0,0,1)),a(Tp,"_temp2",new Se(0,0,0,1)),Tp);let si=jt;k([m()],si.prototype,"mode",2),k([m(Se)],si.prototype,"color",2),k([m(Se)],si.prototype,"colorMin",2),k([m(Se)],si.prototype,"colorMax",2),k([m(Qo)],si.prototype,"gradient",2),k([m(Qo)],si.prototype,"gradientMin",2),k([m(Qo)],si.prototype,"gradientMax",2);var H0=(s=>(s[s.Hierarchy=0]="Hierarchy",s[s.Local=1]="Local",s[s.Shape=2]="Shape",s))(H0||{});class Lt{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")}}k([m(Q)],Lt.prototype,"gravityModifier",2),k([m(si)],Lt.prototype,"startColor",2),k([m(Q)],Lt.prototype,"startDelay",2),k([m(Q)],Lt.prototype,"startLifetime",2),k([m(Q)],Lt.prototype,"startRotation",2),k([m(Q)],Lt.prototype,"startRotationX",2),k([m(Q)],Lt.prototype,"startRotationY",2),k([m(Q)],Lt.prototype,"startRotationZ",2),k([m(Q)],Lt.prototype,"startSize",2),k([m(Q)],Lt.prototype,"startSizeX",2),k([m(Q)],Lt.prototype,"startSizeY",2),k([m(Q)],Lt.prototype,"startSizeZ",2),k([m(Q)],Lt.prototype,"startSpeed",2);class Mh{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(t){if(t<=this.time)return 0;let i=0;if(this.cycleCount===0||this._performed<this.cycleCount){const n=this.time+this.repeatInterval*this._performed;if(t>=n&&(this._performed+=1,Math.random()<this.probability))switch(this.count.mode){case 0:i=this.count.constant;break;case 3:i=W.lerp(this.count.constantMin,this.count.constantMax,Math.random());break;case 1:i=this.count.curve.evaluate(Math.random());break;case 2:const o=Math.random();i=W.lerp(this.count.curveMin.evaluate(o),this.count.curveMax.evaluate(o),Math.random());break}}return i}}class hn{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 t;return((t=this.bursts)==null?void 0:t.length)??0}reset(){var t;(t=this.bursts)==null||t.forEach(i=>i.reset())}getBurst(){let t=0;if(this.burstCount>0)for(let i=0;i<this.burstCount;i++){const n=this.bursts[i];this.system.main.loop&&n.time>=this.system.time&&n.reset(),t+=Math.round(n.run(this.system.time))}return t}}k([m()],hn.prototype,"enabled",2),k([m()],hn.prototype,"bursts",2),k([m(Q)],hn.prototype,"rateOverTime",2),k([m()],hn.prototype,"rateOverTimeMultiplier",2),k([m(Q)],hn.prototype,"rateOverDistance",2),k([m()],hn.prototype,"rateOverDistanceMultiplier",2);class Rh{constructor(){a(this,"enabled"),a(this,"color")}}k([m(si)],Rh.prototype,"color",2);class Yo{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(t,i,n){if(i||(i=this._temp),!this.enabled)return i.x=i.y=i.z=1,i;if(this.separateAxes)i.x=this.x.evaluate(t,n)*this.xMultiplier,i.y=this.y.evaluate(t,n)*this.yMultiplier,i.z=this.z.evaluate(t,n)*this.zMultiplier;else{const o=this.size.evaluate(t,n)*this.sizeMultiplier;i.x=o}return i}}k([m(Q)],Yo.prototype,"size",2),k([m(Q)],Yo.prototype,"x",2),k([m(Q)],Yo.prototype,"y",2),k([m(Q)],Yo.prototype,"z",2);var Ep;const Th=(Ep=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 Ut),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 ne),a(this,"_worldSpaceMatrixInverse",new ne),a(this,"_vector",new x(0,0,0)),a(this,"_temp",new x(0,0,0)),a(this,"_triangle",new mC),a(this,"_dir",new x),a(this,"_loopTime",0),a(this,"_loopDirection",1),Mp&&console.log(this)}get type(){return Rp[this.shapeType]}initialize(s){this.onInitialize(s),s.position.x=this._vector.x,s.position.y=this._vector.y,s.position.z=this._vector.z}toJSON(){return this}clone(){return new Th}setMesh(s){this.meshRenderer=s,s?(this._meshObj=s.sharedMeshes[Math.floor(Math.random()*s.sharedMeshes.length)],this._meshGeometry=this._meshObj.geometry):(this._meshObj=void 0,this._meshGeometry=void 0)}update(s,t){}onUpdate(s,t,i,n){this.system=s,this._space=i,i===1&&(this._worldSpaceMatrix.copy(n.matrixWorld),this._worldSpaceMatrix.elements[0]=1,this._worldSpaceMatrix.elements[5]=1,this._worldSpaceMatrix.elements[10]=1,this._worldSpaceMatrixInverse.copy(this._worldSpaceMatrix).invert())}applyRotation(s){const t=this.rotation.x!==0||this.rotation.y!==0||this.rotation.z!==0;return t&&(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",s.applyEuler(this._rotation)),t}onInitialize(s){this._vector.set(0,0,0),s.mesh=void 0,s.mesh_geometry=void 0;const t=this._temp.copy(this.position),i=this._space===1;i&&t.applyQuaternion(this.system.worldQuaternion);let n=this.radius;if(i&&(n*=this.system.worldScale.x),this.enabled){switch(this.shapeType){case 5:Mp&&q.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(t);break;case 4:this.randomConePoint(this.position,this.angle,n,this.radiusThickness,this.arc,this.arcMode,this._vector);break;case 0:this.randomSpherePoint(this.position,n,this.radiusThickness,this.arc,this._vector);break;case 10:this.randomCirclePoint(this.position,n,this.radiusThickness,this.arc,this._vector);break;case 13:const o=this.meshRenderer;o?.destroyed==!1&&this.setMesh(o);const r=s.mesh=this._meshObj,l=s.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),s.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,y=u*3+2;p=c.getX(p),g=c.getX(g),y=c.getX(y);const f=l.getAttribute("position");this._triangle.a.fromBufferAttribute(f,p),this._triangle.b.fromBufferAttribute(f,g),this._triangle.c.fromBufferAttribute(f,y),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),s.mesh_normal=u}}break}break;default:this._vector.set(0,0,0),F()&&!globalThis.__particlesystem_shapetype_unsupported&&(console.warn("ParticleSystem ShapeType is not supported:",Rp[this.shapeType]),globalThis.__particlesystem_shapetype_unsupported=!0);break}this.randomizePosition(this._vector,this.randomPositionAmount)}this.applyRotation(this._vector),i&&(this._vector.applyQuaternion(this.system.worldQuaternion),this._vector.add(this.system.worldPos)),Mp&&q.DrawSphere(this._vector,.03,16711680,.5,!0)}getDirection(s,t){var i;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 n=t.x,o=t.y,r=t.z;this._dir.set(n,o,r),(i=this.system)!=null&&i.worldspace?this._dir.sub(this.system.worldPos):this._dir.sub(this.position);break;case 13:const l=s.mesh,c=s.mesh_geometry;if(l&&c)switch(this.meshShapeType){case 0:{const h=c.getAttribute("normal"),d=s.mesh_normal;this._dir.fromBufferAttribute(h,d)}break;case 1:break;case 2:{const h=c.index;if(h){const d=s.mesh_normal,u=h.getX(d*3),p=h.getX(d*3+1),g=h.getX(d*3+2),y=c.getAttribute("position"),f=G(),v=G(),b=G();f.fromBufferAttribute(y,u),v.fromBufferAttribute(y,p),b.fromBufferAttribute(y,g),f.sub(v),b.sub(v),f.cross(b),this._dir.copy(f).multiplyScalar(-1);const w=Oe(l);this._dir.applyQuaternion(w)}}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),Mp&&(q.DrawSphere(t,.01,8925952,.5,!0),q.DrawDirection(t,this._dir,8925952,.5,!0)),this._dir}randomizePosition(s,t){if(t<=0)return;const i=Th._tempVec;i.set(Math.random()*2-1,Math.random()*2-1,Math.random()*2-1),i.x*=t*this.scale.x,i.y*=t*this.scale.y,i.z*=t*this.scale.z,s.add(i)}randomizeDirection(s,t){if(t===0)return;const i=Th._randomQuat,n=Th._tempVec;n.set(Math.random()-.5,Math.random()-.5,Math.random()-.5).normalize(),i.setFromAxisAngle(n,t*Math.random()*Math.PI),s.applyQuaternion(i)}spherizeDirection(s,t){if(t===0)return;const i=Math.random()*Math.PI*2,n=Math.acos(1-Math.random()*2),o=Math.sin(n)*Math.cos(i),r=Math.sin(n)*Math.sin(i),l=Math.cos(n),c=new x(o,r,l);s.lerp(c,t)}randomSpherePoint(s,t,i,n,o){const r=Math.random(),l=Math.random(),c=2*Math.PI*r*(n/360),h=Math.acos(2*l-1),d=W.lerp(1,1-Math.pow(1-Math.random(),Math.PI),i)*t,u=s.x+this.scale.x*(-d*Math.sin(h)*Math.cos(c)),p=s.y+this.scale.y*(d*Math.sin(h)*Math.sin(c)),g=s.z+this.scale.z*(d*Math.cos(h));o.x=u,o.y=p,o.z=g}randomCirclePoint(s,t,i,n,o){const r=Math.random(),l=2*Math.PI*r*(n/360),c=W.lerp(1,1-Math.pow(1-Math.random(),Math.PI),i)*t,h=s.x+this.scale.x*c*Math.cos(l),d=s.y+this.scale.y*c*Math.sin(l),u=s.z;o.x=h,o.y=d,o.z=u}randomConePoint(s,t,i,n,o,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*(o/360);switch(r){case 2:case 1:d+=Math.PI+.5,d+=this._loopTime*Math.PI*2,d%=W.toRadians(o);break}const u=Math.acos(2*h-1),p=W.lerp(1,1-Math.pow(1-Math.random(),Math.PI),n)*i,g=s.x+-p*Math.sin(u)*Math.cos(d),y=s.y+p*Math.sin(u)*Math.sin(d),f=s.z;l.x=g*this.scale.x,l.y=y*this.scale.y,l.z=f*this.scale.z}},a(Ep,"_randomQuat",new V),a(Ep,"_tempVec",new x),Ep);let Xe=Th;k([m()],Xe.prototype,"shapeType",2),k([m()],Xe.prototype,"enabled",2),k([m()],Xe.prototype,"alignToDirection",2),k([m()],Xe.prototype,"angle",2),k([m()],Xe.prototype,"arc",2),k([m()],Xe.prototype,"arcSpread",2),k([m()],Xe.prototype,"arcSpeedMultiplier",2),k([m()],Xe.prototype,"arcMode",2),k([m(x)],Xe.prototype,"boxThickness",2),k([m(x)],Xe.prototype,"position",2),k([m(x)],Xe.prototype,"rotation",2),k([m(x)],Xe.prototype,"scale",2),k([m()],Xe.prototype,"radius",2),k([m()],Xe.prototype,"radiusThickness",2),k([m()],Xe.prototype,"sphericalDirectionAmount",2),k([m()],Xe.prototype,"randomDirectionAmount",2),k([m()],Xe.prototype,"randomPositionAmount",2),k([m()],Xe.prototype,"meshShapeType",2),k([m(oh)],Xe.prototype,"meshRenderer",2);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(t){this._time+=t.time.deltaTime*this.scrollSpeedMultiplier}apply(t,i,n,o,r,l){if(!this.enabled)return;this._noise||(this._noise=JC(()=>0));const c=this._temp.set(i.x,i.y,i.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)),n.x+=this._temp.x,n.y+=this._temp.y,n.z+=this._temp.z}}k([m()],Ce.prototype,"damping",2),k([m()],Ce.prototype,"enabled",2),k([m()],Ce.prototype,"frequency",2),k([m()],Ce.prototype,"octaveCount",2),k([m()],Ce.prototype,"octaveMultiplier",2),k([m()],Ce.prototype,"octaveScale",2),k([m(Q)],Ce.prototype,"positionAmount",2),k([m()],Ce.prototype,"quality",2),k([m(Q)],Ce.prototype,"remap",2),k([m()],Ce.prototype,"remapEnabled",2),k([m()],Ce.prototype,"remapMultiplier",2),k([m(Q)],Ce.prototype,"remapX",2),k([m()],Ce.prototype,"remapXMultiplier",2),k([m(Q)],Ce.prototype,"remapY",2),k([m()],Ce.prototype,"remapYMultiplier",2),k([m(Q)],Ce.prototype,"remapZ",2),k([m()],Ce.prototype,"remapZMultiplier",2),k([m()],Ce.prototype,"scrollSpeedMultiplier",2),k([m()],Ce.prototype,"separateAxes",2),k([m()],Ce.prototype,"strengthMultiplier",2),k([m(Q)],Ce.prototype,"strengthX",2),k([m()],Ce.prototype,"strengthXMultiplier",2),k([m(Q)],Ce.prototype,"strengthY",2),k([m()],Ce.prototype,"strengthYMultiplier",2),k([m(Q)],Ce.prototype,"strengthZ",2),k([m()],Ce.prototype,"strengthZMultiplier",2);class Ue{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(t,i,n,o){const r=this.widthOverTrail.evaluate(n,o);return t*=r,t}getColor(t,i,n){const o=this.colorOverTrail.evaluate(n),r=this.colorOverLifetime.evaluate(i);t.x*=o.r*r.r,t.y*=o.g*r.g,t.z*=o.b*r.b,"alpha"in o&&"alpha"in r&&(t.w*=o.alpha*r.alpha)}}k([m()],Ue.prototype,"enabled",2),k([m()],Ue.prototype,"attachRibbonToTransform",2),k([m(si)],Ue.prototype,"colorOverLifetime",2),k([m(si)],Ue.prototype,"colorOverTrail",2),k([m()],Ue.prototype,"dieWithParticles",2),k([m()],Ue.prototype,"inheritParticleColor",2),k([m(Q)],Ue.prototype,"lifetime",2),k([m()],Ue.prototype,"lifetimeMultiplier",2),k([m()],Ue.prototype,"minVertexDistance",2),k([m()],Ue.prototype,"mode",2),k([m()],Ue.prototype,"ratio",2),k([m()],Ue.prototype,"ribbonCount",2),k([m()],Ue.prototype,"shadowBias",2),k([m()],Ue.prototype,"sizeAffectsLifetime",2),k([m()],Ue.prototype,"sizeAffectsWidth",2),k([m()],Ue.prototype,"splitSubEmitterRibbons",2),k([m()],Ue.prototype,"textureMode",2),k([m(Q)],Ue.prototype,"widthOverTrail",2),k([m()],Ue.prototype,"widthOverTrailMultiplier",2),k([m()],Ue.prototype,"worldSpace",2);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 ne)}update(t){this._system=t}init(t){this._index==0&&(t.debug=!0),this._index+=1,t.orbitx=this.orbitalX.evaluate(Math.random()),t.orbity=this.orbitalY.evaluate(Math.random()),t.orbitz=this.orbitalZ.evaluate(Math.random()),this._hasOrbital=t.orbitx!=0||t.orbity!=0||t.orbitz!=0}apply(t,i,n,o,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),y=this.z.evaluate(d);if(this._temp.set(-p,g,y),this._system&&this._system.main.simulationSpace===1&&this._temp.applyQuaternion(this._system.worldQuaternion),this._hasOrbital&&((h=this._system)==null?void 0:h.worldPos)){const f=this._temp2.set(n.x,n.y,n.z),v=this.orbitalXMultiplier,b=this.orbitalYMultiplier,w=this.orbitalZMultiplier,_=u*Math.PI*2*10,C=Math.cos(_*v),R=Math.sin(_*v),M=Math.cos(_*b),T=Math.sin(_*b),j=Math.cos(_*w),D=Math.sin(_*w),U=f.x*(M*j)+f.y*(M*D)+f.z*-T,B=f.x*(R*T*j-C*D)+f.y*(R*T*D+C*j)+f.z*(R*M),Y=f.x*(C*T*j+R*D)+f.y*(C*T*D-R*j)+f.z*(C*M),$=this._temp3.set(f.x-U,f.y-B,f.z-Y);$.normalize(),$.multiplyScalar(.2/r*Math.max(this.orbitalXMultiplier,this.orbitalYMultiplier,this.orbitalZMultiplier)),o.x+=$.x,o.y+=$.y,o.z+=$.z}o.x+=this._temp.x,o.y+=this._temp.y,o.z+=this._temp.z,o.x*=u,o.y*=u,o.z*=u}}k([m()],Qe.prototype,"enabled",2),k([m()],Qe.prototype,"space",2),k([m(Q)],Qe.prototype,"orbitalX",2),k([m(Q)],Qe.prototype,"orbitalY",2),k([m(Q)],Qe.prototype,"orbitalZ",2),k([m()],Qe.prototype,"orbitalXMultiplier",2),k([m()],Qe.prototype,"orbitalYMultiplier",2),k([m()],Qe.prototype,"orbitalZMultiplier",2),k([m()],Qe.prototype,"orbitalOffsetX",2),k([m()],Qe.prototype,"orbitalOffsetY",2),k([m()],Qe.prototype,"orbitalOffsetZ",2),k([m(Q)],Qe.prototype,"speedModifier",2),k([m()],Qe.prototype,"speedModifierMultiplier",2),k([m(Q)],Qe.prototype,"x",2),k([m()],Qe.prototype,"xMultiplier",2),k([m(Q)],Qe.prototype,"y",2),k([m()],Qe.prototype,"yMultiplier",2),k([m(Q)],Qe.prototype,"z",2),k([m()],Qe.prototype,"zMultiplier",2);class Dt{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(t){if(!this.sampleOnceAtStart())return this.getIndex(t)}getIndex(t){const i=this.numTilesX*this.numTilesY;t=t*this.cycleCount;let n=this.frameOverTime.evaluate(t%1);return n*=this.frameOverTimeMultiplier,n*=i,n=n%i,n=Math.floor(n),n}}k([m()],Dt.prototype,"animation",2),k([m()],Dt.prototype,"enabled",2),k([m()],Dt.prototype,"cycleCount",2),k([m(Q)],Dt.prototype,"frameOverTime",2),k([m()],Dt.prototype,"frameOverTimeMultiplier",2),k([m()],Dt.prototype,"numTilesX",2),k([m()],Dt.prototype,"numTilesY",2),k([m(Q)],Dt.prototype,"startFrame",2),k([m()],Dt.prototype,"startFrameMultiplier",2),k([m()],Dt.prototype,"rowMode",2),k([m()],Dt.prototype,"rowIndex",2),k([m()],Dt.prototype,"spriteCount",2),k([m()],Dt.prototype,"timeMode",2);class ns{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(t,i){return this.enabled?this.separateAxes?0:this.z.evaluate(t,i)*-1:0}}k([m()],ns.prototype,"enabled",2),k([m()],ns.prototype,"separateAxes",2),k([m(Q)],ns.prototype,"x",2),k([m()],ns.prototype,"xMultiplier",2),k([m(Q)],ns.prototype,"y",2),k([m()],ns.prototype,"yMultiplier",2),k([m(Q)],ns.prototype,"z",2),k([m()],ns.prototype,"zMultiplier",2);class Fi{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(t,i){if(!this.enabled)return 0;if(!this.separateAxes){const n=W.lerp(this.range.x,this.range.y,i);return this.z.evaluate(n)*-1}return 0}}k([m()],Fi.prototype,"enabled",2),k([m()],Fi.prototype,"range",2),k([m()],Fi.prototype,"separateAxes",2),k([m(Q)],Fi.prototype,"x",2),k([m()],Fi.prototype,"xMultiplier",2),k([m(Q)],Fi.prototype,"y",2),k([m()],Fi.prototype,"yMultiplier",2),k([m(Q)],Fi.prototype,"z",2),k([m()],Fi.prototype,"zMultiplier",2);class lt{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(t,i,n,o,r,l,c){if(this.enabled){const h=this.limit.evaluate(r)*this.limitMultiplier;if(i.length()>h){this._temp.copy(i).normalize().multiplyScalar(h);const d=this.dampen*.5;i.x=W.lerp(i.x,this._temp.x,d),i.y=W.lerp(i.y,this._temp.y,d),i.z=W.lerp(i.z,this._temp.z,d),n.x=W.lerp(n.x,this._temp.x,d),n.y=W.lerp(n.y,this._temp.y,d),n.z=W.lerp(n.z,this._temp.z,d)}}}}k([m()],lt.prototype,"enabled",2),k([m()],lt.prototype,"dampen",2),k([m(Q)],lt.prototype,"drag",2),k([m()],lt.prototype,"dragMultiplier",2),k([m(Q)],lt.prototype,"limit",2),k([m()],lt.prototype,"limitMultiplier",2),k([m()],lt.prototype,"separateAxes",2),k([m(Q)],lt.prototype,"limitX",2),k([m()],lt.prototype,"limitXMultiplier",2),k([m(Q)],lt.prototype,"limitY",2),k([m()],lt.prototype,"limitYMultiplier",2),k([m(Q)],lt.prototype,"limitZ",2),k([m()],lt.prototype,"limitZMultiplier",2),k([m()],lt.prototype,"multiplyDragByParticleSize",2),k([m()],lt.prototype,"multiplyDragByParticleVelocity",2),k([m()],lt.prototype,"space",2);const s1=class{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 s;const t=new s1;return t.enabled=this.enabled,t.curve=(s=this.curve)==null?void 0:s.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(s){this.system=s,this.reset()}reset(){this._firstUpdate=!0}update(s){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(s){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),s.x+=this._temp.x,s.y+=this._temp.y,s.z+=this._temp.z}}applyCurrent(s,t,i){if(this.enabled&&this.system&&this.system.worldspace!==!1&&this.mode===1){const n=this.curve.evaluate(t,i);this._temp.copy(this._velocity).multiplyScalar(n),s.x+=this._temp.x,s.y+=this._temp.y,s.z+=this._temp.z}}};let Ko=s1;k([m()],Ko.prototype,"enabled",2),k([m(Q)],Ko.prototype,"curve",2),k([m()],Ko.prototype,"curveMultiplier",2),k([m()],Ko.prototype,"mode",2);class ni{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(t,i,n,o){const r=t.length(),l=W.remap(r,this.range.x,this.range.y,0,1),c=this.size.evaluate(l,n);return o.x*=c,o.y*=c,o.z*=c,o}}k([m()],ni.prototype,"enabled",2),k([m(oe)],ni.prototype,"range",2),k([m()],ni.prototype,"separateAxes",2),k([m(Q)],ni.prototype,"size",2),k([m()],ni.prototype,"sizeMultiplier",2),k([m(Q)],ni.prototype,"x",2),k([m()],ni.prototype,"xMultiplier",2),k([m(Q)],ni.prototype,"y",2),k([m()],ni.prototype,"yMultiplier",2),k([m(Q)],ni.prototype,"z",2),k([m()],ni.prototype,"zMultiplier",2);class ta{constructor(){a(this,"enabled"),a(this,"range"),a(this,"color")}evaluate(t,i,n){const o=t.length(),r=W.remap(o,this.range.x,this.range.y,0,1),l=this.color.evaluate(r,i);n.x*=l.r,n.y*=l.g,n.z*=l.b,"alpha"in l&&(n.w*=l.alpha)}}k([m()],ta.prototype,"enabled",2),k([m(oe)],ta.prototype,"range",2),k([m(si)],ta.prototype,"color",2),new x(1,1,1),new x(0,0,1);class Ap{constructor(t,i,n,o){a(this,"type","NeedleParticleSubEmitter"),a(this,"emitterType"),a(this,"emitterProbability"),a(this,"q_",new V),a(this,"v_",new x),a(this,"v2_",new x),a(this,"_emitterMatrix",new Om),a(this,"_circularBuffer"),this.system=t,this.particleSystem=i,this.subSystem=n,this.subParticleSystem=o,this.subParticleSystem&&this.subParticleSystem&&(this.subParticleSystem.onlyUsedByOther=!0);const r=1e3;this._circularBuffer=new Si(()=>new Om,r)}clone(){throw new Error("Method not implemented.")}initialize(t){t.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===$0.Birth&&this.run(t)}update(t,i){this.run(t)}frameUpdate(t){}toJSON(){}reset(){}run(t){if(this.subSystem.currentParticles>=this.subSystem.main.maxParticles||!this.subParticleSystem||!t.emissionState||this.emitterProbability&&Math.random()>this.emitterProbability)return;const i=this.system.deltaTime;if(this.emitterType===$0.Death){let o=t.life;if(t[Rl]!==void 0&&(o=t[Rl]),!(t.age+i*1.2>=o))return;const r=this.subSystem.main.maxParticles-this.subSystem.currentParticles;t.emissionState.waitEmiting=r}const n=new Om;n.set(1,0,0,t.position.x,0,1,0,t.position.y,0,0,1,t.position.z,0,0,0,1),this.particleSystem.worldSpace||n.multiplyMatrices(this._emitterMatrix,n),this.subParticleSystem.emit(i,t.emissionState,n)}}var IE=Object.defineProperty,jE=Object.getOwnPropertyDescriptor,Ye=(s,t,i,n)=>{for(var o=n>1?void 0:n?jE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&IE(t,i,o),o};const Zo=O("debugparticles"),LE=O("noprogressive"),DE=O("debugprogressive");var $0=(s=>(s[s.Birth=0]="Birth",s[s.Collision=1]="Collision",s[s.Death=2]="Death",s[s.Trigger=3]="Trigger",s[s.Manual=4]="Manual",s))($0||{});class os extends A{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 t=`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(t)}}get transparent(){var t;return((t=this.particleMaterial)==null?void 0:t.transparent)??!1}getMaterial(t=!1){let i=t===!0&&this.trailMaterial?this.trailMaterial:this.particleMaterial;if(i){if(i.type==="MeshStandardMaterial"){Zo&&console.debug("ParticleSystemRenderer.getMaterial: MeshStandardMaterial detected, converting to MeshBasicMaterial. See https://github.com/Alchemist0823/three.quarks/issues/101"),"map"in i&&i.map&&(i.map.colorSpace=mr,i.map.premultiplyAlpha=!1);const n=new Re;n.copy(i),t?this.trailMaterial=n:this.particleMaterial=n}i.map&&(i.map.colorSpace=mr,i.map.premultiplyAlpha=!1),t&&i.side===co&&(i=i.clone(),i.side=ym,t?this.trailMaterial=i:this.particleMaterial=i)}return i&&!LE&&i._didRequestTextureLOD===void 0&&(i._didRequestTextureLOD=0,DE&&console.log("Load material LOD",i.name),it.assignTextureLOD(i,0)),i}getMesh(t){let i=null;if(!i&&(this.particleMesh instanceof K&&(i=this.particleMesh.geometry),i===null)){i=new Fs(1,1);const n=i.attributes.uv;for(let o=0;o<n.count;o++)n.setX(o,1-n.getX(o))}return new K(i,this.getMaterial())}}Ye([m()],os.prototype,"renderMode",2),Ye([m(ke)],os.prototype,"particleMaterial",2),Ye([m(ke)],os.prototype,"trailMaterial",2),Ye([m()],os.prototype,"maxParticleSize",2),Ye([m()],os.prototype,"minParticleSize",2),Ye([m()],os.prototype,"velocityScale",2),Ye([m()],os.prototype,"cameraVelocityScale",2),Ye([m()],os.prototype,"lengthScale",2);class Ip{constructor(t,i=1){a(this,"_curve"),a(this,"_factor"),a(this,"type","function"),this._curve=t,this._factor=i}startGen(t){}genValue(t,i){return this._curve.evaluate(i,Math.random())*this._factor}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}}class q0{constructor(t){a(this,"type","value"),a(this,"system"),this.system=t}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}startGen(t){}}class BE extends q0{genValue(){return this.system.textureSheetAnimation.getStartIndex()}}class FE extends q0{constructor(){super(...arguments),a(this,"_lastPosition",new x),a(this,"_lastDistance",0)}update(){const t=te(this.system.gameObject);this._lastDistance=this._lastPosition.distanceTo(t),this._lastPosition.copy(t)}genValue(){if(!this.system.isPlaying||!this.system.emission.enabled||this.system.currentParticles>=this.system.maxParticles)return 0;let t=this.system.emission.rateOverTime.evaluate(this.system.time/this.system.duration,Math.random());if(this.system.deltaTime>0){const o=this.system.emission.rateOverDistance.evaluate(this.system.time/this.system.duration,Math.random());let r=this._lastDistance/this.system.deltaTime*o;Number.isFinite(r)||(r=0),t+=r}const i=this.system.emission.getBurst();i>0&&(t+=i/this.system.deltaTime);const n=this.system.maxParticles-this.system.currentParticles;return W.clamp(t,0,n/this.system.deltaTime)}}class zE extends q0{genValue(){return this.system.isPlaying,0}}class Jo{constructor(t){a(this,"system"),a(this,"type"),this.type=Object.getPrototypeOf(this).constructor.name||"ParticleSystemBaseBehaviour",t&&(this.system=t)}get context(){return this.system.context}initialize(t){}update(t,i){}frameUpdate(t){}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}reset(){}}class UE extends Jo{constructor(){super(...arguments),a(this,"type","NeedleTextureSheet")}update(t,i){const n=this.system.textureSheetAnimation;if(n.enabled){const o=t.age/t.life,r=n.evaluate(o);r!==void 0&&(t.uvTile=r)}}}const n1=Symbol("particleRotation");class NE extends Jo{constructor(){super(...arguments),a(this,"type","NeedleRotation")}initialize(t){t[n1]=Math.random()}update(t,i){if(t.rotation===void 0)return;const n=t.age/t.life;if(typeof t.rotation=="number"&&(this.system.rotationOverLifetime.enabled?t.rotation+=this.system.rotationOverLifetime.evaluate(n,t[n1])*i:this.system.renderer.renderMode===qn.Billboard&&(t.rotation=Math.PI),this.system.rotationBySpeed.enabled)){const o=t.velocity.length();t.rotation+=this.system.rotationBySpeed.evaluate(n,o)*i}}}const o1=Symbol("sizeLerpFactor"),WE=new x;class VE extends Jo{constructor(){super(...arguments),a(this,"type","NeedleSize"),a(this,"_minSize",0),a(this,"_maxSize",1)}initialize(t){t[o1]=Math.random(),this._minSize=this.system.renderer.minParticleSize,this._maxSize=this.system.renderer.maxParticleSize}update(t,i){const n=t.age/t.life;let o=1;this.system.sizeOverLifetime.enabled&&(o*=this.system.sizeOverLifetime.evaluate(n,void 0,t[o1]).x);let r=1;this.system.renderer.renderMode!==qn.Mesh&&(r=this.system.worldScale.x/this.system.cameraScale);const l=G(t.startSize).multiplyScalar(o*r);if(t.size.set(l.x,l.y,l.z),this.system.localspace){const c=h1(this.system,WE);t.size.x*=c.x,t.size.y*=c.y,t.size.z*=c.z}}}const Rl=Symbol("particleLife"),G0=Symbol("trailLifetime"),r1=Symbol("trailStartLength"),X0=Symbol("trailWidthRandom");class HE extends Jo{constructor(){super(...arguments),a(this,"type","NeedleTrail")}initialize(t){t instanceof gv&&(t[Rl]=t.life,this.system.trails.enabled&&this.system.trails.dieWithParticles===!1&&(t[G0]=this.system.trails.lifetime.evaluate(Math.random(),Math.random()),t.life+=t[G0]),t[r1]=t.length,t[X0]=Math.random())}update(t){var i;if((i=this.system.trails)!=null&&i.enabled&&t instanceof gv){const n=t,o=t.age/t[Rl],r=t.previous.values(),l=t.previous.length;for(let c=0;c<l;c++){const h=r.next().value,d=1-c/(l-1),u=t.size;if(u.x<=0&&!this.system.trails.sizeAffectsWidth){const p=20*this.system.trails.widthOverTrail.evaluate(.5,n[X0]);u.x=p,u.y=p,u.z=p}h.size=this.system.trails.getWidth(u.x,o,d,n[X0]),h.color.copy(t.color),this.system.trails.getColor(h.color,o,d)}if(t.age>t[Rl]){t.velocity.set(0,0,0);const c=(t.age-t[Rl])/t[G0];n.length=W.lerp(t[r1],0,c)}}}}const jp=Symbol("startVelocity"),a1=Symbol("gravityModifier"),Q0=Symbol("gravitySpeed"),Lp=Symbol("velocity lerp factor"),Y0=new x;class $E extends Jo{constructor(){super(...arguments),a(this,"type","NeedleVelocity"),a(this,"_gravityDirection",new x)}initialize(t){var i,n;const o=this.system.main.simulationSpeed;t.startSpeed=this.system.main.startSpeed.evaluate(Math.random(),Math.random());const r=this.system.shape.getDirection(t,t.position);t.velocity.x=r.x*t.startSpeed,t.velocity.y=r.y*t.startSpeed,t.velocity.z=r.z*t.startSpeed,(i=this.system.inheritVelocity)!=null&&i.enabled&&this.system.inheritVelocity.applyInitial(t.velocity),t[jp]?t[jp].copy(t.velocity):t[jp]=t.velocity.clone();const l=this.system.main.gravityModifier.evaluate(Math.random(),Math.random());t[a1]=l*o,t[Q0]=l*o*.5,t[Lp]=Math.random(),(n=this.system.velocityOverLifetime)==null||n.init(t),this._gravityDirection.set(0,-1,0),this.system.main.simulationSpace===Ph.Local&&this._gravityDirection.applyQuaternion(this.system.worldQuaternionInverted).normalize()}update(t,i){var n;const o=t[jp],r=t[a1];if(r!==0){const g=r*t[Q0];Y0.copy(this._gravityDirection).multiplyScalar(g),t[Q0]+=i*.05,o.add(Y0)}t.velocity.copy(o);const l=t.age/t.life;(n=this.system.inheritVelocity)!=null&&n.enabled&&this.system.inheritVelocity.applyCurrent(t.velocity,l,t[Lp]);const c=this.system.noise;c.enabled&&c.apply(0,t.position,t.velocity,i,t.age,t.life);const h=this.system.sizeBySpeed;h!=null&&h.enabled&&(t.size=h.evaluate(t.velocity,l,t[Lp],t.size));const d=this.system.colorBySpeed;d!=null&&d.enabled&&d.evaluate(t.velocity,t[Lp],t.color);const u=this.system.velocityOverLifetime;u.enabled&&u.apply(t,0,t.position,t.velocity,i,t.age,t.life);const p=this.system.limitVelocityOverLifetime;if(p.enabled&&p.apply(t.position,o,t.velocity,t.size,l,i,1),this.system.worldspace){const g=this.system.worldScale;t.velocity.x*=g.x,t.velocity.y*=g.y,t.velocity.z*=g.z}}}const l1=Symbol("colorLerpFactor"),c1=new Se(1,1,1,1),ia=new Se(1,1,1,1);class qE extends Jo{constructor(){super(...arguments),a(this,"type","NeedleColor")}initialize(t){}_init(t){const i=this.system.renderer.particleMaterial;ia.copy(this.system.main.startColor.evaluate(Math.random())),i!=null&&i.color&&(c1.copy(i.color),ia.multiply(c1)),ia.convertLinearToSRGB(),t.startColor.set(ia.r,ia.g,ia.b,ia.alpha),t.color.copy(t.startColor),t[l1]=Math.random()}update(t,i){if(t.age===0&&this._init(t),this.system.colorOverLifetime.enabled){const n=t.age/t.life,o=this.system.colorOverLifetime.color.evaluate(n,t[l1]);t.color.set(o.r,o.g,o.b,"alpha"in o?o.alpha:1).multiply(t.startColor)}else t.color.copy(t.startColor)}}class GE{constructor(t){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 nO(220),followLocalOrigin:!1}),a(this,"flatWhiteTexture"),a(this,"clonedTexture",{original:void 0,clone:void 0}),this.system=t,this.emission=new FE(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 Ip(this.system.main.startLifetime)}get startSpeed(){return new Ip(this.system.main.startSpeed)}get startRotation(){return new Ip(this.system.main.startRotation)}get startSize(){return new Ip(this.system.main.startSize)}get startColor(){return new iO(new sO(1,1,1,1))}get emissionOverTime(){return this.emission}get emissionOverDistance(){return new zE(this.system)}get instancingGeometry(){return this.system.renderer.getMesh(this.system.renderer.renderMode).geometry}get renderMode(){if(this.system.trails.enabled===!0)return xn.Trail;switch(this.system.renderer.renderMode){case qn.Billboard:return xn.BillBoard;case qn.Stretch:return xn.StretchedBillBoard;case qn.HorizontalBillboard:return xn.HorizontalBillBoard;case qn.VerticalBillboard:return xn.VerticalBillBoard;case qn.Mesh:return xn.Mesh}return xn.BillBoard}get speedFactor(){var t;let i=this.system.main.simulationSpeed;return((t=this.system.renderer)==null?void 0:t.renderMode)===qn.Stretch&&(i*=this.system.renderer.velocityScale??1),i}get texture(){const t=this.material;if(t&&t.map){const i=t.map;if(this.clonedTexture.original!==i||!this.clonedTexture.clone){const n=i.clone();n.premultiplyAlpha=!1,n.colorSpace=mr,this.clonedTexture.original=i,this.clonedTexture.clone=n}return this.clonedTexture.clone}return this.flatWhiteTexture||(this.flatWhiteTexture=Kg(new Se(1,1,1,1),1)),this.flatWhiteTexture}get startTileIndex(){return new BE(this.system)}get uTileCount(){var t;return this.anim.enabled?(t=this.anim)==null?void 0:t.numTilesX:void 0}get vTileCount(){var t;return this.anim.enabled?(t=this.anim)==null?void 0:t.numTilesY:void 0}get renderOrder(){return 1}get blending(){var t;return((t=this.system.renderer.particleMaterial)==null?void 0:t.blending)??gC}get transparent(){return this.system.renderer.transparent}get worldSpace(){return this.system.main.simulationSpace===Ph.World}}class XE{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 Dp=class extends A{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 V),a(this,"_worldQuaternionInverted",new V),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(s=!1){var t;s&&P.foreachComponent(this.gameObject,i=>{i instanceof Dp&&i!==this&&i.play(!1)},!0),this._isPlaying=!0,this._particleSystem&&(this._particleSystem.emissionState.time=0,this._particleSystem.emitEnded=!1),(t=this.emission)==null||t.reset()}pause(s=!0){s&&P.foreachComponent(this.gameObject,t=>{t instanceof Dp&&t!==this&&t.pause(!1)},!0),this._isPlaying=!1}stop(s=!0,t=!1){s&&P.foreachComponent(this.gameObject,i=>{i instanceof Dp&&i!==this&&i.stop(!1,t)},!0),this._isPlaying=!1,this._time=0,t&&this.reset()}reset(){var s;this._time=0,this._particleSystem&&(this._particleSystem.particleNum=0,this._particleSystem.emissionState.time=0,this._particleSystem.emitEnded=!1,(s=this.emission)==null||s.reset())}emit(s){if(this._particleSystem){this.onUpdate(),s=Math.min(s,this.maxParticles-this.currentParticles),this._state||(this._state=new XE),this._state.waitEmiting=s,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(s){this.main.playOnAwake=s}get renderer(){return this._renderer}get isPlaying(){return this._isPlaying}get currentParticles(){var s;return((s=this._particleSystem)==null?void 0:s.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(s){return this._particleSystem?(s instanceof Jo&&(s.system=this),(F()||Zo)&&console.debug("Add custom ParticleSystem Behaviour",s),this._particleSystem.addBehavior(s),!0):!1}removeBehaviour(s){if(!this._particleSystem)return!1;const t=this._particleSystem.behaviors,i=t.indexOf(s);return i!==-1&&((F()||Zo)&&console.debug("Remove custom ParticleSystem Behaviour",i,s),t.splice(i,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(s){for(let t=0;t<s.length;t++){const i=s[t];if(!(i instanceof Mh)){const n=new Mh;Da(n,i),s[t]=n}}this._bursts=s}set subEmitterSystems(s){for(let t=0;t<s.length;t++){const i=s[t];if(!(i instanceof Eh)){const n=new Eh;Da(n,i),s[t]=n}}Zo&&s.length>0&&console.log("SubEmitters: ",s,this),this._subEmitterSystems=s}onAfterDeserialize(s){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(os),!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 I,this._container.matrixAutoUpdate=!1,this.context.scene.add(this._container),this._batchSystem=new eO,this._batchSystem.name=this.gameObject.name,this._container.add(this._batchSystem),this._interface=new GE(this),this._particleSystem=new tO(this._interface),this._particleSystem.addBehavior(new VE(this)),this._particleSystem.addBehavior(new qE(this)),this._particleSystem.addBehavior(new UE(this)),this._particleSystem.addBehavior(new NE(this)),this._particleSystem.addBehavior(new $E(this)),this._particleSystem.addBehavior(new HE(this)),this._batchSystem.addSystem(this._particleSystem);const s=this._particleSystem.emitter;this.context.scene.add(s),this.inheritVelocity.system&&this.inheritVelocity.system!==this&&(this.inheritVelocity=this.inheritVelocity.clone()),this.inheritVelocity.awake(this),Zo&&(console.log(this),this.gameObject.add(new wi(1)))}start(){this.addSubParticleSystems(),this.updateLayers(),this.renderer.particleMesh instanceof K&&this._interface.renderMode==xn.Mesh&&it.assignMeshLOD(this.renderer.particleMesh,0).then(s=>{s&&this.particleSystem&&this._interface.renderMode==xn.Mesh&&(this.particleSystem.instancingGeometry=s)})}onDestroy(){var s,t,i,n;(s=this._container)==null||s.removeFromParent(),(t=this._batchSystem)==null||t.removeFromParent(),(i=this._particleSystem)==null||i.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 s;this.main&&(this._didPreWarm===!1&&((s=this.main)==null?void 0:s.prewarm)===!0&&(this._didPreWarm=!0,this.preWarm()),this.onUpdate(),this.onSimulate(this.deltaTime))}preWarm(){var s;if(!((s=this.emission)!=null&&s.enabled)||this.emission.rateOverTime.getMax()<=0)return;const t=1/60,i=this.main.duration,n=this.main.startLifetime.getMax(),o=1e3,r=Math.min(Math.max(i,n)/Math.max(.01,this.main.simulationSpeed),o),l=Math.ceil(r/t),c=Date.now();Zo&&console.log(`Particles ${this.name} - Prewarm for ${l} frames (${r} sec). Duration: ${i}, 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(s){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(s)}this._time+=s,this._time>this.duration&&(this._time=0)}updateLayers(){if(this._batchSystem)for(let s=0;s<this._batchSystem.batches.length;s++){const t=this._batchSystem.batches[s];t.layers.disableAll();const i=this.layer;t.layers.mask=1<<i}}onUpdate(){var s,t;if(this._bursts&&(this.emission.bursts=this._bursts,delete this._bursts),!this._isPlaying)return;const i=this.context.mainCamera;if(i){const r=Je(i);this._cameraScale=r.x}const n=!this.worldspace,o=this.gameObject;if(Oe(o,this.__worldQuaternion),this._worldQuaternionInverted.copy(this.__worldQuaternion).invert(),Je(this.gameObject,this._worldScale),n&&this._container&&(s=this.gameObject)!=null&&s.parent){const r=h1(this,Y0);this._container.matrix.makeScale(r.x,r.y,r.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 s;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 i=(s=t.particleSystem)==null?void 0:s._particleSystem;if(i){t.particleSystem._isUsedAsSubsystem=!0;const n=new Ap(this,this._particleSystem,t.particleSystem,i);n.emitterType=t.type,n.emitterProbability=t.emitProbability,this._particleSystem.addBehavior(n)}else Zo&&console.warn("Could not add SubParticleSystem",t,this)}}};let ct=Dp;Ye([m(Rh)],ct.prototype,"colorOverLifetime",2),Ye([m(Lt)],ct.prototype,"main",2),Ye([m(hn)],ct.prototype,"emission",2),Ye([m(Yo)],ct.prototype,"sizeOverLifetime",2),Ye([m(Xe)],ct.prototype,"shape",2),Ye([m(Ce)],ct.prototype,"noise",2),Ye([m(Ue)],ct.prototype,"trails",2),Ye([m(Qe)],ct.prototype,"velocityOverLifetime",2),Ye([m(lt)],ct.prototype,"limitVelocityOverLifetime",2),Ye([m(Ko)],ct.prototype,"inheritVelocity",2),Ye([m(ta)],ct.prototype,"colorBySpeed",2),Ye([m(Dt)],ct.prototype,"textureSheetAnimation",2),Ye([m(ns)],ct.prototype,"rotationOverLifetime",2),Ye([m(Fi)],ct.prototype,"rotationBySpeed",2),Ye([m(ni)],ct.prototype,"sizeBySpeed",2);class Eh{constructor(){a(this,"particleSystem"),a(this,"emitProbability",1),a(this,"properties"),a(this,"type")}_deserialize(t,i){const n=this.particleSystem;if(n instanceof ct)return;let o="";n&&typeof n.guid=="string"&&(o=n.guid,this.particleSystem=P.findByGuid(o,i)),Zo&&!(this.particleSystem instanceof ct)&&console.warn("Could not find particle system for sub emitter",o,i,this)}}function h1(s,t){if(t.set(1,1,1),s.gameObject.parent&&s.localspace)switch(s.main.scalingMode){case H0.Local:t=Je(s.gameObject.parent,t),t.x=1/t.x,t.y=1/t.y,t.z=1/t.z;break;default:if(!s.unsupported_scaling_mode){s.unsupported_scaling_mode=!0;const i="ParticleSystem scale mode "+H0[s.main.scalingMode]+" is not supported";F()&&xe(i),console.warn(i,s.name,s)}t=Je(s.gameObject,t);break}return t}class Vl extends A{constructor(){super(...arguments),a(this,"_didAssignPlayerColor",!1),a(this,"tryAssignColor",()=>{const t=P.getComponentInParent(this.gameObject,Li);if(t&&t.owner)return this._didAssignPlayerColor=!0,this.assignUserColor(t.owner),!0;const i=P.getComponentInParent(this.gameObject,Rt);return i!=null&&i.connectionId?(this._didAssignPlayerColor=!0,this.assignUserColor(i.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 V_(.2),!this.tryAssignColor()););}assignUserColor(t){const i=Vl.hashCode(t),n=Vl.colorFromHashCode(i);if(this.gameObject.type==="Mesh"){const o=this.gameObject;this.assignColor(n,t,o)}else if(this.gameObject.children)for(const o of this.gameObject.children){const r=o;r.material&&r.material.color&&this.assignColor(n,t,r)}}assignColor(t,i,n){let o=n.material;o&&(o._playerMaterial!==i&&(o=o.clone(),o._playerMaterial=i,n.material=o),o.color=t)}static hashCode(t){var i=0,n,o;if(t.length===0)return i;for(n=0;n<t.length;n++)o=t.charCodeAt(n),i=(i<<5)-i+o,i|=0;return i}static colorFromHashCode(t){const i=(t&16711680)>>16,n=(t&65280)>>8,o=t&255;return new re(i/255,n/255,o/255)}}const QE=O("debugpost");let K0=null;function YE(s){K0=s}function d1(s){let t=s.gameObject;for(;t;){for(const i of ou(t))if(i.isPostProcessingManager===!0)return i;t=t.parent}return null}function KE(s){let t=d1(s);if(!t)if(K0){QE&&console.warn("Adding postprocessing manager to the scene.");const i=s.scene;t=Mi(i,K0)}else F()&&console.warn("No post processing manager found");return t}var ZE=Object.defineProperty,JE=Object.getOwnPropertyDescriptor,u1=(s,t,i,n)=>{for(var o=n>1?void 0:n?JE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&ZE(t,i,o),o};const eA=O("debugpost");class N{constructor(t){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"),t!==void 0&&this.initialize(t)}get isInitialized(){return this._isInitialized}initialize(t){t!==void 0&&(this._value=t,this._defaultValue=t,this._valueRaw=t,this._isInitialized=!0)}get overrideState(){return this._active}set overrideState(t){if(this._active===t)return;this._active=t;const i=t?this._valueRaw:this._defaultValue;this.processValue(i,!0)}get value(){return this._valueRaw}set value(t){this.isInitialized||this.initialize(t),this.processValue(t,!1)}set defaultValue(t){this._defaultValue=t}__init(){this.processValue(this._valueRaw,!0)}processValue(t,i){if(t==null||!i&&this.testIfValueChanged(t)===!1)return;const n=this._value;eA&&typeof n=="number"&&typeof t=="number"&&(n?.toFixed(4),t?.toFixed(4)),!this._active&&this._defaultValue!==void 0?(this._value=this._defaultValue,t=this._defaultValue,this._valueRaw=t):(this._valueRaw=t,this._active&&this.valueProcessor&&(t=this.valueProcessor(t)),this._value=t),this.onValueChanged&&this.onValueChanged(t,n,this)}testIfValueChanged(t){return this._valueRaw!==t}}u1([m()],N.prototype,"overrideState",1),u1([m()],N.prototype,"value",1);class tA extends Zi{constructor(){super([N])}onSerialize(t,i){}onDeserialize(t,i){const n=i.target,o=i.path;let r;if(n&&o&&(r=n[o]),(typeof r!="object"||typeof r=="object"&&r.isVolumeParameter!==!0)&&(r=new N),typeof t=="object"&&"value"in t){const l=t.value;r.initialize(l),r.overrideState=t.overrideState}else r.value=t;return r}}new tA;var iA=Object.defineProperty,sA=Object.getOwnPropertyDescriptor,nA=(s,t,i,n)=>{for(var o=n>1?void 0:n?sA(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&iA(t,i,o),o};const oA=O("debugpost");class ht extends A{constructor(t=void 0){if(super(),a(this,"active",!0),a(this,"_manager",null),a(this,"_result"),a(this,"_postprocessingContext",null),t)for(const i of Object.keys(t)){const n=t[i],o=this[i];o instanceof N?o.initialize(n):o!==void 0&&(this[i]=n)}}get isPostProcessingEffect(){return!0}onEnable(){super.onEnable(),this.onEffectEnabled(),this.__internalDidAwakeAndStart&&(this.active=!0)}onDisable(){var t;super.onDisable(),(t=this._manager)==null||t.removeEffect(this),this.active=!1}onEffectEnabled(t){var i;t&&t.isPostProcessingManager===!0?this._manager=t:this._manager||(this._manager=KE(this)),(i=this._manager)==null||i.addEffect(this)}init(){}get postprocessingContext(){return this._postprocessingContext}apply(t){var i;return this._postprocessingContext=t,this._result||(this.initParameters(),this._result=(i=this.onCreateEffect)==null?void 0:i.call(this)),this._result&&this.initParameters(),this._result}unapply(){}dispose(){oA&&console.warn("DISPOSE",this),this._result&&(Array.isArray(this._result)?this._result.forEach(t=>t.dispose()):this._result.dispose()),this._result=void 0}initParameters(){const t=Object.keys(this);for(const i of t){const n=this[i];n instanceof N&&n.__init()}}onEditorModification(t){const i=t.propertyName;if(this[i]instanceof N){const n=t.value;return this[i].value=n,!0}}}nA([m()],ht.prototype,"active",2);var rA=Object.defineProperty,aA=Object.getOwnPropertyDescriptor,lA=(s,t,i,n)=>{for(var o=n>1?void 0:n?aA(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&rA(t,i,o),o};const cA=O("debugpost"),Z0={};function rs(s,t){Z0[s]=t}function hA(s){return s.__type in Z0?Z0[s.__type]:(cA&&s.__type&&console.warn("Unknown postprocessing type",s.__type,s),ht)}class Ah{constructor(){a(this,"components",[])}init(){var t;(t=this.components)==null||t.forEach(i=>i.init())}addEffect(t){this.components.push(t)}removeEffect(t){const i=this.components.indexOf(t);i>=0&&this.components.splice(i,1)}}lA([$a([s=>hA(s),ht])],Ah.prototype,"components",2);var dA=Object.defineProperty,uA=Object.getOwnPropertyDescriptor,pA=(s,t,i,n)=>{for(var o=n>1?void 0:n?uA(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&dA(t,i,o),o};class Ih extends ht{constructor(){super(...arguments),a(this,"preset",new N(2))}get typeName(){return"Antialiasing"}onCreateEffect(){const t=new L.POSTPROCESSING.MODULE.SMAAEffect({preset:L.POSTPROCESSING.MODULE.SMAAPreset.HIGH,edgeDetectionMode:L.POSTPROCESSING.MODULE.EdgeDetectionMode.DEPTH});return this.preset.onValueChanged=i=>{t.applyPreset(i)},t}}pA([m(N)],Ih.prototype,"preset",2),rs("Antialiasing",Ih);var mA=Object.defineProperty,gA=Object.getOwnPropertyDescriptor,J0=(s,t,i,n)=>{for(var o=n>1?void 0:n?gA(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&mA(t,i,o),o},ey;const p1=(ey=class extends ht{constructor(){super(...arguments),a(this,"threshold",new N(.9)),a(this,"intensity",new N(1)),a(this,"scatter",new N(.3)),a(this,"selectiveBloom")}get typeName(){return"Bloom"}init(){this.threshold.valueProcessor=s=>s,this.intensity.valueProcessor=s=>s,this.scatter.valueProcessor=s=>s}onCreateEffect(){let s;if(this.selectiveBloom==null&&(this.selectiveBloom=p1.useSelectiveBloom),this.selectiveBloom){const t=s=new L.POSTPROCESSING.MODULE.SelectiveBloomEffect(this.context.scene,this.context.mainCamera,{blendFunction:L.POSTPROCESSING.MODULE.BlendFunction.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,radius:.85,intensity:this.intensity.value});t.inverted=!0}else s=new L.POSTPROCESSING.MODULE.BloomEffect({blendFunction:L.POSTPROCESSING.MODULE.BlendFunction.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,radius:.85,intensity:this.intensity.value});return this.intensity.onValueChanged=t=>{s.intensity=t},this.threshold.onValueChanged=t=>{s.luminanceMaterial.threshold=Math.pow(t,2.2)},this.scatter.onValueChanged=t=>{s.luminancePass.enabled=!0,s.luminanceMaterial.smoothing=t,s.mipmapBlurPass&&(s.mipmapBlurPass.radius=vn.lerp(.1,.9,t))},s}},a(ey,"useSelectiveBloom",!1),ey);let sa=p1;J0([m(N)],sa.prototype,"threshold",2),J0([m(N)],sa.prototype,"intensity",2),J0([m(N)],sa.prototype,"scatter",2),rs("Bloom",sa);var fA=Object.defineProperty,yA=Object.getOwnPropertyDescriptor,vA=(s,t,i,n)=>{for(var o=n>1?void 0:n?yA(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&fA(t,i,o),o};class jh extends ht{constructor(){super(...arguments),a(this,"intensity",new N(0))}get typeName(){return"ChromaticAberration"}onCreateEffect(){const t=new L.POSTPROCESSING.MODULE.ChromaticAberrationEffect;return t.offset=new oe(0,0),t.radialModulation=!0,t.modulationOffset=.15,this.intensity.valueProcessor=i=>i*.02,this.intensity.onValueChanged=i=>{t.offset.x=-i,t.offset.y=i},t}}vA([m(N)],jh.prototype,"intensity",2),rs("ChromaticAberration",jh);var bA=Object.defineProperty,_A=Object.getOwnPropertyDescriptor,m1=(s,t,i,n)=>{for(var o=n>1?void 0:n?_A(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&bA(t,i,o),o};const g1=O("debugpost");var Bp=(s=>(s[s.None=0]="None",s[s.Neutral=1]="Neutral",s[s.ACES=2]="ACES",s[s.AgX=3]="AgX",s[s.KhronosNeutral=4]="KhronosNeutral",s))(Bp||{});function ty(s){switch(s){case 0:return fd;case 1:return _m;case 2:return bm;case 3:return gd;case 4:return Ql;default:return Ql}}function wA(s){switch(s){case fd:return 0;case bm:return 2;case gd:return 3;case Ql:return 1;case _m:return 1;default:return 0}}function f1(s){switch(s){case fd:return L.POSTPROCESSING.MODULE.ToneMappingMode.LINEAR;case bm:return L.POSTPROCESSING.MODULE.ToneMappingMode.ACES_FILMIC;case gd:return L.POSTPROCESSING.MODULE.ToneMappingMode.AGX;case Ql:return L.POSTPROCESSING.MODULE.ToneMappingMode.NEUTRAL;case _m:return L.POSTPROCESSING.MODULE.ToneMappingMode.REINHARD;default:return L.POSTPROCESSING.MODULE.ToneMappingMode.LINEAR}}const y1=class extends ht{constructor(){super(...arguments),a(this,"mode",new N(void 0)),a(this,"exposure",new N(1))}get typeName(){return"ToneMapping"}setMode(s){const t=Bp[s];return t===void 0?(console.error("Invalid ToneMapping mode",s),this):(this.mode.value=t,this)}get isToneMapping(){return!0}onEffectEnabled(){const s=d1(this);s&&super.onEffectEnabled(s)}onCreateEffect(){if(this.postprocessingContext)for(const i of this.postprocessingContext.components){if(i===this)break;if(i!=this&&i instanceof y1){console.warn("Multiple tonemapping effects found in the same postprocessing stack: Please check your scene setup.",{activeEffect:i,ignoredEffect:this});return}}if(this.mode.isInitialized==!1){const i=wA(this.context.renderer.toneMapping);this.mode.initialize(i)}const s=ty(this.mode.value),t=new L.POSTPROCESSING.MODULE.ToneMappingEffect({mode:f1(s)});return this.mode.onValueChanged=i=>{const n=ty(i);t.mode=f1(n),g1&&console.log("ToneMapping mode changed to",Bp[i],n,t.mode)},g1&&console.log("Use ToneMapping",Bp[this.mode.value],s,t.mode,"renderer.tonemapping: "+this.context.renderer.toneMapping),this.exposure.onValueChanged=i=>{this.context.renderer.toneMappingExposure=i},t}onBeforeRender(){this.mode.overrideState&&(this.context.renderer.toneMapping=ty(this.mode.value)),this.exposure.overrideState&&(this.context.renderer.toneMappingExposure=this.exposure.value)}};let er=y1;m1([m(N)],er.prototype,"mode",2),m1([m(N)],er.prototype,"exposure",2),rs("Tonemapping",er);var xA=Object.defineProperty,SA=Object.getOwnPropertyDescriptor,Fp=(s,t,i,n)=>{for(var o=n>1?void 0:n?SA(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&xA(t,i,o),o};class tr extends ht{constructor(){super(...arguments),a(this,"postExposure",new N(0)),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=t=>(t=Math.pow(2,t),t),this.contrast.valueProcessor=t=>{let i=1;return t>0?i=200:t<0&&(i=100),t/i},this.contrast.defaultValue=0,this.hueShift.valueProcessor=t=>Math.PI*t/180,this.hueShift.defaultValue=0,this.saturation.valueProcessor=t=>t<0?t/100:t/(100*Math.PI),this.saturation.defaultValue=0}onCreateEffect(){var t,i;const n=[];this.context.renderer.toneMapping!==wa&&this.postExposure.overrideState&&(this.context.renderer.toneMapping=wa);let o=(t=this.postprocessingContext)==null?void 0:t.components.find(c=>c instanceof er);o||(o=new er,(i=this.postprocessingContext)==null||i.components.push(o)),this.postExposure.onValueChanged=c=>{this.postExposure.overrideState&&(o.exposure.value=c)};const r=new L.POSTPROCESSING.MODULE.BrightnessContrastEffect;this.contrast.onValueChanged=c=>r.contrast=c;const l=new L.POSTPROCESSING.MODULE.HueSaturationEffect;return n.push(r),n.push(l),this.hueShift.onValueChanged=c=>l.hue=c,this.saturation.onValueChanged=c=>l.saturation=c,n}}Fp([m(N)],tr.prototype,"postExposure",2),Fp([m(N)],tr.prototype,"contrast",2),Fp([m(N)],tr.prototype,"hueShift",2),Fp([m(N)],tr.prototype,"saturation",2),rs("ColorAdjustments",tr);var CA=Object.defineProperty,OA=Object.getOwnPropertyDescriptor,na=(s,t,i,n)=>{for(var o=n>1?void 0:n?OA(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&CA(t,i,o),o};const PA=O("debugpost");class As extends ht{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*1/window.devicePixelRatio)),a(this,"bokehScale",new N)}get typeName(){return"DepthOfField"}init(){this.focalLength.valueProcessor=i=>{const n=i/300,o=2;return W.lerp(o,.01,n)};const t=20;this.aperture.valueProcessor=i=>{const n=1-i/32;return W.lerp(1,t,n)}}onCreateEffect(){if(this.mode===0){PA&&console.warn("DepthOfField: Mode is set to Off");return}const t=new L.POSTPROCESSING.MODULE.DepthOfFieldEffect(this.context.mainCamera,{worldFocusRange:.2,focalLength:1,bokehScale:20,resolutionScale:this.resolutionScale.value});return this.focusDistance.onValueChanged=i=>{t.cocMaterial.worldFocusDistance=i},this.focalLength.onValueChanged=i=>t.cocMaterial.worldFocusRange=i,this.aperture.onValueChanged=i=>t.bokehScale=i,this.resolutionScale&&(this.resolutionScale.onValueChanged=i=>t.resolution.scale=i),[t]}unapply(){}}na([m()],As.prototype,"mode",2),na([m(N)],As.prototype,"focusDistance",2),na([m(N)],As.prototype,"focalLength",2),na([m(N)],As.prototype,"aperture",2),na([m(N)],As.prototype,"gaussianMaxRadius",2),na([m(N)],As.prototype,"resolutionScale",2),na([m(N)],As.prototype,"bokehScale",2),rs("DepthOfField",As);class Lh extends ht{constructor(t){super(),a(this,"effect"),this.effect=t}get typeName(){return this.effect.constructor.name}onCreateEffect(){return this.effect}}var kA=Object.defineProperty,MA=Object.getOwnPropertyDescriptor,RA=(s,t,i,n)=>{for(var o=n>1?void 0:n?MA(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&kA(t,i,o),o};class Dh extends ht{constructor(){super(...arguments),a(this,"granularity",new N(10))}get typeName(){return"PixelationEffect"}onCreateEffect(){const t=new L.POSTPROCESSING.MODULE.PixelationEffect;return this.granularity.onValueChanged=i=>{t.granularity=i},t}}RA([m(N)],Dh.prototype,"granularity",2),rs("PixelationEffect",Dh);var TA=Object.defineProperty,EA=Object.getOwnPropertyDescriptor,Bh=(s,t,i,n)=>{for(var o=n>1?void 0:n?EA(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&TA(t,i,o),o};class Gn extends ht{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 re(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 t=this.context.mainCamera.far-this.context.mainCamera.near;this._ssao.ssaoMaterial.worldDistanceFalloff=t*.01,this._ssao.ssaoMaterial.worldDistanceThreshold=this.context.mainCamera.far}}onCreateEffect(){const t=this.context.mainCamera,i=new L.POSTPROCESSING.MODULE.NormalPass(this.context.scene,t),n=new L.POSTPROCESSING.MODULE.DepthDownsamplingPass({normalBuffer:i.texture,resolutionScale:.5}),o=this._ssao=new L.POSTPROCESSING.MODULE.SSAOEffect(t,i.texture,{normalDepthBuffer:n.texture,worldDistanceThreshold:1,worldDistanceFalloff:1,worldProximityThreshold:.1,worldProximityFalloff:2,intensity:1,blendFunction:L.POSTPROCESSING.MODULE.BlendFunction.MULTIPLY,luminanceInfluence:.5});this.intensity.onValueChanged=l=>{o.intensity=l},this.falloff.onValueChanged=l=>{o.ssaoMaterial.radius=l*.1},this.samples.onValueChanged=l=>{o.ssaoMaterial.samples=l},this.color.onValueChanged=l=>{o.color||(o.color=new re),o.color.copy(l)},this.luminanceInfluence.onValueChanged=l=>{o.luminanceInfluence=l};const r=new Array;return r.push(i),r.push(n),r.push(o),r}}Bh([m(N)],Gn.prototype,"intensity",2),Bh([m(N)],Gn.prototype,"falloff",2),Bh([m(N)],Gn.prototype,"samples",2),Bh([m(N)],Gn.prototype,"color",2),Bh([m(N)],Gn.prototype,"luminanceInfluence",2),rs("ScreenSpaceAmbientOcclusion",Gn);var AA=Object.defineProperty,IA=Object.getOwnPropertyDescriptor,oa=(s,t,i,n)=>{for(var o=n>1?void 0:n?IA(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&AA(t,i,o),o},iy=(s=>(s[s.Performance=0]="Performance",s[s.Low=1]="Low",s[s.Medium=2]="Medium",s[s.High=3]="High",s[s.Ultra=4]="Ultra",s))(iy||{});class Is extends ht{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 re(0,0,0))),a(this,"screenspaceRadius",!1),a(this,"quality",2),a(this,"_ssao")}get typeName(){return"ScreenSpaceAmbientOcclusionN8"}onValidate(){this._ssao&&(this._ssao.setQualityMode(iy[this.quality]),this._ssao.configuration.gammaCorrection=this.gammaCorrection,this._ssao.configuration.screenSpaceRadius=this.screenspaceRadius)}onCreateEffect(){const t=this.context.mainCamera,i=this._ssao=new L.POSTPROCESSING_AO.MODULE.N8AOPostPass(this.context.scene,t,this.context.domWidth,this.context.domHeight),n=iy[this.quality];i.setQualityMode(n),i.configuration.gammaCorrection=this.gammaCorrection,i.configuration.screenSpaceRadius=this.screenspaceRadius,this.intensity.onValueChanged=r=>{i.configuration.intensity=r},this.falloff.onValueChanged=r=>{i.configuration.distanceFalloff=r},this.aoRadius.onValueChanged=r=>{i.configuration.aoRadius=r},this.color.onValueChanged=r=>{i.color||(i.color=new re),i.configuration.color.copy(r)};const o=new Array;return o.push(i),o}}oa([Mt(),m()],Is.prototype,"gammaCorrection",2),oa([m(N)],Is.prototype,"aoRadius",2),oa([m(N)],Is.prototype,"falloff",2),oa([m(N)],Is.prototype,"intensity",2),oa([m(N)],Is.prototype,"color",2),oa([Mt(),m()],Is.prototype,"screenspaceRadius",2),oa([Mt(),m()],Is.prototype,"quality",2),rs("ScreenSpaceAmbientOcclusionN8",Is);var jA=Object.defineProperty,LA=Object.getOwnPropertyDescriptor,v1=(s,t,i,n)=>{for(var o=n>1?void 0:n?LA(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&jA(t,i,o),o};class Fh extends ht{constructor(){super(...arguments),a(this,"_effect"),a(this,"_amount",1),a(this,"_radius",1)}get typeName(){return"Sharpening"}onCreateEffect(){return this._effect??(this._effect=new(DA())),this.effect}get effect(){return this._effect}set amount(t){this._amount=t,this._effect&&(this._effect.uniforms.get("amount").value=t)}get amount(){return this._effect?this._effect.uniforms.get("amount").value:this._amount}set radius(t){this._radius=t,this._effect&&(this._effect.uniforms.get("radius").value=t)}get radius(){return this._effect?this._effect.uniforms.get("radius").value:this._radius}}v1([m()],Fh.prototype,"amount",1),v1([m()],Fh.prototype,"radius",1);function DA(){const s=`
1205
+ `)}l&&r.size&&console.log(p);const f=new Set;for(const w of y){w.getPath||console.error("USDZExporter: Animation target object has no getPath method. This is likely a bug",w);let _=w.getPath();_.startsWith("<")&&(_=_.substring(1)),_.endsWith(">")&&(_=_.substring(0,_.length-1)),f.add({path:_,obj:w})}const v=Array.from(f).sort((w,_)=>w.path.length-_.path.length),b=new Array;for(let w=0;w<v.length;w++)for(let _=w+1;_<v.length;_++)if(v[_].path.startsWith(v[w].path)){const C=v[_],R=v[w];b.push({child:C.obj.displayName+" ("+C.path+")",parent:R.obj.displayName+" ("+R.path+")"})}b.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:b,playAnimationActions:r})}for(const p of new Set([...i,...n]))if(Array.isArray(p))for(const g of p)o.add(g.uuid);else o.add(p.uuid);dp&&console.log("All Behavior trigger sources and action targets",i,n,o),this.targetUuids=new Set(o)}onAfterHierarchy(t,i){var n;if((n=this.behaviours)!=null&&n.length){i.beginBlock('def Scope "Behaviors"');for(const o of this.behaviours)o.writeTo(this,t.document,i);i.closeBlock()}}async onAfterSerialize(t){dp&&console.log("onAfterSerialize behaviours",this.behaviourComponentsCopy);for(const i of this.behaviourComponentsCopy)typeof i.afterSerialize=="function"&&(i.afterSerialize.constructor.name==="AsyncFunction"?await i.afterSerialize(this,t):i.afterSerialize(this,t));for(const{clipUrl:i,filesKey:n}of this.audioClipsCopy){if(t.files[n])return;const o=await(await(await fetch(i)).blob()).arrayBuffer(),r=new Uint8Array(o);t.files[n]=r}this.behaviourComponentsCopy.length=0,this.audioClipsCopy.length=0}}var mT=Object.defineProperty,gT=Object.getOwnPropertyDescriptor,$e=(s,t,i,n)=>{for(var o=n>1?void 0:n?gT(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&mT(t,i,o),o};const Ux=O("debugusdzbehaviours");function ch(s){s&&(s.getComponentInParent(Xa)||(F()&&console.debug('Raycaster on "'+s.name+'" was automatically added, because no raycaster was found in the parent hierarchy.'),s.addComponent(Ei)))}class qr extends A{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 V),a(this,"targetScale",new x)}start(){ch(this.gameObject)}onPointerClick(t){t.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 t=te(this.object).clone(),i=te(this.target).clone(),n=Oe(this.object).clone(),o=Oe(this.target).clone(),r=Je(this.object).clone(),l=Je(this.target).clone(),c=t.distanceTo(i),h=n.angleTo(o),d=r.distanceTo(l);if(c<.01&&h<.01&&d<.01){dt(this.object,i),Gi(this.object,o),Pa(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(t,i,p),this.targetRot.slerpQuaternions(n,o,p),this.targetScale.lerpVectors(r,l,p),dt(this.object,this.targetPos),Gi(this.object,this.targetRot),Pa(this.object,this.targetScale),yield;this.coroutine=null}*moveRelative(){if(!this.target||!this.object)return;const t=this.object.position.clone(),i=this.object.quaternion.clone(),n=this.object.scale.clone(),o=this.target.position.clone(),r=this.target.quaternion.clone(),l=this.target.scale.clone();o.applyQuaternion(this.object.quaternion),this.targetPos.copy(this.object.position).add(o),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(t,this.targetPos,h),this.object.quaternion.slerpQuaternions(i,this.targetRot,h),this.object.scale.lerpVectors(n,this.targetScale,h),yield;this.coroutine=null}beforeCreateDocument(t){var i;if(this.target&&this.object&&this.gameObject){const n=new Tt("Move to "+((i=this.target)==null?void 0:i.name),wt.tapTrigger(this.gameObject),fe.transformAction(this.object,this.target,this.duration,this.relativeMotion?"relative":"absolute"));t.addBehavior(n)}}}$e([m(I)],qr.prototype,"object",2),$e([m(I)],qr.prototype,"target",2),$e([m()],qr.prototype,"duration",2),$e([m()],qr.prototype,"relativeMotion",2);var fl;const ti=(fl=class extends A{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 s;this._objectsWithThisMaterial=this.objectsWithThisMaterial,ch(this.gameObject),F()&&this._objectsWithThisMaterial.length<=0&&console.warn('ChangeMaterialOnClick: No objects found with material "'+((s=this.materialToSwitch)==null?void 0:s.name)+'"')}onPointerEnter(s){this.context.input.setCursor("pointer")}onPointerExit(s){this.context.input.unsetCursor("pointer")}onPointerClick(s){if(s.use(),!!this.variantMaterial)for(let t=0;t<this.objectsWithThisMaterial.length;t++){const i=this.objectsWithThisMaterial[t];i.material=this.variantMaterial}}get objectsWithThisMaterial(){return this._objectsWithThisMaterial!=null?this._objectsWithThisMaterial:(this._objectsWithThisMaterial=[],this.variantMaterial&&this.materialToSwitch&&this.context.scene.traverse(s=>{if(s instanceof K)if(Array.isArray(s.material)){for(const t of s.material)if(t===this.materialToSwitch){this.objectsWithThisMaterial.push(s);break}}else s.material===this.materialToSwitch?this.objectsWithThisMaterial.push(s):m_(s.material,this.materialToSwitch)&&this.objectsWithThisMaterial.push(s)}),this._objectsWithThisMaterial)}async beforeCreateDocument(s,t){this.targetModels=[],ti._materialTriggersPerId={},ti.variantSwitchIndex=0,this.materialToSwitch&&await it.assignTextureLOD(this.materialToSwitch,0),this.variantMaterial&&await it.assignTextureLOD(this.variantMaterial,0)}createBehaviours(s,t,i){this.objectsWithThisMaterial.find(n=>n.uuid===t.uuid)&&this.targetModels.push(t),this.gameObject.uuid===t.uuid&&(this.selfModel=t,this.materialToSwitch&&(ti._materialTriggersPerId[this.materialToSwitch.uuid]||(ti._materialTriggersPerId[this.materialToSwitch.uuid]=[]),ti._materialTriggersPerId[this.materialToSwitch.uuid].push(this)))}afterCreateDocument(s,t){if(!this.materialToSwitch)return;const i=ti._materialTriggersPerId[this.materialToSwitch.uuid];if(i){const n={};for(const o of i){const r=o.createVariants();r&&r.length>0&&(n[o.selfModel.uuid]=r)}for(const o of i){const r=[];for(const l in n)l!==o.selfModel.uuid&&r.push(...n[l]);o.createAndAttachBehaviors(s,n[o.selfModel.uuid],r)}}delete ti._materialTriggersPerId[this.materialToSwitch.uuid]}createAndAttachBehaviors(s,t,i){const n=[],o=Math.max(0,this.fadeDuration);n.push(fe.fadeAction([...this.targetModels,...i],o,!1)),n.push(fe.fadeAction(t,o,!0)),s.addBehavior(new Tt("Select_"+this.selfModel.name,wt.tapTrigger(this.selfModel),fe.parallel(...n))),ti._parallelStartHiddenActions.push(...t),ti._startHiddenBehaviour||(ti._startHiddenBehaviour=new Tt("StartHidden_"+this.selfModel.name,wt.sceneStartTrigger(),fe.fadeAction(ti._parallelStartHiddenActions,o,!1)),s.addBehavior(ti._startHiddenBehaviour))}static getMaterialName(s){return Ts(s.name||"Material")+"_"+s.id}createVariants(){if(!this.variantMaterial)return null;const s=[];for(const t of this.targetModels){const i=t.clone();i.name+="_Variant_"+ti.variantSwitchIndex+++"_"+ti.getMaterialName(this.variantMaterial),i.displayName=i.displayName+": Variant with material "+this.variantMaterial.name,i.material=this.variantMaterial,i.geometry=t.geometry,i.transform=t.transform,(!t.parent||!t.parent.isEmpty())&&Zt.createEmptyParent(t),t.parent&&t.parent.add(i),s.push(i)}return s}},a(fl,"_materialTriggersPerId",{}),a(fl,"_startHiddenBehaviour",null),a(fl,"_parallelStartHiddenActions",[]),a(fl,"variantSwitchIndex",0),fl);let yl=ti;$e([m(ke)],yl.prototype,"materialToSwitch",2),$e([m(ke)],yl.prototype,"variantMaterial",2),$e([m()],yl.prototype,"fadeDuration",2);var vl;const qe=(vl=class extends A{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(){ch(this.gameObject)}onPointerClick(s){s.use(),!this.toggleOnClick&&this.hideSelf&&(this.gameObject.visible=!1),this.target&&(this.target.visible=this.toggleOnClick?!this.target.visible:this.targetState)}createBehaviours(s,t,i){t.uuid===this.gameObject.uuid&&(this.selfModel=t,this.selfModelClone=t.clone())}beforeCreateDocument(){this.target&&(this.gameObject[qe.wasVisible]===void 0&&(this.gameObject[qe.wasVisible]=this.gameObject.activeSelf),this.target[qe.wasVisible]===void 0&&(this.target[qe.wasVisible]=this.target.activeSelf),this.stateBeforeCreatingDocument=this.gameObject[qe.wasVisible],this.targetStateBeforeCreatingDocument=this.target[qe.wasVisible],this.gameObject.visible=!0,this.target.visible=!0)}afterCreateDocument(s,t){if(!this.target)return;this.targetModel=t.document.findById(this.target.uuid);const i=this.selfModel;if(this.selfModel&&this.targetModel){let n=this.selfModel,o=this.targetState;if(this.toggleOnClick)if(o=!this.targetStateBeforeCreatingDocument,!this.selfModelClone.geometry)(!this.selfModel.parent||this.selfModel.parent.isEmpty())&&Zf.createEmptyParent(this.selfModel),this.toggleModel=this.selfModel.deepClone(),this.toggleModel.name+="_toggle",this.selfModel.parent.add(this.toggleModel);else{if(!this.gameObject[qe.toggleClone]){const c=this.selfModelClone.clone();c.setMatrix(new ne),c.name+="_toggle"+qe.clonedToggleIndex++,i.add(c),this.gameObject[qe.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[qe.toggleClone];if(!this.gameObject[qe.reverseToggleClone]){const c=this.selfModelClone.clone();c.setMatrix(new ne),c.name+="_toggleReverse"+qe.clonedToggleIndex++,i.add(c),this.gameObject[qe.reverseToggleClone]=c}this.toggleModel=this.gameObject[qe.reverseToggleClone],(!this.toggleModel.geometry||!l.geometry)&&console.error("triggers without childs and without geometry won't work!",this,i.geometry),n=l,i.geometry=null,i.material=null}if(this.toggleModel){if(this.toggleOnClick){const l=[];l.push(fe.fadeAction(n,0,!1)),l.push(fe.fadeAction(this.toggleModel,0,!0)),l.push(fe.fadeAction(this.targetModel,0,o)),s.addBehavior(new Tt("Toggle_"+n.name+"_ToggleTo"+(o?"On":"Off"),wt.tapTrigger(n),fe.parallel(...l)));const c=[];c.push(fe.fadeAction(this.toggleModel,0,!1)),c.push(fe.fadeAction(n,0,!0)),c.push(fe.fadeAction(this.targetModel,0,!o)),s.addBehavior(new Tt("Toggle_"+n.name+"_ToggleTo"+(o?"Off":"On"),wt.tapTrigger(this.toggleModel),fe.parallel(...c)))}}else{const l=[];this.hideSelf&&l.push(fe.fadeAction(n,0,!1)),l.push(fe.fadeAction(this.targetModel,0,o)),s.addBehavior(new Tt("Toggle_"+n.name+"_ToggleTo"+(o?"On":"Off"),wt.tapTrigger(n),l.length>1?fe.parallel(...l):l[0]))}const r=new Array;this.targetStateBeforeCreatingDocument||r.push(this.targetModel),this.stateBeforeCreatingDocument||r.push(i),this.toggleModel&&r.push(this.toggleModel),bl.add(r,s)}}afterSerialize(s,t){this.gameObject[qe.wasVisible]!==void 0&&(this.gameObject.visible=this.gameObject[qe.wasVisible],delete this.gameObject[qe.wasVisible]),this.target&&this.target[qe.wasVisible]!==void 0&&(this.target.visible=this.target[qe.wasVisible],delete this.target[qe.wasVisible]),delete this.gameObject[qe.toggleClone],delete this.gameObject[qe.reverseToggleClone]}},a(vl,"clonedToggleIndex",0),a(vl,"wasVisible",Symbol("usdz_SetActiveOnClick_wasVisible")),a(vl,"toggleClone",Symbol("clone for toggling")),a(vl,"reverseToggleClone",Symbol("clone for reverse toggling")),vl);let Gr=qe;$e([m(I)],Gr.prototype,"target",2),$e([m()],Gr.prototype,"toggleOnClick",2),$e([m()],Gr.prototype,"targetState",2),$e([m()],Gr.prototype,"hideSelf",2);const Do=class extends A{constructor(){super(...arguments),a(this,"wasVisible",!1)}static add(s,t){const i=Array.isArray(s)?s:[s];for(const n of i)Do._fadeObjects.includes(n)||(console.log("adding hide on start",n),Do._fadeObjects.push(n));Do._fadeBehaviour===void 0&&(Do._fadeBehaviour=new Tt("HideOnStart",wt.sceneStartTrigger(),fe.fadeAction(Do._fadeObjects,0,!1)),t.addBehavior(Do._fadeBehaviour))}start(){P.setActive(this.gameObject,!1)}createBehaviours(s,t,i){t.uuid===this.gameObject.uuid&&(this.wasVisible||Do.add(t,s))}beforeCreateDocument(){this.wasVisible=P.isActiveSelf(this.gameObject)}};let bl=Do;a(bl,"_fadeBehaviour"),a(bl,"_fadeObjects",[]);class _l extends A{constructor(){super(...arguments),a(this,"target"),a(this,"duration",.5),a(this,"motionType","bounce")}beforeCreateDocument(){}createBehaviours(t,i,n){if(this.target&&i.uuid===this.gameObject.uuid){const o=new Tt("emphasize "+this.name,wt.tapTrigger(this.gameObject),fe.emphasize(this.target,this.duration,this.motionType,void 0,"basic"));t.addBehavior(o)}}afterCreateDocument(t,i){}}$e([m()],_l.prototype,"target",2),$e([m()],_l.prototype,"duration",2),$e([m()],_l.prototype,"motionType",2);class Bo extends A{constructor(){super(...arguments),a(this,"target"),a(this,"clip",""),a(this,"toggleOnClick",!1),a(this,"trigger","tap")}start(){ch(this.gameObject)}ensureAudioSource(){if(!this.target){const t=this.gameObject.addComponent(We);t&&(this.target=t,t.spatialBlend=1,t.volume=1,t.loop=!1,t.preload=!0)}}onPointerClick(t){var i;t.use(),!(!((i=this.target)!=null&&i.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(t,i,n){if(!(!this.target&&!this.clip)&&i.uuid===this.gameObject.uuid){const o=this.clip?this.clip:this.target?this.target.clip:void 0;if(!o||typeof o!="string")return;const r=this.target?this.target.gameObject:this.gameObject;dr.getName(o);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 K&&g.visible&&(h=!0)}),h=!0;const d=t.addAudioClip(o);let u=fe.playAudioAction(r,d,"play",l,c);this.target&&this.target.loop&&(u=fe.sequence(u).makeLooping());const p=this.name?"_"+this.name:"";if(h&&this.trigger==="tap"){this.toggleOnClick&&(u.multiplePerformOperation="stop");const g=new Tt("playAudio"+p,wt.tapTrigger(i),u);t.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 Tt("playAudioOnStart"+p,wt.sceneStartTrigger(),u);t.addBehavior(g)}}}}$e([m(We)],Bo.prototype,"target",2),$e([m(URL)],Bo.prototype,"clip",2),$e([m()],Bo.prototype,"toggleOnClick",2);var pp;const nn=(pp=class extends A{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 s,t;return((s=this.animator)==null?void 0:s.gameObject)||((t=this.animation)==null?void 0:t.gameObject)}start(){ch(this.gameObject)}onPointerClick(s){var t;s.use(),this.target&&this.stateName&&((t=this.animator)==null||t.play(this.stateName,0,0,.1))}createBehaviours(s,t,i){t.uuid===this.gameObject.uuid&&(this.selfModel=t)}afterSerialize(){if(nn.rootsWithExclusivePlayback.size>1){const s='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()&&xe(s),console.warn(s,...nn.rootsWithExclusivePlayback)}nn.animationActions=[],nn.rootsWithExclusivePlayback=new Set}afterCreateDocument(s,t){if(this.animationSequence===void 0&&this.animationLoopAfterSequence===void 0||!this.stateAnimationModel||!this.target)return;const i=t.document,n=t.extensions.find(l=>l instanceof lh);if(!n)return;const o=n.getClipCount(this.target)>1;o&&(F()&&console.warn("Setting exclusive playback for "+this.target.name+"@"+this.stateName+" because it has "+n.getClipCount(this.target)+" animations. This works around QuickLook bug FB13410767."),nn.rootsWithExclusivePlayback.add(this.target));const r=this.name?this.name:"";i.traverse(l=>{var c,h;if(l.uuid===((c=this.target)==null?void 0:c.uuid)){const d=nn.getActionForSequences(i,l,this.animationSequence,this.animationLoopAfterSequence,this.randomOffsetNormalized),u=new Tt(this.trigger+"_"+r+"_toPlayAnimation_"+this.stateName+"_on_"+((h=this.target)==null?void 0:h.name),this.trigger=="tap"?wt.tapTrigger(this.selfModel):wt.sceneStartTrigger(),d);o&&u.makeExclusive(!0),s.addBehavior(u)}})}static getActionForSequences(s,t,i,n,o){const r=(c,h)=>{let d=nn.animationActions.find(u=>u.affectedObjects==c&&u.start==h.start&&u.duration==h.duration&&u.animationSpeed==h.speed);return d||(d=fe.startAnimationAction(c,h),nn.animationActions.push(d)),d},l=fe.sequence();if(i&&i.length>0)for(const c of i)l.addAction(r(t,c));if(n&&n.length>0){const c=l.actions.length==0?l:fe.sequence();for(const h of n)c.addAction(r(t,h));c.makeLooping(),l!==c&&l.addAction(c)}return o&&o>0&&l.actions.unshift(fe.waitAction(o)),l}static getAndRegisterAnimationSequences(s,t,i){var n,o,r,l,c,h,d,u;if(!t)return;const p=t.getComponent(kt),g=t.getComponent(Wt);if(!p&&!g)return;if(p&&!i)throw new Error("PlayAnimationOnClick: No stateName specified for animator "+p.name+" on "+t.name);let y=[],f=[];if(g){const M=s.registerAnimation(t,g.clip);M&&(g.loop?f.push(M):y.push(M));let T=0;if(g.minMaxOffsetNormalized){const j=g.minMaxOffsetNormalized.x,D=g.minMaxOffsetNormalized.y;T=(((n=g.clip)==null?void 0:n.duration)||1)*(j+Math.random()*(D-j))}return{animationSequence:y,animationLoopAfterSequence:f,randomTimeOffset:T}}const v=p?.runtimeAnimatorController;let b=v?.findState(i),w=[],_=[];if(v&&b){const M=new Array;M.push(b);let T=!1;for(;M.length<100;){if(!b||b===null||!b.transitions||b.transitions.length===0){(o=b.motion)!=null&&o.isLooping&&(T=!0);break}const j=b.transitions.find(U=>U.conditions.length===0),D=j?v.getState(j.destinationState,0):null;if(D&&M.includes(D)){b=D,T=!0;break}else if(j){if(b=D,!b)break;M.push(b)}else{T=((r=b.motion)==null?void 0:r.isLooping)??!1;break}}if(T&&b){const j=M.indexOf(b);w=M.slice(0,j),_=M.slice(j),Ux&&console.log("found loop from "+i,"states until loop",w,"states looping",_)}else w=M,_=[],Ux&&console.log("found no loop from "+i,"states",w);if(!_.length){const j=w[w.length-1],D=(l=j.motion)==null?void 0:l.clip;if(D){let U;if(s.holdClipMap.has(D))U=s.holdClipMap.get(D);else{const B=j.name+"_hold";U=D.clone(),U.duration=1,U.name=B;const Y=D.duration;U.tracks=D.tracks.map($=>{const E=$.clone();E.times=new Float32Array([0,Y]);const z=$.values.length,H=$.getValueSize(),se=$.values.slice(z-H,z);return E.values=new Float32Array(2*H),E.values.set(se,0),E.values.set(se,H),E}),U.name=B,s.holdClipMap.set(D,U)}if(U){const B={name:U.name,motion:{clip:U,isLooping:!1,name:U.name},speed:1,transitions:[],behaviours:[],hash:j.hash+1};_.push(B)}}}}if(w.length===1&&(!((c=w[0].motion)!=null&&c.clip)||((d=(h=w[0].motion)==null?void 0:h.clip.tracks)==null?void 0:d.length)===0)){y=new Array;const M=s.registerAnimation(t,null);M&&y.push(M);return}if(w=w.filter(M=>{var T,j,D;return((T=M.motion)==null?void 0:T.clip)&&((D=(j=M.motion)==null?void 0:j.clip.tracks)==null?void 0:D.length)>0}),_=_.filter(M=>{var T,j,D;return((T=M.motion)==null?void 0:T.clip)&&((D=(j=M.motion)==null?void 0:j.clip.tracks)==null?void 0:D.length)>0}),w.length===0&&_.length===0){console.warn("No clips found for state "+i+" on "+p?.name+", can't export animation data");return}const C=(M,T)=>{if(!t)return;const j=s.registerAnimation(t,M.motion.clip??null);j?(j.speed=M.speed,T.push(j)):console.warn("Couldn't register animation for state "+M.name+" on "+p?.name)};if(w.length>0){y=new Array;for(const M of w)C(M,y)}if(_.length>0){f=new Array;for(const M of _)C(M,f)}let R=0;if(p&&v&&p.minMaxOffsetNormalized){const M=p.minMaxOffsetNormalized.x,T=p.minMaxOffsetNormalized.y,j=w.length?w[0]:_.length?_[0]:null;R=(((u=j?.motion.clip)==null?void 0:u.duration)||1)*(M+Math.random()*(T-M))}return{animationSequence:y,animationLoopAfterSequence:f,randomTimeOffset:R}}createAnimation(s,t,i){if(!this.target||!this.animator&&!this.animation)return;const n=nn.getAndRegisterAnimationSequences(s,this.target,this.stateName);n&&(this.animationSequence=n.animationSequence,this.animationLoopAfterSequence=n.animationLoopAfterSequence,this.randomOffsetNormalized=n.randomTimeOffset,this.stateAnimationModel=t)}},a(pp,"animationActions",[]),a(pp,"rootsWithExclusivePlayback",new Set),pp);let Xr=nn;$e([m(kt)],Xr.prototype,"animator",2),$e([m()],Xr.prototype,"stateName",2);class wl extends A{constructor(){super(...arguments),a(this,"target")}getType(){}getDuration(){}}$e([m(I)],wl.prototype,"target",2);class hh extends A{constructor(){super(...arguments),a(this,"target")}}$e([m(wl)],hh.prototype,"target",2);class dh extends wl{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}}$e([m()],dh.prototype,"type",2),$e([m()],dh.prototype,"duration",2);class d0 extends hh{}class mp{get extensionName(){return"Physics"}onExportObject(t,i,n){const o=P.getComponents(t,ve).filter(h=>h.enabled),r=P.getComponents(t,pi).filter(h=>h.enabled&&!h.isTrigger);let l=o.length>0?o[0]:null;const c=r.length>0?r[0]:null;c&&!l&&(l=new ve,l.isKinematic=!0),l&&i.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 y=r[0];h.beginBlock('def RealityKitStruct "material"',"{",!0);const f=y.sharedMaterial;f&&f.dynamicFriction!==void 0&&h.appendLine(`double dynamicFriction = ${(u=y.sharedMaterial)==null?void 0:u.dynamicFriction}`),f&&f.bounciness!==void 0&&h.appendLine(`double restitution = ${(p=y.sharedMaterial)==null?void 0:p.bounciness}`),f&&f.staticFriction!==void 0&&h.appendLine(`double staticFriction = ${(g=y.sharedMaterial)==null?void 0:g.staticFriction}`),h.closeBlock("}")}h.closeBlock("}")}}),c&&(i.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 tl){const g=c;h.appendLine('token shapeType = "Sphere"'),h.appendLine(`float radius = ${g.radius}`)}else if(c instanceof il){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 In){const g=c;h.appendLine('token shapeType = "Capsule"'),h.appendLine(`float radius = ${g.radius}`),h.appendLine(`float height = ${g.height}`)}else if(c instanceof Io&&(u=c.sharedMesh)!=null&&u.geometry){const g=c.sharedMesh.geometry;g.boundingBox||g.computeBoundingBox();const y=c.sharedMesh.geometry.boundingBox;y&&(h.appendLine('token shapeType = "Box"'),h.appendLine(`float3 extent = (${y.max.x-y.min.x}, ${y.max.y-y.min.y}, ${y.max.z-y.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))}}class u0{get extensionName(){return"DocumentExtension"}onAfterBuildDocument(t){}}var fT=Object.defineProperty,yT=Object.getOwnPropertyDescriptor,uh=(s,t,i,n)=>{for(var o=n>1?void 0:n?yT(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&fT(t,i,o),o};const p0=O("debugui"),m0=O("debuguilayout");class g0{constructor(){a(this,"width"),a(this,"height")}}class f0{constructor(){a(this,"x"),a(this,"y"),a(this,"width"),a(this,"height")}}const Es=new x,ph=new ne,gp=new V,Nx=class extends ls{constructor(){super(...arguments),a(this,"_anchoredPosition"),a(this,"sizeDelta",new oe(100,100)),a(this,"pivot",new oe(.5,.5)),a(this,"anchorMin",new oe(0,0)),a(this,"anchorMax",new oe(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 oe),this._anchoredPosition}set anchoredPosition(s){this._anchoredPosition=s}get width(){let s=this.sizeDelta.x;if(this.anchorMin.x!==this.anchorMax.x&&this._parentRectTransform){const t=this._parentRectTransform.width,i=this.anchorMax.x-this.anchorMin.x;s=t*i,s+=this.sizeDelta.x}return this.minWidth!==void 0&&s<this.minWidth?this.minWidth:s}get height(){let s=this.sizeDelta.y;if(this.anchorMin.y!==this.anchorMax.y&&this._parentRectTransform){const t=this._parentRectTransform.height,i=this.anchorMax.y-this.anchorMin.y;s=t*i,s+=this.sizeDelta.y}return this.minHeight!==void 0&&s<this.minHeight?this.minHeight:s}awake(){super.awake(),this._anchoredPosition||(this._anchoredPosition=new oe),this.lastMatrix=new ne,this.rectBlock=new I,this.rectBlock.name=this.name,this._initialPosition=this.gameObject.position.clone(),this._initialPosition.z=0,Ya(this,"_anchoredPosition",()=>{this.markDirty()}),Ya(this,"sizeDelta",()=>{this.markDirty()}),Ya(this,"pivot",()=>{this.markDirty()}),Ya(this,"anchorMin",()=>{this.markDirty()}),Ya(this,"anchorMax",()=>{this.markDirty()})}onEnable(){var s;super.onEnable(),this.rectBlock||(this.rectBlock=new I),this.lastMatrix||(this.lastMatrix=new ne),this._lastAnchoring||(this._lastAnchoring=new oe),this._initialPosition||(this._initialPosition=new x),this._anchoredPosition||(this._anchoredPosition=new oe),this.addShadowComponent(this.rectBlock),this._transformNeedsUpdate=!0,(s=this.canvas)==null||s.registerTransform(this)}onDisable(){var s;super.onDisable(),this.removeShadowComponent(),(s=this.canvas)==null||s.unregisterTransform(this)}onParentRectTransformChanged(s){this._transformNeedsUpdate||this.onApplyTransform(m0?`${s.name} changed`:void 0)}get isDirty(){return this._transformNeedsUpdate||(this._transformNeedsUpdate=!this.lastMatrix.equals(this.gameObject.matrix)),this._transformNeedsUpdate}markDirty(){this._transformNeedsUpdate||(m0&&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(s){var t;if(this.context.time.frameCount===this._lastUpdateFrame)return;this._lastUpdateFrame=this.context.time.frameCount;const i=this.shadowComponent;if(!i)return;this.gameObject.parent?this._parentRectTransform=P.getComponentInParent(this.gameObject.parent,Nx):this._parentRectTransform=void 0,this._transformNeedsUpdate=!1,m0&&console.warn("RectTransform \u2192 ApplyTransform",this.name+" because "+s),this.isRoot()?this.Root.screenspace||(i.rotation.y=Math.PI):(i.matrix.identity(),i.matrixAutoUpdate=!1,Es.set(0,0,0),this.applyPivot(Es),i.matrix.setPosition(Es.x,Es.y,0),(this.gameObject.quaternion.x||this.gameObject.quaternion.y||this.gameObject.quaternion.z)&&(gp.copy(this.gameObject.quaternion),gp.x*=-1,gp.z*=-1,ph.makeRotationFromQuaternion(gp),i.matrix.premultiply(ph)),Es.set(0,0,0),this.applyAnchoring(Es),(t=this.canvas)!=null&&t.screenspace?Es.z+=.1:Es.z+=.01,ph.identity(),ph.setPosition(Es.x,Es.y,Es.z),i.matrix.premultiply(ph),i.matrix.scale(this.gameObject.scale)),this.lastMatrix.copy(this.gameObject.matrix);const n=!0;for(const o of ou(this.gameObject,ls,n,1)){if(o===this||!o.activeAndEnabled)continue;const r=o;r.onParentRectTransformChanged&&r.onParentRectTransformChanged(this)}}applyAnchoring(s){this._lastAnchoring||(this._lastAnchoring=new oe);const t=this._lastAnchoring.sub(this._anchoredPosition);this.gameObject.position.x+=t.x,this.gameObject.position.y+=t.y,this._lastAnchoring.copy(this._anchoredPosition),s.x+=this._initialPosition.x-this.gameObject.position.x,s.y+=this._initialPosition.y-this.gameObject.position.y,s.z+=this._initialPosition.z-this.gameObject.position.z;const i=this._parentRectTransform;if(i){let n=0;const o=1-this.anchorMax.y-this.anchorMin.y;n-=i.height*.5*o,s.y+=n;let r=0;const l=1-this.anchorMax.x-this.anchorMin.x;r-=i.width*.5*l,s.x+=r}}applyPivot(s){if(this.pivot&&!this.isRoot()){const t=this.pivot.x-.5;s.x-=t*this.sizeDelta.x*this.gameObject.scale.x;const i=this.pivot.y-.5;s.y-=i*this.sizeDelta.y*this.gameObject.scale.y}}getBasicOptions(){const s={width:this.sizeDelta.x,height:this.sizeDelta.y,offset:0,backgroundOpacity:0,borderWidth:0,borderRadius:0,borderOpacity:0,letterSpacing:-.03};return this.ensureValidSize(s),s}ensureValidSize(s,t=1e-4){return s.width<=0&&(s.width=t),s.height<=0&&(s.height=1e-4),s}createNewBlock(s){s={...this.getBasicOptions(),...s},p0&&console.log(this.name,s);const t=new yv(s);return this._createdBlocks.push(t),t}createNewText(s){p0&&console.log(s),s={...this.getBasicOptions(),...s},p0&&console.log(this.name,s);const t=new fv(s);return this._createdTextBlocks.push(t),t}};let Ht=Nx;uh([m(oe)],Ht.prototype,"anchoredPosition",1),uh([m(oe)],Ht.prototype,"sizeDelta",2),uh([m(oe)],Ht.prototype,"pivot",2),uh([m(oe)],Ht.prototype,"anchorMin",2),uh([m(oe)],Ht.prototype,"anchorMax",2);var vT=Object.defineProperty,bT=Object.getOwnPropertyDescriptor,Wx=(s,t,i,n)=>{for(var o=n>1?void 0:n?bT(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&vT(t,i,o),o};class xl extends A{constructor(){super(...arguments),a(this,"effectColor"),a(this,"effectDistance")}}Wx([m(Se)],xl.prototype,"effectColor",2),Wx([m(oe)],xl.prototype,"effectDistance",2);var _T=Object.defineProperty,wT=Object.getOwnPropertyDescriptor,Vx=(s,t,i,n)=>{for(var o=n>1?void 0:n?wT(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&_T(t,i,o),o};const fp={backgroundColor:new re(1,1,1),backgroundOpacity:1,borderColor:new re(1,1,1),borderOpacity:1};var y0;const mh=(y0=class extends ls{constructor(){super(...arguments),a(this,"_alphaFactor",1),a(this,"sRGBColor",new re(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 Se(1,1,1,1)),this._color}set color(s){(!this._color||this._color.r!==s.r||this._color.g!==s.g||this._color.b!==s.b||this._color.alpha!==s.alpha)&&(this._color||(this._color=new Se(1,1,1,1)),this._color.copy(s),this.onColorChanged())}setAlphaFactor(s){this._alphaFactor=s,this.onColorChanged()}get alphaFactor(){return this._alphaFactor}onColorChanged(){this.uiObject&&(this.sRGBColor.copy(this._color),this.sRGBColor.convertLinearToSRGB(),fp.backgroundColor=this.sRGBColor,fp.backgroundOpacity=this._color.alpha*this._alphaFactor,this.applyEffects(fp,this._alphaFactor),this.uiObject.set(fp),this.markDirty())}get m_Color(){return this._color}get rectTransform(){if(this._rect||(this._rect=P.getComponent(this.gameObject,Ht)),!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 s;(s=this.uiObject)==null||s.set({width:this.rectTransform.width,height:this.rectTransform.height}),this.markDirty()}__internalNewInstanceCreated(s){return super.__internalNewInstanceCreated(s),this._rect=null,this.uiObject=null,this._color&&(this._color=this._color.clone()),this}setState(s){this.makePanel(),this.uiObject&&(this.uiObject.setState(s),this==null||this.markDirty())}setupState(s){this.makePanel(),this.uiObject&&(this._stateManager||(this._stateManager=new cO(this.uiObject)),this.uiObject.setupState(s.state,s.attributes))}setOptions(s){this.makePanel(),this.uiObject&&this.uiObject.set(s)}awake(){super.awake(),this.makePanel(),Ya(this,"_color",()=>vM(this,this.onColorChanged))}onEnable(){var s;super.onEnable(),this.uiObject&&((s=this.rectTransform.shadowComponent)==null||s.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 s=.015,t={backgroundColor:this.color,backgroundOpacity:this.color.alpha,offset:s};this.onBeforeCreate(t),this.applyEffects(t),this.onCreate(t),this.controlsChildLayout=!1,this._currentlyCreatingPanel=!1,this.onAfterCreated(),this.onColorChanged()}onBeforeCreate(s){}onCreate(s){this.uiObject=this.rectTransform.createNewBlock(s),this.uiObject.name=this.name}onAfterCreated(){}applyEffects(s,t=1){var i;const n=(i=this.gameObject)==null?void 0:i.getComponent(xl);n&&(n.effectDistance&&(s.borderWidth=Math.max(Math.abs(n.effectDistance.x),Math.abs(n.effectDistance.y))),n.effectColor&&(s.borderColor=n.effectColor,s.borderOpacity=n.effectColor.alpha*t))}async setTexture(s){if(this.setOptions({backgroundOpacity:0}),s){if(mh.textureCache.has(s))s=mh.textureCache.get(s);else if(!s.isRenderTargetTexture){const t=s.clone();t.colorSpace=mr,mh.textureCache.set(s,t),s=t}this.setOptions({backgroundImage:s,borderRadius:0,backgroundOpacity:this.color.alpha,backgroundSize:"stretch"}),it.assignTextureLOD(s,0).then(t=>{t instanceof Le&&(s&&mh.textureCache.set(s,t),this.setOptions({backgroundImage:t}),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(y0,"textureCache",new Map),y0);let Qr=mh;Vx([m(Se)],Qr.prototype,"color",1),Vx([m()],Qr.prototype,"raycastTarget",2);class gh extends Qr{constructor(){super(...arguments),a(this,"_flippedObject",!1)}onAfterCreated(){this.uiObject&&!this._flippedObject&&(this._flippedObject=!0,this.uiObject.scale.y*=-1)}}var xT=Object.defineProperty,ST=Object.getOwnPropertyDescriptor,Wn=(s,t,i,n)=>{for(var o=n>1?void 0:n?ST(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&xT(t,i,o),o};const Yr=O("debugtext");var mt=(s=>(s[s.UpperLeft=0]="UpperLeft",s[s.UpperCenter=1]="UpperCenter",s[s.UpperRight=2]="UpperRight",s[s.MiddleLeft=3]="MiddleLeft",s[s.MiddleCenter=4]="MiddleCenter",s[s.MiddleRight=5]="MiddleRight",s[s.LowerLeft=6]="LowerLeft",s[s.LowerCenter=7]="LowerCenter",s[s.LowerRight=8]="LowerRight",s))(mt||{}),Hx=(s=>(s[s.Normal=0]="Normal",s[s.Bold=1]="Bold",s[s.Italic=2]="Italic",s[s.BoldAndItalic=3]="BoldAndItalic",s))(Hx||{});class $t extends Qr{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 re(1,0,1)),a(this,"_text",""),a(this,"_fontSize",12),a(this,"_textMeshUi",null),a(this,"_didHandleTextRenderOnTop",!1)}setAlphaFactor(t){var i;super.setAlphaFactor(t),(i=this.uiObject)==null||i.set({fontOpacity:this.color.alpha*this.alphaFactor}),this.markDirty()}get text(){return this._text}set text(t){t!==this._text&&(this._text=t,this.feedText(this.text,this.supportRichText),this.markDirty())}set_text(t){this.text=t}get fontSize(){return this._fontSize}set fontSize(t){var i;this._fontSize=t,(i=this.uiObject)==null||i.set({fontSize:t})}onColorChanged(){var t;this.sRGBTextColor.copy(this.color),this.sRGBTextColor.convertLinearToSRGB(),(t=this.uiObject)==null||t.set({color:this.sRGBTextColor,fontOpacity:this.color.alpha})}onParentRectTransformChanged(){super.onParentRectTransformChanged(),this.uiObject&&this.updateOverflow()}onBeforeCanvasRender(t){this.updateOverflow()}updateOverflow(){var t;const i=(t=this.uiObject)==null?void 0:t._overflow;i&&(i._needsUpdate=!0)}onCreate(t){Yr&&console.log(this),this.horizontalOverflow==1&&(t.whiteSpace="pre"),this.verticalOverflow==0&&(this.context.renderer.localClippingEnabled=!0,t.overflow="hidden"),this.horizontalOverflow==1&&this.verticalOverflow==0,t.lineHeight=this.lineSpacing,delete t.backgroundOpacity,delete t.backgroundColor,Yr&&(t.backgroundColor=16750848,t.backgroundOpacity=.5);const i=this.rectTransform;t={...t,...this.getTextOpts()},this.getAlignment(t),Yr&&(t.backgroundColor=Math.random()*16777215,t.backgroundOpacity=.1),this.uiObject=i.createNewText(t),this.feedText(this.text,this.supportRichText)}onAfterAddedToScene(){super.onAfterAddedToScene(),this.handleTextRenderOnTop()}getTextOpts(){const t=this.fontSize,i={color:this.color,fontOpacity:this.color.alpha,fontSize:t,fontKerning:"normal"};return this.setFont(i,this.fontStyle),i}onEnable(){var t;super.onEnable(),this._didHandleTextRenderOnTop=!1,this.uiObject&&this.uiObject.addAfterUpdate(()=>{this.setShadowComponentOwner(this.uiObject),this.markDirty()}),setTimeout(()=>this.markDirty(),10),(t=this.canvas)==null||t.registerEventReceiver(this)}onDisable(){var t;super.onDisable(),(t=this.canvas)==null||t.unregisterEventReceiver(this)}getAlignment(t){switch(t.flexDirection="column",this.alignment){case 0:case 3:case 6:t.textAlign="left";break;case 1:case 4:case 7:t.textAlign="center";break;case 2:case 5:case 8:t.textAlign="right";break}switch(this.alignment){default:case 0:case 1:case 2:t.alignItems="start";break;case 3:case 4:case 5:t.alignItems="center";break;case 6:case 7:case 8:t.alignItems="end";break}return t}feedText(t,i){var n,o,r;if(Yr&&console.log("feedText",this.uiObject,t,i),!!this.uiObject)if(this._textMeshUi||(this._textMeshUi=[]),this.uiObject.children.length=0,!i||t.length===0)this.uiObject.textContent=t;else{let l=this.getNextTag(t);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 Pm({textContent:t.substring(0,l.startIndex),color:"inherit"});this.uiObject.add(h)}}else{this.uiObject.textContent="",this.setOptions({textContent:t});return}const c=[];for(;l;){const h=this.getNextTag(t,l.endIndex),d={fontFamily:(n=this.uiObject)==null?void 0:n.get("fontFamily"),color:"inherit",textContent:""};if(h){d.textContent=this.getText(t,l,h),this.handleTag(l,d,c);const u=new Pm(d);(o=this.uiObject)==null||o.add(u)}else{d.textContent=t.substring(l.endIndex),this.handleTag(l,d,c);const u=new Pm(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 t=[],i=this.canvas,n={renderOnTop:i.renderOnTop,depthWrite:i.depthWrite,doubleSided:i.doubleSided};for(;;){let o=!1;if(this._textMeshUi)for(let r=0;r<this._textMeshUi.length;r++){if(t[r]===!0)continue;o=!0;const l=this._textMeshUi[r];l.textContent&&(Du(l,n),t[r]=!0)}if(!o)break;yield}}handleTag(t,i,n){if(!t.isEndTag){if(t.type.includes("color")){const o=new v0(t,{color:i.color});if(n.push(o),t.type.length>6){const r=parseInt("0x"+t.type.substring(7));i.color=r}else i.color=new re(1,1,1)}else if(t.type=="b"){this.setFont(i,1);const o=new v0(t,{fontWeight:700});n.push(o)}else if(t.type=="i"){this.setFont(i,2);const o=new v0(t,{fontStyle:"italic"});n.push(o)}}}getText(t,i,n){return t.substring(i.endIndex,n.startIndex)}getNextTag(t,i=0){const n=t.indexOf("<",i),o=t.indexOf(">",n);if(n>=0&&o>=0){const r=t.substring(n+1,o);return{type:r,startIndex:n,endIndex:o+1,isEndTag:r.startsWith("/")}}return null}setFont(t,i){if(!this.font)return;const n=this.font,o=this.getFamilyNameWithCorrectSuffix(n,i);Yr&&console.log("Selected font family:"+o);let r=vv.getFontFamily(o);switch(r||(r=vv.addFontFamily(o)),t.fontFamily=r,i){default:case 0:t.fontWeight=400,t.fontStyle="normal";break;case 1:t.fontWeight=700,t.fontStyle="normal";break;case 2:t.fontWeight=400,t.fontStyle="italic";break;case 3:t.fontStyle="italic",t.fontWeight=400}let l=r.getVariant(t.fontWeight,t.fontStyle);if(!l){let c=o;c!=null&&c.endsWith("-msdf.json")||(c+="-msdf.json");let h=o;h!=null&&h.endsWith(".png")||(h+=".png"),l=r.addVariant(t.fontWeight,t.fontStyle,c,h),l?.addEventListener("ready",()=>{this.markDirty()})}}getFamilyNameWithCorrectSuffix(t,i){var n;const o=t.lastIndexOf("-");if(o<0)return t;const r=(n=t.substring(o+1))==null?void 0:n.toLowerCase();if(CT.includes(r))return Yr&&console.warn("Unsupported font style: "+r),t;const l=t.lastIndexOf("/");let c=t;l>=0&&(c=c.substring(l+1));const h=c[0]===c[0].toUpperCase(),d=t.substring(0,o);switch(Yr&&console.log("Select font: ",t,Hx[i],c,h,d),i){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 t}}}Wn([m()],$t.prototype,"alignment",2),Wn([m()],$t.prototype,"verticalOverflow",2),Wn([m()],$t.prototype,"horizontalOverflow",2),Wn([m()],$t.prototype,"lineSpacing",2),Wn([m()],$t.prototype,"supportRichText",2),Wn([m(URL)],$t.prototype,"font",2),Wn([m()],$t.prototype,"fontStyle",2),Wn([m()],$t.prototype,"text",1),Wn([m()],$t.prototype,"fontSize",1);class v0{constructor(t,i){a(this,"tag"),a(this,"previousValues"),this.tag=t,this.previousValues=i}}const CT=["medium","mediumitalic","black","blackitalic","thin","thinitalic","extrabold","light","lightitalic","semibold"];class Fo{constructor(t){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=t}static getId(){return this.global_id++}setDepth(t){return this.depth=t,this}setPointSize(t){return this.pointSize=t,this}setHorizontalAlignment(t){return this.horizontalAlignment=t,this}setVerticalAlignment(t){return this.verticalAlignment=t,this}writeTo(t,i){var n;i.beginBlock(`def Preliminary_Text "${this.id}"`,"(",!1),i.appendLine('prepend apiSchemas = ["MaterialBindingAPI"]'),i.closeBlock(")"),i.beginBlock(),this.content&&i.appendLine(`string content = "${this.content}"`),(!this.font||this.font.length<=0)&&(this.font||(this.font=[]),(n=this.font)==null||n.push("sans-serif"));const o=this.font.map(r=>`"${r}"`).join(", ");i.appendLine(`string[] font = [ ${o} ]`),i.appendLine(`double pointSize = ${this.pointSize}`),typeof this.width=="number"&&i.appendLine(`double width = ${this.width}`),typeof this.height=="number"&&i.appendLine(`double height = ${this.height}`),typeof this.depth=="number"&&i.appendLine(`double depth = ${this.depth}`),this.wrapMode&&i.appendLine(`token wrapMode = "${this.wrapMode}"`),this.horizontalAlignment&&i.appendLine(`token horizontalAlignment = "${this.horizontalAlignment}"`),this.verticalAlignment&&i.appendLine(`token verticalAlignment = "${this.verticalAlignment}"`),this.material!==void 0&&i.appendLine(`rel material:binding = </StageRoot/Materials/${i0(this.material)}>`),i.closeBlock()}}a(Fo,"global_id",0);class yp{static singleLine(t,i,n){const o=new Fo("text_"+Fo.getId());return o.content=t,i&&(o.pointSize=i),n&&(o.depth=n),o}static multiLine(t,i,n,o,r,l){const c=new Fo("text_"+Fo.getId());return c.content=t,c.width=i,c.height=n,c.horizontalAlignment=o,c.verticalAlignment=r,l!==void 0&&(c.wrapMode=l),c}}const OT=new ne().makeRotationY(Math.PI),PT=new ne().makeScale(-1,1,-1);class fh{get extensionName(){return"text"}exportText(t,i,n){const o=P.getComponent(t,$t);if(!o)return;const r=P.getComponent(t,Ht);let l=100,c=100;r&&(l=r.width,c=r.height);const h=OT.clone();r&&h.premultiply(PT),i.setMatrix(h);const d=o.color.clone();i.material=new li({color:d,emissive:d}),i.addEventListener("serialize",(u,p)=>{let g=o.text;g=g.replace(/\r/g,""),g=g.replace(/\n/g,"\\n");const y=yp.multiLine(g,l,c,"center","bottom","flowing");this.setTextAlignment(y,o.alignment),this.setOverflow(y,o),i.material&&(y.material=i.material),y.pointSize=this.convertToTextSize(o.fontSize),y.depth=.001,y.writeTo(void 0,u)})}convertToTextSize(t){return 1/.0502*144*t}setOverflow(t,i){i.horizontalOverflow?t.wrapMode="singleLine":t.wrapMode="flowing"}setTextAlignment(t,i){switch(i){case mt.LowerLeft:case mt.MiddleLeft:case mt.UpperLeft:t.horizontalAlignment="left";break;case mt.LowerCenter:case mt.MiddleCenter:case mt.UpperCenter:t.horizontalAlignment="center";break;case mt.LowerRight:case mt.MiddleRight:case mt.UpperRight:t.horizontalAlignment="right";break}switch(i){case mt.LowerLeft:case mt.LowerCenter:case mt.LowerRight:t.verticalAlignment="bottom";break;case mt.MiddleLeft:case mt.MiddleCenter:case mt.MiddleRight:t.verticalAlignment="middle";break;case mt.UpperLeft:case mt.UpperCenter:case mt.UpperRight:t.verticalAlignment="top";break}}}var kT=Object.defineProperty,MT=Object.getOwnPropertyDescriptor,at=(s,t,i,n)=>{for(var o=n>1?void 0:n?MT(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&kT(t,i,o),o};const $x=O("debuguilayout");class zo{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}}at([m()],zo.prototype,"left",2),at([m()],zo.prototype,"right",2),at([m()],zo.prototype,"top",2),at([m()],zo.prototype,"bottom",2);class ji extends A{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(t){this._needsUpdate=!0}get isDirty(){return this._needsUpdate}get isLayoutGroup(){return!0}updateLayout(){this._rectTransform&&($x&&console.warn("Layout Update",this.context.time.frame,this.name),this._needsUpdate=!1,this.onCalculateLayout(this._rectTransform))}start(){this._needsUpdate=!0}onEnable(){$x&&console.log(this.name,this),this._rectTransform=this.gameObject.getComponent(Ht);const t=this.gameObject.getComponentInParent(Et);t&&t.registerLayoutGroup(this),this._needsUpdate=!0}onDisable(){const t=this.gameObject.getComponentInParent(Et);t&&t.unregisterLayoutGroup(this)}set m_Spacing(t){t!==this.spacing&&(this._needsUpdate=!0,this.spacing=t)}get m_Spacing(){return this.spacing}}at([m()],ji.prototype,"childAlignment",2),at([m()],ji.prototype,"reverseArrangement",2),at([m()],ji.prototype,"spacing",2),at([m(zo)],ji.prototype,"padding",2),at([m()],ji.prototype,"minWidth",2),at([m()],ji.prototype,"minHeight",2),at([m()],ji.prototype,"flexibleHeight",2),at([m()],ji.prototype,"flexibleWidth",2),at([m()],ji.prototype,"preferredHeight",2),at([m()],ji.prototype,"preferredWidth",2);class Uo extends ji{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(t){var i;const n=this.primaryAxis,o=t.width;let r=o;const l=t.height;let c=l;r-=this.padding.horizontal,c-=this.padding.vertical,n==="x"?this.padding.horizontal:this.padding.vertical;const h=n==="x",d=h?"y":"x",u=h?this.childControlWidth:this.childControlHeight,p=h?this.childControlHeight:this.childControlWidth,g=h?this.childForceExpandWidth:this.childForceExpandHeight,y=h?this.childForceExpandHeight:this.childForceExpandWidth,f=h?c:r,v=h?o:l,b=.5*(h?this.childAlignment%3:Math.floor(this.childAlignment/3));let w=0;h?w+=this.padding.left:w+=this.padding.top;let _=0,C=0;for(let D=0;D<this.gameObject.children.length;D++){const U=this.gameObject.children[D],B=P.getComponent(U,Ht);B!=null&&B.activeAndEnabled&&(C+=1,h?_+=B.width:_+=B.height)}let R=0;const M=this.spacing*(C-1);if(g||u){let D=0;h?D=r-=M:D=c-=M,C>0&&(R=D/C)}let T=0;T+=this.padding.left,T-=this.padding.right,b!==0&&(w=v-_,w*=b,w-=M*b,h?(w-=this.padding.right*b,w+=this.padding.left*(1-b),w<this.padding.left&&(w=this.padding.left)):(w-=this.padding.bottom*b,w+=this.padding.top*(1-b),w<this.padding.top&&(w=this.padding.top)));let j=1;for(let D=0;D<this.gameObject.children.length;D++){const U=this.gameObject.children[D],B=P.getComponent(U,Ht);if(B!=null&&B.activeAndEnabled){(i=B.pivot)==null||i.set(.5,.5),B.anchorMin.set(0,1),B.anchorMax.set(0,1);const Y=o*.5+T*.5;B.anchoredPosition.x!==Y&&(B.anchoredPosition.x=Y);const $=l*-.5;B.anchoredPosition.y!==$&&(B.anchoredPosition.y=$),y&&p&&B.sizeDelta[d]!==f&&(B.sizeDelta[d]=f),g&&u&&B.sizeDelta[n]!==R&&(B.sizeDelta[n]=R);const E=h?B.width:B.height,z=E*.5;if(w+=z,g){const se=R*j-R*.5;se>w&&(w=se-R*.5+E+this.padding.left,w-=z)}let H=w;n==="y"&&(H=-H),B.anchoredPosition[n]!==H&&(B.anchoredPosition[n]=H),w+=z,w+=this.spacing,j+=1}}}}at([m()],Uo.prototype,"childControlHeight",2),at([m()],Uo.prototype,"childControlWidth",2),at([m()],Uo.prototype,"childForceExpandHeight",2),at([m()],Uo.prototype,"childForceExpandWidth",2),at([m()],Uo.prototype,"childScaleHeight",2),at([m()],Uo.prototype,"childScaleWidth",2);class b0 extends Uo{get primaryAxis(){return"y"}}class _0 extends Uo{get primaryAxis(){return"x"}}class w0 extends ji{onCalculateLayout(){}}var RT=Object.defineProperty,TT=Object.getOwnPropertyDescriptor,on=(s,t,i,n)=>{for(var o=n>1?void 0:n?TT(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&RT(t,i,o),o},qx=(s=>(s[s.ScreenSpaceOverlay=0]="ScreenSpaceOverlay",s[s.ScreenSpaceCamera=1]="ScreenSpaceCamera",s[s.WorldSpace=2]="WorldSpace",s[s.Undefined=-1]="Undefined",s))(qx||{});const x0=O("debuguilayout"),Gx=class extends Wc{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 s,t,i,n;if(this.previousParent=this.gameObject.parent,((s=this.context.xr)!=null&&s.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(),(i=this.shadowComponent)==null||i.updateMatrixWorld(!0),(n=this.shadowComponent)==null||n.updateWorldMatrix(!0,!0),this.invokeBeforeRenderEvents(),ai.ensureUpdateMeshUI(bv,this.context))}),a(this,"onAfterRenderRoutine",()=>{var s,t,i,n,o;if(((s=this.context.xr)!=null&&s.isVR||(t=this.context.xr)!=null&&t.isPassThrough)&&this.screenspace){(i=this.previousParent)==null||i.add(this.gameObject);return}if((this.screenspace||this.renderOnTop)&&this.previousParent&&this.context.mainCamera){if(this.screenspace){const c=this.context.mainCamera;c?.add(this.gameObject)}else this.previousParent.add(this.gameObject);const r=this.context.renderer.autoClear,l=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(),ai.ensureUpdateMeshUI(bv,this.context,!0),this.context.renderer.render(this.gameObject,this.context.mainCamera),this.context.renderer.autoClear=r,this.context.renderer.autoClearColor=l,this.previousParent.add(this.gameObject)}(o=this._lastMatrixWorld)==null||o.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(s){s!==this._renderOnTop&&(this._renderOnTop=s,this.onRenderSettingsChanged())}get renderOnTop(){return this._renderOnTop!==void 0?this._renderOnTop:!!(this.screenspace&&this._renderMode===0)}set depthWrite(s){this._depthWrite!==s&&(this._depthWrite=s,this.onRenderSettingsChanged())}get depthWrite(){return this._depthWrite}set doubleSided(s){this._doubleSided!==s&&(this._doubleSided=s,this.onRenderSettingsChanged())}get doubleSided(){return this._doubleSided}set castShadows(s){this._castShadows!==s&&(this._castShadows=s,this.onRenderSettingsChanged())}get castShadows(){return this._castShadows}set receiveShadows(s){this._receiveShadows!==s&&(this._receiveShadows=s,this.onRenderSettingsChanged())}get receiveShadows(){return this._receiveShadows}get renderMode(){return this._renderMode}set renderMode(s){this._renderMode!==s&&(this._renderMode=s,this.onRenderSettingsChanged())}set rootCanvas(s){this._rootCanvas instanceof Gx||(this._rootCanvas=s)}get rootCanvas(){return this._rootCanvas}get scaleFactor(){return this._scaleFactor}set scaleFactor(s){this._scaleFactor=s}awake(){var s;this.shadowComponent=this.gameObject,this.previousParent=this.gameObject.parent,x0&&console.log("Canvas.Awake()",((s=this.previousParent)==null?void 0:s.name)+"/"+this.gameObject.name),super.awake()}start(){this.onUpdateRenderMode()}onEnable(){super.onEnable(),this._updateRenderSettingsRoutine=void 0,this._lastMatrixWorld=new ne,this.onUpdateRenderMode(),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 s=this.context.pre_render_callbacks.indexOf(this.onBeforeRenderRoutine);s!==-1&&this.context.pre_render_callbacks.splice(s,1);const t=this.context.post_render_callbacks.indexOf(this.onAfterRenderRoutine);t!==-1&&this.context.post_render_callbacks.splice(t,1)}registerTransform(s){this._rectTransforms.push(s)}unregisterTransform(s){const t=this._rectTransforms.indexOf(s);t!==-1&&this._rectTransforms.splice(t,1)}registerLayoutGroup(s){const t=s.gameObject;this._layoutGroups.set(t,s)}unregisterLayoutGroup(s){const t=s.gameObject;this._layoutGroups.delete(t)}registerEventReceiver(s){this._receivers.push(s)}unregisterEventReceiver(s){const t=this._receivers.indexOf(s);t!==-1&&this._receivers.splice(t,1)}async onEnterXR(s){this.screenspace?(s.xr.isVR||s.xr.isPassThrough)&&(this.gameObject.visible=!1):(this.gameObject.visible=!1,await Jl(1).then(()=>{this.gameObject.visible=!0}))}onLeaveXR(s){this.screenspace&&(s.xr.isVR||s.xr.isPassThrough)&&(this.gameObject.visible=!0)}invokeBeforeRenderEvents(){var s;for(const t of this._receivers)(s=t.onBeforeCanvasRender)==null||s.call(t,this)}handleLayoutUpdates(){this._lastMatrixWorld===null&&(this._lastMatrixWorld=new ne);const s=!this._lastMatrixWorld.equals(this.gameObject.matrixWorld);x0&&s&&console.log("Canvas Layout changed",this.context.time.frameCount,this.name);const t=!1;for(const i of this._rectTransforms){s&&i.markDirty();let n=this._layoutGroups.get(i.gameObject);i.isDirty&&!n&&(n=i.gameObject.getComponentInParent(ji)),(i.isDirty||n!=null&&n.isDirty)&&(x0&&!t&&console.log("CANVAS UPDATE ### "+i.name+" ##################################### "+this.context.time.frame),n?.updateLayout(),i.updateTransform())}}applyRenderSettings(){this.onRenderSettingsChanged()}onRenderSettingsChanged(){this._updateRenderSettingsRoutine||(this._updateRenderSettingsRoutine=this.startCoroutine(this._updateRenderSettingsDelayed(),Me.OnBeforeRender))}*_updateRenderSettingsDelayed(){if(yield,this._updateRenderSettingsRoutine=void 0,this.shadowComponent){this.onUpdateRenderMode(),Du(this.shadowComponent,this);for(const s of P.getComponentsInChildren(this.gameObject,ls))Du(s.shadowComponent,this)}}onUpdateRenderMode(s=!1){if(!s&&this._renderMode===this._activeRenderMode&&this._lastWidth===this.context.domWidth&&this._lastHeight===this.context.domHeight)return;this._activeRenderMode=this._renderMode;let t=this.context.mainCameraComponent,i=10;switch(t&&t.nearClipPlane>0&&t.farClipPlane>0&&(i=W.lerp(t.nearClipPlane,t.farClipPlane,.01)),this._renderMode===1&&(this.worldCamera&&(t=this.worldCamera),this.planeDistance>0&&(i=this.planeDistance)),this._renderMode){case 0:case 1:if(this._lastWidth=this.context.domWidth,this._lastHeight=this.context.domHeight,!t)return;const n=i+.01;this.gameObject.position.x=0,this.gameObject.position.y=0,this.gameObject.position.z=-n,this.gameObject.quaternion.identity();const o=this.gameObject.getComponent(Ht);let r=!1;o.sizeDelta.x!==this.context.domWidth&&(r=!0),o.sizeDelta.y!==this.context.domHeight&&(r=!0);const l=t.fieldOfView*Math.PI/180,c=2*Math.tan(l/2)*Math.abs(n);this.gameObject.scale.x=c/this.context.domHeight,this.gameObject.scale.y=c/this.context.domHeight,this.gameObject.scale.z=.01,r&&(o.sizeDelta.x=this.context.domWidth,o.sizeDelta.y=this.context.domHeight,o?.markDirty());break;case 2:this._lastWidth=-1,this._lastHeight=-1;break}}};let Et=Gx;on([m()],Et.prototype,"renderOnTop",1),on([m()],Et.prototype,"depthWrite",1),on([m()],Et.prototype,"doubleSided",1),on([m()],Et.prototype,"castShadows",1),on([m()],Et.prototype,"receiveShadows",1),on([m()],Et.prototype,"renderMode",1),on([m(Et)],Et.prototype,"rootCanvas",1),on([m()],Et.prototype,"scaleFactor",1),on([m(Pe)],Et.prototype,"worldCamera",2),on([m()],Et.prototype,"planeDistance",2);var ET=Object.defineProperty,AT=Object.getOwnPropertyDescriptor,S0=(s,t,i,n)=>{for(var o=n>1?void 0:n?AT(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&ET(t,i,o),o};class No extends A{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(t){t!==this._alpha&&(this._alpha=t,this.markDirty())}get isCanvasGroup(){return!0}markDirty(){this._isDirty||(this._isDirty=!0,this.startCoroutine(this.applyChangesDelayed(),Me.OnBeforeRender))}*applyChangesDelayed(){this._isDirty=!1,this.applyChangesNow()}applyChangesNow(){this._buffer.length=0;for(const t of P.getComponentsInChildren(this.gameObject,ls,this._buffer)){const i=t;i.setAlphaFactor&&i.setAlphaFactor(this._alpha)}}}S0([m()],No.prototype,"alpha",1),S0([m()],No.prototype,"interactable",2),S0([m()],No.prototype,"blocksRaycasts",2);class vp{get extensionName(){return"tmui"}onExportObject(t,i,n){const o=P.getComponent(t,Et);if(o&&o.enabled&&o.renderMode===qx.WorldSpace){const r=new fh,l=P.getComponent(t,Ht),c=P.getComponent(t,No),h=new Array;if(l){if(!P.isActiveSelf(t)){const p=P.isActiveSelf(t);P.setActive(t,!0),l.onEnable(),l.updateTransform(),h.push(()=>{l.onDisable(),P.setActive(t,p)})}t.traverse(p=>{if(!P.isActiveInHierarchy(p)){const g=P.isActiveSelf(p);P.setActive(p,!0);const y=P.getComponent(p,ls);y&&(y.onEnable(),h.push(()=>{y.onDisable()}));const f=P.getComponent(p,Ht);f&&(f.onEnable(),f.updateTransform(),f.onApplyTransform(),h.push(()=>{f.onDisable()}));const v=P.getComponent(p,$t);v&&(v.onEnable(),h.push(()=>{v.onDisable()})),h.push(()=>{P.setActive(p,g)})}}),l.width,l.height;const d=Zt.createEmpty(),u=l.shadowComponent;if(i.add(d),u){const p=u.matrix;d.setMatrix(p);const g=new Map,y=new Map;g.set(u,d),y.set(u,c?c.alpha:1),u.traverse(f=>{if(f===u)return;const v=Zt.createEmpty();v.setMatrix(f.matrix);const b=f.parent,w=!!b&&typeof b.textContent=="string"&&b.textContent.length>0;let _=y.get(b)||1;const C=P.getComponent(f,No);if(C&&(_*=C.alpha),f instanceof K&&w){const M=f[ts];M?r.exportText(M.gameObject,v,n):console.error("Error when exporting UI: shadow component owner not found. This is likely a bug.",f)}if(f instanceof K&&!w){const M=f.geometry.clone();M.scale(1,1,-1),this.flipWindingOrder(M),v.geometry=M;const T=new re,j=f.material.opacity;T.copy(f.material.color),v.material=new Re({color:T,opacity:j*_,map:f.material.map,transparent:!0})}g.set(f,v),y.set(f,_);const R=g.get(b);if(!R){console.error("Error when exporting UI: shadow component parent not found!",f,f.parent);return}R.add(v)})}}for(const d of h)d()}}flipWindingOrder(t){const i=t.index.array;for(let n=0,o=i.length/3;n<o;n++){const r=i[n*3];i[n*3]=i[n*3+2],i[n*3+2]=r}t.index.needsUpdate=!0}}const Xx=class{constructor(){a(this,"_quicklookButton"),a(this,"_arButton"),a(this,"_vrButton"),a(this,"_sendToQuestButton")}static create(){return new Xx}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 Tn.getOrCreate().createQRCode()}createQuicklookButton(){if(this._quicklookButton)return this._quicklookButton;const s=document.createElement("button");this._quicklookButton=s,s.dataset.needle="quicklook-button";const t=X.supportsQuickLookAR();s.innerText="View in AR",s.prepend(Pt("view_in_ar"));let i=!1,n=null;return s.addEventListener("click",()=>{n=Zd(Ge),n||(i=!0,n=new Ge),i&&(n.objectToExport=ee.Current.scene),n?(s.classList.add("this-mode-is-requested"),n.exportAndOpen().then(()=>{s.classList.remove("this-mode-is-requested")}).catch(o=>{s.classList.remove("this-mode-is-requested"),console.error(o)})):console.warn("No USDZExporter component found in the scene")}),this.hideElementDuringXRSession(s),s}createARButton(s){var t;if(this._arButton)return this._arButton;const i="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(Pt("view_in_ar")),n.title="Click to start an AR session",n.addEventListener("click",()=>J.start(i,s)),this.updateSessionSupported(n,i),this.listenToXRSessionState(n,i),this.hideElementDuringXRSession(n),this.isSecureConnection||(n.disabled=!0,n.title="WebXR requires a secure connection (HTTPS)"),X.isMozillaXR()||(t=navigator.xr)==null||t.addEventListener("devicechange",()=>this.updateSessionSupported(n,i)),n}createVRButton(s){var t;if(this._vrButton)return this._vrButton;const i="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(Pt("panorama_photosphere")),n.title="Click to start a VR session",n.addEventListener("click",()=>J.start(i,s)),this.updateSessionSupported(n,i),this.listenToXRSessionState(n,i),this.hideElementDuringXRSession(n),this.isSecureConnection||(n.disabled=!0,n.title="WebXR requires a secure connection (HTTPS)"),X.isMozillaXR()||(t=navigator.xr)==null||t.addEventListener("devicechange",()=>this.updateSessionSupported(n,i)),n}createSendToQuestButton(){var s;if(this._sendToQuestButton)return this._sendToQuestButton;const t="https://oculus.com/open_url/?url=",i=document.createElement("button");return this._sendToQuestButton=i,i.dataset.needle="webxr-sendtoquest-button",i.innerText="Open on Quest",i.prepend(Pt("share_windows")),i.title="Click to send this page to the Oculus Browser on your Quest",i.addEventListener("click",()=>{const n=encodeURIComponent(window.location.href),o=t+n;window.open(o)==null&&De("This page doesn't allow popups. Please paste "+o+" into your browser.")}),this.listenToXRSessionState(i),this.hideElementDuringXRSession(i),X.isMozillaXR()||(s=navigator.xr)==null||s.addEventListener("devicechange",()=>{var n;(n=navigator.xr)!=null&&n.isSessionSupported("immersive-vr")?i.style.display="none":i.style.display=""}),i}createQRCode(){return Tn.getOrCreate().createQRCode()}updateSessionSupported(s,t){if(!("xr"in navigator)){s.style.display="none";return}J.isSessionSupported(t).then(i=>{s.style.display=i?"":"none",F()&&!i&&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(s){Ad(t=>{s["previous-display"]=s.style.display,s.style.display="none"}),ng(t=>{s["previous-display"]!=null&&(s.style.display=s["previous-display"])})}listenToXRSessionState(s,t){t&&(J.onSessionRequestStart(i=>{i.mode===t?s.classList.add("this-mode-is-requested"):(s["was-disabled"]=s.disabled,s.disabled=!0,s.classList.add("other-mode-is-requested"))}),J.onSessionRequestEnd(i=>{s.classList.remove("this-mode-is-requested"),s.classList.remove("other-mode-is-requested"),s.disabled=s["was-disabled"]}))}};let Kr=Xx;a(Kr,"_instance");var IT=Object.defineProperty,jT=Object.getOwnPropertyDescriptor,xt=(s,t,i,n)=>{for(var o=n>1?void 0:n?jT(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&IT(t,i,o),o};const bp=O("debugspriterenderer"),LT=O("wireframe"),C0=class{static getOrCreateGeometry(s){if(s.__cached_geometry)return s.__cached_geometry;if(s.guid&&C0.cache[s.guid])return bp&&console.log("Take cached geometry for sprite",s.guid),C0.cache[s.guid];const t=new bn;s.__cached_geometry=t;const i=new Float32Array(s.triangles.length*3),n=new Float32Array(s.triangles.length*2);for(let o=0;o<s.triangles.length;o+=1){const r=s.triangles[o];i[o*3]=-s.vertices[r].x,i[o*3+1]=s.vertices[r].y,i[o*3+2]=0;const l=s.uv[r];n[o*2]=l.x,n[o*2+1]=1-l.y}return t.setAttribute("position",new ft(i,3)),t.setAttribute("uv",new ft(n,2)),s.guid&&(this.cache[s.guid]=t),bp&&console.log("Built sprite geometry",s,t),t}};let yh=C0;a(yh,"cache",{});class DT{constructor(){a(this,"x"),a(this,"y")}}function Qx(s){s&&(s.colorSpace!=gs&&(s.colorSpace=gs,s.needsUpdate=!0),s.minFilter==md&&s.magFilter==md&&(s.anisotropy=1,s.needsUpdate=!0))}let rn=class{constructor(s){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"),s&&(this.texture=s,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 K(yh.getOrCreateGeometry(this),this.material)),this._mesh}get material(){return this._material||(this.texture&&Qx(this.texture),this._material=new Re({map:this.texture,color:16777215,side:xi,transparent:!0})),this._material}getGeometry(){return yh.getOrCreateGeometry(this)}};xt([m()],rn.prototype,"guid",2),xt([m(Le)],rn.prototype,"texture",2),xt([$a()],rn.prototype,"triangles",2),xt([$a()],rn.prototype,"uv",2),xt([$a()],rn.prototype,"vertices",2);const O0=Symbol("spriteOwner");class Wo{constructor(){a(this,"sprites")}}xt([m(rn)],Wo.prototype,"sprites",2);const Yx=class{constructor(){a(this,"spriteSheet"),a(this,"index",0)}static create(){const s=new Yx;return s.spriteSheet=new Wo,s}set sprite(s){s&&(this.spriteSheet?((this.index===null||this.index===void 0)&&(this.index=0),this.spriteSheet.sprites[this.index]=s):(this.spriteSheet=new Wo,this.spriteSheet.sprites=[s],this.index=0))}get sprite(){if(this.spriteSheet)return this.spriteSheet.sprites[this.index]}update(s){if(!this.spriteSheet)return;const t=this.index;if(t<0||t>=this.spriteSheet.sprites.length)return;const i=this.spriteSheet.sprites[t],n=i?.texture;if(n&&(Qx(n),!i.__hasLoadedProgressive)){i.__hasLoadedProgressive=!0;const o=n;it.assignTextureLOD(n,0).then(r=>{r instanceof Le&&(i.texture=r,s?.map===o&&(s.map=r,s.needsUpdate=!0))})}}};let Vn=Yx;xt([m(Wo)],Vn.prototype,"spriteSheet",2),xt([m()],Vn.prototype,"index",2);class fi extends A{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(t){var i;if(!this._spriteSheet)return;const n=(i=this._spriteSheet.spriteSheet)==null?void 0:i.sprites[this.spriteIndex];n&&(n.texture=t,this.updateSprite())}addSprite(t,i=!1){var n,o;if(this._spriteSheet||(this._spriteSheet=Vn.create()),!this._spriteSheet.spriteSheet)return-1;(n=this._spriteSheet.spriteSheet)==null||n.sprites.push(t);const r=((o=this._spriteSheet.spriteSheet)==null?void 0:o.sprites.length)-1;return i&&(this.spriteIndex=r),r}get sprite(){return this._spriteSheet}set sprite(t){if(t!==this._spriteSheet)if(typeof t=="number"){const i=Math.floor(t);this.spriteIndex=i;return}else t instanceof rn?(this._spriteSheet||(this._spriteSheet=Vn.create()),this._spriteSheet.sprite!=t&&(this._spriteSheet.sprite=t,this.updateSprite())):t!=this._spriteSheet&&(this._spriteSheet=t,this.updateSprite())}set spriteIndex(t){this._spriteSheet&&t!==this.spriteIndex&&(this._spriteSheet.index=t,this.updateSprite())}get spriteIndex(){var t;return((t=this._spriteSheet)==null?void 0:t.index)??0}get spriteFrames(){var t,i;return((i=(t=this._spriteSheet)==null?void 0:t.spriteSheet)==null?void 0:i.sprites.length)??0}awake(){this._currentSprite=void 0,this._spriteSheet||(this._spriteSheet=new Vn,this._spriteSheet.spriteSheet=new Wo),bp&&console.log("Awake",this.name,this,this.sprite)}start(){this._currentSprite?this.gameObject&&this.gameObject.add(this._currentSprite):this.updateSprite()}updateSprite(t=!1){var i;if(!this.__didAwake&&!t)return!1;const n=this._spriteSheet;if(!((i=n?.spriteSheet)!=null&&i.sprites))return console.warn("SpriteRenderer has no data or spritesheet assigned..."),!1;const o=n.spriteSheet.sprites[this.spriteIndex];if(!o)return bp&&console.warn("Sprite not found",this.spriteIndex,n.spriteSheet.sprites),!1;if(this._currentSprite)this._currentSprite.geometry=yh.getOrCreateGeometry(o),this._currentSprite.material.map=o.texture;else{const r=new Re({color:16777215,side:xi});if(LT&&(r.wireframe=!0),this.color&&(r.color||(r.color=new re),r.color.copy(this.color),r.opacity=this.color.alpha),r.transparent=!0,r.toneMapped=this.toneMapped,o.texture&&!r.wireframe){let l=o.texture;l[O0]!==void 0&&l[O0]!==this&&this.spriteFrames>1&&(l=o.texture=l.clone()),l[O0]=this,r.map=l}this.sharedMaterial=r,this._currentSprite=new K(yh.getOrCreateGeometry(o),r),this._currentSprite.renderOrder=Math.round(this.renderOrder),it.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,n?.update(this.sharedMaterial),!0}}xt([m()],fi.prototype,"drawMode",2),xt([m(DT)],fi.prototype,"size",2),xt([m(Se)],fi.prototype,"color",2),xt([m(ke)],fi.prototype,"sharedMaterial",2),xt([m()],fi.prototype,"transparent",2),xt([m()],fi.prototype,"cutoutThreshold",2),xt([m()],fi.prototype,"castShadows",2),xt([m()],fi.prototype,"renderOrder",2),xt([m()],fi.prototype,"toneMapped",2),xt([m(Vn)],fi.prototype,"sprite",1);const Kx=O("debugwebxr"),BT=new ne().makeRotationY(Math.PI);class Hn extends A{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 ne),a(this,"_createdPlacementObject",null),a(this,"_reparentedComponents",[]),a(this,"_placementScene",new qi),a(this,"_reticle",[]),a(this,"_hits",[]),a(this,"_placementStartTime",-1),a(this,"_rigPlacementMatrix"),a(this,"_anchor",null),a(this,"userInput"),a(this,"onPlaceScene",t=>{var i;if(this._isPlacing==!1||t!=null&&t.used)return;let n=this._reticle[0];if(!n){console.warn("No reticle to place...");return}if(!n.visible&&!this.autoPlace){console.warn("Reticle is not visible (can not place)");return}if((i=J.active)!=null&&i.isTrackingImages){console.warn("Scene Placement is disabled while images are being tracked");return}let o=this._hits[0];if(t&&t.origin instanceof og){const r=this._reticle[t.origin.index];r&&(n=r,o=this._hits[t.origin.index])}if(t&&(t.stopImmediatePropagation(),t.stopPropagation(),t.use()),this._isPlacing=!1,this.context.input.removeEventListener("pointerup",this.onPlaceScene),this.onRevertSceneChanges(),n.position.copy(n.lastPos),n.quaternion.copy(n.lastQuat),this.onApplyPose(n),this.useXRAnchor&&this.onCreateAnchor(J.active,o),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(t){const i="placed";return this._eventListeners[i]||(this._eventListeners[i]=[]),this._eventListeners[i].push(t),()=>{const n=this._eventListeners[i].indexOf(t);n>=0&&this._eventListeners[i].splice(n,1)}}get arScale(){return this._arScale}set arScale(t){t!==this._arScale&&(this._arScale=t,this.onScaleChanged())}onEnable(){var t;(t=this.customReticle)==null||t.preload()}supportsXR(t){return t==="immersive-ar"}onEnterXR(t){Kx&&console.log("ENTER WEBXR: SessionRoot start..."),this._anchor=null,this.gameObject.updateMatrixWorld(),this._startOffset.copy(this.gameObject.matrixWorld);const i=new I;this._createdPlacementObject=i,i.name="AR Session Root",this._placementScene.name="AR Placement Scene",this._placementScene.children.length=0;for(let n=this.context.scene.children.length-1;n>=0;n--){const o=this.context.scene.children[n];this._placementScene.add(o)}if(this.context.scene.add(i),this.autoCenter){const n=ci(this._placementScene.children),o=n.getCenter(new x),r=n.getSize(new x),l=new ne;l.makeTranslation(o.x,o.y-r.y*.5,o.z),this._startOffset.multiply(l)}this._reparentedComponents.length=0,this._reparentedComponents.push({comp:this,originalObject:this.gameObject}),P.addComponent(i,this);for(const n of this._reticle)Ri(n);this._reticle.length=0,this._isPlacing=!0,this.context.input.addEventListener("pointerup",this.onPlaceScene,{queue:Oi.Early})}onLeaveXR(){this.context.input.removeEventListener("pointerup",this.onPlaceScene,{queue:Oi.Early}),this.onRevertSceneChanges(),this._anchor=null,this._rigPlacementMatrix=void 0}onUpdateXR(t){var i,n,o,r;if(t.xr.isTrackingImages){for(const l of this._reticle)l.visible=!1;return}if(this._isPlacing){const l=(i=t.xr.rig)==null?void 0:i.gameObject;l&&l.parent!==this.context.scene&&this.context.scene.add(l);let c=!1;if(t.xr.isPassThrough&&t.xr.controllers.length>0&&!this.autoPlace)for(const h of t.xr.controllers){const d=h.getHitTest();d&&(c=!0,this.updateReticleAndHits(t.xr,h.index,d,t.xr.rigScale))}if(!c){const h=t.xr.getHitTest();h&&this.updateReticleAndHits(t.xr,0,h,t.xr.rigScale)}}else{if(this._anchor&&t.xr.referenceSpace){const l=t.xr.frame.getPose(this._anchor.anchorSpace,t.xr.referenceSpace);if(l&&this.context.time.frame%20===0){const c=t.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 _p(this.context)),(n=this.userInput)==null||n.enable()):(o=this.userInput)==null||o.disable(),this.arTouchTransform&&(r=this.userInput)!=null&&r.hasChanged){if(t.xr.rig){const l=t.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(t,i,n,o){this._hits[i]=n.hit;let r=this._reticle[i];if(!r){if(this.customReticle)if(this.customReticle.asset)r=Ua(this.customReticle.asset);else{this.customReticle.loadAssetAsync();return}else r=new K(new aC(.07,.09,32).rotateX(-Math.PI/2),new Re({side:xi,depthTest:!1,depthWrite:!1,transparent:!0,opacity:1,color:15658734})),r.name="AR Placement Reticle";if(Kx){const l=new wi(1);l.position.y+=.01,r.add(l)}this._reticle[i]=r,r.matrixAutoUpdate=!1,r.visible=!1}if(r.lastPos=r.lastPos||n.position.clone(),r.lastQuat=r.lastQuat||n.quaternion.clone(),r.position.copy(r.lastPos.lerp(n.position,this.context.time.deltaTime/.1)),r.lastPos.copy(r.position),r.quaternion.copy(r.lastQuat.slerp(n.quaternion,this.context.time.deltaTime/.05)),r.lastQuat.copy(r.quaternion),r.scale.set(o,o,o),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(G(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}onScaleChanged(){}onRevertSceneChanges(){var t;for(const i of this._reticle)i&&(i.visible=!1,i?.removeFromParent());this._reticle.length=0;for(let i=this._placementScene.children.length-1;i>=0;i--){const n=this._placementScene.children[i];this.context.scene.add(n)}(t=this._createdPlacementObject)==null||t.removeFromParent();for(const i of this._reparentedComponents)P.addComponent(i.originalObject,i.comp)}async onCreateAnchor(t,i){if(i.createAnchor===void 0){console.warn("Hit does not support creating an anchor",i),F()&&xe("Hit does not support creating an anchor");return}else{const n=await i.createAnchor(t.viewerPose.transform);t.running&&n&&(this._anchor=n)}}applyViewBasedTransform(t){const i=this.context.mainCamera,n=t,o=i.worldPosition,r=n.worldPosition;this.upVec.set(0,1,0).applyQuaternion(t.quaternion);const l=i.worldPosition;l&&t.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(t.position).add(this.upVec),this.lookPoint.y=t.position.y,t.lookAt(this.lookPoint)):(o.y=r.y,t.lookAt(o))}onApplyPose(t){var i,n,o,r;const l=(n=(i=J.active)==null?void 0:i.rig)==null?void 0:n.gameObject;if(!l){console.warn("No rig object to place");return}(o=J.active)!=null&&o.rigScale;const c=l.parent||this.context.scene;this._rigPlacementMatrix?(r=this._rigPlacementMatrix)==null||r.decompose(l.position,l.quaternion,l.scale):this._rigPlacementMatrix=l.matrix.clone(),this.applyViewBasedTransform(t),t.updateMatrix(),this.context.scene.add(t),t.attach(l),t.removeFromParent(),l.scale.set(this.arScale,this.arScale,this.arScale),l.position.multiplyScalar(this.arScale),l.updateMatrix(),this.invertForward&&l.matrix.premultiply(BT),l.matrix.premultiply(this._startOffset),l.matrix.decompose(l.position,l.quaternion,l.scale),c.add(l)}}a(Hn,"_eventListeners",{});const P0=class{constructor(s){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 i=0;i<t.changedTouches.length;i++){const n=t.changedTouches[i],o=X.isAndroidDevice()&&n.clientY<window.innerHeight*.1;this.prev.has(n.identifier)||this.prev.set(n.identifier,{ignore:o,x:0,z:0,screenx:0,screeny:0});const r=this.prev.get(n.identifier);if(r){const l=this.getPositionOnPlane(n.clientX,n.clientY);r.x=l.x,r.z=l.z,r.screenx=n.clientX,r.screeny=n.clientY}}}),a(this,"touchEnd",t=>{t.touches.length<=0&&(this._didMultitouch=!1);for(let i=0;i<t.changedTouches.length;i++){const n=t.changedTouches[i];this.prev.delete(n.identifier)}}),a(this,"touchMove",t=>{if(!t.defaultPrevented&&this.isActive){if(t.touches.length===1){if(this._didMultitouch)return;const i=t.touches[0],n=this.prev.get(i.identifier);if(!n||n.ignore)return;const o=this.getPositionOnPlane(i.clientX,i.clientY),r=o.x-n.x,l=o.z-n.z;if(r===0&&l===0)return;this.oneFingerDrag&&this.addMovement(r,l),n.x=o.x,n.z=o.z,n.screenx=i.clientX,n.screeny=i.clientY;return}else if(t.touches.length===2){this._didMultitouch=!0;const i=t.touches[0],n=t.touches[1],o=this.prev.get(i.identifier),r=this.prev.get(n.identifier);if(!o||!r)return;if(this.twoFingerRotate){const l=Math.atan2(i.clientY-n.clientY,i.clientX-n.clientX),c=Math.atan2(o.screeny-r.screeny,o.screenx-r.screenx),h=l-c;Math.abs(h)>.001&&this.addRotation(h)}if(this.twoFingerScale){const l=i.clientX-n.clientX,c=i.clientY-n.clientY,h=Math.sqrt(l*l+c*c),d=o.screenx-r.screenx,u=o.screeny-r.screeny,p=Math.sqrt(d*d+u*u),g=h-p;Math.abs(g)>2&&this.addScale(g)}o.screenx=i.clientX,o.screeny=i.clientY,r.screenx=n.clientX,r.screeny=n.clientY}}}),a(this,"_raycaster",new ud),a(this,"_intersection",new x),a(this,"_screenPos",new x),a(this,"_tempMatrix",new ne),this.context=s,this.offset=new ne,this.plane=new pr,this.plane.setFromNormalAndCoplanarPoint(P0.up,P0.zero)}reset(){this._scale=1,this.offset.identity()}get hasChanged(){return this._hasChanged}applyMatrixTo(s,t){this._hasChanged=!1,t?(this.offset.invert(),s.premultiply(this.offset)):s.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:Oi.Early}),this.context.input.addEventListener("pointerdown",this.onPointerDownLate,{queue:Oi.Late}),this.context.input.addEventListener("pointerup",this.onPointerUpEarly,{queue:Oi.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:Oi.Early}),this.context.input.removeEventListener("pointerdown",this.onPointerDownLate,{queue:Oi.Late}),this.context.input.removeEventListener("pointerup",this.onPointerUpEarly,{queue:Oi.Early}),window.removeEventListener("touchstart",this.touchStart),window.removeEventListener("touchmove",this.touchMove),window.removeEventListener("touchend",this.touchEnd))}getPositionOnPlane(s,t){const i=this.context.mainCamera;return this._screenPos.x=s/window.innerWidth*2-1,this._screenPos.y=-(t/window.innerHeight)*2+1,this._screenPos.z=1,this._screenPos.unproject(i),this._raycaster.set(i.position,this._screenPos.sub(i.position)),this._raycaster.ray.intersectPlane(this.plane,this._intersection),this._intersection}addMovement(s,t){s/=this._scale,t/=this._scale,s*=this.factor,t*=this.factor,this.offset.elements[12]+=s,this.offset.elements[14]+=t,(s!==0||t!==0)&&(this._hasChanged=!0)}addScale(s){s/=window.innerWidth,s*=-1,this._scale*=1+s,this._tempMatrix.makeScale(1-s,1-s,1-s),this.offset.premultiply(this._tempMatrix),s!==0&&(this._hasChanged=!0)}addRotation(s){s*=-1,this._tempMatrix.makeRotationY(s),this.offset.premultiply(this._tempMatrix),s!==0&&(this._hasChanged=!0)}};let _p=P0;a(_p,"up",new x(0,1,0)),a(_p,"zero",new x(0,0,0)),a(_p,"one",new x(1,1,1));const Vo=O("debugautosync"),k0=Symbol("syncerId");class FT{constructor(){a(this,"_syncers",{})}getOrCreateSyncer(t){if(!t.guid)return null;if(this._syncers[t.guid])return this._syncers[t.guid];const i=new zT(t);return i[k0]=t.guid,this._syncers[i[k0]]=i,i}removeSyncer(t){delete this._syncers[t[k0]]}}const M0=new FT;class zT{constructor(t){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 i=this.comp.context.connection;if(!i||!i.isConnected||!i.isInRoom){for(const n in this.changedProperties)delete this.changedProperties[n];return}for(const n in this.changedProperties){const o=this.changedProperties[n];Vo&&console.log("SEND",this.comp.guid,this.networkingKey),i.send(this.networkingKey,{guid:this.comp.guid,property:n,data:o},ws.Queued),delete this.changedProperties[n]}}),a(this,"onHandleReceiving",i=>{if(Vo&&console.log("SYNCFIELD RECEIVE",this.comp.name,this.comp.guid,i),!!this._isInit&&this.comp&&i.guid===this.comp.guid)try{this._isReceiving=!0,this.comp[i.property]=i.data}catch(n){console.error(n)}finally{this._isReceiving=!1}}),this.comp=t}get networkingKey(){return this.comp.guid}init(t){if(this._isInit)return;this._isInit=!0,this.comp=t,this.comp.context.post_render_callbacks.push(this.onHandleSending),this.comp.context.connection.beginListen(this.networkingKey,this.onHandleReceiving);const i=this.comp.context.connection.tryGetState(this.comp.guid);i&&this.onHandleReceiving(i)}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(t,i){this._isReceiving||(Vo&&console.log("Property changed: "+t,i),this.hasChanges=!0,this.changedProperties[t]=i)}}function UT(s,t){let i=t!==s;return!i&&s&&t&&(Array.isArray(s)&&Array.isArray(t)||typeof s=="object"&&typeof t=="object")&&(i=!0),i}const vh=Symbol("AutoSyncHandler");function NT(s){if(s[vh])return s[vh];const t=M0.getOrCreateSyncer(s);return t?.init(s),s[vh]=t,t}function WT(s){const t=s[vh];t&&(M0.removeSyncer(t),t.destroy(),delete s[vh])}const R0=function(s=null){return function(t,i){var n;let o="";typeof i=="string"?o=i:o=i.name;let r=null,l;typeof s=="string"?l=t[s]:typeof s=="function"&&(l=s),l==null&&(F()||Vo)&&s!=null&&console.warn('syncField: no callback function found for property "'+o+'"','"'+s+'"');const c=t,h=c.__internalAwake;if(typeof h!="function"){(Vo||F())&&console.error('@syncField can currently only used on Needle Engine Components, custom object of type "'+((n=t?.constructor)==null?void 0:n.name)+'" is not supported',t);return}Vo&&console.log(o);const d=Symbol(o);c.__internalAwake=function(){if(this[d]!==void 0)return;this[d]=this[o],r=M0.getOrCreateSyncer(this);const p=Object.getOwnPropertyDescriptor(this,o);if(p?.set===void 0){let g=!1;Object.defineProperty(this,o,{set:function(y){var f;const v=this[d];if(this[d]=y,g){(F()||Vo)&&console.warn("Recursive call detected",o);return}g=!0;try{const b=UT(y,v);Vo&&console.log("SyncField assignment",o,"changed?",b,y,l),b&&l?.call(this,y,v)!==!1&&((f=NT(this))==null||f.notifyChanged(o,y))}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(){WT(this),u.call(this)}}};var VT=Object.defineProperty,HT=Object.getOwnPropertyDescriptor,wp=(s,t,i,n)=>{for(var o=n>1?void 0:n?HT(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&VT(t,i,o),o};const ii=O("debugplayersync"),Zx=class extends A{constructor(){super(...arguments),a(this,"autoSync",!0),a(this,"asset"),a(this,"onPlayerSpawned"),a(this,"_localInstance"),a(this,"onJoinedRoom",()=>{ii&&console.log("PlayerSync.joinedRoom. autoSync is set to "+this.autoSync),this.autoSync&&this.getInstance()}),a(this,"destroyInstance",()=>{var s;(s=this._localInstance)==null||s.then(t=>{ii&&console.log("PlayerSync.destroyInstance",t),xc(t,this.context.connection,!0,{saveInRoom:!1})}),this._localInstance=void 0})}static async setupFrom(s,t){const i=ae.getOrCreateFromUrl(s);if(!i.asset){const r=await i.loadAssetAsync();r&&P.getOrAddComponent(r,Li)}const n=new Zx;n._internalInit(t),n.asset=i;const o=new I;return o.guid=s,P.addComponent(o,n),n}awake(){this.watchTabVisible(),this.onPlayerSpawned||(this.onPlayerSpawned=new _e)}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 s,t,i,n,o,r;if(this._localInstance)return this._localInstance;if(ii&&console.log("PlayerSync.createInstance",(s=this.asset)==null?void 0:s.url),!((t=this.asset)!=null&&t.asset)&&!((i=this.asset)!=null&&i.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 l=await this._localInstance;if(l){const c=P.getComponentsInChildren(l,Li);if(ii&&console.log(`PlayerSync.createInstance: found ${c?.length} PlayerState components. Owner: ${this.context.connection.connectionId}`),c!=null&&c.length){for(const h of c)h.owner=this.context.connection.connectionId;(o=this.onPlayerSpawned)==null||o.invoke(l)}else this._localInstance=void 0,console.error("<strong>Failed finding PlayerState on "+((r=this.asset)==null?void 0:r.url)+"</strong>: please make sure the asset has a PlayerState component!"),P.destroySynced(l)}else this._localInstance=void 0,console.warn("PlayerSync: failed instantiating asset!");return this._localInstance}watchTabVisible(){window.addEventListener("visibilitychange",s=>{if(document.visibilityState==="visible")for(let t=Li.all.length-1;t>=0;t--){const i=Li.all[t];(!i.owner||!this.context.connection.userIsInRoom(i.owner))&&i.doDestroy()}})}};let Sl=Zx;wp([m()],Sl.prototype,"autoSync",2),wp([m(ae)],Sl.prototype,"asset",2),wp([m(_e)],Sl.prototype,"onPlayerSpawned",2);var Jx=(s=>(s.OwnerChanged="ownerChanged",s))(Jx||{}),bh;const At=(bh=class extends A{constructor(){super(...arguments),a(this,"onOwnerChangeEvent",new _e),a(this,"onFirstOwnerChangeEvent",new _e),a(this,"hasOwner",!1),a(this,"owner"),a(this,"dontDestroy",!1),a(this,"onUserLeftRoom",s=>{if(s.userId===this.owner){ii&&console.log("PLAYERSYNC LEFT",this.owner),this.doDestroy();return}})}static get all(){return At._all}static get local(){return At._local}static getFor(s){if(s instanceof I)return P.getComponentInParent(s,At);if(s instanceof A)return P.getComponentInParent(s.gameObject,At)}static isLocalPlayer(s){const t=At.getFor(s);return t?.isLocalPlayer??!1}static addEventListener(s,t){return this._callbacks[s]||(this._callbacks[s]=[]),this._callbacks[s].push(t),t}static removeEventListener(s,t){if(!this._callbacks[s])return;const i=this._callbacks[s].indexOf(t);i>=0&&this._callbacks[s].splice(i,1)}static dispatchEvent(s,t){if(this._callbacks[s])for(const i of this._callbacks[s])i(t)}get isLocalPlayer(){return this.owner===this.context.connection.connectionId}onOwnerChange(s,t){var i,n;ii&&console.log(`PlayerSync.onOwnerChange: ${t} \u2192 ${s} (me: ${this.context.connection.connectionId})`);const o=At._local.indexOf(this);o>=0&&At._local.splice(o,1);const r={playerState:this,oldValue:t,newValue:s};if(this.hasOwner||(this.hasOwner=!0,(i=this.onFirstOwnerChangeEvent)==null||i.invoke(r)),(n=this.onOwnerChangeEvent)==null||n.invoke(r),this.owner===this.context.connection.connectionId){At._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),At.dispatchEvent("ownerChanged",l)}awake(){At.all.push(this),ii&&console.log("Registered new PlayerState",this.guid,At.all.length-1,At.all),this.context.connection.beginListen(ie.UserLeftRoom,this.onUserLeftRoom)}async start(){ii&&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&&(ii&&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||(ii&&console.warn("PlayerState.start \u2192 owner is undefined!",this.name),setTimeout(()=>{!this.destroyed&&!this.owner?this.dontDestroy?ii&&console.warn("PlayerState.start \u2192 owner is still undefined but dontDestroy is set to true",this.name):(ii&&console.warn(`PlayerState.start \u2192 owner is still undefined: destroying "${this.name}" instance now`),this.doDestroy()):ii&&console.log("PlayerState.start \u2192 owner is assigned",this.owner)},2e3))}doDestroy(){ii&&console.log("PlayerSync.doDestroy \u2192 syncDestroy",this.name),xc(this.gameObject,this.context.connection,!0,{saveInRoom:!1})}onDestroy(){if(ii&&console.warn("PlayerState.onDestroy",this.owner),this.context.connection.stopListen(ie.UserLeftRoom,this.onUserLeftRoom),At.all.splice(At.all.indexOf(this),1),this.isLocalPlayer){const s=At._local.indexOf(this);s>=0&&At._local.splice(s,1)}}},a(bh,"_all",[]),a(bh,"_local",[]),a(bh,"_callbacks",{}),bh);let Li=At;wp([R0(Li.prototype.onOwnerChange)],Li.prototype,"owner",2);var $T=Object.defineProperty,qT=Object.getOwnPropertyDescriptor,Cl=(s,t,i,n)=>{for(var o=n>1?void 0:n?qT(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&$T(t,i,o),o};class an extends A{constructor(){super(...arguments),a(this,"position","bottom"),a(this,"showNeedleLogo",!0),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&&(X.isMobileDevice()||this.context.menu.showQRCodeButton(!0))}}Cl([m()],an.prototype,"position",2),Cl([m()],an.prototype,"showNeedleLogo",2),Cl([m()],an.prototype,"showSpatialMenu",2),Cl([m()],an.prototype,"createFullscreenButton",2),Cl([m()],an.prototype,"createMuteButton",2),Cl([m()],an.prototype,"createQRCodeButton",2);var GT=Object.defineProperty,XT=Object.getOwnPropertyDescriptor,T0=(s,t,i,n)=>{for(var o=n>1?void 0:n?XT(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&GT(t,i,o),o};const _h=O("debugwebxr"),e1=new V().setFromAxisAngle(new x(0,1,0),Math.PI);class Ho extends A{constructor(){super(...arguments),a(this,"head"),a(this,"leftHand"),a(this,"rightHand"),a(this,"_leftHandMeshes"),a(this,"_rightHandMeshes"),a(this,"_syncTransforms")}async onEnterXR(t){if(!this.activeAndEnabled)return;_h&&console.warn("AVATAR ENTER XR",this.guid,this.sourceId,this,this.activeAndEnabled),this._syncTransforms&&(this._syncTransforms.length=0),await this.prepareAvatar();const i=Li.getFor(this);if(i!=null&&i.owner){const n=this.gameObject.addComponent(Rt);n.avatar=this.gameObject,n.connectionId=i.owner}else this.context.connection.isConnected?console.error("No player state found for avatar",this):i&&!this.context.connection.isConnected&&(i.dontDestroy=!0)}onLeaveXR(t){const i=this.gameObject.getComponent(Rt);i&&i.destroy()}onUpdateXR(t){var i,n;if(!this.activeAndEnabled)return;const o=Li.isLocalPlayer(this);if(!o)return;const r=t.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&&o)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,Ai);for(const g of p)g.enabled=!1,g.gameObject.visible=!1}}const l=t.xr.leftController,c=(i=this.leftHand)==null?void 0:i.asset;l&&c?(c.position.copy(l.gripPosition),c.quaternion.copy(l.gripQuaternion),c.quaternion.multiply(e1),c.visible=l.isTracking,this.updateHandVisibility(l,c,this._leftHandMeshes)):c&&c.visible&&(c.visible=!1);const h=t.xr.rightController,d=(n=this.rightHand)==null?void 0:n.asset;h&&d?(d.position.copy(h.gripPosition),d.quaternion.copy(h.gripQuaternion),d.quaternion.multiply(e1),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(t,i,n){if(n){const o=t.model&&t.model.visible&&t.model!==i;n.forEach(r=>{Mn(r,!o)})}}updateRemoteAvatarVisibility(){var t,i,n;if(this.context.connection.isConnected){const o=Li.getFor(this);if(o&&o.isLocalPlayer==!1){const r=J.getXRSync(this.context);if(r&&r.hasState(o.owner)){this.tryFindAvatarObjectsIfMissing();const l=(t=this.leftHand)==null?void 0:t.asset;l&&(l.visible=r?.isTracking(o.owner,"left")??!1);const c=(i=this.rightHand)==null?void 0:i.asset;c&&(c.visible=r?.isTracking(o.owner,"right")??!1)}if((n=this.head)!=null&&n.asset){const l=P.getComponentsInChildren(this.head.asset,Ai);for(const c of l)c.enabled=!1,c.gameObject.visible=!0}}}}tryFindAvatarObjectsIfMissing(){if(!this.head||!this.leftHand||!this.rightHand){const t={head:this.head,leftHand:this.leftHand,rightHand:this.rightHand};Nb.tryFindAvatarObjects(this.gameObject,this.sourceId||"",t),t.head&&(this.head=t.head),t.leftHand&&(this.leftHand=t.leftHand),t.rightHand&&(this.rightHand=t.rightHand)}}async prepareAvatar(){var t,i;if(this.tryFindAvatarObjectsIfMissing(),this.head)this.head instanceof I&&(this.head=new ae("",this.sourceId,this.head));else{const n=new I;n.name="Head";const o=go.createPrimitive(wr.Cube);n.add(o),this.gameObject.add(n),this.head=new ae("",this.sourceId,n),_h&&console.log("Create head",n)}if(this.rightHand)this.rightHand instanceof I&&(this.rightHand=new ae("",this.sourceId,this.rightHand));else{const n=new I;n.name="Right Hand",this.gameObject.add(n),this.rightHand=new ae("",this.sourceId,n),_h&&console.log("Create right hand",n)}if(this.leftHand)this.leftHand instanceof I&&(this.leftHand=new ae("",this.sourceId,this.leftHand));else{const n=new I;n.name="Left Hand",this.gameObject.add(n),this.leftHand=new ae("",this.sourceId,n),_h&&console.log("Create left hand",n)}await this.loadAvatarObjects(this.head,this.leftHand,this.rightHand),this._leftHandMeshes=[],(t=this.leftHand.asset)==null||t.traverse(n=>{n!=null&&n.isMesh&&this._leftHandMeshes.push(n)}),this._rightHandMeshes=[],(i=this.rightHand.asset)==null||i.traverse(n=>{n!=null&&n.isMesh&&this._rightHandMeshes.push(n)}),Li.isLocalPlayer(this.gameObject)&&(this._syncTransforms=P.getComponentsInChildren(this.gameObject,qs))}async loadAvatarObjects(t,i,n){const o=t.loadAssetAsync(),r=i.loadAssetAsync(),l=n.loadAssetAsync(),c=new Array;o&&c.push(o),r&&c.push(r),l&&c.push(l);const h=await wd(c);_h&&console.log("Avatar loaded results:",h)}}T0([m(ae)],Ho.prototype,"head",2),T0([m(ae)],Ho.prototype,"leftHand",2),T0([m(ae)],Ho.prototype,"rightHand",2);var QT=Object.defineProperty,YT=Object.getOwnPropertyDescriptor,xp=(s,t,i,n)=>{for(var o=n>1?void 0:n?YT(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&QT(t,i,o),o};const $n=O("debugwebxr"),$o=new Array;class ln extends A{constructor(){super(...arguments),a(this,"createControllerModel",!0),a(this,"createHandModel",!0),a(this,"customLeftHand"),a(this,"customRightHand"),a(this,"_models",new Array)}supportsXR(t){return t==="immersive-vr"||t==="immersive-ar"}async onXRControllerAdded(t){var i;if(!(t.xr.isVR||t.xr.isPassThrough))return;const{controller:n}=t;if($n&&console.warn("Add Controller Model for",n.side,n.index),this.createControllerModel||this.createHandModel){if(n.hand){if(this.createHandModel){const o=await this.loadHandModel(this,n);if(!o||!n.connected||!n.isHand){o!=null&&o.handObject&&za(o.handObject,!1),(i=o?.handObject)==null||i.destroy();return}this._models.push({controller:n,model:o.handObject,handmesh:o.handmesh}),this._models.sort((r,l)=>r.controller.index-l.controller.index),this.scene.add(o.handObject),n.model=o.handObject}}else if(this.createControllerModel){const o=await n.getModelUrl();if(o){const r=await this.loadModel(n,o);if(!r||!n.connected||n.isHand)return;this._models.push({controller:n,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()}),n.model=r}else n.targetRayMode!=="transient-pointer"&&console.warn("XRControllerModel: no model found for "+n.side)}}}onXRControllerRemoved(t){console.debug("XR Controller Removed",t.controller.side,t.controller.index);const i=this._models.findIndex(o=>o.controller===t.controller),n=this._models[i];n&&(this._models.splice(i,1),n.model&&(za(n.model,!1),n.model.destroy(),n.model=void 0))}onBeforeXR(t,i){this.createHandModel&&(this.customLeftHand||this.customRightHand)&&(i.optionalFeatures=i.optionalFeatures||[],i.optionalFeatures.includes("hand-tracking")||i.optionalFeatures.push("hand-tracking"))}onLeaveXR(t){for(const i of this._models)i&&(i.model&&(za(i.model,!1),i.model.destroy(),i.model=void 0),i.controller.model===i.model&&(i.controller.model=null));this._models.length=0}onBeforeRender(){if(J.active&&($n&&($o[0]=Date.now()),this.updateRendering(J.active),$n)){const t=Date.now()-$o[0];$o.push(t),$o.length>=30&&($o[0]=0,$o.reduce((i,n)=>i+n,0)/$o.length,$o.length=0)}}updateRendering(t){var i,n,o,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){$n&&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,(i=t.rig)==null||i.gameObject.add(h.model);else if(d.inputSource.hand&&h.handmesh){const u=t.referenceSpace,p=this.context.renderer.xr.getHand(d.index);if(u&&t.frame.getJointPose){for(const g of d.inputSource.hand.values()){const y=p.joints[g.jointName];if(y){const f=d.getHandJointPose(g);if(f){const v=f.transform.position,b=f.transform.orientation;y.position.copy(v),y.quaternion.copy(b),y.matrixAutoUpdate=!1}y.visible=f!=null}}h.model&&(h.model.visible=d.isTracking,h.model.visible&&h.model.parent!==((n=t.rig)==null?void 0:n.gameObject)&&((o=t.rig)==null||o.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(Ra))}}}}async loadModel(t,i){var n;if(!t.connected)return console.warn("XRControllerModel.onXRControllerAdded: controller is not connected anymore",t.side),null;const o=await ae.getOrCreate("",i).instantiate();return za(o),(n=J.active)!=null&&n.isPassThrough&&o.traverseVisible(r=>{this.makeOccluder(r)}),o}async loadHandModel(t,i){const n=this.context,o=n.renderer.xr.getHand(i.index);o||($n?q.DrawLabel(i.rayWorldPosition,"No hand found for index "+i.index,.05,5):console.warn("No hand found for index "+i.index));const r=new gr;Su(r,n),await Zu(r,n,this.sourceId??"");const l=Ku(r);let c="";const h=i.side==="left"?this.customLeftHand:this.customRightHand;h?(c=h.url.split(".").slice(0,-1).join("."),r.setPath("")):(c=i.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 I;za(d);const u=new UC(d,o,r.path,c,r,p=>{var g;const y=l.gltf;((g=y?.scene.children)==null?void 0:g.length)===0&&(y.scene.children[0]=p),fs().createBuiltinComponents(t.context,t.sourceId||c,l.gltf,null,l),p.traverse(f=>{var v;f.layers.set(2),(v=J.active)!=null&&v.isPassThrough&&!h&&this.makeOccluder(f),f instanceof K&&it.assignMeshLOD(f,0)}),i.connected||($n&&q.DrawLabel(i.rayWorldPosition,"Hand is loaded but not connected anymore",.05,5),p.removeFromParent())});if($n&&d.add(new wi(.5)),i.inputSource.hand){$n&&console.log(i.inputSource.hand);for(const p of i.inputSource.hand.values())if(o.joints[p.jointName]===void 0){const g=new ro;g.matrixAutoUpdate=!1,g.visible=!0,o.joints[p.jointName]=g,o.add(g)}}else $n&&q.DrawLabel(i.rayWorldPosition,"No inputSource.hand found for index "+i.index,.05,5);return{handObject:d,handmesh:u}}makeOccluder(t){if(t instanceof K){let i=t.material;i instanceof ke&&(i=t.material=i.clone(),i.depthWrite=!0,i.depthTest=!0,i.colorWrite=!1,t.receiveShadow=!1,t.renderOrder=-100)}}}a(ln,"factory",new zC),xp([m()],ln.prototype,"createControllerModel",2),xp([m()],ln.prototype,"createHandModel",2),xp([m(ae)],ln.prototype,"customLeftHand",2),xp([m(ae)],ln.prototype,"customRightHand",2);class Sp extends A{}var KT=Object.defineProperty,ZT=Object.getOwnPropertyDescriptor,qo=(s,t,i,n)=>{for(var o=n>1?void 0:n?ZT(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&KT(t,i,o),o};const E0=O("debugwebxr");class Di extends A{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",t=>t.type==="SkinnedMesh"?"continue in children":!0)}onUpdateXR(t){const i=t.xr.rig;if(!(i!=null&&i.gameObject)||t.xr.isPassThrough)return;const n=t.xr.leftController,o=t.xr.rightController;n&&this.onHandleMovement(n,i.gameObject),o&&(this.onHandleRotation(o,i.gameObject),this.useTeleport&&this.onHandleTeleport(o,i.gameObject))}onLeaveXR(t){for(const i of this._lines)i.removeFromParent();for(const i of this._hitDiscs)i?.removeFromParent()}onBeforeRender(){var t;(t=this.context.xr)!=null&&t.running&&(this.showRays&&this.renderRays(this.context.xr),this.showHits&&this.renderHits(this.context.xr))}onHandleMovement(t,i){const n=t.getStick("xr-standard-thumbstick");if(n.x!=0||n.y!=0){const o=G(n.x,0,n.y);o.multiplyScalar(this.context.time.deltaTimeUnscaled*this.movementSpeed);const r=Je(i);o.multiplyScalar(r.x),o.applyQuaternion(t.xr.poseOrientation),o.y=0,o.applyQuaternion(i.worldQuaternion),i.position.add(o),i.updateWorldMatrix(!1,!1);for(const l of i.children)l.updateWorldMatrix(!1,!1)}}onHandleRotation(t,i){if(t._isMxInk)return;const n=t.getStick("xr-standard-thumbstick").x;if(this._didApplyRotation)Math.abs(n)<.3&&(this._didApplyRotation=!1);else if(Math.abs(n)>.5){this._didApplyRotation=!0;const o=n>0?1:-1,r=te(this.context.mainCamera).clone();i.rotateY(o*W.toRadians(this.rotationStep));const l=te(this.context.mainCamera).clone().sub(r);l.y=0,i.position.sub(l)}}onHandleTeleport(t,i){var n,o,r,l,c;let h=0;if(t.hand&&this.usePinchToTeleport&&t.isTeleportGesture){const d=t.getPointerId("primary");if(d!=null&&this.context.input.getIsPointerIdInUse(d))return;const u=t.getGesture("pinch");u&&(h=u.value)}else h=(n=t.getStick("xr-standard-thumbstick"))==null?void 0:n.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(t.ray)[0];if(d&&d.object instanceof Sa){const p=(o=d.normal)==null?void 0:o.dot(G(0,1,0));if(p!==void 0&&p<.4)return}let u=d?.point;if(!u&&!this.useTeleportTarget){this._plane||(this._plane=new pr(new x(0,1,0),0));const p=i.worldPosition;this._plane.setFromNormalAndCoplanarPoint(new x(0,1,0),p);const g=t.ray;u=p.clone(),this._plane.intersectLine(new lC(g.origin,G(g.direction).multiplyScalar(1e4).add(g.origin)),u),u.distanceTo(p)>i.scale.x*10&&(u=null)}if(u){if(this.useTeleportTarget&&!P.getComponentInParent(d.object,Sp))return;const p=u.clone();if(E0&&q.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),E0&&q.DrawWireSphere(g.add(p),.025,65280,5))}this._teleportBuffer.push(i.matrix.clone()),this._teleportBuffer.length>10&&this._teleportBuffer.shift(),this.useTeleportFade?(c=t.xr.fadeTransition())==null||c.then(()=>{i.worldPosition=p}):i.worldPosition=p}}else if(h<-.8&&(this._didTeleport=!0,this._teleportBuffer.length>0)){const d=this._teleportBuffer.pop();d&&d.decompose(i.position,i.quaternion,i.scale)}}renderRays(t){var i;for(let n=0;n<this._lines.length;n++){const o=this._lines[n];o&&(o.visible=!1)}for(let n=0;n<t.controllers.length;n++){const o=t.controllers[n];let r=this._lines[n];if(!o.connected||!o.isTracking||!o.ray||o.targetRayMode==="transient-pointer"||!o.hasSelectEvent){r&&(r.visible=!1);continue}r||(r=this.createRayLineObject(),r.scale.z=.5,this._lines[n]=r),o.updateRayWorldPosition(),o.updateRayWorldQuaternion();const l=o.rayWorldPosition,c=o.rayWorldQuaternion;r.position.copy(l),r.quaternion.copy(c);const h=t.rigScale,d=this.usePinchToTeleport&&o.isTeleportGesture,u=this._lastHitDistances[n],p=this._hitDistances[n]!=null,g=u??h;r.scale.set(h,h,g),r.visible=!0,r.layers.disableAll(),r.layers.enable(2);let y=r.material.opacity;d?y=1:this.showHits&&g<t.rigScale*.5?y=0:(i=o.getButton("primary"))!=null&&i.pressed?y=.5:y=p?.2:.1,r.material.opacity=W.lerp(r.material.opacity,y,this.context.time.deltaTimeUnscaled/.1),r.parent!==this.context.scene&&this.context.scene.add(r)}}renderHits(t){var i;for(const n of this._hitDiscs){if(!n)continue;const o=n.controller;if(!o||!o.connected||!o.isTracking){n.visible=!1;continue}}for(let n=0;n<t.controllers.length;n++){const o=t.controllers[n];if(!o.connected||!o.isTracking||!o.ray||!o.hasSelectEvent)continue;let r=this._hitDiscs[n],l=!0;const c=o.getPointerId("primary");c!=null&&this.context.input.getIsPointerIdInUse(c)&&(r&&(r.visible=!1),this._hitDistances[n]=null,this._lastHitDistances[n]=0,l=!1);const h=this.context.time.smoothedFps>=59?1:10;if((this.context.time.frame+o.index)%h!==0&&(l=!1),!l){const p=this._hitDiscs[n];p&&p.visible&&p.hit&&this.updateHitPointerPosition(o,p,p.hit.distance);continue}const d=this.context.physics.raycastFromRay(o.ray,{testObject:this.hitPointRaycastFilter,precise:!1});let u=d.find(p=>this.usePinchToTeleport&&o.isTeleportGesture?!0:this.isObjectWithInteractiveComponent(p.object));if(u||(u=d[0]),r&&(r.controller=o,r.hit=u),this._hitDistances[n]=u?.distance||null,u){this._lastHitDistances[n]=u.distance;const p=t.rigScale??1;E0&&(q.DrawWireSphere(u.point,.025*p,16711680),q.DrawLabel(G(0,.2,0).add(u.point),u.object.name,.02,0)),r||(r=this.createHitPointObject(),this._hitDiscs[n]=r),r.hit=u,r.visible=u.distance>p*.05;let g=.01*(p+u.distance);const y=(i=o.getButton("primary"))==null?void 0:i.pressed;y&&(g*=1.1),r.scale.set(g,g,g),r.layers.set(2);let f=r.material.opacity;if(y?f=1:f=u.distance<.15*p?.2:.6,r.material.opacity=W.lerp(r.material.opacity,f,this.context.time.deltaTimeUnscaled/.1),r.visible){if(u.normal){this.updateHitPointerPosition(o,r,u.distance);const v=u.normal.applyQuaternion(Oe(u.object));r.quaternion.setFromUnitVectors(JT,v)}else this.updateHitPointerPosition(o,r,u.distance);r.parent!==this.context.scene&&this.context.scene.add(r)}}else this._hitDiscs[n]&&(this._hitDiscs[n].visible=!1)}}isObjectWithInteractiveComponent(t,i=0){return Tu(t)||t.isUI===!0?!0:t.isScene?!1:t.parent?this.isObjectWithInteractiveComponent(t.parent,i+1):!1}updateHitPointerPosition(t,i,n){const o=G(t.rayWorldPosition);o.add(G(0,0,n-.01).applyQuaternion(t.rayWorldQuaternion)),i.position.lerp(o,this.context.time.deltaTimeUnscaled/.05)}createHitPointObject(){const t=new K(new hd(.3,6,6),new Re({color:15658734,opacity:.7,transparent:!0,depthTest:!1,depthWrite:!1,side:xi}));return t.layers.disableAll(),t.layers.enable(2),t}createRayLineObject(){const t=new NC;t.layers.disableAll(),t.layers.enable(2);const i=new WC;t.geometry=i;const n=new Float32Array(9);n.set([0,0,.02,0,0,.4,0,0,1]),i.setPositions(n);const o=new Float32Array(9);o.set([1,1,1,.1,.1,.1,0,0,0]),i.setColors(o);const r=new VC({color:16777215,vertexColors:!0,worldUnits:!0,linewidth:.004,transparent:!0,depthWrite:!1,blending:iv,dashed:!1});return t.material=r,t}}qo([m()],Di.prototype,"movementSpeed",2),qo([m()],Di.prototype,"rotationStep",2),qo([m()],Di.prototype,"useTeleport",2),qo([m()],Di.prototype,"usePinchToTeleport",2),qo([m()],Di.prototype,"useTeleportTarget",2),qo([m()],Di.prototype,"useTeleportFade",2),qo([m()],Di.prototype,"showRays",2),qo([m()],Di.prototype,"showHits",2);const JT=new x(0,1,0);var eE=Object.defineProperty,tE=Object.getOwnPropertyDescriptor,St=(s,t,i,n)=>{for(var o=n>1?void 0:n?tE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&eE(t,i,o),o};const wh=O("debugwebxr"),iE=O("debugusdz");var A0;const Ol=(A0=class extends A{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,"onAvatarSpawned",s=>{wh&&console.log("WebXR.onAvatarSpawned",s),P.getComponentInChildren(s,Ho)??(e=P.addComponent(s,Ho))}),a(this,"_buttonFactory"),a(this,"_buttons",[])}awake(){J.getXRSync(this.context)}onEnable(){var s,t;window.location.protocol!=="https:"&&xe('<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(Ge)||(wh&&console.log("WebXR: Adding USDZExporter"),this._usdzExporter=P.addComponent(this.gameObject,Ge),this._usdzExporter.objectToExport=this.context.scene,this._usdzExporter.autoExportAnimations=!0,this._usdzExporter.autoExportAudioSources=!0)),this.handleCreatingHTML(),this.handleOfferSession(),this.defaultAvatar===!0&&(wh&&console.warn("WebXR: No default avatar set, using static default avatar"),this.defaultAvatar=new ae("https://cdn.needle.tools/static/avatars/DefaultAvatar.glb")),this.defaultAvatar&&(this._playerSync=this.gameObject.getOrAddComponent(Sl),this._playerSync.autoSync=!1),this._playerSync&&typeof this.defaultAvatar!="boolean"&&(this._playerSync.asset=this.defaultAvatar,(s=this._playerSync.onPlayerSpawned)==null||s.removeEventListener(this.onAvatarSpawned),(t=this._playerSync.onPlayerSpawned)==null||t.addEventListener(this.onAvatarSpawned))}onDisable(){var s;(s=this._usdzExporter)==null||s.destroy(),this.removeButtons()}async handleOfferSession(){return this.createVRButton&&await J.isVRSupported()&&this.createVRButton?J.offerSession("immersive-vr","default",this.context):this.createARButton&&await J.isARSupported()&&this.createARButton?J.offerSession("immersive-ar","default",this.context):!1}get session(){return J.active??null}get sessionMode(){return J.activeMode??null}async enterVR(s){return J.start("immersive-vr",s,this.context)}async enterAR(s){return J.start("immersive-ar",s,this.context)}exitXR(){J.stop()}get isActiveWebXR(){return!Ol.activeWebXRComponent||Ol.activeWebXRComponent===this}onBeforeXR(s,t){var i;if(!this.isActiveWebXR){console.warn(`WebXR: another WebXR component is already active (${(i=Ol.activeWebXRComponent)==null?void 0:i.name}). This is ignored: ${this.name}`);return}Ol.activeWebXRComponent=this,s=="immersive-ar"&&this.useDepthSensing&&(t.optionalFeatures=t.optionalFeatures||[],t.optionalFeatures.push("depth-sensing"))}async onEnterXR(s){if(!this.isActiveWebXR)return;wh&&console.log("WebXR onEnterXR"),this._previousXRState=Kt.Global.Mask;const t=s.xr.isVR;if(Kt.Global.Set(t?Zs.VR:Zs.AR),s.xr.isAR){let i=P.findObjectOfType(Hn);if(!i)if(this.usePlacementReticle){const n=new I;for(const o of this.context.scene.children)n.add(o);this.context.scene.add(n),i=P.addComponent(n,Hn),this._createdComponentsInSession.push(i)}else(wh||F())&&console.warn("WebXR: No WebARSessionRoot found in scene and usePlacementReticle is disabled in WebXR component.");i&&(i.customReticle=this.customARPlacementReticle,i.arScale=this.arScale,i.arTouchTransform=this.usePlacementAdjustment,i.autoPlace=this.autoPlace,i.autoCenter=this.autoCenter,i.useXRAnchor=this.useXRAnchor)}this.useDefaultControls&&this.setDefaultMovementEnabled(!0),(this.showControllerModels||this.showHandModels)&&this.setDefaultControllerRenderingEnabled(!0),this.useSpatialGrab&&(this._spatialGrabRaycaster=P.findObjectOfType(Qa)??void 0,this._spatialGrabRaycaster||(this._spatialGrabRaycaster=this.gameObject.addComponent(Qa))),this.createLocalAvatar(s.xr),s.xr.isScreenBasedAR||(this._exitXRMenuButton=this.context.menu.appendChild({label:"Quit XR",onClick:()=>this.exitXR(),icon:"exit_to_app",priority:2e4}))}onUpdateXR(s){this.isActiveWebXR&&this._spatialGrabRaycaster&&(this._spatialGrabRaycaster.enabled=this.useSpatialGrab)}onLeaveXR(s){var t,i;if((t=this._exitXRMenuButton)==null||t.remove(),!!this.isActiveWebXR){Kt.Global.Set(this._previousXRState),(i=this._playerSync)==null||i.destroyInstance();for(const n of this._createdComponentsInSession)n.destroy();this._createdComponentsInSession.length=0,this.handleOfferSession(),Jl(1).then(()=>Ol.activeWebXRComponent=null)}}setDefaultMovementEnabled(s){let t=this.gameObject.getComponent(Di);return!t&&s&&(t=this.gameObject.addComponent(Di),this._createdComponentsInSession.push(t)),t&&(t.enabled=s),t}setDefaultControllerRenderingEnabled(s){let t=this.gameObject.getComponent(ln);return!t&&s&&(t=this.gameObject.addComponent(ln),this._createdComponentsInSession.push(t),t.createControllerModel=this.showControllerModels,t.createHandModel==this.showHandModels),t&&(t.enabled=s),t}async createLocalAvatar(s){this._playerSync&&s.running&&typeof this.defaultAvatar!="boolean"&&(this._playerSync.asset=this.defaultAvatar,await this._playerSync.getInstance())}getButtonsContainer(){return this.getButtonsFactory()}getButtonsFactory(){return this._buttonFactory||(this._buttonFactory=Kr.getOrCreate()),this._buttonFactory}handleCreatingHTML(){if(this.createARButton||this.createVRButton||this.useQuicklookExport){if((X.isiOS()&&X.isSafari()||iE)&&this.useQuicklookExport){const s=P.findObjectOfType(Ge);if(!s||s&&s.allowCreateQuicklookButton){const t=this.getButtonsFactory().createQuicklookButton();this.addButton(t,50)}}if(this.createARButton){const s=this.getButtonsFactory().createARButton();this.addButton(s,50)}if(this.createVRButton){const s=this.getButtonsFactory().createVRButton();this.addButton(s,50)}}if(this.createSendToQuestButton&&!X.isQuest()&&J.isVRSupported().then(s=>{if(!s){const t=this.getButtonsFactory().createSendToQuestButton();this.addButton(t,50)}}),this.createQRCode){const s=Zd(an);if(s&&s.createQRCodeButton===!1)F()&&console.warn("WebXR: QRCode button is disabled in the Needle Menu component");else if(!X.isMobileDevice()){const t=Tn.getOrCreate().createQRCode();this.addButton(t,50)}}}addButton(s,t){this._buttons.push(s),s.setAttribute("priority",t.toString()),this.context.menu.appendChild(s)}removeButtons(){for(const s of this._buttons)s.remove();this._buttons.length=0}},a(A0,"activeWebXRComponent",null),A0);let tt=Ol;St([m()],tt.prototype,"createVRButton",2),St([m()],tt.prototype,"createARButton",2),St([m()],tt.prototype,"createSendToQuestButton",2),St([m()],tt.prototype,"createQRCode",2),St([m()],tt.prototype,"useDefaultControls",2),St([m()],tt.prototype,"showControllerModels",2),St([m()],tt.prototype,"showHandModels",2),St([m()],tt.prototype,"usePlacementReticle",2),St([m(ae)],tt.prototype,"customARPlacementReticle",2),St([m()],tt.prototype,"usePlacementAdjustment",2),St([m()],tt.prototype,"arScale",2),St([m()],tt.prototype,"useXRAnchor",2),St([m()],tt.prototype,"autoPlace",2),St([m()],tt.prototype,"autoCenter",2),St([m()],tt.prototype,"useQuicklookExport",2),St([m()],tt.prototype,"useDepthSensing",2),St([m()],tt.prototype,"useSpatialGrab",2),St([m(ae)],tt.prototype,"defaultAvatar",2);const xh=O("debugusdz");function sE(s,t){var i;const n=[],o=P.getComponentsInChildren(s,kt),r=P.getComponentsInChildren(s,Wt),l=new Array,c=new Array;if(t.injectImplicitBehaviours)for(const h of o){if(!h||!h.runtimeAnimatorController||!h.enabled)continue;const d=h.runtimeAnimatorController.activeState;if(!d||!d.motion||!d.motion.clip||((i=d.motion.clip.tracks)==null?void 0:i.length)<1||l.includes(h))continue;const u=new Xr;u.animator=h,u.stateName=d.name,u.trigger="start",u.name="PlayAnimationOnClick_implicitAtStart_"+u.stateName;const p=new I;P.addComponent(p,u),c.push(p),l.push(h),s.add(p)}else for(const h of o){if(!h||!h.runtimeAnimatorController||!h.enabled)continue;xh&&console.log(h);const d=[];for(const u of h.runtimeAnimatorController.enumerateActions()){xh&&console.log(u);const p=u.getClip();d.includes(p)||d.push(p)}n.push({root:h.gameObject,clips:d})}if(t.injectImplicitBehaviours)for(const h of r){if(!h||!h.clip||!h.enabled||!h.playAutomatically||l.includes(h))continue;const d=new Xr;d.animation=h,d.stateName=h.clip.name,d.trigger="start",d.name="PlayAnimationOnClick_implicitAtStart_"+d.stateName;const u=new I;P.addComponent(u,d),c.push(u),l.push(h),s.add(u)}else for(const h of r){xh&&console.log(h);const d=[];for(const u of h.animations)d.includes(u)||d.push(u);n.push({root:h.gameObject,clips:d})}xh&&n?.length>0&&console.log("USDZ Animation Clips without behaviours",n);for(const h of n)for(const d of h.clips)t.registerAnimation(h.root,d);return c}function nE(s,t){const i=P.getComponentsInChildren(s,We),n=P.getComponentsInChildren(s,Bo),o=new Array,r=new Array;xh&&console.log({audioSources:i,playAudioOnClicks:n});for(const l of n){if(!l.target)continue;const c=i.indexOf(l.target);c>-1&&i.splice(c,1)}for(const l of i){if(!l||!l.clip||l.volume<=0||o.includes(l))continue;const c=new Bo;c.target=l,c.name="PlayAudioOnClick_implicitAtStart_",c.trigger="start";const h=new I;P.addComponent(h,c),console.log("implicit PlayAudioOnStart",h,c),r.push(h),o.push(l),s.add(h)}return r}function oE(s){return new Tt("DisableAtStart",wt.sceneStartTrigger(),fe.fadeAction(s,0,!1))}function t1(s,t){const i=s.domElement.shadowRoot.querySelector("link[rel='ar']");if(i)return i;const n=document.createElement("div");n.classList.add("menu"),n.classList.add("quicklook-menu"),n.style.display="none",n.style.visibility="hidden";const o=document.createElement("button");o.id="open-in-ar",t?(o.innerText="View in AR",o.title="View this scene in AR. The scene will be exported to USDZ and opened with Apple's QuickLook."):(o.innerText="View in AR",o.title="Download this scene for AR. Open the downloaded USDZ file to view it in AR using Apple's QuickLook."),n.appendChild(o);const r=document.createElement("a");r.id="needle-usdz-link",r.style.display="none",r.rel="ar",r.href="",r.target="_blank",n.appendChild(r);const l=document.createElement("img");return l.id="button",r.appendChild(l),s.domElement.shadowRoot.appendChild(n),r}var rE=Object.defineProperty,aE=Object.getOwnPropertyDescriptor,It=(s,t,i,n)=>{for(var o=n>1?void 0:n?aE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&rE(t,i,o),o};const Bi=O("debugusdz"),lE=O("debugusdzpruning");class Go{constructor(){a(this,"callToAction"),a(this,"checkoutTitle"),a(this,"checkoutSubtitle"),a(this,"callToActionURL")}}It([m()],Go.prototype,"callToAction",2),It([m()],Go.prototype,"checkoutTitle",2),It([m()],Go.prototype,"checkoutSubtitle",2),It([m()],Go.prototype,"callToActionURL",2);var Cp;const I0=(Cp=class extends A{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",s=>{s.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 V),a(this,"_rootScaleBeforeExport",new x)}start(){var s,t,i;Bi&&(console.log("USDZExporter",this),console.log("Debug USDZ Mode. Press 'T' to export"),window.addEventListener("keydown",n=>{switch(n.key){case"t":this.exportAndOpen();break}})),this.objectToExport||(this.objectToExport=this.gameObject),!((t=(s=this.objectToExport)==null?void 0:s.children)!=null&&t.length)&&!((i=this.objectToExport)!=null&&i.isMesh)&&(this.objectToExport=this.context.scene)}onEnable(){var s;const t=X.supportsQuickLookAR(),i=X.isiOS()||X.isiPad();!this.button&&(Bi||t||i)&&(this.allowCreateQuicklookButton&&(this.button=this.createQuicklookButton()),this.lastCallback=this.quicklookCallback.bind(this),this.link=t1(this.context,t),this.link.addEventListener("message",this.lastCallback)),Bi&&De("USDZ Exporter enabled: "+this.name),(s=document.getElementById("open-in-ar"))==null||s.addEventListener("click",this.onClickedOpenInARElement),gc.registerExporter(this)}onDisable(){var s,t,i;(s=this.button)==null||s.remove(),(t=this.link)==null||t.removeEventListener("message",this.lastCallback),Bi&&De("USDZ Exporter disabled: "+this.name),(i=document.getElementById("open-in-ar"))==null||i.removeEventListener("click",this.onClickedOpenInARElement),gc.unregisterExporter(this)}async exportAsync(){return this.exportAndOpen()}async exportAndOpen(){var s;let t=this.exportFileName??((s=this.objectToExport)==null?void 0:s.name)??this.name;if(t+="-"+yx(),_o()||(t!==""&&(t+="-"),t+="MadeWithNeedle"),this.link||(this.link=t1(this.context,X.supportsQuickLookAR())),this.customUsdzFile)return Bi&&console.log("Exporting custom usdz",this.customUsdzFile),this.openInQuickLook(this.customUsdzFile,t),null;if(!this.objectToExport)return console.warn("No object to export",this),null;const i=await this.export(this.objectToExport);return i?(Bi&&console.log("USDZ generation done. Downloading as "+t),this.openInQuickLook(i,t),i):(console.error("USDZ generation failed. Please report a bug",this),null)}async export(s){if(!s)return console.warn("No object to export"),null;const t=this._currentExportTasks.get(s);if(t)return t;const i=this.internalExport(s);return i instanceof Promise?(this._currentExportTasks.set(s,i),i.then(n=>(this._currentExportTasks.delete(s),n)).catch(n=>(this._currentExportTasks.delete(s),console.error("Error during USDZ export \u2013 please report a bug!",n),null))):i}async internalExport(s){ce.start("export-usdz",{onProgress:C=>{this.dispatchEvent(new CustomEvent("export-progress",{detail:{progress:C}}))}}),ce.report("export-usdz",{message:"Starting export",totalSteps:40,currentStep:0}),ce.report("export-usdz",{message:"Load progressive textures",autoStep:5}),ce.start("export-usdz-textures","export-usdz");const t=P.getComponentsInChildren(s,fi);for(const C of t)C&&C.enabled&&C.updateSprite(!0);const i=P.getComponentsInChildren(s,et),n=new Array;let o=0;for(const C of i){for(const R of C.sharedMeshes)if(R){const M=it.assignMeshLOD(R,0);M instanceof Promise&&n.push(new Promise((T,j)=>{M.then(()=>{o++,ce.report("export-usdz-textures",{message:"Loaded progressive mesh",currentStep:o,totalSteps:n.length}),T()}).catch(D=>j(D))}))}for(const R of C.sharedMaterials)if(R){const M=it.assignTextureLOD(R,0);M instanceof Promise&&n.push(new Promise((T,j)=>{M.then(()=>{o++,ce.report("export-usdz-textures",{message:"Loaded progressive texture",currentStep:o,totalSteps:n.length}),T()}).catch(D=>j(D))}))}}Bi&&De("Progressive Loading: "+n.length),await Promise.all(n),Bi&&De("Progressive Loading: done"),ce.end("export-usdz-textures");const r=Kt.Global.Mask;Kt.Global.Set(Zs.AR);const l=new xx,c=new lh(this.quickLookCompatible);let h;const d=[];this.interactive&&(d.push(new up),d.push(new dr),globalThis.false&&P.getComponentsInChildren(s,ve).length>0&&(this.physics?(h=new mp,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 fh),d.push(new vp));const u=[c,...d,...this.extensions],p={self:this,exporter:l,extensions:u,object:s};ce.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,ce.report("export-usdz","auto export animations and audio sources");const g=new Array;this.autoExportAnimations&&g.push(...sE(s,c)),u.find(C=>C.extensionName==="Audio")&&this.autoExportAudioSources&&g.push(...nE(s)),l.debug=Bi,l.pruneUnusedNodes=!lE;const y=Hr.instance.objs.map(C=>C.batchedMesh);l.keepObject=C=>{let R=!0;const M=P.getComponent(C,et);return M&&!M.enabled&&(R=!1),R&&y.includes(C)&&(R=!1),R&&P.getComponentInParent(C,ks)&&(R=!1),R&&P.getComponentInParent(C,Hs)&&(R=!1),Bi&&!R&&console.log("USDZExporter: Discarding object",C),R},l.beforeWritingDocument=()=>{if(F()&&c&&h){const C=c.animatedRoots;for(const R of C){const M=P.getComponentsInChildren(R,ve).filter(j=>j.enabled),T=P.getComponents(R,pi).filter(j=>j.enabled&&!j.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.",R)}}};const f=new Array;this.objectToExport&&this.quickLookCompatible&&this.interactive&&this.objectToExport.traverse(C=>{C.visible||f.push(C)});const v=u.find(C=>C.extensionName==="Behaviour");this.interactive&&v&&f.length>0&&v.addBehavior(oE(f));let b=!0;this.quickLookCompatible&&!this.interactive&&(b=!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"),ce.report("export-usdz","Invoking exporter.parse");const w=await l.parse(this.objectToExport,{ar:{anchoring:{type:this.anchoringType},planeAnchoring:{alignment:this.planeAnchoringAlignment}},extensions:u,quickLookCompatible:this.quickLookCompatible,maxTextureSize:this.maxTextureSize,exportInvisible:b}),_=new Blob([w],{type:"model/vnd.usdz+zip"});this.revertWebARSessionRoot(),this.context.time.timeScale=this._previousTimeScale,ce.report("export-usdz","Invoking after-export"),this.dispatchEvent(new CustomEvent("after-export",{detail:p}));for(const C of g)P.destroy(C);return Kt.Global.Set(r),ce.end("export-usdz"),_}openInQuickLook(s,t){const i=s instanceof Blob?URL.createObjectURL(s):s,n=this.buildQuicklookOverlay();Bi&&console.log("QuickLook Overlay",n);const o=n.callToAction?encodeURIComponent(n.callToAction):"",r=n.checkoutTitle?encodeURIComponent(n.checkoutTitle):"",l=n.checkoutSubtitle?encodeURIComponent(n.checkoutSubtitle):"";this.link.href=i+`#callToAction=${o}&checkoutTitle=${r}&checkoutSubtitle=${l}&callToActionURL=${n.callToActionURL}`,this.lastCallback||(this.lastCallback=this.quicklookCallback.bind(this),this.link.addEventListener("message",this.lastCallback)),this.link.download=t+".usdz",this.link.click()}download(s,t){I0.save(s,t)}static save(s,t){const i=document.createElement("a");i.style.display="none",document.body.appendChild(i),typeof s=="string"?i.href=s:i.href=URL.createObjectURL(s),i.download=t,i.click(),i.remove()}quicklookCallback(s){if(s?.data=="_apple_ar_quicklook_button_tapped"){Bi&&xe("Quicklook closed via call to action button");var t=new CustomEvent("quicklook-button-tapped",{detail:this});if(this.dispatchEvent(t),!t.defaultPrevented){const i=new URLSearchParams(this.link.href);if(i){const n=i.get("callToActionURL");Bi&&De("Quicklook url: "+n),n&&(_o()?globalThis.open(n,"_blank"):console.warn("Quicklook closed: custom redirects require a Needle Engine Pro license: https://needle.tools/pricing",n))}}}}buildQuicklookOverlay(){var s,t,i,n,o,r;const l={};return this.customBranding&&Object.assign(l,this.customBranding),_o()||(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="_"),(((s=l.callToAction)==null?void 0:s.length)||((t=l.checkoutTitle)==null?void 0:t.length)||((i=l.checkoutSubtitle)==null?void 0:i.length))&&((n=l.callToAction)!=null&&n.length||(l.callToAction="\0"),(o=l.checkoutTitle)!=null&&o.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 s=P.findObjectOfType(tt);let t=P.getComponentInParent(this.objectToExport,Hn);t||(t=P.getComponentInChildren(this.objectToExport,Hn));let i=1,n=!1;const o=this.objectToExport;return s?i=s.arScale:t&&(i=t.arScale,n=t.invertForward),{scale:1/i,_invertForward:n,target:o,sessionRoot:t?.gameObject??null}}applyWebARSessionRoot(){if(!this.objectToExport)return;const{scale:s,_invertForward:t,target:i,sessionRoot:n}=this.getARScaleAndTarget(),o=n?.matrixWorld.clone().invert();this._rootSessionRootWasAppliedTo=i,this._rootPositionBeforeExport.copy(i.position),this._rootRotationBeforeExport.copy(i.quaternion),this._rootScaleBeforeExport.copy(i.scale),i.scale.multiplyScalar(s),t&&i.quaternion.multiply(I0.invertForwardQuaternion),i.updateMatrix(),i.updateMatrixWorld(!0),n&&o&&i.matrix.premultiply(o)}revertWebARSessionRoot(){if(!this.objectToExport||!this._rootSessionRootWasAppliedTo)return;const s=this._rootSessionRootWasAppliedTo;s.position.copy(this._rootPositionBeforeExport),s.quaternion.copy(this._rootRotationBeforeExport),s.scale.copy(this._rootScaleBeforeExport),s.updateMatrix(),s.updateMatrixWorld(!0),this._rootSessionRootWasAppliedTo=null}createQuicklookButton(){const s=Kr.getOrCreate().createQuicklookButton();return s.parentNode||this.context.menu.appendChild(s),s}},a(Cp,"invertForwardMatrix",new ne().makeRotationY(Math.PI)),a(Cp,"invertForwardQuaternion",new V().setFromEuler(new Ut(0,Math.PI,0))),Cp);let Ge=I0;It([m(I)],Ge.prototype,"objectToExport",2),It([m()],Ge.prototype,"autoExportAnimations",2),It([m()],Ge.prototype,"autoExportAudioSources",2),It([m()],Ge.prototype,"exportFileName",2),It([m(URL)],Ge.prototype,"customUsdzFile",2),It([m(Go)],Ge.prototype,"customBranding",2),It([m()],Ge.prototype,"anchoringType",2),It([m()],Ge.prototype,"maxTextureSize",2),It([m()],Ge.prototype,"planeAnchoringAlignment",2),It([m()],Ge.prototype,"interactive",2),It([m()],Ge.prototype,"physics",2),It([m()],Ge.prototype,"allowCreateQuicklookButton",2),It([m()],Ge.prototype,"quickLookCompatible",2);var cE=Object.defineProperty,hE=Object.getOwnPropertyDescriptor,j0=(s,t,i,n)=>{for(var o=n>1?void 0:n?hE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&cE(t,i,o),o};class Pl extends A{constructor(){super(...arguments),a(this,"_fog")}get fog(){return this._fog||(this._fog=new $y(0,0,50)),this._fog}get mode(){return 1}set near(t){this.fog.near=t}get near(){return this.fog.near}set far(t){this.fog.far=t}get far(){return this.fog.far}set color(t){this.fog.color.copy(t)}get color(){return this.fog.color}onEnable(){this.scene.fog=this.fog}onDisable(){this.scene.fog===this._fog&&(this.scene.fog=null)}}j0([m()],Pl.prototype,"near",1),j0([m()],Pl.prototype,"far",1),j0([m(re)],Pl.prototype,"color",1);var dE=Object.defineProperty,uE=Object.getOwnPropertyDescriptor,L0=(s,t,i,n)=>{for(var o=n>1?void 0:n?uE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&dE(t,i,o),o};class Zr extends A{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&&!Sc||(this._gizmoObject||(this.objectBounds?this._gizmoObject=new cC(this.gameObject,this.color??16776960):(this.objectBounds=!1,this._gizmoObject=_g(this.color??16776960))),this.objectBounds?(this.scene.add(this._gizmoObject),this._boxHelper=this._gizmoObject,this.startCoroutine(this.syncObjectBounds(),Me.OnBeforeRender)):this.gameObject.add(this._gizmoObject))}onDisable(){this._gizmoObject&&this.gameObject.remove(this._gizmoObject)}*syncObjectBounds(){for(var t;this._boxHelper;)(t=this._boxHelper)==null||t.update(),yield}}L0([m()],Zr.prototype,"objectBounds",2),L0([m(re)],Zr.prototype,"color",2),L0([m()],Zr.prototype,"isGizmo",2);var pE=Object.defineProperty,mE=Object.getOwnPropertyDescriptor,D0=(s,t,i,n)=>{for(var o=n>1?void 0:n?mE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&pE(t,i,o),o};class kl extends A{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&&!Sc)return;const t=this.size,i=this.divisions;this.gridHelper||(this.gridHelper=new cm(t,i,this.color0??new re(.4,.4,.4),this.color1??new re(.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)}}D0([m()],kl.prototype,"isGizmo",2),D0([m(re)],kl.prototype,"color0",2),D0([m(re)],kl.prototype,"color1",2);var gE=Object.defineProperty,fE=Object.getOwnPropertyDescriptor,B0=(s,t,i,n)=>{for(var o=n>1?void 0:n?fE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&gE(t,i,o),o};class F0 extends A{constructor(){super(...arguments),a(this,"connectedBody"),a(this,"_rigidBody",null)}get rigidBody(){return this._rigidBody}onEnable(){this._rigidBody||(this._rigidBody=this.gameObject.getComponent(ve)),this.rigidBody&&this.connectedBody&&this.startCoroutine(this.create())}*create(){yield,this.rigidBody&&this.connectedBody&&this.activeAndEnabled&&this.createJoint(this.rigidBody,this.connectedBody)}}B0([m(ve)],F0.prototype,"connectedBody",2);class z0 extends F0{createJoint(t,i){var n;(n=this.context.physics.engine)==null||n.addFixedJoint(t,i)}}class Sh extends F0{constructor(){super(...arguments),a(this,"anchor"),a(this,"axis")}createJoint(t,i){var n;this.axis&&this.anchor&&((n=this.context.physics.engine)==null||n.addHingeJoint(t,i,this.anchor,this.axis))}}B0([m(x)],Sh.prototype,"anchor",2),B0([m(x)],Sh.prototype,"axis",2);var yE=Object.defineProperty,vE=Object.getOwnPropertyDescriptor,cn=(s,t,i,n)=>{for(var o=n>1?void 0:n?vE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&yE(t,i,o),o};function U0(s){return s*Math.PI/180}const i1=300,Xo=O("debuglights");class yi extends A{constructor(){super(...arguments),a(this,"type",0),a(this,"range",1),a(this,"spotAngle",1),a(this,"innerSpotAngle",1),a(this,"_color",new re(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(t){this._color=t,this.light!==void 0&&(this.light.color=t)}get color(){return this.light?this.light.color:this._color}set shadowNearPlane(t){var i,n;if(t!==this._shadowNearPlane&&(this._shadowNearPlane=t,((n=(i=this.light)==null?void 0:i.shadow)==null?void 0:n.camera)!==void 0)){const o=this.light.shadow.camera;o.near=t}}get shadowNearPlane(){return this._shadowNearPlane}set shadowBias(t){var i,n;t!==this._shadowBias&&(this._shadowBias=t,((n=(i=this.light)==null?void 0:i.shadow)==null?void 0:n.bias)!==void 0&&(this.light.shadow.bias=t,this.light.shadow.needsUpdate=!0))}get shadowBias(){return this._shadowBias}set shadowNormalBias(t){var i,n;t!==this._shadowNormalBias&&(this._shadowNormalBias=t,((n=(i=this.light)==null?void 0:i.shadow)==null?void 0:n.normalBias)!==void 0&&(this.light.shadow.normalBias=t,this.light.shadow.needsUpdate=!0))}get shadowNormalBias(){return this._shadowNormalBias}set shadows(t){this._shadows=t,this.light&&(this.light.castShadow=t!==0,this.updateShadowSoftHard())}get shadows(){return this._shadows}set intensity(t){var i;if(this._intensity=t,this.light){let n=1;if(this.context.isInXR&&this._webARRoot){const o=(i=this._webARRoot)==null?void 0:i.arScale;typeof o=="number"&&o>0&&(n/=o)}this.light.intensity=t*n}Xo&&console.log("Set light intensity to "+this._intensity,t,this)}get intensity(){return this._intensity}get shadowDistance(){const t=this.light;return t!=null&&t.shadow?t.shadow.camera.far:-1}set shadowDistance(t){this._shadowDistance=t;const i=this.light;if(i!=null&&i.shadow){const n=i.shadow.camera;n.far=t,n.updateProjectionMatrix()}}get shadowResolution(){const t=this.light;return t!=null&&t.shadow?t.shadow.mapSize.x:-1}set shadowResolution(t){if(t===this._shadowResolution)return;this._shadowResolution=t;const i=this.light;i!=null&&i.shadow&&(i.shadow.mapSize.set(t,t),i.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(t){return this.light?this.type===1?this.light.getWorldPosition(t).multiplyScalar(1):this.light.getWorldPosition(t):t}awake(){this.color=new re(this.color??16777215),Xo&&console.log(this.name,this)}onEnable(){Xo&&console.log("ENABLE LIGHT",this.name),this.createLight(),!this.isBaked&&(this.light&&(this.light.visible=!0,this.light.intensity=this._intensity,Xo&&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(),Me.LateUpdate))}onDisable(){Xo&&console.log("DISABLE LIGHT",this.name),this.light&&(this.selfIsLight?this.light.intensity=0:this.light.visible=!1)}onEnterXR(t){this._webARRoot=P.getComponentInParent(this.gameObject,Hn)??void 0}onLeaveXR(t){}createLight(){const t=this.selfIsLight;if(t&&!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 i=new hm(this.color,this.intensity*Math.PI);if(i.position.set(0,0,-i1*.5).applyQuaternion(this.gameObject.quaternion),this.gameObject.add(i.target),yr(i.target,0,0,0),this.light=i,this.gameObject.position.set(0,0,0),this.gameObject.rotation.set(0,0,0),Xo){const l=new dC(this.light,.2,this.color);this.context.scene.add(l)}break;case 0:const n=new hC(this.color,this.intensity*Math.PI,this.range,U0(this.spotAngle/2),1-U0(this.innerSpotAngle/2)/U0(this.spotAngle/2),2);n.position.set(0,0,0),n.rotation.set(0,0,0),this.light=n;const o=n.target;n.add(o),o.position.set(0,0,this.range),o.rotation.set(0,0,0);break;case 2:const r=new qy(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),Xo&&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 i=this.light.shadow.camera;if(i.near=this.shadowNearPlane,this._shadowDistance!==void 0&&typeof this._shadowDistance=="number"?i.far=this._shadowDistance:i.far=i1*Math.abs(this.gameObject.scale.z),this.gameObject.scale.set(1,1,1),this.shadowWidth!==void 0)i.left=-this.shadowWidth/2,i.right=this.shadowWidth/2;else{const n=this.gameObject.scale.x;i.left*=n,i.right*=n}if(this.shadowHeight!==void 0)i.top=this.shadowHeight/2,i.bottom=-this.shadowHeight/2;else{const n=this.gameObject.scale.y;i.top*=n,i.bottom*=n}this.light.shadow.needsUpdate=!0,Xo&&this.context.scene.add(new uC(i))}this.isBaked?this.light.removeFromParent():t||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(t){t.add(t.target),t.target.position.set(0,0,-1)}}a(yi,"allowChangingRendererShadowMapType",!0),cn([m()],yi.prototype,"type",2),cn([m(re)],yi.prototype,"color",1),cn([m()],yi.prototype,"shadowNearPlane",1),cn([m()],yi.prototype,"shadowBias",1),cn([m()],yi.prototype,"shadowNormalBias",1),cn([m()],yi.prototype,"shadows",1),cn([m()],yi.prototype,"lightmapBakeType",2),cn([m()],yi.prototype,"intensity",1),cn([m()],yi.prototype,"shadowDistance",1),cn([m()],yi.prototype,"shadowResolution",1),new x(0,0,0);var bE=Object.defineProperty,_E=Object.getOwnPropertyDescriptor,Ch=(s,t,i,n)=>{for(var o=n>1?void 0:n?_E(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&bE(t,i,o),o};const N0=O("debuglods"),wE=O("nolods");class Jr{constructor(){a(this,"screenRelativeTransitionHeight"),a(this,"distance"),a(this,"renderers")}}Ch([m()],Jr.prototype,"screenRelativeTransitionHeight",2),Ch([m()],Jr.prototype,"distance",2),Ch([m(et)],Jr.prototype,"renderers",2);class xE{constructor(t){a(this,"model"),this.model=t}get renderers(){return this.model.renderers}}class Oh extends A{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(N0&&console.log("LODGROUP",this.name,this.lodModels,this),!wE&&!this._lodsHandler&&this.gameObject&&this.lodModels&&Array.isArray(this.lodModels)){const t=[];for(const n of this.lodModels){const o=new xE(n);this._lods.push(o);for(const r of o.renderers)t.includes(r)||t.push(r)}this._lodsHandler=new Array;for(let n=0;n<t.length;n++){const o=new pC;this._lodsHandler.push(o),this.gameObject.add(o)}const i=new I;i.name="Cull "+this.name;for(let n=0;n<t.length;n++){const o=t[n],r=this._lodsHandler[n],l=o.gameObject;N0&&console.log(n,l.name);for(const c of this._lods){const h=c.model.distance;let d=null;if(c.renderers.includes(o)?d=l:d=i,d.type==="Group"){console.warn(`LODGroup ${this.name}: Group or MultiMaterial object's are not supported as LOD object: ${d.name}`);continue}N0&&console.log("LEVEL",d.name,h),r.autoUpdate=!1,this.onAddLodLevel(r,d,c.model.distance)}}}}onAfterRender(){if(!this.gameObject||!this._lodsHandler)return;const t=this.context.mainCamera;if(t)for(const i of this._lodsHandler){i.update(t);const n=i.getCurrentLevel(),o=i.levels[n];i.layers.mask=o.object.layers.mask}}onAddLodLevel(t,i,n){if(i===this.gameObject){console.warn("LODGroup component must be on parent object and not mesh directly at the moment",i.name,i);return}t.addLevel(i,n*this._distanceFactor,.01);const o={lod:t,levelIndex:t.levels.length-1,distance:n};this._settings.push(o)}distanceFactor(t){if(t!==this._distanceFactor){this._distanceFactor=t;for(const i of this._settings){const n=i.lod.levels[i.levelIndex];n.distance=i.distance*t}}}}Ch([m(x)],Oh.prototype,"localReferencePoint",2),Ch([m(Jr)],Oh.prototype,"lodModels",2);var SE=Object.defineProperty,CE=Object.getOwnPropertyDescriptor,OE=(s,t,i,n)=>{for(var o=n>1?void 0:n?CE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&SE(t,i,o),o};const Op=O("debugnestedgltf");class Pp extends A{constructor(){super(...arguments),a(this,"filePath"),a(this,"loadAssetInParent",!0),a(this,"_isLoadingOrDoneLoading",!1)}listenToProgress(t){var i;(i=this.filePath)==null||i.beginListenDownload(t)}preload(){var t;(t=this.filePath)==null||t.preload()}async start(){var t,i,n,o,r;if(this._isLoadingOrDoneLoading)return;Op&&console.log(this,this.guid);const l=this.gameObject.parent;if(l){this._isLoadingOrDoneLoading=!0;const c=new Ds;c.idProvider=new zt(this.hash(this.guid)),c.parent=this.loadAssetInParent!==!1?l:this.gameObject,this.gameObject.updateMatrix();const h=this.gameObject.matrix;Op&&console.log("Load nested:",((t=this.filePath)==null?void 0:t.url)??this.filePath,this.gameObject.position);const d=await((n=(i=this.filePath)==null?void 0:i.instantiate)==null?void 0:n.call(this.filePath,c));Op&&console.log("Nested loaded:",((o=this.filePath)==null?void 0:o.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}}))),Op&&console.log("Nested loading done:",((r=this.filePath)==null?void 0:r.url)??this.filePath,d)}}onDestroy(){var t;(t=this.filePath)==null||t.unload()}hash(t){let i=0;for(let n=0;n<t.length;n++)i=t.charCodeAt(n)+((i<<5)-i);return i}}OE([m(ae)],Pp.prototype,"filePath",2);var PE=Object.defineProperty,kE=Object.getOwnPropertyDescriptor,W0=(s,t,i,n)=>{for(var o=n>1?void 0:n?kE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&PE(t,i,o),o};const ME=O("debugnet"),V0=class extends A{constructor(){super(...arguments),a(this,"url",null),a(this,"urlParameterName",null),a(this,"localhost",null)}awake(){ME&&console.log(this),this.context.connection.registerProvider(this)}getWebsocketUrl(){let s=this.url?V0.GetUrl(this.url,this.localhost):null;if(this.urlParameterName){const i=O(this.urlParameterName);i&&typeof i=="string"&&(s=i)}if(!s)return null;const t=new RegExp("(((https?)|(?<socket_prefix>wss?))://)?(www.)?(?<url>.+)","gm").exec(s);return t!=null&&t.groups?t?.groups.socket_prefix?s:"wss://"+t?.groups.url:null}static GetUrl(s,t){let i=s;const n=V0.IsLocalNetwork()&&t;if(n&&(i=t),s!=null&&s.startsWith("/")){const o=n?i:window.location.origin;o!=null&&o.endsWith("/")&&s.startsWith("/")&&(s=s.substring(1)),i=o+s}return i}static IsLocalNetwork(s=window.location.hostname){return Gt(s)}};let Ml=V0;W0([m()],Ml.prototype,"url",2),W0([m()],Ml.prototype,"urlParameterName",2),W0([m()],Ml.prototype,"localhost",2);var RE=Object.defineProperty,TE=Object.getOwnPropertyDescriptor,kp=(s,t,i,n)=>{for(var o=n>1?void 0:n?TE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&RE(t,i,o),o};class ea extends A{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 t=te(this.from),i=Oe(this.from);this.offset.copy(this.positionOffset);const n=this.offset.length();if(this.referenceSpace&&this.offset.transformDirection(this.referenceSpace.matrixWorld).multiplyScalar(n),t.add(this.offset),this.levelPosition&&this.referenceSpace){const c=new pr(this.gameObject.up,0),h=te(this.referenceSpace);c.setFromNormalAndCoplanarPoint(this.gameObject.up,h);const d=new x(0,0,0);c.projectPoint(t,d),t.copy(d)}this.affectPosition&&dt(this.gameObject,t);const o=new Ut(this.rotationOffset.x,this.rotationOffset.y,this.rotationOffset.z),r=new V().setFromEuler(o);this.affectRotation&&Gi(this.gameObject,i.multiply(r));const l=new x;this.from.getWorldDirection(l).multiplyScalar(50),this.levelLookDirection&&(l.y=0),this.alignLookDirection&&this.gameObject.lookAt(l)}}kp([m(P)],ea.prototype,"referenceSpace",2),kp([m(P)],ea.prototype,"from",2),kp([m(x)],ea.prototype,"positionOffset",2),kp([m(x)],ea.prototype,"rotationOffset",2);var EE=Object.defineProperty,AE=Object.getOwnPropertyDescriptor,k=(s,t,i,n)=>{for(var o=n>1?void 0:n?AE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&EE(t,i,o),o};const Mp=O("debugparticles");var qn=(s=>(s[s.Billboard=0]="Billboard",s[s.Stretch=1]="Stretch",s[s.HorizontalBillboard=2]="HorizontalBillboard",s[s.VerticalBillboard=3]="VerticalBillboard",s[s.Mesh=4]="Mesh",s))(qn||{});class Qo{constructor(){a(this,"alphaKeys",[]),a(this,"colorKeys",[])}get duration(){return 1}evaluate(t,i){let n,o=0,r=null,l=0;for(let c=0;c<this.alphaKeys.length;c++){const h=this.alphaKeys[c];(h.time<t||!n)&&(n=h,o=c)}for(let c=0;c<this.colorKeys.length;c++){const h=this.colorKeys[c];(h.time<t||!r)&&(r=h,l=c)}if(r)if(l+1<this.colorKeys.length){const c=this.colorKeys[l+1],h=W.remap(t,r.time,c.time,0,1);i.r=W.lerp(r.color.r,c.color.r,h),i.g=W.lerp(r.color.g,c.color.g,h),i.b=W.lerp(r.color.b,c.color.b,h)}else i.r=r.color.r,i.g=r.color.g,i.b=r.color.b;if(n)if(o+1<this.alphaKeys.length){const c=this.alphaKeys[o+1],h=W.remap(t,n.time,c.time,0,1);i.alpha=W.lerp(n.alpha,c.alpha,h)}else i.alpha=n.alpha;return i}}k([m()],Qo.prototype,"alphaKeys",2),k([m()],Qo.prototype,"colorKeys",2);var Ph=(s=>(s[s.Local=0]="Local",s[s.World=1]="World",s[s.Custom=2]="Custom",s))(Ph||{}),Rp=(s=>(s[s.Sphere=0]="Sphere",s[s.SphereShell=1]="SphereShell",s[s.Hemisphere=2]="Hemisphere",s[s.HemisphereShell=3]="HemisphereShell",s[s.Cone=4]="Cone",s[s.Box=5]="Box",s[s.Mesh=6]="Mesh",s[s.ConeShell=7]="ConeShell",s[s.ConeVolume=8]="ConeVolume",s[s.ConeVolumeShell=9]="ConeVolumeShell",s[s.Circle=10]="Circle",s[s.CircleEdge=11]="CircleEdge",s[s.SingleSidedEdge=12]="SingleSidedEdge",s[s.MeshRenderer=13]="MeshRenderer",s[s.SkinnedMeshRenderer=14]="SkinnedMeshRenderer",s[s.BoxShell=15]="BoxShell",s[s.BoxEdge=16]="BoxEdge",s[s.Donut=17]="Donut",s[s.Rectangle=18]="Rectangle",s[s.Sprite=19]="Sprite",s[s.SpriteRenderer=20]="SpriteRenderer",s))(Rp||{});const kh=class{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(s){const t=new kh;return t.setConstant(s),t}static betweenTwoConstants(s,t){const i=new kh;return i.setMinMaxConstant(s,t),i}static curve(s,t=1){const i=new kh;return i.setCurve(s,t),i}setConstant(s){this.mode=0,this.constant=s}setMinMaxConstant(s,t){this.mode=3,this.constantMin=s,this.constantMax=t}setCurve(s,t=1){this.mode=1,this.curve=s,this.curveMultiplier=t}clone(){var s,t,i;const n=new kh;return n.mode=this.mode,n.constant=this.constant,n.constantMin=this.constantMin,n.constantMax=this.constantMax,n.curve=(s=this.curve)==null?void 0:s.clone(),n.curveMin=(t=this.curveMin)==null?void 0:t.clone(),n.curveMax=(i=this.curveMax)==null?void 0:i.clone(),n.curveMultiplier=this.curveMultiplier,n}evaluate(s,t){const i=t===void 0?Math.random():t;switch(this.mode){case 0:case"Constant":return this.constant;case 1:case"Curve":return s=W.clamp01(s),this.curve.evaluate(s)*this.curveMultiplier;case 2:case"TwoCurves":const n=s*this.curveMin.duration,o=s*this.curveMax.duration;return W.lerp(this.curveMin.evaluate(n),this.curveMax.evaluate(o),i%1)*this.curveMultiplier;case 3:case"TwoConstants":return W.lerp(this.constantMin,this.constantMax,i%1);default:this.curveMax.evaluate(s)*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(s){if(!s)return 0;let t=Number.MIN_VALUE;for(let i=0;i<s.keys.length;i++){const n=s.keys[i];n.value>t&&(t=n.value)}return t}};let Q=kh;k([m()],Q.prototype,"mode",2),k([m()],Q.prototype,"constant",2),k([m()],Q.prototype,"constantMin",2),k([m()],Q.prototype,"constantMax",2),k([m(Dr)],Q.prototype,"curve",2),k([m(Dr)],Q.prototype,"curveMin",2),k([m(Dr)],Q.prototype,"curveMax",2),k([m()],Q.prototype,"curveMultiplier",2);var Tp;const jt=(Tp=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(s){const t=new jt;return t.constant(s),t}static betweenTwoColors(s,t){const i=new jt;return i.betweenTwoColors(s,t),i}constant(s){return this.mode=0,this.color=s,this}betweenTwoColors(s,t){return this.mode=2,this.colorMin=s,this.colorMax=t,this}evaluate(s,t){const i=t===void 0?Math.random():t;switch(this.mode){case 0:case"Color":return this.color;case 1:case"Gradient":return this.gradient.evaluate(s,jt._temp),jt._temp;case 2:case"TwoColors":return jt._temp.lerpColors(this.colorMin,this.colorMax,i);case 3:case"TwoGradients":return this.gradientMin.evaluate(s,jt._temp),this.gradientMax.evaluate(s,jt._temp2),jt._temp.lerp(jt._temp2,i);case 4:case"RandomColor":const n=Math.random();return this.gradientMin.evaluate(s,jt._temp),this.gradientMax.evaluate(s,jt._temp2),jt._temp.lerp(jt._temp2,n)}return jt._temp.set(16777215),jt._temp.alpha=1,jt._temp}},a(Tp,"_temp",new Se(0,0,0,1)),a(Tp,"_temp2",new Se(0,0,0,1)),Tp);let si=jt;k([m()],si.prototype,"mode",2),k([m(Se)],si.prototype,"color",2),k([m(Se)],si.prototype,"colorMin",2),k([m(Se)],si.prototype,"colorMax",2),k([m(Qo)],si.prototype,"gradient",2),k([m(Qo)],si.prototype,"gradientMin",2),k([m(Qo)],si.prototype,"gradientMax",2);var H0=(s=>(s[s.Hierarchy=0]="Hierarchy",s[s.Local=1]="Local",s[s.Shape=2]="Shape",s))(H0||{});class Lt{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")}}k([m(Q)],Lt.prototype,"gravityModifier",2),k([m(si)],Lt.prototype,"startColor",2),k([m(Q)],Lt.prototype,"startDelay",2),k([m(Q)],Lt.prototype,"startLifetime",2),k([m(Q)],Lt.prototype,"startRotation",2),k([m(Q)],Lt.prototype,"startRotationX",2),k([m(Q)],Lt.prototype,"startRotationY",2),k([m(Q)],Lt.prototype,"startRotationZ",2),k([m(Q)],Lt.prototype,"startSize",2),k([m(Q)],Lt.prototype,"startSizeX",2),k([m(Q)],Lt.prototype,"startSizeY",2),k([m(Q)],Lt.prototype,"startSizeZ",2),k([m(Q)],Lt.prototype,"startSpeed",2);class Mh{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(t){if(t<=this.time)return 0;let i=0;if(this.cycleCount===0||this._performed<this.cycleCount){const n=this.time+this.repeatInterval*this._performed;if(t>=n&&(this._performed+=1,Math.random()<this.probability))switch(this.count.mode){case 0:i=this.count.constant;break;case 3:i=W.lerp(this.count.constantMin,this.count.constantMax,Math.random());break;case 1:i=this.count.curve.evaluate(Math.random());break;case 2:const o=Math.random();i=W.lerp(this.count.curveMin.evaluate(o),this.count.curveMax.evaluate(o),Math.random());break}}return i}}class hn{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 t;return((t=this.bursts)==null?void 0:t.length)??0}reset(){var t;(t=this.bursts)==null||t.forEach(i=>i.reset())}getBurst(){let t=0;if(this.burstCount>0)for(let i=0;i<this.burstCount;i++){const n=this.bursts[i];this.system.main.loop&&n.time>=this.system.time&&n.reset(),t+=Math.round(n.run(this.system.time))}return t}}k([m()],hn.prototype,"enabled",2),k([m()],hn.prototype,"bursts",2),k([m(Q)],hn.prototype,"rateOverTime",2),k([m()],hn.prototype,"rateOverTimeMultiplier",2),k([m(Q)],hn.prototype,"rateOverDistance",2),k([m()],hn.prototype,"rateOverDistanceMultiplier",2);class Rh{constructor(){a(this,"enabled"),a(this,"color")}}k([m(si)],Rh.prototype,"color",2);class Yo{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(t,i,n){if(i||(i=this._temp),!this.enabled)return i.x=i.y=i.z=1,i;if(this.separateAxes)i.x=this.x.evaluate(t,n)*this.xMultiplier,i.y=this.y.evaluate(t,n)*this.yMultiplier,i.z=this.z.evaluate(t,n)*this.zMultiplier;else{const o=this.size.evaluate(t,n)*this.sizeMultiplier;i.x=o}return i}}k([m(Q)],Yo.prototype,"size",2),k([m(Q)],Yo.prototype,"x",2),k([m(Q)],Yo.prototype,"y",2),k([m(Q)],Yo.prototype,"z",2);var Ep;const Th=(Ep=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 Ut),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 ne),a(this,"_worldSpaceMatrixInverse",new ne),a(this,"_vector",new x(0,0,0)),a(this,"_temp",new x(0,0,0)),a(this,"_triangle",new mC),a(this,"_dir",new x),a(this,"_loopTime",0),a(this,"_loopDirection",1),Mp&&console.log(this)}get type(){return Rp[this.shapeType]}initialize(s){this.onInitialize(s),s.position.x=this._vector.x,s.position.y=this._vector.y,s.position.z=this._vector.z}toJSON(){return this}clone(){return new Th}setMesh(s){this.meshRenderer=s,s?(this._meshObj=s.sharedMeshes[Math.floor(Math.random()*s.sharedMeshes.length)],this._meshGeometry=this._meshObj.geometry):(this._meshObj=void 0,this._meshGeometry=void 0)}update(s,t){}onUpdate(s,t,i,n){this.system=s,this._space=i,i===1&&(this._worldSpaceMatrix.copy(n.matrixWorld),this._worldSpaceMatrix.elements[0]=1,this._worldSpaceMatrix.elements[5]=1,this._worldSpaceMatrix.elements[10]=1,this._worldSpaceMatrixInverse.copy(this._worldSpaceMatrix).invert())}applyRotation(s){const t=this.rotation.x!==0||this.rotation.y!==0||this.rotation.z!==0;return t&&(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",s.applyEuler(this._rotation)),t}onInitialize(s){this._vector.set(0,0,0),s.mesh=void 0,s.mesh_geometry=void 0;const t=this._temp.copy(this.position),i=this._space===1;i&&t.applyQuaternion(this.system.worldQuaternion);let n=this.radius;if(i&&(n*=this.system.worldScale.x),this.enabled){switch(this.shapeType){case 5:Mp&&q.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(t);break;case 4:this.randomConePoint(this.position,this.angle,n,this.radiusThickness,this.arc,this.arcMode,this._vector);break;case 0:this.randomSpherePoint(this.position,n,this.radiusThickness,this.arc,this._vector);break;case 10:this.randomCirclePoint(this.position,n,this.radiusThickness,this.arc,this._vector);break;case 13:const o=this.meshRenderer;o?.destroyed==!1&&this.setMesh(o);const r=s.mesh=this._meshObj,l=s.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),s.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,y=u*3+2;p=c.getX(p),g=c.getX(g),y=c.getX(y);const f=l.getAttribute("position");this._triangle.a.fromBufferAttribute(f,p),this._triangle.b.fromBufferAttribute(f,g),this._triangle.c.fromBufferAttribute(f,y),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),s.mesh_normal=u}}break}break;default:this._vector.set(0,0,0),F()&&!globalThis.__particlesystem_shapetype_unsupported&&(console.warn("ParticleSystem ShapeType is not supported:",Rp[this.shapeType]),globalThis.__particlesystem_shapetype_unsupported=!0);break}this.randomizePosition(this._vector,this.randomPositionAmount)}this.applyRotation(this._vector),i&&(this._vector.applyQuaternion(this.system.worldQuaternion),this._vector.add(this.system.worldPos)),Mp&&q.DrawSphere(this._vector,.03,16711680,.5,!0)}getDirection(s,t){var i;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 n=t.x,o=t.y,r=t.z;this._dir.set(n,o,r),(i=this.system)!=null&&i.worldspace?this._dir.sub(this.system.worldPos):this._dir.sub(this.position);break;case 13:const l=s.mesh,c=s.mesh_geometry;if(l&&c)switch(this.meshShapeType){case 0:{const h=c.getAttribute("normal"),d=s.mesh_normal;this._dir.fromBufferAttribute(h,d)}break;case 1:break;case 2:{const h=c.index;if(h){const d=s.mesh_normal,u=h.getX(d*3),p=h.getX(d*3+1),g=h.getX(d*3+2),y=c.getAttribute("position"),f=G(),v=G(),b=G();f.fromBufferAttribute(y,u),v.fromBufferAttribute(y,p),b.fromBufferAttribute(y,g),f.sub(v),b.sub(v),f.cross(b),this._dir.copy(f).multiplyScalar(-1);const w=Oe(l);this._dir.applyQuaternion(w)}}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),Mp&&(q.DrawSphere(t,.01,8925952,.5,!0),q.DrawDirection(t,this._dir,8925952,.5,!0)),this._dir}randomizePosition(s,t){if(t<=0)return;const i=Th._tempVec;i.set(Math.random()*2-1,Math.random()*2-1,Math.random()*2-1),i.x*=t*this.scale.x,i.y*=t*this.scale.y,i.z*=t*this.scale.z,s.add(i)}randomizeDirection(s,t){if(t===0)return;const i=Th._randomQuat,n=Th._tempVec;n.set(Math.random()-.5,Math.random()-.5,Math.random()-.5).normalize(),i.setFromAxisAngle(n,t*Math.random()*Math.PI),s.applyQuaternion(i)}spherizeDirection(s,t){if(t===0)return;const i=Math.random()*Math.PI*2,n=Math.acos(1-Math.random()*2),o=Math.sin(n)*Math.cos(i),r=Math.sin(n)*Math.sin(i),l=Math.cos(n),c=new x(o,r,l);s.lerp(c,t)}randomSpherePoint(s,t,i,n,o){const r=Math.random(),l=Math.random(),c=2*Math.PI*r*(n/360),h=Math.acos(2*l-1),d=W.lerp(1,1-Math.pow(1-Math.random(),Math.PI),i)*t,u=s.x+this.scale.x*(-d*Math.sin(h)*Math.cos(c)),p=s.y+this.scale.y*(d*Math.sin(h)*Math.sin(c)),g=s.z+this.scale.z*(d*Math.cos(h));o.x=u,o.y=p,o.z=g}randomCirclePoint(s,t,i,n,o){const r=Math.random(),l=2*Math.PI*r*(n/360),c=W.lerp(1,1-Math.pow(1-Math.random(),Math.PI),i)*t,h=s.x+this.scale.x*c*Math.cos(l),d=s.y+this.scale.y*c*Math.sin(l),u=s.z;o.x=h,o.y=d,o.z=u}randomConePoint(s,t,i,n,o,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*(o/360);switch(r){case 2:case 1:d+=Math.PI+.5,d+=this._loopTime*Math.PI*2,d%=W.toRadians(o);break}const u=Math.acos(2*h-1),p=W.lerp(1,1-Math.pow(1-Math.random(),Math.PI),n)*i,g=s.x+-p*Math.sin(u)*Math.cos(d),y=s.y+p*Math.sin(u)*Math.sin(d),f=s.z;l.x=g*this.scale.x,l.y=y*this.scale.y,l.z=f*this.scale.z}},a(Ep,"_randomQuat",new V),a(Ep,"_tempVec",new x),Ep);let Xe=Th;k([m()],Xe.prototype,"shapeType",2),k([m()],Xe.prototype,"enabled",2),k([m()],Xe.prototype,"alignToDirection",2),k([m()],Xe.prototype,"angle",2),k([m()],Xe.prototype,"arc",2),k([m()],Xe.prototype,"arcSpread",2),k([m()],Xe.prototype,"arcSpeedMultiplier",2),k([m()],Xe.prototype,"arcMode",2),k([m(x)],Xe.prototype,"boxThickness",2),k([m(x)],Xe.prototype,"position",2),k([m(x)],Xe.prototype,"rotation",2),k([m(x)],Xe.prototype,"scale",2),k([m()],Xe.prototype,"radius",2),k([m()],Xe.prototype,"radiusThickness",2),k([m()],Xe.prototype,"sphericalDirectionAmount",2),k([m()],Xe.prototype,"randomDirectionAmount",2),k([m()],Xe.prototype,"randomPositionAmount",2),k([m()],Xe.prototype,"meshShapeType",2),k([m(oh)],Xe.prototype,"meshRenderer",2);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(t){this._time+=t.time.deltaTime*this.scrollSpeedMultiplier}apply(t,i,n,o,r,l){if(!this.enabled)return;this._noise||(this._noise=JC(()=>0));const c=this._temp.set(i.x,i.y,i.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)),n.x+=this._temp.x,n.y+=this._temp.y,n.z+=this._temp.z}}k([m()],Ce.prototype,"damping",2),k([m()],Ce.prototype,"enabled",2),k([m()],Ce.prototype,"frequency",2),k([m()],Ce.prototype,"octaveCount",2),k([m()],Ce.prototype,"octaveMultiplier",2),k([m()],Ce.prototype,"octaveScale",2),k([m(Q)],Ce.prototype,"positionAmount",2),k([m()],Ce.prototype,"quality",2),k([m(Q)],Ce.prototype,"remap",2),k([m()],Ce.prototype,"remapEnabled",2),k([m()],Ce.prototype,"remapMultiplier",2),k([m(Q)],Ce.prototype,"remapX",2),k([m()],Ce.prototype,"remapXMultiplier",2),k([m(Q)],Ce.prototype,"remapY",2),k([m()],Ce.prototype,"remapYMultiplier",2),k([m(Q)],Ce.prototype,"remapZ",2),k([m()],Ce.prototype,"remapZMultiplier",2),k([m()],Ce.prototype,"scrollSpeedMultiplier",2),k([m()],Ce.prototype,"separateAxes",2),k([m()],Ce.prototype,"strengthMultiplier",2),k([m(Q)],Ce.prototype,"strengthX",2),k([m()],Ce.prototype,"strengthXMultiplier",2),k([m(Q)],Ce.prototype,"strengthY",2),k([m()],Ce.prototype,"strengthYMultiplier",2),k([m(Q)],Ce.prototype,"strengthZ",2),k([m()],Ce.prototype,"strengthZMultiplier",2);class Ue{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(t,i,n,o){const r=this.widthOverTrail.evaluate(n,o);return t*=r,t}getColor(t,i,n){const o=this.colorOverTrail.evaluate(n),r=this.colorOverLifetime.evaluate(i);t.x*=o.r*r.r,t.y*=o.g*r.g,t.z*=o.b*r.b,"alpha"in o&&"alpha"in r&&(t.w*=o.alpha*r.alpha)}}k([m()],Ue.prototype,"enabled",2),k([m()],Ue.prototype,"attachRibbonToTransform",2),k([m(si)],Ue.prototype,"colorOverLifetime",2),k([m(si)],Ue.prototype,"colorOverTrail",2),k([m()],Ue.prototype,"dieWithParticles",2),k([m()],Ue.prototype,"inheritParticleColor",2),k([m(Q)],Ue.prototype,"lifetime",2),k([m()],Ue.prototype,"lifetimeMultiplier",2),k([m()],Ue.prototype,"minVertexDistance",2),k([m()],Ue.prototype,"mode",2),k([m()],Ue.prototype,"ratio",2),k([m()],Ue.prototype,"ribbonCount",2),k([m()],Ue.prototype,"shadowBias",2),k([m()],Ue.prototype,"sizeAffectsLifetime",2),k([m()],Ue.prototype,"sizeAffectsWidth",2),k([m()],Ue.prototype,"splitSubEmitterRibbons",2),k([m()],Ue.prototype,"textureMode",2),k([m(Q)],Ue.prototype,"widthOverTrail",2),k([m()],Ue.prototype,"widthOverTrailMultiplier",2),k([m()],Ue.prototype,"worldSpace",2);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 ne)}update(t){this._system=t}init(t){this._index==0&&(t.debug=!0),this._index+=1,t.orbitx=this.orbitalX.evaluate(Math.random()),t.orbity=this.orbitalY.evaluate(Math.random()),t.orbitz=this.orbitalZ.evaluate(Math.random()),this._hasOrbital=t.orbitx!=0||t.orbity!=0||t.orbitz!=0}apply(t,i,n,o,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),y=this.z.evaluate(d);if(this._temp.set(-p,g,y),this._system&&this._system.main.simulationSpace===1&&this._temp.applyQuaternion(this._system.worldQuaternion),this._hasOrbital&&((h=this._system)==null?void 0:h.worldPos)){const f=this._temp2.set(n.x,n.y,n.z),v=this.orbitalXMultiplier,b=this.orbitalYMultiplier,w=this.orbitalZMultiplier,_=u*Math.PI*2*10,C=Math.cos(_*v),R=Math.sin(_*v),M=Math.cos(_*b),T=Math.sin(_*b),j=Math.cos(_*w),D=Math.sin(_*w),U=f.x*(M*j)+f.y*(M*D)+f.z*-T,B=f.x*(R*T*j-C*D)+f.y*(R*T*D+C*j)+f.z*(R*M),Y=f.x*(C*T*j+R*D)+f.y*(C*T*D-R*j)+f.z*(C*M),$=this._temp3.set(f.x-U,f.y-B,f.z-Y);$.normalize(),$.multiplyScalar(.2/r*Math.max(this.orbitalXMultiplier,this.orbitalYMultiplier,this.orbitalZMultiplier)),o.x+=$.x,o.y+=$.y,o.z+=$.z}o.x+=this._temp.x,o.y+=this._temp.y,o.z+=this._temp.z,o.x*=u,o.y*=u,o.z*=u}}k([m()],Qe.prototype,"enabled",2),k([m()],Qe.prototype,"space",2),k([m(Q)],Qe.prototype,"orbitalX",2),k([m(Q)],Qe.prototype,"orbitalY",2),k([m(Q)],Qe.prototype,"orbitalZ",2),k([m()],Qe.prototype,"orbitalXMultiplier",2),k([m()],Qe.prototype,"orbitalYMultiplier",2),k([m()],Qe.prototype,"orbitalZMultiplier",2),k([m()],Qe.prototype,"orbitalOffsetX",2),k([m()],Qe.prototype,"orbitalOffsetY",2),k([m()],Qe.prototype,"orbitalOffsetZ",2),k([m(Q)],Qe.prototype,"speedModifier",2),k([m()],Qe.prototype,"speedModifierMultiplier",2),k([m(Q)],Qe.prototype,"x",2),k([m()],Qe.prototype,"xMultiplier",2),k([m(Q)],Qe.prototype,"y",2),k([m()],Qe.prototype,"yMultiplier",2),k([m(Q)],Qe.prototype,"z",2),k([m()],Qe.prototype,"zMultiplier",2);class Dt{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(t){if(!this.sampleOnceAtStart())return this.getIndex(t)}getIndex(t){const i=this.numTilesX*this.numTilesY;t=t*this.cycleCount;let n=this.frameOverTime.evaluate(t%1);return n*=this.frameOverTimeMultiplier,n*=i,n=n%i,n=Math.floor(n),n}}k([m()],Dt.prototype,"animation",2),k([m()],Dt.prototype,"enabled",2),k([m()],Dt.prototype,"cycleCount",2),k([m(Q)],Dt.prototype,"frameOverTime",2),k([m()],Dt.prototype,"frameOverTimeMultiplier",2),k([m()],Dt.prototype,"numTilesX",2),k([m()],Dt.prototype,"numTilesY",2),k([m(Q)],Dt.prototype,"startFrame",2),k([m()],Dt.prototype,"startFrameMultiplier",2),k([m()],Dt.prototype,"rowMode",2),k([m()],Dt.prototype,"rowIndex",2),k([m()],Dt.prototype,"spriteCount",2),k([m()],Dt.prototype,"timeMode",2);class ns{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(t,i){return this.enabled?this.separateAxes?0:this.z.evaluate(t,i)*-1:0}}k([m()],ns.prototype,"enabled",2),k([m()],ns.prototype,"separateAxes",2),k([m(Q)],ns.prototype,"x",2),k([m()],ns.prototype,"xMultiplier",2),k([m(Q)],ns.prototype,"y",2),k([m()],ns.prototype,"yMultiplier",2),k([m(Q)],ns.prototype,"z",2),k([m()],ns.prototype,"zMultiplier",2);class Fi{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(t,i){if(!this.enabled)return 0;if(!this.separateAxes){const n=W.lerp(this.range.x,this.range.y,i);return this.z.evaluate(n)*-1}return 0}}k([m()],Fi.prototype,"enabled",2),k([m()],Fi.prototype,"range",2),k([m()],Fi.prototype,"separateAxes",2),k([m(Q)],Fi.prototype,"x",2),k([m()],Fi.prototype,"xMultiplier",2),k([m(Q)],Fi.prototype,"y",2),k([m()],Fi.prototype,"yMultiplier",2),k([m(Q)],Fi.prototype,"z",2),k([m()],Fi.prototype,"zMultiplier",2);class lt{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(t,i,n,o,r,l,c){if(this.enabled){const h=this.limit.evaluate(r)*this.limitMultiplier;if(i.length()>h){this._temp.copy(i).normalize().multiplyScalar(h);const d=this.dampen*.5;i.x=W.lerp(i.x,this._temp.x,d),i.y=W.lerp(i.y,this._temp.y,d),i.z=W.lerp(i.z,this._temp.z,d),n.x=W.lerp(n.x,this._temp.x,d),n.y=W.lerp(n.y,this._temp.y,d),n.z=W.lerp(n.z,this._temp.z,d)}}}}k([m()],lt.prototype,"enabled",2),k([m()],lt.prototype,"dampen",2),k([m(Q)],lt.prototype,"drag",2),k([m()],lt.prototype,"dragMultiplier",2),k([m(Q)],lt.prototype,"limit",2),k([m()],lt.prototype,"limitMultiplier",2),k([m()],lt.prototype,"separateAxes",2),k([m(Q)],lt.prototype,"limitX",2),k([m()],lt.prototype,"limitXMultiplier",2),k([m(Q)],lt.prototype,"limitY",2),k([m()],lt.prototype,"limitYMultiplier",2),k([m(Q)],lt.prototype,"limitZ",2),k([m()],lt.prototype,"limitZMultiplier",2),k([m()],lt.prototype,"multiplyDragByParticleSize",2),k([m()],lt.prototype,"multiplyDragByParticleVelocity",2),k([m()],lt.prototype,"space",2);const s1=class{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 s;const t=new s1;return t.enabled=this.enabled,t.curve=(s=this.curve)==null?void 0:s.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(s){this.system=s,this.reset()}reset(){this._firstUpdate=!0}update(s){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(s){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),s.x+=this._temp.x,s.y+=this._temp.y,s.z+=this._temp.z}}applyCurrent(s,t,i){if(this.enabled&&this.system&&this.system.worldspace!==!1&&this.mode===1){const n=this.curve.evaluate(t,i);this._temp.copy(this._velocity).multiplyScalar(n),s.x+=this._temp.x,s.y+=this._temp.y,s.z+=this._temp.z}}};let Ko=s1;k([m()],Ko.prototype,"enabled",2),k([m(Q)],Ko.prototype,"curve",2),k([m()],Ko.prototype,"curveMultiplier",2),k([m()],Ko.prototype,"mode",2);class ni{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(t,i,n,o){const r=t.length(),l=W.remap(r,this.range.x,this.range.y,0,1),c=this.size.evaluate(l,n);return o.x*=c,o.y*=c,o.z*=c,o}}k([m()],ni.prototype,"enabled",2),k([m(oe)],ni.prototype,"range",2),k([m()],ni.prototype,"separateAxes",2),k([m(Q)],ni.prototype,"size",2),k([m()],ni.prototype,"sizeMultiplier",2),k([m(Q)],ni.prototype,"x",2),k([m()],ni.prototype,"xMultiplier",2),k([m(Q)],ni.prototype,"y",2),k([m()],ni.prototype,"yMultiplier",2),k([m(Q)],ni.prototype,"z",2),k([m()],ni.prototype,"zMultiplier",2);class ta{constructor(){a(this,"enabled"),a(this,"range"),a(this,"color")}evaluate(t,i,n){const o=t.length(),r=W.remap(o,this.range.x,this.range.y,0,1),l=this.color.evaluate(r,i);n.x*=l.r,n.y*=l.g,n.z*=l.b,"alpha"in l&&(n.w*=l.alpha)}}k([m()],ta.prototype,"enabled",2),k([m(oe)],ta.prototype,"range",2),k([m(si)],ta.prototype,"color",2),new x(1,1,1),new x(0,0,1);class Ap{constructor(t,i,n,o){a(this,"type","NeedleParticleSubEmitter"),a(this,"emitterType"),a(this,"emitterProbability"),a(this,"q_",new V),a(this,"v_",new x),a(this,"v2_",new x),a(this,"_emitterMatrix",new Om),a(this,"_circularBuffer"),this.system=t,this.particleSystem=i,this.subSystem=n,this.subParticleSystem=o,this.subParticleSystem&&this.subParticleSystem&&(this.subParticleSystem.onlyUsedByOther=!0);const r=1e3;this._circularBuffer=new Si(()=>new Om,r)}clone(){throw new Error("Method not implemented.")}initialize(t){t.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===$0.Birth&&this.run(t)}update(t,i){this.run(t)}frameUpdate(t){}toJSON(){}reset(){}run(t){if(this.subSystem.currentParticles>=this.subSystem.main.maxParticles||!this.subParticleSystem||!t.emissionState||this.emitterProbability&&Math.random()>this.emitterProbability)return;const i=this.system.deltaTime;if(this.emitterType===$0.Death){let o=t.life;if(t[Rl]!==void 0&&(o=t[Rl]),!(t.age+i*1.2>=o))return;const r=this.subSystem.main.maxParticles-this.subSystem.currentParticles;t.emissionState.waitEmiting=r}const n=new Om;n.set(1,0,0,t.position.x,0,1,0,t.position.y,0,0,1,t.position.z,0,0,0,1),this.particleSystem.worldSpace||n.multiplyMatrices(this._emitterMatrix,n),this.subParticleSystem.emit(i,t.emissionState,n)}}var IE=Object.defineProperty,jE=Object.getOwnPropertyDescriptor,Ye=(s,t,i,n)=>{for(var o=n>1?void 0:n?jE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&IE(t,i,o),o};const Zo=O("debugparticles"),LE=O("noprogressive"),DE=O("debugprogressive");var $0=(s=>(s[s.Birth=0]="Birth",s[s.Collision=1]="Collision",s[s.Death=2]="Death",s[s.Trigger=3]="Trigger",s[s.Manual=4]="Manual",s))($0||{});class os extends A{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 t=`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(t)}}get transparent(){var t;return((t=this.particleMaterial)==null?void 0:t.transparent)??!1}getMaterial(t=!1){let i=t===!0&&this.trailMaterial?this.trailMaterial:this.particleMaterial;if(i){if(i.type==="MeshStandardMaterial"){Zo&&console.debug("ParticleSystemRenderer.getMaterial: MeshStandardMaterial detected, converting to MeshBasicMaterial. See https://github.com/Alchemist0823/three.quarks/issues/101"),"map"in i&&i.map&&(i.map.colorSpace=mr,i.map.premultiplyAlpha=!1);const n=new Re;n.copy(i),t?this.trailMaterial=n:this.particleMaterial=n}i.map&&(i.map.colorSpace=mr,i.map.premultiplyAlpha=!1),t&&i.side===co&&(i=i.clone(),i.side=ym,t?this.trailMaterial=i:this.particleMaterial=i)}return i&&!LE&&i._didRequestTextureLOD===void 0&&(i._didRequestTextureLOD=0,DE&&console.log("Load material LOD",i.name),it.assignTextureLOD(i,0)),i}getMesh(t){let i=null;if(!i&&(this.particleMesh instanceof K&&(i=this.particleMesh.geometry),i===null)){i=new Fs(1,1);const n=i.attributes.uv;for(let o=0;o<n.count;o++)n.setX(o,1-n.getX(o))}return new K(i,this.getMaterial())}}Ye([m()],os.prototype,"renderMode",2),Ye([m(ke)],os.prototype,"particleMaterial",2),Ye([m(ke)],os.prototype,"trailMaterial",2),Ye([m()],os.prototype,"maxParticleSize",2),Ye([m()],os.prototype,"minParticleSize",2),Ye([m()],os.prototype,"velocityScale",2),Ye([m()],os.prototype,"cameraVelocityScale",2),Ye([m()],os.prototype,"lengthScale",2);class Ip{constructor(t,i=1){a(this,"_curve"),a(this,"_factor"),a(this,"type","function"),this._curve=t,this._factor=i}startGen(t){}genValue(t,i){return this._curve.evaluate(i,Math.random())*this._factor}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}}class q0{constructor(t){a(this,"type","value"),a(this,"system"),this.system=t}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}startGen(t){}}class BE extends q0{genValue(){return this.system.textureSheetAnimation.getStartIndex()}}class FE extends q0{constructor(){super(...arguments),a(this,"_lastPosition",new x),a(this,"_lastDistance",0)}update(){const t=te(this.system.gameObject);this._lastDistance=this._lastPosition.distanceTo(t),this._lastPosition.copy(t)}genValue(){if(!this.system.isPlaying||!this.system.emission.enabled||this.system.currentParticles>=this.system.maxParticles)return 0;let t=this.system.emission.rateOverTime.evaluate(this.system.time/this.system.duration,Math.random());if(this.system.deltaTime>0){const o=this.system.emission.rateOverDistance.evaluate(this.system.time/this.system.duration,Math.random());let r=this._lastDistance/this.system.deltaTime*o;Number.isFinite(r)||(r=0),t+=r}const i=this.system.emission.getBurst();i>0&&(t+=i/this.system.deltaTime);const n=this.system.maxParticles-this.system.currentParticles;return W.clamp(t,0,n/this.system.deltaTime)}}class zE extends q0{genValue(){return this.system.isPlaying,0}}class Jo{constructor(t){a(this,"system"),a(this,"type"),this.type=Object.getPrototypeOf(this).constructor.name||"ParticleSystemBaseBehaviour",t&&(this.system=t)}get context(){return this.system.context}initialize(t){}update(t,i){}frameUpdate(t){}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}reset(){}}class UE extends Jo{constructor(){super(...arguments),a(this,"type","NeedleTextureSheet")}update(t,i){const n=this.system.textureSheetAnimation;if(n.enabled){const o=t.age/t.life,r=n.evaluate(o);r!==void 0&&(t.uvTile=r)}}}const n1=Symbol("particleRotation");class NE extends Jo{constructor(){super(...arguments),a(this,"type","NeedleRotation")}initialize(t){t[n1]=Math.random()}update(t,i){if(t.rotation===void 0)return;const n=t.age/t.life;if(typeof t.rotation=="number"&&(this.system.rotationOverLifetime.enabled?t.rotation+=this.system.rotationOverLifetime.evaluate(n,t[n1])*i:this.system.renderer.renderMode===qn.Billboard&&(t.rotation=Math.PI),this.system.rotationBySpeed.enabled)){const o=t.velocity.length();t.rotation+=this.system.rotationBySpeed.evaluate(n,o)*i}}}const o1=Symbol("sizeLerpFactor"),WE=new x;class VE extends Jo{constructor(){super(...arguments),a(this,"type","NeedleSize"),a(this,"_minSize",0),a(this,"_maxSize",1)}initialize(t){t[o1]=Math.random(),this._minSize=this.system.renderer.minParticleSize,this._maxSize=this.system.renderer.maxParticleSize}update(t,i){const n=t.age/t.life;let o=1;this.system.sizeOverLifetime.enabled&&(o*=this.system.sizeOverLifetime.evaluate(n,void 0,t[o1]).x);let r=1;this.system.renderer.renderMode!==qn.Mesh&&(r=this.system.worldScale.x/this.system.cameraScale);const l=G(t.startSize).multiplyScalar(o*r);if(t.size.set(l.x,l.y,l.z),this.system.localspace){const c=h1(this.system,WE);t.size.x*=c.x,t.size.y*=c.y,t.size.z*=c.z}}}const Rl=Symbol("particleLife"),G0=Symbol("trailLifetime"),r1=Symbol("trailStartLength"),X0=Symbol("trailWidthRandom");class HE extends Jo{constructor(){super(...arguments),a(this,"type","NeedleTrail")}initialize(t){t instanceof gv&&(t[Rl]=t.life,this.system.trails.enabled&&this.system.trails.dieWithParticles===!1&&(t[G0]=this.system.trails.lifetime.evaluate(Math.random(),Math.random()),t.life+=t[G0]),t[r1]=t.length,t[X0]=Math.random())}update(t){var i;if((i=this.system.trails)!=null&&i.enabled&&t instanceof gv){const n=t,o=t.age/t[Rl],r=t.previous.values(),l=t.previous.length;for(let c=0;c<l;c++){const h=r.next().value,d=1-c/(l-1),u=t.size;if(u.x<=0&&!this.system.trails.sizeAffectsWidth){const p=20*this.system.trails.widthOverTrail.evaluate(.5,n[X0]);u.x=p,u.y=p,u.z=p}h.size=this.system.trails.getWidth(u.x,o,d,n[X0]),h.color.copy(t.color),this.system.trails.getColor(h.color,o,d)}if(t.age>t[Rl]){t.velocity.set(0,0,0);const c=(t.age-t[Rl])/t[G0];n.length=W.lerp(t[r1],0,c)}}}}const jp=Symbol("startVelocity"),a1=Symbol("gravityModifier"),Q0=Symbol("gravitySpeed"),Lp=Symbol("velocity lerp factor"),Y0=new x;class $E extends Jo{constructor(){super(...arguments),a(this,"type","NeedleVelocity"),a(this,"_gravityDirection",new x)}initialize(t){var i,n;const o=this.system.main.simulationSpeed;t.startSpeed=this.system.main.startSpeed.evaluate(Math.random(),Math.random());const r=this.system.shape.getDirection(t,t.position);t.velocity.x=r.x*t.startSpeed,t.velocity.y=r.y*t.startSpeed,t.velocity.z=r.z*t.startSpeed,(i=this.system.inheritVelocity)!=null&&i.enabled&&this.system.inheritVelocity.applyInitial(t.velocity),t[jp]?t[jp].copy(t.velocity):t[jp]=t.velocity.clone();const l=this.system.main.gravityModifier.evaluate(Math.random(),Math.random());t[a1]=l*o,t[Q0]=l*o*.5,t[Lp]=Math.random(),(n=this.system.velocityOverLifetime)==null||n.init(t),this._gravityDirection.set(0,-1,0),this.system.main.simulationSpace===Ph.Local&&this._gravityDirection.applyQuaternion(this.system.worldQuaternionInverted).normalize()}update(t,i){var n;const o=t[jp],r=t[a1];if(r!==0){const g=r*t[Q0];Y0.copy(this._gravityDirection).multiplyScalar(g),t[Q0]+=i*.05,o.add(Y0)}t.velocity.copy(o);const l=t.age/t.life;(n=this.system.inheritVelocity)!=null&&n.enabled&&this.system.inheritVelocity.applyCurrent(t.velocity,l,t[Lp]);const c=this.system.noise;c.enabled&&c.apply(0,t.position,t.velocity,i,t.age,t.life);const h=this.system.sizeBySpeed;h!=null&&h.enabled&&(t.size=h.evaluate(t.velocity,l,t[Lp],t.size));const d=this.system.colorBySpeed;d!=null&&d.enabled&&d.evaluate(t.velocity,t[Lp],t.color);const u=this.system.velocityOverLifetime;u.enabled&&u.apply(t,0,t.position,t.velocity,i,t.age,t.life);const p=this.system.limitVelocityOverLifetime;if(p.enabled&&p.apply(t.position,o,t.velocity,t.size,l,i,1),this.system.worldspace){const g=this.system.worldScale;t.velocity.x*=g.x,t.velocity.y*=g.y,t.velocity.z*=g.z}}}const l1=Symbol("colorLerpFactor"),c1=new Se(1,1,1,1),ia=new Se(1,1,1,1);class qE extends Jo{constructor(){super(...arguments),a(this,"type","NeedleColor")}initialize(t){}_init(t){const i=this.system.renderer.particleMaterial;ia.copy(this.system.main.startColor.evaluate(Math.random())),i!=null&&i.color&&(c1.copy(i.color),ia.multiply(c1)),ia.convertLinearToSRGB(),t.startColor.set(ia.r,ia.g,ia.b,ia.alpha),t.color.copy(t.startColor),t[l1]=Math.random()}update(t,i){if(t.age===0&&this._init(t),this.system.colorOverLifetime.enabled){const n=t.age/t.life,o=this.system.colorOverLifetime.color.evaluate(n,t[l1]);t.color.set(o.r,o.g,o.b,"alpha"in o?o.alpha:1).multiply(t.startColor)}else t.color.copy(t.startColor)}}class GE{constructor(t){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 nO(220),followLocalOrigin:!1}),a(this,"flatWhiteTexture"),a(this,"clonedTexture",{original:void 0,clone:void 0}),this.system=t,this.emission=new FE(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 Ip(this.system.main.startLifetime)}get startSpeed(){return new Ip(this.system.main.startSpeed)}get startRotation(){return new Ip(this.system.main.startRotation)}get startSize(){return new Ip(this.system.main.startSize)}get startColor(){return new iO(new sO(1,1,1,1))}get emissionOverTime(){return this.emission}get emissionOverDistance(){return new zE(this.system)}get instancingGeometry(){return this.system.renderer.getMesh(this.system.renderer.renderMode).geometry}get renderMode(){if(this.system.trails.enabled===!0)return xn.Trail;switch(this.system.renderer.renderMode){case qn.Billboard:return xn.BillBoard;case qn.Stretch:return xn.StretchedBillBoard;case qn.HorizontalBillboard:return xn.HorizontalBillBoard;case qn.VerticalBillboard:return xn.VerticalBillBoard;case qn.Mesh:return xn.Mesh}return xn.BillBoard}get speedFactor(){var t;let i=this.system.main.simulationSpeed;return((t=this.system.renderer)==null?void 0:t.renderMode)===qn.Stretch&&(i*=this.system.renderer.velocityScale??1),i}get texture(){const t=this.material;if(t&&t.map){const i=t.map;if(this.clonedTexture.original!==i||!this.clonedTexture.clone){const n=i.clone();n.premultiplyAlpha=!1,n.colorSpace=mr,this.clonedTexture.original=i,this.clonedTexture.clone=n}return this.clonedTexture.clone}return this.flatWhiteTexture||(this.flatWhiteTexture=Kg(new Se(1,1,1,1),1)),this.flatWhiteTexture}get startTileIndex(){return new BE(this.system)}get uTileCount(){var t;return this.anim.enabled?(t=this.anim)==null?void 0:t.numTilesX:void 0}get vTileCount(){var t;return this.anim.enabled?(t=this.anim)==null?void 0:t.numTilesY:void 0}get renderOrder(){return 1}get blending(){var t;return((t=this.system.renderer.particleMaterial)==null?void 0:t.blending)??gC}get transparent(){return this.system.renderer.transparent}get worldSpace(){return this.system.main.simulationSpace===Ph.World}}class XE{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 Dp=class extends A{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 V),a(this,"_worldQuaternionInverted",new V),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(s=!1){var t;s&&P.foreachComponent(this.gameObject,i=>{i instanceof Dp&&i!==this&&i.play(!1)},!0),this._isPlaying=!0,this._particleSystem&&(this._particleSystem.emissionState.time=0,this._particleSystem.emitEnded=!1),(t=this.emission)==null||t.reset()}pause(s=!0){s&&P.foreachComponent(this.gameObject,t=>{t instanceof Dp&&t!==this&&t.pause(!1)},!0),this._isPlaying=!1}stop(s=!0,t=!1){s&&P.foreachComponent(this.gameObject,i=>{i instanceof Dp&&i!==this&&i.stop(!1,t)},!0),this._isPlaying=!1,this._time=0,t&&this.reset()}reset(){var s;this._time=0,this._particleSystem&&(this._particleSystem.particleNum=0,this._particleSystem.emissionState.time=0,this._particleSystem.emitEnded=!1,(s=this.emission)==null||s.reset())}emit(s){if(this._particleSystem){this.onUpdate(),s=Math.min(s,this.maxParticles-this.currentParticles),this._state||(this._state=new XE),this._state.waitEmiting=s,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(s){this.main.playOnAwake=s}get renderer(){return this._renderer}get isPlaying(){return this._isPlaying}get currentParticles(){var s;return((s=this._particleSystem)==null?void 0:s.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(s){return this._particleSystem?(s instanceof Jo&&(s.system=this),(F()||Zo)&&console.debug("Add custom ParticleSystem Behaviour",s),this._particleSystem.addBehavior(s),!0):!1}removeBehaviour(s){if(!this._particleSystem)return!1;const t=this._particleSystem.behaviors,i=t.indexOf(s);return i!==-1&&((F()||Zo)&&console.debug("Remove custom ParticleSystem Behaviour",i,s),t.splice(i,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(s){for(let t=0;t<s.length;t++){const i=s[t];if(!(i instanceof Mh)){const n=new Mh;Da(n,i),s[t]=n}}this._bursts=s}set subEmitterSystems(s){for(let t=0;t<s.length;t++){const i=s[t];if(!(i instanceof Eh)){const n=new Eh;Da(n,i),s[t]=n}}Zo&&s.length>0&&console.log("SubEmitters: ",s,this),this._subEmitterSystems=s}onAfterDeserialize(s){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(os),!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 I,this._container.matrixAutoUpdate=!1,this.context.scene.add(this._container),this._batchSystem=new eO,this._batchSystem.name=this.gameObject.name,this._container.add(this._batchSystem),this._interface=new GE(this),this._particleSystem=new tO(this._interface),this._particleSystem.addBehavior(new VE(this)),this._particleSystem.addBehavior(new qE(this)),this._particleSystem.addBehavior(new UE(this)),this._particleSystem.addBehavior(new NE(this)),this._particleSystem.addBehavior(new $E(this)),this._particleSystem.addBehavior(new HE(this)),this._batchSystem.addSystem(this._particleSystem);const s=this._particleSystem.emitter;this.context.scene.add(s),this.inheritVelocity.system&&this.inheritVelocity.system!==this&&(this.inheritVelocity=this.inheritVelocity.clone()),this.inheritVelocity.awake(this),Zo&&(console.log(this),this.gameObject.add(new wi(1)))}start(){this.addSubParticleSystems(),this.updateLayers(),this.renderer.particleMesh instanceof K&&this._interface.renderMode==xn.Mesh&&it.assignMeshLOD(this.renderer.particleMesh,0).then(s=>{s&&this.particleSystem&&this._interface.renderMode==xn.Mesh&&(this.particleSystem.instancingGeometry=s)})}onDestroy(){var s,t,i,n;(s=this._container)==null||s.removeFromParent(),(t=this._batchSystem)==null||t.removeFromParent(),(i=this._particleSystem)==null||i.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 s;this.main&&(this._didPreWarm===!1&&((s=this.main)==null?void 0:s.prewarm)===!0&&(this._didPreWarm=!0,this.preWarm()),this.onUpdate(),this.onSimulate(this.deltaTime))}preWarm(){var s;if(!((s=this.emission)!=null&&s.enabled)||this.emission.rateOverTime.getMax()<=0)return;const t=1/60,i=this.main.duration,n=this.main.startLifetime.getMax(),o=1e3,r=Math.min(Math.max(i,n)/Math.max(.01,this.main.simulationSpeed),o),l=Math.ceil(r/t),c=Date.now();Zo&&console.log(`Particles ${this.name} - Prewarm for ${l} frames (${r} sec). Duration: ${i}, 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(s){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(s)}this._time+=s,this._time>this.duration&&(this._time=0)}updateLayers(){if(this._batchSystem)for(let s=0;s<this._batchSystem.batches.length;s++){const t=this._batchSystem.batches[s];t.layers.disableAll();const i=this.layer;t.layers.mask=1<<i}}onUpdate(){var s,t;if(this._bursts&&(this.emission.bursts=this._bursts,delete this._bursts),!this._isPlaying)return;const i=this.context.mainCamera;if(i){const r=Je(i);this._cameraScale=r.x}const n=!this.worldspace,o=this.gameObject;if(Oe(o,this.__worldQuaternion),this._worldQuaternionInverted.copy(this.__worldQuaternion).invert(),Je(this.gameObject,this._worldScale),n&&this._container&&(s=this.gameObject)!=null&&s.parent){const r=h1(this,Y0);this._container.matrix.makeScale(r.x,r.y,r.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 s;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 i=(s=t.particleSystem)==null?void 0:s._particleSystem;if(i){t.particleSystem._isUsedAsSubsystem=!0;const n=new Ap(this,this._particleSystem,t.particleSystem,i);n.emitterType=t.type,n.emitterProbability=t.emitProbability,this._particleSystem.addBehavior(n)}else Zo&&console.warn("Could not add SubParticleSystem",t,this)}}};let ct=Dp;Ye([m(Rh)],ct.prototype,"colorOverLifetime",2),Ye([m(Lt)],ct.prototype,"main",2),Ye([m(hn)],ct.prototype,"emission",2),Ye([m(Yo)],ct.prototype,"sizeOverLifetime",2),Ye([m(Xe)],ct.prototype,"shape",2),Ye([m(Ce)],ct.prototype,"noise",2),Ye([m(Ue)],ct.prototype,"trails",2),Ye([m(Qe)],ct.prototype,"velocityOverLifetime",2),Ye([m(lt)],ct.prototype,"limitVelocityOverLifetime",2),Ye([m(Ko)],ct.prototype,"inheritVelocity",2),Ye([m(ta)],ct.prototype,"colorBySpeed",2),Ye([m(Dt)],ct.prototype,"textureSheetAnimation",2),Ye([m(ns)],ct.prototype,"rotationOverLifetime",2),Ye([m(Fi)],ct.prototype,"rotationBySpeed",2),Ye([m(ni)],ct.prototype,"sizeBySpeed",2);class Eh{constructor(){a(this,"particleSystem"),a(this,"emitProbability",1),a(this,"properties"),a(this,"type")}_deserialize(t,i){const n=this.particleSystem;if(n instanceof ct)return;let o="";n&&typeof n.guid=="string"&&(o=n.guid,this.particleSystem=P.findByGuid(o,i)),Zo&&!(this.particleSystem instanceof ct)&&console.warn("Could not find particle system for sub emitter",o,i,this)}}function h1(s,t){if(t.set(1,1,1),s.gameObject.parent&&s.localspace)switch(s.main.scalingMode){case H0.Local:t=Je(s.gameObject.parent,t),t.x=1/t.x,t.y=1/t.y,t.z=1/t.z;break;default:if(!s.unsupported_scaling_mode){s.unsupported_scaling_mode=!0;const i="ParticleSystem scale mode "+H0[s.main.scalingMode]+" is not supported";F()&&xe(i),console.warn(i,s.name,s)}t=Je(s.gameObject,t);break}return t}class Vl extends A{constructor(){super(...arguments),a(this,"_didAssignPlayerColor",!1),a(this,"tryAssignColor",()=>{const t=P.getComponentInParent(this.gameObject,Li);if(t&&t.owner)return this._didAssignPlayerColor=!0,this.assignUserColor(t.owner),!0;const i=P.getComponentInParent(this.gameObject,Rt);return i!=null&&i.connectionId?(this._didAssignPlayerColor=!0,this.assignUserColor(i.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 V_(.2),!this.tryAssignColor()););}assignUserColor(t){const i=Vl.hashCode(t),n=Vl.colorFromHashCode(i);if(this.gameObject.type==="Mesh"){const o=this.gameObject;this.assignColor(n,t,o)}else if(this.gameObject.children)for(const o of this.gameObject.children){const r=o;r.material&&r.material.color&&this.assignColor(n,t,r)}}assignColor(t,i,n){let o=n.material;o&&(o._playerMaterial!==i&&(o=o.clone(),o._playerMaterial=i,n.material=o),o.color=t)}static hashCode(t){var i=0,n,o;if(t.length===0)return i;for(n=0;n<t.length;n++)o=t.charCodeAt(n),i=(i<<5)-i+o,i|=0;return i}static colorFromHashCode(t){const i=(t&16711680)>>16,n=(t&65280)>>8,o=t&255;return new re(i/255,n/255,o/255)}}const QE=O("debugpost");let K0=null;function YE(s){K0=s}function d1(s){let t=s.gameObject;for(;t;){for(const i of ou(t))if(i.isPostProcessingManager===!0)return i;t=t.parent}return null}function KE(s){let t=d1(s);if(!t)if(K0){QE&&console.warn("Adding postprocessing manager to the scene.");const i=s.scene;t=Mi(i,K0)}else F()&&console.warn("No post processing manager found");return t}var ZE=Object.defineProperty,JE=Object.getOwnPropertyDescriptor,u1=(s,t,i,n)=>{for(var o=n>1?void 0:n?JE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&ZE(t,i,o),o};const eA=O("debugpost");class N{constructor(t){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"),t!==void 0&&this.initialize(t)}get isInitialized(){return this._isInitialized}initialize(t){t!==void 0&&(this._value=t,this._defaultValue=t,this._valueRaw=t,this._isInitialized=!0)}get overrideState(){return this._active}set overrideState(t){if(this._active===t)return;this._active=t;const i=t?this._valueRaw:this._defaultValue;this.processValue(i,!0)}get value(){return this._valueRaw}set value(t){this.isInitialized||this.initialize(t),this.processValue(t,!1)}set defaultValue(t){this._defaultValue=t}__init(){this.processValue(this._valueRaw,!0)}processValue(t,i){if(t==null||!i&&this.testIfValueChanged(t)===!1)return;const n=this._value;eA&&typeof n=="number"&&typeof t=="number"&&(n?.toFixed(4),t?.toFixed(4)),!this._active&&this._defaultValue!==void 0?(this._value=this._defaultValue,t=this._defaultValue,this._valueRaw=t):(this._valueRaw=t,this._active&&this.valueProcessor&&(t=this.valueProcessor(t)),this._value=t),this.onValueChanged&&this.onValueChanged(t,n,this)}testIfValueChanged(t){return this._valueRaw!==t}}u1([m()],N.prototype,"overrideState",1),u1([m()],N.prototype,"value",1);class tA extends Zi{constructor(){super([N])}onSerialize(t,i){}onDeserialize(t,i){const n=i.target,o=i.path;let r;if(n&&o&&(r=n[o]),(typeof r!="object"||typeof r=="object"&&r.isVolumeParameter!==!0)&&(r=new N),typeof t=="object"&&"value"in t){const l=t.value;r.initialize(l),r.overrideState=t.overrideState}else r.value=t;return r}}new tA;var iA=Object.defineProperty,sA=Object.getOwnPropertyDescriptor,nA=(s,t,i,n)=>{for(var o=n>1?void 0:n?sA(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&iA(t,i,o),o};const oA=O("debugpost");class ht extends A{constructor(t=void 0){if(super(),a(this,"active",!0),a(this,"_manager",null),a(this,"_result"),a(this,"_postprocessingContext",null),t)for(const i of Object.keys(t)){const n=t[i],o=this[i];o instanceof N?o.initialize(n):o!==void 0&&(this[i]=n)}}get isPostProcessingEffect(){return!0}onEnable(){super.onEnable(),this.onEffectEnabled(),this.__internalDidAwakeAndStart&&(this.active=!0)}onDisable(){var t;super.onDisable(),(t=this._manager)==null||t.removeEffect(this),this.active=!1}onEffectEnabled(t){var i;t&&t.isPostProcessingManager===!0?this._manager=t:this._manager||(this._manager=KE(this)),(i=this._manager)==null||i.addEffect(this)}init(){}get postprocessingContext(){return this._postprocessingContext}apply(t){var i;return this._postprocessingContext=t,this._result||(this.initParameters(),this._result=(i=this.onCreateEffect)==null?void 0:i.call(this)),this._result&&this.initParameters(),this._result}unapply(){}dispose(){oA&&console.warn("DISPOSE",this),this._result&&(Array.isArray(this._result)?this._result.forEach(t=>t.dispose()):this._result.dispose()),this._result=void 0}initParameters(){const t=Object.keys(this);for(const i of t){const n=this[i];n instanceof N&&n.__init()}}onEditorModification(t){const i=t.propertyName;if(this[i]instanceof N){const n=t.value;return this[i].value=n,!0}}}nA([m()],ht.prototype,"active",2);var rA=Object.defineProperty,aA=Object.getOwnPropertyDescriptor,lA=(s,t,i,n)=>{for(var o=n>1?void 0:n?aA(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&rA(t,i,o),o};const cA=O("debugpost"),Z0={};function rs(s,t){Z0[s]=t}function hA(s){return s.__type in Z0?Z0[s.__type]:(cA&&s.__type&&console.warn("Unknown postprocessing type",s.__type,s),ht)}class Ah{constructor(){a(this,"components",[])}init(){var t;(t=this.components)==null||t.forEach(i=>i.init())}addEffect(t){this.components.push(t)}removeEffect(t){const i=this.components.indexOf(t);i>=0&&this.components.splice(i,1)}}lA([$a([s=>hA(s),ht])],Ah.prototype,"components",2);var dA=Object.defineProperty,uA=Object.getOwnPropertyDescriptor,pA=(s,t,i,n)=>{for(var o=n>1?void 0:n?uA(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&dA(t,i,o),o};class Ih extends ht{constructor(){super(...arguments),a(this,"preset",new N(2))}get typeName(){return"Antialiasing"}onCreateEffect(){const t=new L.POSTPROCESSING.MODULE.SMAAEffect({preset:L.POSTPROCESSING.MODULE.SMAAPreset.HIGH,edgeDetectionMode:L.POSTPROCESSING.MODULE.EdgeDetectionMode.DEPTH});return this.preset.onValueChanged=i=>{t.applyPreset(i)},t}}pA([m(N)],Ih.prototype,"preset",2),rs("Antialiasing",Ih);var mA=Object.defineProperty,gA=Object.getOwnPropertyDescriptor,J0=(s,t,i,n)=>{for(var o=n>1?void 0:n?gA(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&mA(t,i,o),o},ey;const p1=(ey=class extends ht{constructor(){super(...arguments),a(this,"threshold",new N(.9)),a(this,"intensity",new N(1)),a(this,"scatter",new N(.3)),a(this,"selectiveBloom")}get typeName(){return"Bloom"}init(){this.threshold.valueProcessor=s=>s,this.intensity.valueProcessor=s=>s,this.scatter.valueProcessor=s=>s}onCreateEffect(){let s;if(this.selectiveBloom==null&&(this.selectiveBloom=p1.useSelectiveBloom),this.selectiveBloom){const t=s=new L.POSTPROCESSING.MODULE.SelectiveBloomEffect(this.context.scene,this.context.mainCamera,{blendFunction:L.POSTPROCESSING.MODULE.BlendFunction.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,radius:.85,intensity:this.intensity.value});t.inverted=!0}else s=new L.POSTPROCESSING.MODULE.BloomEffect({blendFunction:L.POSTPROCESSING.MODULE.BlendFunction.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,radius:.85,intensity:this.intensity.value});return this.intensity.onValueChanged=t=>{s.intensity=t},this.threshold.onValueChanged=t=>{s.luminanceMaterial.threshold=Math.pow(t,2.2)},this.scatter.onValueChanged=t=>{s.luminancePass.enabled=!0,s.luminanceMaterial.smoothing=t,s.mipmapBlurPass&&(s.mipmapBlurPass.radius=vn.lerp(.1,.9,t))},s}},a(ey,"useSelectiveBloom",!1),ey);let sa=p1;J0([m(N)],sa.prototype,"threshold",2),J0([m(N)],sa.prototype,"intensity",2),J0([m(N)],sa.prototype,"scatter",2),rs("Bloom",sa);var fA=Object.defineProperty,yA=Object.getOwnPropertyDescriptor,vA=(s,t,i,n)=>{for(var o=n>1?void 0:n?yA(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&fA(t,i,o),o};class jh extends ht{constructor(){super(...arguments),a(this,"intensity",new N(0))}get typeName(){return"ChromaticAberration"}onCreateEffect(){const t=new L.POSTPROCESSING.MODULE.ChromaticAberrationEffect;return t.offset=new oe(0,0),t.radialModulation=!0,t.modulationOffset=.15,this.intensity.valueProcessor=i=>i*.02,this.intensity.onValueChanged=i=>{t.offset.x=-i,t.offset.y=i},t}}vA([m(N)],jh.prototype,"intensity",2),rs("ChromaticAberration",jh);var bA=Object.defineProperty,_A=Object.getOwnPropertyDescriptor,m1=(s,t,i,n)=>{for(var o=n>1?void 0:n?_A(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&bA(t,i,o),o};const g1=O("debugpost");var Bp=(s=>(s[s.None=0]="None",s[s.Neutral=1]="Neutral",s[s.ACES=2]="ACES",s[s.AgX=3]="AgX",s[s.KhronosNeutral=4]="KhronosNeutral",s))(Bp||{});function ty(s){switch(s){case 0:return fd;case 1:return _m;case 2:return bm;case 3:return gd;case 4:return Ql;default:return Ql}}function wA(s){switch(s){case fd:return 0;case bm:return 2;case gd:return 3;case Ql:return 1;case _m:return 1;default:return 0}}function f1(s){switch(s){case fd:return L.POSTPROCESSING.MODULE.ToneMappingMode.LINEAR;case bm:return L.POSTPROCESSING.MODULE.ToneMappingMode.ACES_FILMIC;case gd:return L.POSTPROCESSING.MODULE.ToneMappingMode.AGX;case Ql:return L.POSTPROCESSING.MODULE.ToneMappingMode.NEUTRAL;case _m:return L.POSTPROCESSING.MODULE.ToneMappingMode.REINHARD;default:return L.POSTPROCESSING.MODULE.ToneMappingMode.LINEAR}}const y1=class extends ht{constructor(){super(...arguments),a(this,"mode",new N(void 0)),a(this,"exposure",new N(1))}get typeName(){return"ToneMapping"}setMode(s){const t=Bp[s];return t===void 0?(console.error("Invalid ToneMapping mode",s),this):(this.mode.value=t,this)}get isToneMapping(){return!0}onEffectEnabled(){const s=d1(this);s&&super.onEffectEnabled(s)}onCreateEffect(){if(this.postprocessingContext)for(const i of this.postprocessingContext.components){if(i===this)break;if(i!=this&&i instanceof y1){console.warn("Multiple tonemapping effects found in the same postprocessing stack: Please check your scene setup.",{activeEffect:i,ignoredEffect:this});return}}if(this.mode.isInitialized==!1){const i=wA(this.context.renderer.toneMapping);this.mode.initialize(i)}const s=ty(this.mode.value),t=new L.POSTPROCESSING.MODULE.ToneMappingEffect({mode:f1(s)});return this.mode.onValueChanged=i=>{const n=ty(i);t.mode=f1(n),g1&&console.log("ToneMapping mode changed to",Bp[i],n,t.mode)},g1&&console.log("Use ToneMapping",Bp[this.mode.value],s,t.mode,"renderer.tonemapping: "+this.context.renderer.toneMapping),this.exposure.onValueChanged=i=>{this.context.renderer.toneMappingExposure=i},t}onBeforeRender(){this.mode.overrideState&&(this.context.renderer.toneMapping=ty(this.mode.value)),this.exposure.overrideState&&(this.context.renderer.toneMappingExposure=this.exposure.value)}};let er=y1;m1([m(N)],er.prototype,"mode",2),m1([m(N)],er.prototype,"exposure",2),rs("Tonemapping",er);var xA=Object.defineProperty,SA=Object.getOwnPropertyDescriptor,Fp=(s,t,i,n)=>{for(var o=n>1?void 0:n?SA(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&xA(t,i,o),o};class tr extends ht{constructor(){super(...arguments),a(this,"postExposure",new N(0)),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=t=>(t=Math.pow(2,t),t),this.contrast.valueProcessor=t=>{let i=1;return t>0?i=200:t<0&&(i=100),t/i},this.contrast.defaultValue=0,this.hueShift.valueProcessor=t=>Math.PI*t/180,this.hueShift.defaultValue=0,this.saturation.valueProcessor=t=>t<0?t/100:t/(100*Math.PI),this.saturation.defaultValue=0}onCreateEffect(){var t,i;const n=[];this.context.renderer.toneMapping!==wa&&this.postExposure.overrideState&&(this.context.renderer.toneMapping=wa);let o=(t=this.postprocessingContext)==null?void 0:t.components.find(c=>c instanceof er);o||(o=new er,(i=this.postprocessingContext)==null||i.components.push(o)),this.postExposure.onValueChanged=c=>{this.postExposure.overrideState&&(o.exposure.value=c)};const r=new L.POSTPROCESSING.MODULE.BrightnessContrastEffect;this.contrast.onValueChanged=c=>r.contrast=c;const l=new L.POSTPROCESSING.MODULE.HueSaturationEffect;return n.push(r),n.push(l),this.hueShift.onValueChanged=c=>l.hue=c,this.saturation.onValueChanged=c=>l.saturation=c,n}}Fp([m(N)],tr.prototype,"postExposure",2),Fp([m(N)],tr.prototype,"contrast",2),Fp([m(N)],tr.prototype,"hueShift",2),Fp([m(N)],tr.prototype,"saturation",2),rs("ColorAdjustments",tr);var CA=Object.defineProperty,OA=Object.getOwnPropertyDescriptor,na=(s,t,i,n)=>{for(var o=n>1?void 0:n?OA(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&CA(t,i,o),o};const PA=O("debugpost");class As extends ht{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*1/window.devicePixelRatio)),a(this,"bokehScale",new N)}get typeName(){return"DepthOfField"}init(){this.focalLength.valueProcessor=i=>{const n=i/300,o=2;return W.lerp(o,.01,n)};const t=20;this.aperture.valueProcessor=i=>{const n=1-i/32;return W.lerp(1,t,n)}}onCreateEffect(){if(this.mode===0){PA&&console.warn("DepthOfField: Mode is set to Off");return}const t=new L.POSTPROCESSING.MODULE.DepthOfFieldEffect(this.context.mainCamera,{worldFocusRange:.2,focalLength:1,bokehScale:20,resolutionScale:this.resolutionScale.value});return this.focusDistance.onValueChanged=i=>{t.cocMaterial.worldFocusDistance=i},this.focalLength.onValueChanged=i=>t.cocMaterial.worldFocusRange=i,this.aperture.onValueChanged=i=>t.bokehScale=i,this.resolutionScale&&(this.resolutionScale.onValueChanged=i=>t.resolution.scale=i),[t]}unapply(){}}na([m()],As.prototype,"mode",2),na([m(N)],As.prototype,"focusDistance",2),na([m(N)],As.prototype,"focalLength",2),na([m(N)],As.prototype,"aperture",2),na([m(N)],As.prototype,"gaussianMaxRadius",2),na([m(N)],As.prototype,"resolutionScale",2),na([m(N)],As.prototype,"bokehScale",2),rs("DepthOfField",As);class Lh extends ht{constructor(t){super(),a(this,"effect"),this.effect=t}get typeName(){return this.effect.constructor.name}onCreateEffect(){return this.effect}}var kA=Object.defineProperty,MA=Object.getOwnPropertyDescriptor,RA=(s,t,i,n)=>{for(var o=n>1?void 0:n?MA(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&kA(t,i,o),o};class Dh extends ht{constructor(){super(...arguments),a(this,"granularity",new N(10))}get typeName(){return"PixelationEffect"}onCreateEffect(){const t=new L.POSTPROCESSING.MODULE.PixelationEffect;return this.granularity.onValueChanged=i=>{t.granularity=i},t}}RA([m(N)],Dh.prototype,"granularity",2),rs("PixelationEffect",Dh);var TA=Object.defineProperty,EA=Object.getOwnPropertyDescriptor,Bh=(s,t,i,n)=>{for(var o=n>1?void 0:n?EA(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&TA(t,i,o),o};class Gn extends ht{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 re(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 t=this.context.mainCamera.far-this.context.mainCamera.near;this._ssao.ssaoMaterial.worldDistanceFalloff=t*.01,this._ssao.ssaoMaterial.worldDistanceThreshold=this.context.mainCamera.far}}onCreateEffect(){const t=this.context.mainCamera,i=new L.POSTPROCESSING.MODULE.NormalPass(this.context.scene,t),n=new L.POSTPROCESSING.MODULE.DepthDownsamplingPass({normalBuffer:i.texture,resolutionScale:.5}),o=this._ssao=new L.POSTPROCESSING.MODULE.SSAOEffect(t,i.texture,{normalDepthBuffer:n.texture,worldDistanceThreshold:1,worldDistanceFalloff:1,worldProximityThreshold:.1,worldProximityFalloff:2,intensity:1,blendFunction:L.POSTPROCESSING.MODULE.BlendFunction.MULTIPLY,luminanceInfluence:.5});this.intensity.onValueChanged=l=>{o.intensity=l},this.falloff.onValueChanged=l=>{o.ssaoMaterial.radius=l*.1},this.samples.onValueChanged=l=>{o.ssaoMaterial.samples=l},this.color.onValueChanged=l=>{o.color||(o.color=new re),o.color.copy(l)},this.luminanceInfluence.onValueChanged=l=>{o.luminanceInfluence=l};const r=new Array;return r.push(i),r.push(n),r.push(o),r}}Bh([m(N)],Gn.prototype,"intensity",2),Bh([m(N)],Gn.prototype,"falloff",2),Bh([m(N)],Gn.prototype,"samples",2),Bh([m(N)],Gn.prototype,"color",2),Bh([m(N)],Gn.prototype,"luminanceInfluence",2),rs("ScreenSpaceAmbientOcclusion",Gn);var AA=Object.defineProperty,IA=Object.getOwnPropertyDescriptor,oa=(s,t,i,n)=>{for(var o=n>1?void 0:n?IA(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&AA(t,i,o),o},iy=(s=>(s[s.Performance=0]="Performance",s[s.Low=1]="Low",s[s.Medium=2]="Medium",s[s.High=3]="High",s[s.Ultra=4]="Ultra",s))(iy||{});class Is extends ht{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 re(0,0,0))),a(this,"screenspaceRadius",!1),a(this,"quality",2),a(this,"_ssao")}get typeName(){return"ScreenSpaceAmbientOcclusionN8"}onValidate(){this._ssao&&(this._ssao.setQualityMode(iy[this.quality]),this._ssao.configuration.gammaCorrection=this.gammaCorrection,this._ssao.configuration.screenSpaceRadius=this.screenspaceRadius)}onCreateEffect(){const t=this.context.mainCamera,i=this._ssao=new L.POSTPROCESSING_AO.MODULE.N8AOPostPass(this.context.scene,t,this.context.domWidth,this.context.domHeight),n=iy[this.quality];i.setQualityMode(n),i.configuration.gammaCorrection=this.gammaCorrection,i.configuration.screenSpaceRadius=this.screenspaceRadius,this.intensity.onValueChanged=r=>{i.configuration.intensity=r},this.falloff.onValueChanged=r=>{i.configuration.distanceFalloff=r},this.aoRadius.onValueChanged=r=>{i.configuration.aoRadius=r},this.color.onValueChanged=r=>{i.color||(i.color=new re),i.configuration.color.copy(r)};const o=new Array;return o.push(i),o}}oa([Mt(),m()],Is.prototype,"gammaCorrection",2),oa([m(N)],Is.prototype,"aoRadius",2),oa([m(N)],Is.prototype,"falloff",2),oa([m(N)],Is.prototype,"intensity",2),oa([m(N)],Is.prototype,"color",2),oa([Mt(),m()],Is.prototype,"screenspaceRadius",2),oa([Mt(),m()],Is.prototype,"quality",2),rs("ScreenSpaceAmbientOcclusionN8",Is);var jA=Object.defineProperty,LA=Object.getOwnPropertyDescriptor,v1=(s,t,i,n)=>{for(var o=n>1?void 0:n?LA(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&jA(t,i,o),o};class Fh extends ht{constructor(){super(...arguments),a(this,"_effect"),a(this,"_amount",1),a(this,"_radius",1)}get typeName(){return"Sharpening"}onCreateEffect(){return this._effect??(this._effect=new(DA())),this.effect}get effect(){return this._effect}set amount(t){this._amount=t,this._effect&&(this._effect.uniforms.get("amount").value=t)}get amount(){return this._effect?this._effect.uniforms.get("amount").value:this._amount}set radius(t){this._radius=t,this._effect&&(this._effect.uniforms.get("radius").value=t)}get radius(){return this._effect?this._effect.uniforms.get("radius").value:this._radius}}v1([m()],Fh.prototype,"amount",1),v1([m()],Fh.prototype,"radius",1);function DA(){const s=`
1206
1206
  void mainSupport() {
1207
1207
  vUv = uv;
1208
1208
  gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
@@ -1361,7 +1361,7 @@ void main() {
1361
1361
  #include <colorspace_fragment>
1362
1362
  }
1363
1363
  `;var hj=Object.defineProperty,dj=Object.getOwnPropertyDescriptor,cr=(s,t,i,n)=>{for(var o=n>1?void 0:n?dj(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&hj(t,i,o),o};const z1=O("debugimagetracking"),Cy=class{constructor(s,t,i,n,o,r){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=s,this._trackedImage=t,this._bitmap=i,this.measuredSize=n,this.state=o,this._pose=r}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(s){return this.ensureTransformData(),s.copy(this._position),s}getQuaternion(s){return this.ensureTransformData(),s.copy(this._rotation),s}applyToObject(s,t=void 0){this.ensureTransformData();const i=s.position.distanceToSquared(this._position)/.05+s.quaternion.angleTo(this._rotation)/.05;t&&(t*=Math.max(1,i)),t===void 0||t>=1?(s.position.copy(this._position),s.quaternion.copy(this._rotation)):(t=Math.max(0,Math.min(1,t)),s.position.lerp(this._position,t),s.quaternion.slerp(this._rotation,t))}ensureTransformData(){if(!this._position){this._position=Cy._positionBuffer.get(),this._rotation=Cy._rotationBuffer.get();const s=this._pose.transform,t=J.active.convertSpace(s);this._position.copy(t?.position),this._rotation.copy(t?.quaternion)}}};let Bl=Cy;a(Bl,"_positionBuffer",new Si(()=>new x,20)),a(Bl,"_rotationBuffer",new Si(()=>new V,20));class fn{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)],fn.prototype,"image",2),cr([m()],fn.prototype,"widthInMeters",2),cr([m(ae)],fn.prototype,"object",2),cr([m()],fn.prototype,"createObjectInstance",2),cr([m()],fn.prototype,"imageDoesNotMove",2),cr([m()],fn.prototype,"hideWhenTrackingIsLost",2);class uj{constructor(t,i,n){a(this,"filename"),a(this,"widthInMeters"),a(this,"imageData"),this.filename=t,this.imageData=i,this.widthInMeters=n}get extensionName(){return"image-tracking"}onAfterHierarchy(t,i){const n=X.getiOSVersion(),o=(n?parseInt(n.split(".")[0]):18)>=18?1:100;i.beginBlock('def Preliminary_ReferenceImage "AnchoringReferenceImage"'),i.appendLine("uniform asset image = @image_tracking/"+this.filename+"@"),i.appendLine("uniform double physicalWidth = "+(this.widthInMeters*o).toFixed(8)),i.closeBlock()}onBeforeBuildDocument(t){const i=P.findObjectOfType(da);!i||!i.trackedImages||i.trackedImages.length>1&&(F()&&xe("USDZ: Only one tracked image is supported."),console.warn("USDZ: Only one tracked image is supported."))}onAfterSerialize(t){t.files["image_tracking/"+this.filename]=this.imageData}onExportObject(t,i,n){var o;const r=P.findObjectOfType(da);if(!(!r||!r.trackedImages)){for(const l of r.trackedImages)if(((o=l.object)==null?void 0:o.asset)===t){const c=P.findObjectOfType(Ge);if(!c)continue;const{scale:h,target:d}=c.getARScaleAndTarget();let u=t;const p=new ne;if(t!==d)for(;u.parent&&u.parent!==d;)u=u.parent,p.premultiply(u.matrix);const g=p.clone().invert();i.setMatrix(g.scale(new x(h,h,h)));break}}}}var Oy;const td=(Oy=class extends A{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",s=>{const t=J.active;if(t)for(const i of s){const n=i.model,o=i.state==="tracked";if(!n.object)continue;let r=this.imageToObjectMap.get(n);if(r===void 0)r={object:null,frames:0,lastTrackingTime:Date.now()},this.imageToObjectMap.set(n,r),n.object.loadAssetAsync().then(l=>{if(n.createObjectInstance&&l&&(l=P.instantiate(l)),l){r.object=l;for(const c of l.getComponentsInChildren(et))c.setInstancingEnabled(!1);t.rig?(t.rig.gameObject.add(l),i.applyToObject(l),l.activeSelf||P.setActive(l,!0)):console.warn("XRImageTracking: missing XRRig")}});else{if(r.frames++,o&&(r.lastTrackingTime=Date.now()),n.imageDoesNotMove&&r.frames>10||!r.object)continue;t.rig&&(t.rig.gameObject.add(r.object),i.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(z1&&console.log(this),!!this.trackedImages){for(const s of this.trackedImages)if(s.image&&!td._imageElements.has(s.image)){const t=s.image;td._imageElements.set(t,null);const i=document.createElement("img");i.src=t,i.addEventListener("load",async()=>{const n=await createImageBitmap(i);td._imageElements.set(t,n);const o=await Mx(n);if(o){const r=await(await o.convertToBlob({type:"image/png"})).arrayBuffer(),l=P.findObjectOfType(Ge);l&&this.trackedImages&&(l.extensions.push(new uj("marker.png",new Uint8Array(r),this.trackedImages[0].widthInMeters)),l.anchoringType="image")}})}}}onBeforeXR(s,t){var i;if(this.trackedImages){t.optionalFeatures=t.optionalFeatures||[],t.optionalFeatures.includes("image-tracking")||t.optionalFeatures.push("image-tracking"),t.trackedImages=[];for(const n of this.trackedImages)if((i=n.image)!=null&&i.length&&n.widthInMeters>0){const o=td._imageElements.get(n.image);o&&(this.trackedImageIndexMap.set(t.trackedImages.length,n),t.trackedImages.push({image:o,widthInMeters:n.widthInMeters}))}}}onEnterXR(s){var t;if(this.trackedImages){for(const i of this.trackedImages)if((t=i.object)!=null&&t.asset){const n=i.object.asset;n.userData||(n.userData={});const o={visible:n.visible,parent:n.parent,matrix:n.matrix.clone()};n.userData["image-tracking"]=o}}for(const i of this.imageToObjectMap.values())i.frames=0}onLeaveXR(s){var t,i;if(!this.supported&&X.isAndroidDevice()&&xe(this.webXRIncubationsWarning),this.trackedImages){for(const n of this.trackedImages)if((t=n.object)!=null&&t.asset){const o=n.object.asset;if(o.userData){const r=o.userData["image-tracking"];r&&(o.visible=r.visible,(i=r.parent)==null||i.add(o),o.matrix.copy(r.matrix),o.matrix.decompose(o.position,o.quaternion,o.scale)),delete o.userData["image-tracking"]}}}}onUpdateXR(s){var t;this.currentImages.length=0;const i=s.xr.frame;if(!i)return;if("getImageTrackingResults"in i){if(((t=s.xr.session.enabledFeatures)==null?void 0:t.includes("image-tracking"))===!1)return;if(i.session&&typeof i.getImageTrackingResults=="function"){const o=i.getImageTrackingResults();if(o.length>0){const r=this.context.renderer.xr.getReferenceSpace();if(r){for(const l of o){const c=l.trackingState,h=l.index,d=this.trackedImageIndexMap.get(h);if(d){const u=i.getPose(l.imageSpace,r),p=new Bl(this,d,l.image,l.measuredSize,c,u);this.currentImages.push(p)}else z1&&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,xe(this.webXRIncubationsWarning);return}const n=1e3;for(const[o,r]of this.imageToObjectMap){if(!r.object||!o||o.hideWhenTrackingIsLost===!1)continue;let l=!1;for(const c of this.currentImages)if(c.model===o){const h=Date.now()-r.lastTrackingTime;if(o.imageDoesNotMove||c.state==="tracked"||h<=n){l=!0;break}}l||P.setActive(r.object,!1)}}},a(Oy,"_imageElements",new Map),Oy);let da=td;cr([m(fn)],da.prototype,"trackedImages",2),cr([m()],da.prototype,"smooth",2);var pj=Object.defineProperty,mj=Object.getOwnPropertyDescriptor,Fl=(s,t,i,n)=>{for(var o=n>1?void 0:n?mj(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&pj(t,i,o),o};const ua=O("debugplanetracking");class Jn extends A{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 _i),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",(t,i,n=!1)=>{if(i){if(i instanceof Array){for(const o of i)this.makeOccluder(t,o,n);return}!n&&!i.name.toLowerCase().includes("occlu")||(i.colorWrite=!1,i.depthTest=!0,i.depthWrite=!0,i.transparent=!1,i.polygonOffset=!0,i.polygonOffsetFactor=1,i.polygonOffsetUnits=.1,t.renderOrder=-1e3)}}),a(this,"_flipForwardMatrix",new ne().makeRotationY(Math.PI)),a(this,"_verticesCache",new Map)}get trackedPlanes(){return this._allPlanes.values()}get trackedMeshes(){return this._allMeshes.values()}onBeforeXR(t,i){t==="immersive-vr"&&!this.runInVR||(i.optionalFeatures=i.optionalFeatures||[],this.usePlaneData&&!i.optionalFeatures.includes("plane-detection")&&i.optionalFeatures.push("plane-detection"),this.useMeshData&&!i.optionalFeatures.includes("mesh-detection")&&i.optionalFeatures.push("mesh-detection"))}onEnterXR(t){for(const i of this._allPlanes.keys())this.removeData(i,this._allPlanes);for(const i of this._allMeshes.keys())this.removeData(i,this._allMeshes)}onLeaveXR(t){for(const i of this._allPlanes.keys())this.removeData(i,this._allPlanes);for(const i of this._allMeshes.keys())this.removeData(i,this._allMeshes)}onUpdateXR(t){if(!this.runInVR&&t.xr.isVR)return;const i=t.xr.rig;if(!i){console.warn("No XR rig found, cannot parent tracked planes to it");return}const n=t.xr.frame;if(!this.context.renderer.xr.getReferenceSpace())return;const o=n.detectedPlanes,r=n.detectedMeshes,l=o!==void 0&&o.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 n.session&&(n.session.initiateRoomCapture(),this.firstTimeNoPlanesDetected=-1)),o!==void 0&&this.processFrameData(t.xr,i.gameObject,n,o,this._allPlanes),r!==void 0&&this.processFrameData(t.xr,i.gameObject,n,r,this._allMeshes),ua){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 K&&this.bounds.expandByObject(u)}),this.bounds.getCenter(this.center),this.labelOffset.copy(h).sub(this.center).normalize().multiplyScalar(.1),q.DrawLabel(this.center.add(this.labelOffset),(d.xrData.semanticLabel||"plane").toUpperCase()+`
1364
- `+d.xrData.lastChangedTime.toFixed(2),.02))}}removeData(t,i){const n=i.get(t);if(!n)return;i.delete(t),ua&&console.log("Plane no longer tracked, id="+n.id),n.mesh&&(n.mesh.removeFromParent(),n.mesh.traverse(r=>{const l=r.userData.normalsHelper;l?(l.dispose(),l.removeFromParent()):ua&&console.warn("No normals helper found for mesh",n.mesh)}),Ri(n.mesh,!0,!0));const o=new CustomEvent("plane-tracking",{detail:{type:"plane-removed",context:n}});this.dispatchEvent(o)}processFrameData(t,i,n,o,r){const l=this.context.renderer.xr.getReferenceSpace();if(l){for(const c of r.keys())o.has(c)||this.removeData(c,r);for(const c of o){const h="planeSpace"in c?c.planeSpace:"meshSpace"in c?c.meshSpace:void 0;if(!h)continue;const d=n.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 y=this.createGeometry(c);if(p.mesh instanceof K)p.mesh.geometry.dispose(),p.mesh.geometry=y,this.makeOccluder(p.mesh,p.mesh.material);else if(p.mesh instanceof ro)for(const f of p.mesh.children)f instanceof K&&(f.geometry.dispose(),f.geometry=y,this.makeOccluder(f,f.material));if(p.collider){const f=p.mesh;p.collider.sharedMesh=f,p.collider.convex=this.checkIfContextShouldBeConvex(f,p.xrData),p.collider.onDisable(),p.collider.onEnable()}ua&&(console.log("Plane updated, id="+p.id,p),p.mesh.traverse(f=>{if(!(f instanceof K))return;const v=f.userData.normalsHelper;v&&v.update()}))}const g=new CustomEvent("plane-tracking",{detail:{type:"plane-updated",context:p}});this.dispatchEvent(g)}}else{if(!this.dataTemplate){const p=new K;ua?p.material=new CC:this.occluder?(p.material=new Re,this.makeOccluder(p,p.material,!0)):p.material=new Re({wireframe:!0,opacity:.5,transparent:!0,color:3355443}),this.dataTemplate=new ae("","",p)}if(!this.dataTemplate.asset)this.dataTemplate.loadAssetAsync();else{const p=P.instantiate(this.dataTemplate.asset);if(p.name="xr-tracked-plane",u=p,Qm(p,!1),p instanceof K)Ee(p.geometry),p.geometry=this.createGeometry(c),this.makeOccluder(p,p.material,this.occluder&&!this.dataTemplate);else if(p instanceof ro)for(const f of p.children)f instanceof K&&(Ee(f.geometry),f.geometry=this.createGeometry(c),this.makeOccluder(f,f.material,this.occluder&&!this.dataTemplate));const g=p.getComponent(Io);if(g){const f=p;g.sharedMesh=f,g.convex=this.checkIfContextShouldBeConvex(f,c),g.onDisable(),g.onEnable()}p.matrixAutoUpdate=!1,p.matrixWorldNeedsUpdate=!0,i.add(p);const y={id:this._dataId++,xrData:c,timestamp:c.lastChangedTime,mesh:p,collider:g};r.set(c,y),ua&&console.log("New plane detected, id="+y.id,y,{hasCollider:!!g,isGroup:p instanceof ro});try{const f=new CustomEvent("plane-tracking",{detail:{type:"plane-added",context:y}});this.dispatchEvent(f)}catch(f){console.error(f)}}}u&&(d?(u.visible=!0,u.matrix.fromArray(d.transform.matrix),u.matrix.premultiply(this._flipForwardMatrix)):u.visible=!1,ua&&u.traverse(p=>{if(p instanceof K)if(p.userData.normalsHelper)p.userData.normalsHelper.update();else{const g=new XC(p,.05,255);g.layers.disableAll(),g.layers.set(2),this.context.scene.add(g),p.userData.normalsHelper=g}}))}}}checkIfContextShouldBeConvex(t,i){if(!t)return!0;if(t){const n=new _i;n.expandByObject(t);const o=new x;n.getSize(o);let r=!0;return o.x>2&&o.y>2&&o.z>1.5&&(r=!1),r&&"semanticLabel"in i&&i.semanticLabel==="wall"&&(r=!0),r}return!0}createGeometry(t){return"polygon"in t?this.createPlaneGeometry(t.polygon):"vertices"in t&&"indices"in t?this.createMeshGeometry(t.vertices,t.indices):new bn}createMeshGeometry(t,i){const n=t.toString()+"_"+i.toString();if(this._verticesCache.has(n))return this._verticesCache.get(n);const o=new bn;o.setIndex(new ft(i,1)),o.setAttribute("position",new ft(t,3));const r=Array();for(let l=0;l<t.length;l+=3)r.push(t[l],t[l+2]);return o.setAttribute("uv",new ft(t,3)),o.computeVertexNormals(),this._verticesCache.set(n,o),o}createPlaneGeometry(t){const i=new bn,n=[],o=[];t.forEach(g=>{n.push(g.x,g.y,g.z),o.push(g.x,g.z)});const r=new x(n[0],n[1],n[2]),l=new x(n[3],n[4],n[5]),c=new x(n[6],n[7],n[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<n.length/3;g++)u.push(h.x,h.y,h.z);const p=[];for(let g=2;g<t.length;++g)p.push(0,g-1,g);return i.setAttribute("position",new ft(new Float32Array(n),3)),i.setAttribute("uv",new ft(new Float32Array(o),2)),i.setAttribute("normal",new ft(new Float32Array(u),3)),i.setIndex(p),i.computeBoundingBox(),i.computeBoundingSphere(),i}}Fl([m(ae)],Jn.prototype,"dataTemplate",2),Fl([m()],Jn.prototype,"occluder",2),Fl([m()],Jn.prototype,"initiateRoomCaptureIfNoData",2),Fl([m()],Jn.prototype,"usePlaneData",2),Fl([m()],Jn.prototype,"useMeshData",2),Fl([m()],Jn.prototype,"runInVR",2);var gj=Object.defineProperty,fj=Object.getOwnPropertyDescriptor,yj=(s,t,i,n)=>{for(var o=n>1?void 0:n?fj(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&gj(t,i,o),o};const U1=O("debugwebxr");class im extends A{constructor(){super(...arguments),a(this,"priority",0),a(this,"_startScale")}get isActive(){return this.activeAndEnabled&&this.gameObject.visible}setAsActiveXRRig(){var t;(t=J.active)==null||t.setRigActive(this)}setPriority(t){this.priority=t}awake(){if(U1){const t=new I;t.position.y+=.5,this.gameObject.add(t);const i=t.addNewComponent(Zr);i&&(i.isGizmo=!1);const n=new wi(.5);this.gameObject.add(n)}}isXRRig(){return!0}supportsXR(t){return!0}onEnterXR(t){this._startScale=this.gameObject.scale.clone(),t.xr.addRig(this),U1&&console.log("WebXR: add Rig",this.name,this.priority)}onLeaveXR(t){t.xr.removeRig(this),this._startScale&&this.gameObject&&this.gameObject.scale.copy(this._startScale)}}yj([m()],im.prototype,"priority",2);class Py{}const vj=Object.freeze(Object.defineProperty({__proto__:null,ActionBuilder:fe,ActionCollection:h0,ActionModel:Ii,AlignmentConstraint:Lc,Animation:Wt,AnimationCurve:Dr,AnimationExtension:lh,AnimationTrackHandler:Qp,Animator:kt,AnimatorController:Hi,Antialiasing:Ih,AudioExtension:dr,AudioListener:To,AudioSource:We,AudioTrackHandler:Qh,Avatar:Ho,AvatarBlink_Simple:zr,AvatarEyeLook_Rotation:Ja,AvatarLoader:Mf,AvatarMarker:Rt,AvatarModel:Wu,Avatar_Brain_LookAt:$c,Avatar_MouthShapes:Xc,Avatar_MustacheShake:Of,Avatar_POI:Qs,AxesHelper:el,BaseUIComponent:ls,BasicIKConstraint:Tf,BehaviorExtension:up,BehaviorModel:Tt,BloomEffect:sa,BoxCollider:il,BoxGizmo:Zr,BoxHelperComponent:is,Button:Kn,CallInfo:Gs,Camera:Pe,CameraTargetReachedEvent:Vc,Canvas:Et,CanvasGroup:No,CapsuleCollider:In,ChangeMaterialOnClick:yl,ChangeTransformOnClick:qr,CharacterController:Ur,CharacterControllerInput:Ln,ChromaticAberration:jh,Collider:pi,ColorAdjustments:tr,ColorBySpeedModule:ta,ColorOverLifetimeModule:Rh,ContactShadows:ks,ControlTrackHandler:Yp,CustomBranding:Go,Deletable:Lf,DeleteBox:eh,DepthOfField:As,DeviceFlag:Hu,DocumentExtension:u0,DragControls:mi,DropListener:Dn,Duplicatable:Wr,EffectWrapper:Lh,EmissionModule:hn,EmphasizeOnClick:_l,EventList:_e,EventListEvent:Eu,EventSystem:ai,EventTrigger:Gu,FieldWithDefault:Qf,FixedJoint:z0,Fog:Pl,GltfExport:rh,GltfExportBox:Kf,Gradient:Qo,Graphic:Qr,GraphicRaycaster:ju,GridHelper:kl,GridLayoutGroup:w0,GroundProjectedEnv:Hs,GroupActionModel:Nn,HideOnStart:bl,HingeJoint:Sh,HorizontalLayoutGroup:_0,Image:Il,InheritVelocityModule:Ko,InputField:ca,InstanceHandle:ih,InstancingHandler:Hr,Interactable:jf,Keyframe:Qt,LODGroup:Oh,LODModel:Jr,Light:yi,LimitVelocityOverLifetimeModule:lt,LogStats:If,LookAt:ha,LookAtConstraint:Br,MainModule:Lt,MaskableGraphic:gh,MeshCollider:Io,MeshRenderer:oh,MinMaxCurve:Q,MinMaxGradient:si,NeedleMenu:an,NestedGltf:Pp,Networking:Ml,NoiseModule:Ce,ObjectRaycaster:Ei,OffsetConstraint:ea,OpenURL:Ll,OrbitControls:be,Outline:xl,Padding:zo,ParticleBurst:Mh,ParticleSubEmitter:Ap,ParticleSystem:ct,ParticleSystemRenderer:os,PhysicsExtension:mp,PixelationEffect:Dh,PlayAnimationOnClick:Xr,PlayAudioOnClick:Bo,PlayableDirector:rr,PlayerColor:Vl,PointerEventData:Wl,PostProcessingHandler:zp,PreliminaryAction:wl,PreliminaryTrigger:hh,RawImage:Jp,Rect:f0,RectTransform:Ht,ReflectionProbe:ll,RegisteredAnimationInfo:io,RemoteSkybox:un,Renderer:et,RendererLightmap:sh,Rigidbody:ve,RotationBySpeedModule:Fi,RotationOverLifetimeModule:ns,SceneSwitcher:ot,ScreenCapture:sr,ScreenSpaceAmbientOcclusion:Gn,ScreenSpaceAmbientOcclusionN8:Is,SetActiveOnClick:Gr,ShadowCatcher:Nh,ShapeModule:Xe,SharpeningEffect:Fh,SignalAsset:qh,SignalReceiver:Al,SignalReceiverEvent:El,SignalTrackHandler:Yh,Size:g0,SizeBySpeedModule:ni,SizeOverLifetimeModule:Yo,SkinnedMeshRenderer:Yf,SmoothFollow:nr,SpatialGrabRaycaster:Qa,SpatialHtml:Kh,SpatialTrigger:$h,SpatialTriggerReceiver:pn,SpectatorCamera:$p,SphereCollider:tl,Sprite:rn,SpriteData:Vn,SpriteRenderer:fi,SpriteSheet:Wo,SubEmitterSystem:Eh,SyncedCamera:Gp,SyncedRoom:js,SyncedTransform:qs,TapGestureTrigger:d0,TeleportTarget:Sp,TestRunner:my,TestSimulateUserData:gy,Text:$t,TextBuilder:yp,TextExtension:fh,TextureSheetAnimationModule:Dt,TiltShiftEffect:dn,ToneMappingEffect:er,TrailModule:Ue,TransformData:He,TransformGizmo:aa,TriggerBuilder:wt,TriggerModel:Lo,UIRaycastUtils:Lu,UIRootComponent:Wc,USDZExporter:Ge,USDZText:Fo,USDZUIExtension:vp,UsageMarker:Jc,VariantAction:c0,VelocityOverLifetimeModule:Qe,VerticalLayoutGroup:b0,VideoPlayer:gt,Vignette:ra,VisibilityAction:dh,Voip:Ao,Volume:zh,VolumeParameter:N,VolumeProfile:Ah,WebARCameraBackground:ed,WebARSessionRoot:Hn,WebXR:tt,WebXRImageTracking:da,WebXRImageTrackingModel:fn,WebXRPlaneTracking:Jn,WebXRTrackedImage:Bl,XRControllerFollow:Zn,XRControllerModel:ln,XRControllerMovement:Di,XRFlag:Ai,XRRig:im,XRState:Kt,__Ignore:Py},Symbol.toStringTag,{value:"Module"}));class bj extends A{constructor(){super(...arguments),a(this,"toggleKey","KeyP")}update(){this.context.input.isKeyDown(this.toggleKey)&&this.context.domElement.classList.toggle("presentation-mode")}}S.add("AlignmentConstraint",Lc),S.add("Animation",Wt),S.add("Keyframe",Qt),S.add("AnimationCurve",Dr),S.add("Animator",kt),S.add("AnimatorController",Hi),S.add("AudioListener",To),S.add("AudioSource",We),S.add("Avatar_POI",Qs),S.add("Avatar_Brain_LookAt",$c),S.add("Avatar_MouthShapes",Xc),S.add("Avatar_MustacheShake",Of),S.add("AvatarBlink_Simple",zr),S.add("AvatarEyeLook_Rotation",Ja),S.add("AvatarModel",Wu),S.add("AvatarLoader",Mf),S.add("AxesHelper",el),S.add("BasicIKConstraint",Tf),S.add("BoxHelperComponent",is),S.add("Camera",Pe),S.add("CharacterController",Ur),S.add("CharacterControllerInput",Ln),S.add("__Ignore",Py),S.add("Collider",pi),S.add("SphereCollider",tl),S.add("BoxCollider",il),S.add("MeshCollider",Io),S.add("CapsuleCollider",In),S.add("ContactShadows",ks),S.add("LogStats",If),S.add("DeleteBox",eh),S.add("Deletable",Lf),S.add("DeviceFlag",Hu),S.add("DragControls",mi),S.add("DropListener",Dn),S.add("Duplicatable",Wr),S.add("CallInfo",Gs),S.add("EventListEvent",Eu),S.add("EventList",_e),S.add("EventTrigger",Gu),S.add("GltfExportBox",Kf),S.add("GltfExport",rh),S.add("RegisteredAnimationInfo",io),S.add("TransformData",He),S.add("AnimationExtension",lh),S.add("VariantAction",c0),S.add("ActionCollection",h0),S.add("AudioExtension",dr),S.add("BehaviorExtension",up),S.add("ChangeTransformOnClick",qr),S.add("ChangeMaterialOnClick",yl),S.add("SetActiveOnClick",Gr),S.add("HideOnStart",bl),S.add("EmphasizeOnClick",_l),S.add("PlayAudioOnClick",Bo),S.add("PlayAnimationOnClick",Xr),S.add("PreliminaryAction",wl),S.add("PreliminaryTrigger",hh),S.add("VisibilityAction",dh),S.add("TapGestureTrigger",d0),S.add("BehaviorModel",Tt),S.add("TriggerModel",Lo),S.add("TriggerBuilder",wt),S.add("GroupActionModel",Nn),S.add("ActionModel",Ii),S.add("ActionBuilder",fe),S.add("PhysicsExtension",mp),S.add("DocumentExtension",u0),S.add("USDZText",Fo),S.add("TextBuilder",yp),S.add("TextExtension",fh),S.add("USDZUIExtension",vp),S.add("CustomBranding",Go),S.add("USDZExporter",Ge),S.add("Fog",Pl),S.add("BoxGizmo",Zr),S.add("GridHelper",kl),S.add("GroundProjectedEnv",Hs),S.add("UsageMarker",Jc),S.add("Interactable",jf),S.add("FixedJoint",z0),S.add("HingeJoint",Sh),S.add("Light",yi),S.add("LODModel",Jr),S.add("LODGroup",Oh),S.add("LookAtConstraint",Br),S.add("NeedleMenu",an),S.add("NestedGltf",Pp),S.add("Networking",Ml),S.add("OffsetConstraint",ea),S.add("CameraTargetReachedEvent",Vc),S.add("OrbitControls",be),S.add("ParticleSystemRenderer",os),S.add("ParticleSystem",ct),S.add("SubEmitterSystem",Eh),S.add("Gradient",Qo),S.add("MinMaxCurve",Q),S.add("MinMaxGradient",si),S.add("MainModule",Lt),S.add("ParticleBurst",Mh),S.add("EmissionModule",hn),S.add("ColorOverLifetimeModule",Rh),S.add("SizeOverLifetimeModule",Yo),S.add("ShapeModule",Xe),S.add("NoiseModule",Ce),S.add("TrailModule",Ue),S.add("VelocityOverLifetimeModule",Qe),S.add("TextureSheetAnimationModule",Dt),S.add("RotationOverLifetimeModule",ns),S.add("RotationBySpeedModule",Fi),S.add("LimitVelocityOverLifetimeModule",lt),S.add("InheritVelocityModule",Ko),S.add("SizeBySpeedModule",ni),S.add("ColorBySpeedModule",ta),S.add("ParticleSubEmitter",Ap),S.add("PlayerColor",Vl),S.add("Antialiasing",Ih),S.add("BloomEffect",sa),S.add("ChromaticAberration",jh),S.add("ColorAdjustments",tr),S.add("DepthOfField",As),S.add("EffectWrapper",Lh),S.add("PixelationEffect",Dh),S.add("ScreenSpaceAmbientOcclusion",Gn),S.add("ScreenSpaceAmbientOcclusionN8",Is),S.add("SharpeningEffect",Fh),S.add("TiltShiftEffect",dn),S.add("ToneMappingEffect",er),S.add("Vignette",ra),S.add("PostProcessingHandler",zp),S.add("Volume",zh),S.add("VolumeParameter",N),S.add("VolumeProfile",Ah),S.add("ReflectionProbe",ll),S.add("FieldWithDefault",Qf),S.add("Renderer",et),S.add("MeshRenderer",oh),S.add("SkinnedMeshRenderer",Yf),S.add("InstancingHandler",Hr),S.add("InstanceHandle",ih),S.add("RendererLightmap",sh),S.add("Rigidbody",ve),S.add("SceneSwitcher",ot),S.add("ScreenCapture",sr),S.add("ShadowCatcher",Nh),S.add("RemoteSkybox",un),S.add("SmoothFollow",nr),S.add("SpatialTriggerReceiver",pn),S.add("SpatialTrigger",$h),S.add("SpectatorCamera",$p),S.add("Sprite",rn),S.add("SpriteSheet",Wo),S.add("SpriteData",Vn),S.add("SpriteRenderer",fi),S.add("SyncedCamera",Gp),S.add("SyncedRoom",js),S.add("SyncedTransform",qs),S.add("TestRunner",my),S.add("TestSimulateUserData",gy),S.add("PlayableDirector",rr),S.add("SignalAsset",qh),S.add("SignalReceiverEvent",El),S.add("SignalReceiver",Al),S.add("AnimationTrackHandler",Qp),S.add("AudioTrackHandler",Qh),S.add("SignalTrackHandler",Yh),S.add("ControlTrackHandler",Yp),S.add("TransformGizmo",aa),S.add("BaseUIComponent",ls),S.add("UIRootComponent",Wc),S.add("Button",Kn),S.add("Canvas",Et),S.add("CanvasGroup",No),S.add("EventSystem",ai),S.add("Graphic",Qr),S.add("MaskableGraphic",gh),S.add("Image",Il),S.add("RawImage",Jp),S.add("InputField",ca),S.add("Padding",zo),S.add("VerticalLayoutGroup",b0),S.add("HorizontalLayoutGroup",_0),S.add("GridLayoutGroup",w0),S.add("Outline",xl),S.add("PointerEventData",Wl),S.add("ObjectRaycaster",Ei),S.add("GraphicRaycaster",ju),S.add("SpatialGrabRaycaster",Qa),S.add("UIRaycastUtils",Lu),S.add("Size",g0),S.add("Rect",f0),S.add("RectTransform",Ht),S.add("SpatialHtml",Kh),S.add("Text",$t),S.add("LookAt",ha),S.add("OpenURL",Ll),S.add("VideoPlayer",gt),S.add("Voip",Ao),S.add("Avatar",Ho),S.add("XRControllerFollow",Zn),S.add("XRControllerModel",ln),S.add("XRControllerMovement",Di),S.add("TeleportTarget",Sp),S.add("WebARCameraBackground",ed),S.add("WebARSessionRoot",Hn),S.add("WebXR",tt),S.add("AvatarMarker",Rt),S.add("WebXRTrackedImage",Bl),S.add("WebXRImageTrackingModel",fn),S.add("WebXRImageTracking",da),S.add("WebXRPlaneTracking",Jn),S.add("XRRig",im),S.add("XRState",Kt),S.add("XRFlag",Ai),S.add("PlayerSync",Sl),S.add("PlayerState",Li),S.add("PresentationMode",bj);const id=vt,_j=O("debugtypestore");_j&&console.log(S);function wj(s,t){const i=v_(s,t);return i!==void 0?i:null}const xj=new T2,ky=Symbol("deserialize-queue");async function Sj(s,t,i,n=null,o){if(!i){console.debug("Can not create component instances: gltf is null");return}let r=n;typeof r=="number"&&(r=new zt(n));const l=t.indexOf("?");t=l===-1?t:t.substring(0,l);const c=new Wg(i.scene);c.gltfId=t,c.context=s,c.gltf=i,c.nodeToObject=o?.nodeToObjectMap,c.implementationInformation=xj;let h=s[ky];if(h||(h=s[ky]=[]),i.scenes)for(const d of i.scenes)await Ty(c,d,h);if(i.children)for(const d of i.children)await Ty(c,d,h);s.new_scripts_pre_setup_callbacks.push(()=>{const d=s[ky];if(d){for(const u of d)Cj(u,c);d.length=0}if(r){const u={},p=[];Ry(i,r,u,p);for(const g of i.scenes)Ry(g,r,u,p);for(const g of p)g.resolveGuids(u)}})}const My=Symbol("original-component-name"),zl=new Map;function Ry(s,t,i,n){if(t===null||!s)return;const o=s.guid,r=s.guid;r!=null&&r.length&&(zl.has(r)||(id&&console.log('Creating InstanceIdProvider with key "'+r+'" for object '+s.name),zl.set(r,new zt(r))));const l=r&&zl.get(r)||t;if(s.guid=l.generateUUID(),o&&o!=="invalid"&&(i[o]=s.guid),s&&s.userData&&s.userData.components)for(const c of s.userData.components){if(c===null)continue;const h=c.guid;h?zl.has(h)||(id&&console.log('Creating InstanceIdProvider with key "'+h+'" for component '+c[My]),zl.set(h,new zt(h))):id&&console.warn("Can not create IdProvider: component "+c[My]+" has no guid",c.guid);const d=zl.get(h)||t,u=c.guid;c.guid=d.generateUUID(),u&&u!=="invalid"&&(i[u]=c.guid),c.resolveGuids&&n.push(c)}if(s.children)for(const c of s.children)Ry(c,t,i,n)}const sd=[];async function Ty(s,t,i,n){var o,r,l,c,h;if(!t)return;const d=t.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=S.get(p.name);if(g!=null){const y=new g;y.sourceId=s.gltfId,Da(y,p,s.implementationInformation),y.context=s.context,"guid"in p&&(y[dc]=p.guid),y[My]=p.name,Or(t,y,!1),i.push({instance:y,compData:p,obj:t}),y.isCamera&&s.context&&s.context.mainCamera===null&&y.tag==="MainCamera"&&s.context.setCurrentCamera(y),((l=(r=(o=s.context)==null?void 0:o.physics)==null?void 0:r.engine)==null?void 0:l.isInitialized)===!1&&(y.isCollider||y.isRigidbody)&&((h=(c=s.context)==null?void 0:c.physics.engine)==null||h.initialize())}else id&&console.debug("unknown component: "+p.name),sd.includes(p.name)||sd.push(p.name)}catch(g){console.error(p.name+" - "+g.message,g)}if(sd.length>0){const p=sd.join(", ");console.warn("unknown components: "+p),sd.length=0,Gt()&&De(`<strong>Unknown components in scene</strong>:
1364
+ `+d.xrData.lastChangedTime.toFixed(2),.02))}}removeData(t,i){const n=i.get(t);if(!n)return;i.delete(t),ua&&console.log("Plane no longer tracked, id="+n.id),n.mesh&&(n.mesh.removeFromParent(),n.mesh.traverse(r=>{const l=r.userData.normalsHelper;l?(l.dispose(),l.removeFromParent()):ua&&console.warn("No normals helper found for mesh",n.mesh)}),Ri(n.mesh,!0,!0));const o=new CustomEvent("plane-tracking",{detail:{type:"plane-removed",context:n}});this.dispatchEvent(o)}processFrameData(t,i,n,o,r){const l=this.context.renderer.xr.getReferenceSpace();if(l){for(const c of r.keys())o.has(c)||this.removeData(c,r);for(const c of o){const h="planeSpace"in c?c.planeSpace:"meshSpace"in c?c.meshSpace:void 0;if(!h)continue;const d=n.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 y=this.createGeometry(c);if(p.mesh instanceof K)p.mesh.geometry.dispose(),p.mesh.geometry=y,this.makeOccluder(p.mesh,p.mesh.material);else if(p.mesh instanceof ro)for(const f of p.mesh.children)f instanceof K&&(f.geometry.dispose(),f.geometry=y,this.makeOccluder(f,f.material));if(p.collider){const f=p.mesh;p.collider.sharedMesh=f,p.collider.convex=this.checkIfContextShouldBeConvex(f,p.xrData),p.collider.onDisable(),p.collider.onEnable()}ua&&(console.log("Plane updated, id="+p.id,p),p.mesh.traverse(f=>{if(!(f instanceof K))return;const v=f.userData.normalsHelper;v&&v.update()}))}const g=new CustomEvent("plane-tracking",{detail:{type:"plane-updated",context:p}});this.dispatchEvent(g)}}else{if(!this.dataTemplate){const p=new K;ua?p.material=new CC:this.occluder?(p.material=new Re,this.makeOccluder(p,p.material,!0)):p.material=new Re({wireframe:!0,opacity:.5,transparent:!0,color:3355443}),this.dataTemplate=new ae("","",p)}if(!this.dataTemplate.asset)this.dataTemplate.loadAssetAsync();else{const p=P.instantiate(this.dataTemplate.asset);if(p.name="xr-tracked-plane",u=p,Qm(p,!1),p instanceof K)Ee(p.geometry),p.geometry=this.createGeometry(c),this.makeOccluder(p,p.material,this.occluder&&!this.dataTemplate);else if(p instanceof ro)for(const f of p.children)f instanceof K&&(Ee(f.geometry),f.geometry=this.createGeometry(c),this.makeOccluder(f,f.material,this.occluder&&!this.dataTemplate));const g=p.getComponent(Io);if(g){const f=p;g.sharedMesh=f,g.convex=this.checkIfContextShouldBeConvex(f,c),g.onDisable(),g.onEnable()}p.matrixAutoUpdate=!1,p.matrixWorldNeedsUpdate=!0,i.add(p);const y={id:this._dataId++,xrData:c,timestamp:c.lastChangedTime,mesh:p,collider:g};r.set(c,y),ua&&console.log("New plane detected, id="+y.id,y,{hasCollider:!!g,isGroup:p instanceof ro});try{const f=new CustomEvent("plane-tracking",{detail:{type:"plane-added",context:y}});this.dispatchEvent(f)}catch(f){console.error(f)}}}u&&(d?(u.visible=!0,u.matrix.fromArray(d.transform.matrix),u.matrix.premultiply(this._flipForwardMatrix)):u.visible=!1,ua&&u.traverse(p=>{if(p instanceof K)if(p.userData.normalsHelper)p.userData.normalsHelper.update();else{const g=new XC(p,.05,255);g.layers.disableAll(),g.layers.set(2),this.context.scene.add(g),p.userData.normalsHelper=g}}))}}}checkIfContextShouldBeConvex(t,i){if(!t)return!0;if(t){const n=new _i;n.expandByObject(t);const o=new x;n.getSize(o);let r=!0;return o.x>2&&o.y>2&&o.z>1.5&&(r=!1),r&&"semanticLabel"in i&&i.semanticLabel==="wall"&&(r=!0),r}return!0}createGeometry(t){return"polygon"in t?this.createPlaneGeometry(t.polygon):"vertices"in t&&"indices"in t?this.createMeshGeometry(t.vertices,t.indices):new bn}createMeshGeometry(t,i){const n=t.toString()+"_"+i.toString();if(this._verticesCache.has(n))return this._verticesCache.get(n);const o=new bn;o.setIndex(new ft(i,1)),o.setAttribute("position",new ft(t,3));const r=Array();for(let l=0;l<t.length;l+=3)r.push(t[l],t[l+2]);return o.setAttribute("uv",new ft(t,3)),o.computeVertexNormals(),this._verticesCache.set(n,o),o}createPlaneGeometry(t){const i=new bn,n=[],o=[];t.forEach(g=>{n.push(g.x,g.y,g.z),o.push(g.x,g.z)});const r=new x(n[0],n[1],n[2]),l=new x(n[3],n[4],n[5]),c=new x(n[6],n[7],n[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<n.length/3;g++)u.push(h.x,h.y,h.z);const p=[];for(let g=2;g<t.length;++g)p.push(0,g-1,g);return i.setAttribute("position",new ft(new Float32Array(n),3)),i.setAttribute("uv",new ft(new Float32Array(o),2)),i.setAttribute("normal",new ft(new Float32Array(u),3)),i.setIndex(p),i.computeBoundingBox(),i.computeBoundingSphere(),i}}Fl([m(ae)],Jn.prototype,"dataTemplate",2),Fl([m()],Jn.prototype,"occluder",2),Fl([m()],Jn.prototype,"initiateRoomCaptureIfNoData",2),Fl([m()],Jn.prototype,"usePlaneData",2),Fl([m()],Jn.prototype,"useMeshData",2),Fl([m()],Jn.prototype,"runInVR",2);var gj=Object.defineProperty,fj=Object.getOwnPropertyDescriptor,yj=(s,t,i,n)=>{for(var o=n>1?void 0:n?fj(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&gj(t,i,o),o};const U1=O("debugwebxr");class im extends A{constructor(){super(...arguments),a(this,"priority",0),a(this,"_startScale")}get isActive(){return this.activeAndEnabled&&this.gameObject.visible}setAsActiveXRRig(){var t;(t=J.active)==null||t.setRigActive(this)}setPriority(t){this.priority=t}awake(){if(U1){const t=new I;t.position.y+=.5,this.gameObject.add(t);const i=t.addNewComponent(Zr);i&&(i.isGizmo=!1);const n=new wi(.5);this.gameObject.add(n)}}isXRRig(){return!0}supportsXR(t){return!0}onEnterXR(t){this._startScale=this.gameObject.scale.clone(),t.xr.addRig(this),U1&&console.log("WebXR: add Rig",this.name,this.priority)}onLeaveXR(t){t.xr.removeRig(this),this._startScale&&this.gameObject&&this.gameObject.scale.copy(this._startScale)}}yj([m()],im.prototype,"priority",2);class Py{}const vj=Object.freeze(Object.defineProperty({__proto__:null,ActionBuilder:fe,ActionCollection:h0,ActionModel:Ii,AlignmentConstraint:Lc,Animation:Wt,AnimationCurve:Dr,AnimationExtension:lh,AnimationTrackHandler:Qp,Animator:kt,AnimatorController:Hi,Antialiasing:Ih,AudioExtension:dr,AudioListener:To,AudioSource:We,AudioTrackHandler:Qh,Avatar:Ho,AvatarBlink_Simple:zr,AvatarEyeLook_Rotation:Ja,AvatarLoader:Mf,AvatarMarker:Rt,AvatarModel:Wu,Avatar_Brain_LookAt:$c,Avatar_MouthShapes:Xc,Avatar_MustacheShake:Of,Avatar_POI:Qs,AxesHelper:el,BaseUIComponent:ls,BasicIKConstraint:Tf,BehaviorExtension:up,BehaviorModel:Tt,BloomEffect:sa,BoxCollider:il,BoxGizmo:Zr,BoxHelperComponent:is,Button:Kn,CallInfo:Gs,Camera:Pe,CameraTargetReachedEvent:Vc,Canvas:Et,CanvasGroup:No,CapsuleCollider:In,ChangeMaterialOnClick:yl,ChangeTransformOnClick:qr,CharacterController:Ur,CharacterControllerInput:Ln,ChromaticAberration:jh,Collider:pi,ColorAdjustments:tr,ColorBySpeedModule:ta,ColorOverLifetimeModule:Rh,ContactShadows:ks,ControlTrackHandler:Yp,CustomBranding:Go,Deletable:Lf,DeleteBox:eh,DepthOfField:As,DeviceFlag:Hu,DocumentExtension:u0,DragControls:mi,DropListener:Dn,Duplicatable:Wr,EffectWrapper:Lh,EmissionModule:hn,EmphasizeOnClick:_l,EventList:_e,EventListEvent:Eu,EventSystem:ai,EventTrigger:Gu,FieldWithDefault:Qf,FixedJoint:z0,Fog:Pl,GltfExport:rh,GltfExportBox:Kf,Gradient:Qo,Graphic:Qr,GraphicRaycaster:ju,GridHelper:kl,GridLayoutGroup:w0,GroundProjectedEnv:Hs,GroupActionModel:Nn,HideOnStart:bl,HingeJoint:Sh,HorizontalLayoutGroup:_0,Image:Il,InheritVelocityModule:Ko,InputField:ca,InstanceHandle:ih,InstancingHandler:Hr,Interactable:jf,Keyframe:Qt,LODGroup:Oh,LODModel:Jr,Light:yi,LimitVelocityOverLifetimeModule:lt,LogStats:If,LookAt:ha,LookAtConstraint:Br,MainModule:Lt,MaskableGraphic:gh,MeshCollider:Io,MeshRenderer:oh,MinMaxCurve:Q,MinMaxGradient:si,NeedleMenu:an,NestedGltf:Pp,Networking:Ml,NoiseModule:Ce,ObjectRaycaster:Ei,OffsetConstraint:ea,OpenURL:Ll,OrbitControls:be,Outline:xl,Padding:zo,ParticleBurst:Mh,ParticleSubEmitter:Ap,ParticleSystem:ct,ParticleSystemRenderer:os,PhysicsExtension:mp,PixelationEffect:Dh,PlayAnimationOnClick:Xr,PlayAudioOnClick:Bo,PlayableDirector:rr,PlayerColor:Vl,PointerEventData:Wl,PostProcessingHandler:zp,PreliminaryAction:wl,PreliminaryTrigger:hh,RawImage:Jp,Rect:f0,RectTransform:Ht,ReflectionProbe:ll,RegisteredAnimationInfo:io,RemoteSkybox:un,Renderer:et,RendererLightmap:sh,Rigidbody:ve,RotationBySpeedModule:Fi,RotationOverLifetimeModule:ns,SceneSwitcher:ot,ScreenCapture:sr,ScreenSpaceAmbientOcclusion:Gn,ScreenSpaceAmbientOcclusionN8:Is,SetActiveOnClick:Gr,ShadowCatcher:Nh,ShapeModule:Xe,SharpeningEffect:Fh,SignalAsset:qh,SignalReceiver:Al,SignalReceiverEvent:El,SignalTrackHandler:Yh,Size:g0,SizeBySpeedModule:ni,SizeOverLifetimeModule:Yo,SkinnedMeshRenderer:Yf,SmoothFollow:nr,SpatialGrabRaycaster:Qa,SpatialHtml:Kh,SpatialTrigger:$h,SpatialTriggerReceiver:pn,SpectatorCamera:$p,SphereCollider:tl,Sprite:rn,SpriteData:Vn,SpriteRenderer:fi,SpriteSheet:Wo,SubEmitterSystem:Eh,SyncedCamera:Gp,SyncedRoom:js,SyncedTransform:qs,TapGestureTrigger:d0,TeleportTarget:Sp,TestRunner:my,TestSimulateUserData:gy,Text:$t,TextBuilder:yp,TextExtension:fh,TextureSheetAnimationModule:Dt,TiltShiftEffect:dn,ToneMappingEffect:er,TrailModule:Ue,TransformData:He,TransformGizmo:aa,TriggerBuilder:wt,TriggerModel:Lo,UIRaycastUtils:Lu,UIRootComponent:Wc,USDZExporter:Ge,USDZText:Fo,USDZUIExtension:vp,UsageMarker:Jc,VariantAction:c0,VelocityOverLifetimeModule:Qe,VerticalLayoutGroup:b0,VideoPlayer:gt,Vignette:ra,VisibilityAction:dh,Voip:Ao,Volume:zh,VolumeParameter:N,VolumeProfile:Ah,WebARCameraBackground:ed,WebARSessionRoot:Hn,WebXR:tt,WebXRImageTracking:da,WebXRImageTrackingModel:fn,WebXRPlaneTracking:Jn,WebXRTrackedImage:Bl,XRControllerFollow:Zn,XRControllerModel:ln,XRControllerMovement:Di,XRFlag:Ai,XRRig:im,XRState:Kt,__Ignore:Py},Symbol.toStringTag,{value:"Module"}));class bj extends A{constructor(){super(...arguments),a(this,"toggleKey","KeyP")}update(){this.context.input.isKeyDown(this.toggleKey)&&this.context.domElement.classList.toggle("presentation-mode")}}S.add("AlignmentConstraint",Lc),S.add("Animation",Wt),S.add("Keyframe",Qt),S.add("AnimationCurve",Dr),S.add("Animator",kt),S.add("AnimatorController",Hi),S.add("AudioListener",To),S.add("AudioSource",We),S.add("Avatar_POI",Qs),S.add("Avatar_Brain_LookAt",$c),S.add("Avatar_MouthShapes",Xc),S.add("Avatar_MustacheShake",Of),S.add("AvatarBlink_Simple",zr),S.add("AvatarEyeLook_Rotation",Ja),S.add("AvatarModel",Wu),S.add("AvatarLoader",Mf),S.add("AxesHelper",el),S.add("BasicIKConstraint",Tf),S.add("BoxHelperComponent",is),S.add("Camera",Pe),S.add("CharacterController",Ur),S.add("CharacterControllerInput",Ln),S.add("__Ignore",Py),S.add("Collider",pi),S.add("SphereCollider",tl),S.add("BoxCollider",il),S.add("MeshCollider",Io),S.add("CapsuleCollider",In),S.add("ContactShadows",ks),S.add("LogStats",If),S.add("DeleteBox",eh),S.add("Deletable",Lf),S.add("DeviceFlag",Hu),S.add("DragControls",mi),S.add("DropListener",Dn),S.add("Duplicatable",Wr),S.add("CallInfo",Gs),S.add("EventListEvent",Eu),S.add("EventList",_e),S.add("EventTrigger",Gu),S.add("GltfExportBox",Kf),S.add("GltfExport",rh),S.add("RegisteredAnimationInfo",io),S.add("TransformData",He),S.add("AnimationExtension",lh),S.add("VariantAction",c0),S.add("ActionCollection",h0),S.add("AudioExtension",dr),S.add("BehaviorExtension",up),S.add("ChangeTransformOnClick",qr),S.add("ChangeMaterialOnClick",yl),S.add("SetActiveOnClick",Gr),S.add("HideOnStart",bl),S.add("EmphasizeOnClick",_l),S.add("PlayAudioOnClick",Bo),S.add("PlayAnimationOnClick",Xr),S.add("PreliminaryAction",wl),S.add("PreliminaryTrigger",hh),S.add("VisibilityAction",dh),S.add("TapGestureTrigger",d0),S.add("BehaviorModel",Tt),S.add("TriggerModel",Lo),S.add("TriggerBuilder",wt),S.add("GroupActionModel",Nn),S.add("ActionModel",Ii),S.add("ActionBuilder",fe),S.add("PhysicsExtension",mp),S.add("DocumentExtension",u0),S.add("USDZText",Fo),S.add("TextBuilder",yp),S.add("TextExtension",fh),S.add("USDZUIExtension",vp),S.add("CustomBranding",Go),S.add("USDZExporter",Ge),S.add("Fog",Pl),S.add("BoxGizmo",Zr),S.add("GridHelper",kl),S.add("GroundProjectedEnv",Hs),S.add("UsageMarker",Jc),S.add("Interactable",jf),S.add("FixedJoint",z0),S.add("HingeJoint",Sh),S.add("Light",yi),S.add("LODModel",Jr),S.add("LODGroup",Oh),S.add("LookAtConstraint",Br),S.add("NeedleMenu",an),S.add("NestedGltf",Pp),S.add("Networking",Ml),S.add("OffsetConstraint",ea),S.add("CameraTargetReachedEvent",Vc),S.add("OrbitControls",be),S.add("ParticleSystemRenderer",os),S.add("ParticleSystem",ct),S.add("SubEmitterSystem",Eh),S.add("Gradient",Qo),S.add("MinMaxCurve",Q),S.add("MinMaxGradient",si),S.add("MainModule",Lt),S.add("ParticleBurst",Mh),S.add("EmissionModule",hn),S.add("ColorOverLifetimeModule",Rh),S.add("SizeOverLifetimeModule",Yo),S.add("ShapeModule",Xe),S.add("NoiseModule",Ce),S.add("TrailModule",Ue),S.add("VelocityOverLifetimeModule",Qe),S.add("TextureSheetAnimationModule",Dt),S.add("RotationOverLifetimeModule",ns),S.add("RotationBySpeedModule",Fi),S.add("LimitVelocityOverLifetimeModule",lt),S.add("InheritVelocityModule",Ko),S.add("SizeBySpeedModule",ni),S.add("ColorBySpeedModule",ta),S.add("ParticleSubEmitter",Ap),S.add("PlayerColor",Vl),S.add("Antialiasing",Ih),S.add("BloomEffect",sa),S.add("ChromaticAberration",jh),S.add("ColorAdjustments",tr),S.add("DepthOfField",As),S.add("EffectWrapper",Lh),S.add("PixelationEffect",Dh),S.add("ScreenSpaceAmbientOcclusion",Gn),S.add("ScreenSpaceAmbientOcclusionN8",Is),S.add("SharpeningEffect",Fh),S.add("TiltShiftEffect",dn),S.add("ToneMappingEffect",er),S.add("Vignette",ra),S.add("PostProcessingHandler",zp),S.add("Volume",zh),S.add("VolumeParameter",N),S.add("VolumeProfile",Ah),S.add("ReflectionProbe",ll),S.add("FieldWithDefault",Qf),S.add("Renderer",et),S.add("MeshRenderer",oh),S.add("SkinnedMeshRenderer",Yf),S.add("InstancingHandler",Hr),S.add("InstanceHandle",ih),S.add("RendererLightmap",sh),S.add("Rigidbody",ve),S.add("SceneSwitcher",ot),S.add("ScreenCapture",sr),S.add("ShadowCatcher",Nh),S.add("RemoteSkybox",un),S.add("SmoothFollow",nr),S.add("SpatialTriggerReceiver",pn),S.add("SpatialTrigger",$h),S.add("SpectatorCamera",$p),S.add("Sprite",rn),S.add("SpriteSheet",Wo),S.add("SpriteData",Vn),S.add("SpriteRenderer",fi),S.add("SyncedCamera",Gp),S.add("SyncedRoom",js),S.add("SyncedTransform",qs),S.add("TestRunner",my),S.add("TestSimulateUserData",gy),S.add("PlayableDirector",rr),S.add("SignalAsset",qh),S.add("SignalReceiverEvent",El),S.add("SignalReceiver",Al),S.add("AnimationTrackHandler",Qp),S.add("AudioTrackHandler",Qh),S.add("SignalTrackHandler",Yh),S.add("ControlTrackHandler",Yp),S.add("TransformGizmo",aa),S.add("BaseUIComponent",ls),S.add("UIRootComponent",Wc),S.add("Button",Kn),S.add("Canvas",Et),S.add("CanvasGroup",No),S.add("EventSystem",ai),S.add("Graphic",Qr),S.add("MaskableGraphic",gh),S.add("Image",Il),S.add("RawImage",Jp),S.add("InputField",ca),S.add("Padding",zo),S.add("VerticalLayoutGroup",b0),S.add("HorizontalLayoutGroup",_0),S.add("GridLayoutGroup",w0),S.add("Outline",xl),S.add("PointerEventData",Wl),S.add("ObjectRaycaster",Ei),S.add("GraphicRaycaster",ju),S.add("SpatialGrabRaycaster",Qa),S.add("UIRaycastUtils",Lu),S.add("Size",g0),S.add("Rect",f0),S.add("RectTransform",Ht),S.add("SpatialHtml",Kh),S.add("Text",$t),S.add("LookAt",ha),S.add("OpenURL",Ll),S.add("VideoPlayer",gt),S.add("Voip",Ao),S.add("Avatar",Ho),S.add("XRControllerFollow",Zn),S.add("XRControllerModel",ln),S.add("XRControllerMovement",Di),S.add("TeleportTarget",Sp),S.add("WebARCameraBackground",ed),S.add("WebARSessionRoot",Hn),S.add("WebXR",tt),S.add("AvatarMarker",Rt),S.add("WebXRTrackedImage",Bl),S.add("WebXRImageTrackingModel",fn),S.add("WebXRImageTracking",da),S.add("WebXRPlaneTracking",Jn),S.add("XRRig",im),S.add("XRState",Kt),S.add("XRFlag",Ai),S.add("PlayerSync",Sl),S.add("PlayerState",Li),S.add("PresentationMode",bj);const id=vt,_j=O("debugtypestore");_j&&console.log(S);function wj(s,t){const i=v_(s,t);return i!==void 0?i:null}const xj=new Tk,ky=Symbol("deserialize-queue");async function Sj(s,t,i,n=null,o){if(!i){console.debug("Can not create component instances: gltf is null");return}let r=n;typeof r=="number"&&(r=new zt(n));const l=t.indexOf("?");t=l===-1?t:t.substring(0,l);const c=new Wg(i.scene);c.gltfId=t,c.context=s,c.gltf=i,c.nodeToObject=o?.nodeToObjectMap,c.implementationInformation=xj;let h=s[ky];if(h||(h=s[ky]=[]),i.scenes)for(const d of i.scenes)await Ty(c,d,h);if(i.children)for(const d of i.children)await Ty(c,d,h);s.new_scripts_pre_setup_callbacks.push(()=>{const d=s[ky];if(d){for(const u of d)Cj(u,c);d.length=0}if(r){const u={},p=[];Ry(i,r,u,p);for(const g of i.scenes)Ry(g,r,u,p);for(const g of p)g.resolveGuids(u)}})}const My=Symbol("original-component-name"),zl=new Map;function Ry(s,t,i,n){if(t===null||!s)return;const o=s.guid,r=s.guid;r!=null&&r.length&&(zl.has(r)||(id&&console.log('Creating InstanceIdProvider with key "'+r+'" for object '+s.name),zl.set(r,new zt(r))));const l=r&&zl.get(r)||t;if(s.guid=l.generateUUID(),o&&o!=="invalid"&&(i[o]=s.guid),s&&s.userData&&s.userData.components)for(const c of s.userData.components){if(c===null)continue;const h=c.guid;h?zl.has(h)||(id&&console.log('Creating InstanceIdProvider with key "'+h+'" for component '+c[My]),zl.set(h,new zt(h))):id&&console.warn("Can not create IdProvider: component "+c[My]+" has no guid",c.guid);const d=zl.get(h)||t,u=c.guid;c.guid=d.generateUUID(),u&&u!=="invalid"&&(i[u]=c.guid),c.resolveGuids&&n.push(c)}if(s.children)for(const c of s.children)Ry(c,t,i,n)}const sd=[];async function Ty(s,t,i,n){var o,r,l,c,h;if(!t)return;const d=t.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=S.get(p.name);if(g!=null){const y=new g;y.sourceId=s.gltfId,Da(y,p,s.implementationInformation),y.context=s.context,"guid"in p&&(y[dc]=p.guid),y[My]=p.name,Or(t,y,!1),i.push({instance:y,compData:p,obj:t}),y.isCamera&&s.context&&s.context.mainCamera===null&&y.tag==="MainCamera"&&s.context.setCurrentCamera(y),((l=(r=(o=s.context)==null?void 0:o.physics)==null?void 0:r.engine)==null?void 0:l.isInitialized)===!1&&(y.isCollider||y.isRigidbody)&&((h=(c=s.context)==null?void 0:c.physics.engine)==null||h.initialize())}else id&&console.debug("unknown component: "+p.name),sd.includes(p.name)||sd.push(p.name)}catch(g){console.error(p.name+" - "+g.message,g)}if(sd.length>0){const p=sd.join(", ");console.warn("unknown components: "+p),sd.length=0,Gt()&&De(`<strong>Unknown components in scene</strong>:
1365
1365
 
1366
1366
  ${p}
1367
1367
 
@@ -1370,8 +1370,8 @@ This could mean you forgot to add a npmdef to your ExportInfo
1370
1370
  `,'"'+new TextDecoder().decode(s)+`"
1371
1371
  `,i),i[0]==103&&i[1]==108&&i[2]==84&&i[3]==70)return console.debug("GLTF detected"),"glb";if(i[0]==80&&i[1]==75&&i[2]==3&&i[3]==4)return console.debug("USDZ detected"),"usdz";if(i[0]==80&&i[1]==88&&i[2]==82&&i[3]==45&&i[4]==85&&i[5]==83&&i[6]==68&&i[7]==67)return console.debug("Binary USD detected"),"usd";if(i[0]==35&&i[1]==117&&i[2]==115&&i[3]==100&&i[4]==97)return console.debug("ASCII USD detected"),"usda";if(i[0]==75&&i[1]==97&&i[2]==121&&i[3]==100&&i[4]==97&&i[5]==114&&i[6]==97&&i[7]==32)return console.debug("Binary FBX detected"),"fbx";if(i[0]==59&&i[1]==32&&i[2]==70&&i[3]==66&&i[4]==88&&i[5]==32)return console.debug("ASCII FBX detected"),"fbx";if(i[0]==35&&i[1]==32&&i[2]==66&&i[3]==108&&i[4]==101&&i[5]==110&&i[6]==100&&i[7]==101&&i[8]==114&&i[9]==32||i[0]==35&&i[1]==32&&i[2]==65&&i[3]==108&&i[4]==105&&i[5]==97&&i[6]==115&&i[7]==32&&i[8]==79&&i[9]==66&&i[10]==74)return console.debug("OBJ detected"),"obj";if(t.headers.has("content-type")){const n=t.headers.get("content-type");switch(console.debug("Content-Type: "+n),n){case"model/gltf+json":return"gltf";case"model/gltf-binary":return"glb";case"model/vrm":return"vrm";case"model/vnd.usdz+zip":return"usdz";case"model/vnd.usd+zip":return"usd";case"model/vnd.usda+zip":return"usda";case"model/fbx":return"fbx";case"model/obj":return"obj"}}if(i[0]==118&&i[1]==32||i[0]==102&&i[1]==32)return console.debug("OBJ detected (the file has no header and starts with vertex or face)"),"obj";if(i[0]==35&&i[1]==32&&i[2]==70&&i[3]==105&&i[4]==108&&i[5]==101&&i[6]==32&&i[7]==101&&i[8]==120&&i[9]==112&&i[10]==111&&i[11]==114&&i[12]==116&&i[13]==101&&i[14]==100&&i[15]==32&&i[16]==98&&i[17]==121&&i[18]==32&&i[19]==90&&i[20]==66&&i[21]==114&&i[22]==117&&i[23]==115&&i[24]==104)return console.debug("OBJ detected (exported by ZBrush)"),"obj";if(i[0]==109&&i[1]==116&&i[2]==108&&i[3]==108&&i[4]==105&&i[5]==98)return console.debug("OBJ detected (mtllib)"),"obj";if(F()||sm){const n=new TextDecoder().decode(s.slice(0,16));console.debug('Could not determine file type from binary data: "'+n+'..."',i)}else console.debug("Could not determine file type from binary data",i);return"unknown"}class Ey{createBuiltinComponents(t,i,n,o,r){return Sj(t,i,n,o,r)}writeBuiltinComponentData(t,i){return wj(t,i)}parseSync(t,i,n,o){return G1(t,i,n,o)}loadSync(t,i,n,o,r){return X1(t,i,n,o,r)}}km(Ey);const V1=O("printGltf")||O("printgltf"),H1=O("downloadgltf"),Oj=O("debugfileformat");var $1=(s=>(s[s.BeforeLoad=0]="BeforeLoad",s[s.AfterLoaded=1]="AfterLoaded",s[s.FinishedSetup=10]="FinishedSetup",s))($1||{});class pa{constructor(t,i,n,o){a(this,"context"),a(this,"loader"),a(this,"path"),a(this,"gltf"),this.context=t,this.path=i,this.loader=n,this.gltf=o}}const hr={};function Pj(s,t){hr[s]=hr[s]||[],hr[s].push(t)}function kj(s,t){if(hr[s]){const i=hr[s].indexOf(t);i>=0&&hr[s].splice(i,1)}}function Ul(s,t){if(hr[s])for(const i of hr[s])i(t)}async function q1(s,t,i,n,o){V1&&console.warn("glTF",t,i),t.includes("?")&&(t=t.split("?")[0]),await fs().createBuiltinComponents(s,t,i,n,o)}async function Ay(s,t){const i=await N1(s)||"unknown";switch(Oj&&console.debug("Determined file type: "+i+" for url",s),i){case"unknown":{console.warn("Unknown file type. Assuming glTF:",s);const n=new gr;return await Zu(n,t,s),n}case"fbx":return new hv;case"obj":return new Sm;case"usd":case"usda":case"usdz":return console.warn(i.toUpperCase()+" files are not supported."),null;default:console.warn("Unknown file type:",i);case"gltf":case"glb":case"vrm":{const n=new gr;return await Zu(n,t,s),n}}}async function G1(s,t,i,n){typeof i!="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",i,typeof i),i=""),V1&&console.log("Parse glTF",i);const o=await Ay(i,s);if(!o)return;if(o instanceof Sm){typeof t!="string"&&(t=new TextDecoder().decode(t));const l=o.parse(t);return{animations:l.animations,scene:l,scenes:[l]}}if(!(o instanceof gr)){const l=o.parse(t,i);return K1(o,l),{animations:l.animations,scene:l,scenes:[l]}}const r=Ku(o);return new Promise((l,c)=>{try{let h=i.split("?")[0].trimEnd();{const u=h.split("/");u.length>0&&u[u.length-1]!==""&&u.pop(),h=u.join("/"),h.endsWith("/")||(h+="/")}o.resourcePath=h,Su(o,s),Ul(0,new pa(s,i,o));const d=s.mainCamera;o.parse(t,"",async u=>{Gf(i,u,s),Ul(1,new pa(s,i,o,u)),await q1(s,i,u,n,r),await Q1(u.scene,s,d),Ul(10,new pa(s,i,o,u)),l(u),H1&&Y1(t)},u=>{console.error('Loading asset at "'+i+`" failed
1372
1372
  `,u),l(void 0)})}catch(h){console.error(h),c(h)}})}async function X1(s,t,i,n,o){Mj(t);const r=await Ay(t,s);if(!r)return;if(!(r instanceof gr)){const c=await r.loadAsync(t,o);return K1(r,c),{animations:c.animations,scene:c,scenes:[c]}}const l=Ku(r);return new Promise((c,h)=>{try{Su(r,s),Ul(0,new pa(s,t,r));const d=s.mainCamera;r.load(t,async u=>{Gf(t,u,s),Ul(1,new pa(s,t,r,u)),await q1(s,i,u,n,l),await Q1(u.scene,s,d),Ul(10,new pa(s,t,r,u)),c(u),H1&&Y1(t)},u=>{o?.call(r,u)},u=>{console.error('Loading asset at "'+t+`" failed
1373
- `,u),c(void 0)})}catch(d){console.error(d),h(d)}})}async function Q1(s,t,i){i||(i=t.mainCamera);try{i?await t.renderer.compileAsync(s,i,t.scene).catch(n=>{console.warn(n.message)}):g2(s,t)}catch(n){console.warn(n?.message||n)}}function Mj(s){if(new URL(s,window.location.href).href.startsWith("file://")){const t=`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.
1374
- 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>`;De(t),console.warn(t)}}function Y1(s){if(typeof s=="string"){const t=document.createElement("a");t.href=s,t.download=s.split("/").pop(),t.click()}else{const t=new Blob([s],{type:"application/octet-stream"}),i=window.URL.createObjectURL(t),n=document.createElement("a");n.href=i,n.download="download.glb",n.click()}}function K1(s,t){if(t!=null&&t.isObject3D){const i=t;(s instanceof hv||s instanceof Sm)&&i.traverse(n=>{const o=n;o!=null&&o.isMesh&&Ym(o,o.material)})}}km(Ey);const Ne=O("debugwebcomponent"),Z1="needle-engine",J1="vr",eS="desktop",Rj=[mw,J1,eS],nd="ar-session-active",od="desktop-session-active",Tj=["public-key","version","hash","src","camera-controls","loadstart","progress","loadfinished","dracoDecoderPath","dracoDecoderType","ktx2DecoderPath","tone-mapping","tone-mapping-exposure","background-blurriness","background-color"];class Iy 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 i;const n=this.context.xrSessionMode;n==="immersive-ar"?this.onEnterAR(this.context.xrSession):n==="immersive-vr"&&this.onEnterVR(this.context.xrSession),(i=this.context.xrSession)==null||i.addEventListener("end",()=>{this.dispatchEvent(new CustomEvent("xr-session-ended",{detail:{session:this.context.xrSession,context:this._context,sessionMode:n}})),n==="immersive-ar"?this.onExitAR(this.context.xrSession):n==="immersive-vr"&&this.onExitVR(this.context.xrSession)})}),a(this,"onReady",()=>{var i;return(i=this._loadingView)==null?void 0:i.onLoadingFinished()}),a(this,"onError",()=>{var i;return(i=this._loadingView)==null?void 0:i.setMessage("Loading failed!")}),a(this,"_previouslyRegisteredMap",new Map),this._overlay_ar=new Ck,this.addEventListener("ready",this.onReady),nw(),this.attachShadow({mode:"open"});const t=document.createElement("template");t.innerHTML=`<style>
1373
+ `,u),c(void 0)})}catch(d){console.error(d),h(d)}})}async function Q1(s,t,i){i||(i=t.mainCamera);try{i?await t.renderer.compileAsync(s,i,t.scene).catch(n=>{console.warn(n.message)}):gk(s,t)}catch(n){console.warn(n?.message||n)}}function Mj(s){if(new URL(s,window.location.href).href.startsWith("file://")){const t=`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.
1374
+ 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>`;De(t),console.warn(t)}}function Y1(s){if(typeof s=="string"){const t=document.createElement("a");t.href=s,t.download=s.split("/").pop(),t.click()}else{const t=new Blob([s],{type:"application/octet-stream"}),i=window.URL.createObjectURL(t),n=document.createElement("a");n.href=i,n.download="download.glb",n.click()}}function K1(s,t){if(t!=null&&t.isObject3D){const i=t;(s instanceof hv||s instanceof Sm)&&i.traverse(n=>{const o=n;o!=null&&o.isMesh&&Ym(o,o.material)})}}km(Ey);const Ne=O("debugwebcomponent"),Z1="needle-engine",J1="vr",eS="desktop",Rj=[mw,J1,eS],nd="ar-session-active",od="desktop-session-active",Tj=["public-key","version","hash","src","camera-controls","loadstart","progress","loadfinished","dracoDecoderPath","dracoDecoderType","ktx2DecoderPath","tone-mapping","tone-mapping-exposure","background-blurriness","background-color"];class Iy 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 i;const n=this.context.xrSessionMode;n==="immersive-ar"?this.onEnterAR(this.context.xrSession):n==="immersive-vr"&&this.onEnterVR(this.context.xrSession),(i=this.context.xrSession)==null||i.addEventListener("end",()=>{this.dispatchEvent(new CustomEvent("xr-session-ended",{detail:{session:this.context.xrSession,context:this._context,sessionMode:n}})),n==="immersive-ar"?this.onExitAR(this.context.xrSession):n==="immersive-vr"&&this.onExitVR(this.context.xrSession)})}),a(this,"onReady",()=>{var i;return(i=this._loadingView)==null?void 0:i.onLoadingFinished()}),a(this,"onError",()=>{var i;return(i=this._loadingView)==null?void 0:i.setMessage("Loading failed!")}),a(this,"_previouslyRegisteredMap",new Map),this._overlay_ar=new C2,this.addEventListener("ready",this.onReady),nw(),this.attachShadow({mode:"open"});const t=document.createElement("template");t.innerHTML=`<style>
1375
1375
  @import url('https://fonts.googleapis.com/css2?family=Roboto+Flex:opsz,wght@8..144,100..1000&display=swap');
1376
1376
 
1377
1377
  :host {
@@ -1486,4 +1486,4 @@ Error:`,l),null}}updateColliderCollisionGroups(s){const t=s[ri],i=s.membership;l
1486
1486
  justify-content: center;
1487
1487
  gap: .5rem;
1488
1488
  }
1489
- `),pe(this,ga).innerHTML=pe(this,bi).innerHTML,pe(this,ga).style.cssText="display: flex; align-items: center; justify-content: center;",pe(this,bi).innerHTML=pe(this,ga).outerHTML,pe(this,ma).innerHTML=pe(this,bi).outerHTML,pe(this,ma).prepend(pe(this,fa)),yu(sf,{element:pe(this,ma)}),(t=pe(this,Nl))==null||t.disconnect(),pe(this,Nl)??Bs(this,Nl,new MutationObserver(()=>va(this,Uy,aS).call(this))),pe(this,Nl).observe(pe(this,bi),{attributes:!0}),Fy&&console.log("Needle Button updated")},Uy=new WeakSet,aS=function(){pe(this,bi)&&(pe(this,bi).style.display==="none"?this.style.display="none":this.style.display==="none"&&(this.style.display=""))},rm=new WeakMap,a(Ny,"observedAttributes",["ar","vr","quicklook"]),typeof window<"u"&&!window.customElements.get(oS)&&window.customElements.define(oS,Ny);const am=O("debugmissingcamera");ge.registerCallback(ye.MissingCamera,s=>{var t,i,n;am&&console.warn("Creating missing camera");const o=s.context.scene,r=new we;r.name="Default Fallback Camera",o.add(r);const l=new Pe;l.sourceId=((i=(t=s.files)==null?void 0:t[0])==null?void 0:i.src)??"unknown",(n=s.context.domElement.getAttribute("skybox-image"))!=null&&n.length||0>0||s.context.lightmaps.tryGetSkybox(l.sourceId)?l.clearFlags=Mo.Skybox:l.clearFlags=Mo.SolidColor,l.backgroundColor=new Se(.5,.5,.5,1),l.fieldOfView=35,s.context.domElement.getAttribute("transparent")!=null&&(l.clearFlags=Mo.Uninitialized),l.backgroundBlurriness=.2;const c=Or(r,l,!0);r.position.x=0,r.position.y=1,r.position.z=2;const h=s.context.domElement;return h?.cameraControls!=!1&&lS(s.context,c),c}),ge.registerCallback(ye.ContextCreated,s=>{if(!s.context.mainCamera){am&&console.log("Will not auto-fit because a default camera exists");return}const t=s.context.domElement;if(t?.cameraControls==!0){const i=Nv(s.context.mainCamera);if(i?.isCameraController==!0){am&&console.log("Will not auto-fit because a camera controller exists");return}lS(s.context)}});function lS(s,t){t=t??s.mainCameraComponent;const i=t?.gameObject;if(am&&console.log("Creating default camera controls",t?.name),i){const n=Cc(i,be);n.sourceId=t?.sourceId??"unknown";const o=s.domElement.getAttribute("auto-rotate");if(n.autoRotate=o!=null&&o!="0"&&o?.toLowerCase()!="false",n.autoRotateSpeed=.5,n.autoFit=!0,n.autoRotate&&o){const r=parseFloat(o);isNaN(r)||(n.autoRotateSpeed=r)}}else console.warn("Missing camera object, can not add orbit controls")}ge.registerCallback(ye.ContextCreated,s=>{const t=s.context.domElement.getAttribute("autoplay");if(t!==void 0&&(t===""||t==="true"||t==="1")&&s.files)for(const i of s.files)P.foreachComponent(i.file.scene,n=>{if(n.enabled!==!1){if(n instanceof Wt&&n.playAutomatically||n instanceof kt||n instanceof rr&&n.playOnAwake===!0)return!0;if(n instanceof Wt)return n.playAutomatically=!0,!0;if(n instanceof rr)return n.playOnAwake=!0,!0}},!0)!==!0&&Wa.assignAnimationsFromFile(i.file,{createAnimationComponent:(n,o)=>Mi(n,Wt)})});class Gj extends oO{constructor(){super(new rO),this.name="GenerateMeshBVHWorker"}runTask(t,i,n={}){return new Promise((o,r)=>{if(i.getAttribute("position").isInterleavedBufferAttribute||i.index&&i.index.isInterleavedBufferAttribute)throw new Error("GenerateMeshBVHWorker: InterleavedBufferAttribute are not supported for the geometry attributes.");t.onerror=d=>{r(new Error(`GenerateMeshBVHWorker: ${d.message}`))},t.onmessage=d=>{const{data:u}=d;if(u.error)r(new Error(u.error)),t.onmessage=null;else if(u.serialized){const{serialized:p,position:g}=u,y=aO.deserialize(p,i,{setIndex:!1}),f=Object.assign({setBoundingBox:!0},n);if(i.attributes.position.array=g,p.index)if(i.index)i.index.array=p.index;else{const v=new ft(p.index,1,!1);i.setIndex(v)}f.setBoundingBox&&(i.boundingBox=y.getBoundingBox(new _i)),n.onProgress&&n.onProgress(u.progress),o(y),t.onmessage=null}else n.onProgress&&n.onProgress(u.progress)};const l=i.index?i.index.array:null,c=i.attributes.position.array,h=[c];l&&h.push(l),t.postMessage({index:l,position:c,options:{...n,onProgress:null,includedProgressCallback:!!n.onProgress,groups:[...i.groups]}},h.map(d=>d.buffer).filter(d=>typeof SharedArrayBuffer>"u"||!(d instanceof SharedArrayBuffer)))})}}const Xj=Object.freeze(Object.defineProperty({__proto__:null,GenerateMeshBVHWorker:Gj},Symbol.toStringTag,{value:"Module"}));export{Pg as $,Wa as A,br as B,ee as C,eg as D,ob as E,z_ as F,P as G,ae as H,cs as I,au as J,U_ as K,Ci as L,L as M,J as N,cu as O,N_ as P,hu as Q,Rn as R,Gb as S,S as T,r2 as U,_s as V,Qb as W,Og as X,a2 as Y,Ee as Z,Zb as _,Mw as a,Pw as a$,c2 as a0,$g as a1,Cc as a2,Or as a3,Mi as a4,M_ as a5,Pr as a6,Oc as a7,Pc as a8,Ba as a9,Ds as aA,Fa as aB,Mc as aC,A_ as aD,I_ as aE,iu as aF,qg as aG,kr as aH,L_ as aI,za as aJ,Ri as aK,Mr as aL,ou as aM,Ua as aN,fs as aO,km as aP,jj as aQ,Lj as aR,Dj as aS,Fj as aT,Id as aU,Be as aV,Cn as aW,uc as aX,IP as aY,Oi as aZ,fb as a_,kc as aa,Kd as ab,Zd as ac,E_ as ad,vc as ae,Rd as af,tg as ag,hc as ah,Sn as ai,_r as aj,dc as ak,pk as al,mk as am,Me as an,wu as ao,ye as ap,ge as aq,V_ as ar,G2 as as,H_ as at,wr as au,go as av,Iy as aw,xk as ax,cf as ay,df as az,Xk as b,Ey as b$,qk as b0,Gk as b1,Qk as b2,W as b3,Sd as b4,zm as b5,di as b6,pc as b7,Rb as b8,ie as b9,Sf as bA,Nw as bB,Ww as bC,Gc as bD,cd as bE,Ks as bF,ws as bG,Gt as bH,xv as bI,Td as bJ,RP as bK,Ed as bL,Ws as bM,xg as bN,Fd as bO,_t as bP,Ru as bQ,st as bR,Ga as bS,ld as bT,bo as bU,G_ as bV,X_ as bW,Ha as bX,gu as bY,K_ as bZ,Z_ as b_,HP as ba,$P as bb,qP as bc,Tb as bd,dg as be,Eb as bf,Rr as bg,Jw as bh,dR as bi,jo as bj,zt as bk,r_ as bl,xc as bm,Lg as bn,a_ as bo,v2 as bp,l_ as bq,Dg as br,c_ as bs,h_ as bt,u_ as bu,UP as bv,NP as bw,Ob as bx,kb as by,Ys as bz,Pk as c,hO as c$,$1 as c0,pa as c1,Pj as c2,kj as c3,Ay as c4,G1 as c5,Yd as c6,Wg as c7,v_ as c8,m as c9,qm as cA,Gm as cB,sc as cC,Xm as cD,nc as cE,kd as cF,iP as cG,Kv as cH,Xi as cI,Zv as cJ,sP as cK,Qm as cL,Jv as cM,ci as cN,eb as cO,tb as cP,Ym as cQ,ew as cR,yx as cS,ce as cT,Uu as cU,Bw as cV,TM as cW,Fw as cX,zw as cY,Uw as cZ,Sv as c_,$a as ca,rM as cb,lM as cc,Ew as cd,Au as ce,uM as cf,Aw as cg,Iw as ch,Nj as ci,qa as cj,$O as ck,qO as cl,ic as cm,G as cn,Hv as co,vs as cp,te as cq,dt as cr,yr as cs,Oe as ct,Gi as cu,$m as cv,Je as cw,Pa as cx,JO as cy,Xv as cz,vj as d,Sw as d$,dO as d0,Si as d1,Yl as d2,O as d3,uO as d4,Kl as d5,Tm as d6,Cv as d7,Em as d8,pO as d9,RO as dA,TO as dB,EO as dC,Tv as dD,Ev as dE,Im as dF,wd as dG,Av as dH,N1 as dI,W1 as dJ,nj as dK,Sy as dL,B1 as dM,Jh as dN,Wj as dO,Hj as dP,m_ as dQ,Qu as dR,Rs as dS,DR as dT,BR as dU,Ku as dV,Zu as dW,qf as dX,Gf as dY,Lk as dZ,Bc as d_,mO as da,kv as db,Mv as dc,Ca as dd,Zl as de,ys as df,Jl as dg,Rv as dh,gO as di,ho as dj,eo as dk,_d as dl,Am as dm,X as dn,yO as dp,vO as dq,bO as dr,_O as ds,wO as dt,xO as du,SO as dv,CO as dw,OO as dx,PO as dy,kO as dz,Um as e,Gu as e$,So as e0,pf as e1,C_ as e2,O_ as e3,Jd as e4,Se as e5,Tn as e6,Ny as e7,Kr as e8,Pt as e9,Of as eA,zr as eB,Ja as eC,Wu as eD,Mf as eE,el as eF,Tf as eG,is as eH,Pe as eI,Ur as eJ,Ln as eK,pi as eL,tl as eM,il as eN,Io as eO,In as eP,ks as eQ,If as eR,eh as eS,Lf as eT,Hu as eU,mi as eV,Dn as eW,Wr as eX,Gs as eY,Eu as eZ,_e as e_,sw as ea,ef as eb,Ad as ec,EP as ed,ng as ee,AP as ef,mb as eg,gb as eh,og as ei,Ab as ej,Nb as ek,A as el,Mo as em,Bf as en,Py as eo,Lc as ep,Wt as eq,Qt as er,Dr as es,kt as et,Hi as eu,To as ev,We as ew,Qs as ex,$c as ey,Xc as ez,q as f,Xe as f$,Kf as f0,rh as f1,io as f2,He as f3,lh as f4,c0 as f5,h0 as f6,dr as f7,up as f8,qr as f9,kl as fA,Hs as fB,Jc as fC,jf as fD,z0 as fE,Sh as fF,yi as fG,Jr as fH,Oh as fI,Br as fJ,an as fK,Pp as fL,Ml as fM,ea as fN,Vc as fO,be as fP,os as fQ,ct as fR,Eh as fS,Qo as fT,Q as fU,si as fV,Lt as fW,Mh as fX,hn as fY,Rh as fZ,Yo as f_,yl as fa,Gr as fb,bl as fc,_l as fd,Bo as fe,Xr as ff,wl as fg,hh as fh,dh as fi,d0 as fj,Tt as fk,Lo as fl,wt as fm,Nn as fn,Ii as fo,fe as fp,mp as fq,u0 as fr,Fo as fs,yp as ft,fh as fu,vp as fv,Go as fw,Ge as fx,Pl as fy,Zr as fz,Nv as g,aa as g$,Ce as g0,Ue as g1,Qe as g2,Dt as g3,ns as g4,Fi as g5,lt as g6,Ko as g7,ni as g8,ta as g9,sh as gA,ve as gB,ot as gC,sr as gD,Nh as gE,un as gF,nr as gG,pn as gH,$h as gI,$p as gJ,rn as gK,Wo as gL,Vn as gM,fi as gN,Gp as gO,js as gP,qs as gQ,my as gR,gy as gS,rr as gT,qh as gU,El as gV,Al as gW,Qp as gX,Qh as gY,Yh as gZ,Yp as g_,Ap as ga,Vl as gb,Ih as gc,sa as gd,jh as ge,tr as gf,As as gg,Lh as gh,Dh as gi,Gn as gj,Is as gk,Fh as gl,dn as gm,er as gn,ra as go,zp as gp,zh as gq,N as gr,Ah as gs,ll as gt,Qf as gu,et as gv,oh as gw,Yf as gx,Hr as gy,ih as gz,Os as h,Sl as h$,ls as h0,Wc as h1,Kn as h2,Et as h3,No as h4,ai as h5,Qr as h6,gh as h7,Il as h8,Jp as h9,Hn as hA,tt as hB,Rt as hC,Bl as hD,fn as hE,da as hF,Jn as hG,im as hH,Kt as hI,Ai as hJ,kx as hK,Mx as hL,Ts as hM,xx as hN,Zf as hO,Zt as hP,wx as hQ,ht as hR,rs as hS,Wi as hT,mn as hU,yy as hV,Gh as hW,Tu as hX,Zs as hY,Jo as hZ,Rp as h_,ca as ha,zo as hb,b0 as hc,_0 as hd,w0 as he,xl as hf,Wl as hg,Ei as hh,ju as hi,Qa as hj,Lu as hk,g0 as hl,f0 as hm,Ht as hn,Kh as ho,$t as hp,ha as hq,Ll as hr,gt as hs,Ao as ht,Ho as hu,Zn as hv,ln as hw,Di as hx,Sp as hy,ed as hz,rf as i,Jx as i0,Li as i1,ag as i2,lg as i3,Sb as i4,Cb as i5,_o as j,R0 as k,X1 as l,zO as m,Dv as n,kw as o,Kk as p,LO as q,S2 as r,Od as s,De as t,Wv as u,Mt as v,xe as w,ac as x,F as y,hP as z};
1489
+ `),pe(this,ga).innerHTML=pe(this,bi).innerHTML,pe(this,ga).style.cssText="display: flex; align-items: center; justify-content: center;",pe(this,bi).innerHTML=pe(this,ga).outerHTML,pe(this,ma).innerHTML=pe(this,bi).outerHTML,pe(this,ma).prepend(pe(this,fa)),yu(sf,{element:pe(this,ma)}),(t=pe(this,Nl))==null||t.disconnect(),pe(this,Nl)??Bs(this,Nl,new MutationObserver(()=>va(this,Uy,aS).call(this))),pe(this,Nl).observe(pe(this,bi),{attributes:!0}),Fy&&console.log("Needle Button updated")},Uy=new WeakSet,aS=function(){pe(this,bi)&&(pe(this,bi).style.display==="none"?this.style.display="none":this.style.display==="none"&&(this.style.display=""))},rm=new WeakMap,a(Ny,"observedAttributes",["ar","vr","quicklook"]),typeof window<"u"&&!window.customElements.get(oS)&&window.customElements.define(oS,Ny);const am=O("debugmissingcamera");ge.registerCallback(ye.MissingCamera,s=>{var t,i,n;am&&console.warn("Creating missing camera");const o=s.context.scene,r=new we;r.name="Default Fallback Camera",o.add(r);const l=new Pe;l.sourceId=((i=(t=s.files)==null?void 0:t[0])==null?void 0:i.src)??"unknown",(n=s.context.domElement.getAttribute("skybox-image"))!=null&&n.length||0>0||s.context.lightmaps.tryGetSkybox(l.sourceId)?l.clearFlags=Mo.Skybox:l.clearFlags=Mo.SolidColor,l.backgroundColor=new Se(.5,.5,.5,1),l.fieldOfView=35,s.context.domElement.getAttribute("transparent")!=null&&(l.clearFlags=Mo.Uninitialized),l.backgroundBlurriness=.2;const c=Or(r,l,!0);r.position.x=0,r.position.y=1,r.position.z=2;const h=s.context.domElement;return h?.cameraControls!=!1&&lS(s.context,c),c}),ge.registerCallback(ye.ContextCreated,s=>{if(!s.context.mainCamera){am&&console.log("Will not auto-fit because a default camera exists");return}const t=s.context.domElement;if(t?.cameraControls==!0){const i=Nv(s.context.mainCamera);if(i?.isCameraController==!0){am&&console.log("Will not auto-fit because a camera controller exists");return}lS(s.context)}});function lS(s,t){t=t??s.mainCameraComponent;const i=t?.gameObject;if(am&&console.log("Creating default camera controls",t?.name),i){const n=Cc(i,be);n.sourceId=t?.sourceId??"unknown";const o=s.domElement.getAttribute("auto-rotate");if(n.autoRotate=o!=null&&o!="0"&&o?.toLowerCase()!="false",n.autoRotateSpeed=.5,n.autoFit=!0,n.autoRotate&&o){const r=parseFloat(o);isNaN(r)||(n.autoRotateSpeed=r)}}else console.warn("Missing camera object, can not add orbit controls")}ge.registerCallback(ye.ContextCreated,s=>{const t=s.context.domElement.getAttribute("autoplay");if(t!==void 0&&(t===""||t==="true"||t==="1")&&s.files)for(const i of s.files)P.foreachComponent(i.file.scene,n=>{if(n.enabled!==!1){if(n instanceof Wt&&n.playAutomatically||n instanceof kt||n instanceof rr&&n.playOnAwake===!0)return!0;if(n instanceof Wt)return n.playAutomatically=!0,!0;if(n instanceof rr)return n.playOnAwake=!0,!0}},!0)!==!0&&Wa.assignAnimationsFromFile(i.file,{createAnimationComponent:(n,o)=>Mi(n,Wt)})});class Gj extends oO{constructor(){super(new rO),this.name="GenerateMeshBVHWorker"}runTask(t,i,n={}){return new Promise((o,r)=>{if(i.getAttribute("position").isInterleavedBufferAttribute||i.index&&i.index.isInterleavedBufferAttribute)throw new Error("GenerateMeshBVHWorker: InterleavedBufferAttribute are not supported for the geometry attributes.");t.onerror=d=>{r(new Error(`GenerateMeshBVHWorker: ${d.message}`))},t.onmessage=d=>{const{data:u}=d;if(u.error)r(new Error(u.error)),t.onmessage=null;else if(u.serialized){const{serialized:p,position:g}=u,y=aO.deserialize(p,i,{setIndex:!1}),f=Object.assign({setBoundingBox:!0},n);if(i.attributes.position.array=g,p.index)if(i.index)i.index.array=p.index;else{const v=new ft(p.index,1,!1);i.setIndex(v)}f.setBoundingBox&&(i.boundingBox=y.getBoundingBox(new _i)),n.onProgress&&n.onProgress(u.progress),o(y),t.onmessage=null}else n.onProgress&&n.onProgress(u.progress)};const l=i.index?i.index.array:null,c=i.attributes.position.array,h=[c];l&&h.push(l),t.postMessage({index:l,position:c,options:{...n,onProgress:null,includedProgressCallback:!!n.onProgress,groups:[...i.groups]}},h.map(d=>d.buffer).filter(d=>typeof SharedArrayBuffer>"u"||!(d instanceof SharedArrayBuffer)))})}}const Xj=Object.freeze(Object.defineProperty({__proto__:null,GenerateMeshBVHWorker:Gj},Symbol.toStringTag,{value:"Module"}));export{Pg as $,Wa as A,br as B,ee as C,eg as D,ob as E,z_ as F,P as G,ae as H,cs as I,au as J,U_ as K,Ci as L,L as M,J as N,cu as O,N_ as P,hu as Q,Rn as R,Gb as S,S as T,rk as U,_s as V,Qb as W,Og as X,ak as Y,Ee as Z,Zb as _,Mw as a,Pw as a$,ck as a0,$g as a1,Cc as a2,Or as a3,Mi as a4,M_ as a5,Pr as a6,Oc as a7,Pc as a8,Ba as a9,Ds as aA,Fa as aB,Mc as aC,A_ as aD,I_ as aE,iu as aF,qg as aG,kr as aH,L_ as aI,za as aJ,Ri as aK,Mr as aL,ou as aM,Ua as aN,fs as aO,km as aP,jj as aQ,Lj as aR,Dj as aS,Fj as aT,Id as aU,Be as aV,Cn as aW,uc as aX,IP as aY,Oi as aZ,fb as a_,kc as aa,Kd as ab,Zd as ac,E_ as ad,vc as ae,Rd as af,tg as ag,hc as ah,Sn as ai,_r as aj,dc as ak,p2 as al,m2 as am,Me as an,wu as ao,ye as ap,ge as aq,V_ as ar,Gk as as,H_ as at,wr as au,go as av,Iy as aw,x2 as ax,cf as ay,df as az,X2 as b,Ey as b$,q2 as b0,G2 as b1,Q2 as b2,W as b3,Sd as b4,zm as b5,di as b6,pc as b7,Rb as b8,ie as b9,Sf as bA,Nw as bB,Ww as bC,Gc as bD,cd as bE,Ks as bF,ws as bG,Gt as bH,xv as bI,Td as bJ,RP as bK,Ed as bL,Ws as bM,xg as bN,Fd as bO,_t as bP,Ru as bQ,st as bR,Ga as bS,ld as bT,bo as bU,G_ as bV,X_ as bW,Ha as bX,gu as bY,K_ as bZ,Z_ as b_,HP as ba,$P as bb,qP as bc,Tb as bd,dg as be,Eb as bf,Rr as bg,Jw as bh,dR as bi,jo as bj,zt as bk,r_ as bl,xc as bm,Lg as bn,a_ as bo,vk as bp,l_ as bq,Dg as br,c_ as bs,h_ as bt,u_ as bu,UP as bv,NP as bw,Ob as bx,kb as by,Ys as bz,P2 as c,hO as c$,$1 as c0,pa as c1,Pj as c2,kj as c3,Ay as c4,G1 as c5,Yd as c6,Wg as c7,v_ as c8,m as c9,qm as cA,Gm as cB,sc as cC,Xm as cD,nc as cE,kd as cF,iP as cG,Kv as cH,Xi as cI,Zv as cJ,sP as cK,Qm as cL,Jv as cM,ci as cN,eb as cO,tb as cP,Ym as cQ,ew as cR,yx as cS,ce as cT,Uu as cU,Bw as cV,TM as cW,Fw as cX,zw as cY,Uw as cZ,Sv as c_,$a as ca,rM as cb,lM as cc,Ew as cd,Au as ce,uM as cf,Aw as cg,Iw as ch,Nj as ci,qa as cj,$O as ck,qO as cl,ic as cm,G as cn,Hv as co,vs as cp,te as cq,dt as cr,yr as cs,Oe as ct,Gi as cu,$m as cv,Je as cw,Pa as cx,JO as cy,Xv as cz,vj as d,Sw as d$,dO as d0,Si as d1,Yl as d2,O as d3,uO as d4,Kl as d5,Tm as d6,Cv as d7,Em as d8,pO as d9,RO as dA,TO as dB,EO as dC,Tv as dD,Ev as dE,Im as dF,wd as dG,Av as dH,N1 as dI,W1 as dJ,nj as dK,Sy as dL,B1 as dM,Jh as dN,Wj as dO,Hj as dP,m_ as dQ,Qu as dR,Rs as dS,DR as dT,BR as dU,Ku as dV,Zu as dW,qf as dX,Gf as dY,L2 as dZ,Bc as d_,mO as da,kv as db,Mv as dc,Ca as dd,Zl as de,ys as df,Jl as dg,Rv as dh,gO as di,ho as dj,eo as dk,_d as dl,Am as dm,X as dn,yO as dp,vO as dq,bO as dr,_O as ds,wO as dt,xO as du,SO as dv,CO as dw,OO as dx,PO as dy,kO as dz,Um as e,Gu as e$,So as e0,pf as e1,C_ as e2,O_ as e3,Jd as e4,Se as e5,Tn as e6,Ny as e7,Kr as e8,Pt as e9,Of as eA,zr as eB,Ja as eC,Wu as eD,Mf as eE,el as eF,Tf as eG,is as eH,Pe as eI,Ur as eJ,Ln as eK,pi as eL,tl as eM,il as eN,Io as eO,In as eP,ks as eQ,If as eR,eh as eS,Lf as eT,Hu as eU,mi as eV,Dn as eW,Wr as eX,Gs as eY,Eu as eZ,_e as e_,sw as ea,ef as eb,Ad as ec,EP as ed,ng as ee,AP as ef,mb as eg,gb as eh,og as ei,Ab as ej,Nb as ek,A as el,Mo as em,Bf as en,Py as eo,Lc as ep,Wt as eq,Qt as er,Dr as es,kt as et,Hi as eu,To as ev,We as ew,Qs as ex,$c as ey,Xc as ez,q as f,Xe as f$,Kf as f0,rh as f1,io as f2,He as f3,lh as f4,c0 as f5,h0 as f6,dr as f7,up as f8,qr as f9,kl as fA,Hs as fB,Jc as fC,jf as fD,z0 as fE,Sh as fF,yi as fG,Jr as fH,Oh as fI,Br as fJ,an as fK,Pp as fL,Ml as fM,ea as fN,Vc as fO,be as fP,os as fQ,ct as fR,Eh as fS,Qo as fT,Q as fU,si as fV,Lt as fW,Mh as fX,hn as fY,Rh as fZ,Yo as f_,yl as fa,Gr as fb,bl as fc,_l as fd,Bo as fe,Xr as ff,wl as fg,hh as fh,dh as fi,d0 as fj,Tt as fk,Lo as fl,wt as fm,Nn as fn,Ii as fo,fe as fp,mp as fq,u0 as fr,Fo as fs,yp as ft,fh as fu,vp as fv,Go as fw,Ge as fx,Pl as fy,Zr as fz,Nv as g,aa as g$,Ce as g0,Ue as g1,Qe as g2,Dt as g3,ns as g4,Fi as g5,lt as g6,Ko as g7,ni as g8,ta as g9,sh as gA,ve as gB,ot as gC,sr as gD,Nh as gE,un as gF,nr as gG,pn as gH,$h as gI,$p as gJ,rn as gK,Wo as gL,Vn as gM,fi as gN,Gp as gO,js as gP,qs as gQ,my as gR,gy as gS,rr as gT,qh as gU,El as gV,Al as gW,Qp as gX,Qh as gY,Yh as gZ,Yp as g_,Ap as ga,Vl as gb,Ih as gc,sa as gd,jh as ge,tr as gf,As as gg,Lh as gh,Dh as gi,Gn as gj,Is as gk,Fh as gl,dn as gm,er as gn,ra as go,zp as gp,zh as gq,N as gr,Ah as gs,ll as gt,Qf as gu,et as gv,oh as gw,Yf as gx,Hr as gy,ih as gz,Os as h,Sl as h$,ls as h0,Wc as h1,Kn as h2,Et as h3,No as h4,ai as h5,Qr as h6,gh as h7,Il as h8,Jp as h9,Hn as hA,tt as hB,Rt as hC,Bl as hD,fn as hE,da as hF,Jn as hG,im as hH,Kt as hI,Ai as hJ,kx as hK,Mx as hL,Ts as hM,xx as hN,Zf as hO,Zt as hP,wx as hQ,ht as hR,rs as hS,Wi as hT,mn as hU,yy as hV,Gh as hW,Tu as hX,Zs as hY,Jo as hZ,Rp as h_,ca as ha,zo as hb,b0 as hc,_0 as hd,w0 as he,xl as hf,Wl as hg,Ei as hh,ju as hi,Qa as hj,Lu as hk,g0 as hl,f0 as hm,Ht as hn,Kh as ho,$t as hp,ha as hq,Ll as hr,gt as hs,Ao as ht,Ho as hu,Zn as hv,ln as hw,Di as hx,Sp as hy,ed as hz,rf as i,Jx as i0,Li as i1,ag as i2,lg as i3,Sb as i4,Cb as i5,_o as j,R0 as k,X1 as l,zO as m,Dv as n,kw as o,K2 as p,LO as q,Sk as r,Od as s,De as t,Wv as u,Mt as v,xe as w,ac as x,F as y,hP as z};