@needle-tools/engine 3.45.2-beta.1 → 3.45.2-beta.4

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.
@@ -4344,7 +4344,7 @@ Open this page to get the console: `+A.toString())}const g=In()||bk()&&ae();if((
4344
4344
  #__vconsole .vc-mask {
4345
4345
  overflow: hidden;
4346
4346
  }
4347
- `,As==null||As.prepend(t),g===!0&&yJ()<=0&&h3(),console.log("🌵 Debug console has loaded")}},A.src="https://unpkg.com/vconsole@latest/dist/vconsole.min.js",document.body.appendChild(A)}function JgA(){const g=new VConsole.VConsolePlugin("needle-console","🌵 Inspect glTF"),A=()=>document.querySelector("#__vc_plug_"+g._id+" iframe");return g.on("renderTab",function(e){const t=globalThis["needle:codegen_files"];if(!t||t.length===0)return;let i=globalThis["needle:codegen_files"][0];const I=i.indexOf("?");I>-1&&(i=i.substring(0,I));const s=location.protocol+"//"+location.host+location.pathname+"/"+i,n=encodeURIComponent(s);g.fullUrl="https://viewer.needle.tools?inspect&file="+n;var r='<iframe src="" style="width: 100%; height: 99%; border: none;"></iframe>';e(r)}),g.on("show",function(){const e=A();e&&e.src!==g.fullUrl&&(e.src=g.fullUrl)}),g.on("hide",function(){const e=A();e&&(e.src="")}),g.on("addTopBar",function(e){var t=new Array;t.push({name:"Open in new window ↗",onClick:function(i){window.open(g.fullUrl,"_blank"),os==null||os.hide()}}),t.push({name:"Reload",onClick:function(i){const I=A();I&&(I.src=g.fullUrl)}}),t.push({name:"Fullscreen",onClick:function(i){const I=A();I.requestFullscreen?I.requestFullscreen():I.webkitRequestFullscreen instanceof Function&&I.webkitRequestFullscreen()}}),e(t)}),g}function xgA(){const g=document.querySelector("#__vconsole .vc-switch");return g||null}function vgA(){const g=document.querySelector("#__vconsole");return g||null}const p3=gA("debugdefines");gd('if(!globalThis[""3.45.2-beta.1""]) globalThis[""3.45.2-beta.1""] = "0.0.0";');gd('if(!globalThis[""undefined""]) globalThis[""undefined""] = "unknown";');gd('if(!globalThis[""Wed Jul 17 2024 19:33:24 GMT+0200 (Central European Summer Time)""]) globalThis[""Wed Jul 17 2024 19:33:24 GMT+0200 (Central European Summer Time)""] = "unknown";');gd('globalThis["__NEEDLE_ENGINE_VERSION__"] = "3.45.2-beta.1";');gd('globalThis["__NEEDLE_ENGINE_GENERATOR__"] = "undefined";');gd('globalThis["__NEEDLE_PROJECT_BUILD_TIME__"] = "Wed Jul 17 2024 19:33:24 GMT+0200 (Central European Summer Time)";');const Os="3.45.2-beta.1",_k="undefined",gx="Wed Jul 17 2024 19:33:24 GMT+0200 (Central European Summer Time)";p3&&console.log(`Engine version: ${Os} (generator: ${_k})
4347
+ `,As==null||As.prepend(t),g===!0&&yJ()<=0&&h3(),console.log("🌵 Debug console has loaded")}},A.src="https://unpkg.com/vconsole@latest/dist/vconsole.min.js",document.body.appendChild(A)}function JgA(){const g=new VConsole.VConsolePlugin("needle-console","🌵 Inspect glTF"),A=()=>document.querySelector("#__vc_plug_"+g._id+" iframe");return g.on("renderTab",function(e){const t=globalThis["needle:codegen_files"];if(!t||t.length===0)return;let i=globalThis["needle:codegen_files"][0];const I=i.indexOf("?");I>-1&&(i=i.substring(0,I));const s=location.protocol+"//"+location.host+location.pathname+"/"+i,n=encodeURIComponent(s);g.fullUrl="https://viewer.needle.tools?inspect&file="+n;var r='<iframe src="" style="width: 100%; height: 99%; border: none;"></iframe>';e(r)}),g.on("show",function(){const e=A();e&&e.src!==g.fullUrl&&(e.src=g.fullUrl)}),g.on("hide",function(){const e=A();e&&(e.src="")}),g.on("addTopBar",function(e){var t=new Array;t.push({name:"Open in new window ↗",onClick:function(i){window.open(g.fullUrl,"_blank"),os==null||os.hide()}}),t.push({name:"Reload",onClick:function(i){const I=A();I&&(I.src=g.fullUrl)}}),t.push({name:"Fullscreen",onClick:function(i){const I=A();I.requestFullscreen?I.requestFullscreen():I.webkitRequestFullscreen instanceof Function&&I.webkitRequestFullscreen()}}),e(t)}),g}function xgA(){const g=document.querySelector("#__vconsole .vc-switch");return g||null}function vgA(){const g=document.querySelector("#__vconsole");return g||null}const p3=gA("debugdefines");gd('if(!globalThis[""3.45.2-beta.4""]) globalThis[""3.45.2-beta.4""] = "0.0.0";');gd('if(!globalThis[""undefined""]) globalThis[""undefined""] = "unknown";');gd('if(!globalThis[""Fri Jul 19 2024 19:15:04 GMT+0200 (Central European Summer Time)""]) globalThis[""Fri Jul 19 2024 19:15:04 GMT+0200 (Central European Summer Time)""] = "unknown";');gd('globalThis["__NEEDLE_ENGINE_VERSION__"] = "3.45.2-beta.4";');gd('globalThis["__NEEDLE_ENGINE_GENERATOR__"] = "undefined";');gd('globalThis["__NEEDLE_PROJECT_BUILD_TIME__"] = "Fri Jul 19 2024 19:15:04 GMT+0200 (Central European Summer Time)";');const Os="3.45.2-beta.4",_k="undefined",gx="Fri Jul 19 2024 19:15:04 GMT+0200 (Central European Summer Time)";p3&&console.log(`Engine version: ${Os} (generator: ${_k})
4348
4348
  Project built at ${gx}`);const ja="needle_isActiveInHierarchy",ZQ="builtin_components",Sp="needle_editor_guid";function gd(g){try{(0,eval)(g)}catch(A){p3&&console.error(A)}}const qgA='<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>',LgA=btoa(qgA),_gA="data:image/svg+xml;base64,"+LgA,TgA=_gA,HgA=`<?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(HgA);const YgA='<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>',OgA=btoa(YgA),PgA="data:image/svg+xml;charset=utf-8;base64,"+OgA,WgA=PgA,_s=gA("debuglicense");let hc="basic";_s&&console.log("License Type: "+hc);function fB(){switch(hc){case"pro":case"enterprise":return!0}return!1}function Ix(){switch(hc){case"indie":return!0}return!1}function za(){return fB()||Ix()}const f3=[];function ZgA(g){if(fB()||Ix())return g(!0);f3.push(g)}function jgA(g){for(const A of f3)try{A(g)}catch{}}Et.registerCallback(Gt.ContextRegistered,g=>{XgA(g.context),AIA(),VgA(g.context)});let DB,WF=!1,Pu="";async function zgA(){if(DB)return DB;if(hc==="basic")try{const g="https://engine.needle.tools/licensing/check?location="+encodeURIComponent(window.location.href)+"&version="+Os+"&generator="+encodeURIComponent(_k),A=await fetch(g,{method:"GET"}).catch(e=>{_s&&console.error("License check failed",e)});(A==null?void 0:A.status)===200?(WF=!1,_s&&console.log("License check succeeded"),hc="pro",jgA(!0)):(A==null?void 0:A.status)===403?(WF=!0,Pu=await A.text()):_s&&console.log("License check failed with status "+(A==null?void 0:A.status))}catch(g){_s&&console.error("License check failed",g)}else _s&&console.log('Runtime license check is skipped because license is already applied as "'+hc+'"')}DB=zgA();async function VgA(g){function A(){const i=document.createElement("div");i.className="needle-forbidden",i.style.cssText=`
4349
4349
  position: fixed;
4350
4350
  top: 0;
@@ -5148,7 +5148,7 @@ in script ${t}.ts
5148
5148
  *
5149
5149
  * @author Feross Aboukhadijeh <https://feross.org>
5150
5150
  * @license MIT
5151
- */var KBA=function(g){return g!=null&&(QW(g)||bBA(g)||!!g._isBuffer)};function QW(g){return!!g.constructor&&typeof g.constructor.isBuffer=="function"&&g.constructor.isBuffer(g)}function bBA(g){return typeof g.readFloatLE=="function"&&typeof g.slice=="function"&&QW(g.slice(0,0))}(function(){var g=FBA,A=DY.utf8,e=KBA,t=DY.bin,i=function(I,o){I.constructor==String?o&&o.encoding==="binary"?I=t.stringToBytes(I):I=A.stringToBytes(I):e(I)?I=Array.prototype.slice.call(I,0):!Array.isArray(I)&&I.constructor!==Uint8Array&&(I=I.toString());for(var s=g.bytesToWords(I),n=I.length*8,r=1732584193,a=-271733879,C=-1732584194,Q=271733878,c=0;c<s.length;c++)s[c]=(s[c]<<8|s[c]>>>24)&16711935|(s[c]<<24|s[c]>>>8)&4278255360;s[n>>>5]|=128<<n%32,s[(n+64>>>9<<4)+14]=n;for(var E=i._ff,h=i._gg,l=i._hh,d=i._ii,c=0;c<s.length;c+=16){var p=r,u=a,f=C,w=Q;r=E(r,a,C,Q,s[c+0],7,-680876936),Q=E(Q,r,a,C,s[c+1],12,-389564586),C=E(C,Q,r,a,s[c+2],17,606105819),a=E(a,C,Q,r,s[c+3],22,-1044525330),r=E(r,a,C,Q,s[c+4],7,-176418897),Q=E(Q,r,a,C,s[c+5],12,1200080426),C=E(C,Q,r,a,s[c+6],17,-1473231341),a=E(a,C,Q,r,s[c+7],22,-45705983),r=E(r,a,C,Q,s[c+8],7,1770035416),Q=E(Q,r,a,C,s[c+9],12,-1958414417),C=E(C,Q,r,a,s[c+10],17,-42063),a=E(a,C,Q,r,s[c+11],22,-1990404162),r=E(r,a,C,Q,s[c+12],7,1804603682),Q=E(Q,r,a,C,s[c+13],12,-40341101),C=E(C,Q,r,a,s[c+14],17,-1502002290),a=E(a,C,Q,r,s[c+15],22,1236535329),r=h(r,a,C,Q,s[c+1],5,-165796510),Q=h(Q,r,a,C,s[c+6],9,-1069501632),C=h(C,Q,r,a,s[c+11],14,643717713),a=h(a,C,Q,r,s[c+0],20,-373897302),r=h(r,a,C,Q,s[c+5],5,-701558691),Q=h(Q,r,a,C,s[c+10],9,38016083),C=h(C,Q,r,a,s[c+15],14,-660478335),a=h(a,C,Q,r,s[c+4],20,-405537848),r=h(r,a,C,Q,s[c+9],5,568446438),Q=h(Q,r,a,C,s[c+14],9,-1019803690),C=h(C,Q,r,a,s[c+3],14,-187363961),a=h(a,C,Q,r,s[c+8],20,1163531501),r=h(r,a,C,Q,s[c+13],5,-1444681467),Q=h(Q,r,a,C,s[c+2],9,-51403784),C=h(C,Q,r,a,s[c+7],14,1735328473),a=h(a,C,Q,r,s[c+12],20,-1926607734),r=l(r,a,C,Q,s[c+5],4,-378558),Q=l(Q,r,a,C,s[c+8],11,-2022574463),C=l(C,Q,r,a,s[c+11],16,1839030562),a=l(a,C,Q,r,s[c+14],23,-35309556),r=l(r,a,C,Q,s[c+1],4,-1530992060),Q=l(Q,r,a,C,s[c+4],11,1272893353),C=l(C,Q,r,a,s[c+7],16,-155497632),a=l(a,C,Q,r,s[c+10],23,-1094730640),r=l(r,a,C,Q,s[c+13],4,681279174),Q=l(Q,r,a,C,s[c+0],11,-358537222),C=l(C,Q,r,a,s[c+3],16,-722521979),a=l(a,C,Q,r,s[c+6],23,76029189),r=l(r,a,C,Q,s[c+9],4,-640364487),Q=l(Q,r,a,C,s[c+12],11,-421815835),C=l(C,Q,r,a,s[c+15],16,530742520),a=l(a,C,Q,r,s[c+2],23,-995338651),r=d(r,a,C,Q,s[c+0],6,-198630844),Q=d(Q,r,a,C,s[c+7],10,1126891415),C=d(C,Q,r,a,s[c+14],15,-1416354905),a=d(a,C,Q,r,s[c+5],21,-57434055),r=d(r,a,C,Q,s[c+12],6,1700485571),Q=d(Q,r,a,C,s[c+3],10,-1894986606),C=d(C,Q,r,a,s[c+10],15,-1051523),a=d(a,C,Q,r,s[c+1],21,-2054922799),r=d(r,a,C,Q,s[c+8],6,1873313359),Q=d(Q,r,a,C,s[c+15],10,-30611744),C=d(C,Q,r,a,s[c+6],15,-1560198380),a=d(a,C,Q,r,s[c+13],21,1309151649),r=d(r,a,C,Q,s[c+4],6,-145523070),Q=d(Q,r,a,C,s[c+11],10,-1120210379),C=d(C,Q,r,a,s[c+2],15,718787259),a=d(a,C,Q,r,s[c+9],21,-343485551),r=r+p>>>0,a=a+u>>>0,C=C+f>>>0,Q=Q+w>>>0}return g.endian([r,a,C,Q])};i._ff=function(I,o,s,n,r,a,C){var Q=I+(o&s|~o&n)+(r>>>0)+C;return(Q<<a|Q>>>32-a)+o},i._gg=function(I,o,s,n,r,a,C){var Q=I+(o&n|s&~n)+(r>>>0)+C;return(Q<<a|Q>>>32-a)+o},i._hh=function(I,o,s,n,r,a,C){var Q=I+(o^s^n)+(r>>>0)+C;return(Q<<a|Q>>>32-a)+o},i._ii=function(I,o,s,n,r,a,C){var Q=I+(s^(o|~n))+(r>>>0)+C;return(Q<<a|Q>>>32-a)+o},i._blocksize=16,i._digestsize=16,CW.exports=function(I,o){if(I==null)throw new Error("Illegal argument "+I);var s=g.wordsToBytes(i(I,o));return o&&o.asBytes?s:o&&o.asString?t.bytesToString(s):g.bytesToHex(s)}})();var JBA=CW.exports;const xBA=tM(JBA);class kK{constructor(A,e,t,i){B(this,"success");B(this,"filename");B(this,"hash");B(this,"size");B(this,"url");this.success=A,this.filename=e,this.hash=t,this.size=i}}async function cW(g,A){const e=await g.arrayBuffer(),t=Lx(e),i=g.name.split(".").pop(),I=t+"."+i,o=g.name.split(".").shift();console.assert(o!==void 0);const s={alias:o,filename:I},r=await(await fetch(A+"/exists",{method:"POST",body:JSON.stringify(s)})).json();if(r.success||console.warn("exists check did fail"),r.exists)return console.log("file already exists",t),new kK(!0,I,t,g.size);console.log("begin uploading file",o,g.size);const a=new FormData;a.append("file",g);const C={};C.filesize=g.size,o&&(C.alias=o);const c=await(await fetch(A+"/upload/file",{method:"POST",body:a,headers:C})).json();if((c==null?void 0:c.success)===!1)return c.message!==void 0?console.error("Upload failed:",c.message):console.error("Upload failed"),null;console.assert(c.hash_sum===t,"hash sum did not match","received:",c.hash_sum,"expected:",t),c.success&&console.log("successfully uploaded",t,c.id);const E=new kK(c.success,I,t,g.size);return E.url=A,E}function Lx(g){return xBA(new Uint8Array(g))}async function _x(g,A,e,t,i=!1){try{const I=await fetch(t+"/download/file",{method:"POST",body:g});if(I.status!==200)return console.error("download failed",I),null;const o=await I.blob(),s=await o.arrayBuffer();i||console.assert(o.size===e,"size mismatch","expected:",e,"got:",o.size);const n=Lx(s);return i||console.assert(n===A,"hash mismatch, downloaded file is invalid"),o.arrayBuffer()}catch(I){console.error(I)}return null}async function EW(g,A){var a;const e=await fetch(g),t=(a=e.body)==null?void 0:a.getReader(),i=e.headers.get("Content-Length"),I=i?parseInt(i):0;if(!t)return null;let o=0;const s=[];for(;;){const{done:C,value:Q}=await t.read();if(Q&&(s.push(Q),o+=Q.length,A.call(null,new ProgressEvent("progress",{loaded:o,total:I}))),C)break}const n=new Uint8Array(o);let r=0;for(const C of s)n.set(C,r),r+=C.length;return n}const _C=gA("debugaddressables");class lW{constructor(A){B(this,"_context");B(this,"_assetReferences",{});B(this,"preUpdate",()=>{});this._context=A,this._context.pre_update_callbacks.push(this.preUpdate)}dispose(){const A=this._context.pre_update_callbacks.indexOf(this.preUpdate);A>=0&&this._context.pre_update_callbacks.splice(A,1);for(const e in this._assetReferences){const t=this._assetReferences[e];t==null||t.unload()}this._assetReferences={}}findAssetReference(A){return this._assetReferences[A]||null}registerAssetReference(A){return A.uri&&(this._assetReferences[A.uri]?console.warn("Asset reference already registered",A):this._assetReferences[A.uri]=A),A}unregisterAssetReference(A){A.uri&&delete this._assetReferences[A.uri]}}const bU=Symbol("assetReference"),XQ=class{constructor(A,e,t=null){B(this,"_loading");B(this,"_asset");B(this,"_glbRoot");B(this,"_url");B(this,"_progressListeners",[]);B(this,"_hash");B(this,"_hashedUri");B(this,"_isLoadingRawBinary",!1);B(this,"_rawBinary");this._url=A,this._hash=e,A.includes("?v=")?this._hashedUri=A:this._hashedUri=e?A+"?v="+e:A,t!==null&&(this.asset=t),LZ(this._url,this.onResolvePrefab.bind(this))}static getOrCreateFromUrl(A,e){if(!e&&(e=be.Current,!e))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 t=e.addressables,i=t.findAssetReference(A);if(i)return i;const I=new XQ(A,e.hash);return t.registerAssetReference(I),I}static getOrCreate(A,e,t){if(typeof A=="string"){if(!t&&(t=be.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.')}else t=A.context,A=A.sourceId;const i=OB(A,e);_C&&console.log("GetOrCreate Addressable from",A,e,"FinalPath=",i);const I=t.addressables,o=I.findAssetReference(i);if(o)return o;const s=new XQ(i,t.hash);return I.registerAssetReference(s),s}get asset(){return this._glbRoot??this._asset}set asset(A){this._asset=A}get uri(){return this._url}get url(){return this._url}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(A){return A===this.uri&&(this.mustLoad&&await this.loadAssetAsync(),this.asset)?this.asset:null}get mustLoad(){return!this.asset||this.asset.__destroyed===!0||Yc(this.asset)===!0}isLoaded(){return this._rawBinary||this.asset!==void 0}unload(){this.asset&&(_C&&console.log("Unload",this.asset),this.asset.scene&&Vs(this.asset.scene,!0,!0),Vs(this.asset,!0,!0)),this.asset=null,this._rawBinary=void 0,this._glbRoot=null,this._loading=void 0,be.Current&&be.Current.addressables.unregisterAssetReference(this)}async preload(){if(!this.mustLoad||this._isLoadingRawBinary)return null;if(this._rawBinary!==void 0)return this._rawBinary;this._isLoadingRawBinary=!0,_C&&console.log("Preload",this._hashedUri);const A=await EW(this._hashedUri,e=>{this.raiseProgressEvent(e)});return this._rawBinary=(A==null?void 0:A.buffer)??null,this._isLoadingRawBinary=!1,this._rawBinary}async loadAssetAsync(A){if(_C&&console.log("loadAssetAsync",this.uri),!this.mustLoad)return this.asset;if(A&&this._progressListeners.push(A),this._loading!==void 0)return this._loading.then(i=>this.asset);const e=be.Current;this._rawBinary?(this._loading=Ln().parseSync(e,this._rawBinary,this.uri,null),this.raiseProgressEvent(new ProgressEvent("progress",{loaded:this._rawBinary.byteLength,total:this._rawBinary.byteLength}))):(_C&&console.log("Load async",this.uri),this._loading=Ln().loadSync(e,this._hashedUri,this.uri,null,i=>{this.raiseProgressEvent(i)}));const t=await this._loading;if(this._progressListeners.length=0,this._glbRoot=this.tryGetActualGameObjectRoot(t),this._loading=void 0,t)return t[bU]=this,this._glbRoot&&(this._glbRoot[bU]=this),this.asset&&(this.asset[bU]=this),nm(e),t.scene!==void 0&&(this.asset=t),this.asset}async instantiate(A){return this.onInstantiate(A,!1)}async instantiateSynced(A,e=!0){return this.onInstantiate(A,!0,e)}beginListenDownload(A){this._progressListeners.indexOf(A)<0&&this._progressListeners.push(A)}endListenDownload(A){const e=this._progressListeners.indexOf(A);e>=0&&this._progressListeners.splice(e,1)}raiseProgressEvent(A){for(const e of this._progressListeners)e(this,A)}async onInstantiate(A,e=!1,t){const i=be.Current,I=new Wn;if(A instanceof DA?I.parent=A:A&&(Object.assign(I,A),I.cloneAssign(A)),I.parent||(I.parent=i.scene),this.mustLoad&&await this.loadAssetAsync(),_C&&console.log("Instantiate",this.uri,"parent:",A),this.asset){_C&&console.log("Add to scene",this.asset);let o=XQ.currentlyInstantiating.get(this.uri);if(o!==void 0&&o>=1e4)return console.error("Recursive or too many instantiations of "+this.uri+" in the same frame ("+o+")"),null;try{if(o===void 0&&(o=0),o+=1,XQ.currentlyInstantiating.set(this.uri,o),e){I.context=i;const s=this.asset;s.guid=this.uri;const n=iv(s,I,void 0,t);if(n)return n}else{const s=Qd(this.asset,I);if(s)return s}}finally{i.post_render_callbacks.push(()=>{o===void 0||o<0?o=0:o-=1,XQ.currentlyInstantiating.set(this.uri,o)})}}else _C&&console.warn("Failed to load asset",this.uri);return null}tryGetActualGameObjectRoot(A){if(A&&A.scene){const e=A.scene;return e.isGroup&&e.children.length===1&&e.children[0].name+"glb"===e.name?e.children[0]:e}return null}};let et=XQ;B(et,"currentlyInstantiating",new Map);class vBA extends on{constructor(){super([et],"AssetReferenceSerializer")}onSerialize(A,e){if(A&&A.uri!==void 0&&typeof A.uri=="string")return A.uri}onDeserialize(A,e){if(typeof A=="string")return e.context?e.gltfId?et.getOrCreate(e.gltfId,A,e.context):(console.error("Missing source id"),null):(console.error("Missing context"),null);if(A instanceof DA){if(!e.context)return console.error("Missing context"),null;if(!e.gltfId)return console.error("Missing source id"),null;const t=A,i=e.context,I=t.guid??t.uuid,o=i.addressables.findAssetReference(I);if(o)return o;const s=new et(I,void 0,t);return i.addressables.registerAssetReference(s),s}return null}}new vBA;const qBA=Promise.resolve(null),Zp=class{constructor(A){B(this,"url");B(this,"_bitmap");B(this,"_bitmapObject");B(this,"loader",null);this.url=A}static getOrCreate(A){let e=Zp.imageReferences.get(A);return e||(e=new Zp(A),Zp.imageReferences.set(A,e)),e}dispose(){this._bitmapObject&&this._bitmapObject.close(),this._bitmap=void 0}createHTMLImage(){const A=new Image;return A.src=this.url,A}createTexture(){return this.url?(this.loader||(this.loader=new Rr),this.loader.setCrossOrigin("anonymous"),this.loader.loadAsync(this.url)):qBA}getBitmap(){return this._bitmap?this._bitmap:(this._bitmap=new Promise((A,e)=>{const t=document.createElement("img");t.addEventListener("load",()=>{this._bitmap=createImageBitmap(t).then(i=>(this._bitmapObject=i,A(i),i))}),t.addEventListener("error",i=>{console.error("Failed to load image:"+this.url,i),A(null)}),t.src=this.url}),this._bitmap)}};let lh=Zp;B(lh,"imageReferences",new Map);class hW extends on{constructor(){super([lh],"ImageReferenceSerializer")}onSerialize(A,e){return null}onDeserialize(A,e){if(typeof A=="string"){const t=OB(e.gltfId,A);return lh.getOrCreate(t)}}}new hW;const jp=class{constructor(A){B(this,"url");B(this,"res");this.url=A}static getOrCreate(A){let e=jp.cache.get(A);return e||(e=new jp(A),jp.cache.set(A,e)),e}async loadRaw(){return this.res||(this.res=fetch(this.url)),this.res.then(A=>A.blob())}async loadText(){return this.res||(this.res=fetch(this.url)),this.res.then(A=>A.text())}};let hh=jp;B(hh,"cache",new Map);class dW extends on{constructor(){super([hh],"FileReferenceSerializer")}onSerialize(A,e){return null}onDeserialize(A,e){if(typeof A=="string"){const t=OB(e.gltfId,A);return hh.getOrCreate(t)}}}new dW;class LBA{constructor(A){B(this,"context");B(this,"mixers",[]);this.context=A}onDestroy(){this.mixers.forEach(A=>A.stopAllAction()),this.mixers.length=0}registerAnimationMixer(A){if(!A){console.warn("AnimationsRegistry.registerAnimationMixer called with null or undefined mixer");return}this.mixers.includes(A)||this.mixers.push(A)}unregisterAnimationMixer(A){if(!A)return;const e=this.mixers.indexOf(A);e!==-1&&this.mixers.splice(e,1)}}class vh{static tryGetActionsFromMixer(A){const e=A._actions;return e||null}static tryGetAnimationClipsFromObjectHierarchy(A,e){if(e||(e=new Array),A)A.animations&&e.push(...A.animations);else return e;if(A.children)for(const t of A.children)this.tryGetAnimationClipsFromObjectHierarchy(t,e);return e}static assignAnimationsFromFile(A,e){if(!A||!A.animations)return;for(let i=0;i<A.animations.length;i++){const I=A.animations[i];if(!(!I.tracks||I.tracks.length<=0))for(const o in I.tracks){const s=I.tracks[o],n=Xe.parseTrackName(s.name);let r=Xe.findNode(A.scene,n.nodeName);if(!r){const C=s.__objectName??s.name.substring(0,s.name.indexOf("."));if(r=A.scene.getObjectByProperty("uuid",C),!r)continue}let a=t(r);if(!a){if(!(e!=null&&e.createAnimationComponent)){console.warn("No AnimationComponent found in parent hierarchy of object and no 'createAnimationComponent' callback was provided in options.");continue}a=e.createAnimationComponent(A.scene,I)}a.addClip&&a.addClip(I)}}function t(i){var o;if(!i)return null;const I=(o=i.userData)==null?void 0:o.components;if(I&&I.length>0){for(let s=0;s<I.length;s++)if(I[s].isAnimationComponent===!0)return i}return t(i.parent)}}}const qh=[];function iM(g){qh.indexOf(g)===-1&&qh.push(g)}function _BA(g){const A=qh.indexOf(g);A!==-1&&qh.splice(A,1)}const Lh=[];function Tx(g){Lh.indexOf(g)===-1&&Lh.push(g)}function TBA(g){const A=Lh.indexOf(g);A!==-1&&Lh.splice(A,1)}function uW(g){globalThis.dispatchEvent(new CustomEvent("needle-xrsession-start",{detail:g}));for(let A=0;A<qh.length;A++)qh[A](g)}function pW(g){globalThis.dispatchEvent(new CustomEvent("needle-xrsession-end",{detail:g}));for(let A=0;A<Lh.length;A++)Lh[A](g)}const Yg={Handedness:Object.freeze({NONE:"none",LEFT:"left",RIGHT:"right"}),ComponentState:Object.freeze({DEFAULT:"default",TOUCHED:"touched",PRESSED:"pressed"}),ComponentProperty:Object.freeze({BUTTON:"button",X_AXIS:"xAxis",Y_AXIS:"yAxis",STATE:"state"}),ComponentType:Object.freeze({TRIGGER:"trigger",SQUEEZE:"squeeze",TOUCHPAD:"touchpad",THUMBSTICK:"thumbstick",BUTTON:"button"}),ButtonTouchThreshold:.05,AxisTouchThreshold:.1,VisualResponseProperty:Object.freeze({TRANSFORM:"transform",VISIBILITY:"visibility"})};async function fW(g){const A=await fetch(g);if(A.ok)return A.json();throw new Error(A.statusText)}async function HBA(g){if(!g)throw new Error("No basePath supplied");return await fW(`${g}/profilesList.json`)}async function YBA(g,A,e=null,t=!0){if(!g)throw new Error("No xrInputSource supplied");if(!A)throw new Error("No basePath supplied");const i=await HBA(A);let I;if(g.profiles.some(n=>{const r=i[n];return r&&(I={profileId:n,profilePath:`${A}/${r.path}`,deprecated:!!r.deprecated}),!!I}),!I){if(!e)throw new Error("No matching profile name found");const n=i[e];if(!n)throw new Error(`No matching profile name found and default profile "${e}" missing.`);I={profileId:e,profilePath:`${A}/${n.path}`,deprecated:!!n.deprecated}}const o=await fW(I.profilePath);let s;if(t){let n;if(g.handedness==="any"?n=o.layouts[Object.keys(o.layouts)[0]]:n=o.layouts[g.handedness],!n)throw new Error(`No matching handedness, ${g.handedness}, in profile ${I.profileId}`);n.assetPath&&(s=I.profilePath.replace("profile.json",n.assetPath))}return{profile:o,assetPath:s}}const OBA={xAxis:0,yAxis:0,button:0,state:Yg.ComponentState.DEFAULT};function PBA(g=0,A=0){let e=g,t=A;if(Math.sqrt(g*g+A*A)>1){const o=Math.atan2(A,g);e=Math.cos(o),t=Math.sin(o)}return{normalizedXAxis:e*.5+.5,normalizedYAxis:t*.5+.5}}let WBA=class{constructor(A){this.componentProperty=A.componentProperty,this.states=A.states,this.valueNodeName=A.valueNodeName,this.valueNodeProperty=A.valueNodeProperty,this.valueNodeProperty===Yg.VisualResponseProperty.TRANSFORM&&(this.minNodeName=A.minNodeName,this.maxNodeName=A.maxNodeName),this.value=0,this.updateFromComponent(OBA)}updateFromComponent({xAxis:A,yAxis:e,button:t,state:i}){const{normalizedXAxis:I,normalizedYAxis:o}=PBA(A,e);switch(this.componentProperty){case Yg.ComponentProperty.X_AXIS:this.value=this.states.includes(i)?I:.5;break;case Yg.ComponentProperty.Y_AXIS:this.value=this.states.includes(i)?o:.5;break;case Yg.ComponentProperty.BUTTON:this.value=this.states.includes(i)?t:0;break;case Yg.ComponentProperty.STATE:this.valueNodeProperty===Yg.VisualResponseProperty.VISIBILITY?this.value=this.states.includes(i):this.value=this.states.includes(i)?1:0;break;default:throw new Error(`Unexpected visualResponse componentProperty ${this.componentProperty}`)}}},ZBA=class{constructor(A,e){if(!A||!e||!e.visualResponses||!e.gamepadIndices||Object.keys(e.gamepadIndices).length===0)throw new Error("Invalid arguments supplied");this.id=A,this.type=e.type,this.rootNodeName=e.rootNodeName,this.touchPointNodeName=e.touchPointNodeName,this.visualResponses={},Object.keys(e.visualResponses).forEach(t=>{const i=new WBA(e.visualResponses[t]);this.visualResponses[t]=i}),this.gamepadIndices=Object.assign({},e.gamepadIndices),this.values={state:Yg.ComponentState.DEFAULT,button:this.gamepadIndices.button!==void 0?0:void 0,xAxis:this.gamepadIndices.xAxis!==void 0?0:void 0,yAxis:this.gamepadIndices.yAxis!==void 0?0:void 0}}get data(){return{id:this.id,...this.values}}updateFromGamepad(A){if(this.values.state=Yg.ComponentState.DEFAULT,this.gamepadIndices.button!==void 0&&A.buttons.length>this.gamepadIndices.button){const e=A.buttons[this.gamepadIndices.button];this.values.button=e.value,this.values.button=this.values.button<0?0:this.values.button,this.values.button=this.values.button>1?1:this.values.button,e.pressed||this.values.button===1?this.values.state=Yg.ComponentState.PRESSED:(e.touched||this.values.button>Yg.ButtonTouchThreshold)&&(this.values.state=Yg.ComponentState.TOUCHED)}this.gamepadIndices.xAxis!==void 0&&A.axes.length>this.gamepadIndices.xAxis&&(this.values.xAxis=A.axes[this.gamepadIndices.xAxis],this.values.xAxis=this.values.xAxis<-1?-1:this.values.xAxis,this.values.xAxis=this.values.xAxis>1?1:this.values.xAxis,this.values.state===Yg.ComponentState.DEFAULT&&Math.abs(this.values.xAxis)>Yg.AxisTouchThreshold&&(this.values.state=Yg.ComponentState.TOUCHED)),this.gamepadIndices.yAxis!==void 0&&A.axes.length>this.gamepadIndices.yAxis&&(this.values.yAxis=A.axes[this.gamepadIndices.yAxis],this.values.yAxis=this.values.yAxis<-1?-1:this.values.yAxis,this.values.yAxis=this.values.yAxis>1?1:this.values.yAxis,this.values.state===Yg.ComponentState.DEFAULT&&Math.abs(this.values.yAxis)>Yg.AxisTouchThreshold&&(this.values.state=Yg.ComponentState.TOUCHED)),Object.values(this.visualResponses).forEach(e=>{e.updateFromComponent(this.values)})}},jBA=class{constructor(A,e,t){if(!A)throw new Error("No xrInputSource supplied");if(!e)throw new Error("No profile supplied");this.xrInputSource=A,this.assetUrl=t,this.id=e.profileId,this.layoutDescription=e.layouts[A.handedness],this.components={},Object.keys(this.layoutDescription.components).forEach(i=>{const I=this.layoutDescription.components[i];this.components[i]=new ZBA(i,I)}),this.updateFromGamepad()}get gripSpace(){return this.xrInputSource.gripSpace}get targetRaySpace(){return this.xrInputSource.targetRaySpace}get data(){const A=[];return Object.values(this.components).forEach(e=>{A.push(e.data)}),A}updateFromGamepad(){Object.values(this.components).forEach(A=>{A.updateFromGamepad(this.xrInputSource.gamepad)})}};const to=new y,yY=new y,wY=new GA,zBA=gA("debuggizmos"),$n=8947848,mn=class{constructor(){}static isGizmo(A){return A[MK]!==void 0}static DrawLabel(A,e,t=.05,i=0,I,o,s){var a;if(!mn.enabled)return null;I||(I=$n);const n=((a=ye.active)==null?void 0:a.rigScale)??1,r=Ti.getTextLabel(i,e,t*n,I,o);return s instanceof DA&&s.add(r),r.position.x=A.x,r.position.y=A.y,r.position.z=A.z,r}static DrawRay(A,e,t=$n,i=0,I=!0){if(!mn.enabled)return;const o=Ti.getLine(i),s=o.geometry.getAttribute("position");s.setXYZ(0,A.x,A.y,A.z),to.set(e.x,e.y,e.z).multiplyScalar(999999999),s.setXYZ(1,A.x+to.x,A.y+to.y,A.z+to.z),s.needsUpdate=!0,o.material.color.set(t),o.material.depthTest=I,o.material.depthWrite=!1}static DrawDirection(A,e,t=$n,i=0,I=!0,o=1){if(!mn.enabled)return;const s=Ti.getLine(i),n=s.geometry.getAttribute("position");n.setXYZ(0,A.x,A.y,A.z),e.w!==void 0?(to.set(0,0,-o),wY.set(e.x,e.y,e.z,e.w),to.applyQuaternion(wY)):(to.set(e.x,e.y,e.z),to.multiplyScalar(o)),n.setXYZ(1,A.x+to.x,A.y+to.y,A.z+to.z),n.needsUpdate=!0,s.material.color.set(t),s.material.depthTest=I,s.material.depthWrite=!1}static DrawLine(A,e,t=$n,i=0,I=!0){if(!mn.enabled)return;const o=Ti.getLine(i),s=o.geometry.getAttribute("position");s.setXYZ(0,A.x,A.y,A.z),s.setXYZ(1,e.x,e.y,e.z),s.needsUpdate=!0,o.material.color.set(t),o.material.depthTest=I,o.material.depthWrite=!1,o.material.fog=!1}static DrawWireSphere(A,e,t=$n,i=0,I=!0){if(!mn.enabled)return;const o=Ti.getSphere(e,i,!0);Tc(o,A.x,A.y,A.z),o.material.color.set(t),o.material.depthTest=I,o.material.depthWrite=!1,o.material.fog=!1}static DrawSphere(A,e,t=$n,i=0,I=!0){if(!mn.enabled)return;const o=Ti.getSphere(e,i,!1);Tc(o,A.x,A.y,A.z),o.material.color.set(t),o.material.depthTest=I,o.material.depthWrite=!1}static DrawWireBox(A,e,t=$n,i=0,I=!0){if(!mn.enabled)return;const o=Ti.getBox(i);o.position.set(A.x,A.y,A.z),o.scale.set(e.x,e.y,e.z),o.material.color.set(t),o.material.depthTest=I,o.material.wireframe=!0,o.material.depthWrite=!1,o.material.fog=!1}static DrawWireBox3(A,e=$n,t=0,i=!0){if(!mn.enabled)return;const I=Ti.getBox(t);I.position.copy(A.getCenter(to)),I.scale.copy(A.getSize(to)),I.material.color.set(e),I.material.depthTest=i,I.material.wireframe=!0,I.material.depthWrite=!1,I.material.fog=!1}static DrawArrow(A,e,t=$n,i=0,I=!0,o=!1){if(!mn.enabled)return;const s=Ti.getArrowHead(i);s.position.set(e.x,e.y,e.z),s.quaternion.setFromUnitVectors(this._up.set(0,1,0),to.set(e.x,e.y,e.z).sub(yY.set(A.x,A.y,A.z)).normalize());const r=to.set(e.x,e.y,e.z).sub(yY.set(A.x,A.y,A.z)).length()*.1;s.scale.set(r,r,r),s.material.color.set(t),s.material.depthTest=I,s.material.wireframe=o,this.DrawLine(A,e,t,i,I)}static DrawWireMesh(A){const e=Ti.getMesh(A.duration??0);"mesh"in A?(e.geometry=A.mesh.geometry,e.matrix.copy(A.mesh.matrixWorld)):(e.geometry=A.geometry,e.matrix.copy(A.matrix)),e.matrixAutoUpdate=!1,e.matrixWorldAutoUpdate=!1,e.material.color.set(A.color??$n),e.material.depthTest=A.depthTest??!0,e.material.wireframe=!0}};let fe=mn;B(fe,"enabled",!0),B(fe,"_up",new y(0,1,0));const VBA=new ti(1,1,1);function Hx(g=null){const A=new yA(g??14540253),e=new IJ(VBA);return new TI(e,new Ii({color:A}))}const MK=Symbol("GizmoCache");class Ti{static ensureFont(){let A=Vt.FontLibrary.getFontFamily(this.familyName);if(!A){A=Vt.FontLibrary.addFontFamily(this.familyName);const e=A.addVariant("normal","normal","https://uploads.needle.tools/include/font-msdf.json","https://uploads.needle.tools/include/font.png");e==null||e.addEventListener("ready",()=>{Vt.update()})}}static getTextLabel(A,e,t,i,I){this.ensureFont();let o=this.textLabelCache.pop(),s=1;I&&typeof I=="string"&&(I==null?void 0:I.length)>=8&&I.startsWith("#")?(s=parseInt(I.substring(7),16)/255,I=I.substring(0,7),zBA&&console.log(I,s)):typeof I=="object"&&I.a!==void 0&&(s=I.a);const n={boxSizing:"border-box",fontFamily:this.familyName,width:"auto",fontSize:t,color:i,lineHeight:1,backgroundColor:I??void 0,backgroundOpacity:s,textContent:e,borderRadius:.5*t,padding:.8*t,whiteSpace:"pre"};if(o)o.set(n);else{o=new WJ(n);const r=this,a=o;a.setText=function(C){this.set({textContent:C}),r.tmuiNeedsUpdate=!0}}return this.tmuiNeedsUpdate=!0,this.registerTimedObject(be.Current,o,A,this.textLabelCache),o}static getBox(A){let e=this.boxesCache.pop();if(!e){const t=new ti(1,1,1);e=new hA(t)}return this.registerTimedObject(be.Current,e,A,this.boxesCache),e}static getLine(A){let e=this.linesCache.pop();if(!e){e=new Oi;let t=e.geometry.getAttribute("position");t||(t=new ne(new Float32Array(2*3),3),e.geometry.setAttribute("position",t))}return e.frustumCulled=!1,this.registerTimedObject(be.Current,e,A,this.linesCache),e}static getSphere(A,e,t){let i=this.spheresCache.pop();return i||(i=new hA(new gn(1,8,8))),i.scale.set(A,A,A),i.material.wireframe=t,this.registerTimedObject(be.Current,i,e,this.spheresCache),i}static getArrowHead(A){let e=this.arrowHeadsCache.pop();return e||(e=new hA(new Ag(0,.5,1,8))),this.registerTimedObject(be.Current,e,A,this.arrowHeadsCache),e}static getMesh(A){let e=this.mesh.pop();return e||(e=new hA,e.material=new ot),this.registerTimedObject(be.Current,e,A,this.mesh),e}static registerTimedObject(A,e,t,i){const I=this.contextBeforeRenderCallbacks.get(A),o=this.contextPostRenderCallbacks.get(A);if(I){if(A.pre_render_callbacks[A.pre_render_callbacks.length-1]!==I){const s=A.pre_render_callbacks.indexOf(I);s>=0&&A.pre_render_callbacks.splice(s,1),A.pre_render_callbacks.push(I)}}else{const s=()=>{this.onBeforeRender(A,this.timedObjectsBuffer)};this.contextBeforeRenderCallbacks.set(A,s),A.pre_render_callbacks.push(s)}if(o){if(A.post_render_callbacks[A.post_render_callbacks.length-1]!==o){const s=A.post_render_callbacks.indexOf(o);s>=0&&A.post_render_callbacks.splice(s,1),A.post_render_callbacks.push(o)}}else{const s=()=>{this.onPostRender(A,this.timedObjectsBuffer,this.timesBuffer)};this.contextPostRenderCallbacks.set(A,s),A.post_render_callbacks.push(s)}e.traverse(s=>{s.layers.disableAll(),s.layers.enable(2)}),e.renderOrder=999999,e[MK]=i,e.isGizmo=!0,this.timedObjectsBuffer.push(e),t<=0&&A.currentFrameEvent>=oi.OnBeforeRender?this.timesBuffer.push(0):this.timesBuffer.push(be.Current.time.realtimeSinceStartup+t),A.scene.add(e)}static onBeforeRender(A,e){this.tmuiNeedsUpdate&&Vt.update();for(let t=0;t<e.length;t++){const i=e[t];if(A.mainCamera&&i instanceof Vt.MeshUIBaseElement){if(Yc(i))continue;const I=A.isInVR,o=!1,s=!I;hD(i,A.mainCamera,o,s)}}}static onPostRender(A,e,t){const i=A.time.realtimeSinceStartup;for(let I=e.length-1;I>=0;I--){const o=e[I];i>t[I]&&(e.splice(I,1),t.splice(I,1),o.removeFromParent(),Yc(o)!=!0&&o[MK].push(o))}}}B(Ti,"familyName","needle-gizmos"),B(Ti,"linesCache",[]),B(Ti,"spheresCache",[]),B(Ti,"boxesCache",[]),B(Ti,"arrowHeadsCache",[]),B(Ti,"mesh",[]),B(Ti,"textLabelCache",[]),B(Ti,"timedObjectsBuffer",new Array),B(Ti,"timesBuffer",new Array),B(Ti,"contextPostRenderCallbacks",new Map),B(Ti,"contextBeforeRenderCallbacks",new Map),B(Ti,"tmuiNeedsUpdate",!1);const Dg=gA("debuginput");var gM=(g=>(g.Mouse="mouse",g.Touch="touch",g.Controller="controller",g.Hand="hand",g))(gM||{}),pi=(g=>(g.PointerDown="pointerdown",g.PointerUp="pointerup",g.PointerMove="pointermove",g.KeyDown="keydown",g.KeyUp="keyup",g.KeyPressed="keypress",g))(pi||{});class ma extends PointerEvent{constructor(e,t,i){super(e,i);B(this,"deviceIndex");B(this,"origin");B(this,"source");B(this,"mode");B(this,"_ray");B(this,"space");B(this,"isClick",!1);B(this,"isDoubleClick",!1);B(this,"_used",!1);B(this,"_pointerid");B(this,"_pointerType");B(this,"_type");B(this,"metadata",{});B(this,"intersections",new Array);B(this,"_immediatePropagationStopped",!1);B(this,"_propagationStopped",!1);this._pointerid=i.pointerId,this._pointerType=i.pointerType,this._type=e,this.deviceIndex=i.deviceIndex,this.origin=i.origin,this.source=t,this.mode=i.mode,this._ray=i.ray,this.space=i.device}get ray(){return this._ray||(this._ray=new xo(this.space.worldPosition.clone(),this.space.worldForward.clone())),this._ray}set ray(e){this._ray=e}get hasRay(){return this._ray!==void 0}get used(){return this._used}use(){this._used=!0}get pointerId(){return this._pointerid}get pointerType(){return this._pointerType}get type(){return this._type}get immediatePropagationStopped(){return this._immediatePropagationStopped}get propagationStopped(){return this._immediatePropagationStopped||this._propagationStopped}stopImmediatePropagation(){var e;this._immediatePropagationStopped=!0,super.stopImmediatePropagation(),(e=this.source)==null||e.stopImmediatePropagation()}stopPropagation(){var e;this._propagationStopped=!0,super.stopPropagation(),(e=this.source)==null||e.stopPropagation(),Dg&&console.warn("Stop propagation...",this.pointerId,this.pointerType)}}class ep extends KeyboardEvent{constructor(e,t,i){super(e,i);B(this,"source");this.source=t}stopImmediatePropagation(){var e;super.stopImmediatePropagation(),(e=this.source)==null||e.stopImmediatePropagation()}}class XBA{constructor(A){B(this,"key");B(this,"keyType");B(this,"source");this.key=A.key,this.keyType=A.type,this.source=A}}var cr=(g=>(g[g.Early=-100]="Early",g[g.Default=0]="Default",g[g.Late=100]="Late",g))(cr||{});class DW{constructor(A){B(this,"_eventListeners",{});B(this,"_doubleClickTimeThreshold",.2);B(this,"_longPressTimeThreshold",1);B(this,"_specialCursorTrigger",0);B(this,"context");B(this,"_pointerDown",[!1]);B(this,"_pointerUp",[!1]);B(this,"_pointerClick",[!1]);B(this,"_pointerDoubleClick",[!1]);B(this,"_pointerPressed",[!1]);B(this,"_pointerPositions",[new tA]);B(this,"_pointerPositionsLastFrame",[new tA]);B(this,"_pointerPositionsDelta",[new tA]);B(this,"_pointerPositionsRC",[new tA]);B(this,"_pointerPositionDown",[new tA]);B(this,"_pointerDownTime",[]);B(this,"_pointerUpTime",[]);B(this,"_pointerUpTimestamp",[]);B(this,"_pointerIds",[]);B(this,"_pointerTypes",[""]);B(this,"_mouseWheelChanged",[!1]);B(this,"_mouseWheelDeltaY",[0]);B(this,"_pointerEvent",[]);B(this,"_pointerUsed",[]);B(this,"_pointerSpace",[]);B(this,"_pressedStack",new Map);B(this,"_htmlEventSource");B(this,"onLostFocus",()=>{for(const A in this.keysPressed)this.keysPressed[A].pressed=!1});B(this,"onEndOfFrame",()=>{for(let A=0;A<this._pointerUp.length;A++)this._pointerUp[A]=!1;for(let A=0;A<this._pointerDown.length;A++)this._pointerDown[A]=!1;for(let A=0;A<this._pointerClick.length;A++)this._pointerClick[A]=!1;for(let A=0;A<this._pointerDoubleClick.length;A++)this._pointerDoubleClick[A]=!1;for(const A of this._pointerPositionsDelta)A.set(0,0);for(let A=0;A<this._mouseWheelChanged.length;A++)this._mouseWheelChanged[A]=!1;for(let A=0;A<this._mouseWheelDeltaY.length;A++)this._mouseWheelDeltaY[A]=0});B(this,"onContextMenu",A=>{this.canReceiveInput(A)!==!1&&A instanceof PointerEvent&&A.pointerType});B(this,"keysPressed",{});B(this,"onKeyDown",A=>{if(Dg&&console.log(`key down ${A.code}, ${this.context.application.hasFocus}`,A),!this.context.application.hasFocus)return;const e=this.keysPressed[A.code];if(e&&e.pressed)return;this.keysPressed[A.code]={pressed:!0,frame:this.context.time.frameCount+1,startFrame:this.context.time.frameCount+1,key:A.key,code:A.code};const t=new ep("keydown",A,A);this.onDispatchEvent(t)});B(this,"onKeyPressed",A=>{if(!this.context.application.hasFocus)return;const e=this.keysPressed[A.code];if(!e)return;e.pressed=!0,e.frame=this.context.time.frameCount+1;const t=new ep("keypress",A,A);this.onDispatchEvent(t)});B(this,"onKeyUp",A=>{if(!this.context.application.hasFocus)return;const e=this.keysPressed[A.code];if(!e)return;e.pressed=!1,e.frame=this.context.time.frameCount+1;const t=new ep("keyup",A,A);this.onDispatchEvent(t)});B(this,"onWheelWindow",A=>{document.pointerLockElement&&this.onMouseWheel(A)});B(this,"onMouseWheel",A=>{if(this.canReceiveInput(A)===!1)return;this._mouseWheelDeltaY.length<=0&&this._mouseWheelDeltaY.push(0),this._mouseWheelChanged.length<=0&&this._mouseWheelChanged.push(!1),this._mouseWheelChanged[0]=!0;const e=this._mouseWheelDeltaY[0];this._mouseWheelDeltaY[0]=e+A.deltaY});B(this,"onPointerDown",A=>{if(this.context.isInAR||this.canReceiveInput(A)===!1)return;A.target instanceof HTMLElement&&A.target.setPointerCapture(A.pointerId);const e=this.getPointerId(A);Dg&&fi(`pointer down #${e}, identifier:${A.pointerId}`);const t=this.getAndUpdateSpatialObjectForScreenPosition(e,A.clientX,A.clientY),i=new ma("pointerdown",A,{origin:this,mode:"screen",deviceIndex:0,pointerId:e,button:A.button,clientX:A.clientX,clientY:A.clientY,pointerType:A.pointerType,buttonName:this.getButtonName(A),device:t,pressure:A.pressure});this.onDown(i)});B(this,"onPointerMove",A=>{if(this.context.isInAR)return;let e=A.button;A.pointerType==="mouse"&&(e=this.getFirstPressedButtonForPointer(0)??0);const t=this.getPointerId(A,e);e===-1&&(e=t);const i=this.getAndUpdateSpatialObjectForScreenPosition(t,A.clientX,A.clientY),I=new ma("pointermove",A,{origin:this,mode:"screen",deviceIndex:0,pointerId:t,button:e,clientX:A.clientX,clientY:A.clientY,pointerType:A.pointerType,buttonName:this.getButtonName(A),device:i,pressure:A.pressure});this.onMove(I)});B(this,"onPointerCancel",A=>{this.context.isInAR||(Dg&&console.log("Pointer cancel",A),this.onPointerUp(A))});B(this,"onPointerUp",A=>{if(this.context.isInAR)return;A.target instanceof HTMLElement&&A.target.releasePointerCapture(A.pointerId);const e=this.getPointerId(A),t=new ma("pointerup",A,{origin:this,mode:"screen",deviceIndex:0,pointerId:e,button:A.button,clientX:A.clientX,clientY:A.clientY,pointerType:A.pointerType,buttonName:this.getButtonName(A),device:this.getAndUpdateSpatialObjectForScreenPosition(e,A.clientX,A.clientY),pressure:A.pressure});this.onUp(t),this._pointerIds[e]=-1,Dg&&console.log("ID="+e,"PointerId="+A.pointerId,"ALL:",[...this._pointerIds])});B(this,"onTouchStart",A=>{if(this.context.isInAR)for(let e=0;e<A.changedTouches.length;e++){const t=A.changedTouches[e],i=this.getPointerIndex(t.identifier),I=this.getAndUpdateSpatialObjectForScreenPosition(i,t.clientX,t.clientY),o=new ma("pointerdown",A,{origin:this,mode:"screen",deviceIndex:0,pointerId:i,button:0,clientX:t.clientX,clientY:t.clientY,pointerType:"touch",buttonName:"unknown",device:I,pressure:t.force});this.onDown(o)}});B(this,"onTouchMove",A=>{if(this.context.isInAR)for(let e=0;e<A.changedTouches.length;e++){const t=A.changedTouches[e],i=this.getPointerIndex(t.identifier),I=this.getAndUpdateSpatialObjectForScreenPosition(i,t.clientX,t.clientY),o=new ma("pointermove",A,{origin:this,mode:"screen",deviceIndex:0,pointerId:i,button:0,clientX:t.clientX,clientY:t.clientY,pointerType:"touch",buttonName:"unknown",device:I,pressure:t.force});this.onMove(o)}});B(this,"onTouchEnd",A=>{if(this.context.isInAR)for(let e=0;e<A.changedTouches.length;e++){const t=A.changedTouches[e],i=this.getPointerIndex(t.identifier),I=new ma("pointerup",A,{origin:this,mode:"screen",deviceIndex:0,pointerId:i,button:0,clientX:t.clientX,clientY:t.clientY,pointerType:"touch",buttonName:"unknown",device:this.getAndUpdateSpatialObjectForScreenPosition(i,t.clientX,t.clientY),pressure:t.force});this.onUp(I),this._pointerIds[i]=-1}});B(this,"tempNearPlaneVector",new y);B(this,"tempFarPlaneVector",new y);B(this,"tempLookMatrix",new fA);this.context=A,this.context.post_render_callbacks.push(this.onEndOfFrame)}addEventListener(A,e,t){if(this._eventListeners[A]||(this._eventListeners[A]=[]),!e||typeof e!="function"){console.error("Invalid call to addEventListener: callback is required and must be a function!");return}t?t={...t}:t={};let i=0;(t==null?void 0:t.queue)!=null&&(i=t.queue);const I=this._eventListeners[A],o=I.find(s=>s.priority===i);o?o.listeners.push({callback:e,options:t}):(I.push({priority:i,listeners:[{callback:e,options:t}]}),I.sort((s,n)=>s.priority-n.priority))}removeEventListener(A,e,t){if(!this._eventListeners[A]||!e)return;const i=this._eventListeners[A];if((t==null?void 0:t.queue)!=null){const I=i.find(s=>s.priority===t.queue);if(!I)return;const o=I.listeners.findIndex(s=>s.callback===e);o>=0&&I.listeners.splice(o,1)}else for(const I of i){const o=I.listeners.findIndex(s=>s.callback===e);o>=0&&I.listeners.splice(o,1)}}dispatchEvent(A){var t,i,I,o;let e=!1;if(A instanceof ep){const s=this._eventListeners[A.type];if(s)for(const n of s)for(let r=0;r<n.listeners.length;r++){const a=n.listeners[r];if((i=(t=a.options)==null?void 0:t.signal)!=null&&i.aborted){n.listeners.splice(r,1),r--;continue}a.options.once&&(n.listeners.splice(r,1),r--),a.callback(A)}}if(A instanceof ma){const s=this._eventListeners[A.type];if(s)for(const n of s){if(e)break;for(let r=0;r<n.listeners.length;r++){const a=n.listeners[r];if((o=(I=a.options)==null?void 0:I.signal)!=null&&o.aborted){n.listeners.splice(r,1),r--;continue}if(A.immediatePropagationStopped){e=!0,Dg&&console.log("immediatePropagationStopped",A.type);break}else A.propagationStopped&&(e=!0,Dg&&console.log("propagationStopped",A.type));a.options.once&&(n.listeners.splice(r,1),r--),a.callback(A)}}}}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)}setCursorPointer(){this._specialCursorTrigger+=1,this.context.domElement.style.cursor="pointer"}setCursorNormal(){this._specialCursorTrigger-=1,this._specialCursorTrigger=Math.max(0,this._specialCursorTrigger),this._specialCursorTrigger===0&&(this.context.domElement.style.cursor="default")}setPointerUsed(A,e=!0){if(A>=this._pointerUsed.length){if(A>=this._pointerIds.length)return;for(;this._pointerUsed.length<=A;)this._pointerUsed.push(!1)}this._pointerUsed[A]=e}getPointerUsed(A){return A>=this._pointerUsed.length?!1:this._pointerUsed[A]}getPointerPressedCount(){let A=0;for(let e=0;e<this._pointerPressed.length;e++)this._pointerPressed[e]&&A++;return A}getPointerPosition(A){return A>=this._pointerPositions.length?null:this._pointerPositions[A]}getPointerPositionLastFrame(A){return A>=this._pointerPositionsLastFrame.length?null:this._pointerPositionsLastFrame[A]}getPointerPositionDelta(A){return A>=this._pointerPositionsDelta.length?null:this._pointerPositionsDelta[A]}getPointerPositionRC(A){return A>=this._pointerPositionsRC.length?null:this._pointerPositionsRC[A]}getPointerDown(A){return A>=this._pointerDown.length?!1:this._pointerDown[A]}getPointerUp(A){return A>=this._pointerUp.length?!1:this._pointerUp[A]}getPointerPressed(A){return A>=this._pointerPressed.length?!1:this._pointerPressed[A]}getPointerClicked(A){return A>=this._pointerClick.length?!1:this._pointerClick[A]}getPointerDoubleClicked(A){return A>=this._pointerDoubleClick.length?!1:this._pointerDoubleClick[A]}getPointerDownTime(A){return A>=this._pointerDownTime.length?-1:this._pointerDownTime[A]}getPointerUpTime(A){return A>=this._pointerUpTime.length?-1:this._pointerUpTime[A]}getPointerLongPress(A){return A>=this._pointerDownTime.length?!1:this.getPointerPressed(A)&&this.context.time.time-this._pointerDownTime[A]>this._longPressTimeThreshold}getIsMouse(A){return A<0||A>=this._pointerTypes.length?!1:this._pointerTypes[A]==="mouse"}getIsTouch(A){return A<0||A>=this._pointerTypes.length?!1:this._pointerTypes[A]==="touch"}getTouchesPressedCount(){let A=0;for(let e=0;e<this._pointerPressed.length;e++)this._pointerPressed[e]&&this.getIsTouch(e)&&A++;return A}getMouseWheelChanged(A=0){return A>=this._mouseWheelChanged.length?!1:this._mouseWheelChanged[A]}getMouseWheelDeltaY(A=0){return A>=this._mouseWheelDeltaY.length?0:this._mouseWheelDeltaY[A]}getPointerEvent(A){if(!(A>=this._pointerEvent.length))return this._pointerEvent[A]??void 0}*foreachPointerId(A){for(let e=0;e<this._pointerTypes.length;e++)if(this._pointerIsActive(e)){if(A!==void 0){const t=this._pointerTypes[e];if(Array.isArray(A)){let i=!1;for(const I of A)if(t===I){i=!0;break}if(!i)continue}else if(A!==t)continue}yield e}}*foreachTouchId(){for(let A=0;A<this._pointerTypes.length;A++)this._pointerTypes[A]==="touch"&&this._pointerIsActive[A]&&(yield A)}_pointerIsActive(A){return A<0?!1:this._pointerPressed[A]||this._pointerDown[A]||this._pointerUp[A]}onDownButton(A,e){let t=this._pressedStack.get(A);t||(t=[],this._pressedStack.set(A,t)),t.push(e)}onReleaseButton(A,e){const t=this._pressedStack.get(A);if(!t)return;const i=t.indexOf(e);i>=0&&t.splice(i,1)}getFirstPressedButtonForPointer(A){const e=this._pressedStack.get(A);if(e)return e[0]}getLatestPressedButtonForPointer(A){const e=this._pressedStack.get(A);if(e)return e[e.length-1]}getKeyDown(){for(const A in this.keysPressed){const e=this.keysPressed[A];if(e.startFrame===this.context.time.frameCount)return e.key}return null}getKeyPressed(){for(const A in this.keysPressed){const e=this.keysPressed[A];if(e.pressed)return e.key}return null}isKeyDown(A){var t;if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const e=this.getCodeForCommonKeyName(A);if(e!==null){for(const i of e)if(this.isKeyDown(i))return!0;return!1}return((t=this.keysPressed[A])==null?void 0:t.startFrame)===this.context.time.frameCount&&this.keysPressed[A].pressed}isKeyUp(A){var t;if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const e=this.getCodeForCommonKeyName(A);if(e!==null){for(const i of e)if(this.isKeyUp(i))return!0;return!1}return((t=this.keysPressed[A])==null?void 0:t.frame)===this.context.time.frameCount&&!this.keysPressed[A].pressed}isKeyPressed(A){var t;if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const e=this.getCodeForCommonKeyName(A);if(e!==null){for(const i of e)if(this.isKeyPressed(i))return!0;return!1}return(t=this.keysPressed[A])==null?void 0:t.pressed}getCodeForCommonKeyName(A){if(A.length===1){if(A>="0"&&A<="9")return["Digit"+A];if(A>="a"&&A<="z")return["Key"+A.toUpperCase()];if(A==" ")return["Space"]}switch(A){case"shift":case"Shift":return["ShiftLeft","ShiftRight"];case"control":case"Control":return["ControlLeft","ControlRight"];case"alt":case"Alt":return["AltLeft","AltRight"]}return null}createInputEvent(A){switch(A.type){case"pointerdown":Dg&&fi("Create Pointer down"),this.onDownButton(A.deviceIndex,A.button),this.onDown(A);break;case"pointermove":Dg&&fi("Create Pointer move"),this.onMove(A);break;case"pointerup":Dg&&fi("Create Pointer up"),this.onUp(A),this.onReleaseButton(A.deviceIndex,A.button);break}}convertScreenspaceToRaycastSpace(A){return A.x=(A.x-this.context.domX)/this.context.domWidth*2-1,A.y=-((A.y-this.context.domY)/this.context.domHeight)*2+1,A}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 A,e;window.removeEventListener("contextmenu",this.onContextMenu),(A=this._htmlEventSource)==null||A.removeEventListener("pointerdown",this.onPointerDown),window.removeEventListener("pointermove",this.onPointerMove),window.removeEventListener("pointerup",this.onPointerUp),window.removeEventListener("pointercancel",this.onPointerCancel),(e=this._htmlEventSource)==null||e.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 A=this.context.post_render_callbacks.indexOf(this.onEndOfFrame);A>=0&&this.context.post_render_callbacks.splice(A,1),this.unbindEvents()}canReceiveInput(A){var e;return A.target===((e=this.context.renderer)==null?void 0:e.domElement)||A.target===this.context.domElement||this.context.isInAR||this.context.isInAR&&A.target===document.body&&Ec()?!0:(Dg&&console.warn("CanReceiveInput:False for",A.target),!1)}getPointerId(A,e){return A.pointerType==="mouse"?0+(e??A.button):this.getPointerIndex(A.pointerId)}getButtonName(A){const e=A.button;if(A.pointerType==="mouse")switch(e){case 0:return"left";case 1:return"middle";case 2:return"right"}return"unknown"}getAndUpdateSpatialObjectForScreenPosition(A,e,t){let i=this._pointerSpace[A];i||(i=new DA,this._pointerSpace[A]=i),this._pointerSpace[A]=i;const I=this.context.mainCamera;if(I){const o=this.tempNearPlaneVector.set(e,t,-1);this.convertScreenspaceToRaycastSpace(o);const s=this.tempFarPlaneVector.set(o.x,o.y,1);o.unproject(I),s.unproject(I);const n=I.worldUp||dt(0,1,0).applyQuaternion(Jt(I));this.tempLookMatrix.lookAt(s,o,n),i.position.set(o.x,o.y,o.z),i.quaternion.setFromRotationMatrix(this.tempLookMatrix)}return i}isInRect(A){if(this.context.isInXR)return!0;const e=this.context.domElement.getBoundingClientRect(),t=A.clientX,i=A.clientY,I=t>=e.x&&t<=e.right&&i>=e.y&&i<=e.bottom;return Dg&&!I&&console.log("Not in rect",e,t,i),I}onDown(A){const e=A.pointerId;if(this.getPointerPressed(e)&&console.warn(`pointerId is already pressed: ${e}`,Dg?A:""),Dg&&console.log(A.pointerType,"DOWN",e),!!this.isInRect(A)){for(this.setPointerState(e,this._pointerPressed,!0),this.setPointerState(e,this._pointerDown,!0),this.setPointerStateT(e,this._pointerEvent,A.source);e>=this._pointerTypes.length;)this._pointerTypes.push(A.pointerType);for(this._pointerTypes[e]=A.pointerType;e>=this._pointerPositionDown.length;)this._pointerPositionDown.push(new tA);for(this._pointerPositionDown[e].set(A.clientX,A.clientY);e>=this._pointerPositions.length;)this._pointerPositions.push(new tA);this._pointerPositions[e].set(A.clientX,A.clientY),e>=this._pointerDownTime.length&&this._pointerDownTime.push(0),this._pointerDownTime[e]=this.context.time.time,this.updatePointerPosition(A),this.onDispatchEvent(A)}}onMove(A){const e=A.pointerId,t=this.getPointerPressed(e);t===!1&&!this.isInRect(A)||A.pointerType==="touch"&&!t||(this.updatePointerPosition(A),this.setPointerStateT(e,this._pointerEvent,A.source),this.onDispatchEvent(A))}onUp(A){const e=A.pointerId;if(!this.getPointerPressed(e)){Dg&&console.log(A.pointerType,"UP",e,"was not down");return}for(Dg&&console.log(A.pointerType,"UP",e),this.setPointerState(e,this._pointerPressed,!1),this.setPointerStateT(e,this._pointerEvent,A.source),this.setPointerState(e,this._pointerUp,!0);e>=this._pointerUsed.length;)this._pointerUsed.push(!1);if(this.setPointerState(e,this._pointerUsed,!1),this.updatePointerPosition(A),!this._pointerPositionDown[e]){Dg&&Ot("Received pointer up event without matching down event for button: "+e),console.warn("Received pointer up event without matching down event for button: "+e);return}const i=A.clientX-this._pointerPositionDown[e].x,I=A.clientY-this._pointerPositionDown[e].y;if(e>=this._pointerUpTime.length&&this._pointerUpTime.push(-99),Math.abs(i)<5&&Math.abs(I)<5){Dg&&console.log("CLICK",e),this.setPointerState(e,this._pointerClick,!0),A.isClick=!0;const o=this._pointerUpTime[e],s=this.context.time.time-o;s<this._doubleClickTimeThreshold&&s>0&&(this.setPointerState(e,this._pointerDoubleClick,!0),A.isDoubleClick=!0)}this._pointerUpTime[e]=this.context.time.time,this.onDispatchEvent(A)}updatePointerPosition(A){const e=A.pointerId;for(;e>=this._pointerPositions.length;)this._pointerPositions.push(new tA);for(;e>=this._pointerPositionsLastFrame.length;)this._pointerPositionsLastFrame.push(new tA);for(;e>=this._pointerPositionsDelta.length;)this._pointerPositionsDelta.push(new tA);const t=this._pointerPositionsLastFrame[e];t.copy(this._pointerPositions[e]);const i=this._pointerPositionsDelta[e];let I=A.clientX-t.x,o=A.clientY-t.y;if(A.source instanceof MouseEvent||A.source instanceof TouchEvent){const a=A.source;I===0&&a.movementX!==0&&(I=a.movementX||0),o===0&&a.movementY!==0&&(o=a.movementY||0)}i.x+=I,i.y+=o,this._pointerPositions[e].x=A.clientX,this._pointerPositions[e].y=A.clientY;const s=A.clientX,n=A.clientY;for(;e>=this._pointerPositionsRC.length;)this._pointerPositionsRC.push(new tA);const r=this._pointerPositionsRC[e];r.set(s,n),this.convertScreenspaceToRaycastSpace(r)}getPointerIndex(A){let e=-1;for(let t=0;t<this._pointerIds.length;t++){if(this._pointerIds[t]===A)return t;e===-1&&this._pointerIds[t]===-1&&(e=t)}return e!==-1?(this._pointerIds[e]=A,e):(Dg&&console.log("PUSH pointerId:",A),this._pointerIds.push(A),this._pointerIds.length-1)}setPointerState(A,e,t){e[A]=t}setPointerStateT(A,e,t){return e[A]=t,t}onDispatchEvent(A){const e=be.Current;try{be.Current=this.context,this.dispatchEvent(A)}finally{be.Current=e}}}const Bm=new fA().makeRotationY(Math.PI),bs=new GA().setFromAxisAngle(new y(0,1,0),Math.PI),$BA=gA("debugwebxr");class AQA{constructor(){B(this,"priority",-1e5);B(this,"gameObject");if(this.gameObject=new DA,this.gameObject.name="Implicit XR Rig",$BA){const A=Hx(16733661);A.position.y+=.5,this.gameObject.add(A)}}isXRRig(){return!0}get isActive(){return this.gameObject.visible}}const TC=gA("debugwebxr"),gS=gA("debugcustomgesture"),eQA="https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles",tQA="generic-trigger";class Yx{constructor(A,e,t){B(this,"xr");B(this,"inputSource");B(this,"index",0);B(this,"emitEvents",!0);B(this,"_connected",!0);B(this,"_isTracking",!1);B(this,"_hitTestSource");B(this,"_hasSelectEvent",!1);B(this,"_handJointPoses",new Map);B(this,"_gripPosition",new y);B(this,"_gripQuaternion",new GA);B(this,"_linearVelocity",new y);B(this,"_rayPosition",new y);B(this,"_rayQuaternion",new GA);B(this,"_gripWorldPosition",new y);B(this,"_gripWorldQuaternion",new GA);B(this,"_rayWorldPosition",new y);B(this,"_rayWorldQuaternion",new GA);B(this,"_ray");B(this,"_object");B(this,"model",null);B(this,"_debugAxesHelper",new Qs(.2));B(this,"onPointerHits",A=>{});B(this,"_needleGamepadButtons",{});B(this,"_buttonMap",new Map);B(this,"_motioncontroller");B(this,"_layout");B(this,"getMotionController");B(this,"_selectButtonIndex");B(this,"_squeezeButtonIndex");B(this,"onSelectStart",A=>{var i,I,o,s;if(this.inputSource!==A.inputSource)return;this.onUpdateFrame(A.frame),this._hasSelectEvent=!0;const e=(i=this._layout)==null?void 0:i.selectComponentId,t=(s=(o=(I=this._layout)==null?void 0:I.components[e])==null?void 0:o.gamepadIndices)==null?void 0:s.button;t!==void 0&&(this._selectButtonIndex=t),!gS&&(TC&&fe.DrawDirection(this.rayWorldPosition,dt(0,.01,1).applyQuaternion(this.rayWorldQuaternion),16711680,10),this.emitPointerEvent(pi.PointerDown,this._selectButtonIndex||0,"xr-standard-trigger",!0,A))});B(this,"onSelectEnd",A=>{gS||this.inputSource===A.inputSource&&this.emitPointerEvent(pi.PointerUp,this._selectButtonIndex||0,"xr-standard-trigger",!0,A)});B(this,"onSequeezeStart",A=>{var e,t,i;this.inputSource===A.inputSource&&(this._squeezeButtonIndex=(i=(t=(e=this._layout)==null?void 0:e.components["xr-standard-squeeze"])==null?void 0:t.gamepadIndices)==null?void 0:i.button,this._squeezeButtonIndex!==void 0&&(TC&&fe.DrawDirection(this.rayWorldPosition,dt(0,.01,1).applyQuaternion(this.rayWorldQuaternion),255,10),this.emitPointerEvent(pi.PointerDown,this._squeezeButtonIndex||0,"xr-standard-squeeze",!0,A)))});B(this,"onSequeezeEnd",A=>{this.inputSource===A.inputSource&&this._squeezeButtonIndex!==void 0&&this.emitPointerEvent(pi.PointerUp,this._squeezeButtonIndex||0,"xr-standard-squeeze",!0,A)});B(this,"states",{});B(this,"_didMoveLastFrame",!1);B(this,"_lastPointerMovePosition",new y);B(this,"_lastPointerMoveQuaternion",new GA);B(this,"pointerInit");var i,I,o;this.xr=A,this.inputSource=e,this.index=t,this._object=new DA,TC&&this._object.add(this._debugAxesHelper),this.xr.context.scene.add(this._object),this._ray=new xo,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(),this.xr.mode==="immersive-ar"&&this.inputSource.targetRayMode==="tracked-pointer"&&((o=(I=(i=this.xr.session).requestHitTestSourceForTransientInput)==null?void 0:I.call(i,{profile:this.inputSource.profiles[0],offsetRay:new XRRay}))==null||o.then(s=>this._hitTestSource=s))}get context(){return this.xr.context}get connected(){return this._connected}get isTracking(){return this._isTracking}get gamepad(){return this.inputSource.gamepad}get isHand(){return this.inputSource.hand!=null}get hand(){return 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.inputSource.handedness}get isRight(){return this.side==="right"}get isLeft(){return this.side==="left"}get hitTestSource(){return this._hitTestSource}get hasSelectEvent(){return this._hasSelectEvent}getHitTest(){return this.xr.getHitTest(this)}getHandJointPose(A){var t,i;if(!this.hand||!((t=this.xr.frame)!=null&&t.getJointPose)||!this.xr.referenceSpace)return null;let e=(i=this._handJointPoses)==null?void 0:i.get(A);return e||(e=this.xr.frame.getJointPose(A,this.xr.referenceSpace),e&&this._handJointPoses.set(A,e),e)}get gripPosition(){return dt(this._gripPosition).applyMatrix4(Bm)}get gripQuaternion(){return gc(this._gripQuaternion).premultiply(bs)}get gripLinearVelocity(){return dt(this._linearVelocity).applyQuaternion(bs)}get rayPosition(){return dt(this._rayPosition).applyMatrix4(Bm)}get rayQuaternion(){return gc(this._rayQuaternion).premultiply(bs)}get gripWorldPosition(){return dt(this._gripWorldPosition)}get gripWorldQuaternion(){return gc(this._gripWorldQuaternion)}get rayWorldPosition(){return dt(this._rayWorldPosition)}updateRayWorldPosition(){var e;const A=(e=this.xr.context.mainCamera)==null?void 0:e.parent;this._rayWorldPosition.copy(this._rayPosition),A&&this._rayWorldPosition.applyMatrix4(A.matrixWorld)}get rayWorldQuaternion(){return gc(this._rayWorldQuaternion)}updateRayWorldQuaternion(){var t;const A=(t=this.xr.context.mainCamera)==null?void 0:t.parent,e=A?Jt(A):void 0;this._rayWorldQuaternion.copy(this._rayQuaternion).multiply(bs),e&&this._rayWorldQuaternion.premultiply(e)}get ray(){return this._ray.origin.copy(this.rayWorldPosition),this._ray.direction.copy(dt(0,0,1).applyQuaternion(this.rayWorldQuaternion)),this._ray}get object(){return this._object}async getModelUrl(){var A;return(A=this.getMotionController)==null?void 0:A.then(e=>(e==null?void 0:e.assetUrl)||null)}onUpdate(A){this.onUpdateFrame(A),this.updateInputEvents(),this.onUpdateMove()}onRenderDebug(){var i;fe.DrawWireSphere(this.rayWorldPosition,.02),fe.DrawDirection(this.rayWorldPosition,dt(0,0,10).applyQuaternion(this.rayWorldQuaternion));const A=this.gripWorldPosition.sub(this.object.worldForward.multiplyScalar(.1)),e=this.inputSource.profiles.join(`
5151
+ */var KBA=function(g){return g!=null&&(QW(g)||bBA(g)||!!g._isBuffer)};function QW(g){return!!g.constructor&&typeof g.constructor.isBuffer=="function"&&g.constructor.isBuffer(g)}function bBA(g){return typeof g.readFloatLE=="function"&&typeof g.slice=="function"&&QW(g.slice(0,0))}(function(){var g=FBA,A=DY.utf8,e=KBA,t=DY.bin,i=function(I,o){I.constructor==String?o&&o.encoding==="binary"?I=t.stringToBytes(I):I=A.stringToBytes(I):e(I)?I=Array.prototype.slice.call(I,0):!Array.isArray(I)&&I.constructor!==Uint8Array&&(I=I.toString());for(var s=g.bytesToWords(I),n=I.length*8,r=1732584193,a=-271733879,C=-1732584194,Q=271733878,c=0;c<s.length;c++)s[c]=(s[c]<<8|s[c]>>>24)&16711935|(s[c]<<24|s[c]>>>8)&4278255360;s[n>>>5]|=128<<n%32,s[(n+64>>>9<<4)+14]=n;for(var E=i._ff,h=i._gg,l=i._hh,d=i._ii,c=0;c<s.length;c+=16){var p=r,u=a,f=C,w=Q;r=E(r,a,C,Q,s[c+0],7,-680876936),Q=E(Q,r,a,C,s[c+1],12,-389564586),C=E(C,Q,r,a,s[c+2],17,606105819),a=E(a,C,Q,r,s[c+3],22,-1044525330),r=E(r,a,C,Q,s[c+4],7,-176418897),Q=E(Q,r,a,C,s[c+5],12,1200080426),C=E(C,Q,r,a,s[c+6],17,-1473231341),a=E(a,C,Q,r,s[c+7],22,-45705983),r=E(r,a,C,Q,s[c+8],7,1770035416),Q=E(Q,r,a,C,s[c+9],12,-1958414417),C=E(C,Q,r,a,s[c+10],17,-42063),a=E(a,C,Q,r,s[c+11],22,-1990404162),r=E(r,a,C,Q,s[c+12],7,1804603682),Q=E(Q,r,a,C,s[c+13],12,-40341101),C=E(C,Q,r,a,s[c+14],17,-1502002290),a=E(a,C,Q,r,s[c+15],22,1236535329),r=h(r,a,C,Q,s[c+1],5,-165796510),Q=h(Q,r,a,C,s[c+6],9,-1069501632),C=h(C,Q,r,a,s[c+11],14,643717713),a=h(a,C,Q,r,s[c+0],20,-373897302),r=h(r,a,C,Q,s[c+5],5,-701558691),Q=h(Q,r,a,C,s[c+10],9,38016083),C=h(C,Q,r,a,s[c+15],14,-660478335),a=h(a,C,Q,r,s[c+4],20,-405537848),r=h(r,a,C,Q,s[c+9],5,568446438),Q=h(Q,r,a,C,s[c+14],9,-1019803690),C=h(C,Q,r,a,s[c+3],14,-187363961),a=h(a,C,Q,r,s[c+8],20,1163531501),r=h(r,a,C,Q,s[c+13],5,-1444681467),Q=h(Q,r,a,C,s[c+2],9,-51403784),C=h(C,Q,r,a,s[c+7],14,1735328473),a=h(a,C,Q,r,s[c+12],20,-1926607734),r=l(r,a,C,Q,s[c+5],4,-378558),Q=l(Q,r,a,C,s[c+8],11,-2022574463),C=l(C,Q,r,a,s[c+11],16,1839030562),a=l(a,C,Q,r,s[c+14],23,-35309556),r=l(r,a,C,Q,s[c+1],4,-1530992060),Q=l(Q,r,a,C,s[c+4],11,1272893353),C=l(C,Q,r,a,s[c+7],16,-155497632),a=l(a,C,Q,r,s[c+10],23,-1094730640),r=l(r,a,C,Q,s[c+13],4,681279174),Q=l(Q,r,a,C,s[c+0],11,-358537222),C=l(C,Q,r,a,s[c+3],16,-722521979),a=l(a,C,Q,r,s[c+6],23,76029189),r=l(r,a,C,Q,s[c+9],4,-640364487),Q=l(Q,r,a,C,s[c+12],11,-421815835),C=l(C,Q,r,a,s[c+15],16,530742520),a=l(a,C,Q,r,s[c+2],23,-995338651),r=d(r,a,C,Q,s[c+0],6,-198630844),Q=d(Q,r,a,C,s[c+7],10,1126891415),C=d(C,Q,r,a,s[c+14],15,-1416354905),a=d(a,C,Q,r,s[c+5],21,-57434055),r=d(r,a,C,Q,s[c+12],6,1700485571),Q=d(Q,r,a,C,s[c+3],10,-1894986606),C=d(C,Q,r,a,s[c+10],15,-1051523),a=d(a,C,Q,r,s[c+1],21,-2054922799),r=d(r,a,C,Q,s[c+8],6,1873313359),Q=d(Q,r,a,C,s[c+15],10,-30611744),C=d(C,Q,r,a,s[c+6],15,-1560198380),a=d(a,C,Q,r,s[c+13],21,1309151649),r=d(r,a,C,Q,s[c+4],6,-145523070),Q=d(Q,r,a,C,s[c+11],10,-1120210379),C=d(C,Q,r,a,s[c+2],15,718787259),a=d(a,C,Q,r,s[c+9],21,-343485551),r=r+p>>>0,a=a+u>>>0,C=C+f>>>0,Q=Q+w>>>0}return g.endian([r,a,C,Q])};i._ff=function(I,o,s,n,r,a,C){var Q=I+(o&s|~o&n)+(r>>>0)+C;return(Q<<a|Q>>>32-a)+o},i._gg=function(I,o,s,n,r,a,C){var Q=I+(o&n|s&~n)+(r>>>0)+C;return(Q<<a|Q>>>32-a)+o},i._hh=function(I,o,s,n,r,a,C){var Q=I+(o^s^n)+(r>>>0)+C;return(Q<<a|Q>>>32-a)+o},i._ii=function(I,o,s,n,r,a,C){var Q=I+(s^(o|~n))+(r>>>0)+C;return(Q<<a|Q>>>32-a)+o},i._blocksize=16,i._digestsize=16,CW.exports=function(I,o){if(I==null)throw new Error("Illegal argument "+I);var s=g.wordsToBytes(i(I,o));return o&&o.asBytes?s:o&&o.asString?t.bytesToString(s):g.bytesToHex(s)}})();var JBA=CW.exports;const xBA=tM(JBA);class kK{constructor(A,e,t,i){B(this,"success");B(this,"filename");B(this,"hash");B(this,"size");B(this,"url");this.success=A,this.filename=e,this.hash=t,this.size=i}}async function cW(g,A){const e=await g.arrayBuffer(),t=Lx(e),i=g.name.split(".").pop(),I=t+"."+i,o=g.name.split(".").shift();console.assert(o!==void 0);const s={alias:o,filename:I},r=await(await fetch(A+"/exists",{method:"POST",body:JSON.stringify(s)})).json();if(r.success||console.warn("exists check did fail"),r.exists)return console.log("file already exists",t),new kK(!0,I,t,g.size);console.log("begin uploading file",o,g.size);const a=new FormData;a.append("file",g);const C={};C.filesize=g.size,o&&(C.alias=o);const c=await(await fetch(A+"/upload/file",{method:"POST",body:a,headers:C})).json();if((c==null?void 0:c.success)===!1)return c.message!==void 0?console.error("Upload failed:",c.message):console.error("Upload failed"),null;console.assert(c.hash_sum===t,"hash sum did not match","received:",c.hash_sum,"expected:",t),c.success&&console.log("successfully uploaded",t,c.id);const E=new kK(c.success,I,t,g.size);return E.url=A,E}function Lx(g){return xBA(new Uint8Array(g))}async function _x(g,A,e,t,i=!1){try{const I=await fetch(t+"/download/file",{method:"POST",body:g});if(I.status!==200)return console.error("download failed",I),null;const o=await I.blob(),s=await o.arrayBuffer();i||console.assert(o.size===e,"size mismatch","expected:",e,"got:",o.size);const n=Lx(s);return i||console.assert(n===A,"hash mismatch, downloaded file is invalid"),o.arrayBuffer()}catch(I){console.error(I)}return null}async function EW(g,A){var a;const e=await fetch(g),t=(a=e.body)==null?void 0:a.getReader(),i=e.headers.get("Content-Length"),I=i?parseInt(i):0;if(!t)return null;let o=0;const s=[];for(;;){const{done:C,value:Q}=await t.read();if(Q&&(s.push(Q),o+=Q.length,A.call(null,new ProgressEvent("progress",{loaded:o,total:I}))),C)break}const n=new Uint8Array(o);let r=0;for(const C of s)n.set(C,r),r+=C.length;return n}const _C=gA("debugaddressables");class lW{constructor(A){B(this,"_context");B(this,"_assetReferences",{});B(this,"preUpdate",()=>{});this._context=A,this._context.pre_update_callbacks.push(this.preUpdate)}dispose(){const A=this._context.pre_update_callbacks.indexOf(this.preUpdate);A>=0&&this._context.pre_update_callbacks.splice(A,1);for(const e in this._assetReferences){const t=this._assetReferences[e];t==null||t.unload()}this._assetReferences={}}findAssetReference(A){return this._assetReferences[A]||null}registerAssetReference(A){return A.uri&&(this._assetReferences[A.uri]?console.warn("Asset reference already registered",A):this._assetReferences[A.uri]=A),A}unregisterAssetReference(A){A.uri&&delete this._assetReferences[A.uri]}}const bU=Symbol("assetReference"),XQ=class{constructor(A,e,t=null){B(this,"_loading");B(this,"_asset");B(this,"_glbRoot");B(this,"_url");B(this,"_progressListeners",[]);B(this,"_hash");B(this,"_hashedUri");B(this,"_isLoadingRawBinary",!1);B(this,"_rawBinary");this._url=A,this._hash=e,A.includes("?v=")?this._hashedUri=A:this._hashedUri=e?A+"?v="+e:A,t!==null&&(this.asset=t),LZ(this._url,this.onResolvePrefab.bind(this))}static getOrCreateFromUrl(A,e){if(!e&&(e=be.Current,!e))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 t=e.addressables,i=t.findAssetReference(A);if(i)return i;const I=new XQ(A,e.hash);return t.registerAssetReference(I),I}static getOrCreate(A,e,t){if(typeof A=="string"){if(!t&&(t=be.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.')}else t=A.context,A=A.sourceId;const i=OB(A,e);_C&&console.log("GetOrCreate Addressable from",A,e,"FinalPath=",i);const I=t.addressables,o=I.findAssetReference(i);if(o)return o;const s=new XQ(i,t.hash);return I.registerAssetReference(s),s}get asset(){return this._glbRoot??this._asset}set asset(A){this._asset=A}get uri(){return this._url}get url(){return this._url}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(A){return A===this.uri&&(this.mustLoad&&await this.loadAssetAsync(),this.asset)?this.asset:null}get mustLoad(){return!this.asset||this.asset.__destroyed===!0||Yc(this.asset)===!0}isLoaded(){return this._rawBinary||this.asset!==void 0}unload(){this.asset&&(_C&&console.log("Unload",this.asset),this.asset.scene&&Vs(this.asset.scene,!0,!0),Vs(this.asset,!0,!0)),this.asset=null,this._rawBinary=void 0,this._glbRoot=null,this._loading=void 0,be.Current&&be.Current.addressables.unregisterAssetReference(this)}async preload(){if(!this.mustLoad||this._isLoadingRawBinary)return null;if(this._rawBinary!==void 0)return this._rawBinary;this._isLoadingRawBinary=!0,_C&&console.log("Preload",this._hashedUri);const A=await EW(this._hashedUri,e=>{this.raiseProgressEvent(e)});return this._rawBinary=(A==null?void 0:A.buffer)??null,this._isLoadingRawBinary=!1,this._rawBinary}async loadAssetAsync(A){if(_C&&console.log("loadAssetAsync",this.uri),!this.mustLoad)return this.asset;if(A&&this._progressListeners.push(A),this._loading!==void 0)return this._loading.then(i=>this.asset);const e=be.Current;this._rawBinary?(this._loading=Ln().parseSync(e,this._rawBinary,this.uri,null),this.raiseProgressEvent(new ProgressEvent("progress",{loaded:this._rawBinary.byteLength,total:this._rawBinary.byteLength}))):(_C&&console.log("Load async",this.uri),this._loading=Ln().loadSync(e,this._hashedUri,this.uri,null,i=>{this.raiseProgressEvent(i)}));const t=await this._loading;if(this._progressListeners.length=0,this._glbRoot=this.tryGetActualGameObjectRoot(t),this._loading=void 0,t)return t[bU]=this,this._glbRoot&&(this._glbRoot[bU]=this),this.asset&&(this.asset[bU]=this),nm(e),t.scene!==void 0&&(this.asset=t),this.asset}async instantiate(A){return this.onInstantiate(A,!1)}async instantiateSynced(A,e=!0){return this.onInstantiate(A,!0,e)}beginListenDownload(A){this._progressListeners.indexOf(A)<0&&this._progressListeners.push(A)}endListenDownload(A){const e=this._progressListeners.indexOf(A);e>=0&&this._progressListeners.splice(e,1)}raiseProgressEvent(A){for(const e of this._progressListeners)e(this,A)}async onInstantiate(A,e=!1,t){const i=be.Current,I=new Wn;if(A instanceof DA?I.parent=A:A&&(Object.assign(I,A),I.cloneAssign(A)),I.parent||(I.parent=i.scene),this.mustLoad&&await this.loadAssetAsync(),_C&&console.log("Instantiate",this.uri,"parent:",A),this.asset){_C&&console.log("Add to scene",this.asset);let o=XQ.currentlyInstantiating.get(this.uri);if(o!==void 0&&o>=1e4)return console.error("Recursive or too many instantiations of "+this.uri+" in the same frame ("+o+")"),null;try{if(o===void 0&&(o=0),o+=1,XQ.currentlyInstantiating.set(this.uri,o),e){I.context=i;const s=this.asset;s.guid=this.uri;const n=iv(s,I,void 0,t);if(n)return n}else{const s=Qd(this.asset,I);if(s)return s}}finally{i.post_render_callbacks.push(()=>{o===void 0||o<0?o=0:o-=1,XQ.currentlyInstantiating.set(this.uri,o)})}}else _C&&console.warn("Failed to load asset",this.uri);return null}tryGetActualGameObjectRoot(A){if(A&&A.scene){const e=A.scene;return e.isGroup&&e.children.length===1&&e.children[0].name+"glb"===e.name?e.children[0]:e}return null}};let et=XQ;B(et,"currentlyInstantiating",new Map);class vBA extends on{constructor(){super([et],"AssetReferenceSerializer")}onSerialize(A,e){if(A&&A.uri!==void 0&&typeof A.uri=="string")return A.uri}onDeserialize(A,e){if(typeof A=="string")return e.context?e.gltfId?et.getOrCreate(e.gltfId,A,e.context):(console.error("Missing source id"),null):(console.error("Missing context"),null);if(A instanceof DA){if(!e.context)return console.error("Missing context"),null;if(!e.gltfId)return console.error("Missing source id"),null;const t=A,i=e.context,I=t.guid??t.uuid,o=i.addressables.findAssetReference(I);if(o)return o;const s=new et(I,void 0,t);return i.addressables.registerAssetReference(s),s}return null}}new vBA;const qBA=Promise.resolve(null),Zp=class{constructor(A){B(this,"url");B(this,"_bitmap");B(this,"_bitmapObject");B(this,"loader",null);this.url=A}static getOrCreate(A){let e=Zp.imageReferences.get(A);return e||(e=new Zp(A),Zp.imageReferences.set(A,e)),e}dispose(){this._bitmapObject&&this._bitmapObject.close(),this._bitmap=void 0}createHTMLImage(){const A=new Image;return A.src=this.url,A}createTexture(){return this.url?(this.loader||(this.loader=new Rr),this.loader.setCrossOrigin("anonymous"),this.loader.loadAsync(this.url)):qBA}getBitmap(){return this._bitmap?this._bitmap:(this._bitmap=new Promise((A,e)=>{const t=document.createElement("img");t.addEventListener("load",()=>{this._bitmap=createImageBitmap(t).then(i=>(this._bitmapObject=i,A(i),i))}),t.addEventListener("error",i=>{console.error("Failed to load image:"+this.url,i),A(null)}),t.src=this.url}),this._bitmap)}};let lh=Zp;B(lh,"imageReferences",new Map);class hW extends on{constructor(){super([lh],"ImageReferenceSerializer")}onSerialize(A,e){return null}onDeserialize(A,e){if(typeof A=="string"){const t=OB(e.gltfId,A);return lh.getOrCreate(t)}}}new hW;const jp=class{constructor(A){B(this,"url");B(this,"res");this.url=A}static getOrCreate(A){let e=jp.cache.get(A);return e||(e=new jp(A),jp.cache.set(A,e)),e}async loadRaw(){return this.res||(this.res=fetch(this.url)),this.res.then(A=>A.blob())}async loadText(){return this.res||(this.res=fetch(this.url)),this.res.then(A=>A.text())}};let hh=jp;B(hh,"cache",new Map);class dW extends on{constructor(){super([hh],"FileReferenceSerializer")}onSerialize(A,e){return null}onDeserialize(A,e){if(typeof A=="string"){const t=OB(e.gltfId,A);return hh.getOrCreate(t)}}}new dW;class LBA{constructor(A){B(this,"context");B(this,"mixers",[]);this.context=A}onDestroy(){this.mixers.forEach(A=>A.stopAllAction()),this.mixers.length=0}registerAnimationMixer(A){if(!A){console.warn("AnimationsRegistry.registerAnimationMixer called with null or undefined mixer");return}this.mixers.includes(A)||this.mixers.push(A)}unregisterAnimationMixer(A){if(!A)return;const e=this.mixers.indexOf(A);e!==-1&&this.mixers.splice(e,1)}}class vh{static tryGetActionsFromMixer(A){const e=A._actions;return e||null}static tryGetAnimationClipsFromObjectHierarchy(A,e){if(e||(e=new Array),A)A.animations&&e.push(...A.animations);else return e;if(A.children)for(const t of A.children)this.tryGetAnimationClipsFromObjectHierarchy(t,e);return e}static assignAnimationsFromFile(A,e){if(!A||!A.animations)return;for(let i=0;i<A.animations.length;i++){const I=A.animations[i];if(!(!I.tracks||I.tracks.length<=0))for(const o in I.tracks){const s=I.tracks[o],n=Xe.parseTrackName(s.name);let r=Xe.findNode(A.scene,n.nodeName);if(!r){const C=s.__objectName??s.name.substring(0,s.name.indexOf("."));if(r=A.scene.getObjectByProperty("uuid",C),!r)continue}let a=t(r);if(!a){if(!(e!=null&&e.createAnimationComponent)){console.warn("No AnimationComponent found in parent hierarchy of object and no 'createAnimationComponent' callback was provided in options.");continue}a=e.createAnimationComponent(A.scene,I)}a.addClip&&a.addClip(I)}}function t(i){var o;if(!i)return null;const I=(o=i.userData)==null?void 0:o.components;if(I&&I.length>0){for(let s=0;s<I.length;s++)if(I[s].isAnimationComponent===!0)return i}return t(i.parent)}}}const qh=[];function iM(g){qh.indexOf(g)===-1&&qh.push(g)}function _BA(g){const A=qh.indexOf(g);A!==-1&&qh.splice(A,1)}const Lh=[];function Tx(g){Lh.indexOf(g)===-1&&Lh.push(g)}function TBA(g){const A=Lh.indexOf(g);A!==-1&&Lh.splice(A,1)}function uW(g){globalThis.dispatchEvent(new CustomEvent("needle-xrsession-start",{detail:g}));for(let A=0;A<qh.length;A++)qh[A](g)}function pW(g){globalThis.dispatchEvent(new CustomEvent("needle-xrsession-end",{detail:g}));for(let A=0;A<Lh.length;A++)Lh[A](g)}const Yg={Handedness:Object.freeze({NONE:"none",LEFT:"left",RIGHT:"right"}),ComponentState:Object.freeze({DEFAULT:"default",TOUCHED:"touched",PRESSED:"pressed"}),ComponentProperty:Object.freeze({BUTTON:"button",X_AXIS:"xAxis",Y_AXIS:"yAxis",STATE:"state"}),ComponentType:Object.freeze({TRIGGER:"trigger",SQUEEZE:"squeeze",TOUCHPAD:"touchpad",THUMBSTICK:"thumbstick",BUTTON:"button"}),ButtonTouchThreshold:.05,AxisTouchThreshold:.1,VisualResponseProperty:Object.freeze({TRANSFORM:"transform",VISIBILITY:"visibility"})};async function fW(g){const A=await fetch(g);if(A.ok)return A.json();throw new Error(A.statusText)}async function HBA(g){if(!g)throw new Error("No basePath supplied");return await fW(`${g}/profilesList.json`)}async function YBA(g,A,e=null,t=!0){if(!g)throw new Error("No xrInputSource supplied");if(!A)throw new Error("No basePath supplied");const i=await HBA(A);let I;if(g.profiles.some(n=>{const r=i[n];return r&&(I={profileId:n,profilePath:`${A}/${r.path}`,deprecated:!!r.deprecated}),!!I}),!I){if(!e)throw new Error("No matching profile name found");const n=i[e];if(!n)throw new Error(`No matching profile name found and default profile "${e}" missing.`);I={profileId:e,profilePath:`${A}/${n.path}`,deprecated:!!n.deprecated}}const o=await fW(I.profilePath);let s;if(t){let n;if(g.handedness==="any"?n=o.layouts[Object.keys(o.layouts)[0]]:n=o.layouts[g.handedness],!n)throw new Error(`No matching handedness, ${g.handedness}, in profile ${I.profileId}`);n.assetPath&&(s=I.profilePath.replace("profile.json",n.assetPath))}return{profile:o,assetPath:s}}const OBA={xAxis:0,yAxis:0,button:0,state:Yg.ComponentState.DEFAULT};function PBA(g=0,A=0){let e=g,t=A;if(Math.sqrt(g*g+A*A)>1){const o=Math.atan2(A,g);e=Math.cos(o),t=Math.sin(o)}return{normalizedXAxis:e*.5+.5,normalizedYAxis:t*.5+.5}}let WBA=class{constructor(A){this.componentProperty=A.componentProperty,this.states=A.states,this.valueNodeName=A.valueNodeName,this.valueNodeProperty=A.valueNodeProperty,this.valueNodeProperty===Yg.VisualResponseProperty.TRANSFORM&&(this.minNodeName=A.minNodeName,this.maxNodeName=A.maxNodeName),this.value=0,this.updateFromComponent(OBA)}updateFromComponent({xAxis:A,yAxis:e,button:t,state:i}){const{normalizedXAxis:I,normalizedYAxis:o}=PBA(A,e);switch(this.componentProperty){case Yg.ComponentProperty.X_AXIS:this.value=this.states.includes(i)?I:.5;break;case Yg.ComponentProperty.Y_AXIS:this.value=this.states.includes(i)?o:.5;break;case Yg.ComponentProperty.BUTTON:this.value=this.states.includes(i)?t:0;break;case Yg.ComponentProperty.STATE:this.valueNodeProperty===Yg.VisualResponseProperty.VISIBILITY?this.value=this.states.includes(i):this.value=this.states.includes(i)?1:0;break;default:throw new Error(`Unexpected visualResponse componentProperty ${this.componentProperty}`)}}},ZBA=class{constructor(A,e){if(!A||!e||!e.visualResponses||!e.gamepadIndices||Object.keys(e.gamepadIndices).length===0)throw new Error("Invalid arguments supplied");this.id=A,this.type=e.type,this.rootNodeName=e.rootNodeName,this.touchPointNodeName=e.touchPointNodeName,this.visualResponses={},Object.keys(e.visualResponses).forEach(t=>{const i=new WBA(e.visualResponses[t]);this.visualResponses[t]=i}),this.gamepadIndices=Object.assign({},e.gamepadIndices),this.values={state:Yg.ComponentState.DEFAULT,button:this.gamepadIndices.button!==void 0?0:void 0,xAxis:this.gamepadIndices.xAxis!==void 0?0:void 0,yAxis:this.gamepadIndices.yAxis!==void 0?0:void 0}}get data(){return{id:this.id,...this.values}}updateFromGamepad(A){if(this.values.state=Yg.ComponentState.DEFAULT,this.gamepadIndices.button!==void 0&&A.buttons.length>this.gamepadIndices.button){const e=A.buttons[this.gamepadIndices.button];this.values.button=e.value,this.values.button=this.values.button<0?0:this.values.button,this.values.button=this.values.button>1?1:this.values.button,e.pressed||this.values.button===1?this.values.state=Yg.ComponentState.PRESSED:(e.touched||this.values.button>Yg.ButtonTouchThreshold)&&(this.values.state=Yg.ComponentState.TOUCHED)}this.gamepadIndices.xAxis!==void 0&&A.axes.length>this.gamepadIndices.xAxis&&(this.values.xAxis=A.axes[this.gamepadIndices.xAxis],this.values.xAxis=this.values.xAxis<-1?-1:this.values.xAxis,this.values.xAxis=this.values.xAxis>1?1:this.values.xAxis,this.values.state===Yg.ComponentState.DEFAULT&&Math.abs(this.values.xAxis)>Yg.AxisTouchThreshold&&(this.values.state=Yg.ComponentState.TOUCHED)),this.gamepadIndices.yAxis!==void 0&&A.axes.length>this.gamepadIndices.yAxis&&(this.values.yAxis=A.axes[this.gamepadIndices.yAxis],this.values.yAxis=this.values.yAxis<-1?-1:this.values.yAxis,this.values.yAxis=this.values.yAxis>1?1:this.values.yAxis,this.values.state===Yg.ComponentState.DEFAULT&&Math.abs(this.values.yAxis)>Yg.AxisTouchThreshold&&(this.values.state=Yg.ComponentState.TOUCHED)),Object.values(this.visualResponses).forEach(e=>{e.updateFromComponent(this.values)})}},jBA=class{constructor(A,e,t){if(!A)throw new Error("No xrInputSource supplied");if(!e)throw new Error("No profile supplied");this.xrInputSource=A,this.assetUrl=t,this.id=e.profileId,this.layoutDescription=e.layouts[A.handedness],this.components={},Object.keys(this.layoutDescription.components).forEach(i=>{const I=this.layoutDescription.components[i];this.components[i]=new ZBA(i,I)}),this.updateFromGamepad()}get gripSpace(){return this.xrInputSource.gripSpace}get targetRaySpace(){return this.xrInputSource.targetRaySpace}get data(){const A=[];return Object.values(this.components).forEach(e=>{A.push(e.data)}),A}updateFromGamepad(){Object.values(this.components).forEach(A=>{A.updateFromGamepad(this.xrInputSource.gamepad)})}};const to=new y,yY=new y,wY=new GA,zBA=gA("debuggizmos"),$n=8947848,mn=class{constructor(){}static isGizmo(A){return A[MK]!==void 0}static DrawLabel(A,e,t=.05,i=0,I,o,s){var a;if(!mn.enabled)return null;I||(I=$n);const n=((a=ye.active)==null?void 0:a.rigScale)??1,r=Ti.getTextLabel(i,e,t*n,I,o);return s instanceof DA&&s.add(r),r.position.x=A.x,r.position.y=A.y,r.position.z=A.z,r}static DrawRay(A,e,t=$n,i=0,I=!0){if(!mn.enabled)return;const o=Ti.getLine(i),s=o.geometry.getAttribute("position");s.setXYZ(0,A.x,A.y,A.z),to.set(e.x,e.y,e.z).multiplyScalar(999999999),s.setXYZ(1,A.x+to.x,A.y+to.y,A.z+to.z),s.needsUpdate=!0,o.material.color.set(t),o.material.depthTest=I,o.material.depthWrite=!1}static DrawDirection(A,e,t=$n,i=0,I=!0,o=1){if(!mn.enabled)return;const s=Ti.getLine(i),n=s.geometry.getAttribute("position");n.setXYZ(0,A.x,A.y,A.z),e.w!==void 0?(to.set(0,0,-o),wY.set(e.x,e.y,e.z,e.w),to.applyQuaternion(wY)):(to.set(e.x,e.y,e.z),to.multiplyScalar(o)),n.setXYZ(1,A.x+to.x,A.y+to.y,A.z+to.z),n.needsUpdate=!0,s.material.color.set(t),s.material.depthTest=I,s.material.depthWrite=!1}static DrawLine(A,e,t=$n,i=0,I=!0){if(!mn.enabled)return;const o=Ti.getLine(i),s=o.geometry.getAttribute("position");s.setXYZ(0,A.x,A.y,A.z),s.setXYZ(1,e.x,e.y,e.z),s.needsUpdate=!0,o.material.color.set(t),o.material.depthTest=I,o.material.depthWrite=!1,o.material.fog=!1}static DrawWireSphere(A,e,t=$n,i=0,I=!0){if(!mn.enabled)return;const o=Ti.getSphere(e,i,!0);Tc(o,A.x,A.y,A.z),o.material.color.set(t),o.material.depthTest=I,o.material.depthWrite=!1,o.material.fog=!1}static DrawSphere(A,e,t=$n,i=0,I=!0){if(!mn.enabled)return;const o=Ti.getSphere(e,i,!1);Tc(o,A.x,A.y,A.z),o.material.color.set(t),o.material.depthTest=I,o.material.depthWrite=!1}static DrawWireBox(A,e,t=$n,i=0,I=!0){if(!mn.enabled)return;const o=Ti.getBox(i);o.position.set(A.x,A.y,A.z),o.scale.set(e.x,e.y,e.z),o.material.color.set(t),o.material.depthTest=I,o.material.wireframe=!0,o.material.depthWrite=!1,o.material.fog=!1}static DrawWireBox3(A,e=$n,t=0,i=!0){if(!mn.enabled)return;const I=Ti.getBox(t);I.position.copy(A.getCenter(to)),I.scale.copy(A.getSize(to)),I.material.color.set(e),I.material.depthTest=i,I.material.wireframe=!0,I.material.depthWrite=!1,I.material.fog=!1}static DrawArrow(A,e,t=$n,i=0,I=!0,o=!1){if(!mn.enabled)return;const s=Ti.getArrowHead(i);s.position.set(e.x,e.y,e.z),s.quaternion.setFromUnitVectors(this._up.set(0,1,0),to.set(e.x,e.y,e.z).sub(yY.set(A.x,A.y,A.z)).normalize());const r=to.set(e.x,e.y,e.z).sub(yY.set(A.x,A.y,A.z)).length()*.1;s.scale.set(r,r,r),s.material.color.set(t),s.material.depthTest=I,s.material.wireframe=o,this.DrawLine(A,e,t,i,I)}static DrawWireMesh(A){const e=Ti.getMesh(A.duration??0);"mesh"in A?(e.geometry=A.mesh.geometry,e.matrix.copy(A.mesh.matrixWorld)):(e.geometry=A.geometry,e.matrix.copy(A.matrix)),e.matrixAutoUpdate=!1,e.matrixWorldAutoUpdate=!1,e.material.color.set(A.color??$n),e.material.depthTest=A.depthTest??!0,e.material.wireframe=!0}};let fe=mn;B(fe,"enabled",!0),B(fe,"_up",new y(0,1,0));const VBA=new ti(1,1,1);function Hx(g=null){const A=new yA(g??14540253),e=new IJ(VBA);return new TI(e,new Ii({color:A}))}const MK=Symbol("GizmoCache");class Ti{static ensureFont(){let A=Vt.FontLibrary.getFontFamily(this.familyName);if(!A){A=Vt.FontLibrary.addFontFamily(this.familyName);const e=A.addVariant("normal","normal","https://uploads.needle.tools/include/font-msdf.json","https://uploads.needle.tools/include/font.png");e==null||e.addEventListener("ready",()=>{Vt.update()})}}static getTextLabel(A,e,t,i,I){this.ensureFont();let o=this.textLabelCache.pop(),s=1;I&&typeof I=="string"&&(I==null?void 0:I.length)>=8&&I.startsWith("#")?(s=parseInt(I.substring(7),16)/255,I=I.substring(0,7),zBA&&console.log(I,s)):typeof I=="object"&&I.a!==void 0&&(s=I.a);const n={boxSizing:"border-box",fontFamily:this.familyName,width:"auto",fontSize:t,color:i,lineHeight:1,backgroundColor:I??void 0,backgroundOpacity:s,textContent:e,borderRadius:.5*t,padding:.8*t,whiteSpace:"pre"};if(o)o.set(n);else{o=new WJ(n);const r=this,a=o;a.setText=function(C){this.set({textContent:C}),r.tmuiNeedsUpdate=!0}}return this.tmuiNeedsUpdate=!0,this.registerTimedObject(be.Current,o,A,this.textLabelCache),o}static getBox(A){let e=this.boxesCache.pop();if(!e){const t=new ti(1,1,1);e=new hA(t)}return this.registerTimedObject(be.Current,e,A,this.boxesCache),e}static getLine(A){let e=this.linesCache.pop();if(!e){e=new Oi;let t=e.geometry.getAttribute("position");t||(t=new ne(new Float32Array(2*3),3),e.geometry.setAttribute("position",t))}return e.frustumCulled=!1,this.registerTimedObject(be.Current,e,A,this.linesCache),e}static getSphere(A,e,t){let i=this.spheresCache.pop();return i||(i=new hA(new gn(1,8,8))),i.scale.set(A,A,A),i.material.wireframe=t,this.registerTimedObject(be.Current,i,e,this.spheresCache),i}static getArrowHead(A){let e=this.arrowHeadsCache.pop();return e||(e=new hA(new Ag(0,.5,1,8))),this.registerTimedObject(be.Current,e,A,this.arrowHeadsCache),e}static getMesh(A){let e=this.mesh.pop();return e||(e=new hA,e.material=new ot),this.registerTimedObject(be.Current,e,A,this.mesh),e}static registerTimedObject(A,e,t,i){const I=this.contextBeforeRenderCallbacks.get(A),o=this.contextPostRenderCallbacks.get(A);if(I){if(A.pre_render_callbacks[A.pre_render_callbacks.length-1]!==I){const s=A.pre_render_callbacks.indexOf(I);s>=0&&A.pre_render_callbacks.splice(s,1),A.pre_render_callbacks.push(I)}}else{const s=()=>{this.onBeforeRender(A,this.timedObjectsBuffer)};this.contextBeforeRenderCallbacks.set(A,s),A.pre_render_callbacks.push(s)}if(o){if(A.post_render_callbacks[A.post_render_callbacks.length-1]!==o){const s=A.post_render_callbacks.indexOf(o);s>=0&&A.post_render_callbacks.splice(s,1),A.post_render_callbacks.push(o)}}else{const s=()=>{this.onPostRender(A,this.timedObjectsBuffer,this.timesBuffer)};this.contextPostRenderCallbacks.set(A,s),A.post_render_callbacks.push(s)}e.traverse(s=>{s.layers.disableAll(),s.layers.enable(2)}),e.renderOrder=999999,e[MK]=i,e.isGizmo=!0,this.timedObjectsBuffer.push(e),t<=0&&A.currentFrameEvent>=oi.OnBeforeRender?this.timesBuffer.push(0):this.timesBuffer.push(be.Current.time.realtimeSinceStartup+t),A.scene.add(e)}static onBeforeRender(A,e){this.tmuiNeedsUpdate&&Vt.update();for(let t=0;t<e.length;t++){const i=e[t];if(A.mainCamera&&i instanceof Vt.MeshUIBaseElement){if(Yc(i))continue;const I=A.isInVR,o=!1,s=!I;hD(i,A.mainCamera,o,s)}}}static onPostRender(A,e,t){const i=A.time.realtimeSinceStartup;for(let I=e.length-1;I>=0;I--){const o=e[I];i>t[I]&&(e.splice(I,1),t.splice(I,1),o.removeFromParent(),Yc(o)!=!0&&o[MK].push(o))}}}B(Ti,"familyName","needle-gizmos"),B(Ti,"linesCache",[]),B(Ti,"spheresCache",[]),B(Ti,"boxesCache",[]),B(Ti,"arrowHeadsCache",[]),B(Ti,"mesh",[]),B(Ti,"textLabelCache",[]),B(Ti,"timedObjectsBuffer",new Array),B(Ti,"timesBuffer",new Array),B(Ti,"contextPostRenderCallbacks",new Map),B(Ti,"contextBeforeRenderCallbacks",new Map),B(Ti,"tmuiNeedsUpdate",!1);const Dg=gA("debuginput");var gM=(g=>(g.Mouse="mouse",g.Touch="touch",g.Controller="controller",g.Hand="hand",g))(gM||{}),pi=(g=>(g.PointerDown="pointerdown",g.PointerUp="pointerup",g.PointerMove="pointermove",g.KeyDown="keydown",g.KeyUp="keyup",g.KeyPressed="keypress",g))(pi||{});class ma extends PointerEvent{constructor(e,t,i){super(e,i);B(this,"deviceIndex");B(this,"origin");B(this,"source");B(this,"mode");B(this,"_ray");B(this,"space");B(this,"isClick",!1);B(this,"isDoubleClick",!1);B(this,"_used",!1);B(this,"_pointerid");B(this,"_pointerType");B(this,"_type");B(this,"metadata",{});B(this,"intersections",new Array);B(this,"_immediatePropagationStopped",!1);B(this,"_propagationStopped",!1);this._pointerid=i.pointerId,this._pointerType=i.pointerType,this._type=e,this.deviceIndex=i.deviceIndex,this.origin=i.origin,this.source=t,this.mode=i.mode,this._ray=i.ray,this.space=i.device}get isSpatial(){return this.mode!="screen"}get ray(){return this._ray||(this._ray=new xo(this.space.worldPosition.clone(),this.space.worldForward.clone())),this._ray}set ray(e){this._ray=e}get hasRay(){return this._ray!==void 0}get used(){return this._used}use(){this._used=!0}get pointerId(){return this._pointerid}get pointerType(){return this._pointerType}get type(){return this._type}get immediatePropagationStopped(){return this._immediatePropagationStopped}get propagationStopped(){return this._immediatePropagationStopped||this._propagationStopped}stopImmediatePropagation(){var e;this._immediatePropagationStopped=!0,super.stopImmediatePropagation(),(e=this.source)==null||e.stopImmediatePropagation()}stopPropagation(){var e;this._propagationStopped=!0,super.stopPropagation(),(e=this.source)==null||e.stopPropagation(),Dg&&console.warn("Stop propagation...",this.pointerId,this.pointerType)}}class ep extends KeyboardEvent{constructor(e,t,i){super(e,i);B(this,"source");this.source=t}stopImmediatePropagation(){var e;super.stopImmediatePropagation(),(e=this.source)==null||e.stopImmediatePropagation()}}class XBA{constructor(A){B(this,"key");B(this,"keyType");B(this,"source");this.key=A.key,this.keyType=A.type,this.source=A}}var cr=(g=>(g[g.Early=-100]="Early",g[g.Default=0]="Default",g[g.Late=100]="Late",g))(cr||{});class DW{constructor(A){B(this,"_eventListeners",{});B(this,"_doubleClickTimeThreshold",.2);B(this,"_longPressTimeThreshold",1);B(this,"_specialCursorTrigger",0);B(this,"context");B(this,"_pointerDown",[!1]);B(this,"_pointerUp",[!1]);B(this,"_pointerClick",[!1]);B(this,"_pointerDoubleClick",[!1]);B(this,"_pointerPressed",[!1]);B(this,"_pointerPositions",[new tA]);B(this,"_pointerPositionsLastFrame",[new tA]);B(this,"_pointerPositionsDelta",[new tA]);B(this,"_pointerPositionsRC",[new tA]);B(this,"_pointerPositionDown",[new tA]);B(this,"_pointerDownTime",[]);B(this,"_pointerUpTime",[]);B(this,"_pointerUpTimestamp",[]);B(this,"_pointerIds",[]);B(this,"_pointerTypes",[""]);B(this,"_mouseWheelChanged",[!1]);B(this,"_mouseWheelDeltaY",[0]);B(this,"_pointerEvent",[]);B(this,"_pointerUsed",[]);B(this,"_pointerSpace",[]);B(this,"_pressedStack",new Map);B(this,"_htmlEventSource");B(this,"onLostFocus",()=>{for(const A in this.keysPressed)this.keysPressed[A].pressed=!1});B(this,"onEndOfFrame",()=>{for(let A=0;A<this._pointerUp.length;A++)this._pointerUp[A]=!1;for(let A=0;A<this._pointerDown.length;A++)this._pointerDown[A]=!1;for(let A=0;A<this._pointerClick.length;A++)this._pointerClick[A]=!1;for(let A=0;A<this._pointerDoubleClick.length;A++)this._pointerDoubleClick[A]=!1;for(const A of this._pointerPositionsDelta)A.set(0,0);for(let A=0;A<this._mouseWheelChanged.length;A++)this._mouseWheelChanged[A]=!1;for(let A=0;A<this._mouseWheelDeltaY.length;A++)this._mouseWheelDeltaY[A]=0});B(this,"onContextMenu",A=>{this.canReceiveInput(A)!==!1&&A instanceof PointerEvent&&A.pointerType});B(this,"keysPressed",{});B(this,"onKeyDown",A=>{if(Dg&&console.log(`key down ${A.code}, ${this.context.application.hasFocus}`,A),!this.context.application.hasFocus)return;const e=this.keysPressed[A.code];if(e&&e.pressed)return;this.keysPressed[A.code]={pressed:!0,frame:this.context.time.frameCount+1,startFrame:this.context.time.frameCount+1,key:A.key,code:A.code};const t=new ep("keydown",A,A);this.onDispatchEvent(t)});B(this,"onKeyPressed",A=>{if(!this.context.application.hasFocus)return;const e=this.keysPressed[A.code];if(!e)return;e.pressed=!0,e.frame=this.context.time.frameCount+1;const t=new ep("keypress",A,A);this.onDispatchEvent(t)});B(this,"onKeyUp",A=>{if(!this.context.application.hasFocus)return;const e=this.keysPressed[A.code];if(!e)return;e.pressed=!1,e.frame=this.context.time.frameCount+1;const t=new ep("keyup",A,A);this.onDispatchEvent(t)});B(this,"onWheelWindow",A=>{document.pointerLockElement&&this.onMouseWheel(A)});B(this,"onMouseWheel",A=>{if(this.canReceiveInput(A)===!1)return;this._mouseWheelDeltaY.length<=0&&this._mouseWheelDeltaY.push(0),this._mouseWheelChanged.length<=0&&this._mouseWheelChanged.push(!1),this._mouseWheelChanged[0]=!0;const e=this._mouseWheelDeltaY[0];this._mouseWheelDeltaY[0]=e+A.deltaY});B(this,"onPointerDown",A=>{if(this.context.isInAR||this.canReceiveInput(A)===!1)return;A.target instanceof HTMLElement&&A.target.setPointerCapture(A.pointerId);const e=this.getPointerId(A);Dg&&fi(`pointer down #${e}, identifier:${A.pointerId}`);const t=this.getAndUpdateSpatialObjectForScreenPosition(e,A.clientX,A.clientY),i=new ma("pointerdown",A,{origin:this,mode:"screen",deviceIndex:0,pointerId:e,button:A.button,clientX:A.clientX,clientY:A.clientY,pointerType:A.pointerType,buttonName:this.getButtonName(A),device:t,pressure:A.pressure});this.onDown(i)});B(this,"onPointerMove",A=>{if(this.context.isInAR)return;let e=A.button;A.pointerType==="mouse"&&(e=this.getFirstPressedButtonForPointer(0)??0);const t=this.getPointerId(A,e);e===-1&&(e=t);const i=this.getAndUpdateSpatialObjectForScreenPosition(t,A.clientX,A.clientY),I=new ma("pointermove",A,{origin:this,mode:"screen",deviceIndex:0,pointerId:t,button:e,clientX:A.clientX,clientY:A.clientY,pointerType:A.pointerType,buttonName:this.getButtonName(A),device:i,pressure:A.pressure});this.onMove(I)});B(this,"onPointerCancel",A=>{this.context.isInAR||(Dg&&console.log("Pointer cancel",A),this.onPointerUp(A))});B(this,"onPointerUp",A=>{if(this.context.isInAR)return;A.target instanceof HTMLElement&&A.target.releasePointerCapture(A.pointerId);const e=this.getPointerId(A),t=new ma("pointerup",A,{origin:this,mode:"screen",deviceIndex:0,pointerId:e,button:A.button,clientX:A.clientX,clientY:A.clientY,pointerType:A.pointerType,buttonName:this.getButtonName(A),device:this.getAndUpdateSpatialObjectForScreenPosition(e,A.clientX,A.clientY),pressure:A.pressure});this.onUp(t),this._pointerIds[e]=-1,Dg&&console.log("ID="+e,"PointerId="+A.pointerId,"ALL:",[...this._pointerIds])});B(this,"onTouchStart",A=>{if(this.context.isInAR)for(let e=0;e<A.changedTouches.length;e++){const t=A.changedTouches[e],i=this.getPointerIndex(t.identifier),I=this.getAndUpdateSpatialObjectForScreenPosition(i,t.clientX,t.clientY),o=new ma("pointerdown",A,{origin:this,mode:"screen",deviceIndex:0,pointerId:i,button:0,clientX:t.clientX,clientY:t.clientY,pointerType:"touch",buttonName:"unknown",device:I,pressure:t.force});this.onDown(o)}});B(this,"onTouchMove",A=>{if(this.context.isInAR)for(let e=0;e<A.changedTouches.length;e++){const t=A.changedTouches[e],i=this.getPointerIndex(t.identifier),I=this.getAndUpdateSpatialObjectForScreenPosition(i,t.clientX,t.clientY),o=new ma("pointermove",A,{origin:this,mode:"screen",deviceIndex:0,pointerId:i,button:0,clientX:t.clientX,clientY:t.clientY,pointerType:"touch",buttonName:"unknown",device:I,pressure:t.force});this.onMove(o)}});B(this,"onTouchEnd",A=>{if(this.context.isInAR)for(let e=0;e<A.changedTouches.length;e++){const t=A.changedTouches[e],i=this.getPointerIndex(t.identifier),I=new ma("pointerup",A,{origin:this,mode:"screen",deviceIndex:0,pointerId:i,button:0,clientX:t.clientX,clientY:t.clientY,pointerType:"touch",buttonName:"unknown",device:this.getAndUpdateSpatialObjectForScreenPosition(i,t.clientX,t.clientY),pressure:t.force});this.onUp(I),this._pointerIds[i]=-1}});B(this,"tempNearPlaneVector",new y);B(this,"tempFarPlaneVector",new y);B(this,"tempLookMatrix",new fA);this.context=A,this.context.post_render_callbacks.push(this.onEndOfFrame)}addEventListener(A,e,t){if(this._eventListeners[A]||(this._eventListeners[A]=[]),!e||typeof e!="function"){console.error("Invalid call to addEventListener: callback is required and must be a function!");return}t?t={...t}:t={};let i=0;(t==null?void 0:t.queue)!=null&&(i=t.queue);const I=this._eventListeners[A],o=I.find(s=>s.priority===i);o?o.listeners.push({callback:e,options:t}):(I.push({priority:i,listeners:[{callback:e,options:t}]}),I.sort((s,n)=>s.priority-n.priority))}removeEventListener(A,e,t){if(!this._eventListeners[A]||!e)return;const i=this._eventListeners[A];if((t==null?void 0:t.queue)!=null){const I=i.find(s=>s.priority===t.queue);if(!I)return;const o=I.listeners.findIndex(s=>s.callback===e);o>=0&&I.listeners.splice(o,1)}else for(const I of i){const o=I.listeners.findIndex(s=>s.callback===e);o>=0&&I.listeners.splice(o,1)}}dispatchEvent(A){var t,i,I,o;let e=!1;if(A instanceof ep){const s=this._eventListeners[A.type];if(s)for(const n of s)for(let r=0;r<n.listeners.length;r++){const a=n.listeners[r];if((i=(t=a.options)==null?void 0:t.signal)!=null&&i.aborted){n.listeners.splice(r,1),r--;continue}a.options.once&&(n.listeners.splice(r,1),r--),a.callback(A)}}if(A instanceof ma){const s=this._eventListeners[A.type];if(s)for(const n of s){if(e)break;for(let r=0;r<n.listeners.length;r++){const a=n.listeners[r];if((o=(I=a.options)==null?void 0:I.signal)!=null&&o.aborted){n.listeners.splice(r,1),r--;continue}if(A.immediatePropagationStopped){e=!0,Dg&&console.log("immediatePropagationStopped",A.type);break}else A.propagationStopped&&(e=!0,Dg&&console.log("propagationStopped",A.type));a.options.once&&(n.listeners.splice(r,1),r--),a.callback(A)}}}}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)}setCursorPointer(){this._specialCursorTrigger+=1,this.context.domElement.style.cursor="pointer"}setCursorNormal(){this._specialCursorTrigger-=1,this._specialCursorTrigger=Math.max(0,this._specialCursorTrigger),this._specialCursorTrigger===0&&(this.context.domElement.style.cursor="default")}setPointerUsed(A,e=!0){if(A>=this._pointerUsed.length){if(A>=this._pointerIds.length)return;for(;this._pointerUsed.length<=A;)this._pointerUsed.push(!1)}this._pointerUsed[A]=e}getPointerUsed(A){return A>=this._pointerUsed.length?!1:this._pointerUsed[A]}getPointerPressedCount(){let A=0;for(let e=0;e<this._pointerPressed.length;e++)this._pointerPressed[e]&&A++;return A}getPointerPosition(A){return A>=this._pointerPositions.length?null:this._pointerPositions[A]}getPointerPositionLastFrame(A){return A>=this._pointerPositionsLastFrame.length?null:this._pointerPositionsLastFrame[A]}getPointerPositionDelta(A){return A>=this._pointerPositionsDelta.length?null:this._pointerPositionsDelta[A]}getPointerPositionRC(A){return A>=this._pointerPositionsRC.length?null:this._pointerPositionsRC[A]}getPointerDown(A){return A>=this._pointerDown.length?!1:this._pointerDown[A]}getPointerUp(A){return A>=this._pointerUp.length?!1:this._pointerUp[A]}getPointerPressed(A){return A>=this._pointerPressed.length?!1:this._pointerPressed[A]}getPointerClicked(A){return A>=this._pointerClick.length?!1:this._pointerClick[A]}getPointerDoubleClicked(A){return A>=this._pointerDoubleClick.length?!1:this._pointerDoubleClick[A]}getPointerDownTime(A){return A>=this._pointerDownTime.length?-1:this._pointerDownTime[A]}getPointerUpTime(A){return A>=this._pointerUpTime.length?-1:this._pointerUpTime[A]}getPointerLongPress(A){return A>=this._pointerDownTime.length?!1:this.getPointerPressed(A)&&this.context.time.time-this._pointerDownTime[A]>this._longPressTimeThreshold}getIsMouse(A){return A<0||A>=this._pointerTypes.length?!1:this._pointerTypes[A]==="mouse"}getIsTouch(A){return A<0||A>=this._pointerTypes.length?!1:this._pointerTypes[A]==="touch"}getTouchesPressedCount(){let A=0;for(let e=0;e<this._pointerPressed.length;e++)this._pointerPressed[e]&&this.getIsTouch(e)&&A++;return A}getMouseWheelChanged(A=0){return A>=this._mouseWheelChanged.length?!1:this._mouseWheelChanged[A]}getMouseWheelDeltaY(A=0){return A>=this._mouseWheelDeltaY.length?0:this._mouseWheelDeltaY[A]}getPointerEvent(A){if(!(A>=this._pointerEvent.length))return this._pointerEvent[A]??void 0}*foreachPointerId(A){for(let e=0;e<this._pointerTypes.length;e++)if(this._pointerIsActive(e)){if(A!==void 0){const t=this._pointerTypes[e];if(Array.isArray(A)){let i=!1;for(const I of A)if(t===I){i=!0;break}if(!i)continue}else if(A!==t)continue}yield e}}*foreachTouchId(){for(let A=0;A<this._pointerTypes.length;A++)this._pointerTypes[A]==="touch"&&this._pointerIsActive[A]&&(yield A)}_pointerIsActive(A){return A<0?!1:this._pointerPressed[A]||this._pointerDown[A]||this._pointerUp[A]}onDownButton(A,e){let t=this._pressedStack.get(A);t||(t=[],this._pressedStack.set(A,t)),t.push(e)}onReleaseButton(A,e){const t=this._pressedStack.get(A);if(!t)return;const i=t.indexOf(e);i>=0&&t.splice(i,1)}getFirstPressedButtonForPointer(A){const e=this._pressedStack.get(A);if(e)return e[0]}getLatestPressedButtonForPointer(A){const e=this._pressedStack.get(A);if(e)return e[e.length-1]}getKeyDown(){for(const A in this.keysPressed){const e=this.keysPressed[A];if(e.startFrame===this.context.time.frameCount)return e.key}return null}getKeyPressed(){for(const A in this.keysPressed){const e=this.keysPressed[A];if(e.pressed)return e.key}return null}isKeyDown(A){var t;if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const e=this.getCodeForCommonKeyName(A);if(e!==null){for(const i of e)if(this.isKeyDown(i))return!0;return!1}return((t=this.keysPressed[A])==null?void 0:t.startFrame)===this.context.time.frameCount&&this.keysPressed[A].pressed}isKeyUp(A){var t;if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const e=this.getCodeForCommonKeyName(A);if(e!==null){for(const i of e)if(this.isKeyUp(i))return!0;return!1}return((t=this.keysPressed[A])==null?void 0:t.frame)===this.context.time.frameCount&&!this.keysPressed[A].pressed}isKeyPressed(A){var t;if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const e=this.getCodeForCommonKeyName(A);if(e!==null){for(const i of e)if(this.isKeyPressed(i))return!0;return!1}return(t=this.keysPressed[A])==null?void 0:t.pressed}getCodeForCommonKeyName(A){if(A.length===1){if(A>="0"&&A<="9")return["Digit"+A];if(A>="a"&&A<="z")return["Key"+A.toUpperCase()];if(A==" ")return["Space"]}switch(A){case"shift":case"Shift":return["ShiftLeft","ShiftRight"];case"control":case"Control":return["ControlLeft","ControlRight"];case"alt":case"Alt":return["AltLeft","AltRight"]}return null}createInputEvent(A){switch(A.type){case"pointerdown":Dg&&fi("Create Pointer down"),this.onDownButton(A.deviceIndex,A.button),this.onDown(A);break;case"pointermove":Dg&&fi("Create Pointer move"),this.onMove(A);break;case"pointerup":Dg&&fi("Create Pointer up"),this.onUp(A),this.onReleaseButton(A.deviceIndex,A.button);break}}convertScreenspaceToRaycastSpace(A){return A.x=(A.x-this.context.domX)/this.context.domWidth*2-1,A.y=-((A.y-this.context.domY)/this.context.domHeight)*2+1,A}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 A,e;window.removeEventListener("contextmenu",this.onContextMenu),(A=this._htmlEventSource)==null||A.removeEventListener("pointerdown",this.onPointerDown),window.removeEventListener("pointermove",this.onPointerMove),window.removeEventListener("pointerup",this.onPointerUp),window.removeEventListener("pointercancel",this.onPointerCancel),(e=this._htmlEventSource)==null||e.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 A=this.context.post_render_callbacks.indexOf(this.onEndOfFrame);A>=0&&this.context.post_render_callbacks.splice(A,1),this.unbindEvents()}canReceiveInput(A){var e;return A.target===((e=this.context.renderer)==null?void 0:e.domElement)||A.target===this.context.domElement||this.context.isInAR||this.context.isInAR&&A.target===document.body&&Ec()?!0:(Dg&&console.warn("CanReceiveInput:False for",A.target),!1)}getPointerId(A,e){return A.pointerType==="mouse"?0+(e??A.button):this.getPointerIndex(A.pointerId)}getButtonName(A){const e=A.button;if(A.pointerType==="mouse")switch(e){case 0:return"left";case 1:return"middle";case 2:return"right"}return"unknown"}getAndUpdateSpatialObjectForScreenPosition(A,e,t){let i=this._pointerSpace[A];i||(i=new DA,this._pointerSpace[A]=i),this._pointerSpace[A]=i;const I=this.context.mainCamera;if(I){const o=this.tempNearPlaneVector.set(e,t,-1);this.convertScreenspaceToRaycastSpace(o);const s=this.tempFarPlaneVector.set(o.x,o.y,1);o.unproject(I),s.unproject(I);const n=I.worldUp||dt(0,1,0).applyQuaternion(Jt(I));this.tempLookMatrix.lookAt(s,o,n),i.position.set(o.x,o.y,o.z),i.quaternion.setFromRotationMatrix(this.tempLookMatrix)}return i}isInRect(A){if(this.context.isInXR)return!0;const e=this.context.domElement.getBoundingClientRect(),t=A.clientX,i=A.clientY,I=t>=e.x&&t<=e.right&&i>=e.y&&i<=e.bottom;return Dg&&!I&&console.log("Not in rect",e,t,i),I}onDown(A){const e=A.pointerId;if(this.getPointerPressed(e)&&console.warn(`pointerId is already pressed: ${e}`,Dg?A:""),Dg&&console.log(A.pointerType,"DOWN",e),!!this.isInRect(A)){for(this.setPointerState(e,this._pointerPressed,!0),this.setPointerState(e,this._pointerDown,!0),this.setPointerStateT(e,this._pointerEvent,A.source);e>=this._pointerTypes.length;)this._pointerTypes.push(A.pointerType);for(this._pointerTypes[e]=A.pointerType;e>=this._pointerPositionDown.length;)this._pointerPositionDown.push(new tA);for(this._pointerPositionDown[e].set(A.clientX,A.clientY);e>=this._pointerPositions.length;)this._pointerPositions.push(new tA);this._pointerPositions[e].set(A.clientX,A.clientY),e>=this._pointerDownTime.length&&this._pointerDownTime.push(0),this._pointerDownTime[e]=this.context.time.time,this.updatePointerPosition(A),this.onDispatchEvent(A)}}onMove(A){const e=A.pointerId,t=this.getPointerPressed(e);t===!1&&!this.isInRect(A)||A.pointerType==="touch"&&!t||(this.updatePointerPosition(A),this.setPointerStateT(e,this._pointerEvent,A.source),this.onDispatchEvent(A))}onUp(A){const e=A.pointerId;if(!this.getPointerPressed(e)){Dg&&console.log(A.pointerType,"UP",e,"was not down");return}for(Dg&&console.log(A.pointerType,"UP",e),this.setPointerState(e,this._pointerPressed,!1),this.setPointerStateT(e,this._pointerEvent,A.source),this.setPointerState(e,this._pointerUp,!0);e>=this._pointerUsed.length;)this._pointerUsed.push(!1);if(this.setPointerState(e,this._pointerUsed,!1),this.updatePointerPosition(A),!this._pointerPositionDown[e]){Dg&&Ot("Received pointer up event without matching down event for button: "+e),console.warn("Received pointer up event without matching down event for button: "+e);return}const i=A.clientX-this._pointerPositionDown[e].x,I=A.clientY-this._pointerPositionDown[e].y;if(e>=this._pointerUpTime.length&&this._pointerUpTime.push(-99),Math.abs(i)<5&&Math.abs(I)<5){Dg&&console.log("CLICK",e),this.setPointerState(e,this._pointerClick,!0),A.isClick=!0;const o=this._pointerUpTime[e],s=this.context.time.time-o;s<this._doubleClickTimeThreshold&&s>0&&(this.setPointerState(e,this._pointerDoubleClick,!0),A.isDoubleClick=!0)}this._pointerUpTime[e]=this.context.time.time,this.onDispatchEvent(A)}updatePointerPosition(A){const e=A.pointerId;for(;e>=this._pointerPositions.length;)this._pointerPositions.push(new tA);for(;e>=this._pointerPositionsLastFrame.length;)this._pointerPositionsLastFrame.push(new tA);for(;e>=this._pointerPositionsDelta.length;)this._pointerPositionsDelta.push(new tA);const t=this._pointerPositionsLastFrame[e];t.copy(this._pointerPositions[e]);const i=this._pointerPositionsDelta[e];let I=A.clientX-t.x,o=A.clientY-t.y;if(A.source instanceof MouseEvent||A.source instanceof TouchEvent){const a=A.source;I===0&&a.movementX!==0&&(I=a.movementX||0),o===0&&a.movementY!==0&&(o=a.movementY||0)}i.x+=I,i.y+=o,this._pointerPositions[e].x=A.clientX,this._pointerPositions[e].y=A.clientY;const s=A.clientX,n=A.clientY;for(;e>=this._pointerPositionsRC.length;)this._pointerPositionsRC.push(new tA);const r=this._pointerPositionsRC[e];r.set(s,n),this.convertScreenspaceToRaycastSpace(r)}getPointerIndex(A){let e=-1;for(let t=0;t<this._pointerIds.length;t++){if(this._pointerIds[t]===A)return t;e===-1&&this._pointerIds[t]===-1&&(e=t)}return e!==-1?(this._pointerIds[e]=A,e):(Dg&&console.log("PUSH pointerId:",A),this._pointerIds.push(A),this._pointerIds.length-1)}setPointerState(A,e,t){e[A]=t}setPointerStateT(A,e,t){return e[A]=t,t}onDispatchEvent(A){const e=be.Current;try{be.Current=this.context,this.dispatchEvent(A)}finally{be.Current=e}}}const Bm=new fA().makeRotationY(Math.PI),bs=new GA().setFromAxisAngle(new y(0,1,0),Math.PI),$BA=gA("debugwebxr");class AQA{constructor(){B(this,"priority",-1e5);B(this,"gameObject");if(this.gameObject=new DA,this.gameObject.name="Implicit XR Rig",$BA){const A=Hx(16733661);A.position.y+=.5,this.gameObject.add(A)}}isXRRig(){return!0}get isActive(){return this.gameObject.visible}}const TC=gA("debugwebxr"),gS=gA("debugcustomgesture"),eQA="https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles",tQA="generic-trigger";class Yx{constructor(A,e,t){B(this,"xr");B(this,"inputSource");B(this,"index",0);B(this,"emitEvents",!0);B(this,"_connected",!0);B(this,"_isTracking",!1);B(this,"_hitTestSource");B(this,"_hasSelectEvent",!1);B(this,"_handJointPoses",new Map);B(this,"_gripPosition",new y);B(this,"_gripQuaternion",new GA);B(this,"_linearVelocity",new y);B(this,"_rayPosition",new y);B(this,"_rayQuaternion",new GA);B(this,"_gripWorldPosition",new y);B(this,"_gripWorldQuaternion",new GA);B(this,"_rayWorldPosition",new y);B(this,"_rayWorldQuaternion",new GA);B(this,"_ray");B(this,"_object");B(this,"model",null);B(this,"_debugAxesHelper",new Qs(.2));B(this,"onPointerHits",A=>{});B(this,"_needleGamepadButtons",{});B(this,"_buttonMap",new Map);B(this,"_motioncontroller");B(this,"_layout");B(this,"getMotionController");B(this,"_selectButtonIndex");B(this,"_squeezeButtonIndex");B(this,"onSelectStart",A=>{var i,I,o,s;if(this.inputSource!==A.inputSource)return;this.onUpdateFrame(A.frame),this._hasSelectEvent=!0;const e=(i=this._layout)==null?void 0:i.selectComponentId,t=(s=(o=(I=this._layout)==null?void 0:I.components[e])==null?void 0:o.gamepadIndices)==null?void 0:s.button;t!==void 0&&(this._selectButtonIndex=t),!gS&&(TC&&fe.DrawDirection(this.rayWorldPosition,dt(0,.01,1).applyQuaternion(this.rayWorldQuaternion),16711680,10),this.emitPointerEvent(pi.PointerDown,this._selectButtonIndex||0,"xr-standard-trigger",!0,A))});B(this,"onSelectEnd",A=>{gS||this.inputSource===A.inputSource&&this.emitPointerEvent(pi.PointerUp,this._selectButtonIndex||0,"xr-standard-trigger",!0,A)});B(this,"onSequeezeStart",A=>{var e,t,i;this.inputSource===A.inputSource&&(this._squeezeButtonIndex=(i=(t=(e=this._layout)==null?void 0:e.components["xr-standard-squeeze"])==null?void 0:t.gamepadIndices)==null?void 0:i.button,this._squeezeButtonIndex!==void 0&&(TC&&fe.DrawDirection(this.rayWorldPosition,dt(0,.01,1).applyQuaternion(this.rayWorldQuaternion),255,10),this.emitPointerEvent(pi.PointerDown,this._squeezeButtonIndex||0,"xr-standard-squeeze",!0,A)))});B(this,"onSequeezeEnd",A=>{this.inputSource===A.inputSource&&this._squeezeButtonIndex!==void 0&&this.emitPointerEvent(pi.PointerUp,this._squeezeButtonIndex||0,"xr-standard-squeeze",!0,A)});B(this,"states",{});B(this,"_didMoveLastFrame",!1);B(this,"_lastPointerMovePosition",new y);B(this,"_lastPointerMoveQuaternion",new GA);B(this,"pointerInit");var i,I,o;this.xr=A,this.inputSource=e,this.index=t,this._object=new DA,TC&&this._object.add(this._debugAxesHelper),this.xr.context.scene.add(this._object),this._ray=new xo,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(),this.xr.mode==="immersive-ar"&&this.inputSource.targetRayMode==="tracked-pointer"&&((o=(I=(i=this.xr.session).requestHitTestSourceForTransientInput)==null?void 0:I.call(i,{profile:this.inputSource.profiles[0],offsetRay:new XRRay}))==null||o.then(s=>this._hitTestSource=s))}get context(){return this.xr.context}get connected(){return this._connected}get isTracking(){return this._isTracking}get gamepad(){return this.inputSource.gamepad}get isHand(){return this.inputSource.hand!=null}get hand(){return 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.inputSource.handedness}get isRight(){return this.side==="right"}get isLeft(){return this.side==="left"}get hitTestSource(){return this._hitTestSource}get hasSelectEvent(){return this._hasSelectEvent}getHitTest(){return this.xr.getHitTest(this)}getHandJointPose(A){var t,i;if(!this.hand||!((t=this.xr.frame)!=null&&t.getJointPose)||!this.xr.referenceSpace)return null;let e=(i=this._handJointPoses)==null?void 0:i.get(A);return e||(e=this.xr.frame.getJointPose(A,this.xr.referenceSpace),e&&this._handJointPoses.set(A,e),e)}get gripPosition(){return dt(this._gripPosition).applyMatrix4(Bm)}get gripQuaternion(){return gc(this._gripQuaternion).premultiply(bs)}get gripLinearVelocity(){return dt(this._linearVelocity).applyQuaternion(bs)}get rayPosition(){return dt(this._rayPosition).applyMatrix4(Bm)}get rayQuaternion(){return gc(this._rayQuaternion).premultiply(bs)}get gripWorldPosition(){return dt(this._gripWorldPosition)}get gripWorldQuaternion(){return gc(this._gripWorldQuaternion)}get rayWorldPosition(){return dt(this._rayWorldPosition)}updateRayWorldPosition(){var e;const A=(e=this.xr.context.mainCamera)==null?void 0:e.parent;this._rayWorldPosition.copy(this._rayPosition),A&&this._rayWorldPosition.applyMatrix4(A.matrixWorld)}get rayWorldQuaternion(){return gc(this._rayWorldQuaternion)}updateRayWorldQuaternion(){var t;const A=(t=this.xr.context.mainCamera)==null?void 0:t.parent,e=A?Jt(A):void 0;this._rayWorldQuaternion.copy(this._rayQuaternion).multiply(bs),e&&this._rayWorldQuaternion.premultiply(e)}get ray(){return this._ray.origin.copy(this.rayWorldPosition),this._ray.direction.copy(dt(0,0,1).applyQuaternion(this.rayWorldQuaternion)),this._ray}get object(){return this._object}async getModelUrl(){var A;return(A=this.getMotionController)==null?void 0:A.then(e=>(e==null?void 0:e.assetUrl)||null)}onUpdate(A){this.onUpdateFrame(A),this.updateInputEvents(),this.onUpdateMove()}onRenderDebug(){var i;fe.DrawWireSphere(this.rayWorldPosition,.02),fe.DrawDirection(this.rayWorldPosition,dt(0,0,10).applyQuaternion(this.rayWorldQuaternion));const A=this.gripWorldPosition.sub(this.object.worldForward.multiplyScalar(.1)),e=this.inputSource.profiles.join(`
5152
5152
  `);let t=`Controller[${this.index}] ${this.side}
5153
5153
  C:${this.connected?"yes":"no"} T:${this.isTracking?"yes":"no"} Hand:${this.inputSource.hand?"yes":"no"}`;this.inputSource.hand&&(t+=`
5154
5154
  Pinch: ${(i=this.getGesture("pinch"))==null?void 0:i.value.toFixed(3)}`),t+=`
@@ -5232,7 +5232,7 @@ a=extmap-allow-mixed`)!==-1){const I=i.sdp.split(`
5232
5232
  isUnifiedPlanSupported:`).concat(this.isUnifiedPlanSupported())},g}()),_Y={iceServers:[{urls:"stun:stun.l.google.com:19302"},{urls:["turn:eu-0.turn.peerjs.com:3478","turn:us-0.turn.peerjs.com:3478"],username:"peerjs",credential:"peerjsp"}],sdpSemantics:"unified-plan"},fQA=function(){function g(){this.CLOUD_HOST="0.peerjs.com",this.CLOUD_PORT=443,this.chunkedBrowsers={Chrome:1,chrome:1},this.chunkedMTU=16300,this.defaultConfig=_Y,this.browser=mu.getBrowser(),this.browserVersion=mu.getVersion(),this.supports=function(){var A={browser:mu.isBrowserSupported(),webRTC:mu.isWebRTCSupported(),audioVideo:!1,data:!1,binaryBlob:!1,reliable:!1};if(!A.webRTC)return A;var e;try{e=new RTCPeerConnection(_Y),A.audioVideo=!0;var t=void 0;try{t=e.createDataChannel("_PEERJSTEST",{ordered:!0}),A.data=!0,A.reliable=!!t.ordered;try{t.binaryType="blob",A.binaryBlob=!mu.isIOS}catch{}}catch{}finally{t&&t.close()}}catch{}finally{e&&e.close()}return A}(),this.pack=RY.pack,this.unpack=RY.unpack,this._dataCount=1}return g.prototype.noop=function(){},g.prototype.validateId=function(A){return!A||/^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/.test(A)},g.prototype.chunk=function(A){for(var e=[],t=A.size,i=Math.ceil(t/Rt.chunkedMTU),I=0,o=0;o<t;){var s=Math.min(t,o+Rt.chunkedMTU),n=A.slice(o,s),r={__peerData:this._dataCount,n:I,data:n,total:i};e.push(r),o=s,I++}return this._dataCount++,e},g.prototype.blobToArrayBuffer=function(A,e){var t=new FileReader;return t.onload=function(i){i.target&&e(i.target.result)},t.readAsArrayBuffer(A),t},g.prototype.binaryStringToArrayBuffer=function(A){for(var e=new Uint8Array(A.length),t=0;t<A.length;t++)e[t]=A.charCodeAt(t)&255;return e.buffer},g.prototype.randomToken=function(){return Math.random().toString(36).slice(2)},g.prototype.isSecure=function(){return location.protocol==="https:"},g}(),Rt=new fQA,rZ={};Or(rZ,"Peer",()=>vK,g=>vK=g);var kD={},DQA=Object.prototype.hasOwnProperty,lo="~";function Gf(){}Object.create&&(Gf.prototype=Object.create(null),new Gf().__proto__||(lo=!1));function yQA(g,A,e){this.fn=g,this.context=A,this.once=e||!1}function aZ(g,A,e,t,i){if(typeof e!="function")throw new TypeError("The listener must be a function");var I=new yQA(e,t||g,i),o=lo?lo+A:A;return g._events[o]?g._events[o].fn?g._events[o]=[g._events[o],I]:g._events[o].push(I):(g._events[o]=I,g._eventsCount++),g}function u0(g,A){--g._eventsCount===0?g._events=new Gf:delete g._events[A]}function YI(){this._events=new Gf,this._eventsCount=0}YI.prototype.eventNames=function(){var A=[],e,t;if(this._eventsCount===0)return A;for(t in e=this._events)DQA.call(e,t)&&A.push(lo?t.slice(1):t);return Object.getOwnPropertySymbols?A.concat(Object.getOwnPropertySymbols(e)):A};YI.prototype.listeners=function(A){var e=lo?lo+A:A,t=this._events[e];if(!t)return[];if(t.fn)return[t.fn];for(var i=0,I=t.length,o=new Array(I);i<I;i++)o[i]=t[i].fn;return o};YI.prototype.listenerCount=function(A){var e=lo?lo+A:A,t=this._events[e];return t?t.fn?1:t.length:0};YI.prototype.emit=function(A,e,t,i,I,o){var s=lo?lo+A:A;if(!this._events[s])return!1;var n=this._events[s],r=arguments.length,a,C;if(n.fn){switch(n.once&&this.removeListener(A,n.fn,void 0,!0),r){case 1:return n.fn.call(n.context),!0;case 2:return n.fn.call(n.context,e),!0;case 3:return n.fn.call(n.context,e,t),!0;case 4:return n.fn.call(n.context,e,t,i),!0;case 5:return n.fn.call(n.context,e,t,i,I),!0;case 6:return n.fn.call(n.context,e,t,i,I,o),!0}for(C=1,a=new Array(r-1);C<r;C++)a[C-1]=arguments[C];n.fn.apply(n.context,a)}else{var Q=n.length,c;for(C=0;C<Q;C++)switch(n[C].once&&this.removeListener(A,n[C].fn,void 0,!0),r){case 1:n[C].fn.call(n[C].context);break;case 2:n[C].fn.call(n[C].context,e);break;case 3:n[C].fn.call(n[C].context,e,t);break;case 4:n[C].fn.call(n[C].context,e,t,i);break;default:if(!a)for(c=1,a=new Array(r-1);c<r;c++)a[c-1]=arguments[c];n[C].fn.apply(n[C].context,a)}}return!0};YI.prototype.on=function(A,e,t){return aZ(this,A,e,t,!1)};YI.prototype.once=function(A,e,t){return aZ(this,A,e,t,!0)};YI.prototype.removeListener=function(A,e,t,i){var I=lo?lo+A:A;if(!this._events[I])return this;if(!e)return u0(this,I),this;var o=this._events[I];if(o.fn)o.fn===e&&(!i||o.once)&&(!t||o.context===t)&&u0(this,I);else{for(var s=0,n=[],r=o.length;s<r;s++)(o[s].fn!==e||i&&!o[s].once||t&&o[s].context!==t)&&n.push(o[s]);n.length?this._events[I]=n.length===1?n[0]:n:u0(this,I)}return this};YI.prototype.removeAllListeners=function(A){var e;return A?(e=lo?lo+A:A,this._events[e]&&u0(this,e)):(this._events=new Gf,this._eventsCount=0),this};YI.prototype.off=YI.prototype.removeListener;YI.prototype.addListener=YI.prototype.on;YI.prefixed=lo;YI.EventEmitter=YI;kD=YI;var le={};Or(le,"LogLevel",()=>So,g=>So=g);Or(le,"default",()=>TY,g=>TY=g);var UQ=function(g,A){var e=typeof Symbol=="function"&&g[Symbol.iterator];if(!e)return g;var t=e.call(g),i,I=[],o;try{for(;(A===void 0||A-- >0)&&!(i=t.next()).done;)I.push(i.value)}catch(s){o={error:s}}finally{try{i&&!i.done&&(e=t.return)&&e.call(t)}finally{if(o)throw o.error}}return I},NQ=function(g,A,e){if(e||arguments.length===2)for(var t=0,i=A.length,I;t<i;t++)(I||!(t in A))&&(I||(I=Array.prototype.slice.call(A,0,t)),I[t]=A[t]);return g.concat(I||Array.prototype.slice.call(A))},wQA="PeerJS: ",So;(function(g){g[g.Disabled=0]="Disabled",g[g.Errors=1]="Errors",g[g.Warnings=2]="Warnings",g[g.All=3]="All"})(So||(So={}));var SQA=function(){function g(){this._logLevel=So.Disabled}return Object.defineProperty(g.prototype,"logLevel",{get:function(){return this._logLevel},set:function(A){this._logLevel=A},enumerable:!1,configurable:!0}),g.prototype.log=function(){for(var A=[],e=0;e<arguments.length;e++)A[e]=arguments[e];this._logLevel>=So.All&&this._print.apply(this,NQ([So.All],UQ(A),!1))},g.prototype.warn=function(){for(var A=[],e=0;e<arguments.length;e++)A[e]=arguments[e];this._logLevel>=So.Warnings&&this._print.apply(this,NQ([So.Warnings],UQ(A),!1))},g.prototype.error=function(){for(var A=[],e=0;e<arguments.length;e++)A[e]=arguments[e];this._logLevel>=So.Errors&&this._print.apply(this,NQ([So.Errors],UQ(A),!1))},g.prototype.setLogFunction=function(A){this._print=A},g.prototype._print=function(A){for(var e=[],t=1;t<arguments.length;t++)e[t-1]=arguments[t];var i=NQ([wQA],UQ(e),!1);for(var I in i)i[I]instanceof Error&&(i[I]="("+i[I].name+") "+i[I].message);A>=So.All?console.log.apply(console,NQ([],UQ(i),!1)):A>=So.Warnings?console.warn.apply(console,NQ(["WARNING"],UQ(i),!1)):A>=So.Errors&&console.error.apply(console,NQ(["ERROR"],UQ(i),!1))},g}(),TY=new SQA,CZ={};Or(CZ,"Socket",()=>HY,g=>HY=g);var Fn;(function(g){g.Data="data",g.Media="media"})(Fn||(Fn={}));var eg;(function(g){g.BrowserIncompatible="browser-incompatible",g.Disconnected="disconnected",g.InvalidID="invalid-id",g.InvalidKey="invalid-key",g.Network="network",g.PeerUnavailable="peer-unavailable",g.SslUnavailable="ssl-unavailable",g.ServerError="server-error",g.SocketError="socket-error",g.SocketClosed="socket-closed",g.UnavailableID="unavailable-id",g.WebRTC="webrtc"})(eg||(eg={}));var ka;(function(g){g.Binary="binary",g.BinaryUTF8="binary-utf8",g.JSON="json"})(ka||(ka={}));var Ya;(function(g){g.Message="message",g.Disconnected="disconnected",g.Error="error",g.Close="close"})(Ya||(Ya={}));var aI;(function(g){g.Heartbeat="HEARTBEAT",g.Candidate="CANDIDATE",g.Offer="OFFER",g.Answer="ANSWER",g.Open="OPEN",g.Error="ERROR",g.IdTaken="ID-TAKEN",g.InvalidKey="INVALID-KEY",g.Leave="LEAVE",g.Expire="EXPIRE"})(aI||(aI={}));var jx={};jx=JSON.parse('{"name":"peerjs","version":"1.4.7","keywords":["peerjs","webrtc","p2p","rtc"],"description":"PeerJS client","homepage":"https://peerjs.com","bugs":{"url":"https://github.com/peers/peerjs/issues"},"repository":{"type":"git","url":"https://github.com/peers/peerjs"},"license":"MIT","contributors":["Michelle Bu <michelle@michellebu.com>","afrokick <devbyru@gmail.com>","ericz <really.ez@gmail.com>","Jairo <kidandcat@gmail.com>","Jonas Gloning <34194370+jonasgloning@users.noreply.github.com>","Jairo Caro-Accino Viciana <jairo@galax.be>","Carlos Caballero <carlos.caballero.gonzalez@gmail.com>","hc <hheennrryy@gmail.com>","Muhammad Asif <capripio@gmail.com>","PrashoonB <prashoonbhattacharjee@gmail.com>","Harsh Bardhan Mishra <47351025+HarshCasper@users.noreply.github.com>","akotynski <aleksanderkotbury@gmail.com>","lmb <i@lmb.io>","Jairooo <jairocaro@msn.com>","Moritz Stückler <moritz.stueckler@gmail.com>","Simon <crydotsnakegithub@gmail.com>","Denis Lukov <denismassters@gmail.com>","Philipp Hancke <fippo@andyet.net>","Hans Oksendahl <hansoksendahl@gmail.com>","Jess <jessachandler@gmail.com>","khankuan <khankuan@gmail.com>","DUODVK <kurmanov.work@gmail.com>","XiZhao <kwang1imsa@gmail.com>","Matthias Lohr <matthias@lohr.me>","=frank tree <=frnktrb@googlemail.com>","Andre Eckardt <aeckardt@outlook.com>","Chris Cowan <agentme49@gmail.com>","Alex Chuev <alex@chuev.com>","alxnull <alxnull@e.mail.de>","Yemel Jardi <angel.jardi@gmail.com>","Ben Parnell <benjaminparnell.94@gmail.com>","Benny Lichtner <bennlich@gmail.com>","fresheneesz <bitetrudpublic@gmail.com>","bob.barstead@exaptive.com <bob.barstead@exaptive.com>","chandika <chandika@gmail.com>","emersion <contact@emersion.fr>","Christopher Van <cvan@users.noreply.github.com>","eddieherm <edhermoso@gmail.com>","Eduardo Pinho <enet4mikeenet@gmail.com>","Evandro Zanatta <ezanatta@tray.net.br>","Gardner Bickford <gardner@users.noreply.github.com>","Gian Luca <gianluca.cecchi@cynny.com>","PatrickJS <github@gdi2290.com>","jonnyf <github@jonathanfoss.co.uk>","Hizkia Felix <hizkifw@gmail.com>","Hristo Oskov <hristo.oskov@gmail.com>","Isaac Madwed <i.madwed@gmail.com>","Ilya Konanykhin <ilya.konanykhin@gmail.com>","jasonbarry <jasbarry@me.com>","Jonathan Burke <jonathan.burke.1311@googlemail.com>","Josh Hamit <josh.hamit@gmail.com>","Jordan Austin <jrax86@gmail.com>","Joel Wetzell <jwetzell@yahoo.com>","xizhao <kevin.wang@cloudera.com>","Alberto Torres <kungfoobar@gmail.com>","Jonathan Mayol <mayoljonathan@gmail.com>","Jefferson Felix <me@jsfelix.dev>","Rolf Erik Lekang <me@rolflekang.com>","Kevin Mai-Husan Chia <mhchia@users.noreply.github.com>","Pepijn de Vos <pepijndevos@gmail.com>","JooYoung <qkdlql@naver.com>","Tobias Speicher <rootcommander@gmail.com>","Steve Blaurock <sblaurock@gmail.com>","Kyrylo Shegeda <shegeda@ualberta.ca>","Diwank Singh Tomer <singh@diwank.name>","Sören Balko <Soeren.Balko@gmail.com>","Arpit Solanki <solankiarpit1997@gmail.com>","Yuki Ito <yuki@gnnk.net>","Artur Zayats <zag2art@gmail.com>"],"funding":{"type":"opencollective","url":"https://opencollective.com/peer"},"collective":{"type":"opencollective","url":"https://opencollective.com/peer"},"files":["dist/*"],"sideEffects":["lib/global.ts","lib/supports.ts"],"main":"dist/bundler.cjs","module":"dist/bundler.mjs","browser-minified":"dist/peerjs.min.js","browser-unminified":"dist/peerjs.js","types":"dist/types.d.ts","engines":{"node":">= 10"},"targets":{"types":{"source":"lib/exports.ts"},"main":{"source":"lib/exports.ts","sourceMap":{"inlineSources":true}},"module":{"source":"lib/exports.ts","includeNodeModules":["eventemitter3"],"sourceMap":{"inlineSources":true}},"browser-minified":{"context":"browser","outputFormat":"global","optimize":true,"engines":{"browsers":"cover 99%, not dead"},"source":"lib/global.ts"},"browser-unminified":{"context":"browser","outputFormat":"global","optimize":false,"engines":{"browsers":"cover 99%, not dead"},"source":"lib/global.ts"}},"scripts":{"contributors":"git-authors-cli --print=false && prettier --write package.json && git add package.json package-lock.json && git commit -m \\"chore(contributors): update and sort contributors list\\"","check":"tsc --noEmit","watch":"parcel watch","build":"rm -rf dist && parcel build","prepublishOnly":"npm run build","test":"mocha -r ts-node/register -r jsdom-global/register test/**/*.ts","format":"prettier --write .","semantic-release":"semantic-release"},"devDependencies":{"@parcel/config-default":"^2.5.0","@parcel/packager-ts":"^2.5.0","@parcel/transformer-typescript-tsc":"^2.5.0","@parcel/transformer-typescript-types":"^2.5.0","@semantic-release/changelog":"^6.0.1","@semantic-release/git":"^10.0.1","@types/chai":"^4.3.0","@types/mocha":"^9.1.0","@types/node":"^17.0.18","chai":"^4.3.6","git-authors-cli":"^1.0.40","jsdom":"^19.0.0","jsdom-global":"^3.0.2","mocha":"^9.2.0","mock-socket":"8.0.5","parcel":"^2.5.0","parcel-transformer-tsc-sourcemaps":"^1.0.2","prettier":"^2.6.2","semantic-release":"^19.0.2","standard":"^16.0.4","ts-node":"^10.5.0","typescript":"^4.5.5"},"dependencies":{"@swc/helpers":"^0.3.13","eventemitter3":"^4.0.7","peerjs-js-binarypack":"1.0.1","webrtc-adapter":"^7.7.1"}}');var mQA=function(){var g=function(A,e){return g=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,i){t.__proto__=i}||function(t,i){for(var I in i)Object.prototype.hasOwnProperty.call(i,I)&&(t[I]=i[I])},g(A,e)};return function(A,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");g(A,e);function t(){this.constructor=A}A.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}}(),kQA=function(g,A){var e=typeof Symbol=="function"&&g[Symbol.iterator];if(!e)return g;var t=e.call(g),i,I=[],o;try{for(;(A===void 0||A-- >0)&&!(i=t.next()).done;)I.push(i.value)}catch(s){o={error:s}}finally{try{i&&!i.done&&(e=t.return)&&e.call(t)}finally{if(o)throw o.error}}return I},MQA=function(g,A,e){if(e||arguments.length===2)for(var t=0,i=A.length,I;t<i;t++)(I||!(t in A))&&(I||(I=Array.prototype.slice.call(A,0,t)),I[t]=A[t]);return g.concat(I||Array.prototype.slice.call(A))},GQA=function(g){var A=typeof Symbol=="function"&&Symbol.iterator,e=A&&g[A],t=0;if(e)return e.call(g);if(g&&typeof g.length=="number")return{next:function(){return g&&t>=g.length&&(g=void 0),{value:g&&g[t++],done:!g}}};throw new TypeError(A?"Object is not iterable.":"Symbol.iterator is not defined.")},HY=function(g){mQA(A,g);function A(e,t,i,I,o,s){s===void 0&&(s=5e3);var n=g.call(this)||this;n.pingInterval=s,n._disconnected=!0,n._messagesQueue=[];var r=e?"wss://":"ws://";return n._baseUrl=r+t+":"+i+I+"peerjs?key="+o,n}return A.prototype.start=function(e,t){var i=this;this._id=e;var I="".concat(this._baseUrl,"&id=").concat(e,"&token=").concat(t);this._socket||!this._disconnected||(this._socket=new WebSocket(I+"&version="+jx.version),this._disconnected=!1,this._socket.onmessage=function(o){var s;try{s=JSON.parse(o.data),le.default.log("Server message received:",s)}catch{le.default.log("Invalid server message",o.data);return}i.emit(Ya.Message,s)},this._socket.onclose=function(o){i._disconnected||(le.default.log("Socket closed.",o),i._cleanup(),i._disconnected=!0,i.emit(Ya.Disconnected))},this._socket.onopen=function(){i._disconnected||(i._sendQueuedMessages(),le.default.log("Socket open"),i._scheduleHeartbeat())})},A.prototype._scheduleHeartbeat=function(){var e=this;this._wsPingTimer=setTimeout(function(){e._sendHeartbeat()},this.pingInterval)},A.prototype._sendHeartbeat=function(){if(!this._wsOpen()){le.default.log("Cannot send heartbeat, because socket closed");return}var e=JSON.stringify({type:aI.Heartbeat});this._socket.send(e),this._scheduleHeartbeat()},A.prototype._wsOpen=function(){return!!this._socket&&this._socket.readyState===1},A.prototype._sendQueuedMessages=function(){var e,t,i=MQA([],kQA(this._messagesQueue),!1);this._messagesQueue=[];try{for(var I=GQA(i),o=I.next();!o.done;o=I.next()){var s=o.value;this.send(s)}}catch(n){e={error:n}}finally{try{o&&!o.done&&(t=I.return)&&t.call(I)}finally{if(e)throw e.error}}},A.prototype.send=function(e){if(!this._disconnected){if(!this._id){this._messagesQueue.push(e);return}if(!e.type){this.emit(Ya.Error,"Invalid message");return}if(this._wsOpen()){var t=JSON.stringify(e);this._socket.send(t)}}},A.prototype.close=function(){this._disconnected||(this._cleanup(),this._disconnected=!0)},A.prototype._cleanup=function(){this._socket&&(this._socket.onopen=this._socket.onmessage=this._socket.onclose=null,this._socket.close(),this._socket=void 0),clearTimeout(this._wsPingTimer)},A}(kD.EventEmitter),JK={};Or(JK,"MediaConnection",()=>PY,g=>PY=g);var zx={};Or(zx,"Negotiator",()=>YY,g=>YY=g);var Qm=function(){return Qm=Object.assign||function(g){for(var A,e=1,t=arguments.length;e<t;e++){A=arguments[e];for(var i in A)Object.prototype.hasOwnProperty.call(A,i)&&(g[i]=A[i])}return g},Qm.apply(this,arguments)},nS=function(g,A,e,t){function i(I){return I instanceof e?I:new e(function(o){o(I)})}return new(e||(e=Promise))(function(I,o){function s(a){try{r(t.next(a))}catch(C){o(C)}}function n(a){try{r(t.throw(a))}catch(C){o(C)}}function r(a){a.done?I(a.value):i(a.value).then(s,n)}r((t=t.apply(g,A||[])).next())})},rS=function(g,A){var e={label:0,sent:function(){if(I[0]&1)throw I[1];return I[1]},trys:[],ops:[]},t,i,I,o;return o={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function s(r){return function(a){return n([r,a])}}function n(r){if(t)throw new TypeError("Generator is already executing.");for(;e;)try{if(t=1,i&&(I=r[0]&2?i.return:r[0]?i.throw||((I=i.return)&&I.call(i),0):i.next)&&!(I=I.call(i,r[1])).done)return I;switch(i=0,I&&(r=[r[0]&2,I.value]),r[0]){case 0:case 1:I=r;break;case 4:return e.label++,{value:r[1],done:!1};case 5:e.label++,i=r[1],r=[0];continue;case 7:r=e.ops.pop(),e.trys.pop();continue;default:if(I=e.trys,!(I=I.length>0&&I[I.length-1])&&(r[0]===6||r[0]===2)){e=0;continue}if(r[0]===3&&(!I||r[1]>I[0]&&r[1]<I[3])){e.label=r[1];break}if(r[0]===6&&e.label<I[1]){e.label=I[1],I=r;break}if(I&&e.label<I[2]){e.label=I[2],e.ops.push(r);break}I[2]&&e.ops.pop(),e.trys.pop();continue}r=A.call(g,e)}catch(a){r=[6,a],i=0}finally{t=I=0}if(r[0]&5)throw r[1];return{value:r[0]?r[1]:void 0,done:!0}}},YY=function(){function g(A){this.connection=A}return g.prototype.startConnection=function(A){var e=this._startPeerConnection();if(this.connection.peerConnection=e,this.connection.type===Fn.Media&&A._stream&&this._addTracksToConnection(A._stream,e),A.originator){if(this.connection.type===Fn.Data){var t=this.connection,i={ordered:!!A.reliable},I=e.createDataChannel(t.label,i);t.initialize(I)}this._makeOffer()}else this.handleSDP("OFFER",A.sdp)},g.prototype._startPeerConnection=function(){le.default.log("Creating RTCPeerConnection.");var A=new RTCPeerConnection(this.connection.provider.options.config);return this._setupListeners(A),A},g.prototype._setupListeners=function(A){var e=this,t=this.connection.peer,i=this.connection.connectionId,I=this.connection.type,o=this.connection.provider;le.default.log("Listening for ICE candidates."),A.onicecandidate=function(s){!s.candidate||!s.candidate.candidate||(le.default.log("Received ICE candidates for ".concat(t,":"),s.candidate),o.socket.send({type:aI.Candidate,payload:{candidate:s.candidate,type:I,connectionId:i},dst:t}))},A.oniceconnectionstatechange=function(){switch(A.iceConnectionState){case"failed":le.default.log("iceConnectionState is failed, closing connections to "+t),e.connection.emit("error",new Error("Negotiation of connection to "+t+" failed.")),e.connection.close();break;case"closed":le.default.log("iceConnectionState is closed, closing connections to "+t),e.connection.emit("error",new Error("Connection to "+t+" closed.")),e.connection.close();break;case"disconnected":le.default.log("iceConnectionState changed to disconnected on the connection with "+t);break;case"completed":A.onicecandidate=Rt.noop;break}e.connection.emit("iceStateChanged",A.iceConnectionState)},le.default.log("Listening for data channel"),A.ondatachannel=function(s){le.default.log("Received data channel");var n=s.channel,r=o.getConnection(t,i);r.initialize(n)},le.default.log("Listening for remote stream"),A.ontrack=function(s){le.default.log("Received remote stream");var n=s.streams[0],r=o.getConnection(t,i);if(r.type===Fn.Media){var a=r;e._addStreamToMediaConnection(n,a)}}},g.prototype.cleanup=function(){le.default.log("Cleaning up PeerConnection to "+this.connection.peer);var A=this.connection.peerConnection;if(A){this.connection.peerConnection=null,A.onicecandidate=A.oniceconnectionstatechange=A.ondatachannel=A.ontrack=function(){};var e=A.signalingState!=="closed",t=!1;if(this.connection.type===Fn.Data){var i=this.connection,I=i.dataChannel;I&&(t=!!I.readyState&&I.readyState!=="closed")}(e||t)&&A.close()}},g.prototype._makeOffer=function(){return nS(this,void 0,Promise,function(){var A,e,t,i,I,o,s;return rS(this,function(n){switch(n.label){case 0:A=this.connection.peerConnection,e=this.connection.provider,n.label=1;case 1:return n.trys.push([1,7,,8]),[4,A.createOffer(this.connection.options.constraints)];case 2:t=n.sent(),le.default.log("Created offer."),this.connection.options.sdpTransform&&typeof this.connection.options.sdpTransform=="function"&&(t.sdp=this.connection.options.sdpTransform(t.sdp)||t.sdp),n.label=3;case 3:return n.trys.push([3,5,,6]),[4,A.setLocalDescription(t)];case 4:return n.sent(),le.default.log("Set localDescription:",t,"for:".concat(this.connection.peer)),i={sdp:t,type:this.connection.type,connectionId:this.connection.connectionId,metadata:this.connection.metadata,browser:Rt.browser},this.connection.type===Fn.Data&&(I=this.connection,i=Qm(Qm({},i),{label:I.label,reliable:I.reliable,serialization:I.serialization})),e.socket.send({type:aI.Offer,payload:i,dst:this.connection.peer}),[3,6];case 5:return o=n.sent(),o!="OperationError: Failed to set local offer sdp: Called in wrong state: kHaveRemoteOffer"&&(e.emitError(eg.WebRTC,o),le.default.log("Failed to setLocalDescription, ",o)),[3,6];case 6:return[3,8];case 7:return s=n.sent(),e.emitError(eg.WebRTC,s),le.default.log("Failed to createOffer, ",s),[3,8];case 8:return[2]}})})},g.prototype._makeAnswer=function(){return nS(this,void 0,Promise,function(){var A,e,t,i,I;return rS(this,function(o){switch(o.label){case 0:A=this.connection.peerConnection,e=this.connection.provider,o.label=1;case 1:return o.trys.push([1,7,,8]),[4,A.createAnswer()];case 2:t=o.sent(),le.default.log("Created answer."),this.connection.options.sdpTransform&&typeof this.connection.options.sdpTransform=="function"&&(t.sdp=this.connection.options.sdpTransform(t.sdp)||t.sdp),o.label=3;case 3:return o.trys.push([3,5,,6]),[4,A.setLocalDescription(t)];case 4:return o.sent(),le.default.log("Set localDescription:",t,"for:".concat(this.connection.peer)),e.socket.send({type:aI.Answer,payload:{sdp:t,type:this.connection.type,connectionId:this.connection.connectionId,browser:Rt.browser},dst:this.connection.peer}),[3,6];case 5:return i=o.sent(),e.emitError(eg.WebRTC,i),le.default.log("Failed to setLocalDescription, ",i),[3,6];case 6:return[3,8];case 7:return I=o.sent(),e.emitError(eg.WebRTC,I),le.default.log("Failed to create answer, ",I),[3,8];case 8:return[2]}})})},g.prototype.handleSDP=function(A,e){return nS(this,void 0,Promise,function(){var t,i,I,o;return rS(this,function(s){switch(s.label){case 0:e=new RTCSessionDescription(e),t=this.connection.peerConnection,i=this.connection.provider,le.default.log("Setting remote description",e),I=this,s.label=1;case 1:return s.trys.push([1,5,,6]),[4,t.setRemoteDescription(e)];case 2:return s.sent(),le.default.log("Set remoteDescription:".concat(A," for:").concat(this.connection.peer)),A!=="OFFER"?[3,4]:[4,I._makeAnswer()];case 3:s.sent(),s.label=4;case 4:return[3,6];case 5:return o=s.sent(),i.emitError(eg.WebRTC,o),le.default.log("Failed to setRemoteDescription, ",o),[3,6];case 6:return[2]}})})},g.prototype.handleCandidate=function(A){return nS(this,void 0,Promise,function(){var e,t,i,I,o,s;return rS(this,function(n){switch(n.label){case 0:le.default.log("handleCandidate:",A),e=A.candidate,t=A.sdpMLineIndex,i=A.sdpMid,I=this.connection.peerConnection,o=this.connection.provider,n.label=1;case 1:return n.trys.push([1,3,,4]),[4,I.addIceCandidate(new RTCIceCandidate({sdpMid:i,sdpMLineIndex:t,candidate:e}))];case 2:return n.sent(),le.default.log("Added ICE candidate for:".concat(this.connection.peer)),[3,4];case 3:return s=n.sent(),o.emitError(eg.WebRTC,s),le.default.log("Failed to handleCandidate, ",s),[3,4];case 4:return[2]}})})},g.prototype._addTracksToConnection=function(A,e){if(le.default.log("add tracks from stream ".concat(A.id," to peer connection")),!e.addTrack)return le.default.error("Your browser does't support RTCPeerConnection#addTrack. Ignored.");A.getTracks().forEach(function(t){e.addTrack(t,A)})},g.prototype._addStreamToMediaConnection=function(A,e){le.default.log("add stream ".concat(A.id," to media connection ").concat(e.connectionId)),e.addStream(A)},g}(),Vx={};Or(Vx,"BaseConnection",()=>OY,g=>OY=g);var RQA=function(){var g=function(A,e){return g=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,i){t.__proto__=i}||function(t,i){for(var I in i)Object.prototype.hasOwnProperty.call(i,I)&&(t[I]=i[I])},g(A,e)};return function(A,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");g(A,e);function t(){this.constructor=A}A.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}}(),OY=function(g){RQA(A,g);function A(e,t,i){var I=g.call(this)||this;return I.peer=e,I.provider=t,I.options=i,I._open=!1,I.metadata=i.metadata,I}return Object.defineProperty(A.prototype,"open",{get:function(){return this._open},enumerable:!1,configurable:!0}),A}(kD.EventEmitter),UQA=function(){var g=function(A,e){return g=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,i){t.__proto__=i}||function(t,i){for(var I in i)Object.prototype.hasOwnProperty.call(i,I)&&(t[I]=i[I])},g(A,e)};return function(A,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");g(A,e);function t(){this.constructor=A}A.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}}(),cm=function(){return cm=Object.assign||function(g){for(var A,e=1,t=arguments.length;e<t;e++){A=arguments[e];for(var i in A)Object.prototype.hasOwnProperty.call(A,i)&&(g[i]=A[i])}return g},cm.apply(this,arguments)},NQA=function(g){var A=typeof Symbol=="function"&&Symbol.iterator,e=A&&g[A],t=0;if(e)return e.call(g);if(g&&typeof g.length=="number")return{next:function(){return g&&t>=g.length&&(g=void 0),{value:g&&g[t++],done:!g}}};throw new TypeError(A?"Object is not iterable.":"Symbol.iterator is not defined.")},PY=function(g){UQA(A,g);function A(e,t,i){var I=g.call(this,e,t,i)||this;return I._localStream=I.options._stream,I.connectionId=I.options.connectionId||A.ID_PREFIX+Rt.randomToken(),I._negotiator=new zx.Negotiator(I),I._localStream&&I._negotiator.startConnection({_stream:I._localStream,originator:!0}),I}return Object.defineProperty(A.prototype,"type",{get:function(){return Fn.Media},enumerable:!1,configurable:!0}),Object.defineProperty(A.prototype,"localStream",{get:function(){return this._localStream},enumerable:!1,configurable:!0}),Object.defineProperty(A.prototype,"remoteStream",{get:function(){return this._remoteStream},enumerable:!1,configurable:!0}),A.prototype.addStream=function(e){le.default.log("Receiving stream",e),this._remoteStream=e,g.prototype.emit.call(this,"stream",e)},A.prototype.handleMessage=function(e){var t=e.type,i=e.payload;switch(e.type){case aI.Answer:this._negotiator.handleSDP(t,i.sdp),this._open=!0;break;case aI.Candidate:this._negotiator.handleCandidate(i.candidate);break;default:le.default.warn("Unrecognized message type:".concat(t," from peer:").concat(this.peer));break}},A.prototype.answer=function(e,t){var i,I;if(t===void 0&&(t={}),this._localStream){le.default.warn("Local stream already exists on this MediaConnection. Are you answering a call twice?");return}this._localStream=e,t&&t.sdpTransform&&(this.options.sdpTransform=t.sdpTransform),this._negotiator.startConnection(cm(cm({},this.options._payload),{_stream:e}));var o=this.provider._getMessages(this.connectionId);try{for(var s=NQA(o),n=s.next();!n.done;n=s.next()){var r=n.value;this.handleMessage(r)}}catch(a){i={error:a}}finally{try{n&&!n.done&&(I=s.return)&&I.call(s)}finally{if(i)throw i.error}}this._open=!0},A.prototype.close=function(){this._negotiator&&(this._negotiator.cleanup(),this._negotiator=null),this._localStream=null,this._remoteStream=null,this.provider&&(this.provider._removeConnection(this),this.provider=null),this.options&&this.options._stream&&(this.options._stream=null),this.open&&(this._open=!1,g.prototype.emit.call(this,"close"))},A.ID_PREFIX="mc_",A}(Vx.BaseConnection),xK={};Or(xK,"DataConnection",()=>ZY,g=>ZY=g);var BZ={};Or(BZ,"EncodingQueue",()=>WY,g=>WY=g);var FQA=function(){var g=function(A,e){return g=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,i){t.__proto__=i}||function(t,i){for(var I in i)Object.prototype.hasOwnProperty.call(i,I)&&(t[I]=i[I])},g(A,e)};return function(A,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");g(A,e);function t(){this.constructor=A}A.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}}(),WY=function(g){FQA(A,g);function A(){var e=g.call(this)||this;return e.fileReader=new FileReader,e._queue=[],e._processing=!1,e.fileReader.onload=function(t){e._processing=!1,t.target&&e.emit("done",t.target.result),e.doNextTask()},e.fileReader.onerror=function(t){le.default.error("EncodingQueue error:",t),e._processing=!1,e.destroy(),e.emit("error",t)},e}return Object.defineProperty(A.prototype,"queue",{get:function(){return this._queue},enumerable:!1,configurable:!0}),Object.defineProperty(A.prototype,"size",{get:function(){return this.queue.length},enumerable:!1,configurable:!0}),Object.defineProperty(A.prototype,"processing",{get:function(){return this._processing},enumerable:!1,configurable:!0}),A.prototype.enque=function(e){this.queue.push(e),!this.processing&&this.doNextTask()},A.prototype.destroy=function(){this.fileReader.abort(),this._queue=[]},A.prototype.doNextTask=function(){this.size!==0&&(this.processing||(this._processing=!0,this.fileReader.readAsArrayBuffer(this.queue.shift())))},A}(kD.EventEmitter),KQA=function(){var g=function(A,e){return g=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,i){t.__proto__=i}||function(t,i){for(var I in i)Object.prototype.hasOwnProperty.call(i,I)&&(t[I]=i[I])},g(A,e)};return function(A,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");g(A,e);function t(){this.constructor=A}A.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}}(),bQA=function(g){var A=typeof Symbol=="function"&&Symbol.iterator,e=A&&g[A],t=0;if(e)return e.call(g);if(g&&typeof g.length=="number")return{next:function(){return g&&t>=g.length&&(g=void 0),{value:g&&g[t++],done:!g}}};throw new TypeError(A?"Object is not iterable.":"Symbol.iterator is not defined.")},ZY=function(g){KQA(A,g);function A(e,t,i){var I=g.call(this,e,t,i)||this;return I.stringify=JSON.stringify,I.parse=JSON.parse,I._buffer=[],I._bufferSize=0,I._buffering=!1,I._chunkedData={},I._encodingQueue=new BZ.EncodingQueue,I.connectionId=I.options.connectionId||A.ID_PREFIX+Rt.randomToken(),I.label=I.options.label||I.connectionId,I.serialization=I.options.serialization||ka.Binary,I.reliable=!!I.options.reliable,I._encodingQueue.on("done",function(o){I._bufferedSend(o)}),I._encodingQueue.on("error",function(){le.default.error("DC#".concat(I.connectionId,": Error occured in encoding from blob to arraybuffer, close DC")),I.close()}),I._negotiator=new zx.Negotiator(I),I._negotiator.startConnection(I.options._payload||{originator:!0}),I}return Object.defineProperty(A.prototype,"type",{get:function(){return Fn.Data},enumerable:!1,configurable:!0}),Object.defineProperty(A.prototype,"dataChannel",{get:function(){return this._dc},enumerable:!1,configurable:!0}),Object.defineProperty(A.prototype,"bufferSize",{get:function(){return this._bufferSize},enumerable:!1,configurable:!0}),A.prototype.initialize=function(e){this._dc=e,this._configureDataChannel()},A.prototype._configureDataChannel=function(){var e=this;(!Rt.supports.binaryBlob||Rt.supports.reliable)&&(this.dataChannel.binaryType="arraybuffer"),this.dataChannel.onopen=function(){le.default.log("DC#".concat(e.connectionId," dc connection success")),e._open=!0,e.emit("open")},this.dataChannel.onmessage=function(t){le.default.log("DC#".concat(e.connectionId," dc onmessage:"),t.data),e._handleDataMessage(t)},this.dataChannel.onclose=function(){le.default.log("DC#".concat(e.connectionId," dc closed for:"),e.peer),e.close()}},A.prototype._handleDataMessage=function(e){var t=this,i=e.data,I=i.constructor,o=this.serialization===ka.Binary||this.serialization===ka.BinaryUTF8,s=i;if(o){if(I===Blob){Rt.blobToArrayBuffer(i,function(r){var a=Rt.unpack(r);t.emit("data",a)});return}else if(I===ArrayBuffer)s=Rt.unpack(i);else if(I===String){var n=Rt.binaryStringToArrayBuffer(i);s=Rt.unpack(n)}}else this.serialization===ka.JSON&&(s=this.parse(i));if(s.__peerData){this._handleChunk(s);return}g.prototype.emit.call(this,"data",s)},A.prototype._handleChunk=function(e){var t=e.__peerData,i=this._chunkedData[t]||{data:[],count:0,total:e.total};if(i.data[e.n]=e.data,i.count++,this._chunkedData[t]=i,i.total===i.count){delete this._chunkedData[t];var I=new Blob(i.data);this._handleDataMessage({data:I})}},A.prototype.close=function(){this._buffer=[],this._bufferSize=0,this._chunkedData={},this._negotiator&&(this._negotiator.cleanup(),this._negotiator=null),this.provider&&(this.provider._removeConnection(this),this.provider=null),this.dataChannel&&(this.dataChannel.onopen=null,this.dataChannel.onmessage=null,this.dataChannel.onclose=null,this._dc=null),this._encodingQueue&&(this._encodingQueue.destroy(),this._encodingQueue.removeAllListeners(),this._encodingQueue=null),this.open&&(this._open=!1,g.prototype.emit.call(this,"close"))},A.prototype.send=function(e,t){if(!this.open){g.prototype.emit.call(this,"error",new Error("Connection is not open. You should listen for the `open` event before sending messages."));return}if(this.serialization===ka.JSON)this._bufferedSend(this.stringify(e));else if(this.serialization===ka.Binary||this.serialization===ka.BinaryUTF8){var i=Rt.pack(e);if(!t&&i.size>Rt.chunkedMTU){this._sendChunks(i);return}Rt.supports.binaryBlob?this._bufferedSend(i):this._encodingQueue.enque(i)}else this._bufferedSend(e)},A.prototype._bufferedSend=function(e){(this._buffering||!this._trySend(e))&&(this._buffer.push(e),this._bufferSize=this._buffer.length)},A.prototype._trySend=function(e){var t=this;if(!this.open)return!1;if(this.dataChannel.bufferedAmount>A.MAX_BUFFERED_AMOUNT)return this._buffering=!0,setTimeout(function(){t._buffering=!1,t._tryBuffer()},50),!1;try{this.dataChannel.send(e)}catch(i){return le.default.error("DC#:".concat(this.connectionId," Error when sending:"),i),this._buffering=!0,this.close(),!1}return!0},A.prototype._tryBuffer=function(){if(this.open&&this._buffer.length!==0){var e=this._buffer[0];this._trySend(e)&&(this._buffer.shift(),this._bufferSize=this._buffer.length,this._tryBuffer())}},A.prototype._sendChunks=function(e){var t,i,I=Rt.chunk(e);le.default.log("DC#".concat(this.connectionId," Try to send ").concat(I.length," chunks..."));try{for(var o=bQA(I),s=o.next();!s.done;s=o.next()){var n=s.value;this.send(n,!0)}}catch(r){t={error:r}}finally{try{s&&!s.done&&(i=o.return)&&i.call(o)}finally{if(t)throw t.error}}},A.prototype.handleMessage=function(e){var t=e.payload;switch(e.type){case aI.Answer:this._negotiator.handleSDP(e.type,t.sdp);break;case aI.Candidate:this._negotiator.handleCandidate(t.candidate);break;default:le.default.warn("Unrecognized message type:",e.type,"from peer:",this.peer);break}},A.ID_PREFIX="dc_",A.MAX_BUFFERED_AMOUNT=8388608,A}(Vx.BaseConnection),QZ={};Or(QZ,"API",()=>VY,g=>VY=g);var jY=function(g,A,e,t){function i(I){return I instanceof e?I:new e(function(o){o(I)})}return new(e||(e=Promise))(function(I,o){function s(a){try{r(t.next(a))}catch(C){o(C)}}function n(a){try{r(t.throw(a))}catch(C){o(C)}}function r(a){a.done?I(a.value):i(a.value).then(s,n)}r((t=t.apply(g,A||[])).next())})},zY=function(g,A){var e={label:0,sent:function(){if(I[0]&1)throw I[1];return I[1]},trys:[],ops:[]},t,i,I,o;return o={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function s(r){return function(a){return n([r,a])}}function n(r){if(t)throw new TypeError("Generator is already executing.");for(;e;)try{if(t=1,i&&(I=r[0]&2?i.return:r[0]?i.throw||((I=i.return)&&I.call(i),0):i.next)&&!(I=I.call(i,r[1])).done)return I;switch(i=0,I&&(r=[r[0]&2,I.value]),r[0]){case 0:case 1:I=r;break;case 4:return e.label++,{value:r[1],done:!1};case 5:e.label++,i=r[1],r=[0];continue;case 7:r=e.ops.pop(),e.trys.pop();continue;default:if(I=e.trys,!(I=I.length>0&&I[I.length-1])&&(r[0]===6||r[0]===2)){e=0;continue}if(r[0]===3&&(!I||r[1]>I[0]&&r[1]<I[3])){e.label=r[1];break}if(r[0]===6&&e.label<I[1]){e.label=I[1],I=r;break}if(I&&e.label<I[2]){e.label=I[2],e.ops.push(r);break}I[2]&&e.ops.pop(),e.trys.pop();continue}r=A.call(g,e)}catch(a){r=[6,a],i=0}finally{t=I=0}if(r[0]&5)throw r[1];return{value:r[0]?r[1]:void 0,done:!0}}},VY=function(){function g(A){this._options=A}return g.prototype._buildRequest=function(A){var e=this._options.secure?"https":"http",t=this._options,i=t.host,I=t.port,o=t.path,s=t.key,n=new URL("".concat(e,"://").concat(i,":").concat(I).concat(o).concat(s,"/").concat(A));return n.searchParams.set("ts","".concat(Date.now()).concat(Math.random())),n.searchParams.set("version",jx.version),fetch(n.href,{referrerPolicy:this._options.referrerPolicy})},g.prototype.retrieveId=function(){return jY(this,void 0,Promise,function(){var A,e,t;return zY(this,function(i){switch(i.label){case 0:return i.trys.push([0,2,,3]),[4,this._buildRequest("id")];case 1:if(A=i.sent(),A.status!==200)throw new Error("Error. Status:".concat(A.status));return[2,A.text()];case 2:throw e=i.sent(),le.default.error("Error retrieving ID",e),t="",this._options.path==="/"&&this._options.host!==Rt.CLOUD_HOST&&(t=" If you passed in a `path` to your self-hosted PeerServer, you'll also need to pass in that same path when creating a new Peer."),new Error("Could not get an ID from the server."+t);case 3:return[2]}})})},g.prototype.listAllPeers=function(){return jY(this,void 0,Promise,function(){var A,e,t;return zY(this,function(i){switch(i.label){case 0:return i.trys.push([0,2,,3]),[4,this._buildRequest("peers")];case 1:if(A=i.sent(),A.status!==200)throw A.status===401?(e="",this._options.host===Rt.CLOUD_HOST?e="It looks like you're using the cloud server. You can email team@peerjs.com to enable peer listing for your API key.":e="You need to enable `allow_discovery` on your self-hosted PeerServer to use this feature.",new Error("It doesn't look like you have permission to list peers IDs. "+e)):new Error("Error. Status:".concat(A.status));return[2,A.json()];case 2:throw t=i.sent(),le.default.error("Error retrieving list peers",t),new Error("Could not get list peers from the server."+t);case 3:return[2]}})})},g}(),JQA=function(){var g=function(A,e){return g=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,i){t.__proto__=i}||function(t,i){for(var I in i)Object.prototype.hasOwnProperty.call(i,I)&&(t[I]=i[I])},g(A,e)};return function(A,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");g(A,e);function t(){this.constructor=A}A.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}}(),Jp=function(){return Jp=Object.assign||function(g){for(var A,e=1,t=arguments.length;e<t;e++){A=arguments[e];for(var i in A)Object.prototype.hasOwnProperty.call(A,i)&&(g[i]=A[i])}return g},Jp.apply(this,arguments)},ku=function(g){var A=typeof Symbol=="function"&&Symbol.iterator,e=A&&g[A],t=0;if(e)return e.call(g);if(g&&typeof g.length=="number")return{next:function(){return g&&t>=g.length&&(g=void 0),{value:g&&g[t++],done:!g}}};throw new TypeError(A?"Object is not iterable.":"Symbol.iterator is not defined.")},xQA=function(g,A){var e=typeof Symbol=="function"&&g[Symbol.iterator];if(!e)return g;var t=e.call(g),i,I=[],o;try{for(;(A===void 0||A-- >0)&&!(i=t.next()).done;)I.push(i.value)}catch(s){o={error:s}}finally{try{i&&!i.done&&(e=t.return)&&e.call(t)}finally{if(o)throw o.error}}return I},vK=function(g){JQA(A,g);function A(e,t){var i=g.call(this)||this;i._id=null,i._lastServerId=null,i._destroyed=!1,i._disconnected=!1,i._open=!1,i._connections=new Map,i._lostMessages=new Map;var I;return e&&e.constructor==Object?t=e:e&&(I=e.toString()),t=Jp({debug:0,host:Rt.CLOUD_HOST,port:Rt.CLOUD_PORT,path:"/",key:A.DEFAULT_KEY,token:Rt.randomToken(),config:Rt.defaultConfig,referrerPolicy:"strict-origin-when-cross-origin"},t),i._options=t,i._options.host==="/"&&(i._options.host=window.location.hostname),i._options.path&&(i._options.path[0]!=="/"&&(i._options.path="/"+i._options.path),i._options.path[i._options.path.length-1]!=="/"&&(i._options.path+="/")),i._options.secure===void 0&&i._options.host!==Rt.CLOUD_HOST?i._options.secure=Rt.isSecure():i._options.host==Rt.CLOUD_HOST&&(i._options.secure=!0),i._options.logFunction&&le.default.setLogFunction(i._options.logFunction),le.default.logLevel=i._options.debug||0,i._api=new QZ.API(t),i._socket=i._createServerConnection(),!Rt.supports.audioVideo&&!Rt.supports.data?(i._delayedAbort(eg.BrowserIncompatible,"The current browser does not support WebRTC"),i):I&&!Rt.validateId(I)?(i._delayedAbort(eg.InvalidID,'ID "'.concat(I,'" is invalid')),i):(I?i._initialize(I):i._api.retrieveId().then(function(o){return i._initialize(o)}).catch(function(o){return i._abort(eg.ServerError,o)}),i)}return Object.defineProperty(A.prototype,"id",{get:function(){return this._id},enumerable:!1,configurable:!0}),Object.defineProperty(A.prototype,"options",{get:function(){return this._options},enumerable:!1,configurable:!0}),Object.defineProperty(A.prototype,"open",{get:function(){return this._open},enumerable:!1,configurable:!0}),Object.defineProperty(A.prototype,"socket",{get:function(){return this._socket},enumerable:!1,configurable:!0}),Object.defineProperty(A.prototype,"connections",{get:function(){var e,t,i=Object.create(null);try{for(var I=ku(this._connections),o=I.next();!o.done;o=I.next()){var s=xQA(o.value,2),n=s[0],r=s[1];i[n]=r}}catch(a){e={error:a}}finally{try{o&&!o.done&&(t=I.return)&&t.call(I)}finally{if(e)throw e.error}}return i},enumerable:!1,configurable:!0}),Object.defineProperty(A.prototype,"destroyed",{get:function(){return this._destroyed},enumerable:!1,configurable:!0}),Object.defineProperty(A.prototype,"disconnected",{get:function(){return this._disconnected},enumerable:!1,configurable:!0}),A.prototype._createServerConnection=function(){var e=this,t=new CZ.Socket(this._options.secure,this._options.host,this._options.port,this._options.path,this._options.key,this._options.pingInterval);return t.on(Ya.Message,function(i){e._handleMessage(i)}),t.on(Ya.Error,function(i){e._abort(eg.SocketError,i)}),t.on(Ya.Disconnected,function(){e.disconnected||(e.emitError(eg.Network,"Lost connection to server."),e.disconnect())}),t.on(Ya.Close,function(){e.disconnected||e._abort(eg.SocketClosed,"Underlying socket is already closed.")}),t},A.prototype._initialize=function(e){this._id=e,this.socket.start(e,this._options.token)},A.prototype._handleMessage=function(e){var t,i,I=e.type,o=e.payload,s=e.src;switch(I){case aI.Open:this._lastServerId=this.id,this._open=!0,this.emit("open",this.id);break;case aI.Error:this._abort(eg.ServerError,o.msg);break;case aI.IdTaken:this._abort(eg.UnavailableID,'ID "'.concat(this.id,'" is taken'));break;case aI.InvalidKey:this._abort(eg.InvalidKey,'API KEY "'.concat(this._options.key,'" is invalid'));break;case aI.Leave:le.default.log("Received leave message from ".concat(s)),this._cleanupPeer(s),this._connections.delete(s);break;case aI.Expire:this.emitError(eg.PeerUnavailable,"Could not connect to peer ".concat(s));break;case aI.Offer:var E=o.connectionId,h=this.getConnection(s,E);if(h&&(h.close(),le.default.warn("Offer received for existing Connection ID:".concat(E))),o.type===Fn.Media){var n=new JK.MediaConnection(s,this,{connectionId:E,_payload:o,metadata:o.metadata});h=n,this._addConnection(s,h),this.emit("call",n)}else if(o.type===Fn.Data){var r=new xK.DataConnection(s,this,{connectionId:E,_payload:o,metadata:o.metadata,label:o.label,serialization:o.serialization,reliable:o.reliable});h=r,this._addConnection(s,h),this.emit("connection",r)}else{le.default.warn("Received malformed connection type:".concat(o.type));return}var a=this._getMessages(E);try{for(var C=ku(a),Q=C.next();!Q.done;Q=C.next()){var c=Q.value;h.handleMessage(c)}}catch(l){t={error:l}}finally{try{Q&&!Q.done&&(i=C.return)&&i.call(C)}finally{if(t)throw t.error}}break;default:if(!o){le.default.warn("You received a malformed message from ".concat(s," of type ").concat(I));return}var E=o.connectionId,h=this.getConnection(s,E);h&&h.peerConnection?h.handleMessage(e):E?this._storeMessage(E,e):le.default.warn("You received an unrecognized message:",e);break}},A.prototype._storeMessage=function(e,t){this._lostMessages.has(e)||this._lostMessages.set(e,[]),this._lostMessages.get(e).push(t)},A.prototype._getMessages=function(e){var t=this._lostMessages.get(e);return t?(this._lostMessages.delete(e),t):[]},A.prototype.connect=function(e,t){if(t===void 0&&(t={}),this.disconnected){le.default.warn("You cannot connect to a new Peer because you called .disconnect() on this Peer and ended your connection with the server. You can create a new Peer to reconnect, or call reconnect on this peer if you believe its ID to still be available."),this.emitError(eg.Disconnected,"Cannot connect to new Peer after disconnecting from server.");return}var i=new xK.DataConnection(e,this,t);return this._addConnection(e,i),i},A.prototype.call=function(e,t,i){if(i===void 0&&(i={}),this.disconnected){le.default.warn("You cannot connect to a new Peer because you called .disconnect() on this Peer and ended your connection with the server. You can create a new Peer to reconnect."),this.emitError(eg.Disconnected,"Cannot connect to new Peer after disconnecting from server.");return}if(!t){le.default.error("To call a peer, you must provide a stream from your browser's `getUserMedia`.");return}var I=new JK.MediaConnection(e,this,Jp(Jp({},i),{_stream:t}));return this._addConnection(e,I),I},A.prototype._addConnection=function(e,t){le.default.log("add connection ".concat(t.type,":").concat(t.connectionId," to peerId:").concat(e)),this._connections.has(e)||this._connections.set(e,[]),this._connections.get(e).push(t)},A.prototype._removeConnection=function(e){var t=this._connections.get(e.peer);if(t){var i=t.indexOf(e);i!==-1&&t.splice(i,1)}this._lostMessages.delete(e.connectionId)},A.prototype.getConnection=function(e,t){var i,I,o=this._connections.get(e);if(!o)return null;try{for(var s=ku(o),n=s.next();!n.done;n=s.next()){var r=n.value;if(r.connectionId===t)return r}}catch(a){i={error:a}}finally{try{n&&!n.done&&(I=s.return)&&I.call(s)}finally{if(i)throw i.error}}return null},A.prototype._delayedAbort=function(e,t){var i=this;setTimeout(function(){i._abort(e,t)},0)},A.prototype._abort=function(e,t){le.default.error("Aborting!"),this.emitError(e,t),this._lastServerId?this.disconnect():this.destroy()},A.prototype.emitError=function(e,t){le.default.error("Error:",t);var i;typeof t=="string"?i=new Error(t):i=t,i.type=e,this.emit("error",i)},A.prototype.destroy=function(){this.destroyed||(le.default.log("Destroy peer with ID:".concat(this.id)),this.disconnect(),this._cleanup(),this._destroyed=!0,this.emit("close"))},A.prototype._cleanup=function(){var e,t;try{for(var i=ku(this._connections.keys()),I=i.next();!I.done;I=i.next()){var o=I.value;this._cleanupPeer(o),this._connections.delete(o)}}catch(s){e={error:s}}finally{try{I&&!I.done&&(t=i.return)&&t.call(i)}finally{if(e)throw e.error}}this.socket.removeAllListeners()},A.prototype._cleanupPeer=function(e){var t,i,I=this._connections.get(e);if(I)try{for(var o=ku(I),s=o.next();!s.done;s=o.next()){var n=s.value;n.close()}}catch(r){t={error:r}}finally{try{s&&!s.done&&(i=o.return)&&i.call(o)}finally{if(t)throw t.error}}},A.prototype.disconnect=function(){if(!this.disconnected){var e=this.id;le.default.log("Disconnect peer with ID:".concat(e)),this._disconnected=!0,this._open=!1,this.socket.close(),this._lastServerId=e,this._id=null,this.emit("disconnected",e)}},A.prototype.reconnect=function(){if(this.disconnected&&!this.destroyed)le.default.log("Attempting reconnection to server with ID ".concat(this._lastServerId)),this._disconnected=!1,this._initialize(this._lastServerId);else{if(this.destroyed)throw new Error("This peer cannot reconnect to the server. It has already been destroyed.");if(!this.disconnected&&!this.open)le.default.error("In a hurry? We're still trying to make the initial connection!");else throw new Error("Peer ".concat(this.id," cannot reconnect because it is not disconnected from the server!"))}},A.prototype.listAllPeers=function(e){var t=this;e===void 0&&(e=function(i){}),this._api.listAllPeers().then(function(i){return e(i)}).catch(function(i){return t._abort(eg.ServerError,i)})},A.DEFAULT_KEY="peerjs",A}(kD.EventEmitter),qK=rZ.Peer;const vQA=Object.freeze(Object.defineProperty({__proto__:null,get Peer(){return vK},default:qK,util:Rt},Symbol.toStringTag,{value:"Module"}));let Xx;function qQA(){return Xx}function LQA(g){Xx=g}function cZ(g,A){return A||(A={}),A={...Xx,...A},g?new qK(g,A):new qK(A)}async function XY(){const g=await Promise.resolve().then(()=>vQA);return console.log(g),g.default===void 0?g:g.default}class EZ{constructor(){B(this,"_host");B(this,"_client");B(this,"_clientData");this.onEnable()}get isHost(){return this._host!==void 0}onEnable(){const A="HOST-5980e65c-8438-453e-8b35-f13c736dcd81";this.trySetupHost(A)}async trySetupHost(A){const e=await XY(),t=new e(A);t.on("error",i=>{console.error(i),this._host=void 0,this.trySetupClient(A)}),t.on("open",i=>{this._host=new TQA(t)})}async trySetupClient(A){const e=await XY();this._client=new e,this._client.on("error",t=>{console.error("Client error",t)}),this._client.on("open",t=>{console.log("client connected",t),this._clientData=this._client.connect(A,{metadata:{id:t}}),this._clientData.on("open",()=>{console.log("Connected to host")}),this._clientData.on("data",i=>{console.log("<<",i)})})}}class _QA{constructor(A){B(this,"_peer");this._peer=A}}class TQA extends _QA{constructor(e){var t;super(e);B(this,"_connections",[]);console.log("I AM THE HOST"),(t=this._peer)==null||t.on("connection",this.onConnection.bind(this)),this._peer.on("close",()=>{this.broadcast("BYE")}),setInterval(()=>{this.broadcast("HELLO")},2e3)}get isHost(){return!0}onConnection(e){console.log("host connection",e),e.on("open",()=>{this._connections.push(e),this.broadcastConnection(e)})}broadcastConnection(e){const t=this._connections.map(i=>{var I;return(I=i.metadata)==null?void 0:I.id}).filter(i=>i!==void 0);this.broadcast({type:"connection-list",connections:t})}broadcast(e){if(e!=null){console.log(">>",e);for(const t in this._peer.connections){const i=this._peer.connections[t];if(i)if(Array.isArray(i))for(const I of i)I&&I.send(e);else console.warn(i)}}}}const $Y="https://urls.needle.tools/default-networking-backend/index";let HC="wss://needle-tiny-starter.glitch.me/socket";const oo=!!gA("debugnet"),Ip=!!(oo||gA("debugowner")),A2=gA("debugnetbin");var lZ=(g=>(g.ConnectionInfo="connection-start-info",g))(lZ||{}),ze=(g=>(g.Join="join-room",g.Leave="leave-room",g.JoinedRoom="joined-room",g.LeftRoom="left-room",g.UserJoinedRoom="user-joined-room",g.UserLeftRoom="user-left-room",g.RoomStateSent="room-state-sent",g))(ze||{});class HQA{constructor(){B(this,"room");B(this,"viewId");B(this,"allowEditing");B(this,"inRoom")}}class YQA{constructor(){B(this,"room")}}class OQA{constructor(){B(this,"userId")}}var hZ=(g=>(g.RequestHasOwner="request-has-owner",g.ResponseHasOwner="response-has-owner",g.RequestIsOwner="request-is-owner",g.ResponseIsOwner="response-is-owner",g.RequestOwnership="request-ownership",g.GainedOwnership="gained-ownership",g.RemoveOwnership="remove-ownership",g.LostOwnership="lost-ownership",g.GainedOwnershipBroadcast="gained-ownership-broadcast",g.LostOwnershipBroadcast="lost-ownership-broadcast",g))(hZ||{});class $x{constructor(A,e){B(this,"guid");B(this,"connection");B(this,"_hasOwnership",!1);B(this,"_isOwned");B(this,"_gainSubscription");B(this,"_lostSubscription");B(this,"_hasOwnerResponse");B(this,"_isWaitingForOwnershipResponseCallback",null);this.connection=A,this.guid=e,this._gainSubscription=this.onGainedOwnership.bind(this),this._lostSubscription=this.onLostOwnership.bind(this),A.beginListen("lost-ownership",this._lostSubscription),A.beginListen("gained-ownership-broadcast",this._gainSubscription),this._hasOwnerResponse=this.onHasOwnerResponse.bind(this),A.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(A){A.guid===this.guid&&(this._isOwned=A.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(A){A.guid===this.guid&&(this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this._isOwned=A.value,A.value||(Ip&&console.log("request ownership",this.guid),this.requestOwnership()))}requestOwnershipAsync(){return new Promise((A,e)=>{this.requestOwnership();let t=0;const i=()=>{if(t++>10)return e("Timeout");setTimeout(()=>{this.hasOwnership?A(this):i()},100)};i()})}requestOwnership(){return Ip&&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(A){A.guid===this.guid&&(this._isOwned=!0,this.connection.connectionId===A.owner?(Ip&&console.log("GAINED OWNERSHIP",this.guid),this._hasOwnership=!0):this._hasOwnership=!1)}onLostOwnership(A){A===this.guid&&(Ip&&console.log("LOST OWNERSHIP",this.guid),this._hasOwnership=!1,this._isOwned=!1)}}class dZ{constructor(A){B(this,"context");B(this,"_peer",null);B(this,"_usersInRoomCopy",[]);B(this,"_defaultMessagesBuffer",[]);B(this,"_defaultMessagesBufferArray",[]);B(this,"netWebSocketUrlProvider");B(this,"_listeners",{});B(this,"_listenersBinary",{});B(this,"connected",!1);B(this,"channelId");B(this,"_connectionId",null);B(this,"_ws");B(this,"_waitingForSocket",{});B(this,"_isInRoom",!1);B(this,"_currentRoomName",null);B(this,"_currentRoomViewId",null);B(this,"_currentRoomAllowEditing",!0);B(this,"_currentInRoom",[]);B(this,"_state",{});B(this,"_currentDelay",-1);B(this,"_connectingToWebsocketPromise",null);this.context=A}get peer(){return this._peer||(this._peer=new EZ),this._peer}tryGetState(A){return A==="invalid"?null:this._state[A]}get connectionId(){return this._connectionId}get isDebugEnabled(){return oo}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 A=new URL(window.location.href);return A.searchParams.set("view",this.currentRoomViewId),A.href}get isInRoom(){return this._isInRoom}get currentLatency(){return this._currentDelay}get currentServerUrl(){var A;return((A=this._ws)==null?void 0:A.url)??null}sendPing(){this.send("ping",{time:this.context.time.time})}userIsInRoom(A){return this._currentInRoom.indexOf(A)!==-1}usersInRoom(A=null){A||(A=this._usersInRoomCopy),A.length=0;for(const e of this._currentInRoom)A.push(e);return A}joinRoom(A,e=!1){return A?A.length>1024?(console.error('Room name too long, can not join: "'+A+'". Max length is 1024 characters.'),!1):(this.connect(),oo&&console.log("join: "+A),this.send("join-room",{room:A,viewOnly:e},Gn.OnConnection),!0):(console.error('Missing room name, can not join: "'+A+'"'),!1)}leaveRoom(A=null){return A||(A=this.currentRoomName),A?(this.send("leave-room",{room:A}),!0):(console.error('Missing room name, can not join: "'+A+'"'),!1)}send(A,e=null,t=Gn.Queued){if(e===null&&(e={}),t===Gn.Queued){this._defaultMessagesBuffer.push({key:A,value:e});return}return this.sendWithWebsocket(A,e,t)}sendDeleteRemoteState(A){this.send("delete-state",{guid:A,dontSave:!0}),delete this._state[A]}sendDeleteRemoteStateAll(){this.send("delete-all-state"),this._state={}}sendBinary(A){var e;A2&&console.log("<< send binary",this.context.time.frame,A.length/1024+" KB"),(e=this._ws)==null||e.send(A)}sendBufferedMessagesNow(){var t;if(!this._ws)return;this._defaultMessagesBufferArray.length=0;const A=Object.keys(this._defaultMessagesBuffer).length;for(const i in this._defaultMessagesBuffer){const I=this._defaultMessagesBuffer[i];if(A<=1){this.sendWithWebsocket(I.key,I.value,Gn.Immediate);break}const o=this.toMessage(I.key,I.value);this._defaultMessagesBufferArray.push(o)}if(this._defaultMessagesBuffer.length=0,this._defaultMessagesBufferArray.length>0&&oo&&console.log("SEND BUFFERED",this._defaultMessagesBufferArray.length),this._defaultMessagesBufferArray.length<=0)return;const e=JSON.stringify(this._defaultMessagesBufferArray);(t=this._ws)==null||t.send(e)}beginListen(A,e){return this._listeners[A]||(this._listeners[A]=[]),this._listeners[A].push(e),e}stopListening(A,e){return this.stopListen(A,e)}stopListen(A,e){if(!e||!this._listeners[A])return;const t=this._listeners[A].indexOf(e);t>=0&&this._listeners[A].splice(t,1)}beginListenBinary(A,e){return this._listenersBinary[A]||(this._listenersBinary[A]=[]),this._listenersBinary[A].push(e),e}stopListenBinary(A,e){if(!this._listenersBinary[A])return;const t=this._listenersBinary[A].indexOf(e);t>=0&&this._listenersBinary[A].splice(t,1)}registerProvider(A){this.netWebSocketUrlProvider=A}async connect(){var e;if(this.connected)return Promise.resolve(!0);oo&&console.log("connecting");const A=(e=this.netWebSocketUrlProvider)==null?void 0:e.getWebsocketUrl();return A?HC=A:t4()&&(HC="wss://"+window.location.host+"/socket"),this.connectWebsocket()}disconnect(){var A;(A=this._ws)==null||A.close(),this._ws=void 0}connectWebsocket(){return this._connectingToWebsocketPromise?this._connectingToWebsocketPromise:this._connectingToWebsocketPromise=new Promise(async(A,e)=>{var r,a;let t=!1;const i=C=>{t||(t=!0,A(C))};if(HC===void 0&&(console.log("Fetch default backend url: "+$Y),HC=await(await fetch($Y)).text()),HC===void 0){i(!1);return}console.log(`⊡ Connecting to networking backend on
5233
5233
  `+HC);const I=await Promise.resolve().then(()=>mwA),o=((r=I.default)==null?void 0:r.WebsocketBuilder)??I.WebsocketBuilder,s=((a=I.default)==null?void 0:a.ExponentialBackoff)??I.ExponentialBackoff,n=new o(HC).withMaxRetries(3).withBackoff(new s(2e3,2)).onOpen(()=>{this._connectingToWebsocketPromise=null,this._ws=n,this.connected=!0,console.log(`⊞ Connected to networking backend
5234
5234
  `+HC),i(!0),this.onSendQueued(Gn.OnConnection)}).onClose(C=>{this._connectingToWebsocketPromise=null,this.connected=!1,this._isInRoom=!1,i(!1)}).onError(C=>{console.error("⊠ Websocket error"),i(!1)}).onRetry(()=>{console.log("Retry connecting to networking websocket")}).build();n.addEventListener(I.WebsocketEvent.message,(C,Q)=>{this.onMessage(C,Q)})})}onMessage(A,e){const t=e.data;try{if(typeof t!="string"){t.size&&this.handleIncomingBinaryMessage(t);return}const i=JSON.parse(t);if(Array.isArray(i))for(const I of i)this.handleIncomingStringMessage(I);else this.handleIncomingStringMessage(i);return}catch(i){oo&&t==="pong"?console.log("<<",t):ae()&&console.error("Failed to parse message",i)}}async handleIncomingBinaryMessage(A){A2&&console.log("<< bin",this.context.time.frame);const e=await A.arrayBuffer();var t=new Uint8Array(e);const i=new Mf(t),I=i.getBufferIdentifier(),o=this._listenersBinary[I],s=yW(i),n=wW(s);if(n&&typeof n=="string"&&(this._state[n]=s),!o)return;const r=s??i;for(const a of o)a(r)}handleIncomingStringMessage(A){var i,I;if(oo&&console.log("<<",A.key??A),A.key)switch(A.key){case"connection-start-info":if(A.data){const n=A.data;n&&(console.assert(n.id!==void 0&&n.id!==null&&n.id.length>0,"server did not send connection id",n.id),console.log("Your id is: "+n.id,this.context.alias??""),this._connectionId=n.id)}else console.warn("Expected connection id in "+A.key);break;case"joined-room":if(oo&&console.log(A),A){this._isInRoom=!0;const n=A;this._currentRoomName=n.room,this._currentRoomViewId=n.viewId,this._currentRoomAllowEditing=n.allowEditing??!0,this._currentInRoom.length=0,this._currentInRoom.push(...n.inRoom),oo&&console.log("joined room with",this._currentInRoom,this.context.alias??"");const r=new URL(window.location.href);r.searchParams.has("room")&&r.searchParams.delete("room"),r.searchParams.set("view",this._currentRoomViewId),console.log("Room view id: "+this._currentRoomViewId+`
5235
- `+r.href)}this.onSendQueued(Gn.OnRoomJoin);break;case"left-room":A.room===this.currentRoomName&&(this._isInRoom=!1,this._currentRoomName=null,this._currentInRoom.length=0);break;case"user-joined-room":if(A.data){const n=A.data;this._currentInRoom.push(n.userId),oo&&console.log(n.userId+" joined","now in room:",this._currentInRoom)}break;case"user-left-room":if(A.data){const n=A.data,r=this._currentInRoom.indexOf(n.userId);r>=0&&(oo&&console.log(n.userId+" left","now in room:",this._currentInRoom),this._currentInRoom.splice(r,1)),n.userId===this.connectionId&&console.log("you left the room")}break;case"all-room-state-deleted":oo&&console.log("RECEIVED all-room-state-deleted"),this._state={};break;case"ping":case"pong":const s=(i=A.data)==null?void 0:i.time;s&&(this._currentDelay=this.context.time.time-s),oo&&console.log("Current latency: "+this._currentDelay.toFixed(4)+" sec","Clients in room: "+((I=this._currentInRoom)==null?void 0:I.length));break}const e=A.data;e&&(this._state[e.guid]=e);let t=this._listeners[A.key];if(t){t=[...t];for(const o of t)try{o(A.data)}catch(s){console.error('Error invoking callback for "'+A.key+'"',s)}}}toMessage(A,e){return{key:A,data:e}}sendWithWebsocket(A,e,t=Gn.OnRoomJoin){if(!this._ws){const I=this._waitingForSocket[t]||[];I.push(()=>this.sendWithWebsocket(A,e,t)),this._waitingForSocket[t]=I;return}const i=JSON.stringify(this.toMessage(A,e));oo&&console.log(">>",A),this._ws.send(i)}onSendQueued(A){const e=this._waitingForSocket[A];if(e){for(const t of e)t();e.length=0}}}const xp=gA("debugwebxr");class LU{constructor(A,e){B(this,"controllerStates",[]);B(this,"userId");B(this,"context");B(this,"userStateEvtName");B(this,"onReceivedControllerState",A=>{xp&&console.log(`XRSync: Received change for ${this.userId}: ${A.type} ${A.handedness}; tracked=${A.isTracking}`);let e=!1;for(let t=0;t<this.controllerStates.length;t++)if(this.controllerStates[t].index===A.index){this.controllerStates[t]=A,e=!0;break}e||this.controllerStates.push(A)});this.userId=A,this.context=e,this.userStateEvtName="xr-sync-user-state-"+A,this.context.connection.beginListen(this.userStateEvtName,this.onReceivedControllerState)}dispose(){this.context.connection.stopListen(this.userStateEvtName,this.onReceivedControllerState)}update(A){if(this.context.connection.isConnected!=!1){for(let e=this.controllerStates.length-1;e>=0;e--){const t=this.controllerStates[e];let i=!1;for(let I=0;I<A.controllers.length;I++)A.controllers[I].index===t.index&&(i=!0);i||(xp&&console.log(`XRSync: ${t.type} ${t.handedness} removed`,t.index),this.controllerStates.splice(e,1),this.sendControllerRemoved(t))}for(const e of A.controllers)this.updateControllerStates(e)}}onExitXR(A){for(const e of this.controllerStates)this.sendControllerRemoved(e);this.controllerStates.length=0}sendControllerRemoved(A){A.isTracking=!1,A.guid="",this.context.connection.send(this.userStateEvtName,A),this.context.connection.sendDeleteRemoteState(A.guid)}updateControllerStates(A){const e=this.controllerStates.find(t=>t.index===A.index);if(e){let t=!1;t||(t=e.isTracking!=A.isTracking),t&&(e.isTracking=A.isTracking,this.context.connection.send(this.userStateEvtName,e))}else{const t={guid:this.userId+"-"+A.index,isTracking:A.isTracking,handedness:A.side,index:A.index,type:A.hand?"hand":"controller"};this.controllerStates.push(t),this.context.connection.send(this.userStateEvtName,t),xp&&console.log(`XRSync: ${t.type} ${t.handedness} added`,t.index)}}}class uZ{constructor(A){B(this,"context");B(this,"onJoinedRoom",()=>{if(this.context.connection.connectionId){this._states.has(this.context.connection.connectionId)||(xp&&console.log("XRSync: Local user joined room",this.context.connection.connectionId),this._states.set(this.context.connection.connectionId,new LU(this.context.connection.connectionId,this.context)));for(const A of this.context.connection.usersInRoom())this._states.has(A)||this._states.set(A,new LU(A,this.context))}});B(this,"onLeftRoom",()=>{if(this.context.connection.connectionId&&!this._states.has(this.context.connection.connectionId)){const A=this._states.get(this.context.connection.connectionId);A==null||A.dispose(),this._states.delete(this.context.connection.connectionId)}});B(this,"onOtherUserJoinedRoom",A=>{const e=A.userId;this._states.has(e)||(xp&&console.log("XRSync: Remote user joined room",e),this._states.set(e,new LU(e,this.context)))});B(this,"onOtherUserLeftRoom",A=>{const e=A.userId;if(!this._states.has(e)){const t=this._states.get(e);t==null||t.dispose(),this._states.delete(e)}});B(this,"_states",new Map);this.context=A,this.context.connection.beginListen(ze.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(ze.LeftRoom,this.onLeftRoom),this.context.connection.beginListen(ze.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.beginListen(ze.UserLeftRoom,this.onOtherUserLeftRoom)}hasState(A){return A?this._states.has(A):!1}isTracking(A,e){if(!A)return;const t=this._states.get(A);if(!t)return;const i=t.controllerStates.find(I=>I.handedness===e);return(i==null?void 0:i.isTracking)||!1}getDeviceType(A,e){if(!A)return;const t=this._states.get(A);if(!t)return;const i=t.controllerStates.find(I=>I.handedness===e);return(i==null?void 0:i.type)||"unknown"}destroy(){this.context.connection.stopListen(ze.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(ze.LeftRoom,this.onLeftRoom),this.context.connection.stopListen(ze.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.stopListen(ze.UserLeftRoom,this.onOtherUserLeftRoom)}onUpdate(A){if(this.context.connection.isConnected&&this.context.connection.connectionId){const e=this._states.get(this.context.connection.connectionId);e==null||e.update(A)}}onExitXR(A){if(this.context.connection.isConnected&&this.context.connection.connectionId){const e=this._states.get(this.context.connection.connectionId);e==null||e.onExitXR(A)}}}class e2{constructor(){B(this,"_fadeToColorQuad");B(this,"_fadeToColorMaterial");B(this,"_requestedFadeValue",0);B(this,"_transitionPromise",null);B(this,"_transitionResolve",null);this._fadeToColorMaterial=new ot({color:0,transparent:!0,depthTest:!1,fog:!1,side:kt}),this._fadeToColorQuad=new hA(new hg(10,10),this._fadeToColorMaterial)}dispose(){this._fadeToColorQuad.geometry.dispose(),this._fadeToColorMaterial.dispose()}update(A,e){const t=this._fadeToColorQuad,i=this._fadeToColorMaterial;t.parent!==A&&i.opacity>0?A.add(t):i.opacity===0&&t.removeFromParent(),t.layers.set(2),t.material=this._fadeToColorMaterial,t.position.z=-1,t.renderOrder=1/0;const I=this._requestedFadeValue;i.opacity=ge.lerp(i.opacity,I,e/.03),Math.abs(i.opacity-I)<=.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 A=new Promise(e=>{this._transitionResolve=e});return this._transitionPromise=A,A}}var Hc=(g=>(g[g.Quad=0]="Quad",g[g.Cube=1]="Cube",g[g.Sphere=2]="Sphere",g))(Hc||{});class MD{static createPrimitive(A,e){let t;switch(A){case"Quad":case 0:{const I=new hg(1,1,1,1),o=(e==null?void 0:e.material)??new LI({color:16777215});e!=null&&e.texture&&"map"in o&&(o.map=e.texture),t=new hA(I,o)}break;case"Cube":case 1:{const I=new ti(1,1,1),o=(e==null?void 0:e.material)??new LI({color:16777215});e!=null&&e.texture&&"map"in o&&(o.map=e.texture),t=new hA(I,o)}break;case"Sphere":case 2:{const I=new gn(.5,16,16),o=(e==null?void 0:e.material)??new LI({color:16777215});e!=null&&e.texture&&"map"in o&&(o.map=e.texture),t=new hA(I,o)}break}return this.applyDefaultObjectOptions(t,e),t}static createSprite(A){const t=new rk({color:16777215});A!=null&&A.texture&&"map"in t&&(t.map=A.texture);const i=new Zb(t);return this.applyDefaultObjectOptions(i,A),i}static applyDefaultObjectOptions(A,e){e!=null&&e.name&&(A.name=e.name),e!=null&&e.position&&A.position.set(e.position.x,e.position.y,e.position.z),e!=null&&e.rotation&&A.rotation.set(e.rotation.x,e.rotation.y,e.rotation.z),e!=null&&e.scale&&A.scale.set(e.scale.x,e.scale.y,e.scale.z)}}const AL=class{constructor(A,e,t){B(this,"_session");B(this,"_mode");B(this,"_init");B(this,"_renderer");B(this,"_camera");B(this,"_scene");B(this,"onEnd",()=>{var A;(A=this._session)==null||A.removeEventListener("end",this.onEnd),this._renderer.setAnimationLoop(null),this._renderer.dispose(),this._scene.clear()});B(this,"_lastTime",0);B(this,"onFrame",(A,e)=>{const t=A-this._lastTime;this.update(A,t),this._camera.parent!==this._scene&&this._scene.add(this._camera),this._renderer.render(this._scene,this._camera)});B(this,"_objects",[]);this._mode=A,this._init=e,this._session=t,this._session.addEventListener("end",this.onEnd),this._renderer=new nC({alpha:!0}),this._renderer.setAnimationLoop(this.onFrame),this._renderer.xr.setSession(t),this._renderer.xr.enabled=!0,this._camera=new He,this._scene=new lI,this._scene.fog=new nk(4473924,10,250),this._scene.add(this._camera),this.setupScene()}static get active(){return this._active}static async start(A,e){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(!e)return console.error("XRSessionInit must be provided"),null;this._requestInFlight=!0;const t=await navigator.xr.requestSession(A,e);return t.addEventListener("end",()=>{this._active=null}),this._requestInFlight?(this._requestInFlight=!1,this._active=new AL(A,e,t),this._active):(t.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 vr(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 A={session:this._session,mode:this._mode,init:this._init};return await this.onBeforeHandoff(),this.onEnd(),this._session=null,A}async onBeforeHandoff(){await vr(1e3),this._scene.clear()}setupScene(){this._scene.background=new yA(0),this._scene.add(new Fk(5,10,1118481,1118481));const A=new vc(16777215,1);A.position.set(0,20,0),A.castShadow=!1,this._scene.add(A);const e=new vc(16777215,1);e.position.set(0,-1,0),e.castShadow=!1,this._scene.add(e);const t=new xc(16777215,1,100,1);t.position.set(0,2,0),t.castShadow=!1,t.distance=200,this._scene.add(t);const i=50;for(let I=0;I<100;I++){const o=new LI({color:2236962,metalness:1,roughness:.8});this.isAR&&(o.emissive=new yA(Math.random(),Math.random(),Math.random()),o.emissiveIntensity=Math.random());const s=ge.random(0,1)>.5?Hc.Sphere:Hc.Cube,n=MD.createPrimitive(s,{material:o});n.position.x=ge.random(-i,i),n.position.y=ge.random(-2,i),n.position.z=ge.random(-i,i),n.rotation.x=ge.random(0,Math.PI*2),n.rotation.y=ge.random(0,Math.PI*2),n.rotation.z=ge.random(0,Math.PI*2),n.scale.multiplyScalar(.5+Math.random()*10);const r=n.position.distanceTo(this._camera.position)-n.scale.x;r<1&&n.position.multiplyScalar(1+1/r),this._objects.push(n),this._scene.add(n)}}update(A,e){const t=A*4e-4;for(let i=0;i<this._objects.length;i++){const I=this._objects[i];I.position.y+=Math.sin(t+i*.5)*.005,I.rotateY(.002)}}};let QB=AL;B(QB,"_active",null),B(QB,"_requestInFlight",!1);const Jg=gA("debugwebxr"),PQA=gA("stats");function WQA(g){let A=null;const e=g;return e.getAROverlayContainer?A=e.getAROverlayContainer():A=g,A}ZQA();async function ZQA(){var g;if(gA("debugasap")){let A=globalThis["needle:XRSession"];if(A instanceof Promise){delete globalThis["needle:XRSession"],Et.addContextCreatedCallback(async e=>{if(!A)return;Nh(!0);const t=await A;if(t){const i=ye.getDefaultSessionInit("immersive-vr");ye.setSession("immersive-vr",t,i,e.context)}else console.error("NeedleXRSession: ASAP session was rejected");A=void 0});return}}if("xr"in navigator){if(/WebXRViewer\//i.test(navigator.userAgent)){console.warn("WebXRViewer does not support addEventListener");return}(g=navigator.xr)==null||g.addEventListener("sessiongranted",async()=>{Nh(!0),console.log("Received Session Granted..."),await vr(100);const A=sessionStorage.getItem("needle_xr_session_mode"),e=sessionStorage.getItem("needle_xr_session_init")??null,t=e?JSON.parse(e):null;let i=null;if(pZ()&&(await QB.start(A||"immersive-vr",t||ye.getDefaultSessionInit("immersive-vr")),await VQA(),i=await QB.handoff()),i)ye.setSession(i.mode,i.session,i.init,be.Current);else if(A&&e){console.log("Session Granted: Restore last session");const I=JSON.parse(e);ye.start(A,I).catch(o=>console.warn(o))}else ye.start("immersive-vr").catch(I=>console.warn("Session Granted failed:",I))},{once:!0})}}function jQA(g,A){sessionStorage.setItem("needle_xr_session_mode",g),sessionStorage.setItem("needle_xr_session_init",JSON.stringify(A))}function zQA(){sessionStorage.removeItem("needle_xr_session_mode"),sessionStorage.removeItem("needle_xr_session_init")}const Av=new Set;Et.registerCallback(Gt.ContextCreationStart,async g=>{Av.add(g.context)});Et.registerCallback(Gt.ContextCreated,async g=>{Av.delete(g.context)});function pZ(){return Av.size>0}function VQA(){return new Promise(g=>{const A=Date.now(),e=setInterval(()=>{(!pZ()||Date.now()-A>6e4)&&(clearInterval(e),g())},100)})}qc()&&ae()&&window.addEventListener("keydown",g=>{(g.key==="x"||g.key==="Escape")&&ye.active&&ye.stop()});const Ga=class{constructor(A,e,t,i){B(this,"context");B(this,"session");B(this,"mode");B(this,"controllers",[]);B(this,"_rigScale",1);B(this,"_lastRigScaleUpdate",-1);B(this,"_rigs",[]);B(this,"_viewerHitTestSource",null);B(this,"_defaultRig");B(this,"_xr_scripts");B(this,"_xr_update_scripts",[]);B(this,"_inactive_scripts",[]);B(this,"_controllerAdded");B(this,"_controllerRemoved");B(this,"_originalCameraWorldPosition");B(this,"_originalCameraWorldRotation");B(this,"_originalCameraWorldScale");B(this,"_originalCameraParent");B(this,"_mainCamera",null);B(this,"onRendererSessionSet",()=>{var A;this.running&&(this.context.renderer.xr.enabled=!0,this.context.renderer.xr.updateCamera(this.context.mainCamera),(A=this.context.mainCameraComponent)==null||A.applyClearFlags())});B(this,"onInputSourceAdded",A=>{if(A.targetRayMode==="screen")return;let e=0;for(let i=0;i<this.session.inputSources.length;i++)if(this.session.inputSources[i]===A){e=i;break}if(this.controllers.find(i=>i.inputSource===A)){console.warn("Controller already exists for input source",e);return}Jg&&console.log("Adding controller",e);const t=new Yx(this,A,e);this._newControllers.push(t)});B(this,"_ended",!1);B(this,"_newControllers",[]);B(this,"onEnd",A=>{var i,I,o;if(this._ended)return;this._ended=!0,Jg&&console.log("XR Session ended"),zQA(),this.onAfterRender(),this.revertCustomForward(),this._didStart=!1,this._previousCameraParent=null,jB(this.onBefore,oi.LateUpdate);const e=this.context.pre_render_callbacks.indexOf(this.onBeforeRender);e>=0&&this.context.pre_render_callbacks.splice(e,1);const t=this.context.post_render_callbacks.indexOf(this.onAfterRender);t>=0&&this.context.post_render_callbacks.splice(t,1),this.context.xr=null,this.context.renderer.xr.enabled=!1,this.context.pre_update_oneshot_callbacks.push(()=>{var s;(s=this.context.mainCameraComponent)==null||s.applyClearFlags()}),pW({session:this});for(const s of Ga._xrEndListeners)s({xr:this});for(let s=0;s<this.controllers.length;s++)this.disconnectInputSource(this.controllers[s].inputSource);for(const s of this._xr_scripts)(i=s==null?void 0:s.onLeaveXR)==null||i.call(s,{xr:this});(I=this.sync)==null||I.onExitXR(this),this.context.mainCamera&&((o=this._originalCameraParent)==null||o.add(this.context.mainCamera),this._originalCameraWorldPosition&&Mg(this.context.mainCamera,this._originalCameraWorldPosition),this._originalCameraWorldRotation&&zs(this.context.mainCamera,this._originalCameraWorldRotation),this._originalCameraWorldScale&&Uh(this.context.mainCamera,this._originalCameraWorldScale)),this.context.requestSizeUpdate(),this._defaultRig.gameObject.removeFromParent(),Nh(!1)});B(this,"_didStart",!1);B(this,"onBefore",A=>{var i,I,o,s,n,r,a,C;const e=A.xrFrame;if(!e)return;this.context.xr=this,this.context.mainCameraComponent&&this.context.mainCameraComponent!==this._mainCamera&&(this._mainCamera=this.context.mainCameraComponent),((i=this.rig)==null?void 0:i.isActive)==!1&&(Jg&&console.warn("Latest rig is not active - trying to activate a different rig",this.rig),this.updateActiveXRRig()),this.rig&&((I=this._mainCamera)!=null&&I.gameObject)&&((s=(o=this._mainCamera)==null?void 0:o.gameObject)==null?void 0:s.parent)!==this.rig.gameObject&&this.rig.gameObject.add((n=this._mainCamera)==null?void 0:n.gameObject),this.internalUpdateState(),this.applyCustomForward();const t={xr:this};if(this._didStart){if(this.context.new_scripts_xr.length>0){const Q=[...this.context.new_scripts_xr];for(let c=0;c<Q.length;c++){const E=this.context.new_scripts_xr[c];if(!E||E.destroyed||((r=E.supportsXR)==null?void 0:r.call(E,this.mode))==!1){this.context.new_scripts_xr.splice(c,1);continue}if(!E.activeAndEnabled){this.context.new_scripts_xr.splice(c,1),this.markInactive(E);continue}if(this.addScript(E)){this.invokeCallback_EnterXR(E);for(const h of this.controllers)this.invokeCallback_ControllerAdded(E,h)}}}}else{if(this._didStart=!0,this.mode==="immersive-vr"){const c=qr(this.context.scene.children);if(c){const E=c.getSize(dt());if(E.length()>0){const h=this._defaultRig.gameObject;h.position.set(c.min.x+E.x*.5,c.min.y,c.max.z+E.z*.5+1.5);const l=c.getCenter(dt());l.y=h.position.y,h.lookAt(l)}}}uW({session:this});for(const c of Ga._xrStartListeners)c(t);const Q=[...this._xr_scripts];Jg&&console.log("NeedleXRSession start, handle scripts:",Q);for(const c of Q){if(c.destroyed){this._script_to_remove.push(c);continue}if(!c.activeAndEnabled){this.markInactive(c);continue}this.invokeCallback_EnterXR(c);for(const E of this.controllers)this.invokeCallback_ControllerAdded(c,E)}}this.syncCameraCullingMask();for(const Q of this.controllers)Q.onUpdate(e);if(this._newControllers.length>0){const Q=[...this._newControllers];this._newControllers.length=0;for(const c of Q)if(c.connected){this.controllers.push(c);for(const E of this._xr_scripts){if(E.destroyed){this._script_to_remove.push(E);continue}E.activeAndEnabled!==!1&&this.invokeCallback_ControllerAdded(E,c)}}this.controllers.sort((c,E)=>c.index-E.index)}for(const Q of this._xr_update_scripts){if(Q.destroyed===!0){this._script_to_remove.push(Q);continue}if(Q.activeAndEnabled===!1){this.markInactive(Q);continue}Q.onUpdateXR&&Q.onUpdateXR(t)}if(this.handleInactiveScripts(),this._script_to_remove.length>0){const Q=[...new Set(this._script_to_remove)];this._script_to_remove.length=0;for(const c of Q)!c.destroyed&&this.running&&((a=c.onLeaveXR)==null||a.call(c,t)),this.removeScript(c)}(C=this.sync)==null||C.onUpdate(this),this.onRenderDebug()});B(this,"onBeforeRender",()=>{this.context.mainCamera&&this.updateFade(this.context.mainCamera)});B(this,"onAfterRender",()=>{if(this.onUpdateFade_PostRender(),qc()){const A=this.context.renderer;if(A.xr.isPresenting&&this.context.mainCamera){const e=A.xr.enabled,t=A.getRenderTarget();A.xr.enabled=!1,A.setRenderTarget(null),A.render(this.context.scene,this.context.mainCamera),A.xr.enabled=e,A.setRenderTarget(t)}}});B(this,"_script_to_remove",[]);B(this,"_camera");B(this,"_cameraRenderParent",new DA().rotateY(Math.PI));B(this,"_previousCameraParent");B(this,"_customforward",!0);B(this,"originalCameraNearPlane");B(this,"_viewerPose");B(this,"_transformOrientation",new GA);B(this,"_transformPosition",new y);B(this,"_transition");var I,o;jQA(A,i.init),this.session=e,this.mode=A,this.context=t,(Jg||gA("console"))&&Nh(!0),this._xr_scripts=[...i.scripts],this._xr_update_scripts=this._xr_scripts.filter(s=>typeof s.onUpdateXR=="function"),this._controllerAdded=i.controller_added,this._controllerRemoved=i.controller_removed,ZB(this.onBefore,oi.LateUpdate),this.context.pre_render_callbacks.push(this.onBeforeRender),this.context.post_render_callbacks.push(this.onAfterRender),((I=i.init.optionalFeatures)!=null&&I.includes("hit-test")||(o=i.init.requiredFeatures)!=null&&o.includes("hit-test"))&&e.requestReferenceSpace("viewer").then(s=>{var n,r;return(r=(n=e.requestHitTestSource)==null?void 0:n.call(e,{space:s}))==null?void 0:r.then(a=>this._viewerHitTestSource=a)}).catch(s=>console.warn(s)),this.context.mainCamera&&(this._originalCameraWorldPosition=ve(this.context.mainCamera,new y),this._originalCameraWorldRotation=Jt(this.context.mainCamera,new GA),this._originalCameraWorldScale=ii(this.context.mainCamera,new y),this._originalCameraParent=this.context.mainCamera.parent),this._defaultRig=new AQA,this.context.scene.add(this._defaultRig.gameObject),this.addRig(this._defaultRig);for(let s=0;s<e.inputSources.length;s++){const n=e.inputSources[s];if(!n.handedness){console.warn("Input source in xr session has no handedness - ignoring",s);continue}this.onInputSourceAdded(n)}this.session.addEventListener("end",this.onEnd),this.session.addEventListener("inputsourceschange",s=>{for(const n of s.removed)this.disconnectInputSource(n);for(const n of s.added)this.onInputSourceAdded(n)}),this.context.xr=this,this.context.renderer.xr.setSession(this.session).then(this.onRendererSessionSet)}static getXRSync(A){return this._sync||(this._sync=new uZ(A)),this._sync}static get currentSessionRequest(){return this._currentSessionRequestMode}static get active(){return this._activeSession}static get activeMode(){var A;return((A=this._activeSession)==null?void 0:A.mode)??null}static get xrSystem(){return"xr"in navigator?navigator.xr:void 0}static isXRSupported(){return Promise.all([this.isVRSupported(),this.isARSupported()]).then(A=>A.some(e=>e)).catch(()=>!1)}static isVRSupported(){return this.isSessionSupported("immersive-vr")}static isARSupported(){return this.isSessionSupported("immersive-ar")}static isSessionSupported(A){var e;return((e=this.xrSystem)==null?void 0:e.isSessionSupported(A).catch(t=>(Jg&&console.error(t),!1)))??Promise.resolve(!1)}static onSessionRequestStart(A){this._sessionRequestStartListeners.push(A)}static offSessionRequestStart(A){const e=this._sessionRequestStartListeners.indexOf(A);e>=0&&this._sessionRequestStartListeners.splice(e,1)}static onSessionRequestEnd(A){this._sessionRequestEndListeners.push(A)}static offSessionRequestEnd(A){const e=this._sessionRequestEndListeners.indexOf(A);e>=0&&this._sessionRequestEndListeners.splice(e,1)}static onXRSessionStart(A){this._xrStartListeners.push(A)}static offXRSessionStart(A){const e=this._xrStartListeners.indexOf(A);e>=0&&this._xrStartListeners.splice(e,1)}static onXRSessionEnd(A){this._xrEndListeners.push(A)}static offXRSessionEnd(A){const e=this._xrEndListeners.indexOf(A);e>=0&&this._xrEndListeners.splice(e,1)}static onControllerAdded(A){this._controllerAddedListeners.push(A)}static offControllerAdded(A){const e=this._controllerAddedListeners.indexOf(A);e>=0&&this._controllerAddedListeners.splice(e,1)}static onControllerRemoved(A){this._controllerRemovedListeners.push(A)}static offControllerRemoved(A){const e=this._controllerRemovedListeners.indexOf(A);e>=0&&this._controllerRemovedListeners.splice(e,1)}static offerSession(A,e,t){return"xr"in navigator&&navigator.xr&&"offerSession"in navigator.xr?(typeof navigator.xr.offerSession=="function"&&(console.log("WebXR offerSession is available - requesting mode: "+A),e=="default"&&(e=this.getDefaultSessionInit(A)),navigator.xr.offerSession(A,{...e}).then(i=>Ga.setSession(A,i,e,t)).catch(i=>{console.log("XRSession offer rejected (perhaps because another call to offerSession was made or a call to requestSession was made)")})),!0):!1}static getDefaultSessionInit(A){switch(A){case"immersive-ar":return{optionalFeatures:["anchors","local-floor","hand-tracking","layers","dom-overlay","hit-test"]};case"immersive-vr":return{optionalFeatures:["local-floor","bounded-floor","hand-tracking","high-fixed-foveation-level","layers"]};default:return console.warn("No default session init for mode",A),{}}}static async start(A,e,t){var o,s,n,r;if(ae()&&gA("debugxrpreroom"))return console.warn("Debug: Starting temporary XR session"),await QB.start(A,e||Ga.getDefaultSessionInit(A)),null;if(this._currentSessionRequest)return console.warn("A XRSession is already being requested"),(Jg||ae())&&Ot("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(t||(t=be.Current),t||(t=Et.All[0]),!t)throw new Error("No Needle Engine Context found");switch(e||(e={}),A){case"immersive-ar":{if(await((o=this.xrSystem)==null?void 0:o.isSessionSupported("immersive-ar"))!==!0)return console.error(A+" is not supported by this browser."),null;const C=this.getDefaultSessionInit(A),Q=WQA(t.domElement);Q&&!bk()&&(C.domOverlay={root:Q},C.optionalFeatures.push("dom-overlay")),e={...C,...e}}break;case"immersive-vr":{if(await((s=this.xrSystem)==null?void 0:s.isSessionSupported("immersive-vr"))!==!0)return console.error(A+" is not supported by this browser."),null;e={...this.getDefaultSessionInit(A),...e}}break;default:console.warn("No default session init for mode",A);break}e.optionalFeatures??(e.optionalFeatures=[]),e.requiredFeatures??(e.requiredFeatures=[]),await QB.stop();const i=A=="immersive-ar"?t.scripts_immersive_ar:t.scripts_immersive_vr;Jg?console.log(`%cRequesting ${A} session`,"font-weight:bold;",e,i):console.log(`%cRequesting ${A} session`,"font-weight:bold;");for(const a of i)a.onBeforeXR&&a.onBeforeXR(A,e);for(const a of this._sessionRequestStartListeners)a({mode:A,init:e});Jg&&fi("Requesting "+A+" session ("+Date.now()+")"),this._currentSessionRequest=(n=navigator.xr)==null?void 0:n.requestSession(A,e),this._currentSessionRequestMode=A;const I=await((r=this._currentSessionRequest)==null?void 0:r.catch(a=>{console.error(a,"Code: "+a.code),a.code===9&&Ot("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:"&&Ot("XR requires a secure connection (HTTPS)")}));this._currentSessionRequest=void 0,this._currentSessionRequestMode=null;for(const a of this._sessionRequestEndListeners)a({mode:A,init:e,newSession:I||null});return I?this.setSession(A,I,e,t):(console.warn("XR Session request was rejected"),null)}static setSession(A,e,t,i){if(this._activeSession)return console.error("A XRSession is already running"),this._activeSession;const I=A=="immersive-ar"?i.scripts_immersive_ar:i.scripts_immersive_vr;return this._activeSession=new Ga(A,e,i,{scripts:I,controller_added:this._controllerAddedListeners,controller_removed:this._controllerRemovedListeners,init:t}),e.addEventListener("end",this.onEnd),Jg?console.log(`%cStarted ${A} session`,"font-weight:bold;",I):console.log(`%cStarted ${A} session`,"font-weight:bold;"),this._activeSession}static stop(){var A;(A=this._activeSession)==null||A.end()}get sync(){return Ga._sync}get running(){return!this._ended&&this.session!=null}get interactionMode(){return this.session.interactionMode}get visibilityState(){return this.session.visibilityState}get environmentBlendMode(){return this.session.environmentBlendMode}get frame(){return this.context.xrFrame}get leftController(){return this.controllers.find(A=>A.isLeft)}get rightController(){return this.controllers.find(A=>A.isRight)}getController(A){return typeof A=="number"?this.controllers[A]||null:this.controllers.find(e=>e.side===A)||null}get isPassThrough(){return!!(this.environmentBlendMode!=="opaque"&&this.interactionMode==="world-space"||this.mode==="immersive-ar"&&this.environmentBlendMode!=="opaque"&&this.controllers.some(A=>A.inputSource.targetRayMode==="tracked-pointer")||ae()&&qc()&&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 A=this.frame.getImageTrackingResults();for(const e of A)if(e.trackingState==="tracked")return!0}catch{return!1}return!1}get rig(){const A=this._rigs[0]??null;return A!=null&&A.gameObject&&Yc(A.gameObject)||(A==null?void 0:A.isActive)===!1?(this.updateActiveXRRig(),this._rigs[0]??null):A}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(A){this._rigs.indexOf(A)>=0||(A.priority===void 0&&(A.priority=0),this._rigs.push(A),this.updateActiveXRRig())}removeRig(A){const e=this._rigs.indexOf(A);e!==-1&&(this._rigs.splice(e,1),this.updateActiveXRRig())}setRigActive(A){const e=this._rigs.indexOf(A);this._rigs.splice(e,1),this._rigs.unshift(A),this.updateActiveXRRig()}updateActiveXRRig(){const A=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 e=this._rigs[0];e&&e.priority===void 0&&(e.priority=0);for(let t=1;t<this._rigs.length;t++){const i=this._rigs[t];if(i.isActive){if(Yc(i.gameObject)){this._rigs.splice(t,1),t--;continue}(!e||e.isActive===!1||i.priority!==void 0&&i.priority>e.priority)&&(e=i)}}if(A!==e){const t=this._rigs.indexOf(e);t>=0&&this._rigs.splice(t,1),this._rigs.unshift(e)}Jg&&(A===e?console.log("Updated Active XR Rig:",e,"prev:",A):console.log("Updated Active XRRig:",e," (the same as before)"))}getHitTest(A){if(A)return this.getControllerHitTest(A);if(!this._viewerHitTestSource)return null;const e=this._viewerHitTestSource,t=this.frame.getHitTestResults(e);if(t.length>0){const i=t[0];return this.convertHitTestResult(i)}return null}getControllerHitTest(A){const e=A.hitTestSource;if(!e)return null;const t=this.frame.getHitTestResultsForTransientInput(e);for(const i of t)if(i.inputSource===A.inputSource)for(const I of i.results)return this.convertHitTestResult(I);return null}convertHitTestResult(A){const e=this.context.renderer.xr.getReferenceSpace(),t=e&&A.getPose(e);if(t){const i=dt(t.transform.position),I=gc(t.transform.orientation),o=this.context.mainCamera;if((o==null?void 0:o.parent)!==this._cameraRenderParent&&i.applyMatrix4(Bm),o!=null&&o.parent){i.applyMatrix4(o.parent.matrixWorld),I.multiply(bs);const s=Jt(o.parent);s.premultiply(bs),I.premultiply(s)}return{hit:A,position:i,quaternion:I}}return null}convertSpace(A){const e=dt(A.position);e.applyMatrix4(Bm);const t=gc(A.orientation);return t.premultiply(bs),{position:e,quaternion:t}}disconnectInputSource(A){const e=(t,i,I)=>{if(t.inputSource===A){Jg&&console.log("Disconnecting controller",t.index),this.controllers.splice(I,1),this.invokeControllerEvent(t,this._controllerRemoved,"removed");const o={xr:this,controller:t,change:"removed"};for(const s of this._xr_scripts)s.onXRControllerRemoved&&s.onXRControllerRemoved(o);t.onDisconnected()}};for(let t=this.controllers.length-1;t>=0;t--){const i=this.controllers[t];e(i,this.controllers,t)}for(let t=this._newControllers.length-1;t>=0;t--){const i=this._newControllers[t];e(i,this._newControllers,t)}}end(){this._ended||this.session.end().catch(A=>console.warn(A))}onRenderDebug(){if(Jg)for(const A of this.controllers)A.onRenderDebug();if((Jg||PQA)&&this.rig){const A=this.rig.gameObject.worldPosition,e=this.rig.gameObject.worldForward;A.add(e.multiplyScalar(1.5));const t=this.rig.gameObject.worldUp;A.add(t.multiplyScalar(2.5));let i="";if(i+=this.context.time.smoothedFps.toFixed(1),Jg)for(const I of this.controllers)i+=`
5235
+ `+r.href)}this.onSendQueued(Gn.OnRoomJoin);break;case"left-room":A.room===this.currentRoomName&&(this._isInRoom=!1,this._currentRoomName=null,this._currentInRoom.length=0);break;case"user-joined-room":if(A.data){const n=A.data;this._currentInRoom.push(n.userId),oo&&console.log(n.userId+" joined","now in room:",this._currentInRoom)}break;case"user-left-room":if(A.data){const n=A.data,r=this._currentInRoom.indexOf(n.userId);r>=0&&(oo&&console.log(n.userId+" left","now in room:",this._currentInRoom),this._currentInRoom.splice(r,1)),n.userId===this.connectionId&&console.log("you left the room")}break;case"all-room-state-deleted":oo&&console.log("RECEIVED all-room-state-deleted"),this._state={};break;case"ping":case"pong":const s=(i=A.data)==null?void 0:i.time;s&&(this._currentDelay=this.context.time.time-s),oo&&console.log("Current latency: "+this._currentDelay.toFixed(4)+" sec","Clients in room: "+((I=this._currentInRoom)==null?void 0:I.length));break}const e=A.data;e&&(this._state[e.guid]=e);let t=this._listeners[A.key];if(t){t=[...t];for(const o of t)try{o(A.data)}catch(s){console.error('Error invoking callback for "'+A.key+'"',s)}}}toMessage(A,e){return{key:A,data:e}}sendWithWebsocket(A,e,t=Gn.OnRoomJoin){if(!this._ws){const I=this._waitingForSocket[t]||[];I.push(()=>this.sendWithWebsocket(A,e,t)),this._waitingForSocket[t]=I;return}const i=JSON.stringify(this.toMessage(A,e));oo&&console.log(">>",A),this._ws.send(i)}onSendQueued(A){const e=this._waitingForSocket[A];if(e){for(const t of e)t();e.length=0}}}const xp=gA("debugwebxr");class LU{constructor(A,e){B(this,"controllerStates",[]);B(this,"userId");B(this,"context");B(this,"userStateEvtName");B(this,"onReceivedControllerState",A=>{xp&&console.log(`XRSync: Received change for ${this.userId}: ${A.type} ${A.handedness}; tracked=${A.isTracking}`);let e=!1;for(let t=0;t<this.controllerStates.length;t++)if(this.controllerStates[t].index===A.index){this.controllerStates[t]=A,e=!0;break}e||this.controllerStates.push(A)});this.userId=A,this.context=e,this.userStateEvtName="xr-sync-user-state-"+A,this.context.connection.beginListen(this.userStateEvtName,this.onReceivedControllerState)}dispose(){this.context.connection.stopListen(this.userStateEvtName,this.onReceivedControllerState)}update(A){if(this.context.connection.isConnected!=!1){for(let e=this.controllerStates.length-1;e>=0;e--){const t=this.controllerStates[e];let i=!1;for(let I=0;I<A.controllers.length;I++)A.controllers[I].index===t.index&&(i=!0);i||(xp&&console.log(`XRSync: ${t.type} ${t.handedness} removed`,t.index),this.controllerStates.splice(e,1),this.sendControllerRemoved(t))}for(const e of A.controllers)this.updateControllerStates(e)}}onExitXR(A){for(const e of this.controllerStates)this.sendControllerRemoved(e);this.controllerStates.length=0}sendControllerRemoved(A){A.isTracking=!1,A.guid="",this.context.connection.send(this.userStateEvtName,A),this.context.connection.sendDeleteRemoteState(A.guid)}updateControllerStates(A){const e=this.controllerStates.find(t=>t.index===A.index);if(e){let t=!1;t||(t=e.isTracking!=A.isTracking),t&&(e.isTracking=A.isTracking,this.context.connection.send(this.userStateEvtName,e))}else{const t={guid:this.userId+"-"+A.index,isTracking:A.isTracking,handedness:A.side,index:A.index,type:A.hand?"hand":"controller"};this.controllerStates.push(t),this.context.connection.send(this.userStateEvtName,t),xp&&console.log(`XRSync: ${t.type} ${t.handedness} added`,t.index)}}}class uZ{constructor(A){B(this,"context");B(this,"onJoinedRoom",()=>{if(this.context.connection.connectionId){this._states.has(this.context.connection.connectionId)||(xp&&console.log("XRSync: Local user joined room",this.context.connection.connectionId),this._states.set(this.context.connection.connectionId,new LU(this.context.connection.connectionId,this.context)));for(const A of this.context.connection.usersInRoom())this._states.has(A)||this._states.set(A,new LU(A,this.context))}});B(this,"onLeftRoom",()=>{if(this.context.connection.connectionId&&!this._states.has(this.context.connection.connectionId)){const A=this._states.get(this.context.connection.connectionId);A==null||A.dispose(),this._states.delete(this.context.connection.connectionId)}});B(this,"onOtherUserJoinedRoom",A=>{const e=A.userId;this._states.has(e)||(xp&&console.log("XRSync: Remote user joined room",e),this._states.set(e,new LU(e,this.context)))});B(this,"onOtherUserLeftRoom",A=>{const e=A.userId;if(!this._states.has(e)){const t=this._states.get(e);t==null||t.dispose(),this._states.delete(e)}});B(this,"_states",new Map);this.context=A,this.context.connection.beginListen(ze.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(ze.LeftRoom,this.onLeftRoom),this.context.connection.beginListen(ze.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.beginListen(ze.UserLeftRoom,this.onOtherUserLeftRoom)}hasState(A){return A?this._states.has(A):!1}isTracking(A,e){if(!A)return;const t=this._states.get(A);if(!t)return;const i=t.controllerStates.find(I=>I.handedness===e);return(i==null?void 0:i.isTracking)||!1}getDeviceType(A,e){if(!A)return;const t=this._states.get(A);if(!t)return;const i=t.controllerStates.find(I=>I.handedness===e);return(i==null?void 0:i.type)||"unknown"}destroy(){this.context.connection.stopListen(ze.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(ze.LeftRoom,this.onLeftRoom),this.context.connection.stopListen(ze.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.stopListen(ze.UserLeftRoom,this.onOtherUserLeftRoom)}onUpdate(A){if(this.context.connection.isConnected&&this.context.connection.connectionId){const e=this._states.get(this.context.connection.connectionId);e==null||e.update(A)}}onExitXR(A){if(this.context.connection.isConnected&&this.context.connection.connectionId){const e=this._states.get(this.context.connection.connectionId);e==null||e.onExitXR(A)}}}class e2{constructor(){B(this,"_fadeToColorQuad");B(this,"_fadeToColorMaterial");B(this,"_requestedFadeValue",0);B(this,"_transitionPromise",null);B(this,"_transitionResolve",null);this._fadeToColorMaterial=new ot({color:0,transparent:!0,depthTest:!1,fog:!1,side:kt}),this._fadeToColorQuad=new hA(new hg(10,10),this._fadeToColorMaterial)}dispose(){this._fadeToColorQuad.geometry.dispose(),this._fadeToColorMaterial.dispose()}update(A,e){const t=this._fadeToColorQuad,i=this._fadeToColorMaterial;t.parent!==A&&i.opacity>0?A.add(t):i.opacity===0&&t.removeFromParent(),t.layers.set(2),t.material=this._fadeToColorMaterial,t.position.z=-1,t.renderOrder=1/0;const I=this._requestedFadeValue;i.opacity=ge.lerp(i.opacity,I,e/.03),Math.abs(i.opacity-I)<=.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 A=new Promise(e=>{this._transitionResolve=e});return this._transitionPromise=A,A}}var Hc=(g=>(g[g.Quad=0]="Quad",g[g.Cube=1]="Cube",g[g.Sphere=2]="Sphere",g))(Hc||{});class MD{static createPrimitive(A,e){let t;switch(A){case"Quad":case 0:{const I=new hg(1,1,1,1),o=(e==null?void 0:e.material)??new LI({color:16777215});e!=null&&e.texture&&"map"in o&&(o.map=e.texture),t=new hA(I,o)}break;case"Cube":case 1:{const I=new ti(1,1,1),o=(e==null?void 0:e.material)??new LI({color:16777215});e!=null&&e.texture&&"map"in o&&(o.map=e.texture),t=new hA(I,o)}break;case"Sphere":case 2:{const I=new gn(.5,16,16),o=(e==null?void 0:e.material)??new LI({color:16777215});e!=null&&e.texture&&"map"in o&&(o.map=e.texture),t=new hA(I,o)}break}return this.applyDefaultObjectOptions(t,e),t}static createSprite(A){const t=new rk({color:16777215});A!=null&&A.texture&&"map"in t&&(t.map=A.texture);const i=new Zb(t);return this.applyDefaultObjectOptions(i,A),i}static applyDefaultObjectOptions(A,e){e!=null&&e.name&&(A.name=e.name),e!=null&&e.position&&A.position.set(e.position.x,e.position.y,e.position.z),e!=null&&e.rotation&&A.rotation.set(e.rotation.x,e.rotation.y,e.rotation.z),e!=null&&e.scale&&A.scale.set(e.scale.x,e.scale.y,e.scale.z)}}const AL=class{constructor(A,e,t){B(this,"_session");B(this,"_mode");B(this,"_init");B(this,"_renderer");B(this,"_camera");B(this,"_scene");B(this,"onEnd",()=>{var A;(A=this._session)==null||A.removeEventListener("end",this.onEnd),this._renderer.setAnimationLoop(null),this._renderer.dispose(),this._scene.clear()});B(this,"_lastTime",0);B(this,"onFrame",(A,e)=>{const t=A-this._lastTime;this.update(A,t),this._camera.parent!==this._scene&&this._scene.add(this._camera),this._renderer.render(this._scene,this._camera)});B(this,"_objects",[]);this._mode=A,this._init=e,this._session=t,this._session.addEventListener("end",this.onEnd),this._renderer=new nC({alpha:!0}),this._renderer.setAnimationLoop(this.onFrame),this._renderer.xr.setSession(t),this._renderer.xr.enabled=!0,this._camera=new He,this._scene=new lI,this._scene.fog=new nk(4473924,10,250),this._scene.add(this._camera),this.setupScene()}static get active(){return this._active}static async start(A,e){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(!e)return console.error("XRSessionInit must be provided"),null;this._requestInFlight=!0;const t=await navigator.xr.requestSession(A,e);return t.addEventListener("end",()=>{this._active=null}),this._requestInFlight?(this._requestInFlight=!1,this._active=new AL(A,e,t),this._active):(t.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 vr(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 A={session:this._session,mode:this._mode,init:this._init};return await this.onBeforeHandoff(),this.onEnd(),this._session=null,A}async onBeforeHandoff(){await vr(1e3),this._scene.clear()}setupScene(){this._scene.background=new yA(0),this._scene.add(new Fk(5,10,1118481,1118481));const A=new vc(16777215,1);A.position.set(0,20,0),A.castShadow=!1,this._scene.add(A);const e=new vc(16777215,1);e.position.set(0,-1,0),e.castShadow=!1,this._scene.add(e);const t=new xc(16777215,1,100,1);t.position.set(0,2,0),t.castShadow=!1,t.distance=200,this._scene.add(t);const i=50;for(let I=0;I<100;I++){const o=new LI({color:2236962,metalness:1,roughness:.8});this.isAR&&(o.emissive=new yA(Math.random(),Math.random(),Math.random()),o.emissiveIntensity=Math.random());const s=ge.random(0,1)>.5?Hc.Sphere:Hc.Cube,n=MD.createPrimitive(s,{material:o});n.position.x=ge.random(-i,i),n.position.y=ge.random(-2,i),n.position.z=ge.random(-i,i),n.rotation.x=ge.random(0,Math.PI*2),n.rotation.y=ge.random(0,Math.PI*2),n.rotation.z=ge.random(0,Math.PI*2),n.scale.multiplyScalar(.5+Math.random()*10);const r=n.position.distanceTo(this._camera.position)-n.scale.x;r<1&&n.position.multiplyScalar(1+1/r),this._objects.push(n),this._scene.add(n)}}update(A,e){const t=A*4e-4;for(let i=0;i<this._objects.length;i++){const I=this._objects[i];I.position.y+=Math.sin(t+i*.5)*.005,I.rotateY(.002)}}};let QB=AL;B(QB,"_active",null),B(QB,"_requestInFlight",!1);const Jg=gA("debugwebxr"),PQA=gA("stats");function WQA(g){let A=null;const e=g;return e.getAROverlayContainer?A=e.getAROverlayContainer():A=g,A}ZQA();async function ZQA(){var g;if(gA("debugasap")){let A=globalThis["needle:XRSession"];if(A instanceof Promise){delete globalThis["needle:XRSession"],Et.addContextCreatedCallback(async e=>{if(!A)return;Nh(!0);const t=await A;if(t){const i=ye.getDefaultSessionInit("immersive-vr");ye.setSession("immersive-vr",t,i,e.context)}else console.error("NeedleXRSession: ASAP session was rejected");A=void 0});return}}if("xr"in navigator){if(/WebXRViewer\//i.test(navigator.userAgent)){console.warn("WebXRViewer does not support addEventListener");return}(g=navigator.xr)==null||g.addEventListener("sessiongranted",async()=>{Nh(!0),console.log("Received Session Granted..."),await vr(100);const A=sessionStorage.getItem("needle_xr_session_mode"),e=sessionStorage.getItem("needle_xr_session_init")??null,t=e?JSON.parse(e):null;let i=null;if(pZ()&&(await QB.start(A||"immersive-vr",t||ye.getDefaultSessionInit("immersive-vr")),await VQA(),i=await QB.handoff()),i)ye.setSession(i.mode,i.session,i.init,be.Current);else if(A&&e){console.log("Session Granted: Restore last session");const I=JSON.parse(e);ye.start(A,I).catch(o=>console.warn(o))}else ye.start("immersive-vr").catch(I=>console.warn("Session Granted failed:",I))},{once:!0})}}function jQA(g,A){sessionStorage.setItem("needle_xr_session_mode",g),sessionStorage.setItem("needle_xr_session_init",JSON.stringify(A))}function zQA(){sessionStorage.removeItem("needle_xr_session_mode"),sessionStorage.removeItem("needle_xr_session_init")}const Av=new Set;Et.registerCallback(Gt.ContextCreationStart,async g=>{Av.add(g.context)});Et.registerCallback(Gt.ContextCreated,async g=>{Av.delete(g.context)});function pZ(){return Av.size>0}function VQA(){return new Promise(g=>{const A=Date.now(),e=setInterval(()=>{(!pZ()||Date.now()-A>6e4)&&(clearInterval(e),g())},100)})}qc()&&ae()&&window.addEventListener("keydown",g=>{(g.key==="x"||g.key==="Escape")&&ye.active&&ye.stop()});const Ga=class{constructor(A,e,t,i){B(this,"context");B(this,"session");B(this,"mode");B(this,"controllers",[]);B(this,"_rigScale",1);B(this,"_lastRigScaleUpdate",-1);B(this,"_rigs",[]);B(this,"_viewerHitTestSource",null);B(this,"_defaultRig");B(this,"_xr_scripts");B(this,"_xr_update_scripts",[]);B(this,"_inactive_scripts",[]);B(this,"_controllerAdded");B(this,"_controllerRemoved");B(this,"_originalCameraWorldPosition");B(this,"_originalCameraWorldRotation");B(this,"_originalCameraWorldScale");B(this,"_originalCameraParent");B(this,"_mainCamera",null);B(this,"onRendererSessionSet",()=>{var A;this.running&&(this.context.renderer.xr.enabled=!0,this.context.renderer.xr.updateCamera(this.context.mainCamera),(A=this.context.mainCameraComponent)==null||A.applyClearFlags())});B(this,"onInputSourceAdded",A=>{if(A.targetRayMode==="screen")return;let e=0;for(let i=0;i<this.session.inputSources.length;i++)if(this.session.inputSources[i]===A){e=i;break}if(this.controllers.find(i=>i.inputSource===A)){console.warn("Controller already exists for input source",e);return}Jg&&console.log("Adding controller",e);const t=new Yx(this,A,e);this._newControllers.push(t)});B(this,"_ended",!1);B(this,"_newControllers",[]);B(this,"onEnd",A=>{var i,I,o;if(this._ended)return;this._ended=!0,Jg&&console.log("XR Session ended"),zQA(),this.onAfterRender(),this.revertCustomForward(),this._didStart=!1,this._previousCameraParent=null,jB(this.onBefore,oi.LateUpdate);const e=this.context.pre_render_callbacks.indexOf(this.onBeforeRender);e>=0&&this.context.pre_render_callbacks.splice(e,1);const t=this.context.post_render_callbacks.indexOf(this.onAfterRender);t>=0&&this.context.post_render_callbacks.splice(t,1),this.context.xr=null,this.context.renderer.xr.enabled=!1,this.context.pre_update_oneshot_callbacks.push(()=>{var s;(s=this.context.mainCameraComponent)==null||s.applyClearFlags()}),pW({session:this});for(const s of Ga._xrEndListeners)s({xr:this});for(let s=0;s<this.controllers.length;s++)this.disconnectInputSource(this.controllers[s].inputSource);for(const s of this._xr_scripts)(i=s==null?void 0:s.onLeaveXR)==null||i.call(s,{xr:this});(I=this.sync)==null||I.onExitXR(this),this.context.mainCamera&&((o=this._originalCameraParent)==null||o.add(this.context.mainCamera),this._originalCameraWorldPosition&&Mg(this.context.mainCamera,this._originalCameraWorldPosition),this._originalCameraWorldRotation&&zs(this.context.mainCamera,this._originalCameraWorldRotation),this._originalCameraWorldScale&&Uh(this.context.mainCamera,this._originalCameraWorldScale)),this.context.requestSizeUpdate(),this._defaultRig.gameObject.removeFromParent(),Nh(!1)});B(this,"_didStart",!1);B(this,"onBefore",A=>{var i,I,o,s,n,r,a,C;const e=A.xrFrame;if(!e)return;this.context.xr=this,this.context.mainCameraComponent&&this.context.mainCameraComponent!==this._mainCamera&&(this._mainCamera=this.context.mainCameraComponent),((i=this.rig)==null?void 0:i.isActive)==!1&&(Jg&&console.warn("Latest rig is not active - trying to activate a different rig",this.rig),this.updateActiveXRRig()),this.rig&&((I=this._mainCamera)!=null&&I.gameObject)&&((s=(o=this._mainCamera)==null?void 0:o.gameObject)==null?void 0:s.parent)!==this.rig.gameObject&&this.rig.gameObject.add((n=this._mainCamera)==null?void 0:n.gameObject),this.internalUpdateState(),this.applyCustomForward();const t={xr:this};if(this._didStart){if(this.context.new_scripts_xr.length>0){const Q=[...this.context.new_scripts_xr];for(let c=0;c<Q.length;c++){const E=this.context.new_scripts_xr[c];if(!E||E.destroyed||((r=E.supportsXR)==null?void 0:r.call(E,this.mode))==!1){this.context.new_scripts_xr.splice(c,1);continue}if(!E.activeAndEnabled){this.context.new_scripts_xr.splice(c,1),this.markInactive(E);continue}if(this.addScript(E)){this.invokeCallback_EnterXR(E);for(const h of this.controllers)this.invokeCallback_ControllerAdded(E,h)}}}}else{if(this._didStart=!0,this.mode==="immersive-vr"){const c=qr(this.context.scene.children);if(c){const E=c.getSize(dt());if(E.length()>0){const h=this._defaultRig.gameObject;h.position.set(c.min.x+E.x*.5,c.min.y,c.max.z+E.z*.5+1.5);const l=c.getCenter(dt());l.y=h.position.y,h.lookAt(l)}}}uW({session:this});for(const c of Ga._xrStartListeners)c(t);const Q=[...this._xr_scripts];Jg&&console.log("NeedleXRSession start, handle scripts:",Q);for(const c of Q){if(c.destroyed){this._script_to_remove.push(c);continue}if(!c.activeAndEnabled){this.markInactive(c);continue}this.invokeCallback_EnterXR(c);for(const E of this.controllers)this.invokeCallback_ControllerAdded(c,E)}}this.syncCameraCullingMask();for(const Q of this.controllers)Q.onUpdate(e);if(this._newControllers.length>0){const Q=[...this._newControllers];this._newControllers.length=0;for(const c of Q)if(c.connected){this.controllers.push(c);for(const E of this._xr_scripts){if(E.destroyed){this._script_to_remove.push(E);continue}E.activeAndEnabled!==!1&&this.invokeCallback_ControllerAdded(E,c)}}this.controllers.sort((c,E)=>c.index-E.index)}for(const Q of this._xr_update_scripts){if(Q.destroyed===!0){this._script_to_remove.push(Q);continue}if(Q.activeAndEnabled===!1){this.markInactive(Q);continue}Q.onUpdateXR&&Q.onUpdateXR(t)}if(this.handleInactiveScripts(),this._script_to_remove.length>0){const Q=[...new Set(this._script_to_remove)];this._script_to_remove.length=0;for(const c of Q)!c.destroyed&&this.running&&((a=c.onLeaveXR)==null||a.call(c,t)),this.removeScript(c)}(C=this.sync)==null||C.onUpdate(this),this.onRenderDebug()});B(this,"onBeforeRender",()=>{this.context.mainCamera&&this.updateFade(this.context.mainCamera)});B(this,"onAfterRender",()=>{if(this.onUpdateFade_PostRender(),qc()){const A=this.context.renderer;if(A.xr.isPresenting&&this.context.mainCamera){const e=A.xr.enabled,t=A.getRenderTarget();A.xr.enabled=!1,A.setRenderTarget(null),A.render(this.context.scene,this.context.mainCamera),A.xr.enabled=e,A.setRenderTarget(t)}}});B(this,"_script_to_remove",[]);B(this,"_camera");B(this,"_cameraRenderParent",new DA().rotateY(Math.PI));B(this,"_previousCameraParent");B(this,"_customforward",!0);B(this,"originalCameraNearPlane");B(this,"_viewerPose");B(this,"_transformOrientation",new GA);B(this,"_transformPosition",new y);B(this,"_transition");var I,o;jQA(A,i.init),this.session=e,this.mode=A,this.context=t,(Jg||gA("console"))&&Nh(!0),this._xr_scripts=[...i.scripts],this._xr_update_scripts=this._xr_scripts.filter(s=>typeof s.onUpdateXR=="function"),this._controllerAdded=i.controller_added,this._controllerRemoved=i.controller_removed,ZB(this.onBefore,oi.LateUpdate),this.context.pre_render_callbacks.push(this.onBeforeRender),this.context.post_render_callbacks.push(this.onAfterRender),((I=i.init.optionalFeatures)!=null&&I.includes("hit-test")||(o=i.init.requiredFeatures)!=null&&o.includes("hit-test"))&&e.requestReferenceSpace("viewer").then(s=>{var n,r;return(r=(n=e.requestHitTestSource)==null?void 0:n.call(e,{space:s}))==null?void 0:r.then(a=>this._viewerHitTestSource=a)}).catch(s=>console.warn(s)),this.context.mainCamera&&(this._originalCameraWorldPosition=ve(this.context.mainCamera,new y),this._originalCameraWorldRotation=Jt(this.context.mainCamera,new GA),this._originalCameraWorldScale=ii(this.context.mainCamera,new y),this._originalCameraParent=this.context.mainCamera.parent),this._defaultRig=new AQA,this.context.scene.add(this._defaultRig.gameObject),this.addRig(this._defaultRig);for(let s=0;s<e.inputSources.length;s++){const n=e.inputSources[s];if(!n.handedness){console.warn("Input source in xr session has no handedness - ignoring",s);continue}this.onInputSourceAdded(n)}this.session.addEventListener("end",this.onEnd),this.session.addEventListener("inputsourceschange",s=>{for(const n of s.removed)this.disconnectInputSource(n);for(const n of s.added)this.onInputSourceAdded(n)}),this.context.xr=this,this.context.renderer.xr.setSession(this.session).then(this.onRendererSessionSet)}static getXRSync(A){return this._sync||(this._sync=new uZ(A)),this._sync}static get currentSessionRequest(){return this._currentSessionRequestMode}static get active(){return this._activeSession}static get activeMode(){var A;return((A=this._activeSession)==null?void 0:A.mode)??null}static get xrSystem(){return"xr"in navigator?navigator.xr:void 0}static isXRSupported(){return Promise.all([this.isVRSupported(),this.isARSupported()]).then(A=>A.some(e=>e)).catch(()=>!1)}static isVRSupported(){return this.isSessionSupported("immersive-vr")}static isARSupported(){return this.isSessionSupported("immersive-ar")}static isSessionSupported(A){var e;return((e=this.xrSystem)==null?void 0:e.isSessionSupported(A).catch(t=>(Jg&&console.error(t),!1)))??Promise.resolve(!1)}static onSessionRequestStart(A){this._sessionRequestStartListeners.push(A)}static offSessionRequestStart(A){const e=this._sessionRequestStartListeners.indexOf(A);e>=0&&this._sessionRequestStartListeners.splice(e,1)}static onSessionRequestEnd(A){this._sessionRequestEndListeners.push(A)}static offSessionRequestEnd(A){const e=this._sessionRequestEndListeners.indexOf(A);e>=0&&this._sessionRequestEndListeners.splice(e,1)}static onXRSessionStart(A){this._xrStartListeners.push(A)}static offXRSessionStart(A){const e=this._xrStartListeners.indexOf(A);e>=0&&this._xrStartListeners.splice(e,1)}static onXRSessionEnd(A){this._xrEndListeners.push(A)}static offXRSessionEnd(A){const e=this._xrEndListeners.indexOf(A);e>=0&&this._xrEndListeners.splice(e,1)}static onControllerAdded(A){this._controllerAddedListeners.push(A)}static offControllerAdded(A){const e=this._controllerAddedListeners.indexOf(A);e>=0&&this._controllerAddedListeners.splice(e,1)}static onControllerRemoved(A){this._controllerRemovedListeners.push(A)}static offControllerRemoved(A){const e=this._controllerRemovedListeners.indexOf(A);e>=0&&this._controllerRemovedListeners.splice(e,1)}static offerSession(A,e,t){return"xr"in navigator&&navigator.xr&&"offerSession"in navigator.xr?(typeof navigator.xr.offerSession=="function"&&(console.log("WebXR offerSession is available - requesting mode: "+A),e=="default"&&(e=this.getDefaultSessionInit(A)),navigator.xr.offerSession(A,{...e}).then(i=>Ga.setSession(A,i,e,t)).catch(i=>{console.log("XRSession offer rejected (perhaps because another call to offerSession was made or a call to requestSession was made)")})),!0):!1}static getDefaultSessionInit(A){switch(A){case"immersive-ar":return{optionalFeatures:["anchors","local-floor","hand-tracking","layers","dom-overlay","hit-test","unbounded"]};case"immersive-vr":return{optionalFeatures:["local-floor","bounded-floor","hand-tracking","high-fixed-foveation-level","layers"]};default:return console.warn("No default session init for mode",A),{}}}static async start(A,e,t){var o,s,n,r;if(ae()&&gA("debugxrpreroom"))return console.warn("Debug: Starting temporary XR session"),await QB.start(A,e||Ga.getDefaultSessionInit(A)),null;if(this._currentSessionRequest)return console.warn("A XRSession is already being requested"),(Jg||ae())&&Ot("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(t||(t=be.Current),t||(t=Et.All[0]),!t)throw new Error("No Needle Engine Context found");switch(e||(e={}),A){case"immersive-ar":{if(await((o=this.xrSystem)==null?void 0:o.isSessionSupported("immersive-ar"))!==!0)return console.error(A+" is not supported by this browser."),null;const C=this.getDefaultSessionInit(A),Q=WQA(t.domElement);Q&&!bk()&&(C.domOverlay={root:Q},C.optionalFeatures.push("dom-overlay")),e={...C,...e}}break;case"immersive-vr":{if(await((s=this.xrSystem)==null?void 0:s.isSessionSupported("immersive-vr"))!==!0)return console.error(A+" is not supported by this browser."),null;e={...this.getDefaultSessionInit(A),...e}}break;default:console.warn("No default session init for mode",A);break}e.optionalFeatures??(e.optionalFeatures=[]),e.requiredFeatures??(e.requiredFeatures=[]),await QB.stop();const i=A=="immersive-ar"?t.scripts_immersive_ar:t.scripts_immersive_vr;Jg?console.log(`%cRequesting ${A} session`,"font-weight:bold;",e,i):console.log(`%cRequesting ${A} session`,"font-weight:bold;");for(const a of i)a.onBeforeXR&&a.onBeforeXR(A,e);for(const a of this._sessionRequestStartListeners)a({mode:A,init:e});Jg&&fi("Requesting "+A+" session ("+Date.now()+")"),this._currentSessionRequest=(n=navigator.xr)==null?void 0:n.requestSession(A,e),this._currentSessionRequestMode=A;const I=await((r=this._currentSessionRequest)==null?void 0:r.catch(a=>{console.error(a,"Code: "+a.code),a.code===9&&Ot("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:"&&Ot("XR requires a secure connection (HTTPS)")}));this._currentSessionRequest=void 0,this._currentSessionRequestMode=null;for(const a of this._sessionRequestEndListeners)a({mode:A,init:e,newSession:I||null});return I?this.setSession(A,I,e,t):(console.warn("XR Session request was rejected"),null)}static setSession(A,e,t,i){if(this._activeSession)return console.error("A XRSession is already running"),this._activeSession;const I=A=="immersive-ar"?i.scripts_immersive_ar:i.scripts_immersive_vr;return this._activeSession=new Ga(A,e,i,{scripts:I,controller_added:this._controllerAddedListeners,controller_removed:this._controllerRemovedListeners,init:t}),e.addEventListener("end",this.onEnd),Jg?console.log(`%cStarted ${A} session`,"font-weight:bold;",I):console.log(`%cStarted ${A} session`,"font-weight:bold;"),this._activeSession}static stop(){var A;(A=this._activeSession)==null||A.end()}get sync(){return Ga._sync}get running(){return!this._ended&&this.session!=null}get interactionMode(){return this.session.interactionMode}get visibilityState(){return this.session.visibilityState}get environmentBlendMode(){return this.session.environmentBlendMode}get frame(){return this.context.xrFrame}get leftController(){return this.controllers.find(A=>A.isLeft)}get rightController(){return this.controllers.find(A=>A.isRight)}getController(A){return typeof A=="number"?this.controllers[A]||null:this.controllers.find(e=>e.side===A)||null}get isPassThrough(){return!!(this.environmentBlendMode!=="opaque"&&this.interactionMode==="world-space"||this.mode==="immersive-ar"&&this.environmentBlendMode!=="opaque"&&this.controllers.some(A=>A.inputSource.targetRayMode==="tracked-pointer")||ae()&&qc()&&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 A=this.frame.getImageTrackingResults();for(const e of A)if(e.trackingState==="tracked")return!0}catch{return!1}return!1}get rig(){const A=this._rigs[0]??null;return A!=null&&A.gameObject&&Yc(A.gameObject)||(A==null?void 0:A.isActive)===!1?(this.updateActiveXRRig(),this._rigs[0]??null):A}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(A){this._rigs.indexOf(A)>=0||(A.priority===void 0&&(A.priority=0),this._rigs.push(A),this.updateActiveXRRig())}removeRig(A){const e=this._rigs.indexOf(A);e!==-1&&(this._rigs.splice(e,1),this.updateActiveXRRig())}setRigActive(A){const e=this._rigs.indexOf(A);this._rigs.splice(e,1),this._rigs.unshift(A),this.updateActiveXRRig()}updateActiveXRRig(){const A=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 e=this._rigs[0];e&&e.priority===void 0&&(e.priority=0);for(let t=1;t<this._rigs.length;t++){const i=this._rigs[t];if(i.isActive){if(Yc(i.gameObject)){this._rigs.splice(t,1),t--;continue}(!e||e.isActive===!1||i.priority!==void 0&&i.priority>e.priority)&&(e=i)}}if(A!==e){const t=this._rigs.indexOf(e);t>=0&&this._rigs.splice(t,1),this._rigs.unshift(e)}Jg&&(A===e?console.log("Updated Active XR Rig:",e,"prev:",A):console.log("Updated Active XRRig:",e," (the same as before)"))}getHitTest(A){if(A)return this.getControllerHitTest(A);if(!this._viewerHitTestSource)return null;const e=this._viewerHitTestSource,t=this.frame.getHitTestResults(e);if(t.length>0){const i=t[0];return this.convertHitTestResult(i)}return null}getControllerHitTest(A){const e=A.hitTestSource;if(!e)return null;const t=this.frame.getHitTestResultsForTransientInput(e);for(const i of t)if(i.inputSource===A.inputSource)for(const I of i.results)return this.convertHitTestResult(I);return null}convertHitTestResult(A){const e=this.context.renderer.xr.getReferenceSpace(),t=e&&A.getPose(e);if(t){const i=dt(t.transform.position),I=gc(t.transform.orientation),o=this.context.mainCamera;if((o==null?void 0:o.parent)!==this._cameraRenderParent&&i.applyMatrix4(Bm),o!=null&&o.parent){i.applyMatrix4(o.parent.matrixWorld),I.multiply(bs);const s=Jt(o.parent);s.premultiply(bs),I.premultiply(s)}return{hit:A,position:i,quaternion:I}}return null}convertSpace(A){const e=dt(A.position);e.applyMatrix4(Bm);const t=gc(A.orientation);return t.premultiply(bs),{position:e,quaternion:t}}disconnectInputSource(A){const e=(t,i,I)=>{if(t.inputSource===A){Jg&&console.log("Disconnecting controller",t.index),this.controllers.splice(I,1),this.invokeControllerEvent(t,this._controllerRemoved,"removed");const o={xr:this,controller:t,change:"removed"};for(const s of this._xr_scripts)s.onXRControllerRemoved&&s.onXRControllerRemoved(o);t.onDisconnected()}};for(let t=this.controllers.length-1;t>=0;t--){const i=this.controllers[t];e(i,this.controllers,t)}for(let t=this._newControllers.length-1;t>=0;t--){const i=this._newControllers[t];e(i,this._newControllers,t)}}end(){this._ended||this.session.end().catch(A=>console.warn(A))}onRenderDebug(){if(Jg)for(const A of this.controllers)A.onRenderDebug();if((Jg||PQA)&&this.rig){const A=this.rig.gameObject.worldPosition,e=this.rig.gameObject.worldForward;A.add(e.multiplyScalar(1.5));const t=this.rig.gameObject.worldUp;A.add(t.multiplyScalar(2.5));let i="";if(i+=this.context.time.smoothedFps.toFixed(1),Jg)for(const I of this.controllers)i+=`
5236
5236
  ${I.hand?"hand":"ctrl"} ${I.inputSource.handedness}[${I.index}] con:${I.connected} tr:${I.isTracking}`;fe.DrawLabel(A,i)}}addScript(A){return this._xr_scripts.includes(A)?!1:(Jg&&console.log("Register new XRScript",A),this._xr_scripts.push(A),typeof A.onUpdateXR=="function"&&this._xr_update_scripts.push(A),!0)}markInactive(A){if(!(this._inactive_scripts.indexOf(A)>=0)){this.removeScript(A,!1),this._inactive_scripts.push(A);for(const e of this.controllers)this.invokeCallback_ControllerRemoved(A,e);this.invokeCallback_LeaveXR(A)}}handleInactiveScripts(){if(this._inactive_scripts.length>0)for(let A=this._inactive_scripts.length-1;A>=0;A--){const e=this._inactive_scripts[A];if(e.activeAndEnabled){this._inactive_scripts.splice(A,1),this.addScript(e),this.invokeCallback_EnterXR(e);for(const t of this.controllers)this.invokeCallback_ControllerAdded(e,t)}}}removeScript(A,e=!0){Jg&&console.log("Remove XRScript",A);const t=this._xr_scripts.indexOf(A);t>=0&&this._xr_scripts.splice(t,1);const i=this._xr_update_scripts.indexOf(A);if(i>=0&&this._xr_update_scripts.splice(i,1),e){const I=this._inactive_scripts.indexOf(A);I>=0&&this._inactive_scripts.splice(I,1)}}invokeCallback_EnterXR(A){A.onEnterXR&&A.onEnterXR({xr:this})}invokeCallback_ControllerAdded(A,e){A.onXRControllerAdded&&A.onXRControllerAdded({xr:this,controller:e,change:"added"})}invokeCallback_ControllerRemoved(A,e){A.onXRControllerRemoved&&A.onXRControllerRemoved({xr:this,controller:e,change:"removed"})}invokeCallback_LeaveXR(A){A.onLeaveXR&&!A.destroyed&&A.onLeaveXR({xr:this})}syncCameraCullingMask(){var t;const A=this.context.xrCamera,e=(t=this.context.mainCameraComponent)==null?void 0:t.cullingMask;if(A&&e!==void 0){for(const i of A.cameras)i.layers.mask=e;A.layers.mask=e}else if(A){for(const i of A.cameras)i.layers.enableAll();A.layers.enableAll()}}invokeControllerEvent(A,e,t){for(let i=e.length-1;i>=0;i--){const I=e[i];if(I)try{I({xr:this,controller:A,change:t})}catch(o){console.error(o)}}}applyCustomForward(){var A;if(this.context.mainCamera&&this._customforward){this._camera=this.context.mainCamera,this._camera.parent!==this._cameraRenderParent&&(this._previousCameraParent=this._camera.parent,(A=this._previousCameraParent)==null||A.add(this._cameraRenderParent)),this._cameraRenderParent.name="XR Camera Render Parent",this._cameraRenderParent.add(this._camera);let e=.02;if(this.rig){const t=ii(this.rig.gameObject);e*=t.x}this._camera instanceof He&&this._camera.near>e&&(this.originalCameraNearPlane=this._camera.near,this._camera.near=e)}}revertCustomForward(){this._camera&&this._previousCameraParent&&this._previousCameraParent.add(this._camera),this._previousCameraParent=null,this._camera instanceof He&&this.originalCameraNearPlane!=null&&(this._camera.near=this.originalCameraNearPlane)}internalUpdateState(){const A=this.context.renderer.xr.getReferenceSpace();if(!A){this._viewerPose=void 0;return}if(this._viewerPose=this.frame.getViewerPose(A),this._viewerPose){const e=this._viewerPose.transform;this._transformPosition.set(e.position.x,e.position.y,e.position.z),this._transformOrientation.set(e.orientation.x,e.orientation.y,e.orientation.z,e.orientation.w)}}get transition(){return this._transition||(this._transition=new e2),this._transition}fadeTransition(){return this._transition||(this._transition=new e2),this._transition.fadeTransition()}updateFade(A){this._transition&&A instanceof He&&this._transition.update(A,this.context.time.deltaTime)}onUpdateFade_PostRender(){var A;(A=this._transition)==null||A.remove()}};let ye=Ga;B(ye,"_sync",null),B(ye,"_currentSessionRequestMode",null),B(ye,"_currentSessionRequest"),B(ye,"_activeSession"),B(ye,"_sessionRequestStartListeners",[]),B(ye,"_sessionRequestEndListeners",[]),B(ye,"_xrStartListeners",[]),B(ye,"_xrEndListeners",[]),B(ye,"_controllerAddedListeners",[]),B(ye,"_controllerRemovedListeners",[]),B(ye,"onEnd",()=>{Jg&&console.log("XR Session ended"),Ga._activeSession=null});const _U=gA("debugwebxr");class fZ{static tryFindAvatarObjects(A,e,t){if(t.head&&t.leftHand&&t.rightHand)return;const i=A.name.toLocaleLowerCase();!t.head&&i.includes("head")&&(_U&&console.log("FOUND AVATAR HEAD",A.name),t.head=new et("",e,A)),i.includes("hand")&&(!t.leftHand&&i.includes("left")&&(_U&&console.log("FOUND AVATAR LEFT HAND",A.name),t.leftHand=new et("",e,A)),!t.rightHand&&i.includes("right")&&(_U&&console.log("FOUND AVATAR RIGHT HAND",A.name),t.rightHand=new et("",e,A)));for(let I=0;I<A.children.length;I++){if(t.head&&t.leftHand&&t.rightHand)return;const o=A.children[I];this.tryFindAvatarObjects(o,e,t)}}}var Em=(g=>(g.Visible="application-visible",g.Hidden="application-hidden",g.MuteChanged="application-mutechanged",g))(Em||{});let lm=!1;const Ah=[];function Cd(){if(lm)return;ae()&&console.debug("User interaction registered: audio can now be played"),lm=!0;const g=[...Ah];Ah.length=0,g.forEach(A=>A())}document.addEventListener("pointerdown",Cd);document.addEventListener("click",Cd);document.addEventListener("dragstart",Cd);document.addEventListener("touchstart",Cd);document.addEventListener("keydown",Cd);ye.onXRSessionStart(()=>{Cd()});const eL=class extends EventTarget{constructor(e){super();B(this,"_mute",!1);B(this,"context");B(this,"_isVisible",!0);this.context=e,window.addEventListener("visibilitychange",this.onVisiblityChanged.bind(this),!1)}static get userInteractionRegistered(){return lm}static registerWaitForInteraction(e){if(e!==null){if(lm){e();return}Ah.indexOf(e)===-1&&Ah.push(e)}}static unregisterWaitForInteraction(e){const t=Ah.indexOf(e);t!==-1&&Ah.splice(t,1)}get muted(){return this._mute}set muted(e){e!==this._mute&&(this._mute=e,this.dispatchEvent(new Event("application-mutechanged")))}get hasFocus(){return document.hasFocus()}get isVisible(){return this._isVisible}onVisiblityChanged(e){switch(e.target.visibilityState){case"hidden":this._isVisible=!1,this.dispatchEvent(new Event("application-hidden"));break;case"visible":this._isVisible=!0,this.dispatchEvent(new Event("application-visible"));break}}};let Fr=eL;B(Fr,"registerWaitForAllowAudio",eL.registerWaitForInteraction);function*DZ(g,A=null){const e=A?A.time:be.Current.time,t=e.time;for(;e.time-t<g;)yield}function*XQA(g){for(let A=0;A<g;A++)yield}function*yZ(g){let A=!0;for(g.then(()=>A=!1),g.catch(()=>A=!1);A;)yield}class Rf extends aJ{constructor(A){super(A),this.type=kg}parse(A){const U=Math.pow(2.7182818,2.2);function S(F,L){let $=0;for(let T=0;T<65536;++T)(T==0||F[T>>3]&1<<(T&7))&&(L[$++]=T);const N=$-1;for(;$<65536;)L[$++]=0;return N}function R(F){for(let L=0;L<16384;L++)F[L]={},F[L].len=0,F[L].lit=0,F[L].p=null}const v={l:0,c:0,lc:0};function q(F,L,$,N,T){for(;$<F;)L=L<<8|zA(N,T),$+=8;$-=F,v.l=L>>$&(1<<F)-1,v.c=L,v.lc=$}const b=new Array(59);function O(F){for(let $=0;$<=58;++$)b[$]=0;for(let $=0;$<65537;++$)b[F[$]]+=1;let L=0;for(let $=58;$>0;--$){const N=L+b[$]>>1;b[$]=L,L=N}for(let $=0;$<65537;++$){const N=F[$];N>0&&(F[$]=N|b[N]++<<6)}}function K(F,L,$,N,T,Y){const z=L;let V=0,dA=0;for(;N<=T;N++){if(z.value-L.value>$)return!1;q(6,V,dA,F,z);const cA=v.l;if(V=v.c,dA=v.lc,Y[N]=cA,cA==63){if(z.value-L.value>$)throw new Error("Something wrong with hufUnpackEncTable");q(8,V,dA,F,z);let SA=v.l+6;if(V=v.c,dA=v.lc,N+SA>T+1)throw new Error("Something wrong with hufUnpackEncTable");for(;SA--;)Y[N++]=0;N--}else if(cA>=59){let SA=cA-59+2;if(N+SA>T+1)throw new Error("Something wrong with hufUnpackEncTable");for(;SA--;)Y[N++]=0;N--}}O(Y)}function x(F){return F&63}function _(F){return F>>6}function Z(F,L,$,N){for(;L<=$;L++){const T=_(F[L]),Y=x(F[L]);if(T>>Y)throw new Error("Invalid table entry");if(Y>14){const z=N[T>>Y-14];if(z.len)throw new Error("Invalid table entry");if(z.lit++,z.p){const V=z.p;z.p=new Array(z.lit);for(let dA=0;dA<z.lit-1;++dA)z.p[dA]=V[dA]}else z.p=new Array(1);z.p[z.lit-1]=L}else if(Y){let z=0;for(let V=1<<14-Y;V>0;V--){const dA=N[(T<<14-Y)+z];if(dA.len||dA.p)throw new Error("Invalid table entry");dA.len=Y,dA.lit=L,z++}}}return!0}const j={c:0,lc:0};function oA(F,L,$,N){F=F<<8|zA($,N),L+=8,j.c=F,j.lc=L}const BA={c:0,lc:0};function UA(F,L,$,N,T,Y,z,V,dA){if(F==L){N<8&&(oA($,N,T,Y),$=j.c,N=j.lc),N-=8;let cA=$>>N;if(cA=new Uint8Array([cA])[0],V.value+cA>dA)return!1;const SA=z[V.value-1];for(;cA-- >0;)z[V.value++]=SA}else if(V.value<dA)z[V.value++]=F;else return!1;BA.c=$,BA.lc=N}function IA(F){return F&65535}function pA(F){const L=IA(F);return L>32767?L-65536:L}const MA={a:0,b:0};function vA(F,L){const $=pA(F),T=pA(L),Y=$+(T&1)+(T>>1),z=Y,V=Y-T;MA.a=z,MA.b=V}function ZA(F,L){const $=IA(F),N=IA(L),T=$-(N>>1)&65535,Y=N+T-32768&65535;MA.a=Y,MA.b=T}function OA(F,L,$,N,T,Y,z){const V=z<16384,dA=$>T?T:$;let cA=1,SA,bA;for(;cA<=dA;)cA<<=1;for(cA>>=1,SA=cA,cA>>=1;cA>=1;){bA=0;const xA=bA+Y*(T-SA),WA=Y*cA,$A=Y*SA,te=N*cA,Be=N*SA;let Me,St,We,Ne;for(;bA<=xA;bA+=$A){let Lt=bA;const me=bA+N*($-SA);for(;Lt<=me;Lt+=Be){const Zt=Lt+te,zI=Lt+WA,ci=zI+te;V?(vA(F[Lt+L],F[zI+L]),Me=MA.a,We=MA.b,vA(F[Zt+L],F[ci+L]),St=MA.a,Ne=MA.b,vA(Me,St),F[Lt+L]=MA.a,F[Zt+L]=MA.b,vA(We,Ne),F[zI+L]=MA.a,F[ci+L]=MA.b):(ZA(F[Lt+L],F[zI+L]),Me=MA.a,We=MA.b,ZA(F[Zt+L],F[ci+L]),St=MA.a,Ne=MA.b,ZA(Me,St),F[Lt+L]=MA.a,F[Zt+L]=MA.b,ZA(We,Ne),F[zI+L]=MA.a,F[ci+L]=MA.b)}if($&cA){const Zt=Lt+WA;V?vA(F[Lt+L],F[Zt+L]):ZA(F[Lt+L],F[Zt+L]),Me=MA.a,F[Zt+L]=MA.b,F[Lt+L]=Me}}if(T&cA){let Lt=bA;const me=bA+N*($-SA);for(;Lt<=me;Lt+=Be){const Zt=Lt+te;V?vA(F[Lt+L],F[Zt+L]):ZA(F[Lt+L],F[Zt+L]),Me=MA.a,F[Zt+L]=MA.b,F[Lt+L]=Me}}SA=cA,cA>>=1}return bA}function he(F,L,$,N,T,Y,z,V,dA){let cA=0,SA=0;const bA=z,xA=Math.trunc(N.value+(T+7)/8);for(;N.value<xA;)for(oA(cA,SA,$,N),cA=j.c,SA=j.lc;SA>=14;){const $A=cA>>SA-14&16383,te=L[$A];if(te.len)SA-=te.len,UA(te.lit,Y,cA,SA,$,N,V,dA,bA),cA=BA.c,SA=BA.lc;else{if(!te.p)throw new Error("hufDecode issues");let Be;for(Be=0;Be<te.lit;Be++){const Me=x(F[te.p[Be]]);for(;SA<Me&&N.value<xA;)oA(cA,SA,$,N),cA=j.c,SA=j.lc;if(SA>=Me&&_(F[te.p[Be]])==(cA>>SA-Me&(1<<Me)-1)){SA-=Me,UA(te.p[Be],Y,cA,SA,$,N,V,dA,bA),cA=BA.c,SA=BA.lc;break}}if(Be==te.lit)throw new Error("hufDecode issues")}}const WA=8-T&7;for(cA>>=WA,SA-=WA;SA>0;){const $A=L[cA<<14-SA&16383];if($A.len)SA-=$A.len,UA($A.lit,Y,cA,SA,$,N,V,dA,bA),cA=BA.c,SA=BA.lc;else throw new Error("hufDecode issues")}return!0}function oe(F,L,$,N,T,Y){const z={value:0},V=$.value,dA=ce(L,$),cA=ce(L,$);$.value+=4;const SA=ce(L,$);if($.value+=4,dA<0||dA>=65537||cA<0||cA>=65537)throw new Error("Something wrong with HUF_ENCSIZE");const bA=new Array(65537),xA=new Array(16384);R(xA);const WA=N-($.value-V);if(K(F,$,WA,dA,cA,bA),SA>8*(N-($.value-V)))throw new Error("Something wrong with hufUncompress");Z(bA,dA,cA,xA),he(bA,xA,F,$,SA,cA,Y,T,z)}function W(F,L,$){for(let N=0;N<$;++N)L[N]=F[L[N]]}function HA(F){for(let L=1;L<F.length;L++){const $=F[L-1]+F[L]-128;F[L]=$}}function mA(F,L){let $=0,N=Math.floor((F.length+1)/2),T=0;const Y=F.length-1;for(;!(T>Y||(L[T++]=F[$++],T>Y));)L[T++]=F[N++]}function _A(F){let L=F.byteLength;const $=new Array;let N=0;const T=new DataView(F);for(;L>0;){const Y=T.getInt8(N++);if(Y<0){const z=-Y;L-=z+1;for(let V=0;V<z;V++)$.push(T.getUint8(N++))}else{const z=Y;L-=2;const V=T.getUint8(N++);for(let dA=0;dA<z+1;dA++)$.push(V)}}return $}function RA(F,L,$,N,T,Y){let z=new DataView(Y.buffer);const V=$[F.idx[0]].width,dA=$[F.idx[0]].height,cA=3,SA=Math.floor(V/8),bA=Math.ceil(V/8),xA=Math.ceil(dA/8),WA=V-(bA-1)*8,$A=dA-(xA-1)*8,te={value:0},Be=new Array(cA),Me=new Array(cA),St=new Array(cA),We=new Array(cA),Ne=new Array(cA);for(let me=0;me<cA;++me)Ne[me]=L[F.idx[me]],Be[me]=me<1?0:Be[me-1]+bA*xA,Me[me]=new Float32Array(64),St[me]=new Uint16Array(64),We[me]=new Uint16Array(bA*64);for(let me=0;me<xA;++me){let Zt=8;me==xA-1&&(Zt=$A);let zI=8;for(let yt=0;yt<bA;++yt){yt==bA-1&&(zI=WA);for(let je=0;je<cA;++je)St[je].fill(0),St[je][0]=T[Be[je]++],ie(te,N,St[je]),ee(St[je],Me[je]),re(Me[je]);qe(Me);for(let je=0;je<cA;++je)H(Me[je],We[je],yt*64)}let ci=0;for(let yt=0;yt<cA;++yt){const je=$[F.idx[yt]].type;for(let $g=8*me;$g<8*me+Zt;++$g){ci=Ne[yt][$g];for(let ea=0;ea<SA;++ea){const ki=ea*64+($g&7)*8;z.setUint16(ci+0*2*je,We[yt][ki+0],!0),z.setUint16(ci+1*2*je,We[yt][ki+1],!0),z.setUint16(ci+2*2*je,We[yt][ki+2],!0),z.setUint16(ci+3*2*je,We[yt][ki+3],!0),z.setUint16(ci+4*2*je,We[yt][ki+4],!0),z.setUint16(ci+5*2*je,We[yt][ki+5],!0),z.setUint16(ci+6*2*je,We[yt][ki+6],!0),z.setUint16(ci+7*2*je,We[yt][ki+7],!0),ci+=8*2*je}}if(SA!=bA)for(let $g=8*me;$g<8*me+Zt;++$g){const ea=Ne[yt][$g]+8*SA*2*je,ki=SA*64+($g&7)*8;for(let pC=0;pC<zI;++pC)z.setUint16(ea+pC*2*je,We[yt][ki+pC],!0)}}}const Lt=new Uint16Array(V);z=new DataView(Y.buffer);for(let me=0;me<cA;++me){$[F.idx[me]].decoded=!0;const Zt=$[F.idx[me]].type;if($[me].type==2)for(let zI=0;zI<dA;++zI){const ci=Ne[me][zI];for(let yt=0;yt<V;++yt)Lt[yt]=z.getUint16(ci+yt*2*Zt,!0);for(let yt=0;yt<V;++yt)z.setFloat32(ci+yt*2*Zt,CA(Lt[yt]),!0)}}}function ie(F,L,$){let N,T=1;for(;T<64;)N=L[F.value],N==65280?T=64:N>>8==255?T+=N&255:($[T]=N,T++),F.value++}function ee(F,L){L[0]=CA(F[0]),L[1]=CA(F[1]),L[2]=CA(F[5]),L[3]=CA(F[6]),L[4]=CA(F[14]),L[5]=CA(F[15]),L[6]=CA(F[27]),L[7]=CA(F[28]),L[8]=CA(F[2]),L[9]=CA(F[4]),L[10]=CA(F[7]),L[11]=CA(F[13]),L[12]=CA(F[16]),L[13]=CA(F[26]),L[14]=CA(F[29]),L[15]=CA(F[42]),L[16]=CA(F[3]),L[17]=CA(F[8]),L[18]=CA(F[12]),L[19]=CA(F[17]),L[20]=CA(F[25]),L[21]=CA(F[30]),L[22]=CA(F[41]),L[23]=CA(F[43]),L[24]=CA(F[9]),L[25]=CA(F[11]),L[26]=CA(F[18]),L[27]=CA(F[24]),L[28]=CA(F[31]),L[29]=CA(F[40]),L[30]=CA(F[44]),L[31]=CA(F[53]),L[32]=CA(F[10]),L[33]=CA(F[19]),L[34]=CA(F[23]),L[35]=CA(F[32]),L[36]=CA(F[39]),L[37]=CA(F[45]),L[38]=CA(F[52]),L[39]=CA(F[54]),L[40]=CA(F[20]),L[41]=CA(F[22]),L[42]=CA(F[33]),L[43]=CA(F[38]),L[44]=CA(F[46]),L[45]=CA(F[51]),L[46]=CA(F[55]),L[47]=CA(F[60]),L[48]=CA(F[21]),L[49]=CA(F[34]),L[50]=CA(F[37]),L[51]=CA(F[47]),L[52]=CA(F[50]),L[53]=CA(F[56]),L[54]=CA(F[59]),L[55]=CA(F[61]),L[56]=CA(F[35]),L[57]=CA(F[36]),L[58]=CA(F[48]),L[59]=CA(F[49]),L[60]=CA(F[57]),L[61]=CA(F[58]),L[62]=CA(F[62]),L[63]=CA(F[63])}function re(F){const L=.5*Math.cos(.7853975),$=.5*Math.cos(3.14159/16),N=.5*Math.cos(3.14159/8),T=.5*Math.cos(3*3.14159/16),Y=.5*Math.cos(5*3.14159/16),z=.5*Math.cos(3*3.14159/8),V=.5*Math.cos(7*3.14159/16),dA=new Array(4),cA=new Array(4),SA=new Array(4),bA=new Array(4);for(let xA=0;xA<8;++xA){const WA=xA*8;dA[0]=N*F[WA+2],dA[1]=z*F[WA+2],dA[2]=N*F[WA+6],dA[3]=z*F[WA+6],cA[0]=$*F[WA+1]+T*F[WA+3]+Y*F[WA+5]+V*F[WA+7],cA[1]=T*F[WA+1]-V*F[WA+3]-$*F[WA+5]-Y*F[WA+7],cA[2]=Y*F[WA+1]-$*F[WA+3]+V*F[WA+5]+T*F[WA+7],cA[3]=V*F[WA+1]-Y*F[WA+3]+T*F[WA+5]-$*F[WA+7],SA[0]=L*(F[WA+0]+F[WA+4]),SA[3]=L*(F[WA+0]-F[WA+4]),SA[1]=dA[0]+dA[3],SA[2]=dA[1]-dA[2],bA[0]=SA[0]+SA[1],bA[1]=SA[3]+SA[2],bA[2]=SA[3]-SA[2],bA[3]=SA[0]-SA[1],F[WA+0]=bA[0]+cA[0],F[WA+1]=bA[1]+cA[1],F[WA+2]=bA[2]+cA[2],F[WA+3]=bA[3]+cA[3],F[WA+4]=bA[3]-cA[3],F[WA+5]=bA[2]-cA[2],F[WA+6]=bA[1]-cA[1],F[WA+7]=bA[0]-cA[0]}for(let xA=0;xA<8;++xA)dA[0]=N*F[16+xA],dA[1]=z*F[16+xA],dA[2]=N*F[48+xA],dA[3]=z*F[48+xA],cA[0]=$*F[8+xA]+T*F[24+xA]+Y*F[40+xA]+V*F[56+xA],cA[1]=T*F[8+xA]-V*F[24+xA]-$*F[40+xA]-Y*F[56+xA],cA[2]=Y*F[8+xA]-$*F[24+xA]+V*F[40+xA]+T*F[56+xA],cA[3]=V*F[8+xA]-Y*F[24+xA]+T*F[40+xA]-$*F[56+xA],SA[0]=L*(F[xA]+F[32+xA]),SA[3]=L*(F[xA]-F[32+xA]),SA[1]=dA[0]+dA[3],SA[2]=dA[1]-dA[2],bA[0]=SA[0]+SA[1],bA[1]=SA[3]+SA[2],bA[2]=SA[3]-SA[2],bA[3]=SA[0]-SA[1],F[0+xA]=bA[0]+cA[0],F[8+xA]=bA[1]+cA[1],F[16+xA]=bA[2]+cA[2],F[24+xA]=bA[3]+cA[3],F[32+xA]=bA[3]-cA[3],F[40+xA]=bA[2]-cA[2],F[48+xA]=bA[1]-cA[1],F[56+xA]=bA[0]-cA[0]}function qe(F){for(let L=0;L<64;++L){const $=F[0][L],N=F[1][L],T=F[2][L];F[0][L]=$+1.5747*T,F[1][L]=$-.1873*N-.4682*T,F[2][L]=$+1.8556*N}}function H(F,L,$){for(let N=0;N<64;++N)L[$+N]=tc.toHalfFloat(J(F[N]))}function J(F){return F<=1?Math.sign(F)*Math.pow(Math.abs(F),2.2):Math.sign(F)*Math.pow(U,Math.abs(F)-1)}function uA(F){return new DataView(F.array.buffer,F.offset.value,F.size)}function wA(F){const L=F.viewer.buffer.slice(F.offset.value,F.offset.value+F.size),$=new Uint8Array(_A(L)),N=new Uint8Array($.length);return HA($),mA($,N),new DataView(N.buffer)}function KA(F){const L=F.array.slice(F.offset.value,F.offset.value+F.size),$=ju(L),N=new Uint8Array($.length);return HA($),mA($,N),new DataView(N.buffer)}function NA(F){const L=F.viewer,$={value:F.offset.value},N=new Uint16Array(F.width*F.scanlineBlockSize*(F.channels*F.type)),T=new Uint8Array(8192);let Y=0;const z=new Array(F.channels);for(let $A=0;$A<F.channels;$A++)z[$A]={},z[$A].start=Y,z[$A].end=z[$A].start,z[$A].nx=F.width,z[$A].ny=F.lines,z[$A].size=F.type,Y+=z[$A].nx*z[$A].ny*z[$A].size;const V=AA(L,$),dA=AA(L,$);if(dA>=8192)throw new Error("Something is wrong with PIZ_COMPRESSION BITMAP_SIZE");if(V<=dA)for(let $A=0;$A<dA-V+1;$A++)T[$A+V]=Ee(L,$);const cA=new Uint16Array(65536),SA=S(T,cA),bA=ce(L,$);oe(F.array,L,$,bA,N,Y);for(let $A=0;$A<F.channels;++$A){const te=z[$A];for(let Be=0;Be<z[$A].size;++Be)OA(N,te.start+Be,te.nx,te.size,te.ny,te.nx*te.size,SA)}W(cA,N,Y);let xA=0;const WA=new Uint8Array(N.buffer.byteLength);for(let $A=0;$A<F.lines;$A++)for(let te=0;te<F.channels;te++){const Be=z[te],Me=Be.nx*Be.size,St=new Uint8Array(N.buffer,Be.end*2,Me*2);WA.set(St,xA),xA+=Me*2,Be.end+=Me}return new DataView(WA.buffer)}function De(F){const L=F.array.slice(F.offset.value,F.offset.value+F.size),$=ju(L),N=F.lines*F.channels*F.width,T=F.type==1?new Uint16Array(N):new Uint32Array(N);let Y=0,z=0;const V=new Array(4);for(let dA=0;dA<F.lines;dA++)for(let cA=0;cA<F.channels;cA++){let SA=0;switch(F.type){case 1:V[0]=Y,V[1]=V[0]+F.width,Y=V[1]+F.width;for(let bA=0;bA<F.width;++bA){const xA=$[V[0]++]<<8|$[V[1]++];SA+=xA,T[z]=SA,z++}break;case 2:V[0]=Y,V[1]=V[0]+F.width,V[2]=V[1]+F.width,Y=V[2]+F.width;for(let bA=0;bA<F.width;++bA){const xA=$[V[0]++]<<24|$[V[1]++]<<16|$[V[2]++]<<8;SA+=xA,T[z]=SA,z++}break}}return new DataView(T.buffer)}function Qe(F){const L=F.viewer,$={value:F.offset.value},N=new Uint8Array(F.width*F.lines*(F.channels*F.type*2)),T={version:se(L,$),unknownUncompressedSize:se(L,$),unknownCompressedSize:se(L,$),acCompressedSize:se(L,$),dcCompressedSize:se(L,$),rleCompressedSize:se(L,$),rleUncompressedSize:se(L,$),rleRawSize:se(L,$),totalAcUncompressedCount:se(L,$),totalDcUncompressedCount:se(L,$),acCompression:se(L,$)};if(T.version<2)throw new Error("EXRLoader.parse: "+uC.compression+" version "+T.version+" is unsupported");const Y=new Array;let z=AA(L,$)-2;for(;z>0;){const te=qA(L.buffer,$),Be=Ee(L,$),Me=Be>>2&3,St=(Be>>4)-1,We=new Int8Array([St])[0],Ne=Ee(L,$);Y.push({name:te,index:We,type:Ne,compression:Me}),z-=te.length+3}const V=uC.channels,dA=new Array(F.channels);for(let te=0;te<F.channels;++te){const Be=dA[te]={},Me=V[te];Be.name=Me.name,Be.compression=0,Be.decoded=!1,Be.type=Me.pixelType,Be.pLinear=Me.pLinear,Be.width=F.width,Be.height=F.lines}const cA={idx:new Array(3)};for(let te=0;te<F.channels;++te){const Be=dA[te];for(let Me=0;Me<Y.length;++Me){const St=Y[Me];Be.name==St.name&&(Be.compression=St.compression,St.index>=0&&(cA.idx[St.index]=te),Be.offset=te)}}let SA,bA,xA;if(T.acCompressedSize>0)switch(T.acCompression){case 0:SA=new Uint16Array(T.totalAcUncompressedCount),oe(F.array,L,$,T.acCompressedSize,SA,T.totalAcUncompressedCount);break;case 1:const te=F.array.slice($.value,$.value+T.totalAcUncompressedCount),Be=ju(te);SA=new Uint16Array(Be.buffer),$.value+=T.totalAcUncompressedCount;break}if(T.dcCompressedSize>0){const te={array:F.array,offset:$,size:T.dcCompressedSize};bA=new Uint16Array(KA(te).buffer),$.value+=T.dcCompressedSize}if(T.rleRawSize>0){const te=F.array.slice($.value,$.value+T.rleCompressedSize),Be=ju(te);xA=_A(Be.buffer),$.value+=T.rleCompressedSize}let WA=0;const $A=new Array(dA.length);for(let te=0;te<$A.length;++te)$A[te]=new Array;for(let te=0;te<F.lines;++te)for(let Be=0;Be<dA.length;++Be)$A[Be].push(WA),WA+=dA[Be].width*F.type*2;RA(cA,$A,dA,SA,bA,N);for(let te=0;te<dA.length;++te){const Be=dA[te];if(!Be.decoded)switch(Be.compression){case 2:let Me=0,St=0;for(let We=0;We<F.lines;++We){let Ne=$A[te][Me];for(let Lt=0;Lt<Be.width;++Lt){for(let me=0;me<2*Be.type;++me)N[Ne++]=xA[St+me*Be.width*Be.height];St++}Me++}break;case 1:default:throw new Error("EXRLoader.parse: unsupported channel compression")}}return new DataView(N.buffer)}function qA(F,L){const $=new Uint8Array(F);let N=0;for(;$[L.value+N]!=0;)N+=1;const T=new TextDecoder().decode($.slice(L.value,L.value+N));return L.value=L.value+N+1,T}function PA(F,L,$){const N=new TextDecoder().decode(new Uint8Array(F).slice(L.value,L.value+$));return L.value=L.value+$,N}function Se(F,L){const $=it(F,L),N=ce(F,L);return[$,N]}function LA(F,L){const $=ce(F,L),N=ce(F,L);return[$,N]}function it(F,L){const $=F.getInt32(L.value,!0);return L.value=L.value+4,$}function ce(F,L){const $=F.getUint32(L.value,!0);return L.value=L.value+4,$}function zA(F,L){const $=F[L.value];return L.value=L.value+1,$}function Ee(F,L){const $=F.getUint8(L.value);return L.value=L.value+1,$}const se=function(F,L){let $;return"getBigInt64"in DataView.prototype?$=Number(F.getBigInt64(L.value,!0)):$=F.getUint32(L.value+4,!0)+Number(F.getUint32(L.value,!0)<<32),L.value+=8,$};function Fe(F,L){const $=F.getFloat32(L.value,!0);return L.value+=4,$}function P(F,L){return tc.toHalfFloat(Fe(F,L))}function CA(F){const L=(F&31744)>>10,$=F&1023;return(F>>15?-1:1)*(L?L===31?$?NaN:1/0:Math.pow(2,L-15)*(1+$/1024):6103515625e-14*($/1024))}function AA(F,L){const $=F.getUint16(L.value,!0);return L.value+=2,$}function JA(F,L){return CA(AA(F,L))}function QA(F,L,$,N){const T=$.value,Y=[];for(;$.value<T+N-1;){const z=qA(L,$),V=it(F,$),dA=Ee(F,$);$.value+=3;const cA=it(F,$),SA=it(F,$);Y.push({name:z,pixelType:V,pLinear:dA,xSampling:cA,ySampling:SA})}return $.value+=1,Y}function YA(F,L){const $=Fe(F,L),N=Fe(F,L),T=Fe(F,L),Y=Fe(F,L),z=Fe(F,L),V=Fe(F,L),dA=Fe(F,L),cA=Fe(F,L);return{redX:$,redY:N,greenX:T,greenY:Y,blueX:z,blueY:V,whiteX:dA,whiteY:cA}}function VA(F,L){const $=["NO_COMPRESSION","RLE_COMPRESSION","ZIPS_COMPRESSION","ZIP_COMPRESSION","PIZ_COMPRESSION","PXR24_COMPRESSION","B44_COMPRESSION","B44A_COMPRESSION","DWAA_COMPRESSION","DWAB_COMPRESSION"],N=Ee(F,L);return $[N]}function gt(F,L){const $=ce(F,L),N=ce(F,L),T=ce(F,L),Y=ce(F,L);return{xMin:$,yMin:N,xMax:T,yMax:Y}}function Kt(F,L){const $=["INCREASING_Y"],N=Ee(F,L);return $[N]}function Bi(F,L){const $=Fe(F,L),N=Fe(F,L);return[$,N]}function Qi(F,L){const $=Fe(F,L),N=Fe(F,L),T=Fe(F,L);return[$,N,T]}function st(F,L,$,N,T){if(N==="string"||N==="stringvector"||N==="iccProfile")return PA(L,$,T);if(N==="chlist")return QA(F,L,$,T);if(N==="chromaticities")return YA(F,$);if(N==="compression")return VA(F,$);if(N==="box2i")return gt(F,$);if(N==="lineOrder")return Kt(F,$);if(N==="float")return Fe(F,$);if(N==="v2f")return Bi(F,$);if(N==="v3f")return Qi(F,$);if(N==="int")return it(F,$);if(N==="rational")return Se(F,$);if(N==="timecode")return LA(F,$);if(N==="preview")return $.value+=T,"skipped";$.value+=T}function mi(F,L,$){const N={};if(F.getUint32(0,!0)!=20000630)throw new Error("THREE.EXRLoader: Provided file doesn't appear to be in OpenEXR format.");N.version=F.getUint8(4);const T=F.getUint8(5);N.spec={singleTile:!!(T&2),longName:!!(T&4),deepFormat:!!(T&8),multiPart:!!(T&16)},$.value=8;let Y=!0;for(;Y;){const z=qA(L,$);if(z==0)Y=!1;else{const V=qA(L,$),dA=ce(F,$),cA=st(F,L,$,V,dA);cA===void 0?console.warn(`THREE.EXRLoader: Skipped unknown header attribute type '${V}'.`):N[z]=cA}}if(T&-5)throw console.error("THREE.EXRHeader:",N),new Error("THREE.EXRLoader: Provided file is currently unsupported.");return N}function vi(F,L,$,N,T){const Y={size:0,viewer:L,array:$,offset:N,width:F.dataWindow.xMax-F.dataWindow.xMin+1,height:F.dataWindow.yMax-F.dataWindow.yMin+1,channels:F.channels.length,bytesPerLine:null,lines:null,inputSize:null,type:F.channels[0].pixelType,uncompress:null,getter:null,format:null,colorSpace:Ht};switch(F.compression){case"NO_COMPRESSION":Y.lines=1,Y.uncompress=uA;break;case"RLE_COMPRESSION":Y.lines=1,Y.uncompress=wA;break;case"ZIPS_COMPRESSION":Y.lines=1,Y.uncompress=KA;break;case"ZIP_COMPRESSION":Y.lines=16,Y.uncompress=KA;break;case"PIZ_COMPRESSION":Y.lines=32,Y.uncompress=NA;break;case"PXR24_COMPRESSION":Y.lines=16,Y.uncompress=De;break;case"DWAA_COMPRESSION":Y.lines=32,Y.uncompress=Qe;break;case"DWAB_COMPRESSION":Y.lines=256,Y.uncompress=Qe;break;default:throw new Error("EXRLoader.parse: "+F.compression+" is unsupported")}if(Y.scanlineBlockSize=Y.lines,Y.type==1)switch(T){case gg:Y.getter=JA,Y.inputSize=2;break;case kg:Y.getter=AA,Y.inputSize=2;break}else if(Y.type==2)switch(T){case gg:Y.getter=Fe,Y.inputSize=4;break;case kg:Y.getter=P,Y.inputSize=4}else throw new Error("EXRLoader.parse: unsupported pixelType "+Y.type+" for "+F.compression+".");Y.blockCount=(F.dataWindow.yMax+1)/Y.scanlineBlockSize;for(let V=0;V<Y.blockCount;V++)se(L,N);Y.outputChannels=Y.channels==3?4:Y.channels;const z=Y.width*Y.height*Y.outputChannels;switch(T){case gg:Y.byteArray=new Float32Array(z),Y.channels<Y.outputChannels&&Y.byteArray.fill(1,0,z);break;case kg:Y.byteArray=new Uint16Array(z),Y.channels<Y.outputChannels&&Y.byteArray.fill(15360,0,z);break;default:console.error("THREE.EXRLoader: unsupported type: ",T);break}return Y.bytesPerLine=Y.width*Y.inputSize*Y.channels,Y.outputChannels==4?(Y.format=ai,Y.colorSpace=Ht):(Y.format=$h,Y.colorSpace=Mo),Y}const To=new DataView(A),dC=new Uint8Array(A),Ho={value:0},uC=mi(To,A,Ho),tt=vi(uC,To,dC,Ho,this.type),Pd={value:0},Dy={R:0,G:1,B:2,A:3,Y:0};for(let F=0;F<tt.height/tt.scanlineBlockSize;F++){const L=ce(To,Ho);tt.size=ce(To,Ho),tt.lines=L+tt.scanlineBlockSize>tt.height?tt.height-L:tt.scanlineBlockSize;const N=tt.size<tt.lines*tt.bytesPerLine?tt.uncompress(tt):uA(tt);Ho.value+=tt.size;for(let T=0;T<tt.scanlineBlockSize;T++){const Y=T+F*tt.scanlineBlockSize;if(Y>=tt.height)break;for(let z=0;z<tt.channels;z++){const V=Dy[uC.channels[z].name];for(let dA=0;dA<tt.width;dA++){Pd.value=(T*(tt.channels*tt.width)+z*tt.width+dA)*tt.inputSize;const cA=(tt.height-1-Y)*(tt.width*tt.outputChannels)+dA*tt.outputChannels+V;tt.byteArray[cA]=tt.getter(N,Pd)}}}}return{header:uC,width:tt.width,height:tt.height,data:tt.byteArray,format:tt.format,colorSpace:tt.colorSpace,type:this.type}}setDataType(A){return this.type=A,this}load(A,e,t,i){function I(o,s){o.colorSpace=s.colorSpace,o.minFilter=xe,o.magFilter=xe,o.generateMipmaps=!1,o.flipY=!1,e&&e(o,s)}return super.load(A,I,t,i)}}const $QA=Object.freeze(Object.defineProperty({__proto__:null,EXRLoader:Rf},Symbol.toStringTag,{value:"Module"}));class hm extends aJ{constructor(A){super(A),this.type=kg}parse(A){const o=function(G,U){switch(G){case 1:throw new Error("THREE.RGBELoader: Read Error: "+(U||""));case 2:throw new Error("THREE.RGBELoader: Write Error: "+(U||""));case 3:throw new Error("THREE.RGBELoader: Bad File Format: "+(U||""));default:case 4:throw new Error("THREE.RGBELoader: Memory Error: "+(U||""))}},a=`
5237
5237
  `,C=function(G,U,S){U=U||1024;let v=G.pos,q=-1,b=0,O="",K=String.fromCharCode.apply(null,new Uint16Array(G.subarray(v,v+128)));for(;0>(q=K.indexOf(a))&&b<U&&v<G.byteLength;)O+=K,b+=K.length,v+=128,K+=String.fromCharCode.apply(null,new Uint16Array(G.subarray(v,v+128)));return-1<q?(S!==!1&&(G.pos+=b+q+1),O+K.slice(0,q)):!1},Q=function(G){const U=/^#\?(\S+)/,S=/^\s*GAMMA\s*=\s*(\d+(\.\d+)?)\s*$/,R=/^\s*EXPOSURE\s*=\s*(\d+(\.\d+)?)\s*$/,v=/^\s*FORMAT=(\S+)\s*$/,q=/^\s*\-Y\s+(\d+)\s+\+X\s+(\d+)\s*$/,b={valid:0,string:"",comments:"",programtype:"RGBE",format:"",gamma:1,exposure:1,width:0,height:0};let O,K;for((G.pos>=G.byteLength||!(O=C(G)))&&o(1,"no header found"),(K=O.match(U))||o(3,"bad initial token"),b.valid|=1,b.programtype=K[1],b.string+=O+`
5238
5238
  `;O=C(G),O!==!1;){if(b.string+=O+`
@@ -5266,7 +5266,7 @@ TEX `+t.texture_lod;if(TU=="density"&&(p+=`
5266
5266
  `+(d/i.lastScreenCoverage).toFixed(0)+` dens
5267
5267
  `+(i.lastScreenCoverage*100).toFixed(1)+`% cov
5268
5268
  `+(i.lastCentrality*100).toFixed(1)+`% centr
5269
- `+(aS.min.x.toFixed(2)+"-"+aS.max.x.toFixed(2)+"x"+aS.min.y.toFixed(2)+"-"+aS.max.y.toFixed(2))+" scr"),i.lastScreenCoverage>.1){const u=A,f=u.worldForward,w=u.worldPosition,M=dt(f).multiplyScalar(Q*.7).add(C),G=M.distanceTo(w),U=c[Math.min(c.length-1,Math.max(0,I))]+"88",S=this.context.domHeight>0?screen.height/this.context.domHeight:1,R=A.isPerspectiveCamera?Math.tan(A.fov*Math.PI/180/2):1;fe.DrawLabel(M,p,G*.012*S*R,void 0,16777215,U)}}}}}const BS=gA("debugphysics"),g2=new qI;class Yn{constructor(){B(this,"ray");B(this,"cam");B(this,"screenPoint");B(this,"raycaster");B(this,"results");B(this,"targets");B(this,"recursive",!0);B(this,"minDistance");B(this,"maxDistance");B(this,"lineThreshold");B(this,"layerMask");B(this,"ignore");B(this,"testObject")}screenPointFromOffset(A,e){this.screenPoint===void 0&&(this.screenPoint=new tA),this.screenPoint.x=A/window.innerWidth*2-1,this.screenPoint.y=-(e/window.innerHeight)*2+1}setLayer(A){g2.set(A),this.layerMask=g2}setMask(A){this.layerMask||(this.layerMask=new qI);const e=this.layerMask;e?e.mask=A:this.layerMask=A}}B(Yn,"AllLayers",4294967295);class wZ{constructor(A,e,t){B(this,"distance");B(this,"point");B(this,"object");this.object=A,this.distance=e,this.point=t}}class SZ{constructor(A){B(this,"context");B(this,"engine");B(this,"raycaster",new AE);B(this,"defaultRaycastOptions",new Yn);B(this,"targetBuffer",new Array(1));B(this,"defaultThresholds",{Mesh:{},Line:{threshold:-1},LOD:{},Points:{threshold:0},Sprite:{}});B(this,"sphereResults",new Array);B(this,"sphereMask",new qI);B(this,"tempBoundingBox",new Nt);this.context=A}raycastPhysicsFast(A,e=void 0,t=1/0,i=!0){var I;return((I=this.context.physics.engine)==null?void 0:I.raycast(A,e,{maxDistance:t,solid:i}))??null}raycastPhysicsFastAndGetNormal(A,e=void 0,t=1/0,i=!0){var I;return((I=this.context.physics.engine)==null?void 0:I.raycastAndGetNormal(A,e,{maxDistance:t,solid:i}))??null}sphereOverlapPhysics(A,e){var t;return((t=this.context.physics.engine)==null?void 0:t.sphereOverlap(A,e))??null}sphereOverlap(A,e,t=!0){if(this.sphereResults.length=0,!this.context.scene)return this.sphereResults;const i=new Zi(A,e),I=this.sphereMask;I.enableAll(),I.disable(2);for(const o of this.context.scene.children)this.onSphereOverlap(o,i,I,this.sphereResults,t);return this.sphereResults.sort((o,s)=>o.distance-s.distance)}onSphereOverlap(A,e,t,i,I){if(A.type==="Mesh"&&A.layers.test(t)&&!fe.isGizmo(A)){const o=A,s=o.geometry;if(s&&(s.boundingBox||s.computeBoundingBox(),s.boundingBox)){o.matrixWorldNeedsUpdate&&o.updateMatrixWorld();const n=this.tempBoundingBox.copy(s.boundingBox).applyMatrix4(o.matrixWorld);if(e.intersectsBox(n)){const r=ve(A),a=r.distanceTo(e.center),C=new wZ(A,a,r);if(i.push(C),!I)return}}}if(A.children)for(const o of A.children){const s=i.length;if(this.onSphereOverlap(o,e,t,i,I),s!=i.length&&!I)return}}raycastFromRay(A,e=null){const t=e??this.defaultRaycastOptions;t.ray=A;const i=this.raycast(t);return t===this.defaultRaycastOptions&&(t.ray=void 0),i}raycast(A=null){A||(A=this.defaultRaycastOptions);const e=A.screenPoint??this.context.input.mousePositionRC,t=A.raycaster??this.raycaster;if(t.near=A.minDistance??0,t.far=A.maxDistance??1/0,t.params=this.defaultThresholds,A.lineThreshold===void 0&&(A.lineThreshold=-1),t.params.Line={threshold:A.lineThreshold},A.ray)t.ray.copy(A.ray);else{const s=A.cam??this.context.mainCamera;if(!s)return BS&&console.error("Can not perform raycast - no main camera found"),this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),this.defaultRaycastOptions.results??[];const n=this.context.xrCamera;this.context.isInXR&&n instanceof Wb&&n.cameras.length>0?t.setFromCamera(e,n.cameras[0]):t.setFromCamera(e,s)}let i=A.targets;i||(i=this.targetBuffer,i.length=1,i[0]=this.context.scene);let I=A.results;this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),I||(this.defaultRaycastOptions.results||(this.defaultRaycastOptions.results=new Array),I=this.defaultRaycastOptions.results),A.layerMask!==void 0?A.layerMask instanceof qI?t.layers.mask=A.layerMask.mask:t.layers.mask=A.layerMask:(t.layers.enableAll(),t.layers.disable(2)),BS&&(fe.DrawRay(t.ray.origin,t.ray.direction,16711680,2),console.time("raycast")),I.length=0,this.intersect(this.raycaster,i,I,A),I.sort((s,n)=>s.distance-n.distance);const o=A.ignore;return o!==void 0&&o.length>0&&(I=I.filter(s=>!o.includes(s.object))),BS&&(console.timeEnd("raycast"),console.warn("#"+this.context.time.frame+", hits:",I!=null&&I.length?[...I]:"nothing")),I}intersect(A,e,t,i){var I;for(const o of e){if(o.visible===!1||fe.isGizmo(o)||i.lineThreshold!==void 0&&i.lineThreshold<0&&o instanceof Oi)continue;const s=(I=i.testObject)==null?void 0:I.call(i,o);if(s===!1)continue;if(s!=="continue in children"){const r=o,a=r.geometry;if(a){const C=DD(o);C&&(r.geometry=C);const Q=t.length;A.intersectObject(o,!1,t),BS&&t.length!=Q&&fe.DrawWireMesh({mesh:o,depthTest:!1,duration:.2,color:C?8969557:7798784}),r.geometry=a}}i.recursive!==!1&&this.intersect(A,o.children,t,i)}return t}}const gcA=gA("debugplayerview");var SB=(g=>(g.Browser="browser",g.Headset="headset",g.Handheld="handheld",g))(SB||{});class mZ{constructor(A,e){B(this,"userId");B(this,"context");B(this,"viewDevice","browser");B(this,"removed",!1);B(this,"_object");this.userId=A,this.context=e}get currentObject(){return this._object}set currentObject(A){this._object=A}get isConnected(){return this.context.connection.userIsInRoom(this.userId)}}class kZ{constructor(A){B(this,"context");B(this,"playerViews",new Map);this.context=A}setPlayerView(A,e,t){let i=this.playerViews.get(A);i||(i=new mZ(A,this.context),this.playerViews.set(A,i)),i.viewDevice=t,i.currentObject=e,i.removed=!1}getPlayerView(A){if(!A)return;if(!this.context.connection.userIsInRoom(A)){this.playerViews.delete(A);return}return this.playerViews.get(A)}removePlayerView(A,e){const t=this.playerViews.get(A);(t==null?void 0:t.viewDevice)===e&&(gcA&&console.log("REMOVE",A),t.removed=!0,this.playerViews.delete(A))}}new HI;const GD=new Uint8Array(4);GD[0]=255;GD[1]=255;GD[2]=255;GD[3]=255;const IcA=new rs(GD,1,1,ai);function ev(g,A=1){const e="alpha"in g,t=A*A,i=new Uint8Array(4*t),I=Math.floor(g.r*255),o=Math.floor(g.g*255),s=Math.floor(g.b*255);for(let r=0;r<t;r++){const a=r*4;i[a+0]=I,i[a+1]=o,i[a+2]=s,e?i[a+3]=Math.floor(g.alpha*255):i[a+3]=255}const n=new rs(i,A,A);return n.needsUpdate=!0,n}function ocA(g,A,e,t=1,i=3){const o=t*i,s=[g,A,e],n=s.length,r=new Uint8Array(4*n*o),a=new yA;for(let Q=0;Q<i;Q++){const c=Math.floor(Q/i*n),E=ge.clamp(c+1,0,n-1),h=s[c],l=s[E],d=Q/i*n%1;a.lerpColors(h,l,d);const p=Math.floor(a.r*255),u=Math.floor(a.g*255),f=Math.floor(a.b*255);for(let w=0;w<t;w++){const m=(Q*t+w)*4;r[m+0]=p,r[m+1]=u,r[m+2]=f,r[m+3]=255}}const C=new rs(r,t,i);return C.needsUpdate=!0,C}function dm(g,A){const e=g.elements;A||(A=[]),A.length=0;for(let t=0;t<16;t+=4){const i=e[t],I=e[t+1],o=e[t+2],s=e[t+3],n=new Ae(i,I,o,s);A.push(n)}return A}const HU=[],I2=[];function scA(g,A){if(HU.length===0)for(let e=0;e<27;e++)HU.push(0);A||(A=HU);for(let e=0;e<27;e++)I2[e]=A[e];A=I2,g.unity_SHAr={value:new Ae(A[9],A[3],A[6],A[0])},g.unity_SHBr={value:new Ae(A[12],A[15],A[18],A[21])},g.unity_SHAg={value:new Ae(A[10],A[4],A[7],A[1])},g.unity_SHBg={value:new Ae(A[13],A[16],A[19],A[22])},g.unity_SHAb={value:new Ae(A[11],A[5],A[8],A[2])},g.unity_SHBb={value:new Ae(A[14],A[17],A[20],A[23])},g.unity_SHC={value:new Ae(A[24],A[25],A[26],1)}}class ncA{constructor(A,e,t){B(this,"vertexShader");B(this,"fragmentShader");B(this,"technique");this.vertexShader=A,this.fragmentShader=e,this.technique=t}}async function rcA(g,A){if(!g)return console.error("Can not find technique: no shader data"),null;const e=g.programs[A],t=e.vertexShader,i=e.fragmentShader;if(t!==void 0&&i!==void 0){const I=g.shaders[t],o=g.shaders[i];if(I.uri&&o.uri||I.code&&o.code){if(!I.code&&I.uri&&await o2(I),!o.code&&o.uri&&await o2(o),!I.code||!o.code)return null;const s=g.techniques[A];return new ncA(I.code,o.code,s)}}return console.error("Shader technique not found",A),null}async function o2(g){const A=g.uri;if(A)if(A.endsWith(".glsl")){const t=await new HI().loadAsync(A);g.code=t.toString()}else g.code=acA(g.uri)}function acA(g){return decodeURIComponent(Array.prototype.map.call(atob(g),function(A){return"%"+("00"+A.charCodeAt(0).toString(16)).slice(-2)}).join(""))}const Dn=gA("debugenvlight");var dh=(g=>(g[g.Skybox=0]="Skybox",g[g.Trilight=1]="Trilight",g[g.Flat=3]="Flat",g[g.Custom=4]="Custom",g))(dh||{}),um=(g=>(g[g.Skybox=0]="Skybox",g[g.Custom=1]="Custom",g))(um||{});class MZ{constructor(A){B(this,"context");B(this,"_currentLightSettingsId");B(this,"_sceneLightSettings");B(this,"_timevec4",new Ae);B(this,"__currentReflectionId",null);B(this,"_lighting",{});this.context=A,this.context.pre_update_callbacks.push(this.preUpdate.bind(this))}preUpdate(){const A=this.context.time;this._timevec4.x=A.time,this._timevec4.y=Math.sin(A.time),this._timevec4.z=Math.cos(A.time),this._timevec4.w=A.deltaTime}get timeVec4(){return this._timevec4}get environmentIntensity(){if(!this._sceneLightSettings||!this._currentLightSettingsId)return 1;const A=this._sceneLightSettings.get(this._currentLightSettingsId);return A?A.ambientIntensity:1}get sceneLightSettings(){var A;return(A=this._sceneLightSettings)==null?void 0:A.values()}enable(A){var t;A instanceof et&&(A=A.uri);const e=(t=this._sceneLightSettings)==null?void 0:t.get(A);return e?(Dn&&console.log("Enable scene light settings",A,e),A!==this._currentLightSettingsId&&this._currentLightSettingsId&&this.disable(this._currentLightSettingsId),this._currentLightSettingsId=A,e.enabled=!0,!0):(Dn&&console.warn("No light settings found for",A),!1)}disable(A){var t;if(A instanceof et&&(A=A.uri),A==null)return!1;const e=(t=this._sceneLightSettings)==null?void 0:t.get(A);return e?(Dn&&console.log("Disable scene light settings",A,e),e.enabled=!1,!0):!1}disableCurrent(){if(this._currentLightSettingsId){const A=this._currentLightSettingsId;return this.disable(this._currentLightSettingsId),A}return null}internalRegisterSceneLightSettings(A){const e=A.sourceId;if(!e){console.error("Missing source id for scene light settings, can not register:",A);return}Dn&&console.log("Register "+(A==null?void 0:A.sourceId)+" lighting",A),this._sceneLightSettings||(this._sceneLightSettings=new Map),this._sceneLightSettings.set(e,A)}internalUnregisterSceneLightSettings(A){const e=A.sourceId;if(!e){console.error("Missing source id for scene light settings, can not unregister:",A);return}Dn&&console.log("Unregister "+(A==null?void 0:A.sourceId)+" lighting",A),this._sceneLightSettings&&this._sceneLightSettings.delete(e)}internalRegisterReflection(A,e){Dn&&console.log("Register reflection",A,e);const t=new GZ(this.context,e,1);this._lighting[A]=t}internalGetReflection(A){return this._lighting[A]}internalEnableReflection(A){var t;this.__currentReflectionId=A;const e=(t=this._sceneLightSettings)==null?void 0:t.get(A);switch(Dn&&console.log("Enable reflection",A,e?dh[e.ambientMode]:"Unknown ambient mode",e),e==null?void 0:e.ambientMode){case 0:case 4:const i=this.internalGetReflection(A);if(i&&i.Source){Dn&&console.log("Setting environment reflection",i);const I=this.context.scene,o=i.Source;o.mapping=No,I.environment=o;return}else Dn&&console.warn("Could not find reflection for source",A);break}if((e==null?void 0:e.environmentReflectionSource)===1)switch(e==null?void 0:e.ambientMode){case 1:if(e.ambientTrilight){const i=e.ambientTrilight,I=ocA(i[0],i[1],i[2],64,64);I.colorSpace=pe,I.mapping=No,this.context.scene.environment=I}else console.error("Missing ambient trilight",e.sourceId);return;case 3:if(e.ambientLight){const i=ev(e.ambientLight,64);i.colorSpace=pe,i.mapping=No,this.context.scene.environment=i}else console.error("Missing ambientlight",e.sourceId);return;default:return}}internalDisableReflection(A){if(A&&A!==this.__currentReflectionId){Dn&&console.log("Not disabling reflection for",A,"because it is not the current light settings id",this.__currentReflectionId);return}Dn&&console.log("Disable reflection",A);const e=this.context.scene;e.environment=null}}class GZ{constructor(A,e,t=1){B(this,"_source");this._source=e,e.mapping=No}get Source(){return this._source}}const s2=gA("timescale");let LK=1;typeof s2=="number"&&(LK=s2);class RZ{constructor(){B(this,"_time",0);B(this,"_deltaTime",0);B(this,"_deltaTimeUnscaled",0);B(this,"timeScale",1);B(this,"_frame",0);B(this,"clock",new QJ);B(this,"_smoothedFps",0);B(this,"_smoothedDeltaTime",0);B(this,"_fpsSamples",[]);B(this,"_fpsSampleIndex",0);typeof LK=="number"&&(this.timeScale=LK)}get time(){return this._time}set time(A){this._time=A}get deltaTime(){return this._deltaTime}set deltaTime(A){this._deltaTime=A}get deltaTimeUnscaled(){return this._deltaTimeUnscaled}get frame(){return this._frame}set frame(A){this._frame=A}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 A=0;for(let e=0;e<this._fpsSamples.length;e++)A+=this._fpsSamples[e];this._smoothedDeltaTime=A/this._fpsSamples.length,this._smoothedFps=1/this._smoothedDeltaTime}}let n2=!1;function UZ(g){n2||(n2=!0,CcA(),BcA())}UZ();function CcA(){const g=`
5269
+ `+(aS.min.x.toFixed(2)+"-"+aS.max.x.toFixed(2)+"x"+aS.min.y.toFixed(2)+"-"+aS.max.y.toFixed(2))+" scr"),i.lastScreenCoverage>.1){const u=A,f=u.worldForward,w=u.worldPosition,M=dt(f).multiplyScalar(Q*.7).add(C),G=M.distanceTo(w),U=c[Math.min(c.length-1,Math.max(0,I))]+"88",S=this.context.domHeight>0?screen.height/this.context.domHeight:1,R=A.isPerspectiveCamera?Math.tan(A.fov*Math.PI/180/2):1;fe.DrawLabel(M,p,G*.012*S*R,void 0,16777215,U)}}}}}const BS=gA("debugphysics"),g2=new qI;class Yn{constructor(){B(this,"ray");B(this,"cam");B(this,"screenPoint");B(this,"raycaster");B(this,"results");B(this,"targets");B(this,"recursive",!0);B(this,"minDistance");B(this,"maxDistance");B(this,"lineThreshold");B(this,"layerMask");B(this,"ignore");B(this,"testObject")}screenPointFromOffset(A,e){this.screenPoint===void 0&&(this.screenPoint=new tA),this.screenPoint.x=A/window.innerWidth*2-1,this.screenPoint.y=-(e/window.innerHeight)*2+1}setLayer(A){g2.set(A),this.layerMask=g2}setMask(A){this.layerMask||(this.layerMask=new qI);const e=this.layerMask;e?e.mask=A:this.layerMask=A}}B(Yn,"AllLayers",4294967295);class wZ{constructor(A,e,t){B(this,"distance");B(this,"point");B(this,"object");this.object=A,this.distance=e,this.point=t}}class SZ{constructor(A){B(this,"context");B(this,"engine");B(this,"raycaster",new AE);B(this,"defaultRaycastOptions",new Yn);B(this,"targetBuffer",new Array(1));B(this,"defaultThresholds",{Mesh:{},Line:{threshold:-1},LOD:{},Points:{threshold:0},Sprite:{}});B(this,"sphereResults",new Array);B(this,"sphereMask",new qI);B(this,"tempBoundingBox",new Nt);this.context=A}raycastPhysicsFast(A,e=void 0,t=1/0,i=!0){var I;return((I=this.context.physics.engine)==null?void 0:I.raycast(A,e,{maxDistance:t,solid:i}))??null}raycastPhysicsFastAndGetNormal(A,e=void 0,t=1/0,i=!0){var I;return((I=this.context.physics.engine)==null?void 0:I.raycastAndGetNormal(A,e,{maxDistance:t,solid:i}))??null}sphereOverlapPhysics(A,e){var t;return((t=this.context.physics.engine)==null?void 0:t.sphereOverlap(A,e))??null}sphereOverlap(A,e,t=!0){if(this.sphereResults.length=0,!this.context.scene)return this.sphereResults;const i=new Zi(A,e),I=this.sphereMask;I.enableAll(),I.disable(2);for(const o of this.context.scene.children)this.onSphereOverlap(o,i,I,this.sphereResults,t);return this.sphereResults.sort((o,s)=>o.distance-s.distance)}onSphereOverlap(A,e,t,i,I){if(A.type==="Mesh"&&A.layers.test(t)&&!fe.isGizmo(A)){const o=A,s=o.geometry;if(s&&(s.boundingBox||s.computeBoundingBox(),s.boundingBox)){o.matrixWorldNeedsUpdate&&o.updateMatrixWorld();const n=this.tempBoundingBox.copy(s.boundingBox).applyMatrix4(o.matrixWorld);if(e.intersectsBox(n)){const r=ve(A),a=r.distanceTo(e.center),C=new wZ(A,a,r);if(i.push(C),!I)return}}}if(A.children)for(const o of A.children){const s=i.length;if(this.onSphereOverlap(o,e,t,i,I),s!=i.length&&!I)return}}raycastFromRay(A,e=null){const t=e??this.defaultRaycastOptions;t.ray=A;const i=this.raycast(t);return t===this.defaultRaycastOptions&&(t.ray=void 0),i}raycast(A=null){A||(A=this.defaultRaycastOptions);const e=A.screenPoint??this.context.input.mousePositionRC,t=A.raycaster??this.raycaster;if(t.near=A.minDistance??0,t.far=A.maxDistance??1/0,t.params=this.defaultThresholds,A.lineThreshold===void 0&&(A.lineThreshold=-1),t.params.Line={threshold:A.lineThreshold},A.ray)t.ray.copy(A.ray);else{const s=A.cam??this.context.mainCamera;if(!s)return BS&&console.error("Can not perform raycast - no main camera found"),this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),this.defaultRaycastOptions.results??[];const n=this.context.xrCamera;this.context.isInXR&&n instanceof Wb&&n.cameras.length>0?t.setFromCamera(e,n.cameras[0]):t.setFromCamera(e,s)}let i=A.targets;i||(i=this.targetBuffer,i.length=1,i[0]=this.context.scene);let I=A.results;this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),I||(this.defaultRaycastOptions.results||(this.defaultRaycastOptions.results=new Array),I=this.defaultRaycastOptions.results),A.layerMask!==void 0?A.layerMask instanceof qI?t.layers.mask=A.layerMask.mask:t.layers.mask=A.layerMask:(t.layers.enableAll(),t.layers.disable(2)),BS&&(fe.DrawRay(t.ray.origin,t.ray.direction,16711680,2),console.time("raycast")),I.length=0,this.intersect(this.raycaster,i,I,A),I.sort((s,n)=>s.distance-n.distance);const o=A.ignore;return o!==void 0&&o.length>0&&(I=I.filter(s=>!o.includes(s.object))),BS&&(console.timeEnd("raycast"),console.warn("#"+this.context.time.frame+", hits:",I!=null&&I.length?[...I]:"nothing")),I}intersect(A,e,t,i){var I;for(const o of e){if(!o||o.visible===!1||fe.isGizmo(o)||i.lineThreshold!==void 0&&i.lineThreshold<0&&o instanceof Oi)continue;const s=(I=i.testObject)==null?void 0:I.call(i,o);if(s===!1)continue;if(s!=="continue in children"){const r=o,a=r.geometry;if(a){const C=DD(o);C&&(r.geometry=C);const Q=t.length;A.intersectObject(o,!1,t),BS&&t.length!=Q&&fe.DrawWireMesh({mesh:o,depthTest:!1,duration:.2,color:C?8969557:7798784}),r.geometry=a}}i.recursive!==!1&&this.intersect(A,o.children,t,i)}return t}}const gcA=gA("debugplayerview");var SB=(g=>(g.Browser="browser",g.Headset="headset",g.Handheld="handheld",g))(SB||{});class mZ{constructor(A,e){B(this,"userId");B(this,"context");B(this,"viewDevice","browser");B(this,"removed",!1);B(this,"_object");this.userId=A,this.context=e}get currentObject(){return this._object}set currentObject(A){this._object=A}get isConnected(){return this.context.connection.userIsInRoom(this.userId)}}class kZ{constructor(A){B(this,"context");B(this,"playerViews",new Map);this.context=A}setPlayerView(A,e,t){let i=this.playerViews.get(A);i||(i=new mZ(A,this.context),this.playerViews.set(A,i)),i.viewDevice=t,i.currentObject=e,i.removed=!1}getPlayerView(A){if(!A)return;if(!this.context.connection.userIsInRoom(A)){this.playerViews.delete(A);return}return this.playerViews.get(A)}removePlayerView(A,e){const t=this.playerViews.get(A);(t==null?void 0:t.viewDevice)===e&&(gcA&&console.log("REMOVE",A),t.removed=!0,this.playerViews.delete(A))}}new HI;const GD=new Uint8Array(4);GD[0]=255;GD[1]=255;GD[2]=255;GD[3]=255;const IcA=new rs(GD,1,1,ai);function ev(g,A=1){const e="alpha"in g,t=A*A,i=new Uint8Array(4*t),I=Math.floor(g.r*255),o=Math.floor(g.g*255),s=Math.floor(g.b*255);for(let r=0;r<t;r++){const a=r*4;i[a+0]=I,i[a+1]=o,i[a+2]=s,e?i[a+3]=Math.floor(g.alpha*255):i[a+3]=255}const n=new rs(i,A,A);return n.needsUpdate=!0,n}function ocA(g,A,e,t=1,i=3){const o=t*i,s=[g,A,e],n=s.length,r=new Uint8Array(4*n*o),a=new yA;for(let Q=0;Q<i;Q++){const c=Math.floor(Q/i*n),E=ge.clamp(c+1,0,n-1),h=s[c],l=s[E],d=Q/i*n%1;a.lerpColors(h,l,d);const p=Math.floor(a.r*255),u=Math.floor(a.g*255),f=Math.floor(a.b*255);for(let w=0;w<t;w++){const m=(Q*t+w)*4;r[m+0]=p,r[m+1]=u,r[m+2]=f,r[m+3]=255}}const C=new rs(r,t,i);return C.needsUpdate=!0,C}function dm(g,A){const e=g.elements;A||(A=[]),A.length=0;for(let t=0;t<16;t+=4){const i=e[t],I=e[t+1],o=e[t+2],s=e[t+3],n=new Ae(i,I,o,s);A.push(n)}return A}const HU=[],I2=[];function scA(g,A){if(HU.length===0)for(let e=0;e<27;e++)HU.push(0);A||(A=HU);for(let e=0;e<27;e++)I2[e]=A[e];A=I2,g.unity_SHAr={value:new Ae(A[9],A[3],A[6],A[0])},g.unity_SHBr={value:new Ae(A[12],A[15],A[18],A[21])},g.unity_SHAg={value:new Ae(A[10],A[4],A[7],A[1])},g.unity_SHBg={value:new Ae(A[13],A[16],A[19],A[22])},g.unity_SHAb={value:new Ae(A[11],A[5],A[8],A[2])},g.unity_SHBb={value:new Ae(A[14],A[17],A[20],A[23])},g.unity_SHC={value:new Ae(A[24],A[25],A[26],1)}}class ncA{constructor(A,e,t){B(this,"vertexShader");B(this,"fragmentShader");B(this,"technique");this.vertexShader=A,this.fragmentShader=e,this.technique=t}}async function rcA(g,A){if(!g)return console.error("Can not find technique: no shader data"),null;const e=g.programs[A],t=e.vertexShader,i=e.fragmentShader;if(t!==void 0&&i!==void 0){const I=g.shaders[t],o=g.shaders[i];if(I.uri&&o.uri||I.code&&o.code){if(!I.code&&I.uri&&await o2(I),!o.code&&o.uri&&await o2(o),!I.code||!o.code)return null;const s=g.techniques[A];return new ncA(I.code,o.code,s)}}return console.error("Shader technique not found",A),null}async function o2(g){const A=g.uri;if(A)if(A.endsWith(".glsl")){const t=await new HI().loadAsync(A);g.code=t.toString()}else g.code=acA(g.uri)}function acA(g){return decodeURIComponent(Array.prototype.map.call(atob(g),function(A){return"%"+("00"+A.charCodeAt(0).toString(16)).slice(-2)}).join(""))}const Dn=gA("debugenvlight");var dh=(g=>(g[g.Skybox=0]="Skybox",g[g.Trilight=1]="Trilight",g[g.Flat=3]="Flat",g[g.Custom=4]="Custom",g))(dh||{}),um=(g=>(g[g.Skybox=0]="Skybox",g[g.Custom=1]="Custom",g))(um||{});class MZ{constructor(A){B(this,"context");B(this,"_currentLightSettingsId");B(this,"_sceneLightSettings");B(this,"_timevec4",new Ae);B(this,"__currentReflectionId",null);B(this,"_lighting",{});this.context=A,this.context.pre_update_callbacks.push(this.preUpdate.bind(this))}preUpdate(){const A=this.context.time;this._timevec4.x=A.time,this._timevec4.y=Math.sin(A.time),this._timevec4.z=Math.cos(A.time),this._timevec4.w=A.deltaTime}get timeVec4(){return this._timevec4}get environmentIntensity(){if(!this._sceneLightSettings||!this._currentLightSettingsId)return 1;const A=this._sceneLightSettings.get(this._currentLightSettingsId);return A?A.ambientIntensity:1}get sceneLightSettings(){var A;return(A=this._sceneLightSettings)==null?void 0:A.values()}enable(A){var t;A instanceof et&&(A=A.uri);const e=(t=this._sceneLightSettings)==null?void 0:t.get(A);return e?(Dn&&console.log("Enable scene light settings",A,e),A!==this._currentLightSettingsId&&this._currentLightSettingsId&&this.disable(this._currentLightSettingsId),this._currentLightSettingsId=A,e.enabled=!0,!0):(Dn&&console.warn("No light settings found for",A),!1)}disable(A){var t;if(A instanceof et&&(A=A.uri),A==null)return!1;const e=(t=this._sceneLightSettings)==null?void 0:t.get(A);return e?(Dn&&console.log("Disable scene light settings",A,e),e.enabled=!1,!0):!1}disableCurrent(){if(this._currentLightSettingsId){const A=this._currentLightSettingsId;return this.disable(this._currentLightSettingsId),A}return null}internalRegisterSceneLightSettings(A){const e=A.sourceId;if(!e){console.error("Missing source id for scene light settings, can not register:",A);return}Dn&&console.log("Register "+(A==null?void 0:A.sourceId)+" lighting",A),this._sceneLightSettings||(this._sceneLightSettings=new Map),this._sceneLightSettings.set(e,A)}internalUnregisterSceneLightSettings(A){const e=A.sourceId;if(!e){console.error("Missing source id for scene light settings, can not unregister:",A);return}Dn&&console.log("Unregister "+(A==null?void 0:A.sourceId)+" lighting",A),this._sceneLightSettings&&this._sceneLightSettings.delete(e)}internalRegisterReflection(A,e){Dn&&console.log("Register reflection",A,e);const t=new GZ(this.context,e,1);this._lighting[A]=t}internalGetReflection(A){return this._lighting[A]}internalEnableReflection(A){var t;this.__currentReflectionId=A;const e=(t=this._sceneLightSettings)==null?void 0:t.get(A);switch(Dn&&console.log("Enable reflection",A,e?dh[e.ambientMode]:"Unknown ambient mode",e),e==null?void 0:e.ambientMode){case 0:case 4:const i=this.internalGetReflection(A);if(i&&i.Source){Dn&&console.log("Setting environment reflection",i);const I=this.context.scene,o=i.Source;o.mapping=No,I.environment=o;return}else Dn&&console.warn("Could not find reflection for source",A);break}if((e==null?void 0:e.environmentReflectionSource)===1)switch(e==null?void 0:e.ambientMode){case 1:if(e.ambientTrilight){const i=e.ambientTrilight,I=ocA(i[0],i[1],i[2],64,64);I.colorSpace=pe,I.mapping=No,this.context.scene.environment=I}else console.error("Missing ambient trilight",e.sourceId);return;case 3:if(e.ambientLight){const i=ev(e.ambientLight,64);i.colorSpace=pe,i.mapping=No,this.context.scene.environment=i}else console.error("Missing ambientlight",e.sourceId);return;default:return}}internalDisableReflection(A){if(A&&A!==this.__currentReflectionId){Dn&&console.log("Not disabling reflection for",A,"because it is not the current light settings id",this.__currentReflectionId);return}Dn&&console.log("Disable reflection",A);const e=this.context.scene;e.environment=null}}class GZ{constructor(A,e,t=1){B(this,"_source");this._source=e,e.mapping=No}get Source(){return this._source}}const s2=gA("timescale");let LK=1;typeof s2=="number"&&(LK=s2);class RZ{constructor(){B(this,"_time",0);B(this,"_deltaTime",0);B(this,"_deltaTimeUnscaled",0);B(this,"timeScale",1);B(this,"_frame",0);B(this,"clock",new QJ);B(this,"_smoothedFps",0);B(this,"_smoothedDeltaTime",0);B(this,"_fpsSamples",[]);B(this,"_fpsSampleIndex",0);typeof LK=="number"&&(this.timeScale=LK)}get time(){return this._time}set time(A){this._time=A}get deltaTime(){return this._deltaTime}set deltaTime(A){this._deltaTime=A}get deltaTimeUnscaled(){return this._deltaTimeUnscaled}get frame(){return this._frame}set frame(A){this._frame=A}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 A=0;for(let e=0;e<this._fpsSamples.length;e++)A+=this._fpsSamples[e];this._smoothedDeltaTime=A/this._fpsSamples.length,this._smoothedFps=1/this._smoothedDeltaTime}}let n2=!1;function UZ(g){n2||(n2=!0,CcA(),BcA())}UZ();function CcA(){const g=`
5270
5270
  float startCompression = 0.8;
5271
5271
  float desaturation = 0.5;
5272
5272
  // Patched tonemapping function
@@ -5729,7 +5729,7 @@ Could not find method ${a.method} on object ${Q.name}`,Q,typeof Q[a.method])};if
5729
5729
  // Uncomment to visualize blur amount
5730
5730
  // gl_FragColor = vec4(blurAmount, 0.0, 0.0, 1.0);
5731
5731
  }
5732
- `;var iEA=Object.defineProperty,gEA=Object.getOwnPropertyDescriptor,Iv=(g,A,e,t)=>{for(var i=t>1?void 0:t?gEA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&iEA(A,e,i),i};class sE extends FA{constructor(){super(...arguments);B(this,"constraintActive",!0);B(this,"locked",!1);B(this,"sources",[])}}Iv([D()],sE.prototype,"constraintActive",2);Iv([D()],sE.prototype,"locked",2);Iv([D(DA)],sE.prototype,"sources",2);function IEA(g,A){return ZB(g,Gt.ContextCreated,A),()=>jB(g,Gt.ContextCreated)}function oEA(g,A){return ZB(g,Gt.ContextClearing,A),()=>jB(g,Gt.ContextClearing)}function sEA(g,A){return ZB(g,Gt.ContextDestroying,A),()=>jB(g,Gt.ContextDestroying)}function oj(g,A){return ZB(g,oi.Start,A),()=>jB(g,oi.Start)}function sj(g,A){return ZB(g,oi.Update,A),()=>jB(g,oi.Update)}function nEA(g,A){return ZB(g,oi.OnBeforeRender,A),()=>jB(g,oi.OnBeforeRender)}function rEA(g,A){return ZB(g,oi.OnAfterRender,A),()=>jB(g,oi.OnAfterRender)}class yc{constructor(){B(this,"bb",null);B(this,"bb_pos",0)}__init(A,e){return this.bb_pos=A,this.bb=e,this}x(){return this.bb.readFloat32(this.bb_pos)}y(){return this.bb.readFloat32(this.bb_pos+4)}z(){return this.bb.readFloat32(this.bb_pos+8)}static sizeOf(){return 12}static createVec3(A,e,t,i){return A.prep(4,12),A.writeFloat32(i),A.writeFloat32(t),A.writeFloat32(e),A.offset()}}class nj{constructor(){B(this,"bb",null);B(this,"bb_pos",0)}__init(A,e){return this.bb_pos=A,this.bb=e,this}position(A){return(A||new yc).__init(this.bb_pos,this.bb)}rotation(A){return(A||new yc).__init(this.bb_pos+12,this.bb)}scale(A){return(A||new yc).__init(this.bb_pos+24,this.bb)}static sizeOf(){return 36}static createTransform(A,e,t,i,I,o,s,n,r,a){return A.prep(4,36),A.prep(4,12),A.writeFloat32(a),A.writeFloat32(r),A.writeFloat32(n),A.prep(4,12),A.writeFloat32(s),A.writeFloat32(o),A.writeFloat32(I),A.prep(4,12),A.writeFloat32(i),A.writeFloat32(t),A.writeFloat32(e),A.offset()}}class qa{constructor(){B(this,"bb",null);B(this,"bb_pos",0)}__init(A,e){return this.bb_pos=A,this.bb=e,this}static getRootAsSyncedTransformModel(A,e){return(e||new qa).__init(A.readInt32(A.position())+A.position(),A)}static getSizePrefixedRootAsSyncedTransformModel(A,e){return A.setPosition(A.position()+Ox),(e||new qa).__init(A.readInt32(A.position())+A.position(),A)}guid(A){const e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,A):null}fast(){const A=this.bb.__offset(this.bb_pos,6);return A?!!this.bb.readInt8(this.bb_pos+A):!1}transform(A){const e=this.bb.__offset(this.bb_pos,8);return e?(A||new nj).__init(this.bb_pos+e,this.bb):null}dontSave(){const A=this.bb.__offset(this.bb_pos,10);return A?!!this.bb.readInt8(this.bb_pos+A):!1}static startSyncedTransformModel(A){A.startObject(4)}static addGuid(A,e){A.addFieldOffset(0,e,0)}static addFast(A,e){A.addFieldInt8(1,+e,0)}static addTransform(A,e){A.addFieldStruct(2,e,0)}static addDontSave(A,e){A.addFieldInt8(3,+e,0)}static endSyncedTransformModel(A){return A.endObject()}static finishSyncedTransformModelBuffer(A,e){A.finish(e)}static finishSizePrefixedSyncedTransformModelBuffer(A,e){A.finish(e,void 0,!0)}}var Lg=(g=>(g[g.Average=0]="Average",g[g.Multiply=1]="Multiply",g[g.Minimum=2]="Minimum",g[g.Maximum=3]="Maximum",g))(Lg||{}),lM=(g=>(g[g.Discrete=0]="Discrete",g[g.Continuous=1]="Continuous",g))(lM||{}),$i=(g=>(g[g.None=0]="None",g[g.FreezePositionX=2]="FreezePositionX",g[g.FreezePositionY=4]="FreezePositionY",g[g.FreezePositionZ=8]="FreezePositionZ",g[g.FreezePosition=14]="FreezePosition",g[g.FreezeRotationX=16]="FreezeRotationX",g[g.FreezeRotationY=32]="FreezeRotationY",g[g.FreezeRotationZ=64]="FreezeRotationZ",g[g.FreezeRotation=112]="FreezeRotation",g[g.FreezeAll=126]="FreezeAll",g))($i||{}),th=(g=>(g[g.None=0]="None",g[g.X=2]="X",g[g.Y=4]="Y",g[g.Z=8]="Z",g[g.All=-1]="All",g))(th||{});const DI=function(g,A){return function(e,t,i){aEA(e,t,i,g,A)}};function aEA(g,A,e,t,i){if(!i&&!t&&!g.onValidate)return;if(e!==void 0){console.error("Invalid usage of validate decorator. Only fields can be validated.",g,A,e),fi("Invalid usage of validate decorator. Only fields can be validated. Property: "+A,Is.Error);return}let I="";if(typeof A=="string"?I=A:I=A.name,g.__internalAwake){const o=Symbol(I),s=g.__internalAwake;g.__internalAwake=function(){var n;if(!this.onValidate){ae()&&console.warn('Usage of @validate decorate detected but there is no onValidate method in your class: "'+((n=g.constructor)==null?void 0:n.name)+'"');return}if(this[o]===void 0){this[o]=this[I];const r=this[I];if(r instanceof tA||r instanceof y||r instanceof Ae||r instanceof GA){const a=this[I];Kk(a,()=>{this.onValidate(I)})}Object.defineProperty(this,I,{set:function(a){var C;if(this[SK]===!0)this[o]=a;else{t==null||t.call(this,a);const Q=this[o];this[o]=a,(C=this.onValidate)==null||C.call(this,I,Q)}},get:function(){return i==null||i.call(this),this[o]}})}s.call(this)}}}const CEA=function(g){return function(A,e,t){let i="";typeof e=="string"?i=e:i=e.name;const I=g.prototype,o=Object.getOwnPropertyDescriptor(I,i);if(!(o!=null&&o.value)){console.warn("Can not apply prefix: type does not have method named",e,g);return}const s=o.value,n=A[i];Object.defineProperty(I,i,{value:function(...r){const a=n==null?void 0:n.call(this,...r);if(a instanceof Promise){a.then(C=>{if(C!==!1)return s.call(this,...r)});return}if(a!==!1)return s.call(this,...r)}})}};var BEA=Object.defineProperty,QEA=Object.getOwnPropertyDescriptor,Es=(g,A,e,t)=>{for(var i=t>1?void 0:t?QEA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&BEA(A,e,i),i};class cEA{constructor(A,e){B(this,"positionChanged",!1);B(this,"rotationChanged",!1);B(this,"position");B(this,"quaternion");B(this,"_positionKeys",["x","y","z"]);B(this,"_quaternionKeys",["_x","_y","_z","_w"]);B(this,"mute",!1);B(this,"context");B(this,"obj");B(this,"_positionWatch");B(this,"_rotationWatch");this.context=e,this.obj=A}get isDirty(){return this.positionChanged||this.rotationChanged}reset(A=!1){if(this.positionChanged=!1,this.rotationChanged=!1,this.mute=!1,A){if(this.position)for(const e of this._positionKeys)delete this.position[e];if(this.quaternion)for(const e of this._quaternionKeys)delete this.quaternion[e]}}syncValues(){for(const A of this._positionKeys)this.position[A]=this.obj.position[A];for(const A of this._quaternionKeys)this.quaternion[A]=this.obj.quaternion[A]}applyValues(){if(this.positionChanged&&this.position)for(const A of this._positionKeys){const e=this.position[A];e!==void 0&&(this.obj.position[A]=e)}if(this.rotationChanged&&this.quaternion)for(const A of this._quaternionKeys){const e=this.quaternion[A];e!==void 0&&(this.obj.quaternion[A]=e)}}start(A,e){this.reset(),A&&(this._positionWatch||(this._positionWatch=new Za(this.obj.position,["x","y","z"])),this._positionWatch.apply(),this.position={},this._positionWatch.subscribeWrite((I,o)=>{var n;if((n=this.context.physics.engine)!=null&&n.isUpdating||this.mute)return;const s=this.position[o];Math.abs(s-I)<1e-5||(this.position[o]=I,this.positionChanged=!0)})),e&&(this._rotationWatch||(this._rotationWatch=new Za(this.obj.quaternion,["_x","_y","_z","_w"])),this._rotationWatch.apply(),this.quaternion={},this._rotationWatch.subscribeWrite((I,o)=>{var n;if((n=this.context.physics.engine)!=null&&n.isUpdating||this.mute)return;const s=this.quaternion[o];Math.abs(s-I)<1e-5||(this.quaternion[o]=I,this.rotationChanged=!0)}));const t=this.obj.matrixWorld.multiplyMatrices.bind(this.obj.matrixWorld),i=new fA;this.obj.matrixWorld.multiplyMatrices=(I,o)=>{var s;return(s=this.context.physics.engine)!=null&&s.isUpdating||this.mute||i.equals(I)||(this.positionChanged=!0,this.rotationChanged=!0,i.copy(I)),t(I,o)}}stop(){var A,e;(A=this._positionWatch)==null||A.revoke(),(e=this._rotationWatch)==null||e.revoke()}}var FN;const WK=(FN=class extends FA{constructor(){super(...arguments);B(this,"autoMass",!0);B(this,"_mass",0);B(this,"useGravity",!0);B(this,"centerOfMass",new y(0,0,0));B(this,"constraints",$i.None);B(this,"isKinematic",!1);B(this,"drag",0);B(this,"angularDrag",1);B(this,"detectCollisions",!0);B(this,"sleepThreshold",.01);B(this,"collisionDetectionMode",lM.Discrete);B(this,"_gravityScale",1);B(this,"dominanceGroup",0);B(this,"_propertiesChanged",!1);B(this,"_currentVelocity",new y);B(this,"_smoothedVelocity",new y);B(this,"_smoothedVelocityGetter",new y);B(this,"_lastPosition",new y);B(this,"_watch")}set mass(A){A!==this._mass&&(this._mass=A,this._propertiesChanged=!0,this.__didAwake&&(this.autoMass=!1))}get mass(){var A,e;return this.autoMass?((e=(A=this.context.physics.engine)==null?void 0:A.getBody(this))==null?void 0:e.mass())??-1:this._mass}get lockPositionX(){return(this.constraints&$i.FreezePositionX)!==0}get lockPositionY(){return(this.constraints&$i.FreezePositionY)!==0}get lockPositionZ(){return(this.constraints&$i.FreezePositionZ)!==0}get lockRotationX(){return(this.constraints&$i.FreezeRotationX)!==0}get lockRotationY(){return(this.constraints&$i.FreezeRotationY)!==0}get lockRotationZ(){return(this.constraints&$i.FreezeRotationZ)!==0}set lockPositionX(A){A?this.constraints|=$i.FreezePositionX:this.constraints&=~$i.FreezePositionX}set lockPositionY(A){A?this.constraints|=$i.FreezePositionY:this.constraints&=~$i.FreezePositionY}set lockPositionZ(A){A?this.constraints|=$i.FreezePositionZ:this.constraints&=~$i.FreezePositionZ}set lockRotationX(A){A?this.constraints|=$i.FreezeRotationX:this.constraints&=~$i.FreezeRotationX}set lockRotationY(A){A?this.constraints|=$i.FreezeRotationY:this.constraints&=~$i.FreezeRotationY}set lockRotationZ(A){A?this.constraints|=$i.FreezeRotationZ:this.constraints&=~$i.FreezeRotationZ}set gravityScale(A){this._gravityScale=A}get gravityScale(){return this._gravityScale}awake(){this._watch=void 0,this._propertiesChanged=!1}onEnable(){this._watch||(this._watch=new cEA(this.gameObject,this.context)),this._watch.start(!0,!0),this.startCoroutine(this.beforePhysics(),oi.LateUpdate)}onDisable(){var A,e;(A=this._watch)==null||A.stop(),(e=this.context.physics.engine)==null||e.removeBody(this)}onDestroy(){var A;(A=this.context.physics.engine)==null||A.removeBody(this)}onValidate(){this._propertiesChanged=!0}*beforePhysics(){var A,e,t,i;for(;;)this._propertiesChanged&&(this._propertiesChanged=!1,(A=this.context.physics.engine)==null||A.updateProperties(this)),(e=this._watch)!=null&&e.isDirty?(this._watch.mute=!0,this._watch.applyValues(),(t=this.context.physics.engine)==null||t.updateBody(this,this._watch.positionChanged,this._watch.rotationChanged),this._watch.reset()):(i=this._watch)==null||i.syncValues(),this.captureVelocity(),yield}teleport(A,e=!0){var t;(t=this._watch)==null||t.reset(!0),e?this.gameObject.position.set(A.x,A.y,A.z):this.setWorldPosition(A.x,A.y,A.z),this.resetForcesAndTorques(),this.resetVelocities()}resetForces(A=!0){var e;(e=this.context.physics.engine)==null||e.resetForces(this,A)}resetTorques(A=!0){var e;(e=this.context.physics.engine)==null||e.resetTorques(this,A)}resetVelocities(){this.setVelocity(0,0,0),this.setAngularVelocity(0,0,0)}resetForcesAndTorques(){this.resetForces(),this.resetTorques()}wakeUp(){var A;(A=this.context.physics.engine)==null||A.wakeup(this)}get isSleeping(){var A;return(A=this.context.physics.engine)==null?void 0:A.isSleeping(this)}updateProperties(){var A;return this._propertiesChanged=!1,(A=this.context.physics.engine)==null?void 0:A.updateProperties(this)}applyForce(A,e,t=!0){var i;this._propertiesChanged&&this.updateProperties(),(i=this.context.physics.engine)==null||i.addForce(this,A,t)}applyImpulse(A,e=!0){var t;this._propertiesChanged&&this.updateProperties(),(t=this.context.physics.engine)==null||t.applyImpulse(this,A,e)}setForce(A,e,t,i=!0){var I,o,s;(I=this.context.physics.engine)==null||I.resetForces(this,i),typeof A=="number"?(e??(e=0),t??(t=0),(o=this.context.physics.engine)==null||o.addForce(this,{x:A,y:e,z:t},i)):(s=this.context.physics.engine)==null||s.addForce(this,A,i)}getVelocity(){var e;const A=(e=this.context.physics.engine)==null?void 0:e.getLinearVelocity(this);return A?(this._currentVelocity.x=A.x,this._currentVelocity.y=A.y,this._currentVelocity.z=A.z,this._currentVelocity):this._currentVelocity.set(0,0,0)}setVelocity(A,e,t,i=!0){var I,o;if(A instanceof y){const s=A;(I=this.context.physics.engine)==null||I.setLinearVelocity(this,s,i);return}e===void 0||t===void 0||(o=this.context.physics.engine)==null||o.setLinearVelocity(this,{x:A,y:e,z:t},i)}getAngularVelocity(){var e;const A=(e=this.context.physics.engine)==null?void 0:e.getAngularVelocity(this);return A?(this._currentVelocity.x=A.x,this._currentVelocity.y=A.y,this._currentVelocity.z=A.z,this._currentVelocity):this._currentVelocity.set(0,0,0)}setAngularVelocity(A,e,t,i=!0){var I,o;if(A instanceof y){const s=A;(I=this.context.physics.engine)==null||I.setAngularVelocity(this,s,i);return}e===void 0||t===void 0||(o=this.context.physics.engine)==null||o.setAngularVelocity(this,{x:A,y:e,z:t},i)}setTorque(A,e,t){this.setAngularVelocity(A,e,t)}get smoothedVelocity(){return this._smoothedVelocityGetter.copy(this._smoothedVelocity),this._smoothedVelocityGetter.multiplyScalar(1/this.context.time.deltaTime)}setBodyFromGameObject(A=null){}captureVelocity(){const A=ve(this.gameObject);WK.tempPosition.copy(A);const e=A.sub(this._lastPosition);this._lastPosition.copy(WK.tempPosition),this._smoothedVelocity.lerp(e,this.context.time.deltaTime/.1)}},B(FN,"tempPosition",new y),FN);let Pt=WK;Es([DI()],Pt.prototype,"autoMass",2);Es([D()],Pt.prototype,"mass",1);Es([DI(),D()],Pt.prototype,"useGravity",2);Es([D(y)],Pt.prototype,"centerOfMass",2);Es([DI(),D()],Pt.prototype,"constraints",2);Es([DI(),D()],Pt.prototype,"isKinematic",2);Es([DI(),D()],Pt.prototype,"drag",2);Es([DI(),D()],Pt.prototype,"angularDrag",2);Es([DI(),D()],Pt.prototype,"detectCollisions",2);Es([DI(),D()],Pt.prototype,"sleepThreshold",2);Es([DI(),D()],Pt.prototype,"collisionDetectionMode",2);Es([DI()],Pt.prototype,"_gravityScale",2);Es([DI()],Pt.prototype,"dominanceGroup",2);const zC=gA("debugsync"),Nf="STRS";Wx(Nf,qa.getRootAsSyncedTransformModel);const er=new mD;function rj(g,A,e=!0){er.clear();const t=er.createString(g);qa.startSyncedTransformModel(er),qa.addGuid(er,t),qa.addFast(er,e);const i=A.worldPosition,I=A.worldEuler,o=A.gameObject.scale;qa.addTransform(er,nj.createTransform(er,i.x,i.y,i.z,I.x,I.y,I.z,o.x,o.y,o.z));const s=qa.endSyncedTransformModel(er);return er.finish(s,Nf),er.asUint8Array()}let ZK=0,Lp=0;sj(g=>{var t;const e=((t=g.connection.currentServerUrl)==null?void 0:t.includes("glitch"))?10:40;Lp=Math.floor(ZK/e),ZK=0,zC&&Lp>0&&console.log("Sync Transform Fast Interval",Lp)});class bB extends FA{constructor(){super(...arguments);B(this,"overridePhysics",!0);B(this,"interpolatePosition",!0);B(this,"interpolateRotation",!0);B(this,"fastMode",!1);B(this,"syncDestroy",!1);B(this,"_model",null);B(this,"_needsUpdate",!0);B(this,"rb",null);B(this,"_wasKinematic",!1);B(this,"_receivedDataBefore",!1);B(this,"_targetPosition");B(this,"_targetRotation");B(this,"_receivedFastUpdate",!1);B(this,"_shouldRequestOwnership",!1);B(this,"joinedRoomCallback",null);B(this,"receivedDataCallback",null);B(this,"tempEuler",new rt);B(this,"receivedUpdate",!1);B(this,"lastWorldPos");B(this,"lastWorldRotation")}requestOwnership(){zC&&console.log("Request ownership"),this._model?this._model.requestOwnership():(this._shouldRequestOwnership=!0,this._needsUpdate=!0)}hasOwnership(){var e;return((e=this._model)==null?void 0:e.hasOwnership)??void 0}isOwned(){var e;return(e=this._model)==null?void 0:e.isOwned}awake(){zC&&console.log("new instance",this.guid,this),this._receivedDataBefore=!1,this._targetPosition=new y,this._targetRotation=new GA,this.lastWorldPos=new y,this.lastWorldRotation=new GA,this.rb=sA.getComponentInChildren(this.gameObject,Pt),this.rb&&(this._wasKinematic=this.rb.isKinematic),this.receivedUpdate=!0,this._model=new $x(this.context.connection,this.guid),this.context.connection.isConnected&&this.tryGetLastState(),this.joinedRoomCallback=this.tryGetLastState.bind(this),this.context.connection.beginListen(ze.JoinedRoom,this.joinedRoomCallback),this.receivedDataCallback=this.onReceivedData.bind(this),this.context.connection.beginListenBinary(Nf,this.receivedDataCallback)}onDestroy(){this.syncDestroy&&tv(this.guid,this.context.connection),this._model=null,this.context.connection.stopListen(ze.JoinedRoom,this.joinedRoomCallback),this.context.connection.stopListenBinary(Nf,this.receivedDataCallback)}tryGetLastState(){const e=this.context.connection.tryGetState(this.guid);e&&this.onReceivedData(e)}onReceivedData(e){var t;if(!this.destroyed&&typeof e.guid=="function"&&e.guid()===this.guid){zC&&console.log("new data",this.context.connection.connectionId,this.context.time.frameCount,this.guid,e),this.receivedUpdate=!0,this._receivedFastUpdate=e.fast();const i=e.transform();if(i){Ws.markDirty(this.gameObject,!0);const I=i.position();I&&(this.interpolatePosition&&((t=this._targetPosition)==null||t.set(I.x(),I.y(),I.z())),(!this.interpolatePosition||!this._receivedDataBefore)&&this.setWorldPosition(I.x(),I.y(),I.z()));const o=i.rotation();o&&(this.tempEuler.set(o.x(),o.y(),o.z()),this.interpolateRotation&&this._targetRotation.setFromEuler(this.tempEuler),(!this.interpolateRotation||!this._receivedDataBefore)&&$J(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){zC&&console.log("no model or room",this.name,this.guid,this.context.connection.isInRoom);return}this._shouldRequestOwnership&&(this._shouldRequestOwnership=!1,this._model.requestOwnership());const e=this.worldPosition,t=this.worldQuaternion;if(this._model.isOwned&&!this.receivedUpdate){const o=e.distanceTo(this.lastWorldPos),s=t.angleTo(this.lastWorldRotation),n=this._model.hasOwnership||this.fastMode?1e-4:.001;(o>n||s>n)&&(this._model.hasOwnership?this._needsUpdate=!0:(zC&&console.log(this.guid,"reset because not owned but",this.gameObject.name,this.lastWorldPos),this.worldPosition=this.lastWorldPos,e.copy(this.lastWorldPos),this.worldQuaternion=this.lastWorldRotation,t.copy(this.lastWorldRotation),Ws.markDirty(this.gameObject,!0),this._needsUpdate=!1))}if(this._model&&!this._model.hasOwnership&&this._model.isOwned&&this._receivedDataBefore){const s=this._receivedFastUpdate||this.fastMode?.5:.3;let n=!1;if(this.interpolatePosition&&this._targetPosition){const r=this.worldPosition;r.lerp(this._targetPosition,s),this.worldPosition=r,n=!0}if(this.interpolateRotation&&this._targetRotation){const r=this.worldQuaternion;r.slerp(this._targetRotation,s),this.worldQuaternion=r,n=!0}n&&Ws.markDirty(this.gameObject,!0)}if(this.receivedUpdate=!1,this.lastWorldPos.copy(e),this.lastWorldRotation.copy(t),!this._model||!this._model||this._model.hasOwnership===void 0||!this._model.hasOwnership)return;this.rb&&this.overridePhysics&&this._wasKinematic!==void 0&&(zC&&console.log("reset kinematic",this.rb.name,this._wasKinematic),this.rb.isKinematic=this._wasKinematic);const i=10,I=this.rb||this.fastMode;if(this._needsUpdate&&(this.context.time.frameCount%i===0||I)){if(ZK++,I&&Lp>0&&this.context.time.frameCount%Lp!==0)return;zC&&console.log("send update",this.context.connection.connectionId,this.guid,this.gameObject.name,this.gameObject.guid),this._needsUpdate=!1;const o=rj(this.guid,this,!!I);this.context.connection.sendBinary(o)}}}const EEA=gA("debugshadowcomponents");PJ.prototype.interactable={get(){return this.interactive},set(g){this.interactable=g}};const Hs=Symbol("shadowDomOwner");class Xs extends FA{constructor(){super(...arguments);B(this,"_shadowComponent",null);B(this,"_controlsChildLayout",!0);B(this,"_root");B(this,"_parentComponent")}isRoot(){var e;return((e=this.Root)==null?void 0:e.gameObject)===this.gameObject}get canvas(){const e=this.Root;return e!=null&&e.isCanvas?e:null}get Canvas(){return this.canvas}markDirty(){Uo.markUIDirty(this.context)}get shadowComponent(){return this._shadowComponent}set shadowComponent(e){this._shadowComponent=e}get controlsChildLayout(){return this._controlsChildLayout}set controlsChildLayout(e){this._controlsChildLayout=e,this.shadowComponent&&(this.shadowComponent.autoLayout=e)}get Root(){return this._root===void 0&&(this._root=sA.getComponentInParent(this.gameObject,JD)),this._root}__internalNewInstanceCreated(e){return super.__internalNewInstanceCreated(e),this.shadowComponent=null,this._root=void 0,this._parentComponent=void 0,this}onEnable(){super.onEnable()}addShadowComponent(e,t){var o;if(!e)return;this.removeShadowComponent();const i=this.isRoot()?this.gameObject:this.gameObject.parent;if(this._parentComponent=sA.getComponentInParent(i,Xs),!this._parentComponent){console.warn(`Component "${this.name}" doesn't have a UI parent anywhere. Do you have an UI element outside a Canvas? UI components must be a child of a Canvas component`,this);return}e.name=this.name+" ("+(this.constructor.name??"UI")+")",e.autoLayout=this._parentComponent.controlsChildLayout,e[Hs]=this,this.setShadowComponentOwner(e);let I=!1;if(((o=this.Root)==null?void 0:o.gameObject)===this.gameObject)this.gameObject.add(e);else{const s=this._parentComponent.shadowComponent;s&&(s==null||s.add(e),I=!0)}this.shadowComponent=e,t&&t.shadowComponent&&this.shadowComponent&&t.shadowComponent.add(this.shadowComponent),SD&&e.add(new Qs(.5)),this.onAfterAddedToScene(),I&&s3(),EEA&&console.warn("Added shadow component",this.shadowComponent)}setShadowComponentOwner(e){if(e&&(e[Hs]===void 0||e[Hs]===this)&&(e[Hs]=this,e.children))for(const t of e.children)this.setShadowComponentOwner(t)}traverseOwnedShadowComponents(e,t,i){if(e&&e[Hs]===t){i(e);for(const I of e.children)this.traverseOwnedShadowComponents(I,t,i)}}removeShadowComponent(){this.shadowComponent&&this.shadowComponent.removeFromParent()}onAfterAddedToScene(){}setInteractable(e){this.shadowComponent&&(this.shadowComponent.interactable=e)}}class JD extends Xs{awake(){super.awake()}}class Ed{constructor(A,e){B(this,"event");B(this,"button");B(this,"buttonName");B(this,"_used",!1);B(this,"_propagationStopped",!1);B(this,"z__pointer_ctured",!1);B(this,"z__pointer_cture_rleased",!1);B(this,"inputSource");B(this,"object");B(this,"point");B(this,"normal");B(this,"face");B(this,"distance");B(this,"instanceId");B(this,"intersection");B(this,"isDown");B(this,"isUp");B(this,"isPressed");B(this,"isClick");B(this,"isDoubleClick");B(this,"input");this.event=e,this.input=A,this.button=e.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(),this.pointerId!==void 0&&this.input.setPointerUsed(this.pointerId))}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 A=new Ed(this.input,this.event);return Object.assign(A,this),A}Use(){this.use()}StopPropagation(){this.event.stopImmediatePropagation()}}function jK(g,A){return sA.foreachComponent(g,t=>{if(!t.enabled)return;const i=t;if(A)switch(A){case"pointerdown":if(i.onPointerDown)return!0;break;case"pointerup":if(i.onPointerUp||i.onPointerClick)return!0;break;case"pointermove":if(i.onPointerEnter||i.onPointerExit||i.onPointerMove)return!0;break}else if(i.onPointerDown||i.onPointerUp||i.onPointerEnter||i.onPointerExit||i.onPointerClick)return!0},!1)===!0}var lEA=Object.defineProperty,hEA=Object.getOwnPropertyDescriptor,dEA=(g,A,e,t)=>{for(var i=t>1?void 0:t?hEA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&lEA(A,e,i),i};class xD extends FA{awake(){Uo.createIfNoneExists(this.context)}onEnable(){var A;(A=Uo.get(this.context))==null||A.register(this)}onDisable(){var A;(A=Uo.get(this.context))==null||A.unregister(this)}}class cs extends xD{constructor(){super(...arguments);B(this,"targets",null);B(this,"raycastHits",[]);B(this,"ignoreSkinnedMeshes",!1)}start(){this.targets=[this.gameObject]}performRaycast(e=null){if(!this.targets)return null;e??(e=new Yn),e.targets=this.targets,e.results=this.raycastHits;const t=e.testObject;this.ignoreSkinnedMeshes&&(e.testObject=I=>I instanceof Fo?"continue in children":t?t(I):!0);const i=this.context.physics.raycast(e);return e.testObject=t,i}}dEA([D()],cs.prototype,"ignoreSkinnedMeshes",2);class hM extends cs{constructor(){super(),this.ignoreSkinnedMeshes=!0}}class Ff extends xD{performRaycast(A){if(!ye.active||!(A!=null&&A.ray))return null;const e=A.ray.origin,t=.01;return this.context.physics.sphereOverlap(e,t)}}class dM{static getObject(A){const e=A[Hs];return e&&(e.isComponent===!0?A=e.gameObject:A=e),A}static isInteractable(A,e){if(e&&(e.canvasGroup=void 0,e.graphic=void 0),A==null||!A.visible||(A=this.getObject(A),!A.visible))return!1;const t=this.tryFindCanvasGroup(A);if((t==null?void 0:t.isCanvasGroup)===!0&&(e&&(e.canvasGroup=t),t.blocksRaycasts===!1||t.interactable===!1))return!1;const i=Oc(A,I=>{if(I.isGraphic===!0)return I},!1);return e&&(i==null?void 0:i.isGraphic)===!0&&(e.graphic=i),!((i==null?void 0:i.raycastTarget)===!1||(i==null?void 0:i.layer)===2)}static tryFindCanvasGroup(A){if(!A)return null;const e=Oc(A,t=>{const i=t;if(i.blocksRaycasts!==void 0&&i.interactable!==void 0)return i},!1);return e!==void 0?e:this.tryFindCanvasGroup(A.parent)}}function ov(g){const A=g[Hs];return A||(g.parent?ov(g.parent):null)}function uEA(g){return g.isUI===!0||typeof g[Hs]=="object"}function ym(g,A){if(!g)return;const e=g.material;if((e==null?void 0:e.isMaterial)===!0){const t=g.parent;t&&t.isText,e.side=A.doubleSided??!0?kt:Gg,e.shadowSide=A.doubleSided?kt:Gg,g.castShadow=A.castShadows?A.castShadows:!1,g.receiveShadow=A.receiveShadows?A.receiveShadows:!1}for(const t of g.children)ym(t,A)}function vl(g,A,e){g[A]===void 0&&console.warn("Field",A,"is undefined on",g);const t=Proxy.revocable(g[A],{set(o,s,n,r){const a=o[s],C=Reflect.set(o,s,n,r);return e(n,a),C}}),i=t.revoke,I=g[A];return t.revoke=()=>{g[A]=I,i()},g[A]=t.proxy,t}const p2=Symbol("Scheduled action");function pEA(g,A,e=oi.OnBeforeRender){let t=g[p2];t||(t=g[p2]={});const i=A.name;t[e]||(t[e]={});const I=t[e];if(I[i])return;function*s(){A==null||A.call(g),I[i]=null}const n=g.startCoroutine(s(),e);I[i]=n}const fa=gA("debugeventsystem");var zK=(g=>(g.BeforeHandleInput="BeforeHandleInput",g.AfterHandleInput="AfterHandleInput",g))(zK||{});const Br=class extends FA{constructor(){super();B(this,"raycaster",[]);B(this,"_handleInputFn");B(this,"pressedByID",new Map);B(this,"hoveredByID",new Map);B(this,"_sortedHits",[]);B(this,"_testObjectsCache",new Map);B(this,"_currentlyActiveRaycaster",null);B(this,"_currentPointerEventName",null);B(this,"shouldRaycastObject",e=>{var I;let t=null;if(uEA(e)&&(t=(I=e[Hs])==null?void 0:I.gameObject),this._testObjectsCache.has(e)||t&&this._testObjectsCache.has(t))return this._testObjectsCache.get(e)===!1?"continue in children":!0;{let o=jK(e,this._currentPointerEventName);if(!o&&t&&(o=jK(t,this._currentPointerEventName)),o){this._testObjectsCache.set(e,!0);for(const s of e.children)this.shouldRaycastObject_AddToYesCache(s);return!0}return this._testObjectsCache.set(e,!1),"continue in children"}});B(this,"_sortingBuffer",[]);B(this,"_noDepthTestingResults",[]);B(this,"out",{});B(this,"_capturedPointer",{});B(this,"pointerEnterSymbol",Symbol("pointerEnter"));B(this,"pointerExitSymbol",Symbol("pointerExit"));B(this,"currentActiveMeshUIComponents",[]);Br.systems.push(this)}static createIfNoneExists(e){this.didSearchEventSystem||(this.didSearchEventSystem=!0,Br.systems.length<=0&&Br.systems.push(...sA.findObjectsOfType(Br,e)));for(const i of Br.systems)if(i.context===e)return;const t=new DA;sA.addNewComponent(t,Br),e.scene.add(t)}static get systems(){const e=be.Current;return this._eventSystemMap.has(e)||this._eventSystemMap.set(e,[]),this._eventSystemMap.get(e)}static get(e){const t=this._eventSystemMap.get(e);return t&&t.length>0?t[0]:null}static get instance(){return this.systems[0]}static ensureUpdateMeshUI(e,t,i=!1){oB.update(e,t,i)}static markUIDirty(e){oB.markDirty()}get hasActiveUI(){return this.currentActiveMeshUIComponents.length>0}get isHoveringObjects(){return this.hoveredByID.size>0}onDestroy(){Br.systems.splice(Br.systems.indexOf(this),1)}start(){if(this.raycaster.length<=0&&!sA.findObjectOfType(xD,this.context)){const t=sA.addNewComponent(this.context.scene,cs);this.raycaster.push(t),(ae()||fa)&&console.warn("Added an ObjectRaycaster to the scene because no raycaster was found.")}}register(e){var t;e&&this.raycaster&&!this.raycaster.includes(e)&&((t=this.raycaster)==null||t.push(e))}unregister(e){var i,I;const t=(i=this.raycaster)==null?void 0:i.indexOf(e);t!==void 0&&t!==-1&&((I=this.raycaster)==null||I.splice(t,1))}onEnable(){this._handleInputFn??(this._handleInputFn=this.onPointerEvent.bind(this)),this.context.input.addEventListener(pi.PointerDown,this._handleInputFn),this.context.input.addEventListener(pi.PointerUp,this._handleInputFn),this.context.input.addEventListener(pi.PointerMove,this._handleInputFn)}onDisable(){this.context.input.removeEventListener(pi.PointerDown,this._handleInputFn),this.context.input.removeEventListener(pi.PointerUp,this._handleInputFn),this.context.input.removeEventListener(pi.PointerMove,this._handleInputFn)}onBeforeRender(){this.resetMeshUIStates()}onPointerEvent(e){if(e===void 0||e.propagationStopped)return;const t=new Ed(this.context.input,e);this._currentPointerEventName=e.type,t.inputSource=this.context.input,t.isClick=e.isClick,t.isDoubleClick=e.isDoubleClick,t.isDown=e.type==pi.PointerDown,t.isUp=e.type==pi.PointerUp,t.isPressed=this.context.input.getPointerPressed(e.pointerId),fa&&(t.isDown?console.log("DOWN",t.pointerId):t.isUp&&console.log("UP",t.pointerId),t.isClick&&console.log("CLICK",t.pointerId));const i=new Yn;e.hasRay?i.ray=e.ray:i.screenPoint=this.context.input.getPointerPositionRC(e.pointerId);const I=this.performRaycast(i);if(I){for(const s of I)s.event=e,e.intersections.push(s);e.origin.onPointerHits&&e.origin.onPointerHits({sender:this,event:e,hits:I})}fa&&t.isClick&&fi("EventSystem: "+t.pointerId+" - "+this.context.time.frame+" - Up:"+t.isUp+", Down:"+t.isDown);const o={sender:this,args:t,hasActiveUI:this.currentActiveMeshUIComponents.length>0};this.dispatchEvent(new CustomEvent("BeforeHandleInput",{detail:o})),this.handleIntersections(I,t),this.dispatchEvent(new CustomEvent("AfterHandleInput",{detail:o}))}shouldRaycastObject_AddToYesCache(e){this._testObjectsCache.set(e,!0);for(const t of e.children)this.shouldRaycastObject_AddToYesCache(t)}performRaycast(e){if(!this.raycaster)return null;this._testObjectsCache.clear(),this._sortedHits.length=0,e||(e=new Yn),e.testObject=this.shouldRaycastObject;for(const t of this.raycaster){if(!t.activeAndEnabled)continue;this._currentlyActiveRaycaster=t;const i=t.performRaycast(e);this._currentlyActiveRaycaster=null,i&&i.length>0&&this._sortedHits.push(...i)}return this._sortedHits.sort((t,i)=>t.distance-i.distance),this._sortedHits}assignHitInformation(e,t){t?(e.intersection=t,e.point=t.point,e.normal=t.normal,e.face=t.face,e.distance=t.distance,e.instanceId=t.instanceId):(e.intersection=void 0,e.point=void 0,e.normal=void 0,e.face=void 0,e.distance=void 0,e.instanceId=void 0)}handleIntersections(e,t){var I;if(e!=null&&e.length){e=this.sortCandidates(e);for(const o of e){if(t.event.immediatePropagationStopped)return!1;if(this.assignHitInformation(t,o),this.handleEventOnObject(o.object,t))return!0}}this.assignHitInformation(t,e==null?void 0:e[0]),this.invokePointerCapture(t);const i=this.hoveredByID.get(t.pointerId);return i&&this.propagatePointerExit(i.obj,i.data,null),this.hoveredByID.delete(t.pointerId),t.isUp&&((I=this.pressedByID.get(t.pointerId))==null||I.handlers.forEach(o=>this.invokeOnPointerUp(t,o)),this.pressedByID.delete(t.pointerId)),!1}sortCandidates(e){this._sortingBuffer.length=0,this._noDepthTestingResults.length=0;for(let t=0;t<e.length;t++){const i=e[t],I=i.object;if(I.material&&I.material.depthTest===!1){this._noDepthTestingResults.push(i);continue}this._sortingBuffer.push(i)}for(const t of this._sortingBuffer)this._noDepthTestingResults.push(t);return this._noDepthTestingResults}handleEventOnObject(e,t){if(!this.testIsVisible(e))return t.isClick&&fa&&console.log("not allowed",e),!1;if(t.pointerId===void 0)return fa&&console.error("Event without pointer can't be handled",t),!1;t.object=e;const i=e.parent,I=t.isClick??!1;let o=null;if(i&&i.isUI){const C=(t.isPressed||t.isClick)??!1;if(i[Hs]){const Q=i[Hs].gameObject;if(Q){if(!dM.isInteractable(Q,this.out))return!1;o=this.out.canvasGroup??null,this.handleMeshUIIntersection(e,C),e=Q}}}I&&fa&&console.log(this.context.time.frame,e);const s=this.hoveredByID.get(t.pointerId),n=s==null?void 0:s.obj;n!==e&&n&&this.propagatePointerExit(n,s.data,e);const a=this.hoveredByID.get(t.pointerId);if(a?(a.obj=e,a.data=t):this.hoveredByID.set(t.pointerId,{obj:e,data:t}),t.isDown){const C=this.pressedByID.get(t.pointerId);C?(C.obj=e,C.data=t):this.pressedByID.set(t.pointerId,{obj:e,data:t,handlers:new Set})}return(o===null||o.interactable)&&this.handleMainInteraction(e,t,n??null),!0}propagate(e,t){for(;e;)sA.foreachComponent(e,i=>{t(i)},!1),e=e.parent}handleMainInteraction(e,t,i){const I=this.pressedByID.get(t.pointerId),o=i!==e;let s=!0;switch(t.event.pointerType){case"mouse":case"touch":const n=this.context.input.getPointerPositionLastFrame(t.pointerId),r=this.context.input.getPointerPosition(t.pointerId);s=n&&!ge.approximately(n,r);break}this.propagate(e,n=>{var a;const r=n;r.interactable!==!1&&(!r.activeAndEnabled||!r.enabled||(r.onPointerEnter&&o&&this.handlePointerEnter(r,t),t.isDown&&r.onPointerDown&&(r.onPointerDown(t),I==null||I.handlers.add(r),this.handlePointerCapture(t,r)),r.onPointerMove&&(s&&r.onPointerMove(t),this.handlePointerCapture(t,r)),t.isUp&&(r.onPointerUp&&(this.invokeOnPointerUp(t,r),I==null||I.handlers.delete(r)),r.onPointerExit&&((a=t.event)==null?void 0:a.pointerType)===gM.Touch&&(this.handlePointerExit(r,t),this.hoveredByID.delete(t.pointerId))),t.isClick&&r.onPointerClick&&r.onPointerClick(t)))}),t.isUp&&(I==null||I.handlers.forEach(n=>{this.invokeOnPointerUp(t,n)}),this.pressedByID.delete(t.pointerId))}propagatePointerExit(e,t,i){this.propagate(e,I=>{if(!I.gameObject||I.destroyed)return;const o=I;if(o.onPointerExit){if(i&&this.isChild(i,I.gameObject))return;this.handlePointerExit(o,t)}})}invokeOnPointerUp(e,t){var i;(i=t.onPointerUp)==null||i.call(t,e),this.releasePointerCapture(e,t)}handlePointerEnter(e,t){e.onPointerEnter&&this.updatePointerState(e,t.pointerId,this.pointerEnterSymbol,!0)&&e.onPointerEnter(t),this.updatePointerState(e,t.pointerId,this.pointerExitSymbol,!1)}handlePointerExit(e,t){e.onPointerExit&&this.updatePointerState(e,t.pointerId,this.pointerExitSymbol,!0)&&e.onPointerExit(t),this.updatePointerState(e,t.pointerId,this.pointerEnterSymbol,!1)}updatePointerState(e,t,i,I){let o=e[i];if(I)return o&&o.includes(t)?!1:(o=o||[],o.push(t),e[i]=o,!0);{if(!o||!o.includes(t))return!1;const s=o.indexOf(t);return s!==-1&&o.splice(s,1),!0}}handlePointerCapture(e,t){if(e.z__pointer_ctured){e.z__pointer_ctured=!1;const i=e.pointerId;if(t.onPointerMove){const I=this._capturedPointer[i]||[];I.push(t),this._capturedPointer[i]=I}else ae()&&!t.z__warned_no_pointermove&&(t.z__warned_no_pointermove=!0,console.warn("PointerCapture was requested but the component doesn't implement onPointerMove. It will not receive any pointer events"))}else e.z__pointer_cture_rleased&&(e.z__pointer_cture_rleased=!1,this.releasePointerCapture(e,t))}releasePointerCapture(e,t){const i=e.pointerId;if(this._capturedPointer[i]){const I=this._capturedPointer[i].indexOf(t);I!==-1&&(this._capturedPointer[i].splice(I,1),fa&&console.log("released pointer capture",i,t,this._capturedPointer))}}invokePointerCapture(e){var t;if(e.event.type===pi.PointerMove){const i=e.pointerId,I=this._capturedPointer[i];if(I){fa&&console.log("Captured",i,I);for(let o=0;o<I.length;o++){const s=I[o];if(s.destroyed){I.splice(o,1),o--;continue}(t=s.onPointerMove)==null||t.call(s,e)}}}}isChild(e,t){return!e||!t?!1:e===t?!0:e.parent?this.isChild(e.parent,t):!1}handleMeshUiObjectWithoutShadowDom(e,t){return!e||!e.isUI?!0:this.handleMeshUIIntersection(e,t)}handleMeshUIIntersection(e,t){const i=oB.updateState(e,t);return i&&this.currentActiveMeshUIComponents.push(i),i!==null}resetMeshUIStates(){if(this.context.input.getPointerPressedCount()>0&&oB.resetLastSelected(),!(!this.currentActiveMeshUIComponents||this.currentActiveMeshUIComponents.length<=0)){for(let e=0;e<this.currentActiveMeshUIComponents.length;e++){const t=this.currentActiveMeshUIComponents[e];oB.resetState(t)}this.currentActiveMeshUIComponents.length=0}}testIsVisible(e){return e?sA.isActiveSelf(e)?this.testIsVisible(e.parent):!1:!0}};let Uo=Br;B(Uo,"_eventSystemMap",new Map),B(Uo,"didSearchEventSystem",!1);class oB{static markDirty(){this.needsUpdate=!0}static update(A,e,t=!1){if(t){A.update();return}const i=e.time.frameCount;for(const I of this.lastUpdateFrame)if(I.context===e){if(i===I.frame)return;I.frame=i;let o=this.needsUpdate||i<1;I.nextUpdate===e.time.frameCount&&(o=!0),o&&(fa&&console.log("Update threemeshui"),this.needsUpdate=!1,A.update());return}this.lastUpdateFrame=[{context:e,frame:i,nextUpdate:i}],A.update()}static updateState(A,e){let t=null;if(A&&(t=this.findBlockInParent(A),t&&t!==this.lastSelected)){if(t.interactable===!1)return null;this.needsUpdate=!0}return t}static resetLastSelected(){const A=this.lastSelected;A&&(this.lastSelected=null,this.resetState(A))}static resetState(A){A&&(this.needsUpdate=!0)}static findBlockInParent(A){return A?A.isBlock?A:this.findBlockInParent(A.parent):null}}B(oB,"lastSelected",null),B(oB,"lastUpdateFrame",[]),B(oB,"needsUpdate",!1);var fEA=Object.defineProperty,DEA=Object.getOwnPropertyDescriptor,wi=(g,A,e,t)=>{for(var i=t>1?void 0:t?DEA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&fEA(A,e,i),i};const PU=gA("debugorbit"),ES=gA("freecam"),lS=gA("debugcamerafit"),hS=gA("smoothcam"),yEA={LEFT:"",UP:"",RIGHT:"",BOTTOM:""};let WU;class Kf extends CustomEvent{constructor(A,e){super("target-reached",{detail:{controls:A,type:e}})}}class Mt extends FA{constructor(){super(...arguments);B(this,"autoTarget",!0);B(this,"autoFit",!1);B(this,"enableRotate",!0);B(this,"autoRotate",!1);B(this,"autoRotateSpeed",1);B(this,"minAzimuthAngle",1/0);B(this,"maxAzimuthAngle",1/0);B(this,"minPolarAngle",0);B(this,"maxPolarAngle",Math.PI);B(this,"enableKeys",!0);B(this,"enableDamping",!0);B(this,"dampingFactor",.1);B(this,"enableZoom",!0);B(this,"minZoom",0);B(this,"maxZoom",1/0);B(this,"zoomSpeed",1);B(this,"zoomToCursor",!1);B(this,"enablePan",!0);B(this,"lookAtConstraint",null);B(this,"lookAtConstraint01",1);B(this,"allowInterrupt",!0);B(this,"middleClickToFocus",!0);B(this,"doubleClickToFocus",!0);B(this,"clickBackgroundToFitScene",2);B(this,"debugLog",!1);B(this,"targetLerpDuration",1);B(this,"_controls",null);B(this,"_cameraObject",null);B(this,"_lookTargetLerpActive",!1);B(this,"_lookTargetStartPosition",new y);B(this,"_lookTargetEndPosition",new y);B(this,"_lookTargetLerp01",0);B(this,"_lookTargetLerpDuration",0);B(this,"_cameraLerpActive",!1);B(this,"_cameraStartPosition",new y);B(this,"_cameraEndPosition",new y);B(this,"_cameraLerp01",0);B(this,"_cameraLerpDuration",0);B(this,"_inputs",0);B(this,"_enableTime",0);B(this,"_startedListeningToKeyEvents",!1);B(this,"_eventSystem");B(this,"_afterHandleInputFn");B(this,"_camera",null);B(this,"_syncedTransform");B(this,"_didSetTarget",0);B(this,"targetElement",null);B(this,"_lastTimeClickOnBackground",-1);B(this,"_clickOnBackgroundCount",0);B(this,"_onPointerDown",e=>{if(this.clickBackgroundToFitScene>0&&e.isClick&&e.button===0){if(e.hasRay||e.intersections.push(...this.context.physics.raycast()),e.intersections.length<=0){const t=this.context.time.time-this._lastTimeClickOnBackground;this._lastTimeClickOnBackground=this.context.time.time,this.clickBackgroundToFitScene<=1||t<this.clickBackgroundToFitScene*.15?(this._clickOnBackgroundCount+=1,this._clickOnBackgroundCount>=this.clickBackgroundToFitScene-1&&this.fitCamera(this.context.scene.children,{immediate:!1})):this._clickOnBackgroundCount=0}PU&&console.log(this.clickBackgroundToFitScene,e.intersections.length,this._clickOnBackgroundCount)}});B(this,"onControlsChangeStarted",()=>{this._syncedTransform&&this._syncedTransform.requestOwnership()});B(this,"_shouldDisable",!1);B(this,"__onPreRender",()=>{const e=this.context.pre_render_callbacks.indexOf(this.__onPreRender);e>=0&&this.context.pre_render_callbacks.splice(e,1),this.autoFit&&(this.autoFit=!1,this.fitCamera(this.scene.children,{centerCamera:"y",immediate:!0}))});B(this,"_haveAttachedKeyboardEvents",!1)}get isCameraController(){return!0}get controls(){return this._controls}get controllerObject(){return this._cameraObject}onStartInteraction(e){var t;(t=this.controls)==null||t.addEventListener("start",e)}get targetLerpSpeed(){return 5}set targetLerpSpeed(e){this.targetLerpDuration=1/e}awake(){this._didSetTarget=0,this._startedListeningToKeyEvents=!1}start(){this._eventSystem=Uo.get(this.context)??void 0,this._eventSystem&&(this._afterHandleInputFn=this.afterHandleInput.bind(this),this._eventSystem.addEventListener(zK.AfterHandleInput,this._afterHandleInputFn))}onDestroy(){var e,t;(e=this._controls)==null||e.dispose(),(t=this._eventSystem)==null||t.removeEventListener(zK.AfterHandleInput,this._afterHandleInputFn)}onEnable(){this._didSetTarget=0,this._enableTime=this.context.time.time;const e=sA.getComponent(this.gameObject,Wt);this._camera=e;let t=e==null?void 0:e.cam;if(!t&&this.gameObject instanceof He&&(t=this.gameObject),t&&TF(t,this,!0),!this._controls&&t instanceof He){this._cameraObject=t;const i=this.targetElement??this.context.renderer.domElement,I=t==null?void 0:t.quaternion.clone();this._controls=new Ij(t,i),t==null||t.quaternion.copy(I),WU===void 0&&(WU={...this._controls.keys})}this._controls&&(ES&&(this.enablePan=!0,this.enableZoom=!0,this.middleClickToFocus=!0,In()&&(this.doubleClickToFocus=!0)),this._controls.addEventListener("start",this.onControlsChangeStarted),(t==null?void 0:t.type)==="PerspectiveCamera"?ES||(this._controls.minDistance=this.minZoom,this._controls.maxDistance=this.maxZoom):ES||(this._controls.minZoom=this.minZoom,this._controls.maxZoom=this.maxZoom),this._startedListeningToKeyEvents||(this._startedListeningToKeyEvents=!0,this._controls.listenToKeyEvents(window.document.body))),this._syncedTransform=sA.getComponent(this.gameObject,bB)??void 0,this.context.input.addEventListener("pointerup",this._onPointerDown),this.context.pre_render_callbacks.push(this.__onPreRender)}onDisable(){var e;(e=this._camera)!=null&&e.cam&&TF(this._camera.cam,this,!1),this._controls&&(this._controls.enabled=!1,this._controls.autoRotate=!1,this._controls.removeEventListener("start",this.onControlsChangeStarted)),this.context.input.removeEventListener("pointerup",this._onPointerDown)}afterHandleInput(e){e.detail.args.pointerId===0&&(e.detail.args.isDown?this._controls&&this._eventSystem&&(this._shouldDisable=this._eventSystem.hasActiveUI):(!e.detail.args.isPressed||e.detail.args.isUp)&&(this._shouldDisable=!1))}onBeforeRender(){var t,i;if(!this._controls)return;if(this._cameraObject!==this.context.mainCamera){this._controls.enabled=!1;return}if(this._controls.enabled=!0,(this.context.input.getPointerDown(1)||this.context.input.getPointerDown(2)||this.context.input.mouseWheelChanged||this.context.input.getPointerPressed(0)&&((t=this.context.input.getPointerPositionDelta(0))!=null&&t.length())||0>.1)&&(this._inputs+=1),this._inputs>0&&this.allowInterrupt&&(this.enableRotate&&(this.autoRotate=!1),this._cameraLerpActive=!1,this._lookTargetLerpActive=!1),this._inputs=0,this.autoTarget&&this._didSetTarget++===0){const I=sA.getComponent(this.gameObject,Wt);if(I&&!this.setLookTargetFromConstraint()){this.debugLog&&console.log("NO TARGET");const o=ve(I.cam),s=Math.max(.01,o.length()),n=new y(0,0,-s).applyMatrix4(I.cam.matrixWorld);this.setLookTargetPosition(n,!0)}if(!this.setLookTargetFromConstraint()){const o=new Yn;o.screenPoint=new tA(0,0),o.lineThreshold=.1;const s=this.context.physics.raycast(o);s.length>0&&this.setLookTargetPosition(s[0].point,!0),lS&&console.log("OrbitControls hits",...s)}}let e=this.middleClickToFocus&&this.context.input.getPointerClicked(1);if(e||(e=this.doubleClickToFocus&&this.context.input.getPointerDoubleClicked(0)&&this.context.time.time-this._enableTime>.3),e&&this.setTargetFromRaycast(),this._lookTargetLerpActive||this._cameraLerpActive){if(this._cameraLerpActive&&this._cameraObject)if(this._cameraLerp01+=this.context.time.deltaTime/this._cameraLerpDuration,this._cameraLerp01>=1)this._cameraObject.position.copy(this._cameraEndPosition),this._cameraLerpActive=!1,this.dispatchEvent(new Kf(this,"camera"));else{const I=ge.easeInOutCubic(this._cameraLerp01);this._cameraObject.position.lerpVectors(this._cameraStartPosition,this._cameraEndPosition,I)}if(this._lookTargetLerpActive)if(this._lookTargetLerp01+=this.context.time.deltaTime/this._lookTargetLerpDuration,this._lookTargetLerp01>=1)this._controls.target.copy(this._lookTargetEndPosition),this._lookTargetLerpActive=!1,this.dispatchEvent(new Kf(this,"lookat"));else{const I=ge.easeInOutCubic(this._lookTargetLerp01);this._controls.target.lerpVectors(this._lookTargetStartPosition,this._lookTargetEndPosition,I)}}if(this._controls){if(this.debugLog&&(this._controls.domElement=this.context.renderer.domElement),this._controls.enabled=!this._shouldDisable&&this._camera===this.context.mainCameraComponent&&!this.context.isInXR,this._controls.keys=this.enableKeys?WU:yEA,this._controls.autoRotate=this.autoRotate,this._controls.autoRotateSpeed=this.autoRotateSpeed,this._controls.enableZoom=this.enableZoom,this._controls.zoomSpeed=this.zoomSpeed,this._controls.zoomToCursor=this.zoomToCursor,this._controls.enableDamping=this.enableDamping,this._controls.dampingFactor=this.dampingFactor,this._controls.enablePan=this.enablePan,this._controls.enableRotate=this.enableRotate,this._controls.minAzimuthAngle=this.minAzimuthAngle,this._controls.maxAzimuthAngle=this.maxAzimuthAngle,this._controls.minPolarAngle=this.minPolarAngle,this._controls.maxPolarAngle=this.maxPolarAngle,typeof hS=="number"||hS===!0){this._controls.enableDamping=!0;const I=typeof hS=="number"?hS:.99;this._controls.dampingFactor=Math.max(.001,1-Math.min(1,I))}this.allowInterrupt||(this._lookTargetLerpActive&&(this._controls.enablePan=!1),this._cameraLerpActive&&(this._controls.enableRotate=!1,this._controls.autoRotate=!1),(this._lookTargetLerpActive||this._cameraLerpActive)&&(this._controls.enableZoom=!1)),this.context.isInXR||(!ES&&((i=this.lookAtConstraint)!=null&&i.locked)&&this.setLookTargetFromConstraint(0,this.lookAtConstraint01),this._controls.update(),PU&&fe.DrawWireSphere(this._controls.target,.1,65280))}}setCameraAndLookTarget(e){if(!e||!(e instanceof DA))return;const t=ve(e),i=VJ(e);this.setTargetFromRaycast(new xo(t,i)),this.setCameraTargetPosition(t)}setCameraTargetPosition(e,t=!1){var i,I;e&&(e instanceof DA&&(e=ve(e)),this._cameraEndPosition||(this._cameraEndPosition=new y),this._cameraEndPosition.copy(e),t===!0?(this._cameraLerpActive=!1,(i=this.controllerObject)==null||i.position.copy(this._cameraEndPosition)):this._cameraObject&&(this._cameraLerpActive=!0,this._cameraLerp01=0,this._cameraStartPosition.copy((I=this._cameraObject)==null?void 0:I.position),typeof t=="number"?this._cameraLerpDuration=t:this._cameraLerpDuration=this.targetLerpDuration))}get cameraLerpActive(){return this._cameraLerpActive}stopCameraLerp(){this._cameraLerpActive=!1}setLookTargetPosition(e=null,t=!1){this._controls&&e&&(e instanceof DA&&(e=ve(e)),this._lookTargetEndPosition.copy(e),PU&&(console.warn("OrbitControls: setLookTargetPosition",e,t),fe.DrawWireSphere(this._lookTargetEndPosition,.2,16711680,2)),t===!0?this._controls.target.copy(this._lookTargetEndPosition):(this._lookTargetLerpActive=!0,this._lookTargetLerp01=0,this._lookTargetStartPosition.copy(this._controls.target),typeof t=="number"?this._lookTargetLerpDuration=t:this._lookTargetLerpDuration=this.targetLerpDuration))}get lookTargetLerpActive(){return this._lookTargetLerpActive}stopLookTargetLerp(){this._lookTargetLerpActive=!1}setLookTargetFromConstraint(e=0,t=1){var I;if(!this._controls)return!1;const i=(I=this.lookAtConstraint)==null?void 0:I.sources;if(i&&i.length>0){const o=i[e];if(o)return o.getWorldPosition(this._lookTargetEndPosition),this.lerpLookTarget(this._lookTargetEndPosition,t),!0}return!1}lerpTarget(e,t){return this.lerpLookTarget(e,t)}lerpLookTarget(e,t){this._controls&&(t>=1?this._controls.target.copy(e):this._controls.target.lerp(e,t))}setTargetFromRaycast(e){if(!this.controls)return;const t=e?this.context.physics.raycastFromRay(e):this.context.physics.raycast();for(const i of t)if(i.distance>0&&sA.isActiveInHierarchy(i.object)){const I=ov(i.object);if(I){const o=I.canvas;if(o!=null&&o.screenspace)break}this.setLookTargetPosition(i.point);break}}fitCamera(e,t={fitOffset:void 0,immediate:!1}){if(this.context.isInXR)return;const{immediate:i=!1,centerCamera:I}=t;let{fitOffset:o}=t;o==null&&(o=1.1);const s=this._cameraObject,n=this._controls;if(e!=null&&e.length||(e=this.context.scene.children),e.length<=0){console.warn("No objects to fit camera to...");return}if(!s||!n){console.warn("No camera or controls found to fit camera to objects...");return}const r=new y,a=new y,C=qr(e,void 0);s.updateMatrixWorld(),s.updateProjectionMatrix(),C.getCenter(a);const Q=new y;if(C.getSize(Q),C.applyMatrix4(s.matrixWorldInverse),C.getSize(r),C.setFromCenterAndSize(a,r),Number.isNaN(r.x)||Number.isNaN(r.y)||Number.isNaN(r.z)){console.warn("Camera fit size resultet in NaN",s,C,[...e]);return}if(r.length()<=1e-10){lS&&console.warn("Camera fit size is zero",C,[...e]);return}const c=s.fov,E=2*Math.atan(Math.tan(c*Math.PI/360/2)*s.aspect)/Math.PI*360,h=r.y/(2*Math.atan(Math.PI*c/360)),l=r.x/(2*Math.atan(Math.PI*E/360)),d=o*Math.max(h,l)+r.z/2;lS&&console.log("Fit camera to objects",h,l,"distance",d),n.maxDistance=d*10,n.minDistance=d*.01;const p=.05,u=a.clone();u.y-=r.y*p,this.setLookTargetPosition(u,i),this.autoTarget=!1;const f=sA.findObjectOfType(VB),w=f?f.radius:0,m=Math.max(Q.x,Q.y,Q.z,w);s.near=d/100,s.far=m+d*10,s.updateMatrixWorld(),s.updateProjectionMatrix();const M=ve(s),G=a.clone();if(G.sub(M),I==="y"&&(G.y=0),G.normalize(),G.multiplyScalar(d),I==="y"&&(G.y+=-p*4*r.y),s.parent){const U=s.parent.worldToLocal(a.clone().sub(G));this.setCameraTargetPosition(U,i)}else console.error(`Can not fit camera ${s.name} because it has no parent`);if(lS){const U=new dJ(C);this.context.scene.add(U),Ax(U,dD(s)),setTimeout(()=>{this.context.scene.remove(U)},1e4),this._haveAttachedKeyboardEvents||(this._haveAttachedKeyboardEvents=!0,document.body.addEventListener("keydown",S=>{S.code==="KeyF"&&this.fitCamera(e,{fitOffset:o,immediate:i})}))}n.update()}}wi([D()],Mt.prototype,"autoTarget",2);wi([D()],Mt.prototype,"autoFit",2);wi([D()],Mt.prototype,"enableRotate",2);wi([D()],Mt.prototype,"autoRotate",2);wi([D()],Mt.prototype,"autoRotateSpeed",2);wi([D()],Mt.prototype,"minAzimuthAngle",2);wi([D()],Mt.prototype,"maxAzimuthAngle",2);wi([D()],Mt.prototype,"minPolarAngle",2);wi([D()],Mt.prototype,"maxPolarAngle",2);wi([D()],Mt.prototype,"enableKeys",2);wi([D()],Mt.prototype,"enableDamping",2);wi([D()],Mt.prototype,"dampingFactor",2);wi([D()],Mt.prototype,"enableZoom",2);wi([D()],Mt.prototype,"minZoom",2);wi([D()],Mt.prototype,"maxZoom",2);wi([D()],Mt.prototype,"zoomSpeed",2);wi([D()],Mt.prototype,"enablePan",2);wi([D(sE)],Mt.prototype,"lookAtConstraint",2);wi([D()],Mt.prototype,"lookAtConstraint01",2);wi([D()],Mt.prototype,"allowInterrupt",2);wi([D()],Mt.prototype,"middleClickToFocus",2);wi([D()],Mt.prototype,"doubleClickToFocus",2);wi([D()],Mt.prototype,"clickBackgroundToFitScene",2);wi([D()],Mt.prototype,"targetLerpDuration",2);var wEA=Object.defineProperty,SEA=Object.getOwnPropertyDescriptor,uo=(g,A,e,t)=>{for(var i=t>1?void 0:t?SEA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&wEA(A,e,i),i},kB=(g=>(g[g.Skybox=1]="Skybox",g[g.SolidColor=2]="SolidColor",g[g.Uninitialized=4]="Uninitialized",g))(kB||{});const Ma=gA("debugcam"),f2=gA("debugscreenpointtoray");var qS;const op=(qS=class extends FA{constructor(){super(...arguments);B(this,"_nearClipPlane",.1);B(this,"_farClipPlane",1e3);B(this,"orthographic",!1);B(this,"orthographicSize",5);B(this,"ARBackgroundAlpha",0);B(this,"_cullingMask",4294967295);B(this,"_backgroundBlurriness",0);B(this,"_backgroundIntensity",1);B(this,"_backgroundRotation");B(this,"_environmentIntensity");B(this,"_targetTexture",null);B(this,"_backgroundColor");B(this,"_fov");B(this,"_cam",null);B(this,"_clearFlags",2);B(this,"_skybox");B(this,"_frustum");B(this,"_projScreenMatrix",new fA)}get isCamera(){return!0}get aspect(){return this._cam instanceof He?this._cam.aspect:this.context.domWidth/this.context.domHeight}set aspect(A){this._cam instanceof He&&this._cam.aspect!==A&&(this._cam.aspect=A,this._cam.updateProjectionMatrix())}get fieldOfView(){return this._cam instanceof He?this._cam.fov:this._fov}set fieldOfView(A){const e=this.fieldOfView!=A;if(this._fov=A,e&&this._cam&&this._cam instanceof He){if(this._fov===void 0){console.warn("Can not set undefined fov on PerspectiveCamera");return}this._cam.fov=this._fov,this._cam.updateProjectionMatrix()}}get nearClipPlane(){return this._nearClipPlane}set nearClipPlane(A){const e=this._nearClipPlane!=A;this._nearClipPlane=A,this._cam&&e&&(this._cam.near=A,this._cam.updateProjectionMatrix())}get farClipPlane(){return this._farClipPlane}set farClipPlane(A){const e=this._farClipPlane!=A;this._farClipPlane=A,this._cam&&e&&(this._cam.far=A,this._cam.updateProjectionMatrix())}get clearFlags(){return this._clearFlags}set clearFlags(A){A!==this._clearFlags&&(this._clearFlags=A,this.applyClearFlagsIfIsActiveCamera())}set cullingMask(A){this._cullingMask=A,this._cam&&(this._cam.layers.mask=A)}get cullingMask(){return this._cam?this._cam.layers.mask:this._cullingMask}set cullingLayer(A){this.cullingMask=(1<<A|0)>>>0}set backgroundBlurriness(A){A!==this._backgroundBlurriness&&(A===void 0?this._backgroundBlurriness=void 0:this._backgroundBlurriness=Math.min(Math.max(A,0),1),this.applyClearFlagsIfIsActiveCamera())}get backgroundBlurriness(){return this._backgroundBlurriness}set backgroundIntensity(A){A!==this._backgroundIntensity&&(A===void 0?this._backgroundIntensity=void 0:this._backgroundIntensity=Math.min(Math.max(A,0),10),this.applyClearFlagsIfIsActiveCamera())}get backgroundIntensity(){return this._backgroundIntensity}set backgroundRotation(A){A!==this._backgroundRotation&&(A===void 0?this._backgroundRotation=void 0:this._backgroundRotation=A,this.applyClearFlagsIfIsActiveCamera())}get backgroundRotation(){return this._backgroundRotation}set environmentIntensity(A){this._environmentIntensity=A}get environmentIntensity(){return this._environmentIntensity}get backgroundColor(){return this._backgroundColor??null}set backgroundColor(A){if(A){if(this._backgroundColor)this._backgroundColor.copy(A);else{if(!A.clone)return;this._backgroundColor=A.clone()}A.alpha===void 0&&(this._backgroundColor.alpha=1),this.applyClearFlagsIfIsActiveCamera()}}set targetTexture(A){this._targetTexture=A}get targetTexture(){return this._targetTexture}get cam(){return this.activeAndEnabled&&this.buildCamera(),this._cam}screenPointToRay(A,e,t){const i=this.cam,I=op._origin;I.set(A,e,-1),this.context.input.convertScreenspaceToRaycastSpace(I),f2&&console.log("screenPointToRay",A.toFixed(2),e.toFixed(2),"now:",I.x.toFixed(2),I.y.toFixed(2),"isInXR:"+this.context.isInXR),I.z=-1,I.unproject(i);const o=op._direction.set(I.x,I.y,I.z),s=ve(i);return o.sub(s),o.normalize(),t?(t.set(s,o),t):new xo(s.clone(),o.clone())}getFrustum(){return this._frustum||(this._frustum=new Kc,this.updateFrustum()),this._frustum}updateFrustum(){this._frustum||(this._frustum=new Kc),this._frustum.setFromProjectionMatrix(this.getProjectionScreenMatrix(this._projScreenMatrix,!0),this.context.renderer.coordinateSystem)}getProjectionScreenMatrix(A,e){return e&&this._projScreenMatrix.multiplyMatrices(this.cam.projectionMatrix,this.cam.matrixWorldInverse),A===this._projScreenMatrix?A:A.copy(this._projScreenMatrix)}awake(){f2&&window.addEventListener("pointerdown",A=>{const e=A.clientX,t=A.clientY;console.log("touch",e.toFixed(2),t.toFixed(2));const i=this.screenPointToRay(e,t),I="#"+Math.floor(Math.random()*16777215).toString(16);fe.DrawRay(i.origin,i.direction,I,10)})}onEnable(){Ma&&console.log(`Camera enabled: "${this.name}". ClearFlags=${kB[this._clearFlags]}`,this),this.buildCamera(),(this.tag=="MainCamera"||!this.context.mainCameraComponent)&&(this.context.setCurrentCamera(this),kEA(this)),this.applyClearFlagsIfIsActiveCamera({applySkybox:!0})}onDisable(){this.context.removeCamera(this)}onBeforeRender(){if(this._cam&&(this._frustum&&this.updateFrustum(),this._clearFlags===2&&this.applyClearFlagsIfIsActiveCamera(),this._targetTexture)){this.context.isManagedExternally&&(this._warnedAboutExternalRenderer||(this._warnedAboutExternalRenderer=!0,console.warn("Rendering with external renderer is not supported yet. This may not work or throw errors. Please remove the the target texture from your camera: "+this.name,this.targetTexture))),this.context.composer;const A=this.context.renderer;if(A){const e=this.context.mainCameraComponent;this.applyClearFlags(),this._targetTexture.render(this.context.scene,this._cam,A),e==null||e.applyClearFlags()}}}buildCamera(){if(this._cam)return;const A=this.gameObject.isCamera;let e=null;if(A?(e=this.gameObject,e==null||e.layers.enableAll(),e instanceof He&&(this._fov=e.fov)):e=this.gameObject.children[0],e&&e.isCamera)e instanceof He&&(this._fov&&(e.fov=this._fov),e.near=this._nearClipPlane,e.far=this._farClipPlane,e.updateProjectionMatrix());else if(!this.orthographic)e=new He(this.fieldOfView,window.innerWidth/window.innerHeight,this._nearClipPlane,this._farClipPlane),this.fieldOfView&&(e.fov=this.fieldOfView),this.gameObject.add(e);else{const t=this.orthographicSize*100;e=new Tr(window.innerWidth/-t,window.innerWidth/t,window.innerHeight/t,window.innerHeight/-t,this._nearClipPlane,this._farClipPlane),this.gameObject.add(e)}this._cam=e,this._cam.layers.mask=this._cullingMask,this.tag=="MainCamera"&&this.context.setCurrentCamera(this)}applyClearFlagsIfIsActiveCamera(A){this.context.mainCameraComponent===this&&this.applyClearFlags(A)}applyClearFlags(A){if(!this._cam){Ma&&console.log("Camera does not exist (apply clear flags)");return}if(this.fieldOfView=this._fov,Ma){const e=`Camera "${this.name}" clear flags: ${kB[this._clearFlags]}`;console.debug(e)}switch(this._clearFlags){case 1:if(op.backgroundShouldBeTransparent(this.context)&&(!this.ARBackgroundAlpha||this.ARBackgroundAlpha<.001)){this.context.scene.background=null,this.context.renderer.setClearColor(0,0);return}(!this.scene.background||!this._skybox||(A==null?void 0:A.applySkybox)===!0)&&this.applySceneSkybox(),this._backgroundBlurriness!==void 0?this.context.scene.backgroundBlurriness=this._backgroundBlurriness:Ma&&console.warn(`Camera "${this.name}" has no background blurriness`),this._backgroundIntensity!==void 0&&(this.context.scene.backgroundIntensity=this._backgroundIntensity),this._backgroundRotation!==void 0?this.context.scene.backgroundRotation=this._backgroundRotation:Ma&&console.warn(`Camera "${this.name}" has no background intensity`);break;case 2:if(this._backgroundColor){let e=this._backgroundColor.alpha;op.backgroundShouldBeTransparent(this.context)&&(e=this.ARBackgroundAlpha??0),this.context.scene.background=null,this.context.renderer.setClearColor(this._backgroundColor,e)}else Ma&&console.warn(`Camera "${this.name}" has no background color`,this);break;case 4:this.context.scene.background=null,this.context.renderer.setClearColor(0,0);break}}applySceneSkybox(){this._skybox||(this._skybox=new mEA(this)),this._skybox.apply()}static backgroundShouldBeTransparent(A){var I,o,s,n;const e=(I=A.renderer.xr)==null?void 0:I.getSession();if(!e)return!1;if(typeof e._transparent=="boolean")return e._transparent;const t=e.environmentBlendMode;Ma&&fi("Environment blend mode: "+t+" on "+navigator.userAgent);let i=t==="additive"||t==="alpha-blend";return A.isInAR&&t==="opaque"&&((o=navigator.userAgent)!=null&&o.includes("OculusBrowser")||(s=navigator.userAgent)!=null&&s.includes("Mozilla")&&((n=navigator.userAgent)!=null&&n.includes("Mobile WebXRViewer/v2")))&&(i=!0),e._transparent=i,i}},B(qS,"_origin",new y),B(qS,"_direction",new y),qS);let Wt=op;uo([D()],Wt.prototype,"aspect",1);uo([D()],Wt.prototype,"fieldOfView",1);uo([D()],Wt.prototype,"nearClipPlane",1);uo([D()],Wt.prototype,"farClipPlane",1);uo([D()],Wt.prototype,"clearFlags",1);uo([D()],Wt.prototype,"orthographic",2);uo([D()],Wt.prototype,"orthographicSize",2);uo([D()],Wt.prototype,"ARBackgroundAlpha",2);uo([D()],Wt.prototype,"cullingMask",1);uo([D()],Wt.prototype,"backgroundBlurriness",1);uo([D()],Wt.prototype,"backgroundIntensity",1);uo([D(rt)],Wt.prototype,"backgroundRotation",1);uo([D()],Wt.prototype,"environmentIntensity",1);uo([D(Ft)],Wt.prototype,"backgroundColor",1);uo([D(mB)],Wt.prototype,"targetTexture",1);class mEA{constructor(A){B(this,"_camera");B(this,"_skybox");this._camera=A}get context(){var A;return(A=this._camera)==null?void 0:A.context}apply(){this._skybox=this.context.lightmaps.tryGetSkybox(this._camera.sourceId),this._skybox?this.context.scene.background!==this._skybox&&(Ma&&console.log(`Camera "${this._camera.name}" set skybox`,this._camera,this._skybox),this._skybox.mapping=No,this.context.scene.background=this._skybox):(this._did_log_failed_to_find_skybox||(this._did_log_failed_to_find_skybox=!0,console.warn(`Camera "${this._camera.name}" failed to load/find skybox texture`,this._camera.sourceId,this.context.lightmaps,"Current background: ",this.context.scene.background)),(Ma||ae())&&Ot(`Camera "${this._camera.name}" has no skybox texture`))}}function kEA(g){gA("freecam")&&g.context.mainCameraComponent===g&&sA.getOrAddComponent(g.gameObject,Mt)}class MB extends FA{constructor(){super(...arguments);B(this,"_listener",null);B(this,"onInteraction",()=>{this.destroyed||this.listener==null||this.addListenerIfItExists()})}get listener(){return this._listener==null&&(this._listener=new ZP),this._listener}onEnable(){Fr.registerWaitForInteraction(this.onInteraction),this.addListenerIfItExists()}onDisable(){Fr.unregisterWaitForInteraction(this.onInteraction),this.removeListenerIfItExists()}addListenerIfItExists(){const e=this._listener;if(!e||e!=null&&e.parent)return;const t=this.context.mainCameraComponent||sA.getComponentInParent(this.gameObject,Wt);t!=null&&t.cam?t.cam.add(e):this.gameObject.add(e),e.filter?(e.gain.connect(e.filter),e.filter.connect(e.context.destination)):e.gain.connect(e.context.destination)}removeListenerIfItExists(){const e=this._listener;e&&(e.removeFromParent(),e.filter&&e.filter.disconnect(),e.gain&&e.gain.disconnect())}}class MEA extends Oi{constructor(A,e=1,t=16,i=2){const I=new we,o=t+i*2,s=new Float32Array((o*3+3)*3);I.setAttribute("position",new ne(s,3));const n=new Ii({color:65280}),r=new Ii({color:16776960});super(I,[r,n]),this.audio=A,this.range=e,this.divisionsInnerAngle=t,this.divisionsOuterAngle=i,this.type="PositionalAudioHelper",this.update()}update(){const A=this.audio,e=this.range,t=this.divisionsInnerAngle,i=this.divisionsOuterAngle,I=ht.degToRad(A.panner.coneInnerAngle),o=ht.degToRad(A.panner.coneOuterAngle),s=I/2,n=o/2;let r=0,a=0,C,Q;const c=this.geometry,E=c.attributes.position;c.clearGroups();function h(l,d,p,u){const f=(d-l)/p;for(E.setXYZ(r,0,0,0),a++,C=l;C<d;C+=f)Q=r+a,E.setXYZ(Q,Math.sin(C)*e,0,Math.cos(C)*e),E.setXYZ(Q+1,Math.sin(Math.min(C+f,d))*e,0,Math.cos(Math.min(C+f,d))*e),E.setXYZ(Q+2,0,0,0),a+=3;c.addGroup(r,a,u),r+=a,a=0}h(-n,-s,i,0),h(-s,s,t,1),h(s,n,i,0),E.needsUpdate=!0,I===o&&(this.material[0].visible=!1)}dispose(){this.geometry.dispose(),this.material[0].dispose(),this.material[1].dispose()}}var GEA=Object.defineProperty,REA=Object.getOwnPropertyDescriptor,Pr=(g,A,e,t)=>{for(var i=t>1?void 0:t?REA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&GEA(A,e,i),i};const NI=gA("debugaudio"),VC=class extends FA{constructor(){super(...arguments);B(this,"clip","");B(this,"playOnAwake",!1);B(this,"preload",!1);B(this,"_spatialBlend",0);B(this,"_minDistance",1);B(this,"_maxDistance",100);B(this,"_volume",1);B(this,"rollOffMode",0);B(this,"playInBackground",!0);B(this,"_loop",!1);B(this,"sound",null);B(this,"helper",null);B(this,"wasPlaying",!1);B(this,"audioLoader",null);B(this,"shouldPlay",!1);B(this,"_lastClipStartedLoading",null);B(this,"_audioElement",null);B(this,"onVisibilityChanged",()=>{switch(document.visibilityState){case"hidden":(this.playInBackground===!1||In())&&(this.wasPlaying=this.isPlaying,this.isPlaying&&this.pause());break;case"visible":NI&&console.log("visible",this.enabled,this.playOnAwake,!this.isPlaying,VC.userInteractionRegistered,this.wasPlaying),this.enabled&&this.playOnAwake&&!this.isPlaying&&VC.userInteractionRegistered&&this.wasPlaying&&this.play();break}});B(this,"onApplicationMuteChanged",()=>{var A,e;this.context.application.muted?(A=this.sound)==null||A.setVolume(0):(e=this.sound)==null||e.setVolume(this.volume)});B(this,"createAudio",A=>{NI&&console.log("AudioBuffer finished loading",A);const e=this.Sound;if(!e){NI&&console.warn("Failed getting sound?",this.name);return}e.isPlaying&&e.stop(),A&&e.setBuffer(A),e.loop=this._loop,this.context.application.muted?e.setVolume(0):e.setVolume(this.volume),e.autoplay=this.shouldPlay&&VC.userInteractionRegistered,this.applySpatialDistanceSettings(),e.isPlaying&&e.stop(),VC.registerWaitForAllowAudio(this.__onAllowAudioCallback)});B(this,"__onAllowAudioCallback",()=>{this.shouldPlay&&this.play()});B(this,"_lastContextTime",0);B(this,"_hasEnded",!0);B(this,"_needUpdateSpatialDistanceSettings",!1)}static get userInteractionRegistered(){return Fr.userInteractionRegistered}static registerWaitForAllowAudio(A){Fr.registerWaitForAllowAudio(A)}get loop(){return this.sound&&(this._loop=this.sound.getLoop()),this._loop}set loop(A){this._loop=A,this.sound&&this.sound.setLoop(A)}get spatialBlend(){return this._spatialBlend}set spatialBlend(A){A!==this._spatialBlend&&(this._spatialBlend=A,this._needUpdateSpatialDistanceSettings=!0)}get minDistance(){return this._minDistance}set minDistance(A){this._minDistance!==A&&(this._minDistance=A,this._needUpdateSpatialDistanceSettings=!0)}get maxDistance(){return this._maxDistance}set maxDistance(A){this._maxDistance!==A&&(this._maxDistance=A,this._needUpdateSpatialDistanceSettings=!0)}get volume(){return this._volume}set volume(A){this._volume=A,this.sound&&!this.context.application.muted&&(NI&&console.log(this.name,"audio set volume",A),this.sound.setVolume(A))}get Sound(){var A;if(!this.sound&&VC.userInteractionRegistered){let e=sA.getComponent(this.context.mainCamera,MB)??sA.findObjectOfType(MB,this.context);!e&&this.context.mainCamera&&(e=sA.addNewComponent(this.context.mainCamera,MB)),e!=null&&e.listener?(this.sound=new jP(e.listener),(A=this.gameObject)==null||A.add(this.sound)):NI&&console.warn("No audio listener found in scene - can not play audio")}return this.sound}get ShouldPlay(){return this.shouldPlay}get audioContext(){var A;return(A=this.sound)==null?void 0:A.context}awake(){NI&&console.log(this),this.audioLoader=new O0,this.playOnAwake&&(this.shouldPlay=!0),this.preload&&typeof this.clip=="string"&&this.audioLoader.load(this.clip,this.createAudio,()=>{},console.error)}onEnable(){this.sound&&this.gameObject.add(this.sound),VC.userInteractionRegistered?this.playOnAwake&&this.context.application.isVisible&&this.play():VC.registerWaitForAllowAudio(()=>{this.enabled&&!this.destroyed&&this.shouldPlay&&this.onNewClip(this.clip)}),globalThis.addEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.addEventListener(Em.MuteChanged,this.onApplicationMuteChanged)}onDisable(){globalThis.removeEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.removeEventListener(Em.MuteChanged,this.onApplicationMuteChanged),this.pause()}applySpatialDistanceSettings(){const A=this.sound;if(!A)return;this._needUpdateSpatialDistanceSettings=!1;const e=ge.lerp(10*this._maxDistance/Math.max(1e-4,this.spatialBlend),this._minDistance,this.spatialBlend);switch(NI&&console.log(this.name,this._minDistance,this._maxDistance,this.spatialBlend,"Ref distance="+e),A.setRefDistance(e),A.setMaxDistance(Math.max(.01,this._maxDistance)),this.rollOffMode){case 0:A.setDistanceModel("exponential");break;case 1:A.setDistanceModel("linear");break;case 2:console.warn("Custom rolloff for AudioSource is not supported: "+this.name);break}this.spatialBlend>0?NI&&!this.helper&&(this.helper=new MEA(A,A.getRefDistance()),A.add(this.helper)):this.helper&&this.helper.parent&&this.helper.removeFromParent()}async onNewClip(A){if(A&&(this.clip=A),typeof A=="string")if(NI&&console.log(A),A.endsWith(".mp3")||A.endsWith(".wav")){if(this.audioLoader||(this.audioLoader=new O0),this.shouldPlay=!0,this._lastClipStartedLoading===A){NI&&console.log("Is currently loading:",this._lastClipStartedLoading,this);return}this._lastClipStartedLoading=A,NI&&console.log("load audio",A);const e=await this.audioLoader.loadAsync(A).catch(console.error);this._lastClipStartedLoading=null,e&&this.createAudio(e)}else console.warn("Unsupported audio clip type",A);else this.shouldPlay=!0,this.createAudio()}play(A=void 0){var t,i,I;!A&&this.clip&&(A=this.clip),A!==void 0&&typeof A!="string"&&!(A instanceof MediaStream)&&(ae()&&console.warn("Called play on AudioSource with unknown argument type:",A+`
5732
+ `;var iEA=Object.defineProperty,gEA=Object.getOwnPropertyDescriptor,Iv=(g,A,e,t)=>{for(var i=t>1?void 0:t?gEA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&iEA(A,e,i),i};class sE extends FA{constructor(){super(...arguments);B(this,"constraintActive",!0);B(this,"locked",!1);B(this,"sources",[])}}Iv([D()],sE.prototype,"constraintActive",2);Iv([D()],sE.prototype,"locked",2);Iv([D(DA)],sE.prototype,"sources",2);function IEA(g,A){return ZB(g,Gt.ContextCreated,A),()=>jB(g,Gt.ContextCreated)}function oEA(g,A){return ZB(g,Gt.ContextClearing,A),()=>jB(g,Gt.ContextClearing)}function sEA(g,A){return ZB(g,Gt.ContextDestroying,A),()=>jB(g,Gt.ContextDestroying)}function oj(g,A){return ZB(g,oi.Start,A),()=>jB(g,oi.Start)}function sj(g,A){return ZB(g,oi.Update,A),()=>jB(g,oi.Update)}function nEA(g,A){return ZB(g,oi.OnBeforeRender,A),()=>jB(g,oi.OnBeforeRender)}function rEA(g,A){return ZB(g,oi.OnAfterRender,A),()=>jB(g,oi.OnAfterRender)}class yc{constructor(){B(this,"bb",null);B(this,"bb_pos",0)}__init(A,e){return this.bb_pos=A,this.bb=e,this}x(){return this.bb.readFloat32(this.bb_pos)}y(){return this.bb.readFloat32(this.bb_pos+4)}z(){return this.bb.readFloat32(this.bb_pos+8)}static sizeOf(){return 12}static createVec3(A,e,t,i){return A.prep(4,12),A.writeFloat32(i),A.writeFloat32(t),A.writeFloat32(e),A.offset()}}class nj{constructor(){B(this,"bb",null);B(this,"bb_pos",0)}__init(A,e){return this.bb_pos=A,this.bb=e,this}position(A){return(A||new yc).__init(this.bb_pos,this.bb)}rotation(A){return(A||new yc).__init(this.bb_pos+12,this.bb)}scale(A){return(A||new yc).__init(this.bb_pos+24,this.bb)}static sizeOf(){return 36}static createTransform(A,e,t,i,I,o,s,n,r,a){return A.prep(4,36),A.prep(4,12),A.writeFloat32(a),A.writeFloat32(r),A.writeFloat32(n),A.prep(4,12),A.writeFloat32(s),A.writeFloat32(o),A.writeFloat32(I),A.prep(4,12),A.writeFloat32(i),A.writeFloat32(t),A.writeFloat32(e),A.offset()}}class qa{constructor(){B(this,"bb",null);B(this,"bb_pos",0)}__init(A,e){return this.bb_pos=A,this.bb=e,this}static getRootAsSyncedTransformModel(A,e){return(e||new qa).__init(A.readInt32(A.position())+A.position(),A)}static getSizePrefixedRootAsSyncedTransformModel(A,e){return A.setPosition(A.position()+Ox),(e||new qa).__init(A.readInt32(A.position())+A.position(),A)}guid(A){const e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,A):null}fast(){const A=this.bb.__offset(this.bb_pos,6);return A?!!this.bb.readInt8(this.bb_pos+A):!1}transform(A){const e=this.bb.__offset(this.bb_pos,8);return e?(A||new nj).__init(this.bb_pos+e,this.bb):null}dontSave(){const A=this.bb.__offset(this.bb_pos,10);return A?!!this.bb.readInt8(this.bb_pos+A):!1}static startSyncedTransformModel(A){A.startObject(4)}static addGuid(A,e){A.addFieldOffset(0,e,0)}static addFast(A,e){A.addFieldInt8(1,+e,0)}static addTransform(A,e){A.addFieldStruct(2,e,0)}static addDontSave(A,e){A.addFieldInt8(3,+e,0)}static endSyncedTransformModel(A){return A.endObject()}static finishSyncedTransformModelBuffer(A,e){A.finish(e)}static finishSizePrefixedSyncedTransformModelBuffer(A,e){A.finish(e,void 0,!0)}}var Lg=(g=>(g[g.Average=0]="Average",g[g.Multiply=1]="Multiply",g[g.Minimum=2]="Minimum",g[g.Maximum=3]="Maximum",g))(Lg||{}),lM=(g=>(g[g.Discrete=0]="Discrete",g[g.Continuous=1]="Continuous",g))(lM||{}),$i=(g=>(g[g.None=0]="None",g[g.FreezePositionX=2]="FreezePositionX",g[g.FreezePositionY=4]="FreezePositionY",g[g.FreezePositionZ=8]="FreezePositionZ",g[g.FreezePosition=14]="FreezePosition",g[g.FreezeRotationX=16]="FreezeRotationX",g[g.FreezeRotationY=32]="FreezeRotationY",g[g.FreezeRotationZ=64]="FreezeRotationZ",g[g.FreezeRotation=112]="FreezeRotation",g[g.FreezeAll=126]="FreezeAll",g))($i||{}),th=(g=>(g[g.None=0]="None",g[g.X=2]="X",g[g.Y=4]="Y",g[g.Z=8]="Z",g[g.All=-1]="All",g))(th||{});const DI=function(g,A){return function(e,t,i){aEA(e,t,i,g,A)}};function aEA(g,A,e,t,i){if(!i&&!t&&!g.onValidate)return;if(e!==void 0){console.error("Invalid usage of validate decorator. Only fields can be validated.",g,A,e),fi("Invalid usage of validate decorator. Only fields can be validated. Property: "+A,Is.Error);return}let I="";if(typeof A=="string"?I=A:I=A.name,g.__internalAwake){const o=Symbol(I),s=g.__internalAwake;g.__internalAwake=function(){var n;if(!this.onValidate){ae()&&console.warn('Usage of @validate decorate detected but there is no onValidate method in your class: "'+((n=g.constructor)==null?void 0:n.name)+'"');return}if(this[o]===void 0){this[o]=this[I];const r=this[I];if(r instanceof tA||r instanceof y||r instanceof Ae||r instanceof GA){const a=this[I];Kk(a,()=>{this.onValidate(I)})}Object.defineProperty(this,I,{set:function(a){var C;if(this[SK]===!0)this[o]=a;else{t==null||t.call(this,a);const Q=this[o];this[o]=a,(C=this.onValidate)==null||C.call(this,I,Q)}},get:function(){return i==null||i.call(this),this[o]}})}s.call(this)}}}const CEA=function(g){return function(A,e,t){let i="";typeof e=="string"?i=e:i=e.name;const I=g.prototype,o=Object.getOwnPropertyDescriptor(I,i);if(!(o!=null&&o.value)){console.warn("Can not apply prefix: type does not have method named",e,g);return}const s=o.value,n=A[i];Object.defineProperty(I,i,{value:function(...r){const a=n==null?void 0:n.call(this,...r);if(a instanceof Promise){a.then(C=>{if(C!==!1)return s.call(this,...r)});return}if(a!==!1)return s.call(this,...r)}})}};var BEA=Object.defineProperty,QEA=Object.getOwnPropertyDescriptor,Es=(g,A,e,t)=>{for(var i=t>1?void 0:t?QEA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&BEA(A,e,i),i};class cEA{constructor(A,e){B(this,"positionChanged",!1);B(this,"rotationChanged",!1);B(this,"position");B(this,"quaternion");B(this,"_positionKeys",["x","y","z"]);B(this,"_quaternionKeys",["_x","_y","_z","_w"]);B(this,"mute",!1);B(this,"context");B(this,"obj");B(this,"_positionWatch");B(this,"_rotationWatch");this.context=e,this.obj=A}get isDirty(){return this.positionChanged||this.rotationChanged}reset(A=!1){if(this.positionChanged=!1,this.rotationChanged=!1,this.mute=!1,A){if(this.position)for(const e of this._positionKeys)delete this.position[e];if(this.quaternion)for(const e of this._quaternionKeys)delete this.quaternion[e]}}syncValues(){for(const A of this._positionKeys)this.position[A]=this.obj.position[A];for(const A of this._quaternionKeys)this.quaternion[A]=this.obj.quaternion[A]}applyValues(){if(this.positionChanged&&this.position)for(const A of this._positionKeys){const e=this.position[A];e!==void 0&&(this.obj.position[A]=e)}if(this.rotationChanged&&this.quaternion)for(const A of this._quaternionKeys){const e=this.quaternion[A];e!==void 0&&(this.obj.quaternion[A]=e)}}start(A,e){this.reset(),A&&(this._positionWatch||(this._positionWatch=new Za(this.obj.position,["x","y","z"])),this._positionWatch.apply(),this.position={},this._positionWatch.subscribeWrite((I,o)=>{var n;if((n=this.context.physics.engine)!=null&&n.isUpdating||this.mute)return;const s=this.position[o];Math.abs(s-I)<1e-5||(this.position[o]=I,this.positionChanged=!0)})),e&&(this._rotationWatch||(this._rotationWatch=new Za(this.obj.quaternion,["_x","_y","_z","_w"])),this._rotationWatch.apply(),this.quaternion={},this._rotationWatch.subscribeWrite((I,o)=>{var n;if((n=this.context.physics.engine)!=null&&n.isUpdating||this.mute)return;const s=this.quaternion[o];Math.abs(s-I)<1e-5||(this.quaternion[o]=I,this.rotationChanged=!0)}));const t=this.obj.matrixWorld.multiplyMatrices.bind(this.obj.matrixWorld),i=new fA;this.obj.matrixWorld.multiplyMatrices=(I,o)=>{var s;return(s=this.context.physics.engine)!=null&&s.isUpdating||this.mute||i.equals(I)||(this.positionChanged=!0,this.rotationChanged=!0,i.copy(I)),t(I,o)}}stop(){var A,e;(A=this._positionWatch)==null||A.revoke(),(e=this._rotationWatch)==null||e.revoke()}}var FN;const WK=(FN=class extends FA{constructor(){super(...arguments);B(this,"autoMass",!0);B(this,"_mass",0);B(this,"useGravity",!0);B(this,"centerOfMass",new y(0,0,0));B(this,"constraints",$i.None);B(this,"isKinematic",!1);B(this,"drag",0);B(this,"angularDrag",1);B(this,"detectCollisions",!0);B(this,"sleepThreshold",.01);B(this,"collisionDetectionMode",lM.Discrete);B(this,"_gravityScale",1);B(this,"dominanceGroup",0);B(this,"_propertiesChanged",!1);B(this,"_currentVelocity",new y);B(this,"_smoothedVelocity",new y);B(this,"_smoothedVelocityGetter",new y);B(this,"_lastPosition",new y);B(this,"_watch")}set mass(A){A!==this._mass&&(this._mass=A,this._propertiesChanged=!0,this.__didAwake&&(this.autoMass=!1))}get mass(){var A,e;return this.autoMass?((e=(A=this.context.physics.engine)==null?void 0:A.getBody(this))==null?void 0:e.mass())??-1:this._mass}get lockPositionX(){return(this.constraints&$i.FreezePositionX)!==0}get lockPositionY(){return(this.constraints&$i.FreezePositionY)!==0}get lockPositionZ(){return(this.constraints&$i.FreezePositionZ)!==0}get lockRotationX(){return(this.constraints&$i.FreezeRotationX)!==0}get lockRotationY(){return(this.constraints&$i.FreezeRotationY)!==0}get lockRotationZ(){return(this.constraints&$i.FreezeRotationZ)!==0}set lockPositionX(A){A?this.constraints|=$i.FreezePositionX:this.constraints&=~$i.FreezePositionX}set lockPositionY(A){A?this.constraints|=$i.FreezePositionY:this.constraints&=~$i.FreezePositionY}set lockPositionZ(A){A?this.constraints|=$i.FreezePositionZ:this.constraints&=~$i.FreezePositionZ}set lockRotationX(A){A?this.constraints|=$i.FreezeRotationX:this.constraints&=~$i.FreezeRotationX}set lockRotationY(A){A?this.constraints|=$i.FreezeRotationY:this.constraints&=~$i.FreezeRotationY}set lockRotationZ(A){A?this.constraints|=$i.FreezeRotationZ:this.constraints&=~$i.FreezeRotationZ}set gravityScale(A){this._gravityScale=A}get gravityScale(){return this._gravityScale}awake(){this._watch=void 0,this._propertiesChanged=!1}onEnable(){this._watch||(this._watch=new cEA(this.gameObject,this.context)),this._watch.start(!0,!0),this.startCoroutine(this.beforePhysics(),oi.LateUpdate)}onDisable(){var A,e;(A=this._watch)==null||A.stop(),(e=this.context.physics.engine)==null||e.removeBody(this)}onDestroy(){var A;(A=this.context.physics.engine)==null||A.removeBody(this)}onValidate(){this._propertiesChanged=!0}*beforePhysics(){var A,e,t,i;for(;;)this._propertiesChanged&&(this._propertiesChanged=!1,(A=this.context.physics.engine)==null||A.updateProperties(this)),(e=this._watch)!=null&&e.isDirty?(this._watch.mute=!0,this._watch.applyValues(),(t=this.context.physics.engine)==null||t.updateBody(this,this._watch.positionChanged,this._watch.rotationChanged),this._watch.reset()):(i=this._watch)==null||i.syncValues(),this.captureVelocity(),yield}teleport(A,e=!0){var t;(t=this._watch)==null||t.reset(!0),e?this.gameObject.position.set(A.x,A.y,A.z):this.setWorldPosition(A.x,A.y,A.z),this.resetForcesAndTorques(),this.resetVelocities()}resetForces(A=!0){var e;(e=this.context.physics.engine)==null||e.resetForces(this,A)}resetTorques(A=!0){var e;(e=this.context.physics.engine)==null||e.resetTorques(this,A)}resetVelocities(){this.setVelocity(0,0,0),this.setAngularVelocity(0,0,0)}resetForcesAndTorques(){this.resetForces(),this.resetTorques()}wakeUp(){var A;(A=this.context.physics.engine)==null||A.wakeup(this)}get isSleeping(){var A;return(A=this.context.physics.engine)==null?void 0:A.isSleeping(this)}updateProperties(){var A;return this._propertiesChanged=!1,(A=this.context.physics.engine)==null?void 0:A.updateProperties(this)}applyForce(A,e,t=!0){var i;this._propertiesChanged&&this.updateProperties(),(i=this.context.physics.engine)==null||i.addForce(this,A,t)}applyImpulse(A,e=!0){var t;this._propertiesChanged&&this.updateProperties(),(t=this.context.physics.engine)==null||t.applyImpulse(this,A,e)}setForce(A,e,t,i=!0){var I,o,s;(I=this.context.physics.engine)==null||I.resetForces(this,i),typeof A=="number"?(e??(e=0),t??(t=0),(o=this.context.physics.engine)==null||o.addForce(this,{x:A,y:e,z:t},i)):(s=this.context.physics.engine)==null||s.addForce(this,A,i)}getVelocity(){var e;const A=(e=this.context.physics.engine)==null?void 0:e.getLinearVelocity(this);return A?(this._currentVelocity.x=A.x,this._currentVelocity.y=A.y,this._currentVelocity.z=A.z,this._currentVelocity):this._currentVelocity.set(0,0,0)}setVelocity(A,e,t,i=!0){var I,o;if(A instanceof y){const s=A;(I=this.context.physics.engine)==null||I.setLinearVelocity(this,s,i);return}e===void 0||t===void 0||(o=this.context.physics.engine)==null||o.setLinearVelocity(this,{x:A,y:e,z:t},i)}getAngularVelocity(){var e;const A=(e=this.context.physics.engine)==null?void 0:e.getAngularVelocity(this);return A?(this._currentVelocity.x=A.x,this._currentVelocity.y=A.y,this._currentVelocity.z=A.z,this._currentVelocity):this._currentVelocity.set(0,0,0)}setAngularVelocity(A,e,t,i=!0){var I,o;if(A instanceof y){const s=A;(I=this.context.physics.engine)==null||I.setAngularVelocity(this,s,i);return}e===void 0||t===void 0||(o=this.context.physics.engine)==null||o.setAngularVelocity(this,{x:A,y:e,z:t},i)}setTorque(A,e,t){this.setAngularVelocity(A,e,t)}get smoothedVelocity(){return this._smoothedVelocityGetter.copy(this._smoothedVelocity),this._smoothedVelocityGetter.multiplyScalar(1/this.context.time.deltaTime)}setBodyFromGameObject(A=null){}captureVelocity(){const A=ve(this.gameObject);WK.tempPosition.copy(A);const e=A.sub(this._lastPosition);this._lastPosition.copy(WK.tempPosition),this._smoothedVelocity.lerp(e,this.context.time.deltaTime/.1)}},B(FN,"tempPosition",new y),FN);let Pt=WK;Es([DI()],Pt.prototype,"autoMass",2);Es([D()],Pt.prototype,"mass",1);Es([DI(),D()],Pt.prototype,"useGravity",2);Es([D(y)],Pt.prototype,"centerOfMass",2);Es([DI(),D()],Pt.prototype,"constraints",2);Es([DI(),D()],Pt.prototype,"isKinematic",2);Es([DI(),D()],Pt.prototype,"drag",2);Es([DI(),D()],Pt.prototype,"angularDrag",2);Es([DI(),D()],Pt.prototype,"detectCollisions",2);Es([DI(),D()],Pt.prototype,"sleepThreshold",2);Es([DI(),D()],Pt.prototype,"collisionDetectionMode",2);Es([DI()],Pt.prototype,"_gravityScale",2);Es([DI()],Pt.prototype,"dominanceGroup",2);const zC=gA("debugsync"),Nf="STRS";Wx(Nf,qa.getRootAsSyncedTransformModel);const er=new mD;function rj(g,A,e=!0){er.clear();const t=er.createString(g);qa.startSyncedTransformModel(er),qa.addGuid(er,t),qa.addFast(er,e);const i=A.worldPosition,I=A.worldEuler,o=A.gameObject.scale;qa.addTransform(er,nj.createTransform(er,i.x,i.y,i.z,I.x,I.y,I.z,o.x,o.y,o.z));const s=qa.endSyncedTransformModel(er);return er.finish(s,Nf),er.asUint8Array()}let ZK=0,Lp=0;sj(g=>{var t;const e=((t=g.connection.currentServerUrl)==null?void 0:t.includes("glitch"))?10:40;Lp=Math.floor(ZK/e),ZK=0,zC&&Lp>0&&console.log("Sync Transform Fast Interval",Lp)});class bB extends FA{constructor(){super(...arguments);B(this,"overridePhysics",!0);B(this,"interpolatePosition",!0);B(this,"interpolateRotation",!0);B(this,"fastMode",!1);B(this,"syncDestroy",!1);B(this,"_model",null);B(this,"_needsUpdate",!0);B(this,"rb",null);B(this,"_wasKinematic",!1);B(this,"_receivedDataBefore",!1);B(this,"_targetPosition");B(this,"_targetRotation");B(this,"_receivedFastUpdate",!1);B(this,"_shouldRequestOwnership",!1);B(this,"joinedRoomCallback",null);B(this,"receivedDataCallback",null);B(this,"tempEuler",new rt);B(this,"receivedUpdate",!1);B(this,"lastWorldPos");B(this,"lastWorldRotation")}requestOwnership(){zC&&console.log("Request ownership"),this._model?this._model.requestOwnership():(this._shouldRequestOwnership=!0,this._needsUpdate=!0)}hasOwnership(){var e;return((e=this._model)==null?void 0:e.hasOwnership)??void 0}isOwned(){var e;return(e=this._model)==null?void 0:e.isOwned}awake(){zC&&console.log("new instance",this.guid,this),this._receivedDataBefore=!1,this._targetPosition=new y,this._targetRotation=new GA,this.lastWorldPos=new y,this.lastWorldRotation=new GA,this.rb=sA.getComponentInChildren(this.gameObject,Pt),this.rb&&(this._wasKinematic=this.rb.isKinematic),this.receivedUpdate=!0,this._model=new $x(this.context.connection,this.guid),this.context.connection.isConnected&&this.tryGetLastState(),this.joinedRoomCallback=this.tryGetLastState.bind(this),this.context.connection.beginListen(ze.JoinedRoom,this.joinedRoomCallback),this.receivedDataCallback=this.onReceivedData.bind(this),this.context.connection.beginListenBinary(Nf,this.receivedDataCallback)}onDestroy(){this.syncDestroy&&tv(this.guid,this.context.connection),this._model=null,this.context.connection.stopListen(ze.JoinedRoom,this.joinedRoomCallback),this.context.connection.stopListenBinary(Nf,this.receivedDataCallback)}tryGetLastState(){const e=this.context.connection.tryGetState(this.guid);e&&this.onReceivedData(e)}onReceivedData(e){var t;if(!this.destroyed&&typeof e.guid=="function"&&e.guid()===this.guid){zC&&console.log("new data",this.context.connection.connectionId,this.context.time.frameCount,this.guid,e),this.receivedUpdate=!0,this._receivedFastUpdate=e.fast();const i=e.transform();if(i){Ws.markDirty(this.gameObject,!0);const I=i.position();I&&(this.interpolatePosition&&((t=this._targetPosition)==null||t.set(I.x(),I.y(),I.z())),(!this.interpolatePosition||!this._receivedDataBefore)&&this.setWorldPosition(I.x(),I.y(),I.z()));const o=i.rotation();o&&(this.tempEuler.set(o.x(),o.y(),o.z()),this.interpolateRotation&&this._targetRotation.setFromEuler(this.tempEuler),(!this.interpolateRotation||!this._receivedDataBefore)&&$J(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){zC&&console.log("no model or room",this.name,this.guid,this.context.connection.isInRoom);return}this._shouldRequestOwnership&&(this._shouldRequestOwnership=!1,this._model.requestOwnership());const e=this.worldPosition,t=this.worldQuaternion;if(this._model.isOwned&&!this.receivedUpdate){const o=e.distanceTo(this.lastWorldPos),s=t.angleTo(this.lastWorldRotation),n=this._model.hasOwnership||this.fastMode?1e-4:.001;(o>n||s>n)&&(this._model.hasOwnership?this._needsUpdate=!0:(zC&&console.log(this.guid,"reset because not owned but",this.gameObject.name,this.lastWorldPos),this.worldPosition=this.lastWorldPos,e.copy(this.lastWorldPos),this.worldQuaternion=this.lastWorldRotation,t.copy(this.lastWorldRotation),Ws.markDirty(this.gameObject,!0),this._needsUpdate=!1))}if(this._model&&!this._model.hasOwnership&&this._model.isOwned&&this._receivedDataBefore){const s=this._receivedFastUpdate||this.fastMode?.5:.3;let n=!1;if(this.interpolatePosition&&this._targetPosition){const r=this.worldPosition;r.lerp(this._targetPosition,s),this.worldPosition=r,n=!0}if(this.interpolateRotation&&this._targetRotation){const r=this.worldQuaternion;r.slerp(this._targetRotation,s),this.worldQuaternion=r,n=!0}n&&Ws.markDirty(this.gameObject,!0)}if(this.receivedUpdate=!1,this.lastWorldPos.copy(e),this.lastWorldRotation.copy(t),!this._model||!this._model||this._model.hasOwnership===void 0||!this._model.hasOwnership)return;this.rb&&this.overridePhysics&&this._wasKinematic!==void 0&&(zC&&console.log("reset kinematic",this.rb.name,this._wasKinematic),this.rb.isKinematic=this._wasKinematic);const i=10,I=this.rb||this.fastMode;if(this._needsUpdate&&(this.context.time.frameCount%i===0||I)){if(ZK++,I&&Lp>0&&this.context.time.frameCount%Lp!==0)return;zC&&console.log("send update",this.context.connection.connectionId,this.guid,this.gameObject.name,this.gameObject.guid),this._needsUpdate=!1;const o=rj(this.guid,this,!!I);this.context.connection.sendBinary(o)}}}const EEA=gA("debugshadowcomponents");PJ.prototype.interactable={get(){return this.interactive},set(g){this.interactable=g}};const Hs=Symbol("shadowDomOwner");class Xs extends FA{constructor(){super(...arguments);B(this,"_shadowComponent",null);B(this,"_controlsChildLayout",!0);B(this,"_root");B(this,"_parentComponent")}isRoot(){var e;return((e=this.Root)==null?void 0:e.gameObject)===this.gameObject}get canvas(){const e=this.Root;return e!=null&&e.isCanvas?e:null}get Canvas(){return this.canvas}markDirty(){Uo.markUIDirty(this.context)}get shadowComponent(){return this._shadowComponent}set shadowComponent(e){this._shadowComponent=e}get controlsChildLayout(){return this._controlsChildLayout}set controlsChildLayout(e){this._controlsChildLayout=e,this.shadowComponent&&(this.shadowComponent.autoLayout=e)}get Root(){return this._root===void 0&&(this._root=sA.getComponentInParent(this.gameObject,JD)),this._root}__internalNewInstanceCreated(e){return super.__internalNewInstanceCreated(e),this.shadowComponent=null,this._root=void 0,this._parentComponent=void 0,this}onEnable(){super.onEnable()}addShadowComponent(e,t){var o;if(!e)return;this.removeShadowComponent();const i=this.isRoot()?this.gameObject:this.gameObject.parent;if(this._parentComponent=sA.getComponentInParent(i,Xs),!this._parentComponent){console.warn(`Component "${this.name}" doesn't have a UI parent anywhere. Do you have an UI element outside a Canvas? UI components must be a child of a Canvas component`,this);return}e.name=this.name+" ("+(this.constructor.name??"UI")+")",e.autoLayout=this._parentComponent.controlsChildLayout,e[Hs]=this,this.setShadowComponentOwner(e);let I=!1;if(((o=this.Root)==null?void 0:o.gameObject)===this.gameObject)this.gameObject.add(e);else{const s=this._parentComponent.shadowComponent;s&&(s==null||s.add(e),I=!0)}this.shadowComponent=e,t&&t.shadowComponent&&this.shadowComponent&&t.shadowComponent.add(this.shadowComponent),SD&&e.add(new Qs(.5)),this.onAfterAddedToScene(),I&&s3(),EEA&&console.warn("Added shadow component",this.shadowComponent)}setShadowComponentOwner(e){if(e&&(e[Hs]===void 0||e[Hs]===this)&&(e[Hs]=this,e.children))for(const t of e.children)this.setShadowComponentOwner(t)}traverseOwnedShadowComponents(e,t,i){if(e&&e[Hs]===t){i(e);for(const I of e.children)this.traverseOwnedShadowComponents(I,t,i)}}removeShadowComponent(){this.shadowComponent&&this.shadowComponent.removeFromParent()}onAfterAddedToScene(){}setInteractable(e){this.shadowComponent&&(this.shadowComponent.interactable=e)}}class JD extends Xs{awake(){super.awake()}}class Ed{constructor(A,e){B(this,"event");B(this,"button");B(this,"buttonName");B(this,"_used",!1);B(this,"_propagationStopped",!1);B(this,"z__pointer_ctured",!1);B(this,"z__pointer_cture_rleased",!1);B(this,"inputSource");B(this,"object");B(this,"point");B(this,"normal");B(this,"face");B(this,"distance");B(this,"instanceId");B(this,"intersection");B(this,"isDown");B(this,"isUp");B(this,"isPressed");B(this,"isClick");B(this,"isDoubleClick");B(this,"input");this.event=e,this.input=A,this.button=e.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(),this.pointerId!==void 0&&this.input.setPointerUsed(this.pointerId))}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 A=new Ed(this.input,this.event);return Object.assign(A,this),A}Use(){this.use()}StopPropagation(){this.event.stopImmediatePropagation()}}function jK(g,A){return sA.foreachComponent(g,t=>{if(!t.enabled)return;const i=t;if(A)switch(A){case"pointerdown":if(i.onPointerDown)return!0;break;case"pointerup":if(i.onPointerUp||i.onPointerClick)return!0;break;case"pointermove":if(i.onPointerEnter||i.onPointerExit||i.onPointerMove)return!0;break}else if(i.onPointerDown||i.onPointerUp||i.onPointerEnter||i.onPointerExit||i.onPointerClick)return!0},!1)===!0}var lEA=Object.defineProperty,hEA=Object.getOwnPropertyDescriptor,dEA=(g,A,e,t)=>{for(var i=t>1?void 0:t?hEA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&lEA(A,e,i),i};class xD extends FA{awake(){Uo.createIfNoneExists(this.context)}onEnable(){var A;(A=Uo.get(this.context))==null||A.register(this)}onDisable(){var A;(A=Uo.get(this.context))==null||A.unregister(this)}}class cs extends xD{constructor(){super(...arguments);B(this,"targets",null);B(this,"raycastHits",[]);B(this,"ignoreSkinnedMeshes",!1)}start(){this.targets=[this.gameObject]}performRaycast(e=null){if(!this.targets)return null;e??(e=new Yn),e.targets=this.targets,e.results=this.raycastHits;const t=e.testObject;this.ignoreSkinnedMeshes&&(e.testObject=I=>I instanceof Fo?"continue in children":t?t(I):!0);const i=this.context.physics.raycast(e);return e.testObject=t,i}}dEA([D()],cs.prototype,"ignoreSkinnedMeshes",2);class hM extends cs{constructor(){super(),this.ignoreSkinnedMeshes=!0}}class Ff extends xD{performRaycast(A){if(!ye.active||!(A!=null&&A.ray))return null;const e=A.ray.origin,t=.015;return this.context.physics.sphereOverlap(e,t)}}class dM{static getObject(A){const e=A[Hs];return e&&(e.isComponent===!0?A=e.gameObject:A=e),A}static isInteractable(A,e){if(e&&(e.canvasGroup=void 0,e.graphic=void 0),A==null||!A.visible||(A=this.getObject(A),!A.visible))return!1;const t=this.tryFindCanvasGroup(A);if((t==null?void 0:t.isCanvasGroup)===!0&&(e&&(e.canvasGroup=t),t.blocksRaycasts===!1||t.interactable===!1))return!1;const i=Oc(A,I=>{if(I.isGraphic===!0)return I},!1);return e&&(i==null?void 0:i.isGraphic)===!0&&(e.graphic=i),!((i==null?void 0:i.raycastTarget)===!1||(i==null?void 0:i.layer)===2)}static tryFindCanvasGroup(A){if(!A)return null;const e=Oc(A,t=>{const i=t;if(i.blocksRaycasts!==void 0&&i.interactable!==void 0)return i},!1);return e!==void 0?e:this.tryFindCanvasGroup(A.parent)}}function ov(g){const A=g[Hs];return A||(g.parent?ov(g.parent):null)}function uEA(g){return g.isUI===!0||typeof g[Hs]=="object"}function ym(g,A){if(!g)return;const e=g.material;if((e==null?void 0:e.isMaterial)===!0){const t=g.parent;t&&t.isText,e.side=A.doubleSided??!0?kt:Gg,e.shadowSide=A.doubleSided?kt:Gg,g.castShadow=A.castShadows?A.castShadows:!1,g.receiveShadow=A.receiveShadows?A.receiveShadows:!1}for(const t of g.children)ym(t,A)}function vl(g,A,e){g[A]===void 0&&console.warn("Field",A,"is undefined on",g);const t=Proxy.revocable(g[A],{set(o,s,n,r){const a=o[s],C=Reflect.set(o,s,n,r);return e(n,a),C}}),i=t.revoke,I=g[A];return t.revoke=()=>{g[A]=I,i()},g[A]=t.proxy,t}const p2=Symbol("Scheduled action");function pEA(g,A,e=oi.OnBeforeRender){let t=g[p2];t||(t=g[p2]={});const i=A.name;t[e]||(t[e]={});const I=t[e];if(I[i])return;function*s(){A==null||A.call(g),I[i]=null}const n=g.startCoroutine(s(),e);I[i]=n}const fa=gA("debugeventsystem");var zK=(g=>(g.BeforeHandleInput="BeforeHandleInput",g.AfterHandleInput="AfterHandleInput",g))(zK||{});const Br=class extends FA{constructor(){super();B(this,"raycaster",[]);B(this,"_handleInputFn");B(this,"pressedByID",new Map);B(this,"hoveredByID",new Map);B(this,"_sortedHits",[]);B(this,"_testObjectsCache",new Map);B(this,"_currentlyActiveRaycaster",null);B(this,"_currentPointerEventName",null);B(this,"shouldRaycastObject",e=>{var I;let t=null;if(uEA(e)&&(t=(I=e[Hs])==null?void 0:I.gameObject),this._testObjectsCache.has(e)||t&&this._testObjectsCache.has(t))return this._testObjectsCache.get(e)===!1?"continue in children":!0;{let o=jK(e,this._currentPointerEventName);if(!o&&t&&(o=jK(t,this._currentPointerEventName)),o){this._testObjectsCache.set(e,!0);for(const s of e.children)this.shouldRaycastObject_AddToYesCache(s);return!0}return this._testObjectsCache.set(e,!1),"continue in children"}});B(this,"_sortingBuffer",[]);B(this,"_noDepthTestingResults",[]);B(this,"out",{});B(this,"_capturedPointer",{});B(this,"pointerEnterSymbol",Symbol("pointerEnter"));B(this,"pointerExitSymbol",Symbol("pointerExit"));B(this,"currentActiveMeshUIComponents",[]);Br.systems.push(this)}static createIfNoneExists(e){this.didSearchEventSystem||(this.didSearchEventSystem=!0,Br.systems.length<=0&&Br.systems.push(...sA.findObjectsOfType(Br,e)));for(const i of Br.systems)if(i.context===e)return;const t=new DA;sA.addNewComponent(t,Br),e.scene.add(t)}static get systems(){const e=be.Current;return this._eventSystemMap.has(e)||this._eventSystemMap.set(e,[]),this._eventSystemMap.get(e)}static get(e){const t=this._eventSystemMap.get(e);return t&&t.length>0?t[0]:null}static get instance(){return this.systems[0]}static ensureUpdateMeshUI(e,t,i=!1){oB.update(e,t,i)}static markUIDirty(e){oB.markDirty()}get hasActiveUI(){return this.currentActiveMeshUIComponents.length>0}get isHoveringObjects(){return this.hoveredByID.size>0}onDestroy(){Br.systems.splice(Br.systems.indexOf(this),1)}start(){if(this.raycaster.length<=0&&!sA.findObjectOfType(xD,this.context)){const t=sA.addNewComponent(this.context.scene,cs);this.raycaster.push(t),(ae()||fa)&&console.warn("Added an ObjectRaycaster to the scene because no raycaster was found.")}}register(e){var t;e&&this.raycaster&&!this.raycaster.includes(e)&&((t=this.raycaster)==null||t.push(e))}unregister(e){var i,I;const t=(i=this.raycaster)==null?void 0:i.indexOf(e);t!==void 0&&t!==-1&&((I=this.raycaster)==null||I.splice(t,1))}onEnable(){this._handleInputFn??(this._handleInputFn=this.onPointerEvent.bind(this)),this.context.input.addEventListener(pi.PointerDown,this._handleInputFn),this.context.input.addEventListener(pi.PointerUp,this._handleInputFn),this.context.input.addEventListener(pi.PointerMove,this._handleInputFn)}onDisable(){this.context.input.removeEventListener(pi.PointerDown,this._handleInputFn),this.context.input.removeEventListener(pi.PointerUp,this._handleInputFn),this.context.input.removeEventListener(pi.PointerMove,this._handleInputFn)}onBeforeRender(){this.resetMeshUIStates()}onPointerEvent(e){if(e===void 0||e.propagationStopped)return;const t=new Ed(this.context.input,e);this._currentPointerEventName=e.type,t.inputSource=this.context.input,t.isClick=e.isClick,t.isDoubleClick=e.isDoubleClick,t.isDown=e.type==pi.PointerDown,t.isUp=e.type==pi.PointerUp,t.isPressed=this.context.input.getPointerPressed(e.pointerId),fa&&(t.isDown?console.log("DOWN",t.pointerId):t.isUp&&console.log("UP",t.pointerId),t.isClick&&console.log("CLICK",t.pointerId));const i=new Yn;e.hasRay?i.ray=e.ray:i.screenPoint=this.context.input.getPointerPositionRC(e.pointerId);const I=this.performRaycast(i);if(I){for(const s of I)s.event=e,e.intersections.push(s);e.origin.onPointerHits&&e.origin.onPointerHits({sender:this,event:e,hits:I})}fa&&t.isClick&&fi("EventSystem: "+t.pointerId+" - "+this.context.time.frame+" - Up:"+t.isUp+", Down:"+t.isDown);const o={sender:this,args:t,hasActiveUI:this.currentActiveMeshUIComponents.length>0};this.dispatchEvent(new CustomEvent("BeforeHandleInput",{detail:o})),this.handleIntersections(I,t),this.dispatchEvent(new CustomEvent("AfterHandleInput",{detail:o}))}shouldRaycastObject_AddToYesCache(e){this._testObjectsCache.set(e,!0);for(const t of e.children)this.shouldRaycastObject_AddToYesCache(t)}performRaycast(e){if(!this.raycaster)return null;this._testObjectsCache.clear(),this._sortedHits.length=0,e||(e=new Yn),e.testObject=this.shouldRaycastObject;for(const t of this.raycaster){if(!t.activeAndEnabled)continue;this._currentlyActiveRaycaster=t;const i=t.performRaycast(e);this._currentlyActiveRaycaster=null,i&&i.length>0&&this._sortedHits.push(...i)}return this._sortedHits.sort((t,i)=>t.distance-i.distance),this._sortedHits}assignHitInformation(e,t){t?(e.intersection=t,e.point=t.point,e.normal=t.normal,e.face=t.face,e.distance=t.distance,e.instanceId=t.instanceId):(e.intersection=void 0,e.point=void 0,e.normal=void 0,e.face=void 0,e.distance=void 0,e.instanceId=void 0)}handleIntersections(e,t){var I;if(e!=null&&e.length){e=this.sortCandidates(e);for(const o of e){if(t.event.immediatePropagationStopped)return!1;if(this.assignHitInformation(t,o),this.handleEventOnObject(o.object,t))return!0}}this.assignHitInformation(t,e==null?void 0:e[0]),this.invokePointerCapture(t);const i=this.hoveredByID.get(t.pointerId);return i&&this.propagatePointerExit(i.obj,i.data,null),this.hoveredByID.delete(t.pointerId),t.isUp&&((I=this.pressedByID.get(t.pointerId))==null||I.handlers.forEach(o=>this.invokeOnPointerUp(t,o)),this.pressedByID.delete(t.pointerId)),!1}sortCandidates(e){this._sortingBuffer.length=0,this._noDepthTestingResults.length=0;for(let t=0;t<e.length;t++){const i=e[t],I=i.object;if(I.material&&I.material.depthTest===!1){this._noDepthTestingResults.push(i);continue}this._sortingBuffer.push(i)}for(const t of this._sortingBuffer)this._noDepthTestingResults.push(t);return this._noDepthTestingResults}handleEventOnObject(e,t){if(!this.testIsVisible(e))return t.isClick&&fa&&console.log("not allowed",e),!1;if(t.pointerId===void 0)return fa&&console.error("Event without pointer can't be handled",t),!1;t.object=e;const i=e.parent,I=t.isClick??!1;let o=null;if(i&&i.isUI){const C=(t.isPressed||t.isClick)??!1;if(i[Hs]){const Q=i[Hs].gameObject;if(Q){if(!dM.isInteractable(Q,this.out))return!1;o=this.out.canvasGroup??null,this.handleMeshUIIntersection(e,C),e=Q}}}I&&fa&&console.log(this.context.time.frame,e);const s=this.hoveredByID.get(t.pointerId),n=s==null?void 0:s.obj;n!==e&&n&&this.propagatePointerExit(n,s.data,e);const a=this.hoveredByID.get(t.pointerId);if(a?(a.obj=e,a.data=t):this.hoveredByID.set(t.pointerId,{obj:e,data:t}),t.isDown){const C=this.pressedByID.get(t.pointerId);C?(C.obj=e,C.data=t):this.pressedByID.set(t.pointerId,{obj:e,data:t,handlers:new Set})}return(o===null||o.interactable)&&this.handleMainInteraction(e,t,n??null),!0}propagate(e,t){for(;e;)sA.foreachComponent(e,i=>{t(i)},!1),e=e.parent}handleMainInteraction(e,t,i){const I=this.pressedByID.get(t.pointerId),o=i!==e;let s=!0;switch(t.event.pointerType){case"mouse":case"touch":const n=this.context.input.getPointerPositionLastFrame(t.pointerId),r=this.context.input.getPointerPosition(t.pointerId);s=n&&!ge.approximately(n,r);break}this.propagate(e,n=>{var a;const r=n;r.interactable!==!1&&(!r.activeAndEnabled||!r.enabled||(r.onPointerEnter&&o&&this.handlePointerEnter(r,t),t.isDown&&r.onPointerDown&&(r.onPointerDown(t),I==null||I.handlers.add(r),this.handlePointerCapture(t,r)),r.onPointerMove&&(s&&r.onPointerMove(t),this.handlePointerCapture(t,r)),t.isUp&&(r.onPointerUp&&(this.invokeOnPointerUp(t,r),I==null||I.handlers.delete(r)),r.onPointerExit&&((a=t.event)==null?void 0:a.pointerType)===gM.Touch&&(this.handlePointerExit(r,t),this.hoveredByID.delete(t.pointerId))),t.isClick&&r.onPointerClick&&r.onPointerClick(t)))}),t.isUp&&(I==null||I.handlers.forEach(n=>{this.invokeOnPointerUp(t,n)}),this.pressedByID.delete(t.pointerId))}propagatePointerExit(e,t,i){this.propagate(e,I=>{if(!I.gameObject||I.destroyed)return;const o=I;if(o.onPointerExit){if(i&&this.isChild(i,I.gameObject))return;this.handlePointerExit(o,t)}})}invokeOnPointerUp(e,t){var i;(i=t.onPointerUp)==null||i.call(t,e),this.releasePointerCapture(e,t)}handlePointerEnter(e,t){e.onPointerEnter&&this.updatePointerState(e,t.pointerId,this.pointerEnterSymbol,!0)&&e.onPointerEnter(t),this.updatePointerState(e,t.pointerId,this.pointerExitSymbol,!1)}handlePointerExit(e,t){e.onPointerExit&&this.updatePointerState(e,t.pointerId,this.pointerExitSymbol,!0)&&e.onPointerExit(t),this.updatePointerState(e,t.pointerId,this.pointerEnterSymbol,!1)}updatePointerState(e,t,i,I){let o=e[i];if(I)return o&&o.includes(t)?!1:(o=o||[],o.push(t),e[i]=o,!0);{if(!o||!o.includes(t))return!1;const s=o.indexOf(t);return s!==-1&&o.splice(s,1),!0}}handlePointerCapture(e,t){if(e.z__pointer_ctured){e.z__pointer_ctured=!1;const i=e.pointerId;if(t.onPointerMove){const I=this._capturedPointer[i]||[];I.push(t),this._capturedPointer[i]=I}else ae()&&!t.z__warned_no_pointermove&&(t.z__warned_no_pointermove=!0,console.warn("PointerCapture was requested but the component doesn't implement onPointerMove. It will not receive any pointer events"))}else e.z__pointer_cture_rleased&&(e.z__pointer_cture_rleased=!1,this.releasePointerCapture(e,t))}releasePointerCapture(e,t){const i=e.pointerId;if(this._capturedPointer[i]){const I=this._capturedPointer[i].indexOf(t);I!==-1&&(this._capturedPointer[i].splice(I,1),fa&&console.log("released pointer capture",i,t,this._capturedPointer))}}invokePointerCapture(e){var t;if(e.event.type===pi.PointerMove){const i=e.pointerId,I=this._capturedPointer[i];if(I){fa&&console.log("Captured",i,I);for(let o=0;o<I.length;o++){const s=I[o];if(s.destroyed){I.splice(o,1),o--;continue}(t=s.onPointerMove)==null||t.call(s,e)}}}}isChild(e,t){return!e||!t?!1:e===t?!0:e.parent?this.isChild(e.parent,t):!1}handleMeshUiObjectWithoutShadowDom(e,t){return!e||!e.isUI?!0:this.handleMeshUIIntersection(e,t)}handleMeshUIIntersection(e,t){const i=oB.updateState(e,t);return i&&this.currentActiveMeshUIComponents.push(i),i!==null}resetMeshUIStates(){if(this.context.input.getPointerPressedCount()>0&&oB.resetLastSelected(),!(!this.currentActiveMeshUIComponents||this.currentActiveMeshUIComponents.length<=0)){for(let e=0;e<this.currentActiveMeshUIComponents.length;e++){const t=this.currentActiveMeshUIComponents[e];oB.resetState(t)}this.currentActiveMeshUIComponents.length=0}}testIsVisible(e){return e?sA.isActiveSelf(e)?this.testIsVisible(e.parent):!1:!0}};let Uo=Br;B(Uo,"_eventSystemMap",new Map),B(Uo,"didSearchEventSystem",!1);class oB{static markDirty(){this.needsUpdate=!0}static update(A,e,t=!1){if(t){A.update();return}const i=e.time.frameCount;for(const I of this.lastUpdateFrame)if(I.context===e){if(i===I.frame)return;I.frame=i;let o=this.needsUpdate||i<1;I.nextUpdate===e.time.frameCount&&(o=!0),o&&(fa&&console.log("Update threemeshui"),this.needsUpdate=!1,A.update());return}this.lastUpdateFrame=[{context:e,frame:i,nextUpdate:i}],A.update()}static updateState(A,e){let t=null;if(A&&(t=this.findBlockInParent(A),t&&t!==this.lastSelected)){if(t.interactable===!1)return null;this.needsUpdate=!0}return t}static resetLastSelected(){const A=this.lastSelected;A&&(this.lastSelected=null,this.resetState(A))}static resetState(A){A&&(this.needsUpdate=!0)}static findBlockInParent(A){return A?A.isBlock?A:this.findBlockInParent(A.parent):null}}B(oB,"lastSelected",null),B(oB,"lastUpdateFrame",[]),B(oB,"needsUpdate",!1);var fEA=Object.defineProperty,DEA=Object.getOwnPropertyDescriptor,wi=(g,A,e,t)=>{for(var i=t>1?void 0:t?DEA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&fEA(A,e,i),i};const PU=gA("debugorbit"),ES=gA("freecam"),lS=gA("debugcamerafit"),hS=gA("smoothcam"),yEA={LEFT:"",UP:"",RIGHT:"",BOTTOM:""};let WU;class Kf extends CustomEvent{constructor(A,e){super("target-reached",{detail:{controls:A,type:e}})}}class Mt extends FA{constructor(){super(...arguments);B(this,"autoTarget",!0);B(this,"autoFit",!1);B(this,"enableRotate",!0);B(this,"autoRotate",!1);B(this,"autoRotateSpeed",1);B(this,"minAzimuthAngle",1/0);B(this,"maxAzimuthAngle",1/0);B(this,"minPolarAngle",0);B(this,"maxPolarAngle",Math.PI);B(this,"enableKeys",!0);B(this,"enableDamping",!0);B(this,"dampingFactor",.1);B(this,"enableZoom",!0);B(this,"minZoom",0);B(this,"maxZoom",1/0);B(this,"zoomSpeed",1);B(this,"zoomToCursor",!1);B(this,"enablePan",!0);B(this,"lookAtConstraint",null);B(this,"lookAtConstraint01",1);B(this,"allowInterrupt",!0);B(this,"middleClickToFocus",!0);B(this,"doubleClickToFocus",!0);B(this,"clickBackgroundToFitScene",2);B(this,"debugLog",!1);B(this,"targetLerpDuration",1);B(this,"_controls",null);B(this,"_cameraObject",null);B(this,"_lookTargetLerpActive",!1);B(this,"_lookTargetStartPosition",new y);B(this,"_lookTargetEndPosition",new y);B(this,"_lookTargetLerp01",0);B(this,"_lookTargetLerpDuration",0);B(this,"_cameraLerpActive",!1);B(this,"_cameraStartPosition",new y);B(this,"_cameraEndPosition",new y);B(this,"_cameraLerp01",0);B(this,"_cameraLerpDuration",0);B(this,"_inputs",0);B(this,"_enableTime",0);B(this,"_startedListeningToKeyEvents",!1);B(this,"_eventSystem");B(this,"_afterHandleInputFn");B(this,"_camera",null);B(this,"_syncedTransform");B(this,"_didSetTarget",0);B(this,"targetElement",null);B(this,"_lastTimeClickOnBackground",-1);B(this,"_clickOnBackgroundCount",0);B(this,"_onPointerDown",e=>{if(this.clickBackgroundToFitScene>0&&e.isClick&&e.button===0){if(e.hasRay||e.intersections.push(...this.context.physics.raycast()),e.intersections.length<=0){const t=this.context.time.time-this._lastTimeClickOnBackground;this._lastTimeClickOnBackground=this.context.time.time,this.clickBackgroundToFitScene<=1||t<this.clickBackgroundToFitScene*.15?(this._clickOnBackgroundCount+=1,this._clickOnBackgroundCount>=this.clickBackgroundToFitScene-1&&this.fitCamera(this.context.scene.children,{immediate:!1})):this._clickOnBackgroundCount=0}PU&&console.log(this.clickBackgroundToFitScene,e.intersections.length,this._clickOnBackgroundCount)}});B(this,"onControlsChangeStarted",()=>{this._syncedTransform&&this._syncedTransform.requestOwnership()});B(this,"_shouldDisable",!1);B(this,"__onPreRender",()=>{const e=this.context.pre_render_callbacks.indexOf(this.__onPreRender);e>=0&&this.context.pre_render_callbacks.splice(e,1),this.autoFit&&(this.autoFit=!1,this.fitCamera(this.scene.children,{centerCamera:"y",immediate:!0}))});B(this,"_haveAttachedKeyboardEvents",!1)}get isCameraController(){return!0}get controls(){return this._controls}get controllerObject(){return this._cameraObject}onStartInteraction(e){var t;(t=this.controls)==null||t.addEventListener("start",e)}get targetLerpSpeed(){return 5}set targetLerpSpeed(e){this.targetLerpDuration=1/e}awake(){this._didSetTarget=0,this._startedListeningToKeyEvents=!1}start(){this._eventSystem=Uo.get(this.context)??void 0,this._eventSystem&&(this._afterHandleInputFn=this.afterHandleInput.bind(this),this._eventSystem.addEventListener(zK.AfterHandleInput,this._afterHandleInputFn))}onDestroy(){var e,t;(e=this._controls)==null||e.dispose(),(t=this._eventSystem)==null||t.removeEventListener(zK.AfterHandleInput,this._afterHandleInputFn)}onEnable(){this._didSetTarget=0,this._enableTime=this.context.time.time;const e=sA.getComponent(this.gameObject,Wt);this._camera=e;let t=e==null?void 0:e.cam;if(!t&&this.gameObject instanceof He&&(t=this.gameObject),t&&TF(t,this,!0),!this._controls&&t instanceof He){this._cameraObject=t;const i=this.targetElement??this.context.renderer.domElement,I=t==null?void 0:t.quaternion.clone();this._controls=new Ij(t,i),t==null||t.quaternion.copy(I),WU===void 0&&(WU={...this._controls.keys})}this._controls&&(ES&&(this.enablePan=!0,this.enableZoom=!0,this.middleClickToFocus=!0,In()&&(this.doubleClickToFocus=!0)),this._controls.addEventListener("start",this.onControlsChangeStarted),(t==null?void 0:t.type)==="PerspectiveCamera"?ES||(this._controls.minDistance=this.minZoom,this._controls.maxDistance=this.maxZoom):ES||(this._controls.minZoom=this.minZoom,this._controls.maxZoom=this.maxZoom),this._startedListeningToKeyEvents||(this._startedListeningToKeyEvents=!0,this._controls.listenToKeyEvents(window.document.body))),this._syncedTransform=sA.getComponent(this.gameObject,bB)??void 0,this.context.input.addEventListener("pointerup",this._onPointerDown),this.context.pre_render_callbacks.push(this.__onPreRender)}onDisable(){var e;(e=this._camera)!=null&&e.cam&&TF(this._camera.cam,this,!1),this._controls&&(this._controls.enabled=!1,this._controls.autoRotate=!1,this._controls.removeEventListener("start",this.onControlsChangeStarted)),this.context.input.removeEventListener("pointerup",this._onPointerDown)}afterHandleInput(e){e.detail.args.pointerId===0&&(e.detail.args.isDown?this._controls&&this._eventSystem&&(this._shouldDisable=this._eventSystem.hasActiveUI):(!e.detail.args.isPressed||e.detail.args.isUp)&&(this._shouldDisable=!1))}onBeforeRender(){var t,i;if(!this._controls)return;if(this._cameraObject!==this.context.mainCamera){this._controls.enabled=!1;return}if(this._controls.enabled=!0,(this.context.input.getPointerDown(1)||this.context.input.getPointerDown(2)||this.context.input.mouseWheelChanged||this.context.input.getPointerPressed(0)&&((t=this.context.input.getPointerPositionDelta(0))!=null&&t.length())||0>.1)&&(this._inputs+=1),this._inputs>0&&this.allowInterrupt&&(this.enableRotate&&(this.autoRotate=!1),this._cameraLerpActive=!1,this._lookTargetLerpActive=!1),this._inputs=0,this.autoTarget&&this._didSetTarget++===0){const I=sA.getComponent(this.gameObject,Wt);if(I&&!this.setLookTargetFromConstraint()){this.debugLog&&console.log("NO TARGET");const o=ve(I.cam),s=Math.max(.01,o.length()),n=new y(0,0,-s).applyMatrix4(I.cam.matrixWorld);this.setLookTargetPosition(n,!0)}if(!this.setLookTargetFromConstraint()){const o=new Yn;o.screenPoint=new tA(0,0),o.lineThreshold=.1;const s=this.context.physics.raycast(o);s.length>0&&this.setLookTargetPosition(s[0].point,!0),lS&&console.log("OrbitControls hits",...s)}}let e=this.middleClickToFocus&&this.context.input.getPointerClicked(1);if(e||(e=this.doubleClickToFocus&&this.context.input.getPointerDoubleClicked(0)&&this.context.time.time-this._enableTime>.3),e&&this.setTargetFromRaycast(),this._lookTargetLerpActive||this._cameraLerpActive){if(this._cameraLerpActive&&this._cameraObject)if(this._cameraLerp01+=this.context.time.deltaTime/this._cameraLerpDuration,this._cameraLerp01>=1)this._cameraObject.position.copy(this._cameraEndPosition),this._cameraLerpActive=!1,this.dispatchEvent(new Kf(this,"camera"));else{const I=ge.easeInOutCubic(this._cameraLerp01);this._cameraObject.position.lerpVectors(this._cameraStartPosition,this._cameraEndPosition,I)}if(this._lookTargetLerpActive)if(this._lookTargetLerp01+=this.context.time.deltaTime/this._lookTargetLerpDuration,this._lookTargetLerp01>=1)this._controls.target.copy(this._lookTargetEndPosition),this._lookTargetLerpActive=!1,this.dispatchEvent(new Kf(this,"lookat"));else{const I=ge.easeInOutCubic(this._lookTargetLerp01);this._controls.target.lerpVectors(this._lookTargetStartPosition,this._lookTargetEndPosition,I)}}if(this._controls){if(this.debugLog&&(this._controls.domElement=this.context.renderer.domElement),this._controls.enabled=!this._shouldDisable&&this._camera===this.context.mainCameraComponent&&!this.context.isInXR,this._controls.keys=this.enableKeys?WU:yEA,this._controls.autoRotate=this.autoRotate,this._controls.autoRotateSpeed=this.autoRotateSpeed,this._controls.enableZoom=this.enableZoom,this._controls.zoomSpeed=this.zoomSpeed,this._controls.zoomToCursor=this.zoomToCursor,this._controls.enableDamping=this.enableDamping,this._controls.dampingFactor=this.dampingFactor,this._controls.enablePan=this.enablePan,this._controls.enableRotate=this.enableRotate,this._controls.minAzimuthAngle=this.minAzimuthAngle,this._controls.maxAzimuthAngle=this.maxAzimuthAngle,this._controls.minPolarAngle=this.minPolarAngle,this._controls.maxPolarAngle=this.maxPolarAngle,typeof hS=="number"||hS===!0){this._controls.enableDamping=!0;const I=typeof hS=="number"?hS:.99;this._controls.dampingFactor=Math.max(.001,1-Math.min(1,I))}this.allowInterrupt||(this._lookTargetLerpActive&&(this._controls.enablePan=!1),this._cameraLerpActive&&(this._controls.enableRotate=!1,this._controls.autoRotate=!1),(this._lookTargetLerpActive||this._cameraLerpActive)&&(this._controls.enableZoom=!1)),this.context.isInXR||(!ES&&((i=this.lookAtConstraint)!=null&&i.locked)&&this.setLookTargetFromConstraint(0,this.lookAtConstraint01),this._controls.update(),PU&&fe.DrawWireSphere(this._controls.target,.1,65280))}}setCameraAndLookTarget(e){if(!e||!(e instanceof DA))return;const t=ve(e),i=VJ(e);this.setTargetFromRaycast(new xo(t,i)),this.setCameraTargetPosition(t)}setCameraTargetPosition(e,t=!1){var i,I;e&&(e instanceof DA&&(e=ve(e)),this._cameraEndPosition||(this._cameraEndPosition=new y),this._cameraEndPosition.copy(e),t===!0?(this._cameraLerpActive=!1,(i=this.controllerObject)==null||i.position.copy(this._cameraEndPosition)):this._cameraObject&&(this._cameraLerpActive=!0,this._cameraLerp01=0,this._cameraStartPosition.copy((I=this._cameraObject)==null?void 0:I.position),typeof t=="number"?this._cameraLerpDuration=t:this._cameraLerpDuration=this.targetLerpDuration))}get cameraLerpActive(){return this._cameraLerpActive}stopCameraLerp(){this._cameraLerpActive=!1}setLookTargetPosition(e=null,t=!1){this._controls&&e&&(e instanceof DA&&(e=ve(e)),this._lookTargetEndPosition.copy(e),PU&&(console.warn("OrbitControls: setLookTargetPosition",e,t),fe.DrawWireSphere(this._lookTargetEndPosition,.2,16711680,2)),t===!0?this._controls.target.copy(this._lookTargetEndPosition):(this._lookTargetLerpActive=!0,this._lookTargetLerp01=0,this._lookTargetStartPosition.copy(this._controls.target),typeof t=="number"?this._lookTargetLerpDuration=t:this._lookTargetLerpDuration=this.targetLerpDuration))}get lookTargetLerpActive(){return this._lookTargetLerpActive}stopLookTargetLerp(){this._lookTargetLerpActive=!1}setLookTargetFromConstraint(e=0,t=1){var I;if(!this._controls)return!1;const i=(I=this.lookAtConstraint)==null?void 0:I.sources;if(i&&i.length>0){const o=i[e];if(o)return o.getWorldPosition(this._lookTargetEndPosition),this.lerpLookTarget(this._lookTargetEndPosition,t),!0}return!1}lerpTarget(e,t){return this.lerpLookTarget(e,t)}lerpLookTarget(e,t){this._controls&&(t>=1?this._controls.target.copy(e):this._controls.target.lerp(e,t))}setTargetFromRaycast(e){if(!this.controls)return;const t=e?this.context.physics.raycastFromRay(e):this.context.physics.raycast();for(const i of t)if(i.distance>0&&sA.isActiveInHierarchy(i.object)){const I=ov(i.object);if(I){const o=I.canvas;if(o!=null&&o.screenspace)break}this.setLookTargetPosition(i.point);break}}fitCamera(e,t={fitOffset:void 0,immediate:!1}){if(this.context.isInXR)return;const{immediate:i=!1,centerCamera:I}=t;let{fitOffset:o}=t;o==null&&(o=1.1);const s=this._cameraObject,n=this._controls;if(e!=null&&e.length||(e=this.context.scene.children),e.length<=0){console.warn("No objects to fit camera to...");return}if(!s||!n){console.warn("No camera or controls found to fit camera to objects...");return}const r=new y,a=new y,C=qr(e,void 0);s.updateMatrixWorld(),s.updateProjectionMatrix(),C.getCenter(a);const Q=new y;if(C.getSize(Q),C.applyMatrix4(s.matrixWorldInverse),C.getSize(r),C.setFromCenterAndSize(a,r),Number.isNaN(r.x)||Number.isNaN(r.y)||Number.isNaN(r.z)){console.warn("Camera fit size resultet in NaN",s,C,[...e]);return}if(r.length()<=1e-10){lS&&console.warn("Camera fit size is zero",C,[...e]);return}const c=s.fov,E=2*Math.atan(Math.tan(c*Math.PI/360/2)*s.aspect)/Math.PI*360,h=r.y/(2*Math.atan(Math.PI*c/360)),l=r.x/(2*Math.atan(Math.PI*E/360)),d=o*Math.max(h,l)+r.z/2;lS&&console.log("Fit camera to objects",h,l,"distance",d),n.maxDistance=d*10,n.minDistance=d*.01;const p=.05,u=a.clone();u.y-=r.y*p,this.setLookTargetPosition(u,i),this.autoTarget=!1;const f=sA.findObjectOfType(VB),w=f?f.radius:0,m=Math.max(Q.x,Q.y,Q.z,w);s.near=d/100,s.far=m+d*10,s.updateMatrixWorld(),s.updateProjectionMatrix();const M=ve(s),G=a.clone();if(G.sub(M),I==="y"&&(G.y=0),G.normalize(),G.multiplyScalar(d),I==="y"&&(G.y+=-p*4*r.y),s.parent){const U=s.parent.worldToLocal(a.clone().sub(G));this.setCameraTargetPosition(U,i)}else console.error(`Can not fit camera ${s.name} because it has no parent`);if(lS){const U=new dJ(C);this.context.scene.add(U),Ax(U,dD(s)),setTimeout(()=>{this.context.scene.remove(U)},1e4),this._haveAttachedKeyboardEvents||(this._haveAttachedKeyboardEvents=!0,document.body.addEventListener("keydown",S=>{S.code==="KeyF"&&this.fitCamera(e,{fitOffset:o,immediate:i})}))}n.update()}}wi([D()],Mt.prototype,"autoTarget",2);wi([D()],Mt.prototype,"autoFit",2);wi([D()],Mt.prototype,"enableRotate",2);wi([D()],Mt.prototype,"autoRotate",2);wi([D()],Mt.prototype,"autoRotateSpeed",2);wi([D()],Mt.prototype,"minAzimuthAngle",2);wi([D()],Mt.prototype,"maxAzimuthAngle",2);wi([D()],Mt.prototype,"minPolarAngle",2);wi([D()],Mt.prototype,"maxPolarAngle",2);wi([D()],Mt.prototype,"enableKeys",2);wi([D()],Mt.prototype,"enableDamping",2);wi([D()],Mt.prototype,"dampingFactor",2);wi([D()],Mt.prototype,"enableZoom",2);wi([D()],Mt.prototype,"minZoom",2);wi([D()],Mt.prototype,"maxZoom",2);wi([D()],Mt.prototype,"zoomSpeed",2);wi([D()],Mt.prototype,"enablePan",2);wi([D(sE)],Mt.prototype,"lookAtConstraint",2);wi([D()],Mt.prototype,"lookAtConstraint01",2);wi([D()],Mt.prototype,"allowInterrupt",2);wi([D()],Mt.prototype,"middleClickToFocus",2);wi([D()],Mt.prototype,"doubleClickToFocus",2);wi([D()],Mt.prototype,"clickBackgroundToFitScene",2);wi([D()],Mt.prototype,"targetLerpDuration",2);var wEA=Object.defineProperty,SEA=Object.getOwnPropertyDescriptor,uo=(g,A,e,t)=>{for(var i=t>1?void 0:t?SEA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&wEA(A,e,i),i},kB=(g=>(g[g.Skybox=1]="Skybox",g[g.SolidColor=2]="SolidColor",g[g.Uninitialized=4]="Uninitialized",g))(kB||{});const Ma=gA("debugcam"),f2=gA("debugscreenpointtoray");var qS;const op=(qS=class extends FA{constructor(){super(...arguments);B(this,"_nearClipPlane",.1);B(this,"_farClipPlane",1e3);B(this,"orthographic",!1);B(this,"orthographicSize",5);B(this,"ARBackgroundAlpha",0);B(this,"_cullingMask",4294967295);B(this,"_backgroundBlurriness",0);B(this,"_backgroundIntensity",1);B(this,"_backgroundRotation");B(this,"_environmentIntensity");B(this,"_targetTexture",null);B(this,"_backgroundColor");B(this,"_fov");B(this,"_cam",null);B(this,"_clearFlags",2);B(this,"_skybox");B(this,"_frustum");B(this,"_projScreenMatrix",new fA)}get isCamera(){return!0}get aspect(){return this._cam instanceof He?this._cam.aspect:this.context.domWidth/this.context.domHeight}set aspect(A){this._cam instanceof He&&this._cam.aspect!==A&&(this._cam.aspect=A,this._cam.updateProjectionMatrix())}get fieldOfView(){return this._cam instanceof He?this._cam.fov:this._fov}set fieldOfView(A){const e=this.fieldOfView!=A;if(this._fov=A,e&&this._cam&&this._cam instanceof He){if(this._fov===void 0){console.warn("Can not set undefined fov on PerspectiveCamera");return}this._cam.fov=this._fov,this._cam.updateProjectionMatrix()}}get nearClipPlane(){return this._nearClipPlane}set nearClipPlane(A){const e=this._nearClipPlane!=A;this._nearClipPlane=A,this._cam&&e&&(this._cam.near=A,this._cam.updateProjectionMatrix())}get farClipPlane(){return this._farClipPlane}set farClipPlane(A){const e=this._farClipPlane!=A;this._farClipPlane=A,this._cam&&e&&(this._cam.far=A,this._cam.updateProjectionMatrix())}get clearFlags(){return this._clearFlags}set clearFlags(A){A!==this._clearFlags&&(this._clearFlags=A,this.applyClearFlagsIfIsActiveCamera())}set cullingMask(A){this._cullingMask=A,this._cam&&(this._cam.layers.mask=A)}get cullingMask(){return this._cam?this._cam.layers.mask:this._cullingMask}set cullingLayer(A){this.cullingMask=(1<<A|0)>>>0}set backgroundBlurriness(A){A!==this._backgroundBlurriness&&(A===void 0?this._backgroundBlurriness=void 0:this._backgroundBlurriness=Math.min(Math.max(A,0),1),this.applyClearFlagsIfIsActiveCamera())}get backgroundBlurriness(){return this._backgroundBlurriness}set backgroundIntensity(A){A!==this._backgroundIntensity&&(A===void 0?this._backgroundIntensity=void 0:this._backgroundIntensity=Math.min(Math.max(A,0),10),this.applyClearFlagsIfIsActiveCamera())}get backgroundIntensity(){return this._backgroundIntensity}set backgroundRotation(A){A!==this._backgroundRotation&&(A===void 0?this._backgroundRotation=void 0:this._backgroundRotation=A,this.applyClearFlagsIfIsActiveCamera())}get backgroundRotation(){return this._backgroundRotation}set environmentIntensity(A){this._environmentIntensity=A}get environmentIntensity(){return this._environmentIntensity}get backgroundColor(){return this._backgroundColor??null}set backgroundColor(A){if(A){if(this._backgroundColor)this._backgroundColor.copy(A);else{if(!A.clone)return;this._backgroundColor=A.clone()}A.alpha===void 0&&(this._backgroundColor.alpha=1),this.applyClearFlagsIfIsActiveCamera()}}set targetTexture(A){this._targetTexture=A}get targetTexture(){return this._targetTexture}get cam(){return this.activeAndEnabled&&this.buildCamera(),this._cam}screenPointToRay(A,e,t){const i=this.cam,I=op._origin;I.set(A,e,-1),this.context.input.convertScreenspaceToRaycastSpace(I),f2&&console.log("screenPointToRay",A.toFixed(2),e.toFixed(2),"now:",I.x.toFixed(2),I.y.toFixed(2),"isInXR:"+this.context.isInXR),I.z=-1,I.unproject(i);const o=op._direction.set(I.x,I.y,I.z),s=ve(i);return o.sub(s),o.normalize(),t?(t.set(s,o),t):new xo(s.clone(),o.clone())}getFrustum(){return this._frustum||(this._frustum=new Kc,this.updateFrustum()),this._frustum}updateFrustum(){this._frustum||(this._frustum=new Kc),this._frustum.setFromProjectionMatrix(this.getProjectionScreenMatrix(this._projScreenMatrix,!0),this.context.renderer.coordinateSystem)}getProjectionScreenMatrix(A,e){return e&&this._projScreenMatrix.multiplyMatrices(this.cam.projectionMatrix,this.cam.matrixWorldInverse),A===this._projScreenMatrix?A:A.copy(this._projScreenMatrix)}awake(){f2&&window.addEventListener("pointerdown",A=>{const e=A.clientX,t=A.clientY;console.log("touch",e.toFixed(2),t.toFixed(2));const i=this.screenPointToRay(e,t),I="#"+Math.floor(Math.random()*16777215).toString(16);fe.DrawRay(i.origin,i.direction,I,10)})}onEnable(){Ma&&console.log(`Camera enabled: "${this.name}". ClearFlags=${kB[this._clearFlags]}`,this),this.buildCamera(),(this.tag=="MainCamera"||!this.context.mainCameraComponent)&&(this.context.setCurrentCamera(this),kEA(this)),this.applyClearFlagsIfIsActiveCamera({applySkybox:!0})}onDisable(){this.context.removeCamera(this)}onBeforeRender(){if(this._cam&&(this._frustum&&this.updateFrustum(),this._clearFlags===2&&this.applyClearFlagsIfIsActiveCamera(),this._targetTexture)){this.context.isManagedExternally&&(this._warnedAboutExternalRenderer||(this._warnedAboutExternalRenderer=!0,console.warn("Rendering with external renderer is not supported yet. This may not work or throw errors. Please remove the the target texture from your camera: "+this.name,this.targetTexture))),this.context.composer;const A=this.context.renderer;if(A){const e=this.context.mainCameraComponent;this.applyClearFlags(),this._targetTexture.render(this.context.scene,this._cam,A),e==null||e.applyClearFlags()}}}buildCamera(){if(this._cam)return;const A=this.gameObject.isCamera;let e=null;if(A?(e=this.gameObject,e==null||e.layers.enableAll(),e instanceof He&&(this._fov=e.fov)):e=this.gameObject.children[0],e&&e.isCamera)e instanceof He&&(this._fov&&(e.fov=this._fov),e.near=this._nearClipPlane,e.far=this._farClipPlane,e.updateProjectionMatrix());else if(!this.orthographic)e=new He(this.fieldOfView,window.innerWidth/window.innerHeight,this._nearClipPlane,this._farClipPlane),this.fieldOfView&&(e.fov=this.fieldOfView),this.gameObject.add(e);else{const t=this.orthographicSize*100;e=new Tr(window.innerWidth/-t,window.innerWidth/t,window.innerHeight/t,window.innerHeight/-t,this._nearClipPlane,this._farClipPlane),this.gameObject.add(e)}this._cam=e,this._cam.layers.mask=this._cullingMask,this.tag=="MainCamera"&&this.context.setCurrentCamera(this)}applyClearFlagsIfIsActiveCamera(A){this.context.mainCameraComponent===this&&this.applyClearFlags(A)}applyClearFlags(A){if(!this._cam){Ma&&console.log("Camera does not exist (apply clear flags)");return}if(this.fieldOfView=this._fov,Ma){const e=`Camera "${this.name}" clear flags: ${kB[this._clearFlags]}`;console.debug(e)}switch(this._clearFlags){case 1:if(op.backgroundShouldBeTransparent(this.context)&&(!this.ARBackgroundAlpha||this.ARBackgroundAlpha<.001)){this.context.scene.background=null,this.context.renderer.setClearColor(0,0);return}(!this.scene.background||!this._skybox||(A==null?void 0:A.applySkybox)===!0)&&this.applySceneSkybox(),this._backgroundBlurriness!==void 0?this.context.scene.backgroundBlurriness=this._backgroundBlurriness:Ma&&console.warn(`Camera "${this.name}" has no background blurriness`),this._backgroundIntensity!==void 0&&(this.context.scene.backgroundIntensity=this._backgroundIntensity),this._backgroundRotation!==void 0?this.context.scene.backgroundRotation=this._backgroundRotation:Ma&&console.warn(`Camera "${this.name}" has no background intensity`);break;case 2:if(this._backgroundColor){let e=this._backgroundColor.alpha;op.backgroundShouldBeTransparent(this.context)&&(e=this.ARBackgroundAlpha??0),this.context.scene.background=null,this.context.renderer.setClearColor(this._backgroundColor,e)}else Ma&&console.warn(`Camera "${this.name}" has no background color`,this);break;case 4:this.context.scene.background=null,this.context.renderer.setClearColor(0,0);break}}applySceneSkybox(){this._skybox||(this._skybox=new mEA(this)),this._skybox.apply()}static backgroundShouldBeTransparent(A){var I,o,s,n;const e=(I=A.renderer.xr)==null?void 0:I.getSession();if(!e)return!1;if(typeof e._transparent=="boolean")return e._transparent;const t=e.environmentBlendMode;Ma&&fi("Environment blend mode: "+t+" on "+navigator.userAgent);let i=t==="additive"||t==="alpha-blend";return A.isInAR&&t==="opaque"&&((o=navigator.userAgent)!=null&&o.includes("OculusBrowser")||(s=navigator.userAgent)!=null&&s.includes("Mozilla")&&((n=navigator.userAgent)!=null&&n.includes("Mobile WebXRViewer/v2")))&&(i=!0),e._transparent=i,i}},B(qS,"_origin",new y),B(qS,"_direction",new y),qS);let Wt=op;uo([D()],Wt.prototype,"aspect",1);uo([D()],Wt.prototype,"fieldOfView",1);uo([D()],Wt.prototype,"nearClipPlane",1);uo([D()],Wt.prototype,"farClipPlane",1);uo([D()],Wt.prototype,"clearFlags",1);uo([D()],Wt.prototype,"orthographic",2);uo([D()],Wt.prototype,"orthographicSize",2);uo([D()],Wt.prototype,"ARBackgroundAlpha",2);uo([D()],Wt.prototype,"cullingMask",1);uo([D()],Wt.prototype,"backgroundBlurriness",1);uo([D()],Wt.prototype,"backgroundIntensity",1);uo([D(rt)],Wt.prototype,"backgroundRotation",1);uo([D()],Wt.prototype,"environmentIntensity",1);uo([D(Ft)],Wt.prototype,"backgroundColor",1);uo([D(mB)],Wt.prototype,"targetTexture",1);class mEA{constructor(A){B(this,"_camera");B(this,"_skybox");this._camera=A}get context(){var A;return(A=this._camera)==null?void 0:A.context}apply(){this._skybox=this.context.lightmaps.tryGetSkybox(this._camera.sourceId),this._skybox?this.context.scene.background!==this._skybox&&(Ma&&console.log(`Camera "${this._camera.name}" set skybox`,this._camera,this._skybox),this._skybox.mapping=No,this.context.scene.background=this._skybox):(this._did_log_failed_to_find_skybox||(this._did_log_failed_to_find_skybox=!0,console.warn(`Camera "${this._camera.name}" failed to load/find skybox texture`,this._camera.sourceId,this.context.lightmaps,"Current background: ",this.context.scene.background)),(Ma||ae())&&Ot(`Camera "${this._camera.name}" has no skybox texture`))}}function kEA(g){gA("freecam")&&g.context.mainCameraComponent===g&&sA.getOrAddComponent(g.gameObject,Mt)}class MB extends FA{constructor(){super(...arguments);B(this,"_listener",null);B(this,"onInteraction",()=>{this.destroyed||this.listener==null||this.addListenerIfItExists()})}get listener(){return this._listener==null&&(this._listener=new ZP),this._listener}onEnable(){Fr.registerWaitForInteraction(this.onInteraction),this.addListenerIfItExists()}onDisable(){Fr.unregisterWaitForInteraction(this.onInteraction),this.removeListenerIfItExists()}addListenerIfItExists(){const e=this._listener;if(!e||e!=null&&e.parent)return;const t=this.context.mainCameraComponent||sA.getComponentInParent(this.gameObject,Wt);t!=null&&t.cam?t.cam.add(e):this.gameObject.add(e),e.filter?(e.gain.connect(e.filter),e.filter.connect(e.context.destination)):e.gain.connect(e.context.destination)}removeListenerIfItExists(){const e=this._listener;e&&(e.removeFromParent(),e.filter&&e.filter.disconnect(),e.gain&&e.gain.disconnect())}}class MEA extends Oi{constructor(A,e=1,t=16,i=2){const I=new we,o=t+i*2,s=new Float32Array((o*3+3)*3);I.setAttribute("position",new ne(s,3));const n=new Ii({color:65280}),r=new Ii({color:16776960});super(I,[r,n]),this.audio=A,this.range=e,this.divisionsInnerAngle=t,this.divisionsOuterAngle=i,this.type="PositionalAudioHelper",this.update()}update(){const A=this.audio,e=this.range,t=this.divisionsInnerAngle,i=this.divisionsOuterAngle,I=ht.degToRad(A.panner.coneInnerAngle),o=ht.degToRad(A.panner.coneOuterAngle),s=I/2,n=o/2;let r=0,a=0,C,Q;const c=this.geometry,E=c.attributes.position;c.clearGroups();function h(l,d,p,u){const f=(d-l)/p;for(E.setXYZ(r,0,0,0),a++,C=l;C<d;C+=f)Q=r+a,E.setXYZ(Q,Math.sin(C)*e,0,Math.cos(C)*e),E.setXYZ(Q+1,Math.sin(Math.min(C+f,d))*e,0,Math.cos(Math.min(C+f,d))*e),E.setXYZ(Q+2,0,0,0),a+=3;c.addGroup(r,a,u),r+=a,a=0}h(-n,-s,i,0),h(-s,s,t,1),h(s,n,i,0),E.needsUpdate=!0,I===o&&(this.material[0].visible=!1)}dispose(){this.geometry.dispose(),this.material[0].dispose(),this.material[1].dispose()}}var GEA=Object.defineProperty,REA=Object.getOwnPropertyDescriptor,Pr=(g,A,e,t)=>{for(var i=t>1?void 0:t?REA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&GEA(A,e,i),i};const NI=gA("debugaudio"),VC=class extends FA{constructor(){super(...arguments);B(this,"clip","");B(this,"playOnAwake",!1);B(this,"preload",!1);B(this,"_spatialBlend",0);B(this,"_minDistance",1);B(this,"_maxDistance",100);B(this,"_volume",1);B(this,"rollOffMode",0);B(this,"playInBackground",!0);B(this,"_loop",!1);B(this,"sound",null);B(this,"helper",null);B(this,"wasPlaying",!1);B(this,"audioLoader",null);B(this,"shouldPlay",!1);B(this,"_lastClipStartedLoading",null);B(this,"_audioElement",null);B(this,"onVisibilityChanged",()=>{switch(document.visibilityState){case"hidden":(this.playInBackground===!1||In())&&(this.wasPlaying=this.isPlaying,this.isPlaying&&this.pause());break;case"visible":NI&&console.log("visible",this.enabled,this.playOnAwake,!this.isPlaying,VC.userInteractionRegistered,this.wasPlaying),this.enabled&&this.playOnAwake&&!this.isPlaying&&VC.userInteractionRegistered&&this.wasPlaying&&this.play();break}});B(this,"onApplicationMuteChanged",()=>{var A,e;this.context.application.muted?(A=this.sound)==null||A.setVolume(0):(e=this.sound)==null||e.setVolume(this.volume)});B(this,"createAudio",A=>{NI&&console.log("AudioBuffer finished loading",A);const e=this.Sound;if(!e){NI&&console.warn("Failed getting sound?",this.name);return}e.isPlaying&&e.stop(),A&&e.setBuffer(A),e.loop=this._loop,this.context.application.muted?e.setVolume(0):e.setVolume(this.volume),e.autoplay=this.shouldPlay&&VC.userInteractionRegistered,this.applySpatialDistanceSettings(),e.isPlaying&&e.stop(),VC.registerWaitForAllowAudio(this.__onAllowAudioCallback)});B(this,"__onAllowAudioCallback",()=>{this.shouldPlay&&this.play()});B(this,"_lastContextTime",0);B(this,"_hasEnded",!0);B(this,"_needUpdateSpatialDistanceSettings",!1)}static get userInteractionRegistered(){return Fr.userInteractionRegistered}static registerWaitForAllowAudio(A){Fr.registerWaitForAllowAudio(A)}get loop(){return this.sound&&(this._loop=this.sound.getLoop()),this._loop}set loop(A){this._loop=A,this.sound&&this.sound.setLoop(A)}get spatialBlend(){return this._spatialBlend}set spatialBlend(A){A!==this._spatialBlend&&(this._spatialBlend=A,this._needUpdateSpatialDistanceSettings=!0)}get minDistance(){return this._minDistance}set minDistance(A){this._minDistance!==A&&(this._minDistance=A,this._needUpdateSpatialDistanceSettings=!0)}get maxDistance(){return this._maxDistance}set maxDistance(A){this._maxDistance!==A&&(this._maxDistance=A,this._needUpdateSpatialDistanceSettings=!0)}get volume(){return this._volume}set volume(A){this._volume=A,this.sound&&!this.context.application.muted&&(NI&&console.log(this.name,"audio set volume",A),this.sound.setVolume(A))}get Sound(){var A;if(!this.sound&&VC.userInteractionRegistered){let e=sA.getComponent(this.context.mainCamera,MB)??sA.findObjectOfType(MB,this.context);!e&&this.context.mainCamera&&(e=sA.addNewComponent(this.context.mainCamera,MB)),e!=null&&e.listener?(this.sound=new jP(e.listener),(A=this.gameObject)==null||A.add(this.sound)):NI&&console.warn("No audio listener found in scene - can not play audio")}return this.sound}get ShouldPlay(){return this.shouldPlay}get audioContext(){var A;return(A=this.sound)==null?void 0:A.context}awake(){NI&&console.log(this),this.audioLoader=new O0,this.playOnAwake&&(this.shouldPlay=!0),this.preload&&typeof this.clip=="string"&&this.audioLoader.load(this.clip,this.createAudio,()=>{},console.error)}onEnable(){this.sound&&this.gameObject.add(this.sound),VC.userInteractionRegistered?this.playOnAwake&&this.context.application.isVisible&&this.play():VC.registerWaitForAllowAudio(()=>{this.enabled&&!this.destroyed&&this.shouldPlay&&this.onNewClip(this.clip)}),globalThis.addEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.addEventListener(Em.MuteChanged,this.onApplicationMuteChanged)}onDisable(){globalThis.removeEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.removeEventListener(Em.MuteChanged,this.onApplicationMuteChanged),this.pause()}applySpatialDistanceSettings(){const A=this.sound;if(!A)return;this._needUpdateSpatialDistanceSettings=!1;const e=ge.lerp(10*this._maxDistance/Math.max(1e-4,this.spatialBlend),this._minDistance,this.spatialBlend);switch(NI&&console.log(this.name,this._minDistance,this._maxDistance,this.spatialBlend,"Ref distance="+e),A.setRefDistance(e),A.setMaxDistance(Math.max(.01,this._maxDistance)),this.rollOffMode){case 0:A.setDistanceModel("exponential");break;case 1:A.setDistanceModel("linear");break;case 2:console.warn("Custom rolloff for AudioSource is not supported: "+this.name);break}this.spatialBlend>0?NI&&!this.helper&&(this.helper=new MEA(A,A.getRefDistance()),A.add(this.helper)):this.helper&&this.helper.parent&&this.helper.removeFromParent()}async onNewClip(A){if(A&&(this.clip=A),typeof A=="string")if(NI&&console.log(A),A.endsWith(".mp3")||A.endsWith(".wav")){if(this.audioLoader||(this.audioLoader=new O0),this.shouldPlay=!0,this._lastClipStartedLoading===A){NI&&console.log("Is currently loading:",this._lastClipStartedLoading,this);return}this._lastClipStartedLoading=A,NI&&console.log("load audio",A);const e=await this.audioLoader.loadAsync(A).catch(console.error);this._lastClipStartedLoading=null,e&&this.createAudio(e)}else console.warn("Unsupported audio clip type",A);else this.shouldPlay=!0,this.createAudio()}play(A=void 0){var t,i,I;!A&&this.clip&&(A=this.clip),A!==void 0&&typeof A!="string"&&!(A instanceof MediaStream)&&(ae()&&console.warn("Called play on AudioSource with unknown argument type:",A+`
5733
5733
  Using the assigned clip instead:`,this.clip),A=this.clip);let e=!this.sound||A&&A!==this.clip;if(typeof A=="string"&&!this.audioLoader&&(e=!0),(A instanceof MediaStream||typeof A=="string")&&(this.clip=A),e){this.shouldPlay=!0,this.onNewClip(A);return}if(this.shouldPlay=!0,this._hasEnded=!1,NI&&console.log("play",(t=this.sound)==null?void 0:t.getVolume(),this.sound),this.sound&&!this.sound.isPlaying){const o=this.context.application.muted;o&&this.sound.setVolume(0),(i=this.gameObject)==null||i.add(this.sound),this.clip instanceof MediaStream?(this.sound.setMediaStreamSource(this.clip),this._audioElement||(this._audioElement=document.createElement("audio"),this._audioElement.style.display="none"),this._audioElement.parentNode||(I=this.context.domElement.shadowRoot)==null||I.append(this._audioElement),this._audioElement.srcObject=this.clip,this._audioElement.autoplay=!1):(this._audioElement&&this._audioElement.remove(),this.sound.play(o?.1:0))}}pause(){var A,e;NI&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.isPlaying&&this.sound.source&&(this._lastContextTime=(A=this.sound)==null?void 0:A.context.currentTime,this.sound.pause()),(e=this._audioElement)==null||e.remove()}stop(){var A,e;NI&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.source&&(this._lastContextTime=(A=this.sound)==null?void 0:A.context.currentTime,NI&&console.log(this._lastContextTime),this.sound.stop()),(e=this._audioElement)==null||e.remove()}get isPlaying(){var A;return((A=this.sound)==null?void 0:A.isPlaying)??!1}set isPlaying(A){}get time(){var A,e;return(A=this.sound)!=null&&A.source?((e=this.sound.source)==null?void 0:e.context.currentTime)-this._lastContextTime+this.sound.offset:0}set time(A){if(this.sound){if(A===this.sound.offset)return;const e=this.isPlaying;this.stop(),this.sound.offset=A,e&&this.play()}}update(){this.helper&&(this.isPlaying&&this.helper.update(),this.helper.visible=this.isPlaying),this._needUpdateSpatialDistanceSettings&&this.applySpatialDistanceSettings(),this.sound&&!this.sound.isPlaying&&this.shouldPlay&&!this._hasEnded&&(this._hasEnded=!0,NI&&console.log("Audio clip ended",this.clip),this.dispatchEvent(new CustomEvent("ended",{detail:this})))}};let zi=VC;Pr([D(URL)],zi.prototype,"clip",2);Pr([D()],zi.prototype,"playOnAwake",2);Pr([D()],zi.prototype,"preload",2);Pr([D()],zi.prototype,"loop",1);Pr([D()],zi.prototype,"spatialBlend",1);Pr([D()],zi.prototype,"minDistance",1);Pr([D()],zi.prototype,"maxDistance",1);Pr([D()],zi.prototype,"volume",1);Pr([D()],zi.prototype,"rollOffMode",2);Pr([D()],zi.prototype,"playInBackground",2);var UEA=Object.defineProperty,NEA=Object.getOwnPropertyDescriptor,uM=(g,A,e,t)=>{for(var i=t>1?void 0:t?NEA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&UEA(A,e,i),i};const FEA=gA("debugsignals");class vD{constructor(){B(this,"guid")}}uM([D()],vD.prototype,"guid",2);class ld{constructor(){B(this,"signal");B(this,"reaction")}}uM([D(vD)],ld.prototype,"signal",2);uM([D(og)],ld.prototype,"reaction",2);var KN;const Da=(KN=class extends FA{constructor(){super(...arguments);B(this,"events")}static invoke(A){if(Da.receivers[A]){const e=Da.receivers[A];if(!e)return;for(const t of e)t.invoke(A)}}awake(){FEA&&console.log("SignalReceiver awake",this)}onEnable(){if(this.events)for(const A of this.events)Da.receivers[A.signal.guid]||(Da.receivers[A.signal.guid]=[]),Da.receivers[A.signal.guid].push(this)}onDisable(){if(this.events){for(const A of this.events)if(Da.receivers[A.signal.guid]){const e=Da.receivers[A.signal.guid].indexOf(this);e>=0&&Da.receivers[A.signal.guid].splice(e,1)}}}invoke(A){if(!this.events||!Array.isArray(this.events))return;const e=typeof A=="object"?A.guid:A;for(const t of this.events)if(t.signal.guid===e)try{if(t.reaction){if(!t.reaction.invoke){console.warn("Missing invoke - possibly a serialization error",t,this);continue}}else{console.warn("Missing reaction for signal",t,this);continue}t.reaction.invoke()}catch(i){console.error(i)}}},B(KN,"receivers",{}),KN);let hd=Da;uM([D(ld)],hd.prototype,"events",2);var zo=(g=>(g.Activation="ActivationTrack",g.Animation="AnimationTrack",g.Audio="AudioTrack",g.Control="ControlTrack",g.Marker="MarkerTrack",g.Signal="SignalTrack",g))(zo||{}),Cr=(g=>(g[g.None=0]="None",g[g.Hold=1]="Hold",g[g.Loop=2]="Loop",g[g.PingPong=3]="PingPong",g[g.Continue=4]="Continue",g))(Cr||{}),sv=(g=>(g.Signal="SignalEmitter",g))(sv||{});const kr=gA("debugtimeline");class qD{constructor(){B(this,"director");B(this,"track")}get muted(){return this.track.muted}set muted(A){var e;A!==this.track.muted&&(this.track.muted=A,(e=this.onMuteChanged)==null||e.call(this))}*forEachClip(A=!1){var e;if((e=this.track)!=null&&e.clips)if(A)for(let t=this.track.clips.length-1;t>=0;t--)yield this.track.clips[t];else for(const t of this.track.clips)yield t}getClipTime(A,e){return e.clipIn+(A-e.start)*e.timeScale}getClipTimeNormalized(A,e){return(A-e.start)/e.duration}evaluateWeight(A,e,t,i=!0){if(e<0||e>=t.length)return 0;const I=t[e];if(i||A>=I.start&&A<=I.end){let o=1;const s=!1;if(I.easeInDuration>0){const n=Math.min((A-I.start)/I.easeInDuration,1);o*=n}if(I.easeOutDuration>0&&!s){const n=Math.min((I.end-A)/I.easeOutDuration,1);o*=n}return o}return 0}}class KEA{constructor(A){B(this,"clip");B(this,"rootPositionOffset");B(this,"rootQuaternionOffset");B(this,"rootStartPosition");B(this,"rootEndPosition");B(this,"rootStartQuaternion");B(this,"rootEndQuaternion");const e=A.getClip();this.clip=e;const t=A.getRoot(),i=t.name+".position",I=t.name+".quaternion";kr&&console.log(e.name,e.tracks,i);for(const o of e.tracks)if(!(o.times.length<=0)){if(o.name.endsWith(i))this.rootStartPosition=new y().fromArray(o.values,0),this.rootEndPosition=new y().fromArray(o.values,o.values.length-3),this.rootPositionOffset=this.rootEndPosition.clone().sub(this.rootStartPosition),kr&&console.log(this.rootPositionOffset);else if(o.name.endsWith(I)&&(this.rootStartQuaternion=new GA().fromArray(o.values,0),this.rootEndQuaternion=new GA().fromArray(o.values,o.values.length-4),this.rootQuaternionOffset=this.rootEndQuaternion.clone().multiply(this.rootStartQuaternion),kr)){const s=new rt().setFromQuaternion(this.rootQuaternionOffset);console.log("ROT",s)}}}get hasOffsets(){return this.rootPositionOffset!==void 0||this.rootQuaternionOffset!==void 0}}class pM extends qD{constructor(){super(...arguments);B(this,"models",[]);B(this,"trackOffset");B(this,"target");B(this,"mixer");B(this,"clips",[]);B(this,"actions",[]);B(this,"_actionOffsets",[]);B(this,"_didBind",!1);B(this,"_animator",null);B(this,"_useclipOffsets",!0);B(this,"_totalOffsetPosition",new y);B(this,"_totalOffsetRotation",new GA);B(this,"_totalOffsetPosition2",new y);B(this,"_totalOffsetRotation2",new GA);B(this,"_summedPos",new y);B(this,"_tempPos",new y);B(this,"_summedRot",new GA);B(this,"_tempRot",new GA);B(this,"_clipRotQuat",new GA)}onDisable(){var e;(e=this.mixer)==null||e.stopAllAction()}onDestroy(){this.director.context.animations.unregisterAnimationMixer(this.mixer)}onStateChanged(){this._animator&&D2(this._animator.gameObject,this,this.director.isPlaying)}createHooks(e,t){var a,C;if(((a=t.tracks)==null?void 0:a.length)<=0){console.warn("No tracks in AnimationClip",t);return}const i=t.tracks[0].name.split("."),I=i[i.length-2],o=I+".position",s=I+".quaternion";let n=!1,r=!1;for(const Q of t.tracks)Q.name.endsWith(o)?(n=!0,this.createPositionInterpolant(t,e,Q)):Q.name.endsWith(s)&&(r=!0,this.createRotationInterpolant(t,e,Q));if(!n||!r){const Q=(C=this.mixer)==null?void 0:C.getRoot(),c=t.tracks[0],E=c.name.lastIndexOf("."),h=c.name.substring(0,E),l=h.substring(h.lastIndexOf(".")+1),d=Q.getObjectByName(l);if(d)if(n){if(!r){const p=t.tracks[0].name.substring(0,E)+".quaternion";kr&&console.warn("Create quaternion track",l,d);const u=d.quaternion,f=new Zs(p,[0,t.duration],[u.x,u.y,u.z,u.w,u.x,u.y,u.z,u.w]);t.tracks.push(f),this.createRotationInterpolant(t,e,f)}}else{const p=h+".position";kr&&console.warn("Create position track",l,d);const u=d.position,f=new xr(p,[0,t.duration],[u.x,u.y,u.z,u.x,u.y,u.z]);t.tracks.push(f),this.createPositionInterpolant(t,e,f)}}}bind(){if(!this._didBind){this._didBind=!0,kr&&console.log(this.models),this.mixer?this.target=this.mixer.getRoot():console.warn("No mixer was assigned to animation track");for(const e of this.actions){const t=new KEA(e);this._actionOffsets.push(t)}this.target&&(this._animator=sA.getComponent(this.target,hI)??null,this._animator&&D2(this._animator.gameObject,this,!0));for(const e of this.models){const t=e.asset,i=t.position,I=t.rotation;i&&i.x!==void 0&&(i.isVector3||(t.position=new y(i.x,i.y,i.z)),I.isQuaternion||(t.rotation=new GA(I.x,I.y,I.z,I.w)))}this.ensureTrackOffsets()}}ensureTrackOffsets(){if(this.trackOffset){const e=this.trackOffset.position;e&&(e.isVector3||(this.trackOffset.position=new y(e.x,e.y,e.z)));const t=this.trackOffset.rotation;t&&(t.isQuaternion||(this.trackOffset.rotation=new GA(t.x,t.y,t.z,t.w)))}}evaluate(e){var n,r,a,C,Q,c,E;if(this.track.muted||!this.mixer)return;this.bind(),this._totalOffsetPosition.set(0,0,0),this._totalOffsetRotation.set(0,0,0,1),this._totalOffsetPosition2.set(0,0,0),this._totalOffsetRotation2.set(0,0,0,1);let t=0,i=0,I=!1,o=!1,s=0;for(let h=0;h<this.clips.length;h++){const l=this.models[h],d=this.actions[h],p=l.asset;d.weight=0;const u=e>=l.start&&e<=l.end,f=l.preExtrapolationMode,w=l.postExtrapolationMode,m=h<this.clips.length-1?this.models[h+1]:null;let M=u,G=!1;if(!M&&!I&&l.end<e&&w!==Cr.None?(!m||m.start>e)&&(M=!0,I=!0):h==0&&!M&&!o&&l.start>e&&f!==Cr.None&&(!m||m.start<e)&&(M=!0,G=!0,o=!0),M){let U=1;U*=this.evaluateWeight(e,h,this.models,M),U*=this.director.weight;let S=u;if(G)switch(f){case Cr.Hold:break;case Cr.Loop:e+=l.start,S=!0;break;default:e+=l.start,S=!0;break}let R=this.getClipTime(e,l),v=0;const q=p.duration;if(G&&f===Cr.Hold&&(R=0),S){if(p.loop)for(v+=Math.floor(R/(q+1e-6));R>q;)R-=q}else if(!u&&I)switch(w){case Cr.Hold:R=this.getClipTime(l.end,l);break;case Cr.Loop:R%=q;break;case Cr.PingPong:const K=Math.floor(R/q)%2!==0;R%=q,K&&(R=q-R);break}l.reversed===!0?d.time=d.getClip().duration-R:d.time=R,d.timeScale=0;const b=Math.max(0,U);if(d.weight=b,s+=b,d.clampWhenFinished=!1,d.isRunning()||d.play(),this._useclipOffsets){const O=t==0?this._totalOffsetPosition:this._totalOffsetPosition2,K=t==0?this._totalOffsetRotation:this._totalOffsetRotation2;t<1&&(i=1-U),t+=1;const x=this._summedPos.set(0,0,0),_=this._tempPos.set(0,0,0),Z=this._summedRot.identity(),j=this._tempRot.identity(),oA=p.rotation;oA&&(this._clipRotQuat.identity(),this._clipRotQuat.slerp(oA,U));const BA=this._actionOffsets[h];if(BA.hasOffsets)for(let UA=0;UA<v;UA++)BA.rootPositionOffset?_.copy(BA.rootPositionOffset):_.set(0,0,0),_.applyQuaternion(Z),this._clipRotQuat&&_.applyQuaternion(this._clipRotQuat),BA.rootQuaternionOffset&&(j.copy(BA.rootQuaternionOffset),Z.multiply(j)),x.add(_);this._clipRotQuat&&K.multiply(this._clipRotQuat),K.multiply(Z),p.position&&x.add(p.position),O.add(x)}}}if(this._useclipOffsets&&(this._totalOffsetPosition.lerp(this._totalOffsetPosition2,i),this._totalOffsetRotation.slerp(this._totalOffsetRotation2,i)),this.__mixerError===void 0&&(kr||ae())&&((r=(n=this._animator)==null?void 0:n.runtimeAnimatorController)!=null&&r.mixer)&&this.mixer!==((C=(a=this._animator)==null?void 0:a.runtimeAnimatorController)==null?void 0:C.mixer)&&(this.__mixerError=!0,console.error("AnimationTrack mixer is not shared with the animator controller - this might result in the timeline to not animate properly. Please report a bug to the Needle Engine team!",this)),(Q=this._animator)!=null&&Q.runtimeAnimatorController){const h=Math.max(0,1-s);(E=(c=this._animator)==null?void 0:c.runtimeAnimatorController)==null||E.update(h)}else this.mixer.update(e)}createRotationInterpolant(e,t,i){var n;const I=i.createInterpolant.bind(i),o=new GA;this.ensureTrackOffsets();const s=(n=this.trackOffset)==null?void 0:n.rotation;i.createInterpolant=()=>{const r=I(),a=r.evaluate.bind(r);return r.evaluate=C=>{var c;const Q=a(C);if(o.set(Q[0],Q[1],Q[2],Q[3]),o.premultiply(this._totalOffsetRotation),s&&o.premultiply(s),this.director.animationCallbackReceivers)for(const E of this.director.animationCallbackReceivers)(c=E==null?void 0:E.onTimelineRotation)==null||c.call(E,this.director,this.target,C,o);return Q[0]=o.x,Q[1]=o.y,Q[2]=o.z,Q[3]=o.w,Q},r}}createPositionInterpolant(e,t,i){var a,C;const I=i.createInterpolant.bind(i),o=new y;this.ensureTrackOffsets();const s=(a=this.trackOffset)==null?void 0:a.rotation,n=(C=this.trackOffset)==null?void 0:C.position;let r;i.createInterpolant=()=>{const Q=I(),c=Q.evaluate.bind(Q);return Q.evaluate=E=>{var l,d,p;const h=c(E);if(o.set(h[0],h[1],h[2]),t.removeStartOffset&&(r===void 0?(r=null,r=(d=(l=this._actionOffsets.find(u=>u.clip===e))==null?void 0:l.rootStartPosition)==null?void 0:d.clone()):r!=null&&r.isVector3&&o.sub(r)),o.applyQuaternion(this._totalOffsetRotation),o.add(this._totalOffsetPosition),s&&o.applyQuaternion(s),n&&(o.x-=n.x,o.y+=n.y,o.z+=n.z),this.director.animationCallbackReceivers)for(const u of this.director.animationCallbackReceivers)(p=u==null?void 0:u.onTimelinePosition)==null||p.call(u,this.director,this.target,E,o);return h[0]=o.x,h[1]=o.y,h[2]=o.z,h},Q}}}const bEA=gA("mutetimeline"),oh=class extends qD{constructor(){super(...arguments);B(this,"models",[]);B(this,"listener");B(this,"audio",[]);B(this,"audioContextTimeOffset",[]);B(this,"lastTime",0);B(this,"audioSource");B(this,"_audioLoader",null);B(this,"_playableDirectorResumed",!1)}getAudioFilePath(e){const t=this.director.sourceId;return OB(t,e)}onAllowAudioChanged(e){for(let t=0;t<this.models.length;t++){const i=this.models[t];this.audio[t].setVolume(e?i.asset.volume:0)}}addModel(e){const t=new cJ(this.listener);this.audio.push(t);const i=e;i._didTriggerPlay=!1,this.models.push(i)}onDisable(){for(const e of this.audio)e.isPlaying&&e.stop();for(const e of this.models)e._didTriggerPlay=!1}onDestroy(){for(const e of this.audio)e.source&&(e==null||e.disconnect());this.audio.length=0}onMuteChanged(){if(this.muted)for(let e=0;e<this.audio.length;e++){const t=this.audio[e];t!=null&&t.isPlaying&&t.stop()}}stop(){for(let e=0;e<this.audio.length;e++){const t=this.audio[e];t!=null&&t.isPlaying&&t.stop()}for(const e of this.models)e._didTriggerPlay=!1}onPauseChanged(){for(let e=0;e<this.audio.length;e++){const t=this.audio[e];t!=null&&t.isPlaying&&t.stop()}this._playableDirectorResumed=this.director.isPlaying}evaluate(e){if(bEA||this.track.muted||this.director.speed<0)return;const t=this.director.context.application.muted,i=this._playableDirectorResumed;this._playableDirectorResumed=!1;const I=t?.1:0;for(let o=0;o<this.models.length;o++){const s=this.models[o],n=this.audio[o],r=s.asset;if((!n||!n.buffer)&&this.isInTimeRange(s,e-1,e+1)&&this.handleAudioLoading(s,n),zi.userInteractionRegistered!==!1&&!(n===null||!n.buffer))if(n.playbackRate=this.director.context.time.timeScale*this.director.speed,n.loop=r.loop,e>=s.start&&e<=s.end&&e<this.director.duration){if(!n.isPlaying||!this.director.isPlaying)(i||!s._didTriggerPlay&&this.lastTime<e)&&(s.duration*s.timeScale>.3?n.offset=s.clipIn+(e-s.start)*s.timeScale:n.offset=0,kr&&console.log("Timeline Audio ("+this.track.name+") play with offset "+n.offset+" - "+s.asset.clip),n.play(I),s._didTriggerPlay=!0);else{const C=s.clipIn+(e-s.start)*s.timeScale,Q=n.context.currentTime-n._startedAt+n.offset;Math.abs(C-Q)>.3&&(n.offset=C,n.stop(),n.play(I))}let a=r.volume;if(this.track.volume!==void 0&&(a*=this.track.volume),t&&(a=0),s.easeInDuration>0){const C=Math.min((e-s.start)/s.easeInDuration,1);a*=C}if(s.easeOutDuration>0){const C=Math.min((s.end-e)/s.easeOutDuration,1);a*=C}n.setVolume(a*this.director.weight)}else s._didTriggerPlay=!1,this.director.isPlaying&&n.isPlaying&&n.stop()}this.lastTime=e}loadAudio(e,t=0,i=0){let I=null;const o=e-i,s=e+t;for(const n of this.models)if(this.isInTimeRange(n,o,s)){const r=this.audio[this.models.indexOf(n)],a=this.handleAudioLoading(n,r);a!==null&&(I===null&&(I=[]),I.push(a))}return I!==null?Promise.all(I):null}isInTimeRange(e,t,i){return t<=e.start&&i>=e.end||t>=e.start&&t<=e.end||i>=e.start&&i<=e.end}static dispose(){oh._audioBuffers.clear()}handleAudioLoading(e,t){this._audioLoader||(this._audioLoader=new O0);const i=this.getAudioFilePath(e.asset.clip);if(oh._audioBuffers.get(i)){const o=oh._audioBuffers.get(i);return o.then(s=>{s&&t.setBuffer(s)}),o}kr&&console.warn("LOAD audio track",i,this.director.sourceId);const I=new Promise((o,s)=>{this._audioLoader.load(i,n=>{t.setBuffer(n),o(n)},void 0,n=>{console.error("Error loading audio",n),o(null)})});return oh._audioBuffers.set(i,I),I}};let wc=oh;B(wc,"_audioBuffers",new Map);class bf extends qD{constructor(){super(...arguments);B(this,"models",[]);B(this,"didTrigger",[]);B(this,"receivers",[])}evaluate(e){var i;if(this.track.muted)return;const t=this.director.context.time.deltaTime*1.5;for(let I=0;I<this.models.length;I++){const o=this.models[I],s=this.didTrigger[I],n=o.time-e;let r=!1;if(o.retroActive)r=n<=1e-6;else{const a=Math.abs(n);(a===0||a>=1e-5&&a<t)&&(r=!0)}if(r){if(!s)if(kr&&console.log("Trigger signal",e,o.time,o),this.didTrigger[I]=!0,((i=this.receivers)==null?void 0:i.length)<=0)hd.invoke(o.asset);else for(const a of this.receivers)a&&a.invoke(o.asset)}else o.emitOnce||(this.didTrigger[I]=!1)}}}class fM extends qD{constructor(){super(...arguments);B(this,"models",[]);B(this,"timelines",[]);B(this,"_previousActiveModel",null)}resolveSourceObjects(e){for(let t=this.models.length-1;t>=0;t--){const I=this.models[t].asset;if(!I.sourceObject||typeof I.sourceObject!="object"){console.log("no source object, removing model",t,I),this.models.splice(t,1);continue}else{const o=sA.getComponent(I.sourceObject,JB);this.timelines.push(o),o&&I.updateDirector&&(o.playOnAwake=!1)}}}evaluate(e){var t;this._previousActiveModel=null;for(let i=0;i<this.models.length;i++){const I=this.models[i],o=I.asset;if(e>=I.start&&e<=I.end){this._previousActiveModel=I;const s=this.getClipTime(e,I);if(o.controlActivation){const n=o.sourceObject;n.visible=!0}if(o.updateDirector){const n=this.timelines[i];n&&(n.isPlaying&&n.pause(),n.time=s,n.evaluate())}}else{const s=(t=this._previousActiveModel)==null?void 0:t.asset;if(o.controlActivation){const n=o.sourceObject;(s==null?void 0:s.sourceObject)!==n&&(n.visible=!1)}}}}}var JEA=Object.defineProperty,xEA=Object.getOwnPropertyDescriptor,aj=(g,A,e,t)=>{for(var i=t>1?void 0:t?xEA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&JEA(A,e,i),i};const fl=gA("debugtimeline");var bN;const VK=(bN=class extends FA{constructor(){super(...arguments);B(this,"playableAsset");B(this,"playOnAwake");B(this,"extrapolationMode",1);B(this,"waitForAudio",!0);B(this,"_visibilityChangeEvt");B(this,"_clonedPlayableAsset",!1);B(this,"_speed",1);B(this,"_guidsMap");B(this,"_isPlaying",!1);B(this,"_internalUpdateRoutine");B(this,"_isPaused",!1);B(this,"_isStopping",!1);B(this,"_time",0);B(this,"_duration",0);B(this,"_weight",1);B(this,"_animationTracks",[]);B(this,"_audioTracks",[]);B(this,"_signalTracks",[]);B(this,"_controlTracks",[]);B(this,"_customTracks",[]);B(this,"_allTracks",[this._animationTracks,this._audioTracks,this._signalTracks,this._controlTracks,this._customTracks]);B(this,"animationCallbackReceivers",[])}static registerCreateTrack(A,e){this.createTrackFunctions[A]=e}get isPlaying(){return this._isPlaying}get isPaused(){return this._isPaused}get time(){return this._time}set time(A){typeof A=="number"&&!Number.isNaN(A)?this._time=A:(fl||co())&&console.error("INVALID TIMELINE.TIME VALUE",A,this.name)}get duration(){return this._duration}set duration(A){this._duration=A}get weight(){return this._weight}set weight(A){this._weight=A}get speed(){return this._speed}set speed(A){this._speed=A}awake(){var A,e,t;fl&&console.log(this,(A=this.playableAsset)==null?void 0:A.tracks),this.rebuildGraph(),this.isValid()||console.warn("PlayableDirector is not valid",this.playableAsset,(e=this.playableAsset)==null?void 0:e.tracks,Array.isArray((t=this.playableAsset)==null?void 0:t.tracks),this)}onEnable(){var A,e,t;for(const i of this._audioTracks)(A=i.onEnable)==null||A.call(i);for(const i of this._customTracks)(e=i.onEnable)==null||e.call(i);for(const i of this._animationTracks)(t=i.onEnable)==null||t.call(i);this.playOnAwake&&this.play(),this._visibilityChangeEvt||(this._visibilityChangeEvt=()=>{switch(document.visibilityState){case"hidden":this.setAudioTracksAllowPlaying(!1);break;case"visible":this.setAudioTracksAllowPlaying(!0);break}}),window.addEventListener("visibilitychange",this._visibilityChangeEvt)}onDisable(){var A,e,t;this.stop();for(const i of this._audioTracks)(A=i.onDisable)==null||A.call(i);for(const i of this._customTracks)(e=i.onDisable)==null||e.call(i);for(const i of this._animationTracks)(t=i.onDisable)==null||t.call(i);this._visibilityChangeEvt&&window.removeEventListener("visibilitychange",this._visibilityChangeEvt)}onDestroy(){var A;for(const e of this._allTracks)for(const t of e)(A=t.onDestroy)==null||A.call(t)}rebuildGraph(){this.isValid()&&(this.resolveBindings(),this.updateTimelineDuration(),this.setupAndCreateTrackHandlers())}async play(){if(!this.isValid())return;const A=this._isPaused==!0;if(this._isPaused=!1,!this._isPlaying){if(this._isPlaying=!0,A&&this.invokePauseChangedMethodsOnTracks(),this.waitForAudio){const e=[];for(const t of this._audioTracks){const i=t.loadAudio(this._time,1,0);i&&e.push(i)}if(e.length>0&&(await Promise.all(e),!this._isPlaying))return;for(;this._audioTracks.length>0&&this._isPlaying&&!zi.userInteractionRegistered&&this.waitForAudio;)await vr(200)}this.invokeStateChangedMethodsOnTracks(),this._internalUpdateRoutine=this.startCoroutine(this.internalUpdate(),oi.LateUpdate)}}pause(){this.isValid()&&(this._isPlaying=!1,!this._isPaused&&(this._isPaused=!0,this.internalEvaluate(),this.invokePauseChangedMethodsOnTracks(),this.invokeStateChangedMethodsOnTracks()))}stop(){this._isStopping=!0;for(const t of this._audioTracks)t.stop();const A=this._isPaused==!0,e=this._isPlaying;this._isPlaying&&(this._time=0,this._isPlaying=!1,this._isPaused=!1,this.internalEvaluate(),A&&this.invokePauseChangedMethodsOnTracks()),this._isPlaying=!1,this._isPaused=!1,A&&!e&&this.invokePauseChangedMethodsOnTracks(),e&&this.invokeStateChangedMethodsOnTracks(),this._internalUpdateRoutine&&this.stopCoroutine(this._internalUpdateRoutine),this._internalUpdateRoutine=null,this._isStopping=!1}evaluate(){this.internalEvaluate(!0)}isValid(){return this.playableAsset&&this.playableAsset.tracks&&Array.isArray(this.playableAsset.tracks)}*forEachTrack(){for(const A of this._allTracks)for(const e of A)yield e}get audioTracks(){return this._audioTracks}resolveGuids(A){this._guidsMap=A}invokePauseChangedMethodsOnTracks(){var A;for(const e of this.forEachTrack())(A=e.onPauseChanged)==null||A.call(e)}invokeStateChangedMethodsOnTracks(){var A;for(const e of this.forEachTrack())(A=e.onStateChanged)==null||A.call(e,this._isPlaying)}*internalUpdate(){for(;this._isPlaying&&this.activeAndEnabled;)!this._isPaused&&this._isPlaying&&(this._time+=this.context.time.deltaTime*this.speed,this.internalEvaluate()),yield}internalEvaluate(A=!1){if(!this.isValid())return;let e=this._time;switch(this.extrapolationMode){case 0:this._speed>0?e=Math.min(e,this._duration):this._speed<0&&(e=Math.max(e,0)),this._time=e;break;case 1:e%=this._duration,this._time=e;break;case 2:if(e>this._duration){this.stop();return}break}const t=this._time;for(const i of this.playableAsset.tracks)if(!i.muted)switch(i.type){case zo.Activation:if(!A&&!this._isPlaying)continue;for(let I=0;I<i.outputs.length;I++){const o=i.outputs[I];if(typeof o=="object"){let s=!1;if(i.clips)for(const r of i.clips)r.start<=t&&t<=r.end&&(s=!0);const n=o;n.visible!==void 0&&n.visible!==s&&(n.visible=s,fl&&console.warn(this.name,"set ActivationTrack-"+I,n.name,s,t))}}break}if(!this._isStopping)for(const i of this._animationTracks)i.evaluate(t);for(const i of this._audioTracks)i.evaluate(t);for(const i of this._signalTracks)i.evaluate(t);for(const i of this._controlTracks)i.evaluate(t);for(const i of this._customTracks)i.evaluate(t)}resolveBindings(){if(this._clonedPlayableAsset||(this._clonedPlayableAsset=!0,this.playableAsset=cD(this.playableAsset)),!this.playableAsset||!this.playableAsset.tracks)return;const A=this.findRoot(this.gameObject);for(const e of this.playableAsset.tracks){for(let t=e.outputs.length-1;t>=0;t--){let i=e.outputs[t];if(typeof i=="string"){this._guidsMap&&this._guidsMap[i]&&(i=this._guidsMap[i]);const I=sA.findByGuid(i,A);I===null||typeof I!="object"?(e.outputs.splice(t,1),console.warn("Failed to resolve binding",i,e.name,e.type)):(fl&&console.log("Resolved binding",i,"to",I),e.outputs[t]=I)}else if(i===null){if(e.outputs.splice(t,1),VK.createTrackFunctions[e.type])continue;e.type!==zo.Audio&&e.type!==zo.Control&&e.type!==zo.Marker&&e.type!==zo.Signal&&console.warn("Missing binding",i,e.name,e.type,this.name,this.playableAsset.name)}}if(e.type===zo.Control&&e.clips)for(let t=0;t<e.clips.length;t++){const i=e.clips[t];let I=i.asset.sourceObject;if(typeof I=="string"){this._guidsMap&&this._guidsMap[I]&&(I=this._guidsMap[I]);const o=sA.findByGuid(I,A);o===null||typeof o!="object"?console.warn("Failed to resolve sourceObject binding",I,e.name,i):(fl&&console.log("Resolved binding",I,"to",o),i.asset.sourceObject=o)}}}}findRoot(A){return A.parent?this.findRoot(A.parent):A}updateTimelineDuration(){if(this._duration=0,!(!this.playableAsset||!this.playableAsset.tracks)){for(const A of this.playableAsset.tracks)if(A.muted!==!0){if(A.clips)for(const e of A.clips)e.end>this._duration&&(this._duration=e.end);if(A.markers)for(const e of A.markers)e.time>this._duration&&(this._duration=e.time+.001)}}}setupAndCreateTrackHandlers(){var e,t,i;if(this._animationTracks.length=0,this._audioTracks.length=0,this._signalTracks.length=0,!this.playableAsset)return;let A=sA.findObjectOfType(MB,this.context);for(const I of this.playableAsset.tracks){const o=I.type,s=VK.createTrackFunctions[o];if(s!=null){const n=s(this,I);if(typeof n.evaluate=="function"){n.director=this,n.track=I,this._customTracks.push(n);continue}}if(I.type===zo.Animation){if(!I.clips||I.clips.length<=0){fl&&console.warn("Animation track has no clips",I);continue}for(let n=I.outputs.length-1;n>=0;n--){let r=I.outputs[n];if(r instanceof DA){const C=sA.getOrAddComponent(r,hI);C&&(r=C)}const a=(e=r==null?void 0:r.gameObject)==null?void 0:e.animations;if(a){const C=new pM;C.trackOffset=I.trackOffset,C.director=this,C.track=I;for(let Q=0;Q<I.clips.length;Q++){const c=I.clips[Q],E=c.asset;if(!E){console.error(`Timeline ${this.name}: clip #${Q} on track "${I.name}" has no animation data`);continue}const h=E.clip;let l=h;if((typeof l=="string"||typeof l=="number")&&(l=a.find(p=>p.name===h)),!l){console.warn("Could not find animationClip for model",c,I.name,this.name,(t=this.playableAsset)==null?void 0:t.name);continue}r instanceof hI&&r.runtimeAnimatorController&&(r.__internalDidAwakeAndStart||r.initializeRuntimeAnimatorController(),r.runtimeAnimatorController.mixer||r.runtimeAnimatorController.bind(r),C.mixer=r.runtimeAnimatorController.mixer),C.mixer||(C.mixer=new Uk(r.gameObject),this.context.animations.registerAnimationMixer(C.mixer)),C.clips.push(l),C.mixer.uncacheAction(l),C.createHooks(c.asset,l);const d=C.mixer.clipAction(l);C.actions.push(d),C.models.push(c)}this._animationTracks.push(C)}}}else if(I.type===zo.Audio){if(!I.clips||I.clips.length<=0)continue;const n=new wc;n.director=this,n.track=I,n.audioSource=I.outputs.find(r=>r instanceof zi),this._audioTracks.push(n),A||(A=(i=this.context.mainCameraComponent)==null?void 0:i.gameObject.addNewComponent(MB)),n.listener=A.listener;for(let r=0;r<I.clips.length;r++){const a=I.clips[r];n.addModel(a)}}else if(I.type===zo.Marker){const n=new bf;if(n.director=this,n.track=I,I.markers)for(const r of I.markers)switch(r.type){case sv.Signal:n.models.push(r),n.didTrigger.push(!1);break}if(n!==null&&n.models.length>0){const r=sA.getComponent(this.gameObject,hd);r&&(n.receivers.push(r),this._signalTracks.push(n))}}else if(I.type===zo.Signal){const n=new bf;if(n.director=this,n.track=I,I.markers)for(const r of I.markers)n.models.push(r),n.didTrigger.push(!1);for(const r of I.outputs)n.receivers.push(r);this._signalTracks.push(n)}else if(I.type===zo.Control){const n=new fM;if(n.director=this,n.track=I,I.clips)for(const r of I.clips)n.models.push(r);n.resolveSourceObjects(this.context),this._controlTracks.push(n)}}}setAudioTracksAllowPlaying(A){for(const e of this._audioTracks)e.onAllowAudioChanged(A)}registerAnimationCallback(A){this.animationCallbackReceivers.push(A)}unregisterAnimationCallback(A){const e=this.animationCallbackReceivers.indexOf(A);e!==-1&&this.animationCallbackReceivers.splice(e,1)}},B(bN,"createTrackFunctions",{}),bN);let JB=VK;aj([D()],JB.prototype,"playOnAwake",2);aj([D()],JB.prototype,"extrapolationMode",2);const S0=Symbol("objectIsAnimatedData");function D2(g,A,e){if(!g)return;if(g[S0]===void 0){if(!e)return;g[S0]=new Set}const t=g[S0];e?t.add(A):t.has(A)&&t.delete(A)}function vEA(g){if(!g)return!1;const A=g[S0];return A!==void 0&&A.size>0}Et.registerCallback(Gt.ContextCreated,g=>{const A=g.context.domElement.getAttribute("autoplay");if(A!==void 0&&(A===""||A==="true"||A==="1")&&g.files)for(const e of g.files)sA.foreachComponent(e.file.scene,i=>{if(i.enabled!==!1){if(i instanceof _I&&i.playAutomatically||i instanceof hI||i instanceof JB&&i.playOnAwake===!0)return!0;if(i instanceof _I)return i.playAutomatically=!0,!0;if(i instanceof JB)return i.playOnAwake=!0,!0}},!0)!==!0&&vh.assignAnimationsFromFile(e.file,{createAnimationComponent:(i,I)=>qn(i,_I)})});class qEA{constructor(){B(this,"_context")}get context(){return this._context??be.Current}get isStateMachineBehaviour(){return!0}}class sp{constructor(A,e,t,i){B(this,"name");B(this,"nameHash");B(this,"normalizedTime");B(this,"length");B(this,"speed");B(this,"action");B(this,"hasTransitions");var I;this.name=A.name,this.nameHash=A.hash,this.normalizedTime=e,this.length=t,this.speed=i,this.action=A.motion.action||null,this.hasTransitions=((I=A.transitions)==null?void 0:I.length)>0||!1}}function Cj(g,A){return{name:"Empty",isLooping:!1,guid:(A==null?void 0:A.generateUUID())??ht.generateUUID(),index:-1,clip:new Qo(g,0,[])}}var tB=(g=>(g[g.If=1]="If",g[g.IfNot=2]="IfNot",g[g.Greater=3]="Greater",g[g.Less=4]="Less",g[g.Equals=6]="Equals",g[g.NotEqual=7]="NotEqual",g))(tB||{}),nv=(g=>(g[g.Float=1]="Float",g[g.Int=3]="Int",g[g.Bool=4]="Bool",g[g.Trigger=9]="Trigger",g))(nv||{});const xg=gA("debuganimatorcontroller"),dS=gA("debugrootmotion");class Bs{constructor(A){B(this,"_speed",1);B(this,"normalizedStartOffset",0);B(this,"animator");B(this,"model");B(this,"_mixer");B(this,"_activeState");B(this,"_activeStates",[]);B(this,"_heldActions",[]);B(this,"rootMotionHandler");this.model=A,xg&&console.log(this)}static createFromClips(A,e={looping:!1,autoTransition:!0,transitionDuration:0}){const t=[];for(let o=0;o<A.length;o++){const s=A[o],n=[];if(e.autoTransition!==!1){const a=e.transitionDuration??0,C=a/s.duration;let Q=o;(e.autoTransition===void 0||e.autoTransition===!0)&&(Q=(o+1)%A.length),n.push({exitTime:1-C,offset:0,duration:a,hasExitTime:!0,destinationState:Q,conditions:[]})}const r={name:s.name,hash:o,motion:{name:s.name,clip:s,isLooping:(e==null?void 0:e.looping)??!1},transitions:n,behaviours:[]};t.push(r)}const i={name:"AnimatorController",guid:new zg(Date.now()).generateUUID(),parameters:[],layers:[{name:"Base Layer",stateMachine:{defaultState:0,states:t}}]};return new Bs(i)}play(A,e=-1,t=Number.NEGATIVE_INFINITY,i=0){if(e<0)e=0;else if(e>=this.model.layers.length){console.warn("invalid layer");return}const o=this.model.layers[e].stateMachine;for(const s of o.states)if(s.name===A||s.hash===A){xg&&console.log("transition to ",s),this.transitionTo(s,i,t);return}console.warn("Could not find "+A+" to play")}reset(){this.setStartTransition()}setBool(A,e){var i,I;const t=typeof A=="string"?"name":"hash";return(I=(i=this.model)==null?void 0:i.parameters)==null?void 0:I.filter(o=>o[t]===A).forEach(o=>o.value=e)}getBool(A){var t,i,I;const e=typeof A=="string"?"name":"hash";return((I=(i=(t=this.model)==null?void 0:t.parameters)==null?void 0:i.find(o=>o[e]===A))==null?void 0:I.value)??!1}setFloat(A,e){var I,o;const t=typeof A=="string"?"name":"hash",i=(o=(I=this.model)==null?void 0:I.parameters)==null?void 0:o.filter(s=>s[t]===A);return i.forEach(s=>s.value=e),(i==null?void 0:i.length)>0}getFloat(A){var t,i,I;const e=typeof A=="string"?"name":"hash";return((I=(i=(t=this.model)==null?void 0:t.parameters)==null?void 0:i.find(o=>o[e]===A))==null?void 0:I.value)??0}setInteger(A,e){var i,I;const t=typeof A=="string"?"name":"hash";return(I=(i=this.model)==null?void 0:i.parameters)==null?void 0:I.filter(o=>o[t]===A).forEach(o=>o.value=e)}getInteger(A){var t,i,I;const e=typeof A=="string"?"name":"hash";return((I=(i=(t=this.model)==null?void 0:t.parameters)==null?void 0:i.find(o=>o[e]===A))==null?void 0:I.value)??0}setTrigger(A){var t,i;xg&&console.log("SET TRIGGER",A);const e=typeof A=="string"?"name":"hash";return(i=(t=this.model)==null?void 0:t.parameters)==null?void 0:i.filter(I=>I[e]===A).forEach(I=>I.value=!0)}resetTrigger(A){var t,i;const e=typeof A=="string"?"name":"hash";return(i=(t=this.model)==null?void 0:t.parameters)==null?void 0:i.filter(I=>I[e]===A).forEach(I=>I.value=!1)}getTrigger(A){var t,i,I;const e=typeof A=="string"?"name":"hash";return((I=(i=(t=this.model)==null?void 0:t.parameters)==null?void 0:i.find(o=>o[e]===A))==null?void 0:I.value)??!1}isInTransition(){return this._activeStates.length>1}setSpeed(A){this._speed=A}FindState(A){return this.findState(A)}findState(A){if(!A)return null;if(Array.isArray(this.model.layers)){for(const e of this.model.layers)for(const t of e.stateMachine.states)if(t.name===A||t.hash==A)return t}return null}getCurrentStateInfo(){if(!this._activeState)return null;const A=this._activeState.motion.action;if(!A)return null;const e=this._activeState.motion.clip.duration,t=e<=0?0:Math.abs(A.time/e);return new sp(this._activeState,t,e,this._speed)}get currentAction(){if(!this._activeState)return null;const A=this._activeState.motion.action;return A||null}get context(){var A;return(A=this.animator)==null?void 0:A.context}get mixer(){return this._mixer}dispose(){var A;if(this._mixer.stopAllAction(),this.animator){this._mixer.uncacheRoot(this.animator.gameObject);for(const e of this._activeStates)e.motion.clip&&this.mixer.uncacheAction(e.motion.clip,this.animator.gameObject)}(A=this.context)==null||A.animations.unregisterAnimationMixer(this._mixer)}bind(A){var e,t;A?this.animator!==A&&(this._mixer&&(this._mixer.stopAllAction(),(e=this.context)==null||e.animations.unregisterAnimationMixer(this._mixer)),this.animator=A,this._mixer=new Uk(this.animator.gameObject),(t=this.context)==null||t.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;xg&&console.warn("AnimatorController clone()",this.model);const A=cD(this.model,(t,i,I)=>I==null?!0:!(I.type==="Object3D"||I.isObject3D===!0||C3(I)||I.tracks!==void 0||I instanceof Bs));return console.assert(A!==this.model),new Bs(A)}update(A){var t,i;if(!this.animator)return;this.evaluateTransitions(),this.updateActiveStates(A);const e=this.animator.context.time.deltaTime;this.animator.applyRootMotion&&((t=this.rootMotionHandler)==null||t.onBeforeUpdate(A)),this._mixer.update(e),this.animator.applyRootMotion&&((i=this.rootMotionHandler)==null||i.onAfterUpdate(A))}get activeState(){return this._activeState}updateActiveStates(A){for(let e=0;e<this._activeStates.length;e++){const t=this._activeStates[e],i=t.motion;if(!i.action)this._activeStates.splice(e,1),e--;else{const I=i.action;I.weight=A,I.getEffectiveWeight()<=0&&!I.isRunning()&&(xg&&console.debug("REMOVE",t.name,I.getEffectiveWeight(),I.isRunning(),I.isScheduled()),this._activeStates.splice(e,1),e--)}}}setStartTransition(){var A;this.model.layers.length>1&&(xg||ae())&&console.warn("Multiple layers are not supported yet "+((A=this.animator)==null?void 0:A.name));for(const e of this.model.layers){const t=e.stateMachine;t.defaultState===void 0&&(xg&&console.warn("AnimatorController default state is undefined, will assign state 0 as default",e),t.defaultState=0);const i=t.states[t.defaultState];this.transitionTo(i,0,this.normalizedStartOffset);break}}evaluateTransitions(){var I;let A=!1;if(!this._activeState){if(this.setStartTransition(),!this._activeState)return;A=!0}const e=this._activeState,t=e.motion.action;for(const o of e.transitions){if(!o.hasExitTime&&o.conditions.length<=0)continue;let s=!0;for(const n of o.conditions)if(!this.evaluateCondition(n)){s=!1;break}if(s)if(t){const n=e.motion.clip.duration,r=n<=0?1:Math.abs(t.time/n);let a=o.exitTime;t.timeScale<0&&(a=1-a);let C=!1;if(o.hasExitTime?t.timeScale>0?C=r>=o.exitTime:t.timeScale<0&&(C=1-r>=o.exitTime):C=!0,C){for(const Q of o.conditions){const c=this.model.parameters.find(E=>E.name===Q.parameter);(c==null?void 0:c.type)===nv.Trigger&&c.value&&(c.value=!1)}if(t.clampWhenFinished=!0,xg){const Q=this.getState(o.destinationState,0);console.log(`Transition to ${o.destinationState} / ${Q==null?void 0:Q.name}`,o,`
5734
5734
  Timescale: `+t.timeScale,`
5735
5735
  Normalized time: `+r.toFixed(3),`
@@ -6212,7 +6212,7 @@ Texture:`,t),this.setLightmapDebugMaterial()):yl&&console.log("Use debuglightmap
6212
6212
  }
6213
6213
  `};class Kv extends Ke{constructor(A){super({type:"LineMaterial",uniforms:Ad.clone(CI.line.uniforms),vertexShader:CI.line.vertexShader,fragmentShader:CI.line.fragmentShader,clipping:!0}),this.isLineMaterial=!0,this.setValues(A)}get color(){return this.uniforms.diffuse.value}set color(A){this.uniforms.diffuse.value=A}get worldUnits(){return"WORLD_UNITS"in this.defines}set worldUnits(A){A===!0?this.defines.WORLD_UNITS="":delete this.defines.WORLD_UNITS}get linewidth(){return this.uniforms.linewidth.value}set linewidth(A){this.uniforms.linewidth&&(this.uniforms.linewidth.value=A)}get dashed(){return"USE_DASH"in this.defines}set dashed(A){A===!0!==this.dashed&&(this.needsUpdate=!0),A===!0?this.defines.USE_DASH="":delete this.defines.USE_DASH}get dashScale(){return this.uniforms.dashScale.value}set dashScale(A){this.uniforms.dashScale.value=A}get dashSize(){return this.uniforms.dashSize.value}set dashSize(A){this.uniforms.dashSize.value=A}get dashOffset(){return this.uniforms.dashOffset.value}set dashOffset(A){this.uniforms.dashOffset.value=A}get gapSize(){return this.uniforms.gapSize.value}set gapSize(A){this.uniforms.gapSize.value=A}get opacity(){return this.uniforms.opacity.value}set opacity(A){this.uniforms&&(this.uniforms.opacity.value=A)}get resolution(){return this.uniforms.resolution.value}set resolution(A){this.uniforms.resolution.value.copy(A)}get alphaToCoverage(){return"USE_ALPHA_TO_COVERAGE"in this.defines}set alphaToCoverage(A){this.defines&&(A===!0!==this.alphaToCoverage&&(this.needsUpdate=!0),A===!0?(this.defines.USE_ALPHA_TO_COVERAGE="",this.extensions.derivatives=!0):(delete this.defines.USE_ALPHA_TO_COVERAGE,this.extensions.derivatives=!1))}}const L2=new y,_2=new y,eI=new Ae,tI=new Ae,ir=new Ae,gN=new y,IN=new fA,rI=new Nk,T2=new y,kS=new Nt,MS=new Zi,gr=new Ae;let fr,Mc;function H2(g,A,e){return gr.set(0,0,-A,1).applyMatrix4(g.projectionMatrix),gr.multiplyScalar(1/gr.w),gr.x=Mc/e.width,gr.y=Mc/e.height,gr.applyMatrix4(g.projectionMatrixInverse),gr.multiplyScalar(1/gr.w),Math.abs(Math.max(gr.x,gr.y))}function UdA(g,A){const e=g.matrixWorld,t=g.geometry,i=t.attributes.instanceStart,I=t.attributes.instanceEnd,o=Math.min(t.instanceCount,i.count);for(let s=0,n=o;s<n;s++){rI.start.fromBufferAttribute(i,s),rI.end.fromBufferAttribute(I,s),rI.applyMatrix4(e);const r=new y,a=new y;fr.distanceSqToSegment(rI.start,rI.end,a,r),a.distanceTo(r)<Mc*.5&&A.push({point:a,pointOnLine:r,distance:fr.origin.distanceTo(a),object:g,face:null,faceIndex:s,uv:null,uv1:null})}}function NdA(g,A,e){const t=A.projectionMatrix,I=g.material.resolution,o=g.matrixWorld,s=g.geometry,n=s.attributes.instanceStart,r=s.attributes.instanceEnd,a=Math.min(s.instanceCount,n.count),C=-A.near;fr.at(1,ir),ir.w=1,ir.applyMatrix4(A.matrixWorldInverse),ir.applyMatrix4(t),ir.multiplyScalar(1/ir.w),ir.x*=I.x/2,ir.y*=I.y/2,ir.z=0,gN.copy(ir),IN.multiplyMatrices(A.matrixWorldInverse,o);for(let Q=0,c=a;Q<c;Q++){if(eI.fromBufferAttribute(n,Q),tI.fromBufferAttribute(r,Q),eI.w=1,tI.w=1,eI.applyMatrix4(IN),tI.applyMatrix4(IN),eI.z>C&&tI.z>C)continue;if(eI.z>C){const u=eI.z-tI.z,f=(eI.z-C)/u;eI.lerp(tI,f)}else if(tI.z>C){const u=tI.z-eI.z,f=(tI.z-C)/u;tI.lerp(eI,f)}eI.applyMatrix4(t),tI.applyMatrix4(t),eI.multiplyScalar(1/eI.w),tI.multiplyScalar(1/tI.w),eI.x*=I.x/2,eI.y*=I.y/2,tI.x*=I.x/2,tI.y*=I.y/2,rI.start.copy(eI),rI.start.z=0,rI.end.copy(tI),rI.end.z=0;const h=rI.closestPointToPointParameter(gN,!0);rI.at(h,T2);const l=ht.lerp(eI.z,tI.z,h),d=l>=-1&&l<=1,p=gN.distanceTo(T2)<Mc*.5;if(d&&p){rI.start.fromBufferAttribute(n,Q),rI.end.fromBufferAttribute(r,Q),rI.start.applyMatrix4(o),rI.end.applyMatrix4(o);const u=new y,f=new y;fr.distanceSqToSegment(rI.start,rI.end,f,u),e.push({point:f,pointOnLine:u,distance:fr.origin.distanceTo(f),object:g,face:null,faceIndex:Q,uv:null,uv1:null})}}}class FdA extends hA{constructor(A=new qj,e=new Kv({color:Math.random()*16777215})){super(A,e),this.isLineSegments2=!0,this.type="LineSegments2"}computeLineDistances(){const A=this.geometry,e=A.attributes.instanceStart,t=A.attributes.instanceEnd,i=new Float32Array(2*e.count);for(let o=0,s=0,n=e.count;o<n;o++,s+=2)L2.fromBufferAttribute(e,o),_2.fromBufferAttribute(t,o),i[s]=s===0?0:i[s-1],i[s+1]=i[s]+L2.distanceTo(_2);const I=new P0(i,2,1);return A.setAttribute("instanceDistanceStart",new gs(I,1,0)),A.setAttribute("instanceDistanceEnd",new gs(I,1,1)),this}raycast(A,e){const t=this.material.worldUnits,i=A.camera;i===null&&!t&&console.error('LineSegments2: "Raycaster.camera" needs to be set in order to raycast against LineSegments2 while worldUnits is set to false.');const I=A.params.Line2!==void 0&&A.params.Line2.threshold||0;fr=A.ray;const o=this.matrixWorld,s=this.geometry,n=this.material;Mc=n.linewidth+I,s.boundingSphere===null&&s.computeBoundingSphere(),MS.copy(s.boundingSphere).applyMatrix4(o);let r;if(t)r=Mc*.5;else{const C=Math.max(i.near,MS.distanceToPoint(fr.origin));r=H2(i,C,n.resolution)}if(MS.radius+=r,fr.intersectsSphere(MS)===!1)return;s.boundingBox===null&&s.computeBoundingBox(),kS.copy(s.boundingBox).applyMatrix4(o);let a;if(t)a=Mc*.5;else{const C=Math.max(i.near,kS.distanceToPoint(fr.origin));a=H2(i,C,n.resolution)}kS.expandByScalar(a),fr.intersectsBox(kS)!==!1&&(t?UdA(this,e):NdA(this,i,e))}}class Lj extends qj{constructor(){super(),this.isLineGeometry=!0,this.type="LineGeometry"}setPositions(A){const e=A.length-3,t=new Float32Array(2*e);for(let i=0;i<e;i+=3)t[2*i]=A[i],t[2*i+1]=A[i+1],t[2*i+2]=A[i+2],t[2*i+3]=A[i+3],t[2*i+4]=A[i+4],t[2*i+5]=A[i+5];return super.setPositions(t),this}setColors(A){const e=A.length-3,t=new Float32Array(2*e);for(let i=0;i<e;i+=3)t[2*i]=A[i],t[2*i+1]=A[i+1],t[2*i+2]=A[i+2],t[2*i+3]=A[i+3],t[2*i+4]=A[i+4],t[2*i+5]=A[i+5];return super.setColors(t),this}fromLine(A){const e=A.geometry;return this.setPositions(e.attributes.position.array),this}}class KdA extends FdA{constructor(A=new Lj,e=new Kv({color:Math.random()*16777215})){super(A,e),this.isLine2=!0,this.type="Line2"}}class NM extends FA{}var bdA=Object.defineProperty,JdA=Object.getOwnPropertyDescriptor,dE=(g,A,e,t)=>{for(var i=t>1?void 0:t?JdA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&bdA(A,e,i),i};const Y2=gA("debugwebxr");class $s extends FA{constructor(){super(...arguments);B(this,"movementSpeed",1.5);B(this,"rotationStep",30);B(this,"useTeleport",!0);B(this,"useTeleportTarget",!1);B(this,"useTeleportFade",!1);B(this,"showRays",!0);B(this,"showHits",!1);B(this,"isXRMovementHandler",!0);B(this,"xrSessionMode","immersive-vr");B(this,"_didApplyRotation",!1);B(this,"_didTeleport",!1);B(this,"_plane",null);B(this,"_lines",[]);B(this,"_hitDiscs",[]);B(this,"_hitDistances",[]);B(this,"hitPointRaycastFilter",e=>e.type==="SkinnedMesh"?"continue in children":!0)}onUpdateXR(e){const t=e.xr.rig;if(!(t!=null&&t.gameObject)||e.xr.isPassThrough)return;const i=e.xr.leftController,I=e.xr.rightController;i&&this.onHandleMovement(i,t.gameObject),I&&(this.onHandleRotation(I,t.gameObject),this.useTeleport&&this.onHandleTeleport(I,t.gameObject))}onLeaveXR(e){for(const t of this._lines)t.removeFromParent();for(const t of this._hitDiscs)t==null||t.removeFromParent()}onBeforeRender(){var e;(e=this.context.xr)!=null&&e.running&&(this.showRays&&this.renderRays(this.context.xr),this.showHits&&this.renderHits(this.context.xr))}onHandleMovement(e,t){const i=e.getStick("xr-standard-thumbstick"),I=new y(i.x,0,i.y);I.multiplyScalar(this.context.time.deltaTimeUnscaled*this.movementSpeed);const o=ii(t);I.multiplyScalar(o.x),I.applyQuaternion(e.xr.poseOrientation),I.y=0,I.applyQuaternion(t.worldQuaternion),t.position.add(I),t.updateMatrixWorld()}onHandleRotation(e,t){const I=e.getStick("xr-standard-thumbstick").x;if(this._didApplyRotation)Math.abs(I)<.3&&(this._didApplyRotation=!1);else if(Math.abs(I)>.5){this._didApplyRotation=!0;const o=I>0?1:-1;t.rotateY(o*ge.toRadians(this.rotationStep))}}onHandleTeleport(e,t){var I;const i=e.getStick("xr-standard-thumbstick");if(this._didTeleport)i.y<.2&&(this._didTeleport=!1);else if(i.y>.8){this._didTeleport=!0;const o=this.context.physics.raycastFromRay(e.ray)[0];let s=o==null?void 0:o.point;if(!s){this._plane||(this._plane=new xI(new y(0,1,0),0));const n=t.worldPosition;this._plane.setFromNormalAndCoplanarPoint(new y(0,1,0),n);const r=e.ray;s=n.clone(),this._plane.intersectLine(new Nk(r.origin,dt(r.direction).multiplyScalar(1e4).add(r.origin)),s),s.distanceTo(n)>t.scale.x*10&&(s=null)}if(s){if(this.useTeleportTarget&&!sA.getComponentInParent(o.object,NM))return;Y2&&fe.DrawSphere(s,.025,16711680,5);const n=s.clone();this.useTeleportFade?(I=e.xr.fadeTransition())==null||I.then(()=>{t.worldPosition=n}):t.worldPosition=n}}}renderRays(e){for(let t=0;t<this._lines.length;t++){const i=this._lines[t];i&&(i.visible=!1)}for(let t=0;t<e.controllers.length;t++){const i=e.controllers[t];let I=this._lines[t];if(!i.connected||!i.isTracking||!i.ray||i.targetRayMode==="transient-pointer"||!i.hasSelectEvent){I&&(I.visible=!1);continue}I||(I=this.createRayLineObject(),I.scale.z=.5,this._lines[t]=I),i.updateRayWorldPosition(),i.updateRayWorldQuaternion();const o=i.rayWorldPosition,s=i.rayWorldQuaternion;I.position.copy(o),I.quaternion.copy(s);const n=e.rigScale,r=this._hitDistances[t]??n;I.scale.set(n,n,r),I.visible=!0,I.layers.disableAll(),I.layers.enable(2),I.parent!==this.context.scene&&this.context.scene.add(I)}}renderHits(e){for(const t of this._hitDiscs){if(!t)continue;const i=t.controller;if(!i||!i.connected||!i.isTracking){t.visible=!1;continue}}for(let t=0;t<e.controllers.length;t++){const i=e.controllers[t];if(!i.connected||!i.isTracking||!i.ray||!i.hasSelectEvent)continue;const I=this.context.time.smoothedFps>=59?1:10;if((this.context.time.frame+i.index)%I!==0){const n=this._hitDiscs[t];n&&n.hit&&(n.visible=!0,this.hitPointerSetPosition(i,n,n.hit.distance));continue}const o=this.context.physics.raycastFromRay(i.ray,{testObject:this.hitPointRaycastFilter})[0];this._hitDistances[t]=o==null?void 0:o.distance;let s=this._hitDiscs[t];if(s&&(s.controller=i,s.hit=o),o){const n=e.rigScale??1;Y2&&(fe.DrawWireSphere(o.point,.025*n,16711680),fe.DrawLabel(dt(0,.2,0).add(o.point),o.object.name,.02,0)),s||(s=this.createHitPointObject(),this._hitDiscs[t]=s),s.visible=!0;const r=.01*(n+o.distance);if(s.scale.set(r,r,r),s.layers.disableAll(),s.layers.enable(2),s.hit=o,o.normal){this.hitPointerSetPosition(i,s,o.distance);const a=o.normal.applyQuaternion(Jt(o.object));s.quaternion.setFromUnitVectors(xdA,a)}else this.hitPointerSetPosition(i,s,o.distance);s.parent!==this.context.scene&&this.context.scene.add(s)}else this._hitDiscs[t]&&(this._hitDiscs[t].visible=!1)}}hitPointerSetPosition(e,t,i){t.position.copy(e.rayWorldPosition),t.position.add(dt(0,0,i-.01).applyQuaternion(e.rayWorldQuaternion))}createHitPointObject(){var e=new DA;const t=new hA(new gn(.3,6,6),new ot({color:15658734,opacity:.7,transparent:!0,depthTest:!1,side:kt}));return t.layers.disableAll(),t.layers.enable(2),e.add(t),e}createRayLineObject(){const e=new KdA;e.layers.disableAll(),e.layers.enable(2);const t=new Lj;e.geometry=t;const i=new Float32Array(9);i.set([0,0,.02,0,0,.4,0,0,1]),t.setPositions(i);const I=new Float32Array(9);I.set([1,1,1,.1,.1,.1,0,0,0]),t.setColors(I);const o=new Kv({color:16777215,vertexColors:!0,worldUnits:!0,linewidth:.004,transparent:!0,blending:Rc,dashed:!1,alphaToCoverage:!0});return e.material=o,e}}dE([D()],$s.prototype,"movementSpeed",2);dE([D()],$s.prototype,"rotationStep",2);dE([D()],$s.prototype,"useTeleport",2);dE([D()],$s.prototype,"useTeleportTarget",2);dE([D()],$s.prototype,"useTeleportFade",2);dE([D()],$s.prototype,"showRays",2);dE([D()],$s.prototype,"showHits",2);const xdA=new y(0,1,0);var vdA=Object.defineProperty,qdA=Object.getOwnPropertyDescriptor,Lo=(g,A,e,t)=>{for(var i=t>1?void 0:t?qdA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&vdA(A,e,i),i};const Fu=gA("debugwebxr"),LdA=gA("debugusdz");class Xg extends FA{constructor(){super(...arguments);B(this,"createVRButton",!0);B(this,"createARButton",!0);B(this,"createSendToQuestButton",!0);B(this,"createQRCode",!0);B(this,"useDefaultControls",!0);B(this,"showControllerModels",!0);B(this,"showHandModels",!0);B(this,"usePlacementReticle",!0);B(this,"usePlacementAdjustment",!0);B(this,"arSceneScale",1);B(this,"useXRAnchor",!1);B(this,"useQuicklookExport",!1);B(this,"useDepthSensing",!1);B(this,"defaultAvatar");B(this,"_playerSync");B(this,"_createdComponentsInSession",[]);B(this,"_usdzExporter");B(this,"_previousXRState",0);B(this,"onAvatarSpawned",e=>{Fu&&console.log("WebXR.onAvatarSpawned",e),sA.getComponentInChildren(e,xB)??(t=sA.addComponent(e,xB))});B(this,"_buttonFactory");B(this,"_buttons",[])}awake(){ye.getXRSync(this.context)}onEnable(){var e,t;window.location.protocol!=="https:"&&Ot('<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&&(sA.findObjectOfType(ji)||(Fu&&console.log("WebXR: Adding USDZExporter"),this._usdzExporter=sA.addComponent(this.gameObject,ji),this._usdzExporter.objectToExport=this.context.scene,this._usdzExporter.autoExportAnimations=!0,this._usdzExporter.autoExportAudioSources=!0)),this.handleCreatingHTML(),this.handleOfferSession(),this.defaultAvatar||(Fu&&console.warn("WebXR: No default avatar set, using static default avatar"),this.defaultAvatar=new et("https://cdn.needle.tools/static/avatars/DefaultAvatar.glb")),this.defaultAvatar&&(this._playerSync=this.gameObject.getOrAddComponent(dd),this._playerSync.autoSync=!1),this._playerSync&&(this._playerSync.asset=this.defaultAvatar,(e=this._playerSync.onPlayerSpawned)==null||e.removeEventListener(this.onAvatarSpawned),(t=this._playerSync.onPlayerSpawned)==null||t.addEventListener(this.onAvatarSpawned))}onDisable(){var e;(e=this._usdzExporter)==null||e.destroy(),this.removeButtons()}async handleOfferSession(){return this.createVRButton&&await ye.isVRSupported()&&this.createVRButton?ye.offerSession("immersive-vr","default",this.context):this.createARButton&&await ye.isARSupported()&&this.createARButton?ye.offerSession("immersive-ar","default",this.context):!1}get session(){return ye.active??null}get sessionMode(){return ye.activeMode??null}async enterVR(e){return ye.start("immersive-vr",e,this.context)}async enterAR(e){return ye.start("immersive-ar",e,this.context)}exitXR(){ye.stop()}onBeforeXR(e,t){e=="immersive-ar"&&this.useDepthSensing&&(t.optionalFeatures=t.optionalFeatures||[],t.optionalFeatures.push("depth-sensing"))}async onEnterXR(e){Fu&&console.log("WebXR onEnterXR"),this._previousXRState=BI.Global.Mask;const t=e.xr.isVR;if(BI.Global.Set(t?pr.VR:pr.AR),this.usePlacementReticle&&e.xr.isAR){let I=sA.findObjectOfType(ho);if(I)Fu&&console.log("WebXR: WebARSessionRoot already exists, not creating a new one");else{const o=new DA;for(const s of this.context.scene.children)o.add(s);this.context.scene.add(o),I=sA.addComponent(o,ho),this._createdComponentsInSession.push(I),I.arScale=this.arSceneScale,I.arTouchTransform=this.usePlacementAdjustment,I.useXRAnchor=this.useXRAnchor}}this.useDefaultControls&&this.setDefaultMovementEnabled(!0),(this.showControllerModels||this.showHandModels)&&this.setDefaultControllerRenderingEnabled(!0);let i=sA.findObjectOfType(Ff);i||(i=this.gameObject.addNewComponent(Ff)),this.createLocalAvatar(e.xr)}onLeaveXR(e){var t;BI.Global.Set(this._previousXRState),(t=this._playerSync)==null||t.destroyInstance();for(const i of this._createdComponentsInSession)i.destroy();this._createdComponentsInSession.length=0,this.handleOfferSession()}setDefaultMovementEnabled(e){let t=this.gameObject.getComponent($s);return!t&&e&&(t=this.gameObject.addComponent($s),this._createdComponentsInSession.push(t)),t&&(t.enabled=e),t}setDefaultControllerRenderingEnabled(e){let t=this.gameObject.getComponent(Lr);return!t&&e&&(t=this.gameObject.addComponent(Lr),this._createdComponentsInSession.push(t),t.createControllerModel=this.showControllerModels,t.createHandModel==this.showHandModels),t&&(t.enabled=e),t}async createLocalAvatar(e){this._playerSync&&e.running&&(this._playerSync.asset=this.defaultAvatar,await this._playerSync.getInstance())}getButtonsContainer(){return this.getButtonsFactory()}getButtonsFactory(){return this._buttonFactory||(this._buttonFactory=$a.getOrCreate()),this._buttonFactory}handleCreatingHTML(){if(this.createARButton||this.createVRButton||this.useQuicklookExport){if((Lc()&&Ch()||LdA)&&this.useQuicklookExport){const t=sA.findObjectOfType(ji);if(!t||t&&t.allowCreateQuicklookButton){const i=this.getButtonsFactory().createQuicklookButton();this.addButton(i,50)}}if(this.createARButton){const t=this.getButtonsFactory().createARButton();this.addButton(t,50)}if(this.createVRButton){const t=this.getButtonsFactory().createVRButton();this.addButton(t,50)}}if(this.createSendToQuestButton&&!bk()&&ye.isVRSupported().then(t=>{if(!t){const i=this.getButtonsFactory().createSendToQuestButton();this.addButton(i,50)}}),this.createQRCode&&!In()){const t=QM(zr);t&&t.createQRCodeButton===!1?ae()&&console.warn("WebXR: QRCode button is disabled in the Needle Menu component"):ye.isXRSupported().then(i=>{if(qc()||!i){const I=bn.getOrCreate().createQRCode();this.addButton(I,50)}})}}addButton(e,t){this._buttons.push(e),e.setAttribute("priority",t.toString()),this.context.menu.appendChild(e)}removeButtons(){for(const e of this._buttons)e.remove();this._buttons.length=0}}Lo([D()],Xg.prototype,"createVRButton",2);Lo([D()],Xg.prototype,"createARButton",2);Lo([D()],Xg.prototype,"createSendToQuestButton",2);Lo([D()],Xg.prototype,"createQRCode",2);Lo([D()],Xg.prototype,"useDefaultControls",2);Lo([D()],Xg.prototype,"showControllerModels",2);Lo([D()],Xg.prototype,"showHandModels",2);Lo([D()],Xg.prototype,"usePlacementReticle",2);Lo([D()],Xg.prototype,"usePlacementAdjustment",2);Lo([D()],Xg.prototype,"arSceneScale",2);Lo([D()],Xg.prototype,"useXRAnchor",2);Lo([D()],Xg.prototype,"useQuicklookExport",2);Lo([D()],Xg.prototype,"useDepthSensing",2);Lo([D(et)],Xg.prototype,"defaultAvatar",2);class FM{get extensionName(){return"Physics"}onExportObject(A,e,t){const i=sA.getComponents(A,Pt).filter(n=>n.enabled),I=sA.getComponents(A,ls).filter(n=>n.enabled&&!n.isTrigger);let o=i.length>0?i[0]:null;const s=I.length>0?I[0]:null;s&&!o&&(o=new Pt,o.isKinematic=!0),o&&e.addEventListener("serialize",(n,r)=>{var a,C,Q;if(o){if(n.appendLine(),n.beginBlock('def RealityKitComponent "RigidBody"',"{",!0),o.useGravity||n.appendLine("bool gravityEnabled = 0"),n.appendLine('uniform token info:id = "RealityKit.RigidBody"'),o.isKinematic&&n.appendLine('token motionType = "Kinematic"'),n.beginBlock('def RealityKitStruct "massFrame"',"{",!0),n.appendLine(`float m_mass = ${o.mass}`),n.beginBlock('def RealityKitStruct "m_pose"',"{",!0),n.appendLine(`float3 position = (${o.centerOfMass.x}, ${o.centerOfMass.y}, ${o.centerOfMass.z})`),n.closeBlock("}"),n.closeBlock("}"),I.length>0){const c=I[0];n.beginBlock('def RealityKitStruct "material"',"{",!0);const E=c.sharedMaterial;E&&E.dynamicFriction!==void 0&&n.appendLine(`double dynamicFriction = ${(a=c.sharedMaterial)==null?void 0:a.dynamicFriction}`),E&&E.bounciness!==void 0&&n.appendLine(`double restitution = ${(C=c.sharedMaterial)==null?void 0:C.bounciness}`),E&&E.staticFriction!==void 0&&n.appendLine(`double staticFriction = ${(Q=c.sharedMaterial)==null?void 0:Q.staticFriction}`),n.closeBlock("}")}n.closeBlock("}")}}),s&&(e.addEventListener("serialize",(n,r)=>{var Q;n.beginBlock('def RealityKitComponent "Collider"',"{",!0),n.appendLine("uint group = 1"),n.appendLine('uniform token info:id = "RealityKit.Collider"'),n.appendLine("uint mask = 4294967295");const C=s.isTrigger?"Trigger":"Default";if(n.appendLine(`token type = "${C}"`),n.beginBlock('def RealityKitStruct "Shape"',"{",!0),s instanceof fd){const c=s;n.appendLine('token shapeType = "Sphere"'),n.appendLine(`float radius = ${c.radius}`)}else if(s instanceof Dd){const c=s;n.appendLine('token shapeType = "Box"'),n.appendLine(`float3 extent = (${c.size.x}, ${c.size.y}, ${c.size.z})`)}else if(s instanceof iC){const c=s;n.appendLine('token shapeType = "Capsule"'),n.appendLine(`float radius = ${c.radius}`),n.appendLine(`float height = ${c.height}`)}else if(s instanceof CE&&((Q=s.sharedMesh)!=null&&Q.geometry)){const c=s.sharedMesh.geometry;c.boundingBox||c.computeBoundingBox();const E=s.sharedMesh.geometry.boundingBox;E&&(n.appendLine('token shapeType = "Box"'),n.appendLine(`float3 extent = (${E.max.x-E.min.x}, ${E.max.y-E.min.y}, ${E.max.z-E.min.z})`),console.log("[USDZ] Only Box, Sphere, and Capsule colliders are supported in visionOS/iOS. MeshCollider will be exported as Box",s))}else console.warn("[USDZ] Only Box, Sphere, and Capsule colliders are supported in visionOS/iOS. Ignoring collider:",s);n.beginBlock('def RealityKitStruct "pose"',"{",!0),n.closeBlock("}"),n.closeBlock("}"),n.closeBlock("}")}),I.length>1&&console.log("WARNING: Multiple colliders detected. visionOS / iOS can only support objects with a single collider, only exporting the first collider: ",s))}}var _dA=Object.defineProperty,TdA=Object.getOwnPropertyDescriptor,EC=(g,A,e,t)=>{for(var i=t>1?void 0:t?TdA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&_dA(A,e,i),i};const bQ=gA("debugtext");var yg=(g=>(g[g.UpperLeft=0]="UpperLeft",g[g.UpperCenter=1]="UpperCenter",g[g.UpperRight=2]="UpperRight",g[g.MiddleLeft=3]="MiddleLeft",g[g.MiddleCenter=4]="MiddleCenter",g[g.MiddleRight=5]="MiddleRight",g[g.LowerLeft=6]="LowerLeft",g[g.LowerCenter=7]="LowerCenter",g[g.LowerRight=8]="LowerRight",g))(yg||{}),_j=(g=>(g[g.Normal=0]="Normal",g[g.Bold=1]="Bold",g[g.Italic=2]="Italic",g[g.BoldAndItalic=3]="BoldAndItalic",g))(_j||{});class WI extends QE{constructor(){super(...arguments);B(this,"alignment",0);B(this,"verticalOverflow",0);B(this,"horizontalOverflow",0);B(this,"lineSpacing",1);B(this,"supportRichText",!1);B(this,"font");B(this,"fontStyle",0);B(this,"sRGBTextColor",new yA(1,0,1));B(this,"_text","");B(this,"_fontSize",12);B(this,"_textMeshUi",null);B(this,"_didHandleTextRenderOnTop",!1)}setAlphaFactor(e){var t;super.setAlphaFactor(e),(t=this.uiObject)==null||t.set({fontOpacity:this.color.alpha*this.alphaFactor}),this.markDirty()}get text(){return this._text}set text(e){e!==this._text&&(this._text=e,this.feedText(this.text,this.supportRichText),this.markDirty())}set_text(e){this.text=e}get fontSize(){return this._fontSize}set fontSize(e){var t;this._fontSize=e,(t=this.uiObject)==null||t.set({fontSize:e})}onColorChanged(){var e;this.sRGBTextColor.copy(this.color),this.sRGBTextColor.convertLinearToSRGB(),(e=this.uiObject)==null||e.set({color:this.sRGBTextColor,fontOpacity:this.color.alpha})}onParentRectTransformChanged(){super.onParentRectTransformChanged(),this.uiObject&&this.updateOverflow()}onBeforeCanvasRender(e){this.updateOverflow()}updateOverflow(){var t;const e=(t=this.uiObject)==null?void 0:t._overflow;e&&(e._needsUpdate=!0,this.markDirty())}onCreate(e){bQ&&console.log(this),this.horizontalOverflow==1&&(e.whiteSpace="pre"),this.verticalOverflow==0&&(this.context.renderer.localClippingEnabled=!0,e.overflow="hidden"),this.horizontalOverflow==1&&this.verticalOverflow==0,e.lineHeight=this.lineSpacing,delete e.backgroundOpacity,delete e.backgroundColor,bQ&&(e.backgroundColor=16750848,e.backgroundOpacity=.5);const t=this.rectTransform;e={...e,...this.getTextOpts()},this.getAlignment(e),bQ&&(e.backgroundColor=Math.random()*16777215,e.backgroundOpacity=.1),this.uiObject=t.createNewText(e),this.feedText(this.text,this.supportRichText)}onAfterAddedToScene(){super.onAfterAddedToScene(),this.handleTextRenderOnTop()}getTextOpts(){const e=this.fontSize,t={color:this.color,fontOpacity:this.color.alpha,fontSize:e,fontKerning:"normal"};return this.setFont(t,this.fontStyle),t}onEnable(){var e;super.onEnable(),this._didHandleTextRenderOnTop=!1,this.uiObject&&this.uiObject.addAfterUpdate(()=>{this.setShadowComponentOwner(this.uiObject),this.markDirty()}),setTimeout(()=>this.markDirty(),10),(e=this.canvas)==null||e.registerEventReceiver(this)}onDisable(){var e;super.onDisable(),(e=this.canvas)==null||e.unregisterEventReceiver(this)}getAlignment(e){switch(e.flexDirection="column",this.alignment){case 0:case 3:case 6:e.textAlign="left";break;case 1:case 4:case 7:e.textAlign="center";break;case 2:case 5:case 8:e.textAlign="right";break}switch(this.alignment){default:case 0:case 1:case 2:e.alignItems="start";break;case 3:case 4:case 5:e.alignItems="center";break;case 6:case 7:case 8:e.alignItems="end";break}return e}feedText(e,t){var i,I,o;if(bQ&&console.log("feedText",this.uiObject,e,t),!!this.uiObject)if(this._textMeshUi||(this._textMeshUi=[]),this.uiObject.children.length=0,!t||e.length===0)this.uiObject.textContent=e;else{let s=this.getNextTag(e);if(s){if(s.startIndex>0){for(let a=this.uiObject.children.length-1;a>=0;a--){const C=this.uiObject.children[a];C.isUI&&(this.uiObject.remove(C),C.clear())}const r=new i0({textContent:e.substring(0,s.startIndex),color:"inherit"});this.uiObject.add(r)}}else{this.uiObject.textContent="",this.setOptions({textContent:e});return}const n=[];for(;s;){const r=this.getNextTag(e,s.endIndex),a={fontFamily:(i=this.uiObject)==null?void 0:i.get("fontFamily"),color:"inherit",textContent:""};if(r){a.textContent=this.getText(e,s,r),this.handleTag(s,a,n);const C=new i0(a);(I=this.uiObject)==null||I.add(C)}else{a.textContent=e.substring(s.endIndex),this.handleTag(s,a,n);const C=new i0(a);(o=this.uiObject)==null||o.add(C)}s=r}}}handleTextRenderOnTop(){this._didHandleTextRenderOnTop||(this._didHandleTextRenderOnTop=!0,this.startCoroutine(this.renderOnTopCoroutine()))}*renderOnTopCoroutine(){if(!this.canvas)return;const e=[],t=this.canvas,i={renderOnTop:t.renderOnTop,depthWrite:t.depthWrite,doubleSided:t.doubleSided};for(;;){let I=!1;if(this._textMeshUi)for(let o=0;o<this._textMeshUi.length;o++){if(e[o]===!0)continue;I=!0;const s=this._textMeshUi[o];s.textContent&&(ym(s,i),e[o]=!0)}if(!I)break;yield}}handleTag(e,t,i){if(!e.isEndTag){if(e.type.includes("color")){const I=new oN(e,{color:t.color});if(i.push(I),e.type.length>6){const o=parseInt("0x"+e.type.substring(7));t.color=o}else t.color=new yA(1,1,1)}else if(e.type=="b"){this.setFont(t,1);const I=new oN(e,{fontWeight:700});i.push(I)}else if(e.type=="i"){this.setFont(t,2);const I=new oN(e,{fontStyle:"italic"});i.push(I)}}}getText(e,t,i){return e.substring(t.endIndex,i.startIndex)}getNextTag(e,t=0){const i=e.indexOf("<",t),I=e.indexOf(">",i);if(i>=0&&I>=0){const o=e.substring(i+1,I);return{type:o,startIndex:i,endIndex:I+1,isEndTag:o.startsWith("/")}}return null}setFont(e,t){if(!this.font)return;const i=this.font,I=this.getFamilyNameWithCorrectSuffix(i,t);bQ&&console.log("Selected font family:"+I);let o=_F.getFontFamily(I);switch(o||(o=_F.addFontFamily(I)),e.fontFamily=o,t){default:case 0:e.fontWeight=400,e.fontStyle="normal";break;case 1:e.fontWeight=700,e.fontStyle="normal";break;case 2:e.fontWeight=400,e.fontStyle="italic";break;case 3:e.fontStyle="italic",e.fontWeight=400}let s=o.getVariant(e.fontWeight,e.fontStyle);if(!s){let n=I;n!=null&&n.endsWith("-msdf.json")||(n+="-msdf.json");let r=I;r!=null&&r.endsWith(".png")||(r+=".png"),s=o.addVariant(e.fontWeight,e.fontStyle,n,r),s==null||s.addEventListener("ready",()=>{this.markDirty()})}}getFamilyNameWithCorrectSuffix(e,t){var a;const i=e.lastIndexOf("-");if(i<0)return e;const I=(a=e.substring(i+1))==null?void 0:a.toLowerCase();if(HdA.includes(I))return bQ&&console.warn("Unsupported font style: "+I),e;const o=e.lastIndexOf("/");let s=e;o>=0&&(s=s.substring(o+1));const n=s[0]===s[0].toUpperCase(),r=e.substring(0,i);switch(bQ&&console.log("Select font: ",e,_j[t],s,n,r),t){case 0:return n?r+"-Regular":r+"-regular";case 1:return n?r+"-Bold":r+"-bold";case 2:return n?r+"-Italic":r+"-italic";case 3:return n?r+"-BoldItalic":r+"-bolditalic";default:return e}}}EC([D()],WI.prototype,"alignment",2);EC([D()],WI.prototype,"verticalOverflow",2);EC([D()],WI.prototype,"horizontalOverflow",2);EC([D()],WI.prototype,"lineSpacing",2);EC([D()],WI.prototype,"supportRichText",2);EC([D(URL)],WI.prototype,"font",2);EC([D()],WI.prototype,"fontStyle",2);EC([D()],WI.prototype,"text",1);EC([D()],WI.prototype,"fontSize",1);class oN{constructor(A,e){B(this,"tag");B(this,"previousValues");this.tag=A,this.previousValues=e}}const HdA=["medium","mediumitalic","black","blackitalic","thin","thinitalic","extrabold","light","lightitalic","semibold"];class EB{constructor(A){B(this,"id");B(this,"content","");B(this,"font",[]);B(this,"pointSize",144);B(this,"width");B(this,"height");B(this,"depth");B(this,"wrapMode");B(this,"horizontalAlignment");B(this,"verticalAlignment");B(this,"material");this.id=A}static getId(){return this.global_id++}setDepth(A){return this.depth=A,this}setPointSize(A){return this.pointSize=A,this}setHorizontalAlignment(A){return this.horizontalAlignment=A,this}setVerticalAlignment(A){return this.verticalAlignment=A,this}writeTo(A,e){var i;e.beginBlock(`def Preliminary_Text "${this.id}"`,"(",!1),e.appendLine('prepend apiSchemas = ["MaterialBindingAPI"]'),e.closeBlock(")"),e.beginBlock(),this.content&&e.appendLine(`string content = "${this.content}"`),(!this.font||this.font.length<=0)&&(this.font||(this.font=[]),(i=this.font)==null||i.push("sans-serif"));const t=this.font.map(I=>`"${I}"`).join(", ");e.appendLine(`string[] font = [ ${t} ]`),e.appendLine(`double pointSize = ${this.pointSize}`),typeof this.width=="number"&&e.appendLine(`double width = ${this.width}`),typeof this.height=="number"&&e.appendLine(`double height = ${this.height}`),typeof this.depth=="number"&&e.appendLine(`double depth = ${this.depth}`),this.wrapMode&&e.appendLine(`token wrapMode = "${this.wrapMode}"`),this.horizontalAlignment&&e.appendLine(`token horizontalAlignment = "${this.horizontalAlignment}"`),this.verticalAlignment&&e.appendLine(`token verticalAlignment = "${this.verticalAlignment}"`),this.material!==void 0&&e.appendLine(`rel material:binding = </StageRoot/Materials/${wx(this.material)}>`),e.closeBlock()}}B(EB,"global_id",0);class KM{static singleLine(A,e,t){const i=new EB("text_"+EB.getId());return i.content=A,e&&(i.pointSize=e),t&&(i.depth=t),i}static multiLine(A,e,t,i,I,o){const s=new EB("text_"+EB.getId());return s.content=A,s.width=e,s.height=t,s.horizontalAlignment=i,s.verticalAlignment=I,o!==void 0&&(s.wrapMode=o),s}}const YdA=new fA().makeRotationY(Math.PI),OdA=new fA().makeScale(-1,1,-1);class Ay{get extensionName(){return"text"}exportText(A,e,t){const i=sA.getComponent(A,WI);if(!i)return;const I=sA.getComponent(A,OI);let o=100,s=100;I&&(o=I.width,s=I.height),e.matrix=YdA.clone(),I&&e.matrix.premultiply(OdA);const n=i.color.clone();e.material=new LI({color:n,emissive:n}),e.addEventListener("serialize",(r,a)=>{let C=i.text;C=C.replace(/\r/g,""),C=C.replace(/\n/g,"\\n");const Q=KM.multiLine(C,o,s,"center","bottom","flowing");this.setTextAlignment(Q,i.alignment),this.setOverflow(Q,i),e.material&&(Q.material=e.material),Q.pointSize=this.convertToTextSize(i.fontSize),Q.depth=.001,Q.writeTo(void 0,r)})}convertToTextSize(A){return 1/.0502*144*A}setOverflow(A,e){e.horizontalOverflow?A.wrapMode="singleLine":A.wrapMode="flowing"}setTextAlignment(A,e){switch(e){case yg.LowerLeft:case yg.MiddleLeft:case yg.UpperLeft:A.horizontalAlignment="left";break;case yg.LowerCenter:case yg.MiddleCenter:case yg.UpperCenter:A.horizontalAlignment="center";break;case yg.LowerRight:case yg.MiddleRight:case yg.UpperRight:A.horizontalAlignment="right";break}switch(e){case yg.LowerLeft:case yg.LowerCenter:case yg.LowerRight:A.verticalAlignment="bottom";break;case yg.MiddleLeft:case yg.MiddleCenter:case yg.MiddleRight:A.verticalAlignment="middle";break;case yg.UpperLeft:case yg.UpperCenter:case yg.UpperRight:A.verticalAlignment="top";break}}}class bM{get extensionName(){return"tmui"}onExportObject(A,e,t){const i=sA.getComponent(A,dI);if(i&&i.enabled&&i.renderMode===kj.WorldSpace){const I=new Ay,o=sA.getComponent(A,OI),s=sA.getComponent(A,vB),n=new Array;if(o){if(!sA.isActiveSelf(A)){const C=sA.isActiveSelf(A);sA.setActive(A,!0),o.onEnable(),o.updateTransform(),n.push(()=>{o.onDisable(),sA.setActive(A,C)})}A.traverse(C=>{if(!sA.isActiveInHierarchy(C)){const Q=sA.isActiveSelf(C);sA.setActive(C,!0);const c=sA.getComponent(C,Xs);c&&(c.onEnable(),n.push(()=>{c.onDisable()}));const E=sA.getComponent(C,OI);E&&(E.onEnable(),E.updateTransform(),E.onApplyTransform(),n.push(()=>{E.onDisable()}));const h=sA.getComponent(C,WI);h&&(h.onEnable(),n.push(()=>{h.onDisable()})),n.push(()=>{sA.setActive(C,Q)})}}),o.width,o.height;const r=cI.createEmpty(),a=o.shadowComponent;if(e.add(r),a){const C=a.matrix;r.matrix.copy(C);const Q=new Map,c=new Map;Q.set(a,r),c.set(a,s?s.alpha:1),a.traverse(E=>{if(E===a)return;const h=cI.createEmpty();h.matrix.copy(E.matrix);const l=E.parent,d=!!l&&typeof l.textContent=="string"&&l.textContent.length>0;let p=c.get(l)||1;const u=sA.getComponent(E,vB);if(u&&(p*=u.alpha),E instanceof hA&&d){const w=E[Hs];w?I.exportText(w.gameObject,h,t):console.error("Error when exporting UI: shadow component owner not found. This is likely a bug.",E)}if(E instanceof hA&&!d){const w=E.geometry.clone();w.scale(1,1,-1),this.flipWindingOrder(w),h.geometry=w;const m=new yA,M=E.material.opacity;m.copy(E.material.color),h.material=new ot({color:m,opacity:M*p,map:E.material.map,transparent:!0})}Q.set(E,h),c.set(E,p);const f=Q.get(l);if(!f){console.error("Error when exporting UI: shadow component parent not found!",E,E.parent);return}f.add(h)})}}for(const r of n)r()}}flipWindingOrder(A){const e=A.index.array;for(let t=0,i=e.length/3;t<i;t++){const I=e[t*3];e[t*3]=e[t*3+2],e[t*3+2]=I}A.index.needsUpdate=!0}}const Cp=gA("debugusdz");function PdA(g,A){var s;const e=[],t=sA.getComponentsInChildren(g,hI),i=sA.getComponentsInChildren(g,_I),I=new Array,o=new Array;if(A.injectImplicitBehaviours)for(const n of t){if(!n||!n.runtimeAnimatorController||!n.enabled)continue;const r=n.runtimeAnimatorController.activeState;if(!r||!r.motion||!r.motion.clip||((s=r.motion.clip.tracks)==null?void 0:s.length)<1||I.includes(n))continue;const a=new Pc;a.animator=n,a.stateName=r.name,a.trigger="start",a.name="PlayAnimationOnClick_implicitAtStart_"+a.stateName;const C=new DA;sA.addComponent(C,a),o.push(C),I.push(n),g.add(C)}else for(const n of t){if(!n||!n.runtimeAnimatorController||!n.enabled)continue;Cp&&console.log(n);const r=[];for(const a of n.runtimeAnimatorController.enumerateActions()){Cp&&console.log(a);const C=a.getClip();r.includes(C)||r.push(C)}e.push({root:n.gameObject,clips:r})}if(A.injectImplicitBehaviours)for(const n of i){if(!n||!n.clip||!n.enabled||!n.playAutomatically||I.includes(n))continue;const r=new Pc;r.animation=n,r.stateName=n.clip.name,r.trigger="start",r.name="PlayAnimationOnClick_implicitAtStart_"+r.stateName;const a=new DA;sA.addComponent(a,r),o.push(a),I.push(n),g.add(a)}else for(const n of i){Cp&&console.log(n);const r=[];for(const a of n.animations)r.includes(a)||r.push(a);e.push({root:n.gameObject,clips:r})}Cp&&(e==null?void 0:e.length)>0&&console.log("USDZ Animation Clips without behaviours",e);for(const n of e)for(const r of n.clips)A.registerAnimation(n.root,r);return o}function WdA(g,A){const e=sA.getComponentsInChildren(g,zi),t=sA.getComponentsInChildren(g,qB),i=new Array,I=new Array;Cp&&console.log({audioSources:e,playAudioOnClicks:t});for(const o of t){if(!o.target)continue;const s=e.indexOf(o.target);s>-1&&e.splice(s,1)}for(const o of e){if(!o||!o.clip||o.volume<=0||i.includes(o))continue;const s=new qB;s.target=o,s.name="PlayAudioOnClick_implicitAtStart_",s.trigger="start";const n=new DA;sA.addComponent(n,s),console.log("implicit PlayAudioOnStart",n,s),I.push(n),i.push(o),g.add(n)}return I}function ZdA(g){return new cg("DisableAtStart",jg.sceneStartTrigger(),ft.fadeAction(g,0,!1))}function O2(g){const A=g.domElement.shadowRoot.querySelector("link[rel='ar']");if(A)return A;const e=document.createElement("div");e.classList.add("menu"),e.classList.add("quicklook-menu"),e.style.display="none",e.style.visibility="hidden";const t=document.createElement("button");t.id="open-in-ar",t.innerText="Open in QuickLook",e.appendChild(t);const i=document.createElement("a");i.id="needle-usdz-link",i.style.display="none",i.rel="ar",i.href="",e.appendChild(i);const I=document.createElement("img");return I.id="button",i.appendChild(I),g.domElement.shadowRoot.appendChild(e),i}var jdA=Object.defineProperty,zdA=Object.getOwnPropertyDescriptor,ZI=(g,A,e,t)=>{for(var i=t>1?void 0:t?zdA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&jdA(A,e,i),i};const ks=gA("debugusdz");class oQ{constructor(){B(this,"callToAction");B(this,"checkoutTitle");B(this,"checkoutSubtitle");B(this,"callToActionURL")}}ZI([D()],oQ.prototype,"callToAction",2);ZI([D()],oQ.prototype,"checkoutTitle",2);ZI([D()],oQ.prototype,"checkoutSubtitle",2);ZI([D()],oQ.prototype,"callToActionURL",2);var OS;const tb=(OS=class extends FA{constructor(){super(...arguments);B(this,"objectToExport");B(this,"autoExportAnimations",!0);B(this,"autoExportAudioSources",!0);B(this,"exportFileName");B(this,"customUsdzFile");B(this,"customBranding");B(this,"anchoringType","plane");B(this,"maxTextureSize",2048);B(this,"planeAnchoringAlignment","horizontal");B(this,"interactive",!0);B(this,"allowCreateQuicklookButton",!0);B(this,"quickLookCompatible",!0);B(this,"extensions",[]);B(this,"link");B(this,"button");B(this,"onClickedOpenInARElement",A=>{A.preventDefault(),this.exportAndOpen()});B(this,"_currentExportTasks",new Map);B(this,"_previousTimeScale",1);B(this,"lastCallback");B(this,"_rootSessionRootWasAppliedTo",null);B(this,"_rootPositionBeforeExport",new y);B(this,"_rootRotationBeforeExport",new GA);B(this,"_rootScaleBeforeExport",new y)}start(){var A,e,t;ks&&(console.log("USDZExporter",this),console.log("Debug USDZ Mode. Press 'T' to export"),window.addEventListener("keydown",i=>{switch(i.key){case"t":this.exportAsync();break}}),In()&&setTimeout(()=>{this.exportAsync()},2e3)),this.objectToExport||(this.objectToExport=this.gameObject),!((e=(A=this.objectToExport)==null?void 0:A.children)!=null&&e.length)&&!((t=this.objectToExport)!=null&&t.isMesh)&&(this.objectToExport=this.context.scene),this.interactive&&(this.extensions.push(new kM),this.extensions.push(new XB),this.extensions.push(new FM),this.extensions.push(new Ay),this.extensions.push(new bM))}onEnable(){var t;const A=Lc(),e=Ch();(ks||A&&e)&&(this.allowCreateQuicklookButton&&(this.button=this.createQuicklookButton()),this.lastCallback=this.quicklookCallback.bind(this),this.link=O2(this.context),this.link.addEventListener("message",this.lastCallback)),ks&&fi("USDZ Exporter enabled: "+this.name),(t=document.getElementById("open-in-ar"))==null||t.addEventListener("click",this.onClickedOpenInARElement)}onDisable(){var A,e,t;(A=this.button)==null||A.remove(),(e=this.link)==null||e.removeEventListener("message",this.lastCallback),ks&&fi("USDZ Exporter disabled: "+this.name),(t=document.getElementById("open-in-ar"))==null||t.removeEventListener("click",this.onClickedOpenInARElement)}async exportAsync(){return this.exportAndOpen()}async exportAndOpen(){var t;let A=this.exportFileName??((t=this.objectToExport)==null?void 0:t.name)??this.name;if(A+="-"+u8(),fB()||(A!==""&&(A+="-"),A+="MadeWithNeedle"),this.link||(this.link=O2(this.context)),this.customUsdzFile)return ks&&console.log("Exporting custom usdz",this.customUsdzFile),this.openInQuickLook(this.customUsdzFile,A),null;if(!this.objectToExport)return console.warn("No object to export",this),null;const e=await this.export(this.objectToExport);return e?(ks&&console.log("USDZ generation done. Downloading as "+A),this.openInQuickLook(e,A),e):(console.error("USDZ generation failed. Please report a bug",this),null)}async export(A){if(!A)return console.warn("No object to export"),null;const e=this._currentExportTasks.get(A);if(e)return e;const t=this.internalExport(A);return t instanceof Promise?(this._currentExportTasks.set(A,t),t.then(i=>(this._currentExportTasks.delete(A),i)).catch(i=>(this._currentExportTasks.delete(A),console.error("Error during USDZ export – please report a bug!",i),null))):t}async internalExport(A){nt.start("export-usdz",{onProgress:p=>{this.dispatchEvent(new CustomEvent("export-progress",{detail:{progress:p}}))}}),nt.report("export-usdz",{message:"Starting export",totalSteps:40,currentStep:0}),nt.report("export-usdz",{message:"Load progressive textures",autoStep:5}),nt.start("export-usdz-textures","export-usdz");const e=sA.getComponentsInChildren(A,an);for(const p of e)p&&p.enabled&&p.start&&p.start();const t=sA.getComponentsInChildren(A,Vi),i=new Array;let I=0;for(const p of t){for(const u of p.sharedMeshes)if(u){const f=Dt.assignMeshLOD(u,0);f instanceof Promise&&i.push(new Promise((w,m)=>{f.then(()=>{I++,nt.report("export-usdz-textures",{message:"Loaded progressive mesh",currentStep:I,totalSteps:i.length}),w()}).catch(M=>m(M))}))}for(const u of p.sharedMaterials)if(u){const f=Dt.assignTextureLOD(u,0);f instanceof Promise&&i.push(new Promise((w,m)=>{f.then(()=>{I++,nt.report("export-usdz-textures",{message:"Loaded progressive texture",currentStep:I,totalSteps:i.length}),w()}).catch(M=>m(M))}))}}ks&&fi("Progressive Loading: "+i.length),await Promise.all(i),ks&&fi("Progressive Loading: done"),nt.end("export-usdz-textures");const o=BI.Global.Mask;BI.Global.Set(pr.AR);const s=new w8,n=new LD(this.quickLookCompatible),r=[n,...this.extensions],a={self:this,exporter:s,extensions:r,object:A};nt.report("export-usdz","Invoking before-export"),this.dispatchEvent(new CustomEvent("before-export",{detail:a})),this.applyWebARSessionRoot(),this._previousTimeScale=this.context.time.timeScale,this.context.time.timeScale=0,nt.report("export-usdz","auto export animations and audio sources");const C=new Array;this.autoExportAnimations&&C.push(...PdA(A,n)),this.extensions.find(p=>p.extensionName==="Audio")&&this.autoExportAudioSources&&C.push(...WdA(A)),s.debug=ks,s.keepObject=p=>{const u=sA.getComponent(p,Vi);return!(u&&!u.enabled)};const c=new Array;this.objectToExport&&this.quickLookCompatible&&this.interactive&&this.objectToExport.traverse(p=>{p.visible||c.push(p)});const E=this.extensions.find(p=>p.extensionName==="Behaviour");this.interactive&&E&&c.length>0&&E.addBehavior(ZdA(c));let h=!0;this.quickLookCompatible&&!this.interactive&&(h=!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"),nt.report("export-usdz","Invoking exporter.parse");const l=await s.parse(this.objectToExport,{ar:{anchoring:{type:this.anchoringType},planeAnchoring:{alignment:this.planeAnchoringAlignment}},extensions:r,quickLookCompatible:this.quickLookCompatible,maxTextureSize:this.maxTextureSize,exportInvisible:h}),d=new Blob([l],{type:"model/vnd.usdz+zip"});this.revertWebARSessionRoot(),this.context.time.timeScale=this._previousTimeScale,nt.report("export-usdz","Invoking after-export"),this.dispatchEvent(new CustomEvent("after-export",{detail:a}));for(const p of C)sA.destroy(p);return BI.Global.Set(o),nt.end("export-usdz"),d}openInQuickLook(A,e){const t=A instanceof Blob?URL.createObjectURL(A):A,i=this.buildQuicklookOverlay();ks&&console.log("QuickLook Overlay",i);const I=i.callToAction?encodeURIComponent(i.callToAction):"",o=i.checkoutTitle?encodeURIComponent(i.checkoutTitle):"",s=i.checkoutSubtitle?encodeURIComponent(i.checkoutSubtitle):"";this.link.href=t+`#callToAction=${I}&checkoutTitle=${o}&checkoutSubtitle=${s}&callToActionURL=${i.callToActionURL}`,this.lastCallback||(this.lastCallback=this.quicklookCallback.bind(this),this.link.addEventListener("message",this.lastCallback)),this.link.download=e+".usdz",this.link.click()}download(A,e){tb.save(A,e)}static save(A,e){const t=document.createElement("a");t.style.display="none",document.body.appendChild(t),typeof A=="string"?t.href=A:t.href=URL.createObjectURL(A),t.download=e,t.click(),t.remove()}quicklookCallback(A){if((A==null?void 0:A.data)=="_apple_ar_quicklook_button_tapped"){ks&&Ot("Quicklook closed via call to action button");var e=new CustomEvent("quicklook-button-tapped",{detail:this});if(this.dispatchEvent(e),!e.defaultPrevented){const t=new URLSearchParams(this.link.href);if(t){const i=t.get("callToActionURL");ks&&fi("Quicklook url: "+i),i&&(fB()?globalThis.open(i,"_blank"):console.warn("Quicklook closed: custom redirects require a Needle Engine Pro license: https://needle.tools/pricing",i))}}}}buildQuicklookOverlay(){var t,i,I,o,s,n;const A={};return this.customBranding&&Object.assign(A,this.customBranding),fB()||(console.log("Custom Quicklook banner text requires pro license: https://needle.tools/pricing"),A.callToAction="Close",A.checkoutTitle="🌵 Made with Needle",A.checkoutSubtitle="_"),(((t=A.callToAction)==null?void 0:t.length)||((i=A.checkoutTitle)==null?void 0:i.length)||((I=A.checkoutSubtitle)==null?void 0:I.length))&&((o=A.callToAction)!=null&&o.length||(A.callToAction="\0"),(s=A.checkoutTitle)!=null&&s.length||(A.checkoutTitle="\0"),(n=A.checkoutSubtitle)!=null&&n.length||(A.checkoutSubtitle="\0")),this.dispatchEvent(new CustomEvent("quicklook-overlay",{detail:A})),A}getARScaleAndTarget(){if(!this.objectToExport)return{scale:1,_invertForward:!1,target:this.gameObject,sessionRoot:null};let A=sA.getComponentInParent(this.objectToExport,ho);A||(A=sA.getComponentInChildren(this.objectToExport,ho));let e=1,t=!1;const i=this.objectToExport;if(A)e=A.arScale,t=A.invertForward;else{const s=sA.findObjectOfType(Xg);s&&(e=s.arSceneScale)}return{scale:1/e,_invertForward:t,target:i,sessionRoot:(A==null?void 0:A.gameObject)??null}}applyWebARSessionRoot(){if(!this.objectToExport)return;const{scale:A,_invertForward:e,target:t,sessionRoot:i}=this.getARScaleAndTarget(),I=i==null?void 0:i.matrixWorld.clone().invert();this._rootSessionRootWasAppliedTo=t,this._rootPositionBeforeExport.copy(t.position),this._rootRotationBeforeExport.copy(t.quaternion),this._rootScaleBeforeExport.copy(t.scale),t.scale.multiplyScalar(A),e&&t.quaternion.multiply(tb.invertForwardQuaternion),t.updateMatrix(),t.updateMatrixWorld(!0),i&&I&&t.matrix.premultiply(I)}revertWebARSessionRoot(){if(!this.objectToExport||!this._rootSessionRootWasAppliedTo)return;const A=this._rootSessionRootWasAppliedTo;A.position.copy(this._rootPositionBeforeExport),A.quaternion.copy(this._rootRotationBeforeExport),A.scale.copy(this._rootScaleBeforeExport),A.updateMatrix(),A.updateMatrixWorld(!0),this._rootSessionRootWasAppliedTo=null}createQuicklookButton(){const e=$a.getOrCreate().createQuicklookButton();return e.parentNode||this.context.menu.appendChild(e),e}},B(OS,"invertForwardMatrix",new fA().makeRotationY(Math.PI)),B(OS,"invertForwardQuaternion",new GA().setFromEuler(new rt(0,Math.PI,0))),OS);let ji=tb;ZI([D(DA)],ji.prototype,"objectToExport",2);ZI([D()],ji.prototype,"autoExportAnimations",2);ZI([D()],ji.prototype,"autoExportAudioSources",2);ZI([D()],ji.prototype,"exportFileName",2);ZI([D(URL)],ji.prototype,"customUsdzFile",2);ZI([D(oQ)],ji.prototype,"customBranding",2);ZI([D()],ji.prototype,"anchoringType",2);ZI([D()],ji.prototype,"maxTextureSize",2);ZI([D()],ji.prototype,"planeAnchoringAlignment",2);ZI([D()],ji.prototype,"interactive",2);ZI([D()],ji.prototype,"allowCreateQuicklookButton",2);ZI([D()],ji.prototype,"quickLookCompatible",2);class ey extends FA{constructor(){super(...arguments);B(this,"isUsed",!0);B(this,"usedBy",null)}}class bv extends FA{}const P2=gA("debugdeletable");class JM extends Ys{}class Jv extends FA{constructor(){super(...arguments);B(this,"deleteBoxes",[])}awake(){this.deleteBoxes=sA.findObjectsOfType(JM,this.context)}update(){for(const e of this.deleteBoxes){const t=this.gameObject;if(e.isInBox(t)===!0){const I=sA.getComponentInParent(this.gameObject,ey);I?P2&&console.warn("Can not delete object with usage marker",this.guid,I):(P2&&console.log("DESTROY",this.gameObject),RD(this.gameObject,this.context.connection))}}}}var VdA=Object.defineProperty,XdA=Object.getOwnPropertyDescriptor,uE=(g,A,e,t)=>{for(var i=t>1?void 0:t?XdA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&VdA(A,e,i),i};const $dA=gA("debugpost");class Zn extends yI{constructor(){super(...arguments);B(this,"mode");B(this,"focusDistance",new XA(1));B(this,"focalLength",new XA(.2));B(this,"aperture",new XA(20));B(this,"gaussianMaxRadius",new XA);B(this,"resolutionScale",new XA(1*1/window.devicePixelRatio));B(this,"bokehScale",new XA)}get typeName(){return"DepthOfField"}init(){this.focalLength.valueProcessor=t=>{const i=t/300,I=2;return ge.lerp(I,.01,i)};const e=20;this.aperture.valueProcessor=t=>{const i=1-t/32;return ge.lerp(1,e,i)}}onCreateEffect(){if(this.mode===0){$dA&&console.warn("DepthOfField: Mode is set to Off");return}const e=new X8(this.context.mainCamera,{worldFocusRange:.2,focalLength:1,bokehScale:20,resolutionScale:this.resolutionScale.value});return this.focusDistance.onValueChanged=t=>{e.cocMaterial.worldFocusDistance=t},this.focalLength.onValueChanged=t=>e.cocMaterial.worldFocusRange=t,this.aperture.onValueChanged=t=>e.bokehScale=t,this.resolutionScale&&(this.resolutionScale.onValueChanged=t=>e.resolution.scale=t),[e]}unapply(){}}uE([D()],Zn.prototype,"mode",2);uE([D(XA)],Zn.prototype,"focusDistance",2);uE([D(XA)],Zn.prototype,"focalLength",2);uE([D(XA)],Zn.prototype,"aperture",2);uE([D(XA)],Zn.prototype,"gaussianMaxRadius",2);uE([D(XA)],Zn.prototype,"resolutionScale",2);uE([D(XA)],Zn.prototype,"bokehScale",2);nn("DepthOfField",Zn);var AuA=Object.defineProperty,euA=Object.getOwnPropertyDescriptor,tuA=(g,A,e,t)=>{for(var i=t>1?void 0:t?euA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&AuA(A,e,i),i};class xM extends FA{constructor(){super(...arguments);B(this,"visibleOn")}onEnable(){this.apply()}apply(){this.test()||sA.setActive(this.gameObject,!1)}test(){return this.visibleOn<0?!0:In()?(this.visibleOn&2)!==0:(this.visibleOn&1)!==0}}tuA([D()],xM.prototype,"visibleOn",2);class xv{get extensionName(){return"DocumentExtension"}onAfterBuildDocument(A){}}var iuA=Object.defineProperty,guA=Object.getOwnPropertyDescriptor,pE=(g,A,e,t)=>{for(var i=t>1?void 0:t?guA(A,e):A,I=g.length-1,o;I>=0;I--)(o=g[I])&&(i=(t?o(A,e,i):o(i))||i);return t&&i&&iuA(A,e,i),i};const Gr=gA("debugdrag");var Tj=(g=>(g[g.XZPlane=0]="XZPlane",g[g.Attached=1]="Attached",g[g.HitNormal=2]="HitNormal",g[g.DynamicViewAngle=3]="DynamicViewAngle",g[g.SnapToSurfaces=4]="SnapToSurfaces",g[g.None=5]="None",g))(Tj||{}),PS;const rr=(PS=class extends FA{constructor(){super(...arguments);B(this,"dragMode",3);B(this,"snapGridResolution",0);B(this,"keepRotation",!0);B(this,"xrDragMode",1);B(this,"xrKeepRotation",!1);B(this,"xrDistanceDragFactor",1);B(this,"showGizmo",!1);B(this,"targetObject",null);B(this,"orbit",null);B(this,"_dragHelper",null);B(this,"_draggingRigidbodies",[]);B(this,"_potentialDragStartEvt",null);B(this,"_dragHandlers",new Map);B(this,"_totalMovement",new y);B(this,"_marker",null);B(this,"_isDragging",!1);B(this,"_didDrag",!1)}static get HasAnySelected(){return this._active>0}setTargetObject(A){this.targetObject=A;for(const e of this._dragHandlers.values())e.setTargetObject(A)}awake(){this._potentialDragStartEvt=null,this._dragHandlers=new Map,this._totalMovement=new y,this._marker=null,this._isDragging=!1,this._didDrag=!1,this._dragHelper=null,this._draggingRigidbodies=[]}start(){this.orbit=sA.findObjectOfType(Mt,this.context),this.gameObject.getComponentInParent(cs)||this.gameObject.addComponent(cs)}allowEdit(A=null){return this.context.connection.allowEditing}onPointerEnter(A){if(!this.allowEdit(this.gameObject)||A.mode!=="screen"||(A.event.mode==="tracked-pointer"||A.event.mode==="transient-pointer"?this.xrDragMode:this.dragMode)===5)return;const i=sA.getComponentInParent(A.object,rr);!i||i!==this||(rr.lastHovered=A.object,this.context.domElement.style.cursor="pointer")}onPointerExit(A){this.allowEdit(this.gameObject)&&A.mode==="screen"&&rr.lastHovered===A.object&&(this.context.domElement.style.cursor="auto")}onPointerDown(A){if(!(!this.allowEdit(this.gameObject)||A.used||(A.mode==="tracked-pointer"||A.mode==="transient-pointer"?this.xrDragMode:this.dragMode)===5)&&(rr.lastHovered=A.object,A.button===0)){this._dragHandlers.size===0&&(this._didDrag=!1,this._totalMovement.set(0,0,0),this._potentialDragStartEvt=A),rr._active+=1;const i=new ouA(this,this.targetObject||this.gameObject);if(this._dragHandlers.set(A.event.space,i),this.orbit&&(this.orbit.enabled=!1),i.onDragStart(A),this._dragHandlers.size===2){const I=this._dragHandlers.values(),o=I.next().value,s=I.next().value,n=new IuA(this,this.targetObject||this.gameObject,o,s);this._dragHandlers.set(this.gameObject,n),n.onDragStart(A)}A.use()}}onPointerMove(A){(this._isDragging||this._potentialDragStartEvt!==null)&&A.use()}onPointerUp(A){if(Gr&&fe.DrawLabel(A.point??this.gameObject.worldPosition,"POINTERUP:"+A.pointerId+", "+A.button,.03,3),!this.allowEdit(this.gameObject)||A.button!==0)return;this._potentialDragStartEvt=null;const e=this._dragHandlers.get(A.event.space),t=this._dragHandlers.get(this.gameObject);t&&(t.handlerA===e||t.handlerB===e)&&(this._dragHandlers.delete(this.gameObject),t.onDragEnd(A)),e&&(rr._active>0&&(rr._active-=1),e.onDragEnd&&e.onDragEnd(A),this._dragHandlers.delete(A.event.space),this._dragHandlers.size===0&&this.onLastDragEnd(A),A.use()),rr._active===0&&this.orbit&&(this.orbit.enabled=!0)}update(){for(const A of this._dragHandlers.values())A.collectMovementInfo&&A.collectMovementInfo(),A.getTotalMovement&&this._totalMovement.add(A.getTotalMovement());if(this._potentialDragStartEvt){if(!this._didDrag)if(this._totalMovement.length()>3e-4)this._didDrag=!0;else return;const A=this._potentialDragStartEvt;this._potentialDragStartEvt=null,this.onFirstDragStart(A)}for(const A of this._dragHandlers.values())A.onDragUpdate&&A.onDragUpdate(this._dragHandlers.size);this._dragHelper&&this._dragHelper.hasSelected&&this.onAnyDragUpdate()}onFirstDragStart(A){if(!this._dragHelper)if(this.context.mainCamera)this._dragHelper=new M0(this.context.mainCamera);else return;if(!A||!A.object)return;const e=sA.getComponentInParent(A.object,rr);if(!e||e!==this&&e._isDragging)return;const t=this.targetObject||this.gameObject;if(!t)return;this._isDragging=!0,this._dragHelper.setSelected(t,this.context),this.orbit&&(this.orbit.enabled=!1);const i=sA.getComponentInChildren(t,bB);Gr&&console.log("DRAG START",i,t),i&&(i.fastMode=!0,i==null||i.requestOwnership()),this._marker=sA.addComponent(t,ey),this._draggingRigidbodies.length=0;const I=sA.getComponentsInChildren(t,Pt);I&&this._draggingRigidbodies.push(...I)}onAnyDragUpdate(){if(!this._dragHelper)return;this._dragHelper.showGizmo=this.showGizmo,this._dragHelper.onUpdate(this.context);for(const e of this._draggingRigidbodies)e.wakeUp(),e.resetVelocities(),e.resetForcesAndTorques();const A=this.targetObject||this.gameObject;Ws.markDirty(A)}onLastDragEnd(A){if(!this||!this._isDragging||(this._isDragging=!1,!this._dragHelper))return;for(const t of this._draggingRigidbodies)t.setVelocity(t.smoothedVelocity);this._draggingRigidbodies.length=0;const e=this._dragHelper.selected;if(Gr&&console.log("DRAG END",e,e==null?void 0:e.visible),this._dragHelper.setSelected(null,this.context),this.orbit&&(this.orbit.enabled=!0),A!=null&&A.object){const t=sA.getComponentInChildren(A.object,bB);t&&(t.fastMode=!1)}this._marker&&this._marker.destroy()}},B(PS,"_active",0),B(PS,"lastHovered"),PS);let An=rr;pE([D()],An.prototype,"dragMode",2);pE([D()],An.prototype,"snapGridResolution",2);pE([D()],An.prototype,"keepRotation",2);pE([D()],An.prototype,"xrDragMode",2);pE([D()],An.prototype,"xrKeepRotation",2);pE([D()],An.prototype,"xrDistanceDragFactor",2);pE([D()],An.prototype,"showGizmo",2);class IuA{constructor(A,e,t,i){B(this,"handlerA");B(this,"handlerB");B(this,"context");B(this,"settings");B(this,"gameObject");B(this,"_handlerAAttachmentPoint",new y);B(this,"_handlerBAttachmentPoint",new y);B(this,"_followObject");B(this,"_manipulatorObject");B(this,"_deviceMode");B(this,"_followObjectStartWorldQuaternion",new GA);B(this,"_manipulatorPosOffset",new y);B(this,"_manipulatorRotOffset",new GA);B(this,"_manipulatorScaleOffset",new y);B(this,"_tempVec1",new y);B(this,"_tempVec2",new y);B(this,"_tempVec3",new y);B(this,"tempLookMatrix",new fA);B(this,"_initialScale",new y);B(this,"_initialDistance",0);var o,s;this.context=A.context,this.settings=A,this.gameObject=e,this.handlerA=t,this.handlerB=i,this._followObject=new DA,this._manipulatorObject=new DA,this.context.scene.add(this._manipulatorObject);const I=(s=(o=ye.active)==null?void 0:o.rig)==null?void 0:s.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),I&&(I.worldToLocal(this._tempVec1),I.worldToLocal(this._tempVec2)),this._initialDistance=this._tempVec1.distanceTo(this._tempVec2),this._initialDistance<.02?(Gr&&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 – 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(e.scale),Gr){this._followObject.add(new Qs(2)),this._manipulatorObject.add(new Qs(5));const n=r=>`${r.x.toFixed(2)}, ${r.y.toFixed(2)}, ${r.z.toFixed(2)}`;fe.DrawLine(this._tempVec1,this._tempVec2,65535,0,!1),fe.DrawLabel(this._tempVec3,"A:B "+this._initialDistance.toFixed(2)+`
6214
6214
  `+n(this._tempVec1)+`
6215
- `+n(this._tempVec2),.03,5)}}onDragStart(A){this.gameObject.add(this._followObject),this._followObject.matrixAutoUpdate=!1,this._followObject.matrix.identity(),this._deviceMode=A.mode,this._followObjectStartWorldQuaternion.copy(this._followObject.worldQuaternion),this.alignManipulator(),this._manipulatorObject.attach(this._followObject),this._manipulatorPosOffset.copy(this._followObject.position),this._manipulatorRotOffset.copy(this._followObject.quaternion),this._manipulatorScaleOffset.copy(this._followObject.scale)}onDragEnd(A){if(!this.handlerA||!this.handlerB){console.error("onDragEnd called on MultiTouchDragHandler without valid handlers. This is likely a bug.");return}this.handlerA.recenter(),this.handlerB.recenter(),this._manipulatorObject.removeFromParent(),this._followObject.removeFromParent(),this._manipulatorObject.destroy(),this._followObject.destroy()}alignManipulator(){if(!this.handlerA||!this.handlerB){console.error("alignManipulator called on MultiTouchDragHandler without valid handlers. This is likely a bug.",this);return}if(!this.handlerA.followObject||!this.handlerB.followObject){console.error("alignManipulator called on MultiTouchDragHandler without valid follow objects. This is likely a bug.",this.handlerA,this.handlerB);return}this._tempVec1.copy(this._handlerAAttachmentPoint),this._tempVec2.copy(this._handlerBAttachmentPoint),this.handlerA.followObject.localToWorld(this._tempVec1),this.handlerB.followObject.localToWorld(this._tempVec2),this._tempVec3.lerpVectors(this._tempVec1,this._tempVec2,.5),this._manipulatorObject.position.copy(this._tempVec3);const A=this.context.mainCamera;this.tempLookMatrix.lookAt(this._tempVec3,this._tempVec2,A.worldUp),this._manipulatorObject.quaternion.setFromRotationMatrix(this.tempLookMatrix);const e=this._tempVec1.distanceTo(this._tempVec2);this._manipulatorObject.scale.copy(this._initialScale).multiplyScalar(e/this._initialDistance),this._manipulatorObject.updateMatrix(),this._manipulatorObject.updateMatrixWorld(!0),Gr&&(fe.DrawLabel(this._tempVec3.clone().add(new y(0,.2,0)),"A:B "+e.toFixed(2),.03),fe.DrawLine(this._tempVec1,this._tempVec2,65280,0,!1))}onDragUpdate(){this.alignManipulator();const A=30,e=1;this._followObject.position.copy(this._manipulatorPosOffset),this._followObject.quaternion.copy(this._manipulatorRotOffset),this._followObject.scale.copy(this._manipulatorScaleOffset);const t=this.gameObject,i=this._followObject;i.updateMatrix(),i.updateMatrixWorld(!0);const o=this._deviceMode==="tracked-pointer"||this._deviceMode==="transient-pointer"?this.settings.xrKeepRotation:this.settings.keepRotation;if(this.settings.snapGridResolution>0){const C=this._followObject.worldPosition,Q=this.settings.snapGridResolution;C.x=Math.round(C.x/Q)*Q,C.y=Math.round(C.y/Q)*Q,C.z=Math.round(C.z/Q)*Q,this._followObject.worldPosition=C,this._followObject.updateMatrix()}o&&(this._followObject.worldQuaternion=this._followObjectStartWorldQuaternion,this._followObject.updateMatrix());const s=ge.clamp01(this.context.time.deltaTime*A*e),n=t.worldPosition;n.lerp(i.worldPosition,s),t.worldPosition=n;const r=t.worldQuaternion;r.slerp(i.worldQuaternion,s),t.worldQuaternion=r;const a=t.worldScale;a.lerp(i.worldScale,s),t.worldScale=a}setTargetObject(A){this.gameObject=A}}class ouA{constructor(A,e){B(this,"context");B(this,"gameObject");B(this,"settings");B(this,"_lastRig");B(this,"_followObject");B(this,"_totalMovement",new y);B(this,"_totalMovementAlongRayDirection",0);B(this,"_grabStartDistance",0);B(this,"_deviceMode");B(this,"_followObjectStartPosition",new y);B(this,"_followObjectStartQuaternion",new GA);B(this,"_followObjectStartWorldQuaternion",new GA);B(this,"_lastDragPosRigSpace");B(this,"_tempVec",new y);B(this,"_tempMat",new fA);B(this,"_hitPointInLocalSpace",new y);B(this,"_hitNormalInLocalSpace",new y);B(this,"_bottomCenter",new y);B(this,"_backCenter",new y);B(this,"_backBottomCenter",new y);B(this,"_bounds",new Nt);B(this,"_dragPlane",new xI(new y(0,1,0)));B(this,"_draggedOverObject",null);B(this,"_draggedOverObjectLastSetUp",null);B(this,"_draggedOverObjectLastNormal",new y);B(this,"_draggedOverObjectDuration",0);this.settings=A,this.context=A.context,this.gameObject=e,this._followObject=new DA}getTotalMovement(){return this._totalMovement}get followObject(){return this._followObject}get hitPointInLocalSpace(){return this._hitPointInLocalSpace}setTargetObject(A){this.gameObject=A}recenter(){var I,o;if(!this._followObject.parent){console.warn("Error: space follow object doesn't have parent but recenter() is called. This is likely a bug");return}const A=this._followObject.parent;this.gameObject.add(this._followObject),this._followObject.matrixAutoUpdate=!1,this._followObject.position.set(0,0,0),this._followObject.quaternion.set(0,0,0,1),this._followObject.scale.set(1,1,1),this._followObject.updateMatrix(),this._followObject.updateMatrixWorld(!0),A.attach(this._followObject),this._followObjectStartPosition.copy(this._followObject.position),this._followObjectStartQuaternion.copy(this._followObject.quaternion),this._followObjectStartWorldQuaternion.copy(this._followObject.worldQuaternion),this._followObject.updateMatrix(),this._followObject.updateMatrixWorld(!0);const e=this._hitPointInLocalSpace.clone();this.gameObject.localToWorld(e),this._grabStartDistance=e.distanceTo(A.worldPosition);const t=(o=(I=ye.active)==null?void 0:I.rig)==null?void 0:o.gameObject,i=(t==null?void 0:t.worldScale.x)||1;this._grabStartDistance/=i,this._totalMovementAlongRayDirection=0,this._lastDragPosRigSpace=void 0,Gr&&(fe.DrawLine(e,A.worldPosition,65280,.5,!1),fe.DrawLabel(A.worldPosition.add(new y(0,.1,0)),this._grabStartDistance.toFixed(2),.03,.5))}onDragStart(A){if(A.event.space.add(this._followObject),this._lastDragPosRigSpace=void 0,A.point&&A.normal)this._hitPointInLocalSpace.copy(A.point),this.gameObject.worldToLocal(this._hitPointInLocalSpace),this._hitNormalInLocalSpace.copy(A.normal);else if(A){const h=A.event.space,l=h.worldPosition;this.gameObject.worldToLocal(l),this._hitPointInLocalSpace.copy(l);const d=h.worldUp;this._tempMat.copy(this.gameObject.matrixWorld).invert(),d.transformDirection(this._tempMat),this._hitNormalInLocalSpace.copy(d)}this.recenter(),this._totalMovement.set(0,0,0),this._deviceMode=A.mode;const t=this._followObject.parent.worldForward,I=this._deviceMode==="tracked-pointer"||this._deviceMode==="transient-pointer"?this.settings.xrDragMode:this.settings.dragMode,o=this._hitPointInLocalSpace.clone();switch(this.gameObject.localToWorld(o),I){case 0:const h=new y(0,1,0);this.gameObject.parent&&h.transformDirection(this.gameObject.parent.matrixWorld.clone().invert()),this._dragPlane.setFromNormalAndCoplanarPoint(h,o);break;case 2:const l=this._hitNormalInLocalSpace.clone();l.transformDirection(this.gameObject.matrixWorld),this._dragPlane.setFromNormalAndCoplanarPoint(l,o);break;case 1:this._dragPlane.setFromNormalAndCoplanarPoint(t,o);break;case 3:const d=new y(0,1,0),p=t,u=d.angleTo(p),f=.5;u>Math.PI/2+f||u<Math.PI/2-f?this._dragPlane.setFromNormalAndCoplanarPoint(new y(0,1,0),o):this._dragPlane.setFromNormalAndCoplanarPoint(t,o);break}const s=this.gameObject.parent,n=this.gameObject.position.clone(),r=this.gameObject.quaternion.clone(),a=this.gameObject.scale.clone(),C=this.gameObject.matrixWorld.clone();s&&s.remove(this.gameObject),this.gameObject.position.set(0,0,0),this.gameObject.quaternion.set(0,0,0,1),this.gameObject.scale.set(1,1,1);const Q=qr([this.gameObject]);Q.expandByPoint(this.gameObject.worldPosition);const c=new y;Q.getCenter(c);const E=new y;Q.getSize(E),this._bottomCenter.copy(c.clone().add(new y(0,-E.y/2,0))),this._backCenter.copy(c.clone().add(new y(0,0,E.z/2))),this._backBottomCenter.copy(c.clone().add(new y(0,-E.y/2,E.z/2))),this._bounds.copy(Q),s&&s.add(this.gameObject),this.gameObject.position.copy(n),this.gameObject.quaternion.copy(r),this.gameObject.scale.copy(a),this.gameObject.matrixWorld.copy(C),this._draggedOverObject=null,this._draggedOverObjectLastSetUp=null,this._draggedOverObjectLastNormal.set(0,1,0),this._draggedOverObjectDuration=0}collectMovementInfo(){var I,o;if(!this._followObject.parent)return;const A=this._followObject.parent;this._followObject.updateMatrix();const e=A.worldPosition,t=(o=(I=ye.active)==null?void 0:I.rig)==null?void 0:o.gameObject;t&&t.worldToLocal(e),(this._lastDragPosRigSpace===void 0||t!=this._lastRig)&&(this._lastDragPosRigSpace=e.clone(),this._lastRig=t),this._tempVec.copy(e).sub(this._lastDragPosRigSpace);const i=A.worldForward;if(t&&(this._tempMat.copy(t.matrixWorld).invert(),i.transformDirection(this._tempMat)),this._totalMovementAlongRayDirection+=i.dot(this._tempVec),this._tempVec.x=Math.abs(this._tempVec.x),this._tempVec.y=Math.abs(this._tempVec.y),this._tempVec.z=Math.abs(this._tempVec.z),this._totalMovement.add(this._tempVec),this._lastDragPosRigSpace.copy(e),Gr){let s=e;t&&(s=s.clone(),s.transformDirection(t.matrixWorld)),fe.DrawRay(s,i,255)}}onDragUpdate(A){if(A>1)return;const e=this.gameObject,t=this._followObject.parent;this._followObject.updateMatrix();const i=t.worldPosition,I=t.worldForward,o=this._deviceMode==="tracked-pointer"||this._deviceMode==="transient-pointer",s=o?this.settings.xrKeepRotation:this.settings.keepRotation,n=o?this.settings.xrDragMode:this.settings.dragMode;if(n===5)return;const r=10;s&&(this._followObject.worldQuaternion=this._followObjectStartWorldQuaternion),this._followObject.updateMatrix(),this._followObject.updateMatrixWorld(!0);let a=1,C=2;if(o&&this._grabStartDistance>.5){const l=1+this._totalMovementAlongRayDirection*(2*this.settings.xrDistanceDragFactor);a=Math.max(0,l),a=a*a*a}else this._grabStartDistance<=.5&&(C=3);this._followObject.position.copy(this._followObjectStartPosition),s||this._followObject.quaternion.copy(this._followObjectStartQuaternion),this._followObject.position.multiplyScalar(a),this._followObject.updateMatrix();const Q=new xo(i,I);if(n==4){const l=new Yn;l.testObject=p=>p!==this.followObject&&p!==t&&p!==e;const d=this.context.physics.raycastFromRay(Q,l);if(d.length>0){const p=d[0];if(this._draggedOverObject===p.object?this._draggedOverObjectDuration+=this.context.time.deltaTime:(this._draggedOverObject=p.object,this._draggedOverObjectDuration=0),p.face){const f=this._draggedOverObjectDuration>=.15,w=.001,m=this._totalMovement.length()>=w;if((f||m)&&(this._draggedOverObjectLastSetUp!==this._draggedOverObject||this._draggedOverObjectLastNormal.dot(p.face.normal)<.999999||this.context.time.frame%60===0)){this._draggedOverObjectLastSetUp=this._draggedOverObject,this._draggedOverObjectLastNormal.copy(p.face.normal);const M=dt(),G=dt();this._bounds.getCenter(M),this._bounds.getSize(G),M.sub(G.multiplyScalar(.5).multiply(p.face.normal)),this._hitPointInLocalSpace.copy(M),this._hitNormalInLocalSpace.copy(p.face.normal),this._bounds.getCenter(M),this._bounds.getSize(G),M.add(G.multiplyScalar(.5).multiply(p.face.normal));const U=dt(this._hitPointInLocalSpace).add(M);this._followObject.localToWorld(U);const S=p.point;this._dragPlane.setFromNormalAndCoplanarPoint(p.face.normal,S)}else if(!(f||m))return}}}if(n!==1&&Q.intersectPlane(this._dragPlane,this._tempVec)){this._followObject.worldPosition=this._tempVec,this._followObject.updateMatrix(),this._followObject.updateMatrixWorld(!0);const l=this._hitPointInLocalSpace.clone();this._followObject.localToWorld(l),Gr&&fe.DrawLine(l,this._tempVec,65535,0,!1),this._followObject.worldPosition=this._tempVec.multiplyScalar(2).sub(l),this._followObject.updateMatrix(),this._followObject.updateMatrix()}if(this.settings.snapGridResolution>0){const l=this._followObject.worldPosition,d=this.settings.snapGridResolution;l.x=Math.round(l.x/d)*d,l.y=Math.round(l.y/d)*d,l.z=Math.round(l.z/d)*d,this._followObject.worldPosition=l,this._followObject.updateMatrix()}s&&(this._followObject.worldQuaternion=this._followObjectStartWorldQuaternion,this._followObject.updateMatrix());const c=ge.clamp01(this.context.time.deltaTime*r*C),E=e.worldPosition;E.lerp(this._followObject.worldPosition,c),e.worldPosition=E;const h=e.worldQuaternion;if(h.slerp(this._followObject.worldQuaternion,c),e.worldQuaternion=h,Gr){const l=this._hitPointInLocalSpace.clone();e.localToWorld(l),fe.DrawSphere(l,.02,16711680);const d=this._hitNormalInLocalSpace.clone();d.applyQuaternion(h),fe.DrawRay(l,d,16711680),fe.DrawLabel(E.add(new y(0,.25,0)),`Distance: ${this._totalMovement.length().toFixed(2)}
6215
+ `+n(this._tempVec2),.03,5)}}onDragStart(A){this.gameObject.add(this._followObject),this._followObject.matrixAutoUpdate=!1,this._followObject.matrix.identity(),this._deviceMode=A.mode,this._followObjectStartWorldQuaternion.copy(this._followObject.worldQuaternion),this.alignManipulator(),this._manipulatorObject.attach(this._followObject),this._manipulatorPosOffset.copy(this._followObject.position),this._manipulatorRotOffset.copy(this._followObject.quaternion),this._manipulatorScaleOffset.copy(this._followObject.scale)}onDragEnd(A){if(!this.handlerA||!this.handlerB){console.error("onDragEnd called on MultiTouchDragHandler without valid handlers. This is likely a bug.");return}this.handlerA.recenter(),this.handlerB.recenter(),this._manipulatorObject.removeFromParent(),this._followObject.removeFromParent(),this._manipulatorObject.destroy(),this._followObject.destroy()}alignManipulator(){if(!this.handlerA||!this.handlerB){console.error("alignManipulator called on MultiTouchDragHandler without valid handlers. This is likely a bug.",this);return}if(!this.handlerA.followObject||!this.handlerB.followObject){console.error("alignManipulator called on MultiTouchDragHandler without valid follow objects. This is likely a bug.",this.handlerA,this.handlerB);return}this._tempVec1.copy(this._handlerAAttachmentPoint),this._tempVec2.copy(this._handlerBAttachmentPoint),this.handlerA.followObject.localToWorld(this._tempVec1),this.handlerB.followObject.localToWorld(this._tempVec2),this._tempVec3.lerpVectors(this._tempVec1,this._tempVec2,.5),this._manipulatorObject.position.copy(this._tempVec3);const A=this.context.mainCamera;this.tempLookMatrix.lookAt(this._tempVec3,this._tempVec2,A.worldUp),this._manipulatorObject.quaternion.setFromRotationMatrix(this.tempLookMatrix);const e=this._tempVec1.distanceTo(this._tempVec2);this._manipulatorObject.scale.copy(this._initialScale).multiplyScalar(e/this._initialDistance),this._manipulatorObject.updateMatrix(),this._manipulatorObject.updateMatrixWorld(!0),Gr&&(fe.DrawLabel(this._tempVec3.clone().add(new y(0,.2,0)),"A:B "+e.toFixed(2),.03),fe.DrawLine(this._tempVec1,this._tempVec2,65280,0,!1))}onDragUpdate(){this.alignManipulator();const A=30,e=1;this._followObject.position.copy(this._manipulatorPosOffset),this._followObject.quaternion.copy(this._manipulatorRotOffset),this._followObject.scale.copy(this._manipulatorScaleOffset);const t=this.gameObject,i=this._followObject;i.updateMatrix(),i.updateMatrixWorld(!0);const o=this._deviceMode==="tracked-pointer"||this._deviceMode==="transient-pointer"?this.settings.xrKeepRotation:this.settings.keepRotation;if(this.settings.snapGridResolution>0){const C=this._followObject.worldPosition,Q=this.settings.snapGridResolution;C.x=Math.round(C.x/Q)*Q,C.y=Math.round(C.y/Q)*Q,C.z=Math.round(C.z/Q)*Q,this._followObject.worldPosition=C,this._followObject.updateMatrix()}o&&(this._followObject.worldQuaternion=this._followObjectStartWorldQuaternion,this._followObject.updateMatrix());const s=ge.clamp01(this.context.time.deltaTime*A*e),n=t.worldPosition;n.lerp(i.worldPosition,s),t.worldPosition=n;const r=t.worldQuaternion;r.slerp(i.worldQuaternion,s),t.worldQuaternion=r;const a=t.worldScale;a.lerp(i.worldScale,s),t.worldScale=a}setTargetObject(A){this.gameObject=A}}class ouA{constructor(A,e){B(this,"context");B(this,"gameObject");B(this,"settings");B(this,"_lastRig");B(this,"_followObject");B(this,"_totalMovement",new y);B(this,"_totalMovementAlongRayDirection",0);B(this,"_grabStartDistance",0);B(this,"_deviceMode");B(this,"_followObjectStartPosition",new y);B(this,"_followObjectStartQuaternion",new GA);B(this,"_followObjectStartWorldQuaternion",new GA);B(this,"_lastDragPosRigSpace");B(this,"_tempVec",new y);B(this,"_tempMat",new fA);B(this,"_hitPointInLocalSpace",new y);B(this,"_hitNormalInLocalSpace",new y);B(this,"_bottomCenter",new y);B(this,"_backCenter",new y);B(this,"_backBottomCenter",new y);B(this,"_bounds",new Nt);B(this,"_dragPlane",new xI(new y(0,1,0)));B(this,"_draggedOverObject",null);B(this,"_draggedOverObjectLastSetUp",null);B(this,"_draggedOverObjectLastNormal",new y);B(this,"_draggedOverObjectDuration",0);this.settings=A,this.context=A.context,this.gameObject=e,this._followObject=new DA}getTotalMovement(){return this._totalMovement}get followObject(){return this._followObject}get hitPointInLocalSpace(){return this._hitPointInLocalSpace}setTargetObject(A){this.gameObject=A}recenter(){var I,o;if(!this._followObject.parent){console.warn("Error: space follow object doesn't have parent but recenter() is called. This is likely a bug");return}const A=this._followObject.parent;this.gameObject.add(this._followObject),this._followObject.matrixAutoUpdate=!1,this._followObject.position.set(0,0,0),this._followObject.quaternion.set(0,0,0,1),this._followObject.scale.set(1,1,1),this._followObject.updateMatrix(),this._followObject.updateMatrixWorld(!0),A.attach(this._followObject),this._followObjectStartPosition.copy(this._followObject.position),this._followObjectStartQuaternion.copy(this._followObject.quaternion),this._followObjectStartWorldQuaternion.copy(this._followObject.worldQuaternion),this._followObject.updateMatrix(),this._followObject.updateMatrixWorld(!0);const e=this._hitPointInLocalSpace.clone();this.gameObject.localToWorld(e),this._grabStartDistance=e.distanceTo(A.worldPosition);const t=(o=(I=ye.active)==null?void 0:I.rig)==null?void 0:o.gameObject,i=(t==null?void 0:t.worldScale.x)||1;this._grabStartDistance/=i,this._totalMovementAlongRayDirection=0,this._lastDragPosRigSpace=void 0,Gr&&(fe.DrawLine(e,A.worldPosition,65280,.5,!1),fe.DrawLabel(A.worldPosition.add(new y(0,.1,0)),this._grabStartDistance.toFixed(2),.03,.5))}onDragStart(A){if(A.event.space.add(this._followObject),this._lastDragPosRigSpace=void 0,A.point&&A.normal)this._hitPointInLocalSpace.copy(A.point),this.gameObject.worldToLocal(this._hitPointInLocalSpace),this._hitNormalInLocalSpace.copy(A.normal);else if(A){const h=A.event.space,l=h.worldPosition;this.gameObject.worldToLocal(l),this._hitPointInLocalSpace.copy(l);const d=h.worldUp;this._tempMat.copy(this.gameObject.matrixWorld).invert(),d.transformDirection(this._tempMat),this._hitNormalInLocalSpace.copy(d)}this.recenter(),this._totalMovement.set(0,0,0),this._deviceMode=A.mode;const t=this._followObject.parent.worldForward,I=this._deviceMode==="tracked-pointer"||this._deviceMode==="transient-pointer"?this.settings.xrDragMode:this.settings.dragMode,o=this._hitPointInLocalSpace.clone();switch(this.gameObject.localToWorld(o),I){case 0:const h=new y(0,1,0);this.gameObject.parent&&h.transformDirection(this.gameObject.parent.matrixWorld.clone().invert()),this._dragPlane.setFromNormalAndCoplanarPoint(h,o);break;case 2:const l=this._hitNormalInLocalSpace.clone();l.transformDirection(this.gameObject.matrixWorld),this._dragPlane.setFromNormalAndCoplanarPoint(l,o);break;case 1:this._dragPlane.setFromNormalAndCoplanarPoint(t,o);break;case 4:case 3:const d=new y(0,1,0),p=t,u=d.angleTo(p),f=.5;u>Math.PI/2+f||u<Math.PI/2-f?this._dragPlane.setFromNormalAndCoplanarPoint(new y(0,1,0),o):this._dragPlane.setFromNormalAndCoplanarPoint(t,o);break}const s=this.gameObject.parent,n=this.gameObject.position.clone(),r=this.gameObject.quaternion.clone(),a=this.gameObject.scale.clone(),C=this.gameObject.matrixWorld.clone();s&&s.remove(this.gameObject),this.gameObject.position.set(0,0,0),this.gameObject.quaternion.set(0,0,0,1),this.gameObject.scale.set(1,1,1);const Q=qr([this.gameObject]);Q.expandByPoint(this.gameObject.worldPosition);const c=new y;Q.getCenter(c);const E=new y;Q.getSize(E),this._bottomCenter.copy(c.clone().add(new y(0,-E.y/2,0))),this._backCenter.copy(c.clone().add(new y(0,0,E.z/2))),this._backBottomCenter.copy(c.clone().add(new y(0,-E.y/2,E.z/2))),this._bounds.copy(Q),s&&s.add(this.gameObject),this.gameObject.position.copy(n),this.gameObject.quaternion.copy(r),this.gameObject.scale.copy(a),this.gameObject.matrixWorld.copy(C),this._draggedOverObject=null,this._draggedOverObjectLastSetUp=null,this._draggedOverObjectLastNormal.set(0,1,0),this._draggedOverObjectDuration=0}collectMovementInfo(){var I,o;if(!this._followObject.parent)return;const A=this._followObject.parent;this._followObject.updateMatrix();const e=A.worldPosition,t=(o=(I=ye.active)==null?void 0:I.rig)==null?void 0:o.gameObject;t&&t.worldToLocal(e),(this._lastDragPosRigSpace===void 0||t!=this._lastRig)&&(this._lastDragPosRigSpace=e.clone(),this._lastRig=t),this._tempVec.copy(e).sub(this._lastDragPosRigSpace);const i=A.worldForward;if(t&&(this._tempMat.copy(t.matrixWorld).invert(),i.transformDirection(this._tempMat)),this._totalMovementAlongRayDirection+=i.dot(this._tempVec),this._tempVec.x=Math.abs(this._tempVec.x),this._tempVec.y=Math.abs(this._tempVec.y),this._tempVec.z=Math.abs(this._tempVec.z),this._totalMovement.add(this._tempVec),this._lastDragPosRigSpace.copy(e),Gr){let s=e;t&&(s=s.clone(),s.transformDirection(t.matrixWorld)),fe.DrawRay(s,i,255)}}onDragUpdate(A){if(A>1)return;const e=this.gameObject,t=this._followObject.parent;this._followObject.updateMatrix();const i=t.worldPosition,I=t.worldForward,o=this._deviceMode==="tracked-pointer"||this._deviceMode==="transient-pointer",s=o?this.settings.xrKeepRotation:this.settings.keepRotation,n=o?this.settings.xrDragMode:this.settings.dragMode;if(n===5)return;const r=10;s&&(this._followObject.worldQuaternion=this._followObjectStartWorldQuaternion),this._followObject.updateMatrix(),this._followObject.updateMatrixWorld(!0);let a=1,C=2;if(o&&this._grabStartDistance>.5){const l=1+this._totalMovementAlongRayDirection*(2*this.settings.xrDistanceDragFactor);a=Math.max(0,l),a=a*a*a}else this._grabStartDistance<=.5&&(C=3);this._followObject.position.copy(this._followObjectStartPosition),s||this._followObject.quaternion.copy(this._followObjectStartQuaternion),this._followObject.position.multiplyScalar(a),this._followObject.updateMatrix();const Q=new xo(i,I);if(n==4){const l=new Yn;l.testObject=p=>p!==this.followObject&&p!==t&&p!==e;const d=this.context.physics.raycastFromRay(Q,l);if(d.length>0){const p=d[0];if(this._draggedOverObject===p.object?this._draggedOverObjectDuration+=this.context.time.deltaTime:(this._draggedOverObject=p.object,this._draggedOverObjectDuration=0),p.face){const f=this._draggedOverObjectDuration>=.15,w=.001,m=this._totalMovement.length()>=w;if((f||m)&&(this._draggedOverObjectLastSetUp!==this._draggedOverObject||this._draggedOverObjectLastNormal.dot(p.face.normal)<.999999||this.context.time.frame%60===0)){this._draggedOverObjectLastSetUp=this._draggedOverObject,this._draggedOverObjectLastNormal.copy(p.face.normal);const M=dt(),G=dt();this._bounds.getCenter(M),this._bounds.getSize(G),M.sub(G.multiplyScalar(.5).multiply(p.face.normal)),this._hitPointInLocalSpace.copy(M),this._hitNormalInLocalSpace.copy(p.face.normal),this._bounds.getCenter(M),this._bounds.getSize(G),M.add(G.multiplyScalar(.5).multiply(p.face.normal));const U=dt(this._hitPointInLocalSpace).add(M);this._followObject.localToWorld(U);const S=p.point;this._dragPlane.setFromNormalAndCoplanarPoint(p.face.normal,S)}else if(!(f||m))return}}}if(n!==1&&Q.intersectPlane(this._dragPlane,this._tempVec)){this._followObject.worldPosition=this._tempVec,this._followObject.updateMatrix(),this._followObject.updateMatrixWorld(!0);const l=this._hitPointInLocalSpace.clone();this._followObject.localToWorld(l),Gr&&fe.DrawLine(l,this._tempVec,65535,0,!1),this._followObject.worldPosition=this._tempVec.multiplyScalar(2).sub(l),this._followObject.updateMatrix(),this._followObject.updateMatrix()}if(this.settings.snapGridResolution>0){const l=this._followObject.worldPosition,d=this.settings.snapGridResolution;l.x=Math.round(l.x/d)*d,l.y=Math.round(l.y/d)*d,l.z=Math.round(l.z/d)*d,this._followObject.worldPosition=l,this._followObject.updateMatrix()}s&&(this._followObject.worldQuaternion=this._followObjectStartWorldQuaternion,this._followObject.updateMatrix());const c=ge.clamp01(this.context.time.deltaTime*r*C),E=e.worldPosition;E.lerp(this._followObject.worldPosition,c),e.worldPosition=E;const h=e.worldQuaternion;if(h.slerp(this._followObject.worldQuaternion,c),e.worldQuaternion=h,Gr){const l=this._hitPointInLocalSpace.clone();e.localToWorld(l),fe.DrawSphere(l,.02,16711680);const d=this._hitNormalInLocalSpace.clone();d.applyQuaternion(h),fe.DrawRay(l,d,16711680),fe.DrawLabel(E.add(new y(0,.25,0)),`Distance: ${this._totalMovement.length().toFixed(2)}
6216
6216
 
6217
6217
  Along Ray: ${this._totalMovementAlongRayDirection.toFixed(2)}
6218
6218