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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4344,7 +4344,7 @@ Open this page to get the console: `+A.toString())}const 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.4""]) globalThis[""3.45.2-beta.4""] = "0.0.0";'),rc('if(!globalThis[""undefined""]) globalThis[""undefined""] = "unknown";'),rc('if(!globalThis[""Fri Jul 19 2024 19:15:04 GMT+0200 (Central European Summer Time)""]) globalThis[""Fri Jul 19 2024 19:15:04 GMT+0200 (Central European Summer Time)""] = "unknown";'),rc('globalThis["__NEEDLE_ENGINE_VERSION__"] = "3.45.2-beta.4";'),rc('globalThis["__NEEDLE_ENGINE_GENERATOR__"] = "undefined";'),rc('globalThis["__NEEDLE_PROJECT_BUILD_TIME__"] = "Fri Jul 19 2024 19:15:04 GMT+0200 (Central European Summer Time)";');const Bn="3.45.2-beta.4",nm="undefined",jN="Fri Jul 19 2024 19:15:04 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
@@ -5729,7 +5729,7 @@ Could not find method ${C.method} on object ${h.name}`,h,typeof h[C.method])};if
5729
5729
  // Uncomment to visualize blur amount
5730
5730
  // gl_FragColor = vec4(blurAmount, 0.0, 0.0, 1.0);
5731
5731
  }
5732
- `;var gEA=Object.defineProperty,IEA=Object.getOwnPropertyDescriptor,pb=(i,A,e,g)=>{for(var I=g>1?void 0:g?IEA(A,e):A,o=i.length-1,s;o>=0;o--)(s=i[o])&&(I=(g?s(A,e,I):s(I))||I);return g&&I&&gEA(A,e,I),I};class mh extends bA{constructor(){super(...arguments),B(this,"constraintActive",!0),B(this,"locked",!1),B(this,"sources",[])}}pb([y()],mh.prototype,"constraintActive",2),pb([y()],mh.prototype,"locked",2),pb([y(wA)],mh.prototype,"sources",2);function oEA(i,A){return gB(i,Mt.ContextCreated,A),()=>IB(i,Mt.ContextCreated)}function sEA(i,A){return gB(i,Mt.ContextClearing,A),()=>IB(i,Mt.ContextClearing)}function nEA(i,A){return gB(i,Mt.ContextDestroying,A),()=>IB(i,Mt.ContextDestroying)}function o8(i,A){return gB(i,Xt.Start,A),()=>IB(i,Xt.Start)}function s8(i,A){return gB(i,Xt.Update,A),()=>IB(i,Xt.Update)}function aEA(i,A){return gB(i,Xt.OnBeforeRender,A),()=>IB(i,Xt.OnBeforeRender)}function rEA(i,A){return gB(i,Xt.OnAfterRender,A),()=>IB(i,Xt.OnAfterRender)}class Sh{constructor(){B(this,"bb",null),B(this,"bb_pos",0)}__init(A,e){return this.bb_pos=A,this.bb=e,this}x(){return this.bb.readFloat32(this.bb_pos)}y(){return this.bb.readFloat32(this.bb_pos+4)}z(){return this.bb.readFloat32(this.bb_pos+8)}static sizeOf(){return 12}static createVec3(A,e,g,I){return A.prep(4,12),A.writeFloat32(I),A.writeFloat32(g),A.writeFloat32(e),A.offset()}}class n8{constructor(){B(this,"bb",null),B(this,"bb_pos",0)}__init(A,e){return this.bb_pos=A,this.bb=e,this}position(A){return(A||new Sh).__init(this.bb_pos,this.bb)}rotation(A){return(A||new Sh).__init(this.bb_pos+12,this.bb)}scale(A){return(A||new Sh).__init(this.bb_pos+24,this.bb)}static sizeOf(){return 36}static createTransform(A,e,g,I,o,s,n,a,r,C){return A.prep(4,36),A.prep(4,12),A.writeFloat32(C),A.writeFloat32(r),A.writeFloat32(a),A.prep(4,12),A.writeFloat32(n),A.writeFloat32(s),A.writeFloat32(o),A.prep(4,12),A.writeFloat32(I),A.writeFloat32(g),A.writeFloat32(e),A.offset()}}class nC{constructor(){B(this,"bb",null),B(this,"bb_pos",0)}__init(A,e){return this.bb_pos=A,this.bb=e,this}static getRootAsSyncedTransformModel(A,e){return(e||new nC).__init(A.readInt32(A.position())+A.position(),A)}static getSizePrefixedRootAsSyncedTransformModel(A,e){return A.setPosition(A.position()+FK),(e||new nC).__init(A.readInt32(A.position())+A.position(),A)}guid(A){const e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,A):null}fast(){const A=this.bb.__offset(this.bb_pos,6);return A?!!this.bb.readInt8(this.bb_pos+A):!1}transform(A){const e=this.bb.__offset(this.bb_pos,8);return e?(A||new n8).__init(this.bb_pos+e,this.bb):null}dontSave(){const A=this.bb.__offset(this.bb_pos,10);return A?!!this.bb.readInt8(this.bb_pos+A):!1}static startSyncedTransformModel(A){A.startObject(4)}static addGuid(A,e){A.addFieldOffset(0,e,0)}static addFast(A,e){A.addFieldInt8(1,+e,0)}static addTransform(A,e){A.addFieldStruct(2,e,0)}static addDontSave(A,e){A.addFieldInt8(3,+e,0)}static endSyncedTransformModel(A){return A.endObject()}static finishSyncedTransformModelBuffer(A,e){A.finish(e)}static finishSizePrefixedSyncedTransformModelBuffer(A,e){A.finish(e,void 0,!0)}}var Jg=(i=>(i[i.Average=0]="Average",i[i.Multiply=1]="Multiply",i[i.Minimum=2]="Minimum",i[i.Maximum=3]="Maximum",i))(Jg||{}),Sf=(i=>(i[i.Discrete=0]="Discrete",i[i.Continuous=1]="Continuous",i))(Sf||{}),Vi=(i=>(i[i.None=0]="None",i[i.FreezePositionX=2]="FreezePositionX",i[i.FreezePositionY=4]="FreezePositionY",i[i.FreezePositionZ=8]="FreezePositionZ",i[i.FreezePosition=14]="FreezePosition",i[i.FreezeRotationX=16]="FreezeRotationX",i[i.FreezeRotationY=32]="FreezeRotationY",i[i.FreezeRotationZ=64]="FreezeRotationZ",i[i.FreezeRotation=112]="FreezeRotation",i[i.FreezeAll=126]="FreezeAll",i))(Vi||{}),cl=(i=>(i[i.None=0]="None",i[i.X=2]="X",i[i.Y=4]="Y",i[i.Z=8]="Z",i[i.All=-1]="All",i))(cl||{});const gI=function(i,A){return function(e,g,I){CEA(e,g,I,i,A)}};function CEA(i,A,e,g,I){if(!I&&!g&&!i.onValidate)return;if(e!==void 0){console.error("Invalid usage of validate decorator. Only fields can be validated.",i,A,e),Ci("Invalid usage of validate decorator. Only fields can be validated. Property: "+A,To.Error);return}let o="";if(typeof A=="string"?o=A:o=A.name,i.__internalAwake){const s=Symbol(o),n=i.__internalAwake;i.__internalAwake=function(){var a;if(!this.onValidate){se()&&console.warn('Usage of @validate decorate detected but there is no onValidate method in your class: "'+((a=i.constructor)==null?void 0:a.name)+'"');return}if(this[s]===void 0){this[s]=this[o];const r=this[o];if(r instanceof AA||r instanceof S||r instanceof VA||r instanceof GA){const C=this[o];L0(C,()=>{this.onValidate(o)})}Object.defineProperty(this,o,{set:function(C){var Q;if(this[DK]===!0)this[s]=C;else{g?.call(this,C);const h=this[s];this[s]=C,(Q=this.onValidate)==null||Q.call(this,o,h)}},get:function(){return I?.call(this),this[s]}})}n.call(this)}}}const BEA=function(i){return function(A,e,g){let I="";typeof e=="string"?I=e:I=e.name;const o=i.prototype,s=Object.getOwnPropertyDescriptor(o,I);if(!(s!=null&&s.value)){console.warn("Can not apply prefix: type does not have method named",e,i);return}const n=s.value,a=A[I];Object.defineProperty(o,I,{value:function(...r){const C=a?.call(this,...r);if(C instanceof Promise){C.then(Q=>{if(Q!==!1)return n.call(this,...r)});return}if(C!==!1)return n.call(this,...r)}})}};var QEA=Object.defineProperty,hEA=Object.getOwnPropertyDescriptor,Wo=(i,A,e,g)=>{for(var I=g>1?void 0:g?hEA(A,e):A,o=i.length-1,s;o>=0;o--)(s=i[o])&&(I=(g?s(A,e,I):s(I))||I);return g&&I&&QEA(A,e,I),I};class EEA{constructor(A,e){B(this,"positionChanged",!1),B(this,"rotationChanged",!1),B(this,"position"),B(this,"quaternion"),B(this,"_positionKeys",["x","y","z"]),B(this,"_quaternionKeys",["_x","_y","_z","_w"]),B(this,"mute",!1),B(this,"context"),B(this,"obj"),B(this,"_positionWatch"),B(this,"_rotationWatch"),this.context=e,this.obj=A}get isDirty(){return this.positionChanged||this.rotationChanged}reset(A=!1){if(this.positionChanged=!1,this.rotationChanged=!1,this.mute=!1,A){if(this.position)for(const e of this._positionKeys)delete this.position[e];if(this.quaternion)for(const e of this._quaternionKeys)delete this.quaternion[e]}}syncValues(){for(const A of this._positionKeys)this.position[A]=this.obj.position[A];for(const A of this._quaternionKeys)this.quaternion[A]=this.obj.quaternion[A]}applyValues(){if(this.positionChanged&&this.position)for(const A of this._positionKeys){const e=this.position[A];e!==void 0&&(this.obj.position[A]=e)}if(this.rotationChanged&&this.quaternion)for(const A of this._quaternionKeys){const e=this.quaternion[A];e!==void 0&&(this.obj.quaternion[A]=e)}}start(A,e){this.reset(),A&&(this._positionWatch||(this._positionWatch=new eC(this.obj.position,["x","y","z"])),this._positionWatch.apply(),this.position={},this._positionWatch.subscribeWrite((o,s)=>{var n;if((n=this.context.physics.engine)!=null&&n.isUpdating||this.mute)return;const a=this.position[s];Math.abs(a-o)<1e-5||(this.position[s]=o,this.positionChanged=!0)})),e&&(this._rotationWatch||(this._rotationWatch=new eC(this.obj.quaternion,["_x","_y","_z","_w"])),this._rotationWatch.apply(),this.quaternion={},this._rotationWatch.subscribeWrite((o,s)=>{var n;if((n=this.context.physics.engine)!=null&&n.isUpdating||this.mute)return;const a=this.quaternion[s];Math.abs(a-o)<1e-5||(this.quaternion[s]=o,this.rotationChanged=!0)}));const g=this.obj.matrixWorld.multiplyMatrices.bind(this.obj.matrixWorld),I=new DA;this.obj.matrixWorld.multiplyMatrices=(o,s)=>{var n;return(n=this.context.physics.engine)!=null&&n.isUpdating||this.mute||I.equals(o)||(this.positionChanged=!0,this.rotationChanged=!0,I.copy(o)),g(o,s)}}stop(){var A,e;(A=this._positionWatch)==null||A.revoke(),(e=this._rotationWatch)==null||e.revoke()}}var Db;const wb=(Db=class extends bA{constructor(){super(...arguments),B(this,"autoMass",!0),B(this,"_mass",0),B(this,"useGravity",!0),B(this,"centerOfMass",new S(0,0,0)),B(this,"constraints",Vi.None),B(this,"isKinematic",!1),B(this,"drag",0),B(this,"angularDrag",1),B(this,"detectCollisions",!0),B(this,"sleepThreshold",.01),B(this,"collisionDetectionMode",Sf.Discrete),B(this,"_gravityScale",1),B(this,"dominanceGroup",0),B(this,"_propertiesChanged",!1),B(this,"_currentVelocity",new S),B(this,"_smoothedVelocity",new S),B(this,"_smoothedVelocityGetter",new S),B(this,"_lastPosition",new S),B(this,"_watch")}set mass(i){i!==this._mass&&(this._mass=i,this._propertiesChanged=!0,this.__didAwake&&(this.autoMass=!1))}get mass(){var i,A;return this.autoMass?((A=(i=this.context.physics.engine)==null?void 0:i.getBody(this))==null?void 0:A.mass())??-1:this._mass}get lockPositionX(){return(this.constraints&Vi.FreezePositionX)!==0}get lockPositionY(){return(this.constraints&Vi.FreezePositionY)!==0}get lockPositionZ(){return(this.constraints&Vi.FreezePositionZ)!==0}get lockRotationX(){return(this.constraints&Vi.FreezeRotationX)!==0}get lockRotationY(){return(this.constraints&Vi.FreezeRotationY)!==0}get lockRotationZ(){return(this.constraints&Vi.FreezeRotationZ)!==0}set lockPositionX(i){i?this.constraints|=Vi.FreezePositionX:this.constraints&=~Vi.FreezePositionX}set lockPositionY(i){i?this.constraints|=Vi.FreezePositionY:this.constraints&=~Vi.FreezePositionY}set lockPositionZ(i){i?this.constraints|=Vi.FreezePositionZ:this.constraints&=~Vi.FreezePositionZ}set lockRotationX(i){i?this.constraints|=Vi.FreezeRotationX:this.constraints&=~Vi.FreezeRotationX}set lockRotationY(i){i?this.constraints|=Vi.FreezeRotationY:this.constraints&=~Vi.FreezeRotationY}set lockRotationZ(i){i?this.constraints|=Vi.FreezeRotationZ:this.constraints&=~Vi.FreezeRotationZ}set gravityScale(i){this._gravityScale=i}get gravityScale(){return this._gravityScale}awake(){this._watch=void 0,this._propertiesChanged=!1}onEnable(){this._watch||(this._watch=new EEA(this.gameObject,this.context)),this._watch.start(!0,!0),this.startCoroutine(this.beforePhysics(),Xt.LateUpdate)}onDisable(){var i,A;(i=this._watch)==null||i.stop(),(A=this.context.physics.engine)==null||A.removeBody(this)}onDestroy(){var i;(i=this.context.physics.engine)==null||i.removeBody(this)}onValidate(){this._propertiesChanged=!0}*beforePhysics(){for(var i,A,e,g;;)this._propertiesChanged&&(this._propertiesChanged=!1,(i=this.context.physics.engine)==null||i.updateProperties(this)),(A=this._watch)!=null&&A.isDirty?(this._watch.mute=!0,this._watch.applyValues(),(e=this.context.physics.engine)==null||e.updateBody(this,this._watch.positionChanged,this._watch.rotationChanged),this._watch.reset()):(g=this._watch)==null||g.syncValues(),this.captureVelocity(),yield}teleport(i,A=!0){var e;(e=this._watch)==null||e.reset(!0),A?this.gameObject.position.set(i.x,i.y,i.z):this.setWorldPosition(i.x,i.y,i.z),this.resetForcesAndTorques(),this.resetVelocities()}resetForces(i=!0){var A;(A=this.context.physics.engine)==null||A.resetForces(this,i)}resetTorques(i=!0){var A;(A=this.context.physics.engine)==null||A.resetTorques(this,i)}resetVelocities(){this.setVelocity(0,0,0),this.setAngularVelocity(0,0,0)}resetForcesAndTorques(){this.resetForces(),this.resetTorques()}wakeUp(){var i;(i=this.context.physics.engine)==null||i.wakeup(this)}get isSleeping(){var i;return(i=this.context.physics.engine)==null?void 0:i.isSleeping(this)}updateProperties(){var i;return this._propertiesChanged=!1,(i=this.context.physics.engine)==null?void 0:i.updateProperties(this)}applyForce(i,A,e=!0){var g;this._propertiesChanged&&this.updateProperties(),(g=this.context.physics.engine)==null||g.addForce(this,i,e)}applyImpulse(i,A=!0){var e;this._propertiesChanged&&this.updateProperties(),(e=this.context.physics.engine)==null||e.applyImpulse(this,i,A)}setForce(i,A,e,g=!0){var I,o,s;(I=this.context.physics.engine)==null||I.resetForces(this,g),typeof i=="number"?(A??(A=0),e??(e=0),(o=this.context.physics.engine)==null||o.addForce(this,{x:i,y:A,z:e},g)):(s=this.context.physics.engine)==null||s.addForce(this,i,g)}getVelocity(){var i;const A=(i=this.context.physics.engine)==null?void 0:i.getLinearVelocity(this);return A?(this._currentVelocity.x=A.x,this._currentVelocity.y=A.y,this._currentVelocity.z=A.z,this._currentVelocity):this._currentVelocity.set(0,0,0)}setVelocity(i,A,e,g=!0){var I,o;if(i instanceof S){const s=i;(I=this.context.physics.engine)==null||I.setLinearVelocity(this,s,g);return}A===void 0||e===void 0||(o=this.context.physics.engine)==null||o.setLinearVelocity(this,{x:i,y:A,z:e},g)}getAngularVelocity(){var i;const A=(i=this.context.physics.engine)==null?void 0:i.getAngularVelocity(this);return A?(this._currentVelocity.x=A.x,this._currentVelocity.y=A.y,this._currentVelocity.z=A.z,this._currentVelocity):this._currentVelocity.set(0,0,0)}setAngularVelocity(i,A,e,g=!0){var I,o;if(i instanceof S){const s=i;(I=this.context.physics.engine)==null||I.setAngularVelocity(this,s,g);return}A===void 0||e===void 0||(o=this.context.physics.engine)==null||o.setAngularVelocity(this,{x:i,y:A,z:e},g)}setTorque(i,A,e){this.setAngularVelocity(i,A,e)}get smoothedVelocity(){return this._smoothedVelocityGetter.copy(this._smoothedVelocity),this._smoothedVelocityGetter.multiplyScalar(1/this.context.time.deltaTime)}setBodyFromGameObject(i=null){}captureVelocity(){const i=Fe(this.gameObject);wb.tempPosition.copy(i);const A=i.sub(this._lastPosition);this._lastPosition.copy(wb.tempPosition),this._smoothedVelocity.lerp(A,this.context.time.deltaTime/.1)}},B(Db,"tempPosition",new S),Db);let _t=wb;Wo([gI()],_t.prototype,"autoMass",2),Wo([y()],_t.prototype,"mass",1),Wo([gI(),y()],_t.prototype,"useGravity",2),Wo([y(S)],_t.prototype,"centerOfMass",2),Wo([gI(),y()],_t.prototype,"constraints",2),Wo([gI(),y()],_t.prototype,"isKinematic",2),Wo([gI(),y()],_t.prototype,"drag",2),Wo([gI(),y()],_t.prototype,"angularDrag",2),Wo([gI(),y()],_t.prototype,"detectCollisions",2),Wo([gI(),y()],_t.prototype,"sleepThreshold",2),Wo([gI(),y()],_t.prototype,"collisionDetectionMode",2),Wo([gI()],_t.prototype,"_gravityScale",2),Wo([gI()],_t.prototype,"dominanceGroup",2);const EB=iA("debugsync"),$p="STRS";bK($p,nC.getRootAsSyncedTransformModel);const Qa=new jw;function a8(i,A,e=!0){Qa.clear();const g=Qa.createString(i);nC.startSyncedTransformModel(Qa),nC.addGuid(Qa,g),nC.addFast(Qa,e);const I=A.worldPosition,o=A.worldEuler,s=A.gameObject.scale;nC.addTransform(Qa,n8.createTransform(Qa,I.x,I.y,I.z,o.x,o.y,o.z,s.x,s.y,s.z));const n=nC.endSyncedTransformModel(Qa);return Qa.finish(n,$p),Qa.asUint8Array()}let yb=0,AD=0;s8(i=>{var A;const e=(A=i.connection.currentServerUrl)!=null&&A.includes("glitch")?10:40;AD=Math.floor(yb/e),yb=0,EB&&AD>0&&console.log("Sync Transform Fast Interval",AD)});class cB extends bA{constructor(){super(...arguments),B(this,"overridePhysics",!0),B(this,"interpolatePosition",!0),B(this,"interpolateRotation",!0),B(this,"fastMode",!1),B(this,"syncDestroy",!1),B(this,"_model",null),B(this,"_needsUpdate",!0),B(this,"rb",null),B(this,"_wasKinematic",!1),B(this,"_receivedDataBefore",!1),B(this,"_targetPosition"),B(this,"_targetRotation"),B(this,"_receivedFastUpdate",!1),B(this,"_shouldRequestOwnership",!1),B(this,"joinedRoomCallback",null),B(this,"receivedDataCallback",null),B(this,"tempEuler",new It),B(this,"receivedUpdate",!1),B(this,"lastWorldPos"),B(this,"lastWorldRotation")}requestOwnership(){EB&&console.log("Request ownership"),this._model?this._model.requestOwnership():(this._shouldRequestOwnership=!0,this._needsUpdate=!0)}hasOwnership(){var A;return((A=this._model)==null?void 0:A.hasOwnership)??void 0}isOwned(){var A;return(A=this._model)==null?void 0:A.isOwned}awake(){EB&&console.log("new instance",this.guid,this),this._receivedDataBefore=!1,this._targetPosition=new S,this._targetRotation=new GA,this.lastWorldPos=new S,this.lastWorldRotation=new GA,this.rb=gA.getComponentInChildren(this.gameObject,_t),this.rb&&(this._wasKinematic=this.rb.isKinematic),this.receivedUpdate=!0,this._model=new Ab(this.context.connection,this.guid),this.context.connection.isConnected&&this.tryGetLastState(),this.joinedRoomCallback=this.tryGetLastState.bind(this),this.context.connection.beginListen(Pe.JoinedRoom,this.joinedRoomCallback),this.receivedDataCallback=this.onReceivedData.bind(this),this.context.connection.beginListenBinary($p,this.receivedDataCallback)}onDestroy(){this.syncDestroy&&Bb(this.guid,this.context.connection),this._model=null,this.context.connection.stopListen(Pe.JoinedRoom,this.joinedRoomCallback),this.context.connection.stopListenBinary($p,this.receivedDataCallback)}tryGetLastState(){const A=this.context.connection.tryGetState(this.guid);A&&this.onReceivedData(A)}onReceivedData(A){var e;if(!this.destroyed&&typeof A.guid=="function"&&A.guid()===this.guid){EB&&console.log("new data",this.context.connection.connectionId,this.context.time.frameCount,this.guid,A),this.receivedUpdate=!0,this._receivedFastUpdate=A.fast();const g=A.transform();if(g){en.markDirty(this.gameObject,!0);const I=g.position();I&&(this.interpolatePosition&&((e=this._targetPosition)==null||e.set(I.x(),I.y(),I.z())),(!this.interpolatePosition||!this._receivedDataBefore)&&this.setWorldPosition(I.x(),I.y(),I.z()));const o=g.rotation();o&&(this.tempEuler.set(o.x(),o.y(),o.z()),this.interpolateRotation&&this._targetRotation.setFromEuler(this.tempEuler),(!this.interpolateRotation||!this._receivedDataBefore)&&qN(this.gameObject,this.tempEuler))}this._receivedDataBefore=!0}}onEnable(){this.lastWorldPos.copy(this.worldPosition),this.lastWorldRotation.copy(this.worldQuaternion),this._needsUpdate=!0,this._model&&this._model.updateIsOwned()}onDisable(){this._model&&this._model.freeOwnership()}onBeforeRender(){if(!this.activeAndEnabled||!this.context.connection.isConnected)return;if(!this.context.connection.isInRoom||!this._model){EB&&console.log("no model or room",this.name,this.guid,this.context.connection.isInRoom);return}this._shouldRequestOwnership&&(this._shouldRequestOwnership=!1,this._model.requestOwnership());const A=this.worldPosition,e=this.worldQuaternion;if(this._model.isOwned&&!this.receivedUpdate){const o=A.distanceTo(this.lastWorldPos),s=e.angleTo(this.lastWorldRotation),n=this._model.hasOwnership||this.fastMode?1e-4:.001;(o>n||s>n)&&(this._model.hasOwnership?this._needsUpdate=!0:(EB&&console.log(this.guid,"reset because not owned but",this.gameObject.name,this.lastWorldPos),this.worldPosition=this.lastWorldPos,A.copy(this.lastWorldPos),this.worldQuaternion=this.lastWorldRotation,e.copy(this.lastWorldRotation),en.markDirty(this.gameObject,!0),this._needsUpdate=!1))}if(this._model&&!this._model.hasOwnership&&this._model.isOwned&&this._receivedDataBefore){const o=this._receivedFastUpdate||this.fastMode?.5:.3;let s=!1;if(this.interpolatePosition&&this._targetPosition){const n=this.worldPosition;n.lerp(this._targetPosition,o),this.worldPosition=n,s=!0}if(this.interpolateRotation&&this._targetRotation){const n=this.worldQuaternion;n.slerp(this._targetRotation,o),this.worldQuaternion=n,s=!0}s&&en.markDirty(this.gameObject,!0)}if(this.receivedUpdate=!1,this.lastWorldPos.copy(A),this.lastWorldRotation.copy(e),!this._model||!this._model||this._model.hasOwnership===void 0||!this._model.hasOwnership)return;this.rb&&this.overridePhysics&&this._wasKinematic!==void 0&&(EB&&console.log("reset kinematic",this.rb.name,this._wasKinematic),this.rb.isKinematic=this._wasKinematic);const g=10,I=this.rb||this.fastMode;if(this._needsUpdate&&(this.context.time.frameCount%g===0||I)){if(yb++,I&&AD>0&&this.context.time.frameCount%AD!==0)return;EB&&console.log("send update",this.context.connection.connectionId,this.guid,this.gameObject.name,this.gameObject.guid),this._needsUpdate=!1;const o=a8(this.guid,this,!!I);this.context.connection.sendBinary(o)}}}const cEA=iA("debugshadowcomponents");fN.prototype.interactable={get(){return this.interactive},set(i){this.interactable=i}};const Js=Symbol("shadowDomOwner");class $s extends bA{constructor(){super(...arguments),B(this,"_shadowComponent",null),B(this,"_controlsChildLayout",!0),B(this,"_root"),B(this,"_parentComponent")}isRoot(){var A;return((A=this.Root)==null?void 0:A.gameObject)===this.gameObject}get canvas(){const A=this.Root;return A!=null&&A.isCanvas?A:null}get Canvas(){return this.canvas}markDirty(){xs.markUIDirty(this.context)}get shadowComponent(){return this._shadowComponent}set shadowComponent(A){this._shadowComponent=A}get controlsChildLayout(){return this._controlsChildLayout}set controlsChildLayout(A){this._controlsChildLayout=A,this.shadowComponent&&(this.shadowComponent.autoLayout=A)}get Root(){return this._root===void 0&&(this._root=gA.getComponentInParent(this.gameObject,eD)),this._root}__internalNewInstanceCreated(A){return super.__internalNewInstanceCreated(A),this.shadowComponent=null,this._root=void 0,this._parentComponent=void 0,this}onEnable(){super.onEnable()}addShadowComponent(A,e){var g;if(!A)return;this.removeShadowComponent();const I=this.isRoot()?this.gameObject:this.gameObject.parent;if(this._parentComponent=gA.getComponentInParent(I,$s),!this._parentComponent){console.warn(`Component "${this.name}" doesn't have a UI parent anywhere. Do you have an UI element outside a Canvas? UI components must be a child of a Canvas component`,this);return}A.name=this.name+" ("+(this.constructor.name??"UI")+")",A.autoLayout=this._parentComponent.controlsChildLayout,A[Js]=this,this.setShadowComponentOwner(A);let o=!1;if(((g=this.Root)==null?void 0:g.gameObject)===this.gameObject)this.gameObject.add(A);else{const s=this._parentComponent.shadowComponent;s&&(s?.add(A),o=!0)}this.shadowComponent=A,e&&e.shadowComponent&&this.shadowComponent&&e.shadowComponent.add(this.shadowComponent),fp&&A.add(new _o(.5)),this.onAfterAddedToScene(),o&&LY(),cEA&&console.warn("Added shadow component",this.shadowComponent)}setShadowComponentOwner(A){if(A&&(A[Js]===void 0||A[Js]===this)&&(A[Js]=this,A.children))for(const e of A.children)this.setShadowComponentOwner(e)}traverseOwnedShadowComponents(A,e,g){if(A&&A[Js]===e){g(A);for(const I of A.children)this.traverseOwnedShadowComponents(I,e,g)}}removeShadowComponent(){this.shadowComponent&&this.shadowComponent.removeFromParent()}onAfterAddedToScene(){}setInteractable(A){this.shadowComponent&&(this.shadowComponent.interactable=A)}}class eD extends $s{awake(){super.awake()}}class wd{constructor(A,e){B(this,"event"),B(this,"button"),B(this,"buttonName"),B(this,"_used",!1),B(this,"_propagationStopped",!1),B(this,"z__pointer_ctured",!1),B(this,"z__pointer_cture_rleased",!1),B(this,"inputSource"),B(this,"object"),B(this,"point"),B(this,"normal"),B(this,"face"),B(this,"distance"),B(this,"instanceId"),B(this,"intersection"),B(this,"isDown"),B(this,"isUp"),B(this,"isPressed"),B(this,"isClick"),B(this,"isDoubleClick"),B(this,"input"),this.event=e,this.input=A,this.button=e.button}get deviceIndex(){return this.event.deviceIndex}get pointerId(){return this.event.pointerId}get pressure(){return this.event.pressure}get used(){return this._used}use(){this._used||(this._used=!0,this.event.use(),this.pointerId!==void 0&&this.input.setPointerUsed(this.pointerId))}get propagationStopped(){return this._propagationStopped}stopPropagation(){this._propagationStopped=!0,this.event.stopImmediatePropagation()}stopImmediatePropagation(){this._propagationStopped=!0,this.event.stopImmediatePropagation()}setPointerCapture(){this.z__pointer_ctured=!0}releasePointerCapture(){this.z__pointer_cture_rleased=!0}get mode(){return this.event.mode}clone(){const A=new wd(this.input,this.event);return Object.assign(A,this),A}Use(){this.use()}StopPropagation(){this.event.stopImmediatePropagation()}}function mb(i,A){return gA.foreachComponent(i,e=>{if(!e.enabled)return;const g=e;if(A)switch(A){case"pointerdown":if(g.onPointerDown)return!0;break;case"pointerup":if(g.onPointerUp||g.onPointerClick)return!0;break;case"pointermove":if(g.onPointerEnter||g.onPointerExit||g.onPointerMove)return!0;break}else if(g.onPointerDown||g.onPointerUp||g.onPointerEnter||g.onPointerExit||g.onPointerClick)return!0},!1)===!0}var lEA=Object.defineProperty,dEA=Object.getOwnPropertyDescriptor,uEA=(i,A,e,g)=>{for(var I=g>1?void 0:g?dEA(A,e):A,o=i.length-1,s;o>=0;o--)(s=i[o])&&(I=(g?s(A,e,I):s(I))||I);return g&&I&&lEA(A,e,I),I};class tD extends bA{awake(){xs.createIfNoneExists(this.context)}onEnable(){var A;(A=xs.get(this.context))==null||A.register(this)}onDisable(){var A;(A=xs.get(this.context))==null||A.unregister(this)}}class Zo extends tD{constructor(){super(...arguments),B(this,"targets",null),B(this,"raycastHits",[]),B(this,"ignoreSkinnedMeshes",!1)}start(){this.targets=[this.gameObject]}performRaycast(A=null){if(!this.targets)return null;A??(A=new fn),A.targets=this.targets,A.results=this.raycastHits;const e=A.testObject;this.ignoreSkinnedMeshes&&(A.testObject=I=>I instanceof wo?"continue in children":e?e(I):!0);const g=this.context.physics.raycast(A);return A.testObject=e,g}}uEA([y()],Zo.prototype,"ignoreSkinnedMeshes",2);class ff extends Zo{constructor(){super(),this.ignoreSkinnedMeshes=!0}}class iD extends tD{performRaycast(A){if(!me.active||!(A!=null&&A.ray))return null;const e=A.ray.origin,g=.01;return this.context.physics.sphereOverlap(e,g)}}class kf{static getObject(A){const e=A[Js];return e&&(e.isComponent===!0?A=e.gameObject:A=e),A}static isInteractable(A,e){if(e&&(e.canvasGroup=void 0,e.graphic=void 0),A==null||!A.visible||(A=this.getObject(A),!A.visible))return!1;const g=this.tryFindCanvasGroup(A);if(g?.isCanvasGroup===!0&&(e&&(e.canvasGroup=g),g.blocksRaycasts===!1||g.interactable===!1))return!1;const I=dh(A,o=>{if(o.isGraphic===!0)return o},!1);return e&&I?.isGraphic===!0&&(e.graphic=I),!(I?.raycastTarget===!1||I?.layer===2)}static tryFindCanvasGroup(A){if(!A)return null;const e=dh(A,g=>{const I=g;if(I.blocksRaycasts!==void 0&&I.interactable!==void 0)return I},!1);return e!==void 0?e:this.tryFindCanvasGroup(A.parent)}}function Sb(i){return i[Js]||(i.parent?Sb(i.parent):null)}function pEA(i){return i.isUI===!0||typeof i[Js]=="object"}function Mf(i,A){if(!i)return;const e=i.material;if(e?.isMaterial===!0){const g=i.parent;g&&g.isText,e.side=A.doubleSided??!0?yt:Eg,e.shadowSide=A.doubleSided?yt:Eg,i.castShadow=A.castShadows?A.castShadows:!1,i.receiveShadow=A.receiveShadows?A.receiveShadows:!1}for(const g of i.children)Mf(g,A)}function ll(i,A,e){i[A]===void 0&&console.warn("Field",A,"is undefined on",i);const g=Proxy.revocable(i[A],{set(s,n,a,r){const C=s[n],Q=Reflect.set(s,n,a,r);return e(a,C),Q}}),I=g.revoke,o=i[A];return g.revoke=()=>{i[A]=o,I()},i[A]=g.proxy,g}const r8=Symbol("Scheduled action");function DEA(i,A,e=Xt.OnBeforeRender){let g=i[r8];g||(g=i[r8]={});const I=A.name;g[e]||(g[e]={});const o=g[e];if(o[I])return;function*s(){A?.call(i),o[I]=null}const n=i.startCoroutine(s(),e);o[I]=n}const vr=iA("debugeventsystem");var fb=(i=>(i.BeforeHandleInput="BeforeHandleInput",i.AfterHandleInput="AfterHandleInput",i))(fb||{});const Kr=class extends bA{constructor(){super(),B(this,"raycaster",[]),B(this,"_handleInputFn"),B(this,"pressedByID",new Map),B(this,"hoveredByID",new Map),B(this,"_sortedHits",[]),B(this,"_testObjectsCache",new Map),B(this,"_currentlyActiveRaycaster",null),B(this,"_currentPointerEventName",null),B(this,"shouldRaycastObject",i=>{var A;let e=null;if(pEA(i)&&(e=(A=i[Js])==null?void 0:A.gameObject),this._testObjectsCache.has(i)||e&&this._testObjectsCache.has(e))return this._testObjectsCache.get(i)===!1?"continue in children":!0;{let g=mb(i,this._currentPointerEventName);if(!g&&e&&(g=mb(e,this._currentPointerEventName)),g){this._testObjectsCache.set(i,!0);for(const I of i.children)this.shouldRaycastObject_AddToYesCache(I);return!0}return this._testObjectsCache.set(i,!1),"continue in children"}}),B(this,"_sortingBuffer",[]),B(this,"_noDepthTestingResults",[]),B(this,"out",{}),B(this,"_capturedPointer",{}),B(this,"pointerEnterSymbol",Symbol("pointerEnter")),B(this,"pointerExitSymbol",Symbol("pointerExit")),B(this,"currentActiveMeshUIComponents",[]),Kr.systems.push(this)}static createIfNoneExists(i){this.didSearchEventSystem||(this.didSearchEventSystem=!0,Kr.systems.length<=0&&Kr.systems.push(...gA.findObjectsOfType(Kr,i)));for(const e of Kr.systems)if(e.context===i)return;const A=new wA;gA.addNewComponent(A,Kr),i.scene.add(A)}static get systems(){const i=Ke.Current;return this._eventSystemMap.has(i)||this._eventSystemMap.set(i,[]),this._eventSystemMap.get(i)}static get(i){const A=this._eventSystemMap.get(i);return A&&A.length>0?A[0]:null}static get instance(){return this.systems[0]}static ensureUpdateMeshUI(i,A,e=!1){lB.update(i,A,e)}static markUIDirty(i){lB.markDirty()}get hasActiveUI(){return this.currentActiveMeshUIComponents.length>0}get isHoveringObjects(){return this.hoveredByID.size>0}onDestroy(){Kr.systems.splice(Kr.systems.indexOf(this),1)}start(){if(this.raycaster.length<=0&&!gA.findObjectOfType(tD,this.context)){const i=gA.addNewComponent(this.context.scene,Zo);this.raycaster.push(i),(se()||vr)&&console.warn("Added an ObjectRaycaster to the scene because no raycaster was found.")}}register(i){var A;i&&this.raycaster&&!this.raycaster.includes(i)&&((A=this.raycaster)==null||A.push(i))}unregister(i){var A,e;const g=(A=this.raycaster)==null?void 0:A.indexOf(i);g!==void 0&&g!==-1&&((e=this.raycaster)==null||e.splice(g,1))}onEnable(){this._handleInputFn??(this._handleInputFn=this.onPointerEvent.bind(this)),this.context.input.addEventListener(hi.PointerDown,this._handleInputFn),this.context.input.addEventListener(hi.PointerUp,this._handleInputFn),this.context.input.addEventListener(hi.PointerMove,this._handleInputFn)}onDisable(){this.context.input.removeEventListener(hi.PointerDown,this._handleInputFn),this.context.input.removeEventListener(hi.PointerUp,this._handleInputFn),this.context.input.removeEventListener(hi.PointerMove,this._handleInputFn)}onBeforeRender(){this.resetMeshUIStates()}onPointerEvent(i){if(i===void 0||i.propagationStopped)return;const A=new wd(this.context.input,i);this._currentPointerEventName=i.type,A.inputSource=this.context.input,A.isClick=i.isClick,A.isDoubleClick=i.isDoubleClick,A.isDown=i.type==hi.PointerDown,A.isUp=i.type==hi.PointerUp,A.isPressed=this.context.input.getPointerPressed(i.pointerId),vr&&(A.isDown?console.log("DOWN",A.pointerId):A.isUp&&console.log("UP",A.pointerId),A.isClick&&console.log("CLICK",A.pointerId));const e=new fn;i.hasRay?e.ray=i.ray:e.screenPoint=this.context.input.getPointerPositionRC(i.pointerId);const g=this.performRaycast(e);if(g){for(const o of g)o.event=i,i.intersections.push(o);i.origin.onPointerHits&&i.origin.onPointerHits({sender:this,event:i,hits:g})}vr&&A.isClick&&Ci("EventSystem: "+A.pointerId+" - "+this.context.time.frame+" - Up:"+A.isUp+", Down:"+A.isDown);const I={sender:this,args:A,hasActiveUI:this.currentActiveMeshUIComponents.length>0};this.dispatchEvent(new CustomEvent("BeforeHandleInput",{detail:I})),this.handleIntersections(g,A),this.dispatchEvent(new CustomEvent("AfterHandleInput",{detail:I}))}shouldRaycastObject_AddToYesCache(i){this._testObjectsCache.set(i,!0);for(const A of i.children)this.shouldRaycastObject_AddToYesCache(A)}performRaycast(i){if(!this.raycaster)return null;this._testObjectsCache.clear(),this._sortedHits.length=0,i||(i=new fn),i.testObject=this.shouldRaycastObject;for(const A of this.raycaster){if(!A.activeAndEnabled)continue;this._currentlyActiveRaycaster=A;const e=A.performRaycast(i);this._currentlyActiveRaycaster=null,e&&e.length>0&&this._sortedHits.push(...e)}return this._sortedHits.sort((A,e)=>A.distance-e.distance),this._sortedHits}assignHitInformation(i,A){A?(i.intersection=A,i.point=A.point,i.normal=A.normal,i.face=A.face,i.distance=A.distance,i.instanceId=A.instanceId):(i.intersection=void 0,i.point=void 0,i.normal=void 0,i.face=void 0,i.distance=void 0,i.instanceId=void 0)}handleIntersections(i,A){var e;if(i!=null&&i.length){i=this.sortCandidates(i);for(const I of i){if(A.event.immediatePropagationStopped)return!1;if(this.assignHitInformation(A,I),this.handleEventOnObject(I.object,A))return!0}}this.assignHitInformation(A,i?.[0]),this.invokePointerCapture(A);const g=this.hoveredByID.get(A.pointerId);return g&&this.propagatePointerExit(g.obj,g.data,null),this.hoveredByID.delete(A.pointerId),A.isUp&&((e=this.pressedByID.get(A.pointerId))==null||e.handlers.forEach(I=>this.invokeOnPointerUp(A,I)),this.pressedByID.delete(A.pointerId)),!1}sortCandidates(i){this._sortingBuffer.length=0,this._noDepthTestingResults.length=0;for(let A=0;A<i.length;A++){const e=i[A],g=e.object;if(g.material&&g.material.depthTest===!1){this._noDepthTestingResults.push(e);continue}this._sortingBuffer.push(e)}for(const A of this._sortingBuffer)this._noDepthTestingResults.push(A);return this._noDepthTestingResults}handleEventOnObject(i,A){if(!this.testIsVisible(i))return A.isClick&&vr&&console.log("not allowed",i),!1;if(A.pointerId===void 0)return vr&&console.error("Event without pointer can't be handled",A),!1;A.object=i;const e=i.parent,g=A.isClick??!1;let I=null;if(e&&e.isUI){const a=(A.isPressed||A.isClick)??!1;if(e[Js]){const r=e[Js].gameObject;if(r){if(!kf.isInteractable(r,this.out))return!1;I=this.out.canvasGroup??null,this.handleMeshUIIntersection(i,a),i=r}}}g&&vr&&console.log(this.context.time.frame,i);const o=this.hoveredByID.get(A.pointerId),s=o?.obj;s!==i&&s&&this.propagatePointerExit(s,o.data,i);const n=this.hoveredByID.get(A.pointerId);if(n?(n.obj=i,n.data=A):this.hoveredByID.set(A.pointerId,{obj:i,data:A}),A.isDown){const a=this.pressedByID.get(A.pointerId);a?(a.obj=i,a.data=A):this.pressedByID.set(A.pointerId,{obj:i,data:A,handlers:new Set})}return(I===null||I.interactable)&&this.handleMainInteraction(i,A,s??null),!0}propagate(i,A){for(;i;)gA.foreachComponent(i,e=>{A(e)},!1),i=i.parent}handleMainInteraction(i,A,e){const g=this.pressedByID.get(A.pointerId),I=e!==i;let o=!0;switch(A.event.pointerType){case"mouse":case"touch":const s=this.context.input.getPointerPositionLastFrame(A.pointerId),n=this.context.input.getPointerPosition(A.pointerId);o=s&&!ge.approximately(s,n);break}this.propagate(i,s=>{var n;const a=s;a.interactable!==!1&&(!a.activeAndEnabled||!a.enabled||(a.onPointerEnter&&I&&this.handlePointerEnter(a,A),A.isDown&&a.onPointerDown&&(a.onPointerDown(A),g?.handlers.add(a),this.handlePointerCapture(A,a)),a.onPointerMove&&(o&&a.onPointerMove(A),this.handlePointerCapture(A,a)),A.isUp&&(a.onPointerUp&&(this.invokeOnPointerUp(A,a),g?.handlers.delete(a)),a.onPointerExit&&((n=A.event)==null?void 0:n.pointerType)===bS.Touch&&(this.handlePointerExit(a,A),this.hoveredByID.delete(A.pointerId))),A.isClick&&a.onPointerClick&&a.onPointerClick(A)))}),A.isUp&&(g?.handlers.forEach(s=>{this.invokeOnPointerUp(A,s)}),this.pressedByID.delete(A.pointerId))}propagatePointerExit(i,A,e){this.propagate(i,g=>{if(!g.gameObject||g.destroyed)return;const I=g;if(I.onPointerExit){if(e&&this.isChild(e,g.gameObject))return;this.handlePointerExit(I,A)}})}invokeOnPointerUp(i,A){var e;(e=A.onPointerUp)==null||e.call(A,i),this.releasePointerCapture(i,A)}handlePointerEnter(i,A){i.onPointerEnter&&this.updatePointerState(i,A.pointerId,this.pointerEnterSymbol,!0)&&i.onPointerEnter(A),this.updatePointerState(i,A.pointerId,this.pointerExitSymbol,!1)}handlePointerExit(i,A){i.onPointerExit&&this.updatePointerState(i,A.pointerId,this.pointerExitSymbol,!0)&&i.onPointerExit(A),this.updatePointerState(i,A.pointerId,this.pointerEnterSymbol,!1)}updatePointerState(i,A,e,g){let I=i[e];if(g)return I&&I.includes(A)?!1:(I=I||[],I.push(A),i[e]=I,!0);{if(!I||!I.includes(A))return!1;const o=I.indexOf(A);return o!==-1&&I.splice(o,1),!0}}handlePointerCapture(i,A){if(i.z__pointer_ctured){i.z__pointer_ctured=!1;const e=i.pointerId;if(A.onPointerMove){const g=this._capturedPointer[e]||[];g.push(A),this._capturedPointer[e]=g}else se()&&!A.z__warned_no_pointermove&&(A.z__warned_no_pointermove=!0,console.warn("PointerCapture was requested but the component doesn't implement onPointerMove. It will not receive any pointer events"))}else i.z__pointer_cture_rleased&&(i.z__pointer_cture_rleased=!1,this.releasePointerCapture(i,A))}releasePointerCapture(i,A){const e=i.pointerId;if(this._capturedPointer[e]){const g=this._capturedPointer[e].indexOf(A);g!==-1&&(this._capturedPointer[e].splice(g,1),vr&&console.log("released pointer capture",e,A,this._capturedPointer))}}invokePointerCapture(i){var A;if(i.event.type===hi.PointerMove){const e=i.pointerId,g=this._capturedPointer[e];if(g){vr&&console.log("Captured",e,g);for(let I=0;I<g.length;I++){const o=g[I];if(o.destroyed){g.splice(I,1),I--;continue}(A=o.onPointerMove)==null||A.call(o,i)}}}}isChild(i,A){return!i||!A?!1:i===A?!0:i.parent?this.isChild(i.parent,A):!1}handleMeshUiObjectWithoutShadowDom(i,A){return!i||!i.isUI?!0:this.handleMeshUIIntersection(i,A)}handleMeshUIIntersection(i,A){const e=lB.updateState(i,A);return e&&this.currentActiveMeshUIComponents.push(e),e!==null}resetMeshUIStates(){if(this.context.input.getPointerPressedCount()>0&&lB.resetLastSelected(),!(!this.currentActiveMeshUIComponents||this.currentActiveMeshUIComponents.length<=0)){for(let i=0;i<this.currentActiveMeshUIComponents.length;i++){const A=this.currentActiveMeshUIComponents[i];lB.resetState(A)}this.currentActiveMeshUIComponents.length=0}}testIsVisible(i){return i?gA.isActiveSelf(i)?this.testIsVisible(i.parent):!1:!0}};let xs=Kr;B(xs,"_eventSystemMap",new Map),B(xs,"didSearchEventSystem",!1);class lB{static markDirty(){this.needsUpdate=!0}static update(A,e,g=!1){if(g){A.update();return}const I=e.time.frameCount;for(const o of this.lastUpdateFrame)if(o.context===e){if(I===o.frame)return;o.frame=I;let s=this.needsUpdate||I<1;o.nextUpdate===e.time.frameCount&&(s=!0),s&&(vr&&console.log("Update threemeshui"),this.needsUpdate=!1,A.update());return}this.lastUpdateFrame=[{context:e,frame:I,nextUpdate:I}],A.update()}static updateState(A,e){let g=null;if(A&&(g=this.findBlockInParent(A),g&&g!==this.lastSelected)){if(g.interactable===!1)return null;this.needsUpdate=!0}return g}static resetLastSelected(){const A=this.lastSelected;A&&(this.lastSelected=null,this.resetState(A))}static resetState(A){A&&(this.needsUpdate=!0)}static findBlockInParent(A){return A?A.isBlock?A:this.findBlockInParent(A.parent):null}}B(lB,"lastSelected",null),B(lB,"lastUpdateFrame",[]),B(lB,"needsUpdate",!1);var wEA=Object.defineProperty,yEA=Object.getOwnPropertyDescriptor,Ei=(i,A,e,g)=>{for(var I=g>1?void 0:g?yEA(A,e):A,o=i.length-1,s;o>=0;o--)(s=i[o])&&(I=(g?s(A,e,I):s(I))||I);return g&&I&&wEA(A,e,I),I};const kb=iA("debugorbit"),Gf=iA("freecam"),Rf=iA("debugcamerafit"),Uf=iA("smoothcam"),mEA={LEFT:"",UP:"",RIGHT:"",BOTTOM:""};let Mb;class gD extends CustomEvent{constructor(A,e){super("target-reached",{detail:{controls:A,type:e}})}}class St extends bA{constructor(){super(...arguments),B(this,"autoTarget",!0),B(this,"autoFit",!1),B(this,"enableRotate",!0),B(this,"autoRotate",!1),B(this,"autoRotateSpeed",1),B(this,"minAzimuthAngle",1/0),B(this,"maxAzimuthAngle",1/0),B(this,"minPolarAngle",0),B(this,"maxPolarAngle",Math.PI),B(this,"enableKeys",!0),B(this,"enableDamping",!0),B(this,"dampingFactor",.1),B(this,"enableZoom",!0),B(this,"minZoom",0),B(this,"maxZoom",1/0),B(this,"zoomSpeed",1),B(this,"zoomToCursor",!1),B(this,"enablePan",!0),B(this,"lookAtConstraint",null),B(this,"lookAtConstraint01",1),B(this,"allowInterrupt",!0),B(this,"middleClickToFocus",!0),B(this,"doubleClickToFocus",!0),B(this,"clickBackgroundToFitScene",2),B(this,"debugLog",!1),B(this,"targetLerpDuration",1),B(this,"_controls",null),B(this,"_cameraObject",null),B(this,"_lookTargetLerpActive",!1),B(this,"_lookTargetStartPosition",new S),B(this,"_lookTargetEndPosition",new S),B(this,"_lookTargetLerp01",0),B(this,"_lookTargetLerpDuration",0),B(this,"_cameraLerpActive",!1),B(this,"_cameraStartPosition",new S),B(this,"_cameraEndPosition",new S),B(this,"_cameraLerp01",0),B(this,"_cameraLerpDuration",0),B(this,"_inputs",0),B(this,"_enableTime",0),B(this,"_startedListeningToKeyEvents",!1),B(this,"_eventSystem"),B(this,"_afterHandleInputFn"),B(this,"_camera",null),B(this,"_syncedTransform"),B(this,"_didSetTarget",0),B(this,"targetElement",null),B(this,"_lastTimeClickOnBackground",-1),B(this,"_clickOnBackgroundCount",0),B(this,"_onPointerDown",A=>{if(this.clickBackgroundToFitScene>0&&A.isClick&&A.button===0){if(A.hasRay||A.intersections.push(...this.context.physics.raycast()),A.intersections.length<=0){const e=this.context.time.time-this._lastTimeClickOnBackground;this._lastTimeClickOnBackground=this.context.time.time,this.clickBackgroundToFitScene<=1||e<this.clickBackgroundToFitScene*.15?(this._clickOnBackgroundCount+=1,this._clickOnBackgroundCount>=this.clickBackgroundToFitScene-1&&this.fitCamera(this.context.scene.children,{immediate:!1})):this._clickOnBackgroundCount=0}kb&&console.log(this.clickBackgroundToFitScene,A.intersections.length,this._clickOnBackgroundCount)}}),B(this,"onControlsChangeStarted",()=>{this._syncedTransform&&this._syncedTransform.requestOwnership()}),B(this,"_shouldDisable",!1),B(this,"__onPreRender",()=>{const A=this.context.pre_render_callbacks.indexOf(this.__onPreRender);A>=0&&this.context.pre_render_callbacks.splice(A,1),this.autoFit&&(this.autoFit=!1,this.fitCamera(this.scene.children,{centerCamera:"y",immediate:!0}))}),B(this,"_haveAttachedKeyboardEvents",!1)}get isCameraController(){return!0}get controls(){return this._controls}get controllerObject(){return this._cameraObject}onStartInteraction(A){var e;(e=this.controls)==null||e.addEventListener("start",A)}get targetLerpSpeed(){return 5}set targetLerpSpeed(A){this.targetLerpDuration=1/A}awake(){this._didSetTarget=0,this._startedListeningToKeyEvents=!1}start(){this._eventSystem=xs.get(this.context)??void 0,this._eventSystem&&(this._afterHandleInputFn=this.afterHandleInput.bind(this),this._eventSystem.addEventListener(fb.AfterHandleInput,this._afterHandleInputFn))}onDestroy(){var A,e;(A=this._controls)==null||A.dispose(),(e=this._eventSystem)==null||e.removeEventListener(fb.AfterHandleInput,this._afterHandleInputFn)}onEnable(){this._didSetTarget=0,this._enableTime=this.context.time.time;const A=gA.getComponent(this.gameObject,Tt);this._camera=A;let e=A?.cam;if(!e&&this.gameObject instanceof xe&&(e=this.gameObject),e&&RN(e,this,!0),!this._controls&&e instanceof xe){this._cameraObject=e;const g=this.targetElement??this.context.renderer.domElement,I=e?.quaternion.clone();this._controls=new g8(e,g),e?.quaternion.copy(I),Mb===void 0&&(Mb={...this._controls.keys})}this._controls&&(Gf&&(this.enablePan=!0,this.enableZoom=!0,this.middleClickToFocus=!0,ls()&&(this.doubleClickToFocus=!0)),this._controls.addEventListener("start",this.onControlsChangeStarted),e?.type==="PerspectiveCamera"?Gf||(this._controls.minDistance=this.minZoom,this._controls.maxDistance=this.maxZoom):Gf||(this._controls.minZoom=this.minZoom,this._controls.maxZoom=this.maxZoom),this._startedListeningToKeyEvents||(this._startedListeningToKeyEvents=!0,this._controls.listenToKeyEvents(window.document.body))),this._syncedTransform=gA.getComponent(this.gameObject,cB)??void 0,this.context.input.addEventListener("pointerup",this._onPointerDown),this.context.pre_render_callbacks.push(this.__onPreRender)}onDisable(){var A;(A=this._camera)!=null&&A.cam&&RN(this._camera.cam,this,!1),this._controls&&(this._controls.enabled=!1,this._controls.autoRotate=!1,this._controls.removeEventListener("start",this.onControlsChangeStarted)),this.context.input.removeEventListener("pointerup",this._onPointerDown)}afterHandleInput(A){A.detail.args.pointerId===0&&(A.detail.args.isDown?this._controls&&this._eventSystem&&(this._shouldDisable=this._eventSystem.hasActiveUI):(!A.detail.args.isPressed||A.detail.args.isUp)&&(this._shouldDisable=!1))}onBeforeRender(){var A,e;if(!this._controls)return;if(this._cameraObject!==this.context.mainCamera){this._controls.enabled=!1;return}if(this._controls.enabled=!0,(this.context.input.getPointerDown(1)||this.context.input.getPointerDown(2)||this.context.input.mouseWheelChanged||this.context.input.getPointerPressed(0)&&(A=this.context.input.getPointerPositionDelta(0))!=null&&A.length()||0>.1)&&(this._inputs+=1),this._inputs>0&&this.allowInterrupt&&(this.enableRotate&&(this.autoRotate=!1),this._cameraLerpActive=!1,this._lookTargetLerpActive=!1),this._inputs=0,this.autoTarget&&this._didSetTarget++===0){const I=gA.getComponent(this.gameObject,Tt);if(I&&!this.setLookTargetFromConstraint()){this.debugLog&&console.log("NO TARGET");const o=Fe(I.cam),s=Math.max(.01,o.length()),n=new S(0,0,-s).applyMatrix4(I.cam.matrixWorld);this.setLookTargetPosition(n,!0)}if(!this.setLookTargetFromConstraint()){const o=new fn;o.screenPoint=new AA(0,0),o.lineThreshold=.1;const s=this.context.physics.raycast(o);s.length>0&&this.setLookTargetPosition(s[0].point,!0),Rf&&console.log("OrbitControls hits",...s)}}let g=this.middleClickToFocus&&this.context.input.getPointerClicked(1);if(g||(g=this.doubleClickToFocus&&this.context.input.getPointerDoubleClicked(0)&&this.context.time.time-this._enableTime>.3),g&&this.setTargetFromRaycast(),this._lookTargetLerpActive||this._cameraLerpActive){if(this._cameraLerpActive&&this._cameraObject)if(this._cameraLerp01+=this.context.time.deltaTime/this._cameraLerpDuration,this._cameraLerp01>=1)this._cameraObject.position.copy(this._cameraEndPosition),this._cameraLerpActive=!1,this.dispatchEvent(new gD(this,"camera"));else{const I=ge.easeInOutCubic(this._cameraLerp01);this._cameraObject.position.lerpVectors(this._cameraStartPosition,this._cameraEndPosition,I)}if(this._lookTargetLerpActive)if(this._lookTargetLerp01+=this.context.time.deltaTime/this._lookTargetLerpDuration,this._lookTargetLerp01>=1)this._controls.target.copy(this._lookTargetEndPosition),this._lookTargetLerpActive=!1,this.dispatchEvent(new gD(this,"lookat"));else{const I=ge.easeInOutCubic(this._lookTargetLerp01);this._controls.target.lerpVectors(this._lookTargetStartPosition,this._lookTargetEndPosition,I)}}if(this._controls){if(this.debugLog&&(this._controls.domElement=this.context.renderer.domElement),this._controls.enabled=!this._shouldDisable&&this._camera===this.context.mainCameraComponent&&!this.context.isInXR,this._controls.keys=this.enableKeys?Mb:mEA,this._controls.autoRotate=this.autoRotate,this._controls.autoRotateSpeed=this.autoRotateSpeed,this._controls.enableZoom=this.enableZoom,this._controls.zoomSpeed=this.zoomSpeed,this._controls.zoomToCursor=this.zoomToCursor,this._controls.enableDamping=this.enableDamping,this._controls.dampingFactor=this.dampingFactor,this._controls.enablePan=this.enablePan,this._controls.enableRotate=this.enableRotate,this._controls.minAzimuthAngle=this.minAzimuthAngle,this._controls.maxAzimuthAngle=this.maxAzimuthAngle,this._controls.minPolarAngle=this.minPolarAngle,this._controls.maxPolarAngle=this.maxPolarAngle,typeof Uf=="number"||Uf===!0){this._controls.enableDamping=!0;const I=typeof Uf=="number"?Uf:.99;this._controls.dampingFactor=Math.max(.001,1-Math.min(1,I))}this.allowInterrupt||(this._lookTargetLerpActive&&(this._controls.enablePan=!1),this._cameraLerpActive&&(this._controls.enableRotate=!1,this._controls.autoRotate=!1),(this._lookTargetLerpActive||this._cameraLerpActive)&&(this._controls.enableZoom=!1)),this.context.isInXR||(!Gf&&(e=this.lookAtConstraint)!=null&&e.locked&&this.setLookTargetFromConstraint(0,this.lookAtConstraint01),this._controls.update(),kb&&pe.DrawWireSphere(this._controls.target,.1,65280))}}setCameraAndLookTarget(A){if(!A||!(A instanceof wA))return;const e=Fe(A),g=JN(A);this.setTargetFromRaycast(new po(e,g)),this.setCameraTargetPosition(e)}setCameraTargetPosition(A,e=!1){var g,I;A&&(A instanceof wA&&(A=Fe(A)),this._cameraEndPosition||(this._cameraEndPosition=new S),this._cameraEndPosition.copy(A),e===!0?(this._cameraLerpActive=!1,(g=this.controllerObject)==null||g.position.copy(this._cameraEndPosition)):this._cameraObject&&(this._cameraLerpActive=!0,this._cameraLerp01=0,this._cameraStartPosition.copy((I=this._cameraObject)==null?void 0:I.position),typeof e=="number"?this._cameraLerpDuration=e:this._cameraLerpDuration=this.targetLerpDuration))}get cameraLerpActive(){return this._cameraLerpActive}stopCameraLerp(){this._cameraLerpActive=!1}setLookTargetPosition(A=null,e=!1){this._controls&&A&&(A instanceof wA&&(A=Fe(A)),this._lookTargetEndPosition.copy(A),kb&&(console.warn("OrbitControls: setLookTargetPosition",A,e),pe.DrawWireSphere(this._lookTargetEndPosition,.2,16711680,2)),e===!0?this._controls.target.copy(this._lookTargetEndPosition):(this._lookTargetLerpActive=!0,this._lookTargetLerp01=0,this._lookTargetStartPosition.copy(this._controls.target),typeof e=="number"?this._lookTargetLerpDuration=e:this._lookTargetLerpDuration=this.targetLerpDuration))}get lookTargetLerpActive(){return this._lookTargetLerpActive}stopLookTargetLerp(){this._lookTargetLerpActive=!1}setLookTargetFromConstraint(A=0,e=1){var g;if(!this._controls)return!1;const I=(g=this.lookAtConstraint)==null?void 0:g.sources;if(I&&I.length>0){const o=I[A];if(o)return o.getWorldPosition(this._lookTargetEndPosition),this.lerpLookTarget(this._lookTargetEndPosition,e),!0}return!1}lerpTarget(A,e){return this.lerpLookTarget(A,e)}lerpLookTarget(A,e){this._controls&&(e>=1?this._controls.target.copy(A):this._controls.target.lerp(A,e))}setTargetFromRaycast(A){if(!this.controls)return;const e=A?this.context.physics.raycastFromRay(A):this.context.physics.raycast();for(const g of e)if(g.distance>0&&gA.isActiveInHierarchy(g.object)){const I=Sb(g.object);if(I){const o=I.canvas;if(o!=null&&o.screenspace)break}this.setLookTargetPosition(g.point);break}}fitCamera(A,e={fitOffset:void 0,immediate:!1}){if(this.context.isInXR)return;const{immediate:g=!1,centerCamera:I}=e;let{fitOffset:o}=e;o==null&&(o=1.1);const s=this._cameraObject,n=this._controls;if(A!=null&&A.length||(A=this.context.scene.children),A.length<=0){console.warn("No objects to fit camera to...");return}if(!s||!n){console.warn("No camera or controls found to fit camera to objects...");return}const a=new S,r=new S,C=$n(A,void 0);s.updateMatrixWorld(),s.updateProjectionMatrix(),C.getCenter(r);const Q=new S;if(C.getSize(Q),C.applyMatrix4(s.matrixWorldInverse),C.getSize(a),C.setFromCenterAndSize(r,a),Number.isNaN(a.x)||Number.isNaN(a.y)||Number.isNaN(a.z)){console.warn("Camera fit size resultet in NaN",s,C,[...A]);return}if(a.length()<=1e-10){Rf&&console.warn("Camera fit size is zero",C,[...A]);return}const h=s.fov,E=2*Math.atan(Math.tan(h*Math.PI/360/2)*s.aspect)/Math.PI*360,c=a.y/(2*Math.atan(Math.PI*h/360)),l=a.x/(2*Math.atan(Math.PI*E/360)),d=o*Math.max(c,l)+a.z/2;Rf&&console.log("Fit camera to objects",c,l,"distance",d),n.maxDistance=d*10,n.minDistance=d*.01;const u=.05,D=r.clone();D.y-=a.y*u,this.setLookTargetPosition(D,g),this.autoTarget=!1;const p=gA.findObjectOfType(hB),w=p?p.radius:0,f=Math.max(Q.x,Q.y,Q.z,w);s.near=d/100,s.far=f+d*10,s.updateMatrixWorld(),s.updateProjectionMatrix();const G=Fe(s),M=r.clone();if(M.sub(G),I==="y"&&(M.y=0),M.normalize(),M.multiplyScalar(d),I==="y"&&(M.y+=-u*4*a.y),s.parent){const U=s.parent.worldToLocal(r.clone().sub(M));this.setCameraTargetPosition(U,g)}else console.error(`Can not fit camera ${s.name} because it has no parent`);if(Rf){const U=new bU(C);this.context.scene.add(U),LN(U,fu(s)),setTimeout(()=>{this.context.scene.remove(U)},1e4),this._haveAttachedKeyboardEvents||(this._haveAttachedKeyboardEvents=!0,document.body.addEventListener("keydown",v=>{v.code==="KeyF"&&this.fitCamera(A,{fitOffset:o,immediate:g})}))}n.update()}}Ei([y()],St.prototype,"autoTarget",2),Ei([y()],St.prototype,"autoFit",2),Ei([y()],St.prototype,"enableRotate",2),Ei([y()],St.prototype,"autoRotate",2),Ei([y()],St.prototype,"autoRotateSpeed",2),Ei([y()],St.prototype,"minAzimuthAngle",2),Ei([y()],St.prototype,"maxAzimuthAngle",2),Ei([y()],St.prototype,"minPolarAngle",2),Ei([y()],St.prototype,"maxPolarAngle",2),Ei([y()],St.prototype,"enableKeys",2),Ei([y()],St.prototype,"enableDamping",2),Ei([y()],St.prototype,"dampingFactor",2),Ei([y()],St.prototype,"enableZoom",2),Ei([y()],St.prototype,"minZoom",2),Ei([y()],St.prototype,"maxZoom",2),Ei([y()],St.prototype,"zoomSpeed",2),Ei([y()],St.prototype,"enablePan",2),Ei([y(mh)],St.prototype,"lookAtConstraint",2),Ei([y()],St.prototype,"lookAtConstraint01",2),Ei([y()],St.prototype,"allowInterrupt",2),Ei([y()],St.prototype,"middleClickToFocus",2),Ei([y()],St.prototype,"doubleClickToFocus",2),Ei([y()],St.prototype,"clickBackgroundToFitScene",2),Ei([y()],St.prototype,"targetLerpDuration",2);var SEA=Object.defineProperty,fEA=Object.getOwnPropertyDescriptor,no=(i,A,e,g)=>{for(var I=g>1?void 0:g?fEA(A,e):A,o=i.length-1,s;o>=0;o--)(s=i[o])&&(I=(g?s(A,e,I):s(I))||I);return g&&I&&SEA(A,e,I),I},dB=(i=>(i[i.Skybox=1]="Skybox",i[i.SolidColor=2]="SolidColor",i[i.Uninitialized=4]="Uninitialized",i))(dB||{});const br=iA("debugcam"),C8=iA("debugscreenpointtoray");var Nf;const ID=(Nf=class extends bA{constructor(){super(...arguments),B(this,"_nearClipPlane",.1),B(this,"_farClipPlane",1e3),B(this,"orthographic",!1),B(this,"orthographicSize",5),B(this,"ARBackgroundAlpha",0),B(this,"_cullingMask",4294967295),B(this,"_backgroundBlurriness",0),B(this,"_backgroundIntensity",1),B(this,"_backgroundRotation"),B(this,"_environmentIntensity"),B(this,"_targetTexture",null),B(this,"_backgroundColor"),B(this,"_fov"),B(this,"_cam",null),B(this,"_clearFlags",2),B(this,"_skybox"),B(this,"_frustum"),B(this,"_projScreenMatrix",new DA)}get isCamera(){return!0}get aspect(){return this._cam instanceof xe?this._cam.aspect:this.context.domWidth/this.context.domHeight}set aspect(i){this._cam instanceof xe&&this._cam.aspect!==i&&(this._cam.aspect=i,this._cam.updateProjectionMatrix())}get fieldOfView(){return this._cam instanceof xe?this._cam.fov:this._fov}set fieldOfView(i){const A=this.fieldOfView!=i;if(this._fov=i,A&&this._cam&&this._cam instanceof xe){if(this._fov===void 0){console.warn("Can not set undefined fov on PerspectiveCamera");return}this._cam.fov=this._fov,this._cam.updateProjectionMatrix()}}get nearClipPlane(){return this._nearClipPlane}set nearClipPlane(i){const A=this._nearClipPlane!=i;this._nearClipPlane=i,this._cam&&A&&(this._cam.near=i,this._cam.updateProjectionMatrix())}get farClipPlane(){return this._farClipPlane}set farClipPlane(i){const A=this._farClipPlane!=i;this._farClipPlane=i,this._cam&&A&&(this._cam.far=i,this._cam.updateProjectionMatrix())}get clearFlags(){return this._clearFlags}set clearFlags(i){i!==this._clearFlags&&(this._clearFlags=i,this.applyClearFlagsIfIsActiveCamera())}set cullingMask(i){this._cullingMask=i,this._cam&&(this._cam.layers.mask=i)}get cullingMask(){return this._cam?this._cam.layers.mask:this._cullingMask}set cullingLayer(i){this.cullingMask=(1<<i|0)>>>0}set backgroundBlurriness(i){i!==this._backgroundBlurriness&&(i===void 0?this._backgroundBlurriness=void 0:this._backgroundBlurriness=Math.min(Math.max(i,0),1),this.applyClearFlagsIfIsActiveCamera())}get backgroundBlurriness(){return this._backgroundBlurriness}set backgroundIntensity(i){i!==this._backgroundIntensity&&(i===void 0?this._backgroundIntensity=void 0:this._backgroundIntensity=Math.min(Math.max(i,0),10),this.applyClearFlagsIfIsActiveCamera())}get backgroundIntensity(){return this._backgroundIntensity}set backgroundRotation(i){i!==this._backgroundRotation&&(i===void 0?this._backgroundRotation=void 0:this._backgroundRotation=i,this.applyClearFlagsIfIsActiveCamera())}get backgroundRotation(){return this._backgroundRotation}set environmentIntensity(i){this._environmentIntensity=i}get environmentIntensity(){return this._environmentIntensity}get backgroundColor(){return this._backgroundColor??null}set backgroundColor(i){if(i){if(this._backgroundColor)this._backgroundColor.copy(i);else{if(!i.clone)return;this._backgroundColor=i.clone()}i.alpha===void 0&&(this._backgroundColor.alpha=1),this.applyClearFlagsIfIsActiveCamera()}}set targetTexture(i){this._targetTexture=i}get targetTexture(){return this._targetTexture}get cam(){return this.activeAndEnabled&&this.buildCamera(),this._cam}screenPointToRay(i,A,e){const g=this.cam,I=ID._origin;I.set(i,A,-1),this.context.input.convertScreenspaceToRaycastSpace(I),C8&&console.log("screenPointToRay",i.toFixed(2),A.toFixed(2),"now:",I.x.toFixed(2),I.y.toFixed(2),"isInXR:"+this.context.isInXR),I.z=-1,I.unproject(g);const o=ID._direction.set(I.x,I.y,I.z),s=Fe(g);return o.sub(s),o.normalize(),e?(e.set(s,o),e):new po(s.clone(),o.clone())}getFrustum(){return this._frustum||(this._frustum=new cQ,this.updateFrustum()),this._frustum}updateFrustum(){this._frustum||(this._frustum=new cQ),this._frustum.setFromProjectionMatrix(this.getProjectionScreenMatrix(this._projScreenMatrix,!0),this.context.renderer.coordinateSystem)}getProjectionScreenMatrix(i,A){return A&&this._projScreenMatrix.multiplyMatrices(this.cam.projectionMatrix,this.cam.matrixWorldInverse),i===this._projScreenMatrix?i:i.copy(this._projScreenMatrix)}awake(){C8&&window.addEventListener("pointerdown",i=>{const A=i.clientX,e=i.clientY;console.log("touch",A.toFixed(2),e.toFixed(2));const g=this.screenPointToRay(A,e),I="#"+Math.floor(Math.random()*16777215).toString(16);pe.DrawRay(g.origin,g.direction,I,10)})}onEnable(){br&&console.log(`Camera enabled: "${this.name}". ClearFlags=${dB[this._clearFlags]}`,this),this.buildCamera(),(this.tag=="MainCamera"||!this.context.mainCameraComponent)&&(this.context.setCurrentCamera(this),MEA(this)),this.applyClearFlagsIfIsActiveCamera({applySkybox:!0})}onDisable(){this.context.removeCamera(this)}onBeforeRender(){if(this._cam&&(this._frustum&&this.updateFrustum(),this._clearFlags===2&&this.applyClearFlagsIfIsActiveCamera(),this._targetTexture)){this.context.isManagedExternally&&(this._warnedAboutExternalRenderer||(this._warnedAboutExternalRenderer=!0,console.warn("Rendering with external renderer is not supported yet. This may not work or throw errors. Please remove the the target texture from your camera: "+this.name,this.targetTexture))),this.context.composer;const i=this.context.renderer;if(i){const A=this.context.mainCameraComponent;this.applyClearFlags(),this._targetTexture.render(this.context.scene,this._cam,i),A?.applyClearFlags()}}}buildCamera(){if(this._cam)return;const i=this.gameObject.isCamera;let A=null;if(i?(A=this.gameObject,A?.layers.enableAll(),A instanceof xe&&(this._fov=A.fov)):A=this.gameObject.children[0],A&&A.isCamera)A instanceof xe&&(this._fov&&(A.fov=this._fov),A.near=this._nearClipPlane,A.far=this._farClipPlane,A.updateProjectionMatrix());else if(!this.orthographic)A=new xe(this.fieldOfView,window.innerWidth/window.innerHeight,this._nearClipPlane,this._farClipPlane),this.fieldOfView&&(A.fov=this.fieldOfView),this.gameObject.add(A);else{const e=this.orthographicSize*100;A=new jn(window.innerWidth/-e,window.innerWidth/e,window.innerHeight/e,window.innerHeight/-e,this._nearClipPlane,this._farClipPlane),this.gameObject.add(A)}this._cam=A,this._cam.layers.mask=this._cullingMask,this.tag=="MainCamera"&&this.context.setCurrentCamera(this)}applyClearFlagsIfIsActiveCamera(i){this.context.mainCameraComponent===this&&this.applyClearFlags(i)}applyClearFlags(i){if(!this._cam){br&&console.log("Camera does not exist (apply clear flags)");return}if(this.fieldOfView=this._fov,br){const A=`Camera "${this.name}" clear flags: ${dB[this._clearFlags]}`;console.debug(A)}switch(this._clearFlags){case 1:if(ID.backgroundShouldBeTransparent(this.context)&&(!this.ARBackgroundAlpha||this.ARBackgroundAlpha<.001)){this.context.scene.background=null,this.context.renderer.setClearColor(0,0);return}(!this.scene.background||!this._skybox||i?.applySkybox===!0)&&this.applySceneSkybox(),this._backgroundBlurriness!==void 0?this.context.scene.backgroundBlurriness=this._backgroundBlurriness:br&&console.warn(`Camera "${this.name}" has no background blurriness`),this._backgroundIntensity!==void 0&&(this.context.scene.backgroundIntensity=this._backgroundIntensity),this._backgroundRotation!==void 0?this.context.scene.backgroundRotation=this._backgroundRotation:br&&console.warn(`Camera "${this.name}" has no background intensity`);break;case 2:if(this._backgroundColor){let A=this._backgroundColor.alpha;ID.backgroundShouldBeTransparent(this.context)&&(A=this.ARBackgroundAlpha??0),this.context.scene.background=null,this.context.renderer.setClearColor(this._backgroundColor,A)}else br&&console.warn(`Camera "${this.name}" has no background color`,this);break;case 4:this.context.scene.background=null,this.context.renderer.setClearColor(0,0);break}}applySceneSkybox(){this._skybox||(this._skybox=new kEA(this)),this._skybox.apply()}static backgroundShouldBeTransparent(i){var A,e,g,I;const o=(A=i.renderer.xr)==null?void 0:A.getSession();if(!o)return!1;if(typeof o._transparent=="boolean")return o._transparent;const s=o.environmentBlendMode;br&&Ci("Environment blend mode: "+s+" on "+navigator.userAgent);let n=s==="additive"||s==="alpha-blend";return i.isInAR&&s==="opaque"&&((e=navigator.userAgent)!=null&&e.includes("OculusBrowser")||(g=navigator.userAgent)!=null&&g.includes("Mozilla")&&(I=navigator.userAgent)!=null&&I.includes("Mobile WebXRViewer/v2"))&&(n=!0),o._transparent=n,n}},B(Nf,"_origin",new S),B(Nf,"_direction",new S),Nf);let Tt=ID;no([y()],Tt.prototype,"aspect",1),no([y()],Tt.prototype,"fieldOfView",1),no([y()],Tt.prototype,"nearClipPlane",1),no([y()],Tt.prototype,"farClipPlane",1),no([y()],Tt.prototype,"clearFlags",1),no([y()],Tt.prototype,"orthographic",2),no([y()],Tt.prototype,"orthographicSize",2),no([y()],Tt.prototype,"ARBackgroundAlpha",2),no([y()],Tt.prototype,"cullingMask",1),no([y()],Tt.prototype,"backgroundBlurriness",1),no([y()],Tt.prototype,"backgroundIntensity",1),no([y(It)],Tt.prototype,"backgroundRotation",1),no([y()],Tt.prototype,"environmentIntensity",1),no([y(Rt)],Tt.prototype,"backgroundColor",1),no([y(El)],Tt.prototype,"targetTexture",1);class kEA{constructor(A){B(this,"_camera"),B(this,"_skybox"),this._camera=A}get context(){var A;return(A=this._camera)==null?void 0:A.context}apply(){this._skybox=this.context.lightmaps.tryGetSkybox(this._camera.sourceId),this._skybox?this.context.scene.background!==this._skybox&&(br&&console.log(`Camera "${this._camera.name}" set skybox`,this._camera,this._skybox),this._skybox.mapping=Eo,this.context.scene.background=this._skybox):(this._did_log_failed_to_find_skybox||(this._did_log_failed_to_find_skybox=!0,console.warn(`Camera "${this._camera.name}" failed to load/find skybox texture`,this._camera.sourceId,this.context.lightmaps,"Current background: ",this.context.scene.background)),(br||se())&&Lt(`Camera "${this._camera.name}" has no skybox texture`))}}function MEA(i){iA("freecam")&&i.context.mainCameraComponent===i&&gA.getOrAddComponent(i.gameObject,St)}class uB extends bA{constructor(){super(...arguments),B(this,"_listener",null),B(this,"onInteraction",()=>{this.destroyed||this.listener==null||this.addListenerIfItExists()})}get listener(){return this._listener==null&&(this._listener=new g2),this._listener}onEnable(){aB.registerWaitForInteraction(this.onInteraction),this.addListenerIfItExists()}onDisable(){aB.unregisterWaitForInteraction(this.onInteraction),this.removeListenerIfItExists()}addListenerIfItExists(){const A=this._listener;if(!A||A!=null&&A.parent)return;const e=this.context.mainCameraComponent||gA.getComponentInParent(this.gameObject,Tt);e!=null&&e.cam?e.cam.add(A):this.gameObject.add(A),A.filter?(A.gain.connect(A.filter),A.filter.connect(A.context.destination)):A.gain.connect(A.context.destination)}removeListenerIfItExists(){const A=this._listener;A&&(A.removeFromParent(),A.filter&&A.filter.disconnect(),A.gain&&A.gain.disconnect())}}class GEA extends Fi{constructor(A,e=1,g=16,I=2){const o=new ue,s=g+I*2,n=new Float32Array((s*3+3)*3);o.setAttribute("position",new Ie(n,3));const a=new Zt({color:65280}),r=new Zt({color:16776960});super(o,[r,a]),this.audio=A,this.range=e,this.divisionsInnerAngle=g,this.divisionsOuterAngle=I,this.type="PositionalAudioHelper",this.update()}update(){const A=this.audio,e=this.range,g=this.divisionsInnerAngle,I=this.divisionsOuterAngle,o=ct.degToRad(A.panner.coneInnerAngle),s=ct.degToRad(A.panner.coneOuterAngle),n=o/2,a=s/2;let r=0,C=0,Q,h;const E=this.geometry,c=E.attributes.position;E.clearGroups();function l(d,u,D,p){const w=(u-d)/D;for(c.setXYZ(r,0,0,0),C++,Q=d;Q<u;Q+=w)h=r+C,c.setXYZ(h,Math.sin(Q)*e,0,Math.cos(Q)*e),c.setXYZ(h+1,Math.sin(Math.min(Q+w,u))*e,0,Math.cos(Math.min(Q+w,u))*e),c.setXYZ(h+2,0,0,0),C+=3;E.addGroup(r,C,p),r+=C,C=0}l(-a,-n,I,0),l(-n,n,g,1),l(n,a,I,0),c.needsUpdate=!0,o===s&&(this.material[0].visible=!1)}dispose(){this.geometry.dispose(),this.material[0].dispose(),this.material[1].dispose()}}var REA=Object.defineProperty,UEA=Object.getOwnPropertyDescriptor,ha=(i,A,e,g)=>{for(var I=g>1?void 0:g?UEA(A,e):A,o=i.length-1,s;o>=0;o--)(s=i[o])&&(I=(g?s(A,e,I):s(I))||I);return g&&I&&REA(A,e,I),I};const xI=iA("debugaudio"),pB=class extends bA{constructor(){super(...arguments),B(this,"clip",""),B(this,"playOnAwake",!1),B(this,"preload",!1),B(this,"_spatialBlend",0),B(this,"_minDistance",1),B(this,"_maxDistance",100),B(this,"_volume",1),B(this,"rollOffMode",0),B(this,"playInBackground",!0),B(this,"_loop",!1),B(this,"sound",null),B(this,"helper",null),B(this,"wasPlaying",!1),B(this,"audioLoader",null),B(this,"shouldPlay",!1),B(this,"_lastClipStartedLoading",null),B(this,"_audioElement",null),B(this,"onVisibilityChanged",()=>{switch(document.visibilityState){case"hidden":(this.playInBackground===!1||ls())&&(this.wasPlaying=this.isPlaying,this.isPlaying&&this.pause());break;case"visible":xI&&console.log("visible",this.enabled,this.playOnAwake,!this.isPlaying,pB.userInteractionRegistered,this.wasPlaying),this.enabled&&this.playOnAwake&&!this.isPlaying&&pB.userInteractionRegistered&&this.wasPlaying&&this.play();break}}),B(this,"onApplicationMuteChanged",()=>{var i,A;this.context.application.muted?(i=this.sound)==null||i.setVolume(0):(A=this.sound)==null||A.setVolume(this.volume)}),B(this,"createAudio",i=>{xI&&console.log("AudioBuffer finished loading",i);const A=this.Sound;if(!A){xI&&console.warn("Failed getting sound?",this.name);return}A.isPlaying&&A.stop(),i&&A.setBuffer(i),A.loop=this._loop,this.context.application.muted?A.setVolume(0):A.setVolume(this.volume),A.autoplay=this.shouldPlay&&pB.userInteractionRegistered,this.applySpatialDistanceSettings(),A.isPlaying&&A.stop(),pB.registerWaitForAllowAudio(this.__onAllowAudioCallback)}),B(this,"__onAllowAudioCallback",()=>{this.shouldPlay&&this.play()}),B(this,"_lastContextTime",0),B(this,"_hasEnded",!0),B(this,"_needUpdateSpatialDistanceSettings",!1)}static get userInteractionRegistered(){return aB.userInteractionRegistered}static registerWaitForAllowAudio(i){aB.registerWaitForAllowAudio(i)}get loop(){return this.sound&&(this._loop=this.sound.getLoop()),this._loop}set loop(i){this._loop=i,this.sound&&this.sound.setLoop(i)}get spatialBlend(){return this._spatialBlend}set spatialBlend(i){i!==this._spatialBlend&&(this._spatialBlend=i,this._needUpdateSpatialDistanceSettings=!0)}get minDistance(){return this._minDistance}set minDistance(i){this._minDistance!==i&&(this._minDistance=i,this._needUpdateSpatialDistanceSettings=!0)}get maxDistance(){return this._maxDistance}set maxDistance(i){this._maxDistance!==i&&(this._maxDistance=i,this._needUpdateSpatialDistanceSettings=!0)}get volume(){return this._volume}set volume(i){this._volume=i,this.sound&&!this.context.application.muted&&(xI&&console.log(this.name,"audio set volume",i),this.sound.setVolume(i))}get Sound(){var i;if(!this.sound&&pB.userInteractionRegistered){let A=gA.getComponent(this.context.mainCamera,uB)??gA.findObjectOfType(uB,this.context);!A&&this.context.mainCamera&&(A=gA.addNewComponent(this.context.mainCamera,uB)),A!=null&&A.listener?(this.sound=new o2(A.listener),(i=this.gameObject)==null||i.add(this.sound)):xI&&console.warn("No audio listener found in scene - can not play audio")}return this.sound}get ShouldPlay(){return this.shouldPlay}get audioContext(){var i;return(i=this.sound)==null?void 0:i.context}awake(){xI&&console.log(this),this.audioLoader=new k0,this.playOnAwake&&(this.shouldPlay=!0),this.preload&&typeof this.clip=="string"&&this.audioLoader.load(this.clip,this.createAudio,()=>{},console.error)}onEnable(){this.sound&&this.gameObject.add(this.sound),pB.userInteractionRegistered?this.playOnAwake&&this.context.application.isVisible&&this.play():pB.registerWaitForAllowAudio(()=>{this.enabled&&!this.destroyed&&this.shouldPlay&&this.onNewClip(this.clip)}),globalThis.addEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.addEventListener(VS.MuteChanged,this.onApplicationMuteChanged)}onDisable(){globalThis.removeEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.removeEventListener(VS.MuteChanged,this.onApplicationMuteChanged),this.pause()}applySpatialDistanceSettings(){const i=this.sound;if(!i)return;this._needUpdateSpatialDistanceSettings=!1;const A=ge.lerp(10*this._maxDistance/Math.max(1e-4,this.spatialBlend),this._minDistance,this.spatialBlend);switch(xI&&console.log(this.name,this._minDistance,this._maxDistance,this.spatialBlend,"Ref distance="+A),i.setRefDistance(A),i.setMaxDistance(Math.max(.01,this._maxDistance)),this.rollOffMode){case 0:i.setDistanceModel("exponential");break;case 1:i.setDistanceModel("linear");break;case 2:console.warn("Custom rolloff for AudioSource is not supported: "+this.name);break}this.spatialBlend>0?xI&&!this.helper&&(this.helper=new GEA(i,i.getRefDistance()),i.add(this.helper)):this.helper&&this.helper.parent&&this.helper.removeFromParent()}async onNewClip(i){if(i&&(this.clip=i),typeof i=="string")if(xI&&console.log(i),i.endsWith(".mp3")||i.endsWith(".wav")){if(this.audioLoader||(this.audioLoader=new k0),this.shouldPlay=!0,this._lastClipStartedLoading===i){xI&&console.log("Is currently loading:",this._lastClipStartedLoading,this);return}this._lastClipStartedLoading=i,xI&&console.log("load audio",i);const A=await this.audioLoader.loadAsync(i).catch(console.error);this._lastClipStartedLoading=null,A&&this.createAudio(A)}else console.warn("Unsupported audio clip type",i);else this.shouldPlay=!0,this.createAudio()}play(i=void 0){var A,e,g;!i&&this.clip&&(i=this.clip),i!==void 0&&typeof i!="string"&&!(i instanceof MediaStream)&&(se()&&console.warn("Called play on AudioSource with unknown argument type:",i+`
5732
+ `;var gEA=Object.defineProperty,IEA=Object.getOwnPropertyDescriptor,pb=(i,A,e,g)=>{for(var I=g>1?void 0:g?IEA(A,e):A,o=i.length-1,s;o>=0;o--)(s=i[o])&&(I=(g?s(A,e,I):s(I))||I);return g&&I&&gEA(A,e,I),I};class mh extends bA{constructor(){super(...arguments),B(this,"constraintActive",!0),B(this,"locked",!1),B(this,"sources",[])}}pb([y()],mh.prototype,"constraintActive",2),pb([y()],mh.prototype,"locked",2),pb([y(wA)],mh.prototype,"sources",2);function oEA(i,A){return gB(i,Mt.ContextCreated,A),()=>IB(i,Mt.ContextCreated)}function sEA(i,A){return gB(i,Mt.ContextClearing,A),()=>IB(i,Mt.ContextClearing)}function nEA(i,A){return gB(i,Mt.ContextDestroying,A),()=>IB(i,Mt.ContextDestroying)}function o8(i,A){return gB(i,Xt.Start,A),()=>IB(i,Xt.Start)}function s8(i,A){return gB(i,Xt.Update,A),()=>IB(i,Xt.Update)}function aEA(i,A){return gB(i,Xt.OnBeforeRender,A),()=>IB(i,Xt.OnBeforeRender)}function rEA(i,A){return gB(i,Xt.OnAfterRender,A),()=>IB(i,Xt.OnAfterRender)}class Sh{constructor(){B(this,"bb",null),B(this,"bb_pos",0)}__init(A,e){return this.bb_pos=A,this.bb=e,this}x(){return this.bb.readFloat32(this.bb_pos)}y(){return this.bb.readFloat32(this.bb_pos+4)}z(){return this.bb.readFloat32(this.bb_pos+8)}static sizeOf(){return 12}static createVec3(A,e,g,I){return A.prep(4,12),A.writeFloat32(I),A.writeFloat32(g),A.writeFloat32(e),A.offset()}}class n8{constructor(){B(this,"bb",null),B(this,"bb_pos",0)}__init(A,e){return this.bb_pos=A,this.bb=e,this}position(A){return(A||new Sh).__init(this.bb_pos,this.bb)}rotation(A){return(A||new Sh).__init(this.bb_pos+12,this.bb)}scale(A){return(A||new Sh).__init(this.bb_pos+24,this.bb)}static sizeOf(){return 36}static createTransform(A,e,g,I,o,s,n,a,r,C){return A.prep(4,36),A.prep(4,12),A.writeFloat32(C),A.writeFloat32(r),A.writeFloat32(a),A.prep(4,12),A.writeFloat32(n),A.writeFloat32(s),A.writeFloat32(o),A.prep(4,12),A.writeFloat32(I),A.writeFloat32(g),A.writeFloat32(e),A.offset()}}class nC{constructor(){B(this,"bb",null),B(this,"bb_pos",0)}__init(A,e){return this.bb_pos=A,this.bb=e,this}static getRootAsSyncedTransformModel(A,e){return(e||new nC).__init(A.readInt32(A.position())+A.position(),A)}static getSizePrefixedRootAsSyncedTransformModel(A,e){return A.setPosition(A.position()+FK),(e||new nC).__init(A.readInt32(A.position())+A.position(),A)}guid(A){const e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,A):null}fast(){const A=this.bb.__offset(this.bb_pos,6);return A?!!this.bb.readInt8(this.bb_pos+A):!1}transform(A){const e=this.bb.__offset(this.bb_pos,8);return e?(A||new n8).__init(this.bb_pos+e,this.bb):null}dontSave(){const A=this.bb.__offset(this.bb_pos,10);return A?!!this.bb.readInt8(this.bb_pos+A):!1}static startSyncedTransformModel(A){A.startObject(4)}static addGuid(A,e){A.addFieldOffset(0,e,0)}static addFast(A,e){A.addFieldInt8(1,+e,0)}static addTransform(A,e){A.addFieldStruct(2,e,0)}static addDontSave(A,e){A.addFieldInt8(3,+e,0)}static endSyncedTransformModel(A){return A.endObject()}static finishSyncedTransformModelBuffer(A,e){A.finish(e)}static finishSizePrefixedSyncedTransformModelBuffer(A,e){A.finish(e,void 0,!0)}}var Jg=(i=>(i[i.Average=0]="Average",i[i.Multiply=1]="Multiply",i[i.Minimum=2]="Minimum",i[i.Maximum=3]="Maximum",i))(Jg||{}),Sf=(i=>(i[i.Discrete=0]="Discrete",i[i.Continuous=1]="Continuous",i))(Sf||{}),Vi=(i=>(i[i.None=0]="None",i[i.FreezePositionX=2]="FreezePositionX",i[i.FreezePositionY=4]="FreezePositionY",i[i.FreezePositionZ=8]="FreezePositionZ",i[i.FreezePosition=14]="FreezePosition",i[i.FreezeRotationX=16]="FreezeRotationX",i[i.FreezeRotationY=32]="FreezeRotationY",i[i.FreezeRotationZ=64]="FreezeRotationZ",i[i.FreezeRotation=112]="FreezeRotation",i[i.FreezeAll=126]="FreezeAll",i))(Vi||{}),cl=(i=>(i[i.None=0]="None",i[i.X=2]="X",i[i.Y=4]="Y",i[i.Z=8]="Z",i[i.All=-1]="All",i))(cl||{});const gI=function(i,A){return function(e,g,I){CEA(e,g,I,i,A)}};function CEA(i,A,e,g,I){if(!I&&!g&&!i.onValidate)return;if(e!==void 0){console.error("Invalid usage of validate decorator. Only fields can be validated.",i,A,e),Ci("Invalid usage of validate decorator. Only fields can be validated. Property: "+A,To.Error);return}let o="";if(typeof A=="string"?o=A:o=A.name,i.__internalAwake){const s=Symbol(o),n=i.__internalAwake;i.__internalAwake=function(){var a;if(!this.onValidate){se()&&console.warn('Usage of @validate decorate detected but there is no onValidate method in your class: "'+((a=i.constructor)==null?void 0:a.name)+'"');return}if(this[s]===void 0){this[s]=this[o];const r=this[o];if(r instanceof AA||r instanceof S||r instanceof VA||r instanceof GA){const C=this[o];L0(C,()=>{this.onValidate(o)})}Object.defineProperty(this,o,{set:function(C){var Q;if(this[DK]===!0)this[s]=C;else{g?.call(this,C);const h=this[s];this[s]=C,(Q=this.onValidate)==null||Q.call(this,o,h)}},get:function(){return I?.call(this),this[s]}})}n.call(this)}}}const BEA=function(i){return function(A,e,g){let I="";typeof e=="string"?I=e:I=e.name;const o=i.prototype,s=Object.getOwnPropertyDescriptor(o,I);if(!(s!=null&&s.value)){console.warn("Can not apply prefix: type does not have method named",e,i);return}const n=s.value,a=A[I];Object.defineProperty(o,I,{value:function(...r){const C=a?.call(this,...r);if(C instanceof Promise){C.then(Q=>{if(Q!==!1)return n.call(this,...r)});return}if(C!==!1)return n.call(this,...r)}})}};var QEA=Object.defineProperty,hEA=Object.getOwnPropertyDescriptor,Wo=(i,A,e,g)=>{for(var I=g>1?void 0:g?hEA(A,e):A,o=i.length-1,s;o>=0;o--)(s=i[o])&&(I=(g?s(A,e,I):s(I))||I);return g&&I&&QEA(A,e,I),I};class EEA{constructor(A,e){B(this,"positionChanged",!1),B(this,"rotationChanged",!1),B(this,"position"),B(this,"quaternion"),B(this,"_positionKeys",["x","y","z"]),B(this,"_quaternionKeys",["_x","_y","_z","_w"]),B(this,"mute",!1),B(this,"context"),B(this,"obj"),B(this,"_positionWatch"),B(this,"_rotationWatch"),this.context=e,this.obj=A}get isDirty(){return this.positionChanged||this.rotationChanged}reset(A=!1){if(this.positionChanged=!1,this.rotationChanged=!1,this.mute=!1,A){if(this.position)for(const e of this._positionKeys)delete this.position[e];if(this.quaternion)for(const e of this._quaternionKeys)delete this.quaternion[e]}}syncValues(){for(const A of this._positionKeys)this.position[A]=this.obj.position[A];for(const A of this._quaternionKeys)this.quaternion[A]=this.obj.quaternion[A]}applyValues(){if(this.positionChanged&&this.position)for(const A of this._positionKeys){const e=this.position[A];e!==void 0&&(this.obj.position[A]=e)}if(this.rotationChanged&&this.quaternion)for(const A of this._quaternionKeys){const e=this.quaternion[A];e!==void 0&&(this.obj.quaternion[A]=e)}}start(A,e){this.reset(),A&&(this._positionWatch||(this._positionWatch=new eC(this.obj.position,["x","y","z"])),this._positionWatch.apply(),this.position={},this._positionWatch.subscribeWrite((o,s)=>{var n;if((n=this.context.physics.engine)!=null&&n.isUpdating||this.mute)return;const a=this.position[s];Math.abs(a-o)<1e-5||(this.position[s]=o,this.positionChanged=!0)})),e&&(this._rotationWatch||(this._rotationWatch=new eC(this.obj.quaternion,["_x","_y","_z","_w"])),this._rotationWatch.apply(),this.quaternion={},this._rotationWatch.subscribeWrite((o,s)=>{var n;if((n=this.context.physics.engine)!=null&&n.isUpdating||this.mute)return;const a=this.quaternion[s];Math.abs(a-o)<1e-5||(this.quaternion[s]=o,this.rotationChanged=!0)}));const g=this.obj.matrixWorld.multiplyMatrices.bind(this.obj.matrixWorld),I=new DA;this.obj.matrixWorld.multiplyMatrices=(o,s)=>{var n;return(n=this.context.physics.engine)!=null&&n.isUpdating||this.mute||I.equals(o)||(this.positionChanged=!0,this.rotationChanged=!0,I.copy(o)),g(o,s)}}stop(){var A,e;(A=this._positionWatch)==null||A.revoke(),(e=this._rotationWatch)==null||e.revoke()}}var Db;const wb=(Db=class extends bA{constructor(){super(...arguments),B(this,"autoMass",!0),B(this,"_mass",0),B(this,"useGravity",!0),B(this,"centerOfMass",new S(0,0,0)),B(this,"constraints",Vi.None),B(this,"isKinematic",!1),B(this,"drag",0),B(this,"angularDrag",1),B(this,"detectCollisions",!0),B(this,"sleepThreshold",.01),B(this,"collisionDetectionMode",Sf.Discrete),B(this,"_gravityScale",1),B(this,"dominanceGroup",0),B(this,"_propertiesChanged",!1),B(this,"_currentVelocity",new S),B(this,"_smoothedVelocity",new S),B(this,"_smoothedVelocityGetter",new S),B(this,"_lastPosition",new S),B(this,"_watch")}set mass(i){i!==this._mass&&(this._mass=i,this._propertiesChanged=!0,this.__didAwake&&(this.autoMass=!1))}get mass(){var i,A;return this.autoMass?((A=(i=this.context.physics.engine)==null?void 0:i.getBody(this))==null?void 0:A.mass())??-1:this._mass}get lockPositionX(){return(this.constraints&Vi.FreezePositionX)!==0}get lockPositionY(){return(this.constraints&Vi.FreezePositionY)!==0}get lockPositionZ(){return(this.constraints&Vi.FreezePositionZ)!==0}get lockRotationX(){return(this.constraints&Vi.FreezeRotationX)!==0}get lockRotationY(){return(this.constraints&Vi.FreezeRotationY)!==0}get lockRotationZ(){return(this.constraints&Vi.FreezeRotationZ)!==0}set lockPositionX(i){i?this.constraints|=Vi.FreezePositionX:this.constraints&=~Vi.FreezePositionX}set lockPositionY(i){i?this.constraints|=Vi.FreezePositionY:this.constraints&=~Vi.FreezePositionY}set lockPositionZ(i){i?this.constraints|=Vi.FreezePositionZ:this.constraints&=~Vi.FreezePositionZ}set lockRotationX(i){i?this.constraints|=Vi.FreezeRotationX:this.constraints&=~Vi.FreezeRotationX}set lockRotationY(i){i?this.constraints|=Vi.FreezeRotationY:this.constraints&=~Vi.FreezeRotationY}set lockRotationZ(i){i?this.constraints|=Vi.FreezeRotationZ:this.constraints&=~Vi.FreezeRotationZ}set gravityScale(i){this._gravityScale=i}get gravityScale(){return this._gravityScale}awake(){this._watch=void 0,this._propertiesChanged=!1}onEnable(){this._watch||(this._watch=new EEA(this.gameObject,this.context)),this._watch.start(!0,!0),this.startCoroutine(this.beforePhysics(),Xt.LateUpdate)}onDisable(){var i,A;(i=this._watch)==null||i.stop(),(A=this.context.physics.engine)==null||A.removeBody(this)}onDestroy(){var i;(i=this.context.physics.engine)==null||i.removeBody(this)}onValidate(){this._propertiesChanged=!0}*beforePhysics(){for(var i,A,e,g;;)this._propertiesChanged&&(this._propertiesChanged=!1,(i=this.context.physics.engine)==null||i.updateProperties(this)),(A=this._watch)!=null&&A.isDirty?(this._watch.mute=!0,this._watch.applyValues(),(e=this.context.physics.engine)==null||e.updateBody(this,this._watch.positionChanged,this._watch.rotationChanged),this._watch.reset()):(g=this._watch)==null||g.syncValues(),this.captureVelocity(),yield}teleport(i,A=!0){var e;(e=this._watch)==null||e.reset(!0),A?this.gameObject.position.set(i.x,i.y,i.z):this.setWorldPosition(i.x,i.y,i.z),this.resetForcesAndTorques(),this.resetVelocities()}resetForces(i=!0){var A;(A=this.context.physics.engine)==null||A.resetForces(this,i)}resetTorques(i=!0){var A;(A=this.context.physics.engine)==null||A.resetTorques(this,i)}resetVelocities(){this.setVelocity(0,0,0),this.setAngularVelocity(0,0,0)}resetForcesAndTorques(){this.resetForces(),this.resetTorques()}wakeUp(){var i;(i=this.context.physics.engine)==null||i.wakeup(this)}get isSleeping(){var i;return(i=this.context.physics.engine)==null?void 0:i.isSleeping(this)}updateProperties(){var i;return this._propertiesChanged=!1,(i=this.context.physics.engine)==null?void 0:i.updateProperties(this)}applyForce(i,A,e=!0){var g;this._propertiesChanged&&this.updateProperties(),(g=this.context.physics.engine)==null||g.addForce(this,i,e)}applyImpulse(i,A=!0){var e;this._propertiesChanged&&this.updateProperties(),(e=this.context.physics.engine)==null||e.applyImpulse(this,i,A)}setForce(i,A,e,g=!0){var I,o,s;(I=this.context.physics.engine)==null||I.resetForces(this,g),typeof i=="number"?(A??(A=0),e??(e=0),(o=this.context.physics.engine)==null||o.addForce(this,{x:i,y:A,z:e},g)):(s=this.context.physics.engine)==null||s.addForce(this,i,g)}getVelocity(){var i;const A=(i=this.context.physics.engine)==null?void 0:i.getLinearVelocity(this);return A?(this._currentVelocity.x=A.x,this._currentVelocity.y=A.y,this._currentVelocity.z=A.z,this._currentVelocity):this._currentVelocity.set(0,0,0)}setVelocity(i,A,e,g=!0){var I,o;if(i instanceof S){const s=i;(I=this.context.physics.engine)==null||I.setLinearVelocity(this,s,g);return}A===void 0||e===void 0||(o=this.context.physics.engine)==null||o.setLinearVelocity(this,{x:i,y:A,z:e},g)}getAngularVelocity(){var i;const A=(i=this.context.physics.engine)==null?void 0:i.getAngularVelocity(this);return A?(this._currentVelocity.x=A.x,this._currentVelocity.y=A.y,this._currentVelocity.z=A.z,this._currentVelocity):this._currentVelocity.set(0,0,0)}setAngularVelocity(i,A,e,g=!0){var I,o;if(i instanceof S){const s=i;(I=this.context.physics.engine)==null||I.setAngularVelocity(this,s,g);return}A===void 0||e===void 0||(o=this.context.physics.engine)==null||o.setAngularVelocity(this,{x:i,y:A,z:e},g)}setTorque(i,A,e){this.setAngularVelocity(i,A,e)}get smoothedVelocity(){return this._smoothedVelocityGetter.copy(this._smoothedVelocity),this._smoothedVelocityGetter.multiplyScalar(1/this.context.time.deltaTime)}setBodyFromGameObject(i=null){}captureVelocity(){const i=Fe(this.gameObject);wb.tempPosition.copy(i);const A=i.sub(this._lastPosition);this._lastPosition.copy(wb.tempPosition),this._smoothedVelocity.lerp(A,this.context.time.deltaTime/.1)}},B(Db,"tempPosition",new S),Db);let _t=wb;Wo([gI()],_t.prototype,"autoMass",2),Wo([y()],_t.prototype,"mass",1),Wo([gI(),y()],_t.prototype,"useGravity",2),Wo([y(S)],_t.prototype,"centerOfMass",2),Wo([gI(),y()],_t.prototype,"constraints",2),Wo([gI(),y()],_t.prototype,"isKinematic",2),Wo([gI(),y()],_t.prototype,"drag",2),Wo([gI(),y()],_t.prototype,"angularDrag",2),Wo([gI(),y()],_t.prototype,"detectCollisions",2),Wo([gI(),y()],_t.prototype,"sleepThreshold",2),Wo([gI(),y()],_t.prototype,"collisionDetectionMode",2),Wo([gI()],_t.prototype,"_gravityScale",2),Wo([gI()],_t.prototype,"dominanceGroup",2);const EB=iA("debugsync"),$p="STRS";bK($p,nC.getRootAsSyncedTransformModel);const Qa=new jw;function a8(i,A,e=!0){Qa.clear();const g=Qa.createString(i);nC.startSyncedTransformModel(Qa),nC.addGuid(Qa,g),nC.addFast(Qa,e);const I=A.worldPosition,o=A.worldEuler,s=A.gameObject.scale;nC.addTransform(Qa,n8.createTransform(Qa,I.x,I.y,I.z,o.x,o.y,o.z,s.x,s.y,s.z));const n=nC.endSyncedTransformModel(Qa);return Qa.finish(n,$p),Qa.asUint8Array()}let yb=0,AD=0;s8(i=>{var A;const e=(A=i.connection.currentServerUrl)!=null&&A.includes("glitch")?10:40;AD=Math.floor(yb/e),yb=0,EB&&AD>0&&console.log("Sync Transform Fast Interval",AD)});class cB extends bA{constructor(){super(...arguments),B(this,"overridePhysics",!0),B(this,"interpolatePosition",!0),B(this,"interpolateRotation",!0),B(this,"fastMode",!1),B(this,"syncDestroy",!1),B(this,"_model",null),B(this,"_needsUpdate",!0),B(this,"rb",null),B(this,"_wasKinematic",!1),B(this,"_receivedDataBefore",!1),B(this,"_targetPosition"),B(this,"_targetRotation"),B(this,"_receivedFastUpdate",!1),B(this,"_shouldRequestOwnership",!1),B(this,"joinedRoomCallback",null),B(this,"receivedDataCallback",null),B(this,"tempEuler",new It),B(this,"receivedUpdate",!1),B(this,"lastWorldPos"),B(this,"lastWorldRotation")}requestOwnership(){EB&&console.log("Request ownership"),this._model?this._model.requestOwnership():(this._shouldRequestOwnership=!0,this._needsUpdate=!0)}hasOwnership(){var A;return((A=this._model)==null?void 0:A.hasOwnership)??void 0}isOwned(){var A;return(A=this._model)==null?void 0:A.isOwned}awake(){EB&&console.log("new instance",this.guid,this),this._receivedDataBefore=!1,this._targetPosition=new S,this._targetRotation=new GA,this.lastWorldPos=new S,this.lastWorldRotation=new GA,this.rb=gA.getComponentInChildren(this.gameObject,_t),this.rb&&(this._wasKinematic=this.rb.isKinematic),this.receivedUpdate=!0,this._model=new Ab(this.context.connection,this.guid),this.context.connection.isConnected&&this.tryGetLastState(),this.joinedRoomCallback=this.tryGetLastState.bind(this),this.context.connection.beginListen(Pe.JoinedRoom,this.joinedRoomCallback),this.receivedDataCallback=this.onReceivedData.bind(this),this.context.connection.beginListenBinary($p,this.receivedDataCallback)}onDestroy(){this.syncDestroy&&Bb(this.guid,this.context.connection),this._model=null,this.context.connection.stopListen(Pe.JoinedRoom,this.joinedRoomCallback),this.context.connection.stopListenBinary($p,this.receivedDataCallback)}tryGetLastState(){const A=this.context.connection.tryGetState(this.guid);A&&this.onReceivedData(A)}onReceivedData(A){var e;if(!this.destroyed&&typeof A.guid=="function"&&A.guid()===this.guid){EB&&console.log("new data",this.context.connection.connectionId,this.context.time.frameCount,this.guid,A),this.receivedUpdate=!0,this._receivedFastUpdate=A.fast();const g=A.transform();if(g){en.markDirty(this.gameObject,!0);const I=g.position();I&&(this.interpolatePosition&&((e=this._targetPosition)==null||e.set(I.x(),I.y(),I.z())),(!this.interpolatePosition||!this._receivedDataBefore)&&this.setWorldPosition(I.x(),I.y(),I.z()));const o=g.rotation();o&&(this.tempEuler.set(o.x(),o.y(),o.z()),this.interpolateRotation&&this._targetRotation.setFromEuler(this.tempEuler),(!this.interpolateRotation||!this._receivedDataBefore)&&qN(this.gameObject,this.tempEuler))}this._receivedDataBefore=!0}}onEnable(){this.lastWorldPos.copy(this.worldPosition),this.lastWorldRotation.copy(this.worldQuaternion),this._needsUpdate=!0,this._model&&this._model.updateIsOwned()}onDisable(){this._model&&this._model.freeOwnership()}onBeforeRender(){if(!this.activeAndEnabled||!this.context.connection.isConnected)return;if(!this.context.connection.isInRoom||!this._model){EB&&console.log("no model or room",this.name,this.guid,this.context.connection.isInRoom);return}this._shouldRequestOwnership&&(this._shouldRequestOwnership=!1,this._model.requestOwnership());const A=this.worldPosition,e=this.worldQuaternion;if(this._model.isOwned&&!this.receivedUpdate){const o=A.distanceTo(this.lastWorldPos),s=e.angleTo(this.lastWorldRotation),n=this._model.hasOwnership||this.fastMode?1e-4:.001;(o>n||s>n)&&(this._model.hasOwnership?this._needsUpdate=!0:(EB&&console.log(this.guid,"reset because not owned but",this.gameObject.name,this.lastWorldPos),this.worldPosition=this.lastWorldPos,A.copy(this.lastWorldPos),this.worldQuaternion=this.lastWorldRotation,e.copy(this.lastWorldRotation),en.markDirty(this.gameObject,!0),this._needsUpdate=!1))}if(this._model&&!this._model.hasOwnership&&this._model.isOwned&&this._receivedDataBefore){const o=this._receivedFastUpdate||this.fastMode?.5:.3;let s=!1;if(this.interpolatePosition&&this._targetPosition){const n=this.worldPosition;n.lerp(this._targetPosition,o),this.worldPosition=n,s=!0}if(this.interpolateRotation&&this._targetRotation){const n=this.worldQuaternion;n.slerp(this._targetRotation,o),this.worldQuaternion=n,s=!0}s&&en.markDirty(this.gameObject,!0)}if(this.receivedUpdate=!1,this.lastWorldPos.copy(A),this.lastWorldRotation.copy(e),!this._model||!this._model||this._model.hasOwnership===void 0||!this._model.hasOwnership)return;this.rb&&this.overridePhysics&&this._wasKinematic!==void 0&&(EB&&console.log("reset kinematic",this.rb.name,this._wasKinematic),this.rb.isKinematic=this._wasKinematic);const g=10,I=this.rb||this.fastMode;if(this._needsUpdate&&(this.context.time.frameCount%g===0||I)){if(yb++,I&&AD>0&&this.context.time.frameCount%AD!==0)return;EB&&console.log("send update",this.context.connection.connectionId,this.guid,this.gameObject.name,this.gameObject.guid),this._needsUpdate=!1;const o=a8(this.guid,this,!!I);this.context.connection.sendBinary(o)}}}const cEA=iA("debugshadowcomponents");fN.prototype.interactable={get(){return this.interactive},set(i){this.interactable=i}};const Js=Symbol("shadowDomOwner");class $s extends bA{constructor(){super(...arguments),B(this,"_shadowComponent",null),B(this,"_controlsChildLayout",!0),B(this,"_root"),B(this,"_parentComponent")}isRoot(){var A;return((A=this.Root)==null?void 0:A.gameObject)===this.gameObject}get canvas(){const A=this.Root;return A!=null&&A.isCanvas?A:null}get Canvas(){return this.canvas}markDirty(){xs.markUIDirty(this.context)}get shadowComponent(){return this._shadowComponent}set shadowComponent(A){this._shadowComponent=A}get controlsChildLayout(){return this._controlsChildLayout}set controlsChildLayout(A){this._controlsChildLayout=A,this.shadowComponent&&(this.shadowComponent.autoLayout=A)}get Root(){return this._root===void 0&&(this._root=gA.getComponentInParent(this.gameObject,eD)),this._root}__internalNewInstanceCreated(A){return super.__internalNewInstanceCreated(A),this.shadowComponent=null,this._root=void 0,this._parentComponent=void 0,this}onEnable(){super.onEnable()}addShadowComponent(A,e){var g;if(!A)return;this.removeShadowComponent();const I=this.isRoot()?this.gameObject:this.gameObject.parent;if(this._parentComponent=gA.getComponentInParent(I,$s),!this._parentComponent){console.warn(`Component "${this.name}" doesn't have a UI parent anywhere. Do you have an UI element outside a Canvas? UI components must be a child of a Canvas component`,this);return}A.name=this.name+" ("+(this.constructor.name??"UI")+")",A.autoLayout=this._parentComponent.controlsChildLayout,A[Js]=this,this.setShadowComponentOwner(A);let o=!1;if(((g=this.Root)==null?void 0:g.gameObject)===this.gameObject)this.gameObject.add(A);else{const s=this._parentComponent.shadowComponent;s&&(s?.add(A),o=!0)}this.shadowComponent=A,e&&e.shadowComponent&&this.shadowComponent&&e.shadowComponent.add(this.shadowComponent),fp&&A.add(new _o(.5)),this.onAfterAddedToScene(),o&&LY(),cEA&&console.warn("Added shadow component",this.shadowComponent)}setShadowComponentOwner(A){if(A&&(A[Js]===void 0||A[Js]===this)&&(A[Js]=this,A.children))for(const e of A.children)this.setShadowComponentOwner(e)}traverseOwnedShadowComponents(A,e,g){if(A&&A[Js]===e){g(A);for(const I of A.children)this.traverseOwnedShadowComponents(I,e,g)}}removeShadowComponent(){this.shadowComponent&&this.shadowComponent.removeFromParent()}onAfterAddedToScene(){}setInteractable(A){this.shadowComponent&&(this.shadowComponent.interactable=A)}}class eD extends $s{awake(){super.awake()}}class wd{constructor(A,e){B(this,"event"),B(this,"button"),B(this,"buttonName"),B(this,"_used",!1),B(this,"_propagationStopped",!1),B(this,"z__pointer_ctured",!1),B(this,"z__pointer_cture_rleased",!1),B(this,"inputSource"),B(this,"object"),B(this,"point"),B(this,"normal"),B(this,"face"),B(this,"distance"),B(this,"instanceId"),B(this,"intersection"),B(this,"isDown"),B(this,"isUp"),B(this,"isPressed"),B(this,"isClick"),B(this,"isDoubleClick"),B(this,"input"),this.event=e,this.input=A,this.button=e.button}get deviceIndex(){return this.event.deviceIndex}get pointerId(){return this.event.pointerId}get pressure(){return this.event.pressure}get used(){return this._used}use(){this._used||(this._used=!0,this.event.use(),this.pointerId!==void 0&&this.input.setPointerUsed(this.pointerId))}get propagationStopped(){return this._propagationStopped}stopPropagation(){this._propagationStopped=!0,this.event.stopImmediatePropagation()}stopImmediatePropagation(){this._propagationStopped=!0,this.event.stopImmediatePropagation()}setPointerCapture(){this.z__pointer_ctured=!0}releasePointerCapture(){this.z__pointer_cture_rleased=!0}get mode(){return this.event.mode}clone(){const A=new wd(this.input,this.event);return Object.assign(A,this),A}Use(){this.use()}StopPropagation(){this.event.stopImmediatePropagation()}}function mb(i,A){return gA.foreachComponent(i,e=>{if(!e.enabled)return;const g=e;if(A)switch(A){case"pointerdown":if(g.onPointerDown)return!0;break;case"pointerup":if(g.onPointerUp||g.onPointerClick)return!0;break;case"pointermove":if(g.onPointerEnter||g.onPointerExit||g.onPointerMove)return!0;break}else if(g.onPointerDown||g.onPointerUp||g.onPointerEnter||g.onPointerExit||g.onPointerClick)return!0},!1)===!0}var lEA=Object.defineProperty,dEA=Object.getOwnPropertyDescriptor,uEA=(i,A,e,g)=>{for(var I=g>1?void 0:g?dEA(A,e):A,o=i.length-1,s;o>=0;o--)(s=i[o])&&(I=(g?s(A,e,I):s(I))||I);return g&&I&&lEA(A,e,I),I};class tD extends bA{awake(){xs.createIfNoneExists(this.context)}onEnable(){var A;(A=xs.get(this.context))==null||A.register(this)}onDisable(){var A;(A=xs.get(this.context))==null||A.unregister(this)}}class Zo extends tD{constructor(){super(...arguments),B(this,"targets",null),B(this,"raycastHits",[]),B(this,"ignoreSkinnedMeshes",!1)}start(){this.targets=[this.gameObject]}performRaycast(A=null){if(!this.targets)return null;A??(A=new fn),A.targets=this.targets,A.results=this.raycastHits;const e=A.testObject;this.ignoreSkinnedMeshes&&(A.testObject=I=>I instanceof wo?"continue in children":e?e(I):!0);const g=this.context.physics.raycast(A);return A.testObject=e,g}}uEA([y()],Zo.prototype,"ignoreSkinnedMeshes",2);class ff extends Zo{constructor(){super(),this.ignoreSkinnedMeshes=!0}}class iD extends tD{performRaycast(A){if(!me.active||!(A!=null&&A.ray))return null;const e=A.ray.origin,g=.015;return this.context.physics.sphereOverlap(e,g)}}class kf{static getObject(A){const e=A[Js];return e&&(e.isComponent===!0?A=e.gameObject:A=e),A}static isInteractable(A,e){if(e&&(e.canvasGroup=void 0,e.graphic=void 0),A==null||!A.visible||(A=this.getObject(A),!A.visible))return!1;const g=this.tryFindCanvasGroup(A);if(g?.isCanvasGroup===!0&&(e&&(e.canvasGroup=g),g.blocksRaycasts===!1||g.interactable===!1))return!1;const I=dh(A,o=>{if(o.isGraphic===!0)return o},!1);return e&&I?.isGraphic===!0&&(e.graphic=I),!(I?.raycastTarget===!1||I?.layer===2)}static tryFindCanvasGroup(A){if(!A)return null;const e=dh(A,g=>{const I=g;if(I.blocksRaycasts!==void 0&&I.interactable!==void 0)return I},!1);return e!==void 0?e:this.tryFindCanvasGroup(A.parent)}}function Sb(i){return i[Js]||(i.parent?Sb(i.parent):null)}function pEA(i){return i.isUI===!0||typeof i[Js]=="object"}function Mf(i,A){if(!i)return;const e=i.material;if(e?.isMaterial===!0){const g=i.parent;g&&g.isText,e.side=A.doubleSided??!0?yt:Eg,e.shadowSide=A.doubleSided?yt:Eg,i.castShadow=A.castShadows?A.castShadows:!1,i.receiveShadow=A.receiveShadows?A.receiveShadows:!1}for(const g of i.children)Mf(g,A)}function ll(i,A,e){i[A]===void 0&&console.warn("Field",A,"is undefined on",i);const g=Proxy.revocable(i[A],{set(s,n,a,r){const C=s[n],Q=Reflect.set(s,n,a,r);return e(a,C),Q}}),I=g.revoke,o=i[A];return g.revoke=()=>{i[A]=o,I()},i[A]=g.proxy,g}const r8=Symbol("Scheduled action");function DEA(i,A,e=Xt.OnBeforeRender){let g=i[r8];g||(g=i[r8]={});const I=A.name;g[e]||(g[e]={});const o=g[e];if(o[I])return;function*s(){A?.call(i),o[I]=null}const n=i.startCoroutine(s(),e);o[I]=n}const vr=iA("debugeventsystem");var fb=(i=>(i.BeforeHandleInput="BeforeHandleInput",i.AfterHandleInput="AfterHandleInput",i))(fb||{});const Kr=class extends bA{constructor(){super(),B(this,"raycaster",[]),B(this,"_handleInputFn"),B(this,"pressedByID",new Map),B(this,"hoveredByID",new Map),B(this,"_sortedHits",[]),B(this,"_testObjectsCache",new Map),B(this,"_currentlyActiveRaycaster",null),B(this,"_currentPointerEventName",null),B(this,"shouldRaycastObject",i=>{var A;let e=null;if(pEA(i)&&(e=(A=i[Js])==null?void 0:A.gameObject),this._testObjectsCache.has(i)||e&&this._testObjectsCache.has(e))return this._testObjectsCache.get(i)===!1?"continue in children":!0;{let g=mb(i,this._currentPointerEventName);if(!g&&e&&(g=mb(e,this._currentPointerEventName)),g){this._testObjectsCache.set(i,!0);for(const I of i.children)this.shouldRaycastObject_AddToYesCache(I);return!0}return this._testObjectsCache.set(i,!1),"continue in children"}}),B(this,"_sortingBuffer",[]),B(this,"_noDepthTestingResults",[]),B(this,"out",{}),B(this,"_capturedPointer",{}),B(this,"pointerEnterSymbol",Symbol("pointerEnter")),B(this,"pointerExitSymbol",Symbol("pointerExit")),B(this,"currentActiveMeshUIComponents",[]),Kr.systems.push(this)}static createIfNoneExists(i){this.didSearchEventSystem||(this.didSearchEventSystem=!0,Kr.systems.length<=0&&Kr.systems.push(...gA.findObjectsOfType(Kr,i)));for(const e of Kr.systems)if(e.context===i)return;const A=new wA;gA.addNewComponent(A,Kr),i.scene.add(A)}static get systems(){const i=Ke.Current;return this._eventSystemMap.has(i)||this._eventSystemMap.set(i,[]),this._eventSystemMap.get(i)}static get(i){const A=this._eventSystemMap.get(i);return A&&A.length>0?A[0]:null}static get instance(){return this.systems[0]}static ensureUpdateMeshUI(i,A,e=!1){lB.update(i,A,e)}static markUIDirty(i){lB.markDirty()}get hasActiveUI(){return this.currentActiveMeshUIComponents.length>0}get isHoveringObjects(){return this.hoveredByID.size>0}onDestroy(){Kr.systems.splice(Kr.systems.indexOf(this),1)}start(){if(this.raycaster.length<=0&&!gA.findObjectOfType(tD,this.context)){const i=gA.addNewComponent(this.context.scene,Zo);this.raycaster.push(i),(se()||vr)&&console.warn("Added an ObjectRaycaster to the scene because no raycaster was found.")}}register(i){var A;i&&this.raycaster&&!this.raycaster.includes(i)&&((A=this.raycaster)==null||A.push(i))}unregister(i){var A,e;const g=(A=this.raycaster)==null?void 0:A.indexOf(i);g!==void 0&&g!==-1&&((e=this.raycaster)==null||e.splice(g,1))}onEnable(){this._handleInputFn??(this._handleInputFn=this.onPointerEvent.bind(this)),this.context.input.addEventListener(hi.PointerDown,this._handleInputFn),this.context.input.addEventListener(hi.PointerUp,this._handleInputFn),this.context.input.addEventListener(hi.PointerMove,this._handleInputFn)}onDisable(){this.context.input.removeEventListener(hi.PointerDown,this._handleInputFn),this.context.input.removeEventListener(hi.PointerUp,this._handleInputFn),this.context.input.removeEventListener(hi.PointerMove,this._handleInputFn)}onBeforeRender(){this.resetMeshUIStates()}onPointerEvent(i){if(i===void 0||i.propagationStopped)return;const A=new wd(this.context.input,i);this._currentPointerEventName=i.type,A.inputSource=this.context.input,A.isClick=i.isClick,A.isDoubleClick=i.isDoubleClick,A.isDown=i.type==hi.PointerDown,A.isUp=i.type==hi.PointerUp,A.isPressed=this.context.input.getPointerPressed(i.pointerId),vr&&(A.isDown?console.log("DOWN",A.pointerId):A.isUp&&console.log("UP",A.pointerId),A.isClick&&console.log("CLICK",A.pointerId));const e=new fn;i.hasRay?e.ray=i.ray:e.screenPoint=this.context.input.getPointerPositionRC(i.pointerId);const g=this.performRaycast(e);if(g){for(const o of g)o.event=i,i.intersections.push(o);i.origin.onPointerHits&&i.origin.onPointerHits({sender:this,event:i,hits:g})}vr&&A.isClick&&Ci("EventSystem: "+A.pointerId+" - "+this.context.time.frame+" - Up:"+A.isUp+", Down:"+A.isDown);const I={sender:this,args:A,hasActiveUI:this.currentActiveMeshUIComponents.length>0};this.dispatchEvent(new CustomEvent("BeforeHandleInput",{detail:I})),this.handleIntersections(g,A),this.dispatchEvent(new CustomEvent("AfterHandleInput",{detail:I}))}shouldRaycastObject_AddToYesCache(i){this._testObjectsCache.set(i,!0);for(const A of i.children)this.shouldRaycastObject_AddToYesCache(A)}performRaycast(i){if(!this.raycaster)return null;this._testObjectsCache.clear(),this._sortedHits.length=0,i||(i=new fn),i.testObject=this.shouldRaycastObject;for(const A of this.raycaster){if(!A.activeAndEnabled)continue;this._currentlyActiveRaycaster=A;const e=A.performRaycast(i);this._currentlyActiveRaycaster=null,e&&e.length>0&&this._sortedHits.push(...e)}return this._sortedHits.sort((A,e)=>A.distance-e.distance),this._sortedHits}assignHitInformation(i,A){A?(i.intersection=A,i.point=A.point,i.normal=A.normal,i.face=A.face,i.distance=A.distance,i.instanceId=A.instanceId):(i.intersection=void 0,i.point=void 0,i.normal=void 0,i.face=void 0,i.distance=void 0,i.instanceId=void 0)}handleIntersections(i,A){var e;if(i!=null&&i.length){i=this.sortCandidates(i);for(const I of i){if(A.event.immediatePropagationStopped)return!1;if(this.assignHitInformation(A,I),this.handleEventOnObject(I.object,A))return!0}}this.assignHitInformation(A,i?.[0]),this.invokePointerCapture(A);const g=this.hoveredByID.get(A.pointerId);return g&&this.propagatePointerExit(g.obj,g.data,null),this.hoveredByID.delete(A.pointerId),A.isUp&&((e=this.pressedByID.get(A.pointerId))==null||e.handlers.forEach(I=>this.invokeOnPointerUp(A,I)),this.pressedByID.delete(A.pointerId)),!1}sortCandidates(i){this._sortingBuffer.length=0,this._noDepthTestingResults.length=0;for(let A=0;A<i.length;A++){const e=i[A],g=e.object;if(g.material&&g.material.depthTest===!1){this._noDepthTestingResults.push(e);continue}this._sortingBuffer.push(e)}for(const A of this._sortingBuffer)this._noDepthTestingResults.push(A);return this._noDepthTestingResults}handleEventOnObject(i,A){if(!this.testIsVisible(i))return A.isClick&&vr&&console.log("not allowed",i),!1;if(A.pointerId===void 0)return vr&&console.error("Event without pointer can't be handled",A),!1;A.object=i;const e=i.parent,g=A.isClick??!1;let I=null;if(e&&e.isUI){const a=(A.isPressed||A.isClick)??!1;if(e[Js]){const r=e[Js].gameObject;if(r){if(!kf.isInteractable(r,this.out))return!1;I=this.out.canvasGroup??null,this.handleMeshUIIntersection(i,a),i=r}}}g&&vr&&console.log(this.context.time.frame,i);const o=this.hoveredByID.get(A.pointerId),s=o?.obj;s!==i&&s&&this.propagatePointerExit(s,o.data,i);const n=this.hoveredByID.get(A.pointerId);if(n?(n.obj=i,n.data=A):this.hoveredByID.set(A.pointerId,{obj:i,data:A}),A.isDown){const a=this.pressedByID.get(A.pointerId);a?(a.obj=i,a.data=A):this.pressedByID.set(A.pointerId,{obj:i,data:A,handlers:new Set})}return(I===null||I.interactable)&&this.handleMainInteraction(i,A,s??null),!0}propagate(i,A){for(;i;)gA.foreachComponent(i,e=>{A(e)},!1),i=i.parent}handleMainInteraction(i,A,e){const g=this.pressedByID.get(A.pointerId),I=e!==i;let o=!0;switch(A.event.pointerType){case"mouse":case"touch":const s=this.context.input.getPointerPositionLastFrame(A.pointerId),n=this.context.input.getPointerPosition(A.pointerId);o=s&&!ge.approximately(s,n);break}this.propagate(i,s=>{var n;const a=s;a.interactable!==!1&&(!a.activeAndEnabled||!a.enabled||(a.onPointerEnter&&I&&this.handlePointerEnter(a,A),A.isDown&&a.onPointerDown&&(a.onPointerDown(A),g?.handlers.add(a),this.handlePointerCapture(A,a)),a.onPointerMove&&(o&&a.onPointerMove(A),this.handlePointerCapture(A,a)),A.isUp&&(a.onPointerUp&&(this.invokeOnPointerUp(A,a),g?.handlers.delete(a)),a.onPointerExit&&((n=A.event)==null?void 0:n.pointerType)===bS.Touch&&(this.handlePointerExit(a,A),this.hoveredByID.delete(A.pointerId))),A.isClick&&a.onPointerClick&&a.onPointerClick(A)))}),A.isUp&&(g?.handlers.forEach(s=>{this.invokeOnPointerUp(A,s)}),this.pressedByID.delete(A.pointerId))}propagatePointerExit(i,A,e){this.propagate(i,g=>{if(!g.gameObject||g.destroyed)return;const I=g;if(I.onPointerExit){if(e&&this.isChild(e,g.gameObject))return;this.handlePointerExit(I,A)}})}invokeOnPointerUp(i,A){var e;(e=A.onPointerUp)==null||e.call(A,i),this.releasePointerCapture(i,A)}handlePointerEnter(i,A){i.onPointerEnter&&this.updatePointerState(i,A.pointerId,this.pointerEnterSymbol,!0)&&i.onPointerEnter(A),this.updatePointerState(i,A.pointerId,this.pointerExitSymbol,!1)}handlePointerExit(i,A){i.onPointerExit&&this.updatePointerState(i,A.pointerId,this.pointerExitSymbol,!0)&&i.onPointerExit(A),this.updatePointerState(i,A.pointerId,this.pointerEnterSymbol,!1)}updatePointerState(i,A,e,g){let I=i[e];if(g)return I&&I.includes(A)?!1:(I=I||[],I.push(A),i[e]=I,!0);{if(!I||!I.includes(A))return!1;const o=I.indexOf(A);return o!==-1&&I.splice(o,1),!0}}handlePointerCapture(i,A){if(i.z__pointer_ctured){i.z__pointer_ctured=!1;const e=i.pointerId;if(A.onPointerMove){const g=this._capturedPointer[e]||[];g.push(A),this._capturedPointer[e]=g}else se()&&!A.z__warned_no_pointermove&&(A.z__warned_no_pointermove=!0,console.warn("PointerCapture was requested but the component doesn't implement onPointerMove. It will not receive any pointer events"))}else i.z__pointer_cture_rleased&&(i.z__pointer_cture_rleased=!1,this.releasePointerCapture(i,A))}releasePointerCapture(i,A){const e=i.pointerId;if(this._capturedPointer[e]){const g=this._capturedPointer[e].indexOf(A);g!==-1&&(this._capturedPointer[e].splice(g,1),vr&&console.log("released pointer capture",e,A,this._capturedPointer))}}invokePointerCapture(i){var A;if(i.event.type===hi.PointerMove){const e=i.pointerId,g=this._capturedPointer[e];if(g){vr&&console.log("Captured",e,g);for(let I=0;I<g.length;I++){const o=g[I];if(o.destroyed){g.splice(I,1),I--;continue}(A=o.onPointerMove)==null||A.call(o,i)}}}}isChild(i,A){return!i||!A?!1:i===A?!0:i.parent?this.isChild(i.parent,A):!1}handleMeshUiObjectWithoutShadowDom(i,A){return!i||!i.isUI?!0:this.handleMeshUIIntersection(i,A)}handleMeshUIIntersection(i,A){const e=lB.updateState(i,A);return e&&this.currentActiveMeshUIComponents.push(e),e!==null}resetMeshUIStates(){if(this.context.input.getPointerPressedCount()>0&&lB.resetLastSelected(),!(!this.currentActiveMeshUIComponents||this.currentActiveMeshUIComponents.length<=0)){for(let i=0;i<this.currentActiveMeshUIComponents.length;i++){const A=this.currentActiveMeshUIComponents[i];lB.resetState(A)}this.currentActiveMeshUIComponents.length=0}}testIsVisible(i){return i?gA.isActiveSelf(i)?this.testIsVisible(i.parent):!1:!0}};let xs=Kr;B(xs,"_eventSystemMap",new Map),B(xs,"didSearchEventSystem",!1);class lB{static markDirty(){this.needsUpdate=!0}static update(A,e,g=!1){if(g){A.update();return}const I=e.time.frameCount;for(const o of this.lastUpdateFrame)if(o.context===e){if(I===o.frame)return;o.frame=I;let s=this.needsUpdate||I<1;o.nextUpdate===e.time.frameCount&&(s=!0),s&&(vr&&console.log("Update threemeshui"),this.needsUpdate=!1,A.update());return}this.lastUpdateFrame=[{context:e,frame:I,nextUpdate:I}],A.update()}static updateState(A,e){let g=null;if(A&&(g=this.findBlockInParent(A),g&&g!==this.lastSelected)){if(g.interactable===!1)return null;this.needsUpdate=!0}return g}static resetLastSelected(){const A=this.lastSelected;A&&(this.lastSelected=null,this.resetState(A))}static resetState(A){A&&(this.needsUpdate=!0)}static findBlockInParent(A){return A?A.isBlock?A:this.findBlockInParent(A.parent):null}}B(lB,"lastSelected",null),B(lB,"lastUpdateFrame",[]),B(lB,"needsUpdate",!1);var wEA=Object.defineProperty,yEA=Object.getOwnPropertyDescriptor,Ei=(i,A,e,g)=>{for(var I=g>1?void 0:g?yEA(A,e):A,o=i.length-1,s;o>=0;o--)(s=i[o])&&(I=(g?s(A,e,I):s(I))||I);return g&&I&&wEA(A,e,I),I};const kb=iA("debugorbit"),Gf=iA("freecam"),Rf=iA("debugcamerafit"),Uf=iA("smoothcam"),mEA={LEFT:"",UP:"",RIGHT:"",BOTTOM:""};let Mb;class gD extends CustomEvent{constructor(A,e){super("target-reached",{detail:{controls:A,type:e}})}}class St extends bA{constructor(){super(...arguments),B(this,"autoTarget",!0),B(this,"autoFit",!1),B(this,"enableRotate",!0),B(this,"autoRotate",!1),B(this,"autoRotateSpeed",1),B(this,"minAzimuthAngle",1/0),B(this,"maxAzimuthAngle",1/0),B(this,"minPolarAngle",0),B(this,"maxPolarAngle",Math.PI),B(this,"enableKeys",!0),B(this,"enableDamping",!0),B(this,"dampingFactor",.1),B(this,"enableZoom",!0),B(this,"minZoom",0),B(this,"maxZoom",1/0),B(this,"zoomSpeed",1),B(this,"zoomToCursor",!1),B(this,"enablePan",!0),B(this,"lookAtConstraint",null),B(this,"lookAtConstraint01",1),B(this,"allowInterrupt",!0),B(this,"middleClickToFocus",!0),B(this,"doubleClickToFocus",!0),B(this,"clickBackgroundToFitScene",2),B(this,"debugLog",!1),B(this,"targetLerpDuration",1),B(this,"_controls",null),B(this,"_cameraObject",null),B(this,"_lookTargetLerpActive",!1),B(this,"_lookTargetStartPosition",new S),B(this,"_lookTargetEndPosition",new S),B(this,"_lookTargetLerp01",0),B(this,"_lookTargetLerpDuration",0),B(this,"_cameraLerpActive",!1),B(this,"_cameraStartPosition",new S),B(this,"_cameraEndPosition",new S),B(this,"_cameraLerp01",0),B(this,"_cameraLerpDuration",0),B(this,"_inputs",0),B(this,"_enableTime",0),B(this,"_startedListeningToKeyEvents",!1),B(this,"_eventSystem"),B(this,"_afterHandleInputFn"),B(this,"_camera",null),B(this,"_syncedTransform"),B(this,"_didSetTarget",0),B(this,"targetElement",null),B(this,"_lastTimeClickOnBackground",-1),B(this,"_clickOnBackgroundCount",0),B(this,"_onPointerDown",A=>{if(this.clickBackgroundToFitScene>0&&A.isClick&&A.button===0){if(A.hasRay||A.intersections.push(...this.context.physics.raycast()),A.intersections.length<=0){const e=this.context.time.time-this._lastTimeClickOnBackground;this._lastTimeClickOnBackground=this.context.time.time,this.clickBackgroundToFitScene<=1||e<this.clickBackgroundToFitScene*.15?(this._clickOnBackgroundCount+=1,this._clickOnBackgroundCount>=this.clickBackgroundToFitScene-1&&this.fitCamera(this.context.scene.children,{immediate:!1})):this._clickOnBackgroundCount=0}kb&&console.log(this.clickBackgroundToFitScene,A.intersections.length,this._clickOnBackgroundCount)}}),B(this,"onControlsChangeStarted",()=>{this._syncedTransform&&this._syncedTransform.requestOwnership()}),B(this,"_shouldDisable",!1),B(this,"__onPreRender",()=>{const A=this.context.pre_render_callbacks.indexOf(this.__onPreRender);A>=0&&this.context.pre_render_callbacks.splice(A,1),this.autoFit&&(this.autoFit=!1,this.fitCamera(this.scene.children,{centerCamera:"y",immediate:!0}))}),B(this,"_haveAttachedKeyboardEvents",!1)}get isCameraController(){return!0}get controls(){return this._controls}get controllerObject(){return this._cameraObject}onStartInteraction(A){var e;(e=this.controls)==null||e.addEventListener("start",A)}get targetLerpSpeed(){return 5}set targetLerpSpeed(A){this.targetLerpDuration=1/A}awake(){this._didSetTarget=0,this._startedListeningToKeyEvents=!1}start(){this._eventSystem=xs.get(this.context)??void 0,this._eventSystem&&(this._afterHandleInputFn=this.afterHandleInput.bind(this),this._eventSystem.addEventListener(fb.AfterHandleInput,this._afterHandleInputFn))}onDestroy(){var A,e;(A=this._controls)==null||A.dispose(),(e=this._eventSystem)==null||e.removeEventListener(fb.AfterHandleInput,this._afterHandleInputFn)}onEnable(){this._didSetTarget=0,this._enableTime=this.context.time.time;const A=gA.getComponent(this.gameObject,Tt);this._camera=A;let e=A?.cam;if(!e&&this.gameObject instanceof xe&&(e=this.gameObject),e&&RN(e,this,!0),!this._controls&&e instanceof xe){this._cameraObject=e;const g=this.targetElement??this.context.renderer.domElement,I=e?.quaternion.clone();this._controls=new g8(e,g),e?.quaternion.copy(I),Mb===void 0&&(Mb={...this._controls.keys})}this._controls&&(Gf&&(this.enablePan=!0,this.enableZoom=!0,this.middleClickToFocus=!0,ls()&&(this.doubleClickToFocus=!0)),this._controls.addEventListener("start",this.onControlsChangeStarted),e?.type==="PerspectiveCamera"?Gf||(this._controls.minDistance=this.minZoom,this._controls.maxDistance=this.maxZoom):Gf||(this._controls.minZoom=this.minZoom,this._controls.maxZoom=this.maxZoom),this._startedListeningToKeyEvents||(this._startedListeningToKeyEvents=!0,this._controls.listenToKeyEvents(window.document.body))),this._syncedTransform=gA.getComponent(this.gameObject,cB)??void 0,this.context.input.addEventListener("pointerup",this._onPointerDown),this.context.pre_render_callbacks.push(this.__onPreRender)}onDisable(){var A;(A=this._camera)!=null&&A.cam&&RN(this._camera.cam,this,!1),this._controls&&(this._controls.enabled=!1,this._controls.autoRotate=!1,this._controls.removeEventListener("start",this.onControlsChangeStarted)),this.context.input.removeEventListener("pointerup",this._onPointerDown)}afterHandleInput(A){A.detail.args.pointerId===0&&(A.detail.args.isDown?this._controls&&this._eventSystem&&(this._shouldDisable=this._eventSystem.hasActiveUI):(!A.detail.args.isPressed||A.detail.args.isUp)&&(this._shouldDisable=!1))}onBeforeRender(){var A,e;if(!this._controls)return;if(this._cameraObject!==this.context.mainCamera){this._controls.enabled=!1;return}if(this._controls.enabled=!0,(this.context.input.getPointerDown(1)||this.context.input.getPointerDown(2)||this.context.input.mouseWheelChanged||this.context.input.getPointerPressed(0)&&(A=this.context.input.getPointerPositionDelta(0))!=null&&A.length()||0>.1)&&(this._inputs+=1),this._inputs>0&&this.allowInterrupt&&(this.enableRotate&&(this.autoRotate=!1),this._cameraLerpActive=!1,this._lookTargetLerpActive=!1),this._inputs=0,this.autoTarget&&this._didSetTarget++===0){const I=gA.getComponent(this.gameObject,Tt);if(I&&!this.setLookTargetFromConstraint()){this.debugLog&&console.log("NO TARGET");const o=Fe(I.cam),s=Math.max(.01,o.length()),n=new S(0,0,-s).applyMatrix4(I.cam.matrixWorld);this.setLookTargetPosition(n,!0)}if(!this.setLookTargetFromConstraint()){const o=new fn;o.screenPoint=new AA(0,0),o.lineThreshold=.1;const s=this.context.physics.raycast(o);s.length>0&&this.setLookTargetPosition(s[0].point,!0),Rf&&console.log("OrbitControls hits",...s)}}let g=this.middleClickToFocus&&this.context.input.getPointerClicked(1);if(g||(g=this.doubleClickToFocus&&this.context.input.getPointerDoubleClicked(0)&&this.context.time.time-this._enableTime>.3),g&&this.setTargetFromRaycast(),this._lookTargetLerpActive||this._cameraLerpActive){if(this._cameraLerpActive&&this._cameraObject)if(this._cameraLerp01+=this.context.time.deltaTime/this._cameraLerpDuration,this._cameraLerp01>=1)this._cameraObject.position.copy(this._cameraEndPosition),this._cameraLerpActive=!1,this.dispatchEvent(new gD(this,"camera"));else{const I=ge.easeInOutCubic(this._cameraLerp01);this._cameraObject.position.lerpVectors(this._cameraStartPosition,this._cameraEndPosition,I)}if(this._lookTargetLerpActive)if(this._lookTargetLerp01+=this.context.time.deltaTime/this._lookTargetLerpDuration,this._lookTargetLerp01>=1)this._controls.target.copy(this._lookTargetEndPosition),this._lookTargetLerpActive=!1,this.dispatchEvent(new gD(this,"lookat"));else{const I=ge.easeInOutCubic(this._lookTargetLerp01);this._controls.target.lerpVectors(this._lookTargetStartPosition,this._lookTargetEndPosition,I)}}if(this._controls){if(this.debugLog&&(this._controls.domElement=this.context.renderer.domElement),this._controls.enabled=!this._shouldDisable&&this._camera===this.context.mainCameraComponent&&!this.context.isInXR,this._controls.keys=this.enableKeys?Mb:mEA,this._controls.autoRotate=this.autoRotate,this._controls.autoRotateSpeed=this.autoRotateSpeed,this._controls.enableZoom=this.enableZoom,this._controls.zoomSpeed=this.zoomSpeed,this._controls.zoomToCursor=this.zoomToCursor,this._controls.enableDamping=this.enableDamping,this._controls.dampingFactor=this.dampingFactor,this._controls.enablePan=this.enablePan,this._controls.enableRotate=this.enableRotate,this._controls.minAzimuthAngle=this.minAzimuthAngle,this._controls.maxAzimuthAngle=this.maxAzimuthAngle,this._controls.minPolarAngle=this.minPolarAngle,this._controls.maxPolarAngle=this.maxPolarAngle,typeof Uf=="number"||Uf===!0){this._controls.enableDamping=!0;const I=typeof Uf=="number"?Uf:.99;this._controls.dampingFactor=Math.max(.001,1-Math.min(1,I))}this.allowInterrupt||(this._lookTargetLerpActive&&(this._controls.enablePan=!1),this._cameraLerpActive&&(this._controls.enableRotate=!1,this._controls.autoRotate=!1),(this._lookTargetLerpActive||this._cameraLerpActive)&&(this._controls.enableZoom=!1)),this.context.isInXR||(!Gf&&(e=this.lookAtConstraint)!=null&&e.locked&&this.setLookTargetFromConstraint(0,this.lookAtConstraint01),this._controls.update(),kb&&pe.DrawWireSphere(this._controls.target,.1,65280))}}setCameraAndLookTarget(A){if(!A||!(A instanceof wA))return;const e=Fe(A),g=JN(A);this.setTargetFromRaycast(new po(e,g)),this.setCameraTargetPosition(e)}setCameraTargetPosition(A,e=!1){var g,I;A&&(A instanceof wA&&(A=Fe(A)),this._cameraEndPosition||(this._cameraEndPosition=new S),this._cameraEndPosition.copy(A),e===!0?(this._cameraLerpActive=!1,(g=this.controllerObject)==null||g.position.copy(this._cameraEndPosition)):this._cameraObject&&(this._cameraLerpActive=!0,this._cameraLerp01=0,this._cameraStartPosition.copy((I=this._cameraObject)==null?void 0:I.position),typeof e=="number"?this._cameraLerpDuration=e:this._cameraLerpDuration=this.targetLerpDuration))}get cameraLerpActive(){return this._cameraLerpActive}stopCameraLerp(){this._cameraLerpActive=!1}setLookTargetPosition(A=null,e=!1){this._controls&&A&&(A instanceof wA&&(A=Fe(A)),this._lookTargetEndPosition.copy(A),kb&&(console.warn("OrbitControls: setLookTargetPosition",A,e),pe.DrawWireSphere(this._lookTargetEndPosition,.2,16711680,2)),e===!0?this._controls.target.copy(this._lookTargetEndPosition):(this._lookTargetLerpActive=!0,this._lookTargetLerp01=0,this._lookTargetStartPosition.copy(this._controls.target),typeof e=="number"?this._lookTargetLerpDuration=e:this._lookTargetLerpDuration=this.targetLerpDuration))}get lookTargetLerpActive(){return this._lookTargetLerpActive}stopLookTargetLerp(){this._lookTargetLerpActive=!1}setLookTargetFromConstraint(A=0,e=1){var g;if(!this._controls)return!1;const I=(g=this.lookAtConstraint)==null?void 0:g.sources;if(I&&I.length>0){const o=I[A];if(o)return o.getWorldPosition(this._lookTargetEndPosition),this.lerpLookTarget(this._lookTargetEndPosition,e),!0}return!1}lerpTarget(A,e){return this.lerpLookTarget(A,e)}lerpLookTarget(A,e){this._controls&&(e>=1?this._controls.target.copy(A):this._controls.target.lerp(A,e))}setTargetFromRaycast(A){if(!this.controls)return;const e=A?this.context.physics.raycastFromRay(A):this.context.physics.raycast();for(const g of e)if(g.distance>0&&gA.isActiveInHierarchy(g.object)){const I=Sb(g.object);if(I){const o=I.canvas;if(o!=null&&o.screenspace)break}this.setLookTargetPosition(g.point);break}}fitCamera(A,e={fitOffset:void 0,immediate:!1}){if(this.context.isInXR)return;const{immediate:g=!1,centerCamera:I}=e;let{fitOffset:o}=e;o==null&&(o=1.1);const s=this._cameraObject,n=this._controls;if(A!=null&&A.length||(A=this.context.scene.children),A.length<=0){console.warn("No objects to fit camera to...");return}if(!s||!n){console.warn("No camera or controls found to fit camera to objects...");return}const a=new S,r=new S,C=$n(A,void 0);s.updateMatrixWorld(),s.updateProjectionMatrix(),C.getCenter(r);const Q=new S;if(C.getSize(Q),C.applyMatrix4(s.matrixWorldInverse),C.getSize(a),C.setFromCenterAndSize(r,a),Number.isNaN(a.x)||Number.isNaN(a.y)||Number.isNaN(a.z)){console.warn("Camera fit size resultet in NaN",s,C,[...A]);return}if(a.length()<=1e-10){Rf&&console.warn("Camera fit size is zero",C,[...A]);return}const h=s.fov,E=2*Math.atan(Math.tan(h*Math.PI/360/2)*s.aspect)/Math.PI*360,c=a.y/(2*Math.atan(Math.PI*h/360)),l=a.x/(2*Math.atan(Math.PI*E/360)),d=o*Math.max(c,l)+a.z/2;Rf&&console.log("Fit camera to objects",c,l,"distance",d),n.maxDistance=d*10,n.minDistance=d*.01;const u=.05,D=r.clone();D.y-=a.y*u,this.setLookTargetPosition(D,g),this.autoTarget=!1;const p=gA.findObjectOfType(hB),w=p?p.radius:0,f=Math.max(Q.x,Q.y,Q.z,w);s.near=d/100,s.far=f+d*10,s.updateMatrixWorld(),s.updateProjectionMatrix();const G=Fe(s),M=r.clone();if(M.sub(G),I==="y"&&(M.y=0),M.normalize(),M.multiplyScalar(d),I==="y"&&(M.y+=-u*4*a.y),s.parent){const U=s.parent.worldToLocal(r.clone().sub(M));this.setCameraTargetPosition(U,g)}else console.error(`Can not fit camera ${s.name} because it has no parent`);if(Rf){const U=new bU(C);this.context.scene.add(U),LN(U,fu(s)),setTimeout(()=>{this.context.scene.remove(U)},1e4),this._haveAttachedKeyboardEvents||(this._haveAttachedKeyboardEvents=!0,document.body.addEventListener("keydown",v=>{v.code==="KeyF"&&this.fitCamera(A,{fitOffset:o,immediate:g})}))}n.update()}}Ei([y()],St.prototype,"autoTarget",2),Ei([y()],St.prototype,"autoFit",2),Ei([y()],St.prototype,"enableRotate",2),Ei([y()],St.prototype,"autoRotate",2),Ei([y()],St.prototype,"autoRotateSpeed",2),Ei([y()],St.prototype,"minAzimuthAngle",2),Ei([y()],St.prototype,"maxAzimuthAngle",2),Ei([y()],St.prototype,"minPolarAngle",2),Ei([y()],St.prototype,"maxPolarAngle",2),Ei([y()],St.prototype,"enableKeys",2),Ei([y()],St.prototype,"enableDamping",2),Ei([y()],St.prototype,"dampingFactor",2),Ei([y()],St.prototype,"enableZoom",2),Ei([y()],St.prototype,"minZoom",2),Ei([y()],St.prototype,"maxZoom",2),Ei([y()],St.prototype,"zoomSpeed",2),Ei([y()],St.prototype,"enablePan",2),Ei([y(mh)],St.prototype,"lookAtConstraint",2),Ei([y()],St.prototype,"lookAtConstraint01",2),Ei([y()],St.prototype,"allowInterrupt",2),Ei([y()],St.prototype,"middleClickToFocus",2),Ei([y()],St.prototype,"doubleClickToFocus",2),Ei([y()],St.prototype,"clickBackgroundToFitScene",2),Ei([y()],St.prototype,"targetLerpDuration",2);var SEA=Object.defineProperty,fEA=Object.getOwnPropertyDescriptor,no=(i,A,e,g)=>{for(var I=g>1?void 0:g?fEA(A,e):A,o=i.length-1,s;o>=0;o--)(s=i[o])&&(I=(g?s(A,e,I):s(I))||I);return g&&I&&SEA(A,e,I),I},dB=(i=>(i[i.Skybox=1]="Skybox",i[i.SolidColor=2]="SolidColor",i[i.Uninitialized=4]="Uninitialized",i))(dB||{});const br=iA("debugcam"),C8=iA("debugscreenpointtoray");var Nf;const ID=(Nf=class extends bA{constructor(){super(...arguments),B(this,"_nearClipPlane",.1),B(this,"_farClipPlane",1e3),B(this,"orthographic",!1),B(this,"orthographicSize",5),B(this,"ARBackgroundAlpha",0),B(this,"_cullingMask",4294967295),B(this,"_backgroundBlurriness",0),B(this,"_backgroundIntensity",1),B(this,"_backgroundRotation"),B(this,"_environmentIntensity"),B(this,"_targetTexture",null),B(this,"_backgroundColor"),B(this,"_fov"),B(this,"_cam",null),B(this,"_clearFlags",2),B(this,"_skybox"),B(this,"_frustum"),B(this,"_projScreenMatrix",new DA)}get isCamera(){return!0}get aspect(){return this._cam instanceof xe?this._cam.aspect:this.context.domWidth/this.context.domHeight}set aspect(i){this._cam instanceof xe&&this._cam.aspect!==i&&(this._cam.aspect=i,this._cam.updateProjectionMatrix())}get fieldOfView(){return this._cam instanceof xe?this._cam.fov:this._fov}set fieldOfView(i){const A=this.fieldOfView!=i;if(this._fov=i,A&&this._cam&&this._cam instanceof xe){if(this._fov===void 0){console.warn("Can not set undefined fov on PerspectiveCamera");return}this._cam.fov=this._fov,this._cam.updateProjectionMatrix()}}get nearClipPlane(){return this._nearClipPlane}set nearClipPlane(i){const A=this._nearClipPlane!=i;this._nearClipPlane=i,this._cam&&A&&(this._cam.near=i,this._cam.updateProjectionMatrix())}get farClipPlane(){return this._farClipPlane}set farClipPlane(i){const A=this._farClipPlane!=i;this._farClipPlane=i,this._cam&&A&&(this._cam.far=i,this._cam.updateProjectionMatrix())}get clearFlags(){return this._clearFlags}set clearFlags(i){i!==this._clearFlags&&(this._clearFlags=i,this.applyClearFlagsIfIsActiveCamera())}set cullingMask(i){this._cullingMask=i,this._cam&&(this._cam.layers.mask=i)}get cullingMask(){return this._cam?this._cam.layers.mask:this._cullingMask}set cullingLayer(i){this.cullingMask=(1<<i|0)>>>0}set backgroundBlurriness(i){i!==this._backgroundBlurriness&&(i===void 0?this._backgroundBlurriness=void 0:this._backgroundBlurriness=Math.min(Math.max(i,0),1),this.applyClearFlagsIfIsActiveCamera())}get backgroundBlurriness(){return this._backgroundBlurriness}set backgroundIntensity(i){i!==this._backgroundIntensity&&(i===void 0?this._backgroundIntensity=void 0:this._backgroundIntensity=Math.min(Math.max(i,0),10),this.applyClearFlagsIfIsActiveCamera())}get backgroundIntensity(){return this._backgroundIntensity}set backgroundRotation(i){i!==this._backgroundRotation&&(i===void 0?this._backgroundRotation=void 0:this._backgroundRotation=i,this.applyClearFlagsIfIsActiveCamera())}get backgroundRotation(){return this._backgroundRotation}set environmentIntensity(i){this._environmentIntensity=i}get environmentIntensity(){return this._environmentIntensity}get backgroundColor(){return this._backgroundColor??null}set backgroundColor(i){if(i){if(this._backgroundColor)this._backgroundColor.copy(i);else{if(!i.clone)return;this._backgroundColor=i.clone()}i.alpha===void 0&&(this._backgroundColor.alpha=1),this.applyClearFlagsIfIsActiveCamera()}}set targetTexture(i){this._targetTexture=i}get targetTexture(){return this._targetTexture}get cam(){return this.activeAndEnabled&&this.buildCamera(),this._cam}screenPointToRay(i,A,e){const g=this.cam,I=ID._origin;I.set(i,A,-1),this.context.input.convertScreenspaceToRaycastSpace(I),C8&&console.log("screenPointToRay",i.toFixed(2),A.toFixed(2),"now:",I.x.toFixed(2),I.y.toFixed(2),"isInXR:"+this.context.isInXR),I.z=-1,I.unproject(g);const o=ID._direction.set(I.x,I.y,I.z),s=Fe(g);return o.sub(s),o.normalize(),e?(e.set(s,o),e):new po(s.clone(),o.clone())}getFrustum(){return this._frustum||(this._frustum=new cQ,this.updateFrustum()),this._frustum}updateFrustum(){this._frustum||(this._frustum=new cQ),this._frustum.setFromProjectionMatrix(this.getProjectionScreenMatrix(this._projScreenMatrix,!0),this.context.renderer.coordinateSystem)}getProjectionScreenMatrix(i,A){return A&&this._projScreenMatrix.multiplyMatrices(this.cam.projectionMatrix,this.cam.matrixWorldInverse),i===this._projScreenMatrix?i:i.copy(this._projScreenMatrix)}awake(){C8&&window.addEventListener("pointerdown",i=>{const A=i.clientX,e=i.clientY;console.log("touch",A.toFixed(2),e.toFixed(2));const g=this.screenPointToRay(A,e),I="#"+Math.floor(Math.random()*16777215).toString(16);pe.DrawRay(g.origin,g.direction,I,10)})}onEnable(){br&&console.log(`Camera enabled: "${this.name}". ClearFlags=${dB[this._clearFlags]}`,this),this.buildCamera(),(this.tag=="MainCamera"||!this.context.mainCameraComponent)&&(this.context.setCurrentCamera(this),MEA(this)),this.applyClearFlagsIfIsActiveCamera({applySkybox:!0})}onDisable(){this.context.removeCamera(this)}onBeforeRender(){if(this._cam&&(this._frustum&&this.updateFrustum(),this._clearFlags===2&&this.applyClearFlagsIfIsActiveCamera(),this._targetTexture)){this.context.isManagedExternally&&(this._warnedAboutExternalRenderer||(this._warnedAboutExternalRenderer=!0,console.warn("Rendering with external renderer is not supported yet. This may not work or throw errors. Please remove the the target texture from your camera: "+this.name,this.targetTexture))),this.context.composer;const i=this.context.renderer;if(i){const A=this.context.mainCameraComponent;this.applyClearFlags(),this._targetTexture.render(this.context.scene,this._cam,i),A?.applyClearFlags()}}}buildCamera(){if(this._cam)return;const i=this.gameObject.isCamera;let A=null;if(i?(A=this.gameObject,A?.layers.enableAll(),A instanceof xe&&(this._fov=A.fov)):A=this.gameObject.children[0],A&&A.isCamera)A instanceof xe&&(this._fov&&(A.fov=this._fov),A.near=this._nearClipPlane,A.far=this._farClipPlane,A.updateProjectionMatrix());else if(!this.orthographic)A=new xe(this.fieldOfView,window.innerWidth/window.innerHeight,this._nearClipPlane,this._farClipPlane),this.fieldOfView&&(A.fov=this.fieldOfView),this.gameObject.add(A);else{const e=this.orthographicSize*100;A=new jn(window.innerWidth/-e,window.innerWidth/e,window.innerHeight/e,window.innerHeight/-e,this._nearClipPlane,this._farClipPlane),this.gameObject.add(A)}this._cam=A,this._cam.layers.mask=this._cullingMask,this.tag=="MainCamera"&&this.context.setCurrentCamera(this)}applyClearFlagsIfIsActiveCamera(i){this.context.mainCameraComponent===this&&this.applyClearFlags(i)}applyClearFlags(i){if(!this._cam){br&&console.log("Camera does not exist (apply clear flags)");return}if(this.fieldOfView=this._fov,br){const A=`Camera "${this.name}" clear flags: ${dB[this._clearFlags]}`;console.debug(A)}switch(this._clearFlags){case 1:if(ID.backgroundShouldBeTransparent(this.context)&&(!this.ARBackgroundAlpha||this.ARBackgroundAlpha<.001)){this.context.scene.background=null,this.context.renderer.setClearColor(0,0);return}(!this.scene.background||!this._skybox||i?.applySkybox===!0)&&this.applySceneSkybox(),this._backgroundBlurriness!==void 0?this.context.scene.backgroundBlurriness=this._backgroundBlurriness:br&&console.warn(`Camera "${this.name}" has no background blurriness`),this._backgroundIntensity!==void 0&&(this.context.scene.backgroundIntensity=this._backgroundIntensity),this._backgroundRotation!==void 0?this.context.scene.backgroundRotation=this._backgroundRotation:br&&console.warn(`Camera "${this.name}" has no background intensity`);break;case 2:if(this._backgroundColor){let A=this._backgroundColor.alpha;ID.backgroundShouldBeTransparent(this.context)&&(A=this.ARBackgroundAlpha??0),this.context.scene.background=null,this.context.renderer.setClearColor(this._backgroundColor,A)}else br&&console.warn(`Camera "${this.name}" has no background color`,this);break;case 4:this.context.scene.background=null,this.context.renderer.setClearColor(0,0);break}}applySceneSkybox(){this._skybox||(this._skybox=new kEA(this)),this._skybox.apply()}static backgroundShouldBeTransparent(i){var A,e,g,I;const o=(A=i.renderer.xr)==null?void 0:A.getSession();if(!o)return!1;if(typeof o._transparent=="boolean")return o._transparent;const s=o.environmentBlendMode;br&&Ci("Environment blend mode: "+s+" on "+navigator.userAgent);let n=s==="additive"||s==="alpha-blend";return i.isInAR&&s==="opaque"&&((e=navigator.userAgent)!=null&&e.includes("OculusBrowser")||(g=navigator.userAgent)!=null&&g.includes("Mozilla")&&(I=navigator.userAgent)!=null&&I.includes("Mobile WebXRViewer/v2"))&&(n=!0),o._transparent=n,n}},B(Nf,"_origin",new S),B(Nf,"_direction",new S),Nf);let Tt=ID;no([y()],Tt.prototype,"aspect",1),no([y()],Tt.prototype,"fieldOfView",1),no([y()],Tt.prototype,"nearClipPlane",1),no([y()],Tt.prototype,"farClipPlane",1),no([y()],Tt.prototype,"clearFlags",1),no([y()],Tt.prototype,"orthographic",2),no([y()],Tt.prototype,"orthographicSize",2),no([y()],Tt.prototype,"ARBackgroundAlpha",2),no([y()],Tt.prototype,"cullingMask",1),no([y()],Tt.prototype,"backgroundBlurriness",1),no([y()],Tt.prototype,"backgroundIntensity",1),no([y(It)],Tt.prototype,"backgroundRotation",1),no([y()],Tt.prototype,"environmentIntensity",1),no([y(Rt)],Tt.prototype,"backgroundColor",1),no([y(El)],Tt.prototype,"targetTexture",1);class kEA{constructor(A){B(this,"_camera"),B(this,"_skybox"),this._camera=A}get context(){var A;return(A=this._camera)==null?void 0:A.context}apply(){this._skybox=this.context.lightmaps.tryGetSkybox(this._camera.sourceId),this._skybox?this.context.scene.background!==this._skybox&&(br&&console.log(`Camera "${this._camera.name}" set skybox`,this._camera,this._skybox),this._skybox.mapping=Eo,this.context.scene.background=this._skybox):(this._did_log_failed_to_find_skybox||(this._did_log_failed_to_find_skybox=!0,console.warn(`Camera "${this._camera.name}" failed to load/find skybox texture`,this._camera.sourceId,this.context.lightmaps,"Current background: ",this.context.scene.background)),(br||se())&&Lt(`Camera "${this._camera.name}" has no skybox texture`))}}function MEA(i){iA("freecam")&&i.context.mainCameraComponent===i&&gA.getOrAddComponent(i.gameObject,St)}class uB extends bA{constructor(){super(...arguments),B(this,"_listener",null),B(this,"onInteraction",()=>{this.destroyed||this.listener==null||this.addListenerIfItExists()})}get listener(){return this._listener==null&&(this._listener=new g2),this._listener}onEnable(){aB.registerWaitForInteraction(this.onInteraction),this.addListenerIfItExists()}onDisable(){aB.unregisterWaitForInteraction(this.onInteraction),this.removeListenerIfItExists()}addListenerIfItExists(){const A=this._listener;if(!A||A!=null&&A.parent)return;const e=this.context.mainCameraComponent||gA.getComponentInParent(this.gameObject,Tt);e!=null&&e.cam?e.cam.add(A):this.gameObject.add(A),A.filter?(A.gain.connect(A.filter),A.filter.connect(A.context.destination)):A.gain.connect(A.context.destination)}removeListenerIfItExists(){const A=this._listener;A&&(A.removeFromParent(),A.filter&&A.filter.disconnect(),A.gain&&A.gain.disconnect())}}class GEA extends Fi{constructor(A,e=1,g=16,I=2){const o=new ue,s=g+I*2,n=new Float32Array((s*3+3)*3);o.setAttribute("position",new Ie(n,3));const a=new Zt({color:65280}),r=new Zt({color:16776960});super(o,[r,a]),this.audio=A,this.range=e,this.divisionsInnerAngle=g,this.divisionsOuterAngle=I,this.type="PositionalAudioHelper",this.update()}update(){const A=this.audio,e=this.range,g=this.divisionsInnerAngle,I=this.divisionsOuterAngle,o=ct.degToRad(A.panner.coneInnerAngle),s=ct.degToRad(A.panner.coneOuterAngle),n=o/2,a=s/2;let r=0,C=0,Q,h;const E=this.geometry,c=E.attributes.position;E.clearGroups();function l(d,u,D,p){const w=(u-d)/D;for(c.setXYZ(r,0,0,0),C++,Q=d;Q<u;Q+=w)h=r+C,c.setXYZ(h,Math.sin(Q)*e,0,Math.cos(Q)*e),c.setXYZ(h+1,Math.sin(Math.min(Q+w,u))*e,0,Math.cos(Math.min(Q+w,u))*e),c.setXYZ(h+2,0,0,0),C+=3;E.addGroup(r,C,p),r+=C,C=0}l(-a,-n,I,0),l(-n,n,g,1),l(n,a,I,0),c.needsUpdate=!0,o===s&&(this.material[0].visible=!1)}dispose(){this.geometry.dispose(),this.material[0].dispose(),this.material[1].dispose()}}var REA=Object.defineProperty,UEA=Object.getOwnPropertyDescriptor,ha=(i,A,e,g)=>{for(var I=g>1?void 0:g?UEA(A,e):A,o=i.length-1,s;o>=0;o--)(s=i[o])&&(I=(g?s(A,e,I):s(I))||I);return g&&I&&REA(A,e,I),I};const xI=iA("debugaudio"),pB=class extends bA{constructor(){super(...arguments),B(this,"clip",""),B(this,"playOnAwake",!1),B(this,"preload",!1),B(this,"_spatialBlend",0),B(this,"_minDistance",1),B(this,"_maxDistance",100),B(this,"_volume",1),B(this,"rollOffMode",0),B(this,"playInBackground",!0),B(this,"_loop",!1),B(this,"sound",null),B(this,"helper",null),B(this,"wasPlaying",!1),B(this,"audioLoader",null),B(this,"shouldPlay",!1),B(this,"_lastClipStartedLoading",null),B(this,"_audioElement",null),B(this,"onVisibilityChanged",()=>{switch(document.visibilityState){case"hidden":(this.playInBackground===!1||ls())&&(this.wasPlaying=this.isPlaying,this.isPlaying&&this.pause());break;case"visible":xI&&console.log("visible",this.enabled,this.playOnAwake,!this.isPlaying,pB.userInteractionRegistered,this.wasPlaying),this.enabled&&this.playOnAwake&&!this.isPlaying&&pB.userInteractionRegistered&&this.wasPlaying&&this.play();break}}),B(this,"onApplicationMuteChanged",()=>{var i,A;this.context.application.muted?(i=this.sound)==null||i.setVolume(0):(A=this.sound)==null||A.setVolume(this.volume)}),B(this,"createAudio",i=>{xI&&console.log("AudioBuffer finished loading",i);const A=this.Sound;if(!A){xI&&console.warn("Failed getting sound?",this.name);return}A.isPlaying&&A.stop(),i&&A.setBuffer(i),A.loop=this._loop,this.context.application.muted?A.setVolume(0):A.setVolume(this.volume),A.autoplay=this.shouldPlay&&pB.userInteractionRegistered,this.applySpatialDistanceSettings(),A.isPlaying&&A.stop(),pB.registerWaitForAllowAudio(this.__onAllowAudioCallback)}),B(this,"__onAllowAudioCallback",()=>{this.shouldPlay&&this.play()}),B(this,"_lastContextTime",0),B(this,"_hasEnded",!0),B(this,"_needUpdateSpatialDistanceSettings",!1)}static get userInteractionRegistered(){return aB.userInteractionRegistered}static registerWaitForAllowAudio(i){aB.registerWaitForAllowAudio(i)}get loop(){return this.sound&&(this._loop=this.sound.getLoop()),this._loop}set loop(i){this._loop=i,this.sound&&this.sound.setLoop(i)}get spatialBlend(){return this._spatialBlend}set spatialBlend(i){i!==this._spatialBlend&&(this._spatialBlend=i,this._needUpdateSpatialDistanceSettings=!0)}get minDistance(){return this._minDistance}set minDistance(i){this._minDistance!==i&&(this._minDistance=i,this._needUpdateSpatialDistanceSettings=!0)}get maxDistance(){return this._maxDistance}set maxDistance(i){this._maxDistance!==i&&(this._maxDistance=i,this._needUpdateSpatialDistanceSettings=!0)}get volume(){return this._volume}set volume(i){this._volume=i,this.sound&&!this.context.application.muted&&(xI&&console.log(this.name,"audio set volume",i),this.sound.setVolume(i))}get Sound(){var i;if(!this.sound&&pB.userInteractionRegistered){let A=gA.getComponent(this.context.mainCamera,uB)??gA.findObjectOfType(uB,this.context);!A&&this.context.mainCamera&&(A=gA.addNewComponent(this.context.mainCamera,uB)),A!=null&&A.listener?(this.sound=new o2(A.listener),(i=this.gameObject)==null||i.add(this.sound)):xI&&console.warn("No audio listener found in scene - can not play audio")}return this.sound}get ShouldPlay(){return this.shouldPlay}get audioContext(){var i;return(i=this.sound)==null?void 0:i.context}awake(){xI&&console.log(this),this.audioLoader=new k0,this.playOnAwake&&(this.shouldPlay=!0),this.preload&&typeof this.clip=="string"&&this.audioLoader.load(this.clip,this.createAudio,()=>{},console.error)}onEnable(){this.sound&&this.gameObject.add(this.sound),pB.userInteractionRegistered?this.playOnAwake&&this.context.application.isVisible&&this.play():pB.registerWaitForAllowAudio(()=>{this.enabled&&!this.destroyed&&this.shouldPlay&&this.onNewClip(this.clip)}),globalThis.addEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.addEventListener(VS.MuteChanged,this.onApplicationMuteChanged)}onDisable(){globalThis.removeEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.removeEventListener(VS.MuteChanged,this.onApplicationMuteChanged),this.pause()}applySpatialDistanceSettings(){const i=this.sound;if(!i)return;this._needUpdateSpatialDistanceSettings=!1;const A=ge.lerp(10*this._maxDistance/Math.max(1e-4,this.spatialBlend),this._minDistance,this.spatialBlend);switch(xI&&console.log(this.name,this._minDistance,this._maxDistance,this.spatialBlend,"Ref distance="+A),i.setRefDistance(A),i.setMaxDistance(Math.max(.01,this._maxDistance)),this.rollOffMode){case 0:i.setDistanceModel("exponential");break;case 1:i.setDistanceModel("linear");break;case 2:console.warn("Custom rolloff for AudioSource is not supported: "+this.name);break}this.spatialBlend>0?xI&&!this.helper&&(this.helper=new GEA(i,i.getRefDistance()),i.add(this.helper)):this.helper&&this.helper.parent&&this.helper.removeFromParent()}async onNewClip(i){if(i&&(this.clip=i),typeof i=="string")if(xI&&console.log(i),i.endsWith(".mp3")||i.endsWith(".wav")){if(this.audioLoader||(this.audioLoader=new k0),this.shouldPlay=!0,this._lastClipStartedLoading===i){xI&&console.log("Is currently loading:",this._lastClipStartedLoading,this);return}this._lastClipStartedLoading=i,xI&&console.log("load audio",i);const A=await this.audioLoader.loadAsync(i).catch(console.error);this._lastClipStartedLoading=null,A&&this.createAudio(A)}else console.warn("Unsupported audio clip type",i);else this.shouldPlay=!0,this.createAudio()}play(i=void 0){var A,e,g;!i&&this.clip&&(i=this.clip),i!==void 0&&typeof i!="string"&&!(i instanceof MediaStream)&&(se()&&console.warn("Called play on AudioSource with unknown argument type:",i+`
5733
5733
  Using the assigned clip instead:`,this.clip),i=this.clip);let I=!this.sound||i&&i!==this.clip;if(typeof i=="string"&&!this.audioLoader&&(I=!0),(i instanceof MediaStream||typeof i=="string")&&(this.clip=i),I){this.shouldPlay=!0,this.onNewClip(i);return}if(this.shouldPlay=!0,this._hasEnded=!1,xI&&console.log("play",(A=this.sound)==null?void 0:A.getVolume(),this.sound),this.sound&&!this.sound.isPlaying){const o=this.context.application.muted;o&&this.sound.setVolume(0),(e=this.gameObject)==null||e.add(this.sound),this.clip instanceof MediaStream?(this.sound.setMediaStreamSource(this.clip),this._audioElement||(this._audioElement=document.createElement("audio"),this._audioElement.style.display="none"),this._audioElement.parentNode||(g=this.context.domElement.shadowRoot)==null||g.append(this._audioElement),this._audioElement.srcObject=this.clip,this._audioElement.autoplay=!1):(this._audioElement&&this._audioElement.remove(),this.sound.play(o?.1:0))}}pause(){var i,A;xI&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.isPlaying&&this.sound.source&&(this._lastContextTime=(i=this.sound)==null?void 0:i.context.currentTime,this.sound.pause()),(A=this._audioElement)==null||A.remove()}stop(){var i,A;xI&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.source&&(this._lastContextTime=(i=this.sound)==null?void 0:i.context.currentTime,xI&&console.log(this._lastContextTime),this.sound.stop()),(A=this._audioElement)==null||A.remove()}get isPlaying(){var i;return((i=this.sound)==null?void 0:i.isPlaying)??!1}set isPlaying(i){}get time(){var i,A;return(i=this.sound)!=null&&i.source?((A=this.sound.source)==null?void 0:A.context.currentTime)-this._lastContextTime+this.sound.offset:0}set time(i){if(this.sound){if(i===this.sound.offset)return;const A=this.isPlaying;this.stop(),this.sound.offset=i,A&&this.play()}}update(){this.helper&&(this.isPlaying&&this.helper.update(),this.helper.visible=this.isPlaying),this._needUpdateSpatialDistanceSettings&&this.applySpatialDistanceSettings(),this.sound&&!this.sound.isPlaying&&this.shouldPlay&&!this._hasEnded&&(this._hasEnded=!0,xI&&console.log("Audio clip ended",this.clip),this.dispatchEvent(new CustomEvent("ended",{detail:this})))}};let bi=pB;ha([y(URL)],bi.prototype,"clip",2),ha([y()],bi.prototype,"playOnAwake",2),ha([y()],bi.prototype,"preload",2),ha([y()],bi.prototype,"loop",1),ha([y()],bi.prototype,"spatialBlend",1),ha([y()],bi.prototype,"minDistance",1),ha([y()],bi.prototype,"maxDistance",1),ha([y()],bi.prototype,"volume",1),ha([y()],bi.prototype,"rollOffMode",2),ha([y()],bi.prototype,"playInBackground",2);var NEA=Object.defineProperty,FEA=Object.getOwnPropertyDescriptor,Ff=(i,A,e,g)=>{for(var I=g>1?void 0:g?FEA(A,e):A,o=i.length-1,s;o>=0;o--)(s=i[o])&&(I=(g?s(A,e,I):s(I))||I);return g&&I&&NEA(A,e,I),I};const vEA=iA("debugsignals");class oD{constructor(){B(this,"guid")}}Ff([y()],oD.prototype,"guid",2);class dl{constructor(){B(this,"signal"),B(this,"reaction")}}Ff([y(oD)],dl.prototype,"signal",2),Ff([y(zi)],dl.prototype,"reaction",2);var Gb;const Jr=(Gb=class extends bA{constructor(){super(...arguments),B(this,"events")}static invoke(i){if(Jr.receivers[i]){const A=Jr.receivers[i];if(!A)return;for(const e of A)e.invoke(i)}}awake(){vEA&&console.log("SignalReceiver awake",this)}onEnable(){if(this.events)for(const i of this.events)Jr.receivers[i.signal.guid]||(Jr.receivers[i.signal.guid]=[]),Jr.receivers[i.signal.guid].push(this)}onDisable(){if(this.events){for(const i of this.events)if(Jr.receivers[i.signal.guid]){const A=Jr.receivers[i.signal.guid].indexOf(this);A>=0&&Jr.receivers[i.signal.guid].splice(A,1)}}}invoke(i){if(!this.events||!Array.isArray(this.events))return;const A=typeof i=="object"?i.guid:i;for(const e of this.events)if(e.signal.guid===A)try{if(e.reaction){if(!e.reaction.invoke){console.warn("Missing invoke - possibly a serialization error",e,this);continue}}else{console.warn("Missing reaction for signal",e,this);continue}e.reaction.invoke()}catch(g){console.error(g)}}},B(Gb,"receivers",{}),Gb);let ul=Jr;Ff([y(dl)],ul.prototype,"events",2);var zo=(i=>(i.Activation="ActivationTrack",i.Animation="AnimationTrack",i.Audio="AudioTrack",i.Control="ControlTrack",i.Marker="MarkerTrack",i.Signal="SignalTrack",i))(zo||{}),Ea=(i=>(i[i.None=0]="None",i[i.Hold=1]="Hold",i[i.Loop=2]="Loop",i[i.PingPong=3]="PingPong",i[i.Continue=4]="Continue",i))(Ea||{}),Rb=(i=>(i.Signal="SignalEmitter",i))(Rb||{});const ca=iA("debugtimeline");class sD{constructor(){B(this,"director"),B(this,"track")}get muted(){return this.track.muted}set muted(A){var e;A!==this.track.muted&&(this.track.muted=A,(e=this.onMuteChanged)==null||e.call(this))}*forEachClip(A=!1){var e;if((e=this.track)!=null&&e.clips)if(A)for(let g=this.track.clips.length-1;g>=0;g--)yield this.track.clips[g];else for(const g of this.track.clips)yield g}getClipTime(A,e){return e.clipIn+(A-e.start)*e.timeScale}getClipTimeNormalized(A,e){return(A-e.start)/e.duration}evaluateWeight(A,e,g,I=!0){if(e<0||e>=g.length)return 0;const o=g[e];if(I||A>=o.start&&A<=o.end){let s=1;const n=!1;if(o.easeInDuration>0){const a=Math.min((A-o.start)/o.easeInDuration,1);s*=a}if(o.easeOutDuration>0&&!n){const a=Math.min((o.end-A)/o.easeOutDuration,1);s*=a}return s}return 0}}class KEA{constructor(A){B(this,"clip"),B(this,"rootPositionOffset"),B(this,"rootQuaternionOffset"),B(this,"rootStartPosition"),B(this,"rootEndPosition"),B(this,"rootStartQuaternion"),B(this,"rootEndQuaternion");const e=A.getClip();this.clip=e;const g=A.getRoot(),I=g.name+".position",o=g.name+".quaternion";ca&&console.log(e.name,e.tracks,I);for(const s of e.tracks)if(!(s.times.length<=0)){if(s.name.endsWith(I))this.rootStartPosition=new S().fromArray(s.values,0),this.rootEndPosition=new S().fromArray(s.values,s.values.length-3),this.rootPositionOffset=this.rootEndPosition.clone().sub(this.rootStartPosition),ca&&console.log(this.rootPositionOffset);else if(s.name.endsWith(o)&&(this.rootStartQuaternion=new GA().fromArray(s.values,0),this.rootEndQuaternion=new GA().fromArray(s.values,s.values.length-4),this.rootQuaternionOffset=this.rootEndQuaternion.clone().multiply(this.rootStartQuaternion),ca)){const n=new It().setFromQuaternion(this.rootQuaternionOffset);console.log("ROT",n)}}}get hasOffsets(){return this.rootPositionOffset!==void 0||this.rootQuaternionOffset!==void 0}}class vf extends sD{constructor(){super(...arguments),B(this,"models",[]),B(this,"trackOffset"),B(this,"target"),B(this,"mixer"),B(this,"clips",[]),B(this,"actions",[]),B(this,"_actionOffsets",[]),B(this,"_didBind",!1),B(this,"_animator",null),B(this,"_useclipOffsets",!0),B(this,"_totalOffsetPosition",new S),B(this,"_totalOffsetRotation",new GA),B(this,"_totalOffsetPosition2",new S),B(this,"_totalOffsetRotation2",new GA),B(this,"_summedPos",new S),B(this,"_tempPos",new S),B(this,"_summedRot",new GA),B(this,"_tempRot",new GA),B(this,"_clipRotQuat",new GA)}onDisable(){var A;(A=this.mixer)==null||A.stopAllAction()}onDestroy(){this.director.context.animations.unregisterAnimationMixer(this.mixer)}onStateChanged(){this._animator&&Q8(this._animator.gameObject,this,this.director.isPlaying)}createHooks(A,e){var g,I;if(((g=e.tracks)==null?void 0:g.length)<=0){console.warn("No tracks in AnimationClip",e);return}const o=e.tracks[0].name.split("."),s=o[o.length-2],n=s+".position",a=s+".quaternion";let r=!1,C=!1;for(const Q of e.tracks)Q.name.endsWith(n)?(r=!0,this.createPositionInterpolant(e,A,Q)):Q.name.endsWith(a)&&(C=!0,this.createRotationInterpolant(e,A,Q));if(!r||!C){const Q=(I=this.mixer)==null?void 0:I.getRoot(),h=e.tracks[0],E=h.name.lastIndexOf("."),c=h.name.substring(0,E),l=c.substring(c.lastIndexOf(".")+1),d=Q.getObjectByName(l);if(d)if(r){if(!C){const u=e.tracks[0].name.substring(0,E)+".quaternion";ca&&console.warn("Create quaternion track",l,d);const D=d.quaternion,p=new Es(u,[0,e.duration],[D.x,D.y,D.z,D.w,D.x,D.y,D.z,D.w]);e.tracks.push(p),this.createRotationInterpolant(e,A,p)}}else{const u=c+".position";ca&&console.warn("Create position track",l,d);const D=d.position,p=new Wn(u,[0,e.duration],[D.x,D.y,D.z,D.x,D.y,D.z]);e.tracks.push(p),this.createPositionInterpolant(e,A,p)}}}bind(){if(!this._didBind){this._didBind=!0,ca&&console.log(this.models),this.mixer?this.target=this.mixer.getRoot():console.warn("No mixer was assigned to animation track");for(const A of this.actions){const e=new KEA(A);this._actionOffsets.push(e)}this.target&&(this._animator=gA.getComponent(this.target,II)??null,this._animator&&Q8(this._animator.gameObject,this,!0));for(const A of this.models){const e=A.asset,g=e.position,I=e.rotation;g&&g.x!==void 0&&(g.isVector3||(e.position=new S(g.x,g.y,g.z)),I.isQuaternion||(e.rotation=new GA(I.x,I.y,I.z,I.w)))}this.ensureTrackOffsets()}}ensureTrackOffsets(){if(this.trackOffset){const A=this.trackOffset.position;A&&(A.isVector3||(this.trackOffset.position=new S(A.x,A.y,A.z)));const e=this.trackOffset.rotation;e&&(e.isQuaternion||(this.trackOffset.rotation=new GA(e.x,e.y,e.z,e.w)))}}evaluate(A){var e,g,I,o,s,n,a;if(this.track.muted||!this.mixer)return;this.bind(),this._totalOffsetPosition.set(0,0,0),this._totalOffsetRotation.set(0,0,0,1),this._totalOffsetPosition2.set(0,0,0),this._totalOffsetRotation2.set(0,0,0,1);let r=0,C=0,Q=!1,h=!1,E=0;for(let c=0;c<this.clips.length;c++){const l=this.models[c],d=this.actions[c],u=l.asset;d.weight=0;const D=A>=l.start&&A<=l.end,p=l.preExtrapolationMode,w=l.postExtrapolationMode,f=c<this.clips.length-1?this.models[c+1]:null;let G=D,M=!1;if(!G&&!Q&&l.end<A&&w!==Ea.None?(!f||f.start>A)&&(G=!0,Q=!0):c==0&&!G&&!h&&l.start>A&&p!==Ea.None&&(!f||f.start<A)&&(G=!0,M=!0,h=!0),G){let U=1;U*=this.evaluateWeight(A,c,this.models,G),U*=this.director.weight;let v=D;if(M)switch(p){case Ea.Hold:break;case Ea.Loop:A+=l.start,v=!0;break;default:A+=l.start,v=!0;break}let k=this.getClipTime(A,l),N=0;const _=u.duration;if(M&&p===Ea.Hold&&(k=0),v){if(u.loop)for(N+=Math.floor(k/(_+1e-6));k>_;)k-=_}else if(!D&&Q)switch(w){case Ea.Hold:k=this.getClipTime(l.end,l);break;case Ea.Loop:k%=_;break;case Ea.PingPong:const J=Math.floor(k/_)%2!==0;k%=_,J&&(k=_-k);break}l.reversed===!0?d.time=d.getClip().duration-k:d.time=k,d.timeScale=0;const H=Math.max(0,U);if(d.weight=H,E+=H,d.clampWhenFinished=!1,d.isRunning()||d.play(),this._useclipOffsets){const J=r==0?this._totalOffsetPosition:this._totalOffsetPosition2,P=r==0?this._totalOffsetRotation:this._totalOffsetRotation2;r<1&&(C=1-U),r+=1;const b=this._summedPos.set(0,0,0),x=this._tempPos.set(0,0,0),Y=this._summedRot.identity(),X=this._tempRot.identity(),$=u.rotation;$&&(this._clipRotQuat.identity(),this._clipRotQuat.slerp($,U));const aA=this._actionOffsets[c];if(aA.hasOffsets)for(let kA=0;kA<N;kA++)aA.rootPositionOffset?x.copy(aA.rootPositionOffset):x.set(0,0,0),x.applyQuaternion(Y),this._clipRotQuat&&x.applyQuaternion(this._clipRotQuat),aA.rootQuaternionOffset&&(X.copy(aA.rootQuaternionOffset),Y.multiply(X)),b.add(x);this._clipRotQuat&&P.multiply(this._clipRotQuat),P.multiply(Y),u.position&&b.add(u.position),J.add(b)}}}if(this._useclipOffsets&&(this._totalOffsetPosition.lerp(this._totalOffsetPosition2,C),this._totalOffsetRotation.slerp(this._totalOffsetRotation2,C)),this.__mixerError===void 0&&(ca||se())&&(g=(e=this._animator)==null?void 0:e.runtimeAnimatorController)!=null&&g.mixer&&this.mixer!==((o=(I=this._animator)==null?void 0:I.runtimeAnimatorController)==null?void 0:o.mixer)&&(this.__mixerError=!0,console.error("AnimationTrack mixer is not shared with the animator controller - this might result in the timeline to not animate properly. Please report a bug to the Needle Engine team!",this)),(s=this._animator)!=null&&s.runtimeAnimatorController){const c=Math.max(0,1-E);(a=(n=this._animator)==null?void 0:n.runtimeAnimatorController)==null||a.update(c)}else this.mixer.update(A)}createRotationInterpolant(A,e,g){var I;const o=g.createInterpolant.bind(g),s=new GA;this.ensureTrackOffsets();const n=(I=this.trackOffset)==null?void 0:I.rotation;g.createInterpolant=()=>{const a=o(),r=a.evaluate.bind(a);return a.evaluate=C=>{var Q;const h=r(C);if(s.set(h[0],h[1],h[2],h[3]),s.premultiply(this._totalOffsetRotation),n&&s.premultiply(n),this.director.animationCallbackReceivers)for(const E of this.director.animationCallbackReceivers)(Q=E?.onTimelineRotation)==null||Q.call(E,this.director,this.target,C,s);return h[0]=s.x,h[1]=s.y,h[2]=s.z,h[3]=s.w,h},a}}createPositionInterpolant(A,e,g){var I,o;const s=g.createInterpolant.bind(g),n=new S;this.ensureTrackOffsets();const a=(I=this.trackOffset)==null?void 0:I.rotation,r=(o=this.trackOffset)==null?void 0:o.position;let C;g.createInterpolant=()=>{const Q=s(),h=Q.evaluate.bind(Q);return Q.evaluate=E=>{var c,l,d;const u=h(E);if(n.set(u[0],u[1],u[2]),e.removeStartOffset&&(C===void 0?(C=null,C=(l=(c=this._actionOffsets.find(D=>D.clip===A))==null?void 0:c.rootStartPosition)==null?void 0:l.clone()):C!=null&&C.isVector3&&n.sub(C)),n.applyQuaternion(this._totalOffsetRotation),n.add(this._totalOffsetPosition),a&&n.applyQuaternion(a),r&&(n.x-=r.x,n.y+=r.y,n.z+=r.z),this.director.animationCallbackReceivers)for(const D of this.director.animationCallbackReceivers)(d=D?.onTimelinePosition)==null||d.call(D,this.director,this.target,E,n);return u[0]=n.x,u[1]=n.y,u[2]=n.z,u},Q}}}const bEA=iA("mutetimeline"),nD=class extends sD{constructor(){super(...arguments),B(this,"models",[]),B(this,"listener"),B(this,"audio",[]),B(this,"audioContextTimeOffset",[]),B(this,"lastTime",0),B(this,"audioSource"),B(this,"_audioLoader",null),B(this,"_playableDirectorResumed",!1)}getAudioFilePath(i){const A=this.director.sourceId;return MC(A,i)}onAllowAudioChanged(i){for(let A=0;A<this.models.length;A++){const e=this.models[A];this.audio[A].setVolume(i?e.asset.volume:0)}}addModel(i){const A=new GU(this.listener);this.audio.push(A);const e=i;e._didTriggerPlay=!1,this.models.push(e)}onDisable(){for(const i of this.audio)i.isPlaying&&i.stop();for(const i of this.models)i._didTriggerPlay=!1}onDestroy(){for(const i of this.audio)i.source&&i?.disconnect();this.audio.length=0}onMuteChanged(){if(this.muted)for(let i=0;i<this.audio.length;i++){const A=this.audio[i];A!=null&&A.isPlaying&&A.stop()}}stop(){for(let i=0;i<this.audio.length;i++){const A=this.audio[i];A!=null&&A.isPlaying&&A.stop()}for(const i of this.models)i._didTriggerPlay=!1}onPauseChanged(){for(let i=0;i<this.audio.length;i++){const A=this.audio[i];A!=null&&A.isPlaying&&A.stop()}this._playableDirectorResumed=this.director.isPlaying}evaluate(i){if(bEA||this.track.muted||this.director.speed<0)return;const A=this.director.context.application.muted,e=this._playableDirectorResumed;this._playableDirectorResumed=!1;const g=A?.1:0;for(let I=0;I<this.models.length;I++){const o=this.models[I],s=this.audio[I],n=o.asset;if((!s||!s.buffer)&&this.isInTimeRange(o,i-1,i+1)&&this.handleAudioLoading(o,s),bi.userInteractionRegistered!==!1&&!(s===null||!s.buffer))if(s.playbackRate=this.director.context.time.timeScale*this.director.speed,s.loop=n.loop,i>=o.start&&i<=o.end&&i<this.director.duration){if(!s.isPlaying||!this.director.isPlaying)(e||!o._didTriggerPlay&&this.lastTime<i)&&(o.duration*o.timeScale>.3?s.offset=o.clipIn+(i-o.start)*o.timeScale:s.offset=0,ca&&console.log("Timeline Audio ("+this.track.name+") play with offset "+s.offset+" - "+o.asset.clip),s.play(g),o._didTriggerPlay=!0);else{const r=o.clipIn+(i-o.start)*o.timeScale,C=s.context.currentTime-s._startedAt+s.offset;Math.abs(r-C)>.3&&(s.offset=r,s.stop(),s.play(g))}let a=n.volume;if(this.track.volume!==void 0&&(a*=this.track.volume),A&&(a=0),o.easeInDuration>0){const r=Math.min((i-o.start)/o.easeInDuration,1);a*=r}if(o.easeOutDuration>0){const r=Math.min((o.end-i)/o.easeOutDuration,1);a*=r}s.setVolume(a*this.director.weight)}else o._didTriggerPlay=!1,this.director.isPlaying&&s.isPlaying&&s.stop()}this.lastTime=i}loadAudio(i,A=0,e=0){let g=null;const I=i-e,o=i+A;for(const s of this.models)if(this.isInTimeRange(s,I,o)){const n=this.audio[this.models.indexOf(s)],a=this.handleAudioLoading(s,n);a!==null&&(g===null&&(g=[]),g.push(a))}return g!==null?Promise.all(g):null}isInTimeRange(i,A,e){return A<=i.start&&e>=i.end||A>=i.start&&A<=i.end||e>=i.start&&e<=i.end}static dispose(){nD._audioBuffers.clear()}handleAudioLoading(i,A){this._audioLoader||(this._audioLoader=new k0);const e=this.getAudioFilePath(i.asset.clip);if(nD._audioBuffers.get(e)){const I=nD._audioBuffers.get(e);return I.then(o=>{o&&A.setBuffer(o)}),I}ca&&console.warn("LOAD audio track",e,this.director.sourceId);const g=new Promise((I,o)=>{this._audioLoader.load(e,s=>{A.setBuffer(s),I(s)},void 0,s=>{console.error("Error loading audio",s),I(null)})});return nD._audioBuffers.set(e,g),g}};let aD=nD;B(aD,"_audioBuffers",new Map);class rD extends sD{constructor(){super(...arguments),B(this,"models",[]),B(this,"didTrigger",[]),B(this,"receivers",[])}evaluate(A){var e;if(this.track.muted)return;const g=this.director.context.time.deltaTime*1.5;for(let I=0;I<this.models.length;I++){const o=this.models[I],s=this.didTrigger[I],n=o.time-A;let a=!1;if(o.retroActive)a=n<=1e-6;else{const r=Math.abs(n);(r===0||r>=1e-5&&r<g)&&(a=!0)}if(a){if(!s)if(ca&&console.log("Trigger signal",A,o.time,o),this.didTrigger[I]=!0,((e=this.receivers)==null?void 0:e.length)<=0)ul.invoke(o.asset);else for(const r of this.receivers)r&&r.invoke(o.asset)}else o.emitOnce||(this.didTrigger[I]=!1)}}}class Kf extends sD{constructor(){super(...arguments),B(this,"models",[]),B(this,"timelines",[]),B(this,"_previousActiveModel",null)}resolveSourceObjects(A){for(let e=this.models.length-1;e>=0;e--){const g=this.models[e].asset;if(!g.sourceObject||typeof g.sourceObject!="object"){console.log("no source object, removing model",e,g),this.models.splice(e,1);continue}else{const I=gA.getComponent(g.sourceObject,DB);this.timelines.push(I),I&&g.updateDirector&&(I.playOnAwake=!1)}}}evaluate(A){var e;this._previousActiveModel=null;for(let g=0;g<this.models.length;g++){const I=this.models[g],o=I.asset;if(A>=I.start&&A<=I.end){this._previousActiveModel=I;const s=this.getClipTime(A,I);if(o.controlActivation){const n=o.sourceObject;n.visible=!0}if(o.updateDirector){const n=this.timelines[g];n&&(n.isPlaying&&n.pause(),n.time=s,n.evaluate())}}else{const s=(e=this._previousActiveModel)==null?void 0:e.asset;if(o.controlActivation){const n=o.sourceObject;s?.sourceObject!==n&&(n.visible=!1)}}}}}var JEA=Object.defineProperty,xEA=Object.getOwnPropertyDescriptor,B8=(i,A,e,g)=>{for(var I=g>1?void 0:g?xEA(A,e):A,o=i.length-1,s;o>=0;o--)(s=i[o])&&(I=(g?s(A,e,I):s(I))||I);return g&&I&&JEA(A,e,I),I};const pl=iA("debugtimeline");var Ub;const Nb=(Ub=class extends bA{constructor(){super(...arguments),B(this,"playableAsset"),B(this,"playOnAwake"),B(this,"extrapolationMode",1),B(this,"waitForAudio",!0),B(this,"_visibilityChangeEvt"),B(this,"_clonedPlayableAsset",!1),B(this,"_speed",1),B(this,"_guidsMap"),B(this,"_isPlaying",!1),B(this,"_internalUpdateRoutine"),B(this,"_isPaused",!1),B(this,"_isStopping",!1),B(this,"_time",0),B(this,"_duration",0),B(this,"_weight",1),B(this,"_animationTracks",[]),B(this,"_audioTracks",[]),B(this,"_signalTracks",[]),B(this,"_controlTracks",[]),B(this,"_customTracks",[]),B(this,"_allTracks",[this._animationTracks,this._audioTracks,this._signalTracks,this._controlTracks,this._customTracks]),B(this,"animationCallbackReceivers",[])}static registerCreateTrack(i,A){this.createTrackFunctions[i]=A}get isPlaying(){return this._isPlaying}get isPaused(){return this._isPaused}get time(){return this._time}set time(i){typeof i=="number"&&!Number.isNaN(i)?this._time=i:(pl||zI())&&console.error("INVALID TIMELINE.TIME VALUE",i,this.name)}get duration(){return this._duration}set duration(i){this._duration=i}get weight(){return this._weight}set weight(i){this._weight=i}get speed(){return this._speed}set speed(i){this._speed=i}awake(){var i,A,e;pl&&console.log(this,(i=this.playableAsset)==null?void 0:i.tracks),this.rebuildGraph(),this.isValid()||console.warn("PlayableDirector is not valid",this.playableAsset,(A=this.playableAsset)==null?void 0:A.tracks,Array.isArray((e=this.playableAsset)==null?void 0:e.tracks),this)}onEnable(){var i,A,e;for(const g of this._audioTracks)(i=g.onEnable)==null||i.call(g);for(const g of this._customTracks)(A=g.onEnable)==null||A.call(g);for(const g of this._animationTracks)(e=g.onEnable)==null||e.call(g);this.playOnAwake&&this.play(),this._visibilityChangeEvt||(this._visibilityChangeEvt=()=>{switch(document.visibilityState){case"hidden":this.setAudioTracksAllowPlaying(!1);break;case"visible":this.setAudioTracksAllowPlaying(!0);break}}),window.addEventListener("visibilitychange",this._visibilityChangeEvt)}onDisable(){var i,A,e;this.stop();for(const g of this._audioTracks)(i=g.onDisable)==null||i.call(g);for(const g of this._customTracks)(A=g.onDisable)==null||A.call(g);for(const g of this._animationTracks)(e=g.onDisable)==null||e.call(g);this._visibilityChangeEvt&&window.removeEventListener("visibilitychange",this._visibilityChangeEvt)}onDestroy(){var i;for(const A of this._allTracks)for(const e of A)(i=e.onDestroy)==null||i.call(e)}rebuildGraph(){this.isValid()&&(this.resolveBindings(),this.updateTimelineDuration(),this.setupAndCreateTrackHandlers())}async play(){if(!this.isValid())return;const i=this._isPaused==!0;if(this._isPaused=!1,!this._isPlaying){if(this._isPlaying=!0,i&&this.invokePauseChangedMethodsOnTracks(),this.waitForAudio){const A=[];for(const e of this._audioTracks){const g=e.loadAudio(this._time,1,0);g&&A.push(g)}if(A.length>0&&(await Promise.all(A),!this._isPlaying))return;for(;this._audioTracks.length>0&&this._isPlaying&&!bi.userInteractionRegistered&&this.waitForAudio;)await Vn(200)}this.invokeStateChangedMethodsOnTracks(),this._internalUpdateRoutine=this.startCoroutine(this.internalUpdate(),Xt.LateUpdate)}}pause(){this.isValid()&&(this._isPlaying=!1,!this._isPaused&&(this._isPaused=!0,this.internalEvaluate(),this.invokePauseChangedMethodsOnTracks(),this.invokeStateChangedMethodsOnTracks()))}stop(){this._isStopping=!0;for(const e of this._audioTracks)e.stop();const i=this._isPaused==!0,A=this._isPlaying;this._isPlaying&&(this._time=0,this._isPlaying=!1,this._isPaused=!1,this.internalEvaluate(),i&&this.invokePauseChangedMethodsOnTracks()),this._isPlaying=!1,this._isPaused=!1,i&&!A&&this.invokePauseChangedMethodsOnTracks(),A&&this.invokeStateChangedMethodsOnTracks(),this._internalUpdateRoutine&&this.stopCoroutine(this._internalUpdateRoutine),this._internalUpdateRoutine=null,this._isStopping=!1}evaluate(){this.internalEvaluate(!0)}isValid(){return this.playableAsset&&this.playableAsset.tracks&&Array.isArray(this.playableAsset.tracks)}*forEachTrack(){for(const i of this._allTracks)for(const A of i)yield A}get audioTracks(){return this._audioTracks}resolveGuids(i){this._guidsMap=i}invokePauseChangedMethodsOnTracks(){var i;for(const A of this.forEachTrack())(i=A.onPauseChanged)==null||i.call(A)}invokeStateChangedMethodsOnTracks(){var i;for(const A of this.forEachTrack())(i=A.onStateChanged)==null||i.call(A,this._isPlaying)}*internalUpdate(){for(;this._isPlaying&&this.activeAndEnabled;)!this._isPaused&&this._isPlaying&&(this._time+=this.context.time.deltaTime*this.speed,this.internalEvaluate()),yield}internalEvaluate(i=!1){if(!this.isValid())return;let A=this._time;switch(this.extrapolationMode){case 0:this._speed>0?A=Math.min(A,this._duration):this._speed<0&&(A=Math.max(A,0)),this._time=A;break;case 1:A%=this._duration,this._time=A;break;case 2:if(A>this._duration){this.stop();return}break}const e=this._time;for(const g of this.playableAsset.tracks)if(!g.muted)switch(g.type){case zo.Activation:if(!i&&!this._isPlaying)continue;for(let I=0;I<g.outputs.length;I++){const o=g.outputs[I];if(typeof o=="object"){let s=!1;if(g.clips)for(const a of g.clips)a.start<=e&&e<=a.end&&(s=!0);const n=o;n.visible!==void 0&&n.visible!==s&&(n.visible=s,pl&&console.warn(this.name,"set ActivationTrack-"+I,n.name,s,e))}}break}if(!this._isStopping)for(const g of this._animationTracks)g.evaluate(e);for(const g of this._audioTracks)g.evaluate(e);for(const g of this._signalTracks)g.evaluate(e);for(const g of this._controlTracks)g.evaluate(e);for(const g of this._customTracks)g.evaluate(e)}resolveBindings(){if(this._clonedPlayableAsset||(this._clonedPlayableAsset=!0,this.playableAsset=uu(this.playableAsset)),!this.playableAsset||!this.playableAsset.tracks)return;const i=this.findRoot(this.gameObject);for(const A of this.playableAsset.tracks){for(let e=A.outputs.length-1;e>=0;e--){let g=A.outputs[e];if(typeof g=="string"){this._guidsMap&&this._guidsMap[g]&&(g=this._guidsMap[g]);const I=gA.findByGuid(g,i);I===null||typeof I!="object"?(A.outputs.splice(e,1),console.warn("Failed to resolve binding",g,A.name,A.type)):(pl&&console.log("Resolved binding",g,"to",I),A.outputs[e]=I)}else if(g===null){if(A.outputs.splice(e,1),Nb.createTrackFunctions[A.type])continue;A.type!==zo.Audio&&A.type!==zo.Control&&A.type!==zo.Marker&&A.type!==zo.Signal&&console.warn("Missing binding",g,A.name,A.type,this.name,this.playableAsset.name)}}if(A.type===zo.Control&&A.clips)for(let e=0;e<A.clips.length;e++){const g=A.clips[e];let I=g.asset.sourceObject;if(typeof I=="string"){this._guidsMap&&this._guidsMap[I]&&(I=this._guidsMap[I]);const o=gA.findByGuid(I,i);o===null||typeof o!="object"?console.warn("Failed to resolve sourceObject binding",I,A.name,g):(pl&&console.log("Resolved binding",I,"to",o),g.asset.sourceObject=o)}}}}findRoot(i){return i.parent?this.findRoot(i.parent):i}updateTimelineDuration(){if(this._duration=0,!(!this.playableAsset||!this.playableAsset.tracks)){for(const i of this.playableAsset.tracks)if(i.muted!==!0){if(i.clips)for(const A of i.clips)A.end>this._duration&&(this._duration=A.end);if(i.markers)for(const A of i.markers)A.time>this._duration&&(this._duration=A.time+.001)}}}setupAndCreateTrackHandlers(){var i,A,e;if(this._animationTracks.length=0,this._audioTracks.length=0,this._signalTracks.length=0,!this.playableAsset)return;let g=gA.findObjectOfType(uB,this.context);for(const I of this.playableAsset.tracks){const o=I.type,s=Nb.createTrackFunctions[o];if(s!=null){const n=s(this,I);if(typeof n.evaluate=="function"){n.director=this,n.track=I,this._customTracks.push(n);continue}}if(I.type===zo.Animation){if(!I.clips||I.clips.length<=0){pl&&console.warn("Animation track has no clips",I);continue}for(let n=I.outputs.length-1;n>=0;n--){let a=I.outputs[n];if(a instanceof wA){const C=gA.getOrAddComponent(a,II);C&&(a=C)}const r=(i=a?.gameObject)==null?void 0:i.animations;if(r){const C=new vf;C.trackOffset=I.trackOffset,C.director=this,C.track=I;for(let Q=0;Q<I.clips.length;Q++){const h=I.clips[Q],E=h.asset;if(!E){console.error(`Timeline ${this.name}: clip #${Q} on track "${I.name}" has no animation data`);continue}const c=E.clip;let l=c;if((typeof l=="string"||typeof l=="number")&&(l=r.find(u=>u.name===c)),!l){console.warn("Could not find animationClip for model",h,I.name,this.name,(A=this.playableAsset)==null?void 0:A.name);continue}a instanceof II&&a.runtimeAnimatorController&&(a.__internalDidAwakeAndStart||a.initializeRuntimeAnimatorController(),a.runtimeAnimatorController.mixer||a.runtimeAnimatorController.bind(a),C.mixer=a.runtimeAnimatorController.mixer),C.mixer||(C.mixer=new M0(a.gameObject),this.context.animations.registerAnimationMixer(C.mixer)),C.clips.push(l),C.mixer.uncacheAction(l),C.createHooks(h.asset,l);const d=C.mixer.clipAction(l);C.actions.push(d),C.models.push(h)}this._animationTracks.push(C)}}}else if(I.type===zo.Audio){if(!I.clips||I.clips.length<=0)continue;const n=new aD;n.director=this,n.track=I,n.audioSource=I.outputs.find(a=>a instanceof bi),this._audioTracks.push(n),g||(g=(e=this.context.mainCameraComponent)==null?void 0:e.gameObject.addNewComponent(uB)),n.listener=g.listener;for(let a=0;a<I.clips.length;a++){const r=I.clips[a];n.addModel(r)}}else if(I.type===zo.Marker){const n=new rD;if(n.director=this,n.track=I,I.markers)for(const a of I.markers)switch(a.type){case Rb.Signal:n.models.push(a),n.didTrigger.push(!1);break}if(n!==null&&n.models.length>0){const a=gA.getComponent(this.gameObject,ul);a&&(n.receivers.push(a),this._signalTracks.push(n))}}else if(I.type===zo.Signal){const n=new rD;if(n.director=this,n.track=I,I.markers)for(const a of I.markers)n.models.push(a),n.didTrigger.push(!1);for(const a of I.outputs)n.receivers.push(a);this._signalTracks.push(n)}else if(I.type===zo.Control){const n=new Kf;if(n.director=this,n.track=I,I.clips)for(const a of I.clips)n.models.push(a);n.resolveSourceObjects(this.context),this._controlTracks.push(n)}}}setAudioTracksAllowPlaying(i){for(const A of this._audioTracks)A.onAllowAudioChanged(i)}registerAnimationCallback(i){this.animationCallbackReceivers.push(i)}unregisterAnimationCallback(i){const A=this.animationCallbackReceivers.indexOf(i);A!==-1&&this.animationCallbackReceivers.splice(A,1)}},B(Ub,"createTrackFunctions",{}),Ub);let DB=Nb;B8([y()],DB.prototype,"playOnAwake",2),B8([y()],DB.prototype,"extrapolationMode",2);const bf=Symbol("objectIsAnimatedData");function Q8(i,A,e){if(!i)return;if(i[bf]===void 0){if(!e)return;i[bf]=new Set}const g=i[bf];e?g.add(A):g.has(A)&&g.delete(A)}function qEA(i){if(!i)return!1;const A=i[bf];return A!==void 0&&A.size>0}Qt.registerCallback(Mt.ContextCreated,i=>{const A=i.context.domElement.getAttribute("autoplay");if(A!==void 0&&(A===""||A==="true"||A==="1")&&i.files)for(const e of i.files)gA.foreachComponent(e.file.scene,g=>{if(g.enabled!==!1){if(g instanceof JI&&g.playAutomatically||g instanceof II||g instanceof DB&&g.playOnAwake===!0)return!0;if(g instanceof JI)return g.playAutomatically=!0,!0;if(g instanceof DB)return g.playOnAwake=!0,!0}},!0)!==!0&&tl.assignAnimationsFromFile(e.file,{createAnimationComponent:(g,I)=>Mn(g,JI)})});class LEA{constructor(){B(this,"_context")}get context(){return this._context??Ke.Current}get isStateMachineBehaviour(){return!0}}class CD{constructor(A,e,g,I){B(this,"name"),B(this,"nameHash"),B(this,"normalizedTime"),B(this,"length"),B(this,"speed"),B(this,"action"),B(this,"hasTransitions");var o;this.name=A.name,this.nameHash=A.hash,this.normalizedTime=e,this.length=g,this.speed=I,this.action=A.motion.action||null,this.hasTransitions=((o=A.transitions)==null?void 0:o.length)>0||!1}}function h8(i,A){return{name:"Empty",isLooping:!1,guid:A?.generateUUID()??ct.generateUUID(),index:-1,clip:new ZI(i,0,[])}}var wB=(i=>(i[i.If=1]="If",i[i.IfNot=2]="IfNot",i[i.Greater=3]="Greater",i[i.Less=4]="Less",i[i.Equals=6]="Equals",i[i.NotEqual=7]="NotEqual",i))(wB||{}),Fb=(i=>(i[i.Float=1]="Float",i[i.Int=3]="Int",i[i.Bool=4]="Bool",i[i.Trigger=9]="Trigger",i))(Fb||{});const xg=iA("debuganimatorcontroller"),Jf=iA("debugrootmotion");class rs{constructor(A){B(this,"_speed",1),B(this,"normalizedStartOffset",0),B(this,"animator"),B(this,"model"),B(this,"_mixer"),B(this,"_activeState"),B(this,"_activeStates",[]),B(this,"_heldActions",[]),B(this,"rootMotionHandler"),this.model=A,xg&&console.log(this)}static createFromClips(A,e={looping:!1,autoTransition:!0,transitionDuration:0}){const g=[];for(let o=0;o<A.length;o++){const s=A[o],n=[];if(e.autoTransition!==!1){const r=e.transitionDuration??0,C=r/s.duration;let Q=o;(e.autoTransition===void 0||e.autoTransition===!0)&&(Q=(o+1)%A.length),n.push({exitTime:1-C,offset:0,duration:r,hasExitTime:!0,destinationState:Q,conditions:[]})}const a={name:s.name,hash:o,motion:{name:s.name,clip:s,isLooping:e?.looping??!1},transitions:n,behaviours:[]};g.push(a)}const I={name:"AnimatorController",guid:new Pg(Date.now()).generateUUID(),parameters:[],layers:[{name:"Base Layer",stateMachine:{defaultState:0,states:g}}]};return new rs(I)}play(A,e=-1,g=Number.NEGATIVE_INFINITY,I=0){if(e<0)e=0;else if(e>=this.model.layers.length){console.warn("invalid layer");return}const o=this.model.layers[e].stateMachine;for(const s of o.states)if(s.name===A||s.hash===A){xg&&console.log("transition to ",s),this.transitionTo(s,I,g);return}console.warn("Could not find "+A+" to play")}reset(){this.setStartTransition()}setBool(A,e){var g,I;const o=typeof A=="string"?"name":"hash";return(I=(g=this.model)==null?void 0:g.parameters)==null?void 0:I.filter(s=>s[o]===A).forEach(s=>s.value=e)}getBool(A){var e,g,I;const o=typeof A=="string"?"name":"hash";return((I=(g=(e=this.model)==null?void 0:e.parameters)==null?void 0:g.find(s=>s[o]===A))==null?void 0:I.value)??!1}setFloat(A,e){var g,I;const o=typeof A=="string"?"name":"hash",s=(I=(g=this.model)==null?void 0:g.parameters)==null?void 0:I.filter(n=>n[o]===A);return s.forEach(n=>n.value=e),s?.length>0}getFloat(A){var e,g,I;const o=typeof A=="string"?"name":"hash";return((I=(g=(e=this.model)==null?void 0:e.parameters)==null?void 0:g.find(s=>s[o]===A))==null?void 0:I.value)??0}setInteger(A,e){var g,I;const o=typeof A=="string"?"name":"hash";return(I=(g=this.model)==null?void 0:g.parameters)==null?void 0:I.filter(s=>s[o]===A).forEach(s=>s.value=e)}getInteger(A){var e,g,I;const o=typeof A=="string"?"name":"hash";return((I=(g=(e=this.model)==null?void 0:e.parameters)==null?void 0:g.find(s=>s[o]===A))==null?void 0:I.value)??0}setTrigger(A){var e,g;xg&&console.log("SET TRIGGER",A);const I=typeof A=="string"?"name":"hash";return(g=(e=this.model)==null?void 0:e.parameters)==null?void 0:g.filter(o=>o[I]===A).forEach(o=>o.value=!0)}resetTrigger(A){var e,g;const I=typeof A=="string"?"name":"hash";return(g=(e=this.model)==null?void 0:e.parameters)==null?void 0:g.filter(o=>o[I]===A).forEach(o=>o.value=!1)}getTrigger(A){var e,g,I;const o=typeof A=="string"?"name":"hash";return((I=(g=(e=this.model)==null?void 0:e.parameters)==null?void 0:g.find(s=>s[o]===A))==null?void 0:I.value)??!1}isInTransition(){return this._activeStates.length>1}setSpeed(A){this._speed=A}FindState(A){return this.findState(A)}findState(A){if(!A)return null;if(Array.isArray(this.model.layers)){for(const e of this.model.layers)for(const g of e.stateMachine.states)if(g.name===A||g.hash==A)return g}return null}getCurrentStateInfo(){if(!this._activeState)return null;const A=this._activeState.motion.action;if(!A)return null;const e=this._activeState.motion.clip.duration,g=e<=0?0:Math.abs(A.time/e);return new CD(this._activeState,g,e,this._speed)}get currentAction(){return this._activeState&&this._activeState.motion.action||null}get context(){var A;return(A=this.animator)==null?void 0:A.context}get mixer(){return this._mixer}dispose(){var A;if(this._mixer.stopAllAction(),this.animator){this._mixer.uncacheRoot(this.animator.gameObject);for(const e of this._activeStates)e.motion.clip&&this.mixer.uncacheAction(e.motion.clip,this.animator.gameObject)}(A=this.context)==null||A.animations.unregisterAnimationMixer(this._mixer)}bind(A){var e,g;A?this.animator!==A&&(this._mixer&&(this._mixer.stopAllAction(),(e=this.context)==null||e.animations.unregisterAnimationMixer(this._mixer)),this.animator=A,this._mixer=new M0(this.animator.gameObject),(g=this.context)==null||g.animations.registerAnimationMixer(this._mixer),this.createActions(this.animator)):console.error("AnimatorController.bind: animator is null")}clone(){if(typeof this.model=="string")return console.warn("AnimatorController has not been resolved, can not create model from string",this.model),null;xg&&console.warn("AnimatorController clone()",this.model);const A=uu(this.model,(e,g,I)=>I==null?!0:!(I.type==="Object3D"||I.isObject3D===!0||VY(I)||I.tracks!==void 0||I instanceof rs));return console.assert(A!==this.model),new rs(A)}update(A){var e,g;if(!this.animator)return;this.evaluateTransitions(),this.updateActiveStates(A);const I=this.animator.context.time.deltaTime;this.animator.applyRootMotion&&((e=this.rootMotionHandler)==null||e.onBeforeUpdate(A)),this._mixer.update(I),this.animator.applyRootMotion&&((g=this.rootMotionHandler)==null||g.onAfterUpdate(A))}get activeState(){return this._activeState}updateActiveStates(A){for(let e=0;e<this._activeStates.length;e++){const g=this._activeStates[e],I=g.motion;if(!I.action)this._activeStates.splice(e,1),e--;else{const o=I.action;o.weight=A,o.getEffectiveWeight()<=0&&!o.isRunning()&&(xg&&console.debug("REMOVE",g.name,o.getEffectiveWeight(),o.isRunning(),o.isScheduled()),this._activeStates.splice(e,1),e--)}}}setStartTransition(){var A;this.model.layers.length>1&&(xg||se())&&console.warn("Multiple layers are not supported yet "+((A=this.animator)==null?void 0:A.name));for(const e of this.model.layers){const g=e.stateMachine;g.defaultState===void 0&&(xg&&console.warn("AnimatorController default state is undefined, will assign state 0 as default",e),g.defaultState=0);const I=g.states[g.defaultState];this.transitionTo(I,0,this.normalizedStartOffset);break}}evaluateTransitions(){var A;let e=!1;if(!this._activeState){if(this.setStartTransition(),!this._activeState)return;e=!0}const g=this._activeState,I=g.motion.action;for(const s of g.transitions){if(!s.hasExitTime&&s.conditions.length<=0)continue;let n=!0;for(const a of s.conditions)if(!this.evaluateCondition(a)){n=!1;break}if(n)if(I){const a=g.motion.clip.duration,r=a<=0?1:Math.abs(I.time/a);let C=s.exitTime;I.timeScale<0&&(C=1-C);let Q=!1;if(s.hasExitTime?I.timeScale>0?Q=r>=s.exitTime:I.timeScale<0&&(Q=1-r>=s.exitTime):Q=!0,Q){for(const h of s.conditions){const E=this.model.parameters.find(c=>c.name===h.parameter);E?.type===Fb.Trigger&&E.value&&(E.value=!1)}if(I.clampWhenFinished=!0,xg){const h=this.getState(s.destinationState,0);console.log(`Transition to ${s.destinationState} / ${h?.name}`,s,`
5734
5734
  Timescale: `+I.timeScale,`
5735
5735
  Normalized time: `+r.toFixed(3),`
@@ -6212,7 +6212,7 @@ Texture:`,g),this.setLightmapDebugMaterial()):ql&&console.log("Use debuglightmap
6212
6212
  }
6213
6213
  `};class fJ extends Ue{constructor(A){super({type:"LineMaterial",uniforms:LE.clone(Zg.line.uniforms),vertexShader:Zg.line.vertexShader,fragmentShader:Zg.line.fragmentShader,clipping:!0}),this.isLineMaterial=!0,this.setValues(A)}get color(){return this.uniforms.diffuse.value}set color(A){this.uniforms.diffuse.value=A}get worldUnits(){return"WORLD_UNITS"in this.defines}set worldUnits(A){A===!0?this.defines.WORLD_UNITS="":delete this.defines.WORLD_UNITS}get linewidth(){return this.uniforms.linewidth.value}set linewidth(A){this.uniforms.linewidth&&(this.uniforms.linewidth.value=A)}get dashed(){return"USE_DASH"in this.defines}set dashed(A){A===!0!==this.dashed&&(this.needsUpdate=!0),A===!0?this.defines.USE_DASH="":delete this.defines.USE_DASH}get dashScale(){return this.uniforms.dashScale.value}set dashScale(A){this.uniforms.dashScale.value=A}get dashSize(){return this.uniforms.dashSize.value}set dashSize(A){this.uniforms.dashSize.value=A}get dashOffset(){return this.uniforms.dashOffset.value}set dashOffset(A){this.uniforms.dashOffset.value=A}get gapSize(){return this.uniforms.gapSize.value}set gapSize(A){this.uniforms.gapSize.value=A}get opacity(){return this.uniforms.opacity.value}set opacity(A){this.uniforms&&(this.uniforms.opacity.value=A)}get resolution(){return this.uniforms.resolution.value}set resolution(A){this.uniforms.resolution.value.copy(A)}get alphaToCoverage(){return"USE_ALPHA_TO_COVERAGE"in this.defines}set alphaToCoverage(A){this.defines&&(A===!0!==this.alphaToCoverage&&(this.needsUpdate=!0),A===!0?(this.defines.USE_ALPHA_TO_COVERAGE="",this.extensions.derivatives=!0):(delete this.defines.USE_ALPHA_TO_COVERAGE,this.extensions.derivatives=!1))}}const CW=new S,BW=new S,QI=new VA,hI=new VA,Ua=new VA,kJ=new S,MJ=new DA,EI=new U0,QW=new S,ck=new kt,lk=new Ni,Na=new VA;let Fa,_h;function hW(i,A,e){return Na.set(0,0,-A,1).applyMatrix4(i.projectionMatrix),Na.multiplyScalar(1/Na.w),Na.x=_h/e.width,Na.y=_h/e.height,Na.applyMatrix4(i.projectionMatrixInverse),Na.multiplyScalar(1/Na.w),Math.abs(Math.max(Na.x,Na.y))}function NdA(i,A){const e=i.matrixWorld,g=i.geometry,I=g.attributes.instanceStart,o=g.attributes.instanceEnd,s=Math.min(g.instanceCount,I.count);for(let n=0,a=s;n<a;n++){EI.start.fromBufferAttribute(I,n),EI.end.fromBufferAttribute(o,n),EI.applyMatrix4(e);const r=new S,C=new S;Fa.distanceSqToSegment(EI.start,EI.end,C,r),C.distanceTo(r)<_h*.5&&A.push({point:C,pointOnLine:r,distance:Fa.origin.distanceTo(C),object:i,face:null,faceIndex:n,uv:null,uv1:null})}}function FdA(i,A,e){const g=A.projectionMatrix,I=i.material.resolution,o=i.matrixWorld,s=i.geometry,n=s.attributes.instanceStart,a=s.attributes.instanceEnd,r=Math.min(s.instanceCount,n.count),C=-A.near;Fa.at(1,Ua),Ua.w=1,Ua.applyMatrix4(A.matrixWorldInverse),Ua.applyMatrix4(g),Ua.multiplyScalar(1/Ua.w),Ua.x*=I.x/2,Ua.y*=I.y/2,Ua.z=0,kJ.copy(Ua),MJ.multiplyMatrices(A.matrixWorldInverse,o);for(let Q=0,h=r;Q<h;Q++){if(QI.fromBufferAttribute(n,Q),hI.fromBufferAttribute(a,Q),QI.w=1,hI.w=1,QI.applyMatrix4(MJ),hI.applyMatrix4(MJ),QI.z>C&&hI.z>C)continue;if(QI.z>C){const u=QI.z-hI.z,D=(QI.z-C)/u;QI.lerp(hI,D)}else if(hI.z>C){const u=hI.z-QI.z,D=(hI.z-C)/u;hI.lerp(QI,D)}QI.applyMatrix4(g),hI.applyMatrix4(g),QI.multiplyScalar(1/QI.w),hI.multiplyScalar(1/hI.w),QI.x*=I.x/2,QI.y*=I.y/2,hI.x*=I.x/2,hI.y*=I.y/2,EI.start.copy(QI),EI.start.z=0,EI.end.copy(hI),EI.end.z=0;const E=EI.closestPointToPointParameter(kJ,!0);EI.at(E,QW);const c=ct.lerp(QI.z,hI.z,E),l=c>=-1&&c<=1,d=kJ.distanceTo(QW)<_h*.5;if(l&&d){EI.start.fromBufferAttribute(n,Q),EI.end.fromBufferAttribute(a,Q),EI.start.applyMatrix4(o),EI.end.applyMatrix4(o);const u=new S,D=new S;Fa.distanceSqToSegment(EI.start,EI.end,D,u),e.push({point:D,pointOnLine:u,distance:Fa.origin.distanceTo(D),object:i,face:null,faceIndex:Q,uv:null,uv1:null})}}}class vdA extends dA{constructor(A=new rW,e=new fJ({color:Math.random()*16777215})){super(A,e),this.isLineSegments2=!0,this.type="LineSegments2"}computeLineDistances(){const A=this.geometry,e=A.attributes.instanceStart,g=A.attributes.instanceEnd,I=new Float32Array(2*e.count);for(let s=0,n=0,a=e.count;s<a;s++,n+=2)CW.fromBufferAttribute(e,s),BW.fromBufferAttribute(g,s),I[n]=n===0?0:I[n-1],I[n+1]=I[n]+CW.distanceTo(BW);const o=new G0(I,2,1);return A.setAttribute("instanceDistanceStart",new qo(o,1,0)),A.setAttribute("instanceDistanceEnd",new qo(o,1,1)),this}raycast(A,e){const g=this.material.worldUnits,I=A.camera;I===null&&!g&&console.error('LineSegments2: "Raycaster.camera" needs to be set in order to raycast against LineSegments2 while worldUnits is set to false.');const o=A.params.Line2!==void 0&&A.params.Line2.threshold||0;Fa=A.ray;const s=this.matrixWorld,n=this.geometry,a=this.material;_h=a.linewidth+o,n.boundingSphere===null&&n.computeBoundingSphere(),lk.copy(n.boundingSphere).applyMatrix4(s);let r;if(g)r=_h*.5;else{const Q=Math.max(I.near,lk.distanceToPoint(Fa.origin));r=hW(I,Q,a.resolution)}if(lk.radius+=r,Fa.intersectsSphere(lk)===!1)return;n.boundingBox===null&&n.computeBoundingBox(),ck.copy(n.boundingBox).applyMatrix4(s);let C;if(g)C=_h*.5;else{const Q=Math.max(I.near,ck.distanceToPoint(Fa.origin));C=hW(I,Q,a.resolution)}ck.expandByScalar(C),Fa.intersectsBox(ck)!==!1&&(g?NdA(this,e):FdA(this,I,e))}}class EW extends rW{constructor(){super(),this.isLineGeometry=!0,this.type="LineGeometry"}setPositions(A){const e=A.length-3,g=new Float32Array(2*e);for(let I=0;I<e;I+=3)g[2*I]=A[I],g[2*I+1]=A[I+1],g[2*I+2]=A[I+2],g[2*I+3]=A[I+3],g[2*I+4]=A[I+4],g[2*I+5]=A[I+5];return super.setPositions(g),this}setColors(A){const e=A.length-3,g=new Float32Array(2*e);for(let I=0;I<e;I+=3)g[2*I]=A[I],g[2*I+1]=A[I+1],g[2*I+2]=A[I+2],g[2*I+3]=A[I+3],g[2*I+4]=A[I+4],g[2*I+5]=A[I+5];return super.setColors(g),this}fromLine(A){const e=A.geometry;return this.setPositions(e.attributes.position.array),this}}class KdA extends vdA{constructor(A=new EW,e=new fJ({color:Math.random()*16777215})){super(A,e),this.isLine2=!0,this.type="Line2"}}class dk extends bA{}var bdA=Object.defineProperty,JdA=Object.getOwnPropertyDescriptor,Th=(i,A,e,g)=>{for(var I=g>1?void 0:g?JdA(A,e):A,o=i.length-1,s;o>=0;o--)(s=i[o])&&(I=(g?s(A,e,I):s(I))||I);return g&&I&&bdA(A,e,I),I};const cW=iA("debugwebxr");class Hs extends bA{constructor(){super(...arguments),B(this,"movementSpeed",1.5),B(this,"rotationStep",30),B(this,"useTeleport",!0),B(this,"useTeleportTarget",!1),B(this,"useTeleportFade",!1),B(this,"showRays",!0),B(this,"showHits",!1),B(this,"isXRMovementHandler",!0),B(this,"xrSessionMode","immersive-vr"),B(this,"_didApplyRotation",!1),B(this,"_didTeleport",!1),B(this,"_plane",null),B(this,"_lines",[]),B(this,"_hitDiscs",[]),B(this,"_hitDistances",[]),B(this,"hitPointRaycastFilter",A=>A.type==="SkinnedMesh"?"continue in children":!0)}onUpdateXR(A){const e=A.xr.rig;if(!(e!=null&&e.gameObject)||A.xr.isPassThrough)return;const g=A.xr.leftController,I=A.xr.rightController;g&&this.onHandleMovement(g,e.gameObject),I&&(this.onHandleRotation(I,e.gameObject),this.useTeleport&&this.onHandleTeleport(I,e.gameObject))}onLeaveXR(A){for(const e of this._lines)e.removeFromParent();for(const e of this._hitDiscs)e?.removeFromParent()}onBeforeRender(){var A;(A=this.context.xr)!=null&&A.running&&(this.showRays&&this.renderRays(this.context.xr),this.showHits&&this.renderHits(this.context.xr))}onHandleMovement(A,e){const g=A.getStick("xr-standard-thumbstick"),I=new S(g.x,0,g.y);I.multiplyScalar(this.context.time.deltaTimeUnscaled*this.movementSpeed);const o=zt(e);I.multiplyScalar(o.x),I.applyQuaternion(A.xr.poseOrientation),I.y=0,I.applyQuaternion(e.worldQuaternion),e.position.add(I),e.updateMatrixWorld()}onHandleRotation(A,e){const g=A.getStick("xr-standard-thumbstick").x;if(this._didApplyRotation)Math.abs(g)<.3&&(this._didApplyRotation=!1);else if(Math.abs(g)>.5){this._didApplyRotation=!0;const I=g>0?1:-1;e.rotateY(I*ge.toRadians(this.rotationStep))}}onHandleTeleport(A,e){var g;const I=A.getStick("xr-standard-thumbstick");if(this._didTeleport)I.y<.2&&(this._didTeleport=!1);else if(I.y>.8){this._didTeleport=!0;const o=this.context.physics.raycastFromRay(A.ray)[0];let s=o?.point;if(!s){this._plane||(this._plane=new SI(new S(0,1,0),0));const n=e.worldPosition;this._plane.setFromNormalAndCoplanarPoint(new S(0,1,0),n);const a=A.ray;s=n.clone(),this._plane.intersectLine(new U0(a.origin,lt(a.direction).multiplyScalar(1e4).add(a.origin)),s),s.distanceTo(n)>e.scale.x*10&&(s=null)}if(s){if(this.useTeleportTarget&&!gA.getComponentInParent(o.object,dk))return;cW&&pe.DrawSphere(s,.025,16711680,5);const n=s.clone();this.useTeleportFade?(g=A.xr.fadeTransition())==null||g.then(()=>{e.worldPosition=n}):e.worldPosition=n}}}renderRays(A){for(let e=0;e<this._lines.length;e++){const g=this._lines[e];g&&(g.visible=!1)}for(let e=0;e<A.controllers.length;e++){const g=A.controllers[e];let I=this._lines[e];if(!g.connected||!g.isTracking||!g.ray||g.targetRayMode==="transient-pointer"||!g.hasSelectEvent){I&&(I.visible=!1);continue}I||(I=this.createRayLineObject(),I.scale.z=.5,this._lines[e]=I),g.updateRayWorldPosition(),g.updateRayWorldQuaternion();const o=g.rayWorldPosition,s=g.rayWorldQuaternion;I.position.copy(o),I.quaternion.copy(s);const n=A.rigScale,a=this._hitDistances[e]??n;I.scale.set(n,n,a),I.visible=!0,I.layers.disableAll(),I.layers.enable(2),I.parent!==this.context.scene&&this.context.scene.add(I)}}renderHits(A){for(const e of this._hitDiscs){if(!e)continue;const g=e.controller;if(!g||!g.connected||!g.isTracking){e.visible=!1;continue}}for(let e=0;e<A.controllers.length;e++){const g=A.controllers[e];if(!g.connected||!g.isTracking||!g.ray||!g.hasSelectEvent)continue;const I=this.context.time.smoothedFps>=59?1:10;if((this.context.time.frame+g.index)%I!==0){const n=this._hitDiscs[e];n&&n.hit&&(n.visible=!0,this.hitPointerSetPosition(g,n,n.hit.distance));continue}const o=this.context.physics.raycastFromRay(g.ray,{testObject:this.hitPointRaycastFilter})[0];this._hitDistances[e]=o?.distance;let s=this._hitDiscs[e];if(s&&(s.controller=g,s.hit=o),o){const n=A.rigScale??1;cW&&(pe.DrawWireSphere(o.point,.025*n,16711680),pe.DrawLabel(lt(0,.2,0).add(o.point),o.object.name,.02,0)),s||(s=this.createHitPointObject(),this._hitDiscs[e]=s),s.visible=!0;const a=.01*(n+o.distance);if(s.scale.set(a,a,a),s.layers.disableAll(),s.layers.enable(2),s.hit=o,o.normal){this.hitPointerSetPosition(g,s,o.distance);const r=o.normal.applyQuaternion(Nt(o.object));s.quaternion.setFromUnitVectors(xdA,r)}else this.hitPointerSetPosition(g,s,o.distance);s.parent!==this.context.scene&&this.context.scene.add(s)}else this._hitDiscs[e]&&(this._hitDiscs[e].visible=!1)}}hitPointerSetPosition(A,e,g){e.position.copy(A.rayWorldPosition),e.position.add(lt(0,0,g-.01).applyQuaternion(A.rayWorldQuaternion))}createHitPointObject(){var A=new wA;const e=new dA(new Vs(.3,6,6),new tt({color:15658734,opacity:.7,transparent:!0,depthTest:!1,side:yt}));return e.layers.disableAll(),e.layers.enable(2),A.add(e),A}createRayLineObject(){const A=new KdA;A.layers.disableAll(),A.layers.enable(2);const e=new EW;A.geometry=e;const g=new Float32Array(9);g.set([0,0,.02,0,0,.4,0,0,1]),e.setPositions(g);const I=new Float32Array(9);I.set([1,1,1,.1,.1,.1,0,0,0]),e.setColors(I);const o=new fJ({color:16777215,vertexColors:!0,worldUnits:!0,linewidth:.004,transparent:!0,blending:iQ,dashed:!1,alphaToCoverage:!0});return A.material=o,A}}Th([y()],Hs.prototype,"movementSpeed",2),Th([y()],Hs.prototype,"rotationStep",2),Th([y()],Hs.prototype,"useTeleport",2),Th([y()],Hs.prototype,"useTeleportTarget",2),Th([y()],Hs.prototype,"useTeleportFade",2),Th([y()],Hs.prototype,"showRays",2),Th([y()],Hs.prototype,"showHits",2);const xdA=new S(0,1,0);var qdA=Object.defineProperty,LdA=Object.getOwnPropertyDescriptor,No=(i,A,e,g)=>{for(var I=g>1?void 0:g?LdA(A,e):A,o=i.length-1,s;o>=0;o--)(s=i[o])&&(I=(g?s(A,e,I):s(I))||I);return g&&I&&qdA(A,e,I),I};const YD=iA("debugwebxr"),_dA=iA("debugusdz");class _g extends bA{constructor(){super(...arguments),B(this,"createVRButton",!0),B(this,"createARButton",!0),B(this,"createSendToQuestButton",!0),B(this,"createQRCode",!0),B(this,"useDefaultControls",!0),B(this,"showControllerModels",!0),B(this,"showHandModels",!0),B(this,"usePlacementReticle",!0),B(this,"usePlacementAdjustment",!0),B(this,"arSceneScale",1),B(this,"useXRAnchor",!1),B(this,"useQuicklookExport",!1),B(this,"useDepthSensing",!1),B(this,"defaultAvatar"),B(this,"_playerSync"),B(this,"_createdComponentsInSession",[]),B(this,"_usdzExporter"),B(this,"_previousXRState",0),B(this,"onAvatarSpawned",A=>{YD&&console.log("WebXR.onAvatarSpawned",A),gA.getComponentInChildren(A,SB)??(t=gA.addComponent(A,SB))}),B(this,"_buttonFactory"),B(this,"_buttons",[])}awake(){me.getXRSync(this.context)}onEnable(){var A,e;window.location.protocol!=="https:"&&Lt('<a href="https://developer.mozilla.org/en-US/docs/Web/API/WebXR_Device_API" target="_blank">WebXR</a> only works on secure connections (https).'),this.useQuicklookExport&&(gA.findObjectOfType(qi)||(YD&&console.log("WebXR: Adding USDZExporter"),this._usdzExporter=gA.addComponent(this.gameObject,qi),this._usdzExporter.objectToExport=this.context.scene,this._usdzExporter.autoExportAnimations=!0,this._usdzExporter.autoExportAudioSources=!0)),this.handleCreatingHTML(),this.handleOfferSession(),this.defaultAvatar||(YD&&console.warn("WebXR: No default avatar set, using static default avatar"),this.defaultAvatar=new gt("https://cdn.needle.tools/static/avatars/DefaultAvatar.glb")),this.defaultAvatar&&(this._playerSync=this.gameObject.getOrAddComponent(Dl),this._playerSync.autoSync=!1),this._playerSync&&(this._playerSync.asset=this.defaultAvatar,(A=this._playerSync.onPlayerSpawned)==null||A.removeEventListener(this.onAvatarSpawned),(e=this._playerSync.onPlayerSpawned)==null||e.addEventListener(this.onAvatarSpawned))}onDisable(){var A;(A=this._usdzExporter)==null||A.destroy(),this.removeButtons()}async handleOfferSession(){return this.createVRButton&&await me.isVRSupported()&&this.createVRButton?me.offerSession("immersive-vr","default",this.context):this.createARButton&&await me.isARSupported()&&this.createARButton?me.offerSession("immersive-ar","default",this.context):!1}get session(){return me.active??null}get sessionMode(){return me.activeMode??null}async enterVR(A){return me.start("immersive-vr",A,this.context)}async enterAR(A){return me.start("immersive-ar",A,this.context)}exitXR(){me.stop()}onBeforeXR(A,e){A=="immersive-ar"&&this.useDepthSensing&&(e.optionalFeatures=e.optionalFeatures||[],e.optionalFeatures.push("depth-sensing"))}async onEnterXR(A){YD&&console.log("WebXR onEnterXR"),this._previousXRState=ao.Global.Mask;const e=A.xr.isVR;if(ao.Global.Set(e?ua.VR:ua.AR),this.usePlacementReticle&&A.xr.isAR){let I=gA.findObjectOfType(Co);if(I)YD&&console.log("WebXR: WebARSessionRoot already exists, not creating a new one");else{const o=new wA;for(const s of this.context.scene.children)o.add(s);this.context.scene.add(o),I=gA.addComponent(o,Co),this._createdComponentsInSession.push(I),I.arScale=this.arSceneScale,I.arTouchTransform=this.usePlacementAdjustment,I.useXRAnchor=this.useXRAnchor}}this.useDefaultControls&&this.setDefaultMovementEnabled(!0),(this.showControllerModels||this.showHandModels)&&this.setDefaultControllerRenderingEnabled(!0);let g=gA.findObjectOfType(iD);g||(g=this.gameObject.addNewComponent(iD)),this.createLocalAvatar(A.xr)}onLeaveXR(A){var e;ao.Global.Set(this._previousXRState),(e=this._playerSync)==null||e.destroyInstance();for(const g of this._createdComponentsInSession)g.destroy();this._createdComponentsInSession.length=0,this.handleOfferSession()}setDefaultMovementEnabled(A){let e=this.gameObject.getComponent(Hs);return!e&&A&&(e=this.gameObject.addComponent(Hs),this._createdComponentsInSession.push(e)),e&&(e.enabled=A),e}setDefaultControllerRenderingEnabled(A){let e=this.gameObject.getComponent(Ra);return!e&&A&&(e=this.gameObject.addComponent(Ra),this._createdComponentsInSession.push(e),e.createControllerModel=this.showControllerModels,e.createHandModel==this.showHandModels),e&&(e.enabled=A),e}async createLocalAvatar(A){this._playerSync&&A.running&&(this._playerSync.asset=this.defaultAvatar,await this._playerSync.getInstance())}getButtonsContainer(){return this.getButtonsFactory()}getButtonsFactory(){return this._buttonFactory||(this._buttonFactory=Lh.getOrCreate()),this._buttonFactory}handleCreatingHTML(){if(this.createARButton||this.createVRButton||this.useQuicklookExport){if((xQ()&&oc()||_dA)&&this.useQuicklookExport){const A=gA.findObjectOfType(qi);if(!A||A&&A.allowCreateQuicklookButton){const e=this.getButtonsFactory().createQuicklookButton();this.addButton(e,50)}}if(this.createARButton){const A=this.getButtonsFactory().createARButton();this.addButton(A,50)}if(this.createVRButton){const A=this.getButtonsFactory().createVRButton();this.addButton(A,50)}}if(this.createSendToQuestButton&&!T0()&&me.isVRSupported().then(A=>{if(!A){const e=this.getButtonsFactory().createSendToQuestButton();this.addButton(e,50)}}),this.createQRCode&&!ls()){const A=pf(Ma);A&&A.createQRCodeButton===!1?se()&&console.warn("WebXR: QRCode button is disabled in the Needle Menu component"):me.isXRSupported().then(e=>{if(bQ()||!e){const g=Fr.getOrCreate().createQRCode();this.addButton(g,50)}})}}addButton(A,e){this._buttons.push(A),A.setAttribute("priority",e.toString()),this.context.menu.appendChild(A)}removeButtons(){for(const A of this._buttons)A.remove();this._buttons.length=0}}No([y()],_g.prototype,"createVRButton",2),No([y()],_g.prototype,"createARButton",2),No([y()],_g.prototype,"createSendToQuestButton",2),No([y()],_g.prototype,"createQRCode",2),No([y()],_g.prototype,"useDefaultControls",2),No([y()],_g.prototype,"showControllerModels",2),No([y()],_g.prototype,"showHandModels",2),No([y()],_g.prototype,"usePlacementReticle",2),No([y()],_g.prototype,"usePlacementAdjustment",2),No([y()],_g.prototype,"arSceneScale",2),No([y()],_g.prototype,"useXRAnchor",2),No([y()],_g.prototype,"useQuicklookExport",2),No([y()],_g.prototype,"useDepthSensing",2),No([y(gt)],_g.prototype,"defaultAvatar",2);class uk{get extensionName(){return"Physics"}onExportObject(A,e,g){const I=gA.getComponents(A,_t).filter(a=>a.enabled),o=gA.getComponents(A,$o).filter(a=>a.enabled&&!a.isTrigger);let s=I.length>0?I[0]:null;const n=o.length>0?o[0]:null;n&&!s&&(s=new _t,s.isKinematic=!0),s&&e.addEventListener("serialize",(a,r)=>{var C,Q,h;if(s){if(a.appendLine(),a.beginBlock('def RealityKitComponent "RigidBody"',"{",!0),s.useGravity||a.appendLine("bool gravityEnabled = 0"),a.appendLine('uniform token info:id = "RealityKit.RigidBody"'),s.isKinematic&&a.appendLine('token motionType = "Kinematic"'),a.beginBlock('def RealityKitStruct "massFrame"',"{",!0),a.appendLine(`float m_mass = ${s.mass}`),a.beginBlock('def RealityKitStruct "m_pose"',"{",!0),a.appendLine(`float3 position = (${s.centerOfMass.x}, ${s.centerOfMass.y}, ${s.centerOfMass.z})`),a.closeBlock("}"),a.closeBlock("}"),o.length>0){const E=o[0];a.beginBlock('def RealityKitStruct "material"',"{",!0);const c=E.sharedMaterial;c&&c.dynamicFriction!==void 0&&a.appendLine(`double dynamicFriction = ${(C=E.sharedMaterial)==null?void 0:C.dynamicFriction}`),c&&c.bounciness!==void 0&&a.appendLine(`double restitution = ${(Q=E.sharedMaterial)==null?void 0:Q.bounciness}`),c&&c.staticFriction!==void 0&&a.appendLine(`double staticFriction = ${(h=E.sharedMaterial)==null?void 0:h.staticFriction}`),a.closeBlock("}")}a.closeBlock("}")}}),n&&(e.addEventListener("serialize",(a,r)=>{var C;a.beginBlock('def RealityKitComponent "Collider"',"{",!0),a.appendLine("uint group = 1"),a.appendLine('uniform token info:id = "RealityKit.Collider"'),a.appendLine("uint mask = 4294967295");const Q=n.isTrigger?"Trigger":"Default";if(a.appendLine(`token type = "${Q}"`),a.beginBlock('def RealityKitStruct "Shape"',"{",!0),n instanceof fl){const h=n;a.appendLine('token shapeType = "Sphere"'),a.appendLine(`float radius = ${h.radius}`)}else if(n instanceof kl){const h=n;a.appendLine('token shapeType = "Box"'),a.appendLine(`float3 extent = (${h.size.x}, ${h.size.y}, ${h.size.z})`)}else if(n instanceof Lr){const h=n;a.appendLine('token shapeType = "Capsule"'),a.appendLine(`float radius = ${h.radius}`),a.appendLine(`float height = ${h.height}`)}else if(n instanceof Rh&&(C=n.sharedMesh)!=null&&C.geometry){const h=n.sharedMesh.geometry;h.boundingBox||h.computeBoundingBox();const E=n.sharedMesh.geometry.boundingBox;E&&(a.appendLine('token shapeType = "Box"'),a.appendLine(`float3 extent = (${E.max.x-E.min.x}, ${E.max.y-E.min.y}, ${E.max.z-E.min.z})`),console.log("[USDZ] Only Box, Sphere, and Capsule colliders are supported in visionOS/iOS. MeshCollider will be exported as Box",n))}else console.warn("[USDZ] Only Box, Sphere, and Capsule colliders are supported in visionOS/iOS. Ignoring collider:",n);a.beginBlock('def RealityKitStruct "pose"',"{",!0),a.closeBlock("}"),a.closeBlock("}"),a.closeBlock("}")}),o.length>1&&console.log("WARNING: Multiple colliders detected. visionOS / iOS can only support objects with a single collider, only exporting the first collider: ",n))}}var TdA=Object.defineProperty,YdA=Object.getOwnPropertyDescriptor,Zr=(i,A,e,g)=>{for(var I=g>1?void 0:g?YdA(A,e):A,o=i.length-1,s;o>=0;o--)(s=i[o])&&(I=(g?s(A,e,I):s(I))||I);return g&&I&&TdA(A,e,I),I};const Yh=iA("debugtext");var yg=(i=>(i[i.UpperLeft=0]="UpperLeft",i[i.UpperCenter=1]="UpperCenter",i[i.UpperRight=2]="UpperRight",i[i.MiddleLeft=3]="MiddleLeft",i[i.MiddleCenter=4]="MiddleCenter",i[i.MiddleRight=5]="MiddleRight",i[i.LowerLeft=6]="LowerLeft",i[i.LowerCenter=7]="LowerCenter",i[i.LowerRight=8]="LowerRight",i))(yg||{}),lW=(i=>(i[i.Normal=0]="Normal",i[i.Bold=1]="Bold",i[i.Italic=2]="Italic",i[i.BoldAndItalic=3]="BoldAndItalic",i))(lW||{});class _I extends Nh{constructor(){super(...arguments),B(this,"alignment",0),B(this,"verticalOverflow",0),B(this,"horizontalOverflow",0),B(this,"lineSpacing",1),B(this,"supportRichText",!1),B(this,"font"),B(this,"fontStyle",0),B(this,"sRGBTextColor",new fA(1,0,1)),B(this,"_text",""),B(this,"_fontSize",12),B(this,"_textMeshUi",null),B(this,"_didHandleTextRenderOnTop",!1)}setAlphaFactor(A){var e;super.setAlphaFactor(A),(e=this.uiObject)==null||e.set({fontOpacity:this.color.alpha*this.alphaFactor}),this.markDirty()}get text(){return this._text}set text(A){A!==this._text&&(this._text=A,this.feedText(this.text,this.supportRichText),this.markDirty())}set_text(A){this.text=A}get fontSize(){return this._fontSize}set fontSize(A){var e;this._fontSize=A,(e=this.uiObject)==null||e.set({fontSize:A})}onColorChanged(){var A;this.sRGBTextColor.copy(this.color),this.sRGBTextColor.convertLinearToSRGB(),(A=this.uiObject)==null||A.set({color:this.sRGBTextColor,fontOpacity:this.color.alpha})}onParentRectTransformChanged(){super.onParentRectTransformChanged(),this.uiObject&&this.updateOverflow()}onBeforeCanvasRender(A){this.updateOverflow()}updateOverflow(){var A;const e=(A=this.uiObject)==null?void 0:A._overflow;e&&(e._needsUpdate=!0,this.markDirty())}onCreate(A){Yh&&console.log(this),this.horizontalOverflow==1&&(A.whiteSpace="pre"),this.verticalOverflow==0&&(this.context.renderer.localClippingEnabled=!0,A.overflow="hidden"),this.horizontalOverflow==1&&this.verticalOverflow==0,A.lineHeight=this.lineSpacing,delete A.backgroundOpacity,delete A.backgroundColor,Yh&&(A.backgroundColor=16750848,A.backgroundOpacity=.5);const e=this.rectTransform;A={...A,...this.getTextOpts()},this.getAlignment(A),Yh&&(A.backgroundColor=Math.random()*16777215,A.backgroundOpacity=.1),this.uiObject=e.createNewText(A),this.feedText(this.text,this.supportRichText)}onAfterAddedToScene(){super.onAfterAddedToScene(),this.handleTextRenderOnTop()}getTextOpts(){const A=this.fontSize,e={color:this.color,fontOpacity:this.color.alpha,fontSize:A,fontKerning:"normal"};return this.setFont(e,this.fontStyle),e}onEnable(){var A;super.onEnable(),this._didHandleTextRenderOnTop=!1,this.uiObject&&this.uiObject.addAfterUpdate(()=>{this.setShadowComponentOwner(this.uiObject),this.markDirty()}),setTimeout(()=>this.markDirty(),10),(A=this.canvas)==null||A.registerEventReceiver(this)}onDisable(){var A;super.onDisable(),(A=this.canvas)==null||A.unregisterEventReceiver(this)}getAlignment(A){switch(A.flexDirection="column",this.alignment){case 0:case 3:case 6:A.textAlign="left";break;case 1:case 4:case 7:A.textAlign="center";break;case 2:case 5:case 8:A.textAlign="right";break}switch(this.alignment){default:case 0:case 1:case 2:A.alignItems="start";break;case 3:case 4:case 5:A.alignItems="center";break;case 6:case 7:case 8:A.alignItems="end";break}return A}feedText(A,e){var g,I,o;if(Yh&&console.log("feedText",this.uiObject,A,e),!!this.uiObject)if(this._textMeshUi||(this._textMeshUi=[]),this.uiObject.children.length=0,!e||A.length===0)this.uiObject.textContent=A;else{let s=this.getNextTag(A);if(s){if(s.startIndex>0){for(let r=this.uiObject.children.length-1;r>=0;r--){const C=this.uiObject.children[r];C.isUI&&(this.uiObject.remove(C),C.clear())}const a=new tm({textContent:A.substring(0,s.startIndex),color:"inherit"});this.uiObject.add(a)}}else{this.uiObject.textContent="",this.setOptions({textContent:A});return}const n=[];for(;s;){const a=this.getNextTag(A,s.endIndex),r={fontFamily:(g=this.uiObject)==null?void 0:g.get("fontFamily"),color:"inherit",textContent:""};if(a){r.textContent=this.getText(A,s,a),this.handleTag(s,r,n);const C=new tm(r);(I=this.uiObject)==null||I.add(C)}else{r.textContent=A.substring(s.endIndex),this.handleTag(s,r,n);const C=new tm(r);(o=this.uiObject)==null||o.add(C)}s=a}}}handleTextRenderOnTop(){this._didHandleTextRenderOnTop||(this._didHandleTextRenderOnTop=!0,this.startCoroutine(this.renderOnTopCoroutine()))}*renderOnTopCoroutine(){if(!this.canvas)return;const A=[],e=this.canvas,g={renderOnTop:e.renderOnTop,depthWrite:e.depthWrite,doubleSided:e.doubleSided};for(;;){let I=!1;if(this._textMeshUi)for(let o=0;o<this._textMeshUi.length;o++){if(A[o]===!0)continue;I=!0;const s=this._textMeshUi[o];s.textContent&&(Mf(s,g),A[o]=!0)}if(!I)break;yield}}handleTag(A,e,g){if(!A.isEndTag){if(A.type.includes("color")){const I=new GJ(A,{color:e.color});if(g.push(I),A.type.length>6){const o=parseInt("0x"+A.type.substring(7));e.color=o}else e.color=new fA(1,1,1)}else if(A.type=="b"){this.setFont(e,1);const I=new GJ(A,{fontWeight:700});g.push(I)}else if(A.type=="i"){this.setFont(e,2);const I=new GJ(A,{fontStyle:"italic"});g.push(I)}}}getText(A,e,g){return A.substring(e.endIndex,g.startIndex)}getNextTag(A,e=0){const g=A.indexOf("<",e),I=A.indexOf(">",g);if(g>=0&&I>=0){const o=A.substring(g+1,I);return{type:o,startIndex:g,endIndex:I+1,isEndTag:o.startsWith("/")}}return null}setFont(A,e){if(!this.font)return;const g=this.font,I=this.getFamilyNameWithCorrectSuffix(g,e);Yh&&console.log("Selected font family:"+I);let o=kN.getFontFamily(I);switch(o||(o=kN.addFontFamily(I)),A.fontFamily=o,e){default:case 0:A.fontWeight=400,A.fontStyle="normal";break;case 1:A.fontWeight=700,A.fontStyle="normal";break;case 2:A.fontWeight=400,A.fontStyle="italic";break;case 3:A.fontStyle="italic",A.fontWeight=400}let s=o.getVariant(A.fontWeight,A.fontStyle);if(!s){let n=I;n!=null&&n.endsWith("-msdf.json")||(n+="-msdf.json");let a=I;a!=null&&a.endsWith(".png")||(a+=".png"),s=o.addVariant(A.fontWeight,A.fontStyle,n,a),s?.addEventListener("ready",()=>{this.markDirty()})}}getFamilyNameWithCorrectSuffix(A,e){var g;const I=A.lastIndexOf("-");if(I<0)return A;const o=(g=A.substring(I+1))==null?void 0:g.toLowerCase();if(HdA.includes(o))return Yh&&console.warn("Unsupported font style: "+o),A;const s=A.lastIndexOf("/");let n=A;s>=0&&(n=n.substring(s+1));const a=n[0]===n[0].toUpperCase(),r=A.substring(0,I);switch(Yh&&console.log("Select font: ",A,lW[e],n,a,r),e){case 0:return a?r+"-Regular":r+"-regular";case 1:return a?r+"-Bold":r+"-bold";case 2:return a?r+"-Italic":r+"-italic";case 3:return a?r+"-BoldItalic":r+"-bolditalic";default:return A}}}Zr([y()],_I.prototype,"alignment",2),Zr([y()],_I.prototype,"verticalOverflow",2),Zr([y()],_I.prototype,"horizontalOverflow",2),Zr([y()],_I.prototype,"lineSpacing",2),Zr([y()],_I.prototype,"supportRichText",2),Zr([y(URL)],_I.prototype,"font",2),Zr([y()],_I.prototype,"fontStyle",2),Zr([y()],_I.prototype,"text",1),Zr([y()],_I.prototype,"fontSize",1);class GJ{constructor(A,e){B(this,"tag"),B(this,"previousValues"),this.tag=A,this.previousValues=e}}const HdA=["medium","mediumitalic","black","blackitalic","thin","thinitalic","extrabold","light","lightitalic","semibold"];class xB{constructor(A){B(this,"id"),B(this,"content",""),B(this,"font",[]),B(this,"pointSize",144),B(this,"width"),B(this,"height"),B(this,"depth"),B(this,"wrapMode"),B(this,"horizontalAlignment"),B(this,"verticalAlignment"),B(this,"material"),this.id=A}static getId(){return this.global_id++}setDepth(A){return this.depth=A,this}setPointSize(A){return this.pointSize=A,this}setHorizontalAlignment(A){return this.horizontalAlignment=A,this}setVerticalAlignment(A){return this.verticalAlignment=A,this}writeTo(A,e){var g;e.beginBlock(`def Preliminary_Text "${this.id}"`,"(",!1),e.appendLine('prepend apiSchemas = ["MaterialBindingAPI"]'),e.closeBlock(")"),e.beginBlock(),this.content&&e.appendLine(`string content = "${this.content}"`),(!this.font||this.font.length<=0)&&(this.font||(this.font=[]),(g=this.font)==null||g.push("sans-serif"));const I=this.font.map(o=>`"${o}"`).join(", ");e.appendLine(`string[] font = [ ${I} ]`),e.appendLine(`double pointSize = ${this.pointSize}`),typeof this.width=="number"&&e.appendLine(`double width = ${this.width}`),typeof this.height=="number"&&e.appendLine(`double height = ${this.height}`),typeof this.depth=="number"&&e.appendLine(`double depth = ${this.depth}`),this.wrapMode&&e.appendLine(`token wrapMode = "${this.wrapMode}"`),this.horizontalAlignment&&e.appendLine(`token horizontalAlignment = "${this.horizontalAlignment}"`),this.verticalAlignment&&e.appendLine(`token verticalAlignment = "${this.verticalAlignment}"`),this.material!==void 0&&e.appendLine(`rel material:binding = </StageRoot/Materials/${xv(this.material)}>`),e.closeBlock()}}B(xB,"global_id",0);class pk{static singleLine(A,e,g){const I=new xB("text_"+xB.getId());return I.content=A,e&&(I.pointSize=e),g&&(I.depth=g),I}static multiLine(A,e,g,I,o,s){const n=new xB("text_"+xB.getId());return n.content=A,n.width=e,n.height=g,n.horizontalAlignment=I,n.verticalAlignment=o,s!==void 0&&(n.wrapMode=s),n}}const OdA=new DA().makeRotationY(Math.PI),PdA=new DA().makeScale(-1,1,-1);class HD{get extensionName(){return"text"}exportText(A,e,g){const I=gA.getComponent(A,_I);if(!I)return;const o=gA.getComponent(A,qI);let s=100,n=100;o&&(s=o.width,n=o.height),e.matrix=OdA.clone(),o&&e.matrix.premultiply(PdA);const a=I.color.clone();e.material=new MI({color:a,emissive:a}),e.addEventListener("serialize",(r,C)=>{let Q=I.text;Q=Q.replace(/\r/g,""),Q=Q.replace(/\n/g,"\\n");const h=pk.multiLine(Q,s,n,"center","bottom","flowing");this.setTextAlignment(h,I.alignment),this.setOverflow(h,I),e.material&&(h.material=e.material),h.pointSize=this.convertToTextSize(I.fontSize),h.depth=.001,h.writeTo(void 0,r)})}convertToTextSize(A){return 1/.0502*144*A}setOverflow(A,e){e.horizontalOverflow?A.wrapMode="singleLine":A.wrapMode="flowing"}setTextAlignment(A,e){switch(e){case yg.LowerLeft:case yg.MiddleLeft:case yg.UpperLeft:A.horizontalAlignment="left";break;case yg.LowerCenter:case yg.MiddleCenter:case yg.UpperCenter:A.horizontalAlignment="center";break;case yg.LowerRight:case yg.MiddleRight:case yg.UpperRight:A.horizontalAlignment="right";break}switch(e){case yg.LowerLeft:case yg.LowerCenter:case yg.LowerRight:A.verticalAlignment="bottom";break;case yg.MiddleLeft:case yg.MiddleCenter:case yg.MiddleRight:A.verticalAlignment="middle";break;case yg.UpperLeft:case yg.UpperCenter:case yg.UpperRight:A.verticalAlignment="top";break}}}class Dk{get extensionName(){return"tmui"}onExportObject(A,e,g){const I=gA.getComponent(A,aI);if(I&&I.enabled&&I.renderMode===b8.WorldSpace){const o=new HD,s=gA.getComponent(A,qI),n=gA.getComponent(A,GB),a=new Array;if(s){if(!gA.isActiveSelf(A)){const Q=gA.isActiveSelf(A);gA.setActive(A,!0),s.onEnable(),s.updateTransform(),a.push(()=>{s.onDisable(),gA.setActive(A,Q)})}A.traverse(Q=>{if(!gA.isActiveInHierarchy(Q)){const h=gA.isActiveSelf(Q);gA.setActive(Q,!0);const E=gA.getComponent(Q,$s);E&&(E.onEnable(),a.push(()=>{E.onDisable()}));const c=gA.getComponent(Q,qI);c&&(c.onEnable(),c.updateTransform(),c.onApplyTransform(),a.push(()=>{c.onDisable()}));const l=gA.getComponent(Q,_I);l&&(l.onEnable(),a.push(()=>{l.onDisable()})),a.push(()=>{gA.setActive(Q,h)})}}),s.width,s.height;const r=eo.createEmpty(),C=s.shadowComponent;if(e.add(r),C){const Q=C.matrix;r.matrix.copy(Q);const h=new Map,E=new Map;h.set(C,r),E.set(C,n?n.alpha:1),C.traverse(c=>{if(c===C)return;const l=eo.createEmpty();l.matrix.copy(c.matrix);const d=c.parent,u=!!d&&typeof d.textContent=="string"&&d.textContent.length>0;let D=E.get(d)||1;const p=gA.getComponent(c,GB);if(p&&(D*=p.alpha),c instanceof dA&&u){const f=c[Js];f?o.exportText(f.gameObject,l,g):console.error("Error when exporting UI: shadow component owner not found. This is likely a bug.",c)}if(c instanceof dA&&!u){const f=c.geometry.clone();f.scale(1,1,-1),this.flipWindingOrder(f),l.geometry=f;const G=new fA,M=c.material.opacity;G.copy(c.material.color),l.material=new tt({color:G,opacity:M*D,map:c.material.map,transparent:!0})}h.set(c,l),E.set(c,D);const w=h.get(d);if(!w){console.error("Error when exporting UI: shadow component parent not found!",c,c.parent);return}w.add(l)})}}for(const r of a)r()}}flipWindingOrder(A){const e=A.index.array;for(let g=0,I=e.length/3;g<I;g++){const o=e[g*3];e[g*3]=e[g*3+2],e[g*3+2]=o}A.index.needsUpdate=!0}}const OD=iA("debugusdz");function jdA(i,A){var e;const g=[],I=gA.getComponentsInChildren(i,II),o=gA.getComponentsInChildren(i,JI),s=new Array,n=new Array;if(A.injectImplicitBehaviours)for(const a of I){if(!a||!a.runtimeAnimatorController||!a.enabled)continue;const r=a.runtimeAnimatorController.activeState;if(!r||!r.motion||!r.motion.clip||((e=r.motion.clip.tracks)==null?void 0:e.length)<1||s.includes(a))continue;const C=new bh;C.animator=a,C.stateName=r.name,C.trigger="start",C.name="PlayAnimationOnClick_implicitAtStart_"+C.stateName;const Q=new wA;gA.addComponent(Q,C),n.push(Q),s.push(a),i.add(Q)}else for(const a of I){if(!a||!a.runtimeAnimatorController||!a.enabled)continue;OD&&console.log(a);const r=[];for(const C of a.runtimeAnimatorController.enumerateActions()){OD&&console.log(C);const Q=C.getClip();r.includes(Q)||r.push(Q)}g.push({root:a.gameObject,clips:r})}if(A.injectImplicitBehaviours)for(const a of o){if(!a||!a.clip||!a.enabled||!a.playAutomatically||s.includes(a))continue;const r=new bh;r.animation=a,r.stateName=a.clip.name,r.trigger="start",r.name="PlayAnimationOnClick_implicitAtStart_"+r.stateName;const C=new wA;gA.addComponent(C,r),n.push(C),s.push(a),i.add(C)}else for(const a of o){OD&&console.log(a);const r=[];for(const C of a.animations)r.includes(C)||r.push(C);g.push({root:a.gameObject,clips:r})}OD&&g?.length>0&&console.log("USDZ Animation Clips without behaviours",g);for(const a of g)for(const r of a.clips)A.registerAnimation(a.root,r);return n}function WdA(i,A){const e=gA.getComponentsInChildren(i,bi),g=gA.getComponentsInChildren(i,RB),I=new Array,o=new Array;OD&&console.log({audioSources:e,playAudioOnClicks:g});for(const s of g){if(!s.target)continue;const n=e.indexOf(s.target);n>-1&&e.splice(n,1)}for(const s of e){if(!s||!s.clip||s.volume<=0||I.includes(s))continue;const n=new RB;n.target=s,n.name="PlayAudioOnClick_implicitAtStart_",n.trigger="start";const a=new wA;gA.addComponent(a,n),console.log("implicit PlayAudioOnStart",a,n),o.push(a),I.push(s),i.add(a)}return o}function ZdA(i){return new Ug("DisableAtStart",Ng.sceneStartTrigger(),Dt.fadeAction(i,0,!1))}function dW(i){const A=i.domElement.shadowRoot.querySelector("link[rel='ar']");if(A)return A;const e=document.createElement("div");e.classList.add("menu"),e.classList.add("quicklook-menu"),e.style.display="none",e.style.visibility="hidden";const g=document.createElement("button");g.id="open-in-ar",g.innerText="Open in QuickLook",e.appendChild(g);const I=document.createElement("a");I.id="needle-usdz-link",I.style.display="none",I.rel="ar",I.href="",e.appendChild(I);const o=document.createElement("img");return o.id="button",I.appendChild(o),i.domElement.shadowRoot.appendChild(e),I}var zdA=Object.defineProperty,VdA=Object.getOwnPropertyDescriptor,TI=(i,A,e,g)=>{for(var I=g>1?void 0:g?VdA(A,e):A,o=i.length-1,s;o>=0;o--)(s=i[o])&&(I=(g?s(A,e,I):s(I))||I);return g&&I&&zdA(A,e,I),I};const Os=iA("debugusdz");class qB{constructor(){B(this,"callToAction"),B(this,"checkoutTitle"),B(this,"checkoutSubtitle"),B(this,"callToActionURL")}}TI([y()],qB.prototype,"callToAction",2),TI([y()],qB.prototype,"checkoutTitle",2),TI([y()],qB.prototype,"checkoutSubtitle",2),TI([y()],qB.prototype,"callToActionURL",2);var wk;const RJ=(wk=class extends bA{constructor(){super(...arguments),B(this,"objectToExport"),B(this,"autoExportAnimations",!0),B(this,"autoExportAudioSources",!0),B(this,"exportFileName"),B(this,"customUsdzFile"),B(this,"customBranding"),B(this,"anchoringType","plane"),B(this,"maxTextureSize",2048),B(this,"planeAnchoringAlignment","horizontal"),B(this,"interactive",!0),B(this,"allowCreateQuicklookButton",!0),B(this,"quickLookCompatible",!0),B(this,"extensions",[]),B(this,"link"),B(this,"button"),B(this,"onClickedOpenInARElement",i=>{i.preventDefault(),this.exportAndOpen()}),B(this,"_currentExportTasks",new Map),B(this,"_previousTimeScale",1),B(this,"lastCallback"),B(this,"_rootSessionRootWasAppliedTo",null),B(this,"_rootPositionBeforeExport",new S),B(this,"_rootRotationBeforeExport",new GA),B(this,"_rootScaleBeforeExport",new S)}start(){var i,A,e;Os&&(console.log("USDZExporter",this),console.log("Debug USDZ Mode. Press 'T' to export"),window.addEventListener("keydown",g=>{switch(g.key){case"t":this.exportAsync();break}}),ls()&&setTimeout(()=>{this.exportAsync()},2e3)),this.objectToExport||(this.objectToExport=this.gameObject),!((A=(i=this.objectToExport)==null?void 0:i.children)!=null&&A.length)&&!((e=this.objectToExport)!=null&&e.isMesh)&&(this.objectToExport=this.context.scene),this.interactive&&(this.extensions.push(new Hf),this.extensions.push(new VB),this.extensions.push(new uk),this.extensions.push(new HD),this.extensions.push(new Dk))}onEnable(){var i;const A=xQ(),e=oc();(Os||A&&e)&&(this.allowCreateQuicklookButton&&(this.button=this.createQuicklookButton()),this.lastCallback=this.quicklookCallback.bind(this),this.link=dW(this.context),this.link.addEventListener("message",this.lastCallback)),Os&&Ci("USDZ Exporter enabled: "+this.name),(i=document.getElementById("open-in-ar"))==null||i.addEventListener("click",this.onClickedOpenInARElement)}onDisable(){var i,A,e;(i=this.button)==null||i.remove(),(A=this.link)==null||A.removeEventListener("message",this.lastCallback),Os&&Ci("USDZ Exporter disabled: "+this.name),(e=document.getElementById("open-in-ar"))==null||e.removeEventListener("click",this.onClickedOpenInARElement)}async exportAsync(){return this.exportAndOpen()}async exportAndOpen(){var i;let A=this.exportFileName??((i=this.objectToExport)==null?void 0:i.name)??this.name;if(A+="-"+TO(),RC()||(A!==""&&(A+="-"),A+="MadeWithNeedle"),this.link||(this.link=dW(this.context)),this.customUsdzFile)return Os&&console.log("Exporting custom usdz",this.customUsdzFile),this.openInQuickLook(this.customUsdzFile,A),null;if(!this.objectToExport)return console.warn("No object to export",this),null;const e=await this.export(this.objectToExport);return e?(Os&&console.log("USDZ generation done. Downloading as "+A),this.openInQuickLook(e,A),e):(console.error("USDZ generation failed. Please report a bug",this),null)}async export(i){if(!i)return console.warn("No object to export"),null;const A=this._currentExportTasks.get(i);if(A)return A;const e=this.internalExport(i);return e instanceof Promise?(this._currentExportTasks.set(i,e),e.then(g=>(this._currentExportTasks.delete(i),g)).catch(g=>(this._currentExportTasks.delete(i),console.error("Error during USDZ export \u2013 please report a bug!",g),null))):e}async internalExport(i){ot.start("export-usdz",{onProgress:d=>{this.dispatchEvent(new CustomEvent("export-progress",{detail:{progress:d}}))}}),ot.report("export-usdz",{message:"Starting export",totalSteps:40,currentStep:0}),ot.report("export-usdz",{message:"Load progressive textures",autoStep:5}),ot.start("export-usdz-textures","export-usdz");const A=gA.getComponentsInChildren(i,Ys);for(const d of A)d&&d.enabled&&d.start&&d.start();const e=gA.getComponentsInChildren(i,Ji),g=new Array;let I=0;for(const d of e){for(const u of d.sharedMeshes)if(u){const D=ut.assignMeshLOD(u,0);D instanceof Promise&&g.push(new Promise((p,w)=>{D.then(()=>{I++,ot.report("export-usdz-textures",{message:"Loaded progressive mesh",currentStep:I,totalSteps:g.length}),p()}).catch(f=>w(f))}))}for(const u of d.sharedMaterials)if(u){const D=ut.assignTextureLOD(u,0);D instanceof Promise&&g.push(new Promise((p,w)=>{D.then(()=>{I++,ot.report("export-usdz-textures",{message:"Loaded progressive texture",currentStep:I,totalSteps:g.length}),p()}).catch(f=>w(f))}))}}Os&&Ci("Progressive Loading: "+g.length),await Promise.all(g),Os&&Ci("Progressive Loading: done"),ot.end("export-usdz-textures");const o=ao.Global.Mask;ao.Global.Set(ua.AR);const s=new jO,n=new BD(this.quickLookCompatible),a=[n,...this.extensions],r={self:this,exporter:s,extensions:a,object:i};ot.report("export-usdz","Invoking before-export"),this.dispatchEvent(new CustomEvent("before-export",{detail:r})),this.applyWebARSessionRoot(),this._previousTimeScale=this.context.time.timeScale,this.context.time.timeScale=0,ot.report("export-usdz","auto export animations and audio sources");const C=new Array;this.autoExportAnimations&&C.push(...jdA(i,n)),this.extensions.find(d=>d.extensionName==="Audio")&&this.autoExportAudioSources&&C.push(...WdA(i)),s.debug=Os,s.keepObject=d=>{const u=gA.getComponent(d,Ji);return!(u&&!u.enabled)};const Q=new Array;this.objectToExport&&this.quickLookCompatible&&this.interactive&&this.objectToExport.traverse(d=>{d.visible||Q.push(d)});const h=this.extensions.find(d=>d.extensionName==="Behaviour");this.interactive&&h&&Q.length>0&&h.addBehavior(ZdA(Q));let E=!0;this.quickLookCompatible&&!this.interactive&&(E=!1),this.anchoringType!=="plane"&&this.anchoringType!=="none"&&this.anchoringType!=="image"&&this.anchoringType!=="face"&&(this.anchoringType="plane"),this.planeAnchoringAlignment!=="horizontal"&&this.planeAnchoringAlignment!=="vertical"&&this.planeAnchoringAlignment!=="any"&&(this.planeAnchoringAlignment="horizontal"),ot.report("export-usdz","Invoking exporter.parse");const c=await s.parse(this.objectToExport,{ar:{anchoring:{type:this.anchoringType},planeAnchoring:{alignment:this.planeAnchoringAlignment}},extensions:a,quickLookCompatible:this.quickLookCompatible,maxTextureSize:this.maxTextureSize,exportInvisible:E}),l=new Blob([c],{type:"model/vnd.usdz+zip"});this.revertWebARSessionRoot(),this.context.time.timeScale=this._previousTimeScale,ot.report("export-usdz","Invoking after-export"),this.dispatchEvent(new CustomEvent("after-export",{detail:r}));for(const d of C)gA.destroy(d);return ao.Global.Set(o),ot.end("export-usdz"),l}openInQuickLook(i,A){const e=i instanceof Blob?URL.createObjectURL(i):i,g=this.buildQuicklookOverlay();Os&&console.log("QuickLook Overlay",g);const I=g.callToAction?encodeURIComponent(g.callToAction):"",o=g.checkoutTitle?encodeURIComponent(g.checkoutTitle):"",s=g.checkoutSubtitle?encodeURIComponent(g.checkoutSubtitle):"";this.link.href=e+`#callToAction=${I}&checkoutTitle=${o}&checkoutSubtitle=${s}&callToActionURL=${g.callToActionURL}`,this.lastCallback||(this.lastCallback=this.quicklookCallback.bind(this),this.link.addEventListener("message",this.lastCallback)),this.link.download=A+".usdz",this.link.click()}download(i,A){RJ.save(i,A)}static save(i,A){const e=document.createElement("a");e.style.display="none",document.body.appendChild(e),typeof i=="string"?e.href=i:e.href=URL.createObjectURL(i),e.download=A,e.click(),e.remove()}quicklookCallback(i){if(i?.data=="_apple_ar_quicklook_button_tapped"){Os&&Lt("Quicklook closed via call to action button");var A=new CustomEvent("quicklook-button-tapped",{detail:this});if(this.dispatchEvent(A),!A.defaultPrevented){const e=new URLSearchParams(this.link.href);if(e){const g=e.get("callToActionURL");Os&&Ci("Quicklook url: "+g),g&&(RC()?globalThis.open(g,"_blank"):console.warn("Quicklook closed: custom redirects require a Needle Engine Pro license: https://needle.tools/pricing",g))}}}}buildQuicklookOverlay(){var i,A,e,g,I,o;const s={};return this.customBranding&&Object.assign(s,this.customBranding),RC()||(console.log("Custom Quicklook banner text requires pro license: https://needle.tools/pricing"),s.callToAction="Close",s.checkoutTitle="\u{1F335} Made with Needle",s.checkoutSubtitle="_"),(((i=s.callToAction)==null?void 0:i.length)||((A=s.checkoutTitle)==null?void 0:A.length)||((e=s.checkoutSubtitle)==null?void 0:e.length))&&((g=s.callToAction)!=null&&g.length||(s.callToAction="\0"),(I=s.checkoutTitle)!=null&&I.length||(s.checkoutTitle="\0"),(o=s.checkoutSubtitle)!=null&&o.length||(s.checkoutSubtitle="\0")),this.dispatchEvent(new CustomEvent("quicklook-overlay",{detail:s})),s}getARScaleAndTarget(){if(!this.objectToExport)return{scale:1,_invertForward:!1,target:this.gameObject,sessionRoot:null};let i=gA.getComponentInParent(this.objectToExport,Co);i||(i=gA.getComponentInChildren(this.objectToExport,Co));let A=1,e=!1;const g=this.objectToExport;if(i)A=i.arScale,e=i.invertForward;else{const I=gA.findObjectOfType(_g);I&&(A=I.arSceneScale)}return{scale:1/A,_invertForward:e,target:g,sessionRoot:i?.gameObject??null}}applyWebARSessionRoot(){if(!this.objectToExport)return;const{scale:i,_invertForward:A,target:e,sessionRoot:g}=this.getARScaleAndTarget(),I=g?.matrixWorld.clone().invert();this._rootSessionRootWasAppliedTo=e,this._rootPositionBeforeExport.copy(e.position),this._rootRotationBeforeExport.copy(e.quaternion),this._rootScaleBeforeExport.copy(e.scale),e.scale.multiplyScalar(i),A&&e.quaternion.multiply(RJ.invertForwardQuaternion),e.updateMatrix(),e.updateMatrixWorld(!0),g&&I&&e.matrix.premultiply(I)}revertWebARSessionRoot(){if(!this.objectToExport||!this._rootSessionRootWasAppliedTo)return;const i=this._rootSessionRootWasAppliedTo;i.position.copy(this._rootPositionBeforeExport),i.quaternion.copy(this._rootRotationBeforeExport),i.scale.copy(this._rootScaleBeforeExport),i.updateMatrix(),i.updateMatrixWorld(!0),this._rootSessionRootWasAppliedTo=null}createQuicklookButton(){const i=Lh.getOrCreate().createQuicklookButton();return i.parentNode||this.context.menu.appendChild(i),i}},B(wk,"invertForwardMatrix",new DA().makeRotationY(Math.PI)),B(wk,"invertForwardQuaternion",new GA().setFromEuler(new It(0,Math.PI,0))),wk);let qi=RJ;TI([y(wA)],qi.prototype,"objectToExport",2),TI([y()],qi.prototype,"autoExportAnimations",2),TI([y()],qi.prototype,"autoExportAudioSources",2),TI([y()],qi.prototype,"exportFileName",2),TI([y(URL)],qi.prototype,"customUsdzFile",2),TI([y(qB)],qi.prototype,"customBranding",2),TI([y()],qi.prototype,"anchoringType",2),TI([y()],qi.prototype,"maxTextureSize",2),TI([y()],qi.prototype,"planeAnchoringAlignment",2),TI([y()],qi.prototype,"interactive",2),TI([y()],qi.prototype,"allowCreateQuicklookButton",2),TI([y()],qi.prototype,"quickLookCompatible",2);class PD extends bA{constructor(){super(...arguments),B(this,"isUsed",!0),B(this,"usedBy",null)}}class UJ extends bA{}const uW=iA("debugdeletable");class yk extends wa{}class NJ extends bA{constructor(){super(...arguments),B(this,"deleteBoxes",[])}awake(){this.deleteBoxes=gA.findObjectsOfType(yk,this.context)}update(){for(const A of this.deleteBoxes){const e=this.gameObject;if(A.isInBox(e)===!0){const g=gA.getComponentInParent(this.gameObject,PD);g?uW&&console.warn("Can not delete object with usage marker",this.guid,g):(uW&&console.log("DESTROY",this.gameObject),Hp(this.gameObject,this.context.connection))}}}}var XdA=Object.defineProperty,$dA=Object.getOwnPropertyDescriptor,Hh=(i,A,e,g)=>{for(var I=g>1?void 0:g?$dA(A,e):A,o=i.length-1,s;o>=0;o--)(s=i[o])&&(I=(g?s(A,e,I):s(I))||I);return g&&I&&XdA(A,e,I),I};const AuA=iA("debugpost");class vn extends oI{constructor(){super(...arguments),B(this,"mode"),B(this,"focusDistance",new zA(1)),B(this,"focalLength",new zA(.2)),B(this,"aperture",new zA(20)),B(this,"gaussianMaxRadius",new zA),B(this,"resolutionScale",new zA(1*1/window.devicePixelRatio)),B(this,"bokehScale",new zA)}get typeName(){return"DepthOfField"}init(){this.focalLength.valueProcessor=e=>{const g=e/300,I=2;return ge.lerp(I,.01,g)};const A=20;this.aperture.valueProcessor=e=>{const g=1-e/32;return ge.lerp(1,A,g)}}onCreateEffect(){if(this.mode===0){AuA&&console.warn("DepthOfField: Mode is set to Off");return}const A=new HP(this.context.mainCamera,{worldFocusRange:.2,focalLength:1,bokehScale:20,resolutionScale:this.resolutionScale.value});return this.focusDistance.onValueChanged=e=>{A.cocMaterial.worldFocusDistance=e},this.focalLength.onValueChanged=e=>A.cocMaterial.worldFocusRange=e,this.aperture.onValueChanged=e=>A.bokehScale=e,this.resolutionScale&&(this.resolutionScale.onValueChanged=e=>A.resolution.scale=e),[A]}unapply(){}}Hh([y()],vn.prototype,"mode",2),Hh([y(zA)],vn.prototype,"focusDistance",2),Hh([y(zA)],vn.prototype,"focalLength",2),Hh([y(zA)],vn.prototype,"aperture",2),Hh([y(zA)],vn.prototype,"gaussianMaxRadius",2),Hh([y(zA)],vn.prototype,"resolutionScale",2),Hh([y(zA)],vn.prototype,"bokehScale",2),Ls("DepthOfField",vn);var euA=Object.defineProperty,tuA=Object.getOwnPropertyDescriptor,iuA=(i,A,e,g)=>{for(var I=g>1?void 0:g?tuA(A,e):A,o=i.length-1,s;o>=0;o--)(s=i[o])&&(I=(g?s(A,e,I):s(I))||I);return g&&I&&euA(A,e,I),I};class mk extends bA{constructor(){super(...arguments),B(this,"visibleOn")}onEnable(){this.apply()}apply(){this.test()||gA.setActive(this.gameObject,!1)}test(){return this.visibleOn<0?!0:ls()?(this.visibleOn&2)!==0:(this.visibleOn&1)!==0}}iuA([y()],mk.prototype,"visibleOn",2);class FJ{get extensionName(){return"DocumentExtension"}onAfterBuildDocument(A){}}var guA=Object.defineProperty,IuA=Object.getOwnPropertyDescriptor,Oh=(i,A,e,g)=>{for(var I=g>1?void 0:g?IuA(A,e):A,o=i.length-1,s;o>=0;o--)(s=i[o])&&(I=(g?s(A,e,I):s(I))||I);return g&&I&&guA(A,e,I),I};const va=iA("debugdrag");var pW=(i=>(i[i.XZPlane=0]="XZPlane",i[i.Attached=1]="Attached",i[i.HitNormal=2]="HitNormal",i[i.DynamicViewAngle=3]="DynamicViewAngle",i[i.SnapToSurfaces=4]="SnapToSurfaces",i[i.None=5]="None",i))(pW||{}),Sk;const Ka=(Sk=class extends bA{constructor(){super(...arguments),B(this,"dragMode",3),B(this,"snapGridResolution",0),B(this,"keepRotation",!0),B(this,"xrDragMode",1),B(this,"xrKeepRotation",!1),B(this,"xrDistanceDragFactor",1),B(this,"showGizmo",!1),B(this,"targetObject",null),B(this,"orbit",null),B(this,"_dragHelper",null),B(this,"_draggingRigidbodies",[]),B(this,"_potentialDragStartEvt",null),B(this,"_dragHandlers",new Map),B(this,"_totalMovement",new S),B(this,"_marker",null),B(this,"_isDragging",!1),B(this,"_didDrag",!1)}static get HasAnySelected(){return this._active>0}setTargetObject(i){this.targetObject=i;for(const A of this._dragHandlers.values())A.setTargetObject(i)}awake(){this._potentialDragStartEvt=null,this._dragHandlers=new Map,this._totalMovement=new S,this._marker=null,this._isDragging=!1,this._didDrag=!1,this._dragHelper=null,this._draggingRigidbodies=[]}start(){this.orbit=gA.findObjectOfType(St,this.context),this.gameObject.getComponentInParent(Zo)||this.gameObject.addComponent(Zo)}allowEdit(i=null){return this.context.connection.allowEditing}onPointerEnter(i){if(!this.allowEdit(this.gameObject)||i.mode!=="screen"||(i.event.mode==="tracked-pointer"||i.event.mode==="transient-pointer"?this.xrDragMode:this.dragMode)===5)return;const A=gA.getComponentInParent(i.object,Ka);!A||A!==this||(Ka.lastHovered=i.object,this.context.domElement.style.cursor="pointer")}onPointerExit(i){this.allowEdit(this.gameObject)&&i.mode==="screen"&&Ka.lastHovered===i.object&&(this.context.domElement.style.cursor="auto")}onPointerDown(i){if(!(!this.allowEdit(this.gameObject)||i.used||(i.mode==="tracked-pointer"||i.mode==="transient-pointer"?this.xrDragMode:this.dragMode)===5)&&(Ka.lastHovered=i.object,i.button===0)){this._dragHandlers.size===0&&(this._didDrag=!1,this._totalMovement.set(0,0,0),this._potentialDragStartEvt=i),Ka._active+=1;const A=new suA(this,this.targetObject||this.gameObject);if(this._dragHandlers.set(i.event.space,A),this.orbit&&(this.orbit.enabled=!1),A.onDragStart(i),this._dragHandlers.size===2){const e=this._dragHandlers.values(),g=e.next().value,I=e.next().value,o=new ouA(this,this.targetObject||this.gameObject,g,I);this._dragHandlers.set(this.gameObject,o),o.onDragStart(i)}i.use()}}onPointerMove(i){(this._isDragging||this._potentialDragStartEvt!==null)&&i.use()}onPointerUp(i){if(va&&pe.DrawLabel(i.point??this.gameObject.worldPosition,"POINTERUP:"+i.pointerId+", "+i.button,.03,3),!this.allowEdit(this.gameObject)||i.button!==0)return;this._potentialDragStartEvt=null;const A=this._dragHandlers.get(i.event.space),e=this._dragHandlers.get(this.gameObject);e&&(e.handlerA===A||e.handlerB===A)&&(this._dragHandlers.delete(this.gameObject),e.onDragEnd(i)),A&&(Ka._active>0&&(Ka._active-=1),A.onDragEnd&&A.onDragEnd(i),this._dragHandlers.delete(i.event.space),this._dragHandlers.size===0&&this.onLastDragEnd(i),i.use()),Ka._active===0&&this.orbit&&(this.orbit.enabled=!0)}update(){for(const i of this._dragHandlers.values())i.collectMovementInfo&&i.collectMovementInfo(),i.getTotalMovement&&this._totalMovement.add(i.getTotalMovement());if(this._potentialDragStartEvt){if(!this._didDrag)if(this._totalMovement.length()>3e-4)this._didDrag=!0;else return;const i=this._potentialDragStartEvt;this._potentialDragStartEvt=null,this.onFirstDragStart(i)}for(const i of this._dragHandlers.values())i.onDragUpdate&&i.onDragUpdate(this._dragHandlers.size);this._dragHelper&&this._dragHelper.hasSelected&&this.onAnyDragUpdate()}onFirstDragStart(i){if(!this._dragHelper)if(this.context.mainCamera)this._dragHelper=new wW(this.context.mainCamera);else return;if(!i||!i.object)return;const A=gA.getComponentInParent(i.object,Ka);if(!A||A!==this&&A._isDragging)return;const e=this.targetObject||this.gameObject;if(!e)return;this._isDragging=!0,this._dragHelper.setSelected(e,this.context),this.orbit&&(this.orbit.enabled=!1);const g=gA.getComponentInChildren(e,cB);va&&console.log("DRAG START",g,e),g&&(g.fastMode=!0,g?.requestOwnership()),this._marker=gA.addComponent(e,PD),this._draggingRigidbodies.length=0;const I=gA.getComponentsInChildren(e,_t);I&&this._draggingRigidbodies.push(...I)}onAnyDragUpdate(){if(!this._dragHelper)return;this._dragHelper.showGizmo=this.showGizmo,this._dragHelper.onUpdate(this.context);for(const A of this._draggingRigidbodies)A.wakeUp(),A.resetVelocities(),A.resetForcesAndTorques();const i=this.targetObject||this.gameObject;en.markDirty(i)}onLastDragEnd(i){if(!this||!this._isDragging||(this._isDragging=!1,!this._dragHelper))return;for(const e of this._draggingRigidbodies)e.setVelocity(e.smoothedVelocity);this._draggingRigidbodies.length=0;const A=this._dragHelper.selected;if(va&&console.log("DRAG END",A,A?.visible),this._dragHelper.setSelected(null,this.context),this.orbit&&(this.orbit.enabled=!0),i!=null&&i.object){const e=gA.getComponentInChildren(i.object,cB);e&&(e.fastMode=!1)}this._marker&&this._marker.destroy()}},B(Sk,"_active",0),B(Sk,"lastHovered"),Sk);let Ps=Ka;Oh([y()],Ps.prototype,"dragMode",2),Oh([y()],Ps.prototype,"snapGridResolution",2),Oh([y()],Ps.prototype,"keepRotation",2),Oh([y()],Ps.prototype,"xrDragMode",2),Oh([y()],Ps.prototype,"xrKeepRotation",2),Oh([y()],Ps.prototype,"xrDistanceDragFactor",2),Oh([y()],Ps.prototype,"showGizmo",2);class ouA{constructor(A,e,g,I){B(this,"handlerA"),B(this,"handlerB"),B(this,"context"),B(this,"settings"),B(this,"gameObject"),B(this,"_handlerAAttachmentPoint",new S),B(this,"_handlerBAttachmentPoint",new S),B(this,"_followObject"),B(this,"_manipulatorObject"),B(this,"_deviceMode"),B(this,"_followObjectStartWorldQuaternion",new GA),B(this,"_manipulatorPosOffset",new S),B(this,"_manipulatorRotOffset",new GA),B(this,"_manipulatorScaleOffset",new S),B(this,"_tempVec1",new S),B(this,"_tempVec2",new S),B(this,"_tempVec3",new S),B(this,"tempLookMatrix",new DA),B(this,"_initialScale",new S),B(this,"_initialDistance",0);var o,s;this.context=A.context,this.settings=A,this.gameObject=e,this.handlerA=g,this.handlerB=I,this._followObject=new wA,this._manipulatorObject=new wA,this.context.scene.add(this._manipulatorObject);const n=(s=(o=me.active)==null?void 0:o.rig)==null?void 0:s.gameObject;if(!this.handlerA||!this.handlerB||!this.handlerA.hitPointInLocalSpace||!this.handlerB.hitPointInLocalSpace){console.error("Invalid: MultiTouchDragHandler needs two valid DragPointerHandlers with hitPointInLocalSpace set.");return}if(this._tempVec1.copy(this.handlerA.hitPointInLocalSpace),this._tempVec2.copy(this.handlerB.hitPointInLocalSpace),this.gameObject.localToWorld(this._tempVec1),this.gameObject.localToWorld(this._tempVec2),n&&(n.worldToLocal(this._tempVec1),n.worldToLocal(this._tempVec2)),this._initialDistance=this._tempVec1.distanceTo(this._tempVec2),this._initialDistance<.02?(va&&console.log("Finding alternative drag attachment points since initial distance is too low: "+this._initialDistance.toFixed(2)),this.handlerA.followObject.parent.getWorldPosition(this._tempVec1),this.handlerB.followObject.parent.getWorldPosition(this._tempVec2),this._handlerAAttachmentPoint.copy(this._tempVec1),this._handlerBAttachmentPoint.copy(this._tempVec2),this.gameObject.worldToLocal(this._handlerAAttachmentPoint),this.gameObject.worldToLocal(this._handlerBAttachmentPoint),this._initialDistance=this._tempVec1.distanceTo(this._tempVec2),this._initialDistance<.001&&(console.warn("Not supported right now \u2013 controller drag points for multitouch are too close!"),this._initialDistance=1)):(this._handlerAAttachmentPoint.copy(this.handlerA.hitPointInLocalSpace),this._handlerBAttachmentPoint.copy(this.handlerB.hitPointInLocalSpace)),this._tempVec3.lerpVectors(this._tempVec1,this._tempVec2,.5),this._initialScale.copy(e.scale),va){this._followObject.add(new _o(2)),this._manipulatorObject.add(new _o(5));const a=r=>`${r.x.toFixed(2)}, ${r.y.toFixed(2)}, ${r.z.toFixed(2)}`;pe.DrawLine(this._tempVec1,this._tempVec2,65535,0,!1),pe.DrawLabel(this._tempVec3,"A:B "+this._initialDistance.toFixed(2)+`
6214
6214
  `+a(this._tempVec1)+`
6215
- `+a(this._tempVec2),.03,5)}}onDragStart(A){this.gameObject.add(this._followObject),this._followObject.matrixAutoUpdate=!1,this._followObject.matrix.identity(),this._deviceMode=A.mode,this._followObjectStartWorldQuaternion.copy(this._followObject.worldQuaternion),this.alignManipulator(),this._manipulatorObject.attach(this._followObject),this._manipulatorPosOffset.copy(this._followObject.position),this._manipulatorRotOffset.copy(this._followObject.quaternion),this._manipulatorScaleOffset.copy(this._followObject.scale)}onDragEnd(A){if(!this.handlerA||!this.handlerB){console.error("onDragEnd called on MultiTouchDragHandler without valid handlers. This is likely a bug.");return}this.handlerA.recenter(),this.handlerB.recenter(),this._manipulatorObject.removeFromParent(),this._followObject.removeFromParent(),this._manipulatorObject.destroy(),this._followObject.destroy()}alignManipulator(){if(!this.handlerA||!this.handlerB){console.error("alignManipulator called on MultiTouchDragHandler without valid handlers. This is likely a bug.",this);return}if(!this.handlerA.followObject||!this.handlerB.followObject){console.error("alignManipulator called on MultiTouchDragHandler without valid follow objects. This is likely a bug.",this.handlerA,this.handlerB);return}this._tempVec1.copy(this._handlerAAttachmentPoint),this._tempVec2.copy(this._handlerBAttachmentPoint),this.handlerA.followObject.localToWorld(this._tempVec1),this.handlerB.followObject.localToWorld(this._tempVec2),this._tempVec3.lerpVectors(this._tempVec1,this._tempVec2,.5),this._manipulatorObject.position.copy(this._tempVec3);const A=this.context.mainCamera;this.tempLookMatrix.lookAt(this._tempVec3,this._tempVec2,A.worldUp),this._manipulatorObject.quaternion.setFromRotationMatrix(this.tempLookMatrix);const e=this._tempVec1.distanceTo(this._tempVec2);this._manipulatorObject.scale.copy(this._initialScale).multiplyScalar(e/this._initialDistance),this._manipulatorObject.updateMatrix(),this._manipulatorObject.updateMatrixWorld(!0),va&&(pe.DrawLabel(this._tempVec3.clone().add(new S(0,.2,0)),"A:B "+e.toFixed(2),.03),pe.DrawLine(this._tempVec1,this._tempVec2,65280,0,!1))}onDragUpdate(){this.alignManipulator();const A=30,e=1;this._followObject.position.copy(this._manipulatorPosOffset),this._followObject.quaternion.copy(this._manipulatorRotOffset),this._followObject.scale.copy(this._manipulatorScaleOffset);const g=this.gameObject,I=this._followObject;I.updateMatrix(),I.updateMatrixWorld(!0);const o=this._deviceMode==="tracked-pointer"||this._deviceMode==="transient-pointer"?this.settings.xrKeepRotation:this.settings.keepRotation;if(this.settings.snapGridResolution>0){const C=this._followObject.worldPosition,Q=this.settings.snapGridResolution;C.x=Math.round(C.x/Q)*Q,C.y=Math.round(C.y/Q)*Q,C.z=Math.round(C.z/Q)*Q,this._followObject.worldPosition=C,this._followObject.updateMatrix()}o&&(this._followObject.worldQuaternion=this._followObjectStartWorldQuaternion,this._followObject.updateMatrix());const s=ge.clamp01(this.context.time.deltaTime*A*e),n=g.worldPosition;n.lerp(I.worldPosition,s),g.worldPosition=n;const a=g.worldQuaternion;a.slerp(I.worldQuaternion,s),g.worldQuaternion=a;const r=g.worldScale;r.lerp(I.worldScale,s),g.worldScale=r}setTargetObject(A){this.gameObject=A}}class suA{constructor(A,e){B(this,"context"),B(this,"gameObject"),B(this,"settings"),B(this,"_lastRig"),B(this,"_followObject"),B(this,"_totalMovement",new S),B(this,"_totalMovementAlongRayDirection",0),B(this,"_grabStartDistance",0),B(this,"_deviceMode"),B(this,"_followObjectStartPosition",new S),B(this,"_followObjectStartQuaternion",new GA),B(this,"_followObjectStartWorldQuaternion",new GA),B(this,"_lastDragPosRigSpace"),B(this,"_tempVec",new S),B(this,"_tempMat",new DA),B(this,"_hitPointInLocalSpace",new S),B(this,"_hitNormalInLocalSpace",new S),B(this,"_bottomCenter",new S),B(this,"_backCenter",new S),B(this,"_backBottomCenter",new S),B(this,"_bounds",new kt),B(this,"_dragPlane",new SI(new S(0,1,0))),B(this,"_draggedOverObject",null),B(this,"_draggedOverObjectLastSetUp",null),B(this,"_draggedOverObjectLastNormal",new S),B(this,"_draggedOverObjectDuration",0),this.settings=A,this.context=A.context,this.gameObject=e,this._followObject=new wA}getTotalMovement(){return this._totalMovement}get followObject(){return this._followObject}get hitPointInLocalSpace(){return this._hitPointInLocalSpace}setTargetObject(A){this.gameObject=A}recenter(){var A,e;if(!this._followObject.parent){console.warn("Error: space follow object doesn't have parent but recenter() is called. This is likely a bug");return}const g=this._followObject.parent;this.gameObject.add(this._followObject),this._followObject.matrixAutoUpdate=!1,this._followObject.position.set(0,0,0),this._followObject.quaternion.set(0,0,0,1),this._followObject.scale.set(1,1,1),this._followObject.updateMatrix(),this._followObject.updateMatrixWorld(!0),g.attach(this._followObject),this._followObjectStartPosition.copy(this._followObject.position),this._followObjectStartQuaternion.copy(this._followObject.quaternion),this._followObjectStartWorldQuaternion.copy(this._followObject.worldQuaternion),this._followObject.updateMatrix(),this._followObject.updateMatrixWorld(!0);const I=this._hitPointInLocalSpace.clone();this.gameObject.localToWorld(I),this._grabStartDistance=I.distanceTo(g.worldPosition);const o=(e=(A=me.active)==null?void 0:A.rig)==null?void 0:e.gameObject,s=o?.worldScale.x||1;this._grabStartDistance/=s,this._totalMovementAlongRayDirection=0,this._lastDragPosRigSpace=void 0,va&&(pe.DrawLine(I,g.worldPosition,65280,.5,!1),pe.DrawLabel(g.worldPosition.add(new S(0,.1,0)),this._grabStartDistance.toFixed(2),.03,.5))}onDragStart(A){if(A.event.space.add(this._followObject),this._lastDragPosRigSpace=void 0,A.point&&A.normal)this._hitPointInLocalSpace.copy(A.point),this.gameObject.worldToLocal(this._hitPointInLocalSpace),this._hitNormalInLocalSpace.copy(A.normal);else if(A){const E=A.event.space,c=E.worldPosition;this.gameObject.worldToLocal(c),this._hitPointInLocalSpace.copy(c);const l=E.worldUp;this._tempMat.copy(this.gameObject.matrixWorld).invert(),l.transformDirection(this._tempMat),this._hitNormalInLocalSpace.copy(l)}this.recenter(),this._totalMovement.set(0,0,0),this._deviceMode=A.mode;const e=this._followObject.parent.worldForward,g=this._deviceMode==="tracked-pointer"||this._deviceMode==="transient-pointer"?this.settings.xrDragMode:this.settings.dragMode,I=this._hitPointInLocalSpace.clone();switch(this.gameObject.localToWorld(I),g){case 0:const E=new S(0,1,0);this.gameObject.parent&&E.transformDirection(this.gameObject.parent.matrixWorld.clone().invert()),this._dragPlane.setFromNormalAndCoplanarPoint(E,I);break;case 2:const c=this._hitNormalInLocalSpace.clone();c.transformDirection(this.gameObject.matrixWorld),this._dragPlane.setFromNormalAndCoplanarPoint(c,I);break;case 1:this._dragPlane.setFromNormalAndCoplanarPoint(e,I);break;case 3:const l=new S(0,1,0),d=e,u=l.angleTo(d),D=.5;u>Math.PI/2+D||u<Math.PI/2-D?this._dragPlane.setFromNormalAndCoplanarPoint(new S(0,1,0),I):this._dragPlane.setFromNormalAndCoplanarPoint(e,I);break}const o=this.gameObject.parent,s=this.gameObject.position.clone(),n=this.gameObject.quaternion.clone(),a=this.gameObject.scale.clone(),r=this.gameObject.matrixWorld.clone();o&&o.remove(this.gameObject),this.gameObject.position.set(0,0,0),this.gameObject.quaternion.set(0,0,0,1),this.gameObject.scale.set(1,1,1);const C=$n([this.gameObject]);C.expandByPoint(this.gameObject.worldPosition);const Q=new S;C.getCenter(Q);const h=new S;C.getSize(h),this._bottomCenter.copy(Q.clone().add(new S(0,-h.y/2,0))),this._backCenter.copy(Q.clone().add(new S(0,0,h.z/2))),this._backBottomCenter.copy(Q.clone().add(new S(0,-h.y/2,h.z/2))),this._bounds.copy(C),o&&o.add(this.gameObject),this.gameObject.position.copy(s),this.gameObject.quaternion.copy(n),this.gameObject.scale.copy(a),this.gameObject.matrixWorld.copy(r),this._draggedOverObject=null,this._draggedOverObjectLastSetUp=null,this._draggedOverObjectLastNormal.set(0,1,0),this._draggedOverObjectDuration=0}collectMovementInfo(){var A,e;if(!this._followObject.parent)return;const g=this._followObject.parent;this._followObject.updateMatrix();const I=g.worldPosition,o=(e=(A=me.active)==null?void 0:A.rig)==null?void 0:e.gameObject;o&&o.worldToLocal(I),(this._lastDragPosRigSpace===void 0||o!=this._lastRig)&&(this._lastDragPosRigSpace=I.clone(),this._lastRig=o),this._tempVec.copy(I).sub(this._lastDragPosRigSpace);const s=g.worldForward;if(o&&(this._tempMat.copy(o.matrixWorld).invert(),s.transformDirection(this._tempMat)),this._totalMovementAlongRayDirection+=s.dot(this._tempVec),this._tempVec.x=Math.abs(this._tempVec.x),this._tempVec.y=Math.abs(this._tempVec.y),this._tempVec.z=Math.abs(this._tempVec.z),this._totalMovement.add(this._tempVec),this._lastDragPosRigSpace.copy(I),va){let n=I;o&&(n=n.clone(),n.transformDirection(o.matrixWorld)),pe.DrawRay(n,s,255)}}onDragUpdate(A){if(A>1)return;const e=this.gameObject,g=this._followObject.parent;this._followObject.updateMatrix();const I=g.worldPosition,o=g.worldForward,s=this._deviceMode==="tracked-pointer"||this._deviceMode==="transient-pointer",n=s?this.settings.xrKeepRotation:this.settings.keepRotation,a=s?this.settings.xrDragMode:this.settings.dragMode;if(a===5)return;const r=10;n&&(this._followObject.worldQuaternion=this._followObjectStartWorldQuaternion),this._followObject.updateMatrix(),this._followObject.updateMatrixWorld(!0);let C=1,Q=2;if(s&&this._grabStartDistance>.5){const d=1+this._totalMovementAlongRayDirection*(2*this.settings.xrDistanceDragFactor);C=Math.max(0,d),C=C*C*C}else this._grabStartDistance<=.5&&(Q=3);this._followObject.position.copy(this._followObjectStartPosition),n||this._followObject.quaternion.copy(this._followObjectStartQuaternion),this._followObject.position.multiplyScalar(C),this._followObject.updateMatrix();const h=new po(I,o);if(a==4){const d=new fn;d.testObject=D=>D!==this.followObject&&D!==g&&D!==e;const u=this.context.physics.raycastFromRay(h,d);if(u.length>0){const D=u[0];if(this._draggedOverObject===D.object?this._draggedOverObjectDuration+=this.context.time.deltaTime:(this._draggedOverObject=D.object,this._draggedOverObjectDuration=0),D.face){const p=this._draggedOverObjectDuration>=.15,w=.001,f=this._totalMovement.length()>=w;if((p||f)&&(this._draggedOverObjectLastSetUp!==this._draggedOverObject||this._draggedOverObjectLastNormal.dot(D.face.normal)<.999999||this.context.time.frame%60===0)){this._draggedOverObjectLastSetUp=this._draggedOverObject,this._draggedOverObjectLastNormal.copy(D.face.normal);const G=lt(),M=lt();this._bounds.getCenter(G),this._bounds.getSize(M),G.sub(M.multiplyScalar(.5).multiply(D.face.normal)),this._hitPointInLocalSpace.copy(G),this._hitNormalInLocalSpace.copy(D.face.normal),this._bounds.getCenter(G),this._bounds.getSize(M),G.add(M.multiplyScalar(.5).multiply(D.face.normal));const U=lt(this._hitPointInLocalSpace).add(G);this._followObject.localToWorld(U);const v=D.point;this._dragPlane.setFromNormalAndCoplanarPoint(D.face.normal,v)}else if(!(p||f))return}}}if(a!==1&&h.intersectPlane(this._dragPlane,this._tempVec)){this._followObject.worldPosition=this._tempVec,this._followObject.updateMatrix(),this._followObject.updateMatrixWorld(!0);const d=this._hitPointInLocalSpace.clone();this._followObject.localToWorld(d),va&&pe.DrawLine(d,this._tempVec,65535,0,!1),this._followObject.worldPosition=this._tempVec.multiplyScalar(2).sub(d),this._followObject.updateMatrix(),this._followObject.updateMatrix()}if(this.settings.snapGridResolution>0){const d=this._followObject.worldPosition,u=this.settings.snapGridResolution;d.x=Math.round(d.x/u)*u,d.y=Math.round(d.y/u)*u,d.z=Math.round(d.z/u)*u,this._followObject.worldPosition=d,this._followObject.updateMatrix()}n&&(this._followObject.worldQuaternion=this._followObjectStartWorldQuaternion,this._followObject.updateMatrix());const E=ge.clamp01(this.context.time.deltaTime*r*Q),c=e.worldPosition;c.lerp(this._followObject.worldPosition,E),e.worldPosition=c;const l=e.worldQuaternion;if(l.slerp(this._followObject.worldQuaternion,E),e.worldQuaternion=l,va){const d=this._hitPointInLocalSpace.clone();e.localToWorld(d),pe.DrawSphere(d,.02,16711680);const u=this._hitNormalInLocalSpace.clone();u.applyQuaternion(l),pe.DrawRay(d,u,16711680),pe.DrawLabel(c.add(new S(0,.25,0)),`Distance: ${this._totalMovement.length().toFixed(2)}
6215
+ `+a(this._tempVec2),.03,5)}}onDragStart(A){this.gameObject.add(this._followObject),this._followObject.matrixAutoUpdate=!1,this._followObject.matrix.identity(),this._deviceMode=A.mode,this._followObjectStartWorldQuaternion.copy(this._followObject.worldQuaternion),this.alignManipulator(),this._manipulatorObject.attach(this._followObject),this._manipulatorPosOffset.copy(this._followObject.position),this._manipulatorRotOffset.copy(this._followObject.quaternion),this._manipulatorScaleOffset.copy(this._followObject.scale)}onDragEnd(A){if(!this.handlerA||!this.handlerB){console.error("onDragEnd called on MultiTouchDragHandler without valid handlers. This is likely a bug.");return}this.handlerA.recenter(),this.handlerB.recenter(),this._manipulatorObject.removeFromParent(),this._followObject.removeFromParent(),this._manipulatorObject.destroy(),this._followObject.destroy()}alignManipulator(){if(!this.handlerA||!this.handlerB){console.error("alignManipulator called on MultiTouchDragHandler without valid handlers. This is likely a bug.",this);return}if(!this.handlerA.followObject||!this.handlerB.followObject){console.error("alignManipulator called on MultiTouchDragHandler without valid follow objects. This is likely a bug.",this.handlerA,this.handlerB);return}this._tempVec1.copy(this._handlerAAttachmentPoint),this._tempVec2.copy(this._handlerBAttachmentPoint),this.handlerA.followObject.localToWorld(this._tempVec1),this.handlerB.followObject.localToWorld(this._tempVec2),this._tempVec3.lerpVectors(this._tempVec1,this._tempVec2,.5),this._manipulatorObject.position.copy(this._tempVec3);const A=this.context.mainCamera;this.tempLookMatrix.lookAt(this._tempVec3,this._tempVec2,A.worldUp),this._manipulatorObject.quaternion.setFromRotationMatrix(this.tempLookMatrix);const e=this._tempVec1.distanceTo(this._tempVec2);this._manipulatorObject.scale.copy(this._initialScale).multiplyScalar(e/this._initialDistance),this._manipulatorObject.updateMatrix(),this._manipulatorObject.updateMatrixWorld(!0),va&&(pe.DrawLabel(this._tempVec3.clone().add(new S(0,.2,0)),"A:B "+e.toFixed(2),.03),pe.DrawLine(this._tempVec1,this._tempVec2,65280,0,!1))}onDragUpdate(){this.alignManipulator();const A=30,e=1;this._followObject.position.copy(this._manipulatorPosOffset),this._followObject.quaternion.copy(this._manipulatorRotOffset),this._followObject.scale.copy(this._manipulatorScaleOffset);const g=this.gameObject,I=this._followObject;I.updateMatrix(),I.updateMatrixWorld(!0);const o=this._deviceMode==="tracked-pointer"||this._deviceMode==="transient-pointer"?this.settings.xrKeepRotation:this.settings.keepRotation;if(this.settings.snapGridResolution>0){const C=this._followObject.worldPosition,Q=this.settings.snapGridResolution;C.x=Math.round(C.x/Q)*Q,C.y=Math.round(C.y/Q)*Q,C.z=Math.round(C.z/Q)*Q,this._followObject.worldPosition=C,this._followObject.updateMatrix()}o&&(this._followObject.worldQuaternion=this._followObjectStartWorldQuaternion,this._followObject.updateMatrix());const s=ge.clamp01(this.context.time.deltaTime*A*e),n=g.worldPosition;n.lerp(I.worldPosition,s),g.worldPosition=n;const a=g.worldQuaternion;a.slerp(I.worldQuaternion,s),g.worldQuaternion=a;const r=g.worldScale;r.lerp(I.worldScale,s),g.worldScale=r}setTargetObject(A){this.gameObject=A}}class suA{constructor(A,e){B(this,"context"),B(this,"gameObject"),B(this,"settings"),B(this,"_lastRig"),B(this,"_followObject"),B(this,"_totalMovement",new S),B(this,"_totalMovementAlongRayDirection",0),B(this,"_grabStartDistance",0),B(this,"_deviceMode"),B(this,"_followObjectStartPosition",new S),B(this,"_followObjectStartQuaternion",new GA),B(this,"_followObjectStartWorldQuaternion",new GA),B(this,"_lastDragPosRigSpace"),B(this,"_tempVec",new S),B(this,"_tempMat",new DA),B(this,"_hitPointInLocalSpace",new S),B(this,"_hitNormalInLocalSpace",new S),B(this,"_bottomCenter",new S),B(this,"_backCenter",new S),B(this,"_backBottomCenter",new S),B(this,"_bounds",new kt),B(this,"_dragPlane",new SI(new S(0,1,0))),B(this,"_draggedOverObject",null),B(this,"_draggedOverObjectLastSetUp",null),B(this,"_draggedOverObjectLastNormal",new S),B(this,"_draggedOverObjectDuration",0),this.settings=A,this.context=A.context,this.gameObject=e,this._followObject=new wA}getTotalMovement(){return this._totalMovement}get followObject(){return this._followObject}get hitPointInLocalSpace(){return this._hitPointInLocalSpace}setTargetObject(A){this.gameObject=A}recenter(){var A,e;if(!this._followObject.parent){console.warn("Error: space follow object doesn't have parent but recenter() is called. This is likely a bug");return}const g=this._followObject.parent;this.gameObject.add(this._followObject),this._followObject.matrixAutoUpdate=!1,this._followObject.position.set(0,0,0),this._followObject.quaternion.set(0,0,0,1),this._followObject.scale.set(1,1,1),this._followObject.updateMatrix(),this._followObject.updateMatrixWorld(!0),g.attach(this._followObject),this._followObjectStartPosition.copy(this._followObject.position),this._followObjectStartQuaternion.copy(this._followObject.quaternion),this._followObjectStartWorldQuaternion.copy(this._followObject.worldQuaternion),this._followObject.updateMatrix(),this._followObject.updateMatrixWorld(!0);const I=this._hitPointInLocalSpace.clone();this.gameObject.localToWorld(I),this._grabStartDistance=I.distanceTo(g.worldPosition);const o=(e=(A=me.active)==null?void 0:A.rig)==null?void 0:e.gameObject,s=o?.worldScale.x||1;this._grabStartDistance/=s,this._totalMovementAlongRayDirection=0,this._lastDragPosRigSpace=void 0,va&&(pe.DrawLine(I,g.worldPosition,65280,.5,!1),pe.DrawLabel(g.worldPosition.add(new S(0,.1,0)),this._grabStartDistance.toFixed(2),.03,.5))}onDragStart(A){if(A.event.space.add(this._followObject),this._lastDragPosRigSpace=void 0,A.point&&A.normal)this._hitPointInLocalSpace.copy(A.point),this.gameObject.worldToLocal(this._hitPointInLocalSpace),this._hitNormalInLocalSpace.copy(A.normal);else if(A){const E=A.event.space,c=E.worldPosition;this.gameObject.worldToLocal(c),this._hitPointInLocalSpace.copy(c);const l=E.worldUp;this._tempMat.copy(this.gameObject.matrixWorld).invert(),l.transformDirection(this._tempMat),this._hitNormalInLocalSpace.copy(l)}this.recenter(),this._totalMovement.set(0,0,0),this._deviceMode=A.mode;const e=this._followObject.parent.worldForward,g=this._deviceMode==="tracked-pointer"||this._deviceMode==="transient-pointer"?this.settings.xrDragMode:this.settings.dragMode,I=this._hitPointInLocalSpace.clone();switch(this.gameObject.localToWorld(I),g){case 0:const E=new S(0,1,0);this.gameObject.parent&&E.transformDirection(this.gameObject.parent.matrixWorld.clone().invert()),this._dragPlane.setFromNormalAndCoplanarPoint(E,I);break;case 2:const c=this._hitNormalInLocalSpace.clone();c.transformDirection(this.gameObject.matrixWorld),this._dragPlane.setFromNormalAndCoplanarPoint(c,I);break;case 1:this._dragPlane.setFromNormalAndCoplanarPoint(e,I);break;case 4:case 3:const l=new S(0,1,0),d=e,u=l.angleTo(d),D=.5;u>Math.PI/2+D||u<Math.PI/2-D?this._dragPlane.setFromNormalAndCoplanarPoint(new S(0,1,0),I):this._dragPlane.setFromNormalAndCoplanarPoint(e,I);break}const o=this.gameObject.parent,s=this.gameObject.position.clone(),n=this.gameObject.quaternion.clone(),a=this.gameObject.scale.clone(),r=this.gameObject.matrixWorld.clone();o&&o.remove(this.gameObject),this.gameObject.position.set(0,0,0),this.gameObject.quaternion.set(0,0,0,1),this.gameObject.scale.set(1,1,1);const C=$n([this.gameObject]);C.expandByPoint(this.gameObject.worldPosition);const Q=new S;C.getCenter(Q);const h=new S;C.getSize(h),this._bottomCenter.copy(Q.clone().add(new S(0,-h.y/2,0))),this._backCenter.copy(Q.clone().add(new S(0,0,h.z/2))),this._backBottomCenter.copy(Q.clone().add(new S(0,-h.y/2,h.z/2))),this._bounds.copy(C),o&&o.add(this.gameObject),this.gameObject.position.copy(s),this.gameObject.quaternion.copy(n),this.gameObject.scale.copy(a),this.gameObject.matrixWorld.copy(r),this._draggedOverObject=null,this._draggedOverObjectLastSetUp=null,this._draggedOverObjectLastNormal.set(0,1,0),this._draggedOverObjectDuration=0}collectMovementInfo(){var A,e;if(!this._followObject.parent)return;const g=this._followObject.parent;this._followObject.updateMatrix();const I=g.worldPosition,o=(e=(A=me.active)==null?void 0:A.rig)==null?void 0:e.gameObject;o&&o.worldToLocal(I),(this._lastDragPosRigSpace===void 0||o!=this._lastRig)&&(this._lastDragPosRigSpace=I.clone(),this._lastRig=o),this._tempVec.copy(I).sub(this._lastDragPosRigSpace);const s=g.worldForward;if(o&&(this._tempMat.copy(o.matrixWorld).invert(),s.transformDirection(this._tempMat)),this._totalMovementAlongRayDirection+=s.dot(this._tempVec),this._tempVec.x=Math.abs(this._tempVec.x),this._tempVec.y=Math.abs(this._tempVec.y),this._tempVec.z=Math.abs(this._tempVec.z),this._totalMovement.add(this._tempVec),this._lastDragPosRigSpace.copy(I),va){let n=I;o&&(n=n.clone(),n.transformDirection(o.matrixWorld)),pe.DrawRay(n,s,255)}}onDragUpdate(A){if(A>1)return;const e=this.gameObject,g=this._followObject.parent;this._followObject.updateMatrix();const I=g.worldPosition,o=g.worldForward,s=this._deviceMode==="tracked-pointer"||this._deviceMode==="transient-pointer",n=s?this.settings.xrKeepRotation:this.settings.keepRotation,a=s?this.settings.xrDragMode:this.settings.dragMode;if(a===5)return;const r=10;n&&(this._followObject.worldQuaternion=this._followObjectStartWorldQuaternion),this._followObject.updateMatrix(),this._followObject.updateMatrixWorld(!0);let C=1,Q=2;if(s&&this._grabStartDistance>.5){const d=1+this._totalMovementAlongRayDirection*(2*this.settings.xrDistanceDragFactor);C=Math.max(0,d),C=C*C*C}else this._grabStartDistance<=.5&&(Q=3);this._followObject.position.copy(this._followObjectStartPosition),n||this._followObject.quaternion.copy(this._followObjectStartQuaternion),this._followObject.position.multiplyScalar(C),this._followObject.updateMatrix();const h=new po(I,o);if(a==4){const d=new fn;d.testObject=D=>D!==this.followObject&&D!==g&&D!==e;const u=this.context.physics.raycastFromRay(h,d);if(u.length>0){const D=u[0];if(this._draggedOverObject===D.object?this._draggedOverObjectDuration+=this.context.time.deltaTime:(this._draggedOverObject=D.object,this._draggedOverObjectDuration=0),D.face){const p=this._draggedOverObjectDuration>=.15,w=.001,f=this._totalMovement.length()>=w;if((p||f)&&(this._draggedOverObjectLastSetUp!==this._draggedOverObject||this._draggedOverObjectLastNormal.dot(D.face.normal)<.999999||this.context.time.frame%60===0)){this._draggedOverObjectLastSetUp=this._draggedOverObject,this._draggedOverObjectLastNormal.copy(D.face.normal);const G=lt(),M=lt();this._bounds.getCenter(G),this._bounds.getSize(M),G.sub(M.multiplyScalar(.5).multiply(D.face.normal)),this._hitPointInLocalSpace.copy(G),this._hitNormalInLocalSpace.copy(D.face.normal),this._bounds.getCenter(G),this._bounds.getSize(M),G.add(M.multiplyScalar(.5).multiply(D.face.normal));const U=lt(this._hitPointInLocalSpace).add(G);this._followObject.localToWorld(U);const v=D.point;this._dragPlane.setFromNormalAndCoplanarPoint(D.face.normal,v)}else if(!(p||f))return}}}if(a!==1&&h.intersectPlane(this._dragPlane,this._tempVec)){this._followObject.worldPosition=this._tempVec,this._followObject.updateMatrix(),this._followObject.updateMatrixWorld(!0);const d=this._hitPointInLocalSpace.clone();this._followObject.localToWorld(d),va&&pe.DrawLine(d,this._tempVec,65535,0,!1),this._followObject.worldPosition=this._tempVec.multiplyScalar(2).sub(d),this._followObject.updateMatrix(),this._followObject.updateMatrix()}if(this.settings.snapGridResolution>0){const d=this._followObject.worldPosition,u=this.settings.snapGridResolution;d.x=Math.round(d.x/u)*u,d.y=Math.round(d.y/u)*u,d.z=Math.round(d.z/u)*u,this._followObject.worldPosition=d,this._followObject.updateMatrix()}n&&(this._followObject.worldQuaternion=this._followObjectStartWorldQuaternion,this._followObject.updateMatrix());const E=ge.clamp01(this.context.time.deltaTime*r*Q),c=e.worldPosition;c.lerp(this._followObject.worldPosition,E),e.worldPosition=c;const l=e.worldQuaternion;if(l.slerp(this._followObject.worldQuaternion,E),e.worldQuaternion=l,va){const d=this._hitPointInLocalSpace.clone();e.localToWorld(d),pe.DrawSphere(d,.02,16711680);const u=this._hitNormalInLocalSpace.clone();u.applyQuaternion(l),pe.DrawRay(d,u,16711680),pe.DrawLabel(c.add(new S(0,.25,0)),`Distance: ${this._totalMovement.length().toFixed(2)}
6216
6216
 
6217
6217
  Along Ray: ${this._totalMovementAlongRayDirection.toFixed(2)}
6218
6218