@needle-tools/engine 3.45.2-beta → 3.45.2-beta.3

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: `+e.toString())}const n=aa()||ew()&&st();if((
4344
4344
  #__vconsole .vc-mask {
4345
4345
  overflow: hidden;
4346
4346
  }
4347
- `,da?.prepend(r),n===!0&&OI()<=0&&pz(),console.log("\u{1F335} Debug console has loaded")}},e.src="https://unpkg.com/vconsole@latest/dist/vconsole.min.js",document.body.appendChild(e)}function one(){const n=new VConsole.VConsolePlugin("needle-console","\u{1F335} Inspect glTF"),e=()=>document.querySelector("#__vc_plug_"+n._id+" iframe");return n.on("renderTab",function(t){const r=globalThis["needle:codegen_files"];if(!r||r.length===0)return;let s=globalThis["needle:codegen_files"][0];const o=s.indexOf("?");o>-1&&(s=s.substring(0,o));const a=location.protocol+"//"+location.host+location.pathname+"/"+s,l=encodeURIComponent(a);n.fullUrl="https://viewer.needle.tools?inspect&file="+l;var c='<iframe src="" style="width: 100%; height: 99%; border: none;"></iframe>';t(c)}),n.on("show",function(){const t=e();t&&t.src!==n.fullUrl&&(t.src=n.fullUrl)}),n.on("hide",function(){const t=e();t&&(t.src="")}),n.on("addTopBar",function(t){var r=new Array;r.push({name:"Open in new window \u2197",onClick:function(s){window.open(n.fullUrl,"_blank"),ua?.hide()}}),r.push({name:"Reload",onClick:function(s){const o=e();o&&(o.src=n.fullUrl)}}),r.push({name:"Fullscreen",onClick:function(s){const o=e();o.requestFullscreen?o.requestFullscreen():o.webkitRequestFullscreen instanceof Function&&o.webkitRequestFullscreen()}}),t(r)}),n}function ane(){return document.querySelector("#__vconsole .vc-switch")||null}function lne(){return document.querySelector("#__vconsole")||null}const vz=te("debugdefines");zf('if(!globalThis[""3.45.2-beta""]) globalThis[""3.45.2-beta""] = "0.0.0";'),zf('if(!globalThis[""undefined""]) globalThis[""undefined""] = "unknown";'),zf('if(!globalThis[""Wed Jul 17 2024 17:50:18 GMT+0200 (Central European Summer Time)""]) globalThis[""Wed Jul 17 2024 17:50:18 GMT+0200 (Central European Summer Time)""] = "unknown";'),zf('globalThis["__NEEDLE_ENGINE_VERSION__"] = "3.45.2-beta";'),zf('globalThis["__NEEDLE_ENGINE_GENERATOR__"] = "undefined";'),zf('globalThis["__NEEDLE_PROJECT_BUILD_TIME__"] = "Wed Jul 17 2024 17:50:18 GMT+0200 (Central European Summer Time)";');const el="3.45.2-beta",bw="undefined",DR="Wed Jul 17 2024 17:50:18 GMT+0200 (Central European Summer Time)";vz&&console.log(`Engine version: ${el} (generator: ${bw})
4347
+ `,da?.prepend(r),n===!0&&OI()<=0&&pz(),console.log("\u{1F335} Debug console has loaded")}},e.src="https://unpkg.com/vconsole@latest/dist/vconsole.min.js",document.body.appendChild(e)}function one(){const n=new VConsole.VConsolePlugin("needle-console","\u{1F335} Inspect glTF"),e=()=>document.querySelector("#__vc_plug_"+n._id+" iframe");return n.on("renderTab",function(t){const r=globalThis["needle:codegen_files"];if(!r||r.length===0)return;let s=globalThis["needle:codegen_files"][0];const o=s.indexOf("?");o>-1&&(s=s.substring(0,o));const a=location.protocol+"//"+location.host+location.pathname+"/"+s,l=encodeURIComponent(a);n.fullUrl="https://viewer.needle.tools?inspect&file="+l;var c='<iframe src="" style="width: 100%; height: 99%; border: none;"></iframe>';t(c)}),n.on("show",function(){const t=e();t&&t.src!==n.fullUrl&&(t.src=n.fullUrl)}),n.on("hide",function(){const t=e();t&&(t.src="")}),n.on("addTopBar",function(t){var r=new Array;r.push({name:"Open in new window \u2197",onClick:function(s){window.open(n.fullUrl,"_blank"),ua?.hide()}}),r.push({name:"Reload",onClick:function(s){const o=e();o&&(o.src=n.fullUrl)}}),r.push({name:"Fullscreen",onClick:function(s){const o=e();o.requestFullscreen?o.requestFullscreen():o.webkitRequestFullscreen instanceof Function&&o.webkitRequestFullscreen()}}),t(r)}),n}function ane(){return document.querySelector("#__vconsole .vc-switch")||null}function lne(){return document.querySelector("#__vconsole")||null}const vz=te("debugdefines");zf('if(!globalThis[""3.45.2-beta.3""]) globalThis[""3.45.2-beta.3""] = "0.0.0";'),zf('if(!globalThis[""undefined""]) globalThis[""undefined""] = "unknown";'),zf('if(!globalThis[""Thu Jul 18 2024 13:36:34 GMT+0200 (Central European Summer Time)""]) globalThis[""Thu Jul 18 2024 13:36:34 GMT+0200 (Central European Summer Time)""] = "unknown";'),zf('globalThis["__NEEDLE_ENGINE_VERSION__"] = "3.45.2-beta.3";'),zf('globalThis["__NEEDLE_ENGINE_GENERATOR__"] = "undefined";'),zf('globalThis["__NEEDLE_PROJECT_BUILD_TIME__"] = "Thu Jul 18 2024 13:36:34 GMT+0200 (Central European Summer Time)";');const el="3.45.2-beta.3",bw="undefined",DR="Thu Jul 18 2024 13:36:34 GMT+0200 (Central European Summer Time)";vz&&console.log(`Engine version: ${el} (generator: ${bw})
4348
4348
  Project built at ${DR}`);const $c="needle_isActiveInHierarchy",wp="builtin_components",Kv="needle_editor_guid";function zf(n){try{(0,eval)(n)}catch(e){vz&&console.error(e)}}const cne='<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>',hne=btoa(cne),une="data:image/svg+xml;base64,"+hne,dne=une,pne=`<?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(pne);const mne='<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>',fne=btoa(mne),gne="data:image/svg+xml;charset=utf-8;base64,"+fne,vne=gne,pa=te("debuglicense");let Sp="basic";pa&&console.log("License Type: "+Sp);function uu(){switch(Sp){case"pro":case"enterprise":return!0}return!1}function OR(){switch(Sp){case"indie":return!0}return!1}function eh(){return uu()||OR()}const yz=[];function yne(n){if(uu()||OR())return n(!0);yz.push(n)}function Ane(n){for(const e of yz)try{e(n)}catch{}}di.registerCallback(Ci.ContextRegistered,n=>{xne(n.context),Sne(),_ne(n.context)});let Cp,LR=!1,_w="";async function bne(){if(Cp)return Cp;if(Sp==="basic")try{const n="https://engine.needle.tools/licensing/check?location="+encodeURIComponent(window.location.href)+"&version="+el+"&generator="+encodeURIComponent(bw),e=await fetch(n,{method:"GET"}).catch(t=>{pa&&console.error("License check failed",t)});e?.status===200?(LR=!1,pa&&console.log("License check succeeded"),Sp="pro",Ane(!0)):e?.status===403?(LR=!0,_w=await e.text()):pa&&console.log("License check failed with status "+e?.status)}catch(n){pa&&console.error("License check failed",n)}else pa&&console.log('Runtime license check is skipped because license is already applied as "'+Sp+'"')}Cp=bne();async function _ne(n){function e(){const s=document.createElement("div");s.className="needle-forbidden",s.style.cssText=`
4349
4349
  position: fixed;
4350
4350
  top: 0;
@@ -5148,7 +5148,7 @@ in script ${o}.ts
5148
5148
  *
5149
5149
  * @author Feross Aboukhadijeh <https://feross.org>
5150
5150
  * @license MIT
5151
- */var rue=function(n){return n!=null&&(w6(n)||sue(n)||!!n._isBuffer)};function w6(n){return!!n.constructor&&typeof n.constructor.isBuffer=="function"&&n.constructor.isBuffer(n)}function sue(n){return typeof n.readFloatLE=="function"&&typeof n.slice=="function"&&w6(n.slice(0,0))}(function(){var n=nue,e=x6.utf8,t=rue,r=x6.bin,s=function(o,a){o.constructor==String?a&&a.encoding==="binary"?o=r.stringToBytes(o):o=e.stringToBytes(o):t(o)?o=Array.prototype.slice.call(o,0):!Array.isArray(o)&&o.constructor!==Uint8Array&&(o=o.toString());for(var l=n.bytesToWords(o),c=o.length*8,h=1732584193,u=-271733879,p=-1732584194,m=271733878,f=0;f<l.length;f++)l[f]=(l[f]<<8|l[f]>>>24)&16711935|(l[f]<<24|l[f]>>>8)&4278255360;l[c>>>5]|=128<<c%32,l[(c+64>>>9<<4)+14]=c;for(var g=s._ff,v=s._gg,y=s._hh,A=s._ii,f=0;f<l.length;f+=16){var _=h,b=u,x=p,E=m;h=g(h,u,p,m,l[f+0],7,-680876936),m=g(m,h,u,p,l[f+1],12,-389564586),p=g(p,m,h,u,l[f+2],17,606105819),u=g(u,p,m,h,l[f+3],22,-1044525330),h=g(h,u,p,m,l[f+4],7,-176418897),m=g(m,h,u,p,l[f+5],12,1200080426),p=g(p,m,h,u,l[f+6],17,-1473231341),u=g(u,p,m,h,l[f+7],22,-45705983),h=g(h,u,p,m,l[f+8],7,1770035416),m=g(m,h,u,p,l[f+9],12,-1958414417),p=g(p,m,h,u,l[f+10],17,-42063),u=g(u,p,m,h,l[f+11],22,-1990404162),h=g(h,u,p,m,l[f+12],7,1804603682),m=g(m,h,u,p,l[f+13],12,-40341101),p=g(p,m,h,u,l[f+14],17,-1502002290),u=g(u,p,m,h,l[f+15],22,1236535329),h=v(h,u,p,m,l[f+1],5,-165796510),m=v(m,h,u,p,l[f+6],9,-1069501632),p=v(p,m,h,u,l[f+11],14,643717713),u=v(u,p,m,h,l[f+0],20,-373897302),h=v(h,u,p,m,l[f+5],5,-701558691),m=v(m,h,u,p,l[f+10],9,38016083),p=v(p,m,h,u,l[f+15],14,-660478335),u=v(u,p,m,h,l[f+4],20,-405537848),h=v(h,u,p,m,l[f+9],5,568446438),m=v(m,h,u,p,l[f+14],9,-1019803690),p=v(p,m,h,u,l[f+3],14,-187363961),u=v(u,p,m,h,l[f+8],20,1163531501),h=v(h,u,p,m,l[f+13],5,-1444681467),m=v(m,h,u,p,l[f+2],9,-51403784),p=v(p,m,h,u,l[f+7],14,1735328473),u=v(u,p,m,h,l[f+12],20,-1926607734),h=y(h,u,p,m,l[f+5],4,-378558),m=y(m,h,u,p,l[f+8],11,-2022574463),p=y(p,m,h,u,l[f+11],16,1839030562),u=y(u,p,m,h,l[f+14],23,-35309556),h=y(h,u,p,m,l[f+1],4,-1530992060),m=y(m,h,u,p,l[f+4],11,1272893353),p=y(p,m,h,u,l[f+7],16,-155497632),u=y(u,p,m,h,l[f+10],23,-1094730640),h=y(h,u,p,m,l[f+13],4,681279174),m=y(m,h,u,p,l[f+0],11,-358537222),p=y(p,m,h,u,l[f+3],16,-722521979),u=y(u,p,m,h,l[f+6],23,76029189),h=y(h,u,p,m,l[f+9],4,-640364487),m=y(m,h,u,p,l[f+12],11,-421815835),p=y(p,m,h,u,l[f+15],16,530742520),u=y(u,p,m,h,l[f+2],23,-995338651),h=A(h,u,p,m,l[f+0],6,-198630844),m=A(m,h,u,p,l[f+7],10,1126891415),p=A(p,m,h,u,l[f+14],15,-1416354905),u=A(u,p,m,h,l[f+5],21,-57434055),h=A(h,u,p,m,l[f+12],6,1700485571),m=A(m,h,u,p,l[f+3],10,-1894986606),p=A(p,m,h,u,l[f+10],15,-1051523),u=A(u,p,m,h,l[f+1],21,-2054922799),h=A(h,u,p,m,l[f+8],6,1873313359),m=A(m,h,u,p,l[f+15],10,-30611744),p=A(p,m,h,u,l[f+6],15,-1560198380),u=A(u,p,m,h,l[f+13],21,1309151649),h=A(h,u,p,m,l[f+4],6,-145523070),m=A(m,h,u,p,l[f+11],10,-1120210379),p=A(p,m,h,u,l[f+2],15,718787259),u=A(u,p,m,h,l[f+9],21,-343485551),h=h+_>>>0,u=u+b>>>0,p=p+x>>>0,m=m+E>>>0}return n.endian([h,u,p,m])};s._ff=function(o,a,l,c,h,u,p){var m=o+(a&l|~a&c)+(h>>>0)+p;return(m<<u|m>>>32-u)+a},s._gg=function(o,a,l,c,h,u,p){var m=o+(a&c|l&~c)+(h>>>0)+p;return(m<<u|m>>>32-u)+a},s._hh=function(o,a,l,c,h,u,p){var m=o+(a^l^c)+(h>>>0)+p;return(m<<u|m>>>32-u)+a},s._ii=function(o,a,l,c,h,u,p){var m=o+(l^(a|~c))+(h>>>0)+p;return(m<<u|m>>>32-u)+a},s._blocksize=16,s._digestsize=16,b6.exports=function(o,a){if(o==null)throw new Error("Illegal argument "+o);var l=n.wordsToBytes(s(o,a));return a&&a.asBytes?l:a&&a.asString?r.bytesToString(l):n.bytesToHex(l)}})();var oue=b6.exports;const aue=G1(oue);class hB{constructor(e,t,r,s){d(this,"success"),d(this,"filename"),d(this,"hash"),d(this,"size"),d(this,"url"),this.success=e,this.filename=t,this.hash=r,this.size=s}}async function S6(n,e){const t=await n.arrayBuffer(),r=uB(t),s=n.name.split(".").pop(),o=r+"."+s,a=n.name.split(".").shift();console.assert(a!==void 0);const l={alias:a,filename:o},c=await(await fetch(e+"/exists",{method:"POST",body:JSON.stringify(l)})).json();if(c.success||console.warn("exists check did fail"),c.exists)return console.log("file already exists",r),new hB(!0,o,r,n.size);console.log("begin uploading file",a,n.size);const h=new FormData;h.append("file",n);const u={};u.filesize=n.size,a&&(u.alias=a);const p=await(await fetch(e+"/upload/file",{method:"POST",body:h,headers:u})).json();if(p?.success===!1)return p.message!==void 0?console.error("Upload failed:",p.message):console.error("Upload failed"),null;console.assert(p.hash_sum===r,"hash sum did not match","received:",p.hash_sum,"expected:",r),p.success&&console.log("successfully uploaded",r,p.id);const m=new hB(p.success,o,r,n.size);return m.url=e,m}function uB(n){return aue(new Uint8Array(n))}async function dB(n,e,t,r,s=!1){try{const o=await fetch(r+"/download/file",{method:"POST",body:n});if(o.status!==200)return console.error("download failed",o),null;const a=await o.blob(),l=await a.arrayBuffer();s||console.assert(a.size===t,"size mismatch","expected:",t,"got:",a.size);const c=uB(l);return s||console.assert(c===e,"hash mismatch, downloaded file is invalid"),a.arrayBuffer()}catch(o){console.error(o)}return null}async function C6(n,e){var t;const r=await fetch(n),s=(t=r.body)==null?void 0:t.getReader(),o=r.headers.get("Content-Length"),a=o?parseInt(o):0;if(!s)return null;let l=0;const c=[];for(;;){const{done:p,value:m}=await s.read();if(m&&(c.push(m),l+=m.length,e.call(null,new ProgressEvent("progress",{loaded:l,total:a}))),p)break}const h=new Uint8Array(l);let u=0;for(const p of c)h.set(p,u),u+=p.length;return h}const Fu=te("debugaddressables");class E6{constructor(e){d(this,"_context"),d(this,"_assetReferences",{}),d(this,"preUpdate",()=>{}),this._context=e,this._context.pre_update_callbacks.push(this.preUpdate)}dispose(){const e=this._context.pre_update_callbacks.indexOf(this.preUpdate);e>=0&&this._context.pre_update_callbacks.splice(e,1);for(const t in this._assetReferences){const r=this._assetReferences[t];r?.unload()}this._assetReferences={}}findAssetReference(e){return this._assetReferences[e]||null}registerAssetReference(e){return e.uri&&(this._assetReferences[e.uri]?console.warn("Asset reference already registered",e):this._assetReferences[e.uri]=e),e}unregisterAssetReference(e){e.uri&&delete this._assetReferences[e.uri]}}const pB=Symbol("assetReference"),Pg=class{constructor(n,e,t=null){d(this,"_loading"),d(this,"_asset"),d(this,"_glbRoot"),d(this,"_url"),d(this,"_progressListeners",[]),d(this,"_hash"),d(this,"_hashedUri"),d(this,"_isLoadingRawBinary",!1),d(this,"_rawBinary"),this._url=n,this._hash=e,n.includes("?v=")?this._hashedUri=n:this._hashedUri=e?n+"?v="+e:n,t!==null&&(this.asset=t),j8(this._url,this.onResolvePrefab.bind(this))}static getOrCreateFromUrl(n,e){if(!e&&(e=kt.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,r=t.findAssetReference(n);if(r)return r;const s=new Pg(n,e.hash);return t.registerAssetReference(s),s}static getOrCreate(n,e,t){if(typeof n=="string"){if(!t&&(t=kt.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=n.context,n=n.sourceId;const r=cu(n,e);Fu&&console.log("GetOrCreate Addressable from",n,e,"FinalPath=",r);const s=t.addressables,o=s.findAssetReference(r);if(o)return o;const a=new Pg(r,t.hash);return s.registerAssetReference(a),a}get asset(){return this._glbRoot??this._asset}set asset(n){this._asset=n}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:"))}get rawAsset(){return this._asset}async onResolvePrefab(n){return n===this.uri&&(this.mustLoad&&await this.loadAssetAsync(),this.asset)?this.asset:null}get mustLoad(){return!this.asset||this.asset.__destroyed===!0||Jp(this.asset)===!0}isLoaded(){return this._rawBinary||this.asset!==void 0}unload(){this.asset&&(Fu&&console.log("Unload",this.asset),this.asset.scene&&Ca(this.asset.scene,!0,!0),Ca(this.asset,!0,!0)),this.asset=null,this._rawBinary=void 0,this._glbRoot=null,this._loading=void 0,kt.Current&&kt.Current.addressables.unregisterAssetReference(this)}async preload(){if(!this.mustLoad||this._isLoadingRawBinary)return null;if(this._rawBinary!==void 0)return this._rawBinary;this._isLoadingRawBinary=!0,Fu&&console.log("Preload",this._hashedUri);const n=await C6(this._hashedUri,e=>{this.raiseProgressEvent(e)});return this._rawBinary=n?.buffer??null,this._isLoadingRawBinary=!1,this._rawBinary}async loadAssetAsync(n){if(Fu&&console.log("loadAssetAsync",this.uri),!this.mustLoad)return this.asset;if(n&&this._progressListeners.push(n),this._loading!==void 0)return this._loading.then(r=>this.asset);const e=kt.Current;this._rawBinary?(this._loading=Ka().parseSync(e,this._rawBinary,this.uri,null),this.raiseProgressEvent(new ProgressEvent("progress",{loaded:this._rawBinary.byteLength,total:this._rawBinary.byteLength}))):(Fu&&console.log("Load async",this.uri),this._loading=Ka().loadSync(e,this._hashedUri,this.uri,null,r=>{this.raiseProgressEvent(r)}));const t=await this._loading;if(this._progressListeners.length=0,this._glbRoot=this.tryGetActualGameObjectRoot(t),this._loading=void 0,t)return t[pB]=this,this._glbRoot&&(this._glbRoot[pB]=this),this.asset&&(this.asset[pB]=this),B1(e),t.scene!==void 0&&(this.asset=t),this.asset}async instantiate(n){return this.onInstantiate(n,!1)}async instantiateSynced(n,e=!0){return this.onInstantiate(n,!0,e)}beginListenDownload(n){this._progressListeners.indexOf(n)<0&&this._progressListeners.push(n)}endListenDownload(n){const e=this._progressListeners.indexOf(n);e>=0&&this._progressListeners.splice(e,1)}raiseProgressEvent(n){for(const e of this._progressListeners)e(this,n)}async onInstantiate(n,e=!1,t){const r=kt.Current,s=new Ml;if(n instanceof ye?s.parent=n:n&&(Object.assign(s,n),s.cloneAssign(n)),s.parent||(s.parent=r.scene),this.mustLoad&&await this.loadAssetAsync(),Fu&&console.log("Instantiate",this.uri,"parent:",n),this.asset){Fu&&console.log("Add to scene",this.asset);let o=Pg.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,Pg.currentlyInstantiating.set(this.uri,o),e){s.context=r;const a=this.asset;a.guid=this.uri;const l=ek(a,s,void 0,t);if(l)return l}else{const a=Gg(this.asset,s);if(a)return a}}finally{r.post_render_callbacks.push(()=>{o===void 0||o<0?o=0:o-=1,Pg.currentlyInstantiating.set(this.uri,o)})}}else Fu&&console.warn("Failed to load asset",this.uri);return null}tryGetActualGameObjectRoot(n){if(n&&n.scene){const e=n.scene;return e.isGroup&&e.children.length===1&&e.children[0].name+"glb"===e.name?e.children[0]:e}return null}};let ti=Pg;d(ti,"currentlyInstantiating",new Map);class lue extends wa{constructor(){super([ti],"AssetReferenceSerializer")}onSerialize(e,t){if(e&&e.uri!==void 0&&typeof e.uri=="string")return e.uri}onDeserialize(e,t){if(typeof e=="string")return t.context?t.gltfId?ti.getOrCreate(t.gltfId,e,t.context):(console.error("Missing source id"),null):(console.error("Missing context"),null);if(e instanceof ye){if(!t.context)return console.error("Missing context"),null;if(!t.gltfId)return console.error("Missing source id"),null;const r=e,s=t.context,o=r.guid??r.uuid,a=s.addressables.findAssetReference(o);if(a)return a;const l=new ti(o,void 0,r);return s.addressables.registerAssetReference(l),l}return null}}new lue;const cue=Promise.resolve(null),V1=class{constructor(n){d(this,"url"),d(this,"_bitmap"),d(this,"_bitmapObject"),d(this,"loader",null),this.url=n}static getOrCreate(n){let e=V1.imageReferences.get(n);return e||(e=new V1(n),V1.imageReferences.set(n,e)),e}dispose(){this._bitmapObject&&this._bitmapObject.close(),this._bitmap=void 0}createHTMLImage(){const n=new Image;return n.src=this.url,n}createTexture(){return this.url?(this.loader||(this.loader=new Dl),this.loader.setCrossOrigin("anonymous"),this.loader.loadAsync(this.url)):cue}getBitmap(){return this._bitmap?this._bitmap:(this._bitmap=new Promise((n,e)=>{const t=document.createElement("img");t.addEventListener("load",()=>{this._bitmap=createImageBitmap(t).then(r=>(this._bitmapObject=r,n(r),r))}),t.addEventListener("error",r=>{console.error("Failed to load image:"+this.url,r),n(null)}),t.src=this.url}),this._bitmap)}};let Q1=V1;d(Q1,"imageReferences",new Map);class M6 extends wa{constructor(){super([Q1],"ImageReferenceSerializer")}onSerialize(e,t){return null}onDeserialize(e,t){if(typeof e=="string"){const r=cu(t.gltfId,e);return Q1.getOrCreate(r)}}}new M6;const H1=class{constructor(n){d(this,"url"),d(this,"res"),this.url=n}static getOrCreate(n){let e=H1.cache.get(n);return e||(e=new H1(n),H1.cache.set(n,e)),e}async loadRaw(){return this.res||(this.res=fetch(this.url)),this.res.then(n=>n.blob())}async loadText(){return this.res||(this.res=fetch(this.url)),this.res.then(n=>n.text())}};let W1=H1;d(W1,"cache",new Map);class T6 extends wa{constructor(){super([W1],"FileReferenceSerializer")}onSerialize(e,t){return null}onDeserialize(e,t){if(typeof e=="string"){const r=cu(t.gltfId,e);return W1.getOrCreate(r)}}}new T6;class hue{constructor(e){d(this,"context"),d(this,"mixers",[]),this.context=e}onDestroy(){this.mixers.forEach(e=>e.stopAllAction()),this.mixers.length=0}registerAnimationMixer(e){if(!e){console.warn("AnimationsRegistry.registerAnimationMixer called with null or undefined mixer");return}this.mixers.includes(e)||this.mixers.push(e)}unregisterAnimationMixer(e){if(!e)return;const t=this.mixers.indexOf(e);t!==-1&&this.mixers.splice(t,1)}}class Bg{static tryGetActionsFromMixer(e){return e._actions||null}static tryGetAnimationClipsFromObjectHierarchy(e,t){if(t||(t=new Array),e)e.animations&&t.push(...e.animations);else return t;if(e.children)for(const r of e.children)this.tryGetAnimationClipsFromObjectHierarchy(r,t);return t}static assignAnimationsFromFile(e,t){if(!e||!e.animations)return;for(let s=0;s<e.animations.length;s++){const o=e.animations[s];if(!(!o.tracks||o.tracks.length<=0))for(const a in o.tracks){const l=o.tracks[a],c=Xt.parseTrackName(l.name);let h=Xt.findNode(e.scene,c.nodeName);if(!h){const p=l.__objectName??l.name.substring(0,l.name.indexOf("."));if(h=e.scene.getObjectByProperty("uuid",p),!h)continue}let u=r(h);if(!u){if(!(t!=null&&t.createAnimationComponent)){console.warn("No AnimationComponent found in parent hierarchy of object and no 'createAnimationComponent' callback was provided in options.");continue}u=t.createAnimationComponent(e.scene,o)}u.addClip&&u.addClip(o)}}function r(s){var o;if(!s)return null;const a=(o=s.userData)==null?void 0:o.components;if(a&&a.length>0){for(let l=0;l<a.length;l++)if(a[l].isAnimationComponent===!0)return s}return r(s.parent)}}}const kg=[];function X1(n){kg.indexOf(n)===-1&&kg.push(n)}function uue(n){const e=kg.indexOf(n);e!==-1&&kg.splice(e,1)}const Dg=[];function mB(n){Dg.indexOf(n)===-1&&Dg.push(n)}function due(n){const e=Dg.indexOf(n);e!==-1&&Dg.splice(e,1)}function I6(n){globalThis.dispatchEvent(new CustomEvent("needle-xrsession-start",{detail:n}));for(let e=0;e<kg.length;e++)kg[e](n)}function R6(n){globalThis.dispatchEvent(new CustomEvent("needle-xrsession-end",{detail:n}));for(let e=0;e<Dg.length;e++)Dg[e](n)}const wr={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 P6(n){const e=await fetch(n);if(e.ok)return e.json();throw new Error(e.statusText)}async function pue(n){if(!n)throw new Error("No basePath supplied");return await P6(`${n}/profilesList.json`)}async function mue(n,e,t=null,r=!0){if(!n)throw new Error("No xrInputSource supplied");if(!e)throw new Error("No basePath supplied");const s=await pue(e);let o;if(n.profiles.some(c=>{const h=s[c];return h&&(o={profileId:c,profilePath:`${e}/${h.path}`,deprecated:!!h.deprecated}),!!o}),!o){if(!t)throw new Error("No matching profile name found");const c=s[t];if(!c)throw new Error(`No matching profile name found and default profile "${t}" missing.`);o={profileId:t,profilePath:`${e}/${c.path}`,deprecated:!!c.deprecated}}const a=await P6(o.profilePath);let l;if(r){let c;if(n.handedness==="any"?c=a.layouts[Object.keys(a.layouts)[0]]:c=a.layouts[n.handedness],!c)throw new Error(`No matching handedness, ${n.handedness}, in profile ${o.profileId}`);c.assetPath&&(l=o.profilePath.replace("profile.json",c.assetPath))}return{profile:a,assetPath:l}}const fue={xAxis:0,yAxis:0,button:0,state:wr.ComponentState.DEFAULT};function gue(n=0,e=0){let t=n,r=e;if(Math.sqrt(n*n+e*e)>1){const s=Math.atan2(e,n);t=Math.cos(s),r=Math.sin(s)}return{normalizedXAxis:t*.5+.5,normalizedYAxis:r*.5+.5}}let vue=class{constructor(n){this.componentProperty=n.componentProperty,this.states=n.states,this.valueNodeName=n.valueNodeName,this.valueNodeProperty=n.valueNodeProperty,this.valueNodeProperty===wr.VisualResponseProperty.TRANSFORM&&(this.minNodeName=n.minNodeName,this.maxNodeName=n.maxNodeName),this.value=0,this.updateFromComponent(fue)}updateFromComponent({xAxis:n,yAxis:e,button:t,state:r}){const{normalizedXAxis:s,normalizedYAxis:o}=gue(n,e);switch(this.componentProperty){case wr.ComponentProperty.X_AXIS:this.value=this.states.includes(r)?s:.5;break;case wr.ComponentProperty.Y_AXIS:this.value=this.states.includes(r)?o:.5;break;case wr.ComponentProperty.BUTTON:this.value=this.states.includes(r)?t:0;break;case wr.ComponentProperty.STATE:this.valueNodeProperty===wr.VisualResponseProperty.VISIBILITY?this.value=this.states.includes(r):this.value=this.states.includes(r)?1:0;break;default:throw new Error(`Unexpected visualResponse componentProperty ${this.componentProperty}`)}}},yue=class{constructor(n,e){if(!n||!e||!e.visualResponses||!e.gamepadIndices||Object.keys(e.gamepadIndices).length===0)throw new Error("Invalid arguments supplied");this.id=n,this.type=e.type,this.rootNodeName=e.rootNodeName,this.touchPointNodeName=e.touchPointNodeName,this.visualResponses={},Object.keys(e.visualResponses).forEach(t=>{const r=new vue(e.visualResponses[t]);this.visualResponses[t]=r}),this.gamepadIndices=Object.assign({},e.gamepadIndices),this.values={state:wr.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(n){if(this.values.state=wr.ComponentState.DEFAULT,this.gamepadIndices.button!==void 0&&n.buttons.length>this.gamepadIndices.button){const e=n.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=wr.ComponentState.PRESSED:(e.touched||this.values.button>wr.ButtonTouchThreshold)&&(this.values.state=wr.ComponentState.TOUCHED)}this.gamepadIndices.xAxis!==void 0&&n.axes.length>this.gamepadIndices.xAxis&&(this.values.xAxis=n.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===wr.ComponentState.DEFAULT&&Math.abs(this.values.xAxis)>wr.AxisTouchThreshold&&(this.values.state=wr.ComponentState.TOUCHED)),this.gamepadIndices.yAxis!==void 0&&n.axes.length>this.gamepadIndices.yAxis&&(this.values.yAxis=n.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===wr.ComponentState.DEFAULT&&Math.abs(this.values.yAxis)>wr.AxisTouchThreshold&&(this.values.state=wr.ComponentState.TOUCHED)),Object.values(this.visualResponses).forEach(e=>{e.updateFromComponent(this.values)})}},Aue=class{constructor(n,e,t){if(!n)throw new Error("No xrInputSource supplied");if(!e)throw new Error("No profile supplied");this.xrInputSource=n,this.assetUrl=t,this.id=e.profileId,this.layoutDescription=e.layouts[n.handedness],this.components={},Object.keys(this.layoutDescription.components).forEach(r=>{const s=this.layoutDescription.components[r];this.components[r]=new yue(r,s)}),this.updateFromGamepad()}get gripSpace(){return this.xrInputSource.gripSpace}get targetRaySpace(){return this.xrInputSource.targetRaySpace}get data(){const n=[];return Object.values(this.components).forEach(e=>{n.push(e.data)}),n}updateFromGamepad(){Object.values(this.components).forEach(n=>{n.updateFromGamepad(this.xrInputSource.gamepad)})}};const Js=new C,B6=new C,k6=new Ce,bue=te("debuggizmos"),Wl=8947848,Xl=class{constructor(){}static isGizmo(n){return n[gB]!==void 0}static DrawLabel(n,e,t=.05,r=0,s,o,a){var l;if(!Xl.enabled)return null;s||(s=Wl);const c=((l=wt.active)==null?void 0:l.rigScale)??1,h=En.getTextLabel(r,e,t*c,s,o);return a instanceof ye&&a.add(h),h.position.x=n.x,h.position.y=n.y,h.position.z=n.z,h}static DrawRay(n,e,t=Wl,r=0,s=!0){if(!Xl.enabled)return;const o=En.getLine(r),a=o.geometry.getAttribute("position");a.setXYZ(0,n.x,n.y,n.z),Js.set(e.x,e.y,e.z).multiplyScalar(999999999),a.setXYZ(1,n.x+Js.x,n.y+Js.y,n.z+Js.z),a.needsUpdate=!0,o.material.color.set(t),o.material.depthTest=s,o.material.depthWrite=!1}static DrawDirection(n,e,t=Wl,r=0,s=!0,o=1){if(!Xl.enabled)return;const a=En.getLine(r),l=a.geometry.getAttribute("position");l.setXYZ(0,n.x,n.y,n.z),e.w!==void 0?(Js.set(0,0,-o),k6.set(e.x,e.y,e.z,e.w),Js.applyQuaternion(k6)):(Js.set(e.x,e.y,e.z),Js.multiplyScalar(o)),l.setXYZ(1,n.x+Js.x,n.y+Js.y,n.z+Js.z),l.needsUpdate=!0,a.material.color.set(t),a.material.depthTest=s,a.material.depthWrite=!1}static DrawLine(n,e,t=Wl,r=0,s=!0){if(!Xl.enabled)return;const o=En.getLine(r),a=o.geometry.getAttribute("position");a.setXYZ(0,n.x,n.y,n.z),a.setXYZ(1,e.x,e.y,e.z),a.needsUpdate=!0,o.material.color.set(t),o.material.depthTest=s,o.material.depthWrite=!1,o.material.fog=!1}static DrawWireSphere(n,e,t=Wl,r=0,s=!0){if(!Xl.enabled)return;const o=En.getSphere(e,r,!0);_p(o,n.x,n.y,n.z),o.material.color.set(t),o.material.depthTest=s,o.material.depthWrite=!1,o.material.fog=!1}static DrawSphere(n,e,t=Wl,r=0,s=!0){if(!Xl.enabled)return;const o=En.getSphere(e,r,!1);_p(o,n.x,n.y,n.z),o.material.color.set(t),o.material.depthTest=s,o.material.depthWrite=!1}static DrawWireBox(n,e,t=Wl,r=0,s=!0){if(!Xl.enabled)return;const o=En.getBox(r);o.position.set(n.x,n.y,n.z),o.scale.set(e.x,e.y,e.z),o.material.color.set(t),o.material.depthTest=s,o.material.wireframe=!0,o.material.depthWrite=!1,o.material.fog=!1}static DrawWireBox3(n,e=Wl,t=0,r=!0){if(!Xl.enabled)return;const s=En.getBox(t);s.position.copy(n.getCenter(Js)),s.scale.copy(n.getSize(Js)),s.material.color.set(e),s.material.depthTest=r,s.material.wireframe=!0,s.material.depthWrite=!1,s.material.fog=!1}static DrawArrow(n,e,t=Wl,r=0,s=!0,o=!1){if(!Xl.enabled)return;const a=En.getArrowHead(r);a.position.set(e.x,e.y,e.z),a.quaternion.setFromUnitVectors(this._up.set(0,1,0),Js.set(e.x,e.y,e.z).sub(B6.set(n.x,n.y,n.z)).normalize());const l=Js.set(e.x,e.y,e.z).sub(B6.set(n.x,n.y,n.z)).length()*.1;a.scale.set(l,l,l),a.material.color.set(t),a.material.depthTest=s,a.material.wireframe=o,this.DrawLine(n,e,t,r,s)}static DrawWireMesh(n){const e=En.getMesh(n.duration??0);"mesh"in n?(e.geometry=n.mesh.geometry,e.matrix.copy(n.mesh.matrixWorld)):(e.geometry=n.geometry,e.matrix.copy(n.matrix)),e.matrixAutoUpdate=!1,e.matrixWorldAutoUpdate=!1,e.material.color.set(n.color??Wl),e.material.depthTest=n.depthTest??!0,e.material.wireframe=!0}};let At=Xl;d(At,"enabled",!0),d(At,"_up",new C(0,1,0));const _ue=new qi(1,1,1);function fB(n=null){const e=new xe(n??14540253),t=new iI(_ue);return new gs(t,new Gi({color:e}))}const gB=Symbol("GizmoCache");class En{static ensureFont(){let e=Ni.FontLibrary.getFontFamily(this.familyName);if(!e){e=Ni.FontLibrary.addFontFamily(this.familyName);const t=e.addVariant("normal","normal","https://uploads.needle.tools/include/font-msdf.json","https://uploads.needle.tools/include/font.png");t?.addEventListener("ready",()=>{Ni.update()})}}static getTextLabel(e,t,r,s,o){this.ensureFont();let a=this.textLabelCache.pop(),l=1;o&&typeof o=="string"&&o?.length>=8&&o.startsWith("#")?(l=parseInt(o.substring(7),16)/255,o=o.substring(0,7),bue&&console.log(o,l)):typeof o=="object"&&o.a!==void 0&&(l=o.a);const c={boxSizing:"border-box",fontFamily:this.familyName,width:"auto",fontSize:r,color:s,lineHeight:1,backgroundColor:o??void 0,backgroundOpacity:l,textContent:t,borderRadius:.5*r,padding:.8*r,whiteSpace:"pre"};if(a)a.set(c);else{a=new fR(c);const h=this,u=a;u.setText=function(p){this.set({textContent:p}),h.tmuiNeedsUpdate=!0}}return this.tmuiNeedsUpdate=!0,this.registerTimedObject(kt.Current,a,e,this.textLabelCache),a}static getBox(e){let t=this.boxesCache.pop();if(!t){const r=new qi(1,1,1);t=new me(r)}return this.registerTimedObject(kt.Current,t,e,this.boxesCache),t}static getLine(e){let t=this.linesCache.pop();if(!t){t=new Sn;let r=t.geometry.getAttribute("position");r||(r=new nt(new Float32Array(2*3),3),t.geometry.setAttribute("position",r))}return t.frustumCulled=!1,this.registerTimedObject(kt.Current,t,e,this.linesCache),t}static getSphere(e,t,r){let s=this.spheresCache.pop();return s||(s=new me(new ja(1,8,8))),s.scale.set(e,e,e),s.material.wireframe=r,this.registerTimedObject(kt.Current,s,t,this.spheresCache),s}static getArrowHead(e){let t=this.arrowHeadsCache.pop();return t||(t=new me(new jn(0,.5,1,8))),this.registerTimedObject(kt.Current,t,e,this.arrowHeadsCache),t}static getMesh(e){let t=this.mesh.pop();return t||(t=new me,t.material=new $t),this.registerTimedObject(kt.Current,t,e,this.mesh),t}static registerTimedObject(e,t,r,s){const o=this.contextBeforeRenderCallbacks.get(e),a=this.contextPostRenderCallbacks.get(e);if(o){if(e.pre_render_callbacks[e.pre_render_callbacks.length-1]!==o){const l=e.pre_render_callbacks.indexOf(o);l>=0&&e.pre_render_callbacks.splice(l,1),e.pre_render_callbacks.push(o)}}else{const l=()=>{this.onBeforeRender(e,this.timedObjectsBuffer)};this.contextBeforeRenderCallbacks.set(e,l),e.pre_render_callbacks.push(l)}if(a){if(e.post_render_callbacks[e.post_render_callbacks.length-1]!==a){const l=e.post_render_callbacks.indexOf(a);l>=0&&e.post_render_callbacks.splice(l,1),e.post_render_callbacks.push(a)}}else{const l=()=>{this.onPostRender(e,this.timedObjectsBuffer,this.timesBuffer)};this.contextPostRenderCallbacks.set(e,l),e.post_render_callbacks.push(l)}t.traverse(l=>{l.layers.disableAll(),l.layers.enable(2)}),t.renderOrder=999999,t[gB]=s,t.isGizmo=!0,this.timedObjectsBuffer.push(t),r<=0&&e.currentFrameEvent>=Hi.OnBeforeRender?this.timesBuffer.push(0):this.timesBuffer.push(kt.Current.time.realtimeSinceStartup+r),e.scene.add(t)}static onBeforeRender(e,t){this.tmuiNeedsUpdate&&Ni.update();for(let r=0;r<t.length;r++){const s=t[r];if(e.mainCamera&&s instanceof Ni.MeshUIBaseElement){if(Jp(s))continue;const o=e.isInVR,a=!1,l=!o;Hv(s,e.mainCamera,a,l)}}}static onPostRender(e,t,r){const s=e.time.realtimeSinceStartup;for(let o=t.length-1;o>=0;o--){const a=t[o];s>r[o]&&(t.splice(o,1),r.splice(o,1),a.removeFromParent(),Jp(a)!=!0&&a[gB].push(a))}}}d(En,"familyName","needle-gizmos"),d(En,"linesCache",[]),d(En,"spheresCache",[]),d(En,"boxesCache",[]),d(En,"arrowHeadsCache",[]),d(En,"mesh",[]),d(En,"textLabelCache",[]),d(En,"timedObjectsBuffer",new Array),d(En,"timesBuffer",new Array),d(En,"contextPostRenderCallbacks",new Map),d(En,"contextBeforeRenderCallbacks",new Map),d(En,"tmuiNeedsUpdate",!1);const cr=te("debuginput");var q1=(n=>(n.Mouse="mouse",n.Touch="touch",n.Controller="controller",n.Hand="hand",n))(q1||{}),an=(n=>(n.PointerDown="pointerdown",n.PointerUp="pointerup",n.PointerMove="pointermove",n.KeyDown="keydown",n.KeyUp="keyup",n.KeyPressed="keypress",n))(an||{});class mh extends PointerEvent{constructor(e,t,r){super(e,r),d(this,"deviceIndex"),d(this,"origin"),d(this,"source"),d(this,"mode"),d(this,"_ray"),d(this,"space"),d(this,"isClick",!1),d(this,"isDoubleClick",!1),d(this,"_used",!1),d(this,"_pointerid"),d(this,"_pointerType"),d(this,"_type"),d(this,"metadata",{}),d(this,"intersections",new Array),d(this,"_immediatePropagationStopped",!1),d(this,"_propagationStopped",!1),this._pointerid=r.pointerId,this._pointerType=r.pointerType,this._type=e,this.deviceIndex=r.deviceIndex,this.origin=r.origin,this.source=t,this.mode=r.mode,this._ray=r.ray,this.space=r.device}get ray(){return this._ray||(this._ray=new co(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(),cr&&console.warn("Stop propagation...",this.pointerId,this.pointerType)}}class Xy extends KeyboardEvent{constructor(e,t,r){super(e,r),d(this,"source"),this.source=t}stopImmediatePropagation(){var e;super.stopImmediatePropagation(),(e=this.source)==null||e.stopImmediatePropagation()}}class xue{constructor(e){d(this,"key"),d(this,"keyType"),d(this,"source"),this.key=e.key,this.keyType=e.type,this.source=e}}var ql=(n=>(n[n.Early=-100]="Early",n[n.Default=0]="Default",n[n.Late=100]="Late",n))(ql||{});class D6{constructor(e){d(this,"_eventListeners",{}),d(this,"_doubleClickTimeThreshold",.2),d(this,"_longPressTimeThreshold",1),d(this,"_specialCursorTrigger",0),d(this,"context"),d(this,"_pointerDown",[!1]),d(this,"_pointerUp",[!1]),d(this,"_pointerClick",[!1]),d(this,"_pointerDoubleClick",[!1]),d(this,"_pointerPressed",[!1]),d(this,"_pointerPositions",[new Z]),d(this,"_pointerPositionsLastFrame",[new Z]),d(this,"_pointerPositionsDelta",[new Z]),d(this,"_pointerPositionsRC",[new Z]),d(this,"_pointerPositionDown",[new Z]),d(this,"_pointerDownTime",[]),d(this,"_pointerUpTime",[]),d(this,"_pointerUpTimestamp",[]),d(this,"_pointerIds",[]),d(this,"_pointerTypes",[""]),d(this,"_mouseWheelChanged",[!1]),d(this,"_mouseWheelDeltaY",[0]),d(this,"_pointerEvent",[]),d(this,"_pointerUsed",[]),d(this,"_pointerSpace",[]),d(this,"_pressedStack",new Map),d(this,"_htmlEventSource"),d(this,"onLostFocus",()=>{for(const t in this.keysPressed)this.keysPressed[t].pressed=!1}),d(this,"onEndOfFrame",()=>{for(let t=0;t<this._pointerUp.length;t++)this._pointerUp[t]=!1;for(let t=0;t<this._pointerDown.length;t++)this._pointerDown[t]=!1;for(let t=0;t<this._pointerClick.length;t++)this._pointerClick[t]=!1;for(let t=0;t<this._pointerDoubleClick.length;t++)this._pointerDoubleClick[t]=!1;for(const t of this._pointerPositionsDelta)t.set(0,0);for(let t=0;t<this._mouseWheelChanged.length;t++)this._mouseWheelChanged[t]=!1;for(let t=0;t<this._mouseWheelDeltaY.length;t++)this._mouseWheelDeltaY[t]=0}),d(this,"onContextMenu",t=>{this.canReceiveInput(t)!==!1&&t instanceof PointerEvent&&t.pointerType}),d(this,"keysPressed",{}),d(this,"onKeyDown",t=>{if(cr&&console.log(`key down ${t.code}, ${this.context.application.hasFocus}`,t),!this.context.application.hasFocus)return;const r=this.keysPressed[t.code];if(r&&r.pressed)return;this.keysPressed[t.code]={pressed:!0,frame:this.context.time.frameCount+1,startFrame:this.context.time.frameCount+1,key:t.key,code:t.code};const s=new Xy("keydown",t,t);this.onDispatchEvent(s)}),d(this,"onKeyPressed",t=>{if(!this.context.application.hasFocus)return;const r=this.keysPressed[t.code];if(!r)return;r.pressed=!0,r.frame=this.context.time.frameCount+1;const s=new Xy("keypress",t,t);this.onDispatchEvent(s)}),d(this,"onKeyUp",t=>{if(!this.context.application.hasFocus)return;const r=this.keysPressed[t.code];if(!r)return;r.pressed=!1,r.frame=this.context.time.frameCount+1;const s=new Xy("keyup",t,t);this.onDispatchEvent(s)}),d(this,"onWheelWindow",t=>{document.pointerLockElement&&this.onMouseWheel(t)}),d(this,"onMouseWheel",t=>{if(this.canReceiveInput(t)===!1)return;this._mouseWheelDeltaY.length<=0&&this._mouseWheelDeltaY.push(0),this._mouseWheelChanged.length<=0&&this._mouseWheelChanged.push(!1),this._mouseWheelChanged[0]=!0;const r=this._mouseWheelDeltaY[0];this._mouseWheelDeltaY[0]=r+t.deltaY}),d(this,"onPointerDown",t=>{if(this.context.isInAR||this.canReceiveInput(t)===!1)return;t.target instanceof HTMLElement&&t.target.setPointerCapture(t.pointerId);const r=this.getPointerId(t);cr&&rn(`pointer down #${r}, identifier:${t.pointerId}`);const s=this.getAndUpdateSpatialObjectForScreenPosition(r,t.clientX,t.clientY),o=new mh("pointerdown",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:r,button:t.button,clientX:t.clientX,clientY:t.clientY,pointerType:t.pointerType,buttonName:this.getButtonName(t),device:s,pressure:t.pressure});this.onDown(o)}),d(this,"onPointerMove",t=>{if(this.context.isInAR)return;let r=t.button;t.pointerType==="mouse"&&(r=this.getFirstPressedButtonForPointer(0)??0);const s=this.getPointerId(t,r);r===-1&&(r=s);const o=this.getAndUpdateSpatialObjectForScreenPosition(s,t.clientX,t.clientY),a=new mh("pointermove",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:s,button:r,clientX:t.clientX,clientY:t.clientY,pointerType:t.pointerType,buttonName:this.getButtonName(t),device:o,pressure:t.pressure});this.onMove(a)}),d(this,"onPointerCancel",t=>{this.context.isInAR||(cr&&console.log("Pointer cancel",t),this.onPointerUp(t))}),d(this,"onPointerUp",t=>{if(this.context.isInAR)return;t.target instanceof HTMLElement&&t.target.releasePointerCapture(t.pointerId);const r=this.getPointerId(t),s=new mh("pointerup",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:r,button:t.button,clientX:t.clientX,clientY:t.clientY,pointerType:t.pointerType,buttonName:this.getButtonName(t),device:this.getAndUpdateSpatialObjectForScreenPosition(r,t.clientX,t.clientY),pressure:t.pressure});this.onUp(s),this._pointerIds[r]=-1,cr&&console.log("ID="+r,"PointerId="+t.pointerId,"ALL:",[...this._pointerIds])}),d(this,"onTouchStart",t=>{if(this.context.isInAR)for(let r=0;r<t.changedTouches.length;r++){const s=t.changedTouches[r],o=this.getPointerIndex(s.identifier),a=this.getAndUpdateSpatialObjectForScreenPosition(o,s.clientX,s.clientY),l=new mh("pointerdown",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:o,button:0,clientX:s.clientX,clientY:s.clientY,pointerType:"touch",buttonName:"unknown",device:a,pressure:s.force});this.onDown(l)}}),d(this,"onTouchMove",t=>{if(this.context.isInAR)for(let r=0;r<t.changedTouches.length;r++){const s=t.changedTouches[r],o=this.getPointerIndex(s.identifier),a=this.getAndUpdateSpatialObjectForScreenPosition(o,s.clientX,s.clientY),l=new mh("pointermove",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:o,button:0,clientX:s.clientX,clientY:s.clientY,pointerType:"touch",buttonName:"unknown",device:a,pressure:s.force});this.onMove(l)}}),d(this,"onTouchEnd",t=>{if(this.context.isInAR)for(let r=0;r<t.changedTouches.length;r++){const s=t.changedTouches[r],o=this.getPointerIndex(s.identifier),a=new mh("pointerup",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:o,button:0,clientX:s.clientX,clientY:s.clientY,pointerType:"touch",buttonName:"unknown",device:this.getAndUpdateSpatialObjectForScreenPosition(o,s.clientX,s.clientY),pressure:s.force});this.onUp(a),this._pointerIds[o]=-1}}),d(this,"tempNearPlaneVector",new C),d(this,"tempFarPlaneVector",new C),d(this,"tempLookMatrix",new ve),this.context=e,this.context.post_render_callbacks.push(this.onEndOfFrame)}addEventListener(e,t,r){if(this._eventListeners[e]||(this._eventListeners[e]=[]),!t||typeof t!="function"){console.error("Invalid call to addEventListener: callback is required and must be a function!");return}r?r={...r}:r={};let s=0;r?.queue!=null&&(s=r.queue);const o=this._eventListeners[e],a=o.find(l=>l.priority===s);a?a.listeners.push({callback:t,options:r}):(o.push({priority:s,listeners:[{callback:t,options:r}]}),o.sort((l,c)=>l.priority-c.priority))}removeEventListener(e,t,r){if(!this._eventListeners[e]||!t)return;const s=this._eventListeners[e];if(r?.queue!=null){const o=s.find(l=>l.priority===r.queue);if(!o)return;const a=o.listeners.findIndex(l=>l.callback===t);a>=0&&o.listeners.splice(a,1)}else for(const o of s){const a=o.listeners.findIndex(l=>l.callback===t);a>=0&&o.listeners.splice(a,1)}}dispatchEvent(e){var t,r,s,o;let a=!1;if(e instanceof Xy){const l=this._eventListeners[e.type];if(l)for(const c of l)for(let h=0;h<c.listeners.length;h++){const u=c.listeners[h];if((r=(t=u.options)==null?void 0:t.signal)!=null&&r.aborted){c.listeners.splice(h,1),h--;continue}u.options.once&&(c.listeners.splice(h,1),h--),u.callback(e)}}if(e instanceof mh){const l=this._eventListeners[e.type];if(l)for(const c of l){if(a)break;for(let h=0;h<c.listeners.length;h++){const u=c.listeners[h];if((o=(s=u.options)==null?void 0:s.signal)!=null&&o.aborted){c.listeners.splice(h,1),h--;continue}if(e.immediatePropagationStopped){a=!0,cr&&console.log("immediatePropagationStopped",e.type);break}else e.propagationStopped&&(a=!0,cr&&console.log("propagationStopped",e.type));u.options.once&&(c.listeners.splice(h,1),h--),u.callback(e)}}}}get mousePosition(){return this._pointerPositions[0]}get mousePositionRC(){return this._pointerPositionsRC[0]}get mouseDown(){return this._pointerDown[0]}get mouseUp(){return this._pointerUp[0]}get mouseClick(){return this._pointerClick[0]}get mouseDoubleClick(){return this._pointerDoubleClick[0]}get mousePressed(){return this._pointerPressed[0]}get mouseWheelChanged(){return this.getMouseWheelChanged(0)}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(e,t=!0){if(e>=this._pointerUsed.length){if(e>=this._pointerIds.length)return;for(;this._pointerUsed.length<=e;)this._pointerUsed.push(!1)}this._pointerUsed[e]=t}getPointerUsed(e){return e>=this._pointerUsed.length?!1:this._pointerUsed[e]}getPointerPressedCount(){let e=0;for(let t=0;t<this._pointerPressed.length;t++)this._pointerPressed[t]&&e++;return e}getPointerPosition(e){return e>=this._pointerPositions.length?null:this._pointerPositions[e]}getPointerPositionLastFrame(e){return e>=this._pointerPositionsLastFrame.length?null:this._pointerPositionsLastFrame[e]}getPointerPositionDelta(e){return e>=this._pointerPositionsDelta.length?null:this._pointerPositionsDelta[e]}getPointerPositionRC(e){return e>=this._pointerPositionsRC.length?null:this._pointerPositionsRC[e]}getPointerDown(e){return e>=this._pointerDown.length?!1:this._pointerDown[e]}getPointerUp(e){return e>=this._pointerUp.length?!1:this._pointerUp[e]}getPointerPressed(e){return e>=this._pointerPressed.length?!1:this._pointerPressed[e]}getPointerClicked(e){return e>=this._pointerClick.length?!1:this._pointerClick[e]}getPointerDoubleClicked(e){return e>=this._pointerDoubleClick.length?!1:this._pointerDoubleClick[e]}getPointerDownTime(e){return e>=this._pointerDownTime.length?-1:this._pointerDownTime[e]}getPointerUpTime(e){return e>=this._pointerUpTime.length?-1:this._pointerUpTime[e]}getPointerLongPress(e){return e>=this._pointerDownTime.length?!1:this.getPointerPressed(e)&&this.context.time.time-this._pointerDownTime[e]>this._longPressTimeThreshold}getIsMouse(e){return e<0||e>=this._pointerTypes.length?!1:this._pointerTypes[e]==="mouse"}getIsTouch(e){return e<0||e>=this._pointerTypes.length?!1:this._pointerTypes[e]==="touch"}getTouchesPressedCount(){let e=0;for(let t=0;t<this._pointerPressed.length;t++)this._pointerPressed[t]&&this.getIsTouch(t)&&e++;return e}getMouseWheelChanged(e=0){return e>=this._mouseWheelChanged.length?!1:this._mouseWheelChanged[e]}getMouseWheelDeltaY(e=0){return e>=this._mouseWheelDeltaY.length?0:this._mouseWheelDeltaY[e]}getPointerEvent(e){if(!(e>=this._pointerEvent.length))return this._pointerEvent[e]??void 0}*foreachPointerId(e){for(let t=0;t<this._pointerTypes.length;t++)if(this._pointerIsActive(t)){if(e!==void 0){const r=this._pointerTypes[t];if(Array.isArray(e)){let s=!1;for(const o of e)if(r===o){s=!0;break}if(!s)continue}else if(e!==r)continue}yield t}}*foreachTouchId(){for(let e=0;e<this._pointerTypes.length;e++)this._pointerTypes[e]==="touch"&&this._pointerIsActive[e]&&(yield e)}_pointerIsActive(e){return e<0?!1:this._pointerPressed[e]||this._pointerDown[e]||this._pointerUp[e]}onDownButton(e,t){let r=this._pressedStack.get(e);r||(r=[],this._pressedStack.set(e,r)),r.push(t)}onReleaseButton(e,t){const r=this._pressedStack.get(e);if(!r)return;const s=r.indexOf(t);s>=0&&r.splice(s,1)}getFirstPressedButtonForPointer(e){const t=this._pressedStack.get(e);if(t)return t[0]}getLatestPressedButtonForPointer(e){const t=this._pressedStack.get(e);if(t)return t[t.length-1]}getKeyDown(){for(const e in this.keysPressed){const t=this.keysPressed[e];if(t.startFrame===this.context.time.frameCount)return t.key}return null}getKeyPressed(){for(const e in this.keysPressed){const t=this.keysPressed[e];if(t.pressed)return t.key}return null}isKeyDown(e){var t;if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const r=this.getCodeForCommonKeyName(e);if(r!==null){for(const s of r)if(this.isKeyDown(s))return!0;return!1}return((t=this.keysPressed[e])==null?void 0:t.startFrame)===this.context.time.frameCount&&this.keysPressed[e].pressed}isKeyUp(e){var t;if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const r=this.getCodeForCommonKeyName(e);if(r!==null){for(const s of r)if(this.isKeyUp(s))return!0;return!1}return((t=this.keysPressed[e])==null?void 0:t.frame)===this.context.time.frameCount&&!this.keysPressed[e].pressed}isKeyPressed(e){var t;if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const r=this.getCodeForCommonKeyName(e);if(r!==null){for(const s of r)if(this.isKeyPressed(s))return!0;return!1}return(t=this.keysPressed[e])==null?void 0:t.pressed}getCodeForCommonKeyName(e){if(e.length===1){if(e>="0"&&e<="9")return["Digit"+e];if(e>="a"&&e<="z")return["Key"+e.toUpperCase()];if(e==" ")return["Space"]}switch(e){case"shift":case"Shift":return["ShiftLeft","ShiftRight"];case"control":case"Control":return["ControlLeft","ControlRight"];case"alt":case"Alt":return["AltLeft","AltRight"]}return null}createInputEvent(e){switch(e.type){case"pointerdown":cr&&rn("Create Pointer down"),this.onDownButton(e.deviceIndex,e.button),this.onDown(e);break;case"pointermove":cr&&rn("Create Pointer move"),this.onMove(e);break;case"pointerup":cr&&rn("Create Pointer up"),this.onUp(e),this.onReleaseButton(e.deviceIndex,e.button);break}}convertScreenspaceToRaycastSpace(e){return e.x=(e.x-this.context.domX)/this.context.domWidth*2-1,e.y=-((e.y-this.context.domY)/this.context.domHeight)*2+1,e}bindEvents(){this.unbindEvents(),this._htmlEventSource=this.context.renderer.domElement,window.addEventListener("contextmenu",this.onContextMenu),this._htmlEventSource.addEventListener("pointerdown",this.onPointerDown,{passive:!0}),window.addEventListener("pointermove",this.onPointerMove,{passive:!0,capture:!0}),window.addEventListener("pointerup",this.onPointerUp,{passive:!0}),window.addEventListener("pointercancel",this.onPointerCancel,{passive:!0}),window.addEventListener("touchstart",this.onTouchStart,{passive:!0}),window.addEventListener("touchmove",this.onTouchMove,{passive:!0}),window.addEventListener("touchend",this.onTouchEnd,{passive:!0}),this._htmlEventSource.addEventListener("wheel",this.onMouseWheel,{passive:!0}),window.addEventListener("wheel",this.onWheelWindow,{passive:!0}),window.addEventListener("keydown",this.onKeyDown,!1),window.addEventListener("keypress",this.onKeyPressed,!1),window.addEventListener("keyup",this.onKeyUp,!1),window.addEventListener("blur",this.onLostFocus)}unbindEvents(){var e,t;window.removeEventListener("contextmenu",this.onContextMenu),(e=this._htmlEventSource)==null||e.removeEventListener("pointerdown",this.onPointerDown),window.removeEventListener("pointermove",this.onPointerMove),window.removeEventListener("pointerup",this.onPointerUp),window.removeEventListener("pointercancel",this.onPointerCancel),(t=this._htmlEventSource)==null||t.removeEventListener("wheel",this.onMouseWheel,!1),window.removeEventListener("wheel",this.onWheelWindow,!1),window.removeEventListener("keydown",this.onKeyDown,!1),window.removeEventListener("keypress",this.onKeyPressed,!1),window.removeEventListener("keyup",this.onKeyUp,!1),window.removeEventListener("blur",this.onLostFocus)}dispose(){const e=this.context.post_render_callbacks.indexOf(this.onEndOfFrame);e>=0&&this.context.post_render_callbacks.splice(e,1),this.unbindEvents()}canReceiveInput(e){var t;return e.target===((t=this.context.renderer)==null?void 0:t.domElement)||e.target===this.context.domElement||this.context.isInAR||this.context.isInAR&&e.target===document.body&&gp()?!0:(cr&&console.warn("CanReceiveInput:False for",e.target),!1)}getPointerId(e,t){return e.pointerType==="mouse"?0+(t??e.button):this.getPointerIndex(e.pointerId)}getButtonName(e){const t=e.button;if(e.pointerType==="mouse")switch(t){case 0:return"left";case 1:return"middle";case 2:return"right"}return"unknown"}getAndUpdateSpatialObjectForScreenPosition(e,t,r){let s=this._pointerSpace[e];s||(s=new ye,this._pointerSpace[e]=s),this._pointerSpace[e]=s;const o=this.context.mainCamera;if(o){const a=this.tempNearPlaneVector.set(t,r,-1);this.convertScreenspaceToRaycastSpace(a);const l=this.tempFarPlaneVector.set(a.x,a.y,1);a.unproject(o),l.unproject(o);const c=o.worldUp||pi(0,1,0).applyQuaternion(Mi(o));this.tempLookMatrix.lookAt(l,a,c),s.position.set(a.x,a.y,a.z),s.quaternion.setFromRotationMatrix(this.tempLookMatrix)}return s}isInRect(e){if(this.context.isInXR)return!0;const t=this.context.domElement.getBoundingClientRect(),r=e.clientX,s=e.clientY,o=r>=t.x&&r<=t.right&&s>=t.y&&s<=t.bottom;return cr&&!o&&console.log("Not in rect",t,r,s),o}onDown(e){const t=e.pointerId;if(this.getPointerPressed(t)&&console.warn(`pointerId is already pressed: ${t}`,cr?e:""),cr&&console.log(e.pointerType,"DOWN",t),!!this.isInRect(e)){for(this.setPointerState(t,this._pointerPressed,!0),this.setPointerState(t,this._pointerDown,!0),this.setPointerStateT(t,this._pointerEvent,e.source);t>=this._pointerTypes.length;)this._pointerTypes.push(e.pointerType);for(this._pointerTypes[t]=e.pointerType;t>=this._pointerPositionDown.length;)this._pointerPositionDown.push(new Z);for(this._pointerPositionDown[t].set(e.clientX,e.clientY);t>=this._pointerPositions.length;)this._pointerPositions.push(new Z);this._pointerPositions[t].set(e.clientX,e.clientY),t>=this._pointerDownTime.length&&this._pointerDownTime.push(0),this._pointerDownTime[t]=this.context.time.time,this.updatePointerPosition(e),this.onDispatchEvent(e)}}onMove(e){const t=e.pointerId,r=this.getPointerPressed(t);r===!1&&!this.isInRect(e)||e.pointerType==="touch"&&!r||(this.updatePointerPosition(e),this.setPointerStateT(t,this._pointerEvent,e.source),this.onDispatchEvent(e))}onUp(e){const t=e.pointerId;if(!this.getPointerPressed(t)){cr&&console.log(e.pointerType,"UP",t,"was not down");return}for(cr&&console.log(e.pointerType,"UP",t),this.setPointerState(t,this._pointerPressed,!1),this.setPointerStateT(t,this._pointerEvent,e.source),this.setPointerState(t,this._pointerUp,!0);t>=this._pointerUsed.length;)this._pointerUsed.push(!1);if(this.setPointerState(t,this._pointerUsed,!1),this.updatePointerPosition(e),!this._pointerPositionDown[t]){cr&&Di("Received pointer up event without matching down event for button: "+t),console.warn("Received pointer up event without matching down event for button: "+t);return}const r=e.clientX-this._pointerPositionDown[t].x,s=e.clientY-this._pointerPositionDown[t].y;if(t>=this._pointerUpTime.length&&this._pointerUpTime.push(-99),Math.abs(r)<5&&Math.abs(s)<5){cr&&console.log("CLICK",t),this.setPointerState(t,this._pointerClick,!0),e.isClick=!0;const o=this._pointerUpTime[t],a=this.context.time.time-o;a<this._doubleClickTimeThreshold&&a>0&&(this.setPointerState(t,this._pointerDoubleClick,!0),e.isDoubleClick=!0)}this._pointerUpTime[t]=this.context.time.time,this.onDispatchEvent(e)}updatePointerPosition(e){const t=e.pointerId;for(;t>=this._pointerPositions.length;)this._pointerPositions.push(new Z);for(;t>=this._pointerPositionsLastFrame.length;)this._pointerPositionsLastFrame.push(new Z);for(;t>=this._pointerPositionsDelta.length;)this._pointerPositionsDelta.push(new Z);const r=this._pointerPositionsLastFrame[t];r.copy(this._pointerPositions[t]);const s=this._pointerPositionsDelta[t];let o=e.clientX-r.x,a=e.clientY-r.y;if(e.source instanceof MouseEvent||e.source instanceof TouchEvent){const u=e.source;o===0&&u.movementX!==0&&(o=u.movementX||0),a===0&&u.movementY!==0&&(a=u.movementY||0)}s.x+=o,s.y+=a,this._pointerPositions[t].x=e.clientX,this._pointerPositions[t].y=e.clientY;const l=e.clientX,c=e.clientY;for(;t>=this._pointerPositionsRC.length;)this._pointerPositionsRC.push(new Z);const h=this._pointerPositionsRC[t];h.set(l,c),this.convertScreenspaceToRaycastSpace(h)}getPointerIndex(e){let t=-1;for(let r=0;r<this._pointerIds.length;r++){if(this._pointerIds[r]===e)return r;t===-1&&this._pointerIds[r]===-1&&(t=r)}return t!==-1?(this._pointerIds[t]=e,t):(cr&&console.log("PUSH pointerId:",e),this._pointerIds.push(e),this._pointerIds.length-1)}setPointerState(e,t,r){t[e]=r}setPointerStateT(e,t,r){return t[e]=r,r}onDispatchEvent(e){const t=kt.Current;try{kt.Current=this.context,this.dispatchEvent(e)}finally{kt.Current=t}}}const Y1=new ve().makeRotationY(Math.PI),Sa=new Ce().setFromAxisAngle(new C(0,1,0),Math.PI),wue=te("debugwebxr");class Sue{constructor(){if(d(this,"priority",-1e5),d(this,"gameObject"),this.gameObject=new ye,this.gameObject.name="Implicit XR Rig",wue){const e=fB(16733661);e.position.y+=.5,this.gameObject.add(e)}}isXRRig(){return!0}get isActive(){return this.gameObject.visible}}const Uu=te("debugwebxr"),J1=te("debugcustomgesture"),Cue="https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles",Eue="generic-trigger";class vB{constructor(e,t,r){d(this,"xr"),d(this,"inputSource"),d(this,"index",0),d(this,"emitEvents",!0),d(this,"_connected",!0),d(this,"_isTracking",!1),d(this,"_hitTestSource"),d(this,"_hasSelectEvent",!1),d(this,"_handJointPoses",new Map),d(this,"_gripPosition",new C),d(this,"_gripQuaternion",new Ce),d(this,"_linearVelocity",new C),d(this,"_rayPosition",new C),d(this,"_rayQuaternion",new Ce),d(this,"_gripWorldPosition",new C),d(this,"_gripWorldQuaternion",new Ce),d(this,"_rayWorldPosition",new C),d(this,"_rayWorldQuaternion",new Ce),d(this,"_ray"),d(this,"_object"),d(this,"model",null),d(this,"_debugAxesHelper",new Po(.2)),d(this,"onPointerHits",l=>{}),d(this,"_needleGamepadButtons",{}),d(this,"_buttonMap",new Map),d(this,"_motioncontroller"),d(this,"_layout"),d(this,"getMotionController"),d(this,"_selectButtonIndex"),d(this,"_squeezeButtonIndex"),d(this,"onSelectStart",l=>{var c,h,u,p;if(this.inputSource!==l.inputSource)return;this.onUpdateFrame(l.frame),this._hasSelectEvent=!0;const m=(c=this._layout)==null?void 0:c.selectComponentId,f=(p=(u=(h=this._layout)==null?void 0:h.components[m])==null?void 0:u.gamepadIndices)==null?void 0:p.button;f!==void 0&&(this._selectButtonIndex=f),!J1&&(Uu&&At.DrawDirection(this.rayWorldPosition,pi(0,.01,1).applyQuaternion(this.rayWorldQuaternion),16711680,10),this.emitPointerEvent(an.PointerDown,this._selectButtonIndex||0,"xr-standard-trigger",!0,l))}),d(this,"onSelectEnd",l=>{J1||this.inputSource===l.inputSource&&this.emitPointerEvent(an.PointerUp,this._selectButtonIndex||0,"xr-standard-trigger",!0,l)}),d(this,"onSequeezeStart",l=>{var c,h,u;this.inputSource===l.inputSource&&(this._squeezeButtonIndex=(u=(h=(c=this._layout)==null?void 0:c.components["xr-standard-squeeze"])==null?void 0:h.gamepadIndices)==null?void 0:u.button,this._squeezeButtonIndex!==void 0&&(Uu&&At.DrawDirection(this.rayWorldPosition,pi(0,.01,1).applyQuaternion(this.rayWorldQuaternion),255,10),this.emitPointerEvent(an.PointerDown,this._squeezeButtonIndex||0,"xr-standard-squeeze",!0,l)))}),d(this,"onSequeezeEnd",l=>{this.inputSource===l.inputSource&&this._squeezeButtonIndex!==void 0&&this.emitPointerEvent(an.PointerUp,this._squeezeButtonIndex||0,"xr-standard-squeeze",!0,l)}),d(this,"states",{}),d(this,"_didMoveLastFrame",!1),d(this,"_lastPointerMovePosition",new C),d(this,"_lastPointerMoveQuaternion",new Ce),d(this,"pointerInit");var s,o,a;this.xr=e,this.inputSource=t,this.index=r,this._object=new ye,Uu&&this._object.add(this._debugAxesHelper),this.xr.context.scene.add(this._object),this._ray=new co,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"&&((a=(o=(s=this.xr.session).requestHitTestSourceForTransientInput)==null?void 0:o.call(s,{profile:this.inputSource.profiles[0],offsetRay:new XRRay}))==null||a.then(l=>this._hitTestSource=l))}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(e){var t,r;if(!this.hand||!((t=this.xr.frame)!=null&&t.getJointPose)||!this.xr.referenceSpace)return null;let s=(r=this._handJointPoses)==null?void 0:r.get(e);return s||(s=this.xr.frame.getJointPose(e,this.xr.referenceSpace),s&&this._handJointPoses.set(e,s),s)}get gripPosition(){return pi(this._gripPosition).applyMatrix4(Y1)}get gripQuaternion(){return bp(this._gripQuaternion).premultiply(Sa)}get gripLinearVelocity(){return pi(this._linearVelocity).applyQuaternion(Sa)}get rayPosition(){return pi(this._rayPosition).applyMatrix4(Y1)}get rayQuaternion(){return bp(this._rayQuaternion).premultiply(Sa)}get gripWorldPosition(){return pi(this._gripWorldPosition)}get gripWorldQuaternion(){return bp(this._gripWorldQuaternion)}get rayWorldPosition(){return pi(this._rayWorldPosition)}updateRayWorldPosition(){var e;const t=(e=this.xr.context.mainCamera)==null?void 0:e.parent;this._rayWorldPosition.copy(this._rayPosition),t&&this._rayWorldPosition.applyMatrix4(t.matrixWorld)}get rayWorldQuaternion(){return bp(this._rayWorldQuaternion)}updateRayWorldQuaternion(){var e;const t=(e=this.xr.context.mainCamera)==null?void 0:e.parent,r=t?Mi(t):void 0;this._rayWorldQuaternion.copy(this._rayQuaternion).multiply(Sa),r&&this._rayWorldQuaternion.premultiply(r)}get ray(){return this._ray.origin.copy(this.rayWorldPosition),this._ray.direction.copy(pi(0,0,1).applyQuaternion(this.rayWorldQuaternion)),this._ray}get object(){return this._object}async getModelUrl(){var e;return(e=this.getMotionController)==null?void 0:e.then(t=>t?.assetUrl||null)}onUpdate(e){this.onUpdateFrame(e),this.updateInputEvents(),this.onUpdateMove()}onRenderDebug(){var e;At.DrawWireSphere(this.rayWorldPosition,.02),At.DrawDirection(this.rayWorldPosition,pi(0,0,10).applyQuaternion(this.rayWorldQuaternion));const t=this.gripWorldPosition.sub(this.object.worldForward.multiplyScalar(.1)),r=this.inputSource.profiles.join(`
5151
+ */var rue=function(n){return n!=null&&(w6(n)||sue(n)||!!n._isBuffer)};function w6(n){return!!n.constructor&&typeof n.constructor.isBuffer=="function"&&n.constructor.isBuffer(n)}function sue(n){return typeof n.readFloatLE=="function"&&typeof n.slice=="function"&&w6(n.slice(0,0))}(function(){var n=nue,e=x6.utf8,t=rue,r=x6.bin,s=function(o,a){o.constructor==String?a&&a.encoding==="binary"?o=r.stringToBytes(o):o=e.stringToBytes(o):t(o)?o=Array.prototype.slice.call(o,0):!Array.isArray(o)&&o.constructor!==Uint8Array&&(o=o.toString());for(var l=n.bytesToWords(o),c=o.length*8,h=1732584193,u=-271733879,p=-1732584194,m=271733878,f=0;f<l.length;f++)l[f]=(l[f]<<8|l[f]>>>24)&16711935|(l[f]<<24|l[f]>>>8)&4278255360;l[c>>>5]|=128<<c%32,l[(c+64>>>9<<4)+14]=c;for(var g=s._ff,v=s._gg,y=s._hh,A=s._ii,f=0;f<l.length;f+=16){var _=h,b=u,x=p,E=m;h=g(h,u,p,m,l[f+0],7,-680876936),m=g(m,h,u,p,l[f+1],12,-389564586),p=g(p,m,h,u,l[f+2],17,606105819),u=g(u,p,m,h,l[f+3],22,-1044525330),h=g(h,u,p,m,l[f+4],7,-176418897),m=g(m,h,u,p,l[f+5],12,1200080426),p=g(p,m,h,u,l[f+6],17,-1473231341),u=g(u,p,m,h,l[f+7],22,-45705983),h=g(h,u,p,m,l[f+8],7,1770035416),m=g(m,h,u,p,l[f+9],12,-1958414417),p=g(p,m,h,u,l[f+10],17,-42063),u=g(u,p,m,h,l[f+11],22,-1990404162),h=g(h,u,p,m,l[f+12],7,1804603682),m=g(m,h,u,p,l[f+13],12,-40341101),p=g(p,m,h,u,l[f+14],17,-1502002290),u=g(u,p,m,h,l[f+15],22,1236535329),h=v(h,u,p,m,l[f+1],5,-165796510),m=v(m,h,u,p,l[f+6],9,-1069501632),p=v(p,m,h,u,l[f+11],14,643717713),u=v(u,p,m,h,l[f+0],20,-373897302),h=v(h,u,p,m,l[f+5],5,-701558691),m=v(m,h,u,p,l[f+10],9,38016083),p=v(p,m,h,u,l[f+15],14,-660478335),u=v(u,p,m,h,l[f+4],20,-405537848),h=v(h,u,p,m,l[f+9],5,568446438),m=v(m,h,u,p,l[f+14],9,-1019803690),p=v(p,m,h,u,l[f+3],14,-187363961),u=v(u,p,m,h,l[f+8],20,1163531501),h=v(h,u,p,m,l[f+13],5,-1444681467),m=v(m,h,u,p,l[f+2],9,-51403784),p=v(p,m,h,u,l[f+7],14,1735328473),u=v(u,p,m,h,l[f+12],20,-1926607734),h=y(h,u,p,m,l[f+5],4,-378558),m=y(m,h,u,p,l[f+8],11,-2022574463),p=y(p,m,h,u,l[f+11],16,1839030562),u=y(u,p,m,h,l[f+14],23,-35309556),h=y(h,u,p,m,l[f+1],4,-1530992060),m=y(m,h,u,p,l[f+4],11,1272893353),p=y(p,m,h,u,l[f+7],16,-155497632),u=y(u,p,m,h,l[f+10],23,-1094730640),h=y(h,u,p,m,l[f+13],4,681279174),m=y(m,h,u,p,l[f+0],11,-358537222),p=y(p,m,h,u,l[f+3],16,-722521979),u=y(u,p,m,h,l[f+6],23,76029189),h=y(h,u,p,m,l[f+9],4,-640364487),m=y(m,h,u,p,l[f+12],11,-421815835),p=y(p,m,h,u,l[f+15],16,530742520),u=y(u,p,m,h,l[f+2],23,-995338651),h=A(h,u,p,m,l[f+0],6,-198630844),m=A(m,h,u,p,l[f+7],10,1126891415),p=A(p,m,h,u,l[f+14],15,-1416354905),u=A(u,p,m,h,l[f+5],21,-57434055),h=A(h,u,p,m,l[f+12],6,1700485571),m=A(m,h,u,p,l[f+3],10,-1894986606),p=A(p,m,h,u,l[f+10],15,-1051523),u=A(u,p,m,h,l[f+1],21,-2054922799),h=A(h,u,p,m,l[f+8],6,1873313359),m=A(m,h,u,p,l[f+15],10,-30611744),p=A(p,m,h,u,l[f+6],15,-1560198380),u=A(u,p,m,h,l[f+13],21,1309151649),h=A(h,u,p,m,l[f+4],6,-145523070),m=A(m,h,u,p,l[f+11],10,-1120210379),p=A(p,m,h,u,l[f+2],15,718787259),u=A(u,p,m,h,l[f+9],21,-343485551),h=h+_>>>0,u=u+b>>>0,p=p+x>>>0,m=m+E>>>0}return n.endian([h,u,p,m])};s._ff=function(o,a,l,c,h,u,p){var m=o+(a&l|~a&c)+(h>>>0)+p;return(m<<u|m>>>32-u)+a},s._gg=function(o,a,l,c,h,u,p){var m=o+(a&c|l&~c)+(h>>>0)+p;return(m<<u|m>>>32-u)+a},s._hh=function(o,a,l,c,h,u,p){var m=o+(a^l^c)+(h>>>0)+p;return(m<<u|m>>>32-u)+a},s._ii=function(o,a,l,c,h,u,p){var m=o+(l^(a|~c))+(h>>>0)+p;return(m<<u|m>>>32-u)+a},s._blocksize=16,s._digestsize=16,b6.exports=function(o,a){if(o==null)throw new Error("Illegal argument "+o);var l=n.wordsToBytes(s(o,a));return a&&a.asBytes?l:a&&a.asString?r.bytesToString(l):n.bytesToHex(l)}})();var oue=b6.exports;const aue=G1(oue);class hB{constructor(e,t,r,s){d(this,"success"),d(this,"filename"),d(this,"hash"),d(this,"size"),d(this,"url"),this.success=e,this.filename=t,this.hash=r,this.size=s}}async function S6(n,e){const t=await n.arrayBuffer(),r=uB(t),s=n.name.split(".").pop(),o=r+"."+s,a=n.name.split(".").shift();console.assert(a!==void 0);const l={alias:a,filename:o},c=await(await fetch(e+"/exists",{method:"POST",body:JSON.stringify(l)})).json();if(c.success||console.warn("exists check did fail"),c.exists)return console.log("file already exists",r),new hB(!0,o,r,n.size);console.log("begin uploading file",a,n.size);const h=new FormData;h.append("file",n);const u={};u.filesize=n.size,a&&(u.alias=a);const p=await(await fetch(e+"/upload/file",{method:"POST",body:h,headers:u})).json();if(p?.success===!1)return p.message!==void 0?console.error("Upload failed:",p.message):console.error("Upload failed"),null;console.assert(p.hash_sum===r,"hash sum did not match","received:",p.hash_sum,"expected:",r),p.success&&console.log("successfully uploaded",r,p.id);const m=new hB(p.success,o,r,n.size);return m.url=e,m}function uB(n){return aue(new Uint8Array(n))}async function dB(n,e,t,r,s=!1){try{const o=await fetch(r+"/download/file",{method:"POST",body:n});if(o.status!==200)return console.error("download failed",o),null;const a=await o.blob(),l=await a.arrayBuffer();s||console.assert(a.size===t,"size mismatch","expected:",t,"got:",a.size);const c=uB(l);return s||console.assert(c===e,"hash mismatch, downloaded file is invalid"),a.arrayBuffer()}catch(o){console.error(o)}return null}async function C6(n,e){var t;const r=await fetch(n),s=(t=r.body)==null?void 0:t.getReader(),o=r.headers.get("Content-Length"),a=o?parseInt(o):0;if(!s)return null;let l=0;const c=[];for(;;){const{done:p,value:m}=await s.read();if(m&&(c.push(m),l+=m.length,e.call(null,new ProgressEvent("progress",{loaded:l,total:a}))),p)break}const h=new Uint8Array(l);let u=0;for(const p of c)h.set(p,u),u+=p.length;return h}const Fu=te("debugaddressables");class E6{constructor(e){d(this,"_context"),d(this,"_assetReferences",{}),d(this,"preUpdate",()=>{}),this._context=e,this._context.pre_update_callbacks.push(this.preUpdate)}dispose(){const e=this._context.pre_update_callbacks.indexOf(this.preUpdate);e>=0&&this._context.pre_update_callbacks.splice(e,1);for(const t in this._assetReferences){const r=this._assetReferences[t];r?.unload()}this._assetReferences={}}findAssetReference(e){return this._assetReferences[e]||null}registerAssetReference(e){return e.uri&&(this._assetReferences[e.uri]?console.warn("Asset reference already registered",e):this._assetReferences[e.uri]=e),e}unregisterAssetReference(e){e.uri&&delete this._assetReferences[e.uri]}}const pB=Symbol("assetReference"),Pg=class{constructor(n,e,t=null){d(this,"_loading"),d(this,"_asset"),d(this,"_glbRoot"),d(this,"_url"),d(this,"_progressListeners",[]),d(this,"_hash"),d(this,"_hashedUri"),d(this,"_isLoadingRawBinary",!1),d(this,"_rawBinary"),this._url=n,this._hash=e,n.includes("?v=")?this._hashedUri=n:this._hashedUri=e?n+"?v="+e:n,t!==null&&(this.asset=t),j8(this._url,this.onResolvePrefab.bind(this))}static getOrCreateFromUrl(n,e){if(!e&&(e=kt.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,r=t.findAssetReference(n);if(r)return r;const s=new Pg(n,e.hash);return t.registerAssetReference(s),s}static getOrCreate(n,e,t){if(typeof n=="string"){if(!t&&(t=kt.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=n.context,n=n.sourceId;const r=cu(n,e);Fu&&console.log("GetOrCreate Addressable from",n,e,"FinalPath=",r);const s=t.addressables,o=s.findAssetReference(r);if(o)return o;const a=new Pg(r,t.hash);return s.registerAssetReference(a),a}get asset(){return this._glbRoot??this._asset}set asset(n){this._asset=n}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(n){return n===this.uri&&(this.mustLoad&&await this.loadAssetAsync(),this.asset)?this.asset:null}get mustLoad(){return!this.asset||this.asset.__destroyed===!0||Jp(this.asset)===!0}isLoaded(){return this._rawBinary||this.asset!==void 0}unload(){this.asset&&(Fu&&console.log("Unload",this.asset),this.asset.scene&&Ca(this.asset.scene,!0,!0),Ca(this.asset,!0,!0)),this.asset=null,this._rawBinary=void 0,this._glbRoot=null,this._loading=void 0,kt.Current&&kt.Current.addressables.unregisterAssetReference(this)}async preload(){if(!this.mustLoad||this._isLoadingRawBinary)return null;if(this._rawBinary!==void 0)return this._rawBinary;this._isLoadingRawBinary=!0,Fu&&console.log("Preload",this._hashedUri);const n=await C6(this._hashedUri,e=>{this.raiseProgressEvent(e)});return this._rawBinary=n?.buffer??null,this._isLoadingRawBinary=!1,this._rawBinary}async loadAssetAsync(n){if(Fu&&console.log("loadAssetAsync",this.uri),!this.mustLoad)return this.asset;if(n&&this._progressListeners.push(n),this._loading!==void 0)return this._loading.then(r=>this.asset);const e=kt.Current;this._rawBinary?(this._loading=Ka().parseSync(e,this._rawBinary,this.uri,null),this.raiseProgressEvent(new ProgressEvent("progress",{loaded:this._rawBinary.byteLength,total:this._rawBinary.byteLength}))):(Fu&&console.log("Load async",this.uri),this._loading=Ka().loadSync(e,this._hashedUri,this.uri,null,r=>{this.raiseProgressEvent(r)}));const t=await this._loading;if(this._progressListeners.length=0,this._glbRoot=this.tryGetActualGameObjectRoot(t),this._loading=void 0,t)return t[pB]=this,this._glbRoot&&(this._glbRoot[pB]=this),this.asset&&(this.asset[pB]=this),B1(e),t.scene!==void 0&&(this.asset=t),this.asset}async instantiate(n){return this.onInstantiate(n,!1)}async instantiateSynced(n,e=!0){return this.onInstantiate(n,!0,e)}beginListenDownload(n){this._progressListeners.indexOf(n)<0&&this._progressListeners.push(n)}endListenDownload(n){const e=this._progressListeners.indexOf(n);e>=0&&this._progressListeners.splice(e,1)}raiseProgressEvent(n){for(const e of this._progressListeners)e(this,n)}async onInstantiate(n,e=!1,t){const r=kt.Current,s=new Ml;if(n instanceof ye?s.parent=n:n&&(Object.assign(s,n),s.cloneAssign(n)),s.parent||(s.parent=r.scene),this.mustLoad&&await this.loadAssetAsync(),Fu&&console.log("Instantiate",this.uri,"parent:",n),this.asset){Fu&&console.log("Add to scene",this.asset);let o=Pg.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,Pg.currentlyInstantiating.set(this.uri,o),e){s.context=r;const a=this.asset;a.guid=this.uri;const l=ek(a,s,void 0,t);if(l)return l}else{const a=Gg(this.asset,s);if(a)return a}}finally{r.post_render_callbacks.push(()=>{o===void 0||o<0?o=0:o-=1,Pg.currentlyInstantiating.set(this.uri,o)})}}else Fu&&console.warn("Failed to load asset",this.uri);return null}tryGetActualGameObjectRoot(n){if(n&&n.scene){const e=n.scene;return e.isGroup&&e.children.length===1&&e.children[0].name+"glb"===e.name?e.children[0]:e}return null}};let ti=Pg;d(ti,"currentlyInstantiating",new Map);class lue extends wa{constructor(){super([ti],"AssetReferenceSerializer")}onSerialize(e,t){if(e&&e.uri!==void 0&&typeof e.uri=="string")return e.uri}onDeserialize(e,t){if(typeof e=="string")return t.context?t.gltfId?ti.getOrCreate(t.gltfId,e,t.context):(console.error("Missing source id"),null):(console.error("Missing context"),null);if(e instanceof ye){if(!t.context)return console.error("Missing context"),null;if(!t.gltfId)return console.error("Missing source id"),null;const r=e,s=t.context,o=r.guid??r.uuid,a=s.addressables.findAssetReference(o);if(a)return a;const l=new ti(o,void 0,r);return s.addressables.registerAssetReference(l),l}return null}}new lue;const cue=Promise.resolve(null),V1=class{constructor(n){d(this,"url"),d(this,"_bitmap"),d(this,"_bitmapObject"),d(this,"loader",null),this.url=n}static getOrCreate(n){let e=V1.imageReferences.get(n);return e||(e=new V1(n),V1.imageReferences.set(n,e)),e}dispose(){this._bitmapObject&&this._bitmapObject.close(),this._bitmap=void 0}createHTMLImage(){const n=new Image;return n.src=this.url,n}createTexture(){return this.url?(this.loader||(this.loader=new Dl),this.loader.setCrossOrigin("anonymous"),this.loader.loadAsync(this.url)):cue}getBitmap(){return this._bitmap?this._bitmap:(this._bitmap=new Promise((n,e)=>{const t=document.createElement("img");t.addEventListener("load",()=>{this._bitmap=createImageBitmap(t).then(r=>(this._bitmapObject=r,n(r),r))}),t.addEventListener("error",r=>{console.error("Failed to load image:"+this.url,r),n(null)}),t.src=this.url}),this._bitmap)}};let Q1=V1;d(Q1,"imageReferences",new Map);class M6 extends wa{constructor(){super([Q1],"ImageReferenceSerializer")}onSerialize(e,t){return null}onDeserialize(e,t){if(typeof e=="string"){const r=cu(t.gltfId,e);return Q1.getOrCreate(r)}}}new M6;const H1=class{constructor(n){d(this,"url"),d(this,"res"),this.url=n}static getOrCreate(n){let e=H1.cache.get(n);return e||(e=new H1(n),H1.cache.set(n,e)),e}async loadRaw(){return this.res||(this.res=fetch(this.url)),this.res.then(n=>n.blob())}async loadText(){return this.res||(this.res=fetch(this.url)),this.res.then(n=>n.text())}};let W1=H1;d(W1,"cache",new Map);class T6 extends wa{constructor(){super([W1],"FileReferenceSerializer")}onSerialize(e,t){return null}onDeserialize(e,t){if(typeof e=="string"){const r=cu(t.gltfId,e);return W1.getOrCreate(r)}}}new T6;class hue{constructor(e){d(this,"context"),d(this,"mixers",[]),this.context=e}onDestroy(){this.mixers.forEach(e=>e.stopAllAction()),this.mixers.length=0}registerAnimationMixer(e){if(!e){console.warn("AnimationsRegistry.registerAnimationMixer called with null or undefined mixer");return}this.mixers.includes(e)||this.mixers.push(e)}unregisterAnimationMixer(e){if(!e)return;const t=this.mixers.indexOf(e);t!==-1&&this.mixers.splice(t,1)}}class Bg{static tryGetActionsFromMixer(e){return e._actions||null}static tryGetAnimationClipsFromObjectHierarchy(e,t){if(t||(t=new Array),e)e.animations&&t.push(...e.animations);else return t;if(e.children)for(const r of e.children)this.tryGetAnimationClipsFromObjectHierarchy(r,t);return t}static assignAnimationsFromFile(e,t){if(!e||!e.animations)return;for(let s=0;s<e.animations.length;s++){const o=e.animations[s];if(!(!o.tracks||o.tracks.length<=0))for(const a in o.tracks){const l=o.tracks[a],c=Xt.parseTrackName(l.name);let h=Xt.findNode(e.scene,c.nodeName);if(!h){const p=l.__objectName??l.name.substring(0,l.name.indexOf("."));if(h=e.scene.getObjectByProperty("uuid",p),!h)continue}let u=r(h);if(!u){if(!(t!=null&&t.createAnimationComponent)){console.warn("No AnimationComponent found in parent hierarchy of object and no 'createAnimationComponent' callback was provided in options.");continue}u=t.createAnimationComponent(e.scene,o)}u.addClip&&u.addClip(o)}}function r(s){var o;if(!s)return null;const a=(o=s.userData)==null?void 0:o.components;if(a&&a.length>0){for(let l=0;l<a.length;l++)if(a[l].isAnimationComponent===!0)return s}return r(s.parent)}}}const kg=[];function X1(n){kg.indexOf(n)===-1&&kg.push(n)}function uue(n){const e=kg.indexOf(n);e!==-1&&kg.splice(e,1)}const Dg=[];function mB(n){Dg.indexOf(n)===-1&&Dg.push(n)}function due(n){const e=Dg.indexOf(n);e!==-1&&Dg.splice(e,1)}function I6(n){globalThis.dispatchEvent(new CustomEvent("needle-xrsession-start",{detail:n}));for(let e=0;e<kg.length;e++)kg[e](n)}function R6(n){globalThis.dispatchEvent(new CustomEvent("needle-xrsession-end",{detail:n}));for(let e=0;e<Dg.length;e++)Dg[e](n)}const wr={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 P6(n){const e=await fetch(n);if(e.ok)return e.json();throw new Error(e.statusText)}async function pue(n){if(!n)throw new Error("No basePath supplied");return await P6(`${n}/profilesList.json`)}async function mue(n,e,t=null,r=!0){if(!n)throw new Error("No xrInputSource supplied");if(!e)throw new Error("No basePath supplied");const s=await pue(e);let o;if(n.profiles.some(c=>{const h=s[c];return h&&(o={profileId:c,profilePath:`${e}/${h.path}`,deprecated:!!h.deprecated}),!!o}),!o){if(!t)throw new Error("No matching profile name found");const c=s[t];if(!c)throw new Error(`No matching profile name found and default profile "${t}" missing.`);o={profileId:t,profilePath:`${e}/${c.path}`,deprecated:!!c.deprecated}}const a=await P6(o.profilePath);let l;if(r){let c;if(n.handedness==="any"?c=a.layouts[Object.keys(a.layouts)[0]]:c=a.layouts[n.handedness],!c)throw new Error(`No matching handedness, ${n.handedness}, in profile ${o.profileId}`);c.assetPath&&(l=o.profilePath.replace("profile.json",c.assetPath))}return{profile:a,assetPath:l}}const fue={xAxis:0,yAxis:0,button:0,state:wr.ComponentState.DEFAULT};function gue(n=0,e=0){let t=n,r=e;if(Math.sqrt(n*n+e*e)>1){const s=Math.atan2(e,n);t=Math.cos(s),r=Math.sin(s)}return{normalizedXAxis:t*.5+.5,normalizedYAxis:r*.5+.5}}let vue=class{constructor(n){this.componentProperty=n.componentProperty,this.states=n.states,this.valueNodeName=n.valueNodeName,this.valueNodeProperty=n.valueNodeProperty,this.valueNodeProperty===wr.VisualResponseProperty.TRANSFORM&&(this.minNodeName=n.minNodeName,this.maxNodeName=n.maxNodeName),this.value=0,this.updateFromComponent(fue)}updateFromComponent({xAxis:n,yAxis:e,button:t,state:r}){const{normalizedXAxis:s,normalizedYAxis:o}=gue(n,e);switch(this.componentProperty){case wr.ComponentProperty.X_AXIS:this.value=this.states.includes(r)?s:.5;break;case wr.ComponentProperty.Y_AXIS:this.value=this.states.includes(r)?o:.5;break;case wr.ComponentProperty.BUTTON:this.value=this.states.includes(r)?t:0;break;case wr.ComponentProperty.STATE:this.valueNodeProperty===wr.VisualResponseProperty.VISIBILITY?this.value=this.states.includes(r):this.value=this.states.includes(r)?1:0;break;default:throw new Error(`Unexpected visualResponse componentProperty ${this.componentProperty}`)}}},yue=class{constructor(n,e){if(!n||!e||!e.visualResponses||!e.gamepadIndices||Object.keys(e.gamepadIndices).length===0)throw new Error("Invalid arguments supplied");this.id=n,this.type=e.type,this.rootNodeName=e.rootNodeName,this.touchPointNodeName=e.touchPointNodeName,this.visualResponses={},Object.keys(e.visualResponses).forEach(t=>{const r=new vue(e.visualResponses[t]);this.visualResponses[t]=r}),this.gamepadIndices=Object.assign({},e.gamepadIndices),this.values={state:wr.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(n){if(this.values.state=wr.ComponentState.DEFAULT,this.gamepadIndices.button!==void 0&&n.buttons.length>this.gamepadIndices.button){const e=n.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=wr.ComponentState.PRESSED:(e.touched||this.values.button>wr.ButtonTouchThreshold)&&(this.values.state=wr.ComponentState.TOUCHED)}this.gamepadIndices.xAxis!==void 0&&n.axes.length>this.gamepadIndices.xAxis&&(this.values.xAxis=n.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===wr.ComponentState.DEFAULT&&Math.abs(this.values.xAxis)>wr.AxisTouchThreshold&&(this.values.state=wr.ComponentState.TOUCHED)),this.gamepadIndices.yAxis!==void 0&&n.axes.length>this.gamepadIndices.yAxis&&(this.values.yAxis=n.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===wr.ComponentState.DEFAULT&&Math.abs(this.values.yAxis)>wr.AxisTouchThreshold&&(this.values.state=wr.ComponentState.TOUCHED)),Object.values(this.visualResponses).forEach(e=>{e.updateFromComponent(this.values)})}},Aue=class{constructor(n,e,t){if(!n)throw new Error("No xrInputSource supplied");if(!e)throw new Error("No profile supplied");this.xrInputSource=n,this.assetUrl=t,this.id=e.profileId,this.layoutDescription=e.layouts[n.handedness],this.components={},Object.keys(this.layoutDescription.components).forEach(r=>{const s=this.layoutDescription.components[r];this.components[r]=new yue(r,s)}),this.updateFromGamepad()}get gripSpace(){return this.xrInputSource.gripSpace}get targetRaySpace(){return this.xrInputSource.targetRaySpace}get data(){const n=[];return Object.values(this.components).forEach(e=>{n.push(e.data)}),n}updateFromGamepad(){Object.values(this.components).forEach(n=>{n.updateFromGamepad(this.xrInputSource.gamepad)})}};const Js=new C,B6=new C,k6=new Ce,bue=te("debuggizmos"),Wl=8947848,Xl=class{constructor(){}static isGizmo(n){return n[gB]!==void 0}static DrawLabel(n,e,t=.05,r=0,s,o,a){var l;if(!Xl.enabled)return null;s||(s=Wl);const c=((l=wt.active)==null?void 0:l.rigScale)??1,h=En.getTextLabel(r,e,t*c,s,o);return a instanceof ye&&a.add(h),h.position.x=n.x,h.position.y=n.y,h.position.z=n.z,h}static DrawRay(n,e,t=Wl,r=0,s=!0){if(!Xl.enabled)return;const o=En.getLine(r),a=o.geometry.getAttribute("position");a.setXYZ(0,n.x,n.y,n.z),Js.set(e.x,e.y,e.z).multiplyScalar(999999999),a.setXYZ(1,n.x+Js.x,n.y+Js.y,n.z+Js.z),a.needsUpdate=!0,o.material.color.set(t),o.material.depthTest=s,o.material.depthWrite=!1}static DrawDirection(n,e,t=Wl,r=0,s=!0,o=1){if(!Xl.enabled)return;const a=En.getLine(r),l=a.geometry.getAttribute("position");l.setXYZ(0,n.x,n.y,n.z),e.w!==void 0?(Js.set(0,0,-o),k6.set(e.x,e.y,e.z,e.w),Js.applyQuaternion(k6)):(Js.set(e.x,e.y,e.z),Js.multiplyScalar(o)),l.setXYZ(1,n.x+Js.x,n.y+Js.y,n.z+Js.z),l.needsUpdate=!0,a.material.color.set(t),a.material.depthTest=s,a.material.depthWrite=!1}static DrawLine(n,e,t=Wl,r=0,s=!0){if(!Xl.enabled)return;const o=En.getLine(r),a=o.geometry.getAttribute("position");a.setXYZ(0,n.x,n.y,n.z),a.setXYZ(1,e.x,e.y,e.z),a.needsUpdate=!0,o.material.color.set(t),o.material.depthTest=s,o.material.depthWrite=!1,o.material.fog=!1}static DrawWireSphere(n,e,t=Wl,r=0,s=!0){if(!Xl.enabled)return;const o=En.getSphere(e,r,!0);_p(o,n.x,n.y,n.z),o.material.color.set(t),o.material.depthTest=s,o.material.depthWrite=!1,o.material.fog=!1}static DrawSphere(n,e,t=Wl,r=0,s=!0){if(!Xl.enabled)return;const o=En.getSphere(e,r,!1);_p(o,n.x,n.y,n.z),o.material.color.set(t),o.material.depthTest=s,o.material.depthWrite=!1}static DrawWireBox(n,e,t=Wl,r=0,s=!0){if(!Xl.enabled)return;const o=En.getBox(r);o.position.set(n.x,n.y,n.z),o.scale.set(e.x,e.y,e.z),o.material.color.set(t),o.material.depthTest=s,o.material.wireframe=!0,o.material.depthWrite=!1,o.material.fog=!1}static DrawWireBox3(n,e=Wl,t=0,r=!0){if(!Xl.enabled)return;const s=En.getBox(t);s.position.copy(n.getCenter(Js)),s.scale.copy(n.getSize(Js)),s.material.color.set(e),s.material.depthTest=r,s.material.wireframe=!0,s.material.depthWrite=!1,s.material.fog=!1}static DrawArrow(n,e,t=Wl,r=0,s=!0,o=!1){if(!Xl.enabled)return;const a=En.getArrowHead(r);a.position.set(e.x,e.y,e.z),a.quaternion.setFromUnitVectors(this._up.set(0,1,0),Js.set(e.x,e.y,e.z).sub(B6.set(n.x,n.y,n.z)).normalize());const l=Js.set(e.x,e.y,e.z).sub(B6.set(n.x,n.y,n.z)).length()*.1;a.scale.set(l,l,l),a.material.color.set(t),a.material.depthTest=s,a.material.wireframe=o,this.DrawLine(n,e,t,r,s)}static DrawWireMesh(n){const e=En.getMesh(n.duration??0);"mesh"in n?(e.geometry=n.mesh.geometry,e.matrix.copy(n.mesh.matrixWorld)):(e.geometry=n.geometry,e.matrix.copy(n.matrix)),e.matrixAutoUpdate=!1,e.matrixWorldAutoUpdate=!1,e.material.color.set(n.color??Wl),e.material.depthTest=n.depthTest??!0,e.material.wireframe=!0}};let At=Xl;d(At,"enabled",!0),d(At,"_up",new C(0,1,0));const _ue=new qi(1,1,1);function fB(n=null){const e=new xe(n??14540253),t=new iI(_ue);return new gs(t,new Gi({color:e}))}const gB=Symbol("GizmoCache");class En{static ensureFont(){let e=Ni.FontLibrary.getFontFamily(this.familyName);if(!e){e=Ni.FontLibrary.addFontFamily(this.familyName);const t=e.addVariant("normal","normal","https://uploads.needle.tools/include/font-msdf.json","https://uploads.needle.tools/include/font.png");t?.addEventListener("ready",()=>{Ni.update()})}}static getTextLabel(e,t,r,s,o){this.ensureFont();let a=this.textLabelCache.pop(),l=1;o&&typeof o=="string"&&o?.length>=8&&o.startsWith("#")?(l=parseInt(o.substring(7),16)/255,o=o.substring(0,7),bue&&console.log(o,l)):typeof o=="object"&&o.a!==void 0&&(l=o.a);const c={boxSizing:"border-box",fontFamily:this.familyName,width:"auto",fontSize:r,color:s,lineHeight:1,backgroundColor:o??void 0,backgroundOpacity:l,textContent:t,borderRadius:.5*r,padding:.8*r,whiteSpace:"pre"};if(a)a.set(c);else{a=new fR(c);const h=this,u=a;u.setText=function(p){this.set({textContent:p}),h.tmuiNeedsUpdate=!0}}return this.tmuiNeedsUpdate=!0,this.registerTimedObject(kt.Current,a,e,this.textLabelCache),a}static getBox(e){let t=this.boxesCache.pop();if(!t){const r=new qi(1,1,1);t=new me(r)}return this.registerTimedObject(kt.Current,t,e,this.boxesCache),t}static getLine(e){let t=this.linesCache.pop();if(!t){t=new Sn;let r=t.geometry.getAttribute("position");r||(r=new nt(new Float32Array(2*3),3),t.geometry.setAttribute("position",r))}return t.frustumCulled=!1,this.registerTimedObject(kt.Current,t,e,this.linesCache),t}static getSphere(e,t,r){let s=this.spheresCache.pop();return s||(s=new me(new ja(1,8,8))),s.scale.set(e,e,e),s.material.wireframe=r,this.registerTimedObject(kt.Current,s,t,this.spheresCache),s}static getArrowHead(e){let t=this.arrowHeadsCache.pop();return t||(t=new me(new jn(0,.5,1,8))),this.registerTimedObject(kt.Current,t,e,this.arrowHeadsCache),t}static getMesh(e){let t=this.mesh.pop();return t||(t=new me,t.material=new $t),this.registerTimedObject(kt.Current,t,e,this.mesh),t}static registerTimedObject(e,t,r,s){const o=this.contextBeforeRenderCallbacks.get(e),a=this.contextPostRenderCallbacks.get(e);if(o){if(e.pre_render_callbacks[e.pre_render_callbacks.length-1]!==o){const l=e.pre_render_callbacks.indexOf(o);l>=0&&e.pre_render_callbacks.splice(l,1),e.pre_render_callbacks.push(o)}}else{const l=()=>{this.onBeforeRender(e,this.timedObjectsBuffer)};this.contextBeforeRenderCallbacks.set(e,l),e.pre_render_callbacks.push(l)}if(a){if(e.post_render_callbacks[e.post_render_callbacks.length-1]!==a){const l=e.post_render_callbacks.indexOf(a);l>=0&&e.post_render_callbacks.splice(l,1),e.post_render_callbacks.push(a)}}else{const l=()=>{this.onPostRender(e,this.timedObjectsBuffer,this.timesBuffer)};this.contextPostRenderCallbacks.set(e,l),e.post_render_callbacks.push(l)}t.traverse(l=>{l.layers.disableAll(),l.layers.enable(2)}),t.renderOrder=999999,t[gB]=s,t.isGizmo=!0,this.timedObjectsBuffer.push(t),r<=0&&e.currentFrameEvent>=Hi.OnBeforeRender?this.timesBuffer.push(0):this.timesBuffer.push(kt.Current.time.realtimeSinceStartup+r),e.scene.add(t)}static onBeforeRender(e,t){this.tmuiNeedsUpdate&&Ni.update();for(let r=0;r<t.length;r++){const s=t[r];if(e.mainCamera&&s instanceof Ni.MeshUIBaseElement){if(Jp(s))continue;const o=e.isInVR,a=!1,l=!o;Hv(s,e.mainCamera,a,l)}}}static onPostRender(e,t,r){const s=e.time.realtimeSinceStartup;for(let o=t.length-1;o>=0;o--){const a=t[o];s>r[o]&&(t.splice(o,1),r.splice(o,1),a.removeFromParent(),Jp(a)!=!0&&a[gB].push(a))}}}d(En,"familyName","needle-gizmos"),d(En,"linesCache",[]),d(En,"spheresCache",[]),d(En,"boxesCache",[]),d(En,"arrowHeadsCache",[]),d(En,"mesh",[]),d(En,"textLabelCache",[]),d(En,"timedObjectsBuffer",new Array),d(En,"timesBuffer",new Array),d(En,"contextPostRenderCallbacks",new Map),d(En,"contextBeforeRenderCallbacks",new Map),d(En,"tmuiNeedsUpdate",!1);const cr=te("debuginput");var q1=(n=>(n.Mouse="mouse",n.Touch="touch",n.Controller="controller",n.Hand="hand",n))(q1||{}),an=(n=>(n.PointerDown="pointerdown",n.PointerUp="pointerup",n.PointerMove="pointermove",n.KeyDown="keydown",n.KeyUp="keyup",n.KeyPressed="keypress",n))(an||{});class mh extends PointerEvent{constructor(e,t,r){super(e,r),d(this,"deviceIndex"),d(this,"origin"),d(this,"source"),d(this,"mode"),d(this,"_ray"),d(this,"space"),d(this,"isClick",!1),d(this,"isDoubleClick",!1),d(this,"_used",!1),d(this,"_pointerid"),d(this,"_pointerType"),d(this,"_type"),d(this,"metadata",{}),d(this,"intersections",new Array),d(this,"_immediatePropagationStopped",!1),d(this,"_propagationStopped",!1),this._pointerid=r.pointerId,this._pointerType=r.pointerType,this._type=e,this.deviceIndex=r.deviceIndex,this.origin=r.origin,this.source=t,this.mode=r.mode,this._ray=r.ray,this.space=r.device}get isSpatial(){return this.mode!="screen"}get ray(){return this._ray||(this._ray=new co(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(),cr&&console.warn("Stop propagation...",this.pointerId,this.pointerType)}}class Xy extends KeyboardEvent{constructor(e,t,r){super(e,r),d(this,"source"),this.source=t}stopImmediatePropagation(){var e;super.stopImmediatePropagation(),(e=this.source)==null||e.stopImmediatePropagation()}}class xue{constructor(e){d(this,"key"),d(this,"keyType"),d(this,"source"),this.key=e.key,this.keyType=e.type,this.source=e}}var ql=(n=>(n[n.Early=-100]="Early",n[n.Default=0]="Default",n[n.Late=100]="Late",n))(ql||{});class D6{constructor(e){d(this,"_eventListeners",{}),d(this,"_doubleClickTimeThreshold",.2),d(this,"_longPressTimeThreshold",1),d(this,"_specialCursorTrigger",0),d(this,"context"),d(this,"_pointerDown",[!1]),d(this,"_pointerUp",[!1]),d(this,"_pointerClick",[!1]),d(this,"_pointerDoubleClick",[!1]),d(this,"_pointerPressed",[!1]),d(this,"_pointerPositions",[new Z]),d(this,"_pointerPositionsLastFrame",[new Z]),d(this,"_pointerPositionsDelta",[new Z]),d(this,"_pointerPositionsRC",[new Z]),d(this,"_pointerPositionDown",[new Z]),d(this,"_pointerDownTime",[]),d(this,"_pointerUpTime",[]),d(this,"_pointerUpTimestamp",[]),d(this,"_pointerIds",[]),d(this,"_pointerTypes",[""]),d(this,"_mouseWheelChanged",[!1]),d(this,"_mouseWheelDeltaY",[0]),d(this,"_pointerEvent",[]),d(this,"_pointerUsed",[]),d(this,"_pointerSpace",[]),d(this,"_pressedStack",new Map),d(this,"_htmlEventSource"),d(this,"onLostFocus",()=>{for(const t in this.keysPressed)this.keysPressed[t].pressed=!1}),d(this,"onEndOfFrame",()=>{for(let t=0;t<this._pointerUp.length;t++)this._pointerUp[t]=!1;for(let t=0;t<this._pointerDown.length;t++)this._pointerDown[t]=!1;for(let t=0;t<this._pointerClick.length;t++)this._pointerClick[t]=!1;for(let t=0;t<this._pointerDoubleClick.length;t++)this._pointerDoubleClick[t]=!1;for(const t of this._pointerPositionsDelta)t.set(0,0);for(let t=0;t<this._mouseWheelChanged.length;t++)this._mouseWheelChanged[t]=!1;for(let t=0;t<this._mouseWheelDeltaY.length;t++)this._mouseWheelDeltaY[t]=0}),d(this,"onContextMenu",t=>{this.canReceiveInput(t)!==!1&&t instanceof PointerEvent&&t.pointerType}),d(this,"keysPressed",{}),d(this,"onKeyDown",t=>{if(cr&&console.log(`key down ${t.code}, ${this.context.application.hasFocus}`,t),!this.context.application.hasFocus)return;const r=this.keysPressed[t.code];if(r&&r.pressed)return;this.keysPressed[t.code]={pressed:!0,frame:this.context.time.frameCount+1,startFrame:this.context.time.frameCount+1,key:t.key,code:t.code};const s=new Xy("keydown",t,t);this.onDispatchEvent(s)}),d(this,"onKeyPressed",t=>{if(!this.context.application.hasFocus)return;const r=this.keysPressed[t.code];if(!r)return;r.pressed=!0,r.frame=this.context.time.frameCount+1;const s=new Xy("keypress",t,t);this.onDispatchEvent(s)}),d(this,"onKeyUp",t=>{if(!this.context.application.hasFocus)return;const r=this.keysPressed[t.code];if(!r)return;r.pressed=!1,r.frame=this.context.time.frameCount+1;const s=new Xy("keyup",t,t);this.onDispatchEvent(s)}),d(this,"onWheelWindow",t=>{document.pointerLockElement&&this.onMouseWheel(t)}),d(this,"onMouseWheel",t=>{if(this.canReceiveInput(t)===!1)return;this._mouseWheelDeltaY.length<=0&&this._mouseWheelDeltaY.push(0),this._mouseWheelChanged.length<=0&&this._mouseWheelChanged.push(!1),this._mouseWheelChanged[0]=!0;const r=this._mouseWheelDeltaY[0];this._mouseWheelDeltaY[0]=r+t.deltaY}),d(this,"onPointerDown",t=>{if(this.context.isInAR||this.canReceiveInput(t)===!1)return;t.target instanceof HTMLElement&&t.target.setPointerCapture(t.pointerId);const r=this.getPointerId(t);cr&&rn(`pointer down #${r}, identifier:${t.pointerId}`);const s=this.getAndUpdateSpatialObjectForScreenPosition(r,t.clientX,t.clientY),o=new mh("pointerdown",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:r,button:t.button,clientX:t.clientX,clientY:t.clientY,pointerType:t.pointerType,buttonName:this.getButtonName(t),device:s,pressure:t.pressure});this.onDown(o)}),d(this,"onPointerMove",t=>{if(this.context.isInAR)return;let r=t.button;t.pointerType==="mouse"&&(r=this.getFirstPressedButtonForPointer(0)??0);const s=this.getPointerId(t,r);r===-1&&(r=s);const o=this.getAndUpdateSpatialObjectForScreenPosition(s,t.clientX,t.clientY),a=new mh("pointermove",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:s,button:r,clientX:t.clientX,clientY:t.clientY,pointerType:t.pointerType,buttonName:this.getButtonName(t),device:o,pressure:t.pressure});this.onMove(a)}),d(this,"onPointerCancel",t=>{this.context.isInAR||(cr&&console.log("Pointer cancel",t),this.onPointerUp(t))}),d(this,"onPointerUp",t=>{if(this.context.isInAR)return;t.target instanceof HTMLElement&&t.target.releasePointerCapture(t.pointerId);const r=this.getPointerId(t),s=new mh("pointerup",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:r,button:t.button,clientX:t.clientX,clientY:t.clientY,pointerType:t.pointerType,buttonName:this.getButtonName(t),device:this.getAndUpdateSpatialObjectForScreenPosition(r,t.clientX,t.clientY),pressure:t.pressure});this.onUp(s),this._pointerIds[r]=-1,cr&&console.log("ID="+r,"PointerId="+t.pointerId,"ALL:",[...this._pointerIds])}),d(this,"onTouchStart",t=>{if(this.context.isInAR)for(let r=0;r<t.changedTouches.length;r++){const s=t.changedTouches[r],o=this.getPointerIndex(s.identifier),a=this.getAndUpdateSpatialObjectForScreenPosition(o,s.clientX,s.clientY),l=new mh("pointerdown",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:o,button:0,clientX:s.clientX,clientY:s.clientY,pointerType:"touch",buttonName:"unknown",device:a,pressure:s.force});this.onDown(l)}}),d(this,"onTouchMove",t=>{if(this.context.isInAR)for(let r=0;r<t.changedTouches.length;r++){const s=t.changedTouches[r],o=this.getPointerIndex(s.identifier),a=this.getAndUpdateSpatialObjectForScreenPosition(o,s.clientX,s.clientY),l=new mh("pointermove",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:o,button:0,clientX:s.clientX,clientY:s.clientY,pointerType:"touch",buttonName:"unknown",device:a,pressure:s.force});this.onMove(l)}}),d(this,"onTouchEnd",t=>{if(this.context.isInAR)for(let r=0;r<t.changedTouches.length;r++){const s=t.changedTouches[r],o=this.getPointerIndex(s.identifier),a=new mh("pointerup",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:o,button:0,clientX:s.clientX,clientY:s.clientY,pointerType:"touch",buttonName:"unknown",device:this.getAndUpdateSpatialObjectForScreenPosition(o,s.clientX,s.clientY),pressure:s.force});this.onUp(a),this._pointerIds[o]=-1}}),d(this,"tempNearPlaneVector",new C),d(this,"tempFarPlaneVector",new C),d(this,"tempLookMatrix",new ve),this.context=e,this.context.post_render_callbacks.push(this.onEndOfFrame)}addEventListener(e,t,r){if(this._eventListeners[e]||(this._eventListeners[e]=[]),!t||typeof t!="function"){console.error("Invalid call to addEventListener: callback is required and must be a function!");return}r?r={...r}:r={};let s=0;r?.queue!=null&&(s=r.queue);const o=this._eventListeners[e],a=o.find(l=>l.priority===s);a?a.listeners.push({callback:t,options:r}):(o.push({priority:s,listeners:[{callback:t,options:r}]}),o.sort((l,c)=>l.priority-c.priority))}removeEventListener(e,t,r){if(!this._eventListeners[e]||!t)return;const s=this._eventListeners[e];if(r?.queue!=null){const o=s.find(l=>l.priority===r.queue);if(!o)return;const a=o.listeners.findIndex(l=>l.callback===t);a>=0&&o.listeners.splice(a,1)}else for(const o of s){const a=o.listeners.findIndex(l=>l.callback===t);a>=0&&o.listeners.splice(a,1)}}dispatchEvent(e){var t,r,s,o;let a=!1;if(e instanceof Xy){const l=this._eventListeners[e.type];if(l)for(const c of l)for(let h=0;h<c.listeners.length;h++){const u=c.listeners[h];if((r=(t=u.options)==null?void 0:t.signal)!=null&&r.aborted){c.listeners.splice(h,1),h--;continue}u.options.once&&(c.listeners.splice(h,1),h--),u.callback(e)}}if(e instanceof mh){const l=this._eventListeners[e.type];if(l)for(const c of l){if(a)break;for(let h=0;h<c.listeners.length;h++){const u=c.listeners[h];if((o=(s=u.options)==null?void 0:s.signal)!=null&&o.aborted){c.listeners.splice(h,1),h--;continue}if(e.immediatePropagationStopped){a=!0,cr&&console.log("immediatePropagationStopped",e.type);break}else e.propagationStopped&&(a=!0,cr&&console.log("propagationStopped",e.type));u.options.once&&(c.listeners.splice(h,1),h--),u.callback(e)}}}}get mousePosition(){return this._pointerPositions[0]}get mousePositionRC(){return this._pointerPositionsRC[0]}get mouseDown(){return this._pointerDown[0]}get mouseUp(){return this._pointerUp[0]}get mouseClick(){return this._pointerClick[0]}get mouseDoubleClick(){return this._pointerDoubleClick[0]}get mousePressed(){return this._pointerPressed[0]}get mouseWheelChanged(){return this.getMouseWheelChanged(0)}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(e,t=!0){if(e>=this._pointerUsed.length){if(e>=this._pointerIds.length)return;for(;this._pointerUsed.length<=e;)this._pointerUsed.push(!1)}this._pointerUsed[e]=t}getPointerUsed(e){return e>=this._pointerUsed.length?!1:this._pointerUsed[e]}getPointerPressedCount(){let e=0;for(let t=0;t<this._pointerPressed.length;t++)this._pointerPressed[t]&&e++;return e}getPointerPosition(e){return e>=this._pointerPositions.length?null:this._pointerPositions[e]}getPointerPositionLastFrame(e){return e>=this._pointerPositionsLastFrame.length?null:this._pointerPositionsLastFrame[e]}getPointerPositionDelta(e){return e>=this._pointerPositionsDelta.length?null:this._pointerPositionsDelta[e]}getPointerPositionRC(e){return e>=this._pointerPositionsRC.length?null:this._pointerPositionsRC[e]}getPointerDown(e){return e>=this._pointerDown.length?!1:this._pointerDown[e]}getPointerUp(e){return e>=this._pointerUp.length?!1:this._pointerUp[e]}getPointerPressed(e){return e>=this._pointerPressed.length?!1:this._pointerPressed[e]}getPointerClicked(e){return e>=this._pointerClick.length?!1:this._pointerClick[e]}getPointerDoubleClicked(e){return e>=this._pointerDoubleClick.length?!1:this._pointerDoubleClick[e]}getPointerDownTime(e){return e>=this._pointerDownTime.length?-1:this._pointerDownTime[e]}getPointerUpTime(e){return e>=this._pointerUpTime.length?-1:this._pointerUpTime[e]}getPointerLongPress(e){return e>=this._pointerDownTime.length?!1:this.getPointerPressed(e)&&this.context.time.time-this._pointerDownTime[e]>this._longPressTimeThreshold}getIsMouse(e){return e<0||e>=this._pointerTypes.length?!1:this._pointerTypes[e]==="mouse"}getIsTouch(e){return e<0||e>=this._pointerTypes.length?!1:this._pointerTypes[e]==="touch"}getTouchesPressedCount(){let e=0;for(let t=0;t<this._pointerPressed.length;t++)this._pointerPressed[t]&&this.getIsTouch(t)&&e++;return e}getMouseWheelChanged(e=0){return e>=this._mouseWheelChanged.length?!1:this._mouseWheelChanged[e]}getMouseWheelDeltaY(e=0){return e>=this._mouseWheelDeltaY.length?0:this._mouseWheelDeltaY[e]}getPointerEvent(e){if(!(e>=this._pointerEvent.length))return this._pointerEvent[e]??void 0}*foreachPointerId(e){for(let t=0;t<this._pointerTypes.length;t++)if(this._pointerIsActive(t)){if(e!==void 0){const r=this._pointerTypes[t];if(Array.isArray(e)){let s=!1;for(const o of e)if(r===o){s=!0;break}if(!s)continue}else if(e!==r)continue}yield t}}*foreachTouchId(){for(let e=0;e<this._pointerTypes.length;e++)this._pointerTypes[e]==="touch"&&this._pointerIsActive[e]&&(yield e)}_pointerIsActive(e){return e<0?!1:this._pointerPressed[e]||this._pointerDown[e]||this._pointerUp[e]}onDownButton(e,t){let r=this._pressedStack.get(e);r||(r=[],this._pressedStack.set(e,r)),r.push(t)}onReleaseButton(e,t){const r=this._pressedStack.get(e);if(!r)return;const s=r.indexOf(t);s>=0&&r.splice(s,1)}getFirstPressedButtonForPointer(e){const t=this._pressedStack.get(e);if(t)return t[0]}getLatestPressedButtonForPointer(e){const t=this._pressedStack.get(e);if(t)return t[t.length-1]}getKeyDown(){for(const e in this.keysPressed){const t=this.keysPressed[e];if(t.startFrame===this.context.time.frameCount)return t.key}return null}getKeyPressed(){for(const e in this.keysPressed){const t=this.keysPressed[e];if(t.pressed)return t.key}return null}isKeyDown(e){var t;if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const r=this.getCodeForCommonKeyName(e);if(r!==null){for(const s of r)if(this.isKeyDown(s))return!0;return!1}return((t=this.keysPressed[e])==null?void 0:t.startFrame)===this.context.time.frameCount&&this.keysPressed[e].pressed}isKeyUp(e){var t;if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const r=this.getCodeForCommonKeyName(e);if(r!==null){for(const s of r)if(this.isKeyUp(s))return!0;return!1}return((t=this.keysPressed[e])==null?void 0:t.frame)===this.context.time.frameCount&&!this.keysPressed[e].pressed}isKeyPressed(e){var t;if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const r=this.getCodeForCommonKeyName(e);if(r!==null){for(const s of r)if(this.isKeyPressed(s))return!0;return!1}return(t=this.keysPressed[e])==null?void 0:t.pressed}getCodeForCommonKeyName(e){if(e.length===1){if(e>="0"&&e<="9")return["Digit"+e];if(e>="a"&&e<="z")return["Key"+e.toUpperCase()];if(e==" ")return["Space"]}switch(e){case"shift":case"Shift":return["ShiftLeft","ShiftRight"];case"control":case"Control":return["ControlLeft","ControlRight"];case"alt":case"Alt":return["AltLeft","AltRight"]}return null}createInputEvent(e){switch(e.type){case"pointerdown":cr&&rn("Create Pointer down"),this.onDownButton(e.deviceIndex,e.button),this.onDown(e);break;case"pointermove":cr&&rn("Create Pointer move"),this.onMove(e);break;case"pointerup":cr&&rn("Create Pointer up"),this.onUp(e),this.onReleaseButton(e.deviceIndex,e.button);break}}convertScreenspaceToRaycastSpace(e){return e.x=(e.x-this.context.domX)/this.context.domWidth*2-1,e.y=-((e.y-this.context.domY)/this.context.domHeight)*2+1,e}bindEvents(){this.unbindEvents(),this._htmlEventSource=this.context.renderer.domElement,window.addEventListener("contextmenu",this.onContextMenu),this._htmlEventSource.addEventListener("pointerdown",this.onPointerDown,{passive:!0}),window.addEventListener("pointermove",this.onPointerMove,{passive:!0,capture:!0}),window.addEventListener("pointerup",this.onPointerUp,{passive:!0}),window.addEventListener("pointercancel",this.onPointerCancel,{passive:!0}),window.addEventListener("touchstart",this.onTouchStart,{passive:!0}),window.addEventListener("touchmove",this.onTouchMove,{passive:!0}),window.addEventListener("touchend",this.onTouchEnd,{passive:!0}),this._htmlEventSource.addEventListener("wheel",this.onMouseWheel,{passive:!0}),window.addEventListener("wheel",this.onWheelWindow,{passive:!0}),window.addEventListener("keydown",this.onKeyDown,!1),window.addEventListener("keypress",this.onKeyPressed,!1),window.addEventListener("keyup",this.onKeyUp,!1),window.addEventListener("blur",this.onLostFocus)}unbindEvents(){var e,t;window.removeEventListener("contextmenu",this.onContextMenu),(e=this._htmlEventSource)==null||e.removeEventListener("pointerdown",this.onPointerDown),window.removeEventListener("pointermove",this.onPointerMove),window.removeEventListener("pointerup",this.onPointerUp),window.removeEventListener("pointercancel",this.onPointerCancel),(t=this._htmlEventSource)==null||t.removeEventListener("wheel",this.onMouseWheel,!1),window.removeEventListener("wheel",this.onWheelWindow,!1),window.removeEventListener("keydown",this.onKeyDown,!1),window.removeEventListener("keypress",this.onKeyPressed,!1),window.removeEventListener("keyup",this.onKeyUp,!1),window.removeEventListener("blur",this.onLostFocus)}dispose(){const e=this.context.post_render_callbacks.indexOf(this.onEndOfFrame);e>=0&&this.context.post_render_callbacks.splice(e,1),this.unbindEvents()}canReceiveInput(e){var t;return e.target===((t=this.context.renderer)==null?void 0:t.domElement)||e.target===this.context.domElement||this.context.isInAR||this.context.isInAR&&e.target===document.body&&gp()?!0:(cr&&console.warn("CanReceiveInput:False for",e.target),!1)}getPointerId(e,t){return e.pointerType==="mouse"?0+(t??e.button):this.getPointerIndex(e.pointerId)}getButtonName(e){const t=e.button;if(e.pointerType==="mouse")switch(t){case 0:return"left";case 1:return"middle";case 2:return"right"}return"unknown"}getAndUpdateSpatialObjectForScreenPosition(e,t,r){let s=this._pointerSpace[e];s||(s=new ye,this._pointerSpace[e]=s),this._pointerSpace[e]=s;const o=this.context.mainCamera;if(o){const a=this.tempNearPlaneVector.set(t,r,-1);this.convertScreenspaceToRaycastSpace(a);const l=this.tempFarPlaneVector.set(a.x,a.y,1);a.unproject(o),l.unproject(o);const c=o.worldUp||pi(0,1,0).applyQuaternion(Mi(o));this.tempLookMatrix.lookAt(l,a,c),s.position.set(a.x,a.y,a.z),s.quaternion.setFromRotationMatrix(this.tempLookMatrix)}return s}isInRect(e){if(this.context.isInXR)return!0;const t=this.context.domElement.getBoundingClientRect(),r=e.clientX,s=e.clientY,o=r>=t.x&&r<=t.right&&s>=t.y&&s<=t.bottom;return cr&&!o&&console.log("Not in rect",t,r,s),o}onDown(e){const t=e.pointerId;if(this.getPointerPressed(t)&&console.warn(`pointerId is already pressed: ${t}`,cr?e:""),cr&&console.log(e.pointerType,"DOWN",t),!!this.isInRect(e)){for(this.setPointerState(t,this._pointerPressed,!0),this.setPointerState(t,this._pointerDown,!0),this.setPointerStateT(t,this._pointerEvent,e.source);t>=this._pointerTypes.length;)this._pointerTypes.push(e.pointerType);for(this._pointerTypes[t]=e.pointerType;t>=this._pointerPositionDown.length;)this._pointerPositionDown.push(new Z);for(this._pointerPositionDown[t].set(e.clientX,e.clientY);t>=this._pointerPositions.length;)this._pointerPositions.push(new Z);this._pointerPositions[t].set(e.clientX,e.clientY),t>=this._pointerDownTime.length&&this._pointerDownTime.push(0),this._pointerDownTime[t]=this.context.time.time,this.updatePointerPosition(e),this.onDispatchEvent(e)}}onMove(e){const t=e.pointerId,r=this.getPointerPressed(t);r===!1&&!this.isInRect(e)||e.pointerType==="touch"&&!r||(this.updatePointerPosition(e),this.setPointerStateT(t,this._pointerEvent,e.source),this.onDispatchEvent(e))}onUp(e){const t=e.pointerId;if(!this.getPointerPressed(t)){cr&&console.log(e.pointerType,"UP",t,"was not down");return}for(cr&&console.log(e.pointerType,"UP",t),this.setPointerState(t,this._pointerPressed,!1),this.setPointerStateT(t,this._pointerEvent,e.source),this.setPointerState(t,this._pointerUp,!0);t>=this._pointerUsed.length;)this._pointerUsed.push(!1);if(this.setPointerState(t,this._pointerUsed,!1),this.updatePointerPosition(e),!this._pointerPositionDown[t]){cr&&Di("Received pointer up event without matching down event for button: "+t),console.warn("Received pointer up event without matching down event for button: "+t);return}const r=e.clientX-this._pointerPositionDown[t].x,s=e.clientY-this._pointerPositionDown[t].y;if(t>=this._pointerUpTime.length&&this._pointerUpTime.push(-99),Math.abs(r)<5&&Math.abs(s)<5){cr&&console.log("CLICK",t),this.setPointerState(t,this._pointerClick,!0),e.isClick=!0;const o=this._pointerUpTime[t],a=this.context.time.time-o;a<this._doubleClickTimeThreshold&&a>0&&(this.setPointerState(t,this._pointerDoubleClick,!0),e.isDoubleClick=!0)}this._pointerUpTime[t]=this.context.time.time,this.onDispatchEvent(e)}updatePointerPosition(e){const t=e.pointerId;for(;t>=this._pointerPositions.length;)this._pointerPositions.push(new Z);for(;t>=this._pointerPositionsLastFrame.length;)this._pointerPositionsLastFrame.push(new Z);for(;t>=this._pointerPositionsDelta.length;)this._pointerPositionsDelta.push(new Z);const r=this._pointerPositionsLastFrame[t];r.copy(this._pointerPositions[t]);const s=this._pointerPositionsDelta[t];let o=e.clientX-r.x,a=e.clientY-r.y;if(e.source instanceof MouseEvent||e.source instanceof TouchEvent){const u=e.source;o===0&&u.movementX!==0&&(o=u.movementX||0),a===0&&u.movementY!==0&&(a=u.movementY||0)}s.x+=o,s.y+=a,this._pointerPositions[t].x=e.clientX,this._pointerPositions[t].y=e.clientY;const l=e.clientX,c=e.clientY;for(;t>=this._pointerPositionsRC.length;)this._pointerPositionsRC.push(new Z);const h=this._pointerPositionsRC[t];h.set(l,c),this.convertScreenspaceToRaycastSpace(h)}getPointerIndex(e){let t=-1;for(let r=0;r<this._pointerIds.length;r++){if(this._pointerIds[r]===e)return r;t===-1&&this._pointerIds[r]===-1&&(t=r)}return t!==-1?(this._pointerIds[t]=e,t):(cr&&console.log("PUSH pointerId:",e),this._pointerIds.push(e),this._pointerIds.length-1)}setPointerState(e,t,r){t[e]=r}setPointerStateT(e,t,r){return t[e]=r,r}onDispatchEvent(e){const t=kt.Current;try{kt.Current=this.context,this.dispatchEvent(e)}finally{kt.Current=t}}}const Y1=new ve().makeRotationY(Math.PI),Sa=new Ce().setFromAxisAngle(new C(0,1,0),Math.PI),wue=te("debugwebxr");class Sue{constructor(){if(d(this,"priority",-1e5),d(this,"gameObject"),this.gameObject=new ye,this.gameObject.name="Implicit XR Rig",wue){const e=fB(16733661);e.position.y+=.5,this.gameObject.add(e)}}isXRRig(){return!0}get isActive(){return this.gameObject.visible}}const Uu=te("debugwebxr"),J1=te("debugcustomgesture"),Cue="https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles",Eue="generic-trigger";class vB{constructor(e,t,r){d(this,"xr"),d(this,"inputSource"),d(this,"index",0),d(this,"emitEvents",!0),d(this,"_connected",!0),d(this,"_isTracking",!1),d(this,"_hitTestSource"),d(this,"_hasSelectEvent",!1),d(this,"_handJointPoses",new Map),d(this,"_gripPosition",new C),d(this,"_gripQuaternion",new Ce),d(this,"_linearVelocity",new C),d(this,"_rayPosition",new C),d(this,"_rayQuaternion",new Ce),d(this,"_gripWorldPosition",new C),d(this,"_gripWorldQuaternion",new Ce),d(this,"_rayWorldPosition",new C),d(this,"_rayWorldQuaternion",new Ce),d(this,"_ray"),d(this,"_object"),d(this,"model",null),d(this,"_debugAxesHelper",new Po(.2)),d(this,"onPointerHits",l=>{}),d(this,"_needleGamepadButtons",{}),d(this,"_buttonMap",new Map),d(this,"_motioncontroller"),d(this,"_layout"),d(this,"getMotionController"),d(this,"_selectButtonIndex"),d(this,"_squeezeButtonIndex"),d(this,"onSelectStart",l=>{var c,h,u,p;if(this.inputSource!==l.inputSource)return;this.onUpdateFrame(l.frame),this._hasSelectEvent=!0;const m=(c=this._layout)==null?void 0:c.selectComponentId,f=(p=(u=(h=this._layout)==null?void 0:h.components[m])==null?void 0:u.gamepadIndices)==null?void 0:p.button;f!==void 0&&(this._selectButtonIndex=f),!J1&&(Uu&&At.DrawDirection(this.rayWorldPosition,pi(0,.01,1).applyQuaternion(this.rayWorldQuaternion),16711680,10),this.emitPointerEvent(an.PointerDown,this._selectButtonIndex||0,"xr-standard-trigger",!0,l))}),d(this,"onSelectEnd",l=>{J1||this.inputSource===l.inputSource&&this.emitPointerEvent(an.PointerUp,this._selectButtonIndex||0,"xr-standard-trigger",!0,l)}),d(this,"onSequeezeStart",l=>{var c,h,u;this.inputSource===l.inputSource&&(this._squeezeButtonIndex=(u=(h=(c=this._layout)==null?void 0:c.components["xr-standard-squeeze"])==null?void 0:h.gamepadIndices)==null?void 0:u.button,this._squeezeButtonIndex!==void 0&&(Uu&&At.DrawDirection(this.rayWorldPosition,pi(0,.01,1).applyQuaternion(this.rayWorldQuaternion),255,10),this.emitPointerEvent(an.PointerDown,this._squeezeButtonIndex||0,"xr-standard-squeeze",!0,l)))}),d(this,"onSequeezeEnd",l=>{this.inputSource===l.inputSource&&this._squeezeButtonIndex!==void 0&&this.emitPointerEvent(an.PointerUp,this._squeezeButtonIndex||0,"xr-standard-squeeze",!0,l)}),d(this,"states",{}),d(this,"_didMoveLastFrame",!1),d(this,"_lastPointerMovePosition",new C),d(this,"_lastPointerMoveQuaternion",new Ce),d(this,"pointerInit");var s,o,a;this.xr=e,this.inputSource=t,this.index=r,this._object=new ye,Uu&&this._object.add(this._debugAxesHelper),this.xr.context.scene.add(this._object),this._ray=new co,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"&&((a=(o=(s=this.xr.session).requestHitTestSourceForTransientInput)==null?void 0:o.call(s,{profile:this.inputSource.profiles[0],offsetRay:new XRRay}))==null||a.then(l=>this._hitTestSource=l))}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(e){var t,r;if(!this.hand||!((t=this.xr.frame)!=null&&t.getJointPose)||!this.xr.referenceSpace)return null;let s=(r=this._handJointPoses)==null?void 0:r.get(e);return s||(s=this.xr.frame.getJointPose(e,this.xr.referenceSpace),s&&this._handJointPoses.set(e,s),s)}get gripPosition(){return pi(this._gripPosition).applyMatrix4(Y1)}get gripQuaternion(){return bp(this._gripQuaternion).premultiply(Sa)}get gripLinearVelocity(){return pi(this._linearVelocity).applyQuaternion(Sa)}get rayPosition(){return pi(this._rayPosition).applyMatrix4(Y1)}get rayQuaternion(){return bp(this._rayQuaternion).premultiply(Sa)}get gripWorldPosition(){return pi(this._gripWorldPosition)}get gripWorldQuaternion(){return bp(this._gripWorldQuaternion)}get rayWorldPosition(){return pi(this._rayWorldPosition)}updateRayWorldPosition(){var e;const t=(e=this.xr.context.mainCamera)==null?void 0:e.parent;this._rayWorldPosition.copy(this._rayPosition),t&&this._rayWorldPosition.applyMatrix4(t.matrixWorld)}get rayWorldQuaternion(){return bp(this._rayWorldQuaternion)}updateRayWorldQuaternion(){var e;const t=(e=this.xr.context.mainCamera)==null?void 0:e.parent,r=t?Mi(t):void 0;this._rayWorldQuaternion.copy(this._rayQuaternion).multiply(Sa),r&&this._rayWorldQuaternion.premultiply(r)}get ray(){return this._ray.origin.copy(this.rayWorldPosition),this._ray.direction.copy(pi(0,0,1).applyQuaternion(this.rayWorldQuaternion)),this._ray}get object(){return this._object}async getModelUrl(){var e;return(e=this.getMotionController)==null?void 0:e.then(t=>t?.assetUrl||null)}onUpdate(e){this.onUpdateFrame(e),this.updateInputEvents(),this.onUpdateMove()}onRenderDebug(){var e;At.DrawWireSphere(this.rayWorldPosition,.02),At.DrawDirection(this.rayWorldPosition,pi(0,0,10).applyQuaternion(this.rayWorldQuaternion));const t=this.gripWorldPosition.sub(this.object.worldForward.multiplyScalar(.1)),r=this.inputSource.profiles.join(`
5152
5152
  `);let s=`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&&(s+=`
5154
5154
  Pinch: ${(e=this.getGesture("pinch"))==null?void 0:e.value.toFixed(3)}`),s+=`
@@ -5232,7 +5232,7 @@ a=extmap-allow-mixed`)!==-1){const s=r.sdp.split(`
5232
5232
  isUnifiedPlanSupported:`).concat(this.isUnifiedPlanSupported())},n}()),FG={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"},Hue=function(){function n(){this.CLOUD_HOST="0.peerjs.com",this.CLOUD_PORT=443,this.chunkedBrowsers={Chrome:1,chrome:1},this.chunkedMTU=16300,this.defaultConfig=FG,this.browser=Zy.getBrowser(),this.browserVersion=Zy.getVersion(),this.supports=function(){var e={browser:Zy.isBrowserSupported(),webRTC:Zy.isWebRTCSupported(),audioVideo:!1,data:!1,binaryBlob:!1,reliable:!1};if(!e.webRTC)return e;var t;try{t=new RTCPeerConnection(FG),e.audioVideo=!0;var r=void 0;try{r=t.createDataChannel("_PEERJSTEST",{ordered:!0}),e.data=!0,e.reliable=!!r.ordered;try{r.binaryType="blob",e.binaryBlob=!Zy.isIOS}catch{}}catch{}finally{r&&r.close()}}catch{}finally{t&&t.close()}return e}(),this.pack=Q6.pack,this.unpack=Q6.unpack,this._dataCount=1}return n.prototype.noop=function(){},n.prototype.validateId=function(e){return!e||/^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/.test(e)},n.prototype.chunk=function(e){for(var t=[],r=e.size,s=Math.ceil(r/wi.chunkedMTU),o=0,a=0;a<r;){var l=Math.min(r,a+wi.chunkedMTU),c=e.slice(a,l),h={__peerData:this._dataCount,n:o,data:c,total:s};t.push(h),a=l,o++}return this._dataCount++,t},n.prototype.blobToArrayBuffer=function(e,t){var r=new FileReader;return r.onload=function(s){s.target&&t(s.target.result)},r.readAsArrayBuffer(e),r},n.prototype.binaryStringToArrayBuffer=function(e){for(var t=new Uint8Array(e.length),r=0;r<e.length;r++)t[r]=e.charCodeAt(r)&255;return t.buffer},n.prototype.randomToken=function(){return Math.random().toString(36).slice(2)},n.prototype.isSecure=function(){return location.protocol==="https:"},n}(),wi=new Hue,UG={};Kl(UG,"Peer",()=>UB,n=>UB=n);var $y={},Wue=Object.prototype.hasOwnProperty,Ks="~";function eA(){}Object.create&&(eA.prototype=Object.create(null),new eA().__proto__||(Ks=!1));function Xue(n,e,t){this.fn=n,this.context=e,this.once=t||!1}function NG(n,e,t,r,s){if(typeof t!="function")throw new TypeError("The listener must be a function");var o=new Xue(t,r||n,s),a=Ks?Ks+e:e;return n._events[a]?n._events[a].fn?n._events[a]=[n._events[a],o]:n._events[a].push(o):(n._events[a]=o,n._eventsCount++),n}function rS(n,e){--n._eventsCount===0?n._events=new eA:delete n._events[e]}function Cs(){this._events=new eA,this._eventsCount=0}Cs.prototype.eventNames=function(){var n=[],e,t;if(this._eventsCount===0)return n;for(t in e=this._events)Wue.call(e,t)&&n.push(Ks?t.slice(1):t);return Object.getOwnPropertySymbols?n.concat(Object.getOwnPropertySymbols(e)):n},Cs.prototype.listeners=function(n){var e=Ks?Ks+n:n,t=this._events[e];if(!t)return[];if(t.fn)return[t.fn];for(var r=0,s=t.length,o=new Array(s);r<s;r++)o[r]=t[r].fn;return o},Cs.prototype.listenerCount=function(n){var e=Ks?Ks+n:n,t=this._events[e];return t?t.fn?1:t.length:0},Cs.prototype.emit=function(n,e,t,r,s,o){var a=Ks?Ks+n:n;if(!this._events[a])return!1;var l=this._events[a],c=arguments.length,h,u;if(l.fn){switch(l.once&&this.removeListener(n,l.fn,void 0,!0),c){case 1:return l.fn.call(l.context),!0;case 2:return l.fn.call(l.context,e),!0;case 3:return l.fn.call(l.context,e,t),!0;case 4:return l.fn.call(l.context,e,t,r),!0;case 5:return l.fn.call(l.context,e,t,r,s),!0;case 6:return l.fn.call(l.context,e,t,r,s,o),!0}for(u=1,h=new Array(c-1);u<c;u++)h[u-1]=arguments[u];l.fn.apply(l.context,h)}else{var p=l.length,m;for(u=0;u<p;u++)switch(l[u].once&&this.removeListener(n,l[u].fn,void 0,!0),c){case 1:l[u].fn.call(l[u].context);break;case 2:l[u].fn.call(l[u].context,e);break;case 3:l[u].fn.call(l[u].context,e,t);break;case 4:l[u].fn.call(l[u].context,e,t,r);break;default:if(!h)for(m=1,h=new Array(c-1);m<c;m++)h[m-1]=arguments[m];l[u].fn.apply(l[u].context,h)}}return!0},Cs.prototype.on=function(n,e,t){return NG(this,n,e,t,!1)},Cs.prototype.once=function(n,e,t){return NG(this,n,e,t,!0)},Cs.prototype.removeListener=function(n,e,t,r){var s=Ks?Ks+n:n;if(!this._events[s])return this;if(!e)return rS(this,s),this;var o=this._events[s];if(o.fn)o.fn===e&&(!r||o.once)&&(!t||o.context===t)&&rS(this,s);else{for(var a=0,l=[],c=o.length;a<c;a++)(o[a].fn!==e||r&&!o[a].once||t&&o[a].context!==t)&&l.push(o[a]);l.length?this._events[s]=l.length===1?l[0]:l:rS(this,s)}return this},Cs.prototype.removeAllListeners=function(n){var e;return n?(e=Ks?Ks+n:n,this._events[e]&&rS(this,e)):(this._events=new eA,this._eventsCount=0),this},Cs.prototype.off=Cs.prototype.removeListener,Cs.prototype.addListener=Cs.prototype.on,Cs.prefixed=Ks,Cs.EventEmitter=Cs,$y=Cs;var dt={};Kl(dt,"LogLevel",()=>yo,n=>yo=n),Kl(dt,"default",()=>zG,n=>zG=n);var Xp=function(n,e){var t=typeof Symbol=="function"&&n[Symbol.iterator];if(!t)return n;var r=t.call(n),s,o=[],a;try{for(;(e===void 0||e-- >0)&&!(s=r.next()).done;)o.push(s.value)}catch(l){a={error:l}}finally{try{s&&!s.done&&(t=r.return)&&t.call(r)}finally{if(a)throw a.error}}return o},qp=function(n,e,t){if(t||arguments.length===2)for(var r=0,s=e.length,o;r<s;r++)(o||!(r in e))&&(o||(o=Array.prototype.slice.call(e,0,r)),o[r]=e[r]);return n.concat(o||Array.prototype.slice.call(e))},que="PeerJS: ",yo;(function(n){n[n.Disabled=0]="Disabled",n[n.Errors=1]="Errors",n[n.Warnings=2]="Warnings",n[n.All=3]="All"})(yo||(yo={}));var Yue=function(){function n(){this._logLevel=yo.Disabled}return Object.defineProperty(n.prototype,"logLevel",{get:function(){return this._logLevel},set:function(e){this._logLevel=e},enumerable:!1,configurable:!0}),n.prototype.log=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this._logLevel>=yo.All&&this._print.apply(this,qp([yo.All],Xp(e),!1))},n.prototype.warn=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this._logLevel>=yo.Warnings&&this._print.apply(this,qp([yo.Warnings],Xp(e),!1))},n.prototype.error=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this._logLevel>=yo.Errors&&this._print.apply(this,qp([yo.Errors],Xp(e),!1))},n.prototype.setLogFunction=function(e){this._print=e},n.prototype._print=function(e){for(var t=[],r=1;r<arguments.length;r++)t[r-1]=arguments[r];var s=qp([que],Xp(t),!1);for(var o in s)s[o]instanceof Error&&(s[o]="("+s[o].name+") "+s[o].message);e>=yo.All?console.log.apply(console,qp([],Xp(s),!1)):e>=yo.Warnings?console.warn.apply(console,qp(["WARNING"],Xp(s),!1)):e>=yo.Errors&&console.error.apply(console,qp(["ERROR"],Xp(s),!1))},n}(),zG=new Yue,jG={};Kl(jG,"Socket",()=>GG,n=>GG=n);var pl;(function(n){n.Data="data",n.Media="media"})(pl||(pl={}));var Fn;(function(n){n.BrowserIncompatible="browser-incompatible",n.Disconnected="disconnected",n.InvalidID="invalid-id",n.InvalidKey="invalid-key",n.Network="network",n.PeerUnavailable="peer-unavailable",n.SslUnavailable="ssl-unavailable",n.ServerError="server-error",n.SocketError="socket-error",n.SocketClosed="socket-closed",n.UnavailableID="unavailable-id",n.WebRTC="webrtc"})(Fn||(Fn={}));var gh;(function(n){n.Binary="binary",n.BinaryUTF8="binary-utf8",n.JSON="json"})(gh||(gh={}));var vh;(function(n){n.Message="message",n.Disconnected="disconnected",n.Error="error",n.Close="close"})(vh||(vh={}));var Qr;(function(n){n.Heartbeat="HEARTBEAT",n.Candidate="CANDIDATE",n.Offer="OFFER",n.Answer="ANSWER",n.Open="OPEN",n.Error="ERROR",n.IdTaken="ID-TAKEN",n.InvalidKey="INVALID-KEY",n.Leave="LEAVE",n.Expire="EXPIRE"})(Qr||(Qr={}));var kB={};kB=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\xFCckler <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>","So\u0308ren 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 Jue=function(){var n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,s){r.__proto__=s}||function(r,s){for(var o in s)Object.prototype.hasOwnProperty.call(s,o)&&(r[o]=s[o])},n(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");n(e,t);function r(){this.constructor=e}e.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}}(),Kue=function(n,e){var t=typeof Symbol=="function"&&n[Symbol.iterator];if(!t)return n;var r=t.call(n),s,o=[],a;try{for(;(e===void 0||e-- >0)&&!(s=r.next()).done;)o.push(s.value)}catch(l){a={error:l}}finally{try{s&&!s.done&&(t=r.return)&&t.call(r)}finally{if(a)throw a.error}}return o},Zue=function(n,e,t){if(t||arguments.length===2)for(var r=0,s=e.length,o;r<s;r++)(o||!(r in e))&&(o||(o=Array.prototype.slice.call(e,0,r)),o[r]=e[r]);return n.concat(o||Array.prototype.slice.call(e))},$ue=function(n){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&n[e],r=0;if(t)return t.call(n);if(n&&typeof n.length=="number")return{next:function(){return n&&r>=n.length&&(n=void 0),{value:n&&n[r++],done:!n}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},GG=function(n){Jue(e,n);function e(t,r,s,o,a,l){l===void 0&&(l=5e3);var c=n.call(this)||this;c.pingInterval=l,c._disconnected=!0,c._messagesQueue=[];var h=t?"wss://":"ws://";return c._baseUrl=h+r+":"+s+o+"peerjs?key="+a,c}return e.prototype.start=function(t,r){var s=this;this._id=t;var o="".concat(this._baseUrl,"&id=").concat(t,"&token=").concat(r);this._socket||!this._disconnected||(this._socket=new WebSocket(o+"&version="+kB.version),this._disconnected=!1,this._socket.onmessage=function(a){var l;try{l=JSON.parse(a.data),dt.default.log("Server message received:",l)}catch{dt.default.log("Invalid server message",a.data);return}s.emit(vh.Message,l)},this._socket.onclose=function(a){s._disconnected||(dt.default.log("Socket closed.",a),s._cleanup(),s._disconnected=!0,s.emit(vh.Disconnected))},this._socket.onopen=function(){s._disconnected||(s._sendQueuedMessages(),dt.default.log("Socket open"),s._scheduleHeartbeat())})},e.prototype._scheduleHeartbeat=function(){var t=this;this._wsPingTimer=setTimeout(function(){t._sendHeartbeat()},this.pingInterval)},e.prototype._sendHeartbeat=function(){if(!this._wsOpen()){dt.default.log("Cannot send heartbeat, because socket closed");return}var t=JSON.stringify({type:Qr.Heartbeat});this._socket.send(t),this._scheduleHeartbeat()},e.prototype._wsOpen=function(){return!!this._socket&&this._socket.readyState===1},e.prototype._sendQueuedMessages=function(){var t,r,s=Zue([],Kue(this._messagesQueue),!1);this._messagesQueue=[];try{for(var o=$ue(s),a=o.next();!a.done;a=o.next()){var l=a.value;this.send(l)}}catch(c){t={error:c}}finally{try{a&&!a.done&&(r=o.return)&&r.call(o)}finally{if(t)throw t.error}}},e.prototype.send=function(t){if(!this._disconnected){if(!this._id){this._messagesQueue.push(t);return}if(!t.type){this.emit(vh.Error,"Invalid message");return}if(this._wsOpen()){var r=JSON.stringify(t);this._socket.send(r)}}},e.prototype.close=function(){this._disconnected||(this._cleanup(),this._disconnected=!0)},e.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)},e}($y.EventEmitter),DB={};Kl(DB,"MediaConnection",()=>HG,n=>HG=n);var OB={};Kl(OB,"Negotiator",()=>VG,n=>VG=n);var sS=function(){return sS=Object.assign||function(n){for(var e,t=1,r=arguments.length;t<r;t++){e=arguments[t];for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&(n[s]=e[s])}return n},sS.apply(this,arguments)},oS=function(n,e,t,r){function s(o){return o instanceof t?o:new t(function(a){a(o)})}return new(t||(t=Promise))(function(o,a){function l(u){try{h(r.next(u))}catch(p){a(p)}}function c(u){try{h(r.throw(u))}catch(p){a(p)}}function h(u){u.done?o(u.value):s(u.value).then(l,c)}h((r=r.apply(n,e||[])).next())})},aS=function(n,e){var t={label:0,sent:function(){if(o[0]&1)throw o[1];return o[1]},trys:[],ops:[]},r,s,o,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(h){return function(u){return c([h,u])}}function c(h){if(r)throw new TypeError("Generator is already executing.");for(;t;)try{if(r=1,s&&(o=h[0]&2?s.return:h[0]?s.throw||((o=s.return)&&o.call(s),0):s.next)&&!(o=o.call(s,h[1])).done)return o;switch(s=0,o&&(h=[h[0]&2,o.value]),h[0]){case 0:case 1:o=h;break;case 4:return t.label++,{value:h[1],done:!1};case 5:t.label++,s=h[1],h=[0];continue;case 7:h=t.ops.pop(),t.trys.pop();continue;default:if(o=t.trys,!(o=o.length>0&&o[o.length-1])&&(h[0]===6||h[0]===2)){t=0;continue}if(h[0]===3&&(!o||h[1]>o[0]&&h[1]<o[3])){t.label=h[1];break}if(h[0]===6&&t.label<o[1]){t.label=o[1],o=h;break}if(o&&t.label<o[2]){t.label=o[2],t.ops.push(h);break}o[2]&&t.ops.pop(),t.trys.pop();continue}h=e.call(n,t)}catch(u){h=[6,u],s=0}finally{r=o=0}if(h[0]&5)throw h[1];return{value:h[0]?h[1]:void 0,done:!0}}},VG=function(){function n(e){this.connection=e}return n.prototype.startConnection=function(e){var t=this._startPeerConnection();if(this.connection.peerConnection=t,this.connection.type===pl.Media&&e._stream&&this._addTracksToConnection(e._stream,t),e.originator){if(this.connection.type===pl.Data){var r=this.connection,s={ordered:!!e.reliable},o=t.createDataChannel(r.label,s);r.initialize(o)}this._makeOffer()}else this.handleSDP("OFFER",e.sdp)},n.prototype._startPeerConnection=function(){dt.default.log("Creating RTCPeerConnection.");var e=new RTCPeerConnection(this.connection.provider.options.config);return this._setupListeners(e),e},n.prototype._setupListeners=function(e){var t=this,r=this.connection.peer,s=this.connection.connectionId,o=this.connection.type,a=this.connection.provider;dt.default.log("Listening for ICE candidates."),e.onicecandidate=function(l){!l.candidate||!l.candidate.candidate||(dt.default.log("Received ICE candidates for ".concat(r,":"),l.candidate),a.socket.send({type:Qr.Candidate,payload:{candidate:l.candidate,type:o,connectionId:s},dst:r}))},e.oniceconnectionstatechange=function(){switch(e.iceConnectionState){case"failed":dt.default.log("iceConnectionState is failed, closing connections to "+r),t.connection.emit("error",new Error("Negotiation of connection to "+r+" failed.")),t.connection.close();break;case"closed":dt.default.log("iceConnectionState is closed, closing connections to "+r),t.connection.emit("error",new Error("Connection to "+r+" closed.")),t.connection.close();break;case"disconnected":dt.default.log("iceConnectionState changed to disconnected on the connection with "+r);break;case"completed":e.onicecandidate=wi.noop;break}t.connection.emit("iceStateChanged",e.iceConnectionState)},dt.default.log("Listening for data channel"),e.ondatachannel=function(l){dt.default.log("Received data channel");var c=l.channel,h=a.getConnection(r,s);h.initialize(c)},dt.default.log("Listening for remote stream"),e.ontrack=function(l){dt.default.log("Received remote stream");var c=l.streams[0],h=a.getConnection(r,s);if(h.type===pl.Media){var u=h;t._addStreamToMediaConnection(c,u)}}},n.prototype.cleanup=function(){dt.default.log("Cleaning up PeerConnection to "+this.connection.peer);var e=this.connection.peerConnection;if(e){this.connection.peerConnection=null,e.onicecandidate=e.oniceconnectionstatechange=e.ondatachannel=e.ontrack=function(){};var t=e.signalingState!=="closed",r=!1;if(this.connection.type===pl.Data){var s=this.connection,o=s.dataChannel;o&&(r=!!o.readyState&&o.readyState!=="closed")}(t||r)&&e.close()}},n.prototype._makeOffer=function(){return oS(this,void 0,Promise,function(){var e,t,r,s,o,a,l;return aS(this,function(c){switch(c.label){case 0:e=this.connection.peerConnection,t=this.connection.provider,c.label=1;case 1:return c.trys.push([1,7,,8]),[4,e.createOffer(this.connection.options.constraints)];case 2:r=c.sent(),dt.default.log("Created offer."),this.connection.options.sdpTransform&&typeof this.connection.options.sdpTransform=="function"&&(r.sdp=this.connection.options.sdpTransform(r.sdp)||r.sdp),c.label=3;case 3:return c.trys.push([3,5,,6]),[4,e.setLocalDescription(r)];case 4:return c.sent(),dt.default.log("Set localDescription:",r,"for:".concat(this.connection.peer)),s={sdp:r,type:this.connection.type,connectionId:this.connection.connectionId,metadata:this.connection.metadata,browser:wi.browser},this.connection.type===pl.Data&&(o=this.connection,s=sS(sS({},s),{label:o.label,reliable:o.reliable,serialization:o.serialization})),t.socket.send({type:Qr.Offer,payload:s,dst:this.connection.peer}),[3,6];case 5:return a=c.sent(),a!="OperationError: Failed to set local offer sdp: Called in wrong state: kHaveRemoteOffer"&&(t.emitError(Fn.WebRTC,a),dt.default.log("Failed to setLocalDescription, ",a)),[3,6];case 6:return[3,8];case 7:return l=c.sent(),t.emitError(Fn.WebRTC,l),dt.default.log("Failed to createOffer, ",l),[3,8];case 8:return[2]}})})},n.prototype._makeAnswer=function(){return oS(this,void 0,Promise,function(){var e,t,r,s,o;return aS(this,function(a){switch(a.label){case 0:e=this.connection.peerConnection,t=this.connection.provider,a.label=1;case 1:return a.trys.push([1,7,,8]),[4,e.createAnswer()];case 2:r=a.sent(),dt.default.log("Created answer."),this.connection.options.sdpTransform&&typeof this.connection.options.sdpTransform=="function"&&(r.sdp=this.connection.options.sdpTransform(r.sdp)||r.sdp),a.label=3;case 3:return a.trys.push([3,5,,6]),[4,e.setLocalDescription(r)];case 4:return a.sent(),dt.default.log("Set localDescription:",r,"for:".concat(this.connection.peer)),t.socket.send({type:Qr.Answer,payload:{sdp:r,type:this.connection.type,connectionId:this.connection.connectionId,browser:wi.browser},dst:this.connection.peer}),[3,6];case 5:return s=a.sent(),t.emitError(Fn.WebRTC,s),dt.default.log("Failed to setLocalDescription, ",s),[3,6];case 6:return[3,8];case 7:return o=a.sent(),t.emitError(Fn.WebRTC,o),dt.default.log("Failed to create answer, ",o),[3,8];case 8:return[2]}})})},n.prototype.handleSDP=function(e,t){return oS(this,void 0,Promise,function(){var r,s,o,a;return aS(this,function(l){switch(l.label){case 0:t=new RTCSessionDescription(t),r=this.connection.peerConnection,s=this.connection.provider,dt.default.log("Setting remote description",t),o=this,l.label=1;case 1:return l.trys.push([1,5,,6]),[4,r.setRemoteDescription(t)];case 2:return l.sent(),dt.default.log("Set remoteDescription:".concat(e," for:").concat(this.connection.peer)),e!=="OFFER"?[3,4]:[4,o._makeAnswer()];case 3:l.sent(),l.label=4;case 4:return[3,6];case 5:return a=l.sent(),s.emitError(Fn.WebRTC,a),dt.default.log("Failed to setRemoteDescription, ",a),[3,6];case 6:return[2]}})})},n.prototype.handleCandidate=function(e){return oS(this,void 0,Promise,function(){var t,r,s,o,a,l;return aS(this,function(c){switch(c.label){case 0:dt.default.log("handleCandidate:",e),t=e.candidate,r=e.sdpMLineIndex,s=e.sdpMid,o=this.connection.peerConnection,a=this.connection.provider,c.label=1;case 1:return c.trys.push([1,3,,4]),[4,o.addIceCandidate(new RTCIceCandidate({sdpMid:s,sdpMLineIndex:r,candidate:t}))];case 2:return c.sent(),dt.default.log("Added ICE candidate for:".concat(this.connection.peer)),[3,4];case 3:return l=c.sent(),a.emitError(Fn.WebRTC,l),dt.default.log("Failed to handleCandidate, ",l),[3,4];case 4:return[2]}})})},n.prototype._addTracksToConnection=function(e,t){if(dt.default.log("add tracks from stream ".concat(e.id," to peer connection")),!t.addTrack)return dt.default.error("Your browser does't support RTCPeerConnection#addTrack. Ignored.");e.getTracks().forEach(function(r){t.addTrack(r,e)})},n.prototype._addStreamToMediaConnection=function(e,t){dt.default.log("add stream ".concat(e.id," to media connection ").concat(t.connectionId)),t.addStream(e)},n}(),LB={};Kl(LB,"BaseConnection",()=>QG,n=>QG=n);var ede=function(){var n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,s){r.__proto__=s}||function(r,s){for(var o in s)Object.prototype.hasOwnProperty.call(s,o)&&(r[o]=s[o])},n(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");n(e,t);function r(){this.constructor=e}e.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}}(),QG=function(n){ede(e,n);function e(t,r,s){var o=n.call(this)||this;return o.peer=t,o.provider=r,o.options=s,o._open=!1,o.metadata=s.metadata,o}return Object.defineProperty(e.prototype,"open",{get:function(){return this._open},enumerable:!1,configurable:!0}),e}($y.EventEmitter),tde=function(){var n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,s){r.__proto__=s}||function(r,s){for(var o in s)Object.prototype.hasOwnProperty.call(s,o)&&(r[o]=s[o])},n(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");n(e,t);function r(){this.constructor=e}e.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}}(),lS=function(){return lS=Object.assign||function(n){for(var e,t=1,r=arguments.length;t<r;t++){e=arguments[t];for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&(n[s]=e[s])}return n},lS.apply(this,arguments)},ide=function(n){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&n[e],r=0;if(t)return t.call(n);if(n&&typeof n.length=="number")return{next:function(){return n&&r>=n.length&&(n=void 0),{value:n&&n[r++],done:!n}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},HG=function(n){tde(e,n);function e(t,r,s){var o=n.call(this,t,r,s)||this;return o._localStream=o.options._stream,o.connectionId=o.options.connectionId||e.ID_PREFIX+wi.randomToken(),o._negotiator=new OB.Negotiator(o),o._localStream&&o._negotiator.startConnection({_stream:o._localStream,originator:!0}),o}return Object.defineProperty(e.prototype,"type",{get:function(){return pl.Media},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"localStream",{get:function(){return this._localStream},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"remoteStream",{get:function(){return this._remoteStream},enumerable:!1,configurable:!0}),e.prototype.addStream=function(t){dt.default.log("Receiving stream",t),this._remoteStream=t,n.prototype.emit.call(this,"stream",t)},e.prototype.handleMessage=function(t){var r=t.type,s=t.payload;switch(t.type){case Qr.Answer:this._negotiator.handleSDP(r,s.sdp),this._open=!0;break;case Qr.Candidate:this._negotiator.handleCandidate(s.candidate);break;default:dt.default.warn("Unrecognized message type:".concat(r," from peer:").concat(this.peer));break}},e.prototype.answer=function(t,r){var s,o;if(r===void 0&&(r={}),this._localStream){dt.default.warn("Local stream already exists on this MediaConnection. Are you answering a call twice?");return}this._localStream=t,r&&r.sdpTransform&&(this.options.sdpTransform=r.sdpTransform),this._negotiator.startConnection(lS(lS({},this.options._payload),{_stream:t}));var a=this.provider._getMessages(this.connectionId);try{for(var l=ide(a),c=l.next();!c.done;c=l.next()){var h=c.value;this.handleMessage(h)}}catch(u){s={error:u}}finally{try{c&&!c.done&&(o=l.return)&&o.call(l)}finally{if(s)throw s.error}}this._open=!0},e.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,n.prototype.emit.call(this,"close"))},e.ID_PREFIX="mc_",e}(LB.BaseConnection),FB={};Kl(FB,"DataConnection",()=>qG,n=>qG=n);var WG={};Kl(WG,"EncodingQueue",()=>XG,n=>XG=n);var nde=function(){var n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,s){r.__proto__=s}||function(r,s){for(var o in s)Object.prototype.hasOwnProperty.call(s,o)&&(r[o]=s[o])},n(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");n(e,t);function r(){this.constructor=e}e.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}}(),XG=function(n){nde(e,n);function e(){var t=n.call(this)||this;return t.fileReader=new FileReader,t._queue=[],t._processing=!1,t.fileReader.onload=function(r){t._processing=!1,r.target&&t.emit("done",r.target.result),t.doNextTask()},t.fileReader.onerror=function(r){dt.default.error("EncodingQueue error:",r),t._processing=!1,t.destroy(),t.emit("error",r)},t}return Object.defineProperty(e.prototype,"queue",{get:function(){return this._queue},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"size",{get:function(){return this.queue.length},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"processing",{get:function(){return this._processing},enumerable:!1,configurable:!0}),e.prototype.enque=function(t){this.queue.push(t),!this.processing&&this.doNextTask()},e.prototype.destroy=function(){this.fileReader.abort(),this._queue=[]},e.prototype.doNextTask=function(){this.size!==0&&(this.processing||(this._processing=!0,this.fileReader.readAsArrayBuffer(this.queue.shift())))},e}($y.EventEmitter),rde=function(){var n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,s){r.__proto__=s}||function(r,s){for(var o in s)Object.prototype.hasOwnProperty.call(s,o)&&(r[o]=s[o])},n(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");n(e,t);function r(){this.constructor=e}e.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}}(),sde=function(n){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&n[e],r=0;if(t)return t.call(n);if(n&&typeof n.length=="number")return{next:function(){return n&&r>=n.length&&(n=void 0),{value:n&&n[r++],done:!n}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},qG=function(n){rde(e,n);function e(t,r,s){var o=n.call(this,t,r,s)||this;return o.stringify=JSON.stringify,o.parse=JSON.parse,o._buffer=[],o._bufferSize=0,o._buffering=!1,o._chunkedData={},o._encodingQueue=new WG.EncodingQueue,o.connectionId=o.options.connectionId||e.ID_PREFIX+wi.randomToken(),o.label=o.options.label||o.connectionId,o.serialization=o.options.serialization||gh.Binary,o.reliable=!!o.options.reliable,o._encodingQueue.on("done",function(a){o._bufferedSend(a)}),o._encodingQueue.on("error",function(){dt.default.error("DC#".concat(o.connectionId,": Error occured in encoding from blob to arraybuffer, close DC")),o.close()}),o._negotiator=new OB.Negotiator(o),o._negotiator.startConnection(o.options._payload||{originator:!0}),o}return Object.defineProperty(e.prototype,"type",{get:function(){return pl.Data},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"dataChannel",{get:function(){return this._dc},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"bufferSize",{get:function(){return this._bufferSize},enumerable:!1,configurable:!0}),e.prototype.initialize=function(t){this._dc=t,this._configureDataChannel()},e.prototype._configureDataChannel=function(){var t=this;(!wi.supports.binaryBlob||wi.supports.reliable)&&(this.dataChannel.binaryType="arraybuffer"),this.dataChannel.onopen=function(){dt.default.log("DC#".concat(t.connectionId," dc connection success")),t._open=!0,t.emit("open")},this.dataChannel.onmessage=function(r){dt.default.log("DC#".concat(t.connectionId," dc onmessage:"),r.data),t._handleDataMessage(r)},this.dataChannel.onclose=function(){dt.default.log("DC#".concat(t.connectionId," dc closed for:"),t.peer),t.close()}},e.prototype._handleDataMessage=function(t){var r=this,s=t.data,o=s.constructor,a=this.serialization===gh.Binary||this.serialization===gh.BinaryUTF8,l=s;if(a){if(o===Blob){wi.blobToArrayBuffer(s,function(h){var u=wi.unpack(h);r.emit("data",u)});return}else if(o===ArrayBuffer)l=wi.unpack(s);else if(o===String){var c=wi.binaryStringToArrayBuffer(s);l=wi.unpack(c)}}else this.serialization===gh.JSON&&(l=this.parse(s));if(l.__peerData){this._handleChunk(l);return}n.prototype.emit.call(this,"data",l)},e.prototype._handleChunk=function(t){var r=t.__peerData,s=this._chunkedData[r]||{data:[],count:0,total:t.total};if(s.data[t.n]=t.data,s.count++,this._chunkedData[r]=s,s.total===s.count){delete this._chunkedData[r];var o=new Blob(s.data);this._handleDataMessage({data:o})}},e.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,n.prototype.emit.call(this,"close"))},e.prototype.send=function(t,r){if(!this.open){n.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===gh.JSON)this._bufferedSend(this.stringify(t));else if(this.serialization===gh.Binary||this.serialization===gh.BinaryUTF8){var s=wi.pack(t);if(!r&&s.size>wi.chunkedMTU){this._sendChunks(s);return}wi.supports.binaryBlob?this._bufferedSend(s):this._encodingQueue.enque(s)}else this._bufferedSend(t)},e.prototype._bufferedSend=function(t){(this._buffering||!this._trySend(t))&&(this._buffer.push(t),this._bufferSize=this._buffer.length)},e.prototype._trySend=function(t){var r=this;if(!this.open)return!1;if(this.dataChannel.bufferedAmount>e.MAX_BUFFERED_AMOUNT)return this._buffering=!0,setTimeout(function(){r._buffering=!1,r._tryBuffer()},50),!1;try{this.dataChannel.send(t)}catch(s){return dt.default.error("DC#:".concat(this.connectionId," Error when sending:"),s),this._buffering=!0,this.close(),!1}return!0},e.prototype._tryBuffer=function(){if(this.open&&this._buffer.length!==0){var t=this._buffer[0];this._trySend(t)&&(this._buffer.shift(),this._bufferSize=this._buffer.length,this._tryBuffer())}},e.prototype._sendChunks=function(t){var r,s,o=wi.chunk(t);dt.default.log("DC#".concat(this.connectionId," Try to send ").concat(o.length," chunks..."));try{for(var a=sde(o),l=a.next();!l.done;l=a.next()){var c=l.value;this.send(c,!0)}}catch(h){r={error:h}}finally{try{l&&!l.done&&(s=a.return)&&s.call(a)}finally{if(r)throw r.error}}},e.prototype.handleMessage=function(t){var r=t.payload;switch(t.type){case Qr.Answer:this._negotiator.handleSDP(t.type,r.sdp);break;case Qr.Candidate:this._negotiator.handleCandidate(r.candidate);break;default:dt.default.warn("Unrecognized message type:",t.type,"from peer:",this.peer);break}},e.ID_PREFIX="dc_",e.MAX_BUFFERED_AMOUNT=8388608,e}(LB.BaseConnection),YG={};Kl(YG,"API",()=>ZG,n=>ZG=n);var JG=function(n,e,t,r){function s(o){return o instanceof t?o:new t(function(a){a(o)})}return new(t||(t=Promise))(function(o,a){function l(u){try{h(r.next(u))}catch(p){a(p)}}function c(u){try{h(r.throw(u))}catch(p){a(p)}}function h(u){u.done?o(u.value):s(u.value).then(l,c)}h((r=r.apply(n,e||[])).next())})},KG=function(n,e){var t={label:0,sent:function(){if(o[0]&1)throw o[1];return o[1]},trys:[],ops:[]},r,s,o,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(h){return function(u){return c([h,u])}}function c(h){if(r)throw new TypeError("Generator is already executing.");for(;t;)try{if(r=1,s&&(o=h[0]&2?s.return:h[0]?s.throw||((o=s.return)&&o.call(s),0):s.next)&&!(o=o.call(s,h[1])).done)return o;switch(s=0,o&&(h=[h[0]&2,o.value]),h[0]){case 0:case 1:o=h;break;case 4:return t.label++,{value:h[1],done:!1};case 5:t.label++,s=h[1],h=[0];continue;case 7:h=t.ops.pop(),t.trys.pop();continue;default:if(o=t.trys,!(o=o.length>0&&o[o.length-1])&&(h[0]===6||h[0]===2)){t=0;continue}if(h[0]===3&&(!o||h[1]>o[0]&&h[1]<o[3])){t.label=h[1];break}if(h[0]===6&&t.label<o[1]){t.label=o[1],o=h;break}if(o&&t.label<o[2]){t.label=o[2],t.ops.push(h);break}o[2]&&t.ops.pop(),t.trys.pop();continue}h=e.call(n,t)}catch(u){h=[6,u],s=0}finally{r=o=0}if(h[0]&5)throw h[1];return{value:h[0]?h[1]:void 0,done:!0}}},ZG=function(){function n(e){this._options=e}return n.prototype._buildRequest=function(e){var t=this._options.secure?"https":"http",r=this._options,s=r.host,o=r.port,a=r.path,l=r.key,c=new URL("".concat(t,"://").concat(s,":").concat(o).concat(a).concat(l,"/").concat(e));return c.searchParams.set("ts","".concat(Date.now()).concat(Math.random())),c.searchParams.set("version",kB.version),fetch(c.href,{referrerPolicy:this._options.referrerPolicy})},n.prototype.retrieveId=function(){return JG(this,void 0,Promise,function(){var e,t,r;return KG(this,function(s){switch(s.label){case 0:return s.trys.push([0,2,,3]),[4,this._buildRequest("id")];case 1:if(e=s.sent(),e.status!==200)throw new Error("Error. Status:".concat(e.status));return[2,e.text()];case 2:throw t=s.sent(),dt.default.error("Error retrieving ID",t),r="",this._options.path==="/"&&this._options.host!==wi.CLOUD_HOST&&(r=" 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."+r);case 3:return[2]}})})},n.prototype.listAllPeers=function(){return JG(this,void 0,Promise,function(){var e,t,r;return KG(this,function(s){switch(s.label){case 0:return s.trys.push([0,2,,3]),[4,this._buildRequest("peers")];case 1:if(e=s.sent(),e.status!==200)throw e.status===401?(t="",this._options.host===wi.CLOUD_HOST?t="It looks like you're using the cloud server. You can email team@peerjs.com to enable peer listing for your API key.":t="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. "+t)):new Error("Error. Status:".concat(e.status));return[2,e.json()];case 2:throw r=s.sent(),dt.default.error("Error retrieving list peers",r),new Error("Could not get list peers from the server."+r);case 3:return[2]}})})},n}(),ode=function(){var n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,s){r.__proto__=s}||function(r,s){for(var o in s)Object.prototype.hasOwnProperty.call(s,o)&&(r[o]=s[o])},n(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");n(e,t);function r(){this.constructor=e}e.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}}(),tA=function(){return tA=Object.assign||function(n){for(var e,t=1,r=arguments.length;t<r;t++){e=arguments[t];for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&(n[s]=e[s])}return n},tA.apply(this,arguments)},iA=function(n){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&n[e],r=0;if(t)return t.call(n);if(n&&typeof n.length=="number")return{next:function(){return n&&r>=n.length&&(n=void 0),{value:n&&n[r++],done:!n}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},ade=function(n,e){var t=typeof Symbol=="function"&&n[Symbol.iterator];if(!t)return n;var r=t.call(n),s,o=[],a;try{for(;(e===void 0||e-- >0)&&!(s=r.next()).done;)o.push(s.value)}catch(l){a={error:l}}finally{try{s&&!s.done&&(t=r.return)&&t.call(r)}finally{if(a)throw a.error}}return o},UB=function(n){ode(e,n);function e(t,r){var s=n.call(this)||this;s._id=null,s._lastServerId=null,s._destroyed=!1,s._disconnected=!1,s._open=!1,s._connections=new Map,s._lostMessages=new Map;var o;return t&&t.constructor==Object?r=t:t&&(o=t.toString()),r=tA({debug:0,host:wi.CLOUD_HOST,port:wi.CLOUD_PORT,path:"/",key:e.DEFAULT_KEY,token:wi.randomToken(),config:wi.defaultConfig,referrerPolicy:"strict-origin-when-cross-origin"},r),s._options=r,s._options.host==="/"&&(s._options.host=window.location.hostname),s._options.path&&(s._options.path[0]!=="/"&&(s._options.path="/"+s._options.path),s._options.path[s._options.path.length-1]!=="/"&&(s._options.path+="/")),s._options.secure===void 0&&s._options.host!==wi.CLOUD_HOST?s._options.secure=wi.isSecure():s._options.host==wi.CLOUD_HOST&&(s._options.secure=!0),s._options.logFunction&&dt.default.setLogFunction(s._options.logFunction),dt.default.logLevel=s._options.debug||0,s._api=new YG.API(r),s._socket=s._createServerConnection(),!wi.supports.audioVideo&&!wi.supports.data?(s._delayedAbort(Fn.BrowserIncompatible,"The current browser does not support WebRTC"),s):o&&!wi.validateId(o)?(s._delayedAbort(Fn.InvalidID,'ID "'.concat(o,'" is invalid')),s):(o?s._initialize(o):s._api.retrieveId().then(function(a){return s._initialize(a)}).catch(function(a){return s._abort(Fn.ServerError,a)}),s)}return Object.defineProperty(e.prototype,"id",{get:function(){return this._id},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"options",{get:function(){return this._options},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"open",{get:function(){return this._open},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"socket",{get:function(){return this._socket},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"connections",{get:function(){var t,r,s=Object.create(null);try{for(var o=iA(this._connections),a=o.next();!a.done;a=o.next()){var l=ade(a.value,2),c=l[0],h=l[1];s[c]=h}}catch(u){t={error:u}}finally{try{a&&!a.done&&(r=o.return)&&r.call(o)}finally{if(t)throw t.error}}return s},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"destroyed",{get:function(){return this._destroyed},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"disconnected",{get:function(){return this._disconnected},enumerable:!1,configurable:!0}),e.prototype._createServerConnection=function(){var t=this,r=new jG.Socket(this._options.secure,this._options.host,this._options.port,this._options.path,this._options.key,this._options.pingInterval);return r.on(vh.Message,function(s){t._handleMessage(s)}),r.on(vh.Error,function(s){t._abort(Fn.SocketError,s)}),r.on(vh.Disconnected,function(){t.disconnected||(t.emitError(Fn.Network,"Lost connection to server."),t.disconnect())}),r.on(vh.Close,function(){t.disconnected||t._abort(Fn.SocketClosed,"Underlying socket is already closed.")}),r},e.prototype._initialize=function(t){this._id=t,this.socket.start(t,this._options.token)},e.prototype._handleMessage=function(t){var r,s,o=t.type,a=t.payload,l=t.src;switch(o){case Qr.Open:this._lastServerId=this.id,this._open=!0,this.emit("open",this.id);break;case Qr.Error:this._abort(Fn.ServerError,a.msg);break;case Qr.IdTaken:this._abort(Fn.UnavailableID,'ID "'.concat(this.id,'" is taken'));break;case Qr.InvalidKey:this._abort(Fn.InvalidKey,'API KEY "'.concat(this._options.key,'" is invalid'));break;case Qr.Leave:dt.default.log("Received leave message from ".concat(l)),this._cleanupPeer(l),this._connections.delete(l);break;case Qr.Expire:this.emitError(Fn.PeerUnavailable,"Could not connect to peer ".concat(l));break;case Qr.Offer:var g=a.connectionId,v=this.getConnection(l,g);if(v&&(v.close(),dt.default.warn("Offer received for existing Connection ID:".concat(g))),a.type===pl.Media){var c=new DB.MediaConnection(l,this,{connectionId:g,_payload:a,metadata:a.metadata});v=c,this._addConnection(l,v),this.emit("call",c)}else if(a.type===pl.Data){var h=new FB.DataConnection(l,this,{connectionId:g,_payload:a,metadata:a.metadata,label:a.label,serialization:a.serialization,reliable:a.reliable});v=h,this._addConnection(l,v),this.emit("connection",h)}else{dt.default.warn("Received malformed connection type:".concat(a.type));return}var u=this._getMessages(g);try{for(var p=iA(u),m=p.next();!m.done;m=p.next()){var f=m.value;v.handleMessage(f)}}catch(y){r={error:y}}finally{try{m&&!m.done&&(s=p.return)&&s.call(p)}finally{if(r)throw r.error}}break;default:if(!a){dt.default.warn("You received a malformed message from ".concat(l," of type ").concat(o));return}var g=a.connectionId,v=this.getConnection(l,g);v&&v.peerConnection?v.handleMessage(t):g?this._storeMessage(g,t):dt.default.warn("You received an unrecognized message:",t);break}},e.prototype._storeMessage=function(t,r){this._lostMessages.has(t)||this._lostMessages.set(t,[]),this._lostMessages.get(t).push(r)},e.prototype._getMessages=function(t){var r=this._lostMessages.get(t);return r?(this._lostMessages.delete(t),r):[]},e.prototype.connect=function(t,r){if(r===void 0&&(r={}),this.disconnected){dt.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(Fn.Disconnected,"Cannot connect to new Peer after disconnecting from server.");return}var s=new FB.DataConnection(t,this,r);return this._addConnection(t,s),s},e.prototype.call=function(t,r,s){if(s===void 0&&(s={}),this.disconnected){dt.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(Fn.Disconnected,"Cannot connect to new Peer after disconnecting from server.");return}if(!r){dt.default.error("To call a peer, you must provide a stream from your browser's `getUserMedia`.");return}var o=new DB.MediaConnection(t,this,tA(tA({},s),{_stream:r}));return this._addConnection(t,o),o},e.prototype._addConnection=function(t,r){dt.default.log("add connection ".concat(r.type,":").concat(r.connectionId," to peerId:").concat(t)),this._connections.has(t)||this._connections.set(t,[]),this._connections.get(t).push(r)},e.prototype._removeConnection=function(t){var r=this._connections.get(t.peer);if(r){var s=r.indexOf(t);s!==-1&&r.splice(s,1)}this._lostMessages.delete(t.connectionId)},e.prototype.getConnection=function(t,r){var s,o,a=this._connections.get(t);if(!a)return null;try{for(var l=iA(a),c=l.next();!c.done;c=l.next()){var h=c.value;if(h.connectionId===r)return h}}catch(u){s={error:u}}finally{try{c&&!c.done&&(o=l.return)&&o.call(l)}finally{if(s)throw s.error}}return null},e.prototype._delayedAbort=function(t,r){var s=this;setTimeout(function(){s._abort(t,r)},0)},e.prototype._abort=function(t,r){dt.default.error("Aborting!"),this.emitError(t,r),this._lastServerId?this.disconnect():this.destroy()},e.prototype.emitError=function(t,r){dt.default.error("Error:",r);var s;typeof r=="string"?s=new Error(r):s=r,s.type=t,this.emit("error",s)},e.prototype.destroy=function(){this.destroyed||(dt.default.log("Destroy peer with ID:".concat(this.id)),this.disconnect(),this._cleanup(),this._destroyed=!0,this.emit("close"))},e.prototype._cleanup=function(){var t,r;try{for(var s=iA(this._connections.keys()),o=s.next();!o.done;o=s.next()){var a=o.value;this._cleanupPeer(a),this._connections.delete(a)}}catch(l){t={error:l}}finally{try{o&&!o.done&&(r=s.return)&&r.call(s)}finally{if(t)throw t.error}}this.socket.removeAllListeners()},e.prototype._cleanupPeer=function(t){var r,s,o=this._connections.get(t);if(o)try{for(var a=iA(o),l=a.next();!l.done;l=a.next()){var c=l.value;c.close()}}catch(h){r={error:h}}finally{try{l&&!l.done&&(s=a.return)&&s.call(a)}finally{if(r)throw r.error}}},e.prototype.disconnect=function(){if(!this.disconnected){var t=this.id;dt.default.log("Disconnect peer with ID:".concat(t)),this._disconnected=!0,this._open=!1,this.socket.close(),this._lastServerId=t,this._id=null,this.emit("disconnected",t)}},e.prototype.reconnect=function(){if(this.disconnected&&!this.destroyed)dt.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)dt.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!"))}},e.prototype.listAllPeers=function(t){var r=this;t===void 0&&(t=function(s){}),this._api.listAllPeers().then(function(s){return t(s)}).catch(function(s){return r._abort(Fn.ServerError,s)})},e.DEFAULT_KEY="peerjs",e}($y.EventEmitter),NB=UG.Peer;const lde=Object.freeze(Object.defineProperty({__proto__:null,get Peer(){return UB},default:NB,util:wi},Symbol.toStringTag,{value:"Module"}));let zB;function cde(){return zB}function hde(n){zB=n}function $G(n,e){return e||(e={}),e={...zB,...e},n?new NB(n,e):new NB(e)}async function e8(){const n=await Promise.resolve().then(()=>lde);return console.log(n),n.default===void 0?n:n.default}class t8{constructor(){d(this,"_host"),d(this,"_client"),d(this,"_clientData"),this.onEnable()}get isHost(){return this._host!==void 0}onEnable(){const e="HOST-5980e65c-8438-453e-8b35-f13c736dcd81";this.trySetupHost(e)}async trySetupHost(e){const t=await e8(),r=new t(e);r.on("error",s=>{console.error(s),this._host=void 0,this.trySetupClient(e)}),r.on("open",s=>{this._host=new dde(r)})}async trySetupClient(e){const t=await e8();this._client=new t,this._client.on("error",r=>{console.error("Client error",r)}),this._client.on("open",r=>{console.log("client connected",r),this._clientData=this._client.connect(e,{metadata:{id:r}}),this._clientData.on("open",()=>{console.log("Connected to host")}),this._clientData.on("data",s=>{console.log("<<",s)})})}}class ude{constructor(e){d(this,"_peer"),this._peer=e}}class dde extends ude{constructor(e){var t;super(e),d(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(r=>{var s;return(s=r.metadata)==null?void 0:s.id}).filter(r=>r!==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 r=this._peer.connections[t];if(r)if(Array.isArray(r))for(const s of r)s&&s.send(e);else console.warn(r)}}}}const i8="https://urls.needle.tools/default-networking-backend/index";let Gu="wss://needle-tiny-starter.glitch.me/socket";const Zs=!!te("debugnet"),nA=!!(Zs||te("debugowner")),n8=te("debugnetbin");var r8=(n=>(n.ConnectionInfo="connection-start-info",n))(r8||{}),Vt=(n=>(n.Join="join-room",n.Leave="leave-room",n.JoinedRoom="joined-room",n.LeftRoom="left-room",n.UserJoinedRoom="user-joined-room",n.UserLeftRoom="user-left-room",n.RoomStateSent="room-state-sent",n))(Vt||{});class pde{constructor(){d(this,"room"),d(this,"viewId"),d(this,"allowEditing"),d(this,"inRoom")}}class mde{constructor(){d(this,"room")}}class fde{constructor(){d(this,"userId")}}var s8=(n=>(n.RequestHasOwner="request-has-owner",n.ResponseHasOwner="response-has-owner",n.RequestIsOwner="request-is-owner",n.ResponseIsOwner="response-is-owner",n.RequestOwnership="request-ownership",n.GainedOwnership="gained-ownership",n.RemoveOwnership="remove-ownership",n.LostOwnership="lost-ownership",n.GainedOwnershipBroadcast="gained-ownership-broadcast",n.LostOwnershipBroadcast="lost-ownership-broadcast",n))(s8||{});class jB{constructor(e,t){d(this,"guid"),d(this,"connection"),d(this,"_hasOwnership",!1),d(this,"_isOwned"),d(this,"_gainSubscription"),d(this,"_lostSubscription"),d(this,"_hasOwnerResponse"),d(this,"_isWaitingForOwnershipResponseCallback",null),this.connection=e,this.guid=t,this._gainSubscription=this.onGainedOwnership.bind(this),this._lostSubscription=this.onLostOwnership.bind(this),e.beginListen("lost-ownership",this._lostSubscription),e.beginListen("gained-ownership-broadcast",this._gainSubscription),this._hasOwnerResponse=this.onHasOwnerResponse.bind(this),e.beginListen("response-has-owner",this._hasOwnerResponse)}get hasOwnership(){return this._hasOwnership}get isOwned(){return this._isOwned}get isConnected(){return this.connection.isConnected}updateIsOwned(){this.connection.send("request-has-owner",{guid:this.guid})}onHasOwnerResponse(e){e.guid===this.guid&&(this._isOwned=e.value)}requestOwnershipIfNotOwned(){return this._isWaitingForOwnershipResponseCallback!==null?this:(this._isWaitingForOwnershipResponseCallback=this.waitForHasOwnershipRequestResponse.bind(this),this.connection.beginListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this.connection.send("request-has-owner",{guid:this.guid}),this)}waitForHasOwnershipRequestResponse(e){e.guid===this.guid&&(this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this._isOwned=e.value,e.value||(nA&&console.log("request ownership",this.guid),this.requestOwnership()))}requestOwnershipAsync(){return new Promise((e,t)=>{this.requestOwnership();let r=0;const s=()=>{if(r++>10)return t("Timeout");setTimeout(()=>{this.hasOwnership?e(this):s()},100)};s()})}requestOwnership(){return nA&&console.log("Request ownership",this.guid),this.connection.send("request-ownership",{guid:this.guid}),this}freeOwnership(){return this.connection.send("remove-ownership",{guid:this.guid}),this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this}destroy(){this.connection.stopListen("gained-ownership",this._gainSubscription),this.connection.stopListen("lost-ownership",this._lostSubscription),this.connection.stopListen("response-has-owner",this._hasOwnerResponse),this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null)}onGainedOwnership(e){e.guid===this.guid&&(this._isOwned=!0,this.connection.connectionId===e.owner?(nA&&console.log("GAINED OWNERSHIP",this.guid),this._hasOwnership=!0):this._hasOwnership=!1)}onLostOwnership(e){e===this.guid&&(nA&&console.log("LOST OWNERSHIP",this.guid),this._hasOwnership=!1,this._isOwned=!1)}}class o8{constructor(e){d(this,"context"),d(this,"_peer",null),d(this,"_usersInRoomCopy",[]),d(this,"_defaultMessagesBuffer",[]),d(this,"_defaultMessagesBufferArray",[]),d(this,"netWebSocketUrlProvider"),d(this,"_listeners",{}),d(this,"_listenersBinary",{}),d(this,"connected",!1),d(this,"channelId"),d(this,"_connectionId",null),d(this,"_ws"),d(this,"_waitingForSocket",{}),d(this,"_isInRoom",!1),d(this,"_currentRoomName",null),d(this,"_currentRoomViewId",null),d(this,"_currentRoomAllowEditing",!0),d(this,"_currentInRoom",[]),d(this,"_state",{}),d(this,"_currentDelay",-1),d(this,"_connectingToWebsocketPromise",null),this.context=e}get peer(){return this._peer||(this._peer=new t8),this._peer}tryGetState(e){return e==="invalid"?null:this._state[e]}get connectionId(){return this._connectionId}get isDebugEnabled(){return Zs}get isConnected(){return this.connected}get currentRoomName(){return this._currentRoomName}get allowEditing(){return this._currentRoomAllowEditing}get currentRoomViewId(){return this._currentRoomViewId}getViewOnlyUrl(){if(this.currentRoomViewId===null)return null;const e=new URL(window.location.href);return e.searchParams.set("view",this.currentRoomViewId),e.href}get isInRoom(){return this._isInRoom}get currentLatency(){return this._currentDelay}get currentServerUrl(){var e;return((e=this._ws)==null?void 0:e.url)??null}sendPing(){this.send("ping",{time:this.context.time.time})}userIsInRoom(e){return this._currentInRoom.indexOf(e)!==-1}usersInRoom(e=null){e||(e=this._usersInRoomCopy),e.length=0;for(const t of this._currentInRoom)e.push(t);return e}joinRoom(e,t=!1){return e?e.length>1024?(console.error('Room name too long, can not join: "'+e+'". Max length is 1024 characters.'),!1):(this.connect(),Zs&&console.log("join: "+e),this.send("join-room",{room:e,viewOnly:t},dl.OnConnection),!0):(console.error('Missing room name, can not join: "'+e+'"'),!1)}leaveRoom(e=null){return e||(e=this.currentRoomName),e?(this.send("leave-room",{room:e}),!0):(console.error('Missing room name, can not join: "'+e+'"'),!1)}send(e,t=null,r=dl.Queued){if(t===null&&(t={}),r===dl.Queued){this._defaultMessagesBuffer.push({key:e,value:t});return}return this.sendWithWebsocket(e,t,r)}sendDeleteRemoteState(e){this.send("delete-state",{guid:e,dontSave:!0}),delete this._state[e]}sendDeleteRemoteStateAll(){this.send("delete-all-state"),this._state={}}sendBinary(e){var t;n8&&console.log("<< send binary",this.context.time.frame,e.length/1024+" KB"),(t=this._ws)==null||t.send(e)}sendBufferedMessagesNow(){var e;if(!this._ws)return;this._defaultMessagesBufferArray.length=0;const t=Object.keys(this._defaultMessagesBuffer).length;for(const s in this._defaultMessagesBuffer){const o=this._defaultMessagesBuffer[s];if(t<=1){this.sendWithWebsocket(o.key,o.value,dl.Immediate);break}const a=this.toMessage(o.key,o.value);this._defaultMessagesBufferArray.push(a)}if(this._defaultMessagesBuffer.length=0,this._defaultMessagesBufferArray.length>0&&Zs&&console.log("SEND BUFFERED",this._defaultMessagesBufferArray.length),this._defaultMessagesBufferArray.length<=0)return;const r=JSON.stringify(this._defaultMessagesBufferArray);(e=this._ws)==null||e.send(r)}beginListen(e,t){return this._listeners[e]||(this._listeners[e]=[]),this._listeners[e].push(t),t}stopListening(e,t){return this.stopListen(e,t)}stopListen(e,t){if(!t||!this._listeners[e])return;const r=this._listeners[e].indexOf(t);r>=0&&this._listeners[e].splice(r,1)}beginListenBinary(e,t){return this._listenersBinary[e]||(this._listenersBinary[e]=[]),this._listenersBinary[e].push(t),t}stopListenBinary(e,t){if(!this._listenersBinary[e])return;const r=this._listenersBinary[e].indexOf(t);r>=0&&this._listenersBinary[e].splice(r,1)}registerProvider(e){this.netWebSocketUrlProvider=e}async connect(){var e;if(this.connected)return Promise.resolve(!0);Zs&&console.log("connecting");const t=(e=this.netWebSocketUrlProvider)==null?void 0:e.getWebsocketUrl();return t?Gu=t:kU()&&(Gu="wss://"+window.location.host+"/socket"),this.connectWebsocket()}disconnect(){var e;(e=this._ws)==null||e.close(),this._ws=void 0}connectWebsocket(){return this._connectingToWebsocketPromise?this._connectingToWebsocketPromise:this._connectingToWebsocketPromise=new Promise(async(e,t)=>{var r,s;let o=!1;const a=p=>{o||(o=!0,e(p))};if(Gu===void 0&&(console.log("Fetch default backend url: "+i8),Gu=await(await fetch(i8)).text()),Gu===void 0){a(!1);return}console.log(`\u22A1 Connecting to networking backend on
5233
5233
  `+Gu);const l=await Promise.resolve().then(()=>K_e),c=((r=l.default)==null?void 0:r.WebsocketBuilder)??l.WebsocketBuilder,h=((s=l.default)==null?void 0:s.ExponentialBackoff)??l.ExponentialBackoff,u=new c(Gu).withMaxRetries(3).withBackoff(new h(2e3,2)).onOpen(()=>{this._connectingToWebsocketPromise=null,this._ws=u,this.connected=!0,console.log(`\u229E Connected to networking backend
5234
5234
  `+Gu),a(!0),this.onSendQueued(dl.OnConnection)}).onClose(p=>{this._connectingToWebsocketPromise=null,this.connected=!1,this._isInRoom=!1,a(!1)}).onError(p=>{console.error("\u22A0 Websocket error"),a(!1)}).onRetry(()=>{console.log("Retry connecting to networking websocket")}).build();u.addEventListener(l.WebsocketEvent.message,(p,m)=>{this.onMessage(p,m)})})}onMessage(e,t){const r=t.data;try{if(typeof r!="string"){r.size&&this.handleIncomingBinaryMessage(r);return}const s=JSON.parse(r);if(Array.isArray(s))for(const o of s)this.handleIncomingStringMessage(o);else this.handleIncomingStringMessage(s);return}catch(s){Zs&&r==="pong"?console.log("<<",r):st()&&console.error("Failed to parse message",s)}}async handleIncomingBinaryMessage(e){n8&&console.log("<< bin",this.context.time.frame);const t=await e.arrayBuffer();var r=new Uint8Array(t);const s=new r_(r),o=s.getBufferIdentifier(),a=this._listenersBinary[o],l=N6(s),c=z6(l);if(c&&typeof c=="string"&&(this._state[c]=l),!a)return;const h=l??s;for(const u of a)u(h)}handleIncomingStringMessage(e){var t,r;if(Zs&&console.log("<<",e.key??e),e.key)switch(e.key){case"connection-start-info":if(e.data){const l=e.data;l&&(console.assert(l.id!==void 0&&l.id!==null&&l.id.length>0,"server did not send connection id",l.id),console.log("Your id is: "+l.id,this.context.alias??""),this._connectionId=l.id)}else console.warn("Expected connection id in "+e.key);break;case"joined-room":if(Zs&&console.log(e),e){this._isInRoom=!0;const l=e;this._currentRoomName=l.room,this._currentRoomViewId=l.viewId,this._currentRoomAllowEditing=l.allowEditing??!0,this._currentInRoom.length=0,this._currentInRoom.push(...l.inRoom),Zs&&console.log("joined room with",this._currentInRoom,this.context.alias??"");const c=new URL(window.location.href);c.searchParams.has("room")&&c.searchParams.delete("room"),c.searchParams.set("view",this._currentRoomViewId),console.log("Room view id: "+this._currentRoomViewId+`
5235
- `+c.href)}this.onSendQueued(dl.OnRoomJoin);break;case"left-room":e.room===this.currentRoomName&&(this._isInRoom=!1,this._currentRoomName=null,this._currentInRoom.length=0);break;case"user-joined-room":if(e.data){const l=e.data;this._currentInRoom.push(l.userId),Zs&&console.log(l.userId+" joined","now in room:",this._currentInRoom)}break;case"user-left-room":if(e.data){const l=e.data,c=this._currentInRoom.indexOf(l.userId);c>=0&&(Zs&&console.log(l.userId+" left","now in room:",this._currentInRoom),this._currentInRoom.splice(c,1)),l.userId===this.connectionId&&console.log("you left the room")}break;case"all-room-state-deleted":Zs&&console.log("RECEIVED all-room-state-deleted"),this._state={};break;case"ping":case"pong":const a=(t=e.data)==null?void 0:t.time;a&&(this._currentDelay=this.context.time.time-a),Zs&&console.log("Current latency: "+this._currentDelay.toFixed(4)+" sec","Clients in room: "+((r=this._currentInRoom)==null?void 0:r.length));break}const s=e.data;s&&(this._state[s.guid]=s);let o=this._listeners[e.key];if(o){o=[...o];for(const a of o)try{a(e.data)}catch(l){console.error('Error invoking callback for "'+e.key+'"',l)}}}toMessage(e,t){return{key:e,data:t}}sendWithWebsocket(e,t,r=dl.OnRoomJoin){if(!this._ws){const o=this._waitingForSocket[r]||[];o.push(()=>this.sendWithWebsocket(e,t,r)),this._waitingForSocket[r]=o;return}const s=JSON.stringify(this.toMessage(e,t));Zs&&console.log(">>",e),this._ws.send(s)}onSendQueued(e){const t=this._waitingForSocket[e];if(t){for(const r of t)r();t.length=0}}}const rA=te("debugwebxr");class GB{constructor(e,t){d(this,"controllerStates",[]),d(this,"userId"),d(this,"context"),d(this,"userStateEvtName"),d(this,"onReceivedControllerState",r=>{rA&&console.log(`XRSync: Received change for ${this.userId}: ${r.type} ${r.handedness}; tracked=${r.isTracking}`);let s=!1;for(let o=0;o<this.controllerStates.length;o++)if(this.controllerStates[o].index===r.index){this.controllerStates[o]=r,s=!0;break}s||this.controllerStates.push(r)}),this.userId=e,this.context=t,this.userStateEvtName="xr-sync-user-state-"+e,this.context.connection.beginListen(this.userStateEvtName,this.onReceivedControllerState)}dispose(){this.context.connection.stopListen(this.userStateEvtName,this.onReceivedControllerState)}update(e){if(this.context.connection.isConnected!=!1){for(let t=this.controllerStates.length-1;t>=0;t--){const r=this.controllerStates[t];let s=!1;for(let o=0;o<e.controllers.length;o++)e.controllers[o].index===r.index&&(s=!0);s||(rA&&console.log(`XRSync: ${r.type} ${r.handedness} removed`,r.index),this.controllerStates.splice(t,1),this.sendControllerRemoved(r))}for(const t of e.controllers)this.updateControllerStates(t)}}onExitXR(e){for(const t of this.controllerStates)this.sendControllerRemoved(t);this.controllerStates.length=0}sendControllerRemoved(e){e.isTracking=!1,e.guid="",this.context.connection.send(this.userStateEvtName,e),this.context.connection.sendDeleteRemoteState(e.guid)}updateControllerStates(e){const t=this.controllerStates.find(r=>r.index===e.index);if(t){let r=!1;r||(r=t.isTracking!=e.isTracking),r&&(t.isTracking=e.isTracking,this.context.connection.send(this.userStateEvtName,t))}else{const r={guid:this.userId+"-"+e.index,isTracking:e.isTracking,handedness:e.side,index:e.index,type:e.hand?"hand":"controller"};this.controllerStates.push(r),this.context.connection.send(this.userStateEvtName,r),rA&&console.log(`XRSync: ${r.type} ${r.handedness} added`,r.index)}}}class a8{constructor(e){d(this,"context"),d(this,"onJoinedRoom",()=>{if(this.context.connection.connectionId){this._states.has(this.context.connection.connectionId)||(rA&&console.log("XRSync: Local user joined room",this.context.connection.connectionId),this._states.set(this.context.connection.connectionId,new GB(this.context.connection.connectionId,this.context)));for(const t of this.context.connection.usersInRoom())this._states.has(t)||this._states.set(t,new GB(t,this.context))}}),d(this,"onLeftRoom",()=>{if(this.context.connection.connectionId&&!this._states.has(this.context.connection.connectionId)){const t=this._states.get(this.context.connection.connectionId);t?.dispose(),this._states.delete(this.context.connection.connectionId)}}),d(this,"onOtherUserJoinedRoom",t=>{const r=t.userId;this._states.has(r)||(rA&&console.log("XRSync: Remote user joined room",r),this._states.set(r,new GB(r,this.context)))}),d(this,"onOtherUserLeftRoom",t=>{const r=t.userId;if(!this._states.has(r)){const s=this._states.get(r);s?.dispose(),this._states.delete(r)}}),d(this,"_states",new Map),this.context=e,this.context.connection.beginListen(Vt.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(Vt.LeftRoom,this.onLeftRoom),this.context.connection.beginListen(Vt.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.beginListen(Vt.UserLeftRoom,this.onOtherUserLeftRoom)}hasState(e){return e?this._states.has(e):!1}isTracking(e,t){if(!e)return;const r=this._states.get(e);if(!r)return;const s=r.controllerStates.find(o=>o.handedness===t);return s?.isTracking||!1}getDeviceType(e,t){if(!e)return;const r=this._states.get(e);if(!r)return;const s=r.controllerStates.find(o=>o.handedness===t);return s?.type||"unknown"}destroy(){this.context.connection.stopListen(Vt.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(Vt.LeftRoom,this.onLeftRoom),this.context.connection.stopListen(Vt.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.stopListen(Vt.UserLeftRoom,this.onOtherUserLeftRoom)}onUpdate(e){if(this.context.connection.isConnected&&this.context.connection.connectionId){const t=this._states.get(this.context.connection.connectionId);t?.update(e)}}onExitXR(e){if(this.context.connection.isConnected&&this.context.connection.connectionId){const t=this._states.get(this.context.connection.connectionId);t?.onExitXR(e)}}}class l8{constructor(){d(this,"_fadeToColorQuad"),d(this,"_fadeToColorMaterial"),d(this,"_requestedFadeValue",0),d(this,"_transitionPromise",null),d(this,"_transitionResolve",null),this._fadeToColorMaterial=new $t({color:0,transparent:!0,depthTest:!1,fog:!1,side:yi}),this._fadeToColorQuad=new me(new tr(10,10),this._fadeToColorMaterial)}dispose(){this._fadeToColorQuad.geometry.dispose(),this._fadeToColorMaterial.dispose()}update(e,t){const r=this._fadeToColorQuad,s=this._fadeToColorMaterial;r.parent!==e&&s.opacity>0?e.add(r):s.opacity===0&&r.removeFromParent(),r.layers.set(2),r.material=this._fadeToColorMaterial,r.position.z=-1,r.renderOrder=1/0;const o=this._requestedFadeValue;s.opacity=it.lerp(s.opacity,o,t/.03),Math.abs(s.opacity-o)<=.01&&this._transitionResolve&&(this._transitionResolve(),this._transitionResolve=null,this._transitionPromise=null,this._requestedFadeValue=0)}remove(){this._fadeToColorQuad.removeFromParent()}fadeTransition(){if(this._transitionPromise)return this._transitionPromise;this._requestedFadeValue=1;const e=new Promise(t=>{this._transitionResolve=t});return this._transitionPromise=e,e}}var Yp=(n=>(n[n.Quad=0]="Quad",n[n.Cube=1]="Cube",n[n.Sphere=2]="Sphere",n))(Yp||{});class sA{static createPrimitive(e,t){let r;switch(e){case"Quad":case 0:{const s=new tr(1,1,1,1),o=t?.material??new vs({color:16777215});t!=null&&t.texture&&"map"in o&&(o.map=t.texture),r=new me(s,o)}break;case"Cube":case 1:{const s=new qi(1,1,1),o=t?.material??new vs({color:16777215});t!=null&&t.texture&&"map"in o&&(o.map=t.texture),r=new me(s,o)}break;case"Sphere":case 2:{const s=new ja(.5,16,16),o=t?.material??new vs({color:16777215});t!=null&&t.texture&&"map"in o&&(o.map=t.texture),r=new me(s,o)}break}return this.applyDefaultObjectOptions(r,t),r}static createSprite(e){const t=new lx({color:16777215});e!=null&&e.texture&&"map"in t&&(t.map=e.texture);const r=new OT(t);return this.applyDefaultObjectOptions(r,e),r}static applyDefaultObjectOptions(e,t){t!=null&&t.name&&(e.name=t.name),t!=null&&t.position&&e.position.set(t.position.x,t.position.y,t.position.z),t!=null&&t.rotation&&e.rotation.set(t.rotation.x,t.rotation.y,t.rotation.z),t!=null&&t.scale&&e.scale.set(t.scale.x,t.scale.y,t.scale.z)}}const c8=class{constructor(n,e,t){d(this,"_session"),d(this,"_mode"),d(this,"_init"),d(this,"_renderer"),d(this,"_camera"),d(this,"_scene"),d(this,"onEnd",()=>{var r;(r=this._session)==null||r.removeEventListener("end",this.onEnd),this._renderer.setAnimationLoop(null),this._renderer.dispose(),this._scene.clear()}),d(this,"_lastTime",0),d(this,"onFrame",(r,s)=>{const o=r-this._lastTime;this.update(r,o),this._camera.parent!==this._scene&&this._scene.add(this._camera),this._renderer.render(this._scene,this._camera)}),d(this,"_objects",[]),this._mode=n,this._init=e,this._session=t,this._session.addEventListener("end",this.onEnd),this._renderer=new Wc({alpha:!0}),this._renderer.setAnimationLoop(this.onFrame),this._renderer.xr.setSession(t),this._renderer.xr.enabled=!0,this._camera=new Lt,this._scene=new Ur,this._scene.fog=new ax(4473924,10,250),this._scene.add(this._camera),this.setupScene()}static get active(){return this._active}static async start(n,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(n,e);return t.addEventListener("end",()=>{this._active=null}),this._requestInFlight?(this._requestInFlight=!1,this._active=new c8(n,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 Ll(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 n={session:this._session,mode:this._mode,init:this._init};return await this.onBeforeHandoff(),this.onEnd(),this._session=null,n}async onBeforeHandoff(){await Ll(1e3),this._scene.clear()}setupScene(){this._scene.background=new xe(0),this._scene.add(new Hx(5,10,1118481,1118481));const n=new lp(16777215,1);n.position.set(0,20,0),n.castShadow=!1,this._scene.add(n);const e=new lp(16777215,1);e.position.set(0,-1,0),e.castShadow=!1,this._scene.add(e);const t=new ap(16777215,1,100,1);t.position.set(0,2,0),t.castShadow=!1,t.distance=200,this._scene.add(t);const r=50;for(let s=0;s<100;s++){const o=new vs({color:2236962,metalness:1,roughness:.8});this.isAR&&(o.emissive=new xe(Math.random(),Math.random(),Math.random()),o.emissiveIntensity=Math.random());const a=it.random(0,1)>.5?Yp.Sphere:Yp.Cube,l=sA.createPrimitive(a,{material:o});l.position.x=it.random(-r,r),l.position.y=it.random(-2,r),l.position.z=it.random(-r,r),l.rotation.x=it.random(0,Math.PI*2),l.rotation.y=it.random(0,Math.PI*2),l.rotation.z=it.random(0,Math.PI*2),l.scale.multiplyScalar(.5+Math.random()*10);const c=l.position.distanceTo(this._camera.position)-l.scale.x;c<1&&l.position.multiplyScalar(1+1/c),this._objects.push(l),this._scene.add(l)}}update(n,e){const t=n*4e-4;for(let r=0;r<this._objects.length;r++){const s=this._objects[r];s.position.y+=Math.sin(t+r*.5)*.005,s.rotateY(.002)}}};let Lg=c8;d(Lg,"_active",null),d(Lg,"_requestInFlight",!1);const Sr=te("debugwebxr"),gde=te("stats");function vde(n){let e=null;const t=n;return t.getAROverlayContainer?e=t.getAROverlayContainer():e=n,e}yde();async function yde(){var n;if(te("debugasap")){let e=globalThis["needle:XRSession"];if(e instanceof Promise){delete globalThis["needle:XRSession"],di.addContextCreatedCallback(async t=>{if(!e)return;Nf(!0);const r=await e;if(r){const s=wt.getDefaultSessionInit("immersive-vr");wt.setSession("immersive-vr",r,s,t.context)}else console.error("NeedleXRSession: ASAP session was rejected");e=void 0});return}}if("xr"in navigator){if(/WebXRViewer\//i.test(navigator.userAgent)){console.warn("WebXRViewer does not support addEventListener");return}(n=navigator.xr)==null||n.addEventListener("sessiongranted",async()=>{Nf(!0),console.log("Received Session Granted..."),await Ll(100);const e=sessionStorage.getItem("needle_xr_session_mode"),t=sessionStorage.getItem("needle_xr_session_init")??null,r=t?JSON.parse(t):null;let s=null;if(h8()&&(await Lg.start(e||"immersive-vr",r||wt.getDefaultSessionInit("immersive-vr")),await _de(),s=await Lg.handoff()),s)wt.setSession(s.mode,s.session,s.init,kt.Current);else if(e&&t){console.log("Session Granted: Restore last session");const o=JSON.parse(t);wt.start(e,o).catch(a=>console.warn(a))}else wt.start("immersive-vr").catch(o=>console.warn("Session Granted failed:",o))},{once:!0})}}function Ade(n,e){sessionStorage.setItem("needle_xr_session_mode",n),sessionStorage.setItem("needle_xr_session_init",JSON.stringify(e))}function bde(){sessionStorage.removeItem("needle_xr_session_mode"),sessionStorage.removeItem("needle_xr_session_init")}const VB=new Set;di.registerCallback(Ci.ContextCreationStart,async n=>{VB.add(n.context)}),di.registerCallback(Ci.ContextCreated,async n=>{VB.delete(n.context)});function h8(){return VB.size>0}function _de(){return new Promise(n=>{const e=Date.now(),t=setInterval(()=>{(!h8()||Date.now()-e>6e4)&&(clearInterval(t),n())},100)})}fp()&&st()&&window.addEventListener("keydown",n=>{(n.key==="x"||n.key==="Escape")&&wt.active&&wt.stop()});const Vu=class{constructor(n,e,t,r){d(this,"context"),d(this,"session"),d(this,"mode"),d(this,"controllers",[]),d(this,"_rigScale",1),d(this,"_lastRigScaleUpdate",-1),d(this,"_rigs",[]),d(this,"_viewerHitTestSource",null),d(this,"_defaultRig"),d(this,"_xr_scripts"),d(this,"_xr_update_scripts",[]),d(this,"_inactive_scripts",[]),d(this,"_controllerAdded"),d(this,"_controllerRemoved"),d(this,"_originalCameraWorldPosition"),d(this,"_originalCameraWorldRotation"),d(this,"_originalCameraWorldScale"),d(this,"_originalCameraParent"),d(this,"_mainCamera",null),d(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())}),d(this,"onInputSourceAdded",a=>{if(a.targetRayMode==="screen")return;let l=0;for(let h=0;h<this.session.inputSources.length;h++)if(this.session.inputSources[h]===a){l=h;break}if(this.controllers.find(h=>h.inputSource===a)){console.warn("Controller already exists for input source",l);return}Sr&&console.log("Adding controller",l);const c=new vB(this,a,l);this._newControllers.push(c)}),d(this,"_ended",!1),d(this,"_newControllers",[]),d(this,"onEnd",a=>{var l,c,h;if(this._ended)return;this._ended=!0,Sr&&console.log("XR Session ended"),bde(),this.onAfterRender(),this.revertCustomForward(),this._didStart=!1,this._previousCameraParent=null,zu(this.onBefore,Hi.LateUpdate);const u=this.context.pre_render_callbacks.indexOf(this.onBeforeRender);u>=0&&this.context.pre_render_callbacks.splice(u,1);const p=this.context.post_render_callbacks.indexOf(this.onAfterRender);p>=0&&this.context.post_render_callbacks.splice(p,1),this.context.xr=null,this.context.renderer.xr.enabled=!1,this.context.pre_update_oneshot_callbacks.push(()=>{var m;(m=this.context.mainCameraComponent)==null||m.applyClearFlags()}),R6({session:this});for(const m of Vu._xrEndListeners)m({xr:this});for(let m=0;m<this.controllers.length;m++)this.disconnectInputSource(this.controllers[m].inputSource);for(const m of this._xr_scripts)(l=m?.onLeaveXR)==null||l.call(m,{xr:this});(c=this.sync)==null||c.onExitXR(this),this.context.mainCamera&&((h=this._originalCameraParent)==null||h.add(this.context.mainCamera),this._originalCameraWorldPosition&&lr(this.context.mainCamera,this._originalCameraWorldPosition),this._originalCameraWorldRotation&&ca(this.context.mainCamera,this._originalCameraWorldRotation),this._originalCameraWorldScale&&Uf(this.context.mainCamera,this._originalCameraWorldScale)),this.context.requestSizeUpdate(),this._defaultRig.gameObject.removeFromParent(),Nf(!1)}),d(this,"_didStart",!1),d(this,"onBefore",a=>{var l,c,h,u,p,m,f,g;const v=a.xrFrame;if(!v)return;this.context.xr=this,this.context.mainCameraComponent&&this.context.mainCameraComponent!==this._mainCamera&&(this._mainCamera=this.context.mainCameraComponent),((l=this.rig)==null?void 0:l.isActive)==!1&&(Sr&&console.warn("Latest rig is not active - trying to activate a different rig",this.rig),this.updateActiveXRRig()),this.rig&&(c=this._mainCamera)!=null&&c.gameObject&&((u=(h=this._mainCamera)==null?void 0:h.gameObject)==null?void 0:u.parent)!==this.rig.gameObject&&this.rig.gameObject.add((p=this._mainCamera)==null?void 0:p.gameObject),this.internalUpdateState(),this.applyCustomForward();const y={xr:this};if(this._didStart){if(this.context.new_scripts_xr.length>0){const A=[...this.context.new_scripts_xr];for(let _=0;_<A.length;_++){const b=this.context.new_scripts_xr[_];if(!b||b.destroyed||((m=b.supportsXR)==null?void 0:m.call(b,this.mode))==!1){this.context.new_scripts_xr.splice(_,1);continue}if(!b.activeAndEnabled){this.context.new_scripts_xr.splice(_,1),this.markInactive(b);continue}if(this.addScript(b)){this.invokeCallback_EnterXR(b);for(const x of this.controllers)this.invokeCallback_ControllerAdded(b,x)}}}}else{if(this._didStart=!0,this.mode==="immersive-vr"){const _=Ul(this.context.scene.children);if(_){const b=_.getSize(pi());if(b.length()>0){const x=this._defaultRig.gameObject;x.position.set(_.min.x+b.x*.5,_.min.y,_.max.z+b.z*.5+1.5);const E=_.getCenter(pi());E.y=x.position.y,x.lookAt(E)}}}I6({session:this});for(const _ of Vu._xrStartListeners)_(y);const A=[...this._xr_scripts];Sr&&console.log("NeedleXRSession start, handle scripts:",A);for(const _ of A){if(_.destroyed){this._script_to_remove.push(_);continue}if(!_.activeAndEnabled){this.markInactive(_);continue}this.invokeCallback_EnterXR(_);for(const b of this.controllers)this.invokeCallback_ControllerAdded(_,b)}}this.syncCameraCullingMask();for(const A of this.controllers)A.onUpdate(v);if(this._newControllers.length>0){const A=[...this._newControllers];this._newControllers.length=0;for(const _ of A)if(_.connected){this.controllers.push(_);for(const b of this._xr_scripts){if(b.destroyed){this._script_to_remove.push(b);continue}b.activeAndEnabled!==!1&&this.invokeCallback_ControllerAdded(b,_)}}this.controllers.sort((_,b)=>_.index-b.index)}for(const A of this._xr_update_scripts){if(A.destroyed===!0){this._script_to_remove.push(A);continue}if(A.activeAndEnabled===!1){this.markInactive(A);continue}A.onUpdateXR&&A.onUpdateXR(y)}if(this.handleInactiveScripts(),this._script_to_remove.length>0){const A=[...new Set(this._script_to_remove)];this._script_to_remove.length=0;for(const _ of A)!_.destroyed&&this.running&&((f=_.onLeaveXR)==null||f.call(_,y)),this.removeScript(_)}(g=this.sync)==null||g.onUpdate(this),this.onRenderDebug()}),d(this,"onBeforeRender",()=>{this.context.mainCamera&&this.updateFade(this.context.mainCamera)}),d(this,"onAfterRender",()=>{if(this.onUpdateFade_PostRender(),fp()){const a=this.context.renderer;if(a.xr.isPresenting&&this.context.mainCamera){const l=a.xr.enabled,c=a.getRenderTarget();a.xr.enabled=!1,a.setRenderTarget(null),a.render(this.context.scene,this.context.mainCamera),a.xr.enabled=l,a.setRenderTarget(c)}}}),d(this,"_script_to_remove",[]),d(this,"_camera"),d(this,"_cameraRenderParent",new ye().rotateY(Math.PI)),d(this,"_previousCameraParent"),d(this,"_customforward",!0),d(this,"originalCameraNearPlane"),d(this,"_viewerPose"),d(this,"_transformOrientation",new Ce),d(this,"_transformPosition",new C),d(this,"_transition");var s,o;Ade(n,r.init),this.session=e,this.mode=n,this.context=t,(Sr||te("console"))&&Nf(!0),this._xr_scripts=[...r.scripts],this._xr_update_scripts=this._xr_scripts.filter(a=>typeof a.onUpdateXR=="function"),this._controllerAdded=r.controller_added,this._controllerRemoved=r.controller_removed,Nu(this.onBefore,Hi.LateUpdate),this.context.pre_render_callbacks.push(this.onBeforeRender),this.context.post_render_callbacks.push(this.onAfterRender),((s=r.init.optionalFeatures)!=null&&s.includes("hit-test")||(o=r.init.requiredFeatures)!=null&&o.includes("hit-test"))&&e.requestReferenceSpace("viewer").then(a=>{var l,c;return(c=(l=e.requestHitTestSource)==null?void 0:l.call(e,{space:a}))==null?void 0:c.then(h=>this._viewerHitTestSource=h)}).catch(a=>console.warn(a)),this.context.mainCamera&&(this._originalCameraWorldPosition=Bt(this.context.mainCamera,new C),this._originalCameraWorldRotation=Mi(this.context.mainCamera,new Ce),this._originalCameraWorldScale=Vi(this.context.mainCamera,new C),this._originalCameraParent=this.context.mainCamera.parent),this._defaultRig=new Sue,this.context.scene.add(this._defaultRig.gameObject),this.addRig(this._defaultRig);for(let a=0;a<e.inputSources.length;a++){const l=e.inputSources[a];if(!l.handedness){console.warn("Input source in xr session has no handedness - ignoring",a);continue}this.onInputSourceAdded(l)}this.session.addEventListener("end",this.onEnd),this.session.addEventListener("inputsourceschange",a=>{for(const l of a.removed)this.disconnectInputSource(l);for(const l of a.added)this.onInputSourceAdded(l)}),this.context.xr=this,this.context.renderer.xr.setSession(this.session).then(this.onRendererSessionSet)}static getXRSync(n){return this._sync||(this._sync=new a8(n)),this._sync}static get currentSessionRequest(){return this._currentSessionRequestMode}static get active(){return this._activeSession}static get activeMode(){var n;return((n=this._activeSession)==null?void 0:n.mode)??null}static get xrSystem(){return"xr"in navigator?navigator.xr:void 0}static isXRSupported(){return Promise.all([this.isVRSupported(),this.isARSupported()]).then(n=>n.some(e=>e)).catch(()=>!1)}static isVRSupported(){return this.isSessionSupported("immersive-vr")}static isARSupported(){return this.isSessionSupported("immersive-ar")}static isSessionSupported(n){var e;return((e=this.xrSystem)==null?void 0:e.isSessionSupported(n).catch(t=>(Sr&&console.error(t),!1)))??Promise.resolve(!1)}static onSessionRequestStart(n){this._sessionRequestStartListeners.push(n)}static offSessionRequestStart(n){const e=this._sessionRequestStartListeners.indexOf(n);e>=0&&this._sessionRequestStartListeners.splice(e,1)}static onSessionRequestEnd(n){this._sessionRequestEndListeners.push(n)}static offSessionRequestEnd(n){const e=this._sessionRequestEndListeners.indexOf(n);e>=0&&this._sessionRequestEndListeners.splice(e,1)}static onXRSessionStart(n){this._xrStartListeners.push(n)}static offXRSessionStart(n){const e=this._xrStartListeners.indexOf(n);e>=0&&this._xrStartListeners.splice(e,1)}static onXRSessionEnd(n){this._xrEndListeners.push(n)}static offXRSessionEnd(n){const e=this._xrEndListeners.indexOf(n);e>=0&&this._xrEndListeners.splice(e,1)}static onControllerAdded(n){this._controllerAddedListeners.push(n)}static offControllerAdded(n){const e=this._controllerAddedListeners.indexOf(n);e>=0&&this._controllerAddedListeners.splice(e,1)}static onControllerRemoved(n){this._controllerRemovedListeners.push(n)}static offControllerRemoved(n){const e=this._controllerRemovedListeners.indexOf(n);e>=0&&this._controllerRemovedListeners.splice(e,1)}static offerSession(n,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: "+n),e=="default"&&(e=this.getDefaultSessionInit(n)),navigator.xr.offerSession(n,{...e}).then(r=>Vu.setSession(n,r,e,t)).catch(r=>{console.log("XRSession offer rejected (perhaps because another call to offerSession was made or a call to requestSession was made)")})),!0):!1}static getDefaultSessionInit(n){switch(n){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",n),{}}}static async start(n,e,t){var r,s,o,a;if(st()&&te("debugxrpreroom"))return console.warn("Debug: Starting temporary XR session"),await Lg.start(n,e||Vu.getDefaultSessionInit(n)),null;if(this._currentSessionRequest)return console.warn("A XRSession is already being requested"),(Sr||st())&&Di("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=kt.Current),t||(t=di.All[0]),!t)throw new Error("No Needle Engine Context found");switch(e||(e={}),n){case"immersive-ar":{if(await((r=this.xrSystem)==null?void 0:r.isSessionSupported("immersive-ar"))!==!0)return console.error(n+" is not supported by this browser."),null;const h=this.getDefaultSessionInit(n),u=vde(t.domElement);u&&!ew()&&(h.domOverlay={root:u},h.optionalFeatures.push("dom-overlay")),e={...h,...e}}break;case"immersive-vr":{if(await((s=this.xrSystem)==null?void 0:s.isSessionSupported("immersive-vr"))!==!0)return console.error(n+" is not supported by this browser."),null;e={...this.getDefaultSessionInit(n),...e}}break;default:console.warn("No default session init for mode",n);break}e.optionalFeatures??(e.optionalFeatures=[]),e.requiredFeatures??(e.requiredFeatures=[]),await Lg.stop();const l=n=="immersive-ar"?t.scripts_immersive_ar:t.scripts_immersive_vr;Sr?console.log(`%cRequesting ${n} session`,"font-weight:bold;",e,l):console.log(`%cRequesting ${n} session`,"font-weight:bold;");for(const h of l)h.onBeforeXR&&h.onBeforeXR(n,e);for(const h of this._sessionRequestStartListeners)h({mode:n,init:e});Sr&&rn("Requesting "+n+" session ("+Date.now()+")"),this._currentSessionRequest=(o=navigator.xr)==null?void 0:o.requestSession(n,e),this._currentSessionRequestMode=n;const c=await((a=this._currentSessionRequest)==null?void 0:a.catch(h=>{console.error(h,"Code: "+h.code),h.code===9&&Di("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:"&&Di("XR requires a secure connection (HTTPS)")}));this._currentSessionRequest=void 0,this._currentSessionRequestMode=null;for(const h of this._sessionRequestEndListeners)h({mode:n,init:e,newSession:c||null});return c?this.setSession(n,c,e,t):(console.warn("XR Session request was rejected"),null)}static setSession(n,e,t,r){if(this._activeSession)return console.error("A XRSession is already running"),this._activeSession;const s=n=="immersive-ar"?r.scripts_immersive_ar:r.scripts_immersive_vr;return this._activeSession=new Vu(n,e,r,{scripts:s,controller_added:this._controllerAddedListeners,controller_removed:this._controllerRemovedListeners,init:t}),e.addEventListener("end",this.onEnd),Sr?console.log(`%cStarted ${n} session`,"font-weight:bold;",s):console.log(`%cStarted ${n} session`,"font-weight:bold;"),this._activeSession}static stop(){var n;(n=this._activeSession)==null||n.end()}get sync(){return Vu._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(n=>n.isLeft)}get rightController(){return this.controllers.find(n=>n.isRight)}getController(n){return typeof n=="number"?this.controllers[n]||null:this.controllers.find(e=>e.side===n)||null}get isPassThrough(){return!!(this.environmentBlendMode!=="opaque"&&this.interactionMode==="world-space"||this.mode==="immersive-ar"&&this.environmentBlendMode!=="opaque"&&this.controllers.some(n=>n.inputSource.targetRayMode==="tracked-pointer")||st()&&fp()&&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 n=this.frame.getImageTrackingResults();for(const e of n)if(e.trackingState==="tracked")return!0}catch{return!1}return!1}get rig(){const n=this._rigs[0]??null;return n!=null&&n.gameObject&&Jp(n.gameObject)||n?.isActive===!1?(this.updateActiveXRRig(),this._rigs[0]??null):n}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(n){this._rigs.indexOf(n)>=0||(n.priority===void 0&&(n.priority=0),this._rigs.push(n),this.updateActiveXRRig())}removeRig(n){const e=this._rigs.indexOf(n);e!==-1&&(this._rigs.splice(e,1),this.updateActiveXRRig())}setRigActive(n){const e=this._rigs.indexOf(n);this._rigs.splice(e,1),this._rigs.unshift(n),this.updateActiveXRRig()}updateActiveXRRig(){const n=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 r=this._rigs[t];if(r.isActive){if(Jp(r.gameObject)){this._rigs.splice(t,1),t--;continue}(!e||e.isActive===!1||r.priority!==void 0&&r.priority>e.priority)&&(e=r)}}if(n!==e){const t=this._rigs.indexOf(e);t>=0&&this._rigs.splice(t,1),this._rigs.unshift(e)}Sr&&(n===e?console.log("Updated Active XR Rig:",e,"prev:",n):console.log("Updated Active XRRig:",e," (the same as before)"))}getHitTest(n){if(n)return this.getControllerHitTest(n);if(!this._viewerHitTestSource)return null;const e=this._viewerHitTestSource,t=this.frame.getHitTestResults(e);if(t.length>0){const r=t[0];return this.convertHitTestResult(r)}return null}getControllerHitTest(n){const e=n.hitTestSource;if(!e)return null;const t=this.frame.getHitTestResultsForTransientInput(e);for(const r of t)if(r.inputSource===n.inputSource)for(const s of r.results)return this.convertHitTestResult(s);return null}convertHitTestResult(n){const e=this.context.renderer.xr.getReferenceSpace(),t=e&&n.getPose(e);if(t){const r=pi(t.transform.position),s=bp(t.transform.orientation),o=this.context.mainCamera;if(o?.parent!==this._cameraRenderParent&&r.applyMatrix4(Y1),o!=null&&o.parent){r.applyMatrix4(o.parent.matrixWorld),s.multiply(Sa);const a=Mi(o.parent);a.premultiply(Sa),s.premultiply(a)}return{hit:n,position:r,quaternion:s}}return null}convertSpace(n){const e=pi(n.position);e.applyMatrix4(Y1);const t=bp(n.orientation);return t.premultiply(Sa),{position:e,quaternion:t}}disconnectInputSource(n){const e=(t,r,s)=>{if(t.inputSource===n){Sr&&console.log("Disconnecting controller",t.index),this.controllers.splice(s,1),this.invokeControllerEvent(t,this._controllerRemoved,"removed");const o={xr:this,controller:t,change:"removed"};for(const a of this._xr_scripts)a.onXRControllerRemoved&&a.onXRControllerRemoved(o);t.onDisconnected()}};for(let t=this.controllers.length-1;t>=0;t--){const r=this.controllers[t];e(r,this.controllers,t)}for(let t=this._newControllers.length-1;t>=0;t--){const r=this._newControllers[t];e(r,this._newControllers,t)}}end(){this._ended||this.session.end().catch(n=>console.warn(n))}onRenderDebug(){if(Sr)for(const n of this.controllers)n.onRenderDebug();if((Sr||gde)&&this.rig){const n=this.rig.gameObject.worldPosition,e=this.rig.gameObject.worldForward;n.add(e.multiplyScalar(1.5));const t=this.rig.gameObject.worldUp;n.add(t.multiplyScalar(2.5));let r="";if(r+=this.context.time.smoothedFps.toFixed(1),Sr)for(const s of this.controllers)r+=`
5235
+ `+c.href)}this.onSendQueued(dl.OnRoomJoin);break;case"left-room":e.room===this.currentRoomName&&(this._isInRoom=!1,this._currentRoomName=null,this._currentInRoom.length=0);break;case"user-joined-room":if(e.data){const l=e.data;this._currentInRoom.push(l.userId),Zs&&console.log(l.userId+" joined","now in room:",this._currentInRoom)}break;case"user-left-room":if(e.data){const l=e.data,c=this._currentInRoom.indexOf(l.userId);c>=0&&(Zs&&console.log(l.userId+" left","now in room:",this._currentInRoom),this._currentInRoom.splice(c,1)),l.userId===this.connectionId&&console.log("you left the room")}break;case"all-room-state-deleted":Zs&&console.log("RECEIVED all-room-state-deleted"),this._state={};break;case"ping":case"pong":const a=(t=e.data)==null?void 0:t.time;a&&(this._currentDelay=this.context.time.time-a),Zs&&console.log("Current latency: "+this._currentDelay.toFixed(4)+" sec","Clients in room: "+((r=this._currentInRoom)==null?void 0:r.length));break}const s=e.data;s&&(this._state[s.guid]=s);let o=this._listeners[e.key];if(o){o=[...o];for(const a of o)try{a(e.data)}catch(l){console.error('Error invoking callback for "'+e.key+'"',l)}}}toMessage(e,t){return{key:e,data:t}}sendWithWebsocket(e,t,r=dl.OnRoomJoin){if(!this._ws){const o=this._waitingForSocket[r]||[];o.push(()=>this.sendWithWebsocket(e,t,r)),this._waitingForSocket[r]=o;return}const s=JSON.stringify(this.toMessage(e,t));Zs&&console.log(">>",e),this._ws.send(s)}onSendQueued(e){const t=this._waitingForSocket[e];if(t){for(const r of t)r();t.length=0}}}const rA=te("debugwebxr");class GB{constructor(e,t){d(this,"controllerStates",[]),d(this,"userId"),d(this,"context"),d(this,"userStateEvtName"),d(this,"onReceivedControllerState",r=>{rA&&console.log(`XRSync: Received change for ${this.userId}: ${r.type} ${r.handedness}; tracked=${r.isTracking}`);let s=!1;for(let o=0;o<this.controllerStates.length;o++)if(this.controllerStates[o].index===r.index){this.controllerStates[o]=r,s=!0;break}s||this.controllerStates.push(r)}),this.userId=e,this.context=t,this.userStateEvtName="xr-sync-user-state-"+e,this.context.connection.beginListen(this.userStateEvtName,this.onReceivedControllerState)}dispose(){this.context.connection.stopListen(this.userStateEvtName,this.onReceivedControllerState)}update(e){if(this.context.connection.isConnected!=!1){for(let t=this.controllerStates.length-1;t>=0;t--){const r=this.controllerStates[t];let s=!1;for(let o=0;o<e.controllers.length;o++)e.controllers[o].index===r.index&&(s=!0);s||(rA&&console.log(`XRSync: ${r.type} ${r.handedness} removed`,r.index),this.controllerStates.splice(t,1),this.sendControllerRemoved(r))}for(const t of e.controllers)this.updateControllerStates(t)}}onExitXR(e){for(const t of this.controllerStates)this.sendControllerRemoved(t);this.controllerStates.length=0}sendControllerRemoved(e){e.isTracking=!1,e.guid="",this.context.connection.send(this.userStateEvtName,e),this.context.connection.sendDeleteRemoteState(e.guid)}updateControllerStates(e){const t=this.controllerStates.find(r=>r.index===e.index);if(t){let r=!1;r||(r=t.isTracking!=e.isTracking),r&&(t.isTracking=e.isTracking,this.context.connection.send(this.userStateEvtName,t))}else{const r={guid:this.userId+"-"+e.index,isTracking:e.isTracking,handedness:e.side,index:e.index,type:e.hand?"hand":"controller"};this.controllerStates.push(r),this.context.connection.send(this.userStateEvtName,r),rA&&console.log(`XRSync: ${r.type} ${r.handedness} added`,r.index)}}}class a8{constructor(e){d(this,"context"),d(this,"onJoinedRoom",()=>{if(this.context.connection.connectionId){this._states.has(this.context.connection.connectionId)||(rA&&console.log("XRSync: Local user joined room",this.context.connection.connectionId),this._states.set(this.context.connection.connectionId,new GB(this.context.connection.connectionId,this.context)));for(const t of this.context.connection.usersInRoom())this._states.has(t)||this._states.set(t,new GB(t,this.context))}}),d(this,"onLeftRoom",()=>{if(this.context.connection.connectionId&&!this._states.has(this.context.connection.connectionId)){const t=this._states.get(this.context.connection.connectionId);t?.dispose(),this._states.delete(this.context.connection.connectionId)}}),d(this,"onOtherUserJoinedRoom",t=>{const r=t.userId;this._states.has(r)||(rA&&console.log("XRSync: Remote user joined room",r),this._states.set(r,new GB(r,this.context)))}),d(this,"onOtherUserLeftRoom",t=>{const r=t.userId;if(!this._states.has(r)){const s=this._states.get(r);s?.dispose(),this._states.delete(r)}}),d(this,"_states",new Map),this.context=e,this.context.connection.beginListen(Vt.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(Vt.LeftRoom,this.onLeftRoom),this.context.connection.beginListen(Vt.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.beginListen(Vt.UserLeftRoom,this.onOtherUserLeftRoom)}hasState(e){return e?this._states.has(e):!1}isTracking(e,t){if(!e)return;const r=this._states.get(e);if(!r)return;const s=r.controllerStates.find(o=>o.handedness===t);return s?.isTracking||!1}getDeviceType(e,t){if(!e)return;const r=this._states.get(e);if(!r)return;const s=r.controllerStates.find(o=>o.handedness===t);return s?.type||"unknown"}destroy(){this.context.connection.stopListen(Vt.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(Vt.LeftRoom,this.onLeftRoom),this.context.connection.stopListen(Vt.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.stopListen(Vt.UserLeftRoom,this.onOtherUserLeftRoom)}onUpdate(e){if(this.context.connection.isConnected&&this.context.connection.connectionId){const t=this._states.get(this.context.connection.connectionId);t?.update(e)}}onExitXR(e){if(this.context.connection.isConnected&&this.context.connection.connectionId){const t=this._states.get(this.context.connection.connectionId);t?.onExitXR(e)}}}class l8{constructor(){d(this,"_fadeToColorQuad"),d(this,"_fadeToColorMaterial"),d(this,"_requestedFadeValue",0),d(this,"_transitionPromise",null),d(this,"_transitionResolve",null),this._fadeToColorMaterial=new $t({color:0,transparent:!0,depthTest:!1,fog:!1,side:yi}),this._fadeToColorQuad=new me(new tr(10,10),this._fadeToColorMaterial)}dispose(){this._fadeToColorQuad.geometry.dispose(),this._fadeToColorMaterial.dispose()}update(e,t){const r=this._fadeToColorQuad,s=this._fadeToColorMaterial;r.parent!==e&&s.opacity>0?e.add(r):s.opacity===0&&r.removeFromParent(),r.layers.set(2),r.material=this._fadeToColorMaterial,r.position.z=-1,r.renderOrder=1/0;const o=this._requestedFadeValue;s.opacity=it.lerp(s.opacity,o,t/.03),Math.abs(s.opacity-o)<=.01&&this._transitionResolve&&(this._transitionResolve(),this._transitionResolve=null,this._transitionPromise=null,this._requestedFadeValue=0)}remove(){this._fadeToColorQuad.removeFromParent()}fadeTransition(){if(this._transitionPromise)return this._transitionPromise;this._requestedFadeValue=1;const e=new Promise(t=>{this._transitionResolve=t});return this._transitionPromise=e,e}}var Yp=(n=>(n[n.Quad=0]="Quad",n[n.Cube=1]="Cube",n[n.Sphere=2]="Sphere",n))(Yp||{});class sA{static createPrimitive(e,t){let r;switch(e){case"Quad":case 0:{const s=new tr(1,1,1,1),o=t?.material??new vs({color:16777215});t!=null&&t.texture&&"map"in o&&(o.map=t.texture),r=new me(s,o)}break;case"Cube":case 1:{const s=new qi(1,1,1),o=t?.material??new vs({color:16777215});t!=null&&t.texture&&"map"in o&&(o.map=t.texture),r=new me(s,o)}break;case"Sphere":case 2:{const s=new ja(.5,16,16),o=t?.material??new vs({color:16777215});t!=null&&t.texture&&"map"in o&&(o.map=t.texture),r=new me(s,o)}break}return this.applyDefaultObjectOptions(r,t),r}static createSprite(e){const t=new lx({color:16777215});e!=null&&e.texture&&"map"in t&&(t.map=e.texture);const r=new OT(t);return this.applyDefaultObjectOptions(r,e),r}static applyDefaultObjectOptions(e,t){t!=null&&t.name&&(e.name=t.name),t!=null&&t.position&&e.position.set(t.position.x,t.position.y,t.position.z),t!=null&&t.rotation&&e.rotation.set(t.rotation.x,t.rotation.y,t.rotation.z),t!=null&&t.scale&&e.scale.set(t.scale.x,t.scale.y,t.scale.z)}}const c8=class{constructor(n,e,t){d(this,"_session"),d(this,"_mode"),d(this,"_init"),d(this,"_renderer"),d(this,"_camera"),d(this,"_scene"),d(this,"onEnd",()=>{var r;(r=this._session)==null||r.removeEventListener("end",this.onEnd),this._renderer.setAnimationLoop(null),this._renderer.dispose(),this._scene.clear()}),d(this,"_lastTime",0),d(this,"onFrame",(r,s)=>{const o=r-this._lastTime;this.update(r,o),this._camera.parent!==this._scene&&this._scene.add(this._camera),this._renderer.render(this._scene,this._camera)}),d(this,"_objects",[]),this._mode=n,this._init=e,this._session=t,this._session.addEventListener("end",this.onEnd),this._renderer=new Wc({alpha:!0}),this._renderer.setAnimationLoop(this.onFrame),this._renderer.xr.setSession(t),this._renderer.xr.enabled=!0,this._camera=new Lt,this._scene=new Ur,this._scene.fog=new ax(4473924,10,250),this._scene.add(this._camera),this.setupScene()}static get active(){return this._active}static async start(n,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(n,e);return t.addEventListener("end",()=>{this._active=null}),this._requestInFlight?(this._requestInFlight=!1,this._active=new c8(n,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 Ll(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 n={session:this._session,mode:this._mode,init:this._init};return await this.onBeforeHandoff(),this.onEnd(),this._session=null,n}async onBeforeHandoff(){await Ll(1e3),this._scene.clear()}setupScene(){this._scene.background=new xe(0),this._scene.add(new Hx(5,10,1118481,1118481));const n=new lp(16777215,1);n.position.set(0,20,0),n.castShadow=!1,this._scene.add(n);const e=new lp(16777215,1);e.position.set(0,-1,0),e.castShadow=!1,this._scene.add(e);const t=new ap(16777215,1,100,1);t.position.set(0,2,0),t.castShadow=!1,t.distance=200,this._scene.add(t);const r=50;for(let s=0;s<100;s++){const o=new vs({color:2236962,metalness:1,roughness:.8});this.isAR&&(o.emissive=new xe(Math.random(),Math.random(),Math.random()),o.emissiveIntensity=Math.random());const a=it.random(0,1)>.5?Yp.Sphere:Yp.Cube,l=sA.createPrimitive(a,{material:o});l.position.x=it.random(-r,r),l.position.y=it.random(-2,r),l.position.z=it.random(-r,r),l.rotation.x=it.random(0,Math.PI*2),l.rotation.y=it.random(0,Math.PI*2),l.rotation.z=it.random(0,Math.PI*2),l.scale.multiplyScalar(.5+Math.random()*10);const c=l.position.distanceTo(this._camera.position)-l.scale.x;c<1&&l.position.multiplyScalar(1+1/c),this._objects.push(l),this._scene.add(l)}}update(n,e){const t=n*4e-4;for(let r=0;r<this._objects.length;r++){const s=this._objects[r];s.position.y+=Math.sin(t+r*.5)*.005,s.rotateY(.002)}}};let Lg=c8;d(Lg,"_active",null),d(Lg,"_requestInFlight",!1);const Sr=te("debugwebxr"),gde=te("stats");function vde(n){let e=null;const t=n;return t.getAROverlayContainer?e=t.getAROverlayContainer():e=n,e}yde();async function yde(){var n;if(te("debugasap")){let e=globalThis["needle:XRSession"];if(e instanceof Promise){delete globalThis["needle:XRSession"],di.addContextCreatedCallback(async t=>{if(!e)return;Nf(!0);const r=await e;if(r){const s=wt.getDefaultSessionInit("immersive-vr");wt.setSession("immersive-vr",r,s,t.context)}else console.error("NeedleXRSession: ASAP session was rejected");e=void 0});return}}if("xr"in navigator){if(/WebXRViewer\//i.test(navigator.userAgent)){console.warn("WebXRViewer does not support addEventListener");return}(n=navigator.xr)==null||n.addEventListener("sessiongranted",async()=>{Nf(!0),console.log("Received Session Granted..."),await Ll(100);const e=sessionStorage.getItem("needle_xr_session_mode"),t=sessionStorage.getItem("needle_xr_session_init")??null,r=t?JSON.parse(t):null;let s=null;if(h8()&&(await Lg.start(e||"immersive-vr",r||wt.getDefaultSessionInit("immersive-vr")),await _de(),s=await Lg.handoff()),s)wt.setSession(s.mode,s.session,s.init,kt.Current);else if(e&&t){console.log("Session Granted: Restore last session");const o=JSON.parse(t);wt.start(e,o).catch(a=>console.warn(a))}else wt.start("immersive-vr").catch(o=>console.warn("Session Granted failed:",o))},{once:!0})}}function Ade(n,e){sessionStorage.setItem("needle_xr_session_mode",n),sessionStorage.setItem("needle_xr_session_init",JSON.stringify(e))}function bde(){sessionStorage.removeItem("needle_xr_session_mode"),sessionStorage.removeItem("needle_xr_session_init")}const VB=new Set;di.registerCallback(Ci.ContextCreationStart,async n=>{VB.add(n.context)}),di.registerCallback(Ci.ContextCreated,async n=>{VB.delete(n.context)});function h8(){return VB.size>0}function _de(){return new Promise(n=>{const e=Date.now(),t=setInterval(()=>{(!h8()||Date.now()-e>6e4)&&(clearInterval(t),n())},100)})}fp()&&st()&&window.addEventListener("keydown",n=>{(n.key==="x"||n.key==="Escape")&&wt.active&&wt.stop()});const Vu=class{constructor(n,e,t,r){d(this,"context"),d(this,"session"),d(this,"mode"),d(this,"controllers",[]),d(this,"_rigScale",1),d(this,"_lastRigScaleUpdate",-1),d(this,"_rigs",[]),d(this,"_viewerHitTestSource",null),d(this,"_defaultRig"),d(this,"_xr_scripts"),d(this,"_xr_update_scripts",[]),d(this,"_inactive_scripts",[]),d(this,"_controllerAdded"),d(this,"_controllerRemoved"),d(this,"_originalCameraWorldPosition"),d(this,"_originalCameraWorldRotation"),d(this,"_originalCameraWorldScale"),d(this,"_originalCameraParent"),d(this,"_mainCamera",null),d(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())}),d(this,"onInputSourceAdded",a=>{if(a.targetRayMode==="screen")return;let l=0;for(let h=0;h<this.session.inputSources.length;h++)if(this.session.inputSources[h]===a){l=h;break}if(this.controllers.find(h=>h.inputSource===a)){console.warn("Controller already exists for input source",l);return}Sr&&console.log("Adding controller",l);const c=new vB(this,a,l);this._newControllers.push(c)}),d(this,"_ended",!1),d(this,"_newControllers",[]),d(this,"onEnd",a=>{var l,c,h;if(this._ended)return;this._ended=!0,Sr&&console.log("XR Session ended"),bde(),this.onAfterRender(),this.revertCustomForward(),this._didStart=!1,this._previousCameraParent=null,zu(this.onBefore,Hi.LateUpdate);const u=this.context.pre_render_callbacks.indexOf(this.onBeforeRender);u>=0&&this.context.pre_render_callbacks.splice(u,1);const p=this.context.post_render_callbacks.indexOf(this.onAfterRender);p>=0&&this.context.post_render_callbacks.splice(p,1),this.context.xr=null,this.context.renderer.xr.enabled=!1,this.context.pre_update_oneshot_callbacks.push(()=>{var m;(m=this.context.mainCameraComponent)==null||m.applyClearFlags()}),R6({session:this});for(const m of Vu._xrEndListeners)m({xr:this});for(let m=0;m<this.controllers.length;m++)this.disconnectInputSource(this.controllers[m].inputSource);for(const m of this._xr_scripts)(l=m?.onLeaveXR)==null||l.call(m,{xr:this});(c=this.sync)==null||c.onExitXR(this),this.context.mainCamera&&((h=this._originalCameraParent)==null||h.add(this.context.mainCamera),this._originalCameraWorldPosition&&lr(this.context.mainCamera,this._originalCameraWorldPosition),this._originalCameraWorldRotation&&ca(this.context.mainCamera,this._originalCameraWorldRotation),this._originalCameraWorldScale&&Uf(this.context.mainCamera,this._originalCameraWorldScale)),this.context.requestSizeUpdate(),this._defaultRig.gameObject.removeFromParent(),Nf(!1)}),d(this,"_didStart",!1),d(this,"onBefore",a=>{var l,c,h,u,p,m,f,g;const v=a.xrFrame;if(!v)return;this.context.xr=this,this.context.mainCameraComponent&&this.context.mainCameraComponent!==this._mainCamera&&(this._mainCamera=this.context.mainCameraComponent),((l=this.rig)==null?void 0:l.isActive)==!1&&(Sr&&console.warn("Latest rig is not active - trying to activate a different rig",this.rig),this.updateActiveXRRig()),this.rig&&(c=this._mainCamera)!=null&&c.gameObject&&((u=(h=this._mainCamera)==null?void 0:h.gameObject)==null?void 0:u.parent)!==this.rig.gameObject&&this.rig.gameObject.add((p=this._mainCamera)==null?void 0:p.gameObject),this.internalUpdateState(),this.applyCustomForward();const y={xr:this};if(this._didStart){if(this.context.new_scripts_xr.length>0){const A=[...this.context.new_scripts_xr];for(let _=0;_<A.length;_++){const b=this.context.new_scripts_xr[_];if(!b||b.destroyed||((m=b.supportsXR)==null?void 0:m.call(b,this.mode))==!1){this.context.new_scripts_xr.splice(_,1);continue}if(!b.activeAndEnabled){this.context.new_scripts_xr.splice(_,1),this.markInactive(b);continue}if(this.addScript(b)){this.invokeCallback_EnterXR(b);for(const x of this.controllers)this.invokeCallback_ControllerAdded(b,x)}}}}else{if(this._didStart=!0,this.mode==="immersive-vr"){const _=Ul(this.context.scene.children);if(_){const b=_.getSize(pi());if(b.length()>0){const x=this._defaultRig.gameObject;x.position.set(_.min.x+b.x*.5,_.min.y,_.max.z+b.z*.5+1.5);const E=_.getCenter(pi());E.y=x.position.y,x.lookAt(E)}}}I6({session:this});for(const _ of Vu._xrStartListeners)_(y);const A=[...this._xr_scripts];Sr&&console.log("NeedleXRSession start, handle scripts:",A);for(const _ of A){if(_.destroyed){this._script_to_remove.push(_);continue}if(!_.activeAndEnabled){this.markInactive(_);continue}this.invokeCallback_EnterXR(_);for(const b of this.controllers)this.invokeCallback_ControllerAdded(_,b)}}this.syncCameraCullingMask();for(const A of this.controllers)A.onUpdate(v);if(this._newControllers.length>0){const A=[...this._newControllers];this._newControllers.length=0;for(const _ of A)if(_.connected){this.controllers.push(_);for(const b of this._xr_scripts){if(b.destroyed){this._script_to_remove.push(b);continue}b.activeAndEnabled!==!1&&this.invokeCallback_ControllerAdded(b,_)}}this.controllers.sort((_,b)=>_.index-b.index)}for(const A of this._xr_update_scripts){if(A.destroyed===!0){this._script_to_remove.push(A);continue}if(A.activeAndEnabled===!1){this.markInactive(A);continue}A.onUpdateXR&&A.onUpdateXR(y)}if(this.handleInactiveScripts(),this._script_to_remove.length>0){const A=[...new Set(this._script_to_remove)];this._script_to_remove.length=0;for(const _ of A)!_.destroyed&&this.running&&((f=_.onLeaveXR)==null||f.call(_,y)),this.removeScript(_)}(g=this.sync)==null||g.onUpdate(this),this.onRenderDebug()}),d(this,"onBeforeRender",()=>{this.context.mainCamera&&this.updateFade(this.context.mainCamera)}),d(this,"onAfterRender",()=>{if(this.onUpdateFade_PostRender(),fp()){const a=this.context.renderer;if(a.xr.isPresenting&&this.context.mainCamera){const l=a.xr.enabled,c=a.getRenderTarget();a.xr.enabled=!1,a.setRenderTarget(null),a.render(this.context.scene,this.context.mainCamera),a.xr.enabled=l,a.setRenderTarget(c)}}}),d(this,"_script_to_remove",[]),d(this,"_camera"),d(this,"_cameraRenderParent",new ye().rotateY(Math.PI)),d(this,"_previousCameraParent"),d(this,"_customforward",!0),d(this,"originalCameraNearPlane"),d(this,"_viewerPose"),d(this,"_transformOrientation",new Ce),d(this,"_transformPosition",new C),d(this,"_transition");var s,o;Ade(n,r.init),this.session=e,this.mode=n,this.context=t,(Sr||te("console"))&&Nf(!0),this._xr_scripts=[...r.scripts],this._xr_update_scripts=this._xr_scripts.filter(a=>typeof a.onUpdateXR=="function"),this._controllerAdded=r.controller_added,this._controllerRemoved=r.controller_removed,Nu(this.onBefore,Hi.LateUpdate),this.context.pre_render_callbacks.push(this.onBeforeRender),this.context.post_render_callbacks.push(this.onAfterRender),((s=r.init.optionalFeatures)!=null&&s.includes("hit-test")||(o=r.init.requiredFeatures)!=null&&o.includes("hit-test"))&&e.requestReferenceSpace("viewer").then(a=>{var l,c;return(c=(l=e.requestHitTestSource)==null?void 0:l.call(e,{space:a}))==null?void 0:c.then(h=>this._viewerHitTestSource=h)}).catch(a=>console.warn(a)),this.context.mainCamera&&(this._originalCameraWorldPosition=Bt(this.context.mainCamera,new C),this._originalCameraWorldRotation=Mi(this.context.mainCamera,new Ce),this._originalCameraWorldScale=Vi(this.context.mainCamera,new C),this._originalCameraParent=this.context.mainCamera.parent),this._defaultRig=new Sue,this.context.scene.add(this._defaultRig.gameObject),this.addRig(this._defaultRig);for(let a=0;a<e.inputSources.length;a++){const l=e.inputSources[a];if(!l.handedness){console.warn("Input source in xr session has no handedness - ignoring",a);continue}this.onInputSourceAdded(l)}this.session.addEventListener("end",this.onEnd),this.session.addEventListener("inputsourceschange",a=>{for(const l of a.removed)this.disconnectInputSource(l);for(const l of a.added)this.onInputSourceAdded(l)}),this.context.xr=this,this.context.renderer.xr.setSession(this.session).then(this.onRendererSessionSet)}static getXRSync(n){return this._sync||(this._sync=new a8(n)),this._sync}static get currentSessionRequest(){return this._currentSessionRequestMode}static get active(){return this._activeSession}static get activeMode(){var n;return((n=this._activeSession)==null?void 0:n.mode)??null}static get xrSystem(){return"xr"in navigator?navigator.xr:void 0}static isXRSupported(){return Promise.all([this.isVRSupported(),this.isARSupported()]).then(n=>n.some(e=>e)).catch(()=>!1)}static isVRSupported(){return this.isSessionSupported("immersive-vr")}static isARSupported(){return this.isSessionSupported("immersive-ar")}static isSessionSupported(n){var e;return((e=this.xrSystem)==null?void 0:e.isSessionSupported(n).catch(t=>(Sr&&console.error(t),!1)))??Promise.resolve(!1)}static onSessionRequestStart(n){this._sessionRequestStartListeners.push(n)}static offSessionRequestStart(n){const e=this._sessionRequestStartListeners.indexOf(n);e>=0&&this._sessionRequestStartListeners.splice(e,1)}static onSessionRequestEnd(n){this._sessionRequestEndListeners.push(n)}static offSessionRequestEnd(n){const e=this._sessionRequestEndListeners.indexOf(n);e>=0&&this._sessionRequestEndListeners.splice(e,1)}static onXRSessionStart(n){this._xrStartListeners.push(n)}static offXRSessionStart(n){const e=this._xrStartListeners.indexOf(n);e>=0&&this._xrStartListeners.splice(e,1)}static onXRSessionEnd(n){this._xrEndListeners.push(n)}static offXRSessionEnd(n){const e=this._xrEndListeners.indexOf(n);e>=0&&this._xrEndListeners.splice(e,1)}static onControllerAdded(n){this._controllerAddedListeners.push(n)}static offControllerAdded(n){const e=this._controllerAddedListeners.indexOf(n);e>=0&&this._controllerAddedListeners.splice(e,1)}static onControllerRemoved(n){this._controllerRemovedListeners.push(n)}static offControllerRemoved(n){const e=this._controllerRemovedListeners.indexOf(n);e>=0&&this._controllerRemovedListeners.splice(e,1)}static offerSession(n,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: "+n),e=="default"&&(e=this.getDefaultSessionInit(n)),navigator.xr.offerSession(n,{...e}).then(r=>Vu.setSession(n,r,e,t)).catch(r=>{console.log("XRSession offer rejected (perhaps because another call to offerSession was made or a call to requestSession was made)")})),!0):!1}static getDefaultSessionInit(n){switch(n){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",n),{}}}static async start(n,e,t){var r,s,o,a;if(st()&&te("debugxrpreroom"))return console.warn("Debug: Starting temporary XR session"),await Lg.start(n,e||Vu.getDefaultSessionInit(n)),null;if(this._currentSessionRequest)return console.warn("A XRSession is already being requested"),(Sr||st())&&Di("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=kt.Current),t||(t=di.All[0]),!t)throw new Error("No Needle Engine Context found");switch(e||(e={}),n){case"immersive-ar":{if(await((r=this.xrSystem)==null?void 0:r.isSessionSupported("immersive-ar"))!==!0)return console.error(n+" is not supported by this browser."),null;const h=this.getDefaultSessionInit(n),u=vde(t.domElement);u&&!ew()&&(h.domOverlay={root:u},h.optionalFeatures.push("dom-overlay")),e={...h,...e}}break;case"immersive-vr":{if(await((s=this.xrSystem)==null?void 0:s.isSessionSupported("immersive-vr"))!==!0)return console.error(n+" is not supported by this browser."),null;e={...this.getDefaultSessionInit(n),...e}}break;default:console.warn("No default session init for mode",n);break}e.optionalFeatures??(e.optionalFeatures=[]),e.requiredFeatures??(e.requiredFeatures=[]),await Lg.stop();const l=n=="immersive-ar"?t.scripts_immersive_ar:t.scripts_immersive_vr;Sr?console.log(`%cRequesting ${n} session`,"font-weight:bold;",e,l):console.log(`%cRequesting ${n} session`,"font-weight:bold;");for(const h of l)h.onBeforeXR&&h.onBeforeXR(n,e);for(const h of this._sessionRequestStartListeners)h({mode:n,init:e});Sr&&rn("Requesting "+n+" session ("+Date.now()+")"),this._currentSessionRequest=(o=navigator.xr)==null?void 0:o.requestSession(n,e),this._currentSessionRequestMode=n;const c=await((a=this._currentSessionRequest)==null?void 0:a.catch(h=>{console.error(h,"Code: "+h.code),h.code===9&&Di("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:"&&Di("XR requires a secure connection (HTTPS)")}));this._currentSessionRequest=void 0,this._currentSessionRequestMode=null;for(const h of this._sessionRequestEndListeners)h({mode:n,init:e,newSession:c||null});return c?this.setSession(n,c,e,t):(console.warn("XR Session request was rejected"),null)}static setSession(n,e,t,r){if(this._activeSession)return console.error("A XRSession is already running"),this._activeSession;const s=n=="immersive-ar"?r.scripts_immersive_ar:r.scripts_immersive_vr;return this._activeSession=new Vu(n,e,r,{scripts:s,controller_added:this._controllerAddedListeners,controller_removed:this._controllerRemovedListeners,init:t}),e.addEventListener("end",this.onEnd),Sr?console.log(`%cStarted ${n} session`,"font-weight:bold;",s):console.log(`%cStarted ${n} session`,"font-weight:bold;"),this._activeSession}static stop(){var n;(n=this._activeSession)==null||n.end()}get sync(){return Vu._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(n=>n.isLeft)}get rightController(){return this.controllers.find(n=>n.isRight)}getController(n){return typeof n=="number"?this.controllers[n]||null:this.controllers.find(e=>e.side===n)||null}get isPassThrough(){return!!(this.environmentBlendMode!=="opaque"&&this.interactionMode==="world-space"||this.mode==="immersive-ar"&&this.environmentBlendMode!=="opaque"&&this.controllers.some(n=>n.inputSource.targetRayMode==="tracked-pointer")||st()&&fp()&&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 n=this.frame.getImageTrackingResults();for(const e of n)if(e.trackingState==="tracked")return!0}catch{return!1}return!1}get rig(){const n=this._rigs[0]??null;return n!=null&&n.gameObject&&Jp(n.gameObject)||n?.isActive===!1?(this.updateActiveXRRig(),this._rigs[0]??null):n}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(n){this._rigs.indexOf(n)>=0||(n.priority===void 0&&(n.priority=0),this._rigs.push(n),this.updateActiveXRRig())}removeRig(n){const e=this._rigs.indexOf(n);e!==-1&&(this._rigs.splice(e,1),this.updateActiveXRRig())}setRigActive(n){const e=this._rigs.indexOf(n);this._rigs.splice(e,1),this._rigs.unshift(n),this.updateActiveXRRig()}updateActiveXRRig(){const n=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 r=this._rigs[t];if(r.isActive){if(Jp(r.gameObject)){this._rigs.splice(t,1),t--;continue}(!e||e.isActive===!1||r.priority!==void 0&&r.priority>e.priority)&&(e=r)}}if(n!==e){const t=this._rigs.indexOf(e);t>=0&&this._rigs.splice(t,1),this._rigs.unshift(e)}Sr&&(n===e?console.log("Updated Active XR Rig:",e,"prev:",n):console.log("Updated Active XRRig:",e," (the same as before)"))}getHitTest(n){if(n)return this.getControllerHitTest(n);if(!this._viewerHitTestSource)return null;const e=this._viewerHitTestSource,t=this.frame.getHitTestResults(e);if(t.length>0){const r=t[0];return this.convertHitTestResult(r)}return null}getControllerHitTest(n){const e=n.hitTestSource;if(!e)return null;const t=this.frame.getHitTestResultsForTransientInput(e);for(const r of t)if(r.inputSource===n.inputSource)for(const s of r.results)return this.convertHitTestResult(s);return null}convertHitTestResult(n){const e=this.context.renderer.xr.getReferenceSpace(),t=e&&n.getPose(e);if(t){const r=pi(t.transform.position),s=bp(t.transform.orientation),o=this.context.mainCamera;if(o?.parent!==this._cameraRenderParent&&r.applyMatrix4(Y1),o!=null&&o.parent){r.applyMatrix4(o.parent.matrixWorld),s.multiply(Sa);const a=Mi(o.parent);a.premultiply(Sa),s.premultiply(a)}return{hit:n,position:r,quaternion:s}}return null}convertSpace(n){const e=pi(n.position);e.applyMatrix4(Y1);const t=bp(n.orientation);return t.premultiply(Sa),{position:e,quaternion:t}}disconnectInputSource(n){const e=(t,r,s)=>{if(t.inputSource===n){Sr&&console.log("Disconnecting controller",t.index),this.controllers.splice(s,1),this.invokeControllerEvent(t,this._controllerRemoved,"removed");const o={xr:this,controller:t,change:"removed"};for(const a of this._xr_scripts)a.onXRControllerRemoved&&a.onXRControllerRemoved(o);t.onDisconnected()}};for(let t=this.controllers.length-1;t>=0;t--){const r=this.controllers[t];e(r,this.controllers,t)}for(let t=this._newControllers.length-1;t>=0;t--){const r=this._newControllers[t];e(r,this._newControllers,t)}}end(){this._ended||this.session.end().catch(n=>console.warn(n))}onRenderDebug(){if(Sr)for(const n of this.controllers)n.onRenderDebug();if((Sr||gde)&&this.rig){const n=this.rig.gameObject.worldPosition,e=this.rig.gameObject.worldForward;n.add(e.multiplyScalar(1.5));const t=this.rig.gameObject.worldUp;n.add(t.multiplyScalar(2.5));let r="";if(r+=this.context.time.smoothedFps.toFixed(1),Sr)for(const s of this.controllers)r+=`
5236
5236
  ${s.hand?"hand":"ctrl"} ${s.inputSource.handedness}[${s.index}] con:${s.connected} tr:${s.isTracking}`;At.DrawLabel(n,r)}}addScript(n){return this._xr_scripts.includes(n)?!1:(Sr&&console.log("Register new XRScript",n),this._xr_scripts.push(n),typeof n.onUpdateXR=="function"&&this._xr_update_scripts.push(n),!0)}markInactive(n){if(!(this._inactive_scripts.indexOf(n)>=0)){this.removeScript(n,!1),this._inactive_scripts.push(n);for(const e of this.controllers)this.invokeCallback_ControllerRemoved(n,e);this.invokeCallback_LeaveXR(n)}}handleInactiveScripts(){if(this._inactive_scripts.length>0)for(let n=this._inactive_scripts.length-1;n>=0;n--){const e=this._inactive_scripts[n];if(e.activeAndEnabled){this._inactive_scripts.splice(n,1),this.addScript(e),this.invokeCallback_EnterXR(e);for(const t of this.controllers)this.invokeCallback_ControllerAdded(e,t)}}}removeScript(n,e=!0){Sr&&console.log("Remove XRScript",n);const t=this._xr_scripts.indexOf(n);t>=0&&this._xr_scripts.splice(t,1);const r=this._xr_update_scripts.indexOf(n);if(r>=0&&this._xr_update_scripts.splice(r,1),e){const s=this._inactive_scripts.indexOf(n);s>=0&&this._inactive_scripts.splice(s,1)}}invokeCallback_EnterXR(n){n.onEnterXR&&n.onEnterXR({xr:this})}invokeCallback_ControllerAdded(n,e){n.onXRControllerAdded&&n.onXRControllerAdded({xr:this,controller:e,change:"added"})}invokeCallback_ControllerRemoved(n,e){n.onXRControllerRemoved&&n.onXRControllerRemoved({xr:this,controller:e,change:"removed"})}invokeCallback_LeaveXR(n){n.onLeaveXR&&!n.destroyed&&n.onLeaveXR({xr:this})}syncCameraCullingMask(){var n;const e=this.context.xrCamera,t=(n=this.context.mainCameraComponent)==null?void 0:n.cullingMask;if(e&&t!==void 0){for(const r of e.cameras)r.layers.mask=t;e.layers.mask=t}else if(e){for(const r of e.cameras)r.layers.enableAll();e.layers.enableAll()}}invokeControllerEvent(n,e,t){for(let r=e.length-1;r>=0;r--){const s=e[r];if(s)try{s({xr:this,controller:n,change:t})}catch(o){console.error(o)}}}applyCustomForward(){var n;if(this.context.mainCamera&&this._customforward){this._camera=this.context.mainCamera,this._camera.parent!==this._cameraRenderParent&&(this._previousCameraParent=this._camera.parent,(n=this._previousCameraParent)==null||n.add(this._cameraRenderParent)),this._cameraRenderParent.name="XR Camera Render Parent",this._cameraRenderParent.add(this._camera);let e=.02;if(this.rig){const t=Vi(this.rig.gameObject);e*=t.x}this._camera instanceof Lt&&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 Lt&&this.originalCameraNearPlane!=null&&(this._camera.near=this.originalCameraNearPlane)}internalUpdateState(){const n=this.context.renderer.xr.getReferenceSpace();if(!n){this._viewerPose=void 0;return}if(this._viewerPose=this.frame.getViewerPose(n),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 l8),this._transition}fadeTransition(){return this._transition||(this._transition=new l8),this._transition.fadeTransition()}updateFade(n){this._transition&&n instanceof Lt&&this._transition.update(n,this.context.time.deltaTime)}onUpdateFade_PostRender(){var n;(n=this._transition)==null||n.remove()}};let wt=Vu;d(wt,"_sync",null),d(wt,"_currentSessionRequestMode",null),d(wt,"_currentSessionRequest"),d(wt,"_activeSession"),d(wt,"_sessionRequestStartListeners",[]),d(wt,"_sessionRequestEndListeners",[]),d(wt,"_xrStartListeners",[]),d(wt,"_xrEndListeners",[]),d(wt,"_controllerAddedListeners",[]),d(wt,"_controllerRemovedListeners",[]),d(wt,"onEnd",()=>{Sr&&console.log("XR Session ended"),Vu._activeSession=null});const QB=te("debugwebxr");class u8{static tryFindAvatarObjects(e,t,r){if(r.head&&r.leftHand&&r.rightHand)return;const s=e.name.toLocaleLowerCase();!r.head&&s.includes("head")&&(QB&&console.log("FOUND AVATAR HEAD",e.name),r.head=new ti("",t,e)),s.includes("hand")&&(!r.leftHand&&s.includes("left")&&(QB&&console.log("FOUND AVATAR LEFT HAND",e.name),r.leftHand=new ti("",t,e)),!r.rightHand&&s.includes("right")&&(QB&&console.log("FOUND AVATAR RIGHT HAND",e.name),r.rightHand=new ti("",t,e)));for(let o=0;o<e.children.length;o++){if(r.head&&r.leftHand&&r.rightHand)return;const a=e.children[o];this.tryFindAvatarObjects(a,t,r)}}}var cS=(n=>(n.Visible="application-visible",n.Hidden="application-hidden",n.MuteChanged="application-mutechanged",n))(cS||{});let hS=!1;const Fg=[];function Ug(){if(hS)return;st()&&console.debug("User interaction registered: audio can now be played"),hS=!0;const n=[...Fg];Fg.length=0,n.forEach(e=>e())}document.addEventListener("pointerdown",Ug),document.addEventListener("click",Ug),document.addEventListener("dragstart",Ug),document.addEventListener("touchstart",Ug),document.addEventListener("keydown",Ug),wt.onXRSessionStart(()=>{Ug()});const d8=class extends EventTarget{constructor(n){super(),d(this,"_mute",!1),d(this,"context"),d(this,"_isVisible",!0),this.context=n,window.addEventListener("visibilitychange",this.onVisiblityChanged.bind(this),!1)}static get userInteractionRegistered(){return hS}static registerWaitForInteraction(n){if(n!==null){if(hS){n();return}Fg.indexOf(n)===-1&&Fg.push(n)}}static unregisterWaitForInteraction(n){const e=Fg.indexOf(n);e!==-1&&Fg.splice(e,1)}get muted(){return this._mute}set muted(n){n!==this._mute&&(this._mute=n,this.dispatchEvent(new Event("application-mutechanged")))}get hasFocus(){return document.hasFocus()}get isVisible(){return this._isVisible}onVisiblityChanged(n){switch(n.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 Qu=d8;d(Qu,"registerWaitForAllowAudio",d8.registerWaitForInteraction);function*p8(n,e=null){const t=e?e.time:kt.Current.time,r=t.time;for(;t.time-r<n;)yield}function*xde(n){for(let e=0;e<n;e++)yield}function*m8(n){let e=!0;for(n.then(()=>e=!1),n.catch(()=>e=!1);e;)yield}class oA extends hI{constructor(e){super(e),this.type=rr}parse(e){const t=Math.pow(2.7182818,2.2);function r(S,B){let j=0;for(let N=0;N<65536;++N)(N==0||S[N>>3]&1<<(N&7))&&(B[j++]=N);const ee=j-1;for(;j<65536;)B[j++]=0;return ee}function s(S){for(let B=0;B<16384;B++)S[B]={},S[B].len=0,S[B].lit=0,S[B].p=null}const o={l:0,c:0,lc:0};function a(S,B,j,ee,N){for(;j<S;)B=B<<8|X(ee,N),j+=8;j-=S,o.l=B>>j&(1<<S)-1,o.c=B,o.lc=j}const l=new Array(59);function c(S){for(let j=0;j<=58;++j)l[j]=0;for(let j=0;j<65537;++j)l[S[j]]+=1;let B=0;for(let j=58;j>0;--j){const ee=B+l[j]>>1;l[j]=B,B=ee}for(let j=0;j<65537;++j){const ee=S[j];ee>0&&(S[j]=ee|l[ee]++<<6)}}function h(S,B,j,ee,N,Y){const W=B;let ae=0,ce=0;for(;ee<=N;ee++){if(W.value-B.value>j)return!1;a(6,ae,ce,S,W);const _e=o.l;if(ae=o.c,ce=o.lc,Y[ee]=_e,_e==63){if(W.value-B.value>j)throw new Error("Something wrong with hufUnpackEncTable");a(8,ae,ce,S,W);let Re=o.l+6;if(ae=o.c,ce=o.lc,ee+Re>N+1)throw new Error("Something wrong with hufUnpackEncTable");for(;Re--;)Y[ee++]=0;ee--}else if(_e>=59){let Re=_e-59+2;if(ee+Re>N+1)throw new Error("Something wrong with hufUnpackEncTable");for(;Re--;)Y[ee++]=0;ee--}}c(Y)}function u(S){return S&63}function p(S){return S>>6}function m(S,B,j,ee){for(;B<=j;B++){const N=p(S[B]),Y=u(S[B]);if(N>>Y)throw new Error("Invalid table entry");if(Y>14){const W=ee[N>>Y-14];if(W.len)throw new Error("Invalid table entry");if(W.lit++,W.p){const ae=W.p;W.p=new Array(W.lit);for(let ce=0;ce<W.lit-1;++ce)W.p[ce]=ae[ce]}else W.p=new Array(1);W.p[W.lit-1]=B}else if(Y){let W=0;for(let ae=1<<14-Y;ae>0;ae--){const ce=ee[(N<<14-Y)+W];if(ce.len||ce.p)throw new Error("Invalid table entry");ce.len=Y,ce.lit=B,W++}}}return!0}const f={c:0,lc:0};function g(S,B,j,ee){S=S<<8|X(j,ee),B+=8,f.c=S,f.lc=B}const v={c:0,lc:0};function y(S,B,j,ee,N,Y,W,ae,ce){if(S==B){ee<8&&(g(j,ee,N,Y),j=f.c,ee=f.lc),ee-=8;let _e=j>>ee;if(_e=new Uint8Array([_e])[0],ae.value+_e>ce)return!1;const Re=W[ae.value-1];for(;_e-- >0;)W[ae.value++]=Re}else if(ae.value<ce)W[ae.value++]=S;else return!1;v.c=j,v.lc=ee}function A(S){return S&65535}function _(S){const B=A(S);return B>32767?B-65536:B}const b={a:0,b:0};function x(S,B){const j=_(S),ee=_(B),N=j+(ee&1)+(ee>>1),Y=N,W=N-ee;b.a=Y,b.b=W}function E(S,B){const j=A(S),ee=A(B),N=j-(ee>>1)&65535,Y=ee+N-32768&65535;b.a=Y,b.b=N}function I(S,B,j,ee,N,Y,W){const ae=W<16384,ce=j>N?N:j;let _e=1,Re,Xe;for(;_e<=ce;)_e<<=1;for(_e>>=1,Re=_e,_e>>=1;_e>=1;){Xe=0;const We=Xe+Y*(N-Re),Ke=Y*_e,gt=Y*Re,rt=ee*_e,xt=ee*Re;let Jt,Ui,en,pr;for(;Xe<=We;Xe+=gt){let ki=Xe;const ai=Xe+ee*(j-Re);for(;ki<=ai;ki+=xt){const Pn=ki+rt,ro=ki+Ke,Vn=ro+rt;ae?(x(S[ki+B],S[ro+B]),Jt=b.a,en=b.b,x(S[Pn+B],S[Vn+B]),Ui=b.a,pr=b.b,x(Jt,Ui),S[ki+B]=b.a,S[Pn+B]=b.b,x(en,pr),S[ro+B]=b.a,S[Vn+B]=b.b):(E(S[ki+B],S[ro+B]),Jt=b.a,en=b.b,E(S[Pn+B],S[Vn+B]),Ui=b.a,pr=b.b,E(Jt,Ui),S[ki+B]=b.a,S[Pn+B]=b.b,E(en,pr),S[ro+B]=b.a,S[Vn+B]=b.b)}if(j&_e){const Pn=ki+Ke;ae?x(S[ki+B],S[Pn+B]):E(S[ki+B],S[Pn+B]),Jt=b.a,S[Pn+B]=b.b,S[ki+B]=Jt}}if(N&_e){let ki=Xe;const ai=Xe+ee*(j-Re);for(;ki<=ai;ki+=xt){const Pn=ki+rt;ae?x(S[ki+B],S[Pn+B]):E(S[ki+B],S[Pn+B]),Jt=b.a,S[Pn+B]=b.b,S[ki+B]=Jt}}Re=_e,_e>>=1}return Xe}function T(S,B,j,ee,N,Y,W,ae,ce){let _e=0,Re=0;const Xe=W,We=Math.trunc(ee.value+(N+7)/8);for(;ee.value<We;)for(g(_e,Re,j,ee),_e=f.c,Re=f.lc;Re>=14;){const gt=_e>>Re-14&16383,rt=B[gt];if(rt.len)Re-=rt.len,y(rt.lit,Y,_e,Re,j,ee,ae,ce,Xe),_e=v.c,Re=v.lc;else{if(!rt.p)throw new Error("hufDecode issues");let xt;for(xt=0;xt<rt.lit;xt++){const Jt=u(S[rt.p[xt]]);for(;Re<Jt&&ee.value<We;)g(_e,Re,j,ee),_e=f.c,Re=f.lc;if(Re>=Jt&&p(S[rt.p[xt]])==(_e>>Re-Jt&(1<<Jt)-1)){Re-=Jt,y(rt.p[xt],Y,_e,Re,j,ee,ae,ce,Xe),_e=v.c,Re=v.lc;break}}if(xt==rt.lit)throw new Error("hufDecode issues")}}const Ke=8-N&7;for(_e>>=Ke,Re-=Ke;Re>0;){const gt=B[_e<<14-Re&16383];if(gt.len)Re-=gt.len,y(gt.lit,Y,_e,Re,j,ee,ae,ce,Xe),_e=v.c,Re=v.lc;else throw new Error("hufDecode issues")}return!0}function R(S,B,j,ee,N,Y){const W={value:0},ae=j.value,ce=fe(B,j),_e=fe(B,j);j.value+=4;const Re=fe(B,j);if(j.value+=4,ce<0||ce>=65537||_e<0||_e>=65537)throw new Error("Something wrong with HUF_ENCSIZE");const Xe=new Array(65537),We=new Array(16384);s(We);const Ke=ee-(j.value-ae);if(h(S,j,Ke,ce,_e,Xe),Re>8*(ee-(j.value-ae)))throw new Error("Something wrong with hufUncompress");m(Xe,ce,_e,We),T(Xe,We,S,j,Re,_e,Y,N,W)}function D(S,B,j){for(let ee=0;ee<j;++ee)B[ee]=S[B[ee]]}function M(S){for(let B=1;B<S.length;B++){const j=S[B-1]+S[B]-128;S[B]=j}}function P(S,B){let j=0,ee=Math.floor((S.length+1)/2),N=0;const Y=S.length-1;for(;!(N>Y||(B[N++]=S[j++],N>Y));)B[N++]=S[ee++]}function z(S){let B=S.byteLength;const j=new Array;let ee=0;const N=new DataView(S);for(;B>0;){const Y=N.getInt8(ee++);if(Y<0){const W=-Y;B-=W+1;for(let ae=0;ae<W;ae++)j.push(N.getUint8(ee++))}else{const W=Y;B-=2;const ae=N.getUint8(ee++);for(let ce=0;ce<W+1;ce++)j.push(ae)}}return j}function V(S,B,j,ee,N,Y){let W=new DataView(Y.buffer);const ae=j[S.idx[0]].width,ce=j[S.idx[0]].height,_e=3,Re=Math.floor(ae/8),Xe=Math.ceil(ae/8),We=Math.ceil(ce/8),Ke=ae-(Xe-1)*8,gt=ce-(We-1)*8,rt={value:0},xt=new Array(_e),Jt=new Array(_e),Ui=new Array(_e),en=new Array(_e),pr=new Array(_e);for(let ai=0;ai<_e;++ai)pr[ai]=B[S.idx[ai]],xt[ai]=ai<1?0:xt[ai-1]+Xe*We,Jt[ai]=new Float32Array(64),Ui[ai]=new Uint16Array(64),en[ai]=new Uint16Array(Xe*64);for(let ai=0;ai<We;++ai){let Pn=8;ai==We-1&&(Pn=gt);let ro=8;for(let U=0;U<Xe;++U){U==Xe-1&&(ro=Ke);for(let ne=0;ne<_e;++ne)Ui[ne].fill(0),Ui[ne][0]=N[xt[ne]++],L(rt,ee,Ui[ne]),H(Ui[ne],Jt[ne]),O(Jt[ne]);F(Jt);for(let ne=0;ne<_e;++ne)G(Jt[ne],en[ne],U*64)}let Vn=0;for(let U=0;U<_e;++U){const ne=j[S.idx[U]].type;for(let pe=8*ai;pe<8*ai+Pn;++pe){Vn=pr[U][pe];for(let ge=0;ge<Re;++ge){const le=ge*64+(pe&7)*8;W.setUint16(Vn+0*2*ne,en[U][le+0],!0),W.setUint16(Vn+1*2*ne,en[U][le+1],!0),W.setUint16(Vn+2*2*ne,en[U][le+2],!0),W.setUint16(Vn+3*2*ne,en[U][le+3],!0),W.setUint16(Vn+4*2*ne,en[U][le+4],!0),W.setUint16(Vn+5*2*ne,en[U][le+5],!0),W.setUint16(Vn+6*2*ne,en[U][le+6],!0),W.setUint16(Vn+7*2*ne,en[U][le+7],!0),Vn+=8*2*ne}}if(Re!=Xe)for(let pe=8*ai;pe<8*ai+Pn;++pe){const ge=pr[U][pe]+8*Re*2*ne,le=Re*64+(pe&7)*8;for(let Ze=0;Ze<ro;++Ze)W.setUint16(ge+Ze*2*ne,en[U][le+Ze],!0)}}}const ki=new Uint16Array(ae);W=new DataView(Y.buffer);for(let ai=0;ai<_e;++ai){j[S.idx[ai]].decoded=!0;const Pn=j[S.idx[ai]].type;if(j[ai].type==2)for(let ro=0;ro<ce;++ro){const Vn=pr[ai][ro];for(let U=0;U<ae;++U)ki[U]=W.getUint16(Vn+U*2*Pn,!0);for(let U=0;U<ae;++U)W.setFloat32(Vn+U*2*Pn,Ae(ki[U]),!0)}}}function L(S,B,j){let ee,N=1;for(;N<64;)ee=B[S.value],ee==65280?N=64:ee>>8==255?N+=ee&255:(j[N]=ee,N++),S.value++}function H(S,B){B[0]=Ae(S[0]),B[1]=Ae(S[1]),B[2]=Ae(S[5]),B[3]=Ae(S[6]),B[4]=Ae(S[14]),B[5]=Ae(S[15]),B[6]=Ae(S[27]),B[7]=Ae(S[28]),B[8]=Ae(S[2]),B[9]=Ae(S[4]),B[10]=Ae(S[7]),B[11]=Ae(S[13]),B[12]=Ae(S[16]),B[13]=Ae(S[26]),B[14]=Ae(S[29]),B[15]=Ae(S[42]),B[16]=Ae(S[3]),B[17]=Ae(S[8]),B[18]=Ae(S[12]),B[19]=Ae(S[17]),B[20]=Ae(S[25]),B[21]=Ae(S[30]),B[22]=Ae(S[41]),B[23]=Ae(S[43]),B[24]=Ae(S[9]),B[25]=Ae(S[11]),B[26]=Ae(S[18]),B[27]=Ae(S[24]),B[28]=Ae(S[31]),B[29]=Ae(S[40]),B[30]=Ae(S[44]),B[31]=Ae(S[53]),B[32]=Ae(S[10]),B[33]=Ae(S[19]),B[34]=Ae(S[23]),B[35]=Ae(S[32]),B[36]=Ae(S[39]),B[37]=Ae(S[45]),B[38]=Ae(S[52]),B[39]=Ae(S[54]),B[40]=Ae(S[20]),B[41]=Ae(S[22]),B[42]=Ae(S[33]),B[43]=Ae(S[38]),B[44]=Ae(S[46]),B[45]=Ae(S[51]),B[46]=Ae(S[55]),B[47]=Ae(S[60]),B[48]=Ae(S[21]),B[49]=Ae(S[34]),B[50]=Ae(S[37]),B[51]=Ae(S[47]),B[52]=Ae(S[50]),B[53]=Ae(S[56]),B[54]=Ae(S[59]),B[55]=Ae(S[61]),B[56]=Ae(S[35]),B[57]=Ae(S[36]),B[58]=Ae(S[48]),B[59]=Ae(S[49]),B[60]=Ae(S[57]),B[61]=Ae(S[58]),B[62]=Ae(S[62]),B[63]=Ae(S[63])}function O(S){const B=.5*Math.cos(.7853975),j=.5*Math.cos(3.14159/16),ee=.5*Math.cos(3.14159/8),N=.5*Math.cos(3*3.14159/16),Y=.5*Math.cos(5*3.14159/16),W=.5*Math.cos(3*3.14159/8),ae=.5*Math.cos(7*3.14159/16),ce=new Array(4),_e=new Array(4),Re=new Array(4),Xe=new Array(4);for(let We=0;We<8;++We){const Ke=We*8;ce[0]=ee*S[Ke+2],ce[1]=W*S[Ke+2],ce[2]=ee*S[Ke+6],ce[3]=W*S[Ke+6],_e[0]=j*S[Ke+1]+N*S[Ke+3]+Y*S[Ke+5]+ae*S[Ke+7],_e[1]=N*S[Ke+1]-ae*S[Ke+3]-j*S[Ke+5]-Y*S[Ke+7],_e[2]=Y*S[Ke+1]-j*S[Ke+3]+ae*S[Ke+5]+N*S[Ke+7],_e[3]=ae*S[Ke+1]-Y*S[Ke+3]+N*S[Ke+5]-j*S[Ke+7],Re[0]=B*(S[Ke+0]+S[Ke+4]),Re[3]=B*(S[Ke+0]-S[Ke+4]),Re[1]=ce[0]+ce[3],Re[2]=ce[1]-ce[2],Xe[0]=Re[0]+Re[1],Xe[1]=Re[3]+Re[2],Xe[2]=Re[3]-Re[2],Xe[3]=Re[0]-Re[1],S[Ke+0]=Xe[0]+_e[0],S[Ke+1]=Xe[1]+_e[1],S[Ke+2]=Xe[2]+_e[2],S[Ke+3]=Xe[3]+_e[3],S[Ke+4]=Xe[3]-_e[3],S[Ke+5]=Xe[2]-_e[2],S[Ke+6]=Xe[1]-_e[1],S[Ke+7]=Xe[0]-_e[0]}for(let We=0;We<8;++We)ce[0]=ee*S[16+We],ce[1]=W*S[16+We],ce[2]=ee*S[48+We],ce[3]=W*S[48+We],_e[0]=j*S[8+We]+N*S[24+We]+Y*S[40+We]+ae*S[56+We],_e[1]=N*S[8+We]-ae*S[24+We]-j*S[40+We]-Y*S[56+We],_e[2]=Y*S[8+We]-j*S[24+We]+ae*S[40+We]+N*S[56+We],_e[3]=ae*S[8+We]-Y*S[24+We]+N*S[40+We]-j*S[56+We],Re[0]=B*(S[We]+S[32+We]),Re[3]=B*(S[We]-S[32+We]),Re[1]=ce[0]+ce[3],Re[2]=ce[1]-ce[2],Xe[0]=Re[0]+Re[1],Xe[1]=Re[3]+Re[2],Xe[2]=Re[3]-Re[2],Xe[3]=Re[0]-Re[1],S[0+We]=Xe[0]+_e[0],S[8+We]=Xe[1]+_e[1],S[16+We]=Xe[2]+_e[2],S[24+We]=Xe[3]+_e[3],S[32+We]=Xe[3]-_e[3],S[40+We]=Xe[2]-_e[2],S[48+We]=Xe[1]-_e[1],S[56+We]=Xe[0]-_e[0]}function F(S){for(let B=0;B<64;++B){const j=S[0][B],ee=S[1][B],N=S[2][B];S[0][B]=j+1.5747*N,S[1][B]=j-.1873*ee-.4682*N,S[2][B]=j+1.8556*ee}}function G(S,B,j){for(let ee=0;ee<64;++ee)B[j+ee]=Wd.toHalfFloat(J(S[ee]))}function J(S){return S<=1?Math.sign(S)*Math.pow(Math.abs(S),2.2):Math.sign(S)*Math.pow(t,Math.abs(S)-1)}function K(S){return new DataView(S.array.buffer,S.offset.value,S.size)}function oe(S){const B=S.viewer.buffer.slice(S.offset.value,S.offset.value+S.size),j=new Uint8Array(z(B)),ee=new Uint8Array(j.length);return M(j),P(j,ee),new DataView(ee.buffer)}function we(S){const B=S.array.slice(S.offset.value,S.offset.value+S.size),j=Iy(B),ee=new Uint8Array(j.length);return M(j),P(j,ee),new DataView(ee.buffer)}function De(S){const B=S.viewer,j={value:S.offset.value},ee=new Uint16Array(S.width*S.scanlineBlockSize*(S.channels*S.type)),N=new Uint8Array(8192);let Y=0;const W=new Array(S.channels);for(let gt=0;gt<S.channels;gt++)W[gt]={},W[gt].start=Y,W[gt].end=W[gt].start,W[gt].nx=S.width,W[gt].ny=S.lines,W[gt].size=S.type,Y+=W[gt].nx*W[gt].ny*W[gt].size;const ae=et(B,j),ce=et(B,j);if(ce>=8192)throw new Error("Something is wrong with PIZ_COMPRESSION BITMAP_SIZE");if(ae<=ce)for(let gt=0;gt<ce-ae+1;gt++)N[gt+ae]=ze(B,j);const _e=new Uint16Array(65536),Re=r(N,_e),Xe=fe(B,j);R(S.array,B,j,Xe,ee,Y);for(let gt=0;gt<S.channels;++gt){const rt=W[gt];for(let xt=0;xt<W[gt].size;++xt)I(ee,rt.start+xt,rt.nx,rt.size,rt.ny,rt.nx*rt.size,Re)}D(_e,ee,Y);let We=0;const Ke=new Uint8Array(ee.buffer.byteLength);for(let gt=0;gt<S.lines;gt++)for(let rt=0;rt<S.channels;rt++){const xt=W[rt],Jt=xt.nx*xt.size,Ui=new Uint8Array(ee.buffer,xt.end*2,Jt*2);Ke.set(Ui,We),We+=Jt*2,xt.end+=Jt}return new DataView(Ke.buffer)}function se(S){const B=S.array.slice(S.offset.value,S.offset.value+S.size),j=Iy(B),ee=S.lines*S.channels*S.width,N=S.type==1?new Uint16Array(ee):new Uint32Array(ee);let Y=0,W=0;const ae=new Array(4);for(let ce=0;ce<S.lines;ce++)for(let _e=0;_e<S.channels;_e++){let Re=0;switch(S.type){case 1:ae[0]=Y,ae[1]=ae[0]+S.width,Y=ae[1]+S.width;for(let Xe=0;Xe<S.width;++Xe){const We=j[ae[0]++]<<8|j[ae[1]++];Re+=We,N[W]=Re,W++}break;case 2:ae[0]=Y,ae[1]=ae[0]+S.width,ae[2]=ae[1]+S.width,Y=ae[2]+S.width;for(let Xe=0;Xe<S.width;++Xe){const We=j[ae[0]++]<<24|j[ae[1]++]<<16|j[ae[2]++]<<8;Re+=We,N[W]=Re,W++}break}}return new DataView(N.buffer)}function be(S){const B=S.viewer,j={value:S.offset.value},ee=new Uint8Array(S.width*S.lines*(S.channels*S.type*2)),N={version:Te(B,j),unknownUncompressedSize:Te(B,j),unknownCompressedSize:Te(B,j),acCompressedSize:Te(B,j),dcCompressedSize:Te(B,j),rleCompressedSize:Te(B,j),rleUncompressedSize:Te(B,j),rleRawSize:Te(B,j),totalAcUncompressedCount:Te(B,j),totalDcUncompressedCount:Te(B,j),acCompression:Te(B,j)};if(N.version<2)throw new Error("EXRLoader.parse: "+qt.compression+" version "+N.version+" is unsupported");const Y=new Array;let W=et(B,j)-2;for(;W>0;){const rt=Ie(B.buffer,j),xt=ze(B,j),Jt=xt>>2&3,Ui=(xt>>4)-1,en=new Int8Array([Ui])[0],pr=ze(B,j);Y.push({name:rt,index:en,type:pr,compression:Jt}),W-=rt.length+3}const ae=qt.channels,ce=new Array(S.channels);for(let rt=0;rt<S.channels;++rt){const xt=ce[rt]={},Jt=ae[rt];xt.name=Jt.name,xt.compression=0,xt.decoded=!1,xt.type=Jt.pixelType,xt.pLinear=Jt.pLinear,xt.width=S.width,xt.height=S.lines}const _e={idx:new Array(3)};for(let rt=0;rt<S.channels;++rt){const xt=ce[rt];for(let Jt=0;Jt<Y.length;++Jt){const Ui=Y[Jt];xt.name==Ui.name&&(xt.compression=Ui.compression,Ui.index>=0&&(_e.idx[Ui.index]=rt),xt.offset=rt)}}let Re,Xe,We;if(N.acCompressedSize>0)switch(N.acCompression){case 0:Re=new Uint16Array(N.totalAcUncompressedCount),R(S.array,B,j,N.acCompressedSize,Re,N.totalAcUncompressedCount);break;case 1:const rt=S.array.slice(j.value,j.value+N.totalAcUncompressedCount),xt=Iy(rt);Re=new Uint16Array(xt.buffer),j.value+=N.totalAcUncompressedCount;break}if(N.dcCompressedSize>0){const rt={array:S.array,offset:j,size:N.dcCompressedSize};Xe=new Uint16Array(we(rt).buffer),j.value+=N.dcCompressedSize}if(N.rleRawSize>0){const rt=S.array.slice(j.value,j.value+N.rleCompressedSize),xt=Iy(rt);We=z(xt.buffer),j.value+=N.rleCompressedSize}let Ke=0;const gt=new Array(ce.length);for(let rt=0;rt<gt.length;++rt)gt[rt]=new Array;for(let rt=0;rt<S.lines;++rt)for(let xt=0;xt<ce.length;++xt)gt[xt].push(Ke),Ke+=ce[xt].width*S.type*2;V(_e,gt,ce,Re,Xe,ee);for(let rt=0;rt<ce.length;++rt){const xt=ce[rt];if(!xt.decoded)switch(xt.compression){case 2:let Jt=0,Ui=0;for(let en=0;en<S.lines;++en){let pr=gt[rt][Jt];for(let ki=0;ki<xt.width;++ki){for(let ai=0;ai<2*xt.type;++ai)ee[pr++]=We[Ui+ai*xt.width*xt.height];Ui++}Jt++}break;case 1:default:throw new Error("EXRLoader.parse: unsupported channel compression")}}return new DataView(ee.buffer)}function Ie(S,B){const j=new Uint8Array(S);let ee=0;for(;j[B.value+ee]!=0;)ee+=1;const N=new TextDecoder().decode(j.slice(B.value,B.value+ee));return B.value=B.value+ee+1,N}function Je(S,B,j){const ee=new TextDecoder().decode(new Uint8Array(S).slice(B.value,B.value+j));return B.value=B.value+j,ee}function $e(S,B){const j=lt(S,B),ee=fe(S,B);return[j,ee]}function Oe(S,B){const j=fe(S,B),ee=fe(S,B);return[j,ee]}function lt(S,B){const j=S.getInt32(B.value,!0);return B.value=B.value+4,j}function fe(S,B){const j=S.getUint32(B.value,!0);return B.value=B.value+4,j}function X(S,B){const j=S[B.value];return B.value=B.value+1,j}function ze(S,B){const j=S.getUint8(B.value);return B.value=B.value+1,j}const Te=function(S,B){let j;return"getBigInt64"in DataView.prototype?j=Number(S.getBigInt64(B.value,!0)):j=S.getUint32(B.value+4,!0)+Number(S.getUint32(B.value,!0)<<32),B.value+=8,j};function Me(S,B){const j=S.getFloat32(B.value,!0);return B.value+=4,j}function Qe(S,B){return Wd.toHalfFloat(Me(S,B))}function Ae(S){const B=(S&31744)>>10,j=S&1023;return(S>>15?-1:1)*(B?B===31?j?NaN:1/0:Math.pow(2,B-15)*(1+j/1024):6103515625e-14*(j/1024))}function et(S,B){const j=S.getUint16(B.value,!0);return B.value+=2,j}function ct(S,B){return Ae(et(S,B))}function Tt(S,B,j,ee){const N=j.value,Y=[];for(;j.value<N+ee-1;){const W=Ie(B,j),ae=lt(S,j),ce=ze(S,j);j.value+=3;const _e=lt(S,j),Re=lt(S,j);Y.push({name:W,pixelType:ae,pLinear:ce,xSampling:_e,ySampling:Re})}return j.value+=1,Y}function Q(S,B){const j=Me(S,B),ee=Me(S,B),N=Me(S,B),Y=Me(S,B),W=Me(S,B),ae=Me(S,B),ce=Me(S,B),_e=Me(S,B);return{redX:j,redY:ee,greenX:N,greenY:Y,blueX:W,blueY:ae,whiteX:ce,whiteY:_e}}function k(S,B){const j=["NO_COMPRESSION","RLE_COMPRESSION","ZIPS_COMPRESSION","ZIP_COMPRESSION","PIZ_COMPRESSION","PXR24_COMPRESSION","B44_COMPRESSION","B44A_COMPRESSION","DWAA_COMPRESSION","DWAB_COMPRESSION"],ee=ze(S,B);return j[ee]}function he(S,B){const j=fe(S,B),ee=fe(S,B),N=fe(S,B),Y=fe(S,B);return{xMin:j,yMin:ee,xMax:N,yMax:Y}}function Ee(S,B){const j=["INCREASING_Y"],ee=ze(S,B);return j[ee]}function Le(S,B){const j=Me(S,B),ee=Me(S,B);return[j,ee]}function Pe(S,B){const j=Me(S,B),ee=Me(S,B),N=Me(S,B);return[j,ee,N]}function vt(S,B,j,ee,N){if(ee==="string"||ee==="stringvector"||ee==="iccProfile")return Je(B,j,N);if(ee==="chlist")return Tt(S,B,j,N);if(ee==="chromaticities")return Q(S,j);if(ee==="compression")return k(S,j);if(ee==="box2i")return he(S,j);if(ee==="lineOrder")return Ee(S,j);if(ee==="float")return Me(S,j);if(ee==="v2f")return Le(S,j);if(ee==="v3f")return Pe(S,j);if(ee==="int")return lt(S,j);if(ee==="rational")return $e(S,j);if(ee==="timecode")return Oe(S,j);if(ee==="preview")return j.value+=N,"skipped";j.value+=N}function ht(S,B,j){const ee={};if(S.getUint32(0,!0)!=20000630)throw new Error("THREE.EXRLoader: Provided file doesn't appear to be in OpenEXR format.");ee.version=S.getUint8(4);const N=S.getUint8(5);ee.spec={singleTile:!!(N&2),longName:!!(N&4),deepFormat:!!(N&8),multiPart:!!(N&16)},j.value=8;let Y=!0;for(;Y;){const W=Ie(B,j);if(W==0)Y=!1;else{const ae=Ie(B,j),ce=fe(S,j),_e=vt(S,B,j,ae,ce);_e===void 0?console.warn(`THREE.EXRLoader: Skipped unknown header attribute type '${ae}'.`):ee[W]=_e}}if(N&-5)throw console.error("THREE.EXRHeader:",ee),new Error("THREE.EXRLoader: Provided file is currently unsupported.");return ee}function je(S,B,j,ee,N){const Y={size:0,viewer:B,array:j,offset:ee,width:S.dataWindow.xMax-S.dataWindow.xMin+1,height:S.dataWindow.yMax-S.dataWindow.yMin+1,channels:S.channels.length,bytesPerLine:null,lines:null,inputSize:null,type:S.channels[0].pixelType,uncompress:null,getter:null,format:null,colorSpace:Ri};switch(S.compression){case"NO_COMPRESSION":Y.lines=1,Y.uncompress=K;break;case"RLE_COMPRESSION":Y.lines=1,Y.uncompress=oe;break;case"ZIPS_COMPRESSION":Y.lines=1,Y.uncompress=we;break;case"ZIP_COMPRESSION":Y.lines=16,Y.uncompress=we;break;case"PIZ_COMPRESSION":Y.lines=32,Y.uncompress=De;break;case"PXR24_COMPRESSION":Y.lines=16,Y.uncompress=se;break;case"DWAA_COMPRESSION":Y.lines=32,Y.uncompress=be;break;case"DWAB_COMPRESSION":Y.lines=256,Y.uncompress=be;break;default:throw new Error("EXRLoader.parse: "+S.compression+" is unsupported")}if(Y.scanlineBlockSize=Y.lines,Y.type==1)switch(N){case kn:Y.getter=ct,Y.inputSize=2;break;case rr:Y.getter=et,Y.inputSize=2;break}else if(Y.type==2)switch(N){case kn:Y.getter=Me,Y.inputSize=4;break;case rr:Y.getter=Qe,Y.inputSize=4}else throw new Error("EXRLoader.parse: unsupported pixelType "+Y.type+" for "+S.compression+".");Y.blockCount=(S.dataWindow.yMax+1)/Y.scanlineBlockSize;for(let ae=0;ae<Y.blockCount;ae++)Te(B,ee);Y.outputChannels=Y.channels==3?4:Y.channels;const W=Y.width*Y.height*Y.outputChannels;switch(N){case kn:Y.byteArray=new Float32Array(W),Y.channels<Y.outputChannels&&Y.byteArray.fill(1,0,W);break;case rr:Y.byteArray=new Uint16Array(W),Y.channels<Y.outputChannels&&Y.byteArray.fill(15360,0,W);break;default:console.error("THREE.EXRLoader: unsupported type: ",N);break}return Y.bytesPerLine=Y.width*Y.inputSize*Y.channels,Y.outputChannels==4?(Y.format=Yi,Y.colorSpace=Ri):(Y.format=Zm,Y.colorSpace=lo),Y}const Ve=new DataView(e),St=new Uint8Array(e),Ue={value:0},qt=ht(Ve,e,Ue),Fe=je(qt,Ve,St,Ue,this.type),_t={value:0},ut={R:0,G:1,B:2,A:3,Y:0};for(let S=0;S<Fe.height/Fe.scanlineBlockSize;S++){const B=fe(Ve,Ue);Fe.size=fe(Ve,Ue),Fe.lines=B+Fe.scanlineBlockSize>Fe.height?Fe.height-B:Fe.scanlineBlockSize;const j=Fe.size<Fe.lines*Fe.bytesPerLine?Fe.uncompress(Fe):K(Fe);Ue.value+=Fe.size;for(let ee=0;ee<Fe.scanlineBlockSize;ee++){const N=ee+S*Fe.scanlineBlockSize;if(N>=Fe.height)break;for(let Y=0;Y<Fe.channels;Y++){const W=ut[qt.channels[Y].name];for(let ae=0;ae<Fe.width;ae++){_t.value=(ee*(Fe.channels*Fe.width)+Y*Fe.width+ae)*Fe.inputSize;const ce=(Fe.height-1-N)*(Fe.width*Fe.outputChannels)+ae*Fe.outputChannels+W;Fe.byteArray[ce]=Fe.getter(j,_t)}}}}return{header:qt,width:Fe.width,height:Fe.height,data:Fe.byteArray,format:Fe.format,colorSpace:Fe.colorSpace,type:this.type}}setDataType(e){return this.type=e,this}load(e,t,r,s){function o(a,l){a.colorSpace=l.colorSpace,a.minFilter=Pt,a.magFilter=Pt,a.generateMipmaps=!1,a.flipY=!1,t&&t(a,l)}return super.load(e,o,r,s)}}const wde=Object.freeze(Object.defineProperty({__proto__:null,EXRLoader:oA},Symbol.toStringTag,{value:"Module"}));class uS extends hI{constructor(e){super(e),this.type=rr}parse(e){const t=function(A,_){switch(A){case 1:throw new Error("THREE.RGBELoader: Read Error: "+(_||""));case 2:throw new Error("THREE.RGBELoader: Write Error: "+(_||""));case 3:throw new Error("THREE.RGBELoader: Bad File Format: "+(_||""));default:case 4:throw new Error("THREE.RGBELoader: Memory Error: "+(_||""))}},r=`
5237
5237
  `,s=function(A,_,b){_=_||1024;let x=A.pos,E=-1,I=0,T="",R=String.fromCharCode.apply(null,new Uint16Array(A.subarray(x,x+128)));for(;0>(E=R.indexOf(r))&&I<_&&x<A.byteLength;)T+=R,I+=R.length,x+=128,R+=String.fromCharCode.apply(null,new Uint16Array(A.subarray(x,x+128)));return-1<E?(b!==!1&&(A.pos+=I+E+1),T+R.slice(0,E)):!1},o=function(A){const _=/^#\?(\S+)/,b=/^\s*GAMMA\s*=\s*(\d+(\.\d+)?)\s*$/,x=/^\s*EXPOSURE\s*=\s*(\d+(\.\d+)?)\s*$/,E=/^\s*FORMAT=(\S+)\s*$/,I=/^\s*\-Y\s+(\d+)\s+\+X\s+(\d+)\s*$/,T={valid:0,string:"",comments:"",programtype:"RGBE",format:"",gamma:1,exposure:1,width:0,height:0};let R,D;for((A.pos>=A.byteLength||!(R=s(A)))&&t(1,"no header found"),(D=R.match(_))||t(3,"bad initial token"),T.valid|=1,T.programtype=D[1],T.string+=R+`
5238
5238
  `;R=s(A),R!==!1;){if(T.string+=R+`
@@ -5266,7 +5266,7 @@ TEX `+r.texture_lod;if(HB=="density"&&(_+=`
5266
5266
  `+(A/l.lastScreenCoverage).toFixed(0)+` dens
5267
5267
  `+(l.lastScreenCoverage*100).toFixed(1)+`% cov
5268
5268
  `+(l.lastCentrality*100).toFixed(1)+`% centr
5269
- `+(dS.min.x.toFixed(2)+"-"+dS.max.x.toFixed(2)+"x"+dS.min.y.toFixed(2)+"-"+dS.max.y.toFixed(2))+" scr"),l.lastScreenCoverage>.1){const b=e,x=b.worldForward,E=b.worldPosition,I=pi(x).multiplyScalar(m*.7).add(p),T=I.distanceTo(E),R=f[Math.min(f.length-1,Math.max(0,c))]+"88",D=this.context.domHeight>0?screen.height/this.context.domHeight:1,M=e.isPerspectiveCamera?Math.tan(e.fov*Math.PI/180/2):1;At.DrawLabel(I,_,T*.012*D*M,void 0,16777215,R)}}}}}const mS=te("debugphysics"),v8=new ds;class ml{constructor(){d(this,"ray"),d(this,"cam"),d(this,"screenPoint"),d(this,"raycaster"),d(this,"results"),d(this,"targets"),d(this,"recursive",!0),d(this,"minDistance"),d(this,"maxDistance"),d(this,"lineThreshold"),d(this,"layerMask"),d(this,"ignore"),d(this,"testObject")}screenPointFromOffset(e,t){this.screenPoint===void 0&&(this.screenPoint=new Z),this.screenPoint.x=e/window.innerWidth*2-1,this.screenPoint.y=-(t/window.innerHeight)*2+1}setLayer(e){v8.set(e),this.layerMask=v8}setMask(e){this.layerMask||(this.layerMask=new ds);const t=this.layerMask;t?t.mask=e:this.layerMask=e}}d(ml,"AllLayers",4294967295);class y8{constructor(e,t,r){d(this,"distance"),d(this,"point"),d(this,"object"),this.object=e,this.distance=t,this.point=r}}class A8{constructor(e){d(this,"context"),d(this,"engine"),d(this,"raycaster",new pp),d(this,"defaultRaycastOptions",new ml),d(this,"targetBuffer",new Array(1)),d(this,"defaultThresholds",{Mesh:{},Line:{threshold:-1},LOD:{},Points:{threshold:0},Sprite:{}}),d(this,"sphereResults",new Array),d(this,"sphereMask",new ds),d(this,"tempBoundingBox",new xi),this.context=e}raycastPhysicsFast(e,t=void 0,r=1/0,s=!0){var o;return((o=this.context.physics.engine)==null?void 0:o.raycast(e,t,{maxDistance:r,solid:s}))??null}raycastPhysicsFastAndGetNormal(e,t=void 0,r=1/0,s=!0){var o;return((o=this.context.physics.engine)==null?void 0:o.raycastAndGetNormal(e,t,{maxDistance:r,solid:s}))??null}sphereOverlapPhysics(e,t){var r;return((r=this.context.physics.engine)==null?void 0:r.sphereOverlap(e,t))??null}sphereOverlap(e,t,r=!0){if(this.sphereResults.length=0,!this.context.scene)return this.sphereResults;const s=new wn(e,t),o=this.sphereMask;o.enableAll(),o.disable(2);for(const a of this.context.scene.children)this.onSphereOverlap(a,s,o,this.sphereResults,r);return this.sphereResults.sort((a,l)=>a.distance-l.distance)}onSphereOverlap(e,t,r,s,o){if(e.type==="Mesh"&&e.layers.test(r)&&!At.isGizmo(e)){const a=e,l=a.geometry;if(l&&(l.boundingBox||l.computeBoundingBox(),l.boundingBox)){a.matrixWorldNeedsUpdate&&a.updateMatrixWorld();const c=this.tempBoundingBox.copy(l.boundingBox).applyMatrix4(a.matrixWorld);if(t.intersectsBox(c)){const h=Bt(e),u=h.distanceTo(t.center),p=new y8(e,u,h);if(s.push(p),!o)return}}}if(e.children)for(const a of e.children){const l=s.length;if(this.onSphereOverlap(a,t,r,s,o),l!=s.length&&!o)return}}raycastFromRay(e,t=null){const r=t??this.defaultRaycastOptions;r.ray=e;const s=this.raycast(r);return r===this.defaultRaycastOptions&&(r.ray=void 0),s}raycast(e=null){e||(e=this.defaultRaycastOptions);const t=e.screenPoint??this.context.input.mousePositionRC,r=e.raycaster??this.raycaster;if(r.near=e.minDistance??0,r.far=e.maxDistance??1/0,r.params=this.defaultThresholds,e.lineThreshold===void 0&&(e.lineThreshold=-1),r.params.Line={threshold:e.lineThreshold},e.ray)r.ray.copy(e.ray);else{const l=e.cam??this.context.mainCamera;if(!l)return mS&&console.error("Can not perform raycast - no main camera found"),this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),this.defaultRaycastOptions.results??[];const c=this.context.xrCamera;this.context.isInXR&&c instanceof BT&&c.cameras.length>0?r.setFromCamera(t,c.cameras[0]):r.setFromCamera(t,l)}let s=e.targets;s||(s=this.targetBuffer,s.length=1,s[0]=this.context.scene);let o=e.results;this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),o||(this.defaultRaycastOptions.results||(this.defaultRaycastOptions.results=new Array),o=this.defaultRaycastOptions.results),e.layerMask!==void 0?e.layerMask instanceof ds?r.layers.mask=e.layerMask.mask:r.layers.mask=e.layerMask:(r.layers.enableAll(),r.layers.disable(2)),mS&&(At.DrawRay(r.ray.origin,r.ray.direction,16711680,2),console.time("raycast")),o.length=0,this.intersect(this.raycaster,s,o,e),o.sort((l,c)=>l.distance-c.distance);const a=e.ignore;return a!==void 0&&a.length>0&&(o=o.filter(l=>!a.includes(l.object))),mS&&(console.timeEnd("raycast"),console.warn("#"+this.context.time.frame+", hits:",o!=null&&o.length?[...o]:"nothing")),o}intersect(e,t,r,s){var o;for(const a of t){if(a.visible===!1||At.isGizmo(a)||s.lineThreshold!==void 0&&s.lineThreshold<0&&a instanceof Sn)continue;const l=(o=s.testObject)==null?void 0:o.call(s,a);if(l!==!1){if(l!=="continue in children"){const c=a,h=c.geometry;if(h){const u=wy(a);u&&(c.geometry=u);const p=r.length;e.intersectObject(a,!1,r),mS&&r.length!=p&&At.DrawWireMesh({mesh:a,depthTest:!1,duration:.2,color:u?8969557:7798784}),c.geometry=h}}s.recursive!==!1&&this.intersect(e,a.children,r,s)}}return r}}const Tde=te("debugplayerview");var Wu=(n=>(n.Browser="browser",n.Headset="headset",n.Handheld="handheld",n))(Wu||{});class b8{constructor(e,t){d(this,"userId"),d(this,"context"),d(this,"viewDevice","browser"),d(this,"removed",!1),d(this,"_object"),this.userId=e,this.context=t}get currentObject(){return this._object}set currentObject(e){this._object=e}get isConnected(){return this.context.connection.userIsInRoom(this.userId)}}class _8{constructor(e){d(this,"context"),d(this,"playerViews",new Map),this.context=e}setPlayerView(e,t,r){let s=this.playerViews.get(e);s||(s=new b8(e,this.context),this.playerViews.set(e,s)),s.viewDevice=r,s.currentObject=t,s.removed=!1}getPlayerView(e){if(!!e){if(!this.context.connection.userIsInRoom(e)){this.playerViews.delete(e);return}return this.playerViews.get(e)}}removePlayerView(e,t){const r=this.playerViews.get(e);r?.viewDevice===t&&(Tde&&console.log("REMOVE",e),r.removed=!0,this.playerViews.delete(e))}}new ys;const lA=new Uint8Array(4);lA[0]=255,lA[1]=255,lA[2]=255,lA[3]=255;const Ide=new Ro(lA,1,1,Yi);function WB(n,e=1){const t="alpha"in n,r=e*e,s=new Uint8Array(4*r),o=Math.floor(n.r*255),a=Math.floor(n.g*255),l=Math.floor(n.b*255);for(let h=0;h<r;h++){const u=h*4;s[u+0]=o,s[u+1]=a,s[u+2]=l,t?s[u+3]=Math.floor(n.alpha*255):s[u+3]=255}const c=new Ro(s,e,e);return c.needsUpdate=!0,c}function Rde(n,e,t,r=1,s=3){const o=r*s,a=[n,e,t],l=a.length,c=new Uint8Array(4*l*o),h=new xe;for(let p=0;p<s;p++){const m=Math.floor(p/s*l),f=it.clamp(m+1,0,l-1),g=a[m],v=a[f],y=p/s*l%1;h.lerpColors(g,v,y);const A=Math.floor(h.r*255),_=Math.floor(h.g*255),b=Math.floor(h.b*255);for(let x=0;x<r;x++){const E=(p*r+x)*4;c[E+0]=A,c[E+1]=_,c[E+2]=b,c[E+3]=255}}const u=new Ro(c,r,s);return u.needsUpdate=!0,u}function fS(n,e){const t=n.elements;e||(e=[]),e.length=0;for(let r=0;r<16;r+=4){const s=t[r],o=t[r+1],a=t[r+2],l=t[r+3],c=new Ye(s,o,a,l);e.push(c)}return e}const XB=[],x8=[];function Pde(n,e){if(XB.length===0)for(let t=0;t<27;t++)XB.push(0);e||(e=XB);for(let t=0;t<27;t++)x8[t]=e[t];e=x8,n.unity_SHAr={value:new Ye(e[9],e[3],e[6],e[0])},n.unity_SHBr={value:new Ye(e[12],e[15],e[18],e[21])},n.unity_SHAg={value:new Ye(e[10],e[4],e[7],e[1])},n.unity_SHBg={value:new Ye(e[13],e[16],e[19],e[22])},n.unity_SHAb={value:new Ye(e[11],e[5],e[8],e[2])},n.unity_SHBb={value:new Ye(e[14],e[17],e[20],e[23])},n.unity_SHC={value:new Ye(e[24],e[25],e[26],1)}}class Bde{constructor(e,t,r){d(this,"vertexShader"),d(this,"fragmentShader"),d(this,"technique"),this.vertexShader=e,this.fragmentShader=t,this.technique=r}}async function kde(n,e){if(!n)return console.error("Can not find technique: no shader data"),null;const t=n.programs[e],r=t.vertexShader,s=t.fragmentShader;if(r!==void 0&&s!==void 0){const o=n.shaders[r],a=n.shaders[s];if(o.uri&&a.uri||o.code&&a.code){if(!o.code&&o.uri&&await w8(o),!a.code&&a.uri&&await w8(a),!o.code||!a.code)return null;const l=n.techniques[e];return new Bde(o.code,a.code,l)}}return console.error("Shader technique not found",e),null}async function w8(n){const e=n.uri;if(e)if(e.endsWith(".glsl")){const t=await new ys().loadAsync(e);n.code=t.toString()}else n.code=Dde(n.uri)}function Dde(n){return decodeURIComponent(Array.prototype.map.call(atob(n),function(e){return"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)}).join(""))}const fl=te("debugenvlight");var Ng=(n=>(n[n.Skybox=0]="Skybox",n[n.Trilight=1]="Trilight",n[n.Flat=3]="Flat",n[n.Custom=4]="Custom",n))(Ng||{}),gS=(n=>(n[n.Skybox=0]="Skybox",n[n.Custom=1]="Custom",n))(gS||{});class S8{constructor(e){d(this,"context"),d(this,"_currentLightSettingsId"),d(this,"_sceneLightSettings"),d(this,"_timevec4",new Ye),d(this,"__currentReflectionId",null),d(this,"_lighting",{}),this.context=e,this.context.pre_update_callbacks.push(this.preUpdate.bind(this))}preUpdate(){const e=this.context.time;this._timevec4.x=e.time,this._timevec4.y=Math.sin(e.time),this._timevec4.z=Math.cos(e.time),this._timevec4.w=e.deltaTime}get timeVec4(){return this._timevec4}get environmentIntensity(){if(!this._sceneLightSettings||!this._currentLightSettingsId)return 1;const e=this._sceneLightSettings.get(this._currentLightSettingsId);return e?e.ambientIntensity:1}get sceneLightSettings(){var e;return(e=this._sceneLightSettings)==null?void 0:e.values()}enable(e){var t;e instanceof ti&&(e=e.uri);const r=(t=this._sceneLightSettings)==null?void 0:t.get(e);return r?(fl&&console.log("Enable scene light settings",e,r),e!==this._currentLightSettingsId&&this._currentLightSettingsId&&this.disable(this._currentLightSettingsId),this._currentLightSettingsId=e,r.enabled=!0,!0):(fl&&console.warn("No light settings found for",e),!1)}disable(e){var t;if(e instanceof ti&&(e=e.uri),e==null)return!1;const r=(t=this._sceneLightSettings)==null?void 0:t.get(e);return r?(fl&&console.log("Disable scene light settings",e,r),r.enabled=!1,!0):!1}disableCurrent(){if(this._currentLightSettingsId){const e=this._currentLightSettingsId;return this.disable(this._currentLightSettingsId),e}return null}internalRegisterSceneLightSettings(e){const t=e.sourceId;if(!t){console.error("Missing source id for scene light settings, can not register:",e);return}fl&&console.log("Register "+e?.sourceId+" lighting",e),this._sceneLightSettings||(this._sceneLightSettings=new Map),this._sceneLightSettings.set(t,e)}internalUnregisterSceneLightSettings(e){const t=e.sourceId;if(!t){console.error("Missing source id for scene light settings, can not unregister:",e);return}fl&&console.log("Unregister "+e?.sourceId+" lighting",e),this._sceneLightSettings&&this._sceneLightSettings.delete(t)}internalRegisterReflection(e,t){fl&&console.log("Register reflection",e,t);const r=new C8(this.context,t,1);this._lighting[e]=r}internalGetReflection(e){return this._lighting[e]}internalEnableReflection(e){var t;this.__currentReflectionId=e;const r=(t=this._sceneLightSettings)==null?void 0:t.get(e);switch(fl&&console.log("Enable reflection",e,r?Ng[r.ambientMode]:"Unknown ambient mode",r),r?.ambientMode){case 0:case 4:const s=this.internalGetReflection(e);if(s&&s.Source){fl&&console.log("Setting environment reflection",s);const o=this.context.scene,a=s.Source;a.mapping=so,o.environment=a;return}else fl&&console.warn("Could not find reflection for source",e);break}if(r?.environmentReflectionSource===1)switch(r?.ambientMode){case 1:if(r.ambientTrilight){const s=r.ambientTrilight,o=Rde(s[0],s[1],s[2],64,64);o.colorSpace=ft,o.mapping=so,this.context.scene.environment=o}else console.error("Missing ambient trilight",r.sourceId);return;case 3:if(r.ambientLight){const s=WB(r.ambientLight,64);s.colorSpace=ft,s.mapping=so,this.context.scene.environment=s}else console.error("Missing ambientlight",r.sourceId);return;default:return}}internalDisableReflection(e){if(e&&e!==this.__currentReflectionId){fl&&console.log("Not disabling reflection for",e,"because it is not the current light settings id",this.__currentReflectionId);return}fl&&console.log("Disable reflection",e);const t=this.context.scene;t.environment=null}}class C8{constructor(e,t,r=1){d(this,"_source"),this._source=t,t.mapping=so}get Source(){return this._source}}const E8=te("timescale");let qB=1;typeof E8=="number"&&(qB=E8);class M8{constructor(){d(this,"_time",0),d(this,"_deltaTime",0),d(this,"_deltaTimeUnscaled",0),d(this,"timeScale",1),d(this,"_frame",0),d(this,"clock",new fI),d(this,"_smoothedFps",0),d(this,"_smoothedDeltaTime",0),d(this,"_fpsSamples",[]),d(this,"_fpsSampleIndex",0),typeof qB=="number"&&(this.timeScale=qB)}get time(){return this._time}set time(e){this._time=e}get deltaTime(){return this._deltaTime}set deltaTime(e){this._deltaTime=e}get deltaTimeUnscaled(){return this._deltaTimeUnscaled}get frame(){return this._frame}set frame(e){this._frame=e}get frameCount(){return this.frame}get realtimeSinceStartup(){return this.clock.elapsedTime}get smoothedFps(){return this._smoothedFps}get smoothedDeltaTime(){return 1/this._smoothedFps}update(){this.deltaTime=this.clock.getDelta(),this.deltaTime=Math.min(.1,this.deltaTime),this._deltaTimeUnscaled=this.deltaTime,this.deltaTime<=0&&(this.deltaTime=1e-12),this.deltaTime*=this.timeScale,this.frame+=1,this.time+=this.deltaTime,this._fpsSamples.length<60?this._fpsSamples.push(this.deltaTime):this._fpsSamples[this._fpsSampleIndex++%60]=this.deltaTime;let e=0;for(let t=0;t<this._fpsSamples.length;t++)e+=this._fpsSamples[t];this._smoothedDeltaTime=e/this._fpsSamples.length,this._smoothedFps=1/this._smoothedDeltaTime}}let T8=!1;function I8(n){T8||(T8=!0,Ode(),Lde())}I8();function Ode(){const n=`
5269
+ `+(dS.min.x.toFixed(2)+"-"+dS.max.x.toFixed(2)+"x"+dS.min.y.toFixed(2)+"-"+dS.max.y.toFixed(2))+" scr"),l.lastScreenCoverage>.1){const b=e,x=b.worldForward,E=b.worldPosition,I=pi(x).multiplyScalar(m*.7).add(p),T=I.distanceTo(E),R=f[Math.min(f.length-1,Math.max(0,c))]+"88",D=this.context.domHeight>0?screen.height/this.context.domHeight:1,M=e.isPerspectiveCamera?Math.tan(e.fov*Math.PI/180/2):1;At.DrawLabel(I,_,T*.012*D*M,void 0,16777215,R)}}}}}const mS=te("debugphysics"),v8=new ds;class ml{constructor(){d(this,"ray"),d(this,"cam"),d(this,"screenPoint"),d(this,"raycaster"),d(this,"results"),d(this,"targets"),d(this,"recursive",!0),d(this,"minDistance"),d(this,"maxDistance"),d(this,"lineThreshold"),d(this,"layerMask"),d(this,"ignore"),d(this,"testObject")}screenPointFromOffset(e,t){this.screenPoint===void 0&&(this.screenPoint=new Z),this.screenPoint.x=e/window.innerWidth*2-1,this.screenPoint.y=-(t/window.innerHeight)*2+1}setLayer(e){v8.set(e),this.layerMask=v8}setMask(e){this.layerMask||(this.layerMask=new ds);const t=this.layerMask;t?t.mask=e:this.layerMask=e}}d(ml,"AllLayers",4294967295);class y8{constructor(e,t,r){d(this,"distance"),d(this,"point"),d(this,"object"),this.object=e,this.distance=t,this.point=r}}class A8{constructor(e){d(this,"context"),d(this,"engine"),d(this,"raycaster",new pp),d(this,"defaultRaycastOptions",new ml),d(this,"targetBuffer",new Array(1)),d(this,"defaultThresholds",{Mesh:{},Line:{threshold:-1},LOD:{},Points:{threshold:0},Sprite:{}}),d(this,"sphereResults",new Array),d(this,"sphereMask",new ds),d(this,"tempBoundingBox",new xi),this.context=e}raycastPhysicsFast(e,t=void 0,r=1/0,s=!0){var o;return((o=this.context.physics.engine)==null?void 0:o.raycast(e,t,{maxDistance:r,solid:s}))??null}raycastPhysicsFastAndGetNormal(e,t=void 0,r=1/0,s=!0){var o;return((o=this.context.physics.engine)==null?void 0:o.raycastAndGetNormal(e,t,{maxDistance:r,solid:s}))??null}sphereOverlapPhysics(e,t){var r;return((r=this.context.physics.engine)==null?void 0:r.sphereOverlap(e,t))??null}sphereOverlap(e,t,r=!0){if(this.sphereResults.length=0,!this.context.scene)return this.sphereResults;const s=new wn(e,t),o=this.sphereMask;o.enableAll(),o.disable(2);for(const a of this.context.scene.children)this.onSphereOverlap(a,s,o,this.sphereResults,r);return this.sphereResults.sort((a,l)=>a.distance-l.distance)}onSphereOverlap(e,t,r,s,o){if(e.type==="Mesh"&&e.layers.test(r)&&!At.isGizmo(e)){const a=e,l=a.geometry;if(l&&(l.boundingBox||l.computeBoundingBox(),l.boundingBox)){a.matrixWorldNeedsUpdate&&a.updateMatrixWorld();const c=this.tempBoundingBox.copy(l.boundingBox).applyMatrix4(a.matrixWorld);if(t.intersectsBox(c)){const h=Bt(e),u=h.distanceTo(t.center),p=new y8(e,u,h);if(s.push(p),!o)return}}}if(e.children)for(const a of e.children){const l=s.length;if(this.onSphereOverlap(a,t,r,s,o),l!=s.length&&!o)return}}raycastFromRay(e,t=null){const r=t??this.defaultRaycastOptions;r.ray=e;const s=this.raycast(r);return r===this.defaultRaycastOptions&&(r.ray=void 0),s}raycast(e=null){e||(e=this.defaultRaycastOptions);const t=e.screenPoint??this.context.input.mousePositionRC,r=e.raycaster??this.raycaster;if(r.near=e.minDistance??0,r.far=e.maxDistance??1/0,r.params=this.defaultThresholds,e.lineThreshold===void 0&&(e.lineThreshold=-1),r.params.Line={threshold:e.lineThreshold},e.ray)r.ray.copy(e.ray);else{const l=e.cam??this.context.mainCamera;if(!l)return mS&&console.error("Can not perform raycast - no main camera found"),this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),this.defaultRaycastOptions.results??[];const c=this.context.xrCamera;this.context.isInXR&&c instanceof BT&&c.cameras.length>0?r.setFromCamera(t,c.cameras[0]):r.setFromCamera(t,l)}let s=e.targets;s||(s=this.targetBuffer,s.length=1,s[0]=this.context.scene);let o=e.results;this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),o||(this.defaultRaycastOptions.results||(this.defaultRaycastOptions.results=new Array),o=this.defaultRaycastOptions.results),e.layerMask!==void 0?e.layerMask instanceof ds?r.layers.mask=e.layerMask.mask:r.layers.mask=e.layerMask:(r.layers.enableAll(),r.layers.disable(2)),mS&&(At.DrawRay(r.ray.origin,r.ray.direction,16711680,2),console.time("raycast")),o.length=0,this.intersect(this.raycaster,s,o,e),o.sort((l,c)=>l.distance-c.distance);const a=e.ignore;return a!==void 0&&a.length>0&&(o=o.filter(l=>!a.includes(l.object))),mS&&(console.timeEnd("raycast"),console.warn("#"+this.context.time.frame+", hits:",o!=null&&o.length?[...o]:"nothing")),o}intersect(e,t,r,s){var o;for(const a of t){if(!a||a.visible===!1||At.isGizmo(a)||s.lineThreshold!==void 0&&s.lineThreshold<0&&a instanceof Sn)continue;const l=(o=s.testObject)==null?void 0:o.call(s,a);if(l!==!1){if(l!=="continue in children"){const c=a,h=c.geometry;if(h){const u=wy(a);u&&(c.geometry=u);const p=r.length;e.intersectObject(a,!1,r),mS&&r.length!=p&&At.DrawWireMesh({mesh:a,depthTest:!1,duration:.2,color:u?8969557:7798784}),c.geometry=h}}s.recursive!==!1&&this.intersect(e,a.children,r,s)}}return r}}const Tde=te("debugplayerview");var Wu=(n=>(n.Browser="browser",n.Headset="headset",n.Handheld="handheld",n))(Wu||{});class b8{constructor(e,t){d(this,"userId"),d(this,"context"),d(this,"viewDevice","browser"),d(this,"removed",!1),d(this,"_object"),this.userId=e,this.context=t}get currentObject(){return this._object}set currentObject(e){this._object=e}get isConnected(){return this.context.connection.userIsInRoom(this.userId)}}class _8{constructor(e){d(this,"context"),d(this,"playerViews",new Map),this.context=e}setPlayerView(e,t,r){let s=this.playerViews.get(e);s||(s=new b8(e,this.context),this.playerViews.set(e,s)),s.viewDevice=r,s.currentObject=t,s.removed=!1}getPlayerView(e){if(!!e){if(!this.context.connection.userIsInRoom(e)){this.playerViews.delete(e);return}return this.playerViews.get(e)}}removePlayerView(e,t){const r=this.playerViews.get(e);r?.viewDevice===t&&(Tde&&console.log("REMOVE",e),r.removed=!0,this.playerViews.delete(e))}}new ys;const lA=new Uint8Array(4);lA[0]=255,lA[1]=255,lA[2]=255,lA[3]=255;const Ide=new Ro(lA,1,1,Yi);function WB(n,e=1){const t="alpha"in n,r=e*e,s=new Uint8Array(4*r),o=Math.floor(n.r*255),a=Math.floor(n.g*255),l=Math.floor(n.b*255);for(let h=0;h<r;h++){const u=h*4;s[u+0]=o,s[u+1]=a,s[u+2]=l,t?s[u+3]=Math.floor(n.alpha*255):s[u+3]=255}const c=new Ro(s,e,e);return c.needsUpdate=!0,c}function Rde(n,e,t,r=1,s=3){const o=r*s,a=[n,e,t],l=a.length,c=new Uint8Array(4*l*o),h=new xe;for(let p=0;p<s;p++){const m=Math.floor(p/s*l),f=it.clamp(m+1,0,l-1),g=a[m],v=a[f],y=p/s*l%1;h.lerpColors(g,v,y);const A=Math.floor(h.r*255),_=Math.floor(h.g*255),b=Math.floor(h.b*255);for(let x=0;x<r;x++){const E=(p*r+x)*4;c[E+0]=A,c[E+1]=_,c[E+2]=b,c[E+3]=255}}const u=new Ro(c,r,s);return u.needsUpdate=!0,u}function fS(n,e){const t=n.elements;e||(e=[]),e.length=0;for(let r=0;r<16;r+=4){const s=t[r],o=t[r+1],a=t[r+2],l=t[r+3],c=new Ye(s,o,a,l);e.push(c)}return e}const XB=[],x8=[];function Pde(n,e){if(XB.length===0)for(let t=0;t<27;t++)XB.push(0);e||(e=XB);for(let t=0;t<27;t++)x8[t]=e[t];e=x8,n.unity_SHAr={value:new Ye(e[9],e[3],e[6],e[0])},n.unity_SHBr={value:new Ye(e[12],e[15],e[18],e[21])},n.unity_SHAg={value:new Ye(e[10],e[4],e[7],e[1])},n.unity_SHBg={value:new Ye(e[13],e[16],e[19],e[22])},n.unity_SHAb={value:new Ye(e[11],e[5],e[8],e[2])},n.unity_SHBb={value:new Ye(e[14],e[17],e[20],e[23])},n.unity_SHC={value:new Ye(e[24],e[25],e[26],1)}}class Bde{constructor(e,t,r){d(this,"vertexShader"),d(this,"fragmentShader"),d(this,"technique"),this.vertexShader=e,this.fragmentShader=t,this.technique=r}}async function kde(n,e){if(!n)return console.error("Can not find technique: no shader data"),null;const t=n.programs[e],r=t.vertexShader,s=t.fragmentShader;if(r!==void 0&&s!==void 0){const o=n.shaders[r],a=n.shaders[s];if(o.uri&&a.uri||o.code&&a.code){if(!o.code&&o.uri&&await w8(o),!a.code&&a.uri&&await w8(a),!o.code||!a.code)return null;const l=n.techniques[e];return new Bde(o.code,a.code,l)}}return console.error("Shader technique not found",e),null}async function w8(n){const e=n.uri;if(e)if(e.endsWith(".glsl")){const t=await new ys().loadAsync(e);n.code=t.toString()}else n.code=Dde(n.uri)}function Dde(n){return decodeURIComponent(Array.prototype.map.call(atob(n),function(e){return"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)}).join(""))}const fl=te("debugenvlight");var Ng=(n=>(n[n.Skybox=0]="Skybox",n[n.Trilight=1]="Trilight",n[n.Flat=3]="Flat",n[n.Custom=4]="Custom",n))(Ng||{}),gS=(n=>(n[n.Skybox=0]="Skybox",n[n.Custom=1]="Custom",n))(gS||{});class S8{constructor(e){d(this,"context"),d(this,"_currentLightSettingsId"),d(this,"_sceneLightSettings"),d(this,"_timevec4",new Ye),d(this,"__currentReflectionId",null),d(this,"_lighting",{}),this.context=e,this.context.pre_update_callbacks.push(this.preUpdate.bind(this))}preUpdate(){const e=this.context.time;this._timevec4.x=e.time,this._timevec4.y=Math.sin(e.time),this._timevec4.z=Math.cos(e.time),this._timevec4.w=e.deltaTime}get timeVec4(){return this._timevec4}get environmentIntensity(){if(!this._sceneLightSettings||!this._currentLightSettingsId)return 1;const e=this._sceneLightSettings.get(this._currentLightSettingsId);return e?e.ambientIntensity:1}get sceneLightSettings(){var e;return(e=this._sceneLightSettings)==null?void 0:e.values()}enable(e){var t;e instanceof ti&&(e=e.uri);const r=(t=this._sceneLightSettings)==null?void 0:t.get(e);return r?(fl&&console.log("Enable scene light settings",e,r),e!==this._currentLightSettingsId&&this._currentLightSettingsId&&this.disable(this._currentLightSettingsId),this._currentLightSettingsId=e,r.enabled=!0,!0):(fl&&console.warn("No light settings found for",e),!1)}disable(e){var t;if(e instanceof ti&&(e=e.uri),e==null)return!1;const r=(t=this._sceneLightSettings)==null?void 0:t.get(e);return r?(fl&&console.log("Disable scene light settings",e,r),r.enabled=!1,!0):!1}disableCurrent(){if(this._currentLightSettingsId){const e=this._currentLightSettingsId;return this.disable(this._currentLightSettingsId),e}return null}internalRegisterSceneLightSettings(e){const t=e.sourceId;if(!t){console.error("Missing source id for scene light settings, can not register:",e);return}fl&&console.log("Register "+e?.sourceId+" lighting",e),this._sceneLightSettings||(this._sceneLightSettings=new Map),this._sceneLightSettings.set(t,e)}internalUnregisterSceneLightSettings(e){const t=e.sourceId;if(!t){console.error("Missing source id for scene light settings, can not unregister:",e);return}fl&&console.log("Unregister "+e?.sourceId+" lighting",e),this._sceneLightSettings&&this._sceneLightSettings.delete(t)}internalRegisterReflection(e,t){fl&&console.log("Register reflection",e,t);const r=new C8(this.context,t,1);this._lighting[e]=r}internalGetReflection(e){return this._lighting[e]}internalEnableReflection(e){var t;this.__currentReflectionId=e;const r=(t=this._sceneLightSettings)==null?void 0:t.get(e);switch(fl&&console.log("Enable reflection",e,r?Ng[r.ambientMode]:"Unknown ambient mode",r),r?.ambientMode){case 0:case 4:const s=this.internalGetReflection(e);if(s&&s.Source){fl&&console.log("Setting environment reflection",s);const o=this.context.scene,a=s.Source;a.mapping=so,o.environment=a;return}else fl&&console.warn("Could not find reflection for source",e);break}if(r?.environmentReflectionSource===1)switch(r?.ambientMode){case 1:if(r.ambientTrilight){const s=r.ambientTrilight,o=Rde(s[0],s[1],s[2],64,64);o.colorSpace=ft,o.mapping=so,this.context.scene.environment=o}else console.error("Missing ambient trilight",r.sourceId);return;case 3:if(r.ambientLight){const s=WB(r.ambientLight,64);s.colorSpace=ft,s.mapping=so,this.context.scene.environment=s}else console.error("Missing ambientlight",r.sourceId);return;default:return}}internalDisableReflection(e){if(e&&e!==this.__currentReflectionId){fl&&console.log("Not disabling reflection for",e,"because it is not the current light settings id",this.__currentReflectionId);return}fl&&console.log("Disable reflection",e);const t=this.context.scene;t.environment=null}}class C8{constructor(e,t,r=1){d(this,"_source"),this._source=t,t.mapping=so}get Source(){return this._source}}const E8=te("timescale");let qB=1;typeof E8=="number"&&(qB=E8);class M8{constructor(){d(this,"_time",0),d(this,"_deltaTime",0),d(this,"_deltaTimeUnscaled",0),d(this,"timeScale",1),d(this,"_frame",0),d(this,"clock",new fI),d(this,"_smoothedFps",0),d(this,"_smoothedDeltaTime",0),d(this,"_fpsSamples",[]),d(this,"_fpsSampleIndex",0),typeof qB=="number"&&(this.timeScale=qB)}get time(){return this._time}set time(e){this._time=e}get deltaTime(){return this._deltaTime}set deltaTime(e){this._deltaTime=e}get deltaTimeUnscaled(){return this._deltaTimeUnscaled}get frame(){return this._frame}set frame(e){this._frame=e}get frameCount(){return this.frame}get realtimeSinceStartup(){return this.clock.elapsedTime}get smoothedFps(){return this._smoothedFps}get smoothedDeltaTime(){return 1/this._smoothedFps}update(){this.deltaTime=this.clock.getDelta(),this.deltaTime=Math.min(.1,this.deltaTime),this._deltaTimeUnscaled=this.deltaTime,this.deltaTime<=0&&(this.deltaTime=1e-12),this.deltaTime*=this.timeScale,this.frame+=1,this.time+=this.deltaTime,this._fpsSamples.length<60?this._fpsSamples.push(this.deltaTime):this._fpsSamples[this._fpsSampleIndex++%60]=this.deltaTime;let e=0;for(let t=0;t<this._fpsSamples.length;t++)e+=this._fpsSamples[t];this._smoothedDeltaTime=e/this._fpsSamples.length,this._smoothedFps=1/this._smoothedDeltaTime}}let T8=!1;function I8(n){T8||(T8=!0,Ode(),Lde())}I8();function Ode(){const n=`
5270
5270
  float startCompression = 0.8;
5271
5271
  float desaturation = 0.5;
5272
5272
  // Patched tonemapping function
@@ -7586,7 +7586,7 @@ void mainImage(const in vec4 inputColor, const in vec2 uv, out vec4 outputColor)
7586
7586
  outputColor = sharp;
7587
7587
  }
7588
7588
 
7589
- `;class QH extends Ys{constructor(){super("Sharpening",RAe,{vertexShader:IAe,blendFunction:jt.NORMAL,uniforms:new Map([["amount",new Se(1)],["radius",new Se(1)]])})}}const km=te("debugpost"),hO=Symbol("needle:postprocessing-handler"),uO=Symbol("needle:previous-autoclear-state");class lE{constructor(e){d(this,"_composer",null),d(this,"_lastVolumeComponents"),d(this,"_effects",[]),d(this,"_isActive",!1),d(this,"context"),this.context=e}get isActive(){return this._isActive}get composer(){return this._composer}apply(e){this._isActive=!0,this.onApply(this.context,e)}unapply(){var e;if(km&&console.log("Unapplying postprocessing effects"),this._isActive=!1,this._lastVolumeComponents){for(const r of this._lastVolumeComponents)r.unapply();this._lastVolumeComponents.length=0}const t=this.context;t[hO]===this&&delete t[hO],t.composer===this._composer&&((e=t.composer)==null||e.dispose(),t.composer=null),typeof t.renderer[uO]=="boolean"&&(t.renderer.autoClear=t.renderer[uO])}dispose(){this.unapply();for(const e of this._effects)e.dispose();this._effects.length=0,this._composer=null}onApply(e,t){if(!t)return;e[hO]=this,km&&console.log("refreshing volume profile",t),this._lastVolumeComponents=[...t],this._effects.length=0;const r={handler:this,components:this._lastVolumeComponents};for(let s=0;s<this._lastVolumeComponents.length;s++){const o=this._lastVolumeComponents[s];if(o.context=e,o.apply){if(o.active){if(!e.mainCameraComponent){console.error("No camera in scene found or available yet - can not create postprocessing effects");return}const a=o.apply(r);if(!a)continue;Array.isArray(a)?this._effects.push(...a):this._effects.push(a)}}else o.active&&Di("Volume component is not a VolumeComponent: "+o.__type)}if(this.context.renderer.toneMapping!=Ls&&!this._effects.find(s=>s instanceof U1)){const s=new U1;this._effects.push(s)}this.applyEffects(e)}applyEffects(e){const t=this._effects;if(t.length<=0)return;const r=e.mainCameraComponent,s=e.renderer,o=e.scene,a=r.cam;s[uO]=s.autoClear;const l=s.capabilities.maxSamples;this._composer||(this._composer=new JP(s,{frameBufferType:rr,stencilBuffer:!0,multisampling:Math.min(aa()?4:8,l)})),e.composer&&e.composer!==this._composer&&console.warn("There's already an active EffectComposer in your scene: replacing it with a new one. This might cause unexpected behaviour. Make sure to only use one PostprocessingManager/Volume in your scene."),e.composer=this._composer;const c=e.composer;c.setMainCamera(a),c.setRenderer(s),c.setMainScene(o);for(const u of c.passes)u.dispose();c.removeAllPasses();const h=new F1(o,a);h.name="Render To Screen",h.mainScene=o,c.addPass(h);try{this.orderEffects();const u=[];for(const p of t)if(p instanceof Ys)u.push(p);else if(p instanceof jr){const m=new u6(a,...u);m.mainScene=o,m.name=u.map(f=>f.constructor.name).join(", "),m.enabled=!0,u.length=0,c.addPass(p)}if(u.length>0){const p=new u6(a,...u);p.name=u.map(m=>m.name).join(" "),p.mainScene=o,p.enabled=!0,c.addPass(p)}}catch(u){console.error("Error while applying postprocessing effects",u),c.removeAllPasses()}km&&console.log("PostProcessing Passes",t,"->",c.passes)}orderEffects(){var e;km&&console.log("Before ordering effects",[...this._effects]);const t=this._effects;t.sort((r,s)=>{const o=dO.findIndex(l=>r.constructor.name.endsWith(l.name)),a=dO.findIndex(l=>s.constructor.name.endsWith(l.name));return o<0?(km&&console.warn("Unknown effect found: ",r.constructor.name),-1):a<0?(km&&console.warn("Unknown effect found: ",s.constructor.name),1):o<0?1:a<0?-1:o-a}),km&&console.log("After ordering effects",[...this._effects]);for(let r=0;r<t.length;r++){const s=t[r];if(((e=s?.configuration)==null?void 0:e.gammaCorrection)!==void 0){const o=r===t.length-1;s.configuration.gammaCorrection=o}}}}const dO=[d6,tB,s6,a6,GH,l6,$5,J5,$P,i6,c6,t6,U1,e6,Y5,QH];async function pO(n){const{NeedleEngineHTMLElement:e}=await Promise.resolve().then(()=>p_e);e.observedAttributes.includes(n)||e.observedAttributes.push(n)}var PAe=Object.defineProperty,BAe=Object.getOwnPropertyDescriptor,kb=(n,e,t,r)=>{for(var s=r>1?void 0:r?BAe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&PAe(e,t,s),s};const Ua=te("debugskybox");pO("skybox-image"),pO("environment-image");function HH(n,e,t,r,s){const o=new wc;o.allowDrop=!1,o.allowNetworking=!1,o.background=t,o.environment=r,ie.addComponent(n.scene,o);const a=l=>{typeof l=="string"&&(Ua&&console.log(s,"CHANGED TO",l),o.setSkybox(l))};return GU(n.domElement,s,a),o.addEventListener("destroy",()=>{Ua&&console.log("Destroyed attribute remote skybox",s),VU(n.domElement,s,a)}),o.setSkybox(e)}di.addContextCreatedCallback(n=>{var e;const t=n.context,r=t.domElement.getAttribute("skybox-image"),s=t.domElement.getAttribute("environment-image"),o=new Array;if(r){Ua&&console.log("Creating remote skybox to load "+r),((e=t.mainCameraComponent)==null?void 0:e.clearFlags)!==$u.Skybox&&console.warn('"skybox-image" attribute has no effect: camera clearflags are not set to "Skybox"');const a=HH(t,r,!0,!1,"skybox-image");o.push(a)}if(s){Ua&&console.log("Creating remote environment to load "+s);const a=HH(t,s,!1,!0,"environment-image");o.push(a)}return o.length>0?tw(o):Promise.resolve()});function WH(){return globalThis.NEEDLE_ENGINE_SKYBOX_TEXTURES||(globalThis.NEEDLE_ENGINE_SKYBOX_TEXTURES=new Array),globalThis.NEEDLE_ENGINE_SKYBOX_TEXTURES}function XH(n){const e=WH().find(t=>t.src===n);return e?(Ua&&console.log("Skybox: Found previously loaded texture for "+n),e.texture):null}async function kAe(n){const e=await n;UP(e,!0),Qi(e)}function DAe(n,e){const t=WH();for(;t.length>5;){const r=t.shift();r&&kAe(r.texture)}e.then(r=>UP(r,!1)),t.push({src:n,texture:e})}class wc extends Be{constructor(){super(...arguments),d(this,"url"),d(this,"allowDrop",!0),d(this,"background",!0),d(this,"environment",!0),d(this,"allowNetworking",!0),d(this,"_loader"),d(this,"_prevUrl"),d(this,"_prevLoadedEnvironment"),d(this,"_prevEnvironment",null),d(this,"_prevBackground",null),d(this,"validTextureTypes",[".hdr",".exr",".jpg",".jpeg",".png"]),d(this,"onDragOverEvent",e=>{if(this.allowDrop&&e.dataTransfer)for(const t of e.dataTransfer.types)(t==="text/uri-list"||t==="Files")&&e.preventDefault()}),d(this,"onDrop",e=>{var t,r,s,o;if(this.allowDrop&&e.dataTransfer){for(const a of e.dataTransfer.types)if(Ua&&console.log(a),a==="text/uri-list"){const l=e.dataTransfer.getData(a);Ua&&console.log(a,l);let c=(r=(t=new RegExp(/polyhaven.com\/asset_img\/.+?\/(?<name>.+)\.png/).exec(l))==null?void 0:t.groups)==null?void 0:r.name;if(c||(c=(o=(s=new RegExp(/polyhaven\.com\/a\/(?<name>.+)/).exec(l))==null?void 0:s.groups)==null?void 0:o.name),Ua&&console.log(c),c){const h="https://dl.polyhaven.org/file/ph-assets/HDRIs/exr/1k/"+c+"_1k.exr";console.log(`[Remote Skybox] Setting skybox from url: ${h}`),e.preventDefault(),this.setSkybox(h);break}else if(this.isValidTextureType(l)){console.log("[Remote Skybox] Setting skybox from url: "+l),e.preventDefault(),this.setSkybox(l);break}else{console.warn(`[RemoteSkybox] Unknown url ${l}. If you want to load a skybox from a url, make sure it is a valid image url. Url must end with${this.validTextureTypes.join(", ")}.`);const h=new CustomEvent("dropped-unknown-url",{detail:{sender:this,event:e,url:l,apply:u=>{e.preventDefault(),this.setSkybox(u)}}});this.dispatchEvent(h)}}else if(a=="Files"){const l=e.dataTransfer.files.item(0);if(Ua&&console.log(a,l),!l)continue;if(!this.isValidTextureType(l.name)){console.warn(`[RemoteSkybox]: File "${l.name}" is not supported. Supported files are ${this.validTextureTypes.join(", ")}`);return}if(XH(l.name)===null){const c=new Blob([l]),h=URL.createObjectURL(c);e.preventDefault(),this.setSkybox(h,l.name)}else e.preventDefault(),this.setSkybox(l.name);break}}})}onEnable(){this.setSkybox(this.url),this.registerDropEvents()}onDisable(){var e;this.context.scene.environment===this._prevLoadedEnvironment&&(this.context.scene.environment=this._prevEnvironment,Li.backgroundShouldBeTransparent(this.context)||(this.context.scene.background=this._prevBackground),this._prevLoadedEnvironment=void 0),this.unregisterDropEvents(),(e=this.context.mainCameraComponent)==null||e.applyClearFlags()}urlChangedSyncField(){this.allowNetworking&&this.url&&this.isRemoteTexture(this.url)&&this.setSkybox(this.url)}async setSkybox(e,t){var r;if(!this.activeAndEnabled||(e=OAe(e,this.environment,this.background),!e))return!1;if(t??(t=e),this.isValidTextureType(t)||console.warn("Potentially invalid skybox url",t,"on",this.name),Ua&&console.log("Set remote skybox url: "+e),this._prevUrl===e&&this._prevLoadedEnvironment)return this.applySkybox(),!0;(r=this._prevLoadedEnvironment)==null||r.dispose(),this._prevLoadedEnvironment=void 0,this._prevUrl=e;const s=await this.loadTexture(e,t);if(!s||!this.enabled)return!1;this.url=e;const o=e.lastIndexOf("/");return s.name=e.substring(o>=0?o+1:0),this._loader instanceof Dl&&(s.colorSpace=ft),this._prevLoadedEnvironment=s,this.applySkybox(),!0}async loadTexture(e,t){var r,s,o,a,l;if(!e)return Promise.resolve(null);t??(t=e);const c=XH(t);if(c){const m=await c;if(((s=(r=m.source)==null?void 0:r.data)==null?void 0:s.length)>0||(l=(a=(o=m.source)==null?void 0:o.data)==null?void 0:a.data)!=null&&l.length)return m}const h=t.endsWith(".exr"),u=t.endsWith(".hdr");h?this._loader instanceof oA||(this._loader=new oA):u?this._loader instanceof uS||(this._loader=new uS):this._loader instanceof Dl||(this._loader=new Dl),Ua&&console.log("Loading skybox: "+e);const p=this._loader.loadAsync(e);return DAe(t,p),await p}applySkybox(){var e;const t=this._prevLoadedEnvironment;t&&(t.mapping=Ym,t.needsUpdate=!0,this.context.scene.background!==t&&(this._prevBackground=this.context.scene.background),this.context.scene.environment!==t&&(this._prevEnvironment=this.context.scene.environment),Ua&&console.log("Set remote skybox",this.url,!Li.backgroundShouldBeTransparent(this.context)),this.environment&&(this.context.scene.environment=t),this.background&&!Li.backgroundShouldBeTransparent(this.context)&&(this.context.scene.background=t),((e=this.context.mainCameraComponent)==null?void 0:e.backgroundBlurriness)!==void 0&&(this.context.scene.backgroundBlurriness=this.context.mainCameraComponent.backgroundBlurriness))}isRemoteTexture(e){return e.startsWith("http://")||e.startsWith("https://")}isValidTextureType(e){for(const t of this.validTextureTypes)if(e.endsWith(t))return!0;return!1}registerDropEvents(){this.unregisterDropEvents(),this.context.domElement.addEventListener("dragover",this.onDragOverEvent),this.context.domElement.addEventListener("drop",this.onDrop)}unregisterDropEvents(){this.context.domElement.removeEventListener("dragover",this.onDragOverEvent),this.context.domElement.removeEventListener("drop",this.onDrop)}}kb([Ek(wc.prototype.urlChangedSyncField),w(URL)],wc.prototype,"url",2),kb([w()],wc.prototype,"allowDrop",2),kb([w()],wc.prototype,"background",2),kb([w()],wc.prototype,"environment",2),kb([w()],wc.prototype,"allowNetworking",2);function OAe(n,e,t){const r=e&&!t;switch(n?.toLowerCase()){case"studio":return r?"https://cdn.needle.tools/static/skybox/modelviewer-Neutral-small.hdr":"https://cdn.needle.tools/static/skybox/modelviewer-Neutral.hdr";case"blurred-skybox":return r?"https://cdn.needle.tools/static/skybox/blurred-skybox-small.exr":"https://cdn.needle.tools/static/skybox/blurred-skybox.exr";case"quicklook-ar":return r?"https://cdn.needle.tools/static/skybox/QuickLook-ARMode-small.exr":"https://cdn.needle.tools/static/skybox/QuickLook-ARMode.exr";case"quicklook":return r?"https://cdn.needle.tools/static/skybox/QuickLook-ObjectMode-small.exr":"https://cdn.needle.tools/static/skybox/QuickLook-ObjectMode.exr"}return n===void 0?null:n}var LAe=Object.defineProperty,FAe=Object.getOwnPropertyDescriptor,qo=(n,e,t,r)=>{for(var s=r>1?void 0:r?FAe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&LAe(e,t,s),s};const Yo=te("debugsceneswitcher"),cE="scene";pO(cE);const Cd=Promise.resolve(!1);class ks extends Be{constructor(){super(...arguments),d(this,"autoLoadFirstScene",!0),d(this,"scenes",[]),d(this,"loadingScene"),d(this,"queryParameterName","scene"),d(this,"useSceneName",!0),d(this,"clamp",!0),d(this,"useHistory",!0),d(this,"useKeyboard",!0),d(this,"useSwipe",!0),d(this,"useSceneLighting",!0),d(this,"preloadNext",1),d(this,"preloadPrevious",1),d(this,"preloadConcurrent",2),d(this,"_currentIndex",-1),d(this,"_currentScene"),d(this,"_engineElementOverserver"),d(this,"_preloadScheduler"),d(this,"onPopState",async e=>{if(!this.useHistory)return;const t=this.useHistory;try{this.useHistory=!1;let r=!1;if(this.queryParameterName&&(r=await this.tryLoadFromQueryParam()),!r){const s=e?.state;if(s&&s.startsWith(this.guid)){const o=s.substr(this.guid.length+2);Yo&&console.log("PopState",o),await this.trySelectSceneFromValue(o)}}}finally{this.useHistory=t}}),d(this,"normalizedSwipeThresholdX",.1),d(this,"_didSwipe",!1),d(this,"onInputPointerMove",e=>{if(this.useSwipe&&!this._didSwipe&&e.button===0&&e.pointerType==="touch"&&this.context.input.getPointerPressedCount()===1){const t=this.context.input.getPointerPositionDelta(e.button);if(t){const r=t.x/this.context.domWidth;r>=this.normalizedSwipeThresholdX?(this._didSwipe=!0,this.selectPrev()):r<=-this.normalizedSwipeThresholdX&&(this._didSwipe=!0,this.selectNext())}}}),d(this,"onInputPointerUp",e=>{e.button===0&&(this._didSwipe=!1)}),d(this,"onInputKeyDown",e=>{if(!this.useKeyboard||!this.scenes)return;const t=e.key.toLowerCase();if(!t)return;const r=parseInt(t)-1;if(r>=0){this.trySelectSceneFromValue(r);return}switch(t){case"arrowright":case"d":this.selectNext();break;case"arrowleft":case"a":this.selectPrev();break}}),d(this,"__lastSwitchScene"),d(this,"__lastSwitchScenePromise"),d(this,"_currentlyLoadingScene"),d(this,"_lastLoadingScene"),d(this,"_loadingScenePromise"),d(this,"_isCurrentlyLoading",!1),d(this,"_currentLoadingProgress")}get currentIndex(){return this._currentIndex}get currentLoadingProgress(){return this._currentLoadingProgress}get currentlyLoadingScene(){return this._currentlyLoadingScene}get currentlyLoadedScene(){return this._currentScene}awake(){this.scenes===void 0&&(this.scenes=[]);for(const e of this.scenes)e&&!e.hasUrl&&e.asset instanceof ye&&e.asset.removeFromParent();Yo&&console.log("SceneSwitcher",this)}async onEnable(){if(globalThis.addEventListener("popstate",this.onPopState),this.context.input.addEventListener(an.KeyDown,this.onInputKeyDown),this.context.input.addEventListener(an.PointerMove,this.onInputPointerMove),this.context.input.addEventListener(an.PointerUp,this.onInputPointerUp),this._engineElementOverserver||(this._engineElementOverserver=new MutationObserver(e=>{for(const t of e)if(t.type==="attributes"&&t.attributeName===cE){const r=this.context.domElement.getAttribute(cE);r!==null&&this.trySelectSceneFromValue(r)}})),this._engineElementOverserver.observe(this.context.domElement,{attributes:!0}),this._preloadScheduler||(this._preloadScheduler=new UAe(this)),this._preloadScheduler.maxLoadAhead=this.preloadNext,this._preloadScheduler.maxLoadBehind=this.preloadPrevious,this._preloadScheduler.maxConcurrent=this.preloadConcurrent,this._preloadScheduler.begin(),this.autoLoadFirstScene&&this._currentIndex===-1&&!await this.tryLoadFromQueryParam()){const e=this.context.domElement.getAttribute(cE);try{(e===null||!await this.trySelectSceneFromValue(e))&&this._currentIndex===-1&&this.select(0)}finally{}}}onDisable(){var e;globalThis.removeEventListener("popstate",this.onPopState),this.context.input.removeEventListener(an.KeyDown,this.onInputKeyDown),this.context.input.removeEventListener(an.PointerMove,this.onInputPointerMove),this.context.input.removeEventListener(an.PointerUp,this.onInputPointerUp),(e=this._preloadScheduler)==null||e.stop()}addScene(e){if(typeof e=="string"){let t=this.context.addressables.findAssetReference(e);return t||(t=new ti(e),this.context.addressables.registerAssetReference(t)),this.scenes.push(t),t}return this.scenes.push(e),e}selectNext(){return this.select(this._currentIndex+1)}selectPrev(){return this.select(this._currentIndex-1)}select(e){var t,r,s;if(Yo&&console.log("select",e),typeof e=="object"&&console.warn('Switching to "'+e+'" might not work. Please either use an index or a AssetReference (not a scene reference)'),typeof e=="string"){const a=(t=this.scenes)==null?void 0:t.find(l=>l.uri===e);if(!a){const l=ti.getOrCreate(this.sourceId??"",e,this.context);return this.switchScene(l)}if(a)e=(r=this.scenes)==null?void 0:r.indexOf(a);else return Cd}if(!((s=this.scenes)!=null&&s.length))return Cd;if(e<0){if(this.clamp)return Cd;e=this.scenes.length-1}else if(e>=this.scenes.length){if(this.clamp)return Cd;e=0}const o=this.scenes[e];return this.switchScene(o)}async switchScene(e){if(!(e instanceof ti)){const t=typeof e;return t==="string"?this.select(e):t==="number"?this.select(e):(console.warn("SceneSwitcher: Can't switch to scene",e,"of type",t),!1)}return e.uri===this.sourceId?(console.warn("SceneSwitcher: can't load own scene - prevent recursive loading",this.sourceId),!1):this.__lastSwitchScene===e&&this.__lastSwitchScenePromise?this.__lastSwitchScenePromise:(this.__lastSwitchScene=e,this.__lastSwitchScenePromise=this.__internalSwitchScene(e),await this.__lastSwitchScenePromise)}async __internalSwitchScene(e){var t,r;if(this._currentScene){Yo&&console.log("UNLOAD",e.uri);const o=this.tryGetSceneEventListener(this._currentScene.asset);if(o!=null&&o.sceneClosing){const a=o.sceneClosing();a instanceof Promise&&await a}this._currentScene.hasUrl?this._currentScene.unload():this._currentScene.asset instanceof ye&&this._currentScene.asset.removeFromParent()}this._currentScene=void 0;const s=this._currentIndex=((t=this.scenes)==null?void 0:t.indexOf(e))??-1;try{this._currentlyLoadingScene=e,this._currentLoadingProgress=new ProgressEvent("progress",{loaded:0,total:1});const o=new CustomEvent("loadscene-start",{detail:{scene:e,switcher:this,index:s}});this.dispatchEvent(o),await this.onStartLoading(),await e.loadAssetAsync((l,c)=>{this._currentLoadingProgress=c,this.dispatchEvent(c)}).catch(console.error),await this.onEndLoading();const a=new CustomEvent("loadscene-finished",{detail:{scene:e,switcher:this,index:s}});if(this.dispatchEvent(a),this._currentLoadingProgress=void 0,this._currentlyLoadingScene=void 0,a.defaultPrevented)return Yo&&console.warn("Adding loaded scene prevented:",e,a),!1;if(!e.asset)return Yo&&console.warn("Failed loading scene:",e),!1;if(this._currentIndex===s){if(Yo&&console.log("ADD",e.uri),this._currentScene=e,ie.add(e.asset,this.gameObject),this.useSceneLighting&&this.context.sceneLighting.enable(e),this.useHistory&&s>=0){let h=s.toString();if(this.useSceneName&&(h=qH(e.uri)),(r=this.queryParameterName)!=null&&r.length)Jx(this.queryParameterName,h,this.useHistory);else{const u=history.state,p=this.guid+"::"+s;u!==p&&history.pushState(p,"unused",location.href)}}const l=this.tryGetSceneEventListener(e.asset);if(l!=null&&l.sceneOpened){const h=l.sceneOpened(this);h instanceof Promise&&await h}const c=new CustomEvent("scene-opened",{detail:{scene:e,switcher:this,index:s}});return this.dispatchEvent(c),!0}}catch(o){console.error(o)}return!1}preload(e){if(e>=0&&e<this.scenes.length){const t=this.scenes[e];if(t instanceof ti)return t.preload()}return Cd}tryLoadFromQueryParam(){var e;if(!((e=this.queryParameterName)!=null&&e.length))return Cd;const t=te(this.queryParameterName);return typeof t=="boolean"?Cd:this.trySelectSceneFromValue(t)}trySelectSceneFromValue(e){if(typeof e=="string"){const t=parseInt(e);if(t>=0&&t<this.scenes.length)return this.select(t);{const r=e.toLowerCase();for(let s=0;s<this.scenes.length;s++){const o=this.scenes[s];if(o&&qH(o.uri).toLowerCase().includes(r))return this.select(s)}}}else if(typeof e=="number"&&e>=0&&e<this.scenes.length)return this.select(e);return js()&&console.warn('Can not find scene: "'+e+'"',this),Cd}async onStartLoading(){var e,t;if(this._isCurrentlyLoading=!0,this.loadingScene&&(this._lastLoadingScene!==this.loadingScene&&(this._loadingScenePromise=void 0),this._lastLoadingScene=this.loadingScene,this._loadingScenePromise||(this._loadingScenePromise=(e=this.loadingScene)==null?void 0:e.loadAssetAsync()),await this._loadingScenePromise,this._isCurrentlyLoading&&(t=this.loadingScene)!=null&&t.asset)){Yo&&console.log("Add loading scene",this.loadingScene.uri,this.loadingScene.asset);const r=this.loadingScene.asset;ie.add(r,this.gameObject);const s=this.tryGetSceneEventListener(r);if(s!=null&&s.sceneOpened){const o=s.sceneOpened(this);o instanceof Promise&&await o}}if(this._isCurrentlyLoading){const r=this.tryGetSceneEventListener(this.gameObject);if(r&&r.sceneOpened){const s=r.sceneOpened(this);s instanceof Promise&&await s}}}async onEndLoading(){var e;if(this._isCurrentlyLoading=!1,(e=this.loadingScene)!=null&&e.asset){Yo&&console.log("Remove loading scene",this.loadingScene.uri);const t=this.loadingScene.asset,r=this.tryGetSceneEventListener(t);if(typeof r?.sceneClosing=="function"){const s=r.sceneClosing();s instanceof Promise&&await s}ie.remove(t)}if(!this._isCurrentlyLoading){const t=this.tryGetSceneEventListener(this.gameObject);if(t&&t.sceneClosing){const r=t.sceneClosing();r instanceof Promise&&await r}}}tryGetSceneEventListener(e,t=0){const r=ie.foreachComponent(e,s=>s.sceneClosing?s:void 0);if(t===0&&!r&&e.children.length)for(const s of e.children){const o=this.tryGetSceneEventListener(s,t+1);if(o)return o}return r||null}}qo([w()],ks.prototype,"autoLoadFirstScene",2),qo([w(ti)],ks.prototype,"scenes",2),qo([w(ti)],ks.prototype,"loadingScene",2),qo([w()],ks.prototype,"queryParameterName",2),qo([w()],ks.prototype,"useSceneName",2),qo([w()],ks.prototype,"clamp",2),qo([w()],ks.prototype,"useHistory",2),qo([w()],ks.prototype,"useKeyboard",2),qo([w()],ks.prototype,"useSwipe",2),qo([w()],ks.prototype,"useSceneLighting",2),qo([w()],ks.prototype,"preloadNext",2),qo([w()],ks.prototype,"preloadPrevious",2),qo([w()],ks.prototype,"preloadConcurrent",2);function qH(n){const e=n.split("/").pop(),t=e?.split(".").shift();return t!=null&&t.length?t:n}class UAe{constructor(e,t=1,r=1,s=2){d(this,"maxLoadAhead"),d(this,"maxLoadBehind"),d(this,"maxConcurrent"),d(this,"_isRunning",!1),d(this,"_switcher"),d(this,"_loadTasks",[]),d(this,"_maxConcurrentLoads",1),this._switcher=e,this.maxLoadAhead=t,this.maxLoadBehind=r,this.maxConcurrent=s}begin(){if(this._isRunning)return;Yo&&console.log("Preload begin"),this._isRunning=!0;let e=-1,t,r;const s=this._switcher.scenes,o=setInterval(()=>{if(this.allLoaded()&&(Yo&&console.log("All scenes loaded"),this.stop()),!this._isRunning){clearInterval(o);return}if(this.canLoadNewScene()===!1)return;e!==this._switcher.currentIndex&&(e=this._switcher.currentIndex,r=0,t=0);const a=r%2===0;a&&(t+=1),r+=1;const l=a?this.maxLoadAhead:this.maxLoadBehind;if(t>l)return;const c=a?e+t:e-t;if(c<0||c<0||c>=s.length)return;const h=s[c];new NAe(c,h,this._loadTasks)},200)}stop(){this._isRunning=!1}canLoadNewScene(){return this._loadTasks.length<this._maxConcurrentLoads}allLoaded(){if(this._switcher.scenes){for(const e of this._switcher.scenes)if(e?.isLoaded()===!1)return!1}return!0}}class NAe{constructor(e,t,r){d(this,"index"),d(this,"asset"),d(this,"tasks"),this.index=e,this.asset=t,this.tasks=r,r.push(this),this.awaitLoading()}async awaitLoading(){this.asset&&!this.asset.isLoaded()&&(Yo&&console.log("Preload start: "+this.asset.uri,this.index),await this.asset.preload(),Yo&&console.log("Preload finished: "+this.asset.uri,this.index));const e=this.tasks.indexOf(this);e>=0&&this.tasks.splice(e,1)}}function zAe(){return new Promise((n,e)=>{const t=()=>{t!=null&&(document.removeEventListener("pointerdown",t),document.removeEventListener("click",t),document.removeEventListener("dragstart",t),document.removeEventListener("touchstart",t),n())};document.addEventListener("pointerdown",t),document.addEventListener("click",t),document.addEventListener("dragstart",t),document.addEventListener("touchstart",t)})}async function jAe(n){await zAe(),n()}var GAe=Object.defineProperty,VAe=Object.getOwnPropertyDescriptor,Jo=(n,e,t,r)=>{for(var s=r>1?void 0:r?VAe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&GAe(e,t,s),s};const Pr=te("debugvideo");var YH=(n=>(n[n.None=0]="None",n[n.AdjustHeight=1]="AdjustHeight",n[n.AdjustWidth=2]="AdjustWidth",n))(YH||{}),JH=(n=>(n[n.VideoClip=0]="VideoClip",n[n.Url=1]="Url",n))(JH||{}),KH=(n=>(n[n.CameraFarPlane=0]="CameraFarPlane",n[n.CameraNearPlane=1]="CameraNearPlane",n[n.RenderTexture=2]="RenderTexture",n[n.MaterialOverride=3]="MaterialOverride",n))(KH||{});class dr extends Be{constructor(){super(),d(this,"playOnAwake",!0),d(this,"aspectMode",0),d(this,"clip",null),d(this,"source",1),d(this,"_url",null),d(this,"renderMode"),d(this,"targetMaterialProperty"),d(this,"targetMaterialRenderer"),d(this,"targetTexture"),d(this,"time",0),d(this,"_playbackSpeed",1),d(this,"_isLooping",!1),d(this,"_muted",!1),d(this,"_audioOutputMode",2),d(this,"playInBackground",!0),d(this,"_crossOrigin","anonymous"),d(this,"_videoElement",null),d(this,"_videoTexture",null),d(this,"_videoMaterial",null),d(this,"_isPlaying",!1),d(this,"wasPlaying",!1),d(this,"visibilityChanged",e=>{switch(document.visibilityState){case"hidden":this.playInBackground||(this.wasPlaying=this._isPlaying,this.pause());break;case"visible":this.wasPlaying&&!this._isPlaying&&this.play();break}}),d(this,"_receivedInput",!1),d(this,"_overlay",null),d(this,"_targetObjects"),d(this,"_updateAspectRoutineId",-1),d(this,"_hls"),d(this,"onHlsAvailable",()=>{var e;Pr&&console.log("HLS: available",this.clip),!(!this.shouldUseM3U||!this.url)&&(this._hls||(this._hls=new Hls),this.videoElement.autoplay=!0,this._hls.loadSource(this.url),this._hls.attachMedia(this.videoElement),(e=this._videoElement)==null||e.play(),Pr&&console.log("HLS: loaded",this.clip))}),jAe(()=>{this._receivedInput=!0,this.updateVideoElementSettings()}),this._targetObjects=[],te("videoscreenspace")&&window.addEventListener("keydown",e=>{e.key==="f"&&(this.screenspace=!this.screenspace)})}get url(){return this._url}set url(e){const t=this._url!==e;this.__didAwake?t&&this.setClipURL(e??""):this._url=e}get playbackSpeed(){var e;return((e=this._videoElement)==null?void 0:e.playbackRate)??this._playbackSpeed}set playbackSpeed(e){this._playbackSpeed=e,this._videoElement&&(this._videoElement.playbackRate=e)}get isLooping(){var e;return((e=this._videoElement)==null?void 0:e.loop)??this._isLooping}set isLooping(e){this._isLooping=e,this._videoElement&&(this._videoElement.loop=e)}get currentTime(){var e;return((e=this._videoElement)==null?void 0:e.currentTime)??this.time}set currentTime(e){this._videoElement?this._videoElement.currentTime=e:this.time=e}get isPlaying(){const e=this._videoElement;return!!(e&&(e.currentTime>0&&!e.paused&&!e.ended&&e.readyState>e.HAVE_CURRENT_DATA||e.srcObject&&e.srcObject.active))}get crossOrigin(){var e;return((e=this._videoElement)==null?void 0:e.crossOrigin)??this._crossOrigin}set crossOrigin(e){this._crossOrigin=e,this._videoElement&&(e!==null?this._videoElement.setAttribute("crossorigin",e):this._videoElement.removeAttribute("crossorigin"))}get videoMaterial(){return!this._videoMaterial&&!this.create(!1)?null:this._videoMaterial}get videoTexture(){return!this._videoTexture&&!this.create(!1)?null:this._videoTexture}get videoElement(){return!this._videoElement&&!this.create(!1)?null:this._videoElement}get muted(){var e;return((e=this._videoElement)==null?void 0:e.muted)??this._muted}set muted(e){this._muted=e,this._videoElement&&(this._videoElement.muted=e)}get currentVideo(){return this.clip}set audioOutputMode(e){e!==this._audioOutputMode&&(e===1&&st()&&console.warn("VideoAudioOutputMode.AudioSource is not yet implemented"),this._audioOutputMode=e,this.updateVideoElementSettings())}get audioOutputMode(){return this._audioOutputMode}preloadVideo(){Pr&&console.log("Video Preload: "+this.name,this.clip),this.create(!1)}preload(){this.preloadVideo()}setVideo(e){this.clip=e,this.source=0,this._videoElement?(this._videoElement.srcObject=e,this._isPlaying&&this.play(),this.updateAspect()):this.create(this.playOnAwake)}setClipURL(e){this._url!==e&&(this._url=e,this.source=1,Pr&&console.log("set url",e),this._videoElement?e.endsWith(".m3u8")||e.includes(".m3u")?this.ensureM3UCanBePlayed():(this._videoElement.src=e,this._isPlaying&&(this.stop(),this.play())):this.create(this.playOnAwake))}onEnable(){var e,t;Pr&&console.log("VideoPlayer.onEnable",JH[this.source],this.clip,this.url,this),window.addEventListener("visibilitychange",this.visibilityChanged),this.playOnAwake===!0?this.create(!0):this.preloadVideo(),this.screenspace?(e=this._overlay)==null||e.start():(t=this._overlay)==null||t.stop()}onDisable(){var e;window.removeEventListener("visibilitychange",this.visibilityChanged),(e=this._overlay)==null||e.stop(),this.pause()}onDestroy(){var e;this._videoElement&&((e=this.videoElement)==null||e.remove(),this._videoElement=null),this._videoTexture&&(this._videoTexture.dispose(),this._videoTexture=null)}play(){var e,t;if(this._videoElement||this.create(!1),!this._videoElement){Pr&&console.warn("Can not play: no video element found",this);return}if(!(this._isPlaying&&!((e=this._videoElement)!=null&&e.ended)&&!((t=this._videoElement)!=null&&t.paused))){if(this._isPlaying=!0,this._receivedInput||(this._videoElement.muted=!0),this.handleBeginPlaying(!1),this.shouldUseM3U){this.ensureM3UCanBePlayed();return}Pr&&console.log("Video Play()",this.clip,this._videoElement,this.time),this._videoElement.currentTime=this.time,this._videoElement.play().catch(r=>{var s;console.log(r),Pr&&console.error("Error playing video",r,"CODE="+r.code,(s=this.videoElement)==null?void 0:s.src,this),setTimeout(()=>{this._isPlaying&&!this.destroyed&&this.activeAndEnabled&&this.play()},1e3)}),Pr&&console.log("play",this._videoElement,this.time)}}stop(){this._isPlaying=!1,this.time=0,this._videoElement&&(this._videoElement.currentTime=0,this._videoElement.pause(),Pr&&console.log("STOP",this))}pause(){var e,t;this.time=((e=this._videoElement)==null?void 0:e.currentTime)??0,this._isPlaying=!1,(t=this._videoElement)==null||t.pause(),Pr&&console.log("PAUSE",this,this.currentTime)}create(e){let t;switch(this.source){case 0:t=this.clip;break;case 1:t=this.url,!(t!=null&&t.length)&&typeof this.clip=="string"&&(t=this.clip);break}return t?(this._videoElement||(Pr&&console.warn("Create VideoElement",this),this._videoElement=this.createVideoElement(),this.context.domElement.shadowRoot.prepend(this._videoElement),this.updateVideoElementStyles()),typeof t=="string"?(Pr&&console.log("Set Video src",t),this._videoElement.src=t):(Pr&&console.log("Set Video srcObject",t),this._videoElement.srcObject=t),this._videoTexture||(this._videoTexture=new I3(this._videoElement)),this._videoTexture.flipY=!1,this._videoTexture.colorSpace=ft,e&&this.handleBeginPlaying(e),Pr&&console.log("Video: handle playing done...",t,e),!0):(Pr&&console.warn("No video source set",this),!1)}updateAspect(){this.aspectMode!==0&&this.startCoroutine(this.updateAspectImpl())}get screenspace(){var e;return((e=this._overlay)==null?void 0:e.enabled)??!1}set screenspace(e){var t;if(e){if(!this._videoTexture)return;this._overlay||(this._overlay=new QAe(this.context)),this._overlay.add(this._videoTexture)}else(t=this._overlay)==null||t.remove(this._videoTexture);this._overlay&&(this._overlay.enabled=e)}createVideoElement(){const e=document.createElement("video");return this._crossOrigin&&e.setAttribute("crossorigin",this._crossOrigin),Pr&&console.log("created video element",e),e}handleBeginPlaying(e){var t,r;if(!this.activeAndEnabled||!this._videoElement)return;this._targetObjects.length=0;let s=this.gameObject;switch(this.renderMode){case 3:s=(t=this.targetMaterialRenderer)==null?void 0:t.gameObject,s||(s=(r=ie.getComponent(this.gameObject,Tn))==null?void 0:r.gameObject);break;case 2:console.error("VideoPlayer renderTexture not implemented yet. Please use material override instead");return}if(!s){console.error("Missing target for video material renderer",this.name,KH[this.renderMode],this);return}const o=s.material;if(o){this._targetObjects.push(s),o!==this._videoMaterial&&(this._videoMaterial=o.clone(),s.material=this._videoMaterial);const a="map",l=this._videoMaterial;if(!this.targetMaterialProperty)l[a]=this._videoTexture;else switch(this.targetMaterialProperty){default:l[a]=this._videoTexture;break}}else{console.warn("Can not play video, no material found, this might be a multimaterial case which is not supported yet");return}this.updateVideoElementSettings(),this.updateVideoElementStyles(),e&&(this.shouldUseM3U&&this.ensureM3UCanBePlayed(),this.play())}updateVideoElementSettings(){if(!this._videoElement)return;this._videoElement.loop=this._isLooping,this._videoElement.currentTime=this.currentTime,this._videoElement.playbackRate=this._playbackSpeed,this._videoElement.playsInline=!0;let e=!this._receivedInput||this.audioOutputMode===0;!e&&this._muted&&(e=!0),this._videoElement.muted=e,this.playOnAwake&&(this._videoElement.autoplay=!0)}updateVideoElementStyles(){this._videoElement&&(this._videoElement.style.userSelect="none",this._videoElement.style.visibility="hidden",this._videoElement.style.display="none",this.updateAspect())}*updateAspectImpl(){const e=++this._updateAspectRoutineId,t=void 0,r=this.clip;for(;e===this._updateAspectRoutineId&&this.aspectMode!==0&&this.clip&&r===this.clip&&this._isPlaying;){if(!r||typeof r=="string")return;let s;for(const o of r.getVideoTracks()){const a=o.getSettings();if(a&&a.width&&a.height){s=a.width/a.height;break}else s=this.context.renderer.domElement.clientWidth/this.context.renderer.domElement.clientHeight}if(s===void 0){for(let o=0;o<10;o++)yield;if(!this.isPlaying)break;continue}if(t===s){yield;continue}for(const o of this._targetObjects){let a=1;if(o.parent){const l=Vi(o.parent);a=l.x/l.y}switch(this.aspectMode){case 1:o.scale.y=1/s*o.scale.x*a;break;case 2:o.scale.x=s*o.scale.y*a;break}}for(let o=0;o<3;o++)yield}}get shouldUseM3U(){return this.url!=null&&(this.url.endsWith(".m3u8")||this.url.endsWith(".m3u"))&&this.source===1}ensureM3UCanBePlayed(){if(!this.shouldUseM3U)return;let e=document.head.querySelector("script[data-hls_library]");e?globalThis.Hls?this.onHlsAvailable():e.addEventListener("load",this.onHlsAvailable):(Pr&&console.log("HLS: load script"),e=document.createElement("script"),e.dataset.hls_library="hls.js",e.src="https://cdn.jsdelivr.net/npm/hls.js@1",e.addEventListener("load",this.onHlsAvailable),document.head.append(e))}}Jo([w()],dr.prototype,"playOnAwake",2),Jo([w()],dr.prototype,"aspectMode",2),Jo([w(URL)],dr.prototype,"clip",2),Jo([w()],dr.prototype,"source",2),Jo([w(URL)],dr.prototype,"url",1),Jo([w()],dr.prototype,"renderMode",2),Jo([w()],dr.prototype,"targetMaterialProperty",2),Jo([w(Tn)],dr.prototype,"targetMaterialRenderer",2),Jo([w(zt)],dr.prototype,"targetTexture",2),Jo([w()],dr.prototype,"time",2),Jo([w()],dr.prototype,"playbackSpeed",1),Jo([w()],dr.prototype,"isLooping",1),Jo([w()],dr.prototype,"audioOutputMode",1);class QAe{constructor(e){d(this,"context"),d(this,"_videos",[]),d(this,"_screenspaceModeQuad"),d(this,"_isInScreenspaceMode",!1),d(this,"_input"),this.context=e,this._input=new HAe(this)}get enabled(){return this._isInScreenspaceMode}set enabled(e){e?this.start():this.stop()}add(e){this._videos.indexOf(e)===-1&&this._videos.push(e)}remove(e){if(!e)return;const t=this._videos.indexOf(e);t>=0&&this._videos.splice(t,1)}start(){var e;if(this._isInScreenspaceMode||this._videos.length<0)return;const t=this._videos[this._videos.length-1];if(!t)return;if(this._isInScreenspaceMode=!0,!this._screenspaceModeQuad){if(this._screenspaceModeQuad=sA.createPrimitive(Yp.Quad,{material:new WAe(t)}),!this._screenspaceModeQuad)return;this._screenspaceModeQuad.geometry.scale(2,2,2)}const r=this._screenspaceModeQuad;this.context.scene.add(r),this.updateScreenspaceMaterialUniforms();const s=r.material;s?.reset(),(e=this._input)==null||e.enable(s)}stop(){var e;this._isInScreenspaceMode=!1,this._screenspaceModeQuad&&((e=this._input)==null||e.disable(),this._screenspaceModeQuad.removeFromParent())}updateScreenspaceMaterialUniforms(){var e;const t=(e=this._screenspaceModeQuad)==null?void 0:e.material;t&&(t.screenAspect=this.context.domElement.clientWidth/this.context.domElement.clientHeight)}}class HAe{constructor(e){d(this,"_onResizeScreenFn"),d(this,"_onKeyUpFn"),d(this,"_onMouseWheelFn"),d(this,"context"),d(this,"overlay"),d(this,"_material"),d(this,"_isPinching",!1),d(this,"_lastPinch",0),this.overlay=e,this.context=e.context}enable(e){this._material=e,window.addEventListener("resize",this._onResizeScreenFn=()=>{this.overlay.updateScreenspaceMaterialUniforms()}),window.addEventListener("keyup",this._onKeyUpFn=s=>{s.key==="Escape"&&this.overlay.stop()}),window.addEventListener("wheel",this._onMouseWheelFn=s=>{this.overlay.enabled&&(e.zoom+=s.deltaY*5e-4,s.preventDefault())},{passive:!1});const t=new Z;window.addEventListener("mousemove",s=>{if(this.overlay.enabled&&this.context.input.getPointerPressed(0)){const o=new Z(s.movementX,s.movementY);o.x/=this.context.domElement.clientWidth,o.y/=this.context.domElement.clientHeight,t.set(o.x,o.y),t.multiplyScalar(e.zoom/-this.context.time.deltaTime*.01),e.offset=e.offset.add(t)}}),window.addEventListener("pointermove",s=>{this.overlay.enabled&&this.context.input.getPointerPressed(0)&&this.context.input.getTouchesPressedCount()===1&&(t.set(s.movementX,s.movementY),t.multiplyScalar(e.zoom*-this.context.time.deltaTime*.05),e.offset=e.offset.add(t))});let r=0;window.addEventListener("touchstart",s=>{if(s.touches.length<2){this.context.time.time-r<.3&&this.overlay.stop(),r=this.context.time.time;return}this._isPinching=!0,this._lastPinch=0}),window.addEventListener("touchmove",s=>{if(!this._isPinching||!this._material)return;const o=s.touches[0],a=s.touches[1],l=o.clientX-a.clientX,c=o.clientY-a.clientY,h=Math.sqrt(l*l+c*c);if(this._lastPinch!==0){const u=h-this._lastPinch;this._material.zoom-=u*.004}this._lastPinch=h}),window.addEventListener("touchend",()=>{this._isPinching=!1})}disable(){this._onResizeScreenFn&&(window.removeEventListener("resize",this._onResizeScreenFn),this._onResizeScreenFn=void 0),this._onKeyUpFn&&(window.removeEventListener("keyup",this._onKeyUpFn),this._onKeyUpFn=void 0),this._onMouseWheelFn&&(window.removeEventListener("wheel",this._onMouseWheelFn),this._onMouseWheelFn=void 0)}}class WAe extends Rt{constructor(e){super(),d(this,"_offset",new Z),this.uniforms={map:{value:e},screenAspect:{value:1},offsetScale:{value:new Ye(0,0,1,1)}},this.vertexShader=`
7589
+ `;class QH extends Ys{constructor(){super("Sharpening",RAe,{vertexShader:IAe,blendFunction:jt.NORMAL,uniforms:new Map([["amount",new Se(1)],["radius",new Se(1)]])})}}const km=te("debugpost"),hO=Symbol("needle:postprocessing-handler"),uO=Symbol("needle:previous-autoclear-state");class lE{constructor(e){d(this,"_composer",null),d(this,"_lastVolumeComponents"),d(this,"_effects",[]),d(this,"_isActive",!1),d(this,"context"),this.context=e}get isActive(){return this._isActive}get composer(){return this._composer}apply(e){this._isActive=!0,this.onApply(this.context,e)}unapply(){var e;if(km&&console.log("Unapplying postprocessing effects"),this._isActive=!1,this._lastVolumeComponents){for(const r of this._lastVolumeComponents)r.unapply();this._lastVolumeComponents.length=0}const t=this.context;t[hO]===this&&delete t[hO],t.composer===this._composer&&((e=t.composer)==null||e.dispose(),t.composer=null),typeof t.renderer[uO]=="boolean"&&(t.renderer.autoClear=t.renderer[uO])}dispose(){this.unapply();for(const e of this._effects)e.dispose();this._effects.length=0,this._composer=null}onApply(e,t){if(!t)return;e[hO]=this,km&&console.log("refreshing volume profile",t),this._lastVolumeComponents=[...t],this._effects.length=0;const r={handler:this,components:this._lastVolumeComponents};for(let s=0;s<this._lastVolumeComponents.length;s++){const o=this._lastVolumeComponents[s];if(o.context=e,o.apply){if(o.active){if(!e.mainCameraComponent){console.error("No camera in scene found or available yet - can not create postprocessing effects");return}const a=o.apply(r);if(!a)continue;Array.isArray(a)?this._effects.push(...a):this._effects.push(a)}}else o.active&&Di("Volume component is not a VolumeComponent: "+o.__type)}if(this.context.renderer.toneMapping!=Ls&&!this._effects.find(s=>s instanceof U1)){const s=new U1;this._effects.push(s)}this.applyEffects(e)}applyEffects(e){const t=this._effects;if(t.length<=0)return;const r=e.mainCameraComponent,s=e.renderer,o=e.scene,a=r.cam;s[uO]=s.autoClear;const l=s.capabilities.maxSamples;this._composer||(this._composer=new JP(s,{frameBufferType:rr,stencilBuffer:!0,multisampling:Math.min(aa()?4:8,l)})),e.composer&&e.composer!==this._composer&&console.warn("There's already an active EffectComposer in your scene: replacing it with a new one. This might cause unexpected behaviour. Make sure to only use one PostprocessingManager/Volume in your scene."),e.composer=this._composer;const c=e.composer;c.setMainCamera(a),c.setRenderer(s),c.setMainScene(o);for(const u of c.passes)u.dispose();c.removeAllPasses();const h=new F1(o,a);h.name="Render To Screen",h.mainScene=o,c.addPass(h);try{this.orderEffects();const u=[];for(const p of t)if(p instanceof Ys)u.push(p);else if(p instanceof jr){const m=new u6(a,...u);m.mainScene=o,m.name=u.map(f=>f.constructor.name).join(", "),m.enabled=!0,u.length=0,c.addPass(p)}if(u.length>0){const p=new u6(a,...u);p.name=u.map(m=>m.name).join(" "),p.mainScene=o,p.enabled=!0,c.addPass(p)}}catch(u){console.error("Error while applying postprocessing effects",u),c.removeAllPasses()}km&&console.log("PostProcessing Passes",t,"->",c.passes)}orderEffects(){var e;km&&console.log("Before ordering effects",[...this._effects]);const t=this._effects;t.sort((r,s)=>{const o=dO.findIndex(l=>r.constructor.name.endsWith(l.name)),a=dO.findIndex(l=>s.constructor.name.endsWith(l.name));return o<0?(km&&console.warn("Unknown effect found: ",r.constructor.name),-1):a<0?(km&&console.warn("Unknown effect found: ",s.constructor.name),1):o<0?1:a<0?-1:o-a}),km&&console.log("After ordering effects",[...this._effects]);for(let r=0;r<t.length;r++){const s=t[r];if(((e=s?.configuration)==null?void 0:e.gammaCorrection)!==void 0){const o=r===t.length-1;s.configuration.gammaCorrection=o}}}}const dO=[d6,tB,s6,a6,GH,l6,$5,J5,$P,i6,c6,t6,U1,e6,Y5,QH];async function pO(n){const{NeedleEngineHTMLElement:e}=await Promise.resolve().then(()=>p_e);e.observedAttributes.includes(n)||e.observedAttributes.push(n)}var PAe=Object.defineProperty,BAe=Object.getOwnPropertyDescriptor,kb=(n,e,t,r)=>{for(var s=r>1?void 0:r?BAe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&PAe(e,t,s),s};const Ua=te("debugskybox");pO("skybox-image"),pO("environment-image");function HH(n,e,t,r,s){const o=new wc;o.allowDrop=!1,o.allowNetworking=!1,o.background=t,o.environment=r,ie.addComponent(n.scene,o);const a=l=>{typeof l=="string"&&(Ua&&console.log(s,"CHANGED TO",l),o.setSkybox(l))};return GU(n.domElement,s,a),o.addEventListener("destroy",()=>{Ua&&console.log("Destroyed attribute remote skybox",s),VU(n.domElement,s,a)}),o.setSkybox(e)}di.addContextCreatedCallback(n=>{var e;const t=n.context,r=t.domElement.getAttribute("skybox-image"),s=t.domElement.getAttribute("environment-image"),o=new Array;if(r){Ua&&console.log("Creating remote skybox to load "+r),((e=t.mainCameraComponent)==null?void 0:e.clearFlags)!==$u.Skybox&&console.warn('"skybox-image" attribute has no effect: camera clearflags are not set to "Skybox"');const a=HH(t,r,!0,!1,"skybox-image");o.push(a)}if(s){Ua&&console.log("Creating remote environment to load "+s);const a=HH(t,s,!1,!0,"environment-image");o.push(a)}return o.length>0?tw(o):Promise.resolve()});function WH(){return globalThis.NEEDLE_ENGINE_SKYBOX_TEXTURES||(globalThis.NEEDLE_ENGINE_SKYBOX_TEXTURES=new Array),globalThis.NEEDLE_ENGINE_SKYBOX_TEXTURES}function XH(n){const e=WH().find(t=>t.src===n);return e?(Ua&&console.log("Skybox: Found previously loaded texture for "+n),e.texture):null}async function kAe(n){const e=await n;UP(e,!0),Qi(e)}function DAe(n,e){const t=WH();for(;t.length>5;){const r=t.shift();r&&kAe(r.texture)}e.then(r=>UP(r,!1)),t.push({src:n,texture:e})}class wc extends Be{constructor(){super(...arguments),d(this,"url"),d(this,"allowDrop",!0),d(this,"background",!0),d(this,"environment",!0),d(this,"allowNetworking",!0),d(this,"_loader"),d(this,"_prevUrl"),d(this,"_prevLoadedEnvironment"),d(this,"_prevEnvironment",null),d(this,"_prevBackground",null),d(this,"validTextureTypes",[".hdr",".exr",".jpg",".jpeg",".png"]),d(this,"onDragOverEvent",e=>{if(this.allowDrop&&e.dataTransfer)for(const t of e.dataTransfer.types)(t==="text/uri-list"||t==="Files")&&e.preventDefault()}),d(this,"onDrop",e=>{var t,r,s,o;if(this.allowDrop&&e.dataTransfer){for(const a of e.dataTransfer.types)if(Ua&&console.log(a),a==="text/uri-list"){const l=e.dataTransfer.getData(a);Ua&&console.log(a,l);let c=(r=(t=new RegExp(/polyhaven.com\/asset_img\/.+?\/(?<name>.+)\.png/).exec(l))==null?void 0:t.groups)==null?void 0:r.name;if(c||(c=(o=(s=new RegExp(/polyhaven\.com\/a\/(?<name>.+)/).exec(l))==null?void 0:s.groups)==null?void 0:o.name),Ua&&console.log(c),c){const h="https://dl.polyhaven.org/file/ph-assets/HDRIs/exr/1k/"+c+"_1k.exr";console.log(`[Remote Skybox] Setting skybox from url: ${h}`),e.preventDefault(),this.setSkybox(h);break}else if(this.isValidTextureType(l)){console.log("[Remote Skybox] Setting skybox from url: "+l),e.preventDefault(),this.setSkybox(l);break}else{console.warn(`[RemoteSkybox] Unknown url ${l}. If you want to load a skybox from a url, make sure it is a valid image url. Url must end with${this.validTextureTypes.join(", ")}.`);const h=new CustomEvent("dropped-unknown-url",{detail:{sender:this,event:e,url:l,apply:u=>{e.preventDefault(),this.setSkybox(u)}}});this.dispatchEvent(h)}}else if(a=="Files"){const l=e.dataTransfer.files.item(0);if(Ua&&console.log(a,l),!l)continue;if(!this.isValidTextureType(l.name)){console.warn(`[RemoteSkybox]: File "${l.name}" is not supported. Supported files are ${this.validTextureTypes.join(", ")}`);return}if(XH(l.name)===null){const c=new Blob([l]),h=URL.createObjectURL(c);e.preventDefault(),this.setSkybox(h,l.name)}else e.preventDefault(),this.setSkybox(l.name);break}}})}onEnable(){this.setSkybox(this.url),this.registerDropEvents()}onDisable(){var e;this.context.scene.environment===this._prevLoadedEnvironment&&(this.context.scene.environment=this._prevEnvironment,Li.backgroundShouldBeTransparent(this.context)||(this.context.scene.background=this._prevBackground),this._prevLoadedEnvironment=void 0),this.unregisterDropEvents(),(e=this.context.mainCameraComponent)==null||e.applyClearFlags()}urlChangedSyncField(){this.allowNetworking&&this.url&&this.isRemoteTexture(this.url)&&this.setSkybox(this.url)}async setSkybox(e,t){var r;if(!this.activeAndEnabled||(e=OAe(e,this.environment,this.background),!e))return!1;if(t??(t=e),this.isValidTextureType(t)||console.warn("Potentially invalid skybox url",t,"on",this.name),Ua&&console.log("Set remote skybox url: "+e),this._prevUrl===e&&this._prevLoadedEnvironment)return this.applySkybox(),!0;(r=this._prevLoadedEnvironment)==null||r.dispose(),this._prevLoadedEnvironment=void 0,this._prevUrl=e;const s=await this.loadTexture(e,t);if(!s||!this.enabled)return!1;this.url=e;const o=e.lastIndexOf("/");return s.name=e.substring(o>=0?o+1:0),this._loader instanceof Dl&&(s.colorSpace=ft),this._prevLoadedEnvironment=s,this.applySkybox(),!0}async loadTexture(e,t){var r,s,o,a,l;if(!e)return Promise.resolve(null);t??(t=e);const c=XH(t);if(c){const m=await c;if(((s=(r=m.source)==null?void 0:r.data)==null?void 0:s.length)>0||(l=(a=(o=m.source)==null?void 0:o.data)==null?void 0:a.data)!=null&&l.length)return m}const h=t.endsWith(".exr"),u=t.endsWith(".hdr");h?this._loader instanceof oA||(this._loader=new oA):u?this._loader instanceof uS||(this._loader=new uS):this._loader instanceof Dl||(this._loader=new Dl),Ua&&console.log("Loading skybox: "+e);const p=this._loader.loadAsync(e);return DAe(t,p),await p}applySkybox(){var e;const t=this._prevLoadedEnvironment;t&&(t.mapping=Ym,t.needsUpdate=!0,this.context.scene.background!==t&&(this._prevBackground=this.context.scene.background),this.context.scene.environment!==t&&(this._prevEnvironment=this.context.scene.environment),Ua&&console.log("Set remote skybox",this.url,!Li.backgroundShouldBeTransparent(this.context)),this.environment&&(this.context.scene.environment=t),this.background&&!Li.backgroundShouldBeTransparent(this.context)&&(this.context.scene.background=t),((e=this.context.mainCameraComponent)==null?void 0:e.backgroundBlurriness)!==void 0&&(this.context.scene.backgroundBlurriness=this.context.mainCameraComponent.backgroundBlurriness))}isRemoteTexture(e){return e.startsWith("http://")||e.startsWith("https://")}isValidTextureType(e){for(const t of this.validTextureTypes)if(e.endsWith(t))return!0;return!1}registerDropEvents(){this.unregisterDropEvents(),this.context.domElement.addEventListener("dragover",this.onDragOverEvent),this.context.domElement.addEventListener("drop",this.onDrop)}unregisterDropEvents(){this.context.domElement.removeEventListener("dragover",this.onDragOverEvent),this.context.domElement.removeEventListener("drop",this.onDrop)}}kb([Ek(wc.prototype.urlChangedSyncField),w(URL)],wc.prototype,"url",2),kb([w()],wc.prototype,"allowDrop",2),kb([w()],wc.prototype,"background",2),kb([w()],wc.prototype,"environment",2),kb([w()],wc.prototype,"allowNetworking",2);function OAe(n,e,t){const r=e&&!t;switch(n?.toLowerCase()){case"studio":return r?"https://cdn.needle.tools/static/skybox/modelviewer-Neutral-small.hdr":"https://cdn.needle.tools/static/skybox/modelviewer-Neutral.hdr";case"blurred-skybox":return r?"https://cdn.needle.tools/static/skybox/blurred-skybox-small.exr":"https://cdn.needle.tools/static/skybox/blurred-skybox.exr";case"quicklook-ar":return r?"https://cdn.needle.tools/static/skybox/QuickLook-ARMode-small.exr":"https://cdn.needle.tools/static/skybox/QuickLook-ARMode.exr";case"quicklook":return r?"https://cdn.needle.tools/static/skybox/QuickLook-ObjectMode-small.exr":"https://cdn.needle.tools/static/skybox/QuickLook-ObjectMode.exr"}return n===void 0?null:n}var LAe=Object.defineProperty,FAe=Object.getOwnPropertyDescriptor,qo=(n,e,t,r)=>{for(var s=r>1?void 0:r?FAe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&LAe(e,t,s),s};const Yo=te("debugsceneswitcher"),cE="scene";pO(cE);const Cd=Promise.resolve(!1);class ks extends Be{constructor(){super(...arguments),d(this,"autoLoadFirstScene",!0),d(this,"scenes",[]),d(this,"loadingScene"),d(this,"queryParameterName","scene"),d(this,"useSceneName",!0),d(this,"clamp",!0),d(this,"useHistory",!0),d(this,"useKeyboard",!0),d(this,"useSwipe",!0),d(this,"useSceneLighting",!0),d(this,"preloadNext",1),d(this,"preloadPrevious",1),d(this,"preloadConcurrent",2),d(this,"_currentIndex",-1),d(this,"_currentScene"),d(this,"_engineElementOverserver"),d(this,"_preloadScheduler"),d(this,"onPopState",async e=>{if(!this.useHistory)return;const t=this.useHistory;try{this.useHistory=!1;let r=!1;if(this.queryParameterName&&(r=await this.tryLoadFromQueryParam()),!r){const s=e?.state;if(s&&s.startsWith(this.guid)){const o=s.substr(this.guid.length+2);Yo&&console.log("PopState",o),await this.trySelectSceneFromValue(o)}}}finally{this.useHistory=t}}),d(this,"normalizedSwipeThresholdX",.1),d(this,"_didSwipe",!1),d(this,"onInputPointerMove",e=>{if(this.useSwipe&&!this._didSwipe&&e.button===0&&e.pointerType==="touch"&&this.context.input.getPointerPressedCount()===1){const t=this.context.input.getPointerPositionDelta(e.button);if(t){const r=t.x/this.context.domWidth;r>=this.normalizedSwipeThresholdX?(this._didSwipe=!0,this.selectPrev()):r<=-this.normalizedSwipeThresholdX&&(this._didSwipe=!0,this.selectNext())}}}),d(this,"onInputPointerUp",e=>{e.button===0&&(this._didSwipe=!1)}),d(this,"onInputKeyDown",e=>{if(!this.useKeyboard||!this.scenes)return;const t=e.key.toLowerCase();if(!t)return;const r=parseInt(t)-1;if(r>=0){this.trySelectSceneFromValue(r);return}switch(t){case"arrowright":case"d":this.selectNext();break;case"arrowleft":case"a":this.selectPrev();break}}),d(this,"__lastSwitchScene"),d(this,"__lastSwitchScenePromise"),d(this,"_currentlyLoadingScene"),d(this,"_lastLoadingScene"),d(this,"_loadingScenePromise"),d(this,"_isCurrentlyLoading",!1),d(this,"_currentLoadingProgress")}get currentIndex(){return this._currentIndex}get currentLoadingProgress(){return this._currentLoadingProgress}get currentlyLoadingScene(){return this._currentlyLoadingScene}get currentlyLoadedScene(){return this._currentScene}awake(){this.scenes===void 0&&(this.scenes=[]);for(const e of this.scenes)e&&!e.hasUrl&&e.asset instanceof ye&&e.asset.removeFromParent();Yo&&console.log("SceneSwitcher",this)}async onEnable(){if(globalThis.addEventListener("popstate",this.onPopState),this.context.input.addEventListener(an.KeyDown,this.onInputKeyDown),this.context.input.addEventListener(an.PointerMove,this.onInputPointerMove),this.context.input.addEventListener(an.PointerUp,this.onInputPointerUp),this._engineElementOverserver||(this._engineElementOverserver=new MutationObserver(e=>{for(const t of e)if(t.type==="attributes"&&t.attributeName===cE){const r=this.context.domElement.getAttribute(cE);r!==null&&this.trySelectSceneFromValue(r)}})),this._engineElementOverserver.observe(this.context.domElement,{attributes:!0}),this._preloadScheduler||(this._preloadScheduler=new UAe(this)),this._preloadScheduler.maxLoadAhead=this.preloadNext,this._preloadScheduler.maxLoadBehind=this.preloadPrevious,this._preloadScheduler.maxConcurrent=this.preloadConcurrent,this._preloadScheduler.begin(),this.autoLoadFirstScene&&this._currentIndex===-1&&!await this.tryLoadFromQueryParam()){const e=this.context.domElement.getAttribute(cE);try{(e===null||!await this.trySelectSceneFromValue(e))&&this._currentIndex===-1&&this.select(0)}finally{}}}onDisable(){var e;globalThis.removeEventListener("popstate",this.onPopState),this.context.input.removeEventListener(an.KeyDown,this.onInputKeyDown),this.context.input.removeEventListener(an.PointerMove,this.onInputPointerMove),this.context.input.removeEventListener(an.PointerUp,this.onInputPointerUp),(e=this._preloadScheduler)==null||e.stop()}addScene(e){if(typeof e=="string"){let t=this.context.addressables.findAssetReference(e);return t||(t=new ti(e),this.context.addressables.registerAssetReference(t)),this.scenes.push(t),t}return this.scenes.push(e),e}selectNext(){return this.select(this._currentIndex+1)}selectPrev(){return this.select(this._currentIndex-1)}select(e){var t,r,s;if(Yo&&console.log("select",e),typeof e=="object"&&console.warn('Switching to "'+e+'" might not work. Please either use an index or a AssetReference (not a scene reference)'),typeof e=="string"){const a=(t=this.scenes)==null?void 0:t.find(l=>l.uri===e);if(!a){const l=ti.getOrCreate(this.sourceId??"",e,this.context);return this.switchScene(l)}if(a)e=(r=this.scenes)==null?void 0:r.indexOf(a);else return Cd}if(!((s=this.scenes)!=null&&s.length))return Cd;if(e<0){if(this.clamp)return Cd;e=this.scenes.length-1}else if(e>=this.scenes.length){if(this.clamp)return Cd;e=0}const o=this.scenes[e];return this.switchScene(o)}async switchScene(e){if(!(e instanceof ti)){const t=typeof e;return t==="string"?this.select(e):t==="number"?this.select(e):(console.warn("SceneSwitcher: Can't switch to scene",e,"of type",t),!1)}return e.uri===this.sourceId?(console.warn("SceneSwitcher: can't load own scene - prevent recursive loading",this.sourceId),!1):this.__lastSwitchScene===e&&this.__lastSwitchScenePromise?this.__lastSwitchScenePromise:(this.__lastSwitchScene=e,this.__lastSwitchScenePromise=this.__internalSwitchScene(e),await this.__lastSwitchScenePromise)}async __internalSwitchScene(e){var t,r;if(this._currentScene){Yo&&console.log("UNLOAD",this._currentScene.url,"HasURL?: "+this._currentScene.hasUrl);const o=this.tryGetSceneEventListener(this._currentScene.asset);if(o!=null&&o.sceneClosing){const a=o.sceneClosing();a instanceof Promise&&await a}this._currentScene.hasUrl?this._currentScene.unload():this._currentScene.asset instanceof ye&&this._currentScene.asset.removeFromParent()}this._currentScene=void 0;const s=this._currentIndex=((t=this.scenes)==null?void 0:t.indexOf(e))??-1;try{this._currentlyLoadingScene=e,this._currentLoadingProgress=new ProgressEvent("progress",{loaded:0,total:1});const o=new CustomEvent("loadscene-start",{detail:{scene:e,switcher:this,index:s}});this.dispatchEvent(o),await this.onStartLoading(),await e.loadAssetAsync((l,c)=>{this._currentLoadingProgress=c,this.dispatchEvent(c)}).catch(console.error),await this.onEndLoading();const a=new CustomEvent("loadscene-finished",{detail:{scene:e,switcher:this,index:s}});if(this.dispatchEvent(a),this._currentLoadingProgress=void 0,this._currentlyLoadingScene=void 0,a.defaultPrevented)return Yo&&console.warn("Adding loaded scene prevented:",e,a),!1;if(!e.asset)return Yo&&console.warn("Failed loading scene:",e),!1;if(this._currentIndex===s){if(Yo&&console.log("ADD",e.uri),this._currentScene=e,ie.add(e.asset,this.gameObject),this.useSceneLighting&&this.context.sceneLighting.enable(e),this.useHistory&&s>=0){let h=s.toString();if(this.useSceneName&&(h=qH(e.uri)),(r=this.queryParameterName)!=null&&r.length)Jx(this.queryParameterName,h,this.useHistory);else{const u=history.state,p=this.guid+"::"+s;u!==p&&history.pushState(p,"unused",location.href)}}const l=this.tryGetSceneEventListener(e.asset);if(l!=null&&l.sceneOpened){const h=l.sceneOpened(this);h instanceof Promise&&await h}const c=new CustomEvent("scene-opened",{detail:{scene:e,switcher:this,index:s}});return this.dispatchEvent(c),!0}}catch(o){console.error(o)}return!1}preload(e){if(e>=0&&e<this.scenes.length){const t=this.scenes[e];if(t instanceof ti)return t.preload()}return Cd}tryLoadFromQueryParam(){var e;if(!((e=this.queryParameterName)!=null&&e.length))return Cd;const t=te(this.queryParameterName);return typeof t=="boolean"?Cd:this.trySelectSceneFromValue(t)}trySelectSceneFromValue(e){if(typeof e=="string"){const t=parseInt(e);if(t>=0&&t<this.scenes.length)return this.select(t);{const r=e.toLowerCase();for(let s=0;s<this.scenes.length;s++){const o=this.scenes[s];if(o&&qH(o.uri).toLowerCase().includes(r))return this.select(s)}}}else if(typeof e=="number"&&e>=0&&e<this.scenes.length)return this.select(e);return js()&&console.warn('Can not find scene: "'+e+'"',this),Cd}async onStartLoading(){var e,t;if(this._isCurrentlyLoading=!0,this.loadingScene&&(this._lastLoadingScene!==this.loadingScene&&(this._loadingScenePromise=void 0),this._lastLoadingScene=this.loadingScene,this._loadingScenePromise||(this._loadingScenePromise=(e=this.loadingScene)==null?void 0:e.loadAssetAsync()),await this._loadingScenePromise,this._isCurrentlyLoading&&(t=this.loadingScene)!=null&&t.asset)){Yo&&console.log("Add loading scene",this.loadingScene.uri,this.loadingScene.asset);const r=this.loadingScene.asset;ie.add(r,this.gameObject);const s=this.tryGetSceneEventListener(r);if(s!=null&&s.sceneOpened){const o=s.sceneOpened(this);o instanceof Promise&&await o}}if(this._isCurrentlyLoading){const r=this.tryGetSceneEventListener(this.gameObject);if(r&&r.sceneOpened){const s=r.sceneOpened(this);s instanceof Promise&&await s}}}async onEndLoading(){var e;if(this._isCurrentlyLoading=!1,(e=this.loadingScene)!=null&&e.asset){Yo&&console.log("Remove loading scene",this.loadingScene.uri);const t=this.loadingScene.asset,r=this.tryGetSceneEventListener(t);if(typeof r?.sceneClosing=="function"){const s=r.sceneClosing();s instanceof Promise&&await s}ie.remove(t)}if(!this._isCurrentlyLoading){const t=this.tryGetSceneEventListener(this.gameObject);if(t&&t.sceneClosing){const r=t.sceneClosing();r instanceof Promise&&await r}}}tryGetSceneEventListener(e,t=0){const r=ie.foreachComponent(e,s=>s.sceneClosing?s:void 0);if(t===0&&!r&&e.children.length)for(const s of e.children){const o=this.tryGetSceneEventListener(s,t+1);if(o)return o}return r||null}}qo([w()],ks.prototype,"autoLoadFirstScene",2),qo([w(ti)],ks.prototype,"scenes",2),qo([w(ti)],ks.prototype,"loadingScene",2),qo([w()],ks.prototype,"queryParameterName",2),qo([w()],ks.prototype,"useSceneName",2),qo([w()],ks.prototype,"clamp",2),qo([w()],ks.prototype,"useHistory",2),qo([w()],ks.prototype,"useKeyboard",2),qo([w()],ks.prototype,"useSwipe",2),qo([w()],ks.prototype,"useSceneLighting",2),qo([w()],ks.prototype,"preloadNext",2),qo([w()],ks.prototype,"preloadPrevious",2),qo([w()],ks.prototype,"preloadConcurrent",2);function qH(n){const e=n.split("/").pop(),t=e?.split(".").shift();return t!=null&&t.length?t:n}class UAe{constructor(e,t=1,r=1,s=2){d(this,"maxLoadAhead"),d(this,"maxLoadBehind"),d(this,"maxConcurrent"),d(this,"_isRunning",!1),d(this,"_switcher"),d(this,"_loadTasks",[]),d(this,"_maxConcurrentLoads",1),this._switcher=e,this.maxLoadAhead=t,this.maxLoadBehind=r,this.maxConcurrent=s}begin(){if(this._isRunning)return;Yo&&console.log("Preload begin"),this._isRunning=!0;let e=-1,t,r;const s=this._switcher.scenes,o=setInterval(()=>{if(this.allLoaded()&&(Yo&&console.log("All scenes loaded"),this.stop()),!this._isRunning){clearInterval(o);return}if(this.canLoadNewScene()===!1)return;e!==this._switcher.currentIndex&&(e=this._switcher.currentIndex,r=0,t=0);const a=r%2===0;a&&(t+=1),r+=1;const l=a?this.maxLoadAhead:this.maxLoadBehind;if(t>l)return;const c=a?e+t:e-t;if(c<0||c<0||c>=s.length)return;const h=s[c];new NAe(c,h,this._loadTasks)},200)}stop(){this._isRunning=!1}canLoadNewScene(){return this._loadTasks.length<this._maxConcurrentLoads}allLoaded(){if(this._switcher.scenes){for(const e of this._switcher.scenes)if(e?.isLoaded()===!1)return!1}return!0}}class NAe{constructor(e,t,r){d(this,"index"),d(this,"asset"),d(this,"tasks"),this.index=e,this.asset=t,this.tasks=r,r.push(this),this.awaitLoading()}async awaitLoading(){this.asset&&!this.asset.isLoaded()&&(Yo&&console.log("Preload start: "+this.asset.uri,this.index),await this.asset.preload(),Yo&&console.log("Preload finished: "+this.asset.uri,this.index));const e=this.tasks.indexOf(this);e>=0&&this.tasks.splice(e,1)}}function zAe(){return new Promise((n,e)=>{const t=()=>{t!=null&&(document.removeEventListener("pointerdown",t),document.removeEventListener("click",t),document.removeEventListener("dragstart",t),document.removeEventListener("touchstart",t),n())};document.addEventListener("pointerdown",t),document.addEventListener("click",t),document.addEventListener("dragstart",t),document.addEventListener("touchstart",t)})}async function jAe(n){await zAe(),n()}var GAe=Object.defineProperty,VAe=Object.getOwnPropertyDescriptor,Jo=(n,e,t,r)=>{for(var s=r>1?void 0:r?VAe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&GAe(e,t,s),s};const Pr=te("debugvideo");var YH=(n=>(n[n.None=0]="None",n[n.AdjustHeight=1]="AdjustHeight",n[n.AdjustWidth=2]="AdjustWidth",n))(YH||{}),JH=(n=>(n[n.VideoClip=0]="VideoClip",n[n.Url=1]="Url",n))(JH||{}),KH=(n=>(n[n.CameraFarPlane=0]="CameraFarPlane",n[n.CameraNearPlane=1]="CameraNearPlane",n[n.RenderTexture=2]="RenderTexture",n[n.MaterialOverride=3]="MaterialOverride",n))(KH||{});class dr extends Be{constructor(){super(),d(this,"playOnAwake",!0),d(this,"aspectMode",0),d(this,"clip",null),d(this,"source",1),d(this,"_url",null),d(this,"renderMode"),d(this,"targetMaterialProperty"),d(this,"targetMaterialRenderer"),d(this,"targetTexture"),d(this,"time",0),d(this,"_playbackSpeed",1),d(this,"_isLooping",!1),d(this,"_muted",!1),d(this,"_audioOutputMode",2),d(this,"playInBackground",!0),d(this,"_crossOrigin","anonymous"),d(this,"_videoElement",null),d(this,"_videoTexture",null),d(this,"_videoMaterial",null),d(this,"_isPlaying",!1),d(this,"wasPlaying",!1),d(this,"visibilityChanged",e=>{switch(document.visibilityState){case"hidden":this.playInBackground||(this.wasPlaying=this._isPlaying,this.pause());break;case"visible":this.wasPlaying&&!this._isPlaying&&this.play();break}}),d(this,"_receivedInput",!1),d(this,"_overlay",null),d(this,"_targetObjects"),d(this,"_updateAspectRoutineId",-1),d(this,"_hls"),d(this,"onHlsAvailable",()=>{var e;Pr&&console.log("HLS: available",this.clip),!(!this.shouldUseM3U||!this.url)&&(this._hls||(this._hls=new Hls),this.videoElement.autoplay=!0,this._hls.loadSource(this.url),this._hls.attachMedia(this.videoElement),(e=this._videoElement)==null||e.play(),Pr&&console.log("HLS: loaded",this.clip))}),jAe(()=>{this._receivedInput=!0,this.updateVideoElementSettings()}),this._targetObjects=[],te("videoscreenspace")&&window.addEventListener("keydown",e=>{e.key==="f"&&(this.screenspace=!this.screenspace)})}get url(){return this._url}set url(e){const t=this._url!==e;this.__didAwake?t&&this.setClipURL(e??""):this._url=e}get playbackSpeed(){var e;return((e=this._videoElement)==null?void 0:e.playbackRate)??this._playbackSpeed}set playbackSpeed(e){this._playbackSpeed=e,this._videoElement&&(this._videoElement.playbackRate=e)}get isLooping(){var e;return((e=this._videoElement)==null?void 0:e.loop)??this._isLooping}set isLooping(e){this._isLooping=e,this._videoElement&&(this._videoElement.loop=e)}get currentTime(){var e;return((e=this._videoElement)==null?void 0:e.currentTime)??this.time}set currentTime(e){this._videoElement?this._videoElement.currentTime=e:this.time=e}get isPlaying(){const e=this._videoElement;return!!(e&&(e.currentTime>0&&!e.paused&&!e.ended&&e.readyState>e.HAVE_CURRENT_DATA||e.srcObject&&e.srcObject.active))}get crossOrigin(){var e;return((e=this._videoElement)==null?void 0:e.crossOrigin)??this._crossOrigin}set crossOrigin(e){this._crossOrigin=e,this._videoElement&&(e!==null?this._videoElement.setAttribute("crossorigin",e):this._videoElement.removeAttribute("crossorigin"))}get videoMaterial(){return!this._videoMaterial&&!this.create(!1)?null:this._videoMaterial}get videoTexture(){return!this._videoTexture&&!this.create(!1)?null:this._videoTexture}get videoElement(){return!this._videoElement&&!this.create(!1)?null:this._videoElement}get muted(){var e;return((e=this._videoElement)==null?void 0:e.muted)??this._muted}set muted(e){this._muted=e,this._videoElement&&(this._videoElement.muted=e)}get currentVideo(){return this.clip}set audioOutputMode(e){e!==this._audioOutputMode&&(e===1&&st()&&console.warn("VideoAudioOutputMode.AudioSource is not yet implemented"),this._audioOutputMode=e,this.updateVideoElementSettings())}get audioOutputMode(){return this._audioOutputMode}preloadVideo(){Pr&&console.log("Video Preload: "+this.name,this.clip),this.create(!1)}preload(){this.preloadVideo()}setVideo(e){this.clip=e,this.source=0,this._videoElement?(this._videoElement.srcObject=e,this._isPlaying&&this.play(),this.updateAspect()):this.create(this.playOnAwake)}setClipURL(e){this._url!==e&&(this._url=e,this.source=1,Pr&&console.log("set url",e),this._videoElement?e.endsWith(".m3u8")||e.includes(".m3u")?this.ensureM3UCanBePlayed():(this._videoElement.src=e,this._isPlaying&&(this.stop(),this.play())):this.create(this.playOnAwake))}onEnable(){var e,t;Pr&&console.log("VideoPlayer.onEnable",JH[this.source],this.clip,this.url,this),window.addEventListener("visibilitychange",this.visibilityChanged),this.playOnAwake===!0?this.create(!0):this.preloadVideo(),this.screenspace?(e=this._overlay)==null||e.start():(t=this._overlay)==null||t.stop()}onDisable(){var e;window.removeEventListener("visibilitychange",this.visibilityChanged),(e=this._overlay)==null||e.stop(),this.pause()}onDestroy(){var e;this._videoElement&&((e=this.videoElement)==null||e.remove(),this._videoElement=null),this._videoTexture&&(this._videoTexture.dispose(),this._videoTexture=null)}play(){var e,t;if(this._videoElement||this.create(!1),!this._videoElement){Pr&&console.warn("Can not play: no video element found",this);return}if(!(this._isPlaying&&!((e=this._videoElement)!=null&&e.ended)&&!((t=this._videoElement)!=null&&t.paused))){if(this._isPlaying=!0,this._receivedInput||(this._videoElement.muted=!0),this.handleBeginPlaying(!1),this.shouldUseM3U){this.ensureM3UCanBePlayed();return}Pr&&console.log("Video Play()",this.clip,this._videoElement,this.time),this._videoElement.currentTime=this.time,this._videoElement.play().catch(r=>{var s;console.log(r),Pr&&console.error("Error playing video",r,"CODE="+r.code,(s=this.videoElement)==null?void 0:s.src,this),setTimeout(()=>{this._isPlaying&&!this.destroyed&&this.activeAndEnabled&&this.play()},1e3)}),Pr&&console.log("play",this._videoElement,this.time)}}stop(){this._isPlaying=!1,this.time=0,this._videoElement&&(this._videoElement.currentTime=0,this._videoElement.pause(),Pr&&console.log("STOP",this))}pause(){var e,t;this.time=((e=this._videoElement)==null?void 0:e.currentTime)??0,this._isPlaying=!1,(t=this._videoElement)==null||t.pause(),Pr&&console.log("PAUSE",this,this.currentTime)}create(e){let t;switch(this.source){case 0:t=this.clip;break;case 1:t=this.url,!(t!=null&&t.length)&&typeof this.clip=="string"&&(t=this.clip);break}return t?(this._videoElement||(Pr&&console.warn("Create VideoElement",this),this._videoElement=this.createVideoElement(),this.context.domElement.shadowRoot.prepend(this._videoElement),this.updateVideoElementStyles()),typeof t=="string"?(Pr&&console.log("Set Video src",t),this._videoElement.src=t):(Pr&&console.log("Set Video srcObject",t),this._videoElement.srcObject=t),this._videoTexture||(this._videoTexture=new I3(this._videoElement)),this._videoTexture.flipY=!1,this._videoTexture.colorSpace=ft,e&&this.handleBeginPlaying(e),Pr&&console.log("Video: handle playing done...",t,e),!0):(Pr&&console.warn("No video source set",this),!1)}updateAspect(){this.aspectMode!==0&&this.startCoroutine(this.updateAspectImpl())}get screenspace(){var e;return((e=this._overlay)==null?void 0:e.enabled)??!1}set screenspace(e){var t;if(e){if(!this._videoTexture)return;this._overlay||(this._overlay=new QAe(this.context)),this._overlay.add(this._videoTexture)}else(t=this._overlay)==null||t.remove(this._videoTexture);this._overlay&&(this._overlay.enabled=e)}createVideoElement(){const e=document.createElement("video");return this._crossOrigin&&e.setAttribute("crossorigin",this._crossOrigin),Pr&&console.log("created video element",e),e}handleBeginPlaying(e){var t,r;if(!this.activeAndEnabled||!this._videoElement)return;this._targetObjects.length=0;let s=this.gameObject;switch(this.renderMode){case 3:s=(t=this.targetMaterialRenderer)==null?void 0:t.gameObject,s||(s=(r=ie.getComponent(this.gameObject,Tn))==null?void 0:r.gameObject);break;case 2:console.error("VideoPlayer renderTexture not implemented yet. Please use material override instead");return}if(!s){console.error("Missing target for video material renderer",this.name,KH[this.renderMode],this);return}const o=s.material;if(o){this._targetObjects.push(s),o!==this._videoMaterial&&(this._videoMaterial=o.clone(),s.material=this._videoMaterial);const a="map",l=this._videoMaterial;if(!this.targetMaterialProperty)l[a]=this._videoTexture;else switch(this.targetMaterialProperty){default:l[a]=this._videoTexture;break}}else{console.warn("Can not play video, no material found, this might be a multimaterial case which is not supported yet");return}this.updateVideoElementSettings(),this.updateVideoElementStyles(),e&&(this.shouldUseM3U&&this.ensureM3UCanBePlayed(),this.play())}updateVideoElementSettings(){if(!this._videoElement)return;this._videoElement.loop=this._isLooping,this._videoElement.currentTime=this.currentTime,this._videoElement.playbackRate=this._playbackSpeed,this._videoElement.playsInline=!0;let e=!this._receivedInput||this.audioOutputMode===0;!e&&this._muted&&(e=!0),this._videoElement.muted=e,this.playOnAwake&&(this._videoElement.autoplay=!0)}updateVideoElementStyles(){this._videoElement&&(this._videoElement.style.userSelect="none",this._videoElement.style.visibility="hidden",this._videoElement.style.display="none",this.updateAspect())}*updateAspectImpl(){const e=++this._updateAspectRoutineId,t=void 0,r=this.clip;for(;e===this._updateAspectRoutineId&&this.aspectMode!==0&&this.clip&&r===this.clip&&this._isPlaying;){if(!r||typeof r=="string")return;let s;for(const o of r.getVideoTracks()){const a=o.getSettings();if(a&&a.width&&a.height){s=a.width/a.height;break}else s=this.context.renderer.domElement.clientWidth/this.context.renderer.domElement.clientHeight}if(s===void 0){for(let o=0;o<10;o++)yield;if(!this.isPlaying)break;continue}if(t===s){yield;continue}for(const o of this._targetObjects){let a=1;if(o.parent){const l=Vi(o.parent);a=l.x/l.y}switch(this.aspectMode){case 1:o.scale.y=1/s*o.scale.x*a;break;case 2:o.scale.x=s*o.scale.y*a;break}}for(let o=0;o<3;o++)yield}}get shouldUseM3U(){return this.url!=null&&(this.url.endsWith(".m3u8")||this.url.endsWith(".m3u"))&&this.source===1}ensureM3UCanBePlayed(){if(!this.shouldUseM3U)return;let e=document.head.querySelector("script[data-hls_library]");e?globalThis.Hls?this.onHlsAvailable():e.addEventListener("load",this.onHlsAvailable):(Pr&&console.log("HLS: load script"),e=document.createElement("script"),e.dataset.hls_library="hls.js",e.src="https://cdn.jsdelivr.net/npm/hls.js@1",e.addEventListener("load",this.onHlsAvailable),document.head.append(e))}}Jo([w()],dr.prototype,"playOnAwake",2),Jo([w()],dr.prototype,"aspectMode",2),Jo([w(URL)],dr.prototype,"clip",2),Jo([w()],dr.prototype,"source",2),Jo([w(URL)],dr.prototype,"url",1),Jo([w()],dr.prototype,"renderMode",2),Jo([w()],dr.prototype,"targetMaterialProperty",2),Jo([w(Tn)],dr.prototype,"targetMaterialRenderer",2),Jo([w(zt)],dr.prototype,"targetTexture",2),Jo([w()],dr.prototype,"time",2),Jo([w()],dr.prototype,"playbackSpeed",1),Jo([w()],dr.prototype,"isLooping",1),Jo([w()],dr.prototype,"audioOutputMode",1);class QAe{constructor(e){d(this,"context"),d(this,"_videos",[]),d(this,"_screenspaceModeQuad"),d(this,"_isInScreenspaceMode",!1),d(this,"_input"),this.context=e,this._input=new HAe(this)}get enabled(){return this._isInScreenspaceMode}set enabled(e){e?this.start():this.stop()}add(e){this._videos.indexOf(e)===-1&&this._videos.push(e)}remove(e){if(!e)return;const t=this._videos.indexOf(e);t>=0&&this._videos.splice(t,1)}start(){var e;if(this._isInScreenspaceMode||this._videos.length<0)return;const t=this._videos[this._videos.length-1];if(!t)return;if(this._isInScreenspaceMode=!0,!this._screenspaceModeQuad){if(this._screenspaceModeQuad=sA.createPrimitive(Yp.Quad,{material:new WAe(t)}),!this._screenspaceModeQuad)return;this._screenspaceModeQuad.geometry.scale(2,2,2)}const r=this._screenspaceModeQuad;this.context.scene.add(r),this.updateScreenspaceMaterialUniforms();const s=r.material;s?.reset(),(e=this._input)==null||e.enable(s)}stop(){var e;this._isInScreenspaceMode=!1,this._screenspaceModeQuad&&((e=this._input)==null||e.disable(),this._screenspaceModeQuad.removeFromParent())}updateScreenspaceMaterialUniforms(){var e;const t=(e=this._screenspaceModeQuad)==null?void 0:e.material;t&&(t.screenAspect=this.context.domElement.clientWidth/this.context.domElement.clientHeight)}}class HAe{constructor(e){d(this,"_onResizeScreenFn"),d(this,"_onKeyUpFn"),d(this,"_onMouseWheelFn"),d(this,"context"),d(this,"overlay"),d(this,"_material"),d(this,"_isPinching",!1),d(this,"_lastPinch",0),this.overlay=e,this.context=e.context}enable(e){this._material=e,window.addEventListener("resize",this._onResizeScreenFn=()=>{this.overlay.updateScreenspaceMaterialUniforms()}),window.addEventListener("keyup",this._onKeyUpFn=s=>{s.key==="Escape"&&this.overlay.stop()}),window.addEventListener("wheel",this._onMouseWheelFn=s=>{this.overlay.enabled&&(e.zoom+=s.deltaY*5e-4,s.preventDefault())},{passive:!1});const t=new Z;window.addEventListener("mousemove",s=>{if(this.overlay.enabled&&this.context.input.getPointerPressed(0)){const o=new Z(s.movementX,s.movementY);o.x/=this.context.domElement.clientWidth,o.y/=this.context.domElement.clientHeight,t.set(o.x,o.y),t.multiplyScalar(e.zoom/-this.context.time.deltaTime*.01),e.offset=e.offset.add(t)}}),window.addEventListener("pointermove",s=>{this.overlay.enabled&&this.context.input.getPointerPressed(0)&&this.context.input.getTouchesPressedCount()===1&&(t.set(s.movementX,s.movementY),t.multiplyScalar(e.zoom*-this.context.time.deltaTime*.05),e.offset=e.offset.add(t))});let r=0;window.addEventListener("touchstart",s=>{if(s.touches.length<2){this.context.time.time-r<.3&&this.overlay.stop(),r=this.context.time.time;return}this._isPinching=!0,this._lastPinch=0}),window.addEventListener("touchmove",s=>{if(!this._isPinching||!this._material)return;const o=s.touches[0],a=s.touches[1],l=o.clientX-a.clientX,c=o.clientY-a.clientY,h=Math.sqrt(l*l+c*c);if(this._lastPinch!==0){const u=h-this._lastPinch;this._material.zoom-=u*.004}this._lastPinch=h}),window.addEventListener("touchend",()=>{this._isPinching=!1})}disable(){this._onResizeScreenFn&&(window.removeEventListener("resize",this._onResizeScreenFn),this._onResizeScreenFn=void 0),this._onKeyUpFn&&(window.removeEventListener("keyup",this._onKeyUpFn),this._onKeyUpFn=void 0),this._onMouseWheelFn&&(window.removeEventListener("wheel",this._onMouseWheelFn),this._onMouseWheelFn=void 0)}}class WAe extends Rt{constructor(e){super(),d(this,"_offset",new Z),this.uniforms={map:{value:e},screenAspect:{value:1},offsetScale:{value:new Ye(0,0,1,1)}},this.vertexShader=`
7590
7590
  uniform sampler2D map;
7591
7591
  uniform float screenAspect;
7592
7592
  uniform vec4 offsetScale;