@needle-tools/engine 3.45.2-beta.1 → 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: `+A.toString())}const i=ls()||T0()&&se();if((
4344
4344
  #__vconsole .vc-mask {
4345
4345
  overflow: hidden;
4346
4346
  }
4347
- `,ws?.prepend(g),i===!0&&WU()<=0&&gH(),console.log("\u{1F335} Debug console has loaded")}},A.src="https://unpkg.com/vconsole@latest/dist/vconsole.min.js",document.body.appendChild(A)}function JgA(){const i=new VConsole.VConsolePlugin("needle-console","\u{1F335} Inspect glTF"),A=()=>document.querySelector("#__vc_plug_"+i._id+" iframe");return i.on("renderTab",function(e){const g=globalThis["needle:codegen_files"];if(!g||g.length===0)return;let I=globalThis["needle:codegen_files"][0];const o=I.indexOf("?");o>-1&&(I=I.substring(0,o));const s=location.protocol+"//"+location.host+location.pathname+"/"+I,n=encodeURIComponent(s);i.fullUrl="https://viewer.needle.tools?inspect&file="+n;var a='<iframe src="" style="width: 100%; height: 99%; border: none;"></iframe>';e(a)}),i.on("show",function(){const e=A();e&&e.src!==i.fullUrl&&(e.src=i.fullUrl)}),i.on("hide",function(){const e=A();e&&(e.src="")}),i.on("addTopBar",function(e){var g=new Array;g.push({name:"Open in new window \u2197",onClick:function(I){window.open(i.fullUrl,"_blank"),Ds?.hide()}}),g.push({name:"Reload",onClick:function(I){const o=A();o&&(o.src=i.fullUrl)}}),g.push({name:"Fullscreen",onClick:function(I){const o=A();o.requestFullscreen?o.requestFullscreen():o.webkitRequestFullscreen instanceof Function&&o.webkitRequestFullscreen()}}),e(g)}),i}function xgA(){return document.querySelector("#__vconsole .vc-switch")||null}function qgA(){return document.querySelector("#__vconsole")||null}const nH=iA("debugdefines");rc('if(!globalThis[""3.45.2-beta.1""]) globalThis[""3.45.2-beta.1""] = "0.0.0";'),rc('if(!globalThis[""undefined""]) globalThis[""undefined""] = "unknown";'),rc('if(!globalThis[""Wed Jul 17 2024 19:33:24 GMT+0200 (Central European Summer Time)""]) globalThis[""Wed Jul 17 2024 19:33:24 GMT+0200 (Central European Summer Time)""] = "unknown";'),rc('globalThis["__NEEDLE_ENGINE_VERSION__"] = "3.45.2-beta.1";'),rc('globalThis["__NEEDLE_ENGINE_GENERATOR__"] = "undefined";'),rc('globalThis["__NEEDLE_PROJECT_BUILD_TIME__"] = "Wed Jul 17 2024 19:33:24 GMT+0200 (Central European Summer Time)";');const Bn="3.45.2-beta.1",nm="undefined",jN="Wed Jul 17 2024 19:33:24 GMT+0200 (Central European Summer Time)";nH&&console.log(`Engine version: ${Bn} (generator: ${nm})
4347
+ `,ws?.prepend(g),i===!0&&WU()<=0&&gH(),console.log("\u{1F335} Debug console has loaded")}},A.src="https://unpkg.com/vconsole@latest/dist/vconsole.min.js",document.body.appendChild(A)}function JgA(){const i=new VConsole.VConsolePlugin("needle-console","\u{1F335} Inspect glTF"),A=()=>document.querySelector("#__vc_plug_"+i._id+" iframe");return i.on("renderTab",function(e){const g=globalThis["needle:codegen_files"];if(!g||g.length===0)return;let I=globalThis["needle:codegen_files"][0];const o=I.indexOf("?");o>-1&&(I=I.substring(0,o));const s=location.protocol+"//"+location.host+location.pathname+"/"+I,n=encodeURIComponent(s);i.fullUrl="https://viewer.needle.tools?inspect&file="+n;var a='<iframe src="" style="width: 100%; height: 99%; border: none;"></iframe>';e(a)}),i.on("show",function(){const e=A();e&&e.src!==i.fullUrl&&(e.src=i.fullUrl)}),i.on("hide",function(){const e=A();e&&(e.src="")}),i.on("addTopBar",function(e){var g=new Array;g.push({name:"Open in new window \u2197",onClick:function(I){window.open(i.fullUrl,"_blank"),Ds?.hide()}}),g.push({name:"Reload",onClick:function(I){const o=A();o&&(o.src=i.fullUrl)}}),g.push({name:"Fullscreen",onClick:function(I){const o=A();o.requestFullscreen?o.requestFullscreen():o.webkitRequestFullscreen instanceof Function&&o.webkitRequestFullscreen()}}),e(g)}),i}function xgA(){return document.querySelector("#__vconsole .vc-switch")||null}function qgA(){return document.querySelector("#__vconsole")||null}const nH=iA("debugdefines");rc('if(!globalThis[""3.45.2-beta.3""]) globalThis[""3.45.2-beta.3""] = "0.0.0";'),rc('if(!globalThis[""undefined""]) globalThis[""undefined""] = "unknown";'),rc('if(!globalThis[""Thu Jul 18 2024 13:36:22 GMT+0200 (Central European Summer Time)""]) globalThis[""Thu Jul 18 2024 13:36:22 GMT+0200 (Central European Summer Time)""] = "unknown";'),rc('globalThis["__NEEDLE_ENGINE_VERSION__"] = "3.45.2-beta.3";'),rc('globalThis["__NEEDLE_ENGINE_GENERATOR__"] = "undefined";'),rc('globalThis["__NEEDLE_PROJECT_BUILD_TIME__"] = "Thu Jul 18 2024 13:36:22 GMT+0200 (Central European Summer Time)";');const Bn="3.45.2-beta.3",nm="undefined",jN="Thu Jul 18 2024 13:36:22 GMT+0200 (Central European Summer Time)";nH&&console.log(`Engine version: ${Bn} (generator: ${nm})
4348
4348
  Project built at ${jN}`);const hr="needle_isActiveInHierarchy",HQ="builtin_components",Uu="needle_editor_guid";function rc(i){try{(0,eval)(i)}catch(A){nH&&console.error(A)}}const LgA='<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>',_gA=btoa(LgA),TgA="data:image/svg+xml;base64,"+_gA,YgA=TgA,HgA=`<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN' 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'> <svg clip-rule="evenodd" fill-rule="evenodd" stroke-linejoin="round" stroke-miterlimit="2" version="1.1" viewBox="0 0 1014 282" xml:space="preserve" xmlns="http://www.w3.org/2000/svg"> <g transform="matrix(1.008 0 0 1.008 -2.239 .61874)"> <path d="m665.95 132.73v44.88l-10.56-8.4c-0.8-0.64-1.2-1.44-1.2-2.4v-32.4c0-6.48-4.12-9.72-12.36-9.72-2.16 0-4.18 0.4-6.06 1.2s-3.54 1.8-4.98 3-2.56 2.5-3.36 3.9-1.2 2.7-1.2 3.9v40.92l-10.68-8.4c-0.72-0.64-1.08-1.44-1.08-2.4v-53.76l10.92 8.52c0.32 0.24 0.56 0.44 0.72 0.6s0.36 0.32 0.6 0.48c0.96-1.2 2.14-2.28 3.54-3.24s2.92-1.76 4.56-2.4 3.34-1.14 5.1-1.5 3.44-0.54 5.04-0.54c1.44 0 2.92 0.04 4.44 0.12s2.84 0.28 3.96 0.6c4.56 1.12 7.8 3.12 9.72 6s2.88 6.56 2.88 11.04z" fill-rule="nonzero"/> </g> <g transform="matrix(1.008 0 0 1.008 -2.239 .61874)"> <path d="m732.38 146.05c0 0.88 0.02 1.5 0.06 1.86s-0.02 0.98-0.18 1.86h-7.08c-2.08 0-4.44-0.02-7.08-0.06s-5.36-0.06-8.16-0.06h-22.08c0 2.88 0.56 5.36 1.68 7.44s2.6 3.8 4.44 5.16 3.94 2.36 6.3 3 4.74 0.96 7.14 0.96c3.04 0 5.9-0.76 8.58-2.28s4.94-3.52 6.78-6c0.64 0.56 1.54 1.48 2.7 2.76s2.94 3.2 5.34 5.76c-2.8 3.36-6.22 6.02-10.26 7.98s-8.42 2.94-13.14 2.94-8.92-0.64-12.84-1.92-7.32-3.24-10.2-5.88-5.12-5.98-6.72-10.02-2.4-8.82-2.4-14.34c0-4.96 0.66-9.42 1.98-13.38s3.22-7.32 5.7-10.08 5.44-4.9 8.88-6.42 7.32-2.28 11.64-2.28c5.76 0 10.52 0.88 14.28 2.64s6.72 4.16 8.88 7.2 3.66 6.54 4.5 10.5 1.26 8.18 1.26 12.66zm-29.4-22.8c-2.16 0.16-4.16 0.72-6 1.68s-3.42 2.2-4.74 3.72-2.36 3.28-3.12 5.28-1.14 4.12-1.14 6.36h33.12c0-2-0.22-4.06-0.66-6.18s-1.3-4.02-2.58-5.7-3.1-3.02-5.46-4.02-5.5-1.38-9.42-1.14z" fill-rule="nonzero"/> </g> <g transform="matrix(1.008 0 0 1.008 -2.239 .61874)"> <path d="m795.93 146.05c0 0.88 0.02 1.5 0.06 1.86s-0.02 0.98-0.18 1.86h-7.08c-2.08 0-4.44-0.02-7.08-0.06s-5.36-0.06-8.16-0.06h-22.08c0 2.88 0.56 5.36 1.68 7.44s2.6 3.8 4.44 5.16 3.94 2.36 6.3 3 4.74 0.96 7.14 0.96c3.04 0 5.9-0.76 8.58-2.28s4.94-3.52 6.78-6c0.64 0.56 1.54 1.48 2.7 2.76s2.94 3.2 5.34 5.76c-2.8 3.36-6.22 6.02-10.26 7.98s-8.42 2.94-13.14 2.94-8.92-0.64-12.84-1.92-7.32-3.24-10.2-5.88-5.12-5.98-6.72-10.02-2.4-8.82-2.4-14.34c0-4.96 0.66-9.42 1.98-13.38s3.22-7.32 5.7-10.08 5.44-4.9 8.88-6.42 7.32-2.28 11.64-2.28c5.76 0 10.52 0.88 14.28 2.64s6.72 4.16 8.88 7.2 3.66 6.54 4.5 10.5 1.26 8.18 1.26 12.66zm-29.4-22.8c-2.16 0.16-4.16 0.72-6 1.68s-3.42 2.2-4.74 3.72-2.36 3.28-3.12 5.28-1.14 4.12-1.14 6.36h33.12c0-2-0.22-4.06-0.66-6.18s-1.3-4.02-2.58-5.7-3.1-3.02-5.46-4.02-5.5-1.38-9.42-1.14z" fill-rule="nonzero"/> </g> <g transform="matrix(1.008 0 0 1.008 -2.239 .61874)"> <path d="m858.57 97.21c0.64 0.48 0.96 1.16 0.96 2.04v74.88c-0.08 1.04-0.12 2.12-0.12 3.24-1.84-1.52-3.56-2.92-5.16-4.2-1.36-1.12-2.66-2.18-3.9-3.18s-2.06-1.66-2.46-1.98c-1.76 2.48-4.26 4.44-7.5 5.88s-7.02 2.16-11.34 2.16c-3.84 0-7.4-0.7-10.68-2.1s-6.14-3.44-8.58-6.12-4.34-5.94-5.7-9.78-2.04-8.16-2.04-12.96c0-4.32 0.78-8.34 2.34-12.06s3.6-6.92 6.12-9.6 5.38-4.78 8.58-6.3 6.48-2.28 9.84-2.28c2.56 0 4.82 0.22 6.78 0.66s3.68 1.06 5.16 1.86 2.78 1.74 3.9 2.82 2.16 2.22 3.12 3.42v-35.04l10.68 8.64zm-27.96 67.92c3.6 0 6.52-0.68 8.76-2.04s3.98-3.06 5.22-5.1 2.1-4.22 2.58-6.54 0.72-4.44 0.72-6.36v-1.2c0-1.12-0.22-2.7-0.66-4.74s-1.28-4.06-2.52-6.06-3-3.7-5.28-5.1-5.22-2.02-8.82-1.86c-3.44 0-6.26 0.74-8.46 2.22s-3.96 3.26-5.28 5.34-2.24 4.2-2.76 6.36-0.78 3.92-0.78 5.28c0 1.84 0.24 3.92 0.72 6.24s1.36 4.48 2.64 6.48 3.04 3.68 5.28 5.04 5.12 2.04 8.64 2.04z" fill-rule="nonzero"/> </g> <g transform="matrix(1.008 0 0 1.008 -2.239 .61874)"> <path d="m882.81 97.09c0.64 0.48 0.96 1.12 0.96 1.92l-0.12 41.04v37.08l-10.56-8.4c-0.72-0.64-1.08-1.44-1.08-2.4v-77.88l10.8 8.64z" fill-rule="nonzero"/> </g> <g transform="matrix(1.008 0 0 1.008 -2.239 .61874)"> <path d="m950.36 146.05c0 0.88 0.02 1.5 0.06 1.86s-0.02 0.98-0.18 1.86h-7.08c-2.08 0-4.44-0.02-7.08-0.06s-5.36-0.06-8.16-0.06h-22.08c0 2.88 0.56 5.36 1.68 7.44s2.6 3.8 4.44 5.16 3.94 2.36 6.3 3 4.74 0.96 7.14 0.96c3.04 0 5.9-0.76 8.58-2.28s4.94-3.52 6.78-6c0.64 0.56 1.54 1.48 2.7 2.76s2.94 3.2 5.34 5.76c-2.8 3.36-6.22 6.02-10.26 7.98s-8.42 2.94-13.14 2.94-8.92-0.64-12.84-1.92-7.32-3.24-10.2-5.88-5.12-5.98-6.72-10.02-2.4-8.82-2.4-14.34c0-4.96 0.66-9.42 1.98-13.38s3.22-7.32 5.7-10.08 5.44-4.9 8.88-6.42 7.32-2.28 11.64-2.28c5.76 0 10.52 0.88 14.28 2.64s6.72 4.16 8.88 7.2 3.66 6.54 4.5 10.5 1.26 8.18 1.26 12.66zm-29.4-22.8c-2.16 0.16-4.16 0.72-6 1.68s-3.42 2.2-4.74 3.72-2.36 3.28-3.12 5.28-1.14 4.12-1.14 6.36h33.12c0-2-0.22-4.06-0.66-6.18s-1.3-4.02-2.58-5.7-3.1-3.02-5.46-4.02-5.5-1.38-9.42-1.14z" fill-rule="nonzero"/> </g> <g transform="matrix(1.8559 0 0 .7642 45.348 36.475)"> <g transform="translate(2.7114)"> <path d="m3.935 173.02c-0.331 0-0.497-0.402-0.497-1.207v-51.002c0-0.738 0.138-1.107 0.414-1.107h1.781c0.277 0 0.415 0.335 0.415 1.006v5.935c0 0.336 0.027 0.553 0.083 0.654 0.055 0.101 0.151-0.017 0.289-0.352 0.912-1.744 1.754-3.236 2.527-4.477 0.773-1.24 1.554-2.179 2.341-2.816s1.65-0.956 2.588-0.956c1.685 0 3.011 0.922 3.977 2.766 0.967 1.845 1.602 3.84 1.905 5.986 0.056 0.268 0.139 0.369 0.249 0.302s0.221-0.235 0.331-0.503c0.939-1.811 1.802-3.353 2.589-4.628 0.787-1.274 1.581-2.246 2.382-2.917s1.671-1.006 2.61-1.006c2.016 0 3.569 1.392 4.66 4.175 1.09 2.783 1.636 6.421 1.636 10.915v37.925c0 0.871-0.18 1.307-0.539 1.307h-1.739c-0.138 0-0.249-0.1-0.332-0.301-0.083-0.202-0.124-0.503-0.124-0.906v-36.315c0-3.555-0.338-6.321-1.015-8.3-0.676-1.978-1.76-2.967-3.251-2.967-0.884 0-1.726 0.386-2.527 1.157s-1.519 1.727-2.154 2.867-1.201 2.213-1.699 3.219c-0.248 0.469-0.421 0.905-0.517 1.308-0.097 0.402-0.145 0.972-0.145 1.71v37.221c0 0.871-0.166 1.307-0.497 1.307h-1.74c-0.166 0-0.29-0.1-0.373-0.301-0.083-0.202-0.124-0.503-0.124-0.906v-36.315c0-3.555-0.332-6.321-0.994-8.3-0.663-1.978-1.754-2.967-3.273-2.967-1.242 0-2.375 0.704-3.396 2.112-1.022 1.409-2.223 3.555-3.604 6.439v39.031c0 0.805-0.18 1.207-0.539 1.207h-1.698z" fill-rule="nonzero" stroke="#000" stroke-width=".7px"/> </g> <g transform="translate(2.7114)"> <path d="m53.642 166.28c-1.077 2.549-2.237 4.477-3.479 5.785-1.243 1.307-2.61 1.961-4.101 1.961-2.154 0-3.853-1.324-5.095-3.973-1.243-2.649-1.864-6.187-1.864-10.613 0-3.488 0.4-6.489 1.201-9.004s1.988-4.51 3.562-5.985c1.574-1.476 3.521-2.414 5.841-2.817l3.686-0.704c0.221-0.067 0.394-0.218 0.518-0.453 0.124-0.234 0.187-0.587 0.187-1.056v-2.917c0-3.89-0.504-6.975-1.512-9.255s-2.354-3.42-4.039-3.42c-1.298 0-2.472 0.72-3.521 2.162s-2.002 3.572-2.858 6.388c-0.083 0.268-0.159 0.453-0.228 0.554-0.069 0.1-0.172 0.083-0.311-0.051l-1.698-1.71c-0.083-0.134-0.138-0.285-0.166-0.453-0.027-0.167 0.014-0.452 0.125-0.855 0.856-3.353 2.009-6.052 3.459-8.098 1.449-2.045 3.224-3.068 5.322-3.068 1.74 0 3.211 0.687 4.412 2.062s2.112 3.37 2.734 5.986c0.621 2.615 0.932 5.7 0.932 9.255v35.712c0 0.536-0.035 0.888-0.104 1.056s-0.2 0.251-0.393 0.251h-1.533c-0.166 0-0.29-0.117-0.373-0.352-0.083-0.234-0.124-0.553-0.124-0.955l-0.083-5.231c-0.055-0.939-0.221-1.006-0.497-0.202zm0.456-19.314c0-1.14-0.194-1.643-0.58-1.509l-3.107 0.603c-1.436 0.202-2.686 0.638-3.749 1.308-1.063 0.671-1.953 1.543-2.671 2.616s-1.257 2.33-1.616 3.772-0.538 3.102-0.538 4.98c0 3.152 0.455 5.616 1.367 7.393 0.911 1.778 2.14 2.666 3.686 2.666 0.939 0 1.85-0.419 2.734-1.257s1.671-1.895 2.361-3.169c0.663-1.408 1.181-2.85 1.553-4.326 0.373-1.475 0.56-2.883 0.56-4.225v-8.852z" fill-rule="nonzero" stroke="#000" stroke-width=".7px"/> </g> <g transform="translate(2.7114)"> <path d="m79.034 173.02c-0.166 0-0.297-0.117-0.394-0.352-0.096-0.234-0.145-0.553-0.145-0.955v-4.628c0-0.536-0.041-0.838-0.124-0.905s-0.207 0.1-0.373 0.503c-0.276 0.67-0.69 1.593-1.242 2.766-0.553 1.174-1.271 2.23-2.154 3.169-0.884 0.939-1.961 1.408-3.231 1.408-1.74 0-3.314-0.989-4.722-2.967-1.409-1.979-2.534-4.963-3.376-8.953-0.843-3.991-1.264-8.937-1.264-14.838 0-5.701 0.415-10.68 1.243-14.939s1.988-7.595 3.479-10.009c1.492-2.415 3.204-3.622 5.137-3.622 1.436 0 2.616 0.57 3.541 1.71 0.926 1.14 1.719 2.381 2.382 3.722 0.249 0.47 0.414 0.637 0.497 0.503s0.125-0.536 0.125-1.207v-23.841c0-0.805 0.151-1.208 0.455-1.208h1.864c0.276 0 0.414 0.369 0.414 1.107v72.128c0 0.537-0.041 0.905-0.124 1.107-0.083 0.201-0.235 0.301-0.455 0.301h-1.533zm-0.621-42.049c-0.939-2.213-1.885-3.94-2.838-5.181s-2.009-1.861-3.169-1.861c-1.463 0-2.768 0.889-3.914 2.666s-2.044 4.376-2.693 7.796-0.973 7.578-0.973 12.474c0 5.097 0.338 9.272 1.015 12.524 0.676 3.253 1.567 5.651 2.672 7.193 1.104 1.543 2.305 2.314 3.603 2.314 1.188 0 2.258-0.704 3.211-2.113 0.952-1.408 1.705-3.118 2.257-5.13s0.829-3.957 0.829-5.835v-24.847z" fill-rule="nonzero" stroke="#000" stroke-width=".7px"/> </g> <g transform="translate(2.7114)"> <path d="m89.514 149.38c0 3.42 0.345 6.606 1.035 9.557 0.691 2.951 1.609 5.315 2.755 7.092s2.437 2.666 3.873 2.666c1.519 0 2.837-0.738 3.956-2.213 1.118-1.476 2.064-3.655 2.837-6.539 0.083-0.336 0.166-0.52 0.249-0.554 0.083-0.033 0.179 0.017 0.29 0.151l1.408 1.912c0.221 0.268 0.235 0.67 0.041 1.207-0.69 2.548-1.47 4.661-2.34 6.337-0.87 1.677-1.857 2.935-2.962 3.773-1.104 0.838-2.319 1.257-3.645 1.257-2.043 0-3.838-1.14-5.385-3.42-1.546-2.28-2.761-5.482-3.645-9.607-0.884-4.124-1.325-8.836-1.325-14.134 0-5.901 0.455-10.931 1.367-15.089 0.911-4.158 2.14-7.377 3.686-9.658 1.547-2.28 3.3-3.42 5.261-3.42 1.988 0 3.714 1.073 5.178 3.219 1.463 2.146 2.595 5.231 3.396 9.255s1.201 8.886 1.201 14.587c0 0.469-0.02 0.939-0.062 1.408-0.041 0.469-0.214 0.704-0.517 0.704h-16.362c-0.083 0-0.152 0.151-0.207 0.453-0.056 0.302-0.083 0.654-0.083 1.056zm13.752-6.237c0.304 0 0.497-0.1 0.58-0.302 0.083-0.201 0.124-0.57 0.124-1.106 0-3.219-0.283-6.187-0.849-8.903s-1.367-4.896-2.402-6.539c-1.036-1.643-2.272-2.464-3.708-2.464-1.629 0-2.996 0.955-4.101 2.867-1.104 1.911-1.94 4.342-2.506 7.293s-0.849 6.002-0.849 9.154h13.711z" fill-rule="nonzero" stroke="#000" stroke-width=".7px"/> </g> <g transform="translate(2.7114)"> <path d="m148.54 119.7c0.165 0 0.283 0.117 0.352 0.352s0.076 0.52 0.02 0.855l-6.254 50.902c-0.028 0.47-0.104 0.788-0.228 0.956s-0.297 0.251-0.518 0.251h-1.615c-0.442 0-0.718-0.402-0.829-1.207l-5.26-40.138c-0.111-0.604-0.201-0.905-0.27-0.905s-0.131 0.301-0.186 0.905l-5.012 40.138c-0.028 0.47-0.097 0.788-0.207 0.956-0.111 0.168-0.277 0.251-0.497 0.251h-1.74c-0.442 0-0.718-0.402-0.829-1.207l-6.503-50.801c-0.055-0.403-0.048-0.721 0.021-0.956s0.2-0.352 0.393-0.352h1.823c0.166 0 0.297 0.067 0.393 0.201 0.097 0.134 0.159 0.403 0.187 0.805l5.302 41.848c0.083 0.671 0.179 0.989 0.29 0.956 0.11-0.034 0.207-0.386 0.29-1.056l5.219-41.949c0.055-0.268 0.124-0.47 0.207-0.604s0.193-0.201 0.331-0.201h1.533c0.138 0 0.262 0.067 0.373 0.201 0.11 0.134 0.179 0.403 0.207 0.805l5.468 41.848c0.083 0.671 0.179 0.989 0.29 0.956 0.11-0.034 0.207-0.386 0.29-1.056l5.053-41.849c0.055-0.335 0.138-0.57 0.249-0.704 0.11-0.134 0.234-0.201 0.373-0.201h1.284z" fill-rule="nonzero" stroke="#000" stroke-width=".7px"/> </g> <g transform="translate(2.7114)"> <path d="m156.49 171.51c0 0.604-0.042 1.006-0.125 1.208-0.082 0.201-0.262 0.301-0.538 0.301h-1.533c-0.221 0-0.366-0.083-0.435-0.251s-0.103-0.486-0.103-0.956v-50.902c0-0.805 0.152-1.207 0.456-1.207h1.822c0.304 0 0.456 0.402 0.456 1.207v50.6zm0.165-63.979c0 1.207-0.207 1.811-0.621 1.811h-1.905c-0.221 0-0.366-0.135-0.435-0.403s-0.104-0.67-0.104-1.207v-7.847c0-1.006 0.18-1.509 0.539-1.509h1.988c0.359 0 0.538 0.47 0.538 1.409v7.746z" fill-rule="nonzero" stroke="#000" stroke-width=".7px"/> </g> <g transform="translate(2.7114)"> <path d="m168.3 124.83c-0.221 0-0.331 0.269-0.331 0.805v33.801c0 3.42 0.221 5.667 0.663 6.74 0.441 1.073 1.09 1.609 1.946 1.609h3.024c0.138 0 0.242 0.084 0.311 0.252 0.069 0.167 0.103 0.419 0.103 0.754v2.716c0 0.537-0.138 0.906-0.414 1.107-0.248 0.067-0.614 0.134-1.098 0.201-0.483 0.067-0.959 0.118-1.429 0.151-0.469 0.034-0.828 0.05-1.077 0.05-1.712 0-2.934-0.955-3.665-2.867-0.732-1.911-1.098-5.013-1.098-9.305v-35.108c0-0.604-0.124-0.906-0.373-0.906h-3.521c-0.248 0-0.373-0.268-0.373-0.804v-3.521c0-0.537 0.111-0.805 0.332-0.805h3.686c0.166 0 0.263-0.268 0.29-0.805l0.415-16.095c0-0.805 0.124-1.207 0.372-1.207h1.492c0.303 0 0.455 0.436 0.455 1.307v15.995c0 0.537 0.097 0.805 0.29 0.805h5.468c0.221 0 0.331 0.268 0.331 0.805v3.521c0 0.536-0.124 0.804-0.373 0.804h-5.426z" fill-rule="nonzero" stroke="#000" stroke-width=".7px"/> </g> <g transform="translate(2.7114)"> <path d="m179.4 173.02c-0.331 0-0.497-0.402-0.497-1.207v-72.329c0-0.738 0.138-1.107 0.414-1.107h1.782c0.276 0 0.414 0.336 0.414 1.006v27.162c0 0.335 0.034 0.536 0.103 0.603s0.159-0.033 0.27-0.302c0.994-1.81 1.898-3.319 2.713-4.526 0.814-1.208 1.629-2.113 2.444-2.717 0.814-0.603 1.691-0.905 2.63-0.905 2.182 0 3.839 1.375 4.971 4.125 1.132 2.749 1.698 6.404 1.698 10.965v37.925c0 0.871-0.166 1.307-0.497 1.307h-1.74c-0.165 0-0.29-0.1-0.373-0.301-0.082-0.202-0.124-0.503-0.124-0.906v-36.315c0-3.555-0.366-6.321-1.097-8.3-0.732-1.978-1.899-2.967-3.501-2.967-0.883 0-1.705 0.318-2.464 0.956-0.76 0.637-1.526 1.576-2.299 2.816-0.773 1.241-1.643 2.834-2.61 4.779v39.031c0 0.805-0.179 1.207-0.538 1.207h-1.699z" fill-rule="nonzero" stroke="#000" stroke-width=".7px"/> </g> </g> <g transform="matrix(.80638 0 0 .80638 452.53 65.421)" fill-rule="nonzero"> <path d="m79.32 36.98v150.76l15.68-13.2 6.59-156.31-22.27 18.75z" fill="url(#f)"/> <path d="m79.32 36.98-22.27-18.75 6.59 156.31 15.68 13.2v-150.76z" fill="url(#e)"/> <path d="m25.19 104.83 8.63 49.04 12.5-14.95-2.46-56.42-18.67 22.33z" fill="url(#d)"/> <path d="m25.19 104.83-25.19-14.59 16.97 53.86 16.85 9.77-8.63-49.04z" fill="url(#c)"/> <path d="M43.86,82.5L18.69,67.98L0,90.24L25.18,104.83L43.86,82.5Z" fill="#9c3"/> <path d="m134.82 78.69-9.97 56.5 15.58-9.04 19.57-62.05-25.18 14.59z" fill="url(#b)"/> <path d="m134.82 78.69-18.68-22.33-2.86 65 11.57 13.83 9.97-56.5z" fill="url(#a)"/> <path d="m160 64.1-18.69-22.26-25.17 14.52 18.67 22.33 25.19-14.59z" fill="#ffe113"/> <path d="M101.59,18.23L79.32,0L57.05,18.23L79.32,36.98L101.59,18.23Z" fill="#f3e600"/> </g> <defs> <linearGradient id="f" x2="1" gradientTransform="matrix(.84 -162.96 162.96 .84 89.64 184.81)" gradientUnits="userSpaceOnUse"><stop stop-color="#62d399" offset="0"/><stop stop-color="#acd842" offset=".51"/><stop stop-color="#d7db0a" offset=".9"/><stop stop-color="#d7db0a" offset="1"/></linearGradient> <linearGradient id="e" x2="1" gradientTransform="matrix(-1.6,-162.13,162.13,-1.6,69.68,178.9)" gradientUnits="userSpaceOnUse"><stop stop-color="#0ba398" offset="0"/><stop stop-color="#4ca352" offset=".5"/><stop stop-color="#76a30a" offset="1"/></linearGradient> <linearGradient id="d" x2="1" gradientTransform="matrix(-1.9,-67.98,67.98,-1.9,36.6,152.17)" gradientUnits="userSpaceOnUse"><stop stop-color="#36a382" offset="0"/><stop stop-color="#36a382" offset=".19"/><stop stop-color="#49a459" offset=".54"/><stop stop-color="#76a30b" offset="1"/></linearGradient> <linearGradient id="c" x2="1" gradientTransform="matrix(2.18,-62.38,62.38,2.18,15.82,153.24)" gradientUnits="userSpaceOnUse"><stop stop-color="#267880" offset="0"/><stop stop-color="#457a5c" offset=".51"/><stop stop-color="#717516" offset="1"/></linearGradient> <linearGradient id="b" x2="1" gradientTransform="matrix(13.85,-71.96,71.96,13.85,135.08,135.43)" gradientUnits="userSpaceOnUse"><stop stop-color="#b0d939" offset="0"/><stop stop-color="#eadb04" offset="1"/></linearGradient> <linearGradient id="a" x2="1" gradientTransform="matrix(26.159 -64.737 64.737 26.159 107.42 128.14)" gradientUnits="userSpaceOnUse"><stop stop-color="#74af52" offset="0"/><stop stop-color="#74af52" offset=".17"/><stop stop-color="#99be32" offset=".48"/><stop stop-color="#c0c40a" offset="1"/></linearGradient> </defs> </svg>`;btoa(HgA);const OgA='<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>',PgA=btoa(OgA),jgA="data:image/svg+xml;charset=utf-8;base64,"+PgA,WgA=jgA,ys=iA("debuglicense");let OQ="basic";ys&&console.log("License Type: "+OQ);function RC(){switch(OQ){case"pro":case"enterprise":return!0}return!1}function WN(){switch(OQ){case"indie":return!0}return!1}function Er(){return RC()||WN()}const aH=[];function ZgA(i){if(RC()||WN())return i(!0);aH.push(i)}function zgA(i){for(const A of aH)try{A(i)}catch{}}Qt.registerCallback(Mt.ContextRegistered,i=>{$gA(i.context),eIA(),XgA(i.context)});let PQ,ZN=!1,am="";async function VgA(){if(PQ)return PQ;if(OQ==="basic")try{const i="https://engine.needle.tools/licensing/check?location="+encodeURIComponent(window.location.href)+"&version="+Bn+"&generator="+encodeURIComponent(nm),A=await fetch(i,{method:"GET"}).catch(e=>{ys&&console.error("License check failed",e)});A?.status===200?(ZN=!1,ys&&console.log("License check succeeded"),OQ="pro",zgA(!0)):A?.status===403?(ZN=!0,am=await A.text()):ys&&console.log("License check failed with status "+A?.status)}catch(i){ys&&console.error("License check failed",i)}else ys&&console.log('Runtime license check is skipped because license is already applied as "'+OQ+'"')}PQ=VgA();async function XgA(i){function A(){const I=document.createElement("div");I.className="needle-forbidden",I.style.cssText=`
4349
4349
  position: fixed;
4350
4350
  top: 0;
@@ -5148,7 +5148,7 @@ in script ${o}.ts
5148
5148
  *
5149
5149
  * @author Feross Aboukhadijeh <https://feross.org>
5150
5150
  * @license MIT
5151
- */var KBA=function(i){return i!=null&&(h4(i)||bBA(i)||!!i._isBuffer)};function h4(i){return!!i.constructor&&typeof i.constructor.isBuffer=="function"&&i.constructor.isBuffer(i)}function bBA(i){return typeof i.readFloatLE=="function"&&typeof i.slice=="function"&&h4(i.slice(0,0))}(function(){var i=vBA,A=Q4.utf8,e=KBA,g=Q4.bin,I=function(o,s){o.constructor==String?s&&s.encoding==="binary"?o=g.stringToBytes(o):o=A.stringToBytes(o):e(o)?o=Array.prototype.slice.call(o,0):!Array.isArray(o)&&o.constructor!==Uint8Array&&(o=o.toString());for(var n=i.bytesToWords(o),a=o.length*8,r=1732584193,C=-271733879,Q=-1732584194,h=271733878,E=0;E<n.length;E++)n[E]=(n[E]<<8|n[E]>>>24)&16711935|(n[E]<<24|n[E]>>>8)&4278255360;n[a>>>5]|=128<<a%32,n[(a+64>>>9<<4)+14]=a;for(var c=I._ff,l=I._gg,d=I._hh,u=I._ii,E=0;E<n.length;E+=16){var D=r,p=C,w=Q,f=h;r=c(r,C,Q,h,n[E+0],7,-680876936),h=c(h,r,C,Q,n[E+1],12,-389564586),Q=c(Q,h,r,C,n[E+2],17,606105819),C=c(C,Q,h,r,n[E+3],22,-1044525330),r=c(r,C,Q,h,n[E+4],7,-176418897),h=c(h,r,C,Q,n[E+5],12,1200080426),Q=c(Q,h,r,C,n[E+6],17,-1473231341),C=c(C,Q,h,r,n[E+7],22,-45705983),r=c(r,C,Q,h,n[E+8],7,1770035416),h=c(h,r,C,Q,n[E+9],12,-1958414417),Q=c(Q,h,r,C,n[E+10],17,-42063),C=c(C,Q,h,r,n[E+11],22,-1990404162),r=c(r,C,Q,h,n[E+12],7,1804603682),h=c(h,r,C,Q,n[E+13],12,-40341101),Q=c(Q,h,r,C,n[E+14],17,-1502002290),C=c(C,Q,h,r,n[E+15],22,1236535329),r=l(r,C,Q,h,n[E+1],5,-165796510),h=l(h,r,C,Q,n[E+6],9,-1069501632),Q=l(Q,h,r,C,n[E+11],14,643717713),C=l(C,Q,h,r,n[E+0],20,-373897302),r=l(r,C,Q,h,n[E+5],5,-701558691),h=l(h,r,C,Q,n[E+10],9,38016083),Q=l(Q,h,r,C,n[E+15],14,-660478335),C=l(C,Q,h,r,n[E+4],20,-405537848),r=l(r,C,Q,h,n[E+9],5,568446438),h=l(h,r,C,Q,n[E+14],9,-1019803690),Q=l(Q,h,r,C,n[E+3],14,-187363961),C=l(C,Q,h,r,n[E+8],20,1163531501),r=l(r,C,Q,h,n[E+13],5,-1444681467),h=l(h,r,C,Q,n[E+2],9,-51403784),Q=l(Q,h,r,C,n[E+7],14,1735328473),C=l(C,Q,h,r,n[E+12],20,-1926607734),r=d(r,C,Q,h,n[E+5],4,-378558),h=d(h,r,C,Q,n[E+8],11,-2022574463),Q=d(Q,h,r,C,n[E+11],16,1839030562),C=d(C,Q,h,r,n[E+14],23,-35309556),r=d(r,C,Q,h,n[E+1],4,-1530992060),h=d(h,r,C,Q,n[E+4],11,1272893353),Q=d(Q,h,r,C,n[E+7],16,-155497632),C=d(C,Q,h,r,n[E+10],23,-1094730640),r=d(r,C,Q,h,n[E+13],4,681279174),h=d(h,r,C,Q,n[E+0],11,-358537222),Q=d(Q,h,r,C,n[E+3],16,-722521979),C=d(C,Q,h,r,n[E+6],23,76029189),r=d(r,C,Q,h,n[E+9],4,-640364487),h=d(h,r,C,Q,n[E+12],11,-421815835),Q=d(Q,h,r,C,n[E+15],16,530742520),C=d(C,Q,h,r,n[E+2],23,-995338651),r=u(r,C,Q,h,n[E+0],6,-198630844),h=u(h,r,C,Q,n[E+7],10,1126891415),Q=u(Q,h,r,C,n[E+14],15,-1416354905),C=u(C,Q,h,r,n[E+5],21,-57434055),r=u(r,C,Q,h,n[E+12],6,1700485571),h=u(h,r,C,Q,n[E+3],10,-1894986606),Q=u(Q,h,r,C,n[E+10],15,-1051523),C=u(C,Q,h,r,n[E+1],21,-2054922799),r=u(r,C,Q,h,n[E+8],6,1873313359),h=u(h,r,C,Q,n[E+15],10,-30611744),Q=u(Q,h,r,C,n[E+6],15,-1560198380),C=u(C,Q,h,r,n[E+13],21,1309151649),r=u(r,C,Q,h,n[E+4],6,-145523070),h=u(h,r,C,Q,n[E+11],10,-1120210379),Q=u(Q,h,r,C,n[E+2],15,718787259),C=u(C,Q,h,r,n[E+9],21,-343485551),r=r+D>>>0,C=C+p>>>0,Q=Q+w>>>0,h=h+f>>>0}return i.endian([r,C,Q,h])};I._ff=function(o,s,n,a,r,C,Q){var h=o+(s&n|~s&a)+(r>>>0)+Q;return(h<<C|h>>>32-C)+s},I._gg=function(o,s,n,a,r,C,Q){var h=o+(s&a|n&~a)+(r>>>0)+Q;return(h<<C|h>>>32-C)+s},I._hh=function(o,s,n,a,r,C,Q){var h=o+(s^n^a)+(r>>>0)+Q;return(h<<C|h>>>32-C)+s},I._ii=function(o,s,n,a,r,C,Q){var h=o+(n^(s|~a))+(r>>>0)+Q;return(h<<C|h>>>32-C)+s},I._blocksize=16,I._digestsize=16,C4.exports=function(o,s){if(o==null)throw new Error("Illegal argument "+o);var n=i.wordsToBytes(I(o,s));return s&&s.asBytes?n:s&&s.asString?g.bytesToString(n):i.bytesToHex(n)}})();var JBA=C4.exports;const xBA=RS(JBA);class yK{constructor(A,e,g,I){B(this,"success"),B(this,"filename"),B(this,"hash"),B(this,"size"),B(this,"url"),this.success=A,this.filename=e,this.hash=g,this.size=I}}async function E4(i,A){const e=await i.arrayBuffer(),g=mK(e),I=i.name.split(".").pop(),o=g+"."+I,s=i.name.split(".").shift();console.assert(s!==void 0);const n={alias:s,filename:o},a=await(await fetch(A+"/exists",{method:"POST",body:JSON.stringify(n)})).json();if(a.success||console.warn("exists check did fail"),a.exists)return console.log("file already exists",g),new yK(!0,o,g,i.size);console.log("begin uploading file",s,i.size);const r=new FormData;r.append("file",i);const C={};C.filesize=i.size,s&&(C.alias=s);const Q=await(await fetch(A+"/upload/file",{method:"POST",body:r,headers:C})).json();if(Q?.success===!1)return Q.message!==void 0?console.error("Upload failed:",Q.message):console.error("Upload failed"),null;console.assert(Q.hash_sum===g,"hash sum did not match","received:",Q.hash_sum,"expected:",g),Q.success&&console.log("successfully uploaded",g,Q.id);const h=new yK(Q.success,o,g,i.size);return h.url=A,h}function mK(i){return xBA(new Uint8Array(i))}async function SK(i,A,e,g,I=!1){try{const o=await fetch(g+"/download/file",{method:"POST",body:i});if(o.status!==200)return console.error("download failed",o),null;const s=await o.blob(),n=await s.arrayBuffer();I||console.assert(s.size===e,"size mismatch","expected:",e,"got:",s.size);const a=mK(n);return I||console.assert(a===A,"hash mismatch, downloaded file is invalid"),s.arrayBuffer()}catch(o){console.error(o)}return null}async function c4(i,A){var e;const g=await fetch(i),I=(e=g.body)==null?void 0:e.getReader(),o=g.headers.get("Content-Length"),s=o?parseInt(o):0;if(!I)return null;let n=0;const a=[];for(;;){const{done:Q,value:h}=await I.read();if(h&&(a.push(h),n+=h.length,A.call(null,new ProgressEvent("progress",{loaded:n,total:s}))),Q)break}const r=new Uint8Array(n);let C=0;for(const Q of a)r.set(Q,C),C+=Q.length;return r}const tB=iA("debugaddressables");class l4{constructor(A){B(this,"_context"),B(this,"_assetReferences",{}),B(this,"preUpdate",()=>{}),this._context=A,this._context.pre_update_callbacks.push(this.preUpdate)}dispose(){const A=this._context.pre_update_callbacks.indexOf(this.preUpdate);A>=0&&this._context.pre_update_callbacks.splice(A,1);for(const e in this._assetReferences){const g=this._assetReferences[e];g?.unload()}this._assetReferences={}}findAssetReference(A){return this._assetReferences[A]||null}registerAssetReference(A){return A.uri&&(this._assetReferences[A.uri]?console.warn("Asset reference already registered",A):this._assetReferences[A.uri]=A),A}unregisterAssetReference(A){A.uri&&delete this._assetReferences[A.uri]}}const fK=Symbol("assetReference"),el=class{constructor(i,A,e=null){B(this,"_loading"),B(this,"_asset"),B(this,"_glbRoot"),B(this,"_url"),B(this,"_progressListeners",[]),B(this,"_hash"),B(this,"_hashedUri"),B(this,"_isLoadingRawBinary",!1),B(this,"_rawBinary"),this._url=i,this._hash=A,i.includes("?v=")?this._hashedUri=i:this._hashedUri=A?i+"?v="+A:i,e!==null&&(this.asset=e),Nj(this._url,this.onResolvePrefab.bind(this))}static getOrCreateFromUrl(i,A){if(!A&&(A=Ke.Current,!A))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 e=A.addressables,g=e.findAssetReference(i);if(g)return g;const I=new el(i,A.hash);return e.registerAssetReference(I),I}static getOrCreate(i,A,e){if(typeof i=="string"){if(!e&&(e=Ke.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.')}else e=i.context,i=i.sourceId;const g=MC(i,A);tB&&console.log("GetOrCreate Addressable from",i,A,"FinalPath=",g);const I=e.addressables,o=I.findAssetReference(g);if(o)return o;const s=new el(g,e.hash);return I.registerAssetReference(s),s}get asset(){return this._glbRoot??this._asset}set asset(i){this._asset=i}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(i){return i===this.uri&&(this.mustLoad&&await this.loadAssetAsync(),this.asset)?this.asset:null}get mustLoad(){return!this.asset||this.asset.__destroyed===!0||lh(this.asset)===!0}isLoaded(){return this._rawBinary||this.asset!==void 0}unload(){this.asset&&(tB&&console.log("Unload",this.asset),this.asset.scene&&Ks(this.asset.scene,!0,!0),Ks(this.asset,!0,!0)),this.asset=null,this._rawBinary=void 0,this._glbRoot=null,this._loading=void 0,Ke.Current&&Ke.Current.addressables.unregisterAssetReference(this)}async preload(){if(!this.mustLoad||this._isLoadingRawBinary)return null;if(this._rawBinary!==void 0)return this._rawBinary;this._isLoadingRawBinary=!0,tB&&console.log("Preload",this._hashedUri);const i=await c4(this._hashedUri,A=>{this.raiseProgressEvent(A)});return this._rawBinary=i?.buffer??null,this._isLoadingRawBinary=!1,this._rawBinary}async loadAssetAsync(i){if(tB&&console.log("loadAssetAsync",this.uri),!this.mustLoad)return this.asset;if(i&&this._progressListeners.push(i),this._loading!==void 0)return this._loading.then(g=>this.asset);const A=Ke.Current;this._rawBinary?(this._loading=an().parseSync(A,this._rawBinary,this.uri,null),this.raiseProgressEvent(new ProgressEvent("progress",{loaded:this._rawBinary.byteLength,total:this._rawBinary.byteLength}))):(tB&&console.log("Load async",this.uri),this._loading=an().loadSync(A,this._hashedUri,this.uri,null,g=>{this.raiseProgressEvent(g)}));const e=await this._loading;if(this._progressListeners.length=0,this._glbRoot=this.tryGetActualGameObjectRoot(e),this._loading=void 0,e)return e[fK]=this,this._glbRoot&&(this._glbRoot[fK]=this),this.asset&&(this.asset[fK]=this),pS(A),e.scene!==void 0&&(this.asset=e),this.asset}async instantiate(i){return this.onInstantiate(i,!1)}async instantiateSynced(i,A=!0){return this.onInstantiate(i,!0,A)}beginListenDownload(i){this._progressListeners.indexOf(i)<0&&this._progressListeners.push(i)}endListenDownload(i){const A=this._progressListeners.indexOf(i);A>=0&&this._progressListeners.splice(A,1)}raiseProgressEvent(i){for(const A of this._progressListeners)A(this,i)}async onInstantiate(i,A=!1,e){const g=Ke.Current,I=new Ln;if(i instanceof wA?I.parent=i:i&&(Object.assign(I,i),I.cloneAssign(i)),I.parent||(I.parent=g.scene),this.mustLoad&&await this.loadAssetAsync(),tB&&console.log("Instantiate",this.uri,"parent:",i),this.asset){tB&&console.log("Add to scene",this.asset);let o=el.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,el.currentlyInstantiating.set(this.uri,o),A){I.context=g;const s=this.asset;s.guid=this.uri;const n=Qb(s,I,void 0,e);if(n)return n}else{const s=Bl(this.asset,I);if(s)return s}}finally{g.post_render_callbacks.push(()=>{o===void 0||o<0?o=0:o-=1,el.currentlyInstantiating.set(this.uri,o)})}}else tB&&console.warn("Failed to load asset",this.uri);return null}tryGetActualGameObjectRoot(i){if(i&&i.scene){const A=i.scene;return A.isGroup&&A.children.length===1&&A.children[0].name+"glb"===A.name?A.children[0]:A}return null}};let gt=el;B(gt,"currentlyInstantiating",new Map);class qBA extends Fs{constructor(){super([gt],"AssetReferenceSerializer")}onSerialize(A,e){if(A&&A.uri!==void 0&&typeof A.uri=="string")return A.uri}onDeserialize(A,e){if(typeof A=="string")return e.context?e.gltfId?gt.getOrCreate(e.gltfId,A,e.context):(console.error("Missing source id"),null):(console.error("Missing context"),null);if(A instanceof wA){if(!e.context)return console.error("Missing context"),null;if(!e.gltfId)return console.error("Missing source id"),null;const g=A,I=e.context,o=g.guid??g.uuid,s=I.addressables.findAssetReference(o);if(s)return s;const n=new gt(o,void 0,g);return I.addressables.registerAssetReference(n),n}return null}}new qBA;const LBA=Promise.resolve(null),US=class{constructor(i){B(this,"url"),B(this,"_bitmap"),B(this,"_bitmapObject"),B(this,"loader",null),this.url=i}static getOrCreate(i){let A=US.imageReferences.get(i);return A||(A=new US(i),US.imageReferences.set(i,A)),A}dispose(){this._bitmapObject&&this._bitmapObject.close(),this._bitmap=void 0}createHTMLImage(){const i=new Image;return i.src=this.url,i}createTexture(){return this.url?(this.loader||(this.loader=new Zn),this.loader.setCrossOrigin("anonymous"),this.loader.loadAsync(this.url)):LBA}getBitmap(){return this._bitmap?this._bitmap:(this._bitmap=new Promise((i,A)=>{const e=document.createElement("img");e.addEventListener("load",()=>{this._bitmap=createImageBitmap(e).then(g=>(this._bitmapObject=g,i(g),g))}),e.addEventListener("error",g=>{console.error("Failed to load image:"+this.url,g),i(null)}),e.src=this.url}),this._bitmap)}};let NS=US;B(NS,"imageReferences",new Map);class d4 extends Fs{constructor(){super([NS],"ImageReferenceSerializer")}onSerialize(A,e){return null}onDeserialize(A,e){if(typeof A=="string"){const g=MC(e.gltfId,A);return NS.getOrCreate(g)}}}new d4;const FS=class{constructor(i){B(this,"url"),B(this,"res"),this.url=i}static getOrCreate(i){let A=FS.cache.get(i);return A||(A=new FS(i),FS.cache.set(i,A)),A}async loadRaw(){return this.res||(this.res=fetch(this.url)),this.res.then(i=>i.blob())}async loadText(){return this.res||(this.res=fetch(this.url)),this.res.then(i=>i.text())}};let vS=FS;B(vS,"cache",new Map);class u4 extends Fs{constructor(){super([vS],"FileReferenceSerializer")}onSerialize(A,e){return null}onDeserialize(A,e){if(typeof A=="string"){const g=MC(e.gltfId,A);return vS.getOrCreate(g)}}}new u4;class _BA{constructor(A){B(this,"context"),B(this,"mixers",[]),this.context=A}onDestroy(){this.mixers.forEach(A=>A.stopAllAction()),this.mixers.length=0}registerAnimationMixer(A){if(!A){console.warn("AnimationsRegistry.registerAnimationMixer called with null or undefined mixer");return}this.mixers.includes(A)||this.mixers.push(A)}unregisterAnimationMixer(A){if(!A)return;const e=this.mixers.indexOf(A);e!==-1&&this.mixers.splice(e,1)}}class tl{static tryGetActionsFromMixer(A){return A._actions||null}static tryGetAnimationClipsFromObjectHierarchy(A,e){if(e||(e=new Array),A)A.animations&&e.push(...A.animations);else return e;if(A.children)for(const g of A.children)this.tryGetAnimationClipsFromObjectHierarchy(g,e);return e}static assignAnimationsFromFile(A,e){if(!A||!A.animations)return;for(let I=0;I<A.animations.length;I++){const o=A.animations[I];if(!(!o.tracks||o.tracks.length<=0))for(const s in o.tracks){const n=o.tracks[s],a=Ze.parseTrackName(n.name);let r=Ze.findNode(A.scene,a.nodeName);if(!r){const Q=n.__objectName??n.name.substring(0,n.name.indexOf("."));if(r=A.scene.getObjectByProperty("uuid",Q),!r)continue}let C=g(r);if(!C){if(!(e!=null&&e.createAnimationComponent)){console.warn("No AnimationComponent found in parent hierarchy of object and no 'createAnimationComponent' callback was provided in options.");continue}C=e.createAnimationComponent(A.scene,o)}C.addClip&&C.addClip(o)}}function g(I){var o;if(!I)return null;const s=(o=I.userData)==null?void 0:o.components;if(s&&s.length>0){for(let n=0;n<s.length;n++)if(s[n].isAnimationComponent===!0)return I}return g(I.parent)}}}const il=[];function KS(i){il.indexOf(i)===-1&&il.push(i)}function TBA(i){const A=il.indexOf(i);A!==-1&&il.splice(A,1)}const gl=[];function kK(i){gl.indexOf(i)===-1&&gl.push(i)}function YBA(i){const A=gl.indexOf(i);A!==-1&&gl.splice(A,1)}function p4(i){globalThis.dispatchEvent(new CustomEvent("needle-xrsession-start",{detail:i}));for(let A=0;A<il.length;A++)il[A](i)}function D4(i){globalThis.dispatchEvent(new CustomEvent("needle-xrsession-end",{detail:i}));for(let A=0;A<gl.length;A++)gl[A](i)}const Kg={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 w4(i){const A=await fetch(i);if(A.ok)return A.json();throw new Error(A.statusText)}async function HBA(i){if(!i)throw new Error("No basePath supplied");return await w4(`${i}/profilesList.json`)}async function OBA(i,A,e=null,g=!0){if(!i)throw new Error("No xrInputSource supplied");if(!A)throw new Error("No basePath supplied");const I=await HBA(A);let o;if(i.profiles.some(a=>{const r=I[a];return r&&(o={profileId:a,profilePath:`${A}/${r.path}`,deprecated:!!r.deprecated}),!!o}),!o){if(!e)throw new Error("No matching profile name found");const a=I[e];if(!a)throw new Error(`No matching profile name found and default profile "${e}" missing.`);o={profileId:e,profilePath:`${A}/${a.path}`,deprecated:!!a.deprecated}}const s=await w4(o.profilePath);let n;if(g){let a;if(i.handedness==="any"?a=s.layouts[Object.keys(s.layouts)[0]]:a=s.layouts[i.handedness],!a)throw new Error(`No matching handedness, ${i.handedness}, in profile ${o.profileId}`);a.assetPath&&(n=o.profilePath.replace("profile.json",a.assetPath))}return{profile:s,assetPath:n}}const PBA={xAxis:0,yAxis:0,button:0,state:Kg.ComponentState.DEFAULT};function jBA(i=0,A=0){let e=i,g=A;if(Math.sqrt(i*i+A*A)>1){const I=Math.atan2(A,i);e=Math.cos(I),g=Math.sin(I)}return{normalizedXAxis:e*.5+.5,normalizedYAxis:g*.5+.5}}let WBA=class{constructor(i){this.componentProperty=i.componentProperty,this.states=i.states,this.valueNodeName=i.valueNodeName,this.valueNodeProperty=i.valueNodeProperty,this.valueNodeProperty===Kg.VisualResponseProperty.TRANSFORM&&(this.minNodeName=i.minNodeName,this.maxNodeName=i.maxNodeName),this.value=0,this.updateFromComponent(PBA)}updateFromComponent({xAxis:i,yAxis:A,button:e,state:g}){const{normalizedXAxis:I,normalizedYAxis:o}=jBA(i,A);switch(this.componentProperty){case Kg.ComponentProperty.X_AXIS:this.value=this.states.includes(g)?I:.5;break;case Kg.ComponentProperty.Y_AXIS:this.value=this.states.includes(g)?o:.5;break;case Kg.ComponentProperty.BUTTON:this.value=this.states.includes(g)?e:0;break;case Kg.ComponentProperty.STATE:this.valueNodeProperty===Kg.VisualResponseProperty.VISIBILITY?this.value=this.states.includes(g):this.value=this.states.includes(g)?1:0;break;default:throw new Error(`Unexpected visualResponse componentProperty ${this.componentProperty}`)}}},ZBA=class{constructor(i,A){if(!i||!A||!A.visualResponses||!A.gamepadIndices||Object.keys(A.gamepadIndices).length===0)throw new Error("Invalid arguments supplied");this.id=i,this.type=A.type,this.rootNodeName=A.rootNodeName,this.touchPointNodeName=A.touchPointNodeName,this.visualResponses={},Object.keys(A.visualResponses).forEach(e=>{const g=new WBA(A.visualResponses[e]);this.visualResponses[e]=g}),this.gamepadIndices=Object.assign({},A.gamepadIndices),this.values={state:Kg.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(i){if(this.values.state=Kg.ComponentState.DEFAULT,this.gamepadIndices.button!==void 0&&i.buttons.length>this.gamepadIndices.button){const A=i.buttons[this.gamepadIndices.button];this.values.button=A.value,this.values.button=this.values.button<0?0:this.values.button,this.values.button=this.values.button>1?1:this.values.button,A.pressed||this.values.button===1?this.values.state=Kg.ComponentState.PRESSED:(A.touched||this.values.button>Kg.ButtonTouchThreshold)&&(this.values.state=Kg.ComponentState.TOUCHED)}this.gamepadIndices.xAxis!==void 0&&i.axes.length>this.gamepadIndices.xAxis&&(this.values.xAxis=i.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===Kg.ComponentState.DEFAULT&&Math.abs(this.values.xAxis)>Kg.AxisTouchThreshold&&(this.values.state=Kg.ComponentState.TOUCHED)),this.gamepadIndices.yAxis!==void 0&&i.axes.length>this.gamepadIndices.yAxis&&(this.values.yAxis=i.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===Kg.ComponentState.DEFAULT&&Math.abs(this.values.yAxis)>Kg.AxisTouchThreshold&&(this.values.state=Kg.ComponentState.TOUCHED)),Object.values(this.visualResponses).forEach(A=>{A.updateFromComponent(this.values)})}},zBA=class{constructor(i,A,e){if(!i)throw new Error("No xrInputSource supplied");if(!A)throw new Error("No profile supplied");this.xrInputSource=i,this.assetUrl=e,this.id=A.profileId,this.layoutDescription=A.layouts[i.handedness],this.components={},Object.keys(this.layoutDescription.components).forEach(g=>{const I=this.layoutDescription.components[g];this.components[g]=new ZBA(g,I)}),this.updateFromGamepad()}get gripSpace(){return this.xrInputSource.gripSpace}get targetRaySpace(){return this.xrInputSource.targetRaySpace}get data(){const i=[];return Object.values(this.components).forEach(A=>{i.push(A.data)}),i}updateFromGamepad(){Object.values(this.components).forEach(i=>{i.updateFromGamepad(this.xrInputSource.gamepad)})}};const Io=new S,y4=new S,m4=new GA,VBA=iA("debuggizmos"),sa=8947848,na=class{constructor(){}static isGizmo(i){return i[GK]!==void 0}static DrawLabel(i,A,e=.05,g=0,I,o,s){var n;if(!na.enabled)return null;I||(I=sa);const a=((n=me.active)==null?void 0:n.rigScale)??1,r=Ki.getTextLabel(g,A,e*a,I,o);return s instanceof wA&&s.add(r),r.position.x=i.x,r.position.y=i.y,r.position.z=i.z,r}static DrawRay(i,A,e=sa,g=0,I=!0){if(!na.enabled)return;const o=Ki.getLine(g),s=o.geometry.getAttribute("position");s.setXYZ(0,i.x,i.y,i.z),Io.set(A.x,A.y,A.z).multiplyScalar(999999999),s.setXYZ(1,i.x+Io.x,i.y+Io.y,i.z+Io.z),s.needsUpdate=!0,o.material.color.set(e),o.material.depthTest=I,o.material.depthWrite=!1}static DrawDirection(i,A,e=sa,g=0,I=!0,o=1){if(!na.enabled)return;const s=Ki.getLine(g),n=s.geometry.getAttribute("position");n.setXYZ(0,i.x,i.y,i.z),A.w!==void 0?(Io.set(0,0,-o),m4.set(A.x,A.y,A.z,A.w),Io.applyQuaternion(m4)):(Io.set(A.x,A.y,A.z),Io.multiplyScalar(o)),n.setXYZ(1,i.x+Io.x,i.y+Io.y,i.z+Io.z),n.needsUpdate=!0,s.material.color.set(e),s.material.depthTest=I,s.material.depthWrite=!1}static DrawLine(i,A,e=sa,g=0,I=!0){if(!na.enabled)return;const o=Ki.getLine(g),s=o.geometry.getAttribute("position");s.setXYZ(0,i.x,i.y,i.z),s.setXYZ(1,A.x,A.y,A.z),s.needsUpdate=!0,o.material.color.set(e),o.material.depthTest=I,o.material.depthWrite=!1,o.material.fog=!1}static DrawWireSphere(i,A,e=sa,g=0,I=!0){if(!na.enabled)return;const o=Ki.getSphere(A,g,!0);TQ(o,i.x,i.y,i.z),o.material.color.set(e),o.material.depthTest=I,o.material.depthWrite=!1,o.material.fog=!1}static DrawSphere(i,A,e=sa,g=0,I=!0){if(!na.enabled)return;const o=Ki.getSphere(A,g,!1);TQ(o,i.x,i.y,i.z),o.material.color.set(e),o.material.depthTest=I,o.material.depthWrite=!1}static DrawWireBox(i,A,e=sa,g=0,I=!0){if(!na.enabled)return;const o=Ki.getBox(g);o.position.set(i.x,i.y,i.z),o.scale.set(A.x,A.y,A.z),o.material.color.set(e),o.material.depthTest=I,o.material.wireframe=!0,o.material.depthWrite=!1,o.material.fog=!1}static DrawWireBox3(i,A=sa,e=0,g=!0){if(!na.enabled)return;const I=Ki.getBox(e);I.position.copy(i.getCenter(Io)),I.scale.copy(i.getSize(Io)),I.material.color.set(A),I.material.depthTest=g,I.material.wireframe=!0,I.material.depthWrite=!1,I.material.fog=!1}static DrawArrow(i,A,e=sa,g=0,I=!0,o=!1){if(!na.enabled)return;const s=Ki.getArrowHead(g);s.position.set(A.x,A.y,A.z),s.quaternion.setFromUnitVectors(this._up.set(0,1,0),Io.set(A.x,A.y,A.z).sub(y4.set(i.x,i.y,i.z)).normalize());const n=Io.set(A.x,A.y,A.z).sub(y4.set(i.x,i.y,i.z)).length()*.1;s.scale.set(n,n,n),s.material.color.set(e),s.material.depthTest=I,s.material.wireframe=o,this.DrawLine(i,A,e,g,I)}static DrawWireMesh(i){const A=Ki.getMesh(i.duration??0);"mesh"in i?(A.geometry=i.mesh.geometry,A.matrix.copy(i.mesh.matrixWorld)):(A.geometry=i.geometry,A.matrix.copy(i.matrix)),A.matrixAutoUpdate=!1,A.matrixWorldAutoUpdate=!1,A.material.color.set(i.color??sa),A.material.depthTest=i.depthTest??!0,A.material.wireframe=!0}};let pe=na;B(pe,"enabled",!0),B(pe,"_up",new S(0,1,0));const XBA=new Ai(1,1,1);function MK(i=null){const A=new fA(i??14540253),e=new EU(XBA);return new kI(e,new Zt({color:A}))}const GK=Symbol("GizmoCache");class Ki{static ensureFont(){let A=Ot.FontLibrary.getFontFamily(this.familyName);if(!A){A=Ot.FontLibrary.addFontFamily(this.familyName);const e=A.addVariant("normal","normal","https://uploads.needle.tools/include/font-msdf.json","https://uploads.needle.tools/include/font.png");e?.addEventListener("ready",()=>{Ot.update()})}}static getTextLabel(A,e,g,I,o){this.ensureFont();let s=this.textLabelCache.pop(),n=1;o&&typeof o=="string"&&o?.length>=8&&o.startsWith("#")?(n=parseInt(o.substring(7),16)/255,o=o.substring(0,7),VBA&&console.log(o,n)):typeof o=="object"&&o.a!==void 0&&(n=o.a);const a={boxSizing:"border-box",fontFamily:this.familyName,width:"auto",fontSize:g,color:I,lineHeight:1,backgroundColor:o??void 0,backgroundOpacity:n,textContent:e,borderRadius:.5*g,padding:.8*g,whiteSpace:"pre"};if(s)s.set(a);else{s=new MN(a);const r=this,C=s;C.setText=function(Q){this.set({textContent:Q}),r.tmuiNeedsUpdate=!0}}return this.tmuiNeedsUpdate=!0,this.registerTimedObject(Ke.Current,s,A,this.textLabelCache),s}static getBox(A){let e=this.boxesCache.pop();if(!e){const g=new Ai(1,1,1);e=new dA(g)}return this.registerTimedObject(Ke.Current,e,A,this.boxesCache),e}static getLine(A){let e=this.linesCache.pop();if(!e){e=new Fi;let g=e.geometry.getAttribute("position");g||(g=new Ie(new Float32Array(2*3),3),e.geometry.setAttribute("position",g))}return e.frustumCulled=!1,this.registerTimedObject(Ke.Current,e,A,this.linesCache),e}static getSphere(A,e,g){let I=this.spheresCache.pop();return I||(I=new dA(new Vs(1,8,8))),I.scale.set(A,A,A),I.material.wireframe=g,this.registerTimedObject(Ke.Current,I,e,this.spheresCache),I}static getArrowHead(A){let e=this.arrowHeadsCache.pop();return e||(e=new dA(new Xi(0,.5,1,8))),this.registerTimedObject(Ke.Current,e,A,this.arrowHeadsCache),e}static getMesh(A){let e=this.mesh.pop();return e||(e=new dA,e.material=new tt),this.registerTimedObject(Ke.Current,e,A,this.mesh),e}static registerTimedObject(A,e,g,I){const o=this.contextBeforeRenderCallbacks.get(A),s=this.contextPostRenderCallbacks.get(A);if(o){if(A.pre_render_callbacks[A.pre_render_callbacks.length-1]!==o){const n=A.pre_render_callbacks.indexOf(o);n>=0&&A.pre_render_callbacks.splice(n,1),A.pre_render_callbacks.push(o)}}else{const n=()=>{this.onBeforeRender(A,this.timedObjectsBuffer)};this.contextBeforeRenderCallbacks.set(A,n),A.pre_render_callbacks.push(n)}if(s){if(A.post_render_callbacks[A.post_render_callbacks.length-1]!==s){const n=A.post_render_callbacks.indexOf(s);n>=0&&A.post_render_callbacks.splice(n,1),A.post_render_callbacks.push(s)}}else{const n=()=>{this.onPostRender(A,this.timedObjectsBuffer,this.timesBuffer)};this.contextPostRenderCallbacks.set(A,n),A.post_render_callbacks.push(n)}e.traverse(n=>{n.layers.disableAll(),n.layers.enable(2)}),e.renderOrder=999999,e[GK]=I,e.isGizmo=!0,this.timedObjectsBuffer.push(e),g<=0&&A.currentFrameEvent>=Xt.OnBeforeRender?this.timesBuffer.push(0):this.timesBuffer.push(Ke.Current.time.realtimeSinceStartup+g),A.scene.add(e)}static onBeforeRender(A,e){this.tmuiNeedsUpdate&&Ot.update();for(let g=0;g<e.length;g++){const I=e[g];if(A.mainCamera&&I instanceof Ot.MeshUIBaseElement){if(lh(I))continue;const o=A.isInVR,s=!1,n=!o;Su(I,A.mainCamera,s,n)}}}static onPostRender(A,e,g){const I=A.time.realtimeSinceStartup;for(let o=e.length-1;o>=0;o--){const s=e[o];I>g[o]&&(e.splice(o,1),g.splice(o,1),s.removeFromParent(),lh(s)!=!0&&s[GK].push(s))}}}B(Ki,"familyName","needle-gizmos"),B(Ki,"linesCache",[]),B(Ki,"spheresCache",[]),B(Ki,"boxesCache",[]),B(Ki,"arrowHeadsCache",[]),B(Ki,"mesh",[]),B(Ki,"textLabelCache",[]),B(Ki,"timedObjectsBuffer",new Array),B(Ki,"timesBuffer",new Array),B(Ki,"contextPostRenderCallbacks",new Map),B(Ki,"contextBeforeRenderCallbacks",new Map),B(Ki,"tmuiNeedsUpdate",!1);const Dg=iA("debuginput");var bS=(i=>(i.Mouse="mouse",i.Touch="touch",i.Controller="controller",i.Hand="hand",i))(bS||{}),hi=(i=>(i.PointerDown="pointerdown",i.PointerUp="pointerup",i.PointerMove="pointermove",i.KeyDown="keydown",i.KeyUp="keyup",i.KeyPressed="keypress",i))(hi||{});class Gr extends PointerEvent{constructor(A,e,g){super(A,g),B(this,"deviceIndex"),B(this,"origin"),B(this,"source"),B(this,"mode"),B(this,"_ray"),B(this,"space"),B(this,"isClick",!1),B(this,"isDoubleClick",!1),B(this,"_used",!1),B(this,"_pointerid"),B(this,"_pointerType"),B(this,"_type"),B(this,"metadata",{}),B(this,"intersections",new Array),B(this,"_immediatePropagationStopped",!1),B(this,"_propagationStopped",!1),this._pointerid=g.pointerId,this._pointerType=g.pointerType,this._type=A,this.deviceIndex=g.deviceIndex,this.origin=g.origin,this.source=e,this.mode=g.mode,this._ray=g.ray,this.space=g.device}get ray(){return this._ray||(this._ray=new po(this.space.worldPosition.clone(),this.space.worldForward.clone())),this._ray}set ray(A){this._ray=A}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 A;this._immediatePropagationStopped=!0,super.stopImmediatePropagation(),(A=this.source)==null||A.stopImmediatePropagation()}stopPropagation(){var A;this._propagationStopped=!0,super.stopPropagation(),(A=this.source)==null||A.stopPropagation(),Dg&&console.warn("Stop propagation...",this.pointerId,this.pointerType)}}class kp extends KeyboardEvent{constructor(A,e,g){super(A,g),B(this,"source"),this.source=e}stopImmediatePropagation(){var A;super.stopImmediatePropagation(),(A=this.source)==null||A.stopImmediatePropagation()}}class $BA{constructor(A){B(this,"key"),B(this,"keyType"),B(this,"source"),this.key=A.key,this.keyType=A.type,this.source=A}}var aa=(i=>(i[i.Early=-100]="Early",i[i.Default=0]="Default",i[i.Late=100]="Late",i))(aa||{});class S4{constructor(A){B(this,"_eventListeners",{}),B(this,"_doubleClickTimeThreshold",.2),B(this,"_longPressTimeThreshold",1),B(this,"_specialCursorTrigger",0),B(this,"context"),B(this,"_pointerDown",[!1]),B(this,"_pointerUp",[!1]),B(this,"_pointerClick",[!1]),B(this,"_pointerDoubleClick",[!1]),B(this,"_pointerPressed",[!1]),B(this,"_pointerPositions",[new AA]),B(this,"_pointerPositionsLastFrame",[new AA]),B(this,"_pointerPositionsDelta",[new AA]),B(this,"_pointerPositionsRC",[new AA]),B(this,"_pointerPositionDown",[new AA]),B(this,"_pointerDownTime",[]),B(this,"_pointerUpTime",[]),B(this,"_pointerUpTimestamp",[]),B(this,"_pointerIds",[]),B(this,"_pointerTypes",[""]),B(this,"_mouseWheelChanged",[!1]),B(this,"_mouseWheelDeltaY",[0]),B(this,"_pointerEvent",[]),B(this,"_pointerUsed",[]),B(this,"_pointerSpace",[]),B(this,"_pressedStack",new Map),B(this,"_htmlEventSource"),B(this,"onLostFocus",()=>{for(const e in this.keysPressed)this.keysPressed[e].pressed=!1}),B(this,"onEndOfFrame",()=>{for(let e=0;e<this._pointerUp.length;e++)this._pointerUp[e]=!1;for(let e=0;e<this._pointerDown.length;e++)this._pointerDown[e]=!1;for(let e=0;e<this._pointerClick.length;e++)this._pointerClick[e]=!1;for(let e=0;e<this._pointerDoubleClick.length;e++)this._pointerDoubleClick[e]=!1;for(const e of this._pointerPositionsDelta)e.set(0,0);for(let e=0;e<this._mouseWheelChanged.length;e++)this._mouseWheelChanged[e]=!1;for(let e=0;e<this._mouseWheelDeltaY.length;e++)this._mouseWheelDeltaY[e]=0}),B(this,"onContextMenu",e=>{this.canReceiveInput(e)!==!1&&e instanceof PointerEvent&&e.pointerType}),B(this,"keysPressed",{}),B(this,"onKeyDown",e=>{if(Dg&&console.log(`key down ${e.code}, ${this.context.application.hasFocus}`,e),!this.context.application.hasFocus)return;const g=this.keysPressed[e.code];if(g&&g.pressed)return;this.keysPressed[e.code]={pressed:!0,frame:this.context.time.frameCount+1,startFrame:this.context.time.frameCount+1,key:e.key,code:e.code};const I=new kp("keydown",e,e);this.onDispatchEvent(I)}),B(this,"onKeyPressed",e=>{if(!this.context.application.hasFocus)return;const g=this.keysPressed[e.code];if(!g)return;g.pressed=!0,g.frame=this.context.time.frameCount+1;const I=new kp("keypress",e,e);this.onDispatchEvent(I)}),B(this,"onKeyUp",e=>{if(!this.context.application.hasFocus)return;const g=this.keysPressed[e.code];if(!g)return;g.pressed=!1,g.frame=this.context.time.frameCount+1;const I=new kp("keyup",e,e);this.onDispatchEvent(I)}),B(this,"onWheelWindow",e=>{document.pointerLockElement&&this.onMouseWheel(e)}),B(this,"onMouseWheel",e=>{if(this.canReceiveInput(e)===!1)return;this._mouseWheelDeltaY.length<=0&&this._mouseWheelDeltaY.push(0),this._mouseWheelChanged.length<=0&&this._mouseWheelChanged.push(!1),this._mouseWheelChanged[0]=!0;const g=this._mouseWheelDeltaY[0];this._mouseWheelDeltaY[0]=g+e.deltaY}),B(this,"onPointerDown",e=>{if(this.context.isInAR||this.canReceiveInput(e)===!1)return;e.target instanceof HTMLElement&&e.target.setPointerCapture(e.pointerId);const g=this.getPointerId(e);Dg&&Ci(`pointer down #${g}, identifier:${e.pointerId}`);const I=this.getAndUpdateSpatialObjectForScreenPosition(g,e.clientX,e.clientY),o=new Gr("pointerdown",e,{origin:this,mode:"screen",deviceIndex:0,pointerId:g,button:e.button,clientX:e.clientX,clientY:e.clientY,pointerType:e.pointerType,buttonName:this.getButtonName(e),device:I,pressure:e.pressure});this.onDown(o)}),B(this,"onPointerMove",e=>{if(this.context.isInAR)return;let g=e.button;e.pointerType==="mouse"&&(g=this.getFirstPressedButtonForPointer(0)??0);const I=this.getPointerId(e,g);g===-1&&(g=I);const o=this.getAndUpdateSpatialObjectForScreenPosition(I,e.clientX,e.clientY),s=new Gr("pointermove",e,{origin:this,mode:"screen",deviceIndex:0,pointerId:I,button:g,clientX:e.clientX,clientY:e.clientY,pointerType:e.pointerType,buttonName:this.getButtonName(e),device:o,pressure:e.pressure});this.onMove(s)}),B(this,"onPointerCancel",e=>{this.context.isInAR||(Dg&&console.log("Pointer cancel",e),this.onPointerUp(e))}),B(this,"onPointerUp",e=>{if(this.context.isInAR)return;e.target instanceof HTMLElement&&e.target.releasePointerCapture(e.pointerId);const g=this.getPointerId(e),I=new Gr("pointerup",e,{origin:this,mode:"screen",deviceIndex:0,pointerId:g,button:e.button,clientX:e.clientX,clientY:e.clientY,pointerType:e.pointerType,buttonName:this.getButtonName(e),device:this.getAndUpdateSpatialObjectForScreenPosition(g,e.clientX,e.clientY),pressure:e.pressure});this.onUp(I),this._pointerIds[g]=-1,Dg&&console.log("ID="+g,"PointerId="+e.pointerId,"ALL:",[...this._pointerIds])}),B(this,"onTouchStart",e=>{if(this.context.isInAR)for(let g=0;g<e.changedTouches.length;g++){const I=e.changedTouches[g],o=this.getPointerIndex(I.identifier),s=this.getAndUpdateSpatialObjectForScreenPosition(o,I.clientX,I.clientY),n=new Gr("pointerdown",e,{origin:this,mode:"screen",deviceIndex:0,pointerId:o,button:0,clientX:I.clientX,clientY:I.clientY,pointerType:"touch",buttonName:"unknown",device:s,pressure:I.force});this.onDown(n)}}),B(this,"onTouchMove",e=>{if(this.context.isInAR)for(let g=0;g<e.changedTouches.length;g++){const I=e.changedTouches[g],o=this.getPointerIndex(I.identifier),s=this.getAndUpdateSpatialObjectForScreenPosition(o,I.clientX,I.clientY),n=new Gr("pointermove",e,{origin:this,mode:"screen",deviceIndex:0,pointerId:o,button:0,clientX:I.clientX,clientY:I.clientY,pointerType:"touch",buttonName:"unknown",device:s,pressure:I.force});this.onMove(n)}}),B(this,"onTouchEnd",e=>{if(this.context.isInAR)for(let g=0;g<e.changedTouches.length;g++){const I=e.changedTouches[g],o=this.getPointerIndex(I.identifier),s=new Gr("pointerup",e,{origin:this,mode:"screen",deviceIndex:0,pointerId:o,button:0,clientX:I.clientX,clientY:I.clientY,pointerType:"touch",buttonName:"unknown",device:this.getAndUpdateSpatialObjectForScreenPosition(o,I.clientX,I.clientY),pressure:I.force});this.onUp(s),this._pointerIds[o]=-1}}),B(this,"tempNearPlaneVector",new S),B(this,"tempFarPlaneVector",new S),B(this,"tempLookMatrix",new DA),this.context=A,this.context.post_render_callbacks.push(this.onEndOfFrame)}addEventListener(A,e,g){if(this._eventListeners[A]||(this._eventListeners[A]=[]),!e||typeof e!="function"){console.error("Invalid call to addEventListener: callback is required and must be a function!");return}g?g={...g}:g={};let I=0;g?.queue!=null&&(I=g.queue);const o=this._eventListeners[A],s=o.find(n=>n.priority===I);s?s.listeners.push({callback:e,options:g}):(o.push({priority:I,listeners:[{callback:e,options:g}]}),o.sort((n,a)=>n.priority-a.priority))}removeEventListener(A,e,g){if(!this._eventListeners[A]||!e)return;const I=this._eventListeners[A];if(g?.queue!=null){const o=I.find(n=>n.priority===g.queue);if(!o)return;const s=o.listeners.findIndex(n=>n.callback===e);s>=0&&o.listeners.splice(s,1)}else for(const o of I){const s=o.listeners.findIndex(n=>n.callback===e);s>=0&&o.listeners.splice(s,1)}}dispatchEvent(A){var e,g,I,o;let s=!1;if(A instanceof kp){const n=this._eventListeners[A.type];if(n)for(const a of n)for(let r=0;r<a.listeners.length;r++){const C=a.listeners[r];if((g=(e=C.options)==null?void 0:e.signal)!=null&&g.aborted){a.listeners.splice(r,1),r--;continue}C.options.once&&(a.listeners.splice(r,1),r--),C.callback(A)}}if(A instanceof Gr){const n=this._eventListeners[A.type];if(n)for(const a of n){if(s)break;for(let r=0;r<a.listeners.length;r++){const C=a.listeners[r];if((o=(I=C.options)==null?void 0:I.signal)!=null&&o.aborted){a.listeners.splice(r,1),r--;continue}if(A.immediatePropagationStopped){s=!0,Dg&&console.log("immediatePropagationStopped",A.type);break}else A.propagationStopped&&(s=!0,Dg&&console.log("propagationStopped",A.type));C.options.once&&(a.listeners.splice(r,1),r--),C.callback(A)}}}}get mousePosition(){return this._pointerPositions[0]}get mousePositionRC(){return this._pointerPositionsRC[0]}get mouseDown(){return this._pointerDown[0]}get mouseUp(){return this._pointerUp[0]}get mouseClick(){return this._pointerClick[0]}get mouseDoubleClick(){return this._pointerDoubleClick[0]}get mousePressed(){return this._pointerPressed[0]}get mouseWheelChanged(){return this.getMouseWheelChanged(0)}setCursorPointer(){this._specialCursorTrigger+=1,this.context.domElement.style.cursor="pointer"}setCursorNormal(){this._specialCursorTrigger-=1,this._specialCursorTrigger=Math.max(0,this._specialCursorTrigger),this._specialCursorTrigger===0&&(this.context.domElement.style.cursor="default")}setPointerUsed(A,e=!0){if(A>=this._pointerUsed.length){if(A>=this._pointerIds.length)return;for(;this._pointerUsed.length<=A;)this._pointerUsed.push(!1)}this._pointerUsed[A]=e}getPointerUsed(A){return A>=this._pointerUsed.length?!1:this._pointerUsed[A]}getPointerPressedCount(){let A=0;for(let e=0;e<this._pointerPressed.length;e++)this._pointerPressed[e]&&A++;return A}getPointerPosition(A){return A>=this._pointerPositions.length?null:this._pointerPositions[A]}getPointerPositionLastFrame(A){return A>=this._pointerPositionsLastFrame.length?null:this._pointerPositionsLastFrame[A]}getPointerPositionDelta(A){return A>=this._pointerPositionsDelta.length?null:this._pointerPositionsDelta[A]}getPointerPositionRC(A){return A>=this._pointerPositionsRC.length?null:this._pointerPositionsRC[A]}getPointerDown(A){return A>=this._pointerDown.length?!1:this._pointerDown[A]}getPointerUp(A){return A>=this._pointerUp.length?!1:this._pointerUp[A]}getPointerPressed(A){return A>=this._pointerPressed.length?!1:this._pointerPressed[A]}getPointerClicked(A){return A>=this._pointerClick.length?!1:this._pointerClick[A]}getPointerDoubleClicked(A){return A>=this._pointerDoubleClick.length?!1:this._pointerDoubleClick[A]}getPointerDownTime(A){return A>=this._pointerDownTime.length?-1:this._pointerDownTime[A]}getPointerUpTime(A){return A>=this._pointerUpTime.length?-1:this._pointerUpTime[A]}getPointerLongPress(A){return A>=this._pointerDownTime.length?!1:this.getPointerPressed(A)&&this.context.time.time-this._pointerDownTime[A]>this._longPressTimeThreshold}getIsMouse(A){return A<0||A>=this._pointerTypes.length?!1:this._pointerTypes[A]==="mouse"}getIsTouch(A){return A<0||A>=this._pointerTypes.length?!1:this._pointerTypes[A]==="touch"}getTouchesPressedCount(){let A=0;for(let e=0;e<this._pointerPressed.length;e++)this._pointerPressed[e]&&this.getIsTouch(e)&&A++;return A}getMouseWheelChanged(A=0){return A>=this._mouseWheelChanged.length?!1:this._mouseWheelChanged[A]}getMouseWheelDeltaY(A=0){return A>=this._mouseWheelDeltaY.length?0:this._mouseWheelDeltaY[A]}getPointerEvent(A){if(!(A>=this._pointerEvent.length))return this._pointerEvent[A]??void 0}*foreachPointerId(A){for(let e=0;e<this._pointerTypes.length;e++)if(this._pointerIsActive(e)){if(A!==void 0){const g=this._pointerTypes[e];if(Array.isArray(A)){let I=!1;for(const o of A)if(g===o){I=!0;break}if(!I)continue}else if(A!==g)continue}yield e}}*foreachTouchId(){for(let A=0;A<this._pointerTypes.length;A++)this._pointerTypes[A]==="touch"&&this._pointerIsActive[A]&&(yield A)}_pointerIsActive(A){return A<0?!1:this._pointerPressed[A]||this._pointerDown[A]||this._pointerUp[A]}onDownButton(A,e){let g=this._pressedStack.get(A);g||(g=[],this._pressedStack.set(A,g)),g.push(e)}onReleaseButton(A,e){const g=this._pressedStack.get(A);if(!g)return;const I=g.indexOf(e);I>=0&&g.splice(I,1)}getFirstPressedButtonForPointer(A){const e=this._pressedStack.get(A);if(e)return e[0]}getLatestPressedButtonForPointer(A){const e=this._pressedStack.get(A);if(e)return e[e.length-1]}getKeyDown(){for(const A in this.keysPressed){const e=this.keysPressed[A];if(e.startFrame===this.context.time.frameCount)return e.key}return null}getKeyPressed(){for(const A in this.keysPressed){const e=this.keysPressed[A];if(e.pressed)return e.key}return null}isKeyDown(A){var e;if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const g=this.getCodeForCommonKeyName(A);if(g!==null){for(const I of g)if(this.isKeyDown(I))return!0;return!1}return((e=this.keysPressed[A])==null?void 0:e.startFrame)===this.context.time.frameCount&&this.keysPressed[A].pressed}isKeyUp(A){var e;if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const g=this.getCodeForCommonKeyName(A);if(g!==null){for(const I of g)if(this.isKeyUp(I))return!0;return!1}return((e=this.keysPressed[A])==null?void 0:e.frame)===this.context.time.frameCount&&!this.keysPressed[A].pressed}isKeyPressed(A){var e;if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const g=this.getCodeForCommonKeyName(A);if(g!==null){for(const I of g)if(this.isKeyPressed(I))return!0;return!1}return(e=this.keysPressed[A])==null?void 0:e.pressed}getCodeForCommonKeyName(A){if(A.length===1){if(A>="0"&&A<="9")return["Digit"+A];if(A>="a"&&A<="z")return["Key"+A.toUpperCase()];if(A==" ")return["Space"]}switch(A){case"shift":case"Shift":return["ShiftLeft","ShiftRight"];case"control":case"Control":return["ControlLeft","ControlRight"];case"alt":case"Alt":return["AltLeft","AltRight"]}return null}createInputEvent(A){switch(A.type){case"pointerdown":Dg&&Ci("Create Pointer down"),this.onDownButton(A.deviceIndex,A.button),this.onDown(A);break;case"pointermove":Dg&&Ci("Create Pointer move"),this.onMove(A);break;case"pointerup":Dg&&Ci("Create Pointer up"),this.onUp(A),this.onReleaseButton(A.deviceIndex,A.button);break}}convertScreenspaceToRaycastSpace(A){return A.x=(A.x-this.context.domX)/this.context.domWidth*2-1,A.y=-((A.y-this.context.domY)/this.context.domHeight)*2+1,A}bindEvents(){this.unbindEvents(),this._htmlEventSource=this.context.renderer.domElement,window.addEventListener("contextmenu",this.onContextMenu),this._htmlEventSource.addEventListener("pointerdown",this.onPointerDown,{passive:!0}),window.addEventListener("pointermove",this.onPointerMove,{passive:!0,capture:!0}),window.addEventListener("pointerup",this.onPointerUp,{passive:!0}),window.addEventListener("pointercancel",this.onPointerCancel,{passive:!0}),window.addEventListener("touchstart",this.onTouchStart,{passive:!0}),window.addEventListener("touchmove",this.onTouchMove,{passive:!0}),window.addEventListener("touchend",this.onTouchEnd,{passive:!0}),this._htmlEventSource.addEventListener("wheel",this.onMouseWheel,{passive:!0}),window.addEventListener("wheel",this.onWheelWindow,{passive:!0}),window.addEventListener("keydown",this.onKeyDown,!1),window.addEventListener("keypress",this.onKeyPressed,!1),window.addEventListener("keyup",this.onKeyUp,!1),window.addEventListener("blur",this.onLostFocus)}unbindEvents(){var A,e;window.removeEventListener("contextmenu",this.onContextMenu),(A=this._htmlEventSource)==null||A.removeEventListener("pointerdown",this.onPointerDown),window.removeEventListener("pointermove",this.onPointerMove),window.removeEventListener("pointerup",this.onPointerUp),window.removeEventListener("pointercancel",this.onPointerCancel),(e=this._htmlEventSource)==null||e.removeEventListener("wheel",this.onMouseWheel,!1),window.removeEventListener("wheel",this.onWheelWindow,!1),window.removeEventListener("keydown",this.onKeyDown,!1),window.removeEventListener("keypress",this.onKeyPressed,!1),window.removeEventListener("keyup",this.onKeyUp,!1),window.removeEventListener("blur",this.onLostFocus)}dispose(){const A=this.context.post_render_callbacks.indexOf(this.onEndOfFrame);A>=0&&this.context.post_render_callbacks.splice(A,1),this.unbindEvents()}canReceiveInput(A){var e;return A.target===((e=this.context.renderer)==null?void 0:e.domElement)||A.target===this.context.domElement||this.context.isInAR||this.context.isInAR&&A.target===document.body&&JQ()?!0:(Dg&&console.warn("CanReceiveInput:False for",A.target),!1)}getPointerId(A,e){return A.pointerType==="mouse"?0+(e??A.button):this.getPointerIndex(A.pointerId)}getButtonName(A){const e=A.button;if(A.pointerType==="mouse")switch(e){case 0:return"left";case 1:return"middle";case 2:return"right"}return"unknown"}getAndUpdateSpatialObjectForScreenPosition(A,e,g){let I=this._pointerSpace[A];I||(I=new wA,this._pointerSpace[A]=I),this._pointerSpace[A]=I;const o=this.context.mainCamera;if(o){const s=this.tempNearPlaneVector.set(e,g,-1);this.convertScreenspaceToRaycastSpace(s);const n=this.tempFarPlaneVector.set(s.x,s.y,1);s.unproject(o),n.unproject(o);const a=o.worldUp||lt(0,1,0).applyQuaternion(Nt(o));this.tempLookMatrix.lookAt(n,s,a),I.position.set(s.x,s.y,s.z),I.quaternion.setFromRotationMatrix(this.tempLookMatrix)}return I}isInRect(A){if(this.context.isInXR)return!0;const e=this.context.domElement.getBoundingClientRect(),g=A.clientX,I=A.clientY,o=g>=e.x&&g<=e.right&&I>=e.y&&I<=e.bottom;return Dg&&!o&&console.log("Not in rect",e,g,I),o}onDown(A){const e=A.pointerId;if(this.getPointerPressed(e)&&console.warn(`pointerId is already pressed: ${e}`,Dg?A:""),Dg&&console.log(A.pointerType,"DOWN",e),!!this.isInRect(A)){for(this.setPointerState(e,this._pointerPressed,!0),this.setPointerState(e,this._pointerDown,!0),this.setPointerStateT(e,this._pointerEvent,A.source);e>=this._pointerTypes.length;)this._pointerTypes.push(A.pointerType);for(this._pointerTypes[e]=A.pointerType;e>=this._pointerPositionDown.length;)this._pointerPositionDown.push(new AA);for(this._pointerPositionDown[e].set(A.clientX,A.clientY);e>=this._pointerPositions.length;)this._pointerPositions.push(new AA);this._pointerPositions[e].set(A.clientX,A.clientY),e>=this._pointerDownTime.length&&this._pointerDownTime.push(0),this._pointerDownTime[e]=this.context.time.time,this.updatePointerPosition(A),this.onDispatchEvent(A)}}onMove(A){const e=A.pointerId,g=this.getPointerPressed(e);g===!1&&!this.isInRect(A)||A.pointerType==="touch"&&!g||(this.updatePointerPosition(A),this.setPointerStateT(e,this._pointerEvent,A.source),this.onDispatchEvent(A))}onUp(A){const e=A.pointerId;if(!this.getPointerPressed(e)){Dg&&console.log(A.pointerType,"UP",e,"was not down");return}for(Dg&&console.log(A.pointerType,"UP",e),this.setPointerState(e,this._pointerPressed,!1),this.setPointerStateT(e,this._pointerEvent,A.source),this.setPointerState(e,this._pointerUp,!0);e>=this._pointerUsed.length;)this._pointerUsed.push(!1);if(this.setPointerState(e,this._pointerUsed,!1),this.updatePointerPosition(A),!this._pointerPositionDown[e]){Dg&&Lt("Received pointer up event without matching down event for button: "+e),console.warn("Received pointer up event without matching down event for button: "+e);return}const g=A.clientX-this._pointerPositionDown[e].x,I=A.clientY-this._pointerPositionDown[e].y;if(e>=this._pointerUpTime.length&&this._pointerUpTime.push(-99),Math.abs(g)<5&&Math.abs(I)<5){Dg&&console.log("CLICK",e),this.setPointerState(e,this._pointerClick,!0),A.isClick=!0;const o=this._pointerUpTime[e],s=this.context.time.time-o;s<this._doubleClickTimeThreshold&&s>0&&(this.setPointerState(e,this._pointerDoubleClick,!0),A.isDoubleClick=!0)}this._pointerUpTime[e]=this.context.time.time,this.onDispatchEvent(A)}updatePointerPosition(A){const e=A.pointerId;for(;e>=this._pointerPositions.length;)this._pointerPositions.push(new AA);for(;e>=this._pointerPositionsLastFrame.length;)this._pointerPositionsLastFrame.push(new AA);for(;e>=this._pointerPositionsDelta.length;)this._pointerPositionsDelta.push(new AA);const g=this._pointerPositionsLastFrame[e];g.copy(this._pointerPositions[e]);const I=this._pointerPositionsDelta[e];let o=A.clientX-g.x,s=A.clientY-g.y;if(A.source instanceof MouseEvent||A.source instanceof TouchEvent){const C=A.source;o===0&&C.movementX!==0&&(o=C.movementX||0),s===0&&C.movementY!==0&&(s=C.movementY||0)}I.x+=o,I.y+=s,this._pointerPositions[e].x=A.clientX,this._pointerPositions[e].y=A.clientY;const n=A.clientX,a=A.clientY;for(;e>=this._pointerPositionsRC.length;)this._pointerPositionsRC.push(new AA);const r=this._pointerPositionsRC[e];r.set(n,a),this.convertScreenspaceToRaycastSpace(r)}getPointerIndex(A){let e=-1;for(let g=0;g<this._pointerIds.length;g++){if(this._pointerIds[g]===A)return g;e===-1&&this._pointerIds[g]===-1&&(e=g)}return e!==-1?(this._pointerIds[e]=A,e):(Dg&&console.log("PUSH pointerId:",A),this._pointerIds.push(A),this._pointerIds.length-1)}setPointerState(A,e,g){e[A]=g}setPointerStateT(A,e,g){return e[A]=g,g}onDispatchEvent(A){const e=Ke.Current;try{Ke.Current=this.context,this.dispatchEvent(A)}finally{Ke.Current=e}}}const JS=new DA().makeRotationY(Math.PI),vs=new GA().setFromAxisAngle(new S(0,1,0),Math.PI),AQA=iA("debugwebxr");class eQA{constructor(){if(B(this,"priority",-1e5),B(this,"gameObject"),this.gameObject=new wA,this.gameObject.name="Implicit XR Rig",AQA){const A=MK(16733661);A.position.y+=.5,this.gameObject.add(A)}}isXRRig(){return!0}get isActive(){return this.gameObject.visible}}const iB=iA("debugwebxr"),xS=iA("debugcustomgesture"),tQA="https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles",iQA="generic-trigger";class RK{constructor(A,e,g){B(this,"xr"),B(this,"inputSource"),B(this,"index",0),B(this,"emitEvents",!0),B(this,"_connected",!0),B(this,"_isTracking",!1),B(this,"_hitTestSource"),B(this,"_hasSelectEvent",!1),B(this,"_handJointPoses",new Map),B(this,"_gripPosition",new S),B(this,"_gripQuaternion",new GA),B(this,"_linearVelocity",new S),B(this,"_rayPosition",new S),B(this,"_rayQuaternion",new GA),B(this,"_gripWorldPosition",new S),B(this,"_gripWorldQuaternion",new GA),B(this,"_rayWorldPosition",new S),B(this,"_rayWorldQuaternion",new GA),B(this,"_ray"),B(this,"_object"),B(this,"model",null),B(this,"_debugAxesHelper",new _o(.2)),B(this,"onPointerHits",n=>{}),B(this,"_needleGamepadButtons",{}),B(this,"_buttonMap",new Map),B(this,"_motioncontroller"),B(this,"_layout"),B(this,"getMotionController"),B(this,"_selectButtonIndex"),B(this,"_squeezeButtonIndex"),B(this,"onSelectStart",n=>{var a,r,C,Q;if(this.inputSource!==n.inputSource)return;this.onUpdateFrame(n.frame),this._hasSelectEvent=!0;const h=(a=this._layout)==null?void 0:a.selectComponentId,E=(Q=(C=(r=this._layout)==null?void 0:r.components[h])==null?void 0:C.gamepadIndices)==null?void 0:Q.button;E!==void 0&&(this._selectButtonIndex=E),!xS&&(iB&&pe.DrawDirection(this.rayWorldPosition,lt(0,.01,1).applyQuaternion(this.rayWorldQuaternion),16711680,10),this.emitPointerEvent(hi.PointerDown,this._selectButtonIndex||0,"xr-standard-trigger",!0,n))}),B(this,"onSelectEnd",n=>{xS||this.inputSource===n.inputSource&&this.emitPointerEvent(hi.PointerUp,this._selectButtonIndex||0,"xr-standard-trigger",!0,n)}),B(this,"onSequeezeStart",n=>{var a,r,C;this.inputSource===n.inputSource&&(this._squeezeButtonIndex=(C=(r=(a=this._layout)==null?void 0:a.components["xr-standard-squeeze"])==null?void 0:r.gamepadIndices)==null?void 0:C.button,this._squeezeButtonIndex!==void 0&&(iB&&pe.DrawDirection(this.rayWorldPosition,lt(0,.01,1).applyQuaternion(this.rayWorldQuaternion),255,10),this.emitPointerEvent(hi.PointerDown,this._squeezeButtonIndex||0,"xr-standard-squeeze",!0,n)))}),B(this,"onSequeezeEnd",n=>{this.inputSource===n.inputSource&&this._squeezeButtonIndex!==void 0&&this.emitPointerEvent(hi.PointerUp,this._squeezeButtonIndex||0,"xr-standard-squeeze",!0,n)}),B(this,"states",{}),B(this,"_didMoveLastFrame",!1),B(this,"_lastPointerMovePosition",new S),B(this,"_lastPointerMoveQuaternion",new GA),B(this,"pointerInit");var I,o,s;this.xr=A,this.inputSource=e,this.index=g,this._object=new wA,iB&&this._object.add(this._debugAxesHelper),this.xr.context.scene.add(this._object),this._ray=new po,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"&&((s=(o=(I=this.xr.session).requestHitTestSourceForTransientInput)==null?void 0:o.call(I,{profile:this.inputSource.profiles[0],offsetRay:new XRRay}))==null||s.then(n=>this._hitTestSource=n))}get context(){return this.xr.context}get connected(){return this._connected}get isTracking(){return this._isTracking}get gamepad(){return this.inputSource.gamepad}get isHand(){return this.inputSource.hand!=null}get hand(){return this.inputSource.hand}get handObject(){return this.context.renderer.xr.getHand(this.index)}get profiles(){return this.inputSource.profiles}get layout(){return this._layout}get targetRayMode(){return this.inputSource.targetRayMode}get targetRaySpace(){return this.inputSource.targetRaySpace}get gripSpace(){return this.inputSource.gripSpace}get side(){return this.inputSource.handedness}get isRight(){return this.side==="right"}get isLeft(){return this.side==="left"}get hitTestSource(){return this._hitTestSource}get hasSelectEvent(){return this._hasSelectEvent}getHitTest(){return this.xr.getHitTest(this)}getHandJointPose(A){var e,g;if(!this.hand||!((e=this.xr.frame)!=null&&e.getJointPose)||!this.xr.referenceSpace)return null;let I=(g=this._handJointPoses)==null?void 0:g.get(A);return I||(I=this.xr.frame.getJointPose(A,this.xr.referenceSpace),I&&this._handJointPoses.set(A,I),I)}get gripPosition(){return lt(this._gripPosition).applyMatrix4(JS)}get gripQuaternion(){return _Q(this._gripQuaternion).premultiply(vs)}get gripLinearVelocity(){return lt(this._linearVelocity).applyQuaternion(vs)}get rayPosition(){return lt(this._rayPosition).applyMatrix4(JS)}get rayQuaternion(){return _Q(this._rayQuaternion).premultiply(vs)}get gripWorldPosition(){return lt(this._gripWorldPosition)}get gripWorldQuaternion(){return _Q(this._gripWorldQuaternion)}get rayWorldPosition(){return lt(this._rayWorldPosition)}updateRayWorldPosition(){var A;const e=(A=this.xr.context.mainCamera)==null?void 0:A.parent;this._rayWorldPosition.copy(this._rayPosition),e&&this._rayWorldPosition.applyMatrix4(e.matrixWorld)}get rayWorldQuaternion(){return _Q(this._rayWorldQuaternion)}updateRayWorldQuaternion(){var A;const e=(A=this.xr.context.mainCamera)==null?void 0:A.parent,g=e?Nt(e):void 0;this._rayWorldQuaternion.copy(this._rayQuaternion).multiply(vs),g&&this._rayWorldQuaternion.premultiply(g)}get ray(){return this._ray.origin.copy(this.rayWorldPosition),this._ray.direction.copy(lt(0,0,1).applyQuaternion(this.rayWorldQuaternion)),this._ray}get object(){return this._object}async getModelUrl(){var A;return(A=this.getMotionController)==null?void 0:A.then(e=>e?.assetUrl||null)}onUpdate(A){this.onUpdateFrame(A),this.updateInputEvents(),this.onUpdateMove()}onRenderDebug(){var A;pe.DrawWireSphere(this.rayWorldPosition,.02),pe.DrawDirection(this.rayWorldPosition,lt(0,0,10).applyQuaternion(this.rayWorldQuaternion));const e=this.gripWorldPosition.sub(this.object.worldForward.multiplyScalar(.1)),g=this.inputSource.profiles.join(`
5151
+ */var KBA=function(i){return i!=null&&(h4(i)||bBA(i)||!!i._isBuffer)};function h4(i){return!!i.constructor&&typeof i.constructor.isBuffer=="function"&&i.constructor.isBuffer(i)}function bBA(i){return typeof i.readFloatLE=="function"&&typeof i.slice=="function"&&h4(i.slice(0,0))}(function(){var i=vBA,A=Q4.utf8,e=KBA,g=Q4.bin,I=function(o,s){o.constructor==String?s&&s.encoding==="binary"?o=g.stringToBytes(o):o=A.stringToBytes(o):e(o)?o=Array.prototype.slice.call(o,0):!Array.isArray(o)&&o.constructor!==Uint8Array&&(o=o.toString());for(var n=i.bytesToWords(o),a=o.length*8,r=1732584193,C=-271733879,Q=-1732584194,h=271733878,E=0;E<n.length;E++)n[E]=(n[E]<<8|n[E]>>>24)&16711935|(n[E]<<24|n[E]>>>8)&4278255360;n[a>>>5]|=128<<a%32,n[(a+64>>>9<<4)+14]=a;for(var c=I._ff,l=I._gg,d=I._hh,u=I._ii,E=0;E<n.length;E+=16){var D=r,p=C,w=Q,f=h;r=c(r,C,Q,h,n[E+0],7,-680876936),h=c(h,r,C,Q,n[E+1],12,-389564586),Q=c(Q,h,r,C,n[E+2],17,606105819),C=c(C,Q,h,r,n[E+3],22,-1044525330),r=c(r,C,Q,h,n[E+4],7,-176418897),h=c(h,r,C,Q,n[E+5],12,1200080426),Q=c(Q,h,r,C,n[E+6],17,-1473231341),C=c(C,Q,h,r,n[E+7],22,-45705983),r=c(r,C,Q,h,n[E+8],7,1770035416),h=c(h,r,C,Q,n[E+9],12,-1958414417),Q=c(Q,h,r,C,n[E+10],17,-42063),C=c(C,Q,h,r,n[E+11],22,-1990404162),r=c(r,C,Q,h,n[E+12],7,1804603682),h=c(h,r,C,Q,n[E+13],12,-40341101),Q=c(Q,h,r,C,n[E+14],17,-1502002290),C=c(C,Q,h,r,n[E+15],22,1236535329),r=l(r,C,Q,h,n[E+1],5,-165796510),h=l(h,r,C,Q,n[E+6],9,-1069501632),Q=l(Q,h,r,C,n[E+11],14,643717713),C=l(C,Q,h,r,n[E+0],20,-373897302),r=l(r,C,Q,h,n[E+5],5,-701558691),h=l(h,r,C,Q,n[E+10],9,38016083),Q=l(Q,h,r,C,n[E+15],14,-660478335),C=l(C,Q,h,r,n[E+4],20,-405537848),r=l(r,C,Q,h,n[E+9],5,568446438),h=l(h,r,C,Q,n[E+14],9,-1019803690),Q=l(Q,h,r,C,n[E+3],14,-187363961),C=l(C,Q,h,r,n[E+8],20,1163531501),r=l(r,C,Q,h,n[E+13],5,-1444681467),h=l(h,r,C,Q,n[E+2],9,-51403784),Q=l(Q,h,r,C,n[E+7],14,1735328473),C=l(C,Q,h,r,n[E+12],20,-1926607734),r=d(r,C,Q,h,n[E+5],4,-378558),h=d(h,r,C,Q,n[E+8],11,-2022574463),Q=d(Q,h,r,C,n[E+11],16,1839030562),C=d(C,Q,h,r,n[E+14],23,-35309556),r=d(r,C,Q,h,n[E+1],4,-1530992060),h=d(h,r,C,Q,n[E+4],11,1272893353),Q=d(Q,h,r,C,n[E+7],16,-155497632),C=d(C,Q,h,r,n[E+10],23,-1094730640),r=d(r,C,Q,h,n[E+13],4,681279174),h=d(h,r,C,Q,n[E+0],11,-358537222),Q=d(Q,h,r,C,n[E+3],16,-722521979),C=d(C,Q,h,r,n[E+6],23,76029189),r=d(r,C,Q,h,n[E+9],4,-640364487),h=d(h,r,C,Q,n[E+12],11,-421815835),Q=d(Q,h,r,C,n[E+15],16,530742520),C=d(C,Q,h,r,n[E+2],23,-995338651),r=u(r,C,Q,h,n[E+0],6,-198630844),h=u(h,r,C,Q,n[E+7],10,1126891415),Q=u(Q,h,r,C,n[E+14],15,-1416354905),C=u(C,Q,h,r,n[E+5],21,-57434055),r=u(r,C,Q,h,n[E+12],6,1700485571),h=u(h,r,C,Q,n[E+3],10,-1894986606),Q=u(Q,h,r,C,n[E+10],15,-1051523),C=u(C,Q,h,r,n[E+1],21,-2054922799),r=u(r,C,Q,h,n[E+8],6,1873313359),h=u(h,r,C,Q,n[E+15],10,-30611744),Q=u(Q,h,r,C,n[E+6],15,-1560198380),C=u(C,Q,h,r,n[E+13],21,1309151649),r=u(r,C,Q,h,n[E+4],6,-145523070),h=u(h,r,C,Q,n[E+11],10,-1120210379),Q=u(Q,h,r,C,n[E+2],15,718787259),C=u(C,Q,h,r,n[E+9],21,-343485551),r=r+D>>>0,C=C+p>>>0,Q=Q+w>>>0,h=h+f>>>0}return i.endian([r,C,Q,h])};I._ff=function(o,s,n,a,r,C,Q){var h=o+(s&n|~s&a)+(r>>>0)+Q;return(h<<C|h>>>32-C)+s},I._gg=function(o,s,n,a,r,C,Q){var h=o+(s&a|n&~a)+(r>>>0)+Q;return(h<<C|h>>>32-C)+s},I._hh=function(o,s,n,a,r,C,Q){var h=o+(s^n^a)+(r>>>0)+Q;return(h<<C|h>>>32-C)+s},I._ii=function(o,s,n,a,r,C,Q){var h=o+(n^(s|~a))+(r>>>0)+Q;return(h<<C|h>>>32-C)+s},I._blocksize=16,I._digestsize=16,C4.exports=function(o,s){if(o==null)throw new Error("Illegal argument "+o);var n=i.wordsToBytes(I(o,s));return s&&s.asBytes?n:s&&s.asString?g.bytesToString(n):i.bytesToHex(n)}})();var JBA=C4.exports;const xBA=RS(JBA);class yK{constructor(A,e,g,I){B(this,"success"),B(this,"filename"),B(this,"hash"),B(this,"size"),B(this,"url"),this.success=A,this.filename=e,this.hash=g,this.size=I}}async function E4(i,A){const e=await i.arrayBuffer(),g=mK(e),I=i.name.split(".").pop(),o=g+"."+I,s=i.name.split(".").shift();console.assert(s!==void 0);const n={alias:s,filename:o},a=await(await fetch(A+"/exists",{method:"POST",body:JSON.stringify(n)})).json();if(a.success||console.warn("exists check did fail"),a.exists)return console.log("file already exists",g),new yK(!0,o,g,i.size);console.log("begin uploading file",s,i.size);const r=new FormData;r.append("file",i);const C={};C.filesize=i.size,s&&(C.alias=s);const Q=await(await fetch(A+"/upload/file",{method:"POST",body:r,headers:C})).json();if(Q?.success===!1)return Q.message!==void 0?console.error("Upload failed:",Q.message):console.error("Upload failed"),null;console.assert(Q.hash_sum===g,"hash sum did not match","received:",Q.hash_sum,"expected:",g),Q.success&&console.log("successfully uploaded",g,Q.id);const h=new yK(Q.success,o,g,i.size);return h.url=A,h}function mK(i){return xBA(new Uint8Array(i))}async function SK(i,A,e,g,I=!1){try{const o=await fetch(g+"/download/file",{method:"POST",body:i});if(o.status!==200)return console.error("download failed",o),null;const s=await o.blob(),n=await s.arrayBuffer();I||console.assert(s.size===e,"size mismatch","expected:",e,"got:",s.size);const a=mK(n);return I||console.assert(a===A,"hash mismatch, downloaded file is invalid"),s.arrayBuffer()}catch(o){console.error(o)}return null}async function c4(i,A){var e;const g=await fetch(i),I=(e=g.body)==null?void 0:e.getReader(),o=g.headers.get("Content-Length"),s=o?parseInt(o):0;if(!I)return null;let n=0;const a=[];for(;;){const{done:Q,value:h}=await I.read();if(h&&(a.push(h),n+=h.length,A.call(null,new ProgressEvent("progress",{loaded:n,total:s}))),Q)break}const r=new Uint8Array(n);let C=0;for(const Q of a)r.set(Q,C),C+=Q.length;return r}const tB=iA("debugaddressables");class l4{constructor(A){B(this,"_context"),B(this,"_assetReferences",{}),B(this,"preUpdate",()=>{}),this._context=A,this._context.pre_update_callbacks.push(this.preUpdate)}dispose(){const A=this._context.pre_update_callbacks.indexOf(this.preUpdate);A>=0&&this._context.pre_update_callbacks.splice(A,1);for(const e in this._assetReferences){const g=this._assetReferences[e];g?.unload()}this._assetReferences={}}findAssetReference(A){return this._assetReferences[A]||null}registerAssetReference(A){return A.uri&&(this._assetReferences[A.uri]?console.warn("Asset reference already registered",A):this._assetReferences[A.uri]=A),A}unregisterAssetReference(A){A.uri&&delete this._assetReferences[A.uri]}}const fK=Symbol("assetReference"),el=class{constructor(i,A,e=null){B(this,"_loading"),B(this,"_asset"),B(this,"_glbRoot"),B(this,"_url"),B(this,"_progressListeners",[]),B(this,"_hash"),B(this,"_hashedUri"),B(this,"_isLoadingRawBinary",!1),B(this,"_rawBinary"),this._url=i,this._hash=A,i.includes("?v=")?this._hashedUri=i:this._hashedUri=A?i+"?v="+A:i,e!==null&&(this.asset=e),Nj(this._url,this.onResolvePrefab.bind(this))}static getOrCreateFromUrl(i,A){if(!A&&(A=Ke.Current,!A))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 e=A.addressables,g=e.findAssetReference(i);if(g)return g;const I=new el(i,A.hash);return e.registerAssetReference(I),I}static getOrCreate(i,A,e){if(typeof i=="string"){if(!e&&(e=Ke.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.')}else e=i.context,i=i.sourceId;const g=MC(i,A);tB&&console.log("GetOrCreate Addressable from",i,A,"FinalPath=",g);const I=e.addressables,o=I.findAssetReference(g);if(o)return o;const s=new el(g,e.hash);return I.registerAssetReference(s),s}get asset(){return this._glbRoot??this._asset}set asset(i){this._asset=i}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(i){return i===this.uri&&(this.mustLoad&&await this.loadAssetAsync(),this.asset)?this.asset:null}get mustLoad(){return!this.asset||this.asset.__destroyed===!0||lh(this.asset)===!0}isLoaded(){return this._rawBinary||this.asset!==void 0}unload(){this.asset&&(tB&&console.log("Unload",this.asset),this.asset.scene&&Ks(this.asset.scene,!0,!0),Ks(this.asset,!0,!0)),this.asset=null,this._rawBinary=void 0,this._glbRoot=null,this._loading=void 0,Ke.Current&&Ke.Current.addressables.unregisterAssetReference(this)}async preload(){if(!this.mustLoad||this._isLoadingRawBinary)return null;if(this._rawBinary!==void 0)return this._rawBinary;this._isLoadingRawBinary=!0,tB&&console.log("Preload",this._hashedUri);const i=await c4(this._hashedUri,A=>{this.raiseProgressEvent(A)});return this._rawBinary=i?.buffer??null,this._isLoadingRawBinary=!1,this._rawBinary}async loadAssetAsync(i){if(tB&&console.log("loadAssetAsync",this.uri),!this.mustLoad)return this.asset;if(i&&this._progressListeners.push(i),this._loading!==void 0)return this._loading.then(g=>this.asset);const A=Ke.Current;this._rawBinary?(this._loading=an().parseSync(A,this._rawBinary,this.uri,null),this.raiseProgressEvent(new ProgressEvent("progress",{loaded:this._rawBinary.byteLength,total:this._rawBinary.byteLength}))):(tB&&console.log("Load async",this.uri),this._loading=an().loadSync(A,this._hashedUri,this.uri,null,g=>{this.raiseProgressEvent(g)}));const e=await this._loading;if(this._progressListeners.length=0,this._glbRoot=this.tryGetActualGameObjectRoot(e),this._loading=void 0,e)return e[fK]=this,this._glbRoot&&(this._glbRoot[fK]=this),this.asset&&(this.asset[fK]=this),pS(A),e.scene!==void 0&&(this.asset=e),this.asset}async instantiate(i){return this.onInstantiate(i,!1)}async instantiateSynced(i,A=!0){return this.onInstantiate(i,!0,A)}beginListenDownload(i){this._progressListeners.indexOf(i)<0&&this._progressListeners.push(i)}endListenDownload(i){const A=this._progressListeners.indexOf(i);A>=0&&this._progressListeners.splice(A,1)}raiseProgressEvent(i){for(const A of this._progressListeners)A(this,i)}async onInstantiate(i,A=!1,e){const g=Ke.Current,I=new Ln;if(i instanceof wA?I.parent=i:i&&(Object.assign(I,i),I.cloneAssign(i)),I.parent||(I.parent=g.scene),this.mustLoad&&await this.loadAssetAsync(),tB&&console.log("Instantiate",this.uri,"parent:",i),this.asset){tB&&console.log("Add to scene",this.asset);let o=el.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,el.currentlyInstantiating.set(this.uri,o),A){I.context=g;const s=this.asset;s.guid=this.uri;const n=Qb(s,I,void 0,e);if(n)return n}else{const s=Bl(this.asset,I);if(s)return s}}finally{g.post_render_callbacks.push(()=>{o===void 0||o<0?o=0:o-=1,el.currentlyInstantiating.set(this.uri,o)})}}else tB&&console.warn("Failed to load asset",this.uri);return null}tryGetActualGameObjectRoot(i){if(i&&i.scene){const A=i.scene;return A.isGroup&&A.children.length===1&&A.children[0].name+"glb"===A.name?A.children[0]:A}return null}};let gt=el;B(gt,"currentlyInstantiating",new Map);class qBA extends Fs{constructor(){super([gt],"AssetReferenceSerializer")}onSerialize(A,e){if(A&&A.uri!==void 0&&typeof A.uri=="string")return A.uri}onDeserialize(A,e){if(typeof A=="string")return e.context?e.gltfId?gt.getOrCreate(e.gltfId,A,e.context):(console.error("Missing source id"),null):(console.error("Missing context"),null);if(A instanceof wA){if(!e.context)return console.error("Missing context"),null;if(!e.gltfId)return console.error("Missing source id"),null;const g=A,I=e.context,o=g.guid??g.uuid,s=I.addressables.findAssetReference(o);if(s)return s;const n=new gt(o,void 0,g);return I.addressables.registerAssetReference(n),n}return null}}new qBA;const LBA=Promise.resolve(null),US=class{constructor(i){B(this,"url"),B(this,"_bitmap"),B(this,"_bitmapObject"),B(this,"loader",null),this.url=i}static getOrCreate(i){let A=US.imageReferences.get(i);return A||(A=new US(i),US.imageReferences.set(i,A)),A}dispose(){this._bitmapObject&&this._bitmapObject.close(),this._bitmap=void 0}createHTMLImage(){const i=new Image;return i.src=this.url,i}createTexture(){return this.url?(this.loader||(this.loader=new Zn),this.loader.setCrossOrigin("anonymous"),this.loader.loadAsync(this.url)):LBA}getBitmap(){return this._bitmap?this._bitmap:(this._bitmap=new Promise((i,A)=>{const e=document.createElement("img");e.addEventListener("load",()=>{this._bitmap=createImageBitmap(e).then(g=>(this._bitmapObject=g,i(g),g))}),e.addEventListener("error",g=>{console.error("Failed to load image:"+this.url,g),i(null)}),e.src=this.url}),this._bitmap)}};let NS=US;B(NS,"imageReferences",new Map);class d4 extends Fs{constructor(){super([NS],"ImageReferenceSerializer")}onSerialize(A,e){return null}onDeserialize(A,e){if(typeof A=="string"){const g=MC(e.gltfId,A);return NS.getOrCreate(g)}}}new d4;const FS=class{constructor(i){B(this,"url"),B(this,"res"),this.url=i}static getOrCreate(i){let A=FS.cache.get(i);return A||(A=new FS(i),FS.cache.set(i,A)),A}async loadRaw(){return this.res||(this.res=fetch(this.url)),this.res.then(i=>i.blob())}async loadText(){return this.res||(this.res=fetch(this.url)),this.res.then(i=>i.text())}};let vS=FS;B(vS,"cache",new Map);class u4 extends Fs{constructor(){super([vS],"FileReferenceSerializer")}onSerialize(A,e){return null}onDeserialize(A,e){if(typeof A=="string"){const g=MC(e.gltfId,A);return vS.getOrCreate(g)}}}new u4;class _BA{constructor(A){B(this,"context"),B(this,"mixers",[]),this.context=A}onDestroy(){this.mixers.forEach(A=>A.stopAllAction()),this.mixers.length=0}registerAnimationMixer(A){if(!A){console.warn("AnimationsRegistry.registerAnimationMixer called with null or undefined mixer");return}this.mixers.includes(A)||this.mixers.push(A)}unregisterAnimationMixer(A){if(!A)return;const e=this.mixers.indexOf(A);e!==-1&&this.mixers.splice(e,1)}}class tl{static tryGetActionsFromMixer(A){return A._actions||null}static tryGetAnimationClipsFromObjectHierarchy(A,e){if(e||(e=new Array),A)A.animations&&e.push(...A.animations);else return e;if(A.children)for(const g of A.children)this.tryGetAnimationClipsFromObjectHierarchy(g,e);return e}static assignAnimationsFromFile(A,e){if(!A||!A.animations)return;for(let I=0;I<A.animations.length;I++){const o=A.animations[I];if(!(!o.tracks||o.tracks.length<=0))for(const s in o.tracks){const n=o.tracks[s],a=Ze.parseTrackName(n.name);let r=Ze.findNode(A.scene,a.nodeName);if(!r){const Q=n.__objectName??n.name.substring(0,n.name.indexOf("."));if(r=A.scene.getObjectByProperty("uuid",Q),!r)continue}let C=g(r);if(!C){if(!(e!=null&&e.createAnimationComponent)){console.warn("No AnimationComponent found in parent hierarchy of object and no 'createAnimationComponent' callback was provided in options.");continue}C=e.createAnimationComponent(A.scene,o)}C.addClip&&C.addClip(o)}}function g(I){var o;if(!I)return null;const s=(o=I.userData)==null?void 0:o.components;if(s&&s.length>0){for(let n=0;n<s.length;n++)if(s[n].isAnimationComponent===!0)return I}return g(I.parent)}}}const il=[];function KS(i){il.indexOf(i)===-1&&il.push(i)}function TBA(i){const A=il.indexOf(i);A!==-1&&il.splice(A,1)}const gl=[];function kK(i){gl.indexOf(i)===-1&&gl.push(i)}function YBA(i){const A=gl.indexOf(i);A!==-1&&gl.splice(A,1)}function p4(i){globalThis.dispatchEvent(new CustomEvent("needle-xrsession-start",{detail:i}));for(let A=0;A<il.length;A++)il[A](i)}function D4(i){globalThis.dispatchEvent(new CustomEvent("needle-xrsession-end",{detail:i}));for(let A=0;A<gl.length;A++)gl[A](i)}const Kg={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 w4(i){const A=await fetch(i);if(A.ok)return A.json();throw new Error(A.statusText)}async function HBA(i){if(!i)throw new Error("No basePath supplied");return await w4(`${i}/profilesList.json`)}async function OBA(i,A,e=null,g=!0){if(!i)throw new Error("No xrInputSource supplied");if(!A)throw new Error("No basePath supplied");const I=await HBA(A);let o;if(i.profiles.some(a=>{const r=I[a];return r&&(o={profileId:a,profilePath:`${A}/${r.path}`,deprecated:!!r.deprecated}),!!o}),!o){if(!e)throw new Error("No matching profile name found");const a=I[e];if(!a)throw new Error(`No matching profile name found and default profile "${e}" missing.`);o={profileId:e,profilePath:`${A}/${a.path}`,deprecated:!!a.deprecated}}const s=await w4(o.profilePath);let n;if(g){let a;if(i.handedness==="any"?a=s.layouts[Object.keys(s.layouts)[0]]:a=s.layouts[i.handedness],!a)throw new Error(`No matching handedness, ${i.handedness}, in profile ${o.profileId}`);a.assetPath&&(n=o.profilePath.replace("profile.json",a.assetPath))}return{profile:s,assetPath:n}}const PBA={xAxis:0,yAxis:0,button:0,state:Kg.ComponentState.DEFAULT};function jBA(i=0,A=0){let e=i,g=A;if(Math.sqrt(i*i+A*A)>1){const I=Math.atan2(A,i);e=Math.cos(I),g=Math.sin(I)}return{normalizedXAxis:e*.5+.5,normalizedYAxis:g*.5+.5}}let WBA=class{constructor(i){this.componentProperty=i.componentProperty,this.states=i.states,this.valueNodeName=i.valueNodeName,this.valueNodeProperty=i.valueNodeProperty,this.valueNodeProperty===Kg.VisualResponseProperty.TRANSFORM&&(this.minNodeName=i.minNodeName,this.maxNodeName=i.maxNodeName),this.value=0,this.updateFromComponent(PBA)}updateFromComponent({xAxis:i,yAxis:A,button:e,state:g}){const{normalizedXAxis:I,normalizedYAxis:o}=jBA(i,A);switch(this.componentProperty){case Kg.ComponentProperty.X_AXIS:this.value=this.states.includes(g)?I:.5;break;case Kg.ComponentProperty.Y_AXIS:this.value=this.states.includes(g)?o:.5;break;case Kg.ComponentProperty.BUTTON:this.value=this.states.includes(g)?e:0;break;case Kg.ComponentProperty.STATE:this.valueNodeProperty===Kg.VisualResponseProperty.VISIBILITY?this.value=this.states.includes(g):this.value=this.states.includes(g)?1:0;break;default:throw new Error(`Unexpected visualResponse componentProperty ${this.componentProperty}`)}}},ZBA=class{constructor(i,A){if(!i||!A||!A.visualResponses||!A.gamepadIndices||Object.keys(A.gamepadIndices).length===0)throw new Error("Invalid arguments supplied");this.id=i,this.type=A.type,this.rootNodeName=A.rootNodeName,this.touchPointNodeName=A.touchPointNodeName,this.visualResponses={},Object.keys(A.visualResponses).forEach(e=>{const g=new WBA(A.visualResponses[e]);this.visualResponses[e]=g}),this.gamepadIndices=Object.assign({},A.gamepadIndices),this.values={state:Kg.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(i){if(this.values.state=Kg.ComponentState.DEFAULT,this.gamepadIndices.button!==void 0&&i.buttons.length>this.gamepadIndices.button){const A=i.buttons[this.gamepadIndices.button];this.values.button=A.value,this.values.button=this.values.button<0?0:this.values.button,this.values.button=this.values.button>1?1:this.values.button,A.pressed||this.values.button===1?this.values.state=Kg.ComponentState.PRESSED:(A.touched||this.values.button>Kg.ButtonTouchThreshold)&&(this.values.state=Kg.ComponentState.TOUCHED)}this.gamepadIndices.xAxis!==void 0&&i.axes.length>this.gamepadIndices.xAxis&&(this.values.xAxis=i.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===Kg.ComponentState.DEFAULT&&Math.abs(this.values.xAxis)>Kg.AxisTouchThreshold&&(this.values.state=Kg.ComponentState.TOUCHED)),this.gamepadIndices.yAxis!==void 0&&i.axes.length>this.gamepadIndices.yAxis&&(this.values.yAxis=i.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===Kg.ComponentState.DEFAULT&&Math.abs(this.values.yAxis)>Kg.AxisTouchThreshold&&(this.values.state=Kg.ComponentState.TOUCHED)),Object.values(this.visualResponses).forEach(A=>{A.updateFromComponent(this.values)})}},zBA=class{constructor(i,A,e){if(!i)throw new Error("No xrInputSource supplied");if(!A)throw new Error("No profile supplied");this.xrInputSource=i,this.assetUrl=e,this.id=A.profileId,this.layoutDescription=A.layouts[i.handedness],this.components={},Object.keys(this.layoutDescription.components).forEach(g=>{const I=this.layoutDescription.components[g];this.components[g]=new ZBA(g,I)}),this.updateFromGamepad()}get gripSpace(){return this.xrInputSource.gripSpace}get targetRaySpace(){return this.xrInputSource.targetRaySpace}get data(){const i=[];return Object.values(this.components).forEach(A=>{i.push(A.data)}),i}updateFromGamepad(){Object.values(this.components).forEach(i=>{i.updateFromGamepad(this.xrInputSource.gamepad)})}};const Io=new S,y4=new S,m4=new GA,VBA=iA("debuggizmos"),sa=8947848,na=class{constructor(){}static isGizmo(i){return i[GK]!==void 0}static DrawLabel(i,A,e=.05,g=0,I,o,s){var n;if(!na.enabled)return null;I||(I=sa);const a=((n=me.active)==null?void 0:n.rigScale)??1,r=Ki.getTextLabel(g,A,e*a,I,o);return s instanceof wA&&s.add(r),r.position.x=i.x,r.position.y=i.y,r.position.z=i.z,r}static DrawRay(i,A,e=sa,g=0,I=!0){if(!na.enabled)return;const o=Ki.getLine(g),s=o.geometry.getAttribute("position");s.setXYZ(0,i.x,i.y,i.z),Io.set(A.x,A.y,A.z).multiplyScalar(999999999),s.setXYZ(1,i.x+Io.x,i.y+Io.y,i.z+Io.z),s.needsUpdate=!0,o.material.color.set(e),o.material.depthTest=I,o.material.depthWrite=!1}static DrawDirection(i,A,e=sa,g=0,I=!0,o=1){if(!na.enabled)return;const s=Ki.getLine(g),n=s.geometry.getAttribute("position");n.setXYZ(0,i.x,i.y,i.z),A.w!==void 0?(Io.set(0,0,-o),m4.set(A.x,A.y,A.z,A.w),Io.applyQuaternion(m4)):(Io.set(A.x,A.y,A.z),Io.multiplyScalar(o)),n.setXYZ(1,i.x+Io.x,i.y+Io.y,i.z+Io.z),n.needsUpdate=!0,s.material.color.set(e),s.material.depthTest=I,s.material.depthWrite=!1}static DrawLine(i,A,e=sa,g=0,I=!0){if(!na.enabled)return;const o=Ki.getLine(g),s=o.geometry.getAttribute("position");s.setXYZ(0,i.x,i.y,i.z),s.setXYZ(1,A.x,A.y,A.z),s.needsUpdate=!0,o.material.color.set(e),o.material.depthTest=I,o.material.depthWrite=!1,o.material.fog=!1}static DrawWireSphere(i,A,e=sa,g=0,I=!0){if(!na.enabled)return;const o=Ki.getSphere(A,g,!0);TQ(o,i.x,i.y,i.z),o.material.color.set(e),o.material.depthTest=I,o.material.depthWrite=!1,o.material.fog=!1}static DrawSphere(i,A,e=sa,g=0,I=!0){if(!na.enabled)return;const o=Ki.getSphere(A,g,!1);TQ(o,i.x,i.y,i.z),o.material.color.set(e),o.material.depthTest=I,o.material.depthWrite=!1}static DrawWireBox(i,A,e=sa,g=0,I=!0){if(!na.enabled)return;const o=Ki.getBox(g);o.position.set(i.x,i.y,i.z),o.scale.set(A.x,A.y,A.z),o.material.color.set(e),o.material.depthTest=I,o.material.wireframe=!0,o.material.depthWrite=!1,o.material.fog=!1}static DrawWireBox3(i,A=sa,e=0,g=!0){if(!na.enabled)return;const I=Ki.getBox(e);I.position.copy(i.getCenter(Io)),I.scale.copy(i.getSize(Io)),I.material.color.set(A),I.material.depthTest=g,I.material.wireframe=!0,I.material.depthWrite=!1,I.material.fog=!1}static DrawArrow(i,A,e=sa,g=0,I=!0,o=!1){if(!na.enabled)return;const s=Ki.getArrowHead(g);s.position.set(A.x,A.y,A.z),s.quaternion.setFromUnitVectors(this._up.set(0,1,0),Io.set(A.x,A.y,A.z).sub(y4.set(i.x,i.y,i.z)).normalize());const n=Io.set(A.x,A.y,A.z).sub(y4.set(i.x,i.y,i.z)).length()*.1;s.scale.set(n,n,n),s.material.color.set(e),s.material.depthTest=I,s.material.wireframe=o,this.DrawLine(i,A,e,g,I)}static DrawWireMesh(i){const A=Ki.getMesh(i.duration??0);"mesh"in i?(A.geometry=i.mesh.geometry,A.matrix.copy(i.mesh.matrixWorld)):(A.geometry=i.geometry,A.matrix.copy(i.matrix)),A.matrixAutoUpdate=!1,A.matrixWorldAutoUpdate=!1,A.material.color.set(i.color??sa),A.material.depthTest=i.depthTest??!0,A.material.wireframe=!0}};let pe=na;B(pe,"enabled",!0),B(pe,"_up",new S(0,1,0));const XBA=new Ai(1,1,1);function MK(i=null){const A=new fA(i??14540253),e=new EU(XBA);return new kI(e,new Zt({color:A}))}const GK=Symbol("GizmoCache");class Ki{static ensureFont(){let A=Ot.FontLibrary.getFontFamily(this.familyName);if(!A){A=Ot.FontLibrary.addFontFamily(this.familyName);const e=A.addVariant("normal","normal","https://uploads.needle.tools/include/font-msdf.json","https://uploads.needle.tools/include/font.png");e?.addEventListener("ready",()=>{Ot.update()})}}static getTextLabel(A,e,g,I,o){this.ensureFont();let s=this.textLabelCache.pop(),n=1;o&&typeof o=="string"&&o?.length>=8&&o.startsWith("#")?(n=parseInt(o.substring(7),16)/255,o=o.substring(0,7),VBA&&console.log(o,n)):typeof o=="object"&&o.a!==void 0&&(n=o.a);const a={boxSizing:"border-box",fontFamily:this.familyName,width:"auto",fontSize:g,color:I,lineHeight:1,backgroundColor:o??void 0,backgroundOpacity:n,textContent:e,borderRadius:.5*g,padding:.8*g,whiteSpace:"pre"};if(s)s.set(a);else{s=new MN(a);const r=this,C=s;C.setText=function(Q){this.set({textContent:Q}),r.tmuiNeedsUpdate=!0}}return this.tmuiNeedsUpdate=!0,this.registerTimedObject(Ke.Current,s,A,this.textLabelCache),s}static getBox(A){let e=this.boxesCache.pop();if(!e){const g=new Ai(1,1,1);e=new dA(g)}return this.registerTimedObject(Ke.Current,e,A,this.boxesCache),e}static getLine(A){let e=this.linesCache.pop();if(!e){e=new Fi;let g=e.geometry.getAttribute("position");g||(g=new Ie(new Float32Array(2*3),3),e.geometry.setAttribute("position",g))}return e.frustumCulled=!1,this.registerTimedObject(Ke.Current,e,A,this.linesCache),e}static getSphere(A,e,g){let I=this.spheresCache.pop();return I||(I=new dA(new Vs(1,8,8))),I.scale.set(A,A,A),I.material.wireframe=g,this.registerTimedObject(Ke.Current,I,e,this.spheresCache),I}static getArrowHead(A){let e=this.arrowHeadsCache.pop();return e||(e=new dA(new Xi(0,.5,1,8))),this.registerTimedObject(Ke.Current,e,A,this.arrowHeadsCache),e}static getMesh(A){let e=this.mesh.pop();return e||(e=new dA,e.material=new tt),this.registerTimedObject(Ke.Current,e,A,this.mesh),e}static registerTimedObject(A,e,g,I){const o=this.contextBeforeRenderCallbacks.get(A),s=this.contextPostRenderCallbacks.get(A);if(o){if(A.pre_render_callbacks[A.pre_render_callbacks.length-1]!==o){const n=A.pre_render_callbacks.indexOf(o);n>=0&&A.pre_render_callbacks.splice(n,1),A.pre_render_callbacks.push(o)}}else{const n=()=>{this.onBeforeRender(A,this.timedObjectsBuffer)};this.contextBeforeRenderCallbacks.set(A,n),A.pre_render_callbacks.push(n)}if(s){if(A.post_render_callbacks[A.post_render_callbacks.length-1]!==s){const n=A.post_render_callbacks.indexOf(s);n>=0&&A.post_render_callbacks.splice(n,1),A.post_render_callbacks.push(s)}}else{const n=()=>{this.onPostRender(A,this.timedObjectsBuffer,this.timesBuffer)};this.contextPostRenderCallbacks.set(A,n),A.post_render_callbacks.push(n)}e.traverse(n=>{n.layers.disableAll(),n.layers.enable(2)}),e.renderOrder=999999,e[GK]=I,e.isGizmo=!0,this.timedObjectsBuffer.push(e),g<=0&&A.currentFrameEvent>=Xt.OnBeforeRender?this.timesBuffer.push(0):this.timesBuffer.push(Ke.Current.time.realtimeSinceStartup+g),A.scene.add(e)}static onBeforeRender(A,e){this.tmuiNeedsUpdate&&Ot.update();for(let g=0;g<e.length;g++){const I=e[g];if(A.mainCamera&&I instanceof Ot.MeshUIBaseElement){if(lh(I))continue;const o=A.isInVR,s=!1,n=!o;Su(I,A.mainCamera,s,n)}}}static onPostRender(A,e,g){const I=A.time.realtimeSinceStartup;for(let o=e.length-1;o>=0;o--){const s=e[o];I>g[o]&&(e.splice(o,1),g.splice(o,1),s.removeFromParent(),lh(s)!=!0&&s[GK].push(s))}}}B(Ki,"familyName","needle-gizmos"),B(Ki,"linesCache",[]),B(Ki,"spheresCache",[]),B(Ki,"boxesCache",[]),B(Ki,"arrowHeadsCache",[]),B(Ki,"mesh",[]),B(Ki,"textLabelCache",[]),B(Ki,"timedObjectsBuffer",new Array),B(Ki,"timesBuffer",new Array),B(Ki,"contextPostRenderCallbacks",new Map),B(Ki,"contextBeforeRenderCallbacks",new Map),B(Ki,"tmuiNeedsUpdate",!1);const Dg=iA("debuginput");var bS=(i=>(i.Mouse="mouse",i.Touch="touch",i.Controller="controller",i.Hand="hand",i))(bS||{}),hi=(i=>(i.PointerDown="pointerdown",i.PointerUp="pointerup",i.PointerMove="pointermove",i.KeyDown="keydown",i.KeyUp="keyup",i.KeyPressed="keypress",i))(hi||{});class Gr extends PointerEvent{constructor(A,e,g){super(A,g),B(this,"deviceIndex"),B(this,"origin"),B(this,"source"),B(this,"mode"),B(this,"_ray"),B(this,"space"),B(this,"isClick",!1),B(this,"isDoubleClick",!1),B(this,"_used",!1),B(this,"_pointerid"),B(this,"_pointerType"),B(this,"_type"),B(this,"metadata",{}),B(this,"intersections",new Array),B(this,"_immediatePropagationStopped",!1),B(this,"_propagationStopped",!1),this._pointerid=g.pointerId,this._pointerType=g.pointerType,this._type=A,this.deviceIndex=g.deviceIndex,this.origin=g.origin,this.source=e,this.mode=g.mode,this._ray=g.ray,this.space=g.device}get isSpatial(){return this.mode!="screen"}get ray(){return this._ray||(this._ray=new po(this.space.worldPosition.clone(),this.space.worldForward.clone())),this._ray}set ray(A){this._ray=A}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 A;this._immediatePropagationStopped=!0,super.stopImmediatePropagation(),(A=this.source)==null||A.stopImmediatePropagation()}stopPropagation(){var A;this._propagationStopped=!0,super.stopPropagation(),(A=this.source)==null||A.stopPropagation(),Dg&&console.warn("Stop propagation...",this.pointerId,this.pointerType)}}class kp extends KeyboardEvent{constructor(A,e,g){super(A,g),B(this,"source"),this.source=e}stopImmediatePropagation(){var A;super.stopImmediatePropagation(),(A=this.source)==null||A.stopImmediatePropagation()}}class $BA{constructor(A){B(this,"key"),B(this,"keyType"),B(this,"source"),this.key=A.key,this.keyType=A.type,this.source=A}}var aa=(i=>(i[i.Early=-100]="Early",i[i.Default=0]="Default",i[i.Late=100]="Late",i))(aa||{});class S4{constructor(A){B(this,"_eventListeners",{}),B(this,"_doubleClickTimeThreshold",.2),B(this,"_longPressTimeThreshold",1),B(this,"_specialCursorTrigger",0),B(this,"context"),B(this,"_pointerDown",[!1]),B(this,"_pointerUp",[!1]),B(this,"_pointerClick",[!1]),B(this,"_pointerDoubleClick",[!1]),B(this,"_pointerPressed",[!1]),B(this,"_pointerPositions",[new AA]),B(this,"_pointerPositionsLastFrame",[new AA]),B(this,"_pointerPositionsDelta",[new AA]),B(this,"_pointerPositionsRC",[new AA]),B(this,"_pointerPositionDown",[new AA]),B(this,"_pointerDownTime",[]),B(this,"_pointerUpTime",[]),B(this,"_pointerUpTimestamp",[]),B(this,"_pointerIds",[]),B(this,"_pointerTypes",[""]),B(this,"_mouseWheelChanged",[!1]),B(this,"_mouseWheelDeltaY",[0]),B(this,"_pointerEvent",[]),B(this,"_pointerUsed",[]),B(this,"_pointerSpace",[]),B(this,"_pressedStack",new Map),B(this,"_htmlEventSource"),B(this,"onLostFocus",()=>{for(const e in this.keysPressed)this.keysPressed[e].pressed=!1}),B(this,"onEndOfFrame",()=>{for(let e=0;e<this._pointerUp.length;e++)this._pointerUp[e]=!1;for(let e=0;e<this._pointerDown.length;e++)this._pointerDown[e]=!1;for(let e=0;e<this._pointerClick.length;e++)this._pointerClick[e]=!1;for(let e=0;e<this._pointerDoubleClick.length;e++)this._pointerDoubleClick[e]=!1;for(const e of this._pointerPositionsDelta)e.set(0,0);for(let e=0;e<this._mouseWheelChanged.length;e++)this._mouseWheelChanged[e]=!1;for(let e=0;e<this._mouseWheelDeltaY.length;e++)this._mouseWheelDeltaY[e]=0}),B(this,"onContextMenu",e=>{this.canReceiveInput(e)!==!1&&e instanceof PointerEvent&&e.pointerType}),B(this,"keysPressed",{}),B(this,"onKeyDown",e=>{if(Dg&&console.log(`key down ${e.code}, ${this.context.application.hasFocus}`,e),!this.context.application.hasFocus)return;const g=this.keysPressed[e.code];if(g&&g.pressed)return;this.keysPressed[e.code]={pressed:!0,frame:this.context.time.frameCount+1,startFrame:this.context.time.frameCount+1,key:e.key,code:e.code};const I=new kp("keydown",e,e);this.onDispatchEvent(I)}),B(this,"onKeyPressed",e=>{if(!this.context.application.hasFocus)return;const g=this.keysPressed[e.code];if(!g)return;g.pressed=!0,g.frame=this.context.time.frameCount+1;const I=new kp("keypress",e,e);this.onDispatchEvent(I)}),B(this,"onKeyUp",e=>{if(!this.context.application.hasFocus)return;const g=this.keysPressed[e.code];if(!g)return;g.pressed=!1,g.frame=this.context.time.frameCount+1;const I=new kp("keyup",e,e);this.onDispatchEvent(I)}),B(this,"onWheelWindow",e=>{document.pointerLockElement&&this.onMouseWheel(e)}),B(this,"onMouseWheel",e=>{if(this.canReceiveInput(e)===!1)return;this._mouseWheelDeltaY.length<=0&&this._mouseWheelDeltaY.push(0),this._mouseWheelChanged.length<=0&&this._mouseWheelChanged.push(!1),this._mouseWheelChanged[0]=!0;const g=this._mouseWheelDeltaY[0];this._mouseWheelDeltaY[0]=g+e.deltaY}),B(this,"onPointerDown",e=>{if(this.context.isInAR||this.canReceiveInput(e)===!1)return;e.target instanceof HTMLElement&&e.target.setPointerCapture(e.pointerId);const g=this.getPointerId(e);Dg&&Ci(`pointer down #${g}, identifier:${e.pointerId}`);const I=this.getAndUpdateSpatialObjectForScreenPosition(g,e.clientX,e.clientY),o=new Gr("pointerdown",e,{origin:this,mode:"screen",deviceIndex:0,pointerId:g,button:e.button,clientX:e.clientX,clientY:e.clientY,pointerType:e.pointerType,buttonName:this.getButtonName(e),device:I,pressure:e.pressure});this.onDown(o)}),B(this,"onPointerMove",e=>{if(this.context.isInAR)return;let g=e.button;e.pointerType==="mouse"&&(g=this.getFirstPressedButtonForPointer(0)??0);const I=this.getPointerId(e,g);g===-1&&(g=I);const o=this.getAndUpdateSpatialObjectForScreenPosition(I,e.clientX,e.clientY),s=new Gr("pointermove",e,{origin:this,mode:"screen",deviceIndex:0,pointerId:I,button:g,clientX:e.clientX,clientY:e.clientY,pointerType:e.pointerType,buttonName:this.getButtonName(e),device:o,pressure:e.pressure});this.onMove(s)}),B(this,"onPointerCancel",e=>{this.context.isInAR||(Dg&&console.log("Pointer cancel",e),this.onPointerUp(e))}),B(this,"onPointerUp",e=>{if(this.context.isInAR)return;e.target instanceof HTMLElement&&e.target.releasePointerCapture(e.pointerId);const g=this.getPointerId(e),I=new Gr("pointerup",e,{origin:this,mode:"screen",deviceIndex:0,pointerId:g,button:e.button,clientX:e.clientX,clientY:e.clientY,pointerType:e.pointerType,buttonName:this.getButtonName(e),device:this.getAndUpdateSpatialObjectForScreenPosition(g,e.clientX,e.clientY),pressure:e.pressure});this.onUp(I),this._pointerIds[g]=-1,Dg&&console.log("ID="+g,"PointerId="+e.pointerId,"ALL:",[...this._pointerIds])}),B(this,"onTouchStart",e=>{if(this.context.isInAR)for(let g=0;g<e.changedTouches.length;g++){const I=e.changedTouches[g],o=this.getPointerIndex(I.identifier),s=this.getAndUpdateSpatialObjectForScreenPosition(o,I.clientX,I.clientY),n=new Gr("pointerdown",e,{origin:this,mode:"screen",deviceIndex:0,pointerId:o,button:0,clientX:I.clientX,clientY:I.clientY,pointerType:"touch",buttonName:"unknown",device:s,pressure:I.force});this.onDown(n)}}),B(this,"onTouchMove",e=>{if(this.context.isInAR)for(let g=0;g<e.changedTouches.length;g++){const I=e.changedTouches[g],o=this.getPointerIndex(I.identifier),s=this.getAndUpdateSpatialObjectForScreenPosition(o,I.clientX,I.clientY),n=new Gr("pointermove",e,{origin:this,mode:"screen",deviceIndex:0,pointerId:o,button:0,clientX:I.clientX,clientY:I.clientY,pointerType:"touch",buttonName:"unknown",device:s,pressure:I.force});this.onMove(n)}}),B(this,"onTouchEnd",e=>{if(this.context.isInAR)for(let g=0;g<e.changedTouches.length;g++){const I=e.changedTouches[g],o=this.getPointerIndex(I.identifier),s=new Gr("pointerup",e,{origin:this,mode:"screen",deviceIndex:0,pointerId:o,button:0,clientX:I.clientX,clientY:I.clientY,pointerType:"touch",buttonName:"unknown",device:this.getAndUpdateSpatialObjectForScreenPosition(o,I.clientX,I.clientY),pressure:I.force});this.onUp(s),this._pointerIds[o]=-1}}),B(this,"tempNearPlaneVector",new S),B(this,"tempFarPlaneVector",new S),B(this,"tempLookMatrix",new DA),this.context=A,this.context.post_render_callbacks.push(this.onEndOfFrame)}addEventListener(A,e,g){if(this._eventListeners[A]||(this._eventListeners[A]=[]),!e||typeof e!="function"){console.error("Invalid call to addEventListener: callback is required and must be a function!");return}g?g={...g}:g={};let I=0;g?.queue!=null&&(I=g.queue);const o=this._eventListeners[A],s=o.find(n=>n.priority===I);s?s.listeners.push({callback:e,options:g}):(o.push({priority:I,listeners:[{callback:e,options:g}]}),o.sort((n,a)=>n.priority-a.priority))}removeEventListener(A,e,g){if(!this._eventListeners[A]||!e)return;const I=this._eventListeners[A];if(g?.queue!=null){const o=I.find(n=>n.priority===g.queue);if(!o)return;const s=o.listeners.findIndex(n=>n.callback===e);s>=0&&o.listeners.splice(s,1)}else for(const o of I){const s=o.listeners.findIndex(n=>n.callback===e);s>=0&&o.listeners.splice(s,1)}}dispatchEvent(A){var e,g,I,o;let s=!1;if(A instanceof kp){const n=this._eventListeners[A.type];if(n)for(const a of n)for(let r=0;r<a.listeners.length;r++){const C=a.listeners[r];if((g=(e=C.options)==null?void 0:e.signal)!=null&&g.aborted){a.listeners.splice(r,1),r--;continue}C.options.once&&(a.listeners.splice(r,1),r--),C.callback(A)}}if(A instanceof Gr){const n=this._eventListeners[A.type];if(n)for(const a of n){if(s)break;for(let r=0;r<a.listeners.length;r++){const C=a.listeners[r];if((o=(I=C.options)==null?void 0:I.signal)!=null&&o.aborted){a.listeners.splice(r,1),r--;continue}if(A.immediatePropagationStopped){s=!0,Dg&&console.log("immediatePropagationStopped",A.type);break}else A.propagationStopped&&(s=!0,Dg&&console.log("propagationStopped",A.type));C.options.once&&(a.listeners.splice(r,1),r--),C.callback(A)}}}}get mousePosition(){return this._pointerPositions[0]}get mousePositionRC(){return this._pointerPositionsRC[0]}get mouseDown(){return this._pointerDown[0]}get mouseUp(){return this._pointerUp[0]}get mouseClick(){return this._pointerClick[0]}get mouseDoubleClick(){return this._pointerDoubleClick[0]}get mousePressed(){return this._pointerPressed[0]}get mouseWheelChanged(){return this.getMouseWheelChanged(0)}setCursorPointer(){this._specialCursorTrigger+=1,this.context.domElement.style.cursor="pointer"}setCursorNormal(){this._specialCursorTrigger-=1,this._specialCursorTrigger=Math.max(0,this._specialCursorTrigger),this._specialCursorTrigger===0&&(this.context.domElement.style.cursor="default")}setPointerUsed(A,e=!0){if(A>=this._pointerUsed.length){if(A>=this._pointerIds.length)return;for(;this._pointerUsed.length<=A;)this._pointerUsed.push(!1)}this._pointerUsed[A]=e}getPointerUsed(A){return A>=this._pointerUsed.length?!1:this._pointerUsed[A]}getPointerPressedCount(){let A=0;for(let e=0;e<this._pointerPressed.length;e++)this._pointerPressed[e]&&A++;return A}getPointerPosition(A){return A>=this._pointerPositions.length?null:this._pointerPositions[A]}getPointerPositionLastFrame(A){return A>=this._pointerPositionsLastFrame.length?null:this._pointerPositionsLastFrame[A]}getPointerPositionDelta(A){return A>=this._pointerPositionsDelta.length?null:this._pointerPositionsDelta[A]}getPointerPositionRC(A){return A>=this._pointerPositionsRC.length?null:this._pointerPositionsRC[A]}getPointerDown(A){return A>=this._pointerDown.length?!1:this._pointerDown[A]}getPointerUp(A){return A>=this._pointerUp.length?!1:this._pointerUp[A]}getPointerPressed(A){return A>=this._pointerPressed.length?!1:this._pointerPressed[A]}getPointerClicked(A){return A>=this._pointerClick.length?!1:this._pointerClick[A]}getPointerDoubleClicked(A){return A>=this._pointerDoubleClick.length?!1:this._pointerDoubleClick[A]}getPointerDownTime(A){return A>=this._pointerDownTime.length?-1:this._pointerDownTime[A]}getPointerUpTime(A){return A>=this._pointerUpTime.length?-1:this._pointerUpTime[A]}getPointerLongPress(A){return A>=this._pointerDownTime.length?!1:this.getPointerPressed(A)&&this.context.time.time-this._pointerDownTime[A]>this._longPressTimeThreshold}getIsMouse(A){return A<0||A>=this._pointerTypes.length?!1:this._pointerTypes[A]==="mouse"}getIsTouch(A){return A<0||A>=this._pointerTypes.length?!1:this._pointerTypes[A]==="touch"}getTouchesPressedCount(){let A=0;for(let e=0;e<this._pointerPressed.length;e++)this._pointerPressed[e]&&this.getIsTouch(e)&&A++;return A}getMouseWheelChanged(A=0){return A>=this._mouseWheelChanged.length?!1:this._mouseWheelChanged[A]}getMouseWheelDeltaY(A=0){return A>=this._mouseWheelDeltaY.length?0:this._mouseWheelDeltaY[A]}getPointerEvent(A){if(!(A>=this._pointerEvent.length))return this._pointerEvent[A]??void 0}*foreachPointerId(A){for(let e=0;e<this._pointerTypes.length;e++)if(this._pointerIsActive(e)){if(A!==void 0){const g=this._pointerTypes[e];if(Array.isArray(A)){let I=!1;for(const o of A)if(g===o){I=!0;break}if(!I)continue}else if(A!==g)continue}yield e}}*foreachTouchId(){for(let A=0;A<this._pointerTypes.length;A++)this._pointerTypes[A]==="touch"&&this._pointerIsActive[A]&&(yield A)}_pointerIsActive(A){return A<0?!1:this._pointerPressed[A]||this._pointerDown[A]||this._pointerUp[A]}onDownButton(A,e){let g=this._pressedStack.get(A);g||(g=[],this._pressedStack.set(A,g)),g.push(e)}onReleaseButton(A,e){const g=this._pressedStack.get(A);if(!g)return;const I=g.indexOf(e);I>=0&&g.splice(I,1)}getFirstPressedButtonForPointer(A){const e=this._pressedStack.get(A);if(e)return e[0]}getLatestPressedButtonForPointer(A){const e=this._pressedStack.get(A);if(e)return e[e.length-1]}getKeyDown(){for(const A in this.keysPressed){const e=this.keysPressed[A];if(e.startFrame===this.context.time.frameCount)return e.key}return null}getKeyPressed(){for(const A in this.keysPressed){const e=this.keysPressed[A];if(e.pressed)return e.key}return null}isKeyDown(A){var e;if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const g=this.getCodeForCommonKeyName(A);if(g!==null){for(const I of g)if(this.isKeyDown(I))return!0;return!1}return((e=this.keysPressed[A])==null?void 0:e.startFrame)===this.context.time.frameCount&&this.keysPressed[A].pressed}isKeyUp(A){var e;if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const g=this.getCodeForCommonKeyName(A);if(g!==null){for(const I of g)if(this.isKeyUp(I))return!0;return!1}return((e=this.keysPressed[A])==null?void 0:e.frame)===this.context.time.frameCount&&!this.keysPressed[A].pressed}isKeyPressed(A){var e;if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const g=this.getCodeForCommonKeyName(A);if(g!==null){for(const I of g)if(this.isKeyPressed(I))return!0;return!1}return(e=this.keysPressed[A])==null?void 0:e.pressed}getCodeForCommonKeyName(A){if(A.length===1){if(A>="0"&&A<="9")return["Digit"+A];if(A>="a"&&A<="z")return["Key"+A.toUpperCase()];if(A==" ")return["Space"]}switch(A){case"shift":case"Shift":return["ShiftLeft","ShiftRight"];case"control":case"Control":return["ControlLeft","ControlRight"];case"alt":case"Alt":return["AltLeft","AltRight"]}return null}createInputEvent(A){switch(A.type){case"pointerdown":Dg&&Ci("Create Pointer down"),this.onDownButton(A.deviceIndex,A.button),this.onDown(A);break;case"pointermove":Dg&&Ci("Create Pointer move"),this.onMove(A);break;case"pointerup":Dg&&Ci("Create Pointer up"),this.onUp(A),this.onReleaseButton(A.deviceIndex,A.button);break}}convertScreenspaceToRaycastSpace(A){return A.x=(A.x-this.context.domX)/this.context.domWidth*2-1,A.y=-((A.y-this.context.domY)/this.context.domHeight)*2+1,A}bindEvents(){this.unbindEvents(),this._htmlEventSource=this.context.renderer.domElement,window.addEventListener("contextmenu",this.onContextMenu),this._htmlEventSource.addEventListener("pointerdown",this.onPointerDown,{passive:!0}),window.addEventListener("pointermove",this.onPointerMove,{passive:!0,capture:!0}),window.addEventListener("pointerup",this.onPointerUp,{passive:!0}),window.addEventListener("pointercancel",this.onPointerCancel,{passive:!0}),window.addEventListener("touchstart",this.onTouchStart,{passive:!0}),window.addEventListener("touchmove",this.onTouchMove,{passive:!0}),window.addEventListener("touchend",this.onTouchEnd,{passive:!0}),this._htmlEventSource.addEventListener("wheel",this.onMouseWheel,{passive:!0}),window.addEventListener("wheel",this.onWheelWindow,{passive:!0}),window.addEventListener("keydown",this.onKeyDown,!1),window.addEventListener("keypress",this.onKeyPressed,!1),window.addEventListener("keyup",this.onKeyUp,!1),window.addEventListener("blur",this.onLostFocus)}unbindEvents(){var A,e;window.removeEventListener("contextmenu",this.onContextMenu),(A=this._htmlEventSource)==null||A.removeEventListener("pointerdown",this.onPointerDown),window.removeEventListener("pointermove",this.onPointerMove),window.removeEventListener("pointerup",this.onPointerUp),window.removeEventListener("pointercancel",this.onPointerCancel),(e=this._htmlEventSource)==null||e.removeEventListener("wheel",this.onMouseWheel,!1),window.removeEventListener("wheel",this.onWheelWindow,!1),window.removeEventListener("keydown",this.onKeyDown,!1),window.removeEventListener("keypress",this.onKeyPressed,!1),window.removeEventListener("keyup",this.onKeyUp,!1),window.removeEventListener("blur",this.onLostFocus)}dispose(){const A=this.context.post_render_callbacks.indexOf(this.onEndOfFrame);A>=0&&this.context.post_render_callbacks.splice(A,1),this.unbindEvents()}canReceiveInput(A){var e;return A.target===((e=this.context.renderer)==null?void 0:e.domElement)||A.target===this.context.domElement||this.context.isInAR||this.context.isInAR&&A.target===document.body&&JQ()?!0:(Dg&&console.warn("CanReceiveInput:False for",A.target),!1)}getPointerId(A,e){return A.pointerType==="mouse"?0+(e??A.button):this.getPointerIndex(A.pointerId)}getButtonName(A){const e=A.button;if(A.pointerType==="mouse")switch(e){case 0:return"left";case 1:return"middle";case 2:return"right"}return"unknown"}getAndUpdateSpatialObjectForScreenPosition(A,e,g){let I=this._pointerSpace[A];I||(I=new wA,this._pointerSpace[A]=I),this._pointerSpace[A]=I;const o=this.context.mainCamera;if(o){const s=this.tempNearPlaneVector.set(e,g,-1);this.convertScreenspaceToRaycastSpace(s);const n=this.tempFarPlaneVector.set(s.x,s.y,1);s.unproject(o),n.unproject(o);const a=o.worldUp||lt(0,1,0).applyQuaternion(Nt(o));this.tempLookMatrix.lookAt(n,s,a),I.position.set(s.x,s.y,s.z),I.quaternion.setFromRotationMatrix(this.tempLookMatrix)}return I}isInRect(A){if(this.context.isInXR)return!0;const e=this.context.domElement.getBoundingClientRect(),g=A.clientX,I=A.clientY,o=g>=e.x&&g<=e.right&&I>=e.y&&I<=e.bottom;return Dg&&!o&&console.log("Not in rect",e,g,I),o}onDown(A){const e=A.pointerId;if(this.getPointerPressed(e)&&console.warn(`pointerId is already pressed: ${e}`,Dg?A:""),Dg&&console.log(A.pointerType,"DOWN",e),!!this.isInRect(A)){for(this.setPointerState(e,this._pointerPressed,!0),this.setPointerState(e,this._pointerDown,!0),this.setPointerStateT(e,this._pointerEvent,A.source);e>=this._pointerTypes.length;)this._pointerTypes.push(A.pointerType);for(this._pointerTypes[e]=A.pointerType;e>=this._pointerPositionDown.length;)this._pointerPositionDown.push(new AA);for(this._pointerPositionDown[e].set(A.clientX,A.clientY);e>=this._pointerPositions.length;)this._pointerPositions.push(new AA);this._pointerPositions[e].set(A.clientX,A.clientY),e>=this._pointerDownTime.length&&this._pointerDownTime.push(0),this._pointerDownTime[e]=this.context.time.time,this.updatePointerPosition(A),this.onDispatchEvent(A)}}onMove(A){const e=A.pointerId,g=this.getPointerPressed(e);g===!1&&!this.isInRect(A)||A.pointerType==="touch"&&!g||(this.updatePointerPosition(A),this.setPointerStateT(e,this._pointerEvent,A.source),this.onDispatchEvent(A))}onUp(A){const e=A.pointerId;if(!this.getPointerPressed(e)){Dg&&console.log(A.pointerType,"UP",e,"was not down");return}for(Dg&&console.log(A.pointerType,"UP",e),this.setPointerState(e,this._pointerPressed,!1),this.setPointerStateT(e,this._pointerEvent,A.source),this.setPointerState(e,this._pointerUp,!0);e>=this._pointerUsed.length;)this._pointerUsed.push(!1);if(this.setPointerState(e,this._pointerUsed,!1),this.updatePointerPosition(A),!this._pointerPositionDown[e]){Dg&&Lt("Received pointer up event without matching down event for button: "+e),console.warn("Received pointer up event without matching down event for button: "+e);return}const g=A.clientX-this._pointerPositionDown[e].x,I=A.clientY-this._pointerPositionDown[e].y;if(e>=this._pointerUpTime.length&&this._pointerUpTime.push(-99),Math.abs(g)<5&&Math.abs(I)<5){Dg&&console.log("CLICK",e),this.setPointerState(e,this._pointerClick,!0),A.isClick=!0;const o=this._pointerUpTime[e],s=this.context.time.time-o;s<this._doubleClickTimeThreshold&&s>0&&(this.setPointerState(e,this._pointerDoubleClick,!0),A.isDoubleClick=!0)}this._pointerUpTime[e]=this.context.time.time,this.onDispatchEvent(A)}updatePointerPosition(A){const e=A.pointerId;for(;e>=this._pointerPositions.length;)this._pointerPositions.push(new AA);for(;e>=this._pointerPositionsLastFrame.length;)this._pointerPositionsLastFrame.push(new AA);for(;e>=this._pointerPositionsDelta.length;)this._pointerPositionsDelta.push(new AA);const g=this._pointerPositionsLastFrame[e];g.copy(this._pointerPositions[e]);const I=this._pointerPositionsDelta[e];let o=A.clientX-g.x,s=A.clientY-g.y;if(A.source instanceof MouseEvent||A.source instanceof TouchEvent){const C=A.source;o===0&&C.movementX!==0&&(o=C.movementX||0),s===0&&C.movementY!==0&&(s=C.movementY||0)}I.x+=o,I.y+=s,this._pointerPositions[e].x=A.clientX,this._pointerPositions[e].y=A.clientY;const n=A.clientX,a=A.clientY;for(;e>=this._pointerPositionsRC.length;)this._pointerPositionsRC.push(new AA);const r=this._pointerPositionsRC[e];r.set(n,a),this.convertScreenspaceToRaycastSpace(r)}getPointerIndex(A){let e=-1;for(let g=0;g<this._pointerIds.length;g++){if(this._pointerIds[g]===A)return g;e===-1&&this._pointerIds[g]===-1&&(e=g)}return e!==-1?(this._pointerIds[e]=A,e):(Dg&&console.log("PUSH pointerId:",A),this._pointerIds.push(A),this._pointerIds.length-1)}setPointerState(A,e,g){e[A]=g}setPointerStateT(A,e,g){return e[A]=g,g}onDispatchEvent(A){const e=Ke.Current;try{Ke.Current=this.context,this.dispatchEvent(A)}finally{Ke.Current=e}}}const JS=new DA().makeRotationY(Math.PI),vs=new GA().setFromAxisAngle(new S(0,1,0),Math.PI),AQA=iA("debugwebxr");class eQA{constructor(){if(B(this,"priority",-1e5),B(this,"gameObject"),this.gameObject=new wA,this.gameObject.name="Implicit XR Rig",AQA){const A=MK(16733661);A.position.y+=.5,this.gameObject.add(A)}}isXRRig(){return!0}get isActive(){return this.gameObject.visible}}const iB=iA("debugwebxr"),xS=iA("debugcustomgesture"),tQA="https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles",iQA="generic-trigger";class RK{constructor(A,e,g){B(this,"xr"),B(this,"inputSource"),B(this,"index",0),B(this,"emitEvents",!0),B(this,"_connected",!0),B(this,"_isTracking",!1),B(this,"_hitTestSource"),B(this,"_hasSelectEvent",!1),B(this,"_handJointPoses",new Map),B(this,"_gripPosition",new S),B(this,"_gripQuaternion",new GA),B(this,"_linearVelocity",new S),B(this,"_rayPosition",new S),B(this,"_rayQuaternion",new GA),B(this,"_gripWorldPosition",new S),B(this,"_gripWorldQuaternion",new GA),B(this,"_rayWorldPosition",new S),B(this,"_rayWorldQuaternion",new GA),B(this,"_ray"),B(this,"_object"),B(this,"model",null),B(this,"_debugAxesHelper",new _o(.2)),B(this,"onPointerHits",n=>{}),B(this,"_needleGamepadButtons",{}),B(this,"_buttonMap",new Map),B(this,"_motioncontroller"),B(this,"_layout"),B(this,"getMotionController"),B(this,"_selectButtonIndex"),B(this,"_squeezeButtonIndex"),B(this,"onSelectStart",n=>{var a,r,C,Q;if(this.inputSource!==n.inputSource)return;this.onUpdateFrame(n.frame),this._hasSelectEvent=!0;const h=(a=this._layout)==null?void 0:a.selectComponentId,E=(Q=(C=(r=this._layout)==null?void 0:r.components[h])==null?void 0:C.gamepadIndices)==null?void 0:Q.button;E!==void 0&&(this._selectButtonIndex=E),!xS&&(iB&&pe.DrawDirection(this.rayWorldPosition,lt(0,.01,1).applyQuaternion(this.rayWorldQuaternion),16711680,10),this.emitPointerEvent(hi.PointerDown,this._selectButtonIndex||0,"xr-standard-trigger",!0,n))}),B(this,"onSelectEnd",n=>{xS||this.inputSource===n.inputSource&&this.emitPointerEvent(hi.PointerUp,this._selectButtonIndex||0,"xr-standard-trigger",!0,n)}),B(this,"onSequeezeStart",n=>{var a,r,C;this.inputSource===n.inputSource&&(this._squeezeButtonIndex=(C=(r=(a=this._layout)==null?void 0:a.components["xr-standard-squeeze"])==null?void 0:r.gamepadIndices)==null?void 0:C.button,this._squeezeButtonIndex!==void 0&&(iB&&pe.DrawDirection(this.rayWorldPosition,lt(0,.01,1).applyQuaternion(this.rayWorldQuaternion),255,10),this.emitPointerEvent(hi.PointerDown,this._squeezeButtonIndex||0,"xr-standard-squeeze",!0,n)))}),B(this,"onSequeezeEnd",n=>{this.inputSource===n.inputSource&&this._squeezeButtonIndex!==void 0&&this.emitPointerEvent(hi.PointerUp,this._squeezeButtonIndex||0,"xr-standard-squeeze",!0,n)}),B(this,"states",{}),B(this,"_didMoveLastFrame",!1),B(this,"_lastPointerMovePosition",new S),B(this,"_lastPointerMoveQuaternion",new GA),B(this,"pointerInit");var I,o,s;this.xr=A,this.inputSource=e,this.index=g,this._object=new wA,iB&&this._object.add(this._debugAxesHelper),this.xr.context.scene.add(this._object),this._ray=new po,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"&&((s=(o=(I=this.xr.session).requestHitTestSourceForTransientInput)==null?void 0:o.call(I,{profile:this.inputSource.profiles[0],offsetRay:new XRRay}))==null||s.then(n=>this._hitTestSource=n))}get context(){return this.xr.context}get connected(){return this._connected}get isTracking(){return this._isTracking}get gamepad(){return this.inputSource.gamepad}get isHand(){return this.inputSource.hand!=null}get hand(){return this.inputSource.hand}get handObject(){return this.context.renderer.xr.getHand(this.index)}get profiles(){return this.inputSource.profiles}get layout(){return this._layout}get targetRayMode(){return this.inputSource.targetRayMode}get targetRaySpace(){return this.inputSource.targetRaySpace}get gripSpace(){return this.inputSource.gripSpace}get side(){return this.inputSource.handedness}get isRight(){return this.side==="right"}get isLeft(){return this.side==="left"}get hitTestSource(){return this._hitTestSource}get hasSelectEvent(){return this._hasSelectEvent}getHitTest(){return this.xr.getHitTest(this)}getHandJointPose(A){var e,g;if(!this.hand||!((e=this.xr.frame)!=null&&e.getJointPose)||!this.xr.referenceSpace)return null;let I=(g=this._handJointPoses)==null?void 0:g.get(A);return I||(I=this.xr.frame.getJointPose(A,this.xr.referenceSpace),I&&this._handJointPoses.set(A,I),I)}get gripPosition(){return lt(this._gripPosition).applyMatrix4(JS)}get gripQuaternion(){return _Q(this._gripQuaternion).premultiply(vs)}get gripLinearVelocity(){return lt(this._linearVelocity).applyQuaternion(vs)}get rayPosition(){return lt(this._rayPosition).applyMatrix4(JS)}get rayQuaternion(){return _Q(this._rayQuaternion).premultiply(vs)}get gripWorldPosition(){return lt(this._gripWorldPosition)}get gripWorldQuaternion(){return _Q(this._gripWorldQuaternion)}get rayWorldPosition(){return lt(this._rayWorldPosition)}updateRayWorldPosition(){var A;const e=(A=this.xr.context.mainCamera)==null?void 0:A.parent;this._rayWorldPosition.copy(this._rayPosition),e&&this._rayWorldPosition.applyMatrix4(e.matrixWorld)}get rayWorldQuaternion(){return _Q(this._rayWorldQuaternion)}updateRayWorldQuaternion(){var A;const e=(A=this.xr.context.mainCamera)==null?void 0:A.parent,g=e?Nt(e):void 0;this._rayWorldQuaternion.copy(this._rayQuaternion).multiply(vs),g&&this._rayWorldQuaternion.premultiply(g)}get ray(){return this._ray.origin.copy(this.rayWorldPosition),this._ray.direction.copy(lt(0,0,1).applyQuaternion(this.rayWorldQuaternion)),this._ray}get object(){return this._object}async getModelUrl(){var A;return(A=this.getMotionController)==null?void 0:A.then(e=>e?.assetUrl||null)}onUpdate(A){this.onUpdateFrame(A),this.updateInputEvents(),this.onUpdateMove()}onRenderDebug(){var A;pe.DrawWireSphere(this.rayWorldPosition,.02),pe.DrawDirection(this.rayWorldPosition,lt(0,0,10).applyQuaternion(this.rayWorldQuaternion));const e=this.gripWorldPosition.sub(this.object.worldForward.multiplyScalar(.1)),g=this.inputSource.profiles.join(`
5152
5152
  `);let I=`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&&(I+=`
5154
5154
  Pinch: ${(A=this.getGesture("pinch"))==null?void 0:A.value.toFixed(3)}`),I+=`
@@ -5232,7 +5232,7 @@ a=extmap-allow-mixed`)!==-1){const I=g.sdp.split(`
5232
5232
  isUnifiedPlanSupported:`).concat(this.isUnifiedPlanSupported())},i}()),M3={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"},wQA=function(){function i(){this.CLOUD_HOST="0.peerjs.com",this.CLOUD_PORT=443,this.chunkedBrowsers={Chrome:1,chrome:1},this.chunkedMTU=16300,this.defaultConfig=M3,this.browser=Np.getBrowser(),this.browserVersion=Np.getVersion(),this.supports=function(){var A={browser:Np.isBrowserSupported(),webRTC:Np.isWebRTCSupported(),audioVideo:!1,data:!1,binaryBlob:!1,reliable:!1};if(!A.webRTC)return A;var e;try{e=new RTCPeerConnection(M3),A.audioVideo=!0;var g=void 0;try{g=e.createDataChannel("_PEERJSTEST",{ordered:!0}),A.data=!0,A.reliable=!!g.ordered;try{g.binaryType="blob",A.binaryBlob=!Np.isIOS}catch{}}catch{}finally{g&&g.close()}}catch{}finally{e&&e.close()}return A}(),this.pack=K4.pack,this.unpack=K4.unpack,this._dataCount=1}return i.prototype.noop=function(){},i.prototype.validateId=function(A){return!A||/^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/.test(A)},i.prototype.chunk=function(A){for(var e=[],g=A.size,I=Math.ceil(g/Gt.chunkedMTU),o=0,s=0;s<g;){var n=Math.min(g,s+Gt.chunkedMTU),a=A.slice(s,n),r={__peerData:this._dataCount,n:o,data:a,total:I};e.push(r),s=n,o++}return this._dataCount++,e},i.prototype.blobToArrayBuffer=function(A,e){var g=new FileReader;return g.onload=function(I){I.target&&e(I.target.result)},g.readAsArrayBuffer(A),g},i.prototype.binaryStringToArrayBuffer=function(A){for(var e=new Uint8Array(A.length),g=0;g<A.length;g++)e[g]=A.charCodeAt(g)&255;return e.buffer},i.prototype.randomToken=function(){return Math.random().toString(36).slice(2)},i.prototype.isSecure=function(){return location.protocol==="https:"},i}(),Gt=new wQA,G3={};Ba(G3,"Peer",()=>VK,i=>VK=i);var Fp={},yQA=Object.prototype.hasOwnProperty,oo="~";function vp(){}Object.create&&(vp.prototype=Object.create(null),new vp().__proto__||(oo=!1));function mQA(i,A,e){this.fn=i,this.context=A,this.once=e||!1}function R3(i,A,e,g,I){if(typeof e!="function")throw new TypeError("The listener must be a function");var o=new mQA(e,g||i,I),s=oo?oo+A:A;return i._events[s]?i._events[s].fn?i._events[s]=[i._events[s],o]:i._events[s].push(o):(i._events[s]=o,i._eventsCount++),i}function PS(i,A){--i._eventsCount===0?i._events=new vp:delete i._events[A]}function bI(){this._events=new vp,this._eventsCount=0}bI.prototype.eventNames=function(){var i=[],A,e;if(this._eventsCount===0)return i;for(e in A=this._events)yQA.call(A,e)&&i.push(oo?e.slice(1):e);return Object.getOwnPropertySymbols?i.concat(Object.getOwnPropertySymbols(A)):i},bI.prototype.listeners=function(i){var A=oo?oo+i:i,e=this._events[A];if(!e)return[];if(e.fn)return[e.fn];for(var g=0,I=e.length,o=new Array(I);g<I;g++)o[g]=e[g].fn;return o},bI.prototype.listenerCount=function(i){var A=oo?oo+i:i,e=this._events[A];return e?e.fn?1:e.length:0},bI.prototype.emit=function(i,A,e,g,I,o){var s=oo?oo+i:i;if(!this._events[s])return!1;var n=this._events[s],a=arguments.length,r,C;if(n.fn){switch(n.once&&this.removeListener(i,n.fn,void 0,!0),a){case 1:return n.fn.call(n.context),!0;case 2:return n.fn.call(n.context,A),!0;case 3:return n.fn.call(n.context,A,e),!0;case 4:return n.fn.call(n.context,A,e,g),!0;case 5:return n.fn.call(n.context,A,e,g,I),!0;case 6:return n.fn.call(n.context,A,e,g,I,o),!0}for(C=1,r=new Array(a-1);C<a;C++)r[C-1]=arguments[C];n.fn.apply(n.context,r)}else{var Q=n.length,h;for(C=0;C<Q;C++)switch(n[C].once&&this.removeListener(i,n[C].fn,void 0,!0),a){case 1:n[C].fn.call(n[C].context);break;case 2:n[C].fn.call(n[C].context,A);break;case 3:n[C].fn.call(n[C].context,A,e);break;case 4:n[C].fn.call(n[C].context,A,e,g);break;default:if(!r)for(h=1,r=new Array(a-1);h<a;h++)r[h-1]=arguments[h];n[C].fn.apply(n[C].context,r)}}return!0},bI.prototype.on=function(i,A,e){return R3(this,i,A,e,!1)},bI.prototype.once=function(i,A,e){return R3(this,i,A,e,!0)},bI.prototype.removeListener=function(i,A,e,g){var I=oo?oo+i:i;if(!this._events[I])return this;if(!A)return PS(this,I),this;var o=this._events[I];if(o.fn)o.fn===A&&(!g||o.once)&&(!e||o.context===e)&&PS(this,I);else{for(var s=0,n=[],a=o.length;s<a;s++)(o[s].fn!==A||g&&!o[s].once||e&&o[s].context!==e)&&n.push(o[s]);n.length?this._events[I]=n.length===1?n[0]:n:PS(this,I)}return this},bI.prototype.removeAllListeners=function(i){var A;return i?(A=oo?oo+i:i,this._events[A]&&PS(this,A)):(this._events=new vp,this._eventsCount=0),this},bI.prototype.off=bI.prototype.removeListener,bI.prototype.addListener=bI.prototype.on,bI.prefixed=oo,bI.EventEmitter=bI,Fp=bI;var Qe={};Ba(Qe,"LogLevel",()=>Mo,i=>Mo=i),Ba(Qe,"default",()=>U3,i=>U3=i);var hh=function(i,A){var e=typeof Symbol=="function"&&i[Symbol.iterator];if(!e)return i;var g=e.call(i),I,o=[],s;try{for(;(A===void 0||A-- >0)&&!(I=g.next()).done;)o.push(I.value)}catch(n){s={error:n}}finally{try{I&&!I.done&&(e=g.return)&&e.call(g)}finally{if(s)throw s.error}}return o},Eh=function(i,A,e){if(e||arguments.length===2)for(var g=0,I=A.length,o;g<I;g++)(o||!(g in A))&&(o||(o=Array.prototype.slice.call(A,0,g)),o[g]=A[g]);return i.concat(o||Array.prototype.slice.call(A))},SQA="PeerJS: ",Mo;(function(i){i[i.Disabled=0]="Disabled",i[i.Errors=1]="Errors",i[i.Warnings=2]="Warnings",i[i.All=3]="All"})(Mo||(Mo={}));var fQA=function(){function i(){this._logLevel=Mo.Disabled}return Object.defineProperty(i.prototype,"logLevel",{get:function(){return this._logLevel},set:function(A){this._logLevel=A},enumerable:!1,configurable:!0}),i.prototype.log=function(){for(var A=[],e=0;e<arguments.length;e++)A[e]=arguments[e];this._logLevel>=Mo.All&&this._print.apply(this,Eh([Mo.All],hh(A),!1))},i.prototype.warn=function(){for(var A=[],e=0;e<arguments.length;e++)A[e]=arguments[e];this._logLevel>=Mo.Warnings&&this._print.apply(this,Eh([Mo.Warnings],hh(A),!1))},i.prototype.error=function(){for(var A=[],e=0;e<arguments.length;e++)A[e]=arguments[e];this._logLevel>=Mo.Errors&&this._print.apply(this,Eh([Mo.Errors],hh(A),!1))},i.prototype.setLogFunction=function(A){this._print=A},i.prototype._print=function(A){for(var e=[],g=1;g<arguments.length;g++)e[g-1]=arguments[g];var I=Eh([SQA],hh(e),!1);for(var o in I)I[o]instanceof Error&&(I[o]="("+I[o].name+") "+I[o].message);A>=Mo.All?console.log.apply(console,Eh([],hh(I),!1)):A>=Mo.Warnings?console.warn.apply(console,Eh(["WARNING"],hh(I),!1)):A>=Mo.Errors&&console.error.apply(console,Eh(["ERROR"],hh(I),!1))},i}(),U3=new fQA,N3={};Ba(N3,"Socket",()=>F3,i=>F3=i);var Sn;(function(i){i.Data="data",i.Media="media"})(Sn||(Sn={}));var Zi;(function(i){i.BrowserIncompatible="browser-incompatible",i.Disconnected="disconnected",i.InvalidID="invalid-id",i.InvalidKey="invalid-key",i.Network="network",i.PeerUnavailable="peer-unavailable",i.SslUnavailable="ssl-unavailable",i.ServerError="server-error",i.SocketError="socket-error",i.SocketClosed="socket-closed",i.UnavailableID="unavailable-id",i.WebRTC="webrtc"})(Zi||(Zi={}));var Ur;(function(i){i.Binary="binary",i.BinaryUTF8="binary-utf8",i.JSON="json"})(Ur||(Ur={}));var Nr;(function(i){i.Message="message",i.Disconnected="disconnected",i.Error="error",i.Close="close"})(Nr||(Nr={}));var iI;(function(i){i.Heartbeat="HEARTBEAT",i.Candidate="CANDIDATE",i.Offer="OFFER",i.Answer="ANSWER",i.Open="OPEN",i.Error="ERROR",i.IdTaken="ID-TAKEN",i.InvalidKey="INVALID-KEY",i.Leave="LEAVE",i.Expire="EXPIRE"})(iI||(iI={}));var PK={};PK=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 kQA=function(){var i=function(A,e){return i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(g,I){g.__proto__=I}||function(g,I){for(var o in I)Object.prototype.hasOwnProperty.call(I,o)&&(g[o]=I[o])},i(A,e)};return function(A,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");i(A,e);function g(){this.constructor=A}A.prototype=e===null?Object.create(e):(g.prototype=e.prototype,new g)}}(),MQA=function(i,A){var e=typeof Symbol=="function"&&i[Symbol.iterator];if(!e)return i;var g=e.call(i),I,o=[],s;try{for(;(A===void 0||A-- >0)&&!(I=g.next()).done;)o.push(I.value)}catch(n){s={error:n}}finally{try{I&&!I.done&&(e=g.return)&&e.call(g)}finally{if(s)throw s.error}}return o},GQA=function(i,A,e){if(e||arguments.length===2)for(var g=0,I=A.length,o;g<I;g++)(o||!(g in A))&&(o||(o=Array.prototype.slice.call(A,0,g)),o[g]=A[g]);return i.concat(o||Array.prototype.slice.call(A))},RQA=function(i){var A=typeof Symbol=="function"&&Symbol.iterator,e=A&&i[A],g=0;if(e)return e.call(i);if(i&&typeof i.length=="number")return{next:function(){return i&&g>=i.length&&(i=void 0),{value:i&&i[g++],done:!i}}};throw new TypeError(A?"Object is not iterable.":"Symbol.iterator is not defined.")},F3=function(i){kQA(A,i);function A(e,g,I,o,s,n){n===void 0&&(n=5e3);var a=i.call(this)||this;a.pingInterval=n,a._disconnected=!0,a._messagesQueue=[];var r=e?"wss://":"ws://";return a._baseUrl=r+g+":"+I+o+"peerjs?key="+s,a}return A.prototype.start=function(e,g){var I=this;this._id=e;var o="".concat(this._baseUrl,"&id=").concat(e,"&token=").concat(g);this._socket||!this._disconnected||(this._socket=new WebSocket(o+"&version="+PK.version),this._disconnected=!1,this._socket.onmessage=function(s){var n;try{n=JSON.parse(s.data),Qe.default.log("Server message received:",n)}catch{Qe.default.log("Invalid server message",s.data);return}I.emit(Nr.Message,n)},this._socket.onclose=function(s){I._disconnected||(Qe.default.log("Socket closed.",s),I._cleanup(),I._disconnected=!0,I.emit(Nr.Disconnected))},this._socket.onopen=function(){I._disconnected||(I._sendQueuedMessages(),Qe.default.log("Socket open"),I._scheduleHeartbeat())})},A.prototype._scheduleHeartbeat=function(){var e=this;this._wsPingTimer=setTimeout(function(){e._sendHeartbeat()},this.pingInterval)},A.prototype._sendHeartbeat=function(){if(!this._wsOpen()){Qe.default.log("Cannot send heartbeat, because socket closed");return}var e=JSON.stringify({type:iI.Heartbeat});this._socket.send(e),this._scheduleHeartbeat()},A.prototype._wsOpen=function(){return!!this._socket&&this._socket.readyState===1},A.prototype._sendQueuedMessages=function(){var e,g,I=GQA([],MQA(this._messagesQueue),!1);this._messagesQueue=[];try{for(var o=RQA(I),s=o.next();!s.done;s=o.next()){var n=s.value;this.send(n)}}catch(a){e={error:a}}finally{try{s&&!s.done&&(g=o.return)&&g.call(o)}finally{if(e)throw e.error}}},A.prototype.send=function(e){if(!this._disconnected){if(!this._id){this._messagesQueue.push(e);return}if(!e.type){this.emit(Nr.Error,"Invalid message");return}if(this._wsOpen()){var g=JSON.stringify(e);this._socket.send(g)}}},A.prototype.close=function(){this._disconnected||(this._cleanup(),this._disconnected=!0)},A.prototype._cleanup=function(){this._socket&&(this._socket.onopen=this._socket.onmessage=this._socket.onclose=null,this._socket.close(),this._socket=void 0),clearTimeout(this._wsPingTimer)},A}(Fp.EventEmitter),jK={};Ba(jK,"MediaConnection",()=>b3,i=>b3=i);var WK={};Ba(WK,"Negotiator",()=>v3,i=>v3=i);var jS=function(){return jS=Object.assign||function(i){for(var A,e=1,g=arguments.length;e<g;e++){A=arguments[e];for(var I in A)Object.prototype.hasOwnProperty.call(A,I)&&(i[I]=A[I])}return i},jS.apply(this,arguments)},WS=function(i,A,e,g){function I(o){return o instanceof e?o:new e(function(s){s(o)})}return new(e||(e=Promise))(function(o,s){function n(C){try{r(g.next(C))}catch(Q){s(Q)}}function a(C){try{r(g.throw(C))}catch(Q){s(Q)}}function r(C){C.done?o(C.value):I(C.value).then(n,a)}r((g=g.apply(i,A||[])).next())})},ZS=function(i,A){var e={label:0,sent:function(){if(o[0]&1)throw o[1];return o[1]},trys:[],ops:[]},g,I,o,s;return s={next:n(0),throw:n(1),return:n(2)},typeof Symbol=="function"&&(s[Symbol.iterator]=function(){return this}),s;function n(r){return function(C){return a([r,C])}}function a(r){if(g)throw new TypeError("Generator is already executing.");for(;e;)try{if(g=1,I&&(o=r[0]&2?I.return:r[0]?I.throw||((o=I.return)&&o.call(I),0):I.next)&&!(o=o.call(I,r[1])).done)return o;switch(I=0,o&&(r=[r[0]&2,o.value]),r[0]){case 0:case 1:o=r;break;case 4:return e.label++,{value:r[1],done:!1};case 5:e.label++,I=r[1],r=[0];continue;case 7:r=e.ops.pop(),e.trys.pop();continue;default:if(o=e.trys,!(o=o.length>0&&o[o.length-1])&&(r[0]===6||r[0]===2)){e=0;continue}if(r[0]===3&&(!o||r[1]>o[0]&&r[1]<o[3])){e.label=r[1];break}if(r[0]===6&&e.label<o[1]){e.label=o[1],o=r;break}if(o&&e.label<o[2]){e.label=o[2],e.ops.push(r);break}o[2]&&e.ops.pop(),e.trys.pop();continue}r=A.call(i,e)}catch(C){r=[6,C],I=0}finally{g=o=0}if(r[0]&5)throw r[1];return{value:r[0]?r[1]:void 0,done:!0}}},v3=function(){function i(A){this.connection=A}return i.prototype.startConnection=function(A){var e=this._startPeerConnection();if(this.connection.peerConnection=e,this.connection.type===Sn.Media&&A._stream&&this._addTracksToConnection(A._stream,e),A.originator){if(this.connection.type===Sn.Data){var g=this.connection,I={ordered:!!A.reliable},o=e.createDataChannel(g.label,I);g.initialize(o)}this._makeOffer()}else this.handleSDP("OFFER",A.sdp)},i.prototype._startPeerConnection=function(){Qe.default.log("Creating RTCPeerConnection.");var A=new RTCPeerConnection(this.connection.provider.options.config);return this._setupListeners(A),A},i.prototype._setupListeners=function(A){var e=this,g=this.connection.peer,I=this.connection.connectionId,o=this.connection.type,s=this.connection.provider;Qe.default.log("Listening for ICE candidates."),A.onicecandidate=function(n){!n.candidate||!n.candidate.candidate||(Qe.default.log("Received ICE candidates for ".concat(g,":"),n.candidate),s.socket.send({type:iI.Candidate,payload:{candidate:n.candidate,type:o,connectionId:I},dst:g}))},A.oniceconnectionstatechange=function(){switch(A.iceConnectionState){case"failed":Qe.default.log("iceConnectionState is failed, closing connections to "+g),e.connection.emit("error",new Error("Negotiation of connection to "+g+" failed.")),e.connection.close();break;case"closed":Qe.default.log("iceConnectionState is closed, closing connections to "+g),e.connection.emit("error",new Error("Connection to "+g+" closed.")),e.connection.close();break;case"disconnected":Qe.default.log("iceConnectionState changed to disconnected on the connection with "+g);break;case"completed":A.onicecandidate=Gt.noop;break}e.connection.emit("iceStateChanged",A.iceConnectionState)},Qe.default.log("Listening for data channel"),A.ondatachannel=function(n){Qe.default.log("Received data channel");var a=n.channel,r=s.getConnection(g,I);r.initialize(a)},Qe.default.log("Listening for remote stream"),A.ontrack=function(n){Qe.default.log("Received remote stream");var a=n.streams[0],r=s.getConnection(g,I);if(r.type===Sn.Media){var C=r;e._addStreamToMediaConnection(a,C)}}},i.prototype.cleanup=function(){Qe.default.log("Cleaning up PeerConnection to "+this.connection.peer);var A=this.connection.peerConnection;if(A){this.connection.peerConnection=null,A.onicecandidate=A.oniceconnectionstatechange=A.ondatachannel=A.ontrack=function(){};var e=A.signalingState!=="closed",g=!1;if(this.connection.type===Sn.Data){var I=this.connection,o=I.dataChannel;o&&(g=!!o.readyState&&o.readyState!=="closed")}(e||g)&&A.close()}},i.prototype._makeOffer=function(){return WS(this,void 0,Promise,function(){var A,e,g,I,o,s,n;return ZS(this,function(a){switch(a.label){case 0:A=this.connection.peerConnection,e=this.connection.provider,a.label=1;case 1:return a.trys.push([1,7,,8]),[4,A.createOffer(this.connection.options.constraints)];case 2:g=a.sent(),Qe.default.log("Created offer."),this.connection.options.sdpTransform&&typeof this.connection.options.sdpTransform=="function"&&(g.sdp=this.connection.options.sdpTransform(g.sdp)||g.sdp),a.label=3;case 3:return a.trys.push([3,5,,6]),[4,A.setLocalDescription(g)];case 4:return a.sent(),Qe.default.log("Set localDescription:",g,"for:".concat(this.connection.peer)),I={sdp:g,type:this.connection.type,connectionId:this.connection.connectionId,metadata:this.connection.metadata,browser:Gt.browser},this.connection.type===Sn.Data&&(o=this.connection,I=jS(jS({},I),{label:o.label,reliable:o.reliable,serialization:o.serialization})),e.socket.send({type:iI.Offer,payload:I,dst:this.connection.peer}),[3,6];case 5:return s=a.sent(),s!="OperationError: Failed to set local offer sdp: Called in wrong state: kHaveRemoteOffer"&&(e.emitError(Zi.WebRTC,s),Qe.default.log("Failed to setLocalDescription, ",s)),[3,6];case 6:return[3,8];case 7:return n=a.sent(),e.emitError(Zi.WebRTC,n),Qe.default.log("Failed to createOffer, ",n),[3,8];case 8:return[2]}})})},i.prototype._makeAnswer=function(){return WS(this,void 0,Promise,function(){var A,e,g,I,o;return ZS(this,function(s){switch(s.label){case 0:A=this.connection.peerConnection,e=this.connection.provider,s.label=1;case 1:return s.trys.push([1,7,,8]),[4,A.createAnswer()];case 2:g=s.sent(),Qe.default.log("Created answer."),this.connection.options.sdpTransform&&typeof this.connection.options.sdpTransform=="function"&&(g.sdp=this.connection.options.sdpTransform(g.sdp)||g.sdp),s.label=3;case 3:return s.trys.push([3,5,,6]),[4,A.setLocalDescription(g)];case 4:return s.sent(),Qe.default.log("Set localDescription:",g,"for:".concat(this.connection.peer)),e.socket.send({type:iI.Answer,payload:{sdp:g,type:this.connection.type,connectionId:this.connection.connectionId,browser:Gt.browser},dst:this.connection.peer}),[3,6];case 5:return I=s.sent(),e.emitError(Zi.WebRTC,I),Qe.default.log("Failed to setLocalDescription, ",I),[3,6];case 6:return[3,8];case 7:return o=s.sent(),e.emitError(Zi.WebRTC,o),Qe.default.log("Failed to create answer, ",o),[3,8];case 8:return[2]}})})},i.prototype.handleSDP=function(A,e){return WS(this,void 0,Promise,function(){var g,I,o,s;return ZS(this,function(n){switch(n.label){case 0:e=new RTCSessionDescription(e),g=this.connection.peerConnection,I=this.connection.provider,Qe.default.log("Setting remote description",e),o=this,n.label=1;case 1:return n.trys.push([1,5,,6]),[4,g.setRemoteDescription(e)];case 2:return n.sent(),Qe.default.log("Set remoteDescription:".concat(A," for:").concat(this.connection.peer)),A!=="OFFER"?[3,4]:[4,o._makeAnswer()];case 3:n.sent(),n.label=4;case 4:return[3,6];case 5:return s=n.sent(),I.emitError(Zi.WebRTC,s),Qe.default.log("Failed to setRemoteDescription, ",s),[3,6];case 6:return[2]}})})},i.prototype.handleCandidate=function(A){return WS(this,void 0,Promise,function(){var e,g,I,o,s,n;return ZS(this,function(a){switch(a.label){case 0:Qe.default.log("handleCandidate:",A),e=A.candidate,g=A.sdpMLineIndex,I=A.sdpMid,o=this.connection.peerConnection,s=this.connection.provider,a.label=1;case 1:return a.trys.push([1,3,,4]),[4,o.addIceCandidate(new RTCIceCandidate({sdpMid:I,sdpMLineIndex:g,candidate:e}))];case 2:return a.sent(),Qe.default.log("Added ICE candidate for:".concat(this.connection.peer)),[3,4];case 3:return n=a.sent(),s.emitError(Zi.WebRTC,n),Qe.default.log("Failed to handleCandidate, ",n),[3,4];case 4:return[2]}})})},i.prototype._addTracksToConnection=function(A,e){if(Qe.default.log("add tracks from stream ".concat(A.id," to peer connection")),!e.addTrack)return Qe.default.error("Your browser does't support RTCPeerConnection#addTrack. Ignored.");A.getTracks().forEach(function(g){e.addTrack(g,A)})},i.prototype._addStreamToMediaConnection=function(A,e){Qe.default.log("add stream ".concat(A.id," to media connection ").concat(e.connectionId)),e.addStream(A)},i}(),ZK={};Ba(ZK,"BaseConnection",()=>K3,i=>K3=i);var UQA=function(){var i=function(A,e){return i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(g,I){g.__proto__=I}||function(g,I){for(var o in I)Object.prototype.hasOwnProperty.call(I,o)&&(g[o]=I[o])},i(A,e)};return function(A,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");i(A,e);function g(){this.constructor=A}A.prototype=e===null?Object.create(e):(g.prototype=e.prototype,new g)}}(),K3=function(i){UQA(A,i);function A(e,g,I){var o=i.call(this)||this;return o.peer=e,o.provider=g,o.options=I,o._open=!1,o.metadata=I.metadata,o}return Object.defineProperty(A.prototype,"open",{get:function(){return this._open},enumerable:!1,configurable:!0}),A}(Fp.EventEmitter),NQA=function(){var i=function(A,e){return i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(g,I){g.__proto__=I}||function(g,I){for(var o in I)Object.prototype.hasOwnProperty.call(I,o)&&(g[o]=I[o])},i(A,e)};return function(A,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");i(A,e);function g(){this.constructor=A}A.prototype=e===null?Object.create(e):(g.prototype=e.prototype,new g)}}(),zS=function(){return zS=Object.assign||function(i){for(var A,e=1,g=arguments.length;e<g;e++){A=arguments[e];for(var I in A)Object.prototype.hasOwnProperty.call(A,I)&&(i[I]=A[I])}return i},zS.apply(this,arguments)},FQA=function(i){var A=typeof Symbol=="function"&&Symbol.iterator,e=A&&i[A],g=0;if(e)return e.call(i);if(i&&typeof i.length=="number")return{next:function(){return i&&g>=i.length&&(i=void 0),{value:i&&i[g++],done:!i}}};throw new TypeError(A?"Object is not iterable.":"Symbol.iterator is not defined.")},b3=function(i){NQA(A,i);function A(e,g,I){var o=i.call(this,e,g,I)||this;return o._localStream=o.options._stream,o.connectionId=o.options.connectionId||A.ID_PREFIX+Gt.randomToken(),o._negotiator=new WK.Negotiator(o),o._localStream&&o._negotiator.startConnection({_stream:o._localStream,originator:!0}),o}return Object.defineProperty(A.prototype,"type",{get:function(){return Sn.Media},enumerable:!1,configurable:!0}),Object.defineProperty(A.prototype,"localStream",{get:function(){return this._localStream},enumerable:!1,configurable:!0}),Object.defineProperty(A.prototype,"remoteStream",{get:function(){return this._remoteStream},enumerable:!1,configurable:!0}),A.prototype.addStream=function(e){Qe.default.log("Receiving stream",e),this._remoteStream=e,i.prototype.emit.call(this,"stream",e)},A.prototype.handleMessage=function(e){var g=e.type,I=e.payload;switch(e.type){case iI.Answer:this._negotiator.handleSDP(g,I.sdp),this._open=!0;break;case iI.Candidate:this._negotiator.handleCandidate(I.candidate);break;default:Qe.default.warn("Unrecognized message type:".concat(g," from peer:").concat(this.peer));break}},A.prototype.answer=function(e,g){var I,o;if(g===void 0&&(g={}),this._localStream){Qe.default.warn("Local stream already exists on this MediaConnection. Are you answering a call twice?");return}this._localStream=e,g&&g.sdpTransform&&(this.options.sdpTransform=g.sdpTransform),this._negotiator.startConnection(zS(zS({},this.options._payload),{_stream:e}));var s=this.provider._getMessages(this.connectionId);try{for(var n=FQA(s),a=n.next();!a.done;a=n.next()){var r=a.value;this.handleMessage(r)}}catch(C){I={error:C}}finally{try{a&&!a.done&&(o=n.return)&&o.call(n)}finally{if(I)throw I.error}}this._open=!0},A.prototype.close=function(){this._negotiator&&(this._negotiator.cleanup(),this._negotiator=null),this._localStream=null,this._remoteStream=null,this.provider&&(this.provider._removeConnection(this),this.provider=null),this.options&&this.options._stream&&(this.options._stream=null),this.open&&(this._open=!1,i.prototype.emit.call(this,"close"))},A.ID_PREFIX="mc_",A}(ZK.BaseConnection),zK={};Ba(zK,"DataConnection",()=>q3,i=>q3=i);var J3={};Ba(J3,"EncodingQueue",()=>x3,i=>x3=i);var vQA=function(){var i=function(A,e){return i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(g,I){g.__proto__=I}||function(g,I){for(var o in I)Object.prototype.hasOwnProperty.call(I,o)&&(g[o]=I[o])},i(A,e)};return function(A,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");i(A,e);function g(){this.constructor=A}A.prototype=e===null?Object.create(e):(g.prototype=e.prototype,new g)}}(),x3=function(i){vQA(A,i);function A(){var e=i.call(this)||this;return e.fileReader=new FileReader,e._queue=[],e._processing=!1,e.fileReader.onload=function(g){e._processing=!1,g.target&&e.emit("done",g.target.result),e.doNextTask()},e.fileReader.onerror=function(g){Qe.default.error("EncodingQueue error:",g),e._processing=!1,e.destroy(),e.emit("error",g)},e}return Object.defineProperty(A.prototype,"queue",{get:function(){return this._queue},enumerable:!1,configurable:!0}),Object.defineProperty(A.prototype,"size",{get:function(){return this.queue.length},enumerable:!1,configurable:!0}),Object.defineProperty(A.prototype,"processing",{get:function(){return this._processing},enumerable:!1,configurable:!0}),A.prototype.enque=function(e){this.queue.push(e),!this.processing&&this.doNextTask()},A.prototype.destroy=function(){this.fileReader.abort(),this._queue=[]},A.prototype.doNextTask=function(){this.size!==0&&(this.processing||(this._processing=!0,this.fileReader.readAsArrayBuffer(this.queue.shift())))},A}(Fp.EventEmitter),KQA=function(){var i=function(A,e){return i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(g,I){g.__proto__=I}||function(g,I){for(var o in I)Object.prototype.hasOwnProperty.call(I,o)&&(g[o]=I[o])},i(A,e)};return function(A,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");i(A,e);function g(){this.constructor=A}A.prototype=e===null?Object.create(e):(g.prototype=e.prototype,new g)}}(),bQA=function(i){var A=typeof Symbol=="function"&&Symbol.iterator,e=A&&i[A],g=0;if(e)return e.call(i);if(i&&typeof i.length=="number")return{next:function(){return i&&g>=i.length&&(i=void 0),{value:i&&i[g++],done:!i}}};throw new TypeError(A?"Object is not iterable.":"Symbol.iterator is not defined.")},q3=function(i){KQA(A,i);function A(e,g,I){var o=i.call(this,e,g,I)||this;return o.stringify=JSON.stringify,o.parse=JSON.parse,o._buffer=[],o._bufferSize=0,o._buffering=!1,o._chunkedData={},o._encodingQueue=new J3.EncodingQueue,o.connectionId=o.options.connectionId||A.ID_PREFIX+Gt.randomToken(),o.label=o.options.label||o.connectionId,o.serialization=o.options.serialization||Ur.Binary,o.reliable=!!o.options.reliable,o._encodingQueue.on("done",function(s){o._bufferedSend(s)}),o._encodingQueue.on("error",function(){Qe.default.error("DC#".concat(o.connectionId,": Error occured in encoding from blob to arraybuffer, close DC")),o.close()}),o._negotiator=new WK.Negotiator(o),o._negotiator.startConnection(o.options._payload||{originator:!0}),o}return Object.defineProperty(A.prototype,"type",{get:function(){return Sn.Data},enumerable:!1,configurable:!0}),Object.defineProperty(A.prototype,"dataChannel",{get:function(){return this._dc},enumerable:!1,configurable:!0}),Object.defineProperty(A.prototype,"bufferSize",{get:function(){return this._bufferSize},enumerable:!1,configurable:!0}),A.prototype.initialize=function(e){this._dc=e,this._configureDataChannel()},A.prototype._configureDataChannel=function(){var e=this;(!Gt.supports.binaryBlob||Gt.supports.reliable)&&(this.dataChannel.binaryType="arraybuffer"),this.dataChannel.onopen=function(){Qe.default.log("DC#".concat(e.connectionId," dc connection success")),e._open=!0,e.emit("open")},this.dataChannel.onmessage=function(g){Qe.default.log("DC#".concat(e.connectionId," dc onmessage:"),g.data),e._handleDataMessage(g)},this.dataChannel.onclose=function(){Qe.default.log("DC#".concat(e.connectionId," dc closed for:"),e.peer),e.close()}},A.prototype._handleDataMessage=function(e){var g=this,I=e.data,o=I.constructor,s=this.serialization===Ur.Binary||this.serialization===Ur.BinaryUTF8,n=I;if(s){if(o===Blob){Gt.blobToArrayBuffer(I,function(r){var C=Gt.unpack(r);g.emit("data",C)});return}else if(o===ArrayBuffer)n=Gt.unpack(I);else if(o===String){var a=Gt.binaryStringToArrayBuffer(I);n=Gt.unpack(a)}}else this.serialization===Ur.JSON&&(n=this.parse(I));if(n.__peerData){this._handleChunk(n);return}i.prototype.emit.call(this,"data",n)},A.prototype._handleChunk=function(e){var g=e.__peerData,I=this._chunkedData[g]||{data:[],count:0,total:e.total};if(I.data[e.n]=e.data,I.count++,this._chunkedData[g]=I,I.total===I.count){delete this._chunkedData[g];var o=new Blob(I.data);this._handleDataMessage({data:o})}},A.prototype.close=function(){this._buffer=[],this._bufferSize=0,this._chunkedData={},this._negotiator&&(this._negotiator.cleanup(),this._negotiator=null),this.provider&&(this.provider._removeConnection(this),this.provider=null),this.dataChannel&&(this.dataChannel.onopen=null,this.dataChannel.onmessage=null,this.dataChannel.onclose=null,this._dc=null),this._encodingQueue&&(this._encodingQueue.destroy(),this._encodingQueue.removeAllListeners(),this._encodingQueue=null),this.open&&(this._open=!1,i.prototype.emit.call(this,"close"))},A.prototype.send=function(e,g){if(!this.open){i.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===Ur.JSON)this._bufferedSend(this.stringify(e));else if(this.serialization===Ur.Binary||this.serialization===Ur.BinaryUTF8){var I=Gt.pack(e);if(!g&&I.size>Gt.chunkedMTU){this._sendChunks(I);return}Gt.supports.binaryBlob?this._bufferedSend(I):this._encodingQueue.enque(I)}else this._bufferedSend(e)},A.prototype._bufferedSend=function(e){(this._buffering||!this._trySend(e))&&(this._buffer.push(e),this._bufferSize=this._buffer.length)},A.prototype._trySend=function(e){var g=this;if(!this.open)return!1;if(this.dataChannel.bufferedAmount>A.MAX_BUFFERED_AMOUNT)return this._buffering=!0,setTimeout(function(){g._buffering=!1,g._tryBuffer()},50),!1;try{this.dataChannel.send(e)}catch(I){return Qe.default.error("DC#:".concat(this.connectionId," Error when sending:"),I),this._buffering=!0,this.close(),!1}return!0},A.prototype._tryBuffer=function(){if(this.open&&this._buffer.length!==0){var e=this._buffer[0];this._trySend(e)&&(this._buffer.shift(),this._bufferSize=this._buffer.length,this._tryBuffer())}},A.prototype._sendChunks=function(e){var g,I,o=Gt.chunk(e);Qe.default.log("DC#".concat(this.connectionId," Try to send ").concat(o.length," chunks..."));try{for(var s=bQA(o),n=s.next();!n.done;n=s.next()){var a=n.value;this.send(a,!0)}}catch(r){g={error:r}}finally{try{n&&!n.done&&(I=s.return)&&I.call(s)}finally{if(g)throw g.error}}},A.prototype.handleMessage=function(e){var g=e.payload;switch(e.type){case iI.Answer:this._negotiator.handleSDP(e.type,g.sdp);break;case iI.Candidate:this._negotiator.handleCandidate(g.candidate);break;default:Qe.default.warn("Unrecognized message type:",e.type,"from peer:",this.peer);break}},A.ID_PREFIX="dc_",A.MAX_BUFFERED_AMOUNT=8388608,A}(ZK.BaseConnection),L3={};Ba(L3,"API",()=>Y3,i=>Y3=i);var _3=function(i,A,e,g){function I(o){return o instanceof e?o:new e(function(s){s(o)})}return new(e||(e=Promise))(function(o,s){function n(C){try{r(g.next(C))}catch(Q){s(Q)}}function a(C){try{r(g.throw(C))}catch(Q){s(Q)}}function r(C){C.done?o(C.value):I(C.value).then(n,a)}r((g=g.apply(i,A||[])).next())})},T3=function(i,A){var e={label:0,sent:function(){if(o[0]&1)throw o[1];return o[1]},trys:[],ops:[]},g,I,o,s;return s={next:n(0),throw:n(1),return:n(2)},typeof Symbol=="function"&&(s[Symbol.iterator]=function(){return this}),s;function n(r){return function(C){return a([r,C])}}function a(r){if(g)throw new TypeError("Generator is already executing.");for(;e;)try{if(g=1,I&&(o=r[0]&2?I.return:r[0]?I.throw||((o=I.return)&&o.call(I),0):I.next)&&!(o=o.call(I,r[1])).done)return o;switch(I=0,o&&(r=[r[0]&2,o.value]),r[0]){case 0:case 1:o=r;break;case 4:return e.label++,{value:r[1],done:!1};case 5:e.label++,I=r[1],r=[0];continue;case 7:r=e.ops.pop(),e.trys.pop();continue;default:if(o=e.trys,!(o=o.length>0&&o[o.length-1])&&(r[0]===6||r[0]===2)){e=0;continue}if(r[0]===3&&(!o||r[1]>o[0]&&r[1]<o[3])){e.label=r[1];break}if(r[0]===6&&e.label<o[1]){e.label=o[1],o=r;break}if(o&&e.label<o[2]){e.label=o[2],e.ops.push(r);break}o[2]&&e.ops.pop(),e.trys.pop();continue}r=A.call(i,e)}catch(C){r=[6,C],I=0}finally{g=o=0}if(r[0]&5)throw r[1];return{value:r[0]?r[1]:void 0,done:!0}}},Y3=function(){function i(A){this._options=A}return i.prototype._buildRequest=function(A){var e=this._options.secure?"https":"http",g=this._options,I=g.host,o=g.port,s=g.path,n=g.key,a=new URL("".concat(e,"://").concat(I,":").concat(o).concat(s).concat(n,"/").concat(A));return a.searchParams.set("ts","".concat(Date.now()).concat(Math.random())),a.searchParams.set("version",PK.version),fetch(a.href,{referrerPolicy:this._options.referrerPolicy})},i.prototype.retrieveId=function(){return _3(this,void 0,Promise,function(){var A,e,g;return T3(this,function(I){switch(I.label){case 0:return I.trys.push([0,2,,3]),[4,this._buildRequest("id")];case 1:if(A=I.sent(),A.status!==200)throw new Error("Error. Status:".concat(A.status));return[2,A.text()];case 2:throw e=I.sent(),Qe.default.error("Error retrieving ID",e),g="",this._options.path==="/"&&this._options.host!==Gt.CLOUD_HOST&&(g=" 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."+g);case 3:return[2]}})})},i.prototype.listAllPeers=function(){return _3(this,void 0,Promise,function(){var A,e,g;return T3(this,function(I){switch(I.label){case 0:return I.trys.push([0,2,,3]),[4,this._buildRequest("peers")];case 1:if(A=I.sent(),A.status!==200)throw A.status===401?(e="",this._options.host===Gt.CLOUD_HOST?e="It looks like you're using the cloud server. You can email team@peerjs.com to enable peer listing for your API key.":e="You need to enable `allow_discovery` on your self-hosted PeerServer to use this feature.",new Error("It doesn't look like you have permission to list peers IDs. "+e)):new Error("Error. Status:".concat(A.status));return[2,A.json()];case 2:throw g=I.sent(),Qe.default.error("Error retrieving list peers",g),new Error("Could not get list peers from the server."+g);case 3:return[2]}})})},i}(),JQA=function(){var i=function(A,e){return i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(g,I){g.__proto__=I}||function(g,I){for(var o in I)Object.prototype.hasOwnProperty.call(I,o)&&(g[o]=I[o])},i(A,e)};return function(A,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");i(A,e);function g(){this.constructor=A}A.prototype=e===null?Object.create(e):(g.prototype=e.prototype,new g)}}(),Kp=function(){return Kp=Object.assign||function(i){for(var A,e=1,g=arguments.length;e<g;e++){A=arguments[e];for(var I in A)Object.prototype.hasOwnProperty.call(A,I)&&(i[I]=A[I])}return i},Kp.apply(this,arguments)},bp=function(i){var A=typeof Symbol=="function"&&Symbol.iterator,e=A&&i[A],g=0;if(e)return e.call(i);if(i&&typeof i.length=="number")return{next:function(){return i&&g>=i.length&&(i=void 0),{value:i&&i[g++],done:!i}}};throw new TypeError(A?"Object is not iterable.":"Symbol.iterator is not defined.")},xQA=function(i,A){var e=typeof Symbol=="function"&&i[Symbol.iterator];if(!e)return i;var g=e.call(i),I,o=[],s;try{for(;(A===void 0||A-- >0)&&!(I=g.next()).done;)o.push(I.value)}catch(n){s={error:n}}finally{try{I&&!I.done&&(e=g.return)&&e.call(g)}finally{if(s)throw s.error}}return o},VK=function(i){JQA(A,i);function A(e,g){var I=i.call(this)||this;I._id=null,I._lastServerId=null,I._destroyed=!1,I._disconnected=!1,I._open=!1,I._connections=new Map,I._lostMessages=new Map;var o;return e&&e.constructor==Object?g=e:e&&(o=e.toString()),g=Kp({debug:0,host:Gt.CLOUD_HOST,port:Gt.CLOUD_PORT,path:"/",key:A.DEFAULT_KEY,token:Gt.randomToken(),config:Gt.defaultConfig,referrerPolicy:"strict-origin-when-cross-origin"},g),I._options=g,I._options.host==="/"&&(I._options.host=window.location.hostname),I._options.path&&(I._options.path[0]!=="/"&&(I._options.path="/"+I._options.path),I._options.path[I._options.path.length-1]!=="/"&&(I._options.path+="/")),I._options.secure===void 0&&I._options.host!==Gt.CLOUD_HOST?I._options.secure=Gt.isSecure():I._options.host==Gt.CLOUD_HOST&&(I._options.secure=!0),I._options.logFunction&&Qe.default.setLogFunction(I._options.logFunction),Qe.default.logLevel=I._options.debug||0,I._api=new L3.API(g),I._socket=I._createServerConnection(),!Gt.supports.audioVideo&&!Gt.supports.data?(I._delayedAbort(Zi.BrowserIncompatible,"The current browser does not support WebRTC"),I):o&&!Gt.validateId(o)?(I._delayedAbort(Zi.InvalidID,'ID "'.concat(o,'" is invalid')),I):(o?I._initialize(o):I._api.retrieveId().then(function(s){return I._initialize(s)}).catch(function(s){return I._abort(Zi.ServerError,s)}),I)}return Object.defineProperty(A.prototype,"id",{get:function(){return this._id},enumerable:!1,configurable:!0}),Object.defineProperty(A.prototype,"options",{get:function(){return this._options},enumerable:!1,configurable:!0}),Object.defineProperty(A.prototype,"open",{get:function(){return this._open},enumerable:!1,configurable:!0}),Object.defineProperty(A.prototype,"socket",{get:function(){return this._socket},enumerable:!1,configurable:!0}),Object.defineProperty(A.prototype,"connections",{get:function(){var e,g,I=Object.create(null);try{for(var o=bp(this._connections),s=o.next();!s.done;s=o.next()){var n=xQA(s.value,2),a=n[0],r=n[1];I[a]=r}}catch(C){e={error:C}}finally{try{s&&!s.done&&(g=o.return)&&g.call(o)}finally{if(e)throw e.error}}return I},enumerable:!1,configurable:!0}),Object.defineProperty(A.prototype,"destroyed",{get:function(){return this._destroyed},enumerable:!1,configurable:!0}),Object.defineProperty(A.prototype,"disconnected",{get:function(){return this._disconnected},enumerable:!1,configurable:!0}),A.prototype._createServerConnection=function(){var e=this,g=new N3.Socket(this._options.secure,this._options.host,this._options.port,this._options.path,this._options.key,this._options.pingInterval);return g.on(Nr.Message,function(I){e._handleMessage(I)}),g.on(Nr.Error,function(I){e._abort(Zi.SocketError,I)}),g.on(Nr.Disconnected,function(){e.disconnected||(e.emitError(Zi.Network,"Lost connection to server."),e.disconnect())}),g.on(Nr.Close,function(){e.disconnected||e._abort(Zi.SocketClosed,"Underlying socket is already closed.")}),g},A.prototype._initialize=function(e){this._id=e,this.socket.start(e,this._options.token)},A.prototype._handleMessage=function(e){var g,I,o=e.type,s=e.payload,n=e.src;switch(o){case iI.Open:this._lastServerId=this.id,this._open=!0,this.emit("open",this.id);break;case iI.Error:this._abort(Zi.ServerError,s.msg);break;case iI.IdTaken:this._abort(Zi.UnavailableID,'ID "'.concat(this.id,'" is taken'));break;case iI.InvalidKey:this._abort(Zi.InvalidKey,'API KEY "'.concat(this._options.key,'" is invalid'));break;case iI.Leave:Qe.default.log("Received leave message from ".concat(n)),this._cleanupPeer(n),this._connections.delete(n);break;case iI.Expire:this.emitError(Zi.PeerUnavailable,"Could not connect to peer ".concat(n));break;case iI.Offer:var c=s.connectionId,l=this.getConnection(n,c);if(l&&(l.close(),Qe.default.warn("Offer received for existing Connection ID:".concat(c))),s.type===Sn.Media){var a=new jK.MediaConnection(n,this,{connectionId:c,_payload:s,metadata:s.metadata});l=a,this._addConnection(n,l),this.emit("call",a)}else if(s.type===Sn.Data){var r=new zK.DataConnection(n,this,{connectionId:c,_payload:s,metadata:s.metadata,label:s.label,serialization:s.serialization,reliable:s.reliable});l=r,this._addConnection(n,l),this.emit("connection",r)}else{Qe.default.warn("Received malformed connection type:".concat(s.type));return}var C=this._getMessages(c);try{for(var Q=bp(C),h=Q.next();!h.done;h=Q.next()){var E=h.value;l.handleMessage(E)}}catch(d){g={error:d}}finally{try{h&&!h.done&&(I=Q.return)&&I.call(Q)}finally{if(g)throw g.error}}break;default:if(!s){Qe.default.warn("You received a malformed message from ".concat(n," of type ").concat(o));return}var c=s.connectionId,l=this.getConnection(n,c);l&&l.peerConnection?l.handleMessage(e):c?this._storeMessage(c,e):Qe.default.warn("You received an unrecognized message:",e);break}},A.prototype._storeMessage=function(e,g){this._lostMessages.has(e)||this._lostMessages.set(e,[]),this._lostMessages.get(e).push(g)},A.prototype._getMessages=function(e){var g=this._lostMessages.get(e);return g?(this._lostMessages.delete(e),g):[]},A.prototype.connect=function(e,g){if(g===void 0&&(g={}),this.disconnected){Qe.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(Zi.Disconnected,"Cannot connect to new Peer after disconnecting from server.");return}var I=new zK.DataConnection(e,this,g);return this._addConnection(e,I),I},A.prototype.call=function(e,g,I){if(I===void 0&&(I={}),this.disconnected){Qe.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(Zi.Disconnected,"Cannot connect to new Peer after disconnecting from server.");return}if(!g){Qe.default.error("To call a peer, you must provide a stream from your browser's `getUserMedia`.");return}var o=new jK.MediaConnection(e,this,Kp(Kp({},I),{_stream:g}));return this._addConnection(e,o),o},A.prototype._addConnection=function(e,g){Qe.default.log("add connection ".concat(g.type,":").concat(g.connectionId," to peerId:").concat(e)),this._connections.has(e)||this._connections.set(e,[]),this._connections.get(e).push(g)},A.prototype._removeConnection=function(e){var g=this._connections.get(e.peer);if(g){var I=g.indexOf(e);I!==-1&&g.splice(I,1)}this._lostMessages.delete(e.connectionId)},A.prototype.getConnection=function(e,g){var I,o,s=this._connections.get(e);if(!s)return null;try{for(var n=bp(s),a=n.next();!a.done;a=n.next()){var r=a.value;if(r.connectionId===g)return r}}catch(C){I={error:C}}finally{try{a&&!a.done&&(o=n.return)&&o.call(n)}finally{if(I)throw I.error}}return null},A.prototype._delayedAbort=function(e,g){var I=this;setTimeout(function(){I._abort(e,g)},0)},A.prototype._abort=function(e,g){Qe.default.error("Aborting!"),this.emitError(e,g),this._lastServerId?this.disconnect():this.destroy()},A.prototype.emitError=function(e,g){Qe.default.error("Error:",g);var I;typeof g=="string"?I=new Error(g):I=g,I.type=e,this.emit("error",I)},A.prototype.destroy=function(){this.destroyed||(Qe.default.log("Destroy peer with ID:".concat(this.id)),this.disconnect(),this._cleanup(),this._destroyed=!0,this.emit("close"))},A.prototype._cleanup=function(){var e,g;try{for(var I=bp(this._connections.keys()),o=I.next();!o.done;o=I.next()){var s=o.value;this._cleanupPeer(s),this._connections.delete(s)}}catch(n){e={error:n}}finally{try{o&&!o.done&&(g=I.return)&&g.call(I)}finally{if(e)throw e.error}}this.socket.removeAllListeners()},A.prototype._cleanupPeer=function(e){var g,I,o=this._connections.get(e);if(o)try{for(var s=bp(o),n=s.next();!n.done;n=s.next()){var a=n.value;a.close()}}catch(r){g={error:r}}finally{try{n&&!n.done&&(I=s.return)&&I.call(s)}finally{if(g)throw g.error}}},A.prototype.disconnect=function(){if(!this.disconnected){var e=this.id;Qe.default.log("Disconnect peer with ID:".concat(e)),this._disconnected=!0,this._open=!1,this.socket.close(),this._lastServerId=e,this._id=null,this.emit("disconnected",e)}},A.prototype.reconnect=function(){if(this.disconnected&&!this.destroyed)Qe.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)Qe.default.error("In a hurry? We're still trying to make the initial connection!");else throw new Error("Peer ".concat(this.id," cannot reconnect because it is not disconnected from the server!"))}},A.prototype.listAllPeers=function(e){var g=this;e===void 0&&(e=function(I){}),this._api.listAllPeers().then(function(I){return e(I)}).catch(function(I){return g._abort(Zi.ServerError,I)})},A.DEFAULT_KEY="peerjs",A}(Fp.EventEmitter),XK=G3.Peer;const qQA=Object.freeze(Object.defineProperty({__proto__:null,get Peer(){return VK},default:XK,util:Gt},Symbol.toStringTag,{value:"Module"}));let $K;function LQA(){return $K}function _QA(i){$K=i}function H3(i,A){return A||(A={}),A={...$K,...A},i?new XK(i,A):new XK(A)}async function O3(){const i=await Promise.resolve().then(()=>qQA);return console.log(i),i.default===void 0?i:i.default}class P3{constructor(){B(this,"_host"),B(this,"_client"),B(this,"_clientData"),this.onEnable()}get isHost(){return this._host!==void 0}onEnable(){const A="HOST-5980e65c-8438-453e-8b35-f13c736dcd81";this.trySetupHost(A)}async trySetupHost(A){const e=await O3(),g=new e(A);g.on("error",I=>{console.error(I),this._host=void 0,this.trySetupClient(A)}),g.on("open",I=>{this._host=new YQA(g)})}async trySetupClient(A){const e=await O3();this._client=new e,this._client.on("error",g=>{console.error("Client error",g)}),this._client.on("open",g=>{console.log("client connected",g),this._clientData=this._client.connect(A,{metadata:{id:g}}),this._clientData.on("open",()=>{console.log("Connected to host")}),this._clientData.on("data",I=>{console.log("<<",I)})})}}class TQA{constructor(A){B(this,"_peer"),this._peer=A}}class YQA extends TQA{constructor(A){var e;super(A),B(this,"_connections",[]),console.log("I AM THE HOST"),(e=this._peer)==null||e.on("connection",this.onConnection.bind(this)),this._peer.on("close",()=>{this.broadcast("BYE")}),setInterval(()=>{this.broadcast("HELLO")},2e3)}get isHost(){return!0}onConnection(A){console.log("host connection",A),A.on("open",()=>{this._connections.push(A),this.broadcastConnection(A)})}broadcastConnection(A){const e=this._connections.map(g=>{var I;return(I=g.metadata)==null?void 0:I.id}).filter(g=>g!==void 0);this.broadcast({type:"connection-list",connections:e})}broadcast(A){if(A!=null){console.log(">>",A);for(const e in this._peer.connections){const g=this._peer.connections[e];if(g)if(Array.isArray(g))for(const I of g)I&&I.send(A);else console.warn(g)}}}}const j3="https://urls.needle.tools/default-networking-backend/index";let sB="wss://needle-tiny-starter.glitch.me/socket";const so=!!iA("debugnet"),Jp=!!(so||iA("debugowner")),W3=iA("debugnetbin");var Z3=(i=>(i.ConnectionInfo="connection-start-info",i))(Z3||{}),Pe=(i=>(i.Join="join-room",i.Leave="leave-room",i.JoinedRoom="joined-room",i.LeftRoom="left-room",i.UserJoinedRoom="user-joined-room",i.UserLeftRoom="user-left-room",i.RoomStateSent="room-state-sent",i))(Pe||{});class HQA{constructor(){B(this,"room"),B(this,"viewId"),B(this,"allowEditing"),B(this,"inRoom")}}class OQA{constructor(){B(this,"room")}}class PQA{constructor(){B(this,"userId")}}var z3=(i=>(i.RequestHasOwner="request-has-owner",i.ResponseHasOwner="response-has-owner",i.RequestIsOwner="request-is-owner",i.ResponseIsOwner="response-is-owner",i.RequestOwnership="request-ownership",i.GainedOwnership="gained-ownership",i.RemoveOwnership="remove-ownership",i.LostOwnership="lost-ownership",i.GainedOwnershipBroadcast="gained-ownership-broadcast",i.LostOwnershipBroadcast="lost-ownership-broadcast",i))(z3||{});class Ab{constructor(A,e){B(this,"guid"),B(this,"connection"),B(this,"_hasOwnership",!1),B(this,"_isOwned"),B(this,"_gainSubscription"),B(this,"_lostSubscription"),B(this,"_hasOwnerResponse"),B(this,"_isWaitingForOwnershipResponseCallback",null),this.connection=A,this.guid=e,this._gainSubscription=this.onGainedOwnership.bind(this),this._lostSubscription=this.onLostOwnership.bind(this),A.beginListen("lost-ownership",this._lostSubscription),A.beginListen("gained-ownership-broadcast",this._gainSubscription),this._hasOwnerResponse=this.onHasOwnerResponse.bind(this),A.beginListen("response-has-owner",this._hasOwnerResponse)}get hasOwnership(){return this._hasOwnership}get isOwned(){return this._isOwned}get isConnected(){return this.connection.isConnected}updateIsOwned(){this.connection.send("request-has-owner",{guid:this.guid})}onHasOwnerResponse(A){A.guid===this.guid&&(this._isOwned=A.value)}requestOwnershipIfNotOwned(){return this._isWaitingForOwnershipResponseCallback!==null?this:(this._isWaitingForOwnershipResponseCallback=this.waitForHasOwnershipRequestResponse.bind(this),this.connection.beginListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this.connection.send("request-has-owner",{guid:this.guid}),this)}waitForHasOwnershipRequestResponse(A){A.guid===this.guid&&(this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this._isOwned=A.value,A.value||(Jp&&console.log("request ownership",this.guid),this.requestOwnership()))}requestOwnershipAsync(){return new Promise((A,e)=>{this.requestOwnership();let g=0;const I=()=>{if(g++>10)return e("Timeout");setTimeout(()=>{this.hasOwnership?A(this):I()},100)};I()})}requestOwnership(){return Jp&&console.log("Request ownership",this.guid),this.connection.send("request-ownership",{guid:this.guid}),this}freeOwnership(){return this.connection.send("remove-ownership",{guid:this.guid}),this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this}destroy(){this.connection.stopListen("gained-ownership",this._gainSubscription),this.connection.stopListen("lost-ownership",this._lostSubscription),this.connection.stopListen("response-has-owner",this._hasOwnerResponse),this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null)}onGainedOwnership(A){A.guid===this.guid&&(this._isOwned=!0,this.connection.connectionId===A.owner?(Jp&&console.log("GAINED OWNERSHIP",this.guid),this._hasOwnership=!0):this._hasOwnership=!1)}onLostOwnership(A){A===this.guid&&(Jp&&console.log("LOST OWNERSHIP",this.guid),this._hasOwnership=!1,this._isOwned=!1)}}class V3{constructor(A){B(this,"context"),B(this,"_peer",null),B(this,"_usersInRoomCopy",[]),B(this,"_defaultMessagesBuffer",[]),B(this,"_defaultMessagesBufferArray",[]),B(this,"netWebSocketUrlProvider"),B(this,"_listeners",{}),B(this,"_listenersBinary",{}),B(this,"connected",!1),B(this,"channelId"),B(this,"_connectionId",null),B(this,"_ws"),B(this,"_waitingForSocket",{}),B(this,"_isInRoom",!1),B(this,"_currentRoomName",null),B(this,"_currentRoomViewId",null),B(this,"_currentRoomAllowEditing",!0),B(this,"_currentInRoom",[]),B(this,"_state",{}),B(this,"_currentDelay",-1),B(this,"_connectingToWebsocketPromise",null),this.context=A}get peer(){return this._peer||(this._peer=new P3),this._peer}tryGetState(A){return A==="invalid"?null:this._state[A]}get connectionId(){return this._connectionId}get isDebugEnabled(){return so}get isConnected(){return this.connected}get currentRoomName(){return this._currentRoomName}get allowEditing(){return this._currentRoomAllowEditing}get currentRoomViewId(){return this._currentRoomViewId}getViewOnlyUrl(){if(this.currentRoomViewId===null)return null;const A=new URL(window.location.href);return A.searchParams.set("view",this.currentRoomViewId),A.href}get isInRoom(){return this._isInRoom}get currentLatency(){return this._currentDelay}get currentServerUrl(){var A;return((A=this._ws)==null?void 0:A.url)??null}sendPing(){this.send("ping",{time:this.context.time.time})}userIsInRoom(A){return this._currentInRoom.indexOf(A)!==-1}usersInRoom(A=null){A||(A=this._usersInRoomCopy),A.length=0;for(const e of this._currentInRoom)A.push(e);return A}joinRoom(A,e=!1){return A?A.length>1024?(console.error('Room name too long, can not join: "'+A+'". Max length is 1024 characters.'),!1):(this.connect(),so&&console.log("join: "+A),this.send("join-room",{room:A,viewOnly:e},mn.OnConnection),!0):(console.error('Missing room name, can not join: "'+A+'"'),!1)}leaveRoom(A=null){return A||(A=this.currentRoomName),A?(this.send("leave-room",{room:A}),!0):(console.error('Missing room name, can not join: "'+A+'"'),!1)}send(A,e=null,g=mn.Queued){if(e===null&&(e={}),g===mn.Queued){this._defaultMessagesBuffer.push({key:A,value:e});return}return this.sendWithWebsocket(A,e,g)}sendDeleteRemoteState(A){this.send("delete-state",{guid:A,dontSave:!0}),delete this._state[A]}sendDeleteRemoteStateAll(){this.send("delete-all-state"),this._state={}}sendBinary(A){var e;W3&&console.log("<< send binary",this.context.time.frame,A.length/1024+" KB"),(e=this._ws)==null||e.send(A)}sendBufferedMessagesNow(){var A;if(!this._ws)return;this._defaultMessagesBufferArray.length=0;const e=Object.keys(this._defaultMessagesBuffer).length;for(const I in this._defaultMessagesBuffer){const o=this._defaultMessagesBuffer[I];if(e<=1){this.sendWithWebsocket(o.key,o.value,mn.Immediate);break}const s=this.toMessage(o.key,o.value);this._defaultMessagesBufferArray.push(s)}if(this._defaultMessagesBuffer.length=0,this._defaultMessagesBufferArray.length>0&&so&&console.log("SEND BUFFERED",this._defaultMessagesBufferArray.length),this._defaultMessagesBufferArray.length<=0)return;const g=JSON.stringify(this._defaultMessagesBufferArray);(A=this._ws)==null||A.send(g)}beginListen(A,e){return this._listeners[A]||(this._listeners[A]=[]),this._listeners[A].push(e),e}stopListening(A,e){return this.stopListen(A,e)}stopListen(A,e){if(!e||!this._listeners[A])return;const g=this._listeners[A].indexOf(e);g>=0&&this._listeners[A].splice(g,1)}beginListenBinary(A,e){return this._listenersBinary[A]||(this._listenersBinary[A]=[]),this._listenersBinary[A].push(e),e}stopListenBinary(A,e){if(!this._listenersBinary[A])return;const g=this._listenersBinary[A].indexOf(e);g>=0&&this._listenersBinary[A].splice(g,1)}registerProvider(A){this.netWebSocketUrlProvider=A}async connect(){var A;if(this.connected)return Promise.resolve(!0);so&&console.log("connecting");const e=(A=this.netWebSocketUrlProvider)==null?void 0:A.getWebsocketUrl();return e?sB=e:m2()&&(sB="wss://"+window.location.host+"/socket"),this.connectWebsocket()}disconnect(){var A;(A=this._ws)==null||A.close(),this._ws=void 0}connectWebsocket(){return this._connectingToWebsocketPromise?this._connectingToWebsocketPromise:this._connectingToWebsocketPromise=new Promise(async(A,e)=>{var g,I;let o=!1;const s=Q=>{o||(o=!0,A(Q))};if(sB===void 0&&(console.log("Fetch default backend url: "+j3),sB=await(await fetch(j3)).text()),sB===void 0){s(!1);return}console.log(`\u22A1 Connecting to networking backend on
5233
5233
  `+sB);const n=await Promise.resolve().then(()=>k0A),a=((g=n.default)==null?void 0:g.WebsocketBuilder)??n.WebsocketBuilder,r=((I=n.default)==null?void 0:I.ExponentialBackoff)??n.ExponentialBackoff,C=new a(sB).withMaxRetries(3).withBackoff(new r(2e3,2)).onOpen(()=>{this._connectingToWebsocketPromise=null,this._ws=C,this.connected=!0,console.log(`\u229E Connected to networking backend
5234
5234
  `+sB),s(!0),this.onSendQueued(mn.OnConnection)}).onClose(Q=>{this._connectingToWebsocketPromise=null,this.connected=!1,this._isInRoom=!1,s(!1)}).onError(Q=>{console.error("\u22A0 Websocket error"),s(!1)}).onRetry(()=>{console.log("Retry connecting to networking websocket")}).build();C.addEventListener(n.WebsocketEvent.message,(Q,h)=>{this.onMessage(Q,h)})})}onMessage(A,e){const g=e.data;try{if(typeof g!="string"){g.size&&this.handleIncomingBinaryMessage(g);return}const I=JSON.parse(g);if(Array.isArray(I))for(const o of I)this.handleIncomingStringMessage(o);else this.handleIncomingStringMessage(I);return}catch(I){so&&g==="pong"?console.log("<<",g):se()&&console.error("Failed to parse message",I)}}async handleIncomingBinaryMessage(A){W3&&console.log("<< bin",this.context.time.frame);const e=await A.arrayBuffer();var g=new Uint8Array(e);const I=new Pw(g),o=I.getBufferIdentifier(),s=this._listenersBinary[o],n=R4(I),a=U4(n);if(a&&typeof a=="string"&&(this._state[a]=n),!s)return;const r=n??I;for(const C of s)C(r)}handleIncomingStringMessage(A){var e,g;if(so&&console.log("<<",A.key??A),A.key)switch(A.key){case"connection-start-info":if(A.data){const n=A.data;n&&(console.assert(n.id!==void 0&&n.id!==null&&n.id.length>0,"server did not send connection id",n.id),console.log("Your id is: "+n.id,this.context.alias??""),this._connectionId=n.id)}else console.warn("Expected connection id in "+A.key);break;case"joined-room":if(so&&console.log(A),A){this._isInRoom=!0;const n=A;this._currentRoomName=n.room,this._currentRoomViewId=n.viewId,this._currentRoomAllowEditing=n.allowEditing??!0,this._currentInRoom.length=0,this._currentInRoom.push(...n.inRoom),so&&console.log("joined room with",this._currentInRoom,this.context.alias??"");const a=new URL(window.location.href);a.searchParams.has("room")&&a.searchParams.delete("room"),a.searchParams.set("view",this._currentRoomViewId),console.log("Room view id: "+this._currentRoomViewId+`
5235
- `+a.href)}this.onSendQueued(mn.OnRoomJoin);break;case"left-room":A.room===this.currentRoomName&&(this._isInRoom=!1,this._currentRoomName=null,this._currentInRoom.length=0);break;case"user-joined-room":if(A.data){const n=A.data;this._currentInRoom.push(n.userId),so&&console.log(n.userId+" joined","now in room:",this._currentInRoom)}break;case"user-left-room":if(A.data){const n=A.data,a=this._currentInRoom.indexOf(n.userId);a>=0&&(so&&console.log(n.userId+" left","now in room:",this._currentInRoom),this._currentInRoom.splice(a,1)),n.userId===this.connectionId&&console.log("you left the room")}break;case"all-room-state-deleted":so&&console.log("RECEIVED all-room-state-deleted"),this._state={};break;case"ping":case"pong":const s=(e=A.data)==null?void 0:e.time;s&&(this._currentDelay=this.context.time.time-s),so&&console.log("Current latency: "+this._currentDelay.toFixed(4)+" sec","Clients in room: "+((g=this._currentInRoom)==null?void 0:g.length));break}const I=A.data;I&&(this._state[I.guid]=I);let o=this._listeners[A.key];if(o){o=[...o];for(const s of o)try{s(A.data)}catch(n){console.error('Error invoking callback for "'+A.key+'"',n)}}}toMessage(A,e){return{key:A,data:e}}sendWithWebsocket(A,e,g=mn.OnRoomJoin){if(!this._ws){const o=this._waitingForSocket[g]||[];o.push(()=>this.sendWithWebsocket(A,e,g)),this._waitingForSocket[g]=o;return}const I=JSON.stringify(this.toMessage(A,e));so&&console.log(">>",A),this._ws.send(I)}onSendQueued(A){const e=this._waitingForSocket[A];if(e){for(const g of e)g();e.length=0}}}const xp=iA("debugwebxr");class eb{constructor(A,e){B(this,"controllerStates",[]),B(this,"userId"),B(this,"context"),B(this,"userStateEvtName"),B(this,"onReceivedControllerState",g=>{xp&&console.log(`XRSync: Received change for ${this.userId}: ${g.type} ${g.handedness}; tracked=${g.isTracking}`);let I=!1;for(let o=0;o<this.controllerStates.length;o++)if(this.controllerStates[o].index===g.index){this.controllerStates[o]=g,I=!0;break}I||this.controllerStates.push(g)}),this.userId=A,this.context=e,this.userStateEvtName="xr-sync-user-state-"+A,this.context.connection.beginListen(this.userStateEvtName,this.onReceivedControllerState)}dispose(){this.context.connection.stopListen(this.userStateEvtName,this.onReceivedControllerState)}update(A){if(this.context.connection.isConnected!=!1){for(let e=this.controllerStates.length-1;e>=0;e--){const g=this.controllerStates[e];let I=!1;for(let o=0;o<A.controllers.length;o++)A.controllers[o].index===g.index&&(I=!0);I||(xp&&console.log(`XRSync: ${g.type} ${g.handedness} removed`,g.index),this.controllerStates.splice(e,1),this.sendControllerRemoved(g))}for(const e of A.controllers)this.updateControllerStates(e)}}onExitXR(A){for(const e of this.controllerStates)this.sendControllerRemoved(e);this.controllerStates.length=0}sendControllerRemoved(A){A.isTracking=!1,A.guid="",this.context.connection.send(this.userStateEvtName,A),this.context.connection.sendDeleteRemoteState(A.guid)}updateControllerStates(A){const e=this.controllerStates.find(g=>g.index===A.index);if(e){let g=!1;g||(g=e.isTracking!=A.isTracking),g&&(e.isTracking=A.isTracking,this.context.connection.send(this.userStateEvtName,e))}else{const g={guid:this.userId+"-"+A.index,isTracking:A.isTracking,handedness:A.side,index:A.index,type:A.hand?"hand":"controller"};this.controllerStates.push(g),this.context.connection.send(this.userStateEvtName,g),xp&&console.log(`XRSync: ${g.type} ${g.handedness} added`,g.index)}}}class X3{constructor(A){B(this,"context"),B(this,"onJoinedRoom",()=>{if(this.context.connection.connectionId){this._states.has(this.context.connection.connectionId)||(xp&&console.log("XRSync: Local user joined room",this.context.connection.connectionId),this._states.set(this.context.connection.connectionId,new eb(this.context.connection.connectionId,this.context)));for(const e of this.context.connection.usersInRoom())this._states.has(e)||this._states.set(e,new eb(e,this.context))}}),B(this,"onLeftRoom",()=>{if(this.context.connection.connectionId&&!this._states.has(this.context.connection.connectionId)){const e=this._states.get(this.context.connection.connectionId);e?.dispose(),this._states.delete(this.context.connection.connectionId)}}),B(this,"onOtherUserJoinedRoom",e=>{const g=e.userId;this._states.has(g)||(xp&&console.log("XRSync: Remote user joined room",g),this._states.set(g,new eb(g,this.context)))}),B(this,"onOtherUserLeftRoom",e=>{const g=e.userId;if(!this._states.has(g)){const I=this._states.get(g);I?.dispose(),this._states.delete(g)}}),B(this,"_states",new Map),this.context=A,this.context.connection.beginListen(Pe.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(Pe.LeftRoom,this.onLeftRoom),this.context.connection.beginListen(Pe.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.beginListen(Pe.UserLeftRoom,this.onOtherUserLeftRoom)}hasState(A){return A?this._states.has(A):!1}isTracking(A,e){if(!A)return;const g=this._states.get(A);if(!g)return;const I=g.controllerStates.find(o=>o.handedness===e);return I?.isTracking||!1}getDeviceType(A,e){if(!A)return;const g=this._states.get(A);if(!g)return;const I=g.controllerStates.find(o=>o.handedness===e);return I?.type||"unknown"}destroy(){this.context.connection.stopListen(Pe.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(Pe.LeftRoom,this.onLeftRoom),this.context.connection.stopListen(Pe.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.stopListen(Pe.UserLeftRoom,this.onOtherUserLeftRoom)}onUpdate(A){if(this.context.connection.isConnected&&this.context.connection.connectionId){const e=this._states.get(this.context.connection.connectionId);e?.update(A)}}onExitXR(A){if(this.context.connection.isConnected&&this.context.connection.connectionId){const e=this._states.get(this.context.connection.connectionId);e?.onExitXR(A)}}}class $3{constructor(){B(this,"_fadeToColorQuad"),B(this,"_fadeToColorMaterial"),B(this,"_requestedFadeValue",0),B(this,"_transitionPromise",null),B(this,"_transitionResolve",null),this._fadeToColorMaterial=new tt({color:0,transparent:!0,depthTest:!1,fog:!1,side:yt}),this._fadeToColorQuad=new dA(new Qg(10,10),this._fadeToColorMaterial)}dispose(){this._fadeToColorQuad.geometry.dispose(),this._fadeToColorMaterial.dispose()}update(A,e){const g=this._fadeToColorQuad,I=this._fadeToColorMaterial;g.parent!==A&&I.opacity>0?A.add(g):I.opacity===0&&g.removeFromParent(),g.layers.set(2),g.material=this._fadeToColorMaterial,g.position.z=-1,g.renderOrder=1/0;const o=this._requestedFadeValue;I.opacity=ge.lerp(I.opacity,o,e/.03),Math.abs(I.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 A=new Promise(e=>{this._transitionResolve=e});return this._transitionPromise=A,A}}var ch=(i=>(i[i.Quad=0]="Quad",i[i.Cube=1]="Cube",i[i.Sphere=2]="Sphere",i))(ch||{});class qp{static createPrimitive(A,e){let g;switch(A){case"Quad":case 0:{const I=new Qg(1,1,1,1),o=e?.material??new MI({color:16777215});e!=null&&e.texture&&"map"in o&&(o.map=e.texture),g=new dA(I,o)}break;case"Cube":case 1:{const I=new Ai(1,1,1),o=e?.material??new MI({color:16777215});e!=null&&e.texture&&"map"in o&&(o.map=e.texture),g=new dA(I,o)}break;case"Sphere":case 2:{const I=new Vs(.5,16,16),o=e?.material??new MI({color:16777215});e!=null&&e.texture&&"map"in o&&(o.map=e.texture),g=new dA(I,o)}break}return this.applyDefaultObjectOptions(g,e),g}static createSprite(A){const e=new zy({color:16777215});A!=null&&A.texture&&"map"in e&&(e.map=A.texture);const g=new WR(e);return this.applyDefaultObjectOptions(g,A),g}static applyDefaultObjectOptions(A,e){e!=null&&e.name&&(A.name=e.name),e!=null&&e.position&&A.position.set(e.position.x,e.position.y,e.position.z),e!=null&&e.rotation&&A.rotation.set(e.rotation.x,e.rotation.y,e.rotation.z),e!=null&&e.scale&&A.scale.set(e.scale.x,e.scale.y,e.scale.z)}}const Aj=class{constructor(i,A,e){B(this,"_session"),B(this,"_mode"),B(this,"_init"),B(this,"_renderer"),B(this,"_camera"),B(this,"_scene"),B(this,"onEnd",()=>{var g;(g=this._session)==null||g.removeEventListener("end",this.onEnd),this._renderer.setAnimationLoop(null),this._renderer.dispose(),this._scene.clear()}),B(this,"_lastTime",0),B(this,"onFrame",(g,I)=>{const o=g-this._lastTime;this.update(g,o),this._camera.parent!==this._scene&&this._scene.add(this._camera),this._renderer.render(this._scene,this._camera)}),B(this,"_objects",[]),this._mode=i,this._init=A,this._session=e,this._session.addEventListener("end",this.onEnd),this._renderer=new sr({alpha:!0}),this._renderer.setAnimationLoop(this.onFrame),this._renderer.xr.setSession(e),this._renderer.xr.enabled=!0,this._camera=new xe,this._scene=new Vg,this._scene.fog=new Zy(4473924,10,250),this._scene.add(this._camera),this.setupScene()}static get active(){return this._active}static async start(i,A){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(!A)return console.error("XRSessionInit must be provided"),null;this._requestInFlight=!0;const e=await navigator.xr.requestSession(i,A);return e.addEventListener("end",()=>{this._active=null}),this._requestInFlight?(this._requestInFlight=!1,this._active=new Aj(i,A,e),this._active):(e.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 Vn(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 i={session:this._session,mode:this._mode,init:this._init};return await this.onBeforeHandoff(),this.onEnd(),this._session=null,i}async onBeforeHandoff(){await Vn(1e3),this._scene.clear()}setupScene(){this._scene.background=new fA(0),this._scene.add(new F0(5,10,1118481,1118481));const i=new GQ(16777215,1);i.position.set(0,20,0),i.castShadow=!1,this._scene.add(i);const A=new GQ(16777215,1);A.position.set(0,-1,0),A.castShadow=!1,this._scene.add(A);const e=new MQ(16777215,1,100,1);e.position.set(0,2,0),e.castShadow=!1,e.distance=200,this._scene.add(e);const g=50;for(let I=0;I<100;I++){const o=new MI({color:2236962,metalness:1,roughness:.8});this.isAR&&(o.emissive=new fA(Math.random(),Math.random(),Math.random()),o.emissiveIntensity=Math.random());const s=ge.random(0,1)>.5?ch.Sphere:ch.Cube,n=qp.createPrimitive(s,{material:o});n.position.x=ge.random(-g,g),n.position.y=ge.random(-2,g),n.position.z=ge.random(-g,g),n.rotation.x=ge.random(0,Math.PI*2),n.rotation.y=ge.random(0,Math.PI*2),n.rotation.z=ge.random(0,Math.PI*2),n.scale.multiplyScalar(.5+Math.random()*10);const a=n.position.distanceTo(this._camera.position)-n.scale.x;a<1&&n.position.multiplyScalar(1+1/a),this._objects.push(n),this._scene.add(n)}}update(i,A){const e=i*4e-4;for(let g=0;g<this._objects.length;g++){const I=this._objects[g];I.position.y+=Math.sin(e+g*.5)*.005,I.rotateY(.002)}}};let ol=Aj;B(ol,"_active",null),B(ol,"_requestInFlight",!1);const bg=iA("debugwebxr"),jQA=iA("stats");function WQA(i){let A=null;const e=i;return e.getAROverlayContainer?A=e.getAROverlayContainer():A=i,A}ZQA();async function ZQA(){var i;if(iA("debugasap")){let A=globalThis["needle:XRSession"];if(A instanceof Promise){delete globalThis["needle:XRSession"],Qt.addContextCreatedCallback(async e=>{if(!A)return;ac(!0);const g=await A;if(g){const I=me.getDefaultSessionInit("immersive-vr");me.setSession("immersive-vr",g,I,e.context)}else console.error("NeedleXRSession: ASAP session was rejected");A=void 0});return}}if("xr"in navigator){if(/WebXRViewer\//i.test(navigator.userAgent)){console.warn("WebXRViewer does not support addEventListener");return}(i=navigator.xr)==null||i.addEventListener("sessiongranted",async()=>{ac(!0),console.log("Received Session Granted..."),await Vn(100);const A=sessionStorage.getItem("needle_xr_session_mode"),e=sessionStorage.getItem("needle_xr_session_init")??null,g=e?JSON.parse(e):null;let I=null;if(ej()&&(await ol.start(A||"immersive-vr",g||me.getDefaultSessionInit("immersive-vr")),await XQA(),I=await ol.handoff()),I)me.setSession(I.mode,I.session,I.init,Ke.Current);else if(A&&e){console.log("Session Granted: Restore last session");const o=JSON.parse(e);me.start(A,o).catch(s=>console.warn(s))}else me.start("immersive-vr").catch(o=>console.warn("Session Granted failed:",o))},{once:!0})}}function zQA(i,A){sessionStorage.setItem("needle_xr_session_mode",i),sessionStorage.setItem("needle_xr_session_init",JSON.stringify(A))}function VQA(){sessionStorage.removeItem("needle_xr_session_mode"),sessionStorage.removeItem("needle_xr_session_init")}const tb=new Set;Qt.registerCallback(Mt.ContextCreationStart,async i=>{tb.add(i.context)}),Qt.registerCallback(Mt.ContextCreated,async i=>{tb.delete(i.context)});function ej(){return tb.size>0}function XQA(){return new Promise(i=>{const A=Date.now(),e=setInterval(()=>{(!ej()||Date.now()-A>6e4)&&(clearInterval(e),i())},100)})}bQ()&&se()&&window.addEventListener("keydown",i=>{(i.key==="x"||i.key==="Escape")&&me.active&&me.stop()});const nB=class{constructor(i,A,e,g){B(this,"context"),B(this,"session"),B(this,"mode"),B(this,"controllers",[]),B(this,"_rigScale",1),B(this,"_lastRigScaleUpdate",-1),B(this,"_rigs",[]),B(this,"_viewerHitTestSource",null),B(this,"_defaultRig"),B(this,"_xr_scripts"),B(this,"_xr_update_scripts",[]),B(this,"_inactive_scripts",[]),B(this,"_controllerAdded"),B(this,"_controllerRemoved"),B(this,"_originalCameraWorldPosition"),B(this,"_originalCameraWorldRotation"),B(this,"_originalCameraWorldScale"),B(this,"_originalCameraParent"),B(this,"_mainCamera",null),B(this,"onRendererSessionSet",()=>{var s;this.running&&(this.context.renderer.xr.enabled=!0,this.context.renderer.xr.updateCamera(this.context.mainCamera),(s=this.context.mainCameraComponent)==null||s.applyClearFlags())}),B(this,"onInputSourceAdded",s=>{if(s.targetRayMode==="screen")return;let n=0;for(let r=0;r<this.session.inputSources.length;r++)if(this.session.inputSources[r]===s){n=r;break}if(this.controllers.find(r=>r.inputSource===s)){console.warn("Controller already exists for input source",n);return}bg&&console.log("Adding controller",n);const a=new RK(this,s,n);this._newControllers.push(a)}),B(this,"_ended",!1),B(this,"_newControllers",[]),B(this,"onEnd",s=>{var n,a,r;if(this._ended)return;this._ended=!0,bg&&console.log("XR Session ended"),VQA(),this.onAfterRender(),this.revertCustomForward(),this._didStart=!1,this._previousCameraParent=null,IB(this.onBefore,Xt.LateUpdate);const C=this.context.pre_render_callbacks.indexOf(this.onBeforeRender);C>=0&&this.context.pre_render_callbacks.splice(C,1);const Q=this.context.post_render_callbacks.indexOf(this.onAfterRender);Q>=0&&this.context.post_render_callbacks.splice(Q,1),this.context.xr=null,this.context.renderer.xr.enabled=!1,this.context.pre_update_oneshot_callbacks.push(()=>{var h;(h=this.context.mainCameraComponent)==null||h.applyClearFlags()}),D4({session:this});for(const h of nB._xrEndListeners)h({xr:this});for(let h=0;h<this.controllers.length;h++)this.disconnectInputSource(this.controllers[h].inputSource);for(const h of this._xr_scripts)(n=h?.onLeaveXR)==null||n.call(h,{xr:this});(a=this.sync)==null||a.onExitXR(this),this.context.mainCamera&&((r=this._originalCameraParent)==null||r.add(this.context.mainCamera),this._originalCameraWorldPosition&&pg(this.context.mainCamera,this._originalCameraWorldPosition),this._originalCameraWorldRotation&&us(this.context.mainCamera,this._originalCameraWorldRotation),this._originalCameraWorldScale&&nc(this.context.mainCamera,this._originalCameraWorldScale)),this.context.requestSizeUpdate(),this._defaultRig.gameObject.removeFromParent(),ac(!1)}),B(this,"_didStart",!1),B(this,"onBefore",s=>{var n,a,r,C,Q,h,E,c;const l=s.xrFrame;if(!l)return;this.context.xr=this,this.context.mainCameraComponent&&this.context.mainCameraComponent!==this._mainCamera&&(this._mainCamera=this.context.mainCameraComponent),((n=this.rig)==null?void 0:n.isActive)==!1&&(bg&&console.warn("Latest rig is not active - trying to activate a different rig",this.rig),this.updateActiveXRRig()),this.rig&&(a=this._mainCamera)!=null&&a.gameObject&&((C=(r=this._mainCamera)==null?void 0:r.gameObject)==null?void 0:C.parent)!==this.rig.gameObject&&this.rig.gameObject.add((Q=this._mainCamera)==null?void 0:Q.gameObject),this.internalUpdateState(),this.applyCustomForward();const d={xr:this};if(this._didStart){if(this.context.new_scripts_xr.length>0){const u=[...this.context.new_scripts_xr];for(let D=0;D<u.length;D++){const p=this.context.new_scripts_xr[D];if(!p||p.destroyed||((h=p.supportsXR)==null?void 0:h.call(p,this.mode))==!1){this.context.new_scripts_xr.splice(D,1);continue}if(!p.activeAndEnabled){this.context.new_scripts_xr.splice(D,1),this.markInactive(p);continue}if(this.addScript(p)){this.invokeCallback_EnterXR(p);for(const w of this.controllers)this.invokeCallback_ControllerAdded(p,w)}}}}else{if(this._didStart=!0,this.mode==="immersive-vr"){const D=$n(this.context.scene.children);if(D){const p=D.getSize(lt());if(p.length()>0){const w=this._defaultRig.gameObject;w.position.set(D.min.x+p.x*.5,D.min.y,D.max.z+p.z*.5+1.5);const f=D.getCenter(lt());f.y=w.position.y,w.lookAt(f)}}}p4({session:this});for(const D of nB._xrStartListeners)D(d);const u=[...this._xr_scripts];bg&&console.log("NeedleXRSession start, handle scripts:",u);for(const D of u){if(D.destroyed){this._script_to_remove.push(D);continue}if(!D.activeAndEnabled){this.markInactive(D);continue}this.invokeCallback_EnterXR(D);for(const p of this.controllers)this.invokeCallback_ControllerAdded(D,p)}}this.syncCameraCullingMask();for(const u of this.controllers)u.onUpdate(l);if(this._newControllers.length>0){const u=[...this._newControllers];this._newControllers.length=0;for(const D of u)if(D.connected){this.controllers.push(D);for(const p of this._xr_scripts){if(p.destroyed){this._script_to_remove.push(p);continue}p.activeAndEnabled!==!1&&this.invokeCallback_ControllerAdded(p,D)}}this.controllers.sort((D,p)=>D.index-p.index)}for(const u of this._xr_update_scripts){if(u.destroyed===!0){this._script_to_remove.push(u);continue}if(u.activeAndEnabled===!1){this.markInactive(u);continue}u.onUpdateXR&&u.onUpdateXR(d)}if(this.handleInactiveScripts(),this._script_to_remove.length>0){const u=[...new Set(this._script_to_remove)];this._script_to_remove.length=0;for(const D of u)!D.destroyed&&this.running&&((E=D.onLeaveXR)==null||E.call(D,d)),this.removeScript(D)}(c=this.sync)==null||c.onUpdate(this),this.onRenderDebug()}),B(this,"onBeforeRender",()=>{this.context.mainCamera&&this.updateFade(this.context.mainCamera)}),B(this,"onAfterRender",()=>{if(this.onUpdateFade_PostRender(),bQ()){const s=this.context.renderer;if(s.xr.isPresenting&&this.context.mainCamera){const n=s.xr.enabled,a=s.getRenderTarget();s.xr.enabled=!1,s.setRenderTarget(null),s.render(this.context.scene,this.context.mainCamera),s.xr.enabled=n,s.setRenderTarget(a)}}}),B(this,"_script_to_remove",[]),B(this,"_camera"),B(this,"_cameraRenderParent",new wA().rotateY(Math.PI)),B(this,"_previousCameraParent"),B(this,"_customforward",!0),B(this,"originalCameraNearPlane"),B(this,"_viewerPose"),B(this,"_transformOrientation",new GA),B(this,"_transformPosition",new S),B(this,"_transition");var I,o;zQA(i,g.init),this.session=A,this.mode=i,this.context=e,(bg||iA("console"))&&ac(!0),this._xr_scripts=[...g.scripts],this._xr_update_scripts=this._xr_scripts.filter(s=>typeof s.onUpdateXR=="function"),this._controllerAdded=g.controller_added,this._controllerRemoved=g.controller_removed,gB(this.onBefore,Xt.LateUpdate),this.context.pre_render_callbacks.push(this.onBeforeRender),this.context.post_render_callbacks.push(this.onAfterRender),((I=g.init.optionalFeatures)!=null&&I.includes("hit-test")||(o=g.init.requiredFeatures)!=null&&o.includes("hit-test"))&&A.requestReferenceSpace("viewer").then(s=>{var n,a;return(a=(n=A.requestHitTestSource)==null?void 0:n.call(A,{space:s}))==null?void 0:a.then(r=>this._viewerHitTestSource=r)}).catch(s=>console.warn(s)),this.context.mainCamera&&(this._originalCameraWorldPosition=Fe(this.context.mainCamera,new S),this._originalCameraWorldRotation=Nt(this.context.mainCamera,new GA),this._originalCameraWorldScale=zt(this.context.mainCamera,new S),this._originalCameraParent=this.context.mainCamera.parent),this._defaultRig=new eQA,this.context.scene.add(this._defaultRig.gameObject),this.addRig(this._defaultRig);for(let s=0;s<A.inputSources.length;s++){const n=A.inputSources[s];if(!n.handedness){console.warn("Input source in xr session has no handedness - ignoring",s);continue}this.onInputSourceAdded(n)}this.session.addEventListener("end",this.onEnd),this.session.addEventListener("inputsourceschange",s=>{for(const n of s.removed)this.disconnectInputSource(n);for(const n of s.added)this.onInputSourceAdded(n)}),this.context.xr=this,this.context.renderer.xr.setSession(this.session).then(this.onRendererSessionSet)}static getXRSync(i){return this._sync||(this._sync=new X3(i)),this._sync}static get currentSessionRequest(){return this._currentSessionRequestMode}static get active(){return this._activeSession}static get activeMode(){var i;return((i=this._activeSession)==null?void 0:i.mode)??null}static get xrSystem(){return"xr"in navigator?navigator.xr:void 0}static isXRSupported(){return Promise.all([this.isVRSupported(),this.isARSupported()]).then(i=>i.some(A=>A)).catch(()=>!1)}static isVRSupported(){return this.isSessionSupported("immersive-vr")}static isARSupported(){return this.isSessionSupported("immersive-ar")}static isSessionSupported(i){var A;return((A=this.xrSystem)==null?void 0:A.isSessionSupported(i).catch(e=>(bg&&console.error(e),!1)))??Promise.resolve(!1)}static onSessionRequestStart(i){this._sessionRequestStartListeners.push(i)}static offSessionRequestStart(i){const A=this._sessionRequestStartListeners.indexOf(i);A>=0&&this._sessionRequestStartListeners.splice(A,1)}static onSessionRequestEnd(i){this._sessionRequestEndListeners.push(i)}static offSessionRequestEnd(i){const A=this._sessionRequestEndListeners.indexOf(i);A>=0&&this._sessionRequestEndListeners.splice(A,1)}static onXRSessionStart(i){this._xrStartListeners.push(i)}static offXRSessionStart(i){const A=this._xrStartListeners.indexOf(i);A>=0&&this._xrStartListeners.splice(A,1)}static onXRSessionEnd(i){this._xrEndListeners.push(i)}static offXRSessionEnd(i){const A=this._xrEndListeners.indexOf(i);A>=0&&this._xrEndListeners.splice(A,1)}static onControllerAdded(i){this._controllerAddedListeners.push(i)}static offControllerAdded(i){const A=this._controllerAddedListeners.indexOf(i);A>=0&&this._controllerAddedListeners.splice(A,1)}static onControllerRemoved(i){this._controllerRemovedListeners.push(i)}static offControllerRemoved(i){const A=this._controllerRemovedListeners.indexOf(i);A>=0&&this._controllerRemovedListeners.splice(A,1)}static offerSession(i,A,e){return"xr"in navigator&&navigator.xr&&"offerSession"in navigator.xr?(typeof navigator.xr.offerSession=="function"&&(console.log("WebXR offerSession is available - requesting mode: "+i),A=="default"&&(A=this.getDefaultSessionInit(i)),navigator.xr.offerSession(i,{...A}).then(g=>nB.setSession(i,g,A,e)).catch(g=>{console.log("XRSession offer rejected (perhaps because another call to offerSession was made or a call to requestSession was made)")})),!0):!1}static getDefaultSessionInit(i){switch(i){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",i),{}}}static async start(i,A,e){var g,I,o,s;if(se()&&iA("debugxrpreroom"))return console.warn("Debug: Starting temporary XR session"),await ol.start(i,A||nB.getDefaultSessionInit(i)),null;if(this._currentSessionRequest)return console.warn("A XRSession is already being requested"),(bg||se())&&Lt("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(e||(e=Ke.Current),e||(e=Qt.All[0]),!e)throw new Error("No Needle Engine Context found");switch(A||(A={}),i){case"immersive-ar":{if(await((g=this.xrSystem)==null?void 0:g.isSessionSupported("immersive-ar"))!==!0)return console.error(i+" is not supported by this browser."),null;const r=this.getDefaultSessionInit(i),C=WQA(e.domElement);C&&!T0()&&(r.domOverlay={root:C},r.optionalFeatures.push("dom-overlay")),A={...r,...A}}break;case"immersive-vr":{if(await((I=this.xrSystem)==null?void 0:I.isSessionSupported("immersive-vr"))!==!0)return console.error(i+" is not supported by this browser."),null;A={...this.getDefaultSessionInit(i),...A}}break;default:console.warn("No default session init for mode",i);break}A.optionalFeatures??(A.optionalFeatures=[]),A.requiredFeatures??(A.requiredFeatures=[]),await ol.stop();const n=i=="immersive-ar"?e.scripts_immersive_ar:e.scripts_immersive_vr;bg?console.log(`%cRequesting ${i} session`,"font-weight:bold;",A,n):console.log(`%cRequesting ${i} session`,"font-weight:bold;");for(const r of n)r.onBeforeXR&&r.onBeforeXR(i,A);for(const r of this._sessionRequestStartListeners)r({mode:i,init:A});bg&&Ci("Requesting "+i+" session ("+Date.now()+")"),this._currentSessionRequest=(o=navigator.xr)==null?void 0:o.requestSession(i,A),this._currentSessionRequestMode=i;const a=await((s=this._currentSessionRequest)==null?void 0:s.catch(r=>{console.error(r,"Code: "+r.code),r.code===9&&Lt("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:"&&Lt("XR requires a secure connection (HTTPS)")}));this._currentSessionRequest=void 0,this._currentSessionRequestMode=null;for(const r of this._sessionRequestEndListeners)r({mode:i,init:A,newSession:a||null});return a?this.setSession(i,a,A,e):(console.warn("XR Session request was rejected"),null)}static setSession(i,A,e,g){if(this._activeSession)return console.error("A XRSession is already running"),this._activeSession;const I=i=="immersive-ar"?g.scripts_immersive_ar:g.scripts_immersive_vr;return this._activeSession=new nB(i,A,g,{scripts:I,controller_added:this._controllerAddedListeners,controller_removed:this._controllerRemovedListeners,init:e}),A.addEventListener("end",this.onEnd),bg?console.log(`%cStarted ${i} session`,"font-weight:bold;",I):console.log(`%cStarted ${i} session`,"font-weight:bold;"),this._activeSession}static stop(){var i;(i=this._activeSession)==null||i.end()}get sync(){return nB._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(i=>i.isLeft)}get rightController(){return this.controllers.find(i=>i.isRight)}getController(i){return typeof i=="number"?this.controllers[i]||null:this.controllers.find(A=>A.side===i)||null}get isPassThrough(){return!!(this.environmentBlendMode!=="opaque"&&this.interactionMode==="world-space"||this.mode==="immersive-ar"&&this.environmentBlendMode!=="opaque"&&this.controllers.some(i=>i.inputSource.targetRayMode==="tracked-pointer")||se()&&bQ()&&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 i=this.frame.getImageTrackingResults();for(const A of i)if(A.trackingState==="tracked")return!0}catch{return!1}return!1}get rig(){const i=this._rigs[0]??null;return i!=null&&i.gameObject&&lh(i.gameObject)||i?.isActive===!1?(this.updateActiveXRRig(),this._rigs[0]??null):i}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(i){this._rigs.indexOf(i)>=0||(i.priority===void 0&&(i.priority=0),this._rigs.push(i),this.updateActiveXRRig())}removeRig(i){const A=this._rigs.indexOf(i);A!==-1&&(this._rigs.splice(A,1),this.updateActiveXRRig())}setRigActive(i){const A=this._rigs.indexOf(i);this._rigs.splice(A,1),this._rigs.unshift(i),this.updateActiveXRRig()}updateActiveXRRig(){const i=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 A=this._rigs[0];A&&A.priority===void 0&&(A.priority=0);for(let e=1;e<this._rigs.length;e++){const g=this._rigs[e];if(g.isActive){if(lh(g.gameObject)){this._rigs.splice(e,1),e--;continue}(!A||A.isActive===!1||g.priority!==void 0&&g.priority>A.priority)&&(A=g)}}if(i!==A){const e=this._rigs.indexOf(A);e>=0&&this._rigs.splice(e,1),this._rigs.unshift(A)}bg&&(i===A?console.log("Updated Active XR Rig:",A,"prev:",i):console.log("Updated Active XRRig:",A," (the same as before)"))}getHitTest(i){if(i)return this.getControllerHitTest(i);if(!this._viewerHitTestSource)return null;const A=this._viewerHitTestSource,e=this.frame.getHitTestResults(A);if(e.length>0){const g=e[0];return this.convertHitTestResult(g)}return null}getControllerHitTest(i){const A=i.hitTestSource;if(!A)return null;const e=this.frame.getHitTestResultsForTransientInput(A);for(const g of e)if(g.inputSource===i.inputSource)for(const I of g.results)return this.convertHitTestResult(I);return null}convertHitTestResult(i){const A=this.context.renderer.xr.getReferenceSpace(),e=A&&i.getPose(A);if(e){const g=lt(e.transform.position),I=_Q(e.transform.orientation),o=this.context.mainCamera;if(o?.parent!==this._cameraRenderParent&&g.applyMatrix4(JS),o!=null&&o.parent){g.applyMatrix4(o.parent.matrixWorld),I.multiply(vs);const s=Nt(o.parent);s.premultiply(vs),I.premultiply(s)}return{hit:i,position:g,quaternion:I}}return null}convertSpace(i){const A=lt(i.position);A.applyMatrix4(JS);const e=_Q(i.orientation);return e.premultiply(vs),{position:A,quaternion:e}}disconnectInputSource(i){const A=(e,g,I)=>{if(e.inputSource===i){bg&&console.log("Disconnecting controller",e.index),this.controllers.splice(I,1),this.invokeControllerEvent(e,this._controllerRemoved,"removed");const o={xr:this,controller:e,change:"removed"};for(const s of this._xr_scripts)s.onXRControllerRemoved&&s.onXRControllerRemoved(o);e.onDisconnected()}};for(let e=this.controllers.length-1;e>=0;e--){const g=this.controllers[e];A(g,this.controllers,e)}for(let e=this._newControllers.length-1;e>=0;e--){const g=this._newControllers[e];A(g,this._newControllers,e)}}end(){this._ended||this.session.end().catch(i=>console.warn(i))}onRenderDebug(){if(bg)for(const i of this.controllers)i.onRenderDebug();if((bg||jQA)&&this.rig){const i=this.rig.gameObject.worldPosition,A=this.rig.gameObject.worldForward;i.add(A.multiplyScalar(1.5));const e=this.rig.gameObject.worldUp;i.add(e.multiplyScalar(2.5));let g="";if(g+=this.context.time.smoothedFps.toFixed(1),bg)for(const I of this.controllers)g+=`
5235
+ `+a.href)}this.onSendQueued(mn.OnRoomJoin);break;case"left-room":A.room===this.currentRoomName&&(this._isInRoom=!1,this._currentRoomName=null,this._currentInRoom.length=0);break;case"user-joined-room":if(A.data){const n=A.data;this._currentInRoom.push(n.userId),so&&console.log(n.userId+" joined","now in room:",this._currentInRoom)}break;case"user-left-room":if(A.data){const n=A.data,a=this._currentInRoom.indexOf(n.userId);a>=0&&(so&&console.log(n.userId+" left","now in room:",this._currentInRoom),this._currentInRoom.splice(a,1)),n.userId===this.connectionId&&console.log("you left the room")}break;case"all-room-state-deleted":so&&console.log("RECEIVED all-room-state-deleted"),this._state={};break;case"ping":case"pong":const s=(e=A.data)==null?void 0:e.time;s&&(this._currentDelay=this.context.time.time-s),so&&console.log("Current latency: "+this._currentDelay.toFixed(4)+" sec","Clients in room: "+((g=this._currentInRoom)==null?void 0:g.length));break}const I=A.data;I&&(this._state[I.guid]=I);let o=this._listeners[A.key];if(o){o=[...o];for(const s of o)try{s(A.data)}catch(n){console.error('Error invoking callback for "'+A.key+'"',n)}}}toMessage(A,e){return{key:A,data:e}}sendWithWebsocket(A,e,g=mn.OnRoomJoin){if(!this._ws){const o=this._waitingForSocket[g]||[];o.push(()=>this.sendWithWebsocket(A,e,g)),this._waitingForSocket[g]=o;return}const I=JSON.stringify(this.toMessage(A,e));so&&console.log(">>",A),this._ws.send(I)}onSendQueued(A){const e=this._waitingForSocket[A];if(e){for(const g of e)g();e.length=0}}}const xp=iA("debugwebxr");class eb{constructor(A,e){B(this,"controllerStates",[]),B(this,"userId"),B(this,"context"),B(this,"userStateEvtName"),B(this,"onReceivedControllerState",g=>{xp&&console.log(`XRSync: Received change for ${this.userId}: ${g.type} ${g.handedness}; tracked=${g.isTracking}`);let I=!1;for(let o=0;o<this.controllerStates.length;o++)if(this.controllerStates[o].index===g.index){this.controllerStates[o]=g,I=!0;break}I||this.controllerStates.push(g)}),this.userId=A,this.context=e,this.userStateEvtName="xr-sync-user-state-"+A,this.context.connection.beginListen(this.userStateEvtName,this.onReceivedControllerState)}dispose(){this.context.connection.stopListen(this.userStateEvtName,this.onReceivedControllerState)}update(A){if(this.context.connection.isConnected!=!1){for(let e=this.controllerStates.length-1;e>=0;e--){const g=this.controllerStates[e];let I=!1;for(let o=0;o<A.controllers.length;o++)A.controllers[o].index===g.index&&(I=!0);I||(xp&&console.log(`XRSync: ${g.type} ${g.handedness} removed`,g.index),this.controllerStates.splice(e,1),this.sendControllerRemoved(g))}for(const e of A.controllers)this.updateControllerStates(e)}}onExitXR(A){for(const e of this.controllerStates)this.sendControllerRemoved(e);this.controllerStates.length=0}sendControllerRemoved(A){A.isTracking=!1,A.guid="",this.context.connection.send(this.userStateEvtName,A),this.context.connection.sendDeleteRemoteState(A.guid)}updateControllerStates(A){const e=this.controllerStates.find(g=>g.index===A.index);if(e){let g=!1;g||(g=e.isTracking!=A.isTracking),g&&(e.isTracking=A.isTracking,this.context.connection.send(this.userStateEvtName,e))}else{const g={guid:this.userId+"-"+A.index,isTracking:A.isTracking,handedness:A.side,index:A.index,type:A.hand?"hand":"controller"};this.controllerStates.push(g),this.context.connection.send(this.userStateEvtName,g),xp&&console.log(`XRSync: ${g.type} ${g.handedness} added`,g.index)}}}class X3{constructor(A){B(this,"context"),B(this,"onJoinedRoom",()=>{if(this.context.connection.connectionId){this._states.has(this.context.connection.connectionId)||(xp&&console.log("XRSync: Local user joined room",this.context.connection.connectionId),this._states.set(this.context.connection.connectionId,new eb(this.context.connection.connectionId,this.context)));for(const e of this.context.connection.usersInRoom())this._states.has(e)||this._states.set(e,new eb(e,this.context))}}),B(this,"onLeftRoom",()=>{if(this.context.connection.connectionId&&!this._states.has(this.context.connection.connectionId)){const e=this._states.get(this.context.connection.connectionId);e?.dispose(),this._states.delete(this.context.connection.connectionId)}}),B(this,"onOtherUserJoinedRoom",e=>{const g=e.userId;this._states.has(g)||(xp&&console.log("XRSync: Remote user joined room",g),this._states.set(g,new eb(g,this.context)))}),B(this,"onOtherUserLeftRoom",e=>{const g=e.userId;if(!this._states.has(g)){const I=this._states.get(g);I?.dispose(),this._states.delete(g)}}),B(this,"_states",new Map),this.context=A,this.context.connection.beginListen(Pe.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(Pe.LeftRoom,this.onLeftRoom),this.context.connection.beginListen(Pe.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.beginListen(Pe.UserLeftRoom,this.onOtherUserLeftRoom)}hasState(A){return A?this._states.has(A):!1}isTracking(A,e){if(!A)return;const g=this._states.get(A);if(!g)return;const I=g.controllerStates.find(o=>o.handedness===e);return I?.isTracking||!1}getDeviceType(A,e){if(!A)return;const g=this._states.get(A);if(!g)return;const I=g.controllerStates.find(o=>o.handedness===e);return I?.type||"unknown"}destroy(){this.context.connection.stopListen(Pe.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(Pe.LeftRoom,this.onLeftRoom),this.context.connection.stopListen(Pe.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.stopListen(Pe.UserLeftRoom,this.onOtherUserLeftRoom)}onUpdate(A){if(this.context.connection.isConnected&&this.context.connection.connectionId){const e=this._states.get(this.context.connection.connectionId);e?.update(A)}}onExitXR(A){if(this.context.connection.isConnected&&this.context.connection.connectionId){const e=this._states.get(this.context.connection.connectionId);e?.onExitXR(A)}}}class $3{constructor(){B(this,"_fadeToColorQuad"),B(this,"_fadeToColorMaterial"),B(this,"_requestedFadeValue",0),B(this,"_transitionPromise",null),B(this,"_transitionResolve",null),this._fadeToColorMaterial=new tt({color:0,transparent:!0,depthTest:!1,fog:!1,side:yt}),this._fadeToColorQuad=new dA(new Qg(10,10),this._fadeToColorMaterial)}dispose(){this._fadeToColorQuad.geometry.dispose(),this._fadeToColorMaterial.dispose()}update(A,e){const g=this._fadeToColorQuad,I=this._fadeToColorMaterial;g.parent!==A&&I.opacity>0?A.add(g):I.opacity===0&&g.removeFromParent(),g.layers.set(2),g.material=this._fadeToColorMaterial,g.position.z=-1,g.renderOrder=1/0;const o=this._requestedFadeValue;I.opacity=ge.lerp(I.opacity,o,e/.03),Math.abs(I.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 A=new Promise(e=>{this._transitionResolve=e});return this._transitionPromise=A,A}}var ch=(i=>(i[i.Quad=0]="Quad",i[i.Cube=1]="Cube",i[i.Sphere=2]="Sphere",i))(ch||{});class qp{static createPrimitive(A,e){let g;switch(A){case"Quad":case 0:{const I=new Qg(1,1,1,1),o=e?.material??new MI({color:16777215});e!=null&&e.texture&&"map"in o&&(o.map=e.texture),g=new dA(I,o)}break;case"Cube":case 1:{const I=new Ai(1,1,1),o=e?.material??new MI({color:16777215});e!=null&&e.texture&&"map"in o&&(o.map=e.texture),g=new dA(I,o)}break;case"Sphere":case 2:{const I=new Vs(.5,16,16),o=e?.material??new MI({color:16777215});e!=null&&e.texture&&"map"in o&&(o.map=e.texture),g=new dA(I,o)}break}return this.applyDefaultObjectOptions(g,e),g}static createSprite(A){const e=new zy({color:16777215});A!=null&&A.texture&&"map"in e&&(e.map=A.texture);const g=new WR(e);return this.applyDefaultObjectOptions(g,A),g}static applyDefaultObjectOptions(A,e){e!=null&&e.name&&(A.name=e.name),e!=null&&e.position&&A.position.set(e.position.x,e.position.y,e.position.z),e!=null&&e.rotation&&A.rotation.set(e.rotation.x,e.rotation.y,e.rotation.z),e!=null&&e.scale&&A.scale.set(e.scale.x,e.scale.y,e.scale.z)}}const Aj=class{constructor(i,A,e){B(this,"_session"),B(this,"_mode"),B(this,"_init"),B(this,"_renderer"),B(this,"_camera"),B(this,"_scene"),B(this,"onEnd",()=>{var g;(g=this._session)==null||g.removeEventListener("end",this.onEnd),this._renderer.setAnimationLoop(null),this._renderer.dispose(),this._scene.clear()}),B(this,"_lastTime",0),B(this,"onFrame",(g,I)=>{const o=g-this._lastTime;this.update(g,o),this._camera.parent!==this._scene&&this._scene.add(this._camera),this._renderer.render(this._scene,this._camera)}),B(this,"_objects",[]),this._mode=i,this._init=A,this._session=e,this._session.addEventListener("end",this.onEnd),this._renderer=new sr({alpha:!0}),this._renderer.setAnimationLoop(this.onFrame),this._renderer.xr.setSession(e),this._renderer.xr.enabled=!0,this._camera=new xe,this._scene=new Vg,this._scene.fog=new Zy(4473924,10,250),this._scene.add(this._camera),this.setupScene()}static get active(){return this._active}static async start(i,A){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(!A)return console.error("XRSessionInit must be provided"),null;this._requestInFlight=!0;const e=await navigator.xr.requestSession(i,A);return e.addEventListener("end",()=>{this._active=null}),this._requestInFlight?(this._requestInFlight=!1,this._active=new Aj(i,A,e),this._active):(e.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 Vn(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 i={session:this._session,mode:this._mode,init:this._init};return await this.onBeforeHandoff(),this.onEnd(),this._session=null,i}async onBeforeHandoff(){await Vn(1e3),this._scene.clear()}setupScene(){this._scene.background=new fA(0),this._scene.add(new F0(5,10,1118481,1118481));const i=new GQ(16777215,1);i.position.set(0,20,0),i.castShadow=!1,this._scene.add(i);const A=new GQ(16777215,1);A.position.set(0,-1,0),A.castShadow=!1,this._scene.add(A);const e=new MQ(16777215,1,100,1);e.position.set(0,2,0),e.castShadow=!1,e.distance=200,this._scene.add(e);const g=50;for(let I=0;I<100;I++){const o=new MI({color:2236962,metalness:1,roughness:.8});this.isAR&&(o.emissive=new fA(Math.random(),Math.random(),Math.random()),o.emissiveIntensity=Math.random());const s=ge.random(0,1)>.5?ch.Sphere:ch.Cube,n=qp.createPrimitive(s,{material:o});n.position.x=ge.random(-g,g),n.position.y=ge.random(-2,g),n.position.z=ge.random(-g,g),n.rotation.x=ge.random(0,Math.PI*2),n.rotation.y=ge.random(0,Math.PI*2),n.rotation.z=ge.random(0,Math.PI*2),n.scale.multiplyScalar(.5+Math.random()*10);const a=n.position.distanceTo(this._camera.position)-n.scale.x;a<1&&n.position.multiplyScalar(1+1/a),this._objects.push(n),this._scene.add(n)}}update(i,A){const e=i*4e-4;for(let g=0;g<this._objects.length;g++){const I=this._objects[g];I.position.y+=Math.sin(e+g*.5)*.005,I.rotateY(.002)}}};let ol=Aj;B(ol,"_active",null),B(ol,"_requestInFlight",!1);const bg=iA("debugwebxr"),jQA=iA("stats");function WQA(i){let A=null;const e=i;return e.getAROverlayContainer?A=e.getAROverlayContainer():A=i,A}ZQA();async function ZQA(){var i;if(iA("debugasap")){let A=globalThis["needle:XRSession"];if(A instanceof Promise){delete globalThis["needle:XRSession"],Qt.addContextCreatedCallback(async e=>{if(!A)return;ac(!0);const g=await A;if(g){const I=me.getDefaultSessionInit("immersive-vr");me.setSession("immersive-vr",g,I,e.context)}else console.error("NeedleXRSession: ASAP session was rejected");A=void 0});return}}if("xr"in navigator){if(/WebXRViewer\//i.test(navigator.userAgent)){console.warn("WebXRViewer does not support addEventListener");return}(i=navigator.xr)==null||i.addEventListener("sessiongranted",async()=>{ac(!0),console.log("Received Session Granted..."),await Vn(100);const A=sessionStorage.getItem("needle_xr_session_mode"),e=sessionStorage.getItem("needle_xr_session_init")??null,g=e?JSON.parse(e):null;let I=null;if(ej()&&(await ol.start(A||"immersive-vr",g||me.getDefaultSessionInit("immersive-vr")),await XQA(),I=await ol.handoff()),I)me.setSession(I.mode,I.session,I.init,Ke.Current);else if(A&&e){console.log("Session Granted: Restore last session");const o=JSON.parse(e);me.start(A,o).catch(s=>console.warn(s))}else me.start("immersive-vr").catch(o=>console.warn("Session Granted failed:",o))},{once:!0})}}function zQA(i,A){sessionStorage.setItem("needle_xr_session_mode",i),sessionStorage.setItem("needle_xr_session_init",JSON.stringify(A))}function VQA(){sessionStorage.removeItem("needle_xr_session_mode"),sessionStorage.removeItem("needle_xr_session_init")}const tb=new Set;Qt.registerCallback(Mt.ContextCreationStart,async i=>{tb.add(i.context)}),Qt.registerCallback(Mt.ContextCreated,async i=>{tb.delete(i.context)});function ej(){return tb.size>0}function XQA(){return new Promise(i=>{const A=Date.now(),e=setInterval(()=>{(!ej()||Date.now()-A>6e4)&&(clearInterval(e),i())},100)})}bQ()&&se()&&window.addEventListener("keydown",i=>{(i.key==="x"||i.key==="Escape")&&me.active&&me.stop()});const nB=class{constructor(i,A,e,g){B(this,"context"),B(this,"session"),B(this,"mode"),B(this,"controllers",[]),B(this,"_rigScale",1),B(this,"_lastRigScaleUpdate",-1),B(this,"_rigs",[]),B(this,"_viewerHitTestSource",null),B(this,"_defaultRig"),B(this,"_xr_scripts"),B(this,"_xr_update_scripts",[]),B(this,"_inactive_scripts",[]),B(this,"_controllerAdded"),B(this,"_controllerRemoved"),B(this,"_originalCameraWorldPosition"),B(this,"_originalCameraWorldRotation"),B(this,"_originalCameraWorldScale"),B(this,"_originalCameraParent"),B(this,"_mainCamera",null),B(this,"onRendererSessionSet",()=>{var s;this.running&&(this.context.renderer.xr.enabled=!0,this.context.renderer.xr.updateCamera(this.context.mainCamera),(s=this.context.mainCameraComponent)==null||s.applyClearFlags())}),B(this,"onInputSourceAdded",s=>{if(s.targetRayMode==="screen")return;let n=0;for(let r=0;r<this.session.inputSources.length;r++)if(this.session.inputSources[r]===s){n=r;break}if(this.controllers.find(r=>r.inputSource===s)){console.warn("Controller already exists for input source",n);return}bg&&console.log("Adding controller",n);const a=new RK(this,s,n);this._newControllers.push(a)}),B(this,"_ended",!1),B(this,"_newControllers",[]),B(this,"onEnd",s=>{var n,a,r;if(this._ended)return;this._ended=!0,bg&&console.log("XR Session ended"),VQA(),this.onAfterRender(),this.revertCustomForward(),this._didStart=!1,this._previousCameraParent=null,IB(this.onBefore,Xt.LateUpdate);const C=this.context.pre_render_callbacks.indexOf(this.onBeforeRender);C>=0&&this.context.pre_render_callbacks.splice(C,1);const Q=this.context.post_render_callbacks.indexOf(this.onAfterRender);Q>=0&&this.context.post_render_callbacks.splice(Q,1),this.context.xr=null,this.context.renderer.xr.enabled=!1,this.context.pre_update_oneshot_callbacks.push(()=>{var h;(h=this.context.mainCameraComponent)==null||h.applyClearFlags()}),D4({session:this});for(const h of nB._xrEndListeners)h({xr:this});for(let h=0;h<this.controllers.length;h++)this.disconnectInputSource(this.controllers[h].inputSource);for(const h of this._xr_scripts)(n=h?.onLeaveXR)==null||n.call(h,{xr:this});(a=this.sync)==null||a.onExitXR(this),this.context.mainCamera&&((r=this._originalCameraParent)==null||r.add(this.context.mainCamera),this._originalCameraWorldPosition&&pg(this.context.mainCamera,this._originalCameraWorldPosition),this._originalCameraWorldRotation&&us(this.context.mainCamera,this._originalCameraWorldRotation),this._originalCameraWorldScale&&nc(this.context.mainCamera,this._originalCameraWorldScale)),this.context.requestSizeUpdate(),this._defaultRig.gameObject.removeFromParent(),ac(!1)}),B(this,"_didStart",!1),B(this,"onBefore",s=>{var n,a,r,C,Q,h,E,c;const l=s.xrFrame;if(!l)return;this.context.xr=this,this.context.mainCameraComponent&&this.context.mainCameraComponent!==this._mainCamera&&(this._mainCamera=this.context.mainCameraComponent),((n=this.rig)==null?void 0:n.isActive)==!1&&(bg&&console.warn("Latest rig is not active - trying to activate a different rig",this.rig),this.updateActiveXRRig()),this.rig&&(a=this._mainCamera)!=null&&a.gameObject&&((C=(r=this._mainCamera)==null?void 0:r.gameObject)==null?void 0:C.parent)!==this.rig.gameObject&&this.rig.gameObject.add((Q=this._mainCamera)==null?void 0:Q.gameObject),this.internalUpdateState(),this.applyCustomForward();const d={xr:this};if(this._didStart){if(this.context.new_scripts_xr.length>0){const u=[...this.context.new_scripts_xr];for(let D=0;D<u.length;D++){const p=this.context.new_scripts_xr[D];if(!p||p.destroyed||((h=p.supportsXR)==null?void 0:h.call(p,this.mode))==!1){this.context.new_scripts_xr.splice(D,1);continue}if(!p.activeAndEnabled){this.context.new_scripts_xr.splice(D,1),this.markInactive(p);continue}if(this.addScript(p)){this.invokeCallback_EnterXR(p);for(const w of this.controllers)this.invokeCallback_ControllerAdded(p,w)}}}}else{if(this._didStart=!0,this.mode==="immersive-vr"){const D=$n(this.context.scene.children);if(D){const p=D.getSize(lt());if(p.length()>0){const w=this._defaultRig.gameObject;w.position.set(D.min.x+p.x*.5,D.min.y,D.max.z+p.z*.5+1.5);const f=D.getCenter(lt());f.y=w.position.y,w.lookAt(f)}}}p4({session:this});for(const D of nB._xrStartListeners)D(d);const u=[...this._xr_scripts];bg&&console.log("NeedleXRSession start, handle scripts:",u);for(const D of u){if(D.destroyed){this._script_to_remove.push(D);continue}if(!D.activeAndEnabled){this.markInactive(D);continue}this.invokeCallback_EnterXR(D);for(const p of this.controllers)this.invokeCallback_ControllerAdded(D,p)}}this.syncCameraCullingMask();for(const u of this.controllers)u.onUpdate(l);if(this._newControllers.length>0){const u=[...this._newControllers];this._newControllers.length=0;for(const D of u)if(D.connected){this.controllers.push(D);for(const p of this._xr_scripts){if(p.destroyed){this._script_to_remove.push(p);continue}p.activeAndEnabled!==!1&&this.invokeCallback_ControllerAdded(p,D)}}this.controllers.sort((D,p)=>D.index-p.index)}for(const u of this._xr_update_scripts){if(u.destroyed===!0){this._script_to_remove.push(u);continue}if(u.activeAndEnabled===!1){this.markInactive(u);continue}u.onUpdateXR&&u.onUpdateXR(d)}if(this.handleInactiveScripts(),this._script_to_remove.length>0){const u=[...new Set(this._script_to_remove)];this._script_to_remove.length=0;for(const D of u)!D.destroyed&&this.running&&((E=D.onLeaveXR)==null||E.call(D,d)),this.removeScript(D)}(c=this.sync)==null||c.onUpdate(this),this.onRenderDebug()}),B(this,"onBeforeRender",()=>{this.context.mainCamera&&this.updateFade(this.context.mainCamera)}),B(this,"onAfterRender",()=>{if(this.onUpdateFade_PostRender(),bQ()){const s=this.context.renderer;if(s.xr.isPresenting&&this.context.mainCamera){const n=s.xr.enabled,a=s.getRenderTarget();s.xr.enabled=!1,s.setRenderTarget(null),s.render(this.context.scene,this.context.mainCamera),s.xr.enabled=n,s.setRenderTarget(a)}}}),B(this,"_script_to_remove",[]),B(this,"_camera"),B(this,"_cameraRenderParent",new wA().rotateY(Math.PI)),B(this,"_previousCameraParent"),B(this,"_customforward",!0),B(this,"originalCameraNearPlane"),B(this,"_viewerPose"),B(this,"_transformOrientation",new GA),B(this,"_transformPosition",new S),B(this,"_transition");var I,o;zQA(i,g.init),this.session=A,this.mode=i,this.context=e,(bg||iA("console"))&&ac(!0),this._xr_scripts=[...g.scripts],this._xr_update_scripts=this._xr_scripts.filter(s=>typeof s.onUpdateXR=="function"),this._controllerAdded=g.controller_added,this._controllerRemoved=g.controller_removed,gB(this.onBefore,Xt.LateUpdate),this.context.pre_render_callbacks.push(this.onBeforeRender),this.context.post_render_callbacks.push(this.onAfterRender),((I=g.init.optionalFeatures)!=null&&I.includes("hit-test")||(o=g.init.requiredFeatures)!=null&&o.includes("hit-test"))&&A.requestReferenceSpace("viewer").then(s=>{var n,a;return(a=(n=A.requestHitTestSource)==null?void 0:n.call(A,{space:s}))==null?void 0:a.then(r=>this._viewerHitTestSource=r)}).catch(s=>console.warn(s)),this.context.mainCamera&&(this._originalCameraWorldPosition=Fe(this.context.mainCamera,new S),this._originalCameraWorldRotation=Nt(this.context.mainCamera,new GA),this._originalCameraWorldScale=zt(this.context.mainCamera,new S),this._originalCameraParent=this.context.mainCamera.parent),this._defaultRig=new eQA,this.context.scene.add(this._defaultRig.gameObject),this.addRig(this._defaultRig);for(let s=0;s<A.inputSources.length;s++){const n=A.inputSources[s];if(!n.handedness){console.warn("Input source in xr session has no handedness - ignoring",s);continue}this.onInputSourceAdded(n)}this.session.addEventListener("end",this.onEnd),this.session.addEventListener("inputsourceschange",s=>{for(const n of s.removed)this.disconnectInputSource(n);for(const n of s.added)this.onInputSourceAdded(n)}),this.context.xr=this,this.context.renderer.xr.setSession(this.session).then(this.onRendererSessionSet)}static getXRSync(i){return this._sync||(this._sync=new X3(i)),this._sync}static get currentSessionRequest(){return this._currentSessionRequestMode}static get active(){return this._activeSession}static get activeMode(){var i;return((i=this._activeSession)==null?void 0:i.mode)??null}static get xrSystem(){return"xr"in navigator?navigator.xr:void 0}static isXRSupported(){return Promise.all([this.isVRSupported(),this.isARSupported()]).then(i=>i.some(A=>A)).catch(()=>!1)}static isVRSupported(){return this.isSessionSupported("immersive-vr")}static isARSupported(){return this.isSessionSupported("immersive-ar")}static isSessionSupported(i){var A;return((A=this.xrSystem)==null?void 0:A.isSessionSupported(i).catch(e=>(bg&&console.error(e),!1)))??Promise.resolve(!1)}static onSessionRequestStart(i){this._sessionRequestStartListeners.push(i)}static offSessionRequestStart(i){const A=this._sessionRequestStartListeners.indexOf(i);A>=0&&this._sessionRequestStartListeners.splice(A,1)}static onSessionRequestEnd(i){this._sessionRequestEndListeners.push(i)}static offSessionRequestEnd(i){const A=this._sessionRequestEndListeners.indexOf(i);A>=0&&this._sessionRequestEndListeners.splice(A,1)}static onXRSessionStart(i){this._xrStartListeners.push(i)}static offXRSessionStart(i){const A=this._xrStartListeners.indexOf(i);A>=0&&this._xrStartListeners.splice(A,1)}static onXRSessionEnd(i){this._xrEndListeners.push(i)}static offXRSessionEnd(i){const A=this._xrEndListeners.indexOf(i);A>=0&&this._xrEndListeners.splice(A,1)}static onControllerAdded(i){this._controllerAddedListeners.push(i)}static offControllerAdded(i){const A=this._controllerAddedListeners.indexOf(i);A>=0&&this._controllerAddedListeners.splice(A,1)}static onControllerRemoved(i){this._controllerRemovedListeners.push(i)}static offControllerRemoved(i){const A=this._controllerRemovedListeners.indexOf(i);A>=0&&this._controllerRemovedListeners.splice(A,1)}static offerSession(i,A,e){return"xr"in navigator&&navigator.xr&&"offerSession"in navigator.xr?(typeof navigator.xr.offerSession=="function"&&(console.log("WebXR offerSession is available - requesting mode: "+i),A=="default"&&(A=this.getDefaultSessionInit(i)),navigator.xr.offerSession(i,{...A}).then(g=>nB.setSession(i,g,A,e)).catch(g=>{console.log("XRSession offer rejected (perhaps because another call to offerSession was made or a call to requestSession was made)")})),!0):!1}static getDefaultSessionInit(i){switch(i){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",i),{}}}static async start(i,A,e){var g,I,o,s;if(se()&&iA("debugxrpreroom"))return console.warn("Debug: Starting temporary XR session"),await ol.start(i,A||nB.getDefaultSessionInit(i)),null;if(this._currentSessionRequest)return console.warn("A XRSession is already being requested"),(bg||se())&&Lt("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(e||(e=Ke.Current),e||(e=Qt.All[0]),!e)throw new Error("No Needle Engine Context found");switch(A||(A={}),i){case"immersive-ar":{if(await((g=this.xrSystem)==null?void 0:g.isSessionSupported("immersive-ar"))!==!0)return console.error(i+" is not supported by this browser."),null;const r=this.getDefaultSessionInit(i),C=WQA(e.domElement);C&&!T0()&&(r.domOverlay={root:C},r.optionalFeatures.push("dom-overlay")),A={...r,...A}}break;case"immersive-vr":{if(await((I=this.xrSystem)==null?void 0:I.isSessionSupported("immersive-vr"))!==!0)return console.error(i+" is not supported by this browser."),null;A={...this.getDefaultSessionInit(i),...A}}break;default:console.warn("No default session init for mode",i);break}A.optionalFeatures??(A.optionalFeatures=[]),A.requiredFeatures??(A.requiredFeatures=[]),await ol.stop();const n=i=="immersive-ar"?e.scripts_immersive_ar:e.scripts_immersive_vr;bg?console.log(`%cRequesting ${i} session`,"font-weight:bold;",A,n):console.log(`%cRequesting ${i} session`,"font-weight:bold;");for(const r of n)r.onBeforeXR&&r.onBeforeXR(i,A);for(const r of this._sessionRequestStartListeners)r({mode:i,init:A});bg&&Ci("Requesting "+i+" session ("+Date.now()+")"),this._currentSessionRequest=(o=navigator.xr)==null?void 0:o.requestSession(i,A),this._currentSessionRequestMode=i;const a=await((s=this._currentSessionRequest)==null?void 0:s.catch(r=>{console.error(r,"Code: "+r.code),r.code===9&&Lt("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:"&&Lt("XR requires a secure connection (HTTPS)")}));this._currentSessionRequest=void 0,this._currentSessionRequestMode=null;for(const r of this._sessionRequestEndListeners)r({mode:i,init:A,newSession:a||null});return a?this.setSession(i,a,A,e):(console.warn("XR Session request was rejected"),null)}static setSession(i,A,e,g){if(this._activeSession)return console.error("A XRSession is already running"),this._activeSession;const I=i=="immersive-ar"?g.scripts_immersive_ar:g.scripts_immersive_vr;return this._activeSession=new nB(i,A,g,{scripts:I,controller_added:this._controllerAddedListeners,controller_removed:this._controllerRemovedListeners,init:e}),A.addEventListener("end",this.onEnd),bg?console.log(`%cStarted ${i} session`,"font-weight:bold;",I):console.log(`%cStarted ${i} session`,"font-weight:bold;"),this._activeSession}static stop(){var i;(i=this._activeSession)==null||i.end()}get sync(){return nB._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(i=>i.isLeft)}get rightController(){return this.controllers.find(i=>i.isRight)}getController(i){return typeof i=="number"?this.controllers[i]||null:this.controllers.find(A=>A.side===i)||null}get isPassThrough(){return!!(this.environmentBlendMode!=="opaque"&&this.interactionMode==="world-space"||this.mode==="immersive-ar"&&this.environmentBlendMode!=="opaque"&&this.controllers.some(i=>i.inputSource.targetRayMode==="tracked-pointer")||se()&&bQ()&&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 i=this.frame.getImageTrackingResults();for(const A of i)if(A.trackingState==="tracked")return!0}catch{return!1}return!1}get rig(){const i=this._rigs[0]??null;return i!=null&&i.gameObject&&lh(i.gameObject)||i?.isActive===!1?(this.updateActiveXRRig(),this._rigs[0]??null):i}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(i){this._rigs.indexOf(i)>=0||(i.priority===void 0&&(i.priority=0),this._rigs.push(i),this.updateActiveXRRig())}removeRig(i){const A=this._rigs.indexOf(i);A!==-1&&(this._rigs.splice(A,1),this.updateActiveXRRig())}setRigActive(i){const A=this._rigs.indexOf(i);this._rigs.splice(A,1),this._rigs.unshift(i),this.updateActiveXRRig()}updateActiveXRRig(){const i=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 A=this._rigs[0];A&&A.priority===void 0&&(A.priority=0);for(let e=1;e<this._rigs.length;e++){const g=this._rigs[e];if(g.isActive){if(lh(g.gameObject)){this._rigs.splice(e,1),e--;continue}(!A||A.isActive===!1||g.priority!==void 0&&g.priority>A.priority)&&(A=g)}}if(i!==A){const e=this._rigs.indexOf(A);e>=0&&this._rigs.splice(e,1),this._rigs.unshift(A)}bg&&(i===A?console.log("Updated Active XR Rig:",A,"prev:",i):console.log("Updated Active XRRig:",A," (the same as before)"))}getHitTest(i){if(i)return this.getControllerHitTest(i);if(!this._viewerHitTestSource)return null;const A=this._viewerHitTestSource,e=this.frame.getHitTestResults(A);if(e.length>0){const g=e[0];return this.convertHitTestResult(g)}return null}getControllerHitTest(i){const A=i.hitTestSource;if(!A)return null;const e=this.frame.getHitTestResultsForTransientInput(A);for(const g of e)if(g.inputSource===i.inputSource)for(const I of g.results)return this.convertHitTestResult(I);return null}convertHitTestResult(i){const A=this.context.renderer.xr.getReferenceSpace(),e=A&&i.getPose(A);if(e){const g=lt(e.transform.position),I=_Q(e.transform.orientation),o=this.context.mainCamera;if(o?.parent!==this._cameraRenderParent&&g.applyMatrix4(JS),o!=null&&o.parent){g.applyMatrix4(o.parent.matrixWorld),I.multiply(vs);const s=Nt(o.parent);s.premultiply(vs),I.premultiply(s)}return{hit:i,position:g,quaternion:I}}return null}convertSpace(i){const A=lt(i.position);A.applyMatrix4(JS);const e=_Q(i.orientation);return e.premultiply(vs),{position:A,quaternion:e}}disconnectInputSource(i){const A=(e,g,I)=>{if(e.inputSource===i){bg&&console.log("Disconnecting controller",e.index),this.controllers.splice(I,1),this.invokeControllerEvent(e,this._controllerRemoved,"removed");const o={xr:this,controller:e,change:"removed"};for(const s of this._xr_scripts)s.onXRControllerRemoved&&s.onXRControllerRemoved(o);e.onDisconnected()}};for(let e=this.controllers.length-1;e>=0;e--){const g=this.controllers[e];A(g,this.controllers,e)}for(let e=this._newControllers.length-1;e>=0;e--){const g=this._newControllers[e];A(g,this._newControllers,e)}}end(){this._ended||this.session.end().catch(i=>console.warn(i))}onRenderDebug(){if(bg)for(const i of this.controllers)i.onRenderDebug();if((bg||jQA)&&this.rig){const i=this.rig.gameObject.worldPosition,A=this.rig.gameObject.worldForward;i.add(A.multiplyScalar(1.5));const e=this.rig.gameObject.worldUp;i.add(e.multiplyScalar(2.5));let g="";if(g+=this.context.time.smoothedFps.toFixed(1),bg)for(const I of this.controllers)g+=`
5236
5236
  ${I.hand?"hand":"ctrl"} ${I.inputSource.handedness}[${I.index}] con:${I.connected} tr:${I.isTracking}`;pe.DrawLabel(i,g)}}addScript(i){return this._xr_scripts.includes(i)?!1:(bg&&console.log("Register new XRScript",i),this._xr_scripts.push(i),typeof i.onUpdateXR=="function"&&this._xr_update_scripts.push(i),!0)}markInactive(i){if(!(this._inactive_scripts.indexOf(i)>=0)){this.removeScript(i,!1),this._inactive_scripts.push(i);for(const A of this.controllers)this.invokeCallback_ControllerRemoved(i,A);this.invokeCallback_LeaveXR(i)}}handleInactiveScripts(){if(this._inactive_scripts.length>0)for(let i=this._inactive_scripts.length-1;i>=0;i--){const A=this._inactive_scripts[i];if(A.activeAndEnabled){this._inactive_scripts.splice(i,1),this.addScript(A),this.invokeCallback_EnterXR(A);for(const e of this.controllers)this.invokeCallback_ControllerAdded(A,e)}}}removeScript(i,A=!0){bg&&console.log("Remove XRScript",i);const e=this._xr_scripts.indexOf(i);e>=0&&this._xr_scripts.splice(e,1);const g=this._xr_update_scripts.indexOf(i);if(g>=0&&this._xr_update_scripts.splice(g,1),A){const I=this._inactive_scripts.indexOf(i);I>=0&&this._inactive_scripts.splice(I,1)}}invokeCallback_EnterXR(i){i.onEnterXR&&i.onEnterXR({xr:this})}invokeCallback_ControllerAdded(i,A){i.onXRControllerAdded&&i.onXRControllerAdded({xr:this,controller:A,change:"added"})}invokeCallback_ControllerRemoved(i,A){i.onXRControllerRemoved&&i.onXRControllerRemoved({xr:this,controller:A,change:"removed"})}invokeCallback_LeaveXR(i){i.onLeaveXR&&!i.destroyed&&i.onLeaveXR({xr:this})}syncCameraCullingMask(){var i;const A=this.context.xrCamera,e=(i=this.context.mainCameraComponent)==null?void 0:i.cullingMask;if(A&&e!==void 0){for(const g of A.cameras)g.layers.mask=e;A.layers.mask=e}else if(A){for(const g of A.cameras)g.layers.enableAll();A.layers.enableAll()}}invokeControllerEvent(i,A,e){for(let g=A.length-1;g>=0;g--){const I=A[g];if(I)try{I({xr:this,controller:i,change:e})}catch(o){console.error(o)}}}applyCustomForward(){var i;if(this.context.mainCamera&&this._customforward){this._camera=this.context.mainCamera,this._camera.parent!==this._cameraRenderParent&&(this._previousCameraParent=this._camera.parent,(i=this._previousCameraParent)==null||i.add(this._cameraRenderParent)),this._cameraRenderParent.name="XR Camera Render Parent",this._cameraRenderParent.add(this._camera);let A=.02;if(this.rig){const e=zt(this.rig.gameObject);A*=e.x}this._camera instanceof xe&&this._camera.near>A&&(this.originalCameraNearPlane=this._camera.near,this._camera.near=A)}}revertCustomForward(){this._camera&&this._previousCameraParent&&this._previousCameraParent.add(this._camera),this._previousCameraParent=null,this._camera instanceof xe&&this.originalCameraNearPlane!=null&&(this._camera.near=this.originalCameraNearPlane)}internalUpdateState(){const i=this.context.renderer.xr.getReferenceSpace();if(!i){this._viewerPose=void 0;return}if(this._viewerPose=this.frame.getViewerPose(i),this._viewerPose){const A=this._viewerPose.transform;this._transformPosition.set(A.position.x,A.position.y,A.position.z),this._transformOrientation.set(A.orientation.x,A.orientation.y,A.orientation.z,A.orientation.w)}}get transition(){return this._transition||(this._transition=new $3),this._transition}fadeTransition(){return this._transition||(this._transition=new $3),this._transition.fadeTransition()}updateFade(i){this._transition&&i instanceof xe&&this._transition.update(i,this.context.time.deltaTime)}onUpdateFade_PostRender(){var i;(i=this._transition)==null||i.remove()}};let me=nB;B(me,"_sync",null),B(me,"_currentSessionRequestMode",null),B(me,"_currentSessionRequest"),B(me,"_activeSession"),B(me,"_sessionRequestStartListeners",[]),B(me,"_sessionRequestEndListeners",[]),B(me,"_xrStartListeners",[]),B(me,"_xrEndListeners",[]),B(me,"_controllerAddedListeners",[]),B(me,"_controllerRemovedListeners",[]),B(me,"onEnd",()=>{bg&&console.log("XR Session ended"),nB._activeSession=null});const ib=iA("debugwebxr");class tj{static tryFindAvatarObjects(A,e,g){if(g.head&&g.leftHand&&g.rightHand)return;const I=A.name.toLocaleLowerCase();!g.head&&I.includes("head")&&(ib&&console.log("FOUND AVATAR HEAD",A.name),g.head=new gt("",e,A)),I.includes("hand")&&(!g.leftHand&&I.includes("left")&&(ib&&console.log("FOUND AVATAR LEFT HAND",A.name),g.leftHand=new gt("",e,A)),!g.rightHand&&I.includes("right")&&(ib&&console.log("FOUND AVATAR RIGHT HAND",A.name),g.rightHand=new gt("",e,A)));for(let o=0;o<A.children.length;o++){if(g.head&&g.leftHand&&g.rightHand)return;const s=A.children[o];this.tryFindAvatarObjects(s,e,g)}}}var VS=(i=>(i.Visible="application-visible",i.Hidden="application-hidden",i.MuteChanged="application-mutechanged",i))(VS||{});let XS=!1;const sl=[];function nl(){if(XS)return;se()&&console.debug("User interaction registered: audio can now be played"),XS=!0;const i=[...sl];sl.length=0,i.forEach(A=>A())}document.addEventListener("pointerdown",nl),document.addEventListener("click",nl),document.addEventListener("dragstart",nl),document.addEventListener("touchstart",nl),document.addEventListener("keydown",nl),me.onXRSessionStart(()=>{nl()});const ij=class extends EventTarget{constructor(i){super(),B(this,"_mute",!1),B(this,"context"),B(this,"_isVisible",!0),this.context=i,window.addEventListener("visibilitychange",this.onVisiblityChanged.bind(this),!1)}static get userInteractionRegistered(){return XS}static registerWaitForInteraction(i){if(i!==null){if(XS){i();return}sl.indexOf(i)===-1&&sl.push(i)}}static unregisterWaitForInteraction(i){const A=sl.indexOf(i);A!==-1&&sl.splice(A,1)}get muted(){return this._mute}set muted(i){i!==this._mute&&(this._mute=i,this.dispatchEvent(new Event("application-mutechanged")))}get hasFocus(){return document.hasFocus()}get isVisible(){return this._isVisible}onVisiblityChanged(i){switch(i.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 aB=ij;B(aB,"registerWaitForAllowAudio",ij.registerWaitForInteraction);function*gj(i,A=null){const e=A?A.time:Ke.Current.time,g=e.time;for(;e.time-g<i;)yield}function*$QA(i){for(let A=0;A<i;A++)yield}function*Ij(i){let A=!0;for(i.then(()=>A=!1),i.catch(()=>A=!1);A;)yield}class Lp extends yU{constructor(A){super(A),this.type=cg}parse(A){const e=Math.pow(2.7182818,2.2);function g(m,F){let T=0;for(let L=0;L<65536;++L)(L==0||m[L>>3]&1<<(L&7))&&(F[T++]=L);const tA=T-1;for(;T<65536;)F[T++]=0;return tA}function I(m){for(let F=0;F<16384;F++)m[F]={},m[F].len=0,m[F].lit=0,m[F].p=null}const o={l:0,c:0,lc:0};function s(m,F,T,tA,L){for(;T<m;)F=F<<8|W(tA,L),T+=8;T-=m,o.l=F>>T&(1<<m)-1,o.c=F,o.lc=T}const n=new Array(59);function a(m){for(let T=0;T<=58;++T)n[T]=0;for(let T=0;T<65537;++T)n[m[T]]+=1;let F=0;for(let T=58;T>0;--T){const tA=F+n[T]>>1;n[T]=F,F=tA}for(let T=0;T<65537;++T){const tA=m[T];tA>0&&(m[T]=tA|n[tA]++<<6)}}function r(m,F,T,tA,L,V){const j=F;let CA=0,QA=0;for(;tA<=L;tA++){if(j.value-F.value>T)return!1;s(6,CA,QA,m,j);const SA=o.l;if(CA=o.c,QA=o.lc,V[tA]=SA,SA==63){if(j.value-F.value>T)throw new Error("Something wrong with hufUnpackEncTable");s(8,CA,QA,m,j);let vA=o.l+6;if(CA=o.c,QA=o.lc,tA+vA>L+1)throw new Error("Something wrong with hufUnpackEncTable");for(;vA--;)V[tA++]=0;tA--}else if(SA>=59){let vA=SA-59+2;if(tA+vA>L+1)throw new Error("Something wrong with hufUnpackEncTable");for(;vA--;)V[tA++]=0;tA--}}a(V)}function C(m){return m&63}function Q(m){return m>>6}function h(m,F,T,tA){for(;F<=T;F++){const L=Q(m[F]),V=C(m[F]);if(L>>V)throw new Error("Invalid table entry");if(V>14){const j=tA[L>>V-14];if(j.len)throw new Error("Invalid table entry");if(j.lit++,j.p){const CA=j.p;j.p=new Array(j.lit);for(let QA=0;QA<j.lit-1;++QA)j.p[QA]=CA[QA]}else j.p=new Array(1);j.p[j.lit-1]=F}else if(V){let j=0;for(let CA=1<<14-V;CA>0;CA--){const QA=tA[(L<<14-V)+j];if(QA.len||QA.p)throw new Error("Invalid table entry");QA.len=V,QA.lit=F,j++}}}return!0}const E={c:0,lc:0};function c(m,F,T,tA){m=m<<8|W(T,tA),F+=8,E.c=m,E.lc=F}const l={c:0,lc:0};function d(m,F,T,tA,L,V,j,CA,QA){if(m==F){tA<8&&(c(T,tA,L,V),T=E.c,tA=E.lc),tA-=8;let SA=T>>tA;if(SA=new Uint8Array([SA])[0],CA.value+SA>QA)return!1;const vA=j[CA.value-1];for(;SA-- >0;)j[CA.value++]=vA}else if(CA.value<QA)j[CA.value++]=m;else return!1;l.c=T,l.lc=tA}function u(m){return m&65535}function D(m){const F=u(m);return F>32767?F-65536:F}const p={a:0,b:0};function w(m,F){const T=D(m),tA=D(F),L=T+(tA&1)+(tA>>1),V=L,j=L-tA;p.a=V,p.b=j}function f(m,F){const T=u(m),tA=u(F),L=T-(tA>>1)&65535,V=tA+L-32768&65535;p.a=V,p.b=L}function G(m,F,T,tA,L,V,j){const CA=j<16384,QA=T>L?L:T;let SA=1,vA,ZA;for(;SA<=QA;)SA<<=1;for(SA>>=1,vA=SA,SA>>=1;SA>=1;){ZA=0;const WA=ZA+V*(L-vA),$A=V*SA,le=V*vA,oe=tA*SA,ye=tA*vA;let $e,Ht,ni,Sg;for(;ZA<=WA;ZA+=le){let qt=ZA;const Ct=ZA+tA*(T-vA);for(;qt<=Ct;qt+=ye){const Yi=qt+oe,ho=qt+$A,Ag=ho+oe;CA?(w(m[qt+F],m[ho+F]),$e=p.a,ni=p.b,w(m[Yi+F],m[Ag+F]),Ht=p.a,Sg=p.b,w($e,Ht),m[qt+F]=p.a,m[Yi+F]=p.b,w(ni,Sg),m[ho+F]=p.a,m[Ag+F]=p.b):(f(m[qt+F],m[ho+F]),$e=p.a,ni=p.b,f(m[Yi+F],m[Ag+F]),Ht=p.a,Sg=p.b,f($e,Ht),m[qt+F]=p.a,m[Yi+F]=p.b,f(ni,Sg),m[ho+F]=p.a,m[Ag+F]=p.b)}if(T&SA){const Yi=qt+$A;CA?w(m[qt+F],m[Yi+F]):f(m[qt+F],m[Yi+F]),$e=p.a,m[Yi+F]=p.b,m[qt+F]=$e}}if(L&SA){let qt=ZA;const Ct=ZA+tA*(T-vA);for(;qt<=Ct;qt+=ye){const Yi=qt+oe;CA?w(m[qt+F],m[Yi+F]):f(m[qt+F],m[Yi+F]),$e=p.a,m[Yi+F]=p.b,m[qt+F]=$e}}vA=SA,SA>>=1}return ZA}function M(m,F,T,tA,L,V,j,CA,QA){let SA=0,vA=0;const ZA=j,WA=Math.trunc(tA.value+(L+7)/8);for(;tA.value<WA;)for(c(SA,vA,T,tA),SA=E.c,vA=E.lc;vA>=14;){const le=SA>>vA-14&16383,oe=F[le];if(oe.len)vA-=oe.len,d(oe.lit,V,SA,vA,T,tA,CA,QA,ZA),SA=l.c,vA=l.lc;else{if(!oe.p)throw new Error("hufDecode issues");let ye;for(ye=0;ye<oe.lit;ye++){const $e=C(m[oe.p[ye]]);for(;vA<$e&&tA.value<WA;)c(SA,vA,T,tA),SA=E.c,vA=E.lc;if(vA>=$e&&Q(m[oe.p[ye]])==(SA>>vA-$e&(1<<$e)-1)){vA-=$e,d(oe.p[ye],V,SA,vA,T,tA,CA,QA,ZA),SA=l.c,vA=l.lc;break}}if(ye==oe.lit)throw new Error("hufDecode issues")}}const $A=8-L&7;for(SA>>=$A,vA-=$A;vA>0;){const le=F[SA<<14-vA&16383];if(le.len)vA-=le.len,d(le.lit,V,SA,vA,T,tA,CA,QA,ZA),SA=l.c,vA=l.lc;else throw new Error("hufDecode issues")}return!0}function U(m,F,T,tA,L,V){const j={value:0},CA=T.value,QA=uA(F,T),SA=uA(F,T);T.value+=4;const vA=uA(F,T);if(T.value+=4,QA<0||QA>=65537||SA<0||SA>=65537)throw new Error("Something wrong with HUF_ENCSIZE");const ZA=new Array(65537),WA=new Array(16384);I(WA);const $A=tA-(T.value-CA);if(r(m,T,$A,QA,SA,ZA),vA>8*(tA-(T.value-CA)))throw new Error("Something wrong with hufUncompress");h(ZA,QA,SA,WA),M(ZA,WA,m,T,vA,SA,V,L,j)}function v(m,F,T){for(let tA=0;tA<T;++tA)F[tA]=m[F[tA]]}function k(m){for(let F=1;F<m.length;F++){const T=m[F-1]+m[F]-128;m[F]=T}}function N(m,F){let T=0,tA=Math.floor((m.length+1)/2),L=0;const V=m.length-1;for(;!(L>V||(F[L++]=m[T++],L>V));)F[L++]=m[tA++]}function _(m){let F=m.byteLength;const T=new Array;let tA=0;const L=new DataView(m);for(;F>0;){const V=L.getInt8(tA++);if(V<0){const j=-V;F-=j+1;for(let CA=0;CA<j;CA++)T.push(L.getUint8(tA++))}else{const j=V;F-=2;const CA=L.getUint8(tA++);for(let QA=0;QA<j+1;QA++)T.push(CA)}}return T}function H(m,F,T,tA,L,V){let j=new DataView(V.buffer);const CA=T[m.idx[0]].width,QA=T[m.idx[0]].height,SA=3,vA=Math.floor(CA/8),ZA=Math.ceil(CA/8),WA=Math.ceil(QA/8),$A=CA-(ZA-1)*8,le=QA-(WA-1)*8,oe={value:0},ye=new Array(SA),$e=new Array(SA),Ht=new Array(SA),ni=new Array(SA),Sg=new Array(SA);for(let Ct=0;Ct<SA;++Ct)Sg[Ct]=F[m.idx[Ct]],ye[Ct]=Ct<1?0:ye[Ct-1]+ZA*WA,$e[Ct]=new Float32Array(64),Ht[Ct]=new Uint16Array(64),ni[Ct]=new Uint16Array(ZA*64);for(let Ct=0;Ct<WA;++Ct){let Yi=8;Ct==WA-1&&(Yi=le);let ho=8;for(let q=0;q<ZA;++q){q==ZA-1&&(ho=$A);for(let IA=0;IA<SA;++IA)Ht[IA].fill(0),Ht[IA][0]=L[ye[IA]++],J(oe,tA,Ht[IA]),P(Ht[IA],$e[IA]),b($e[IA]);x($e);for(let IA=0;IA<SA;++IA)Y($e[IA],ni[IA],q*64)}let Ag=0;for(let q=0;q<SA;++q){const IA=T[m.idx[q]].type;for(let lA=8*Ct;lA<8*Ct+Yi;++lA){Ag=Sg[q][lA];for(let pA=0;pA<vA;++pA){const BA=pA*64+(lA&7)*8;j.setUint16(Ag+0*2*IA,ni[q][BA+0],!0),j.setUint16(Ag+1*2*IA,ni[q][BA+1],!0),j.setUint16(Ag+2*2*IA,ni[q][BA+2],!0),j.setUint16(Ag+3*2*IA,ni[q][BA+3],!0),j.setUint16(Ag+4*2*IA,ni[q][BA+4],!0),j.setUint16(Ag+5*2*IA,ni[q][BA+5],!0),j.setUint16(Ag+6*2*IA,ni[q][BA+6],!0),j.setUint16(Ag+7*2*IA,ni[q][BA+7],!0),Ag+=8*2*IA}}if(vA!=ZA)for(let lA=8*Ct;lA<8*Ct+Yi;++lA){const pA=Sg[q][lA]+8*vA*2*IA,BA=vA*64+(lA&7)*8;for(let Ae=0;Ae<ho;++Ae)j.setUint16(pA+Ae*2*IA,ni[q][BA+Ae],!0)}}}const qt=new Uint16Array(CA);j=new DataView(V.buffer);for(let Ct=0;Ct<SA;++Ct){T[m.idx[Ct]].decoded=!0;const Yi=T[m.idx[Ct]].type;if(T[Ct].type==2)for(let ho=0;ho<QA;++ho){const Ag=Sg[Ct][ho];for(let q=0;q<CA;++q)qt[q]=j.getUint16(Ag+q*2*Yi,!0);for(let q=0;q<CA;++q)j.setFloat32(Ag+q*2*Yi,yA(qt[q]),!0)}}}function J(m,F,T){let tA,L=1;for(;L<64;)tA=F[m.value],tA==65280?L=64:tA>>8==255?L+=tA&255:(T[L]=tA,L++),m.value++}function P(m,F){F[0]=yA(m[0]),F[1]=yA(m[1]),F[2]=yA(m[5]),F[3]=yA(m[6]),F[4]=yA(m[14]),F[5]=yA(m[15]),F[6]=yA(m[27]),F[7]=yA(m[28]),F[8]=yA(m[2]),F[9]=yA(m[4]),F[10]=yA(m[7]),F[11]=yA(m[13]),F[12]=yA(m[16]),F[13]=yA(m[26]),F[14]=yA(m[29]),F[15]=yA(m[42]),F[16]=yA(m[3]),F[17]=yA(m[8]),F[18]=yA(m[12]),F[19]=yA(m[17]),F[20]=yA(m[25]),F[21]=yA(m[30]),F[22]=yA(m[41]),F[23]=yA(m[43]),F[24]=yA(m[9]),F[25]=yA(m[11]),F[26]=yA(m[18]),F[27]=yA(m[24]),F[28]=yA(m[31]),F[29]=yA(m[40]),F[30]=yA(m[44]),F[31]=yA(m[53]),F[32]=yA(m[10]),F[33]=yA(m[19]),F[34]=yA(m[23]),F[35]=yA(m[32]),F[36]=yA(m[39]),F[37]=yA(m[45]),F[38]=yA(m[52]),F[39]=yA(m[54]),F[40]=yA(m[20]),F[41]=yA(m[22]),F[42]=yA(m[33]),F[43]=yA(m[38]),F[44]=yA(m[46]),F[45]=yA(m[51]),F[46]=yA(m[55]),F[47]=yA(m[60]),F[48]=yA(m[21]),F[49]=yA(m[34]),F[50]=yA(m[37]),F[51]=yA(m[47]),F[52]=yA(m[50]),F[53]=yA(m[56]),F[54]=yA(m[59]),F[55]=yA(m[61]),F[56]=yA(m[35]),F[57]=yA(m[36]),F[58]=yA(m[48]),F[59]=yA(m[49]),F[60]=yA(m[57]),F[61]=yA(m[58]),F[62]=yA(m[62]),F[63]=yA(m[63])}function b(m){const F=.5*Math.cos(.7853975),T=.5*Math.cos(3.14159/16),tA=.5*Math.cos(3.14159/8),L=.5*Math.cos(3*3.14159/16),V=.5*Math.cos(5*3.14159/16),j=.5*Math.cos(3*3.14159/8),CA=.5*Math.cos(7*3.14159/16),QA=new Array(4),SA=new Array(4),vA=new Array(4),ZA=new Array(4);for(let WA=0;WA<8;++WA){const $A=WA*8;QA[0]=tA*m[$A+2],QA[1]=j*m[$A+2],QA[2]=tA*m[$A+6],QA[3]=j*m[$A+6],SA[0]=T*m[$A+1]+L*m[$A+3]+V*m[$A+5]+CA*m[$A+7],SA[1]=L*m[$A+1]-CA*m[$A+3]-T*m[$A+5]-V*m[$A+7],SA[2]=V*m[$A+1]-T*m[$A+3]+CA*m[$A+5]+L*m[$A+7],SA[3]=CA*m[$A+1]-V*m[$A+3]+L*m[$A+5]-T*m[$A+7],vA[0]=F*(m[$A+0]+m[$A+4]),vA[3]=F*(m[$A+0]-m[$A+4]),vA[1]=QA[0]+QA[3],vA[2]=QA[1]-QA[2],ZA[0]=vA[0]+vA[1],ZA[1]=vA[3]+vA[2],ZA[2]=vA[3]-vA[2],ZA[3]=vA[0]-vA[1],m[$A+0]=ZA[0]+SA[0],m[$A+1]=ZA[1]+SA[1],m[$A+2]=ZA[2]+SA[2],m[$A+3]=ZA[3]+SA[3],m[$A+4]=ZA[3]-SA[3],m[$A+5]=ZA[2]-SA[2],m[$A+6]=ZA[1]-SA[1],m[$A+7]=ZA[0]-SA[0]}for(let WA=0;WA<8;++WA)QA[0]=tA*m[16+WA],QA[1]=j*m[16+WA],QA[2]=tA*m[48+WA],QA[3]=j*m[48+WA],SA[0]=T*m[8+WA]+L*m[24+WA]+V*m[40+WA]+CA*m[56+WA],SA[1]=L*m[8+WA]-CA*m[24+WA]-T*m[40+WA]-V*m[56+WA],SA[2]=V*m[8+WA]-T*m[24+WA]+CA*m[40+WA]+L*m[56+WA],SA[3]=CA*m[8+WA]-V*m[24+WA]+L*m[40+WA]-T*m[56+WA],vA[0]=F*(m[WA]+m[32+WA]),vA[3]=F*(m[WA]-m[32+WA]),vA[1]=QA[0]+QA[3],vA[2]=QA[1]-QA[2],ZA[0]=vA[0]+vA[1],ZA[1]=vA[3]+vA[2],ZA[2]=vA[3]-vA[2],ZA[3]=vA[0]-vA[1],m[0+WA]=ZA[0]+SA[0],m[8+WA]=ZA[1]+SA[1],m[16+WA]=ZA[2]+SA[2],m[24+WA]=ZA[3]+SA[3],m[32+WA]=ZA[3]-SA[3],m[40+WA]=ZA[2]-SA[2],m[48+WA]=ZA[1]-SA[1],m[56+WA]=ZA[0]-SA[0]}function x(m){for(let F=0;F<64;++F){const T=m[0][F],tA=m[1][F],L=m[2][F];m[0][F]=T+1.5747*L,m[1][F]=T-.1873*tA-.4682*L,m[2][F]=T+1.8556*tA}}function Y(m,F,T){for(let tA=0;tA<64;++tA)F[T+tA]=QQ.toHalfFloat(X(m[tA]))}function X(m){return m<=1?Math.sign(m)*Math.pow(Math.abs(m),2.2):Math.sign(m)*Math.pow(e,Math.abs(m)-1)}function $(m){return new DataView(m.array.buffer,m.offset.value,m.size)}function aA(m){const F=m.viewer.buffer.slice(m.offset.value,m.offset.value+m.size),T=new Uint8Array(_(F)),tA=new Uint8Array(T.length);return k(T),N(T,tA),new DataView(tA.buffer)}function kA(m){const F=m.array.slice(m.offset.value,m.offset.value+m.size),T=ap(F),tA=new Uint8Array(T.length);return k(T),N(T,tA),new DataView(tA.buffer)}function JA(m){const F=m.viewer,T={value:m.offset.value},tA=new Uint16Array(m.width*m.scanlineBlockSize*(m.channels*m.type)),L=new Uint8Array(8192);let V=0;const j=new Array(m.channels);for(let le=0;le<m.channels;le++)j[le]={},j[le].start=V,j[le].end=j[le].start,j[le].nx=m.width,j[le].ny=m.lines,j[le].size=m.type,V+=j[le].nx*j[le].ny*j[le].size;const CA=te(F,T),QA=te(F,T);if(QA>=8192)throw new Error("Something is wrong with PIZ_COMPRESSION BITMAP_SIZE");if(CA<=QA)for(let le=0;le<QA-CA+1;le++)L[le+CA]=TA(F,T);const SA=new Uint16Array(65536),vA=g(L,SA),ZA=uA(F,T);U(m.array,F,T,ZA,tA,V);for(let le=0;le<m.channels;++le){const oe=j[le];for(let ye=0;ye<j[le].size;++ye)G(tA,oe.start+ye,oe.nx,oe.size,oe.ny,oe.nx*oe.size,vA)}v(SA,tA,V);let WA=0;const $A=new Uint8Array(tA.buffer.byteLength);for(let le=0;le<m.lines;le++)for(let oe=0;oe<m.channels;oe++){const ye=j[oe],$e=ye.nx*ye.size,Ht=new Uint8Array(tA.buffer,ye.end*2,$e*2);$A.set(Ht,WA),WA+=$e*2,ye.end+=$e}return new DataView($A.buffer)}function sA(m){const F=m.array.slice(m.offset.value,m.offset.value+m.size),T=ap(F),tA=m.lines*m.channels*m.width,L=m.type==1?new Uint16Array(tA):new Uint32Array(tA);let V=0,j=0;const CA=new Array(4);for(let QA=0;QA<m.lines;QA++)for(let SA=0;SA<m.channels;SA++){let vA=0;switch(m.type){case 1:CA[0]=V,CA[1]=CA[0]+m.width,V=CA[1]+m.width;for(let ZA=0;ZA<m.width;++ZA){const WA=T[CA[0]++]<<8|T[CA[1]++];vA+=WA,L[j]=vA,j++}break;case 2:CA[0]=V,CA[1]=CA[0]+m.width,CA[2]=CA[1]+m.width,V=CA[2]+m.width;for(let ZA=0;ZA<m.width;++ZA){const WA=T[CA[0]++]<<24|T[CA[1]++]<<16|T[CA[2]++]<<8;vA+=WA,L[j]=vA,j++}break}}return new DataView(L.buffer)}function mA(m){const F=m.viewer,T={value:m.offset.value},tA=new Uint8Array(m.width*m.lines*(m.channels*m.type*2)),L={version:NA(F,T),unknownUncompressedSize:NA(F,T),unknownCompressedSize:NA(F,T),acCompressedSize:NA(F,T),dcCompressedSize:NA(F,T),rleCompressedSize:NA(F,T),rleUncompressedSize:NA(F,T),rleRawSize:NA(F,T),totalAcUncompressedCount:NA(F,T),totalDcUncompressedCount:NA(F,T),acCompression:NA(F,T)};if(L.version<2)throw new Error("EXRLoader.parse: "+Ve.compression+" version "+L.version+" is unsupported");const V=new Array;let j=te(F,T)-2;for(;j>0;){const oe=FA(F.buffer,T),ye=TA(F,T),$e=ye>>2&3,Ht=(ye>>4)-1,ni=new Int8Array([Ht])[0],Sg=TA(F,T);V.push({name:oe,index:ni,type:Sg,compression:$e}),j-=oe.length+3}const CA=Ve.channels,QA=new Array(m.channels);for(let oe=0;oe<m.channels;++oe){const ye=QA[oe]={},$e=CA[oe];ye.name=$e.name,ye.compression=0,ye.decoded=!1,ye.type=$e.pixelType,ye.pLinear=$e.pLinear,ye.width=m.width,ye.height=m.lines}const SA={idx:new Array(3)};for(let oe=0;oe<m.channels;++oe){const ye=QA[oe];for(let $e=0;$e<V.length;++$e){const Ht=V[$e];ye.name==Ht.name&&(ye.compression=Ht.compression,Ht.index>=0&&(SA.idx[Ht.index]=oe),ye.offset=oe)}}let vA,ZA,WA;if(L.acCompressedSize>0)switch(L.acCompression){case 0:vA=new Uint16Array(L.totalAcUncompressedCount),U(m.array,F,T,L.acCompressedSize,vA,L.totalAcUncompressedCount);break;case 1:const oe=m.array.slice(T.value,T.value+L.totalAcUncompressedCount),ye=ap(oe);vA=new Uint16Array(ye.buffer),T.value+=L.totalAcUncompressedCount;break}if(L.dcCompressedSize>0){const oe={array:m.array,offset:T,size:L.dcCompressedSize};ZA=new Uint16Array(kA(oe).buffer),T.value+=L.dcCompressedSize}if(L.rleRawSize>0){const oe=m.array.slice(T.value,T.value+L.rleCompressedSize),ye=ap(oe);WA=_(ye.buffer),T.value+=L.rleCompressedSize}let $A=0;const le=new Array(QA.length);for(let oe=0;oe<le.length;++oe)le[oe]=new Array;for(let oe=0;oe<m.lines;++oe)for(let ye=0;ye<QA.length;++ye)le[ye].push($A),$A+=QA[ye].width*m.type*2;H(SA,le,QA,vA,ZA,tA);for(let oe=0;oe<QA.length;++oe){const ye=QA[oe];if(!ye.decoded)switch(ye.compression){case 2:let $e=0,Ht=0;for(let ni=0;ni<m.lines;++ni){let Sg=le[oe][$e];for(let qt=0;qt<ye.width;++qt){for(let Ct=0;Ct<2*ye.type;++Ct)tA[Sg++]=WA[Ht+Ct*ye.width*ye.height];Ht++}$e++}break;case 1:default:throw new Error("EXRLoader.parse: unsupported channel compression")}}return new DataView(tA.buffer)}function FA(m,F){const T=new Uint8Array(m);let tA=0;for(;T[F.value+tA]!=0;)tA+=1;const L=new TextDecoder().decode(T.slice(F.value,F.value+tA));return F.value=F.value+tA+1,L}function XA(m,F,T){const tA=new TextDecoder().decode(new Uint8Array(m).slice(F.value,F.value+T));return F.value=F.value+T,tA}function ee(m,F){const T=ae(m,F),tA=uA(m,F);return[T,tA]}function xA(m,F){const T=uA(m,F),tA=uA(m,F);return[T,tA]}function ae(m,F){const T=m.getInt32(F.value,!0);return F.value=F.value+4,T}function uA(m,F){const T=m.getUint32(F.value,!0);return F.value=F.value+4,T}function W(m,F){const T=m[F.value];return F.value=F.value+1,T}function TA(m,F){const T=m.getUint8(F.value);return F.value=F.value+1,T}const NA=function(m,F){let T;return"getBigInt64"in DataView.prototype?T=Number(m.getBigInt64(F.value,!0)):T=m.getUint32(F.value+4,!0)+Number(m.getUint32(F.value,!0)<<32),F.value+=8,T};function UA(m,F){const T=m.getFloat32(F.value,!0);return F.value+=4,T}function PA(m,F){return QQ.toHalfFloat(UA(m,F))}function yA(m){const F=(m&31744)>>10,T=m&1023;return(m>>15?-1:1)*(F?F===31?T?NaN:1/0:Math.pow(2,F-15)*(1+T/1024):6103515625e-14*(T/1024))}function te(m,F){const T=m.getUint16(F.value,!0);return F.value+=2,T}function re(m,F){return yA(te(m,F))}function Ge(m,F,T,tA){const L=T.value,V=[];for(;T.value<L+tA-1;){const j=FA(F,T),CA=ae(m,T),QA=TA(m,T);T.value+=3;const SA=ae(m,T),vA=ae(m,T);V.push({name:j,pixelType:CA,pLinear:QA,xSampling:SA,ySampling:vA})}return T.value+=1,V}function O(m,F){const T=UA(m,F),tA=UA(m,F),L=UA(m,F),V=UA(m,F),j=UA(m,F),CA=UA(m,F),QA=UA(m,F),SA=UA(m,F);return{redX:T,redY:tA,greenX:L,greenY:V,blueX:j,blueY:CA,whiteX:QA,whiteY:SA}}function K(m,F){const T=["NO_COMPRESSION","RLE_COMPRESSION","ZIPS_COMPRESSION","ZIP_COMPRESSION","PIZ_COMPRESSION","PXR24_COMPRESSION","B44_COMPRESSION","B44A_COMPRESSION","DWAA_COMPRESSION","DWAB_COMPRESSION"],tA=TA(m,F);return T[tA]}function hA(m,F){const T=uA(m,F),tA=uA(m,F),L=uA(m,F),V=uA(m,F);return{xMin:T,yMin:tA,xMax:L,yMax:V}}function RA(m,F){const T=["INCREASING_Y"],tA=TA(m,F);return T[tA]}function qA(m,F){const T=UA(m,F),tA=UA(m,F);return[T,tA]}function KA(m,F){const T=UA(m,F),tA=UA(m,F),L=UA(m,F);return[T,tA,L]}function de(m,F,T,tA,L){if(tA==="string"||tA==="stringvector"||tA==="iccProfile")return XA(F,T,L);if(tA==="chlist")return Ge(m,F,T,L);if(tA==="chromaticities")return O(m,T);if(tA==="compression")return K(m,T);if(tA==="box2i")return hA(m,T);if(tA==="lineOrder")return RA(m,T);if(tA==="float")return UA(m,T);if(tA==="v2f")return qA(m,T);if(tA==="v3f")return KA(m,T);if(tA==="int")return ae(m,T);if(tA==="rational")return ee(m,T);if(tA==="timecode")return xA(m,T);if(tA==="preview")return T.value+=L,"skipped";T.value+=L}function Ce(m,F,T){const tA={};if(m.getUint32(0,!0)!=20000630)throw new Error("THREE.EXRLoader: Provided file doesn't appear to be in OpenEXR format.");tA.version=m.getUint8(4);const L=m.getUint8(5);tA.spec={singleTile:!!(L&2),longName:!!(L&4),deepFormat:!!(L&8),multiPart:!!(L&16)},T.value=8;let V=!0;for(;V;){const j=FA(F,T);if(j==0)V=!1;else{const CA=FA(F,T),QA=uA(m,T),SA=de(m,F,T,CA,QA);SA===void 0?console.warn(`THREE.EXRLoader: Skipped unknown header attribute type '${CA}'.`):tA[j]=SA}}if(L&-5)throw console.error("THREE.EXRHeader:",tA),new Error("THREE.EXRLoader: Provided file is currently unsupported.");return tA}function YA(m,F,T,tA,L){const V={size:0,viewer:F,array:T,offset:tA,width:m.dataWindow.xMax-m.dataWindow.xMin+1,height:m.dataWindow.yMax-m.dataWindow.yMin+1,channels:m.channels.length,bytesPerLine:null,lines:null,inputSize:null,type:m.channels[0].pixelType,uncompress:null,getter:null,format:null,colorSpace:bt};switch(m.compression){case"NO_COMPRESSION":V.lines=1,V.uncompress=$;break;case"RLE_COMPRESSION":V.lines=1,V.uncompress=aA;break;case"ZIPS_COMPRESSION":V.lines=1,V.uncompress=kA;break;case"ZIP_COMPRESSION":V.lines=16,V.uncompress=kA;break;case"PIZ_COMPRESSION":V.lines=32,V.uncompress=JA;break;case"PXR24_COMPRESSION":V.lines=16,V.uncompress=sA;break;case"DWAA_COMPRESSION":V.lines=32,V.uncompress=mA;break;case"DWAB_COMPRESSION":V.lines=256,V.uncompress=mA;break;default:throw new Error("EXRLoader.parse: "+m.compression+" is unsupported")}if(V.scanlineBlockSize=V.lines,V.type==1)switch(L){case Oi:V.getter=re,V.inputSize=2;break;case cg:V.getter=te,V.inputSize=2;break}else if(V.type==2)switch(L){case Oi:V.getter=UA,V.inputSize=4;break;case cg:V.getter=PA,V.inputSize=4}else throw new Error("EXRLoader.parse: unsupported pixelType "+V.type+" for "+m.compression+".");V.blockCount=(m.dataWindow.yMax+1)/V.scanlineBlockSize;for(let CA=0;CA<V.blockCount;CA++)NA(F,tA);V.outputChannels=V.channels==3?4:V.channels;const j=V.width*V.height*V.outputChannels;switch(L){case Oi:V.byteArray=new Float32Array(j),V.channels<V.outputChannels&&V.byteArray.fill(1,0,j);break;case cg:V.byteArray=new Uint16Array(j),V.channels<V.outputChannels&&V.byteArray.fill(15360,0,j);break;default:console.error("THREE.EXRLoader: unsupported type: ",L);break}return V.bytesPerLine=V.width*V.inputSize*V.channels,V.outputChannels==4?(V.format=ti,V.colorSpace=bt):(V.format=yE,V.colorSpace=uo),V}const OA=new DataView(A),Se=new Uint8Array(A),_A={value:0},Ve=Ce(OA,A,_A),LA=YA(Ve,OA,Se,_A,this.type),we={value:0},Be={R:0,G:1,B:2,A:3,Y:0};for(let m=0;m<LA.height/LA.scanlineBlockSize;m++){const F=uA(OA,_A);LA.size=uA(OA,_A),LA.lines=F+LA.scanlineBlockSize>LA.height?LA.height-F:LA.scanlineBlockSize;const T=LA.size<LA.lines*LA.bytesPerLine?LA.uncompress(LA):$(LA);_A.value+=LA.size;for(let tA=0;tA<LA.scanlineBlockSize;tA++){const L=tA+m*LA.scanlineBlockSize;if(L>=LA.height)break;for(let V=0;V<LA.channels;V++){const j=Be[Ve.channels[V].name];for(let CA=0;CA<LA.width;CA++){we.value=(tA*(LA.channels*LA.width)+V*LA.width+CA)*LA.inputSize;const QA=(LA.height-1-L)*(LA.width*LA.outputChannels)+CA*LA.outputChannels+j;LA.byteArray[QA]=LA.getter(T,we)}}}}return{header:Ve,width:LA.width,height:LA.height,data:LA.byteArray,format:LA.format,colorSpace:LA.colorSpace,type:this.type}}setDataType(A){return this.type=A,this}load(A,e,g,I){function o(s,n){s.colorSpace=n.colorSpace,s.minFilter=Ne,s.magFilter=Ne,s.generateMipmaps=!1,s.flipY=!1,e&&e(s,n)}return super.load(A,o,g,I)}}const AhA=Object.freeze(Object.defineProperty({__proto__:null,EXRLoader:Lp},Symbol.toStringTag,{value:"Module"}));class $S extends yU{constructor(A){super(A),this.type=cg}parse(A){const e=function(u,D){switch(u){case 1:throw new Error("THREE.RGBELoader: Read Error: "+(D||""));case 2:throw new Error("THREE.RGBELoader: Write Error: "+(D||""));case 3:throw new Error("THREE.RGBELoader: Bad File Format: "+(D||""));default:case 4:throw new Error("THREE.RGBELoader: Memory Error: "+(D||""))}},g=`
5237
5237
  `,I=function(u,D,p){D=D||1024;let w=u.pos,f=-1,G=0,M="",U=String.fromCharCode.apply(null,new Uint16Array(u.subarray(w,w+128)));for(;0>(f=U.indexOf(g))&&G<D&&w<u.byteLength;)M+=U,G+=U.length,w+=128,U+=String.fromCharCode.apply(null,new Uint16Array(u.subarray(w,w+128)));return-1<f?(p!==!1&&(u.pos+=G+f+1),M+U.slice(0,f)):!1},o=function(u){const D=/^#\?(\S+)/,p=/^\s*GAMMA\s*=\s*(\d+(\.\d+)?)\s*$/,w=/^\s*EXPOSURE\s*=\s*(\d+(\.\d+)?)\s*$/,f=/^\s*FORMAT=(\S+)\s*$/,G=/^\s*\-Y\s+(\d+)\s+\+X\s+(\d+)\s*$/,M={valid:0,string:"",comments:"",programtype:"RGBE",format:"",gamma:1,exposure:1,width:0,height:0};let U,v;for((u.pos>=u.byteLength||!(U=I(u)))&&e(1,"no header found"),(v=U.match(D))||e(3,"bad initial token"),M.valid|=1,M.programtype=v[1],M.string+=U+`
5238
5238
  `;U=I(u),U!==!1;){if(M.string+=U+`
@@ -5266,7 +5266,7 @@ TEX `+g.texture_lod;if(gb=="density"&&(D+=`
5266
5266
  `+(u/n.lastScreenCoverage).toFixed(0)+` dens
5267
5267
  `+(n.lastScreenCoverage*100).toFixed(1)+`% cov
5268
5268
  `+(n.lastCentrality*100).toFixed(1)+`% centr
5269
- `+(Af.min.x.toFixed(2)+"-"+Af.max.x.toFixed(2)+"x"+Af.min.y.toFixed(2)+"-"+Af.max.y.toFixed(2))+" scr"),n.lastScreenCoverage>.1){const p=A,w=p.worldForward,f=p.worldPosition,G=lt(w).multiplyScalar(h*.7).add(Q),M=G.distanceTo(f),U=E[Math.min(E.length-1,Math.max(0,a))]+"88",v=this.context.domHeight>0?screen.height/this.context.domHeight:1,k=A.isPerspectiveCamera?Math.tan(A.fov*Math.PI/180/2):1;pe.DrawLabel(G,D,M*.012*v*k,void 0,16777215,U)}}}}}const tf=iA("debugphysics"),nj=new yI;class fn{constructor(){B(this,"ray"),B(this,"cam"),B(this,"screenPoint"),B(this,"raycaster"),B(this,"results"),B(this,"targets"),B(this,"recursive",!0),B(this,"minDistance"),B(this,"maxDistance"),B(this,"lineThreshold"),B(this,"layerMask"),B(this,"ignore"),B(this,"testObject")}screenPointFromOffset(A,e){this.screenPoint===void 0&&(this.screenPoint=new AA),this.screenPoint.x=A/window.innerWidth*2-1,this.screenPoint.y=-(e/window.innerHeight)*2+1}setLayer(A){nj.set(A),this.layerMask=nj}setMask(A){this.layerMask||(this.layerMask=new yI);const e=this.layerMask;e?e.mask=A:this.layerMask=A}}B(fn,"AllLayers",4294967295);class aj{constructor(A,e,g){B(this,"distance"),B(this,"point"),B(this,"object"),this.object=A,this.distance=e,this.point=g}}class rj{constructor(A){B(this,"context"),B(this,"engine"),B(this,"raycaster",new vQ),B(this,"defaultRaycastOptions",new fn),B(this,"targetBuffer",new Array(1)),B(this,"defaultThresholds",{Mesh:{},Line:{threshold:-1},LOD:{},Points:{threshold:0},Sprite:{}}),B(this,"sphereResults",new Array),B(this,"sphereMask",new yI),B(this,"tempBoundingBox",new kt),this.context=A}raycastPhysicsFast(A,e=void 0,g=1/0,I=!0){var o;return((o=this.context.physics.engine)==null?void 0:o.raycast(A,e,{maxDistance:g,solid:I}))??null}raycastPhysicsFastAndGetNormal(A,e=void 0,g=1/0,I=!0){var o;return((o=this.context.physics.engine)==null?void 0:o.raycastAndGetNormal(A,e,{maxDistance:g,solid:I}))??null}sphereOverlapPhysics(A,e){var g;return((g=this.context.physics.engine)==null?void 0:g.sphereOverlap(A,e))??null}sphereOverlap(A,e,g=!0){if(this.sphereResults.length=0,!this.context.scene)return this.sphereResults;const I=new Ni(A,e),o=this.sphereMask;o.enableAll(),o.disable(2);for(const s of this.context.scene.children)this.onSphereOverlap(s,I,o,this.sphereResults,g);return this.sphereResults.sort((s,n)=>s.distance-n.distance)}onSphereOverlap(A,e,g,I,o){if(A.type==="Mesh"&&A.layers.test(g)&&!pe.isGizmo(A)){const s=A,n=s.geometry;if(n&&(n.boundingBox||n.computeBoundingBox(),n.boundingBox)){s.matrixWorldNeedsUpdate&&s.updateMatrixWorld();const a=this.tempBoundingBox.copy(n.boundingBox).applyMatrix4(s.matrixWorld);if(e.intersectsBox(a)){const r=Fe(A),C=r.distanceTo(e.center),Q=new aj(A,C,r);if(I.push(Q),!o)return}}}if(A.children)for(const s of A.children){const n=I.length;if(this.onSphereOverlap(s,e,g,I,o),n!=I.length&&!o)return}}raycastFromRay(A,e=null){const g=e??this.defaultRaycastOptions;g.ray=A;const I=this.raycast(g);return g===this.defaultRaycastOptions&&(g.ray=void 0),I}raycast(A=null){A||(A=this.defaultRaycastOptions);const e=A.screenPoint??this.context.input.mousePositionRC,g=A.raycaster??this.raycaster;if(g.near=A.minDistance??0,g.far=A.maxDistance??1/0,g.params=this.defaultThresholds,A.lineThreshold===void 0&&(A.lineThreshold=-1),g.params.Line={threshold:A.lineThreshold},A.ray)g.ray.copy(A.ray);else{const n=A.cam??this.context.mainCamera;if(!n)return tf&&console.error("Can not perform raycast - no main camera found"),this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),this.defaultRaycastOptions.results??[];const a=this.context.xrCamera;this.context.isInXR&&a instanceof OR&&a.cameras.length>0?g.setFromCamera(e,a.cameras[0]):g.setFromCamera(e,n)}let I=A.targets;I||(I=this.targetBuffer,I.length=1,I[0]=this.context.scene);let o=A.results;this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),o||(this.defaultRaycastOptions.results||(this.defaultRaycastOptions.results=new Array),o=this.defaultRaycastOptions.results),A.layerMask!==void 0?A.layerMask instanceof yI?g.layers.mask=A.layerMask.mask:g.layers.mask=A.layerMask:(g.layers.enableAll(),g.layers.disable(2)),tf&&(pe.DrawRay(g.ray.origin,g.ray.direction,16711680,2),console.time("raycast")),o.length=0,this.intersect(this.raycaster,I,o,A),o.sort((n,a)=>n.distance-a.distance);const s=A.ignore;return s!==void 0&&s.length>0&&(o=o.filter(n=>!s.includes(n.object))),tf&&(console.timeEnd("raycast"),console.warn("#"+this.context.time.frame+", hits:",o!=null&&o.length?[...o]:"nothing")),o}intersect(A,e,g,I){var o;for(const s of e){if(s.visible===!1||pe.isGizmo(s)||I.lineThreshold!==void 0&&I.lineThreshold<0&&s instanceof Fi)continue;const n=(o=I.testObject)==null?void 0:o.call(I,s);if(n!==!1){if(n!=="continue in children"){const a=s,r=a.geometry;if(r){const C=ip(s);C&&(a.geometry=C);const Q=g.length;A.intersectObject(s,!1,g),tf&&g.length!=Q&&pe.DrawWireMesh({mesh:s,depthTest:!1,duration:.2,color:C?8969557:7798784}),a.geometry=r}}I.recursive!==!1&&this.intersect(A,s.children,g,I)}}return g}}const IhA=iA("debugplayerview");var CB=(i=>(i.Browser="browser",i.Headset="headset",i.Handheld="handheld",i))(CB||{});class Cj{constructor(A,e){B(this,"userId"),B(this,"context"),B(this,"viewDevice","browser"),B(this,"removed",!1),B(this,"_object"),this.userId=A,this.context=e}get currentObject(){return this._object}set currentObject(A){this._object=A}get isConnected(){return this.context.connection.userIsInRoom(this.userId)}}class Bj{constructor(A){B(this,"context"),B(this,"playerViews",new Map),this.context=A}setPlayerView(A,e,g){let I=this.playerViews.get(A);I||(I=new Cj(A,this.context),this.playerViews.set(A,I)),I.viewDevice=g,I.currentObject=e,I.removed=!1}getPlayerView(A){if(!!A){if(!this.context.connection.userIsInRoom(A)){this.playerViews.delete(A);return}return this.playerViews.get(A)}}removePlayerView(A,e){const g=this.playerViews.get(A);g?.viewDevice===e&&(IhA&&console.log("REMOVE",A),g.removed=!0,this.playerViews.delete(A))}}new GI;const Tp=new Uint8Array(4);Tp[0]=255,Tp[1]=255,Tp[2]=255,Tp[3]=255;const ohA=new Lo(Tp,1,1,ti);function Ib(i,A=1){const e="alpha"in i,g=A*A,I=new Uint8Array(4*g),o=Math.floor(i.r*255),s=Math.floor(i.g*255),n=Math.floor(i.b*255);for(let r=0;r<g;r++){const C=r*4;I[C+0]=o,I[C+1]=s,I[C+2]=n,e?I[C+3]=Math.floor(i.alpha*255):I[C+3]=255}const a=new Lo(I,A,A);return a.needsUpdate=!0,a}function shA(i,A,e,g=1,I=3){const o=g*I,s=[i,A,e],n=s.length,a=new Uint8Array(4*n*o),r=new fA;for(let Q=0;Q<I;Q++){const h=Math.floor(Q/I*n),E=ge.clamp(h+1,0,n-1),c=s[h],l=s[E],d=Q/I*n%1;r.lerpColors(c,l,d);const u=Math.floor(r.r*255),D=Math.floor(r.g*255),p=Math.floor(r.b*255);for(let w=0;w<g;w++){const f=(Q*g+w)*4;a[f+0]=u,a[f+1]=D,a[f+2]=p,a[f+3]=255}}const C=new Lo(a,g,I);return C.needsUpdate=!0,C}function gf(i,A){const e=i.elements;A||(A=[]),A.length=0;for(let g=0;g<16;g+=4){const I=e[g],o=e[g+1],s=e[g+2],n=e[g+3],a=new VA(I,o,s,n);A.push(a)}return A}const ob=[],Qj=[];function nhA(i,A){if(ob.length===0)for(let e=0;e<27;e++)ob.push(0);A||(A=ob);for(let e=0;e<27;e++)Qj[e]=A[e];A=Qj,i.unity_SHAr={value:new VA(A[9],A[3],A[6],A[0])},i.unity_SHBr={value:new VA(A[12],A[15],A[18],A[21])},i.unity_SHAg={value:new VA(A[10],A[4],A[7],A[1])},i.unity_SHBg={value:new VA(A[13],A[16],A[19],A[22])},i.unity_SHAb={value:new VA(A[11],A[5],A[8],A[2])},i.unity_SHBb={value:new VA(A[14],A[17],A[20],A[23])},i.unity_SHC={value:new VA(A[24],A[25],A[26],1)}}class ahA{constructor(A,e,g){B(this,"vertexShader"),B(this,"fragmentShader"),B(this,"technique"),this.vertexShader=A,this.fragmentShader=e,this.technique=g}}async function rhA(i,A){if(!i)return console.error("Can not find technique: no shader data"),null;const e=i.programs[A],g=e.vertexShader,I=e.fragmentShader;if(g!==void 0&&I!==void 0){const o=i.shaders[g],s=i.shaders[I];if(o.uri&&s.uri||o.code&&s.code){if(!o.code&&o.uri&&await hj(o),!s.code&&s.uri&&await hj(s),!o.code||!s.code)return null;const n=i.techniques[A];return new ahA(o.code,s.code,n)}}return console.error("Shader technique not found",A),null}async function hj(i){const A=i.uri;if(A)if(A.endsWith(".glsl")){const e=await new GI().loadAsync(A);i.code=e.toString()}else i.code=ChA(i.uri)}function ChA(i){return decodeURIComponent(Array.prototype.map.call(atob(i),function(A){return"%"+("00"+A.charCodeAt(0).toString(16)).slice(-2)}).join(""))}const kn=iA("debugenvlight");var al=(i=>(i[i.Skybox=0]="Skybox",i[i.Trilight=1]="Trilight",i[i.Flat=3]="Flat",i[i.Custom=4]="Custom",i))(al||{}),If=(i=>(i[i.Skybox=0]="Skybox",i[i.Custom=1]="Custom",i))(If||{});class Ej{constructor(A){B(this,"context"),B(this,"_currentLightSettingsId"),B(this,"_sceneLightSettings"),B(this,"_timevec4",new VA),B(this,"__currentReflectionId",null),B(this,"_lighting",{}),this.context=A,this.context.pre_update_callbacks.push(this.preUpdate.bind(this))}preUpdate(){const A=this.context.time;this._timevec4.x=A.time,this._timevec4.y=Math.sin(A.time),this._timevec4.z=Math.cos(A.time),this._timevec4.w=A.deltaTime}get timeVec4(){return this._timevec4}get environmentIntensity(){if(!this._sceneLightSettings||!this._currentLightSettingsId)return 1;const A=this._sceneLightSettings.get(this._currentLightSettingsId);return A?A.ambientIntensity:1}get sceneLightSettings(){var A;return(A=this._sceneLightSettings)==null?void 0:A.values()}enable(A){var e;A instanceof gt&&(A=A.uri);const g=(e=this._sceneLightSettings)==null?void 0:e.get(A);return g?(kn&&console.log("Enable scene light settings",A,g),A!==this._currentLightSettingsId&&this._currentLightSettingsId&&this.disable(this._currentLightSettingsId),this._currentLightSettingsId=A,g.enabled=!0,!0):(kn&&console.warn("No light settings found for",A),!1)}disable(A){var e;if(A instanceof gt&&(A=A.uri),A==null)return!1;const g=(e=this._sceneLightSettings)==null?void 0:e.get(A);return g?(kn&&console.log("Disable scene light settings",A,g),g.enabled=!1,!0):!1}disableCurrent(){if(this._currentLightSettingsId){const A=this._currentLightSettingsId;return this.disable(this._currentLightSettingsId),A}return null}internalRegisterSceneLightSettings(A){const e=A.sourceId;if(!e){console.error("Missing source id for scene light settings, can not register:",A);return}kn&&console.log("Register "+A?.sourceId+" lighting",A),this._sceneLightSettings||(this._sceneLightSettings=new Map),this._sceneLightSettings.set(e,A)}internalUnregisterSceneLightSettings(A){const e=A.sourceId;if(!e){console.error("Missing source id for scene light settings, can not unregister:",A);return}kn&&console.log("Unregister "+A?.sourceId+" lighting",A),this._sceneLightSettings&&this._sceneLightSettings.delete(e)}internalRegisterReflection(A,e){kn&&console.log("Register reflection",A,e);const g=new cj(this.context,e,1);this._lighting[A]=g}internalGetReflection(A){return this._lighting[A]}internalEnableReflection(A){var e;this.__currentReflectionId=A;const g=(e=this._sceneLightSettings)==null?void 0:e.get(A);switch(kn&&console.log("Enable reflection",A,g?al[g.ambientMode]:"Unknown ambient mode",g),g?.ambientMode){case 0:case 4:const I=this.internalGetReflection(A);if(I&&I.Source){kn&&console.log("Setting environment reflection",I);const o=this.context.scene,s=I.Source;s.mapping=Eo,o.environment=s;return}else kn&&console.warn("Could not find reflection for source",A);break}if(g?.environmentReflectionSource===1)switch(g?.ambientMode){case 1:if(g.ambientTrilight){const I=g.ambientTrilight,o=shA(I[0],I[1],I[2],64,64);o.colorSpace=Ee,o.mapping=Eo,this.context.scene.environment=o}else console.error("Missing ambient trilight",g.sourceId);return;case 3:if(g.ambientLight){const I=Ib(g.ambientLight,64);I.colorSpace=Ee,I.mapping=Eo,this.context.scene.environment=I}else console.error("Missing ambientlight",g.sourceId);return;default:return}}internalDisableReflection(A){if(A&&A!==this.__currentReflectionId){kn&&console.log("Not disabling reflection for",A,"because it is not the current light settings id",this.__currentReflectionId);return}kn&&console.log("Disable reflection",A);const e=this.context.scene;e.environment=null}}class cj{constructor(A,e,g=1){B(this,"_source"),this._source=e,e.mapping=Eo}get Source(){return this._source}}const lj=iA("timescale");let sb=1;typeof lj=="number"&&(sb=lj);class dj{constructor(){B(this,"_time",0),B(this,"_deltaTime",0),B(this,"_deltaTimeUnscaled",0),B(this,"timeScale",1),B(this,"_frame",0),B(this,"clock",new MU),B(this,"_smoothedFps",0),B(this,"_smoothedDeltaTime",0),B(this,"_fpsSamples",[]),B(this,"_fpsSampleIndex",0),typeof sb=="number"&&(this.timeScale=sb)}get time(){return this._time}set time(A){this._time=A}get deltaTime(){return this._deltaTime}set deltaTime(A){this._deltaTime=A}get deltaTimeUnscaled(){return this._deltaTimeUnscaled}get frame(){return this._frame}set frame(A){this._frame=A}get frameCount(){return this.frame}get realtimeSinceStartup(){return this.clock.elapsedTime}get smoothedFps(){return this._smoothedFps}get smoothedDeltaTime(){return 1/this._smoothedFps}update(){this.deltaTime=this.clock.getDelta(),this.deltaTime=Math.min(.1,this.deltaTime),this._deltaTimeUnscaled=this.deltaTime,this.deltaTime<=0&&(this.deltaTime=1e-12),this.deltaTime*=this.timeScale,this.frame+=1,this.time+=this.deltaTime,this._fpsSamples.length<60?this._fpsSamples.push(this.deltaTime):this._fpsSamples[this._fpsSampleIndex++%60]=this.deltaTime;let A=0;for(let e=0;e<this._fpsSamples.length;e++)A+=this._fpsSamples[e];this._smoothedDeltaTime=A/this._fpsSamples.length,this._smoothedFps=1/this._smoothedDeltaTime}}let uj=!1;function pj(i){uj||(uj=!0,BhA(),QhA())}pj();function BhA(){const i=`
5269
+ `+(Af.min.x.toFixed(2)+"-"+Af.max.x.toFixed(2)+"x"+Af.min.y.toFixed(2)+"-"+Af.max.y.toFixed(2))+" scr"),n.lastScreenCoverage>.1){const p=A,w=p.worldForward,f=p.worldPosition,G=lt(w).multiplyScalar(h*.7).add(Q),M=G.distanceTo(f),U=E[Math.min(E.length-1,Math.max(0,a))]+"88",v=this.context.domHeight>0?screen.height/this.context.domHeight:1,k=A.isPerspectiveCamera?Math.tan(A.fov*Math.PI/180/2):1;pe.DrawLabel(G,D,M*.012*v*k,void 0,16777215,U)}}}}}const tf=iA("debugphysics"),nj=new yI;class fn{constructor(){B(this,"ray"),B(this,"cam"),B(this,"screenPoint"),B(this,"raycaster"),B(this,"results"),B(this,"targets"),B(this,"recursive",!0),B(this,"minDistance"),B(this,"maxDistance"),B(this,"lineThreshold"),B(this,"layerMask"),B(this,"ignore"),B(this,"testObject")}screenPointFromOffset(A,e){this.screenPoint===void 0&&(this.screenPoint=new AA),this.screenPoint.x=A/window.innerWidth*2-1,this.screenPoint.y=-(e/window.innerHeight)*2+1}setLayer(A){nj.set(A),this.layerMask=nj}setMask(A){this.layerMask||(this.layerMask=new yI);const e=this.layerMask;e?e.mask=A:this.layerMask=A}}B(fn,"AllLayers",4294967295);class aj{constructor(A,e,g){B(this,"distance"),B(this,"point"),B(this,"object"),this.object=A,this.distance=e,this.point=g}}class rj{constructor(A){B(this,"context"),B(this,"engine"),B(this,"raycaster",new vQ),B(this,"defaultRaycastOptions",new fn),B(this,"targetBuffer",new Array(1)),B(this,"defaultThresholds",{Mesh:{},Line:{threshold:-1},LOD:{},Points:{threshold:0},Sprite:{}}),B(this,"sphereResults",new Array),B(this,"sphereMask",new yI),B(this,"tempBoundingBox",new kt),this.context=A}raycastPhysicsFast(A,e=void 0,g=1/0,I=!0){var o;return((o=this.context.physics.engine)==null?void 0:o.raycast(A,e,{maxDistance:g,solid:I}))??null}raycastPhysicsFastAndGetNormal(A,e=void 0,g=1/0,I=!0){var o;return((o=this.context.physics.engine)==null?void 0:o.raycastAndGetNormal(A,e,{maxDistance:g,solid:I}))??null}sphereOverlapPhysics(A,e){var g;return((g=this.context.physics.engine)==null?void 0:g.sphereOverlap(A,e))??null}sphereOverlap(A,e,g=!0){if(this.sphereResults.length=0,!this.context.scene)return this.sphereResults;const I=new Ni(A,e),o=this.sphereMask;o.enableAll(),o.disable(2);for(const s of this.context.scene.children)this.onSphereOverlap(s,I,o,this.sphereResults,g);return this.sphereResults.sort((s,n)=>s.distance-n.distance)}onSphereOverlap(A,e,g,I,o){if(A.type==="Mesh"&&A.layers.test(g)&&!pe.isGizmo(A)){const s=A,n=s.geometry;if(n&&(n.boundingBox||n.computeBoundingBox(),n.boundingBox)){s.matrixWorldNeedsUpdate&&s.updateMatrixWorld();const a=this.tempBoundingBox.copy(n.boundingBox).applyMatrix4(s.matrixWorld);if(e.intersectsBox(a)){const r=Fe(A),C=r.distanceTo(e.center),Q=new aj(A,C,r);if(I.push(Q),!o)return}}}if(A.children)for(const s of A.children){const n=I.length;if(this.onSphereOverlap(s,e,g,I,o),n!=I.length&&!o)return}}raycastFromRay(A,e=null){const g=e??this.defaultRaycastOptions;g.ray=A;const I=this.raycast(g);return g===this.defaultRaycastOptions&&(g.ray=void 0),I}raycast(A=null){A||(A=this.defaultRaycastOptions);const e=A.screenPoint??this.context.input.mousePositionRC,g=A.raycaster??this.raycaster;if(g.near=A.minDistance??0,g.far=A.maxDistance??1/0,g.params=this.defaultThresholds,A.lineThreshold===void 0&&(A.lineThreshold=-1),g.params.Line={threshold:A.lineThreshold},A.ray)g.ray.copy(A.ray);else{const n=A.cam??this.context.mainCamera;if(!n)return tf&&console.error("Can not perform raycast - no main camera found"),this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),this.defaultRaycastOptions.results??[];const a=this.context.xrCamera;this.context.isInXR&&a instanceof OR&&a.cameras.length>0?g.setFromCamera(e,a.cameras[0]):g.setFromCamera(e,n)}let I=A.targets;I||(I=this.targetBuffer,I.length=1,I[0]=this.context.scene);let o=A.results;this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),o||(this.defaultRaycastOptions.results||(this.defaultRaycastOptions.results=new Array),o=this.defaultRaycastOptions.results),A.layerMask!==void 0?A.layerMask instanceof yI?g.layers.mask=A.layerMask.mask:g.layers.mask=A.layerMask:(g.layers.enableAll(),g.layers.disable(2)),tf&&(pe.DrawRay(g.ray.origin,g.ray.direction,16711680,2),console.time("raycast")),o.length=0,this.intersect(this.raycaster,I,o,A),o.sort((n,a)=>n.distance-a.distance);const s=A.ignore;return s!==void 0&&s.length>0&&(o=o.filter(n=>!s.includes(n.object))),tf&&(console.timeEnd("raycast"),console.warn("#"+this.context.time.frame+", hits:",o!=null&&o.length?[...o]:"nothing")),o}intersect(A,e,g,I){var o;for(const s of e){if(!s||s.visible===!1||pe.isGizmo(s)||I.lineThreshold!==void 0&&I.lineThreshold<0&&s instanceof Fi)continue;const n=(o=I.testObject)==null?void 0:o.call(I,s);if(n!==!1){if(n!=="continue in children"){const a=s,r=a.geometry;if(r){const C=ip(s);C&&(a.geometry=C);const Q=g.length;A.intersectObject(s,!1,g),tf&&g.length!=Q&&pe.DrawWireMesh({mesh:s,depthTest:!1,duration:.2,color:C?8969557:7798784}),a.geometry=r}}I.recursive!==!1&&this.intersect(A,s.children,g,I)}}return g}}const IhA=iA("debugplayerview");var CB=(i=>(i.Browser="browser",i.Headset="headset",i.Handheld="handheld",i))(CB||{});class Cj{constructor(A,e){B(this,"userId"),B(this,"context"),B(this,"viewDevice","browser"),B(this,"removed",!1),B(this,"_object"),this.userId=A,this.context=e}get currentObject(){return this._object}set currentObject(A){this._object=A}get isConnected(){return this.context.connection.userIsInRoom(this.userId)}}class Bj{constructor(A){B(this,"context"),B(this,"playerViews",new Map),this.context=A}setPlayerView(A,e,g){let I=this.playerViews.get(A);I||(I=new Cj(A,this.context),this.playerViews.set(A,I)),I.viewDevice=g,I.currentObject=e,I.removed=!1}getPlayerView(A){if(!!A){if(!this.context.connection.userIsInRoom(A)){this.playerViews.delete(A);return}return this.playerViews.get(A)}}removePlayerView(A,e){const g=this.playerViews.get(A);g?.viewDevice===e&&(IhA&&console.log("REMOVE",A),g.removed=!0,this.playerViews.delete(A))}}new GI;const Tp=new Uint8Array(4);Tp[0]=255,Tp[1]=255,Tp[2]=255,Tp[3]=255;const ohA=new Lo(Tp,1,1,ti);function Ib(i,A=1){const e="alpha"in i,g=A*A,I=new Uint8Array(4*g),o=Math.floor(i.r*255),s=Math.floor(i.g*255),n=Math.floor(i.b*255);for(let r=0;r<g;r++){const C=r*4;I[C+0]=o,I[C+1]=s,I[C+2]=n,e?I[C+3]=Math.floor(i.alpha*255):I[C+3]=255}const a=new Lo(I,A,A);return a.needsUpdate=!0,a}function shA(i,A,e,g=1,I=3){const o=g*I,s=[i,A,e],n=s.length,a=new Uint8Array(4*n*o),r=new fA;for(let Q=0;Q<I;Q++){const h=Math.floor(Q/I*n),E=ge.clamp(h+1,0,n-1),c=s[h],l=s[E],d=Q/I*n%1;r.lerpColors(c,l,d);const u=Math.floor(r.r*255),D=Math.floor(r.g*255),p=Math.floor(r.b*255);for(let w=0;w<g;w++){const f=(Q*g+w)*4;a[f+0]=u,a[f+1]=D,a[f+2]=p,a[f+3]=255}}const C=new Lo(a,g,I);return C.needsUpdate=!0,C}function gf(i,A){const e=i.elements;A||(A=[]),A.length=0;for(let g=0;g<16;g+=4){const I=e[g],o=e[g+1],s=e[g+2],n=e[g+3],a=new VA(I,o,s,n);A.push(a)}return A}const ob=[],Qj=[];function nhA(i,A){if(ob.length===0)for(let e=0;e<27;e++)ob.push(0);A||(A=ob);for(let e=0;e<27;e++)Qj[e]=A[e];A=Qj,i.unity_SHAr={value:new VA(A[9],A[3],A[6],A[0])},i.unity_SHBr={value:new VA(A[12],A[15],A[18],A[21])},i.unity_SHAg={value:new VA(A[10],A[4],A[7],A[1])},i.unity_SHBg={value:new VA(A[13],A[16],A[19],A[22])},i.unity_SHAb={value:new VA(A[11],A[5],A[8],A[2])},i.unity_SHBb={value:new VA(A[14],A[17],A[20],A[23])},i.unity_SHC={value:new VA(A[24],A[25],A[26],1)}}class ahA{constructor(A,e,g){B(this,"vertexShader"),B(this,"fragmentShader"),B(this,"technique"),this.vertexShader=A,this.fragmentShader=e,this.technique=g}}async function rhA(i,A){if(!i)return console.error("Can not find technique: no shader data"),null;const e=i.programs[A],g=e.vertexShader,I=e.fragmentShader;if(g!==void 0&&I!==void 0){const o=i.shaders[g],s=i.shaders[I];if(o.uri&&s.uri||o.code&&s.code){if(!o.code&&o.uri&&await hj(o),!s.code&&s.uri&&await hj(s),!o.code||!s.code)return null;const n=i.techniques[A];return new ahA(o.code,s.code,n)}}return console.error("Shader technique not found",A),null}async function hj(i){const A=i.uri;if(A)if(A.endsWith(".glsl")){const e=await new GI().loadAsync(A);i.code=e.toString()}else i.code=ChA(i.uri)}function ChA(i){return decodeURIComponent(Array.prototype.map.call(atob(i),function(A){return"%"+("00"+A.charCodeAt(0).toString(16)).slice(-2)}).join(""))}const kn=iA("debugenvlight");var al=(i=>(i[i.Skybox=0]="Skybox",i[i.Trilight=1]="Trilight",i[i.Flat=3]="Flat",i[i.Custom=4]="Custom",i))(al||{}),If=(i=>(i[i.Skybox=0]="Skybox",i[i.Custom=1]="Custom",i))(If||{});class Ej{constructor(A){B(this,"context"),B(this,"_currentLightSettingsId"),B(this,"_sceneLightSettings"),B(this,"_timevec4",new VA),B(this,"__currentReflectionId",null),B(this,"_lighting",{}),this.context=A,this.context.pre_update_callbacks.push(this.preUpdate.bind(this))}preUpdate(){const A=this.context.time;this._timevec4.x=A.time,this._timevec4.y=Math.sin(A.time),this._timevec4.z=Math.cos(A.time),this._timevec4.w=A.deltaTime}get timeVec4(){return this._timevec4}get environmentIntensity(){if(!this._sceneLightSettings||!this._currentLightSettingsId)return 1;const A=this._sceneLightSettings.get(this._currentLightSettingsId);return A?A.ambientIntensity:1}get sceneLightSettings(){var A;return(A=this._sceneLightSettings)==null?void 0:A.values()}enable(A){var e;A instanceof gt&&(A=A.uri);const g=(e=this._sceneLightSettings)==null?void 0:e.get(A);return g?(kn&&console.log("Enable scene light settings",A,g),A!==this._currentLightSettingsId&&this._currentLightSettingsId&&this.disable(this._currentLightSettingsId),this._currentLightSettingsId=A,g.enabled=!0,!0):(kn&&console.warn("No light settings found for",A),!1)}disable(A){var e;if(A instanceof gt&&(A=A.uri),A==null)return!1;const g=(e=this._sceneLightSettings)==null?void 0:e.get(A);return g?(kn&&console.log("Disable scene light settings",A,g),g.enabled=!1,!0):!1}disableCurrent(){if(this._currentLightSettingsId){const A=this._currentLightSettingsId;return this.disable(this._currentLightSettingsId),A}return null}internalRegisterSceneLightSettings(A){const e=A.sourceId;if(!e){console.error("Missing source id for scene light settings, can not register:",A);return}kn&&console.log("Register "+A?.sourceId+" lighting",A),this._sceneLightSettings||(this._sceneLightSettings=new Map),this._sceneLightSettings.set(e,A)}internalUnregisterSceneLightSettings(A){const e=A.sourceId;if(!e){console.error("Missing source id for scene light settings, can not unregister:",A);return}kn&&console.log("Unregister "+A?.sourceId+" lighting",A),this._sceneLightSettings&&this._sceneLightSettings.delete(e)}internalRegisterReflection(A,e){kn&&console.log("Register reflection",A,e);const g=new cj(this.context,e,1);this._lighting[A]=g}internalGetReflection(A){return this._lighting[A]}internalEnableReflection(A){var e;this.__currentReflectionId=A;const g=(e=this._sceneLightSettings)==null?void 0:e.get(A);switch(kn&&console.log("Enable reflection",A,g?al[g.ambientMode]:"Unknown ambient mode",g),g?.ambientMode){case 0:case 4:const I=this.internalGetReflection(A);if(I&&I.Source){kn&&console.log("Setting environment reflection",I);const o=this.context.scene,s=I.Source;s.mapping=Eo,o.environment=s;return}else kn&&console.warn("Could not find reflection for source",A);break}if(g?.environmentReflectionSource===1)switch(g?.ambientMode){case 1:if(g.ambientTrilight){const I=g.ambientTrilight,o=shA(I[0],I[1],I[2],64,64);o.colorSpace=Ee,o.mapping=Eo,this.context.scene.environment=o}else console.error("Missing ambient trilight",g.sourceId);return;case 3:if(g.ambientLight){const I=Ib(g.ambientLight,64);I.colorSpace=Ee,I.mapping=Eo,this.context.scene.environment=I}else console.error("Missing ambientlight",g.sourceId);return;default:return}}internalDisableReflection(A){if(A&&A!==this.__currentReflectionId){kn&&console.log("Not disabling reflection for",A,"because it is not the current light settings id",this.__currentReflectionId);return}kn&&console.log("Disable reflection",A);const e=this.context.scene;e.environment=null}}class cj{constructor(A,e,g=1){B(this,"_source"),this._source=e,e.mapping=Eo}get Source(){return this._source}}const lj=iA("timescale");let sb=1;typeof lj=="number"&&(sb=lj);class dj{constructor(){B(this,"_time",0),B(this,"_deltaTime",0),B(this,"_deltaTimeUnscaled",0),B(this,"timeScale",1),B(this,"_frame",0),B(this,"clock",new MU),B(this,"_smoothedFps",0),B(this,"_smoothedDeltaTime",0),B(this,"_fpsSamples",[]),B(this,"_fpsSampleIndex",0),typeof sb=="number"&&(this.timeScale=sb)}get time(){return this._time}set time(A){this._time=A}get deltaTime(){return this._deltaTime}set deltaTime(A){this._deltaTime=A}get deltaTimeUnscaled(){return this._deltaTimeUnscaled}get frame(){return this._frame}set frame(A){this._frame=A}get frameCount(){return this.frame}get realtimeSinceStartup(){return this.clock.elapsedTime}get smoothedFps(){return this._smoothedFps}get smoothedDeltaTime(){return 1/this._smoothedFps}update(){this.deltaTime=this.clock.getDelta(),this.deltaTime=Math.min(.1,this.deltaTime),this._deltaTimeUnscaled=this.deltaTime,this.deltaTime<=0&&(this.deltaTime=1e-12),this.deltaTime*=this.timeScale,this.frame+=1,this.time+=this.deltaTime,this._fpsSamples.length<60?this._fpsSamples.push(this.deltaTime):this._fpsSamples[this._fpsSampleIndex++%60]=this.deltaTime;let A=0;for(let e=0;e<this._fpsSamples.length;e++)A+=this._fpsSamples[e];this._smoothedDeltaTime=A/this._fpsSamples.length,this._smoothedFps=1/this._smoothedDeltaTime}}let uj=!1;function pj(i){uj||(uj=!0,BhA(),QhA())}pj();function BhA(){const i=`
5270
5270
  float startCompression = 0.8;
5271
5271
  float desaturation = 0.5;
5272
5272
  // Patched tonemapping function