@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.
- package/CHANGELOG.md +10 -0
- package/dist/needle-engine.js +13 -8
- package/dist/needle-engine.light.js +13 -8
- package/dist/needle-engine.light.min.js +6 -6
- package/dist/needle-engine.light.umd.cjs +6 -6
- package/dist/needle-engine.min.js +6 -6
- package/dist/needle-engine.umd.cjs +6 -6
- package/lib/engine/engine_input.d.ts +5 -0
- package/lib/engine/engine_input.js +7 -0
- package/lib/engine/engine_input.js.map +1 -1
- package/lib/engine/engine_physics.js +3 -0
- package/lib/engine/engine_physics.js.map +1 -1
- package/lib/engine/xr/NeedleXRSession.js +1 -1
- package/lib/engine/xr/NeedleXRSession.js.map +1 -1
- package/lib/engine-components/DragControls.js +9 -0
- package/lib/engine-components/DragControls.js.map +1 -1
- package/lib/engine-components/ui/Raycaster.js +1 -1
- package/lib/engine-components/ui/Raycaster.js.map +1 -1
- package/package.json +2 -2
- package/plugins/common/license.cjs +1 -1
- package/plugins/types/userconfig.d.ts +6 -0
- package/plugins/vite/alias.js +38 -17
- package/src/engine/engine_input.ts +9 -0
- package/src/engine/engine_physics.ts +2 -0
- package/src/engine/xr/NeedleXRSession.ts +1 -1
- package/src/engine-components/DragControls.ts +10 -0
- package/src/engine-components/ui/Raycaster.ts +1 -1
|
@@ -4344,7 +4344,7 @@ Open this page to get the console: `+e.toString())}const s=qa()||H1()&<();if((
|
|
|
4344
4344
|
#__vconsole .vc-mask {
|
|
4345
4345
|
overflow: hidden;
|
|
4346
4346
|
}
|
|
4347
|
-
`,Qo==null||Qo.prepend(i),s===!0&&dD()<=0&&L5(),console.log("🌵 Debug console has loaded")}},e.src="https://unpkg.com/vconsole@latest/dist/vconsole.min.js",document.body.appendChild(e)}function rne(){const s=new VConsole.VConsolePlugin("needle-console","🌵 Inspect glTF"),e=()=>document.querySelector("#__vc_plug_"+s._id+" iframe");return s.on("renderTab",function(t){const i=globalThis["needle:codegen_files"];if(!i||i.length===0)return;let n=globalThis["needle:codegen_files"][0];const r=n.indexOf("?");r>-1&&(n=n.substring(0,r));const a=location.protocol+"//"+location.host+location.pathname+"/"+n,l=encodeURIComponent(a);s.fullUrl="https://viewer.needle.tools?inspect&file="+l;var c='<iframe src="" style="width: 100%; height: 99%; border: none;"></iframe>';t(c)}),s.on("show",function(){const t=e();t&&t.src!==s.fullUrl&&(t.src=s.fullUrl)}),s.on("hide",function(){const t=e();t&&(t.src="")}),s.on("addTopBar",function(t){var i=new Array;i.push({name:"Open in new window ↗",onClick:function(n){window.open(s.fullUrl,"_blank"),Ko==null||Ko.hide()}}),i.push({name:"Reload",onClick:function(n){const r=e();r&&(r.src=s.fullUrl)}}),i.push({name:"Fullscreen",onClick:function(n){const r=e();r.requestFullscreen?r.requestFullscreen():r.webkitRequestFullscreen instanceof Function&&r.webkitRequestFullscreen()}}),t(i)}),s}function one(){const s=document.querySelector("#__vconsole .vc-switch");return s||null}function ane(){const s=document.querySelector("#__vconsole");return s||null}const U5=ie("debugdefines");Iy('if(!globalThis[""3.45.2-beta.
|
|
4347
|
+
`,Qo==null||Qo.prepend(i),s===!0&&dD()<=0&&L5(),console.log("🌵 Debug console has loaded")}},e.src="https://unpkg.com/vconsole@latest/dist/vconsole.min.js",document.body.appendChild(e)}function rne(){const s=new VConsole.VConsolePlugin("needle-console","🌵 Inspect glTF"),e=()=>document.querySelector("#__vc_plug_"+s._id+" iframe");return s.on("renderTab",function(t){const i=globalThis["needle:codegen_files"];if(!i||i.length===0)return;let n=globalThis["needle:codegen_files"][0];const r=n.indexOf("?");r>-1&&(n=n.substring(0,r));const a=location.protocol+"//"+location.host+location.pathname+"/"+n,l=encodeURIComponent(a);s.fullUrl="https://viewer.needle.tools?inspect&file="+l;var c='<iframe src="" style="width: 100%; height: 99%; border: none;"></iframe>';t(c)}),s.on("show",function(){const t=e();t&&t.src!==s.fullUrl&&(t.src=s.fullUrl)}),s.on("hide",function(){const t=e();t&&(t.src="")}),s.on("addTopBar",function(t){var i=new Array;i.push({name:"Open in new window ↗",onClick:function(n){window.open(s.fullUrl,"_blank"),Ko==null||Ko.hide()}}),i.push({name:"Reload",onClick:function(n){const r=e();r&&(r.src=s.fullUrl)}}),i.push({name:"Fullscreen",onClick:function(n){const r=e();r.requestFullscreen?r.requestFullscreen():r.webkitRequestFullscreen instanceof Function&&r.webkitRequestFullscreen()}}),t(i)}),s}function one(){const s=document.querySelector("#__vconsole .vc-switch");return s||null}function ane(){const s=document.querySelector("#__vconsole");return s||null}const U5=ie("debugdefines");Iy('if(!globalThis[""3.45.2-beta.4""]) globalThis[""3.45.2-beta.4""] = "0.0.0";');Iy('if(!globalThis[""undefined""]) globalThis[""undefined""] = "unknown";');Iy('if(!globalThis[""Fri Jul 19 2024 19:15:17 GMT+0200 (Central European Summer Time)""]) globalThis[""Fri Jul 19 2024 19:15:17 GMT+0200 (Central European Summer Time)""] = "unknown";');Iy('globalThis["__NEEDLE_ENGINE_VERSION__"] = "3.45.2-beta.4";');Iy('globalThis["__NEEDLE_ENGINE_GENERATOR__"] = "undefined";');Iy('globalThis["__NEEDLE_PROJECT_BUILD_TIME__"] = "Fri Jul 19 2024 19:15:17 GMT+0200 (Central European Summer Time)";');const La="3.45.2-beta.4",X1="undefined",qD="Fri Jul 19 2024 19:15:17 GMT+0200 (Central European Summer Time)";U5&&console.log(`Engine version: ${La} (generator: ${X1})
|
|
4348
4348
|
Project built at ${qD}`);const Oh="needle_isActiveInHierarchy",If="builtin_components",GA="needle_editor_guid";function Iy(s){try{(0,eval)(s)}catch(e){U5&&console.error(e)}}const lne='<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>',cne=btoa(lne),hne="data:image/svg+xml;base64,"+cne,une=hne,dne=`<?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(dne);const fne='<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>',pne=btoa(fne),mne="data:image/svg+xml;charset=utf-8;base64,"+pne,gne=mne,Pa=ie("debuglicense");let Zf="basic";Pa&&console.log("License Type: "+Zf);function ed(){switch(Zf){case"pro":case"enterprise":return!0}return!1}function XD(){switch(Zf){case"indie":return!0}return!1}function Lh(){return ed()||XD()}const N5=[];function yne(s){if(ed()||XD())return s(!0);N5.push(s)}function vne(s){for(const e of N5)try{e(s)}catch{}}di.registerCallback(Ii.ContextRegistered,s=>{bne(s.context),wne(),_ne(s.context)});let td,DP=!1,fA="";async function Ane(){if(td)return td;if(Zf==="basic")try{const s="https://engine.needle.tools/licensing/check?location="+encodeURIComponent(window.location.href)+"&version="+La+"&generator="+encodeURIComponent(X1),e=await fetch(s,{method:"GET"}).catch(t=>{Pa&&console.error("License check failed",t)});(e==null?void 0:e.status)===200?(DP=!1,Pa&&console.log("License check succeeded"),Zf="pro",vne(!0)):(e==null?void 0:e.status)===403?(DP=!0,fA=await e.text()):Pa&&console.log("License check failed with status "+(e==null?void 0:e.status))}catch(s){Pa&&console.error("License check failed",s)}else Pa&&console.log('Runtime license check is skipped because license is already applied as "'+Zf+'"')}td=Ane();async function _ne(s){function e(){const n=document.createElement("div");n.className="needle-forbidden",n.style.cssText=`
|
|
4349
4349
|
position: fixed;
|
|
4350
4350
|
top: 0;
|
|
@@ -5148,7 +5148,7 @@ in script ${i}.ts
|
|
|
5148
5148
|
*
|
|
5149
5149
|
* @author Feross Aboukhadijeh <https://feross.org>
|
|
5150
5150
|
* @license MIT
|
|
5151
|
-
*/var nue=function(s){return s!=null&&(PQ(s)||sue(s)||!!s._isBuffer)};function PQ(s){return!!s.constructor&&typeof s.constructor.isBuffer=="function"&&s.constructor.isBuffer(s)}function sue(s){return typeof s.readFloatLE=="function"&&typeof s.slice=="function"&&PQ(s.slice(0,0))}(function(){var s=iue,e=P3.utf8,t=nue,i=P3.bin,n=function(r,o){r.constructor==String?o&&o.encoding==="binary"?r=i.stringToBytes(r):r=e.stringToBytes(r):t(r)?r=Array.prototype.slice.call(r,0):!Array.isArray(r)&&r.constructor!==Uint8Array&&(r=r.toString());for(var a=s.bytesToWords(r),l=r.length*8,c=1732584193,h=-271733879,u=-1732584194,f=271733878,p=0;p<a.length;p++)a[p]=(a[p]<<8|a[p]>>>24)&16711935|(a[p]<<24|a[p]>>>8)&4278255360;a[l>>>5]|=128<<l%32,a[(l+64>>>9<<4)+14]=l;for(var m=n._ff,y=n._gg,g=n._hh,v=n._ii,p=0;p<a.length;p+=16){var _=c,A=h,b=u,S=f;c=m(c,h,u,f,a[p+0],7,-680876936),f=m(f,c,h,u,a[p+1],12,-389564586),u=m(u,f,c,h,a[p+2],17,606105819),h=m(h,u,f,c,a[p+3],22,-1044525330),c=m(c,h,u,f,a[p+4],7,-176418897),f=m(f,c,h,u,a[p+5],12,1200080426),u=m(u,f,c,h,a[p+6],17,-1473231341),h=m(h,u,f,c,a[p+7],22,-45705983),c=m(c,h,u,f,a[p+8],7,1770035416),f=m(f,c,h,u,a[p+9],12,-1958414417),u=m(u,f,c,h,a[p+10],17,-42063),h=m(h,u,f,c,a[p+11],22,-1990404162),c=m(c,h,u,f,a[p+12],7,1804603682),f=m(f,c,h,u,a[p+13],12,-40341101),u=m(u,f,c,h,a[p+14],17,-1502002290),h=m(h,u,f,c,a[p+15],22,1236535329),c=y(c,h,u,f,a[p+1],5,-165796510),f=y(f,c,h,u,a[p+6],9,-1069501632),u=y(u,f,c,h,a[p+11],14,643717713),h=y(h,u,f,c,a[p+0],20,-373897302),c=y(c,h,u,f,a[p+5],5,-701558691),f=y(f,c,h,u,a[p+10],9,38016083),u=y(u,f,c,h,a[p+15],14,-660478335),h=y(h,u,f,c,a[p+4],20,-405537848),c=y(c,h,u,f,a[p+9],5,568446438),f=y(f,c,h,u,a[p+14],9,-1019803690),u=y(u,f,c,h,a[p+3],14,-187363961),h=y(h,u,f,c,a[p+8],20,1163531501),c=y(c,h,u,f,a[p+13],5,-1444681467),f=y(f,c,h,u,a[p+2],9,-51403784),u=y(u,f,c,h,a[p+7],14,1735328473),h=y(h,u,f,c,a[p+12],20,-1926607734),c=g(c,h,u,f,a[p+5],4,-378558),f=g(f,c,h,u,a[p+8],11,-2022574463),u=g(u,f,c,h,a[p+11],16,1839030562),h=g(h,u,f,c,a[p+14],23,-35309556),c=g(c,h,u,f,a[p+1],4,-1530992060),f=g(f,c,h,u,a[p+4],11,1272893353),u=g(u,f,c,h,a[p+7],16,-155497632),h=g(h,u,f,c,a[p+10],23,-1094730640),c=g(c,h,u,f,a[p+13],4,681279174),f=g(f,c,h,u,a[p+0],11,-358537222),u=g(u,f,c,h,a[p+3],16,-722521979),h=g(h,u,f,c,a[p+6],23,76029189),c=g(c,h,u,f,a[p+9],4,-640364487),f=g(f,c,h,u,a[p+12],11,-421815835),u=g(u,f,c,h,a[p+15],16,530742520),h=g(h,u,f,c,a[p+2],23,-995338651),c=v(c,h,u,f,a[p+0],6,-198630844),f=v(f,c,h,u,a[p+7],10,1126891415),u=v(u,f,c,h,a[p+14],15,-1416354905),h=v(h,u,f,c,a[p+5],21,-57434055),c=v(c,h,u,f,a[p+12],6,1700485571),f=v(f,c,h,u,a[p+3],10,-1894986606),u=v(u,f,c,h,a[p+10],15,-1051523),h=v(h,u,f,c,a[p+1],21,-2054922799),c=v(c,h,u,f,a[p+8],6,1873313359),f=v(f,c,h,u,a[p+15],10,-30611744),u=v(u,f,c,h,a[p+6],15,-1560198380),h=v(h,u,f,c,a[p+13],21,1309151649),c=v(c,h,u,f,a[p+4],6,-145523070),f=v(f,c,h,u,a[p+11],10,-1120210379),u=v(u,f,c,h,a[p+2],15,718787259),h=v(h,u,f,c,a[p+9],21,-343485551),c=c+_>>>0,h=h+A>>>0,u=u+b>>>0,f=f+S>>>0}return s.endian([c,h,u,f])};n._ff=function(r,o,a,l,c,h,u){var f=r+(o&a|~o&l)+(c>>>0)+u;return(f<<h|f>>>32-h)+o},n._gg=function(r,o,a,l,c,h,u){var f=r+(o&l|a&~l)+(c>>>0)+u;return(f<<h|f>>>32-h)+o},n._hh=function(r,o,a,l,c,h,u){var f=r+(o^a^l)+(c>>>0)+u;return(f<<h|f>>>32-h)+o},n._ii=function(r,o,a,l,c,h,u){var f=r+(a^(o|~l))+(c>>>0)+u;return(f<<h|f>>>32-h)+o},n._blocksize=16,n._digestsize=16,IQ.exports=function(r,o){if(r==null)throw new Error("Illegal argument "+r);var a=s.wordsToBytes(n(r,o));return o&&o.asBytes?a:o&&o.asString?i.bytesToString(a):s.bytesToHex(a)}})();var rue=IQ.exports;const oue=cE(rue);class fB{constructor(e,t,i,n){d(this,"success");d(this,"filename");d(this,"hash");d(this,"size");d(this,"url");this.success=e,this.filename=t,this.hash=i,this.size=n}}async function BQ(s,e){const t=await s.arrayBuffer(),i=IO(t),n=s.name.split(".").pop(),r=i+"."+n,o=s.name.split(".").shift();console.assert(o!==void 0);const a={alias:o,filename:r},c=await(await fetch(e+"/exists",{method:"POST",body:JSON.stringify(a)})).json();if(c.success||console.warn("exists check did fail"),c.exists)return console.log("file already exists",i),new fB(!0,r,i,s.size);console.log("begin uploading file",o,s.size);const h=new FormData;h.append("file",s);const u={};u.filesize=s.size,o&&(u.alias=o);const p=await(await fetch(e+"/upload/file",{method:"POST",body:h,headers:u})).json();if((p==null?void 0:p.success)===!1)return p.message!==void 0?console.error("Upload failed:",p.message):console.error("Upload failed"),null;console.assert(p.hash_sum===i,"hash sum did not match","received:",p.hash_sum,"expected:",i),p.success&&console.log("successfully uploaded",i,p.id);const m=new fB(p.success,r,i,s.size);return m.url=e,m}function IO(s){return oue(new Uint8Array(s))}async function RO(s,e,t,i,n=!1){try{const r=await fetch(i+"/download/file",{method:"POST",body:s});if(r.status!==200)return console.error("download failed",r),null;const o=await r.blob(),a=await o.arrayBuffer();n||console.assert(o.size===t,"size mismatch","expected:",t,"got:",o.size);const l=IO(a);return n||console.assert(l===e,"hash mismatch, downloaded file is invalid"),o.arrayBuffer()}catch(r){console.error(r)}return null}async function DQ(s,e){var h;const t=await fetch(s),i=(h=t.body)==null?void 0:h.getReader(),n=t.headers.get("Content-Length"),r=n?parseInt(n):0;if(!i)return null;let o=0;const a=[];for(;;){const{done:u,value:f}=await i.read();if(f&&(a.push(f),o+=f.length,e.call(null,new ProgressEvent("progress",{loaded:o,total:r}))),u)break}const l=new Uint8Array(o);let c=0;for(const u of a)l.set(u,c),c+=u.length;return l}const xu=ie("debugaddressables");class OQ{constructor(e){d(this,"_context");d(this,"_assetReferences",{});d(this,"preUpdate",()=>{});this._context=e,this._context.pre_update_callbacks.push(this.preUpdate)}dispose(){const e=this._context.pre_update_callbacks.indexOf(this.preUpdate);e>=0&&this._context.pre_update_callbacks.splice(e,1);for(const t in this._assetReferences){const i=this._assetReferences[t];i==null||i.unload()}this._assetReferences={}}findAssetReference(e){return this._assetReferences[e]||null}registerAssetReference(e){return e.uri&&(this._assetReferences[e.uri]?console.warn("Asset reference already registered",e):this._assetReferences[e.uri]=e),e}unregisterAssetReference(e){e.uri&&delete this._assetReferences[e.uri]}}const xI=Symbol("assetReference"),Df=class{constructor(e,t,i=null){d(this,"_loading");d(this,"_asset");d(this,"_glbRoot");d(this,"_url");d(this,"_progressListeners",[]);d(this,"_hash");d(this,"_hashedUri");d(this,"_isLoadingRawBinary",!1);d(this,"_rawBinary");this._url=e,this._hash=t,e.includes("?v=")?this._hashedUri=e:this._hashedUri=t?e+"?v="+t:e,i!==null&&(this.asset=i),sj(this._url,this.onResolvePrefab.bind(this))}static getOrCreateFromUrl(e,t){if(!t&&(t=Ot.Current,!t))throw new Error('Context is required when sourceId is a string. When you call this method from a component you can call it with "getOrCreate(this, url)" where "this" is the component.');const i=t.addressables,n=i.findAssetReference(e);if(n)return n;const r=new Df(e,t.hash);return i.registerAssetReference(r),r}static getOrCreate(e,t,i){if(typeof e=="string"){if(!i&&(i=Ot.Current,!i))throw new Error('Context is required when sourceId is a string. When you call this method from a component you can call it with "getOrCreate(this, url)" where "this" is the component.')}else i=e.context,e=e.sourceId;const n=wd(e,t);xu&&console.log("GetOrCreate Addressable from",e,t,"FinalPath=",n);const r=i.addressables,o=r.findAssetReference(n);if(o)return o;const a=new Df(n,i.hash);return r.registerAssetReference(a),a}get asset(){return this._glbRoot??this._asset}set asset(e){this._asset=e}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(e){return e===this.uri&&(this.mustLoad&&await this.loadAssetAsync(),this.asset)?this.asset:null}get mustLoad(){return!this.asset||this.asset.__destroyed===!0||Cp(this.asset)===!0}isLoaded(){return this._rawBinary||this.asset!==void 0}unload(){this.asset&&(xu&&console.log("Unload",this.asset),this.asset.scene&&Ga(this.asset.scene,!0,!0),Ga(this.asset,!0,!0)),this.asset=null,this._rawBinary=void 0,this._glbRoot=null,this._loading=void 0,Ot.Current&&Ot.Current.addressables.unregisterAssetReference(this)}async preload(){if(!this.mustLoad||this._isLoadingRawBinary)return null;if(this._rawBinary!==void 0)return this._rawBinary;this._isLoadingRawBinary=!0,xu&&console.log("Preload",this._hashedUri);const e=await DQ(this._hashedUri,t=>{this.raiseProgressEvent(t)});return this._rawBinary=(e==null?void 0:e.buffer)??null,this._isLoadingRawBinary=!1,this._rawBinary}async loadAssetAsync(e){if(xu&&console.log("loadAssetAsync",this.uri),!this.mustLoad)return this.asset;if(e&&this._progressListeners.push(e),this._loading!==void 0)return this._loading.then(n=>this.asset);const t=Ot.Current;this._rawBinary?(this._loading=Cl().parseSync(t,this._rawBinary,this.uri,null),this.raiseProgressEvent(new ProgressEvent("progress",{loaded:this._rawBinary.byteLength,total:this._rawBinary.byteLength}))):(xu&&console.log("Load async",this.uri),this._loading=Cl().loadSync(t,this._hashedUri,this.uri,null,n=>{this.raiseProgressEvent(n)}));const i=await this._loading;if(this._progressListeners.length=0,this._glbRoot=this.tryGetActualGameObjectRoot(i),this._loading=void 0,i)return i[xI]=this,this._glbRoot&&(this._glbRoot[xI]=this),this.asset&&(this.asset[xI]=this),xC(t),i.scene!==void 0&&(this.asset=i),this.asset}async instantiate(e){return this.onInstantiate(e,!1)}async instantiateSynced(e,t=!0){return this.onInstantiate(e,!0,t)}beginListenDownload(e){this._progressListeners.indexOf(e)<0&&this._progressListeners.push(e)}endListenDownload(e){const t=this._progressListeners.indexOf(e);t>=0&&this._progressListeners.splice(t,1)}raiseProgressEvent(e){for(const t of this._progressListeners)t(this,e)}async onInstantiate(e,t=!1,i){const n=Ot.Current,r=new Bl;if(e instanceof ve?r.parent=e:e&&(Object.assign(r,e),r.cloneAssign(e)),r.parent||(r.parent=n.scene),this.mustLoad&&await this.loadAssetAsync(),xu&&console.log("Instantiate",this.uri,"parent:",e),this.asset){xu&&console.log("Add to scene",this.asset);let o=Df.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,Df.currentlyInstantiating.set(this.uri,o),t){r.context=n;const a=this.asset;a.guid=this.uri;const l=WO(a,r,void 0,i);if(l)return l}else{const a=Uy(this.asset,r);if(a)return a}}finally{n.post_render_callbacks.push(()=>{o===void 0||o<0?o=0:o-=1,Df.currentlyInstantiating.set(this.uri,o)})}}else xu&&console.warn("Failed to load asset",this.uri);return null}tryGetActualGameObjectRoot(e){if(e&&e.scene){const t=e.scene;return t.isGroup&&t.children.length===1&&t.children[0].name+"glb"===t.name?t.children[0]:t}return null}};let Zt=Df;d(Zt,"currentlyInstantiating",new Map);class aue extends Xa{constructor(){super([Zt],"AssetReferenceSerializer")}onSerialize(e,t){if(e&&e.uri!==void 0&&typeof e.uri=="string")return e.uri}onDeserialize(e,t){if(typeof e=="string")return t.context?t.gltfId?Zt.getOrCreate(t.gltfId,e,t.context):(console.error("Missing source id"),null):(console.error("Missing context"),null);if(e instanceof ve){if(!t.context)return console.error("Missing context"),null;if(!t.gltfId)return console.error("Missing source id"),null;const i=e,n=t.context,r=i.guid??i.uuid,o=n.addressables.findAssetReference(r);if(o)return o;const a=new Zt(r,void 0,i);return n.addressables.registerAssetReference(a),a}return null}}new aue;const lue=Promise.resolve(null),u0=class{constructor(e){d(this,"url");d(this,"_bitmap");d(this,"_bitmapObject");d(this,"loader",null);this.url=e}static getOrCreate(e){let t=u0.imageReferences.get(e);return t||(t=new u0(e),u0.imageReferences.set(e,t)),t}dispose(){this._bitmapObject&&this._bitmapObject.close(),this._bitmap=void 0}createHTMLImage(){const e=new Image;return e.src=this.url,e}createTexture(){return this.url?(this.loader||(this.loader=new mc),this.loader.setCrossOrigin("anonymous"),this.loader.loadAsync(this.url)):lue}getBitmap(){return this._bitmap?this._bitmap:(this._bitmap=new Promise((e,t)=>{const i=document.createElement("img");i.addEventListener("load",()=>{this._bitmap=createImageBitmap(i).then(n=>(this._bitmapObject=n,e(n),n))}),i.addEventListener("error",n=>{console.error("Failed to load image:"+this.url,n),e(null)}),i.src=this.url}),this._bitmap)}};let qg=u0;d(qg,"imageReferences",new Map);class LQ extends Xa{constructor(){super([qg],"ImageReferenceSerializer")}onSerialize(e,t){return null}onDeserialize(e,t){if(typeof e=="string"){const i=wd(t.gltfId,e);return qg.getOrCreate(i)}}}new LQ;const d0=class{constructor(e){d(this,"url");d(this,"res");this.url=e}static getOrCreate(e){let t=d0.cache.get(e);return t||(t=new d0(e),d0.cache.set(e,t)),t}async loadRaw(){return this.res||(this.res=fetch(this.url)),this.res.then(e=>e.blob())}async loadText(){return this.res||(this.res=fetch(this.url)),this.res.then(e=>e.text())}};let Xg=d0;d(Xg,"cache",new Map);class kQ extends Xa{constructor(){super([Xg],"FileReferenceSerializer")}onSerialize(e,t){return null}onDeserialize(e,t){if(typeof e=="string"){const i=wd(t.gltfId,e);return Xg.getOrCreate(i)}}}new kQ;class cue{constructor(e){d(this,"context");d(this,"mixers",[]);this.context=e}onDestroy(){this.mixers.forEach(e=>e.stopAllAction()),this.mixers.length=0}registerAnimationMixer(e){if(!e){console.warn("AnimationsRegistry.registerAnimationMixer called with null or undefined mixer");return}this.mixers.includes(e)||this.mixers.push(e)}unregisterAnimationMixer(e){if(!e)return;const t=this.mixers.indexOf(e);t!==-1&&this.mixers.splice(t,1)}}class my{static tryGetActionsFromMixer(e){const t=e._actions;return t||null}static tryGetAnimationClipsFromObjectHierarchy(e,t){if(t||(t=new Array),e)e.animations&&t.push(...e.animations);else return t;if(e.children)for(const i of e.children)this.tryGetAnimationClipsFromObjectHierarchy(i,t);return t}static assignAnimationsFromFile(e,t){if(!e||!e.animations)return;for(let n=0;n<e.animations.length;n++){const r=e.animations[n];if(!(!r.tracks||r.tracks.length<=0))for(const o in r.tracks){const a=r.tracks[o],l=Kt.parseTrackName(a.name);let c=Kt.findNode(e.scene,l.nodeName);if(!c){const u=a.__objectName??a.name.substring(0,a.name.indexOf("."));if(c=e.scene.getObjectByProperty("uuid",u),!c)continue}let h=i(c);if(!h){if(!(t!=null&&t.createAnimationComponent)){console.warn("No AnimationComponent found in parent hierarchy of object and no 'createAnimationComponent' callback was provided in options.");continue}h=t.createAnimationComponent(e.scene,r)}h.addClip&&h.addClip(r)}}function i(n){var o;if(!n)return null;const r=(o=n.userData)==null?void 0:o.components;if(r&&r.length>0){for(let a=0;a<r.length;a++)if(r[a].isAnimationComponent===!0)return n}return i(n.parent)}}}const gy=[];function hE(s){gy.indexOf(s)===-1&&gy.push(s)}function hue(s){const e=gy.indexOf(s);e!==-1&&gy.splice(e,1)}const yy=[];function PO(s){yy.indexOf(s)===-1&&yy.push(s)}function uue(s){const e=yy.indexOf(s);e!==-1&&yy.splice(e,1)}function FQ(s){globalThis.dispatchEvent(new CustomEvent("needle-xrsession-start",{detail:s}));for(let e=0;e<gy.length;e++)gy[e](s)}function UQ(s){globalThis.dispatchEvent(new CustomEvent("needle-xrsession-end",{detail:s}));for(let e=0;e<yy.length;e++)yy[e](s)}const Ps={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 NQ(s){const e=await fetch(s);if(e.ok)return e.json();throw new Error(e.statusText)}async function due(s){if(!s)throw new Error("No basePath supplied");return await NQ(`${s}/profilesList.json`)}async function fue(s,e,t=null,i=!0){if(!s)throw new Error("No xrInputSource supplied");if(!e)throw new Error("No basePath supplied");const n=await due(e);let r;if(s.profiles.some(l=>{const c=n[l];return c&&(r={profileId:l,profilePath:`${e}/${c.path}`,deprecated:!!c.deprecated}),!!r}),!r){if(!t)throw new Error("No matching profile name found");const l=n[t];if(!l)throw new Error(`No matching profile name found and default profile "${t}" missing.`);r={profileId:t,profilePath:`${e}/${l.path}`,deprecated:!!l.deprecated}}const o=await NQ(r.profilePath);let a;if(i){let l;if(s.handedness==="any"?l=o.layouts[Object.keys(o.layouts)[0]]:l=o.layouts[s.handedness],!l)throw new Error(`No matching handedness, ${s.handedness}, in profile ${r.profileId}`);l.assetPath&&(a=r.profilePath.replace("profile.json",l.assetPath))}return{profile:o,assetPath:a}}const pue={xAxis:0,yAxis:0,button:0,state:Ps.ComponentState.DEFAULT};function mue(s=0,e=0){let t=s,i=e;if(Math.sqrt(s*s+e*e)>1){const o=Math.atan2(e,s);t=Math.cos(o),i=Math.sin(o)}return{normalizedXAxis:t*.5+.5,normalizedYAxis:i*.5+.5}}let gue=class{constructor(e){this.componentProperty=e.componentProperty,this.states=e.states,this.valueNodeName=e.valueNodeName,this.valueNodeProperty=e.valueNodeProperty,this.valueNodeProperty===Ps.VisualResponseProperty.TRANSFORM&&(this.minNodeName=e.minNodeName,this.maxNodeName=e.maxNodeName),this.value=0,this.updateFromComponent(pue)}updateFromComponent({xAxis:e,yAxis:t,button:i,state:n}){const{normalizedXAxis:r,normalizedYAxis:o}=mue(e,t);switch(this.componentProperty){case Ps.ComponentProperty.X_AXIS:this.value=this.states.includes(n)?r:.5;break;case Ps.ComponentProperty.Y_AXIS:this.value=this.states.includes(n)?o:.5;break;case Ps.ComponentProperty.BUTTON:this.value=this.states.includes(n)?i:0;break;case Ps.ComponentProperty.STATE:this.valueNodeProperty===Ps.VisualResponseProperty.VISIBILITY?this.value=this.states.includes(n):this.value=this.states.includes(n)?1:0;break;default:throw new Error(`Unexpected visualResponse componentProperty ${this.componentProperty}`)}}},yue=class{constructor(e,t){if(!e||!t||!t.visualResponses||!t.gamepadIndices||Object.keys(t.gamepadIndices).length===0)throw new Error("Invalid arguments supplied");this.id=e,this.type=t.type,this.rootNodeName=t.rootNodeName,this.touchPointNodeName=t.touchPointNodeName,this.visualResponses={},Object.keys(t.visualResponses).forEach(i=>{const n=new gue(t.visualResponses[i]);this.visualResponses[i]=n}),this.gamepadIndices=Object.assign({},t.gamepadIndices),this.values={state:Ps.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(e){if(this.values.state=Ps.ComponentState.DEFAULT,this.gamepadIndices.button!==void 0&&e.buttons.length>this.gamepadIndices.button){const t=e.buttons[this.gamepadIndices.button];this.values.button=t.value,this.values.button=this.values.button<0?0:this.values.button,this.values.button=this.values.button>1?1:this.values.button,t.pressed||this.values.button===1?this.values.state=Ps.ComponentState.PRESSED:(t.touched||this.values.button>Ps.ButtonTouchThreshold)&&(this.values.state=Ps.ComponentState.TOUCHED)}this.gamepadIndices.xAxis!==void 0&&e.axes.length>this.gamepadIndices.xAxis&&(this.values.xAxis=e.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===Ps.ComponentState.DEFAULT&&Math.abs(this.values.xAxis)>Ps.AxisTouchThreshold&&(this.values.state=Ps.ComponentState.TOUCHED)),this.gamepadIndices.yAxis!==void 0&&e.axes.length>this.gamepadIndices.yAxis&&(this.values.yAxis=e.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===Ps.ComponentState.DEFAULT&&Math.abs(this.values.yAxis)>Ps.AxisTouchThreshold&&(this.values.state=Ps.ComponentState.TOUCHED)),Object.values(this.visualResponses).forEach(t=>{t.updateFromComponent(this.values)})}},vue=class{constructor(e,t,i){if(!e)throw new Error("No xrInputSource supplied");if(!t)throw new Error("No profile supplied");this.xrInputSource=e,this.assetUrl=i,this.id=t.profileId,this.layoutDescription=t.layouts[e.handedness],this.components={},Object.keys(this.layoutDescription.components).forEach(n=>{const r=this.layoutDescription.components[n];this.components[n]=new yue(n,r)}),this.updateFromGamepad()}get gripSpace(){return this.xrInputSource.gripSpace}get targetRaySpace(){return this.xrInputSource.targetRaySpace}get data(){const e=[];return Object.values(this.components).forEach(t=>{e.push(t.data)}),e}updateFromGamepad(){Object.values(this.components).forEach(e=>{e.updateFromGamepad(this.xrInputSource.gamepad)})}};const qr=new w,B3=new w,D3=new Ce,Aue=ie("debuggizmos"),Ul=8947848,pl=class{constructor(){}static isGizmo(e){return e[pB]!==void 0}static DrawLabel(e,t,i=.05,n=0,r,o,a){var h;if(!pl.enabled)return null;r||(r=Ul);const l=((h=xt.active)==null?void 0:h.rigScale)??1,c=Pn.getTextLabel(n,t,i*l,r,o);return a instanceof ve&&a.add(c),c.position.x=e.x,c.position.y=e.y,c.position.z=e.z,c}static DrawRay(e,t,i=Ul,n=0,r=!0){if(!pl.enabled)return;const o=Pn.getLine(n),a=o.geometry.getAttribute("position");a.setXYZ(0,e.x,e.y,e.z),qr.set(t.x,t.y,t.z).multiplyScalar(999999999),a.setXYZ(1,e.x+qr.x,e.y+qr.y,e.z+qr.z),a.needsUpdate=!0,o.material.color.set(i),o.material.depthTest=r,o.material.depthWrite=!1}static DrawDirection(e,t,i=Ul,n=0,r=!0,o=1){if(!pl.enabled)return;const a=Pn.getLine(n),l=a.geometry.getAttribute("position");l.setXYZ(0,e.x,e.y,e.z),t.w!==void 0?(qr.set(0,0,-o),D3.set(t.x,t.y,t.z,t.w),qr.applyQuaternion(D3)):(qr.set(t.x,t.y,t.z),qr.multiplyScalar(o)),l.setXYZ(1,e.x+qr.x,e.y+qr.y,e.z+qr.z),l.needsUpdate=!0,a.material.color.set(i),a.material.depthTest=r,a.material.depthWrite=!1}static DrawLine(e,t,i=Ul,n=0,r=!0){if(!pl.enabled)return;const o=Pn.getLine(n),a=o.geometry.getAttribute("position");a.setXYZ(0,e.x,e.y,e.z),a.setXYZ(1,t.x,t.y,t.z),a.needsUpdate=!0,o.material.color.set(i),o.material.depthTest=r,o.material.depthWrite=!1,o.material.fog=!1}static DrawWireSphere(e,t,i=Ul,n=0,r=!0){if(!pl.enabled)return;const o=Pn.getSphere(t,n,!0);wp(o,e.x,e.y,e.z),o.material.color.set(i),o.material.depthTest=r,o.material.depthWrite=!1,o.material.fog=!1}static DrawSphere(e,t,i=Ul,n=0,r=!0){if(!pl.enabled)return;const o=Pn.getSphere(t,n,!1);wp(o,e.x,e.y,e.z),o.material.color.set(i),o.material.depthTest=r,o.material.depthWrite=!1}static DrawWireBox(e,t,i=Ul,n=0,r=!0){if(!pl.enabled)return;const o=Pn.getBox(n);o.position.set(e.x,e.y,e.z),o.scale.set(t.x,t.y,t.z),o.material.color.set(i),o.material.depthTest=r,o.material.wireframe=!0,o.material.depthWrite=!1,o.material.fog=!1}static DrawWireBox3(e,t=Ul,i=0,n=!0){if(!pl.enabled)return;const r=Pn.getBox(i);r.position.copy(e.getCenter(qr)),r.scale.copy(e.getSize(qr)),r.material.color.set(t),r.material.depthTest=n,r.material.wireframe=!0,r.material.depthWrite=!1,r.material.fog=!1}static DrawArrow(e,t,i=Ul,n=0,r=!0,o=!1){if(!pl.enabled)return;const a=Pn.getArrowHead(n);a.position.set(t.x,t.y,t.z),a.quaternion.setFromUnitVectors(this._up.set(0,1,0),qr.set(t.x,t.y,t.z).sub(B3.set(e.x,e.y,e.z)).normalize());const c=qr.set(t.x,t.y,t.z).sub(B3.set(e.x,e.y,e.z)).length()*.1;a.scale.set(c,c,c),a.material.color.set(i),a.material.depthTest=r,a.material.wireframe=o,this.DrawLine(e,t,i,n,r)}static DrawWireMesh(e){const t=Pn.getMesh(e.duration??0);"mesh"in e?(t.geometry=e.mesh.geometry,t.matrix.copy(e.mesh.matrixWorld)):(t.geometry=e.geometry,t.matrix.copy(e.matrix)),t.matrixAutoUpdate=!1,t.matrixWorldAutoUpdate=!1,t.material.color.set(e.color??Ul),t.material.depthTest=e.depthTest??!0,t.material.wireframe=!0}};let _t=pl;d(_t,"enabled",!0),d(_t,"_up",new w(0,1,0));const _ue=new Xi(1,1,1);function BO(s=null){const e=new Ae(s??14540253),t=new X2(_ue);return new Dr(t,new Zi({color:e}))}const pB=Symbol("GizmoCache");class Pn{static ensureFont(){let e=Qi.FontLibrary.getFontFamily(this.familyName);if(!e){e=Qi.FontLibrary.addFontFamily(this.familyName);const t=e.addVariant("normal","normal","https://uploads.needle.tools/include/font-msdf.json","https://uploads.needle.tools/include/font.png");t==null||t.addEventListener("ready",()=>{Qi.update()})}}static getTextLabel(e,t,i,n,r){this.ensureFont();let o=this.textLabelCache.pop(),a=1;r&&typeof r=="string"&&(r==null?void 0:r.length)>=8&&r.startsWith("#")?(a=parseInt(r.substring(7),16)/255,r=r.substring(0,7),Aue&&console.log(r,a)):typeof r=="object"&&r.a!==void 0&&(a=r.a);const l={boxSizing:"border-box",fontFamily:this.familyName,width:"auto",fontSize:i,color:n,lineHeight:1,backgroundColor:r??void 0,backgroundOpacity:a,textContent:t,borderRadius:.5*i,padding:.8*i,whiteSpace:"pre"};if(o)o.set(l);else{o=new kD(l);const c=this,h=o;h.setText=function(u){this.set({textContent:u}),c.tmuiNeedsUpdate=!0}}return this.tmuiNeedsUpdate=!0,this.registerTimedObject(Ot.Current,o,e,this.textLabelCache),o}static getBox(e){let t=this.boxesCache.pop();if(!t){const i=new Xi(1,1,1);t=new fe(i)}return this.registerTimedObject(Ot.Current,t,e,this.boxesCache),t}static getLine(e){let t=this.linesCache.pop();if(!t){t=new Dn;let i=t.geometry.getAttribute("position");i||(i=new ot(new Float32Array(2*3),3),t.geometry.setAttribute("position",i))}return t.frustumCulled=!1,this.registerTimedObject(Ot.Current,t,e,this.linesCache),t}static getSphere(e,t,i){let n=this.spheresCache.pop();return n||(n=new fe(new Wa(1,8,8))),n.scale.set(e,e,e),n.material.wireframe=i,this.registerTimedObject(Ot.Current,n,t,this.spheresCache),n}static getArrowHead(e){let t=this.arrowHeadsCache.pop();return t||(t=new fe(new Hn(0,.5,1,8))),this.registerTimedObject(Ot.Current,t,e,this.arrowHeadsCache),t}static getMesh(e){let t=this.mesh.pop();return t||(t=new fe,t.material=new ni),this.registerTimedObject(Ot.Current,t,e,this.mesh),t}static registerTimedObject(e,t,i,n){const r=this.contextBeforeRenderCallbacks.get(e),o=this.contextPostRenderCallbacks.get(e);if(r){if(e.pre_render_callbacks[e.pre_render_callbacks.length-1]!==r){const a=e.pre_render_callbacks.indexOf(r);a>=0&&e.pre_render_callbacks.splice(a,1),e.pre_render_callbacks.push(r)}}else{const a=()=>{this.onBeforeRender(e,this.timedObjectsBuffer)};this.contextBeforeRenderCallbacks.set(e,a),e.pre_render_callbacks.push(a)}if(o){if(e.post_render_callbacks[e.post_render_callbacks.length-1]!==o){const a=e.post_render_callbacks.indexOf(o);a>=0&&e.post_render_callbacks.splice(a,1),e.post_render_callbacks.push(o)}}else{const a=()=>{this.onPostRender(e,this.timedObjectsBuffer,this.timesBuffer)};this.contextPostRenderCallbacks.set(e,a),e.post_render_callbacks.push(a)}t.traverse(a=>{a.layers.disableAll(),a.layers.enable(2)}),t.renderOrder=999999,t[pB]=n,t.isGizmo=!0,this.timedObjectsBuffer.push(t),i<=0&&e.currentFrameEvent>=$i.OnBeforeRender?this.timesBuffer.push(0):this.timesBuffer.push(Ot.Current.time.realtimeSinceStartup+i),e.scene.add(t)}static onBeforeRender(e,t){this.tmuiNeedsUpdate&&Qi.update();for(let i=0;i<t.length;i++){const n=t[i];if(e.mainCamera&&n instanceof Qi.MeshUIBaseElement){if(Cp(n))continue;const r=e.isInVR,o=!1,a=!r;I_(n,e.mainCamera,o,a)}}}static onPostRender(e,t,i){const n=e.time.realtimeSinceStartup;for(let r=t.length-1;r>=0;r--){const o=t[r];n>i[r]&&(t.splice(r,1),i.splice(r,1),o.removeFromParent(),Cp(o)!=!0&&o[pB].push(o))}}}d(Pn,"familyName","needle-gizmos"),d(Pn,"linesCache",[]),d(Pn,"spheresCache",[]),d(Pn,"boxesCache",[]),d(Pn,"arrowHeadsCache",[]),d(Pn,"mesh",[]),d(Pn,"textLabelCache",[]),d(Pn,"timedObjectsBuffer",new Array),d(Pn,"timesBuffer",new Array),d(Pn,"contextPostRenderCallbacks",new Map),d(Pn,"contextBeforeRenderCallbacks",new Map),d(Pn,"tmuiNeedsUpdate",!1);const hs=ie("debuginput");var uE=(s=>(s.Mouse="mouse",s.Touch="touch",s.Controller="controller",s.Hand="hand",s))(uE||{}),fn=(s=>(s.PointerDown="pointerdown",s.PointerUp="pointerup",s.PointerMove="pointermove",s.KeyDown="keydown",s.KeyUp="keyup",s.KeyPressed="keypress",s))(fn||{});class hh extends PointerEvent{constructor(t,i,n){super(t,n);d(this,"deviceIndex");d(this,"origin");d(this,"source");d(this,"mode");d(this,"_ray");d(this,"space");d(this,"isClick",!1);d(this,"isDoubleClick",!1);d(this,"_used",!1);d(this,"_pointerid");d(this,"_pointerType");d(this,"_type");d(this,"metadata",{});d(this,"intersections",new Array);d(this,"_immediatePropagationStopped",!1);d(this,"_propagationStopped",!1);this._pointerid=n.pointerId,this._pointerType=n.pointerType,this._type=t,this.deviceIndex=n.deviceIndex,this.origin=n.origin,this.source=i,this.mode=n.mode,this._ray=n.ray,this.space=n.device}get ray(){return this._ray||(this._ray=new Mo(this.space.worldPosition.clone(),this.space.worldForward.clone())),this._ray}set ray(t){this._ray=t}get hasRay(){return this._ray!==void 0}get used(){return this._used}use(){this._used=!0}get pointerId(){return this._pointerid}get pointerType(){return this._pointerType}get type(){return this._type}get immediatePropagationStopped(){return this._immediatePropagationStopped}get propagationStopped(){return this._immediatePropagationStopped||this._propagationStopped}stopImmediatePropagation(){var t;this._immediatePropagationStopped=!0,super.stopImmediatePropagation(),(t=this.source)==null||t.stopImmediatePropagation()}stopPropagation(){var t;this._propagationStopped=!0,super.stopPropagation(),(t=this.source)==null||t.stopPropagation(),hs&&console.warn("Stop propagation...",this.pointerId,this.pointerType)}}class xA extends KeyboardEvent{constructor(t,i,n){super(t,n);d(this,"source");this.source=i}stopImmediatePropagation(){var t;super.stopImmediatePropagation(),(t=this.source)==null||t.stopImmediatePropagation()}}class bue{constructor(e){d(this,"key");d(this,"keyType");d(this,"source");this.key=e.key,this.keyType=e.type,this.source=e}}var $l=(s=>(s[s.Early=-100]="Early",s[s.Default=0]="Default",s[s.Late=100]="Late",s))($l||{});class zQ{constructor(e){d(this,"_eventListeners",{});d(this,"_doubleClickTimeThreshold",.2);d(this,"_longPressTimeThreshold",1);d(this,"_specialCursorTrigger",0);d(this,"context");d(this,"_pointerDown",[!1]);d(this,"_pointerUp",[!1]);d(this,"_pointerClick",[!1]);d(this,"_pointerDoubleClick",[!1]);d(this,"_pointerPressed",[!1]);d(this,"_pointerPositions",[new ee]);d(this,"_pointerPositionsLastFrame",[new ee]);d(this,"_pointerPositionsDelta",[new ee]);d(this,"_pointerPositionsRC",[new ee]);d(this,"_pointerPositionDown",[new ee]);d(this,"_pointerDownTime",[]);d(this,"_pointerUpTime",[]);d(this,"_pointerUpTimestamp",[]);d(this,"_pointerIds",[]);d(this,"_pointerTypes",[""]);d(this,"_mouseWheelChanged",[!1]);d(this,"_mouseWheelDeltaY",[0]);d(this,"_pointerEvent",[]);d(this,"_pointerUsed",[]);d(this,"_pointerSpace",[]);d(this,"_pressedStack",new Map);d(this,"_htmlEventSource");d(this,"onLostFocus",()=>{for(const e in this.keysPressed)this.keysPressed[e].pressed=!1});d(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});d(this,"onContextMenu",e=>{this.canReceiveInput(e)!==!1&&e instanceof PointerEvent&&e.pointerType});d(this,"keysPressed",{});d(this,"onKeyDown",e=>{if(hs&&console.log(`key down ${e.code}, ${this.context.application.hasFocus}`,e),!this.context.application.hasFocus)return;const t=this.keysPressed[e.code];if(t&&t.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 xA("keydown",e,e);this.onDispatchEvent(i)});d(this,"onKeyPressed",e=>{if(!this.context.application.hasFocus)return;const t=this.keysPressed[e.code];if(!t)return;t.pressed=!0,t.frame=this.context.time.frameCount+1;const i=new xA("keypress",e,e);this.onDispatchEvent(i)});d(this,"onKeyUp",e=>{if(!this.context.application.hasFocus)return;const t=this.keysPressed[e.code];if(!t)return;t.pressed=!1,t.frame=this.context.time.frameCount+1;const i=new xA("keyup",e,e);this.onDispatchEvent(i)});d(this,"onWheelWindow",e=>{document.pointerLockElement&&this.onMouseWheel(e)});d(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 t=this._mouseWheelDeltaY[0];this._mouseWheelDeltaY[0]=t+e.deltaY});d(this,"onPointerDown",e=>{if(this.context.isInAR||this.canReceiveInput(e)===!1)return;e.target instanceof HTMLElement&&e.target.setPointerCapture(e.pointerId);const t=this.getPointerId(e);hs&&pn(`pointer down #${t}, identifier:${e.pointerId}`);const i=this.getAndUpdateSpatialObjectForScreenPosition(t,e.clientX,e.clientY),n=new hh("pointerdown",e,{origin:this,mode:"screen",deviceIndex:0,pointerId:t,button:e.button,clientX:e.clientX,clientY:e.clientY,pointerType:e.pointerType,buttonName:this.getButtonName(e),device:i,pressure:e.pressure});this.onDown(n)});d(this,"onPointerMove",e=>{if(this.context.isInAR)return;let t=e.button;e.pointerType==="mouse"&&(t=this.getFirstPressedButtonForPointer(0)??0);const i=this.getPointerId(e,t);t===-1&&(t=i);const n=this.getAndUpdateSpatialObjectForScreenPosition(i,e.clientX,e.clientY),r=new hh("pointermove",e,{origin:this,mode:"screen",deviceIndex:0,pointerId:i,button:t,clientX:e.clientX,clientY:e.clientY,pointerType:e.pointerType,buttonName:this.getButtonName(e),device:n,pressure:e.pressure});this.onMove(r)});d(this,"onPointerCancel",e=>{this.context.isInAR||(hs&&console.log("Pointer cancel",e),this.onPointerUp(e))});d(this,"onPointerUp",e=>{if(this.context.isInAR)return;e.target instanceof HTMLElement&&e.target.releasePointerCapture(e.pointerId);const t=this.getPointerId(e),i=new hh("pointerup",e,{origin:this,mode:"screen",deviceIndex:0,pointerId:t,button:e.button,clientX:e.clientX,clientY:e.clientY,pointerType:e.pointerType,buttonName:this.getButtonName(e),device:this.getAndUpdateSpatialObjectForScreenPosition(t,e.clientX,e.clientY),pressure:e.pressure});this.onUp(i),this._pointerIds[t]=-1,hs&&console.log("ID="+t,"PointerId="+e.pointerId,"ALL:",[...this._pointerIds])});d(this,"onTouchStart",e=>{if(this.context.isInAR)for(let t=0;t<e.changedTouches.length;t++){const i=e.changedTouches[t],n=this.getPointerIndex(i.identifier),r=this.getAndUpdateSpatialObjectForScreenPosition(n,i.clientX,i.clientY),o=new hh("pointerdown",e,{origin:this,mode:"screen",deviceIndex:0,pointerId:n,button:0,clientX:i.clientX,clientY:i.clientY,pointerType:"touch",buttonName:"unknown",device:r,pressure:i.force});this.onDown(o)}});d(this,"onTouchMove",e=>{if(this.context.isInAR)for(let t=0;t<e.changedTouches.length;t++){const i=e.changedTouches[t],n=this.getPointerIndex(i.identifier),r=this.getAndUpdateSpatialObjectForScreenPosition(n,i.clientX,i.clientY),o=new hh("pointermove",e,{origin:this,mode:"screen",deviceIndex:0,pointerId:n,button:0,clientX:i.clientX,clientY:i.clientY,pointerType:"touch",buttonName:"unknown",device:r,pressure:i.force});this.onMove(o)}});d(this,"onTouchEnd",e=>{if(this.context.isInAR)for(let t=0;t<e.changedTouches.length;t++){const i=e.changedTouches[t],n=this.getPointerIndex(i.identifier),r=new hh("pointerup",e,{origin:this,mode:"screen",deviceIndex:0,pointerId:n,button:0,clientX:i.clientX,clientY:i.clientY,pointerType:"touch",buttonName:"unknown",device:this.getAndUpdateSpatialObjectForScreenPosition(n,i.clientX,i.clientY),pressure:i.force});this.onUp(r),this._pointerIds[n]=-1}});d(this,"tempNearPlaneVector",new w);d(this,"tempFarPlaneVector",new w);d(this,"tempLookMatrix",new ye);this.context=e,this.context.post_render_callbacks.push(this.onEndOfFrame)}addEventListener(e,t,i){if(this._eventListeners[e]||(this._eventListeners[e]=[]),!t||typeof t!="function"){console.error("Invalid call to addEventListener: callback is required and must be a function!");return}i?i={...i}:i={};let n=0;(i==null?void 0:i.queue)!=null&&(n=i.queue);const r=this._eventListeners[e],o=r.find(a=>a.priority===n);o?o.listeners.push({callback:t,options:i}):(r.push({priority:n,listeners:[{callback:t,options:i}]}),r.sort((a,l)=>a.priority-l.priority))}removeEventListener(e,t,i){if(!this._eventListeners[e]||!t)return;const n=this._eventListeners[e];if((i==null?void 0:i.queue)!=null){const r=n.find(a=>a.priority===i.queue);if(!r)return;const o=r.listeners.findIndex(a=>a.callback===t);o>=0&&r.listeners.splice(o,1)}else for(const r of n){const o=r.listeners.findIndex(a=>a.callback===t);o>=0&&r.listeners.splice(o,1)}}dispatchEvent(e){var i,n,r,o;let t=!1;if(e instanceof xA){const a=this._eventListeners[e.type];if(a)for(const l of a)for(let c=0;c<l.listeners.length;c++){const h=l.listeners[c];if((n=(i=h.options)==null?void 0:i.signal)!=null&&n.aborted){l.listeners.splice(c,1),c--;continue}h.options.once&&(l.listeners.splice(c,1),c--),h.callback(e)}}if(e instanceof hh){const a=this._eventListeners[e.type];if(a)for(const l of a){if(t)break;for(let c=0;c<l.listeners.length;c++){const h=l.listeners[c];if((o=(r=h.options)==null?void 0:r.signal)!=null&&o.aborted){l.listeners.splice(c,1),c--;continue}if(e.immediatePropagationStopped){t=!0,hs&&console.log("immediatePropagationStopped",e.type);break}else e.propagationStopped&&(t=!0,hs&&console.log("propagationStopped",e.type));h.options.once&&(l.listeners.splice(c,1),c--),h.callback(e)}}}}get mousePosition(){return this._pointerPositions[0]}get mousePositionRC(){return this._pointerPositionsRC[0]}get mouseDown(){return this._pointerDown[0]}get mouseUp(){return this._pointerUp[0]}get mouseClick(){return this._pointerClick[0]}get mouseDoubleClick(){return this._pointerDoubleClick[0]}get mousePressed(){return this._pointerPressed[0]}get mouseWheelChanged(){return this.getMouseWheelChanged(0)}setCursorPointer(){this._specialCursorTrigger+=1,this.context.domElement.style.cursor="pointer"}setCursorNormal(){this._specialCursorTrigger-=1,this._specialCursorTrigger=Math.max(0,this._specialCursorTrigger),this._specialCursorTrigger===0&&(this.context.domElement.style.cursor="default")}setPointerUsed(e,t=!0){if(e>=this._pointerUsed.length){if(e>=this._pointerIds.length)return;for(;this._pointerUsed.length<=e;)this._pointerUsed.push(!1)}this._pointerUsed[e]=t}getPointerUsed(e){return e>=this._pointerUsed.length?!1:this._pointerUsed[e]}getPointerPressedCount(){let e=0;for(let t=0;t<this._pointerPressed.length;t++)this._pointerPressed[t]&&e++;return e}getPointerPosition(e){return e>=this._pointerPositions.length?null:this._pointerPositions[e]}getPointerPositionLastFrame(e){return e>=this._pointerPositionsLastFrame.length?null:this._pointerPositionsLastFrame[e]}getPointerPositionDelta(e){return e>=this._pointerPositionsDelta.length?null:this._pointerPositionsDelta[e]}getPointerPositionRC(e){return e>=this._pointerPositionsRC.length?null:this._pointerPositionsRC[e]}getPointerDown(e){return e>=this._pointerDown.length?!1:this._pointerDown[e]}getPointerUp(e){return e>=this._pointerUp.length?!1:this._pointerUp[e]}getPointerPressed(e){return e>=this._pointerPressed.length?!1:this._pointerPressed[e]}getPointerClicked(e){return e>=this._pointerClick.length?!1:this._pointerClick[e]}getPointerDoubleClicked(e){return e>=this._pointerDoubleClick.length?!1:this._pointerDoubleClick[e]}getPointerDownTime(e){return e>=this._pointerDownTime.length?-1:this._pointerDownTime[e]}getPointerUpTime(e){return e>=this._pointerUpTime.length?-1:this._pointerUpTime[e]}getPointerLongPress(e){return e>=this._pointerDownTime.length?!1:this.getPointerPressed(e)&&this.context.time.time-this._pointerDownTime[e]>this._longPressTimeThreshold}getIsMouse(e){return e<0||e>=this._pointerTypes.length?!1:this._pointerTypes[e]==="mouse"}getIsTouch(e){return e<0||e>=this._pointerTypes.length?!1:this._pointerTypes[e]==="touch"}getTouchesPressedCount(){let e=0;for(let t=0;t<this._pointerPressed.length;t++)this._pointerPressed[t]&&this.getIsTouch(t)&&e++;return e}getMouseWheelChanged(e=0){return e>=this._mouseWheelChanged.length?!1:this._mouseWheelChanged[e]}getMouseWheelDeltaY(e=0){return e>=this._mouseWheelDeltaY.length?0:this._mouseWheelDeltaY[e]}getPointerEvent(e){if(!(e>=this._pointerEvent.length))return this._pointerEvent[e]??void 0}*foreachPointerId(e){for(let t=0;t<this._pointerTypes.length;t++)if(this._pointerIsActive(t)){if(e!==void 0){const i=this._pointerTypes[t];if(Array.isArray(e)){let n=!1;for(const r of e)if(i===r){n=!0;break}if(!n)continue}else if(e!==i)continue}yield t}}*foreachTouchId(){for(let e=0;e<this._pointerTypes.length;e++)this._pointerTypes[e]==="touch"&&this._pointerIsActive[e]&&(yield e)}_pointerIsActive(e){return e<0?!1:this._pointerPressed[e]||this._pointerDown[e]||this._pointerUp[e]}onDownButton(e,t){let i=this._pressedStack.get(e);i||(i=[],this._pressedStack.set(e,i)),i.push(t)}onReleaseButton(e,t){const i=this._pressedStack.get(e);if(!i)return;const n=i.indexOf(t);n>=0&&i.splice(n,1)}getFirstPressedButtonForPointer(e){const t=this._pressedStack.get(e);if(t)return t[0]}getLatestPressedButtonForPointer(e){const t=this._pressedStack.get(e);if(t)return t[t.length-1]}getKeyDown(){for(const e in this.keysPressed){const t=this.keysPressed[e];if(t.startFrame===this.context.time.frameCount)return t.key}return null}getKeyPressed(){for(const e in this.keysPressed){const t=this.keysPressed[e];if(t.pressed)return t.key}return null}isKeyDown(e){var i;if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const t=this.getCodeForCommonKeyName(e);if(t!==null){for(const n of t)if(this.isKeyDown(n))return!0;return!1}return((i=this.keysPressed[e])==null?void 0:i.startFrame)===this.context.time.frameCount&&this.keysPressed[e].pressed}isKeyUp(e){var i;if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const t=this.getCodeForCommonKeyName(e);if(t!==null){for(const n of t)if(this.isKeyUp(n))return!0;return!1}return((i=this.keysPressed[e])==null?void 0:i.frame)===this.context.time.frameCount&&!this.keysPressed[e].pressed}isKeyPressed(e){var i;if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const t=this.getCodeForCommonKeyName(e);if(t!==null){for(const n of t)if(this.isKeyPressed(n))return!0;return!1}return(i=this.keysPressed[e])==null?void 0:i.pressed}getCodeForCommonKeyName(e){if(e.length===1){if(e>="0"&&e<="9")return["Digit"+e];if(e>="a"&&e<="z")return["Key"+e.toUpperCase()];if(e==" ")return["Space"]}switch(e){case"shift":case"Shift":return["ShiftLeft","ShiftRight"];case"control":case"Control":return["ControlLeft","ControlRight"];case"alt":case"Alt":return["AltLeft","AltRight"]}return null}createInputEvent(e){switch(e.type){case"pointerdown":hs&&pn("Create Pointer down"),this.onDownButton(e.deviceIndex,e.button),this.onDown(e);break;case"pointermove":hs&&pn("Create Pointer move"),this.onMove(e);break;case"pointerup":hs&&pn("Create Pointer up"),this.onUp(e),this.onReleaseButton(e.deviceIndex,e.button);break}}convertScreenspaceToRaycastSpace(e){return e.x=(e.x-this.context.domX)/this.context.domWidth*2-1,e.y=-((e.y-this.context.domY)/this.context.domHeight)*2+1,e}bindEvents(){this.unbindEvents(),this._htmlEventSource=this.context.renderer.domElement,window.addEventListener("contextmenu",this.onContextMenu),this._htmlEventSource.addEventListener("pointerdown",this.onPointerDown,{passive:!0}),window.addEventListener("pointermove",this.onPointerMove,{passive:!0,capture:!0}),window.addEventListener("pointerup",this.onPointerUp,{passive:!0}),window.addEventListener("pointercancel",this.onPointerCancel,{passive:!0}),window.addEventListener("touchstart",this.onTouchStart,{passive:!0}),window.addEventListener("touchmove",this.onTouchMove,{passive:!0}),window.addEventListener("touchend",this.onTouchEnd,{passive:!0}),this._htmlEventSource.addEventListener("wheel",this.onMouseWheel,{passive:!0}),window.addEventListener("wheel",this.onWheelWindow,{passive:!0}),window.addEventListener("keydown",this.onKeyDown,!1),window.addEventListener("keypress",this.onKeyPressed,!1),window.addEventListener("keyup",this.onKeyUp,!1),window.addEventListener("blur",this.onLostFocus)}unbindEvents(){var e,t;window.removeEventListener("contextmenu",this.onContextMenu),(e=this._htmlEventSource)==null||e.removeEventListener("pointerdown",this.onPointerDown),window.removeEventListener("pointermove",this.onPointerMove),window.removeEventListener("pointerup",this.onPointerUp),window.removeEventListener("pointercancel",this.onPointerCancel),(t=this._htmlEventSource)==null||t.removeEventListener("wheel",this.onMouseWheel,!1),window.removeEventListener("wheel",this.onWheelWindow,!1),window.removeEventListener("keydown",this.onKeyDown,!1),window.removeEventListener("keypress",this.onKeyPressed,!1),window.removeEventListener("keyup",this.onKeyUp,!1),window.removeEventListener("blur",this.onLostFocus)}dispose(){const e=this.context.post_render_callbacks.indexOf(this.onEndOfFrame);e>=0&&this.context.post_render_callbacks.splice(e,1),this.unbindEvents()}canReceiveInput(e){var t;return e.target===((t=this.context.renderer)==null?void 0:t.domElement)||e.target===this.context.domElement||this.context.isInAR||this.context.isInAR&&e.target===document.body&&Kf()?!0:(hs&&console.warn("CanReceiveInput:False for",e.target),!1)}getPointerId(e,t){return e.pointerType==="mouse"?0+(t??e.button):this.getPointerIndex(e.pointerId)}getButtonName(e){const t=e.button;if(e.pointerType==="mouse")switch(t){case 0:return"left";case 1:return"middle";case 2:return"right"}return"unknown"}getAndUpdateSpatialObjectForScreenPosition(e,t,i){let n=this._pointerSpace[e];n||(n=new ve,this._pointerSpace[e]=n),this._pointerSpace[e]=n;const r=this.context.mainCamera;if(r){const o=this.tempNearPlaneVector.set(t,i,-1);this.convertScreenspaceToRaycastSpace(o);const a=this.tempFarPlaneVector.set(o.x,o.y,1);o.unproject(r),a.unproject(r);const l=r.worldUp||pi(0,1,0).applyQuaternion(Ri(r));this.tempLookMatrix.lookAt(a,o,l),n.position.set(o.x,o.y,o.z),n.quaternion.setFromRotationMatrix(this.tempLookMatrix)}return n}isInRect(e){if(this.context.isInXR)return!0;const t=this.context.domElement.getBoundingClientRect(),i=e.clientX,n=e.clientY,r=i>=t.x&&i<=t.right&&n>=t.y&&n<=t.bottom;return hs&&!r&&console.log("Not in rect",t,i,n),r}onDown(e){const t=e.pointerId;if(this.getPointerPressed(t)&&console.warn(`pointerId is already pressed: ${t}`,hs?e:""),hs&&console.log(e.pointerType,"DOWN",t),!!this.isInRect(e)){for(this.setPointerState(t,this._pointerPressed,!0),this.setPointerState(t,this._pointerDown,!0),this.setPointerStateT(t,this._pointerEvent,e.source);t>=this._pointerTypes.length;)this._pointerTypes.push(e.pointerType);for(this._pointerTypes[t]=e.pointerType;t>=this._pointerPositionDown.length;)this._pointerPositionDown.push(new ee);for(this._pointerPositionDown[t].set(e.clientX,e.clientY);t>=this._pointerPositions.length;)this._pointerPositions.push(new ee);this._pointerPositions[t].set(e.clientX,e.clientY),t>=this._pointerDownTime.length&&this._pointerDownTime.push(0),this._pointerDownTime[t]=this.context.time.time,this.updatePointerPosition(e),this.onDispatchEvent(e)}}onMove(e){const t=e.pointerId,i=this.getPointerPressed(t);i===!1&&!this.isInRect(e)||e.pointerType==="touch"&&!i||(this.updatePointerPosition(e),this.setPointerStateT(t,this._pointerEvent,e.source),this.onDispatchEvent(e))}onUp(e){const t=e.pointerId;if(!this.getPointerPressed(t)){hs&&console.log(e.pointerType,"UP",t,"was not down");return}for(hs&&console.log(e.pointerType,"UP",t),this.setPointerState(t,this._pointerPressed,!1),this.setPointerStateT(t,this._pointerEvent,e.source),this.setPointerState(t,this._pointerUp,!0);t>=this._pointerUsed.length;)this._pointerUsed.push(!1);if(this.setPointerState(t,this._pointerUsed,!1),this.updatePointerPosition(e),!this._pointerPositionDown[t]){hs&&Ni("Received pointer up event without matching down event for button: "+t),console.warn("Received pointer up event without matching down event for button: "+t);return}const n=e.clientX-this._pointerPositionDown[t].x,r=e.clientY-this._pointerPositionDown[t].y;if(t>=this._pointerUpTime.length&&this._pointerUpTime.push(-99),Math.abs(n)<5&&Math.abs(r)<5){hs&&console.log("CLICK",t),this.setPointerState(t,this._pointerClick,!0),e.isClick=!0;const o=this._pointerUpTime[t],a=this.context.time.time-o;a<this._doubleClickTimeThreshold&&a>0&&(this.setPointerState(t,this._pointerDoubleClick,!0),e.isDoubleClick=!0)}this._pointerUpTime[t]=this.context.time.time,this.onDispatchEvent(e)}updatePointerPosition(e){const t=e.pointerId;for(;t>=this._pointerPositions.length;)this._pointerPositions.push(new ee);for(;t>=this._pointerPositionsLastFrame.length;)this._pointerPositionsLastFrame.push(new ee);for(;t>=this._pointerPositionsDelta.length;)this._pointerPositionsDelta.push(new ee);const i=this._pointerPositionsLastFrame[t];i.copy(this._pointerPositions[t]);const n=this._pointerPositionsDelta[t];let r=e.clientX-i.x,o=e.clientY-i.y;if(e.source instanceof MouseEvent||e.source instanceof TouchEvent){const h=e.source;r===0&&h.movementX!==0&&(r=h.movementX||0),o===0&&h.movementY!==0&&(o=h.movementY||0)}n.x+=r,n.y+=o,this._pointerPositions[t].x=e.clientX,this._pointerPositions[t].y=e.clientY;const a=e.clientX,l=e.clientY;for(;t>=this._pointerPositionsRC.length;)this._pointerPositionsRC.push(new ee);const c=this._pointerPositionsRC[t];c.set(a,l),this.convertScreenspaceToRaycastSpace(c)}getPointerIndex(e){let t=-1;for(let i=0;i<this._pointerIds.length;i++){if(this._pointerIds[i]===e)return i;t===-1&&this._pointerIds[i]===-1&&(t=i)}return t!==-1?(this._pointerIds[t]=e,t):(hs&&console.log("PUSH pointerId:",e),this._pointerIds.push(e),this._pointerIds.length-1)}setPointerState(e,t,i){t[e]=i}setPointerStateT(e,t,i){return t[e]=i,i}onDispatchEvent(e){const t=Ot.Current;try{Ot.Current=this.context,this.dispatchEvent(e)}finally{Ot.Current=t}}}const EC=new ye().makeRotationY(Math.PI),Ca=new Ce().setFromAxisAngle(new w(0,1,0),Math.PI),xue=ie("debugwebxr");class wue{constructor(){d(this,"priority",-1e5);d(this,"gameObject");if(this.gameObject=new ve,this.gameObject.name="Implicit XR Rig",xue){const e=BO(16733661);e.position.y+=.5,this.gameObject.add(e)}}isXRRig(){return!0}get isActive(){return this.gameObject.visible}}const wu=ie("debugwebxr"),mw=ie("debugcustomgesture"),Sue="https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles",Cue="generic-trigger";class DO{constructor(e,t,i){d(this,"xr");d(this,"inputSource");d(this,"index",0);d(this,"emitEvents",!0);d(this,"_connected",!0);d(this,"_isTracking",!1);d(this,"_hitTestSource");d(this,"_hasSelectEvent",!1);d(this,"_handJointPoses",new Map);d(this,"_gripPosition",new w);d(this,"_gripQuaternion",new Ce);d(this,"_linearVelocity",new w);d(this,"_rayPosition",new w);d(this,"_rayQuaternion",new Ce);d(this,"_gripWorldPosition",new w);d(this,"_gripWorldQuaternion",new Ce);d(this,"_rayWorldPosition",new w);d(this,"_rayWorldQuaternion",new Ce);d(this,"_ray");d(this,"_object");d(this,"model",null);d(this,"_debugAxesHelper",new na(.2));d(this,"onPointerHits",e=>{});d(this,"_needleGamepadButtons",{});d(this,"_buttonMap",new Map);d(this,"_motioncontroller");d(this,"_layout");d(this,"getMotionController");d(this,"_selectButtonIndex");d(this,"_squeezeButtonIndex");d(this,"onSelectStart",e=>{var n,r,o,a;if(this.inputSource!==e.inputSource)return;this.onUpdateFrame(e.frame),this._hasSelectEvent=!0;const t=(n=this._layout)==null?void 0:n.selectComponentId,i=(a=(o=(r=this._layout)==null?void 0:r.components[t])==null?void 0:o.gamepadIndices)==null?void 0:a.button;i!==void 0&&(this._selectButtonIndex=i),!mw&&(wu&&_t.DrawDirection(this.rayWorldPosition,pi(0,.01,1).applyQuaternion(this.rayWorldQuaternion),16711680,10),this.emitPointerEvent(fn.PointerDown,this._selectButtonIndex||0,"xr-standard-trigger",!0,e))});d(this,"onSelectEnd",e=>{mw||this.inputSource===e.inputSource&&this.emitPointerEvent(fn.PointerUp,this._selectButtonIndex||0,"xr-standard-trigger",!0,e)});d(this,"onSequeezeStart",e=>{var t,i,n;this.inputSource===e.inputSource&&(this._squeezeButtonIndex=(n=(i=(t=this._layout)==null?void 0:t.components["xr-standard-squeeze"])==null?void 0:i.gamepadIndices)==null?void 0:n.button,this._squeezeButtonIndex!==void 0&&(wu&&_t.DrawDirection(this.rayWorldPosition,pi(0,.01,1).applyQuaternion(this.rayWorldQuaternion),255,10),this.emitPointerEvent(fn.PointerDown,this._squeezeButtonIndex||0,"xr-standard-squeeze",!0,e)))});d(this,"onSequeezeEnd",e=>{this.inputSource===e.inputSource&&this._squeezeButtonIndex!==void 0&&this.emitPointerEvent(fn.PointerUp,this._squeezeButtonIndex||0,"xr-standard-squeeze",!0,e)});d(this,"states",{});d(this,"_didMoveLastFrame",!1);d(this,"_lastPointerMovePosition",new w);d(this,"_lastPointerMoveQuaternion",new Ce);d(this,"pointerInit");var n,r,o;this.xr=e,this.inputSource=t,this.index=i,this._object=new ve,wu&&this._object.add(this._debugAxesHelper),this.xr.context.scene.add(this._object),this._ray=new Mo,this.pointerInit={origin:this,pointerType:this.hand?"hand":"controller",deviceIndex:this.index,pointerId:-1,mode:this.inputSource.targetRayMode,ray:this._ray,device:this._object,buttonName:"none"},this.initialize(),this.subscribeEvents(),this.xr.mode==="immersive-ar"&&this.inputSource.targetRayMode==="tracked-pointer"&&((o=(r=(n=this.xr.session).requestHitTestSourceForTransientInput)==null?void 0:r.call(n,{profile:this.inputSource.profiles[0],offsetRay:new XRRay}))==null||o.then(a=>this._hitTestSource=a))}get context(){return this.xr.context}get connected(){return this._connected}get isTracking(){return this._isTracking}get gamepad(){return this.inputSource.gamepad}get isHand(){return this.inputSource.hand!=null}get hand(){return this.inputSource.hand}get handObject(){return this.context.renderer.xr.getHand(this.index)}get profiles(){return this.inputSource.profiles}get layout(){return this._layout}get targetRayMode(){return this.inputSource.targetRayMode}get targetRaySpace(){return this.inputSource.targetRaySpace}get gripSpace(){return this.inputSource.gripSpace}get side(){return this.inputSource.handedness}get isRight(){return this.side==="right"}get isLeft(){return this.side==="left"}get hitTestSource(){return this._hitTestSource}get hasSelectEvent(){return this._hasSelectEvent}getHitTest(){return this.xr.getHitTest(this)}getHandJointPose(e){var i,n;if(!this.hand||!((i=this.xr.frame)!=null&&i.getJointPose)||!this.xr.referenceSpace)return null;let t=(n=this._handJointPoses)==null?void 0:n.get(e);return t||(t=this.xr.frame.getJointPose(e,this.xr.referenceSpace),t&&this._handJointPoses.set(e,t),t)}get gripPosition(){return pi(this._gripPosition).applyMatrix4(EC)}get gripQuaternion(){return Nf(this._gripQuaternion).premultiply(Ca)}get gripLinearVelocity(){return pi(this._linearVelocity).applyQuaternion(Ca)}get rayPosition(){return pi(this._rayPosition).applyMatrix4(EC)}get rayQuaternion(){return Nf(this._rayQuaternion).premultiply(Ca)}get gripWorldPosition(){return pi(this._gripWorldPosition)}get gripWorldQuaternion(){return Nf(this._gripWorldQuaternion)}get rayWorldPosition(){return pi(this._rayWorldPosition)}updateRayWorldPosition(){var t;const e=(t=this.xr.context.mainCamera)==null?void 0:t.parent;this._rayWorldPosition.copy(this._rayPosition),e&&this._rayWorldPosition.applyMatrix4(e.matrixWorld)}get rayWorldQuaternion(){return Nf(this._rayWorldQuaternion)}updateRayWorldQuaternion(){var i;const e=(i=this.xr.context.mainCamera)==null?void 0:i.parent,t=e?Ri(e):void 0;this._rayWorldQuaternion.copy(this._rayQuaternion).multiply(Ca),t&&this._rayWorldQuaternion.premultiply(t)}get ray(){return this._ray.origin.copy(this.rayWorldPosition),this._ray.direction.copy(pi(0,0,1).applyQuaternion(this.rayWorldQuaternion)),this._ray}get object(){return this._object}async getModelUrl(){var e;return(e=this.getMotionController)==null?void 0:e.then(t=>(t==null?void 0:t.assetUrl)||null)}onUpdate(e){this.onUpdateFrame(e),this.updateInputEvents(),this.onUpdateMove()}onRenderDebug(){var n;_t.DrawWireSphere(this.rayWorldPosition,.02),_t.DrawDirection(this.rayWorldPosition,pi(0,0,10).applyQuaternion(this.rayWorldQuaternion));const e=this.gripWorldPosition.sub(this.object.worldForward.multiplyScalar(.1)),t=this.inputSource.profiles.join(`
|
|
5151
|
+
*/var nue=function(s){return s!=null&&(PQ(s)||sue(s)||!!s._isBuffer)};function PQ(s){return!!s.constructor&&typeof s.constructor.isBuffer=="function"&&s.constructor.isBuffer(s)}function sue(s){return typeof s.readFloatLE=="function"&&typeof s.slice=="function"&&PQ(s.slice(0,0))}(function(){var s=iue,e=P3.utf8,t=nue,i=P3.bin,n=function(r,o){r.constructor==String?o&&o.encoding==="binary"?r=i.stringToBytes(r):r=e.stringToBytes(r):t(r)?r=Array.prototype.slice.call(r,0):!Array.isArray(r)&&r.constructor!==Uint8Array&&(r=r.toString());for(var a=s.bytesToWords(r),l=r.length*8,c=1732584193,h=-271733879,u=-1732584194,f=271733878,p=0;p<a.length;p++)a[p]=(a[p]<<8|a[p]>>>24)&16711935|(a[p]<<24|a[p]>>>8)&4278255360;a[l>>>5]|=128<<l%32,a[(l+64>>>9<<4)+14]=l;for(var m=n._ff,y=n._gg,g=n._hh,v=n._ii,p=0;p<a.length;p+=16){var _=c,A=h,b=u,S=f;c=m(c,h,u,f,a[p+0],7,-680876936),f=m(f,c,h,u,a[p+1],12,-389564586),u=m(u,f,c,h,a[p+2],17,606105819),h=m(h,u,f,c,a[p+3],22,-1044525330),c=m(c,h,u,f,a[p+4],7,-176418897),f=m(f,c,h,u,a[p+5],12,1200080426),u=m(u,f,c,h,a[p+6],17,-1473231341),h=m(h,u,f,c,a[p+7],22,-45705983),c=m(c,h,u,f,a[p+8],7,1770035416),f=m(f,c,h,u,a[p+9],12,-1958414417),u=m(u,f,c,h,a[p+10],17,-42063),h=m(h,u,f,c,a[p+11],22,-1990404162),c=m(c,h,u,f,a[p+12],7,1804603682),f=m(f,c,h,u,a[p+13],12,-40341101),u=m(u,f,c,h,a[p+14],17,-1502002290),h=m(h,u,f,c,a[p+15],22,1236535329),c=y(c,h,u,f,a[p+1],5,-165796510),f=y(f,c,h,u,a[p+6],9,-1069501632),u=y(u,f,c,h,a[p+11],14,643717713),h=y(h,u,f,c,a[p+0],20,-373897302),c=y(c,h,u,f,a[p+5],5,-701558691),f=y(f,c,h,u,a[p+10],9,38016083),u=y(u,f,c,h,a[p+15],14,-660478335),h=y(h,u,f,c,a[p+4],20,-405537848),c=y(c,h,u,f,a[p+9],5,568446438),f=y(f,c,h,u,a[p+14],9,-1019803690),u=y(u,f,c,h,a[p+3],14,-187363961),h=y(h,u,f,c,a[p+8],20,1163531501),c=y(c,h,u,f,a[p+13],5,-1444681467),f=y(f,c,h,u,a[p+2],9,-51403784),u=y(u,f,c,h,a[p+7],14,1735328473),h=y(h,u,f,c,a[p+12],20,-1926607734),c=g(c,h,u,f,a[p+5],4,-378558),f=g(f,c,h,u,a[p+8],11,-2022574463),u=g(u,f,c,h,a[p+11],16,1839030562),h=g(h,u,f,c,a[p+14],23,-35309556),c=g(c,h,u,f,a[p+1],4,-1530992060),f=g(f,c,h,u,a[p+4],11,1272893353),u=g(u,f,c,h,a[p+7],16,-155497632),h=g(h,u,f,c,a[p+10],23,-1094730640),c=g(c,h,u,f,a[p+13],4,681279174),f=g(f,c,h,u,a[p+0],11,-358537222),u=g(u,f,c,h,a[p+3],16,-722521979),h=g(h,u,f,c,a[p+6],23,76029189),c=g(c,h,u,f,a[p+9],4,-640364487),f=g(f,c,h,u,a[p+12],11,-421815835),u=g(u,f,c,h,a[p+15],16,530742520),h=g(h,u,f,c,a[p+2],23,-995338651),c=v(c,h,u,f,a[p+0],6,-198630844),f=v(f,c,h,u,a[p+7],10,1126891415),u=v(u,f,c,h,a[p+14],15,-1416354905),h=v(h,u,f,c,a[p+5],21,-57434055),c=v(c,h,u,f,a[p+12],6,1700485571),f=v(f,c,h,u,a[p+3],10,-1894986606),u=v(u,f,c,h,a[p+10],15,-1051523),h=v(h,u,f,c,a[p+1],21,-2054922799),c=v(c,h,u,f,a[p+8],6,1873313359),f=v(f,c,h,u,a[p+15],10,-30611744),u=v(u,f,c,h,a[p+6],15,-1560198380),h=v(h,u,f,c,a[p+13],21,1309151649),c=v(c,h,u,f,a[p+4],6,-145523070),f=v(f,c,h,u,a[p+11],10,-1120210379),u=v(u,f,c,h,a[p+2],15,718787259),h=v(h,u,f,c,a[p+9],21,-343485551),c=c+_>>>0,h=h+A>>>0,u=u+b>>>0,f=f+S>>>0}return s.endian([c,h,u,f])};n._ff=function(r,o,a,l,c,h,u){var f=r+(o&a|~o&l)+(c>>>0)+u;return(f<<h|f>>>32-h)+o},n._gg=function(r,o,a,l,c,h,u){var f=r+(o&l|a&~l)+(c>>>0)+u;return(f<<h|f>>>32-h)+o},n._hh=function(r,o,a,l,c,h,u){var f=r+(o^a^l)+(c>>>0)+u;return(f<<h|f>>>32-h)+o},n._ii=function(r,o,a,l,c,h,u){var f=r+(a^(o|~l))+(c>>>0)+u;return(f<<h|f>>>32-h)+o},n._blocksize=16,n._digestsize=16,IQ.exports=function(r,o){if(r==null)throw new Error("Illegal argument "+r);var a=s.wordsToBytes(n(r,o));return o&&o.asBytes?a:o&&o.asString?i.bytesToString(a):s.bytesToHex(a)}})();var rue=IQ.exports;const oue=cE(rue);class fB{constructor(e,t,i,n){d(this,"success");d(this,"filename");d(this,"hash");d(this,"size");d(this,"url");this.success=e,this.filename=t,this.hash=i,this.size=n}}async function BQ(s,e){const t=await s.arrayBuffer(),i=IO(t),n=s.name.split(".").pop(),r=i+"."+n,o=s.name.split(".").shift();console.assert(o!==void 0);const a={alias:o,filename:r},c=await(await fetch(e+"/exists",{method:"POST",body:JSON.stringify(a)})).json();if(c.success||console.warn("exists check did fail"),c.exists)return console.log("file already exists",i),new fB(!0,r,i,s.size);console.log("begin uploading file",o,s.size);const h=new FormData;h.append("file",s);const u={};u.filesize=s.size,o&&(u.alias=o);const p=await(await fetch(e+"/upload/file",{method:"POST",body:h,headers:u})).json();if((p==null?void 0:p.success)===!1)return p.message!==void 0?console.error("Upload failed:",p.message):console.error("Upload failed"),null;console.assert(p.hash_sum===i,"hash sum did not match","received:",p.hash_sum,"expected:",i),p.success&&console.log("successfully uploaded",i,p.id);const m=new fB(p.success,r,i,s.size);return m.url=e,m}function IO(s){return oue(new Uint8Array(s))}async function RO(s,e,t,i,n=!1){try{const r=await fetch(i+"/download/file",{method:"POST",body:s});if(r.status!==200)return console.error("download failed",r),null;const o=await r.blob(),a=await o.arrayBuffer();n||console.assert(o.size===t,"size mismatch","expected:",t,"got:",o.size);const l=IO(a);return n||console.assert(l===e,"hash mismatch, downloaded file is invalid"),o.arrayBuffer()}catch(r){console.error(r)}return null}async function DQ(s,e){var h;const t=await fetch(s),i=(h=t.body)==null?void 0:h.getReader(),n=t.headers.get("Content-Length"),r=n?parseInt(n):0;if(!i)return null;let o=0;const a=[];for(;;){const{done:u,value:f}=await i.read();if(f&&(a.push(f),o+=f.length,e.call(null,new ProgressEvent("progress",{loaded:o,total:r}))),u)break}const l=new Uint8Array(o);let c=0;for(const u of a)l.set(u,c),c+=u.length;return l}const xu=ie("debugaddressables");class OQ{constructor(e){d(this,"_context");d(this,"_assetReferences",{});d(this,"preUpdate",()=>{});this._context=e,this._context.pre_update_callbacks.push(this.preUpdate)}dispose(){const e=this._context.pre_update_callbacks.indexOf(this.preUpdate);e>=0&&this._context.pre_update_callbacks.splice(e,1);for(const t in this._assetReferences){const i=this._assetReferences[t];i==null||i.unload()}this._assetReferences={}}findAssetReference(e){return this._assetReferences[e]||null}registerAssetReference(e){return e.uri&&(this._assetReferences[e.uri]?console.warn("Asset reference already registered",e):this._assetReferences[e.uri]=e),e}unregisterAssetReference(e){e.uri&&delete this._assetReferences[e.uri]}}const xI=Symbol("assetReference"),Df=class{constructor(e,t,i=null){d(this,"_loading");d(this,"_asset");d(this,"_glbRoot");d(this,"_url");d(this,"_progressListeners",[]);d(this,"_hash");d(this,"_hashedUri");d(this,"_isLoadingRawBinary",!1);d(this,"_rawBinary");this._url=e,this._hash=t,e.includes("?v=")?this._hashedUri=e:this._hashedUri=t?e+"?v="+t:e,i!==null&&(this.asset=i),sj(this._url,this.onResolvePrefab.bind(this))}static getOrCreateFromUrl(e,t){if(!t&&(t=Ot.Current,!t))throw new Error('Context is required when sourceId is a string. When you call this method from a component you can call it with "getOrCreate(this, url)" where "this" is the component.');const i=t.addressables,n=i.findAssetReference(e);if(n)return n;const r=new Df(e,t.hash);return i.registerAssetReference(r),r}static getOrCreate(e,t,i){if(typeof e=="string"){if(!i&&(i=Ot.Current,!i))throw new Error('Context is required when sourceId is a string. When you call this method from a component you can call it with "getOrCreate(this, url)" where "this" is the component.')}else i=e.context,e=e.sourceId;const n=wd(e,t);xu&&console.log("GetOrCreate Addressable from",e,t,"FinalPath=",n);const r=i.addressables,o=r.findAssetReference(n);if(o)return o;const a=new Df(n,i.hash);return r.registerAssetReference(a),a}get asset(){return this._glbRoot??this._asset}set asset(e){this._asset=e}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(e){return e===this.uri&&(this.mustLoad&&await this.loadAssetAsync(),this.asset)?this.asset:null}get mustLoad(){return!this.asset||this.asset.__destroyed===!0||Cp(this.asset)===!0}isLoaded(){return this._rawBinary||this.asset!==void 0}unload(){this.asset&&(xu&&console.log("Unload",this.asset),this.asset.scene&&Ga(this.asset.scene,!0,!0),Ga(this.asset,!0,!0)),this.asset=null,this._rawBinary=void 0,this._glbRoot=null,this._loading=void 0,Ot.Current&&Ot.Current.addressables.unregisterAssetReference(this)}async preload(){if(!this.mustLoad||this._isLoadingRawBinary)return null;if(this._rawBinary!==void 0)return this._rawBinary;this._isLoadingRawBinary=!0,xu&&console.log("Preload",this._hashedUri);const e=await DQ(this._hashedUri,t=>{this.raiseProgressEvent(t)});return this._rawBinary=(e==null?void 0:e.buffer)??null,this._isLoadingRawBinary=!1,this._rawBinary}async loadAssetAsync(e){if(xu&&console.log("loadAssetAsync",this.uri),!this.mustLoad)return this.asset;if(e&&this._progressListeners.push(e),this._loading!==void 0)return this._loading.then(n=>this.asset);const t=Ot.Current;this._rawBinary?(this._loading=Cl().parseSync(t,this._rawBinary,this.uri,null),this.raiseProgressEvent(new ProgressEvent("progress",{loaded:this._rawBinary.byteLength,total:this._rawBinary.byteLength}))):(xu&&console.log("Load async",this.uri),this._loading=Cl().loadSync(t,this._hashedUri,this.uri,null,n=>{this.raiseProgressEvent(n)}));const i=await this._loading;if(this._progressListeners.length=0,this._glbRoot=this.tryGetActualGameObjectRoot(i),this._loading=void 0,i)return i[xI]=this,this._glbRoot&&(this._glbRoot[xI]=this),this.asset&&(this.asset[xI]=this),xC(t),i.scene!==void 0&&(this.asset=i),this.asset}async instantiate(e){return this.onInstantiate(e,!1)}async instantiateSynced(e,t=!0){return this.onInstantiate(e,!0,t)}beginListenDownload(e){this._progressListeners.indexOf(e)<0&&this._progressListeners.push(e)}endListenDownload(e){const t=this._progressListeners.indexOf(e);t>=0&&this._progressListeners.splice(t,1)}raiseProgressEvent(e){for(const t of this._progressListeners)t(this,e)}async onInstantiate(e,t=!1,i){const n=Ot.Current,r=new Bl;if(e instanceof ve?r.parent=e:e&&(Object.assign(r,e),r.cloneAssign(e)),r.parent||(r.parent=n.scene),this.mustLoad&&await this.loadAssetAsync(),xu&&console.log("Instantiate",this.uri,"parent:",e),this.asset){xu&&console.log("Add to scene",this.asset);let o=Df.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,Df.currentlyInstantiating.set(this.uri,o),t){r.context=n;const a=this.asset;a.guid=this.uri;const l=WO(a,r,void 0,i);if(l)return l}else{const a=Uy(this.asset,r);if(a)return a}}finally{n.post_render_callbacks.push(()=>{o===void 0||o<0?o=0:o-=1,Df.currentlyInstantiating.set(this.uri,o)})}}else xu&&console.warn("Failed to load asset",this.uri);return null}tryGetActualGameObjectRoot(e){if(e&&e.scene){const t=e.scene;return t.isGroup&&t.children.length===1&&t.children[0].name+"glb"===t.name?t.children[0]:t}return null}};let Zt=Df;d(Zt,"currentlyInstantiating",new Map);class aue extends Xa{constructor(){super([Zt],"AssetReferenceSerializer")}onSerialize(e,t){if(e&&e.uri!==void 0&&typeof e.uri=="string")return e.uri}onDeserialize(e,t){if(typeof e=="string")return t.context?t.gltfId?Zt.getOrCreate(t.gltfId,e,t.context):(console.error("Missing source id"),null):(console.error("Missing context"),null);if(e instanceof ve){if(!t.context)return console.error("Missing context"),null;if(!t.gltfId)return console.error("Missing source id"),null;const i=e,n=t.context,r=i.guid??i.uuid,o=n.addressables.findAssetReference(r);if(o)return o;const a=new Zt(r,void 0,i);return n.addressables.registerAssetReference(a),a}return null}}new aue;const lue=Promise.resolve(null),u0=class{constructor(e){d(this,"url");d(this,"_bitmap");d(this,"_bitmapObject");d(this,"loader",null);this.url=e}static getOrCreate(e){let t=u0.imageReferences.get(e);return t||(t=new u0(e),u0.imageReferences.set(e,t)),t}dispose(){this._bitmapObject&&this._bitmapObject.close(),this._bitmap=void 0}createHTMLImage(){const e=new Image;return e.src=this.url,e}createTexture(){return this.url?(this.loader||(this.loader=new mc),this.loader.setCrossOrigin("anonymous"),this.loader.loadAsync(this.url)):lue}getBitmap(){return this._bitmap?this._bitmap:(this._bitmap=new Promise((e,t)=>{const i=document.createElement("img");i.addEventListener("load",()=>{this._bitmap=createImageBitmap(i).then(n=>(this._bitmapObject=n,e(n),n))}),i.addEventListener("error",n=>{console.error("Failed to load image:"+this.url,n),e(null)}),i.src=this.url}),this._bitmap)}};let qg=u0;d(qg,"imageReferences",new Map);class LQ extends Xa{constructor(){super([qg],"ImageReferenceSerializer")}onSerialize(e,t){return null}onDeserialize(e,t){if(typeof e=="string"){const i=wd(t.gltfId,e);return qg.getOrCreate(i)}}}new LQ;const d0=class{constructor(e){d(this,"url");d(this,"res");this.url=e}static getOrCreate(e){let t=d0.cache.get(e);return t||(t=new d0(e),d0.cache.set(e,t)),t}async loadRaw(){return this.res||(this.res=fetch(this.url)),this.res.then(e=>e.blob())}async loadText(){return this.res||(this.res=fetch(this.url)),this.res.then(e=>e.text())}};let Xg=d0;d(Xg,"cache",new Map);class kQ extends Xa{constructor(){super([Xg],"FileReferenceSerializer")}onSerialize(e,t){return null}onDeserialize(e,t){if(typeof e=="string"){const i=wd(t.gltfId,e);return Xg.getOrCreate(i)}}}new kQ;class cue{constructor(e){d(this,"context");d(this,"mixers",[]);this.context=e}onDestroy(){this.mixers.forEach(e=>e.stopAllAction()),this.mixers.length=0}registerAnimationMixer(e){if(!e){console.warn("AnimationsRegistry.registerAnimationMixer called with null or undefined mixer");return}this.mixers.includes(e)||this.mixers.push(e)}unregisterAnimationMixer(e){if(!e)return;const t=this.mixers.indexOf(e);t!==-1&&this.mixers.splice(t,1)}}class my{static tryGetActionsFromMixer(e){const t=e._actions;return t||null}static tryGetAnimationClipsFromObjectHierarchy(e,t){if(t||(t=new Array),e)e.animations&&t.push(...e.animations);else return t;if(e.children)for(const i of e.children)this.tryGetAnimationClipsFromObjectHierarchy(i,t);return t}static assignAnimationsFromFile(e,t){if(!e||!e.animations)return;for(let n=0;n<e.animations.length;n++){const r=e.animations[n];if(!(!r.tracks||r.tracks.length<=0))for(const o in r.tracks){const a=r.tracks[o],l=Kt.parseTrackName(a.name);let c=Kt.findNode(e.scene,l.nodeName);if(!c){const u=a.__objectName??a.name.substring(0,a.name.indexOf("."));if(c=e.scene.getObjectByProperty("uuid",u),!c)continue}let h=i(c);if(!h){if(!(t!=null&&t.createAnimationComponent)){console.warn("No AnimationComponent found in parent hierarchy of object and no 'createAnimationComponent' callback was provided in options.");continue}h=t.createAnimationComponent(e.scene,r)}h.addClip&&h.addClip(r)}}function i(n){var o;if(!n)return null;const r=(o=n.userData)==null?void 0:o.components;if(r&&r.length>0){for(let a=0;a<r.length;a++)if(r[a].isAnimationComponent===!0)return n}return i(n.parent)}}}const gy=[];function hE(s){gy.indexOf(s)===-1&&gy.push(s)}function hue(s){const e=gy.indexOf(s);e!==-1&&gy.splice(e,1)}const yy=[];function PO(s){yy.indexOf(s)===-1&&yy.push(s)}function uue(s){const e=yy.indexOf(s);e!==-1&&yy.splice(e,1)}function FQ(s){globalThis.dispatchEvent(new CustomEvent("needle-xrsession-start",{detail:s}));for(let e=0;e<gy.length;e++)gy[e](s)}function UQ(s){globalThis.dispatchEvent(new CustomEvent("needle-xrsession-end",{detail:s}));for(let e=0;e<yy.length;e++)yy[e](s)}const Ps={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 NQ(s){const e=await fetch(s);if(e.ok)return e.json();throw new Error(e.statusText)}async function due(s){if(!s)throw new Error("No basePath supplied");return await NQ(`${s}/profilesList.json`)}async function fue(s,e,t=null,i=!0){if(!s)throw new Error("No xrInputSource supplied");if(!e)throw new Error("No basePath supplied");const n=await due(e);let r;if(s.profiles.some(l=>{const c=n[l];return c&&(r={profileId:l,profilePath:`${e}/${c.path}`,deprecated:!!c.deprecated}),!!r}),!r){if(!t)throw new Error("No matching profile name found");const l=n[t];if(!l)throw new Error(`No matching profile name found and default profile "${t}" missing.`);r={profileId:t,profilePath:`${e}/${l.path}`,deprecated:!!l.deprecated}}const o=await NQ(r.profilePath);let a;if(i){let l;if(s.handedness==="any"?l=o.layouts[Object.keys(o.layouts)[0]]:l=o.layouts[s.handedness],!l)throw new Error(`No matching handedness, ${s.handedness}, in profile ${r.profileId}`);l.assetPath&&(a=r.profilePath.replace("profile.json",l.assetPath))}return{profile:o,assetPath:a}}const pue={xAxis:0,yAxis:0,button:0,state:Ps.ComponentState.DEFAULT};function mue(s=0,e=0){let t=s,i=e;if(Math.sqrt(s*s+e*e)>1){const o=Math.atan2(e,s);t=Math.cos(o),i=Math.sin(o)}return{normalizedXAxis:t*.5+.5,normalizedYAxis:i*.5+.5}}let gue=class{constructor(e){this.componentProperty=e.componentProperty,this.states=e.states,this.valueNodeName=e.valueNodeName,this.valueNodeProperty=e.valueNodeProperty,this.valueNodeProperty===Ps.VisualResponseProperty.TRANSFORM&&(this.minNodeName=e.minNodeName,this.maxNodeName=e.maxNodeName),this.value=0,this.updateFromComponent(pue)}updateFromComponent({xAxis:e,yAxis:t,button:i,state:n}){const{normalizedXAxis:r,normalizedYAxis:o}=mue(e,t);switch(this.componentProperty){case Ps.ComponentProperty.X_AXIS:this.value=this.states.includes(n)?r:.5;break;case Ps.ComponentProperty.Y_AXIS:this.value=this.states.includes(n)?o:.5;break;case Ps.ComponentProperty.BUTTON:this.value=this.states.includes(n)?i:0;break;case Ps.ComponentProperty.STATE:this.valueNodeProperty===Ps.VisualResponseProperty.VISIBILITY?this.value=this.states.includes(n):this.value=this.states.includes(n)?1:0;break;default:throw new Error(`Unexpected visualResponse componentProperty ${this.componentProperty}`)}}},yue=class{constructor(e,t){if(!e||!t||!t.visualResponses||!t.gamepadIndices||Object.keys(t.gamepadIndices).length===0)throw new Error("Invalid arguments supplied");this.id=e,this.type=t.type,this.rootNodeName=t.rootNodeName,this.touchPointNodeName=t.touchPointNodeName,this.visualResponses={},Object.keys(t.visualResponses).forEach(i=>{const n=new gue(t.visualResponses[i]);this.visualResponses[i]=n}),this.gamepadIndices=Object.assign({},t.gamepadIndices),this.values={state:Ps.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(e){if(this.values.state=Ps.ComponentState.DEFAULT,this.gamepadIndices.button!==void 0&&e.buttons.length>this.gamepadIndices.button){const t=e.buttons[this.gamepadIndices.button];this.values.button=t.value,this.values.button=this.values.button<0?0:this.values.button,this.values.button=this.values.button>1?1:this.values.button,t.pressed||this.values.button===1?this.values.state=Ps.ComponentState.PRESSED:(t.touched||this.values.button>Ps.ButtonTouchThreshold)&&(this.values.state=Ps.ComponentState.TOUCHED)}this.gamepadIndices.xAxis!==void 0&&e.axes.length>this.gamepadIndices.xAxis&&(this.values.xAxis=e.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===Ps.ComponentState.DEFAULT&&Math.abs(this.values.xAxis)>Ps.AxisTouchThreshold&&(this.values.state=Ps.ComponentState.TOUCHED)),this.gamepadIndices.yAxis!==void 0&&e.axes.length>this.gamepadIndices.yAxis&&(this.values.yAxis=e.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===Ps.ComponentState.DEFAULT&&Math.abs(this.values.yAxis)>Ps.AxisTouchThreshold&&(this.values.state=Ps.ComponentState.TOUCHED)),Object.values(this.visualResponses).forEach(t=>{t.updateFromComponent(this.values)})}},vue=class{constructor(e,t,i){if(!e)throw new Error("No xrInputSource supplied");if(!t)throw new Error("No profile supplied");this.xrInputSource=e,this.assetUrl=i,this.id=t.profileId,this.layoutDescription=t.layouts[e.handedness],this.components={},Object.keys(this.layoutDescription.components).forEach(n=>{const r=this.layoutDescription.components[n];this.components[n]=new yue(n,r)}),this.updateFromGamepad()}get gripSpace(){return this.xrInputSource.gripSpace}get targetRaySpace(){return this.xrInputSource.targetRaySpace}get data(){const e=[];return Object.values(this.components).forEach(t=>{e.push(t.data)}),e}updateFromGamepad(){Object.values(this.components).forEach(e=>{e.updateFromGamepad(this.xrInputSource.gamepad)})}};const qr=new w,B3=new w,D3=new Ce,Aue=ie("debuggizmos"),Ul=8947848,pl=class{constructor(){}static isGizmo(e){return e[pB]!==void 0}static DrawLabel(e,t,i=.05,n=0,r,o,a){var h;if(!pl.enabled)return null;r||(r=Ul);const l=((h=xt.active)==null?void 0:h.rigScale)??1,c=Pn.getTextLabel(n,t,i*l,r,o);return a instanceof ve&&a.add(c),c.position.x=e.x,c.position.y=e.y,c.position.z=e.z,c}static DrawRay(e,t,i=Ul,n=0,r=!0){if(!pl.enabled)return;const o=Pn.getLine(n),a=o.geometry.getAttribute("position");a.setXYZ(0,e.x,e.y,e.z),qr.set(t.x,t.y,t.z).multiplyScalar(999999999),a.setXYZ(1,e.x+qr.x,e.y+qr.y,e.z+qr.z),a.needsUpdate=!0,o.material.color.set(i),o.material.depthTest=r,o.material.depthWrite=!1}static DrawDirection(e,t,i=Ul,n=0,r=!0,o=1){if(!pl.enabled)return;const a=Pn.getLine(n),l=a.geometry.getAttribute("position");l.setXYZ(0,e.x,e.y,e.z),t.w!==void 0?(qr.set(0,0,-o),D3.set(t.x,t.y,t.z,t.w),qr.applyQuaternion(D3)):(qr.set(t.x,t.y,t.z),qr.multiplyScalar(o)),l.setXYZ(1,e.x+qr.x,e.y+qr.y,e.z+qr.z),l.needsUpdate=!0,a.material.color.set(i),a.material.depthTest=r,a.material.depthWrite=!1}static DrawLine(e,t,i=Ul,n=0,r=!0){if(!pl.enabled)return;const o=Pn.getLine(n),a=o.geometry.getAttribute("position");a.setXYZ(0,e.x,e.y,e.z),a.setXYZ(1,t.x,t.y,t.z),a.needsUpdate=!0,o.material.color.set(i),o.material.depthTest=r,o.material.depthWrite=!1,o.material.fog=!1}static DrawWireSphere(e,t,i=Ul,n=0,r=!0){if(!pl.enabled)return;const o=Pn.getSphere(t,n,!0);wp(o,e.x,e.y,e.z),o.material.color.set(i),o.material.depthTest=r,o.material.depthWrite=!1,o.material.fog=!1}static DrawSphere(e,t,i=Ul,n=0,r=!0){if(!pl.enabled)return;const o=Pn.getSphere(t,n,!1);wp(o,e.x,e.y,e.z),o.material.color.set(i),o.material.depthTest=r,o.material.depthWrite=!1}static DrawWireBox(e,t,i=Ul,n=0,r=!0){if(!pl.enabled)return;const o=Pn.getBox(n);o.position.set(e.x,e.y,e.z),o.scale.set(t.x,t.y,t.z),o.material.color.set(i),o.material.depthTest=r,o.material.wireframe=!0,o.material.depthWrite=!1,o.material.fog=!1}static DrawWireBox3(e,t=Ul,i=0,n=!0){if(!pl.enabled)return;const r=Pn.getBox(i);r.position.copy(e.getCenter(qr)),r.scale.copy(e.getSize(qr)),r.material.color.set(t),r.material.depthTest=n,r.material.wireframe=!0,r.material.depthWrite=!1,r.material.fog=!1}static DrawArrow(e,t,i=Ul,n=0,r=!0,o=!1){if(!pl.enabled)return;const a=Pn.getArrowHead(n);a.position.set(t.x,t.y,t.z),a.quaternion.setFromUnitVectors(this._up.set(0,1,0),qr.set(t.x,t.y,t.z).sub(B3.set(e.x,e.y,e.z)).normalize());const c=qr.set(t.x,t.y,t.z).sub(B3.set(e.x,e.y,e.z)).length()*.1;a.scale.set(c,c,c),a.material.color.set(i),a.material.depthTest=r,a.material.wireframe=o,this.DrawLine(e,t,i,n,r)}static DrawWireMesh(e){const t=Pn.getMesh(e.duration??0);"mesh"in e?(t.geometry=e.mesh.geometry,t.matrix.copy(e.mesh.matrixWorld)):(t.geometry=e.geometry,t.matrix.copy(e.matrix)),t.matrixAutoUpdate=!1,t.matrixWorldAutoUpdate=!1,t.material.color.set(e.color??Ul),t.material.depthTest=e.depthTest??!0,t.material.wireframe=!0}};let _t=pl;d(_t,"enabled",!0),d(_t,"_up",new w(0,1,0));const _ue=new Xi(1,1,1);function BO(s=null){const e=new Ae(s??14540253),t=new X2(_ue);return new Dr(t,new Zi({color:e}))}const pB=Symbol("GizmoCache");class Pn{static ensureFont(){let e=Qi.FontLibrary.getFontFamily(this.familyName);if(!e){e=Qi.FontLibrary.addFontFamily(this.familyName);const t=e.addVariant("normal","normal","https://uploads.needle.tools/include/font-msdf.json","https://uploads.needle.tools/include/font.png");t==null||t.addEventListener("ready",()=>{Qi.update()})}}static getTextLabel(e,t,i,n,r){this.ensureFont();let o=this.textLabelCache.pop(),a=1;r&&typeof r=="string"&&(r==null?void 0:r.length)>=8&&r.startsWith("#")?(a=parseInt(r.substring(7),16)/255,r=r.substring(0,7),Aue&&console.log(r,a)):typeof r=="object"&&r.a!==void 0&&(a=r.a);const l={boxSizing:"border-box",fontFamily:this.familyName,width:"auto",fontSize:i,color:n,lineHeight:1,backgroundColor:r??void 0,backgroundOpacity:a,textContent:t,borderRadius:.5*i,padding:.8*i,whiteSpace:"pre"};if(o)o.set(l);else{o=new kD(l);const c=this,h=o;h.setText=function(u){this.set({textContent:u}),c.tmuiNeedsUpdate=!0}}return this.tmuiNeedsUpdate=!0,this.registerTimedObject(Ot.Current,o,e,this.textLabelCache),o}static getBox(e){let t=this.boxesCache.pop();if(!t){const i=new Xi(1,1,1);t=new fe(i)}return this.registerTimedObject(Ot.Current,t,e,this.boxesCache),t}static getLine(e){let t=this.linesCache.pop();if(!t){t=new Dn;let i=t.geometry.getAttribute("position");i||(i=new ot(new Float32Array(2*3),3),t.geometry.setAttribute("position",i))}return t.frustumCulled=!1,this.registerTimedObject(Ot.Current,t,e,this.linesCache),t}static getSphere(e,t,i){let n=this.spheresCache.pop();return n||(n=new fe(new Wa(1,8,8))),n.scale.set(e,e,e),n.material.wireframe=i,this.registerTimedObject(Ot.Current,n,t,this.spheresCache),n}static getArrowHead(e){let t=this.arrowHeadsCache.pop();return t||(t=new fe(new Hn(0,.5,1,8))),this.registerTimedObject(Ot.Current,t,e,this.arrowHeadsCache),t}static getMesh(e){let t=this.mesh.pop();return t||(t=new fe,t.material=new ni),this.registerTimedObject(Ot.Current,t,e,this.mesh),t}static registerTimedObject(e,t,i,n){const r=this.contextBeforeRenderCallbacks.get(e),o=this.contextPostRenderCallbacks.get(e);if(r){if(e.pre_render_callbacks[e.pre_render_callbacks.length-1]!==r){const a=e.pre_render_callbacks.indexOf(r);a>=0&&e.pre_render_callbacks.splice(a,1),e.pre_render_callbacks.push(r)}}else{const a=()=>{this.onBeforeRender(e,this.timedObjectsBuffer)};this.contextBeforeRenderCallbacks.set(e,a),e.pre_render_callbacks.push(a)}if(o){if(e.post_render_callbacks[e.post_render_callbacks.length-1]!==o){const a=e.post_render_callbacks.indexOf(o);a>=0&&e.post_render_callbacks.splice(a,1),e.post_render_callbacks.push(o)}}else{const a=()=>{this.onPostRender(e,this.timedObjectsBuffer,this.timesBuffer)};this.contextPostRenderCallbacks.set(e,a),e.post_render_callbacks.push(a)}t.traverse(a=>{a.layers.disableAll(),a.layers.enable(2)}),t.renderOrder=999999,t[pB]=n,t.isGizmo=!0,this.timedObjectsBuffer.push(t),i<=0&&e.currentFrameEvent>=$i.OnBeforeRender?this.timesBuffer.push(0):this.timesBuffer.push(Ot.Current.time.realtimeSinceStartup+i),e.scene.add(t)}static onBeforeRender(e,t){this.tmuiNeedsUpdate&&Qi.update();for(let i=0;i<t.length;i++){const n=t[i];if(e.mainCamera&&n instanceof Qi.MeshUIBaseElement){if(Cp(n))continue;const r=e.isInVR,o=!1,a=!r;I_(n,e.mainCamera,o,a)}}}static onPostRender(e,t,i){const n=e.time.realtimeSinceStartup;for(let r=t.length-1;r>=0;r--){const o=t[r];n>i[r]&&(t.splice(r,1),i.splice(r,1),o.removeFromParent(),Cp(o)!=!0&&o[pB].push(o))}}}d(Pn,"familyName","needle-gizmos"),d(Pn,"linesCache",[]),d(Pn,"spheresCache",[]),d(Pn,"boxesCache",[]),d(Pn,"arrowHeadsCache",[]),d(Pn,"mesh",[]),d(Pn,"textLabelCache",[]),d(Pn,"timedObjectsBuffer",new Array),d(Pn,"timesBuffer",new Array),d(Pn,"contextPostRenderCallbacks",new Map),d(Pn,"contextBeforeRenderCallbacks",new Map),d(Pn,"tmuiNeedsUpdate",!1);const hs=ie("debuginput");var uE=(s=>(s.Mouse="mouse",s.Touch="touch",s.Controller="controller",s.Hand="hand",s))(uE||{}),fn=(s=>(s.PointerDown="pointerdown",s.PointerUp="pointerup",s.PointerMove="pointermove",s.KeyDown="keydown",s.KeyUp="keyup",s.KeyPressed="keypress",s))(fn||{});class hh extends PointerEvent{constructor(t,i,n){super(t,n);d(this,"deviceIndex");d(this,"origin");d(this,"source");d(this,"mode");d(this,"_ray");d(this,"space");d(this,"isClick",!1);d(this,"isDoubleClick",!1);d(this,"_used",!1);d(this,"_pointerid");d(this,"_pointerType");d(this,"_type");d(this,"metadata",{});d(this,"intersections",new Array);d(this,"_immediatePropagationStopped",!1);d(this,"_propagationStopped",!1);this._pointerid=n.pointerId,this._pointerType=n.pointerType,this._type=t,this.deviceIndex=n.deviceIndex,this.origin=n.origin,this.source=i,this.mode=n.mode,this._ray=n.ray,this.space=n.device}get isSpatial(){return this.mode!="screen"}get ray(){return this._ray||(this._ray=new Mo(this.space.worldPosition.clone(),this.space.worldForward.clone())),this._ray}set ray(t){this._ray=t}get hasRay(){return this._ray!==void 0}get used(){return this._used}use(){this._used=!0}get pointerId(){return this._pointerid}get pointerType(){return this._pointerType}get type(){return this._type}get immediatePropagationStopped(){return this._immediatePropagationStopped}get propagationStopped(){return this._immediatePropagationStopped||this._propagationStopped}stopImmediatePropagation(){var t;this._immediatePropagationStopped=!0,super.stopImmediatePropagation(),(t=this.source)==null||t.stopImmediatePropagation()}stopPropagation(){var t;this._propagationStopped=!0,super.stopPropagation(),(t=this.source)==null||t.stopPropagation(),hs&&console.warn("Stop propagation...",this.pointerId,this.pointerType)}}class xA extends KeyboardEvent{constructor(t,i,n){super(t,n);d(this,"source");this.source=i}stopImmediatePropagation(){var t;super.stopImmediatePropagation(),(t=this.source)==null||t.stopImmediatePropagation()}}class bue{constructor(e){d(this,"key");d(this,"keyType");d(this,"source");this.key=e.key,this.keyType=e.type,this.source=e}}var $l=(s=>(s[s.Early=-100]="Early",s[s.Default=0]="Default",s[s.Late=100]="Late",s))($l||{});class zQ{constructor(e){d(this,"_eventListeners",{});d(this,"_doubleClickTimeThreshold",.2);d(this,"_longPressTimeThreshold",1);d(this,"_specialCursorTrigger",0);d(this,"context");d(this,"_pointerDown",[!1]);d(this,"_pointerUp",[!1]);d(this,"_pointerClick",[!1]);d(this,"_pointerDoubleClick",[!1]);d(this,"_pointerPressed",[!1]);d(this,"_pointerPositions",[new ee]);d(this,"_pointerPositionsLastFrame",[new ee]);d(this,"_pointerPositionsDelta",[new ee]);d(this,"_pointerPositionsRC",[new ee]);d(this,"_pointerPositionDown",[new ee]);d(this,"_pointerDownTime",[]);d(this,"_pointerUpTime",[]);d(this,"_pointerUpTimestamp",[]);d(this,"_pointerIds",[]);d(this,"_pointerTypes",[""]);d(this,"_mouseWheelChanged",[!1]);d(this,"_mouseWheelDeltaY",[0]);d(this,"_pointerEvent",[]);d(this,"_pointerUsed",[]);d(this,"_pointerSpace",[]);d(this,"_pressedStack",new Map);d(this,"_htmlEventSource");d(this,"onLostFocus",()=>{for(const e in this.keysPressed)this.keysPressed[e].pressed=!1});d(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});d(this,"onContextMenu",e=>{this.canReceiveInput(e)!==!1&&e instanceof PointerEvent&&e.pointerType});d(this,"keysPressed",{});d(this,"onKeyDown",e=>{if(hs&&console.log(`key down ${e.code}, ${this.context.application.hasFocus}`,e),!this.context.application.hasFocus)return;const t=this.keysPressed[e.code];if(t&&t.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 xA("keydown",e,e);this.onDispatchEvent(i)});d(this,"onKeyPressed",e=>{if(!this.context.application.hasFocus)return;const t=this.keysPressed[e.code];if(!t)return;t.pressed=!0,t.frame=this.context.time.frameCount+1;const i=new xA("keypress",e,e);this.onDispatchEvent(i)});d(this,"onKeyUp",e=>{if(!this.context.application.hasFocus)return;const t=this.keysPressed[e.code];if(!t)return;t.pressed=!1,t.frame=this.context.time.frameCount+1;const i=new xA("keyup",e,e);this.onDispatchEvent(i)});d(this,"onWheelWindow",e=>{document.pointerLockElement&&this.onMouseWheel(e)});d(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 t=this._mouseWheelDeltaY[0];this._mouseWheelDeltaY[0]=t+e.deltaY});d(this,"onPointerDown",e=>{if(this.context.isInAR||this.canReceiveInput(e)===!1)return;e.target instanceof HTMLElement&&e.target.setPointerCapture(e.pointerId);const t=this.getPointerId(e);hs&&pn(`pointer down #${t}, identifier:${e.pointerId}`);const i=this.getAndUpdateSpatialObjectForScreenPosition(t,e.clientX,e.clientY),n=new hh("pointerdown",e,{origin:this,mode:"screen",deviceIndex:0,pointerId:t,button:e.button,clientX:e.clientX,clientY:e.clientY,pointerType:e.pointerType,buttonName:this.getButtonName(e),device:i,pressure:e.pressure});this.onDown(n)});d(this,"onPointerMove",e=>{if(this.context.isInAR)return;let t=e.button;e.pointerType==="mouse"&&(t=this.getFirstPressedButtonForPointer(0)??0);const i=this.getPointerId(e,t);t===-1&&(t=i);const n=this.getAndUpdateSpatialObjectForScreenPosition(i,e.clientX,e.clientY),r=new hh("pointermove",e,{origin:this,mode:"screen",deviceIndex:0,pointerId:i,button:t,clientX:e.clientX,clientY:e.clientY,pointerType:e.pointerType,buttonName:this.getButtonName(e),device:n,pressure:e.pressure});this.onMove(r)});d(this,"onPointerCancel",e=>{this.context.isInAR||(hs&&console.log("Pointer cancel",e),this.onPointerUp(e))});d(this,"onPointerUp",e=>{if(this.context.isInAR)return;e.target instanceof HTMLElement&&e.target.releasePointerCapture(e.pointerId);const t=this.getPointerId(e),i=new hh("pointerup",e,{origin:this,mode:"screen",deviceIndex:0,pointerId:t,button:e.button,clientX:e.clientX,clientY:e.clientY,pointerType:e.pointerType,buttonName:this.getButtonName(e),device:this.getAndUpdateSpatialObjectForScreenPosition(t,e.clientX,e.clientY),pressure:e.pressure});this.onUp(i),this._pointerIds[t]=-1,hs&&console.log("ID="+t,"PointerId="+e.pointerId,"ALL:",[...this._pointerIds])});d(this,"onTouchStart",e=>{if(this.context.isInAR)for(let t=0;t<e.changedTouches.length;t++){const i=e.changedTouches[t],n=this.getPointerIndex(i.identifier),r=this.getAndUpdateSpatialObjectForScreenPosition(n,i.clientX,i.clientY),o=new hh("pointerdown",e,{origin:this,mode:"screen",deviceIndex:0,pointerId:n,button:0,clientX:i.clientX,clientY:i.clientY,pointerType:"touch",buttonName:"unknown",device:r,pressure:i.force});this.onDown(o)}});d(this,"onTouchMove",e=>{if(this.context.isInAR)for(let t=0;t<e.changedTouches.length;t++){const i=e.changedTouches[t],n=this.getPointerIndex(i.identifier),r=this.getAndUpdateSpatialObjectForScreenPosition(n,i.clientX,i.clientY),o=new hh("pointermove",e,{origin:this,mode:"screen",deviceIndex:0,pointerId:n,button:0,clientX:i.clientX,clientY:i.clientY,pointerType:"touch",buttonName:"unknown",device:r,pressure:i.force});this.onMove(o)}});d(this,"onTouchEnd",e=>{if(this.context.isInAR)for(let t=0;t<e.changedTouches.length;t++){const i=e.changedTouches[t],n=this.getPointerIndex(i.identifier),r=new hh("pointerup",e,{origin:this,mode:"screen",deviceIndex:0,pointerId:n,button:0,clientX:i.clientX,clientY:i.clientY,pointerType:"touch",buttonName:"unknown",device:this.getAndUpdateSpatialObjectForScreenPosition(n,i.clientX,i.clientY),pressure:i.force});this.onUp(r),this._pointerIds[n]=-1}});d(this,"tempNearPlaneVector",new w);d(this,"tempFarPlaneVector",new w);d(this,"tempLookMatrix",new ye);this.context=e,this.context.post_render_callbacks.push(this.onEndOfFrame)}addEventListener(e,t,i){if(this._eventListeners[e]||(this._eventListeners[e]=[]),!t||typeof t!="function"){console.error("Invalid call to addEventListener: callback is required and must be a function!");return}i?i={...i}:i={};let n=0;(i==null?void 0:i.queue)!=null&&(n=i.queue);const r=this._eventListeners[e],o=r.find(a=>a.priority===n);o?o.listeners.push({callback:t,options:i}):(r.push({priority:n,listeners:[{callback:t,options:i}]}),r.sort((a,l)=>a.priority-l.priority))}removeEventListener(e,t,i){if(!this._eventListeners[e]||!t)return;const n=this._eventListeners[e];if((i==null?void 0:i.queue)!=null){const r=n.find(a=>a.priority===i.queue);if(!r)return;const o=r.listeners.findIndex(a=>a.callback===t);o>=0&&r.listeners.splice(o,1)}else for(const r of n){const o=r.listeners.findIndex(a=>a.callback===t);o>=0&&r.listeners.splice(o,1)}}dispatchEvent(e){var i,n,r,o;let t=!1;if(e instanceof xA){const a=this._eventListeners[e.type];if(a)for(const l of a)for(let c=0;c<l.listeners.length;c++){const h=l.listeners[c];if((n=(i=h.options)==null?void 0:i.signal)!=null&&n.aborted){l.listeners.splice(c,1),c--;continue}h.options.once&&(l.listeners.splice(c,1),c--),h.callback(e)}}if(e instanceof hh){const a=this._eventListeners[e.type];if(a)for(const l of a){if(t)break;for(let c=0;c<l.listeners.length;c++){const h=l.listeners[c];if((o=(r=h.options)==null?void 0:r.signal)!=null&&o.aborted){l.listeners.splice(c,1),c--;continue}if(e.immediatePropagationStopped){t=!0,hs&&console.log("immediatePropagationStopped",e.type);break}else e.propagationStopped&&(t=!0,hs&&console.log("propagationStopped",e.type));h.options.once&&(l.listeners.splice(c,1),c--),h.callback(e)}}}}get mousePosition(){return this._pointerPositions[0]}get mousePositionRC(){return this._pointerPositionsRC[0]}get mouseDown(){return this._pointerDown[0]}get mouseUp(){return this._pointerUp[0]}get mouseClick(){return this._pointerClick[0]}get mouseDoubleClick(){return this._pointerDoubleClick[0]}get mousePressed(){return this._pointerPressed[0]}get mouseWheelChanged(){return this.getMouseWheelChanged(0)}setCursorPointer(){this._specialCursorTrigger+=1,this.context.domElement.style.cursor="pointer"}setCursorNormal(){this._specialCursorTrigger-=1,this._specialCursorTrigger=Math.max(0,this._specialCursorTrigger),this._specialCursorTrigger===0&&(this.context.domElement.style.cursor="default")}setPointerUsed(e,t=!0){if(e>=this._pointerUsed.length){if(e>=this._pointerIds.length)return;for(;this._pointerUsed.length<=e;)this._pointerUsed.push(!1)}this._pointerUsed[e]=t}getPointerUsed(e){return e>=this._pointerUsed.length?!1:this._pointerUsed[e]}getPointerPressedCount(){let e=0;for(let t=0;t<this._pointerPressed.length;t++)this._pointerPressed[t]&&e++;return e}getPointerPosition(e){return e>=this._pointerPositions.length?null:this._pointerPositions[e]}getPointerPositionLastFrame(e){return e>=this._pointerPositionsLastFrame.length?null:this._pointerPositionsLastFrame[e]}getPointerPositionDelta(e){return e>=this._pointerPositionsDelta.length?null:this._pointerPositionsDelta[e]}getPointerPositionRC(e){return e>=this._pointerPositionsRC.length?null:this._pointerPositionsRC[e]}getPointerDown(e){return e>=this._pointerDown.length?!1:this._pointerDown[e]}getPointerUp(e){return e>=this._pointerUp.length?!1:this._pointerUp[e]}getPointerPressed(e){return e>=this._pointerPressed.length?!1:this._pointerPressed[e]}getPointerClicked(e){return e>=this._pointerClick.length?!1:this._pointerClick[e]}getPointerDoubleClicked(e){return e>=this._pointerDoubleClick.length?!1:this._pointerDoubleClick[e]}getPointerDownTime(e){return e>=this._pointerDownTime.length?-1:this._pointerDownTime[e]}getPointerUpTime(e){return e>=this._pointerUpTime.length?-1:this._pointerUpTime[e]}getPointerLongPress(e){return e>=this._pointerDownTime.length?!1:this.getPointerPressed(e)&&this.context.time.time-this._pointerDownTime[e]>this._longPressTimeThreshold}getIsMouse(e){return e<0||e>=this._pointerTypes.length?!1:this._pointerTypes[e]==="mouse"}getIsTouch(e){return e<0||e>=this._pointerTypes.length?!1:this._pointerTypes[e]==="touch"}getTouchesPressedCount(){let e=0;for(let t=0;t<this._pointerPressed.length;t++)this._pointerPressed[t]&&this.getIsTouch(t)&&e++;return e}getMouseWheelChanged(e=0){return e>=this._mouseWheelChanged.length?!1:this._mouseWheelChanged[e]}getMouseWheelDeltaY(e=0){return e>=this._mouseWheelDeltaY.length?0:this._mouseWheelDeltaY[e]}getPointerEvent(e){if(!(e>=this._pointerEvent.length))return this._pointerEvent[e]??void 0}*foreachPointerId(e){for(let t=0;t<this._pointerTypes.length;t++)if(this._pointerIsActive(t)){if(e!==void 0){const i=this._pointerTypes[t];if(Array.isArray(e)){let n=!1;for(const r of e)if(i===r){n=!0;break}if(!n)continue}else if(e!==i)continue}yield t}}*foreachTouchId(){for(let e=0;e<this._pointerTypes.length;e++)this._pointerTypes[e]==="touch"&&this._pointerIsActive[e]&&(yield e)}_pointerIsActive(e){return e<0?!1:this._pointerPressed[e]||this._pointerDown[e]||this._pointerUp[e]}onDownButton(e,t){let i=this._pressedStack.get(e);i||(i=[],this._pressedStack.set(e,i)),i.push(t)}onReleaseButton(e,t){const i=this._pressedStack.get(e);if(!i)return;const n=i.indexOf(t);n>=0&&i.splice(n,1)}getFirstPressedButtonForPointer(e){const t=this._pressedStack.get(e);if(t)return t[0]}getLatestPressedButtonForPointer(e){const t=this._pressedStack.get(e);if(t)return t[t.length-1]}getKeyDown(){for(const e in this.keysPressed){const t=this.keysPressed[e];if(t.startFrame===this.context.time.frameCount)return t.key}return null}getKeyPressed(){for(const e in this.keysPressed){const t=this.keysPressed[e];if(t.pressed)return t.key}return null}isKeyDown(e){var i;if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const t=this.getCodeForCommonKeyName(e);if(t!==null){for(const n of t)if(this.isKeyDown(n))return!0;return!1}return((i=this.keysPressed[e])==null?void 0:i.startFrame)===this.context.time.frameCount&&this.keysPressed[e].pressed}isKeyUp(e){var i;if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const t=this.getCodeForCommonKeyName(e);if(t!==null){for(const n of t)if(this.isKeyUp(n))return!0;return!1}return((i=this.keysPressed[e])==null?void 0:i.frame)===this.context.time.frameCount&&!this.keysPressed[e].pressed}isKeyPressed(e){var i;if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const t=this.getCodeForCommonKeyName(e);if(t!==null){for(const n of t)if(this.isKeyPressed(n))return!0;return!1}return(i=this.keysPressed[e])==null?void 0:i.pressed}getCodeForCommonKeyName(e){if(e.length===1){if(e>="0"&&e<="9")return["Digit"+e];if(e>="a"&&e<="z")return["Key"+e.toUpperCase()];if(e==" ")return["Space"]}switch(e){case"shift":case"Shift":return["ShiftLeft","ShiftRight"];case"control":case"Control":return["ControlLeft","ControlRight"];case"alt":case"Alt":return["AltLeft","AltRight"]}return null}createInputEvent(e){switch(e.type){case"pointerdown":hs&&pn("Create Pointer down"),this.onDownButton(e.deviceIndex,e.button),this.onDown(e);break;case"pointermove":hs&&pn("Create Pointer move"),this.onMove(e);break;case"pointerup":hs&&pn("Create Pointer up"),this.onUp(e),this.onReleaseButton(e.deviceIndex,e.button);break}}convertScreenspaceToRaycastSpace(e){return e.x=(e.x-this.context.domX)/this.context.domWidth*2-1,e.y=-((e.y-this.context.domY)/this.context.domHeight)*2+1,e}bindEvents(){this.unbindEvents(),this._htmlEventSource=this.context.renderer.domElement,window.addEventListener("contextmenu",this.onContextMenu),this._htmlEventSource.addEventListener("pointerdown",this.onPointerDown,{passive:!0}),window.addEventListener("pointermove",this.onPointerMove,{passive:!0,capture:!0}),window.addEventListener("pointerup",this.onPointerUp,{passive:!0}),window.addEventListener("pointercancel",this.onPointerCancel,{passive:!0}),window.addEventListener("touchstart",this.onTouchStart,{passive:!0}),window.addEventListener("touchmove",this.onTouchMove,{passive:!0}),window.addEventListener("touchend",this.onTouchEnd,{passive:!0}),this._htmlEventSource.addEventListener("wheel",this.onMouseWheel,{passive:!0}),window.addEventListener("wheel",this.onWheelWindow,{passive:!0}),window.addEventListener("keydown",this.onKeyDown,!1),window.addEventListener("keypress",this.onKeyPressed,!1),window.addEventListener("keyup",this.onKeyUp,!1),window.addEventListener("blur",this.onLostFocus)}unbindEvents(){var e,t;window.removeEventListener("contextmenu",this.onContextMenu),(e=this._htmlEventSource)==null||e.removeEventListener("pointerdown",this.onPointerDown),window.removeEventListener("pointermove",this.onPointerMove),window.removeEventListener("pointerup",this.onPointerUp),window.removeEventListener("pointercancel",this.onPointerCancel),(t=this._htmlEventSource)==null||t.removeEventListener("wheel",this.onMouseWheel,!1),window.removeEventListener("wheel",this.onWheelWindow,!1),window.removeEventListener("keydown",this.onKeyDown,!1),window.removeEventListener("keypress",this.onKeyPressed,!1),window.removeEventListener("keyup",this.onKeyUp,!1),window.removeEventListener("blur",this.onLostFocus)}dispose(){const e=this.context.post_render_callbacks.indexOf(this.onEndOfFrame);e>=0&&this.context.post_render_callbacks.splice(e,1),this.unbindEvents()}canReceiveInput(e){var t;return e.target===((t=this.context.renderer)==null?void 0:t.domElement)||e.target===this.context.domElement||this.context.isInAR||this.context.isInAR&&e.target===document.body&&Kf()?!0:(hs&&console.warn("CanReceiveInput:False for",e.target),!1)}getPointerId(e,t){return e.pointerType==="mouse"?0+(t??e.button):this.getPointerIndex(e.pointerId)}getButtonName(e){const t=e.button;if(e.pointerType==="mouse")switch(t){case 0:return"left";case 1:return"middle";case 2:return"right"}return"unknown"}getAndUpdateSpatialObjectForScreenPosition(e,t,i){let n=this._pointerSpace[e];n||(n=new ve,this._pointerSpace[e]=n),this._pointerSpace[e]=n;const r=this.context.mainCamera;if(r){const o=this.tempNearPlaneVector.set(t,i,-1);this.convertScreenspaceToRaycastSpace(o);const a=this.tempFarPlaneVector.set(o.x,o.y,1);o.unproject(r),a.unproject(r);const l=r.worldUp||pi(0,1,0).applyQuaternion(Ri(r));this.tempLookMatrix.lookAt(a,o,l),n.position.set(o.x,o.y,o.z),n.quaternion.setFromRotationMatrix(this.tempLookMatrix)}return n}isInRect(e){if(this.context.isInXR)return!0;const t=this.context.domElement.getBoundingClientRect(),i=e.clientX,n=e.clientY,r=i>=t.x&&i<=t.right&&n>=t.y&&n<=t.bottom;return hs&&!r&&console.log("Not in rect",t,i,n),r}onDown(e){const t=e.pointerId;if(this.getPointerPressed(t)&&console.warn(`pointerId is already pressed: ${t}`,hs?e:""),hs&&console.log(e.pointerType,"DOWN",t),!!this.isInRect(e)){for(this.setPointerState(t,this._pointerPressed,!0),this.setPointerState(t,this._pointerDown,!0),this.setPointerStateT(t,this._pointerEvent,e.source);t>=this._pointerTypes.length;)this._pointerTypes.push(e.pointerType);for(this._pointerTypes[t]=e.pointerType;t>=this._pointerPositionDown.length;)this._pointerPositionDown.push(new ee);for(this._pointerPositionDown[t].set(e.clientX,e.clientY);t>=this._pointerPositions.length;)this._pointerPositions.push(new ee);this._pointerPositions[t].set(e.clientX,e.clientY),t>=this._pointerDownTime.length&&this._pointerDownTime.push(0),this._pointerDownTime[t]=this.context.time.time,this.updatePointerPosition(e),this.onDispatchEvent(e)}}onMove(e){const t=e.pointerId,i=this.getPointerPressed(t);i===!1&&!this.isInRect(e)||e.pointerType==="touch"&&!i||(this.updatePointerPosition(e),this.setPointerStateT(t,this._pointerEvent,e.source),this.onDispatchEvent(e))}onUp(e){const t=e.pointerId;if(!this.getPointerPressed(t)){hs&&console.log(e.pointerType,"UP",t,"was not down");return}for(hs&&console.log(e.pointerType,"UP",t),this.setPointerState(t,this._pointerPressed,!1),this.setPointerStateT(t,this._pointerEvent,e.source),this.setPointerState(t,this._pointerUp,!0);t>=this._pointerUsed.length;)this._pointerUsed.push(!1);if(this.setPointerState(t,this._pointerUsed,!1),this.updatePointerPosition(e),!this._pointerPositionDown[t]){hs&&Ni("Received pointer up event without matching down event for button: "+t),console.warn("Received pointer up event without matching down event for button: "+t);return}const n=e.clientX-this._pointerPositionDown[t].x,r=e.clientY-this._pointerPositionDown[t].y;if(t>=this._pointerUpTime.length&&this._pointerUpTime.push(-99),Math.abs(n)<5&&Math.abs(r)<5){hs&&console.log("CLICK",t),this.setPointerState(t,this._pointerClick,!0),e.isClick=!0;const o=this._pointerUpTime[t],a=this.context.time.time-o;a<this._doubleClickTimeThreshold&&a>0&&(this.setPointerState(t,this._pointerDoubleClick,!0),e.isDoubleClick=!0)}this._pointerUpTime[t]=this.context.time.time,this.onDispatchEvent(e)}updatePointerPosition(e){const t=e.pointerId;for(;t>=this._pointerPositions.length;)this._pointerPositions.push(new ee);for(;t>=this._pointerPositionsLastFrame.length;)this._pointerPositionsLastFrame.push(new ee);for(;t>=this._pointerPositionsDelta.length;)this._pointerPositionsDelta.push(new ee);const i=this._pointerPositionsLastFrame[t];i.copy(this._pointerPositions[t]);const n=this._pointerPositionsDelta[t];let r=e.clientX-i.x,o=e.clientY-i.y;if(e.source instanceof MouseEvent||e.source instanceof TouchEvent){const h=e.source;r===0&&h.movementX!==0&&(r=h.movementX||0),o===0&&h.movementY!==0&&(o=h.movementY||0)}n.x+=r,n.y+=o,this._pointerPositions[t].x=e.clientX,this._pointerPositions[t].y=e.clientY;const a=e.clientX,l=e.clientY;for(;t>=this._pointerPositionsRC.length;)this._pointerPositionsRC.push(new ee);const c=this._pointerPositionsRC[t];c.set(a,l),this.convertScreenspaceToRaycastSpace(c)}getPointerIndex(e){let t=-1;for(let i=0;i<this._pointerIds.length;i++){if(this._pointerIds[i]===e)return i;t===-1&&this._pointerIds[i]===-1&&(t=i)}return t!==-1?(this._pointerIds[t]=e,t):(hs&&console.log("PUSH pointerId:",e),this._pointerIds.push(e),this._pointerIds.length-1)}setPointerState(e,t,i){t[e]=i}setPointerStateT(e,t,i){return t[e]=i,i}onDispatchEvent(e){const t=Ot.Current;try{Ot.Current=this.context,this.dispatchEvent(e)}finally{Ot.Current=t}}}const EC=new ye().makeRotationY(Math.PI),Ca=new Ce().setFromAxisAngle(new w(0,1,0),Math.PI),xue=ie("debugwebxr");class wue{constructor(){d(this,"priority",-1e5);d(this,"gameObject");if(this.gameObject=new ve,this.gameObject.name="Implicit XR Rig",xue){const e=BO(16733661);e.position.y+=.5,this.gameObject.add(e)}}isXRRig(){return!0}get isActive(){return this.gameObject.visible}}const wu=ie("debugwebxr"),mw=ie("debugcustomgesture"),Sue="https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles",Cue="generic-trigger";class DO{constructor(e,t,i){d(this,"xr");d(this,"inputSource");d(this,"index",0);d(this,"emitEvents",!0);d(this,"_connected",!0);d(this,"_isTracking",!1);d(this,"_hitTestSource");d(this,"_hasSelectEvent",!1);d(this,"_handJointPoses",new Map);d(this,"_gripPosition",new w);d(this,"_gripQuaternion",new Ce);d(this,"_linearVelocity",new w);d(this,"_rayPosition",new w);d(this,"_rayQuaternion",new Ce);d(this,"_gripWorldPosition",new w);d(this,"_gripWorldQuaternion",new Ce);d(this,"_rayWorldPosition",new w);d(this,"_rayWorldQuaternion",new Ce);d(this,"_ray");d(this,"_object");d(this,"model",null);d(this,"_debugAxesHelper",new na(.2));d(this,"onPointerHits",e=>{});d(this,"_needleGamepadButtons",{});d(this,"_buttonMap",new Map);d(this,"_motioncontroller");d(this,"_layout");d(this,"getMotionController");d(this,"_selectButtonIndex");d(this,"_squeezeButtonIndex");d(this,"onSelectStart",e=>{var n,r,o,a;if(this.inputSource!==e.inputSource)return;this.onUpdateFrame(e.frame),this._hasSelectEvent=!0;const t=(n=this._layout)==null?void 0:n.selectComponentId,i=(a=(o=(r=this._layout)==null?void 0:r.components[t])==null?void 0:o.gamepadIndices)==null?void 0:a.button;i!==void 0&&(this._selectButtonIndex=i),!mw&&(wu&&_t.DrawDirection(this.rayWorldPosition,pi(0,.01,1).applyQuaternion(this.rayWorldQuaternion),16711680,10),this.emitPointerEvent(fn.PointerDown,this._selectButtonIndex||0,"xr-standard-trigger",!0,e))});d(this,"onSelectEnd",e=>{mw||this.inputSource===e.inputSource&&this.emitPointerEvent(fn.PointerUp,this._selectButtonIndex||0,"xr-standard-trigger",!0,e)});d(this,"onSequeezeStart",e=>{var t,i,n;this.inputSource===e.inputSource&&(this._squeezeButtonIndex=(n=(i=(t=this._layout)==null?void 0:t.components["xr-standard-squeeze"])==null?void 0:i.gamepadIndices)==null?void 0:n.button,this._squeezeButtonIndex!==void 0&&(wu&&_t.DrawDirection(this.rayWorldPosition,pi(0,.01,1).applyQuaternion(this.rayWorldQuaternion),255,10),this.emitPointerEvent(fn.PointerDown,this._squeezeButtonIndex||0,"xr-standard-squeeze",!0,e)))});d(this,"onSequeezeEnd",e=>{this.inputSource===e.inputSource&&this._squeezeButtonIndex!==void 0&&this.emitPointerEvent(fn.PointerUp,this._squeezeButtonIndex||0,"xr-standard-squeeze",!0,e)});d(this,"states",{});d(this,"_didMoveLastFrame",!1);d(this,"_lastPointerMovePosition",new w);d(this,"_lastPointerMoveQuaternion",new Ce);d(this,"pointerInit");var n,r,o;this.xr=e,this.inputSource=t,this.index=i,this._object=new ve,wu&&this._object.add(this._debugAxesHelper),this.xr.context.scene.add(this._object),this._ray=new Mo,this.pointerInit={origin:this,pointerType:this.hand?"hand":"controller",deviceIndex:this.index,pointerId:-1,mode:this.inputSource.targetRayMode,ray:this._ray,device:this._object,buttonName:"none"},this.initialize(),this.subscribeEvents(),this.xr.mode==="immersive-ar"&&this.inputSource.targetRayMode==="tracked-pointer"&&((o=(r=(n=this.xr.session).requestHitTestSourceForTransientInput)==null?void 0:r.call(n,{profile:this.inputSource.profiles[0],offsetRay:new XRRay}))==null||o.then(a=>this._hitTestSource=a))}get context(){return this.xr.context}get connected(){return this._connected}get isTracking(){return this._isTracking}get gamepad(){return this.inputSource.gamepad}get isHand(){return this.inputSource.hand!=null}get hand(){return this.inputSource.hand}get handObject(){return this.context.renderer.xr.getHand(this.index)}get profiles(){return this.inputSource.profiles}get layout(){return this._layout}get targetRayMode(){return this.inputSource.targetRayMode}get targetRaySpace(){return this.inputSource.targetRaySpace}get gripSpace(){return this.inputSource.gripSpace}get side(){return this.inputSource.handedness}get isRight(){return this.side==="right"}get isLeft(){return this.side==="left"}get hitTestSource(){return this._hitTestSource}get hasSelectEvent(){return this._hasSelectEvent}getHitTest(){return this.xr.getHitTest(this)}getHandJointPose(e){var i,n;if(!this.hand||!((i=this.xr.frame)!=null&&i.getJointPose)||!this.xr.referenceSpace)return null;let t=(n=this._handJointPoses)==null?void 0:n.get(e);return t||(t=this.xr.frame.getJointPose(e,this.xr.referenceSpace),t&&this._handJointPoses.set(e,t),t)}get gripPosition(){return pi(this._gripPosition).applyMatrix4(EC)}get gripQuaternion(){return Nf(this._gripQuaternion).premultiply(Ca)}get gripLinearVelocity(){return pi(this._linearVelocity).applyQuaternion(Ca)}get rayPosition(){return pi(this._rayPosition).applyMatrix4(EC)}get rayQuaternion(){return Nf(this._rayQuaternion).premultiply(Ca)}get gripWorldPosition(){return pi(this._gripWorldPosition)}get gripWorldQuaternion(){return Nf(this._gripWorldQuaternion)}get rayWorldPosition(){return pi(this._rayWorldPosition)}updateRayWorldPosition(){var t;const e=(t=this.xr.context.mainCamera)==null?void 0:t.parent;this._rayWorldPosition.copy(this._rayPosition),e&&this._rayWorldPosition.applyMatrix4(e.matrixWorld)}get rayWorldQuaternion(){return Nf(this._rayWorldQuaternion)}updateRayWorldQuaternion(){var i;const e=(i=this.xr.context.mainCamera)==null?void 0:i.parent,t=e?Ri(e):void 0;this._rayWorldQuaternion.copy(this._rayQuaternion).multiply(Ca),t&&this._rayWorldQuaternion.premultiply(t)}get ray(){return this._ray.origin.copy(this.rayWorldPosition),this._ray.direction.copy(pi(0,0,1).applyQuaternion(this.rayWorldQuaternion)),this._ray}get object(){return this._object}async getModelUrl(){var e;return(e=this.getMotionController)==null?void 0:e.then(t=>(t==null?void 0:t.assetUrl)||null)}onUpdate(e){this.onUpdateFrame(e),this.updateInputEvents(),this.onUpdateMove()}onRenderDebug(){var n;_t.DrawWireSphere(this.rayWorldPosition,.02),_t.DrawDirection(this.rayWorldPosition,pi(0,0,10).applyQuaternion(this.rayWorldQuaternion));const e=this.gripWorldPosition.sub(this.object.worldForward.multiplyScalar(.1)),t=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: ${(n=this.getGesture("pinch"))==null?void 0:n.value.toFixed(3)}`),i+=`
|
|
@@ -5232,7 +5232,7 @@ a=extmap-allow-mixed`)!==-1){const r=n.sdp.split(`
|
|
|
5232
5232
|
isUnifiedPlanSupported:`).concat(this.isUnifiedPlanSupported())},s}()),K3={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"},Que=function(){function s(){this.CLOUD_HOST="0.peerjs.com",this.CLOUD_PORT=443,this.chunkedBrowsers={Chrome:1,chrome:1},this.chunkedMTU=16300,this.defaultConfig=K3,this.browser=qv.getBrowser(),this.browserVersion=qv.getVersion(),this.supports=function(){var e={browser:qv.isBrowserSupported(),webRTC:qv.isWebRTCSupported(),audioVideo:!1,data:!1,binaryBlob:!1,reliable:!1};if(!e.webRTC)return e;var t;try{t=new RTCPeerConnection(K3),e.audioVideo=!0;var i=void 0;try{i=t.createDataChannel("_PEERJSTEST",{ordered:!0}),e.data=!0,e.reliable=!!i.ordered;try{i.binaryType="blob",e.binaryBlob=!qv.isIOS}catch{}}catch{}finally{i&&i.close()}}catch{}finally{t&&t.close()}return e}(),this.pack=N3.pack,this.unpack=N3.unpack,this._dataCount=1}return s.prototype.noop=function(){},s.prototype.validateId=function(e){return!e||/^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/.test(e)},s.prototype.chunk=function(e){for(var t=[],i=e.size,n=Math.ceil(i/Si.chunkedMTU),r=0,o=0;o<i;){var a=Math.min(i,o+Si.chunkedMTU),l=e.slice(o,a),c={__peerData:this._dataCount,n:r,data:l,total:n};t.push(c),o=a,r++}return this._dataCount++,t},s.prototype.blobToArrayBuffer=function(e,t){var i=new FileReader;return i.onload=function(n){n.target&&t(n.target.result)},i.readAsArrayBuffer(e),i},s.prototype.binaryStringToArrayBuffer=function(e){for(var t=new Uint8Array(e.length),i=0;i<e.length;i++)t[i]=e.charCodeAt(i)&255;return t.buffer},s.prototype.randomToken=function(){return Math.random().toString(36).slice(2)},s.prototype.isSecure=function(){return location.protocol==="https:"},s}(),Si=new Que,M6={};Rc(M6,"Peer",()=>SB,s=>SB=s);var N_={},jue=Object.prototype.hasOwnProperty,oo="~";function j0(){}Object.create&&(j0.prototype=Object.create(null),new j0().__proto__||(oo=!1));function Wue(s,e,t){this.fn=s,this.context=e,this.once=t||!1}function T6(s,e,t,i,n){if(typeof t!="function")throw new TypeError("The listener must be a function");var r=new Wue(t,i||s,n),o=oo?oo+e:e;return s._events[o]?s._events[o].fn?s._events[o]=[s._events[o],r]:s._events[o].push(r):(s._events[o]=r,s._eventsCount++),s}function DS(s,e){--s._eventsCount===0?s._events=new j0:delete s._events[e]}function Lr(){this._events=new j0,this._eventsCount=0}Lr.prototype.eventNames=function(){var e=[],t,i;if(this._eventsCount===0)return e;for(i in t=this._events)jue.call(t,i)&&e.push(oo?i.slice(1):i);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};Lr.prototype.listeners=function(e){var t=oo?oo+e:e,i=this._events[t];if(!i)return[];if(i.fn)return[i.fn];for(var n=0,r=i.length,o=new Array(r);n<r;n++)o[n]=i[n].fn;return o};Lr.prototype.listenerCount=function(e){var t=oo?oo+e:e,i=this._events[t];return i?i.fn?1:i.length:0};Lr.prototype.emit=function(e,t,i,n,r,o){var a=oo?oo+e:e;if(!this._events[a])return!1;var l=this._events[a],c=arguments.length,h,u;if(l.fn){switch(l.once&&this.removeListener(e,l.fn,void 0,!0),c){case 1:return l.fn.call(l.context),!0;case 2:return l.fn.call(l.context,t),!0;case 3:return l.fn.call(l.context,t,i),!0;case 4:return l.fn.call(l.context,t,i,n),!0;case 5:return l.fn.call(l.context,t,i,n,r),!0;case 6:return l.fn.call(l.context,t,i,n,r,o),!0}for(u=1,h=new Array(c-1);u<c;u++)h[u-1]=arguments[u];l.fn.apply(l.context,h)}else{var f=l.length,p;for(u=0;u<f;u++)switch(l[u].once&&this.removeListener(e,l[u].fn,void 0,!0),c){case 1:l[u].fn.call(l[u].context);break;case 2:l[u].fn.call(l[u].context,t);break;case 3:l[u].fn.call(l[u].context,t,i);break;case 4:l[u].fn.call(l[u].context,t,i,n);break;default:if(!h)for(p=1,h=new Array(c-1);p<c;p++)h[p-1]=arguments[p];l[u].fn.apply(l[u].context,h)}}return!0};Lr.prototype.on=function(e,t,i){return T6(this,e,t,i,!1)};Lr.prototype.once=function(e,t,i){return T6(this,e,t,i,!0)};Lr.prototype.removeListener=function(e,t,i,n){var r=oo?oo+e:e;if(!this._events[r])return this;if(!t)return DS(this,r),this;var o=this._events[r];if(o.fn)o.fn===t&&(!n||o.once)&&(!i||o.context===i)&&DS(this,r);else{for(var a=0,l=[],c=o.length;a<c;a++)(o[a].fn!==t||n&&!o[a].once||i&&o[a].context!==i)&&l.push(o[a]);l.length?this._events[r]=l.length===1?l[0]:l:DS(this,r)}return this};Lr.prototype.removeAllListeners=function(e){var t;return e?(t=oo?oo+e:e,this._events[t]&&DS(this,t)):(this._events=new j0,this._eventsCount=0),this};Lr.prototype.off=Lr.prototype.removeListener;Lr.prototype.addListener=Lr.prototype.on;Lr.prefixed=oo;Lr.EventEmitter=Lr;N_=Lr;var mt={};Rc(mt,"LogLevel",()=>mo,s=>mo=s);Rc(mt,"default",()=>J3,s=>J3=s);var hf=function(s,e){var t=typeof Symbol=="function"&&s[Symbol.iterator];if(!t)return s;var i=t.call(s),n,r=[],o;try{for(;(e===void 0||e-- >0)&&!(n=i.next()).done;)r.push(n.value)}catch(a){o={error:a}}finally{try{n&&!n.done&&(t=i.return)&&t.call(i)}finally{if(o)throw o.error}}return r},uf=function(s,e,t){if(t||arguments.length===2)for(var i=0,n=e.length,r;i<n;i++)(r||!(i in e))&&(r||(r=Array.prototype.slice.call(e,0,i)),r[i]=e[i]);return s.concat(r||Array.prototype.slice.call(e))},que="PeerJS: ",mo;(function(s){s[s.Disabled=0]="Disabled",s[s.Errors=1]="Errors",s[s.Warnings=2]="Warnings",s[s.All=3]="All"})(mo||(mo={}));var Xue=function(){function s(){this._logLevel=mo.Disabled}return Object.defineProperty(s.prototype,"logLevel",{get:function(){return this._logLevel},set:function(e){this._logLevel=e},enumerable:!1,configurable:!0}),s.prototype.log=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this._logLevel>=mo.All&&this._print.apply(this,uf([mo.All],hf(e),!1))},s.prototype.warn=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this._logLevel>=mo.Warnings&&this._print.apply(this,uf([mo.Warnings],hf(e),!1))},s.prototype.error=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this._logLevel>=mo.Errors&&this._print.apply(this,uf([mo.Errors],hf(e),!1))},s.prototype.setLogFunction=function(e){this._print=e},s.prototype._print=function(e){for(var t=[],i=1;i<arguments.length;i++)t[i-1]=arguments[i];var n=uf([que],hf(t),!1);for(var r in n)n[r]instanceof Error&&(n[r]="("+n[r].name+") "+n[r].message);e>=mo.All?console.log.apply(console,uf([],hf(n),!1)):e>=mo.Warnings?console.warn.apply(console,uf(["WARNING"],hf(n),!1)):e>=mo.Errors&&console.error.apply(console,uf(["ERROR"],hf(n),!1))},s}(),J3=new Xue,I6={};Rc(I6,"Socket",()=>Z3,s=>Z3=s);var vl;(function(s){s.Data="data",s.Media="media"})(vl||(vl={}));var Vn;(function(s){s.BrowserIncompatible="browser-incompatible",s.Disconnected="disconnected",s.InvalidID="invalid-id",s.InvalidKey="invalid-key",s.Network="network",s.PeerUnavailable="peer-unavailable",s.SslUnavailable="ssl-unavailable",s.ServerError="server-error",s.SocketError="socket-error",s.SocketClosed="socket-closed",s.UnavailableID="unavailable-id",s.WebRTC="webrtc"})(Vn||(Vn={}));var uh;(function(s){s.Binary="binary",s.BinaryUTF8="binary-utf8",s.JSON="json"})(uh||(uh={}));var Ih;(function(s){s.Message="message",s.Disconnected="disconnected",s.Error="error",s.Close="close"})(Ih||(Ih={}));var $s;(function(s){s.Heartbeat="HEARTBEAT",s.Candidate="CANDIDATE",s.Offer="OFFER",s.Answer="ANSWER",s.Open="OPEN",s.Error="ERROR",s.IdTaken="ID-TAKEN",s.InvalidKey="INVALID-KEY",s.Leave="LEAVE",s.Expire="EXPIRE"})($s||($s={}));var UO={};UO=JSON.parse('{"name":"peerjs","version":"1.4.7","keywords":["peerjs","webrtc","p2p","rtc"],"description":"PeerJS client","homepage":"https://peerjs.com","bugs":{"url":"https://github.com/peers/peerjs/issues"},"repository":{"type":"git","url":"https://github.com/peers/peerjs"},"license":"MIT","contributors":["Michelle Bu <michelle@michellebu.com>","afrokick <devbyru@gmail.com>","ericz <really.ez@gmail.com>","Jairo <kidandcat@gmail.com>","Jonas Gloning <34194370+jonasgloning@users.noreply.github.com>","Jairo Caro-Accino Viciana <jairo@galax.be>","Carlos Caballero <carlos.caballero.gonzalez@gmail.com>","hc <hheennrryy@gmail.com>","Muhammad Asif <capripio@gmail.com>","PrashoonB <prashoonbhattacharjee@gmail.com>","Harsh Bardhan Mishra <47351025+HarshCasper@users.noreply.github.com>","akotynski <aleksanderkotbury@gmail.com>","lmb <i@lmb.io>","Jairooo <jairocaro@msn.com>","Moritz Stückler <moritz.stueckler@gmail.com>","Simon <crydotsnakegithub@gmail.com>","Denis Lukov <denismassters@gmail.com>","Philipp Hancke <fippo@andyet.net>","Hans Oksendahl <hansoksendahl@gmail.com>","Jess <jessachandler@gmail.com>","khankuan <khankuan@gmail.com>","DUODVK <kurmanov.work@gmail.com>","XiZhao <kwang1imsa@gmail.com>","Matthias Lohr <matthias@lohr.me>","=frank tree <=frnktrb@googlemail.com>","Andre Eckardt <aeckardt@outlook.com>","Chris Cowan <agentme49@gmail.com>","Alex Chuev <alex@chuev.com>","alxnull <alxnull@e.mail.de>","Yemel Jardi <angel.jardi@gmail.com>","Ben Parnell <benjaminparnell.94@gmail.com>","Benny Lichtner <bennlich@gmail.com>","fresheneesz <bitetrudpublic@gmail.com>","bob.barstead@exaptive.com <bob.barstead@exaptive.com>","chandika <chandika@gmail.com>","emersion <contact@emersion.fr>","Christopher Van <cvan@users.noreply.github.com>","eddieherm <edhermoso@gmail.com>","Eduardo Pinho <enet4mikeenet@gmail.com>","Evandro Zanatta <ezanatta@tray.net.br>","Gardner Bickford <gardner@users.noreply.github.com>","Gian Luca <gianluca.cecchi@cynny.com>","PatrickJS <github@gdi2290.com>","jonnyf <github@jonathanfoss.co.uk>","Hizkia Felix <hizkifw@gmail.com>","Hristo Oskov <hristo.oskov@gmail.com>","Isaac Madwed <i.madwed@gmail.com>","Ilya Konanykhin <ilya.konanykhin@gmail.com>","jasonbarry <jasbarry@me.com>","Jonathan Burke <jonathan.burke.1311@googlemail.com>","Josh Hamit <josh.hamit@gmail.com>","Jordan Austin <jrax86@gmail.com>","Joel Wetzell <jwetzell@yahoo.com>","xizhao <kevin.wang@cloudera.com>","Alberto Torres <kungfoobar@gmail.com>","Jonathan Mayol <mayoljonathan@gmail.com>","Jefferson Felix <me@jsfelix.dev>","Rolf Erik Lekang <me@rolflekang.com>","Kevin Mai-Husan Chia <mhchia@users.noreply.github.com>","Pepijn de Vos <pepijndevos@gmail.com>","JooYoung <qkdlql@naver.com>","Tobias Speicher <rootcommander@gmail.com>","Steve Blaurock <sblaurock@gmail.com>","Kyrylo Shegeda <shegeda@ualberta.ca>","Diwank Singh Tomer <singh@diwank.name>","Sören Balko <Soeren.Balko@gmail.com>","Arpit Solanki <solankiarpit1997@gmail.com>","Yuki Ito <yuki@gnnk.net>","Artur Zayats <zag2art@gmail.com>"],"funding":{"type":"opencollective","url":"https://opencollective.com/peer"},"collective":{"type":"opencollective","url":"https://opencollective.com/peer"},"files":["dist/*"],"sideEffects":["lib/global.ts","lib/supports.ts"],"main":"dist/bundler.cjs","module":"dist/bundler.mjs","browser-minified":"dist/peerjs.min.js","browser-unminified":"dist/peerjs.js","types":"dist/types.d.ts","engines":{"node":">= 10"},"targets":{"types":{"source":"lib/exports.ts"},"main":{"source":"lib/exports.ts","sourceMap":{"inlineSources":true}},"module":{"source":"lib/exports.ts","includeNodeModules":["eventemitter3"],"sourceMap":{"inlineSources":true}},"browser-minified":{"context":"browser","outputFormat":"global","optimize":true,"engines":{"browsers":"cover 99%, not dead"},"source":"lib/global.ts"},"browser-unminified":{"context":"browser","outputFormat":"global","optimize":false,"engines":{"browsers":"cover 99%, not dead"},"source":"lib/global.ts"}},"scripts":{"contributors":"git-authors-cli --print=false && prettier --write package.json && git add package.json package-lock.json && git commit -m \\"chore(contributors): update and sort contributors list\\"","check":"tsc --noEmit","watch":"parcel watch","build":"rm -rf dist && parcel build","prepublishOnly":"npm run build","test":"mocha -r ts-node/register -r jsdom-global/register test/**/*.ts","format":"prettier --write .","semantic-release":"semantic-release"},"devDependencies":{"@parcel/config-default":"^2.5.0","@parcel/packager-ts":"^2.5.0","@parcel/transformer-typescript-tsc":"^2.5.0","@parcel/transformer-typescript-types":"^2.5.0","@semantic-release/changelog":"^6.0.1","@semantic-release/git":"^10.0.1","@types/chai":"^4.3.0","@types/mocha":"^9.1.0","@types/node":"^17.0.18","chai":"^4.3.6","git-authors-cli":"^1.0.40","jsdom":"^19.0.0","jsdom-global":"^3.0.2","mocha":"^9.2.0","mock-socket":"8.0.5","parcel":"^2.5.0","parcel-transformer-tsc-sourcemaps":"^1.0.2","prettier":"^2.6.2","semantic-release":"^19.0.2","standard":"^16.0.4","ts-node":"^10.5.0","typescript":"^4.5.5"},"dependencies":{"@swc/helpers":"^0.3.13","eventemitter3":"^4.0.7","peerjs-js-binarypack":"1.0.1","webrtc-adapter":"^7.7.1"}}');var Yue=function(){var s=function(e,t){return s=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(i,n){i.__proto__=n}||function(i,n){for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(i[r]=n[r])},s(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");s(e,t);function i(){this.constructor=e}e.prototype=t===null?Object.create(t):(i.prototype=t.prototype,new i)}}(),Kue=function(s,e){var t=typeof Symbol=="function"&&s[Symbol.iterator];if(!t)return s;var i=t.call(s),n,r=[],o;try{for(;(e===void 0||e-- >0)&&!(n=i.next()).done;)r.push(n.value)}catch(a){o={error:a}}finally{try{n&&!n.done&&(t=i.return)&&t.call(i)}finally{if(o)throw o.error}}return r},Jue=function(s,e,t){if(t||arguments.length===2)for(var i=0,n=e.length,r;i<n;i++)(r||!(i in e))&&(r||(r=Array.prototype.slice.call(e,0,i)),r[i]=e[i]);return s.concat(r||Array.prototype.slice.call(e))},Zue=function(s){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&s[e],i=0;if(t)return t.call(s);if(s&&typeof s.length=="number")return{next:function(){return s&&i>=s.length&&(s=void 0),{value:s&&s[i++],done:!s}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},Z3=function(s){Yue(e,s);function e(t,i,n,r,o,a){a===void 0&&(a=5e3);var l=s.call(this)||this;l.pingInterval=a,l._disconnected=!0,l._messagesQueue=[];var c=t?"wss://":"ws://";return l._baseUrl=c+i+":"+n+r+"peerjs?key="+o,l}return e.prototype.start=function(t,i){var n=this;this._id=t;var r="".concat(this._baseUrl,"&id=").concat(t,"&token=").concat(i);this._socket||!this._disconnected||(this._socket=new WebSocket(r+"&version="+UO.version),this._disconnected=!1,this._socket.onmessage=function(o){var a;try{a=JSON.parse(o.data),mt.default.log("Server message received:",a)}catch{mt.default.log("Invalid server message",o.data);return}n.emit(Ih.Message,a)},this._socket.onclose=function(o){n._disconnected||(mt.default.log("Socket closed.",o),n._cleanup(),n._disconnected=!0,n.emit(Ih.Disconnected))},this._socket.onopen=function(){n._disconnected||(n._sendQueuedMessages(),mt.default.log("Socket open"),n._scheduleHeartbeat())})},e.prototype._scheduleHeartbeat=function(){var t=this;this._wsPingTimer=setTimeout(function(){t._sendHeartbeat()},this.pingInterval)},e.prototype._sendHeartbeat=function(){if(!this._wsOpen()){mt.default.log("Cannot send heartbeat, because socket closed");return}var t=JSON.stringify({type:$s.Heartbeat});this._socket.send(t),this._scheduleHeartbeat()},e.prototype._wsOpen=function(){return!!this._socket&&this._socket.readyState===1},e.prototype._sendQueuedMessages=function(){var t,i,n=Jue([],Kue(this._messagesQueue),!1);this._messagesQueue=[];try{for(var r=Zue(n),o=r.next();!o.done;o=r.next()){var a=o.value;this.send(a)}}catch(l){t={error:l}}finally{try{o&&!o.done&&(i=r.return)&&i.call(r)}finally{if(t)throw t.error}}},e.prototype.send=function(t){if(!this._disconnected){if(!this._id){this._messagesQueue.push(t);return}if(!t.type){this.emit(Ih.Error,"Invalid message");return}if(this._wsOpen()){var i=JSON.stringify(t);this._socket.send(i)}}},e.prototype.close=function(){this._disconnected||(this._cleanup(),this._disconnected=!0)},e.prototype._cleanup=function(){this._socket&&(this._socket.onopen=this._socket.onmessage=this._socket.onclose=null,this._socket.close(),this._socket=void 0),clearTimeout(this._wsPingTimer)},e}(N_.EventEmitter),xB={};Rc(xB,"MediaConnection",()=>tz,s=>tz=s);var NO={};Rc(NO,"Negotiator",()=>$3,s=>$3=s);var MC=function(){return MC=Object.assign||function(s){for(var e,t=1,i=arguments.length;t<i;t++){e=arguments[t];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(s[n]=e[n])}return s},MC.apply(this,arguments)},Aw=function(s,e,t,i){function n(r){return r instanceof t?r:new t(function(o){o(r)})}return new(t||(t=Promise))(function(r,o){function a(h){try{c(i.next(h))}catch(u){o(u)}}function l(h){try{c(i.throw(h))}catch(u){o(u)}}function c(h){h.done?r(h.value):n(h.value).then(a,l)}c((i=i.apply(s,e||[])).next())})},_w=function(s,e){var t={label:0,sent:function(){if(r[0]&1)throw r[1];return r[1]},trys:[],ops:[]},i,n,r,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(c){return function(h){return l([c,h])}}function l(c){if(i)throw new TypeError("Generator is already executing.");for(;t;)try{if(i=1,n&&(r=c[0]&2?n.return:c[0]?n.throw||((r=n.return)&&r.call(n),0):n.next)&&!(r=r.call(n,c[1])).done)return r;switch(n=0,r&&(c=[c[0]&2,r.value]),c[0]){case 0:case 1:r=c;break;case 4:return t.label++,{value:c[1],done:!1};case 5:t.label++,n=c[1],c=[0];continue;case 7:c=t.ops.pop(),t.trys.pop();continue;default:if(r=t.trys,!(r=r.length>0&&r[r.length-1])&&(c[0]===6||c[0]===2)){t=0;continue}if(c[0]===3&&(!r||c[1]>r[0]&&c[1]<r[3])){t.label=c[1];break}if(c[0]===6&&t.label<r[1]){t.label=r[1],r=c;break}if(r&&t.label<r[2]){t.label=r[2],t.ops.push(c);break}r[2]&&t.ops.pop(),t.trys.pop();continue}c=e.call(s,t)}catch(h){c=[6,h],n=0}finally{i=r=0}if(c[0]&5)throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}},$3=function(){function s(e){this.connection=e}return s.prototype.startConnection=function(e){var t=this._startPeerConnection();if(this.connection.peerConnection=t,this.connection.type===vl.Media&&e._stream&&this._addTracksToConnection(e._stream,t),e.originator){if(this.connection.type===vl.Data){var i=this.connection,n={ordered:!!e.reliable},r=t.createDataChannel(i.label,n);i.initialize(r)}this._makeOffer()}else this.handleSDP("OFFER",e.sdp)},s.prototype._startPeerConnection=function(){mt.default.log("Creating RTCPeerConnection.");var e=new RTCPeerConnection(this.connection.provider.options.config);return this._setupListeners(e),e},s.prototype._setupListeners=function(e){var t=this,i=this.connection.peer,n=this.connection.connectionId,r=this.connection.type,o=this.connection.provider;mt.default.log("Listening for ICE candidates."),e.onicecandidate=function(a){!a.candidate||!a.candidate.candidate||(mt.default.log("Received ICE candidates for ".concat(i,":"),a.candidate),o.socket.send({type:$s.Candidate,payload:{candidate:a.candidate,type:r,connectionId:n},dst:i}))},e.oniceconnectionstatechange=function(){switch(e.iceConnectionState){case"failed":mt.default.log("iceConnectionState is failed, closing connections to "+i),t.connection.emit("error",new Error("Negotiation of connection to "+i+" failed.")),t.connection.close();break;case"closed":mt.default.log("iceConnectionState is closed, closing connections to "+i),t.connection.emit("error",new Error("Connection to "+i+" closed.")),t.connection.close();break;case"disconnected":mt.default.log("iceConnectionState changed to disconnected on the connection with "+i);break;case"completed":e.onicecandidate=Si.noop;break}t.connection.emit("iceStateChanged",e.iceConnectionState)},mt.default.log("Listening for data channel"),e.ondatachannel=function(a){mt.default.log("Received data channel");var l=a.channel,c=o.getConnection(i,n);c.initialize(l)},mt.default.log("Listening for remote stream"),e.ontrack=function(a){mt.default.log("Received remote stream");var l=a.streams[0],c=o.getConnection(i,n);if(c.type===vl.Media){var h=c;t._addStreamToMediaConnection(l,h)}}},s.prototype.cleanup=function(){mt.default.log("Cleaning up PeerConnection to "+this.connection.peer);var e=this.connection.peerConnection;if(e){this.connection.peerConnection=null,e.onicecandidate=e.oniceconnectionstatechange=e.ondatachannel=e.ontrack=function(){};var t=e.signalingState!=="closed",i=!1;if(this.connection.type===vl.Data){var n=this.connection,r=n.dataChannel;r&&(i=!!r.readyState&&r.readyState!=="closed")}(t||i)&&e.close()}},s.prototype._makeOffer=function(){return Aw(this,void 0,Promise,function(){var e,t,i,n,r,o,a;return _w(this,function(l){switch(l.label){case 0:e=this.connection.peerConnection,t=this.connection.provider,l.label=1;case 1:return l.trys.push([1,7,,8]),[4,e.createOffer(this.connection.options.constraints)];case 2:i=l.sent(),mt.default.log("Created offer."),this.connection.options.sdpTransform&&typeof this.connection.options.sdpTransform=="function"&&(i.sdp=this.connection.options.sdpTransform(i.sdp)||i.sdp),l.label=3;case 3:return l.trys.push([3,5,,6]),[4,e.setLocalDescription(i)];case 4:return l.sent(),mt.default.log("Set localDescription:",i,"for:".concat(this.connection.peer)),n={sdp:i,type:this.connection.type,connectionId:this.connection.connectionId,metadata:this.connection.metadata,browser:Si.browser},this.connection.type===vl.Data&&(r=this.connection,n=MC(MC({},n),{label:r.label,reliable:r.reliable,serialization:r.serialization})),t.socket.send({type:$s.Offer,payload:n,dst:this.connection.peer}),[3,6];case 5:return o=l.sent(),o!="OperationError: Failed to set local offer sdp: Called in wrong state: kHaveRemoteOffer"&&(t.emitError(Vn.WebRTC,o),mt.default.log("Failed to setLocalDescription, ",o)),[3,6];case 6:return[3,8];case 7:return a=l.sent(),t.emitError(Vn.WebRTC,a),mt.default.log("Failed to createOffer, ",a),[3,8];case 8:return[2]}})})},s.prototype._makeAnswer=function(){return Aw(this,void 0,Promise,function(){var e,t,i,n,r;return _w(this,function(o){switch(o.label){case 0:e=this.connection.peerConnection,t=this.connection.provider,o.label=1;case 1:return o.trys.push([1,7,,8]),[4,e.createAnswer()];case 2:i=o.sent(),mt.default.log("Created answer."),this.connection.options.sdpTransform&&typeof this.connection.options.sdpTransform=="function"&&(i.sdp=this.connection.options.sdpTransform(i.sdp)||i.sdp),o.label=3;case 3:return o.trys.push([3,5,,6]),[4,e.setLocalDescription(i)];case 4:return o.sent(),mt.default.log("Set localDescription:",i,"for:".concat(this.connection.peer)),t.socket.send({type:$s.Answer,payload:{sdp:i,type:this.connection.type,connectionId:this.connection.connectionId,browser:Si.browser},dst:this.connection.peer}),[3,6];case 5:return n=o.sent(),t.emitError(Vn.WebRTC,n),mt.default.log("Failed to setLocalDescription, ",n),[3,6];case 6:return[3,8];case 7:return r=o.sent(),t.emitError(Vn.WebRTC,r),mt.default.log("Failed to create answer, ",r),[3,8];case 8:return[2]}})})},s.prototype.handleSDP=function(e,t){return Aw(this,void 0,Promise,function(){var i,n,r,o;return _w(this,function(a){switch(a.label){case 0:t=new RTCSessionDescription(t),i=this.connection.peerConnection,n=this.connection.provider,mt.default.log("Setting remote description",t),r=this,a.label=1;case 1:return a.trys.push([1,5,,6]),[4,i.setRemoteDescription(t)];case 2:return a.sent(),mt.default.log("Set remoteDescription:".concat(e," for:").concat(this.connection.peer)),e!=="OFFER"?[3,4]:[4,r._makeAnswer()];case 3:a.sent(),a.label=4;case 4:return[3,6];case 5:return o=a.sent(),n.emitError(Vn.WebRTC,o),mt.default.log("Failed to setRemoteDescription, ",o),[3,6];case 6:return[2]}})})},s.prototype.handleCandidate=function(e){return Aw(this,void 0,Promise,function(){var t,i,n,r,o,a;return _w(this,function(l){switch(l.label){case 0:mt.default.log("handleCandidate:",e),t=e.candidate,i=e.sdpMLineIndex,n=e.sdpMid,r=this.connection.peerConnection,o=this.connection.provider,l.label=1;case 1:return l.trys.push([1,3,,4]),[4,r.addIceCandidate(new RTCIceCandidate({sdpMid:n,sdpMLineIndex:i,candidate:t}))];case 2:return l.sent(),mt.default.log("Added ICE candidate for:".concat(this.connection.peer)),[3,4];case 3:return a=l.sent(),o.emitError(Vn.WebRTC,a),mt.default.log("Failed to handleCandidate, ",a),[3,4];case 4:return[2]}})})},s.prototype._addTracksToConnection=function(e,t){if(mt.default.log("add tracks from stream ".concat(e.id," to peer connection")),!t.addTrack)return mt.default.error("Your browser does't support RTCPeerConnection#addTrack. Ignored.");e.getTracks().forEach(function(i){t.addTrack(i,e)})},s.prototype._addStreamToMediaConnection=function(e,t){mt.default.log("add stream ".concat(e.id," to media connection ").concat(t.connectionId)),t.addStream(e)},s}(),zO={};Rc(zO,"BaseConnection",()=>ez,s=>ez=s);var $ue=function(){var s=function(e,t){return s=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(i,n){i.__proto__=n}||function(i,n){for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(i[r]=n[r])},s(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");s(e,t);function i(){this.constructor=e}e.prototype=t===null?Object.create(t):(i.prototype=t.prototype,new i)}}(),ez=function(s){$ue(e,s);function e(t,i,n){var r=s.call(this)||this;return r.peer=t,r.provider=i,r.options=n,r._open=!1,r.metadata=n.metadata,r}return Object.defineProperty(e.prototype,"open",{get:function(){return this._open},enumerable:!1,configurable:!0}),e}(N_.EventEmitter),ede=function(){var s=function(e,t){return s=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(i,n){i.__proto__=n}||function(i,n){for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(i[r]=n[r])},s(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");s(e,t);function i(){this.constructor=e}e.prototype=t===null?Object.create(t):(i.prototype=t.prototype,new i)}}(),TC=function(){return TC=Object.assign||function(s){for(var e,t=1,i=arguments.length;t<i;t++){e=arguments[t];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(s[n]=e[n])}return s},TC.apply(this,arguments)},tde=function(s){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&s[e],i=0;if(t)return t.call(s);if(s&&typeof s.length=="number")return{next:function(){return s&&i>=s.length&&(s=void 0),{value:s&&s[i++],done:!s}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},tz=function(s){ede(e,s);function e(t,i,n){var r=s.call(this,t,i,n)||this;return r._localStream=r.options._stream,r.connectionId=r.options.connectionId||e.ID_PREFIX+Si.randomToken(),r._negotiator=new NO.Negotiator(r),r._localStream&&r._negotiator.startConnection({_stream:r._localStream,originator:!0}),r}return Object.defineProperty(e.prototype,"type",{get:function(){return vl.Media},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"localStream",{get:function(){return this._localStream},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"remoteStream",{get:function(){return this._remoteStream},enumerable:!1,configurable:!0}),e.prototype.addStream=function(t){mt.default.log("Receiving stream",t),this._remoteStream=t,s.prototype.emit.call(this,"stream",t)},e.prototype.handleMessage=function(t){var i=t.type,n=t.payload;switch(t.type){case $s.Answer:this._negotiator.handleSDP(i,n.sdp),this._open=!0;break;case $s.Candidate:this._negotiator.handleCandidate(n.candidate);break;default:mt.default.warn("Unrecognized message type:".concat(i," from peer:").concat(this.peer));break}},e.prototype.answer=function(t,i){var n,r;if(i===void 0&&(i={}),this._localStream){mt.default.warn("Local stream already exists on this MediaConnection. Are you answering a call twice?");return}this._localStream=t,i&&i.sdpTransform&&(this.options.sdpTransform=i.sdpTransform),this._negotiator.startConnection(TC(TC({},this.options._payload),{_stream:t}));var o=this.provider._getMessages(this.connectionId);try{for(var a=tde(o),l=a.next();!l.done;l=a.next()){var c=l.value;this.handleMessage(c)}}catch(h){n={error:h}}finally{try{l&&!l.done&&(r=a.return)&&r.call(a)}finally{if(n)throw n.error}}this._open=!0},e.prototype.close=function(){this._negotiator&&(this._negotiator.cleanup(),this._negotiator=null),this._localStream=null,this._remoteStream=null,this.provider&&(this.provider._removeConnection(this),this.provider=null),this.options&&this.options._stream&&(this.options._stream=null),this.open&&(this._open=!1,s.prototype.emit.call(this,"close"))},e.ID_PREFIX="mc_",e}(zO.BaseConnection),wB={};Rc(wB,"DataConnection",()=>nz,s=>nz=s);var R6={};Rc(R6,"EncodingQueue",()=>iz,s=>iz=s);var ide=function(){var s=function(e,t){return s=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(i,n){i.__proto__=n}||function(i,n){for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(i[r]=n[r])},s(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");s(e,t);function i(){this.constructor=e}e.prototype=t===null?Object.create(t):(i.prototype=t.prototype,new i)}}(),iz=function(s){ide(e,s);function e(){var t=s.call(this)||this;return t.fileReader=new FileReader,t._queue=[],t._processing=!1,t.fileReader.onload=function(i){t._processing=!1,i.target&&t.emit("done",i.target.result),t.doNextTask()},t.fileReader.onerror=function(i){mt.default.error("EncodingQueue error:",i),t._processing=!1,t.destroy(),t.emit("error",i)},t}return Object.defineProperty(e.prototype,"queue",{get:function(){return this._queue},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"size",{get:function(){return this.queue.length},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"processing",{get:function(){return this._processing},enumerable:!1,configurable:!0}),e.prototype.enque=function(t){this.queue.push(t),!this.processing&&this.doNextTask()},e.prototype.destroy=function(){this.fileReader.abort(),this._queue=[]},e.prototype.doNextTask=function(){this.size!==0&&(this.processing||(this._processing=!0,this.fileReader.readAsArrayBuffer(this.queue.shift())))},e}(N_.EventEmitter),nde=function(){var s=function(e,t){return s=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(i,n){i.__proto__=n}||function(i,n){for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(i[r]=n[r])},s(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");s(e,t);function i(){this.constructor=e}e.prototype=t===null?Object.create(t):(i.prototype=t.prototype,new i)}}(),sde=function(s){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&s[e],i=0;if(t)return t.call(s);if(s&&typeof s.length=="number")return{next:function(){return s&&i>=s.length&&(s=void 0),{value:s&&s[i++],done:!s}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},nz=function(s){nde(e,s);function e(t,i,n){var r=s.call(this,t,i,n)||this;return r.stringify=JSON.stringify,r.parse=JSON.parse,r._buffer=[],r._bufferSize=0,r._buffering=!1,r._chunkedData={},r._encodingQueue=new R6.EncodingQueue,r.connectionId=r.options.connectionId||e.ID_PREFIX+Si.randomToken(),r.label=r.options.label||r.connectionId,r.serialization=r.options.serialization||uh.Binary,r.reliable=!!r.options.reliable,r._encodingQueue.on("done",function(o){r._bufferedSend(o)}),r._encodingQueue.on("error",function(){mt.default.error("DC#".concat(r.connectionId,": Error occured in encoding from blob to arraybuffer, close DC")),r.close()}),r._negotiator=new NO.Negotiator(r),r._negotiator.startConnection(r.options._payload||{originator:!0}),r}return Object.defineProperty(e.prototype,"type",{get:function(){return vl.Data},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"dataChannel",{get:function(){return this._dc},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"bufferSize",{get:function(){return this._bufferSize},enumerable:!1,configurable:!0}),e.prototype.initialize=function(t){this._dc=t,this._configureDataChannel()},e.prototype._configureDataChannel=function(){var t=this;(!Si.supports.binaryBlob||Si.supports.reliable)&&(this.dataChannel.binaryType="arraybuffer"),this.dataChannel.onopen=function(){mt.default.log("DC#".concat(t.connectionId," dc connection success")),t._open=!0,t.emit("open")},this.dataChannel.onmessage=function(i){mt.default.log("DC#".concat(t.connectionId," dc onmessage:"),i.data),t._handleDataMessage(i)},this.dataChannel.onclose=function(){mt.default.log("DC#".concat(t.connectionId," dc closed for:"),t.peer),t.close()}},e.prototype._handleDataMessage=function(t){var i=this,n=t.data,r=n.constructor,o=this.serialization===uh.Binary||this.serialization===uh.BinaryUTF8,a=n;if(o){if(r===Blob){Si.blobToArrayBuffer(n,function(c){var h=Si.unpack(c);i.emit("data",h)});return}else if(r===ArrayBuffer)a=Si.unpack(n);else if(r===String){var l=Si.binaryStringToArrayBuffer(n);a=Si.unpack(l)}}else this.serialization===uh.JSON&&(a=this.parse(n));if(a.__peerData){this._handleChunk(a);return}s.prototype.emit.call(this,"data",a)},e.prototype._handleChunk=function(t){var i=t.__peerData,n=this._chunkedData[i]||{data:[],count:0,total:t.total};if(n.data[t.n]=t.data,n.count++,this._chunkedData[i]=n,n.total===n.count){delete this._chunkedData[i];var r=new Blob(n.data);this._handleDataMessage({data:r})}},e.prototype.close=function(){this._buffer=[],this._bufferSize=0,this._chunkedData={},this._negotiator&&(this._negotiator.cleanup(),this._negotiator=null),this.provider&&(this.provider._removeConnection(this),this.provider=null),this.dataChannel&&(this.dataChannel.onopen=null,this.dataChannel.onmessage=null,this.dataChannel.onclose=null,this._dc=null),this._encodingQueue&&(this._encodingQueue.destroy(),this._encodingQueue.removeAllListeners(),this._encodingQueue=null),this.open&&(this._open=!1,s.prototype.emit.call(this,"close"))},e.prototype.send=function(t,i){if(!this.open){s.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===uh.JSON)this._bufferedSend(this.stringify(t));else if(this.serialization===uh.Binary||this.serialization===uh.BinaryUTF8){var n=Si.pack(t);if(!i&&n.size>Si.chunkedMTU){this._sendChunks(n);return}Si.supports.binaryBlob?this._bufferedSend(n):this._encodingQueue.enque(n)}else this._bufferedSend(t)},e.prototype._bufferedSend=function(t){(this._buffering||!this._trySend(t))&&(this._buffer.push(t),this._bufferSize=this._buffer.length)},e.prototype._trySend=function(t){var i=this;if(!this.open)return!1;if(this.dataChannel.bufferedAmount>e.MAX_BUFFERED_AMOUNT)return this._buffering=!0,setTimeout(function(){i._buffering=!1,i._tryBuffer()},50),!1;try{this.dataChannel.send(t)}catch(n){return mt.default.error("DC#:".concat(this.connectionId," Error when sending:"),n),this._buffering=!0,this.close(),!1}return!0},e.prototype._tryBuffer=function(){if(this.open&&this._buffer.length!==0){var t=this._buffer[0];this._trySend(t)&&(this._buffer.shift(),this._bufferSize=this._buffer.length,this._tryBuffer())}},e.prototype._sendChunks=function(t){var i,n,r=Si.chunk(t);mt.default.log("DC#".concat(this.connectionId," Try to send ").concat(r.length," chunks..."));try{for(var o=sde(r),a=o.next();!a.done;a=o.next()){var l=a.value;this.send(l,!0)}}catch(c){i={error:c}}finally{try{a&&!a.done&&(n=o.return)&&n.call(o)}finally{if(i)throw i.error}}},e.prototype.handleMessage=function(t){var i=t.payload;switch(t.type){case $s.Answer:this._negotiator.handleSDP(t.type,i.sdp);break;case $s.Candidate:this._negotiator.handleCandidate(i.candidate);break;default:mt.default.warn("Unrecognized message type:",t.type,"from peer:",this.peer);break}},e.ID_PREFIX="dc_",e.MAX_BUFFERED_AMOUNT=8388608,e}(zO.BaseConnection),P6={};Rc(P6,"API",()=>oz,s=>oz=s);var sz=function(s,e,t,i){function n(r){return r instanceof t?r:new t(function(o){o(r)})}return new(t||(t=Promise))(function(r,o){function a(h){try{c(i.next(h))}catch(u){o(u)}}function l(h){try{c(i.throw(h))}catch(u){o(u)}}function c(h){h.done?r(h.value):n(h.value).then(a,l)}c((i=i.apply(s,e||[])).next())})},rz=function(s,e){var t={label:0,sent:function(){if(r[0]&1)throw r[1];return r[1]},trys:[],ops:[]},i,n,r,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(c){return function(h){return l([c,h])}}function l(c){if(i)throw new TypeError("Generator is already executing.");for(;t;)try{if(i=1,n&&(r=c[0]&2?n.return:c[0]?n.throw||((r=n.return)&&r.call(n),0):n.next)&&!(r=r.call(n,c[1])).done)return r;switch(n=0,r&&(c=[c[0]&2,r.value]),c[0]){case 0:case 1:r=c;break;case 4:return t.label++,{value:c[1],done:!1};case 5:t.label++,n=c[1],c=[0];continue;case 7:c=t.ops.pop(),t.trys.pop();continue;default:if(r=t.trys,!(r=r.length>0&&r[r.length-1])&&(c[0]===6||c[0]===2)){t=0;continue}if(c[0]===3&&(!r||c[1]>r[0]&&c[1]<r[3])){t.label=c[1];break}if(c[0]===6&&t.label<r[1]){t.label=r[1],r=c;break}if(r&&t.label<r[2]){t.label=r[2],t.ops.push(c);break}r[2]&&t.ops.pop(),t.trys.pop();continue}c=e.call(s,t)}catch(h){c=[6,h],n=0}finally{i=r=0}if(c[0]&5)throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}},oz=function(){function s(e){this._options=e}return s.prototype._buildRequest=function(e){var t=this._options.secure?"https":"http",i=this._options,n=i.host,r=i.port,o=i.path,a=i.key,l=new URL("".concat(t,"://").concat(n,":").concat(r).concat(o).concat(a,"/").concat(e));return l.searchParams.set("ts","".concat(Date.now()).concat(Math.random())),l.searchParams.set("version",UO.version),fetch(l.href,{referrerPolicy:this._options.referrerPolicy})},s.prototype.retrieveId=function(){return sz(this,void 0,Promise,function(){var e,t,i;return rz(this,function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,this._buildRequest("id")];case 1:if(e=n.sent(),e.status!==200)throw new Error("Error. Status:".concat(e.status));return[2,e.text()];case 2:throw t=n.sent(),mt.default.error("Error retrieving ID",t),i="",this._options.path==="/"&&this._options.host!==Si.CLOUD_HOST&&(i=" 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."+i);case 3:return[2]}})})},s.prototype.listAllPeers=function(){return sz(this,void 0,Promise,function(){var e,t,i;return rz(this,function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,this._buildRequest("peers")];case 1:if(e=n.sent(),e.status!==200)throw e.status===401?(t="",this._options.host===Si.CLOUD_HOST?t="It looks like you're using the cloud server. You can email team@peerjs.com to enable peer listing for your API key.":t="You need to enable `allow_discovery` on your self-hosted PeerServer to use this feature.",new Error("It doesn't look like you have permission to list peers IDs. "+t)):new Error("Error. Status:".concat(e.status));return[2,e.json()];case 2:throw i=n.sent(),mt.default.error("Error retrieving list peers",i),new Error("Could not get list peers from the server."+i);case 3:return[2]}})})},s}(),rde=function(){var s=function(e,t){return s=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(i,n){i.__proto__=n}||function(i,n){for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(i[r]=n[r])},s(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");s(e,t);function i(){this.constructor=e}e.prototype=t===null?Object.create(t):(i.prototype=t.prototype,new i)}}(),ZA=function(){return ZA=Object.assign||function(s){for(var e,t=1,i=arguments.length;t<i;t++){e=arguments[t];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(s[n]=e[n])}return s},ZA.apply(this,arguments)},Xv=function(s){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&s[e],i=0;if(t)return t.call(s);if(s&&typeof s.length=="number")return{next:function(){return s&&i>=s.length&&(s=void 0),{value:s&&s[i++],done:!s}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},ode=function(s,e){var t=typeof Symbol=="function"&&s[Symbol.iterator];if(!t)return s;var i=t.call(s),n,r=[],o;try{for(;(e===void 0||e-- >0)&&!(n=i.next()).done;)r.push(n.value)}catch(a){o={error:a}}finally{try{n&&!n.done&&(t=i.return)&&t.call(i)}finally{if(o)throw o.error}}return r},SB=function(s){rde(e,s);function e(t,i){var n=s.call(this)||this;n._id=null,n._lastServerId=null,n._destroyed=!1,n._disconnected=!1,n._open=!1,n._connections=new Map,n._lostMessages=new Map;var r;return t&&t.constructor==Object?i=t:t&&(r=t.toString()),i=ZA({debug:0,host:Si.CLOUD_HOST,port:Si.CLOUD_PORT,path:"/",key:e.DEFAULT_KEY,token:Si.randomToken(),config:Si.defaultConfig,referrerPolicy:"strict-origin-when-cross-origin"},i),n._options=i,n._options.host==="/"&&(n._options.host=window.location.hostname),n._options.path&&(n._options.path[0]!=="/"&&(n._options.path="/"+n._options.path),n._options.path[n._options.path.length-1]!=="/"&&(n._options.path+="/")),n._options.secure===void 0&&n._options.host!==Si.CLOUD_HOST?n._options.secure=Si.isSecure():n._options.host==Si.CLOUD_HOST&&(n._options.secure=!0),n._options.logFunction&&mt.default.setLogFunction(n._options.logFunction),mt.default.logLevel=n._options.debug||0,n._api=new P6.API(i),n._socket=n._createServerConnection(),!Si.supports.audioVideo&&!Si.supports.data?(n._delayedAbort(Vn.BrowserIncompatible,"The current browser does not support WebRTC"),n):r&&!Si.validateId(r)?(n._delayedAbort(Vn.InvalidID,'ID "'.concat(r,'" is invalid')),n):(r?n._initialize(r):n._api.retrieveId().then(function(o){return n._initialize(o)}).catch(function(o){return n._abort(Vn.ServerError,o)}),n)}return Object.defineProperty(e.prototype,"id",{get:function(){return this._id},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"options",{get:function(){return this._options},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"open",{get:function(){return this._open},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"socket",{get:function(){return this._socket},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"connections",{get:function(){var t,i,n=Object.create(null);try{for(var r=Xv(this._connections),o=r.next();!o.done;o=r.next()){var a=ode(o.value,2),l=a[0],c=a[1];n[l]=c}}catch(h){t={error:h}}finally{try{o&&!o.done&&(i=r.return)&&i.call(r)}finally{if(t)throw t.error}}return n},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"destroyed",{get:function(){return this._destroyed},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"disconnected",{get:function(){return this._disconnected},enumerable:!1,configurable:!0}),e.prototype._createServerConnection=function(){var t=this,i=new I6.Socket(this._options.secure,this._options.host,this._options.port,this._options.path,this._options.key,this._options.pingInterval);return i.on(Ih.Message,function(n){t._handleMessage(n)}),i.on(Ih.Error,function(n){t._abort(Vn.SocketError,n)}),i.on(Ih.Disconnected,function(){t.disconnected||(t.emitError(Vn.Network,"Lost connection to server."),t.disconnect())}),i.on(Ih.Close,function(){t.disconnected||t._abort(Vn.SocketClosed,"Underlying socket is already closed.")}),i},e.prototype._initialize=function(t){this._id=t,this.socket.start(t,this._options.token)},e.prototype._handleMessage=function(t){var i,n,r=t.type,o=t.payload,a=t.src;switch(r){case $s.Open:this._lastServerId=this.id,this._open=!0,this.emit("open",this.id);break;case $s.Error:this._abort(Vn.ServerError,o.msg);break;case $s.IdTaken:this._abort(Vn.UnavailableID,'ID "'.concat(this.id,'" is taken'));break;case $s.InvalidKey:this._abort(Vn.InvalidKey,'API KEY "'.concat(this._options.key,'" is invalid'));break;case $s.Leave:mt.default.log("Received leave message from ".concat(a)),this._cleanupPeer(a),this._connections.delete(a);break;case $s.Expire:this.emitError(Vn.PeerUnavailable,"Could not connect to peer ".concat(a));break;case $s.Offer:var m=o.connectionId,y=this.getConnection(a,m);if(y&&(y.close(),mt.default.warn("Offer received for existing Connection ID:".concat(m))),o.type===vl.Media){var l=new xB.MediaConnection(a,this,{connectionId:m,_payload:o,metadata:o.metadata});y=l,this._addConnection(a,y),this.emit("call",l)}else if(o.type===vl.Data){var c=new wB.DataConnection(a,this,{connectionId:m,_payload:o,metadata:o.metadata,label:o.label,serialization:o.serialization,reliable:o.reliable});y=c,this._addConnection(a,y),this.emit("connection",c)}else{mt.default.warn("Received malformed connection type:".concat(o.type));return}var h=this._getMessages(m);try{for(var u=Xv(h),f=u.next();!f.done;f=u.next()){var p=f.value;y.handleMessage(p)}}catch(g){i={error:g}}finally{try{f&&!f.done&&(n=u.return)&&n.call(u)}finally{if(i)throw i.error}}break;default:if(!o){mt.default.warn("You received a malformed message from ".concat(a," of type ").concat(r));return}var m=o.connectionId,y=this.getConnection(a,m);y&&y.peerConnection?y.handleMessage(t):m?this._storeMessage(m,t):mt.default.warn("You received an unrecognized message:",t);break}},e.prototype._storeMessage=function(t,i){this._lostMessages.has(t)||this._lostMessages.set(t,[]),this._lostMessages.get(t).push(i)},e.prototype._getMessages=function(t){var i=this._lostMessages.get(t);return i?(this._lostMessages.delete(t),i):[]},e.prototype.connect=function(t,i){if(i===void 0&&(i={}),this.disconnected){mt.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(Vn.Disconnected,"Cannot connect to new Peer after disconnecting from server.");return}var n=new wB.DataConnection(t,this,i);return this._addConnection(t,n),n},e.prototype.call=function(t,i,n){if(n===void 0&&(n={}),this.disconnected){mt.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(Vn.Disconnected,"Cannot connect to new Peer after disconnecting from server.");return}if(!i){mt.default.error("To call a peer, you must provide a stream from your browser's `getUserMedia`.");return}var r=new xB.MediaConnection(t,this,ZA(ZA({},n),{_stream:i}));return this._addConnection(t,r),r},e.prototype._addConnection=function(t,i){mt.default.log("add connection ".concat(i.type,":").concat(i.connectionId," to peerId:").concat(t)),this._connections.has(t)||this._connections.set(t,[]),this._connections.get(t).push(i)},e.prototype._removeConnection=function(t){var i=this._connections.get(t.peer);if(i){var n=i.indexOf(t);n!==-1&&i.splice(n,1)}this._lostMessages.delete(t.connectionId)},e.prototype.getConnection=function(t,i){var n,r,o=this._connections.get(t);if(!o)return null;try{for(var a=Xv(o),l=a.next();!l.done;l=a.next()){var c=l.value;if(c.connectionId===i)return c}}catch(h){n={error:h}}finally{try{l&&!l.done&&(r=a.return)&&r.call(a)}finally{if(n)throw n.error}}return null},e.prototype._delayedAbort=function(t,i){var n=this;setTimeout(function(){n._abort(t,i)},0)},e.prototype._abort=function(t,i){mt.default.error("Aborting!"),this.emitError(t,i),this._lastServerId?this.disconnect():this.destroy()},e.prototype.emitError=function(t,i){mt.default.error("Error:",i);var n;typeof i=="string"?n=new Error(i):n=i,n.type=t,this.emit("error",n)},e.prototype.destroy=function(){this.destroyed||(mt.default.log("Destroy peer with ID:".concat(this.id)),this.disconnect(),this._cleanup(),this._destroyed=!0,this.emit("close"))},e.prototype._cleanup=function(){var t,i;try{for(var n=Xv(this._connections.keys()),r=n.next();!r.done;r=n.next()){var o=r.value;this._cleanupPeer(o),this._connections.delete(o)}}catch(a){t={error:a}}finally{try{r&&!r.done&&(i=n.return)&&i.call(n)}finally{if(t)throw t.error}}this.socket.removeAllListeners()},e.prototype._cleanupPeer=function(t){var i,n,r=this._connections.get(t);if(r)try{for(var o=Xv(r),a=o.next();!a.done;a=o.next()){var l=a.value;l.close()}}catch(c){i={error:c}}finally{try{a&&!a.done&&(n=o.return)&&n.call(o)}finally{if(i)throw i.error}}},e.prototype.disconnect=function(){if(!this.disconnected){var t=this.id;mt.default.log("Disconnect peer with ID:".concat(t)),this._disconnected=!0,this._open=!1,this.socket.close(),this._lastServerId=t,this._id=null,this.emit("disconnected",t)}},e.prototype.reconnect=function(){if(this.disconnected&&!this.destroyed)mt.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)mt.default.error("In a hurry? We're still trying to make the initial connection!");else throw new Error("Peer ".concat(this.id," cannot reconnect because it is not disconnected from the server!"))}},e.prototype.listAllPeers=function(t){var i=this;t===void 0&&(t=function(n){}),this._api.listAllPeers().then(function(n){return t(n)}).catch(function(n){return i._abort(Vn.ServerError,n)})},e.DEFAULT_KEY="peerjs",e}(N_.EventEmitter),CB=M6.Peer;const ade=Object.freeze(Object.defineProperty({__proto__:null,get Peer(){return SB},default:CB,util:Si},Symbol.toStringTag,{value:"Module"}));let GO;function lde(){return GO}function cde(s){GO=s}function B6(s,e){return e||(e={}),e={...GO,...e},s?new CB(s,e):new CB(e)}async function az(){const s=await Promise.resolve().then(()=>ade);return console.log(s),s.default===void 0?s:s.default}class D6{constructor(){d(this,"_host");d(this,"_client");d(this,"_clientData");this.onEnable()}get isHost(){return this._host!==void 0}onEnable(){const e="HOST-5980e65c-8438-453e-8b35-f13c736dcd81";this.trySetupHost(e)}async trySetupHost(e){const t=await az(),i=new t(e);i.on("error",n=>{console.error(n),this._host=void 0,this.trySetupClient(e)}),i.on("open",n=>{this._host=new ude(i)})}async trySetupClient(e){const t=await az();this._client=new t,this._client.on("error",i=>{console.error("Client error",i)}),this._client.on("open",i=>{console.log("client connected",i),this._clientData=this._client.connect(e,{metadata:{id:i}}),this._clientData.on("open",()=>{console.log("Connected to host")}),this._clientData.on("data",n=>{console.log("<<",n)})})}}class hde{constructor(e){d(this,"_peer");this._peer=e}}class ude extends hde{constructor(t){var i;super(t);d(this,"_connections",[]);console.log("I AM THE HOST"),(i=this._peer)==null||i.on("connection",this.onConnection.bind(this)),this._peer.on("close",()=>{this.broadcast("BYE")}),setInterval(()=>{this.broadcast("HELLO")},2e3)}get isHost(){return!0}onConnection(t){console.log("host connection",t),t.on("open",()=>{this._connections.push(t),this.broadcastConnection(t)})}broadcastConnection(t){const i=this._connections.map(n=>{var r;return(r=n.metadata)==null?void 0:r.id}).filter(n=>n!==void 0);this.broadcast({type:"connection-list",connections:i})}broadcast(t){if(t!=null){console.log(">>",t);for(const i in this._peer.connections){const n=this._peer.connections[i];if(n)if(Array.isArray(n))for(const r of n)r&&r.send(t);else console.warn(n)}}}}const lz="https://urls.needle.tools/default-networking-backend/index";let Su="wss://needle-tiny-starter.glitch.me/socket";const Jr=!!ie("debugnet"),EA=!!(Jr||ie("debugowner")),cz=ie("debugnetbin");var O6=(s=>(s.ConnectionInfo="connection-start-info",s))(O6||{}),Xt=(s=>(s.Join="join-room",s.Leave="leave-room",s.JoinedRoom="joined-room",s.LeftRoom="left-room",s.UserJoinedRoom="user-joined-room",s.UserLeftRoom="user-left-room",s.RoomStateSent="room-state-sent",s))(Xt||{});class dde{constructor(){d(this,"room");d(this,"viewId");d(this,"allowEditing");d(this,"inRoom")}}class fde{constructor(){d(this,"room")}}class pde{constructor(){d(this,"userId")}}var L6=(s=>(s.RequestHasOwner="request-has-owner",s.ResponseHasOwner="response-has-owner",s.RequestIsOwner="request-is-owner",s.ResponseIsOwner="response-is-owner",s.RequestOwnership="request-ownership",s.GainedOwnership="gained-ownership",s.RemoveOwnership="remove-ownership",s.LostOwnership="lost-ownership",s.GainedOwnershipBroadcast="gained-ownership-broadcast",s.LostOwnershipBroadcast="lost-ownership-broadcast",s))(L6||{});class HO{constructor(e,t){d(this,"guid");d(this,"connection");d(this,"_hasOwnership",!1);d(this,"_isOwned");d(this,"_gainSubscription");d(this,"_lostSubscription");d(this,"_hasOwnerResponse");d(this,"_isWaitingForOwnershipResponseCallback",null);this.connection=e,this.guid=t,this._gainSubscription=this.onGainedOwnership.bind(this),this._lostSubscription=this.onLostOwnership.bind(this),e.beginListen("lost-ownership",this._lostSubscription),e.beginListen("gained-ownership-broadcast",this._gainSubscription),this._hasOwnerResponse=this.onHasOwnerResponse.bind(this),e.beginListen("response-has-owner",this._hasOwnerResponse)}get hasOwnership(){return this._hasOwnership}get isOwned(){return this._isOwned}get isConnected(){return this.connection.isConnected}updateIsOwned(){this.connection.send("request-has-owner",{guid:this.guid})}onHasOwnerResponse(e){e.guid===this.guid&&(this._isOwned=e.value)}requestOwnershipIfNotOwned(){return this._isWaitingForOwnershipResponseCallback!==null?this:(this._isWaitingForOwnershipResponseCallback=this.waitForHasOwnershipRequestResponse.bind(this),this.connection.beginListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this.connection.send("request-has-owner",{guid:this.guid}),this)}waitForHasOwnershipRequestResponse(e){e.guid===this.guid&&(this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this._isOwned=e.value,e.value||(EA&&console.log("request ownership",this.guid),this.requestOwnership()))}requestOwnershipAsync(){return new Promise((e,t)=>{this.requestOwnership();let i=0;const n=()=>{if(i++>10)return t("Timeout");setTimeout(()=>{this.hasOwnership?e(this):n()},100)};n()})}requestOwnership(){return EA&&console.log("Request ownership",this.guid),this.connection.send("request-ownership",{guid:this.guid}),this}freeOwnership(){return this.connection.send("remove-ownership",{guid:this.guid}),this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this}destroy(){this.connection.stopListen("gained-ownership",this._gainSubscription),this.connection.stopListen("lost-ownership",this._lostSubscription),this.connection.stopListen("response-has-owner",this._hasOwnerResponse),this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null)}onGainedOwnership(e){e.guid===this.guid&&(this._isOwned=!0,this.connection.connectionId===e.owner?(EA&&console.log("GAINED OWNERSHIP",this.guid),this._hasOwnership=!0):this._hasOwnership=!1)}onLostOwnership(e){e===this.guid&&(EA&&console.log("LOST OWNERSHIP",this.guid),this._hasOwnership=!1,this._isOwned=!1)}}class k6{constructor(e){d(this,"context");d(this,"_peer",null);d(this,"_usersInRoomCopy",[]);d(this,"_defaultMessagesBuffer",[]);d(this,"_defaultMessagesBufferArray",[]);d(this,"netWebSocketUrlProvider");d(this,"_listeners",{});d(this,"_listenersBinary",{});d(this,"connected",!1);d(this,"channelId");d(this,"_connectionId",null);d(this,"_ws");d(this,"_waitingForSocket",{});d(this,"_isInRoom",!1);d(this,"_currentRoomName",null);d(this,"_currentRoomViewId",null);d(this,"_currentRoomAllowEditing",!0);d(this,"_currentInRoom",[]);d(this,"_state",{});d(this,"_currentDelay",-1);d(this,"_connectingToWebsocketPromise",null);this.context=e}get peer(){return this._peer||(this._peer=new D6),this._peer}tryGetState(e){return e==="invalid"?null:this._state[e]}get connectionId(){return this._connectionId}get isDebugEnabled(){return Jr}get isConnected(){return this.connected}get currentRoomName(){return this._currentRoomName}get allowEditing(){return this._currentRoomAllowEditing}get currentRoomViewId(){return this._currentRoomViewId}getViewOnlyUrl(){if(this.currentRoomViewId===null)return null;const e=new URL(window.location.href);return e.searchParams.set("view",this.currentRoomViewId),e.href}get isInRoom(){return this._isInRoom}get currentLatency(){return this._currentDelay}get currentServerUrl(){var e;return((e=this._ws)==null?void 0:e.url)??null}sendPing(){this.send("ping",{time:this.context.time.time})}userIsInRoom(e){return this._currentInRoom.indexOf(e)!==-1}usersInRoom(e=null){e||(e=this._usersInRoomCopy),e.length=0;for(const t of this._currentInRoom)e.push(t);return e}joinRoom(e,t=!1){return e?e.length>1024?(console.error('Room name too long, can not join: "'+e+'". Max length is 1024 characters.'),!1):(this.connect(),Jr&&console.log("join: "+e),this.send("join-room",{room:e,viewOnly:t},gl.OnConnection),!0):(console.error('Missing room name, can not join: "'+e+'"'),!1)}leaveRoom(e=null){return e||(e=this.currentRoomName),e?(this.send("leave-room",{room:e}),!0):(console.error('Missing room name, can not join: "'+e+'"'),!1)}send(e,t=null,i=gl.Queued){if(t===null&&(t={}),i===gl.Queued){this._defaultMessagesBuffer.push({key:e,value:t});return}return this.sendWithWebsocket(e,t,i)}sendDeleteRemoteState(e){this.send("delete-state",{guid:e,dontSave:!0}),delete this._state[e]}sendDeleteRemoteStateAll(){this.send("delete-all-state"),this._state={}}sendBinary(e){var t;cz&&console.log("<< send binary",this.context.time.frame,e.length/1024+" KB"),(t=this._ws)==null||t.send(e)}sendBufferedMessagesNow(){var i;if(!this._ws)return;this._defaultMessagesBufferArray.length=0;const e=Object.keys(this._defaultMessagesBuffer).length;for(const n in this._defaultMessagesBuffer){const r=this._defaultMessagesBuffer[n];if(e<=1){this.sendWithWebsocket(r.key,r.value,gl.Immediate);break}const o=this.toMessage(r.key,r.value);this._defaultMessagesBufferArray.push(o)}if(this._defaultMessagesBuffer.length=0,this._defaultMessagesBufferArray.length>0&&Jr&&console.log("SEND BUFFERED",this._defaultMessagesBufferArray.length),this._defaultMessagesBufferArray.length<=0)return;const t=JSON.stringify(this._defaultMessagesBufferArray);(i=this._ws)==null||i.send(t)}beginListen(e,t){return this._listeners[e]||(this._listeners[e]=[]),this._listeners[e].push(t),t}stopListening(e,t){return this.stopListen(e,t)}stopListen(e,t){if(!t||!this._listeners[e])return;const i=this._listeners[e].indexOf(t);i>=0&&this._listeners[e].splice(i,1)}beginListenBinary(e,t){return this._listenersBinary[e]||(this._listenersBinary[e]=[]),this._listenersBinary[e].push(t),t}stopListenBinary(e,t){if(!this._listenersBinary[e])return;const i=this._listenersBinary[e].indexOf(t);i>=0&&this._listenersBinary[e].splice(i,1)}registerProvider(e){this.netWebSocketUrlProvider=e}async connect(){var t;if(this.connected)return Promise.resolve(!0);Jr&&console.log("connecting");const e=(t=this.netWebSocketUrlProvider)==null?void 0:t.getWebsocketUrl();return e?Su=e:_V()&&(Su="wss://"+window.location.host+"/socket"),this.connectWebsocket()}disconnect(){var e;(e=this._ws)==null||e.close(),this._ws=void 0}connectWebsocket(){return this._connectingToWebsocketPromise?this._connectingToWebsocketPromise:this._connectingToWebsocketPromise=new Promise(async(e,t)=>{var c,h;let i=!1;const n=u=>{i||(i=!0,e(u))};if(Su===void 0&&(console.log("Fetch default backend url: "+lz),Su=await(await fetch(lz)).text()),Su===void 0){n(!1);return}console.log(`⊡ Connecting to networking backend on
|
|
5233
5233
|
`+Su);const r=await Promise.resolve().then(()=>Kbe),o=((c=r.default)==null?void 0:c.WebsocketBuilder)??r.WebsocketBuilder,a=((h=r.default)==null?void 0:h.ExponentialBackoff)??r.ExponentialBackoff,l=new o(Su).withMaxRetries(3).withBackoff(new a(2e3,2)).onOpen(()=>{this._connectingToWebsocketPromise=null,this._ws=l,this.connected=!0,console.log(`⊞ Connected to networking backend
|
|
5234
5234
|
`+Su),n(!0),this.onSendQueued(gl.OnConnection)}).onClose(u=>{this._connectingToWebsocketPromise=null,this.connected=!1,this._isInRoom=!1,n(!1)}).onError(u=>{console.error("⊠ Websocket error"),n(!1)}).onRetry(()=>{console.log("Retry connecting to networking websocket")}).build();l.addEventListener(r.WebsocketEvent.message,(u,f)=>{this.onMessage(u,f)})})}onMessage(e,t){const i=t.data;try{if(typeof i!="string"){i.size&&this.handleIncomingBinaryMessage(i);return}const n=JSON.parse(i);if(Array.isArray(n))for(const r of n)this.handleIncomingStringMessage(r);else this.handleIncomingStringMessage(n);return}catch(n){Jr&&i==="pong"?console.log("<<",i):lt()&&console.error("Failed to parse message",n)}}async handleIncomingBinaryMessage(e){cz&&console.log("<< bin",this.context.time.frame);const t=await e.arrayBuffer();var i=new Uint8Array(t);const n=new Q0(i),r=n.getBufferIdentifier(),o=this._listenersBinary[r],a=GQ(n),l=HQ(a);if(l&&typeof l=="string"&&(this._state[l]=a),!o)return;const c=a??n;for(const h of o)h(c)}handleIncomingStringMessage(e){var n,r;if(Jr&&console.log("<<",e.key??e),e.key)switch(e.key){case"connection-start-info":if(e.data){const l=e.data;l&&(console.assert(l.id!==void 0&&l.id!==null&&l.id.length>0,"server did not send connection id",l.id),console.log("Your id is: "+l.id,this.context.alias??""),this._connectionId=l.id)}else console.warn("Expected connection id in "+e.key);break;case"joined-room":if(Jr&&console.log(e),e){this._isInRoom=!0;const l=e;this._currentRoomName=l.room,this._currentRoomViewId=l.viewId,this._currentRoomAllowEditing=l.allowEditing??!0,this._currentInRoom.length=0,this._currentInRoom.push(...l.inRoom),Jr&&console.log("joined room with",this._currentInRoom,this.context.alias??"");const c=new URL(window.location.href);c.searchParams.has("room")&&c.searchParams.delete("room"),c.searchParams.set("view",this._currentRoomViewId),console.log("Room view id: "+this._currentRoomViewId+`
|
|
5235
|
-
`+c.href)}this.onSendQueued(gl.OnRoomJoin);break;case"left-room":e.room===this.currentRoomName&&(this._isInRoom=!1,this._currentRoomName=null,this._currentInRoom.length=0);break;case"user-joined-room":if(e.data){const l=e.data;this._currentInRoom.push(l.userId),Jr&&console.log(l.userId+" joined","now in room:",this._currentInRoom)}break;case"user-left-room":if(e.data){const l=e.data,c=this._currentInRoom.indexOf(l.userId);c>=0&&(Jr&&console.log(l.userId+" left","now in room:",this._currentInRoom),this._currentInRoom.splice(c,1)),l.userId===this.connectionId&&console.log("you left the room")}break;case"all-room-state-deleted":Jr&&console.log("RECEIVED all-room-state-deleted"),this._state={};break;case"ping":case"pong":const a=(n=e.data)==null?void 0:n.time;a&&(this._currentDelay=this.context.time.time-a),Jr&&console.log("Current latency: "+this._currentDelay.toFixed(4)+" sec","Clients in room: "+((r=this._currentInRoom)==null?void 0:r.length));break}const t=e.data;t&&(this._state[t.guid]=t);let i=this._listeners[e.key];if(i){i=[...i];for(const o of i)try{o(e.data)}catch(a){console.error('Error invoking callback for "'+e.key+'"',a)}}}toMessage(e,t){return{key:e,data:t}}sendWithWebsocket(e,t,i=gl.OnRoomJoin){if(!this._ws){const r=this._waitingForSocket[i]||[];r.push(()=>this.sendWithWebsocket(e,t,i)),this._waitingForSocket[i]=r;return}const n=JSON.stringify(this.toMessage(e,t));Jr&&console.log(">>",e),this._ws.send(n)}onSendQueued(e){const t=this._waitingForSocket[e];if(t){for(const i of t)i();t.length=0}}}const $A=ie("debugwebxr");class MI{constructor(e,t){d(this,"controllerStates",[]);d(this,"userId");d(this,"context");d(this,"userStateEvtName");d(this,"onReceivedControllerState",e=>{$A&&console.log(`XRSync: Received change for ${this.userId}: ${e.type} ${e.handedness}; tracked=${e.isTracking}`);let t=!1;for(let i=0;i<this.controllerStates.length;i++)if(this.controllerStates[i].index===e.index){this.controllerStates[i]=e,t=!0;break}t||this.controllerStates.push(e)});this.userId=e,this.context=t,this.userStateEvtName="xr-sync-user-state-"+e,this.context.connection.beginListen(this.userStateEvtName,this.onReceivedControllerState)}dispose(){this.context.connection.stopListen(this.userStateEvtName,this.onReceivedControllerState)}update(e){if(this.context.connection.isConnected!=!1){for(let t=this.controllerStates.length-1;t>=0;t--){const i=this.controllerStates[t];let n=!1;for(let r=0;r<e.controllers.length;r++)e.controllers[r].index===i.index&&(n=!0);n||($A&&console.log(`XRSync: ${i.type} ${i.handedness} removed`,i.index),this.controllerStates.splice(t,1),this.sendControllerRemoved(i))}for(const t of e.controllers)this.updateControllerStates(t)}}onExitXR(e){for(const t of this.controllerStates)this.sendControllerRemoved(t);this.controllerStates.length=0}sendControllerRemoved(e){e.isTracking=!1,e.guid="",this.context.connection.send(this.userStateEvtName,e),this.context.connection.sendDeleteRemoteState(e.guid)}updateControllerStates(e){const t=this.controllerStates.find(i=>i.index===e.index);if(t){let i=!1;i||(i=t.isTracking!=e.isTracking),i&&(t.isTracking=e.isTracking,this.context.connection.send(this.userStateEvtName,t))}else{const i={guid:this.userId+"-"+e.index,isTracking:e.isTracking,handedness:e.side,index:e.index,type:e.hand?"hand":"controller"};this.controllerStates.push(i),this.context.connection.send(this.userStateEvtName,i),$A&&console.log(`XRSync: ${i.type} ${i.handedness} added`,i.index)}}}class F6{constructor(e){d(this,"context");d(this,"onJoinedRoom",()=>{if(this.context.connection.connectionId){this._states.has(this.context.connection.connectionId)||($A&&console.log("XRSync: Local user joined room",this.context.connection.connectionId),this._states.set(this.context.connection.connectionId,new MI(this.context.connection.connectionId,this.context)));for(const e of this.context.connection.usersInRoom())this._states.has(e)||this._states.set(e,new MI(e,this.context))}});d(this,"onLeftRoom",()=>{if(this.context.connection.connectionId&&!this._states.has(this.context.connection.connectionId)){const e=this._states.get(this.context.connection.connectionId);e==null||e.dispose(),this._states.delete(this.context.connection.connectionId)}});d(this,"onOtherUserJoinedRoom",e=>{const t=e.userId;this._states.has(t)||($A&&console.log("XRSync: Remote user joined room",t),this._states.set(t,new MI(t,this.context)))});d(this,"onOtherUserLeftRoom",e=>{const t=e.userId;if(!this._states.has(t)){const i=this._states.get(t);i==null||i.dispose(),this._states.delete(t)}});d(this,"_states",new Map);this.context=e,this.context.connection.beginListen(Xt.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(Xt.LeftRoom,this.onLeftRoom),this.context.connection.beginListen(Xt.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.beginListen(Xt.UserLeftRoom,this.onOtherUserLeftRoom)}hasState(e){return e?this._states.has(e):!1}isTracking(e,t){if(!e)return;const i=this._states.get(e);if(!i)return;const n=i.controllerStates.find(r=>r.handedness===t);return(n==null?void 0:n.isTracking)||!1}getDeviceType(e,t){if(!e)return;const i=this._states.get(e);if(!i)return;const n=i.controllerStates.find(r=>r.handedness===t);return(n==null?void 0:n.type)||"unknown"}destroy(){this.context.connection.stopListen(Xt.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(Xt.LeftRoom,this.onLeftRoom),this.context.connection.stopListen(Xt.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.stopListen(Xt.UserLeftRoom,this.onOtherUserLeftRoom)}onUpdate(e){if(this.context.connection.isConnected&&this.context.connection.connectionId){const t=this._states.get(this.context.connection.connectionId);t==null||t.update(e)}}onExitXR(e){if(this.context.connection.isConnected&&this.context.connection.connectionId){const t=this._states.get(this.context.connection.connectionId);t==null||t.onExitXR(e)}}}class hz{constructor(){d(this,"_fadeToColorQuad");d(this,"_fadeToColorMaterial");d(this,"_requestedFadeValue",0);d(this,"_transitionPromise",null);d(this,"_transitionResolve",null);this._fadeToColorMaterial=new ni({color:0,transparent:!0,depthTest:!1,fog:!1,side:xi}),this._fadeToColorQuad=new fe(new os(10,10),this._fadeToColorMaterial)}dispose(){this._fadeToColorQuad.geometry.dispose(),this._fadeToColorMaterial.dispose()}update(e,t){const i=this._fadeToColorQuad,n=this._fadeToColorMaterial;i.parent!==e&&n.opacity>0?e.add(i):n.opacity===0&&i.removeFromParent(),i.layers.set(2),i.material=this._fadeToColorMaterial,i.position.z=-1,i.renderOrder=1/0;const r=this._requestedFadeValue;n.opacity=it.lerp(n.opacity,r,t/.03),Math.abs(n.opacity-r)<=.01&&this._transitionResolve&&(this._transitionResolve(),this._transitionResolve=null,this._transitionPromise=null,this._requestedFadeValue=0)}remove(){this._fadeToColorQuad.removeFromParent()}fadeTransition(){if(this._transitionPromise)return this._transitionPromise;this._requestedFadeValue=1;const e=new Promise(t=>{this._transitionResolve=t});return this._transitionPromise=e,e}}var Sp=(s=>(s[s.Quad=0]="Quad",s[s.Cube=1]="Cube",s[s.Sphere=2]="Sphere",s))(Sp||{});class z_{static createPrimitive(e,t){let i;switch(e){case"Quad":case 0:{const r=new os(1,1,1,1),o=(t==null?void 0:t.material)??new Pr({color:16777215});t!=null&&t.texture&&"map"in o&&(o.map=t.texture),i=new fe(r,o)}break;case"Cube":case 1:{const r=new Xi(1,1,1),o=(t==null?void 0:t.material)??new Pr({color:16777215});t!=null&&t.texture&&"map"in o&&(o.map=t.texture),i=new fe(r,o)}break;case"Sphere":case 2:{const r=new Wa(.5,16,16),o=(t==null?void 0:t.material)??new Pr({color:16777215});t!=null&&t.texture&&"map"in o&&(o.map=t.texture),i=new fe(r,o)}break}return this.applyDefaultObjectOptions(i,t),i}static createSprite(e){const i=new g1({color:16777215});e!=null&&e.texture&&"map"in i&&(i.map=e.texture);const n=new F2(i);return this.applyDefaultObjectOptions(n,e),n}static applyDefaultObjectOptions(e,t){t!=null&&t.name&&(e.name=t.name),t!=null&&t.position&&e.position.set(t.position.x,t.position.y,t.position.z),t!=null&&t.rotation&&e.rotation.set(t.rotation.x,t.rotation.y,t.rotation.z),t!=null&&t.scale&&e.scale.set(t.scale.x,t.scale.y,t.scale.z)}}const ck=class{constructor(e,t,i){d(this,"_session");d(this,"_mode");d(this,"_init");d(this,"_renderer");d(this,"_camera");d(this,"_scene");d(this,"onEnd",()=>{var e;(e=this._session)==null||e.removeEventListener("end",this.onEnd),this._renderer.setAnimationLoop(null),this._renderer.dispose(),this._scene.clear()});d(this,"_lastTime",0);d(this,"onFrame",(e,t)=>{const i=e-this._lastTime;this.update(e,i),this._camera.parent!==this._scene&&this._scene.add(this._camera),this._renderer.render(this._scene,this._camera)});d(this,"_objects",[]);this._mode=e,this._init=t,this._session=i,this._session.addEventListener("end",this.onEnd),this._renderer=new Vh({alpha:!0}),this._renderer.setAnimationLoop(this.onFrame),this._renderer.xr.setSession(i),this._renderer.xr.enabled=!0,this._camera=new Gt,this._scene=new rr,this._scene.fog=new m1(4473924,10,250),this._scene.add(this._camera),this.setupScene()}static get active(){return this._active}static async start(e,t){if(this._active)return console.error("Cannot start a new XR session while one is already active"),null;if(this._requestInFlight)return console.error("Cannot start a new XR session while a request is already in flight"),null;if("xr"in navigator&&navigator.xr){if(!t)return console.error("XRSessionInit must be provided"),null;this._requestInFlight=!0;const i=await navigator.xr.requestSession(e,t);return i.addEventListener("end",()=>{this._active=null}),this._requestInFlight?(this._requestInFlight=!1,this._active=new ck(e,t,i),this._active):(i.end(),null)}return null}static async handoff(){return this._active?this._active.handoff():null}static async stop(){this._requestInFlight=!1,this._active&&(await this._active.end(),await wc(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 e={session:this._session,mode:this._mode,init:this._init};return await this.onBeforeHandoff(),this.onEnd(),this._session=null,e}async onBeforeHandoff(){await wc(1e3),this._scene.clear()}setupScene(){this._scene.background=new Ae(0),this._scene.add(new z1(5,10,1118481,1118481));const e=new Ap(16777215,1);e.position.set(0,20,0),e.castShadow=!1,this._scene.add(e);const t=new Ap(16777215,1);t.position.set(0,-1,0),t.castShadow=!1,this._scene.add(t);const i=new vp(16777215,1,100,1);i.position.set(0,2,0),i.castShadow=!1,i.distance=200,this._scene.add(i);const n=50;for(let r=0;r<100;r++){const o=new Pr({color:2236962,metalness:1,roughness:.8});this.isAR&&(o.emissive=new Ae(Math.random(),Math.random(),Math.random()),o.emissiveIntensity=Math.random());const a=it.random(0,1)>.5?Sp.Sphere:Sp.Cube,l=z_.createPrimitive(a,{material:o});l.position.x=it.random(-n,n),l.position.y=it.random(-2,n),l.position.z=it.random(-n,n),l.rotation.x=it.random(0,Math.PI*2),l.rotation.y=it.random(0,Math.PI*2),l.rotation.z=it.random(0,Math.PI*2),l.scale.multiplyScalar(.5+Math.random()*10);const c=l.position.distanceTo(this._camera.position)-l.scale.x;c<1&&l.position.multiplyScalar(1+1/c),this._objects.push(l),this._scene.add(l)}}update(e,t){const i=e*4e-4;for(let n=0;n<this._objects.length;n++){const r=this._objects[n];r.position.y+=Math.sin(i+n*.5)*.005,r.rotateY(.002)}}};let qu=ck;d(qu,"_active",null),d(qu,"_requestInFlight",!1);const Ss=ie("debugwebxr"),mde=ie("stats");function gde(s){let e=null;const t=s;return t.getAROverlayContainer?e=t.getAROverlayContainer():e=s,e}yde();async function yde(){var s;if(ie("debugasap")){let e=globalThis["needle:XRSession"];if(e instanceof Promise){delete globalThis["needle:XRSession"],di.addContextCreatedCallback(async t=>{if(!e)return;cy(!0);const i=await e;if(i){const n=xt.getDefaultSessionInit("immersive-vr");xt.setSession("immersive-vr",i,n,t.context)}else console.error("NeedleXRSession: ASAP session was rejected");e=void 0});return}}if("xr"in navigator){if(/WebXRViewer\//i.test(navigator.userAgent)){console.warn("WebXRViewer does not support addEventListener");return}(s=navigator.xr)==null||s.addEventListener("sessiongranted",async()=>{cy(!0),console.log("Received Session Granted..."),await wc(100);const e=sessionStorage.getItem("needle_xr_session_mode"),t=sessionStorage.getItem("needle_xr_session_init")??null,i=t?JSON.parse(t):null;let n=null;if(U6()&&(await qu.start(e||"immersive-vr",i||xt.getDefaultSessionInit("immersive-vr")),await _de(),n=await qu.handoff()),n)xt.setSession(n.mode,n.session,n.init,Ot.Current);else if(e&&t){console.log("Session Granted: Restore last session");const r=JSON.parse(t);xt.start(e,r).catch(o=>console.warn(o))}else xt.start("immersive-vr").catch(r=>console.warn("Session Granted failed:",r))},{once:!0})}}function vde(s,e){sessionStorage.setItem("needle_xr_session_mode",s),sessionStorage.setItem("needle_xr_session_init",JSON.stringify(e))}function Ade(){sessionStorage.removeItem("needle_xr_session_mode"),sessionStorage.removeItem("needle_xr_session_init")}const VO=new Set;di.registerCallback(Ii.ContextCreationStart,async s=>{VO.add(s.context)});di.registerCallback(Ii.ContextCreated,async s=>{VO.delete(s.context)});function U6(){return VO.size>0}function _de(){return new Promise(s=>{const e=Date.now(),t=setInterval(()=>{(!U6()||Date.now()-e>6e4)&&(clearInterval(t),s())},100)})}_p()&<()&&window.addEventListener("keydown",s=>{(s.key==="x"||s.key==="Escape")&&xt.active&&xt.stop()});const ph=class{constructor(e,t,i,n){d(this,"context");d(this,"session");d(this,"mode");d(this,"controllers",[]);d(this,"_rigScale",1);d(this,"_lastRigScaleUpdate",-1);d(this,"_rigs",[]);d(this,"_viewerHitTestSource",null);d(this,"_defaultRig");d(this,"_xr_scripts");d(this,"_xr_update_scripts",[]);d(this,"_inactive_scripts",[]);d(this,"_controllerAdded");d(this,"_controllerRemoved");d(this,"_originalCameraWorldPosition");d(this,"_originalCameraWorldRotation");d(this,"_originalCameraWorldScale");d(this,"_originalCameraParent");d(this,"_mainCamera",null);d(this,"onRendererSessionSet",()=>{var e;this.running&&(this.context.renderer.xr.enabled=!0,this.context.renderer.xr.updateCamera(this.context.mainCamera),(e=this.context.mainCameraComponent)==null||e.applyClearFlags())});d(this,"onInputSourceAdded",e=>{if(e.targetRayMode==="screen")return;let t=0;for(let n=0;n<this.session.inputSources.length;n++)if(this.session.inputSources[n]===e){t=n;break}if(this.controllers.find(n=>n.inputSource===e)){console.warn("Controller already exists for input source",t);return}Ss&&console.log("Adding controller",t);const i=new DO(this,e,t);this._newControllers.push(i)});d(this,"_ended",!1);d(this,"_newControllers",[]);d(this,"onEnd",e=>{var n,r,o;if(this._ended)return;this._ended=!0,Ss&&console.log("XR Session ended"),Ade(),this.onAfterRender(),this.revertCustomForward(),this._didStart=!1,this._previousCameraParent=null,Md(this.onBefore,$i.LateUpdate);const t=this.context.pre_render_callbacks.indexOf(this.onBeforeRender);t>=0&&this.context.pre_render_callbacks.splice(t,1);const i=this.context.post_render_callbacks.indexOf(this.onAfterRender);i>=0&&this.context.post_render_callbacks.splice(i,1),this.context.xr=null,this.context.renderer.xr.enabled=!1,this.context.pre_update_oneshot_callbacks.push(()=>{var a;(a=this.context.mainCameraComponent)==null||a.applyClearFlags()}),UQ({session:this});for(const a of ph._xrEndListeners)a({xr:this});for(let a=0;a<this.controllers.length;a++)this.disconnectInputSource(this.controllers[a].inputSource);for(const a of this._xr_scripts)(n=a==null?void 0:a.onLeaveXR)==null||n.call(a,{xr:this});(r=this.sync)==null||r.onExitXR(this),this.context.mainCamera&&((o=this._originalCameraParent)==null||o.add(this.context.mainCamera),this._originalCameraWorldPosition&&gs(this.context.mainCamera,this._originalCameraWorldPosition),this._originalCameraWorldRotation&&za(this.context.mainCamera,this._originalCameraWorldRotation),this._originalCameraWorldScale&&ly(this.context.mainCamera,this._originalCameraWorldScale)),this.context.requestSizeUpdate(),this._defaultRig.gameObject.removeFromParent(),cy(!1)});d(this,"_didStart",!1);d(this,"onBefore",e=>{var n,r,o,a,l,c,h,u;const t=e.xrFrame;if(!t)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&&(Ss&&console.warn("Latest rig is not active - trying to activate a different rig",this.rig),this.updateActiveXRRig()),this.rig&&((r=this._mainCamera)!=null&&r.gameObject)&&((a=(o=this._mainCamera)==null?void 0:o.gameObject)==null?void 0:a.parent)!==this.rig.gameObject&&this.rig.gameObject.add((l=this._mainCamera)==null?void 0:l.gameObject),this.internalUpdateState(),this.applyCustomForward();const i={xr:this};if(this._didStart){if(this.context.new_scripts_xr.length>0){const f=[...this.context.new_scripts_xr];for(let p=0;p<f.length;p++){const m=this.context.new_scripts_xr[p];if(!m||m.destroyed||((c=m.supportsXR)==null?void 0:c.call(m,this.mode))==!1){this.context.new_scripts_xr.splice(p,1);continue}if(!m.activeAndEnabled){this.context.new_scripts_xr.splice(p,1),this.markInactive(m);continue}if(this.addScript(m)){this.invokeCallback_EnterXR(m);for(const y of this.controllers)this.invokeCallback_ControllerAdded(m,y)}}}}else{if(this._didStart=!0,this.mode==="immersive-vr"){const p=Sc(this.context.scene.children);if(p){const m=p.getSize(pi());if(m.length()>0){const y=this._defaultRig.gameObject;y.position.set(p.min.x+m.x*.5,p.min.y,p.max.z+m.z*.5+1.5);const g=p.getCenter(pi());g.y=y.position.y,y.lookAt(g)}}}FQ({session:this});for(const p of ph._xrStartListeners)p(i);const f=[...this._xr_scripts];Ss&&console.log("NeedleXRSession start, handle scripts:",f);for(const p of f){if(p.destroyed){this._script_to_remove.push(p);continue}if(!p.activeAndEnabled){this.markInactive(p);continue}this.invokeCallback_EnterXR(p);for(const m of this.controllers)this.invokeCallback_ControllerAdded(p,m)}}this.syncCameraCullingMask();for(const f of this.controllers)f.onUpdate(t);if(this._newControllers.length>0){const f=[...this._newControllers];this._newControllers.length=0;for(const p of f)if(p.connected){this.controllers.push(p);for(const m of this._xr_scripts){if(m.destroyed){this._script_to_remove.push(m);continue}m.activeAndEnabled!==!1&&this.invokeCallback_ControllerAdded(m,p)}}this.controllers.sort((p,m)=>p.index-m.index)}for(const f of this._xr_update_scripts){if(f.destroyed===!0){this._script_to_remove.push(f);continue}if(f.activeAndEnabled===!1){this.markInactive(f);continue}f.onUpdateXR&&f.onUpdateXR(i)}if(this.handleInactiveScripts(),this._script_to_remove.length>0){const f=[...new Set(this._script_to_remove)];this._script_to_remove.length=0;for(const p of f)!p.destroyed&&this.running&&((h=p.onLeaveXR)==null||h.call(p,i)),this.removeScript(p)}(u=this.sync)==null||u.onUpdate(this),this.onRenderDebug()});d(this,"onBeforeRender",()=>{this.context.mainCamera&&this.updateFade(this.context.mainCamera)});d(this,"onAfterRender",()=>{if(this.onUpdateFade_PostRender(),_p()){const e=this.context.renderer;if(e.xr.isPresenting&&this.context.mainCamera){const t=e.xr.enabled,i=e.getRenderTarget();e.xr.enabled=!1,e.setRenderTarget(null),e.render(this.context.scene,this.context.mainCamera),e.xr.enabled=t,e.setRenderTarget(i)}}});d(this,"_script_to_remove",[]);d(this,"_camera");d(this,"_cameraRenderParent",new ve().rotateY(Math.PI));d(this,"_previousCameraParent");d(this,"_customforward",!0);d(this,"originalCameraNearPlane");d(this,"_viewerPose");d(this,"_transformOrientation",new Ce);d(this,"_transformPosition",new w);d(this,"_transition");var r,o;vde(e,n.init),this.session=t,this.mode=e,this.context=i,(Ss||ie("console"))&&cy(!0),this._xr_scripts=[...n.scripts],this._xr_update_scripts=this._xr_scripts.filter(a=>typeof a.onUpdateXR=="function"),this._controllerAdded=n.controller_added,this._controllerRemoved=n.controller_removed,Ed(this.onBefore,$i.LateUpdate),this.context.pre_render_callbacks.push(this.onBeforeRender),this.context.post_render_callbacks.push(this.onAfterRender),((r=n.init.optionalFeatures)!=null&&r.includes("hit-test")||(o=n.init.requiredFeatures)!=null&&o.includes("hit-test"))&&t.requestReferenceSpace("viewer").then(a=>{var l,c;return(c=(l=t.requestHitTestSource)==null?void 0:l.call(t,{space:a}))==null?void 0:c.then(h=>this._viewerHitTestSource=h)}).catch(a=>console.warn(a)),this.context.mainCamera&&(this._originalCameraWorldPosition=kt(this.context.mainCamera,new w),this._originalCameraWorldRotation=Ri(this.context.mainCamera,new Ce),this._originalCameraWorldScale=Ki(this.context.mainCamera,new w),this._originalCameraParent=this.context.mainCamera.parent),this._defaultRig=new wue,this.context.scene.add(this._defaultRig.gameObject),this.addRig(this._defaultRig);for(let a=0;a<t.inputSources.length;a++){const l=t.inputSources[a];if(!l.handedness){console.warn("Input source in xr session has no handedness - ignoring",a);continue}this.onInputSourceAdded(l)}this.session.addEventListener("end",this.onEnd),this.session.addEventListener("inputsourceschange",a=>{for(const l of a.removed)this.disconnectInputSource(l);for(const l of a.added)this.onInputSourceAdded(l)}),this.context.xr=this,this.context.renderer.xr.setSession(this.session).then(this.onRendererSessionSet)}static getXRSync(e){return this._sync||(this._sync=new F6(e)),this._sync}static get currentSessionRequest(){return this._currentSessionRequestMode}static get active(){return this._activeSession}static get activeMode(){var e;return((e=this._activeSession)==null?void 0:e.mode)??null}static get xrSystem(){return"xr"in navigator?navigator.xr:void 0}static isXRSupported(){return Promise.all([this.isVRSupported(),this.isARSupported()]).then(e=>e.some(t=>t)).catch(()=>!1)}static isVRSupported(){return this.isSessionSupported("immersive-vr")}static isARSupported(){return this.isSessionSupported("immersive-ar")}static isSessionSupported(e){var t;return((t=this.xrSystem)==null?void 0:t.isSessionSupported(e).catch(i=>(Ss&&console.error(i),!1)))??Promise.resolve(!1)}static onSessionRequestStart(e){this._sessionRequestStartListeners.push(e)}static offSessionRequestStart(e){const t=this._sessionRequestStartListeners.indexOf(e);t>=0&&this._sessionRequestStartListeners.splice(t,1)}static onSessionRequestEnd(e){this._sessionRequestEndListeners.push(e)}static offSessionRequestEnd(e){const t=this._sessionRequestEndListeners.indexOf(e);t>=0&&this._sessionRequestEndListeners.splice(t,1)}static onXRSessionStart(e){this._xrStartListeners.push(e)}static offXRSessionStart(e){const t=this._xrStartListeners.indexOf(e);t>=0&&this._xrStartListeners.splice(t,1)}static onXRSessionEnd(e){this._xrEndListeners.push(e)}static offXRSessionEnd(e){const t=this._xrEndListeners.indexOf(e);t>=0&&this._xrEndListeners.splice(t,1)}static onControllerAdded(e){this._controllerAddedListeners.push(e)}static offControllerAdded(e){const t=this._controllerAddedListeners.indexOf(e);t>=0&&this._controllerAddedListeners.splice(t,1)}static onControllerRemoved(e){this._controllerRemovedListeners.push(e)}static offControllerRemoved(e){const t=this._controllerRemovedListeners.indexOf(e);t>=0&&this._controllerRemovedListeners.splice(t,1)}static offerSession(e,t,i){return"xr"in navigator&&navigator.xr&&"offerSession"in navigator.xr?(typeof navigator.xr.offerSession=="function"&&(console.log("WebXR offerSession is available - requesting mode: "+e),t=="default"&&(t=this.getDefaultSessionInit(e)),navigator.xr.offerSession(e,{...t}).then(n=>ph.setSession(e,n,t,i)).catch(n=>{console.log("XRSession offer rejected (perhaps because another call to offerSession was made or a call to requestSession was made)")})),!0):!1}static getDefaultSessionInit(e){switch(e){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",e),{}}}static async start(e,t,i){var o,a,l,c;if(lt()&&ie("debugxrpreroom"))return console.warn("Debug: Starting temporary XR session"),await qu.start(e,t||ph.getDefaultSessionInit(e)),null;if(this._currentSessionRequest)return console.warn("A XRSession is already being requested"),(Ss||lt())&&Ni("A XRSession is already being requested"),this._currentSessionRequest.then(()=>this._activeSession);if(this._activeSession)return console.error("A XRSession is already running"),this._activeSession;if(i||(i=Ot.Current),i||(i=di.All[0]),!i)throw new Error("No Needle Engine Context found");switch(t||(t={}),e){case"immersive-ar":{if(await((o=this.xrSystem)==null?void 0:o.isSessionSupported("immersive-ar"))!==!0)return console.error(e+" is not supported by this browser."),null;const u=this.getDefaultSessionInit(e),f=gde(i.domElement);f&&!H1()&&(u.domOverlay={root:f},u.optionalFeatures.push("dom-overlay")),t={...u,...t}}break;case"immersive-vr":{if(await((a=this.xrSystem)==null?void 0:a.isSessionSupported("immersive-vr"))!==!0)return console.error(e+" is not supported by this browser."),null;t={...this.getDefaultSessionInit(e),...t}}break;default:console.warn("No default session init for mode",e);break}t.optionalFeatures??(t.optionalFeatures=[]),t.requiredFeatures??(t.requiredFeatures=[]),await qu.stop();const n=e=="immersive-ar"?i.scripts_immersive_ar:i.scripts_immersive_vr;Ss?console.log(`%cRequesting ${e} session`,"font-weight:bold;",t,n):console.log(`%cRequesting ${e} session`,"font-weight:bold;");for(const h of n)h.onBeforeXR&&h.onBeforeXR(e,t);for(const h of this._sessionRequestStartListeners)h({mode:e,init:t});Ss&&pn("Requesting "+e+" session ("+Date.now()+")"),this._currentSessionRequest=(l=navigator.xr)==null?void 0:l.requestSession(e,t),this._currentSessionRequestMode=e;const r=await((c=this._currentSessionRequest)==null?void 0:c.catch(h=>{console.error(h,"Code: "+h.code),h.code===9&&Ni("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:"&&Ni("XR requires a secure connection (HTTPS)")}));this._currentSessionRequest=void 0,this._currentSessionRequestMode=null;for(const h of this._sessionRequestEndListeners)h({mode:e,init:t,newSession:r||null});return r?this.setSession(e,r,t,i):(console.warn("XR Session request was rejected"),null)}static setSession(e,t,i,n){if(this._activeSession)return console.error("A XRSession is already running"),this._activeSession;const r=e=="immersive-ar"?n.scripts_immersive_ar:n.scripts_immersive_vr;return this._activeSession=new ph(e,t,n,{scripts:r,controller_added:this._controllerAddedListeners,controller_removed:this._controllerRemovedListeners,init:i}),t.addEventListener("end",this.onEnd),Ss?console.log(`%cStarted ${e} session`,"font-weight:bold;",r):console.log(`%cStarted ${e} session`,"font-weight:bold;"),this._activeSession}static stop(){var e;(e=this._activeSession)==null||e.end()}get sync(){return ph._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(e=>e.isLeft)}get rightController(){return this.controllers.find(e=>e.isRight)}getController(e){return typeof e=="number"?this.controllers[e]||null:this.controllers.find(t=>t.side===e)||null}get isPassThrough(){return!!(this.environmentBlendMode!=="opaque"&&this.interactionMode==="world-space"||this.mode==="immersive-ar"&&this.environmentBlendMode!=="opaque"&&this.controllers.some(e=>e.inputSource.targetRayMode==="tracked-pointer")||lt()&&_p()&&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 e=this.frame.getImageTrackingResults();for(const t of e)if(t.trackingState==="tracked")return!0}catch{return!1}return!1}get rig(){const e=this._rigs[0]??null;return e!=null&&e.gameObject&&Cp(e.gameObject)||(e==null?void 0:e.isActive)===!1?(this.updateActiveXRRig(),this._rigs[0]??null):e}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(e){this._rigs.indexOf(e)>=0||(e.priority===void 0&&(e.priority=0),this._rigs.push(e),this.updateActiveXRRig())}removeRig(e){const t=this._rigs.indexOf(e);t!==-1&&(this._rigs.splice(t,1),this.updateActiveXRRig())}setRigActive(e){const t=this._rigs.indexOf(e);this._rigs.splice(t,1),this._rigs.unshift(e),this.updateActiveXRRig()}updateActiveXRRig(){const e=this._rigs[0]??null;this._defaultRig.gameObject.parent!==this.context.scene&&this.context.scene.add(this._defaultRig.gameObject),this._defaultRig.gameObject.visible=!0,this._rigs.includes(this._defaultRig)||this._rigs.push(this._defaultRig);let t=this._rigs[0];t&&t.priority===void 0&&(t.priority=0);for(let i=1;i<this._rigs.length;i++){const n=this._rigs[i];if(n.isActive){if(Cp(n.gameObject)){this._rigs.splice(i,1),i--;continue}(!t||t.isActive===!1||n.priority!==void 0&&n.priority>t.priority)&&(t=n)}}if(e!==t){const i=this._rigs.indexOf(t);i>=0&&this._rigs.splice(i,1),this._rigs.unshift(t)}Ss&&(e===t?console.log("Updated Active XR Rig:",t,"prev:",e):console.log("Updated Active XRRig:",t," (the same as before)"))}getHitTest(e){if(e)return this.getControllerHitTest(e);if(!this._viewerHitTestSource)return null;const t=this._viewerHitTestSource,i=this.frame.getHitTestResults(t);if(i.length>0){const n=i[0];return this.convertHitTestResult(n)}return null}getControllerHitTest(e){const t=e.hitTestSource;if(!t)return null;const i=this.frame.getHitTestResultsForTransientInput(t);for(const n of i)if(n.inputSource===e.inputSource)for(const r of n.results)return this.convertHitTestResult(r);return null}convertHitTestResult(e){const t=this.context.renderer.xr.getReferenceSpace(),i=t&&e.getPose(t);if(i){const n=pi(i.transform.position),r=Nf(i.transform.orientation),o=this.context.mainCamera;if((o==null?void 0:o.parent)!==this._cameraRenderParent&&n.applyMatrix4(EC),o!=null&&o.parent){n.applyMatrix4(o.parent.matrixWorld),r.multiply(Ca);const a=Ri(o.parent);a.premultiply(Ca),r.premultiply(a)}return{hit:e,position:n,quaternion:r}}return null}convertSpace(e){const t=pi(e.position);t.applyMatrix4(EC);const i=Nf(e.orientation);return i.premultiply(Ca),{position:t,quaternion:i}}disconnectInputSource(e){const t=(i,n,r)=>{if(i.inputSource===e){Ss&&console.log("Disconnecting controller",i.index),this.controllers.splice(r,1),this.invokeControllerEvent(i,this._controllerRemoved,"removed");const o={xr:this,controller:i,change:"removed"};for(const a of this._xr_scripts)a.onXRControllerRemoved&&a.onXRControllerRemoved(o);i.onDisconnected()}};for(let i=this.controllers.length-1;i>=0;i--){const n=this.controllers[i];t(n,this.controllers,i)}for(let i=this._newControllers.length-1;i>=0;i--){const n=this._newControllers[i];t(n,this._newControllers,i)}}end(){this._ended||this.session.end().catch(e=>console.warn(e))}onRenderDebug(){if(Ss)for(const e of this.controllers)e.onRenderDebug();if((Ss||mde)&&this.rig){const e=this.rig.gameObject.worldPosition,t=this.rig.gameObject.worldForward;e.add(t.multiplyScalar(1.5));const i=this.rig.gameObject.worldUp;e.add(i.multiplyScalar(2.5));let n="";if(n+=this.context.time.smoothedFps.toFixed(1),Ss)for(const r of this.controllers)n+=`
|
|
5235
|
+
`+c.href)}this.onSendQueued(gl.OnRoomJoin);break;case"left-room":e.room===this.currentRoomName&&(this._isInRoom=!1,this._currentRoomName=null,this._currentInRoom.length=0);break;case"user-joined-room":if(e.data){const l=e.data;this._currentInRoom.push(l.userId),Jr&&console.log(l.userId+" joined","now in room:",this._currentInRoom)}break;case"user-left-room":if(e.data){const l=e.data,c=this._currentInRoom.indexOf(l.userId);c>=0&&(Jr&&console.log(l.userId+" left","now in room:",this._currentInRoom),this._currentInRoom.splice(c,1)),l.userId===this.connectionId&&console.log("you left the room")}break;case"all-room-state-deleted":Jr&&console.log("RECEIVED all-room-state-deleted"),this._state={};break;case"ping":case"pong":const a=(n=e.data)==null?void 0:n.time;a&&(this._currentDelay=this.context.time.time-a),Jr&&console.log("Current latency: "+this._currentDelay.toFixed(4)+" sec","Clients in room: "+((r=this._currentInRoom)==null?void 0:r.length));break}const t=e.data;t&&(this._state[t.guid]=t);let i=this._listeners[e.key];if(i){i=[...i];for(const o of i)try{o(e.data)}catch(a){console.error('Error invoking callback for "'+e.key+'"',a)}}}toMessage(e,t){return{key:e,data:t}}sendWithWebsocket(e,t,i=gl.OnRoomJoin){if(!this._ws){const r=this._waitingForSocket[i]||[];r.push(()=>this.sendWithWebsocket(e,t,i)),this._waitingForSocket[i]=r;return}const n=JSON.stringify(this.toMessage(e,t));Jr&&console.log(">>",e),this._ws.send(n)}onSendQueued(e){const t=this._waitingForSocket[e];if(t){for(const i of t)i();t.length=0}}}const $A=ie("debugwebxr");class MI{constructor(e,t){d(this,"controllerStates",[]);d(this,"userId");d(this,"context");d(this,"userStateEvtName");d(this,"onReceivedControllerState",e=>{$A&&console.log(`XRSync: Received change for ${this.userId}: ${e.type} ${e.handedness}; tracked=${e.isTracking}`);let t=!1;for(let i=0;i<this.controllerStates.length;i++)if(this.controllerStates[i].index===e.index){this.controllerStates[i]=e,t=!0;break}t||this.controllerStates.push(e)});this.userId=e,this.context=t,this.userStateEvtName="xr-sync-user-state-"+e,this.context.connection.beginListen(this.userStateEvtName,this.onReceivedControllerState)}dispose(){this.context.connection.stopListen(this.userStateEvtName,this.onReceivedControllerState)}update(e){if(this.context.connection.isConnected!=!1){for(let t=this.controllerStates.length-1;t>=0;t--){const i=this.controllerStates[t];let n=!1;for(let r=0;r<e.controllers.length;r++)e.controllers[r].index===i.index&&(n=!0);n||($A&&console.log(`XRSync: ${i.type} ${i.handedness} removed`,i.index),this.controllerStates.splice(t,1),this.sendControllerRemoved(i))}for(const t of e.controllers)this.updateControllerStates(t)}}onExitXR(e){for(const t of this.controllerStates)this.sendControllerRemoved(t);this.controllerStates.length=0}sendControllerRemoved(e){e.isTracking=!1,e.guid="",this.context.connection.send(this.userStateEvtName,e),this.context.connection.sendDeleteRemoteState(e.guid)}updateControllerStates(e){const t=this.controllerStates.find(i=>i.index===e.index);if(t){let i=!1;i||(i=t.isTracking!=e.isTracking),i&&(t.isTracking=e.isTracking,this.context.connection.send(this.userStateEvtName,t))}else{const i={guid:this.userId+"-"+e.index,isTracking:e.isTracking,handedness:e.side,index:e.index,type:e.hand?"hand":"controller"};this.controllerStates.push(i),this.context.connection.send(this.userStateEvtName,i),$A&&console.log(`XRSync: ${i.type} ${i.handedness} added`,i.index)}}}class F6{constructor(e){d(this,"context");d(this,"onJoinedRoom",()=>{if(this.context.connection.connectionId){this._states.has(this.context.connection.connectionId)||($A&&console.log("XRSync: Local user joined room",this.context.connection.connectionId),this._states.set(this.context.connection.connectionId,new MI(this.context.connection.connectionId,this.context)));for(const e of this.context.connection.usersInRoom())this._states.has(e)||this._states.set(e,new MI(e,this.context))}});d(this,"onLeftRoom",()=>{if(this.context.connection.connectionId&&!this._states.has(this.context.connection.connectionId)){const e=this._states.get(this.context.connection.connectionId);e==null||e.dispose(),this._states.delete(this.context.connection.connectionId)}});d(this,"onOtherUserJoinedRoom",e=>{const t=e.userId;this._states.has(t)||($A&&console.log("XRSync: Remote user joined room",t),this._states.set(t,new MI(t,this.context)))});d(this,"onOtherUserLeftRoom",e=>{const t=e.userId;if(!this._states.has(t)){const i=this._states.get(t);i==null||i.dispose(),this._states.delete(t)}});d(this,"_states",new Map);this.context=e,this.context.connection.beginListen(Xt.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(Xt.LeftRoom,this.onLeftRoom),this.context.connection.beginListen(Xt.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.beginListen(Xt.UserLeftRoom,this.onOtherUserLeftRoom)}hasState(e){return e?this._states.has(e):!1}isTracking(e,t){if(!e)return;const i=this._states.get(e);if(!i)return;const n=i.controllerStates.find(r=>r.handedness===t);return(n==null?void 0:n.isTracking)||!1}getDeviceType(e,t){if(!e)return;const i=this._states.get(e);if(!i)return;const n=i.controllerStates.find(r=>r.handedness===t);return(n==null?void 0:n.type)||"unknown"}destroy(){this.context.connection.stopListen(Xt.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(Xt.LeftRoom,this.onLeftRoom),this.context.connection.stopListen(Xt.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.stopListen(Xt.UserLeftRoom,this.onOtherUserLeftRoom)}onUpdate(e){if(this.context.connection.isConnected&&this.context.connection.connectionId){const t=this._states.get(this.context.connection.connectionId);t==null||t.update(e)}}onExitXR(e){if(this.context.connection.isConnected&&this.context.connection.connectionId){const t=this._states.get(this.context.connection.connectionId);t==null||t.onExitXR(e)}}}class hz{constructor(){d(this,"_fadeToColorQuad");d(this,"_fadeToColorMaterial");d(this,"_requestedFadeValue",0);d(this,"_transitionPromise",null);d(this,"_transitionResolve",null);this._fadeToColorMaterial=new ni({color:0,transparent:!0,depthTest:!1,fog:!1,side:xi}),this._fadeToColorQuad=new fe(new os(10,10),this._fadeToColorMaterial)}dispose(){this._fadeToColorQuad.geometry.dispose(),this._fadeToColorMaterial.dispose()}update(e,t){const i=this._fadeToColorQuad,n=this._fadeToColorMaterial;i.parent!==e&&n.opacity>0?e.add(i):n.opacity===0&&i.removeFromParent(),i.layers.set(2),i.material=this._fadeToColorMaterial,i.position.z=-1,i.renderOrder=1/0;const r=this._requestedFadeValue;n.opacity=it.lerp(n.opacity,r,t/.03),Math.abs(n.opacity-r)<=.01&&this._transitionResolve&&(this._transitionResolve(),this._transitionResolve=null,this._transitionPromise=null,this._requestedFadeValue=0)}remove(){this._fadeToColorQuad.removeFromParent()}fadeTransition(){if(this._transitionPromise)return this._transitionPromise;this._requestedFadeValue=1;const e=new Promise(t=>{this._transitionResolve=t});return this._transitionPromise=e,e}}var Sp=(s=>(s[s.Quad=0]="Quad",s[s.Cube=1]="Cube",s[s.Sphere=2]="Sphere",s))(Sp||{});class z_{static createPrimitive(e,t){let i;switch(e){case"Quad":case 0:{const r=new os(1,1,1,1),o=(t==null?void 0:t.material)??new Pr({color:16777215});t!=null&&t.texture&&"map"in o&&(o.map=t.texture),i=new fe(r,o)}break;case"Cube":case 1:{const r=new Xi(1,1,1),o=(t==null?void 0:t.material)??new Pr({color:16777215});t!=null&&t.texture&&"map"in o&&(o.map=t.texture),i=new fe(r,o)}break;case"Sphere":case 2:{const r=new Wa(.5,16,16),o=(t==null?void 0:t.material)??new Pr({color:16777215});t!=null&&t.texture&&"map"in o&&(o.map=t.texture),i=new fe(r,o)}break}return this.applyDefaultObjectOptions(i,t),i}static createSprite(e){const i=new g1({color:16777215});e!=null&&e.texture&&"map"in i&&(i.map=e.texture);const n=new F2(i);return this.applyDefaultObjectOptions(n,e),n}static applyDefaultObjectOptions(e,t){t!=null&&t.name&&(e.name=t.name),t!=null&&t.position&&e.position.set(t.position.x,t.position.y,t.position.z),t!=null&&t.rotation&&e.rotation.set(t.rotation.x,t.rotation.y,t.rotation.z),t!=null&&t.scale&&e.scale.set(t.scale.x,t.scale.y,t.scale.z)}}const ck=class{constructor(e,t,i){d(this,"_session");d(this,"_mode");d(this,"_init");d(this,"_renderer");d(this,"_camera");d(this,"_scene");d(this,"onEnd",()=>{var e;(e=this._session)==null||e.removeEventListener("end",this.onEnd),this._renderer.setAnimationLoop(null),this._renderer.dispose(),this._scene.clear()});d(this,"_lastTime",0);d(this,"onFrame",(e,t)=>{const i=e-this._lastTime;this.update(e,i),this._camera.parent!==this._scene&&this._scene.add(this._camera),this._renderer.render(this._scene,this._camera)});d(this,"_objects",[]);this._mode=e,this._init=t,this._session=i,this._session.addEventListener("end",this.onEnd),this._renderer=new Vh({alpha:!0}),this._renderer.setAnimationLoop(this.onFrame),this._renderer.xr.setSession(i),this._renderer.xr.enabled=!0,this._camera=new Gt,this._scene=new rr,this._scene.fog=new m1(4473924,10,250),this._scene.add(this._camera),this.setupScene()}static get active(){return this._active}static async start(e,t){if(this._active)return console.error("Cannot start a new XR session while one is already active"),null;if(this._requestInFlight)return console.error("Cannot start a new XR session while a request is already in flight"),null;if("xr"in navigator&&navigator.xr){if(!t)return console.error("XRSessionInit must be provided"),null;this._requestInFlight=!0;const i=await navigator.xr.requestSession(e,t);return i.addEventListener("end",()=>{this._active=null}),this._requestInFlight?(this._requestInFlight=!1,this._active=new ck(e,t,i),this._active):(i.end(),null)}return null}static async handoff(){return this._active?this._active.handoff():null}static async stop(){this._requestInFlight=!1,this._active&&(await this._active.end(),await wc(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 e={session:this._session,mode:this._mode,init:this._init};return await this.onBeforeHandoff(),this.onEnd(),this._session=null,e}async onBeforeHandoff(){await wc(1e3),this._scene.clear()}setupScene(){this._scene.background=new Ae(0),this._scene.add(new z1(5,10,1118481,1118481));const e=new Ap(16777215,1);e.position.set(0,20,0),e.castShadow=!1,this._scene.add(e);const t=new Ap(16777215,1);t.position.set(0,-1,0),t.castShadow=!1,this._scene.add(t);const i=new vp(16777215,1,100,1);i.position.set(0,2,0),i.castShadow=!1,i.distance=200,this._scene.add(i);const n=50;for(let r=0;r<100;r++){const o=new Pr({color:2236962,metalness:1,roughness:.8});this.isAR&&(o.emissive=new Ae(Math.random(),Math.random(),Math.random()),o.emissiveIntensity=Math.random());const a=it.random(0,1)>.5?Sp.Sphere:Sp.Cube,l=z_.createPrimitive(a,{material:o});l.position.x=it.random(-n,n),l.position.y=it.random(-2,n),l.position.z=it.random(-n,n),l.rotation.x=it.random(0,Math.PI*2),l.rotation.y=it.random(0,Math.PI*2),l.rotation.z=it.random(0,Math.PI*2),l.scale.multiplyScalar(.5+Math.random()*10);const c=l.position.distanceTo(this._camera.position)-l.scale.x;c<1&&l.position.multiplyScalar(1+1/c),this._objects.push(l),this._scene.add(l)}}update(e,t){const i=e*4e-4;for(let n=0;n<this._objects.length;n++){const r=this._objects[n];r.position.y+=Math.sin(i+n*.5)*.005,r.rotateY(.002)}}};let qu=ck;d(qu,"_active",null),d(qu,"_requestInFlight",!1);const Ss=ie("debugwebxr"),mde=ie("stats");function gde(s){let e=null;const t=s;return t.getAROverlayContainer?e=t.getAROverlayContainer():e=s,e}yde();async function yde(){var s;if(ie("debugasap")){let e=globalThis["needle:XRSession"];if(e instanceof Promise){delete globalThis["needle:XRSession"],di.addContextCreatedCallback(async t=>{if(!e)return;cy(!0);const i=await e;if(i){const n=xt.getDefaultSessionInit("immersive-vr");xt.setSession("immersive-vr",i,n,t.context)}else console.error("NeedleXRSession: ASAP session was rejected");e=void 0});return}}if("xr"in navigator){if(/WebXRViewer\//i.test(navigator.userAgent)){console.warn("WebXRViewer does not support addEventListener");return}(s=navigator.xr)==null||s.addEventListener("sessiongranted",async()=>{cy(!0),console.log("Received Session Granted..."),await wc(100);const e=sessionStorage.getItem("needle_xr_session_mode"),t=sessionStorage.getItem("needle_xr_session_init")??null,i=t?JSON.parse(t):null;let n=null;if(U6()&&(await qu.start(e||"immersive-vr",i||xt.getDefaultSessionInit("immersive-vr")),await _de(),n=await qu.handoff()),n)xt.setSession(n.mode,n.session,n.init,Ot.Current);else if(e&&t){console.log("Session Granted: Restore last session");const r=JSON.parse(t);xt.start(e,r).catch(o=>console.warn(o))}else xt.start("immersive-vr").catch(r=>console.warn("Session Granted failed:",r))},{once:!0})}}function vde(s,e){sessionStorage.setItem("needle_xr_session_mode",s),sessionStorage.setItem("needle_xr_session_init",JSON.stringify(e))}function Ade(){sessionStorage.removeItem("needle_xr_session_mode"),sessionStorage.removeItem("needle_xr_session_init")}const VO=new Set;di.registerCallback(Ii.ContextCreationStart,async s=>{VO.add(s.context)});di.registerCallback(Ii.ContextCreated,async s=>{VO.delete(s.context)});function U6(){return VO.size>0}function _de(){return new Promise(s=>{const e=Date.now(),t=setInterval(()=>{(!U6()||Date.now()-e>6e4)&&(clearInterval(t),s())},100)})}_p()&<()&&window.addEventListener("keydown",s=>{(s.key==="x"||s.key==="Escape")&&xt.active&&xt.stop()});const ph=class{constructor(e,t,i,n){d(this,"context");d(this,"session");d(this,"mode");d(this,"controllers",[]);d(this,"_rigScale",1);d(this,"_lastRigScaleUpdate",-1);d(this,"_rigs",[]);d(this,"_viewerHitTestSource",null);d(this,"_defaultRig");d(this,"_xr_scripts");d(this,"_xr_update_scripts",[]);d(this,"_inactive_scripts",[]);d(this,"_controllerAdded");d(this,"_controllerRemoved");d(this,"_originalCameraWorldPosition");d(this,"_originalCameraWorldRotation");d(this,"_originalCameraWorldScale");d(this,"_originalCameraParent");d(this,"_mainCamera",null);d(this,"onRendererSessionSet",()=>{var e;this.running&&(this.context.renderer.xr.enabled=!0,this.context.renderer.xr.updateCamera(this.context.mainCamera),(e=this.context.mainCameraComponent)==null||e.applyClearFlags())});d(this,"onInputSourceAdded",e=>{if(e.targetRayMode==="screen")return;let t=0;for(let n=0;n<this.session.inputSources.length;n++)if(this.session.inputSources[n]===e){t=n;break}if(this.controllers.find(n=>n.inputSource===e)){console.warn("Controller already exists for input source",t);return}Ss&&console.log("Adding controller",t);const i=new DO(this,e,t);this._newControllers.push(i)});d(this,"_ended",!1);d(this,"_newControllers",[]);d(this,"onEnd",e=>{var n,r,o;if(this._ended)return;this._ended=!0,Ss&&console.log("XR Session ended"),Ade(),this.onAfterRender(),this.revertCustomForward(),this._didStart=!1,this._previousCameraParent=null,Md(this.onBefore,$i.LateUpdate);const t=this.context.pre_render_callbacks.indexOf(this.onBeforeRender);t>=0&&this.context.pre_render_callbacks.splice(t,1);const i=this.context.post_render_callbacks.indexOf(this.onAfterRender);i>=0&&this.context.post_render_callbacks.splice(i,1),this.context.xr=null,this.context.renderer.xr.enabled=!1,this.context.pre_update_oneshot_callbacks.push(()=>{var a;(a=this.context.mainCameraComponent)==null||a.applyClearFlags()}),UQ({session:this});for(const a of ph._xrEndListeners)a({xr:this});for(let a=0;a<this.controllers.length;a++)this.disconnectInputSource(this.controllers[a].inputSource);for(const a of this._xr_scripts)(n=a==null?void 0:a.onLeaveXR)==null||n.call(a,{xr:this});(r=this.sync)==null||r.onExitXR(this),this.context.mainCamera&&((o=this._originalCameraParent)==null||o.add(this.context.mainCamera),this._originalCameraWorldPosition&&gs(this.context.mainCamera,this._originalCameraWorldPosition),this._originalCameraWorldRotation&&za(this.context.mainCamera,this._originalCameraWorldRotation),this._originalCameraWorldScale&&ly(this.context.mainCamera,this._originalCameraWorldScale)),this.context.requestSizeUpdate(),this._defaultRig.gameObject.removeFromParent(),cy(!1)});d(this,"_didStart",!1);d(this,"onBefore",e=>{var n,r,o,a,l,c,h,u;const t=e.xrFrame;if(!t)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&&(Ss&&console.warn("Latest rig is not active - trying to activate a different rig",this.rig),this.updateActiveXRRig()),this.rig&&((r=this._mainCamera)!=null&&r.gameObject)&&((a=(o=this._mainCamera)==null?void 0:o.gameObject)==null?void 0:a.parent)!==this.rig.gameObject&&this.rig.gameObject.add((l=this._mainCamera)==null?void 0:l.gameObject),this.internalUpdateState(),this.applyCustomForward();const i={xr:this};if(this._didStart){if(this.context.new_scripts_xr.length>0){const f=[...this.context.new_scripts_xr];for(let p=0;p<f.length;p++){const m=this.context.new_scripts_xr[p];if(!m||m.destroyed||((c=m.supportsXR)==null?void 0:c.call(m,this.mode))==!1){this.context.new_scripts_xr.splice(p,1);continue}if(!m.activeAndEnabled){this.context.new_scripts_xr.splice(p,1),this.markInactive(m);continue}if(this.addScript(m)){this.invokeCallback_EnterXR(m);for(const y of this.controllers)this.invokeCallback_ControllerAdded(m,y)}}}}else{if(this._didStart=!0,this.mode==="immersive-vr"){const p=Sc(this.context.scene.children);if(p){const m=p.getSize(pi());if(m.length()>0){const y=this._defaultRig.gameObject;y.position.set(p.min.x+m.x*.5,p.min.y,p.max.z+m.z*.5+1.5);const g=p.getCenter(pi());g.y=y.position.y,y.lookAt(g)}}}FQ({session:this});for(const p of ph._xrStartListeners)p(i);const f=[...this._xr_scripts];Ss&&console.log("NeedleXRSession start, handle scripts:",f);for(const p of f){if(p.destroyed){this._script_to_remove.push(p);continue}if(!p.activeAndEnabled){this.markInactive(p);continue}this.invokeCallback_EnterXR(p);for(const m of this.controllers)this.invokeCallback_ControllerAdded(p,m)}}this.syncCameraCullingMask();for(const f of this.controllers)f.onUpdate(t);if(this._newControllers.length>0){const f=[...this._newControllers];this._newControllers.length=0;for(const p of f)if(p.connected){this.controllers.push(p);for(const m of this._xr_scripts){if(m.destroyed){this._script_to_remove.push(m);continue}m.activeAndEnabled!==!1&&this.invokeCallback_ControllerAdded(m,p)}}this.controllers.sort((p,m)=>p.index-m.index)}for(const f of this._xr_update_scripts){if(f.destroyed===!0){this._script_to_remove.push(f);continue}if(f.activeAndEnabled===!1){this.markInactive(f);continue}f.onUpdateXR&&f.onUpdateXR(i)}if(this.handleInactiveScripts(),this._script_to_remove.length>0){const f=[...new Set(this._script_to_remove)];this._script_to_remove.length=0;for(const p of f)!p.destroyed&&this.running&&((h=p.onLeaveXR)==null||h.call(p,i)),this.removeScript(p)}(u=this.sync)==null||u.onUpdate(this),this.onRenderDebug()});d(this,"onBeforeRender",()=>{this.context.mainCamera&&this.updateFade(this.context.mainCamera)});d(this,"onAfterRender",()=>{if(this.onUpdateFade_PostRender(),_p()){const e=this.context.renderer;if(e.xr.isPresenting&&this.context.mainCamera){const t=e.xr.enabled,i=e.getRenderTarget();e.xr.enabled=!1,e.setRenderTarget(null),e.render(this.context.scene,this.context.mainCamera),e.xr.enabled=t,e.setRenderTarget(i)}}});d(this,"_script_to_remove",[]);d(this,"_camera");d(this,"_cameraRenderParent",new ve().rotateY(Math.PI));d(this,"_previousCameraParent");d(this,"_customforward",!0);d(this,"originalCameraNearPlane");d(this,"_viewerPose");d(this,"_transformOrientation",new Ce);d(this,"_transformPosition",new w);d(this,"_transition");var r,o;vde(e,n.init),this.session=t,this.mode=e,this.context=i,(Ss||ie("console"))&&cy(!0),this._xr_scripts=[...n.scripts],this._xr_update_scripts=this._xr_scripts.filter(a=>typeof a.onUpdateXR=="function"),this._controllerAdded=n.controller_added,this._controllerRemoved=n.controller_removed,Ed(this.onBefore,$i.LateUpdate),this.context.pre_render_callbacks.push(this.onBeforeRender),this.context.post_render_callbacks.push(this.onAfterRender),((r=n.init.optionalFeatures)!=null&&r.includes("hit-test")||(o=n.init.requiredFeatures)!=null&&o.includes("hit-test"))&&t.requestReferenceSpace("viewer").then(a=>{var l,c;return(c=(l=t.requestHitTestSource)==null?void 0:l.call(t,{space:a}))==null?void 0:c.then(h=>this._viewerHitTestSource=h)}).catch(a=>console.warn(a)),this.context.mainCamera&&(this._originalCameraWorldPosition=kt(this.context.mainCamera,new w),this._originalCameraWorldRotation=Ri(this.context.mainCamera,new Ce),this._originalCameraWorldScale=Ki(this.context.mainCamera,new w),this._originalCameraParent=this.context.mainCamera.parent),this._defaultRig=new wue,this.context.scene.add(this._defaultRig.gameObject),this.addRig(this._defaultRig);for(let a=0;a<t.inputSources.length;a++){const l=t.inputSources[a];if(!l.handedness){console.warn("Input source in xr session has no handedness - ignoring",a);continue}this.onInputSourceAdded(l)}this.session.addEventListener("end",this.onEnd),this.session.addEventListener("inputsourceschange",a=>{for(const l of a.removed)this.disconnectInputSource(l);for(const l of a.added)this.onInputSourceAdded(l)}),this.context.xr=this,this.context.renderer.xr.setSession(this.session).then(this.onRendererSessionSet)}static getXRSync(e){return this._sync||(this._sync=new F6(e)),this._sync}static get currentSessionRequest(){return this._currentSessionRequestMode}static get active(){return this._activeSession}static get activeMode(){var e;return((e=this._activeSession)==null?void 0:e.mode)??null}static get xrSystem(){return"xr"in navigator?navigator.xr:void 0}static isXRSupported(){return Promise.all([this.isVRSupported(),this.isARSupported()]).then(e=>e.some(t=>t)).catch(()=>!1)}static isVRSupported(){return this.isSessionSupported("immersive-vr")}static isARSupported(){return this.isSessionSupported("immersive-ar")}static isSessionSupported(e){var t;return((t=this.xrSystem)==null?void 0:t.isSessionSupported(e).catch(i=>(Ss&&console.error(i),!1)))??Promise.resolve(!1)}static onSessionRequestStart(e){this._sessionRequestStartListeners.push(e)}static offSessionRequestStart(e){const t=this._sessionRequestStartListeners.indexOf(e);t>=0&&this._sessionRequestStartListeners.splice(t,1)}static onSessionRequestEnd(e){this._sessionRequestEndListeners.push(e)}static offSessionRequestEnd(e){const t=this._sessionRequestEndListeners.indexOf(e);t>=0&&this._sessionRequestEndListeners.splice(t,1)}static onXRSessionStart(e){this._xrStartListeners.push(e)}static offXRSessionStart(e){const t=this._xrStartListeners.indexOf(e);t>=0&&this._xrStartListeners.splice(t,1)}static onXRSessionEnd(e){this._xrEndListeners.push(e)}static offXRSessionEnd(e){const t=this._xrEndListeners.indexOf(e);t>=0&&this._xrEndListeners.splice(t,1)}static onControllerAdded(e){this._controllerAddedListeners.push(e)}static offControllerAdded(e){const t=this._controllerAddedListeners.indexOf(e);t>=0&&this._controllerAddedListeners.splice(t,1)}static onControllerRemoved(e){this._controllerRemovedListeners.push(e)}static offControllerRemoved(e){const t=this._controllerRemovedListeners.indexOf(e);t>=0&&this._controllerRemovedListeners.splice(t,1)}static offerSession(e,t,i){return"xr"in navigator&&navigator.xr&&"offerSession"in navigator.xr?(typeof navigator.xr.offerSession=="function"&&(console.log("WebXR offerSession is available - requesting mode: "+e),t=="default"&&(t=this.getDefaultSessionInit(e)),navigator.xr.offerSession(e,{...t}).then(n=>ph.setSession(e,n,t,i)).catch(n=>{console.log("XRSession offer rejected (perhaps because another call to offerSession was made or a call to requestSession was made)")})),!0):!1}static getDefaultSessionInit(e){switch(e){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",e),{}}}static async start(e,t,i){var o,a,l,c;if(lt()&&ie("debugxrpreroom"))return console.warn("Debug: Starting temporary XR session"),await qu.start(e,t||ph.getDefaultSessionInit(e)),null;if(this._currentSessionRequest)return console.warn("A XRSession is already being requested"),(Ss||lt())&&Ni("A XRSession is already being requested"),this._currentSessionRequest.then(()=>this._activeSession);if(this._activeSession)return console.error("A XRSession is already running"),this._activeSession;if(i||(i=Ot.Current),i||(i=di.All[0]),!i)throw new Error("No Needle Engine Context found");switch(t||(t={}),e){case"immersive-ar":{if(await((o=this.xrSystem)==null?void 0:o.isSessionSupported("immersive-ar"))!==!0)return console.error(e+" is not supported by this browser."),null;const u=this.getDefaultSessionInit(e),f=gde(i.domElement);f&&!H1()&&(u.domOverlay={root:f},u.optionalFeatures.push("dom-overlay")),t={...u,...t}}break;case"immersive-vr":{if(await((a=this.xrSystem)==null?void 0:a.isSessionSupported("immersive-vr"))!==!0)return console.error(e+" is not supported by this browser."),null;t={...this.getDefaultSessionInit(e),...t}}break;default:console.warn("No default session init for mode",e);break}t.optionalFeatures??(t.optionalFeatures=[]),t.requiredFeatures??(t.requiredFeatures=[]),await qu.stop();const n=e=="immersive-ar"?i.scripts_immersive_ar:i.scripts_immersive_vr;Ss?console.log(`%cRequesting ${e} session`,"font-weight:bold;",t,n):console.log(`%cRequesting ${e} session`,"font-weight:bold;");for(const h of n)h.onBeforeXR&&h.onBeforeXR(e,t);for(const h of this._sessionRequestStartListeners)h({mode:e,init:t});Ss&&pn("Requesting "+e+" session ("+Date.now()+")"),this._currentSessionRequest=(l=navigator.xr)==null?void 0:l.requestSession(e,t),this._currentSessionRequestMode=e;const r=await((c=this._currentSessionRequest)==null?void 0:c.catch(h=>{console.error(h,"Code: "+h.code),h.code===9&&Ni("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:"&&Ni("XR requires a secure connection (HTTPS)")}));this._currentSessionRequest=void 0,this._currentSessionRequestMode=null;for(const h of this._sessionRequestEndListeners)h({mode:e,init:t,newSession:r||null});return r?this.setSession(e,r,t,i):(console.warn("XR Session request was rejected"),null)}static setSession(e,t,i,n){if(this._activeSession)return console.error("A XRSession is already running"),this._activeSession;const r=e=="immersive-ar"?n.scripts_immersive_ar:n.scripts_immersive_vr;return this._activeSession=new ph(e,t,n,{scripts:r,controller_added:this._controllerAddedListeners,controller_removed:this._controllerRemovedListeners,init:i}),t.addEventListener("end",this.onEnd),Ss?console.log(`%cStarted ${e} session`,"font-weight:bold;",r):console.log(`%cStarted ${e} session`,"font-weight:bold;"),this._activeSession}static stop(){var e;(e=this._activeSession)==null||e.end()}get sync(){return ph._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(e=>e.isLeft)}get rightController(){return this.controllers.find(e=>e.isRight)}getController(e){return typeof e=="number"?this.controllers[e]||null:this.controllers.find(t=>t.side===e)||null}get isPassThrough(){return!!(this.environmentBlendMode!=="opaque"&&this.interactionMode==="world-space"||this.mode==="immersive-ar"&&this.environmentBlendMode!=="opaque"&&this.controllers.some(e=>e.inputSource.targetRayMode==="tracked-pointer")||lt()&&_p()&&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 e=this.frame.getImageTrackingResults();for(const t of e)if(t.trackingState==="tracked")return!0}catch{return!1}return!1}get rig(){const e=this._rigs[0]??null;return e!=null&&e.gameObject&&Cp(e.gameObject)||(e==null?void 0:e.isActive)===!1?(this.updateActiveXRRig(),this._rigs[0]??null):e}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(e){this._rigs.indexOf(e)>=0||(e.priority===void 0&&(e.priority=0),this._rigs.push(e),this.updateActiveXRRig())}removeRig(e){const t=this._rigs.indexOf(e);t!==-1&&(this._rigs.splice(t,1),this.updateActiveXRRig())}setRigActive(e){const t=this._rigs.indexOf(e);this._rigs.splice(t,1),this._rigs.unshift(e),this.updateActiveXRRig()}updateActiveXRRig(){const e=this._rigs[0]??null;this._defaultRig.gameObject.parent!==this.context.scene&&this.context.scene.add(this._defaultRig.gameObject),this._defaultRig.gameObject.visible=!0,this._rigs.includes(this._defaultRig)||this._rigs.push(this._defaultRig);let t=this._rigs[0];t&&t.priority===void 0&&(t.priority=0);for(let i=1;i<this._rigs.length;i++){const n=this._rigs[i];if(n.isActive){if(Cp(n.gameObject)){this._rigs.splice(i,1),i--;continue}(!t||t.isActive===!1||n.priority!==void 0&&n.priority>t.priority)&&(t=n)}}if(e!==t){const i=this._rigs.indexOf(t);i>=0&&this._rigs.splice(i,1),this._rigs.unshift(t)}Ss&&(e===t?console.log("Updated Active XR Rig:",t,"prev:",e):console.log("Updated Active XRRig:",t," (the same as before)"))}getHitTest(e){if(e)return this.getControllerHitTest(e);if(!this._viewerHitTestSource)return null;const t=this._viewerHitTestSource,i=this.frame.getHitTestResults(t);if(i.length>0){const n=i[0];return this.convertHitTestResult(n)}return null}getControllerHitTest(e){const t=e.hitTestSource;if(!t)return null;const i=this.frame.getHitTestResultsForTransientInput(t);for(const n of i)if(n.inputSource===e.inputSource)for(const r of n.results)return this.convertHitTestResult(r);return null}convertHitTestResult(e){const t=this.context.renderer.xr.getReferenceSpace(),i=t&&e.getPose(t);if(i){const n=pi(i.transform.position),r=Nf(i.transform.orientation),o=this.context.mainCamera;if((o==null?void 0:o.parent)!==this._cameraRenderParent&&n.applyMatrix4(EC),o!=null&&o.parent){n.applyMatrix4(o.parent.matrixWorld),r.multiply(Ca);const a=Ri(o.parent);a.premultiply(Ca),r.premultiply(a)}return{hit:e,position:n,quaternion:r}}return null}convertSpace(e){const t=pi(e.position);t.applyMatrix4(EC);const i=Nf(e.orientation);return i.premultiply(Ca),{position:t,quaternion:i}}disconnectInputSource(e){const t=(i,n,r)=>{if(i.inputSource===e){Ss&&console.log("Disconnecting controller",i.index),this.controllers.splice(r,1),this.invokeControllerEvent(i,this._controllerRemoved,"removed");const o={xr:this,controller:i,change:"removed"};for(const a of this._xr_scripts)a.onXRControllerRemoved&&a.onXRControllerRemoved(o);i.onDisconnected()}};for(let i=this.controllers.length-1;i>=0;i--){const n=this.controllers[i];t(n,this.controllers,i)}for(let i=this._newControllers.length-1;i>=0;i--){const n=this._newControllers[i];t(n,this._newControllers,i)}}end(){this._ended||this.session.end().catch(e=>console.warn(e))}onRenderDebug(){if(Ss)for(const e of this.controllers)e.onRenderDebug();if((Ss||mde)&&this.rig){const e=this.rig.gameObject.worldPosition,t=this.rig.gameObject.worldForward;e.add(t.multiplyScalar(1.5));const i=this.rig.gameObject.worldUp;e.add(i.multiplyScalar(2.5));let n="";if(n+=this.context.time.smoothedFps.toFixed(1),Ss)for(const r of this.controllers)n+=`
|
|
5236
5236
|
${r.hand?"hand":"ctrl"} ${r.inputSource.handedness}[${r.index}] con:${r.connected} tr:${r.isTracking}`;_t.DrawLabel(e,n)}}addScript(e){return this._xr_scripts.includes(e)?!1:(Ss&&console.log("Register new XRScript",e),this._xr_scripts.push(e),typeof e.onUpdateXR=="function"&&this._xr_update_scripts.push(e),!0)}markInactive(e){if(!(this._inactive_scripts.indexOf(e)>=0)){this.removeScript(e,!1),this._inactive_scripts.push(e);for(const t of this.controllers)this.invokeCallback_ControllerRemoved(e,t);this.invokeCallback_LeaveXR(e)}}handleInactiveScripts(){if(this._inactive_scripts.length>0)for(let e=this._inactive_scripts.length-1;e>=0;e--){const t=this._inactive_scripts[e];if(t.activeAndEnabled){this._inactive_scripts.splice(e,1),this.addScript(t),this.invokeCallback_EnterXR(t);for(const i of this.controllers)this.invokeCallback_ControllerAdded(t,i)}}}removeScript(e,t=!0){Ss&&console.log("Remove XRScript",e);const i=this._xr_scripts.indexOf(e);i>=0&&this._xr_scripts.splice(i,1);const n=this._xr_update_scripts.indexOf(e);if(n>=0&&this._xr_update_scripts.splice(n,1),t){const r=this._inactive_scripts.indexOf(e);r>=0&&this._inactive_scripts.splice(r,1)}}invokeCallback_EnterXR(e){e.onEnterXR&&e.onEnterXR({xr:this})}invokeCallback_ControllerAdded(e,t){e.onXRControllerAdded&&e.onXRControllerAdded({xr:this,controller:t,change:"added"})}invokeCallback_ControllerRemoved(e,t){e.onXRControllerRemoved&&e.onXRControllerRemoved({xr:this,controller:t,change:"removed"})}invokeCallback_LeaveXR(e){e.onLeaveXR&&!e.destroyed&&e.onLeaveXR({xr:this})}syncCameraCullingMask(){var i;const e=this.context.xrCamera,t=(i=this.context.mainCameraComponent)==null?void 0:i.cullingMask;if(e&&t!==void 0){for(const n of e.cameras)n.layers.mask=t;e.layers.mask=t}else if(e){for(const n of e.cameras)n.layers.enableAll();e.layers.enableAll()}}invokeControllerEvent(e,t,i){for(let n=t.length-1;n>=0;n--){const r=t[n];if(r)try{r({xr:this,controller:e,change:i})}catch(o){console.error(o)}}}applyCustomForward(){var e;if(this.context.mainCamera&&this._customforward){this._camera=this.context.mainCamera,this._camera.parent!==this._cameraRenderParent&&(this._previousCameraParent=this._camera.parent,(e=this._previousCameraParent)==null||e.add(this._cameraRenderParent)),this._cameraRenderParent.name="XR Camera Render Parent",this._cameraRenderParent.add(this._camera);let t=.02;if(this.rig){const i=Ki(this.rig.gameObject);t*=i.x}this._camera instanceof Gt&&this._camera.near>t&&(this.originalCameraNearPlane=this._camera.near,this._camera.near=t)}}revertCustomForward(){this._camera&&this._previousCameraParent&&this._previousCameraParent.add(this._camera),this._previousCameraParent=null,this._camera instanceof Gt&&this.originalCameraNearPlane!=null&&(this._camera.near=this.originalCameraNearPlane)}internalUpdateState(){const e=this.context.renderer.xr.getReferenceSpace();if(!e){this._viewerPose=void 0;return}if(this._viewerPose=this.frame.getViewerPose(e),this._viewerPose){const t=this._viewerPose.transform;this._transformPosition.set(t.position.x,t.position.y,t.position.z),this._transformOrientation.set(t.orientation.x,t.orientation.y,t.orientation.z,t.orientation.w)}}get transition(){return this._transition||(this._transition=new hz),this._transition}fadeTransition(){return this._transition||(this._transition=new hz),this._transition.fadeTransition()}updateFade(e){this._transition&&e instanceof Gt&&this._transition.update(e,this.context.time.deltaTime)}onUpdateFade_PostRender(){var e;(e=this._transition)==null||e.remove()}};let xt=ph;d(xt,"_sync",null),d(xt,"_currentSessionRequestMode",null),d(xt,"_currentSessionRequest"),d(xt,"_activeSession"),d(xt,"_sessionRequestStartListeners",[]),d(xt,"_sessionRequestEndListeners",[]),d(xt,"_xrStartListeners",[]),d(xt,"_xrEndListeners",[]),d(xt,"_controllerAddedListeners",[]),d(xt,"_controllerRemovedListeners",[]),d(xt,"onEnd",()=>{Ss&&console.log("XR Session ended"),ph._activeSession=null});const TI=ie("debugwebxr");class N6{static tryFindAvatarObjects(e,t,i){if(i.head&&i.leftHand&&i.rightHand)return;const n=e.name.toLocaleLowerCase();!i.head&&n.includes("head")&&(TI&&console.log("FOUND AVATAR HEAD",e.name),i.head=new Zt("",t,e)),n.includes("hand")&&(!i.leftHand&&n.includes("left")&&(TI&&console.log("FOUND AVATAR LEFT HAND",e.name),i.leftHand=new Zt("",t,e)),!i.rightHand&&n.includes("right")&&(TI&&console.log("FOUND AVATAR RIGHT HAND",e.name),i.rightHand=new Zt("",t,e)));for(let r=0;r<e.children.length;r++){if(i.head&&i.leftHand&&i.rightHand)return;const o=e.children[r];this.tryFindAvatarObjects(o,t,i)}}}var IC=(s=>(s.Visible="application-visible",s.Hidden="application-hidden",s.MuteChanged="application-mutechanged",s))(IC||{});let RC=!1;const Rg=[];function ky(){if(RC)return;lt()&&console.debug("User interaction registered: audio can now be played"),RC=!0;const s=[...Rg];Rg.length=0,s.forEach(e=>e())}document.addEventListener("pointerdown",ky);document.addEventListener("click",ky);document.addEventListener("dragstart",ky);document.addEventListener("touchstart",ky);document.addEventListener("keydown",ky);xt.onXRSessionStart(()=>{ky()});const hk=class extends EventTarget{constructor(t){super();d(this,"_mute",!1);d(this,"context");d(this,"_isVisible",!0);this.context=t,window.addEventListener("visibilitychange",this.onVisiblityChanged.bind(this),!1)}static get userInteractionRegistered(){return RC}static registerWaitForInteraction(t){if(t!==null){if(RC){t();return}Rg.indexOf(t)===-1&&Rg.push(t)}}static unregisterWaitForInteraction(t){const i=Rg.indexOf(t);i!==-1&&Rg.splice(i,1)}get muted(){return this._mute}set muted(t){t!==this._mute&&(this._mute=t,this.dispatchEvent(new Event("application-mutechanged")))}get hasFocus(){return document.hasFocus()}get isVisible(){return this._isVisible}onVisiblityChanged(t){switch(t.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 vc=hk;d(vc,"registerWaitForAllowAudio",hk.registerWaitForInteraction);function*z6(s,e=null){const t=e?e.time:Ot.Current.time,i=t.time;for(;t.time-i<s;)yield}function*bde(s){for(let e=0;e<s;e++)yield}function*G6(s){let e=!0;for(s.then(()=>e=!1),s.catch(()=>e=!1);e;)yield}class W0 extends $2{constructor(e){super(e),this.type=ms}parse(e){const R=Math.pow(2.7182818,2.2);function C(B,N){let Z=0;for(let G=0;G<65536;++G)(G==0||B[G>>3]&1<<(G&7))&&(N[Z++]=G);const P=Z-1;for(;Z<65536;)N[Z++]=0;return P}function I(B){for(let N=0;N<16384;N++)B[N]={},B[N].len=0,B[N].lit=0,B[N].p=null}const F={l:0,c:0,lc:0};function U(B,N,Z,P,G){for(;Z<B;)N=N<<8|Xe(P,G),Z+=8;Z-=B,F.l=N>>Z&(1<<B)-1,F.c=N,F.lc=Z}const O=new Array(59);function Q(B){for(let Z=0;Z<=58;++Z)O[Z]=0;for(let Z=0;Z<65537;++Z)O[B[Z]]+=1;let N=0;for(let Z=58;Z>0;--Z){const P=N+O[Z]>>1;O[Z]=N,N=P}for(let Z=0;Z<65537;++Z){const P=B[Z];P>0&&(B[Z]=P|O[P]++<<6)}}function D(B,N,Z,P,G,V){const Y=N;let K=0,pe=0;for(;P<=G;P++){if(Y.value-N.value>Z)return!1;U(6,K,pe,B,Y);const he=F.l;if(K=F.c,pe=F.lc,V[P]=he,he==63){if(Y.value-N.value>Z)throw new Error("Something wrong with hufUnpackEncTable");U(8,K,pe,B,Y);let be=F.l+6;if(K=F.c,pe=F.lc,P+be>G+1)throw new Error("Something wrong with hufUnpackEncTable");for(;be--;)V[P++]=0;P--}else if(he>=59){let be=he-59+2;if(P+be>G+1)throw new Error("Something wrong with hufUnpackEncTable");for(;be--;)V[P++]=0;P--}}Q(V)}function k(B){return B&63}function z(B){return B>>6}function q(B,N,Z,P){for(;N<=Z;N++){const G=z(B[N]),V=k(B[N]);if(G>>V)throw new Error("Invalid table entry");if(V>14){const Y=P[G>>V-14];if(Y.len)throw new Error("Invalid table entry");if(Y.lit++,Y.p){const K=Y.p;Y.p=new Array(Y.lit);for(let pe=0;pe<Y.lit-1;++pe)Y.p[pe]=K[pe]}else Y.p=new Array(1);Y.p[Y.lit-1]=N}else if(V){let Y=0;for(let K=1<<14-V;K>0;K--){const pe=P[(G<<14-V)+Y];if(pe.len||pe.p)throw new Error("Invalid table entry");pe.len=V,pe.lit=N,Y++}}}return!0}const X={c:0,lc:0};function se(B,N,Z,P){B=B<<8|Xe(Z,P),N+=8,X.c=B,X.lc=N}const le={c:0,lc:0};function Me(B,N,Z,P,G,V,Y,K,pe){if(B==N){P<8&&(se(Z,P,G,V),Z=X.c,P=X.lc),P-=8;let he=Z>>P;if(he=new Uint8Array([he])[0],K.value+he>pe)return!1;const be=Y[K.value-1];for(;he-- >0;)Y[K.value++]=be}else if(K.value<pe)Y[K.value++]=B;else return!1;le.c=Z,le.lc=P}function ne(B){return B&65535}function ge(B){const N=ne(B);return N>32767?N-65536:N}const Se={a:0,b:0};function Le(B,N){const Z=ge(B),G=ge(N),V=Z+(G&1)+(G>>1),Y=V,K=V-G;Se.a=Y,Se.b=K}function We(B,N){const Z=ne(B),P=ne(N),G=Z-(P>>1)&65535,V=P+G-32768&65535;Se.a=V,Se.b=G}function Ve(B,N,Z,P,G,V,Y){const K=Y<16384,pe=Z>G?G:Z;let he=1,be,Be;for(;he<=pe;)he<<=1;for(he>>=1,be=he,he>>=1;he>=1;){Be=0;const Oe=Be+V*(G-be),je=V*he,Je=V*be,et=P*he,ht=P*be;let Mt,_i,Qt,Pt;for(;Be<=Oe;Be+=Je){let Oi=Be;const Ct=Be+P*(Z-be);for(;Oi<=Ct;Oi+=ht){const Hi=Oi+et,Gr=Oi+je,an=Gr+et;K?(Le(B[Oi+N],B[Gr+N]),Mt=Se.a,Qt=Se.b,Le(B[Hi+N],B[an+N]),_i=Se.a,Pt=Se.b,Le(Mt,_i),B[Oi+N]=Se.a,B[Hi+N]=Se.b,Le(Qt,Pt),B[Gr+N]=Se.a,B[an+N]=Se.b):(We(B[Oi+N],B[Gr+N]),Mt=Se.a,Qt=Se.b,We(B[Hi+N],B[an+N]),_i=Se.a,Pt=Se.b,We(Mt,_i),B[Oi+N]=Se.a,B[Hi+N]=Se.b,We(Qt,Pt),B[Gr+N]=Se.a,B[an+N]=Se.b)}if(Z&he){const Hi=Oi+je;K?Le(B[Oi+N],B[Hi+N]):We(B[Oi+N],B[Hi+N]),Mt=Se.a,B[Hi+N]=Se.b,B[Oi+N]=Mt}}if(G&he){let Oi=Be;const Ct=Be+P*(Z-be);for(;Oi<=Ct;Oi+=ht){const Hi=Oi+et;K?Le(B[Oi+N],B[Hi+N]):We(B[Oi+N],B[Hi+N]),Mt=Se.a,B[Hi+N]=Se.b,B[Oi+N]=Mt}}be=he,he>>=1}return Be}function gt(B,N,Z,P,G,V,Y,K,pe){let he=0,be=0;const Be=Y,Oe=Math.trunc(P.value+(G+7)/8);for(;P.value<Oe;)for(se(he,be,Z,P),he=X.c,be=X.lc;be>=14;){const Je=he>>be-14&16383,et=N[Je];if(et.len)be-=et.len,Me(et.lit,V,he,be,Z,P,K,pe,Be),he=le.c,be=le.lc;else{if(!et.p)throw new Error("hufDecode issues");let ht;for(ht=0;ht<et.lit;ht++){const Mt=k(B[et.p[ht]]);for(;be<Mt&&P.value<Oe;)se(he,be,Z,P),he=X.c,be=X.lc;if(be>=Mt&&z(B[et.p[ht]])==(he>>be-Mt&(1<<Mt)-1)){be-=Mt,Me(et.p[ht],V,he,be,Z,P,K,pe,Be),he=le.c,be=le.lc;break}}if(ht==et.lit)throw new Error("hufDecode issues")}}const je=8-G&7;for(he>>=je,be-=je;be>0;){const Je=N[he<<14-be&16383];if(Je.len)be-=Je.len,Me(Je.lit,V,he,be,Z,P,K,pe,Be),he=le.c,be=le.lc;else throw new Error("hufDecode issues")}return!0}function st(B,N,Z,P,G,V){const Y={value:0},K=Z.value,pe=ft(N,Z),he=ft(N,Z);Z.value+=4;const be=ft(N,Z);if(Z.value+=4,pe<0||pe>=65537||he<0||he>=65537)throw new Error("Something wrong with HUF_ENCSIZE");const Be=new Array(65537),Oe=new Array(16384);I(Oe);const je=P-(Z.value-K);if(D(B,Z,je,pe,he,Be),be>8*(P-(Z.value-K)))throw new Error("Something wrong with hufUncompress");q(Be,pe,he,Oe),gt(Be,Oe,B,Z,be,he,V,G,Y)}function W(B,N,Z){for(let P=0;P<Z;++P)N[P]=B[N[P]]}function Ge(B){for(let N=1;N<B.length;N++){const Z=B[N-1]+B[N]-128;B[N]=Z}}function xe(B,N){let Z=0,P=Math.floor((B.length+1)/2),G=0;const V=B.length-1;for(;!(G>V||(N[G++]=B[Z++],G>V));)N[G++]=B[P++]}function Ne(B){let N=B.byteLength;const Z=new Array;let P=0;const G=new DataView(B);for(;N>0;){const V=G.getInt8(P++);if(V<0){const Y=-V;N-=Y+1;for(let K=0;K<Y;K++)Z.push(G.getUint8(P++))}else{const Y=V;N-=2;const K=G.getUint8(P++);for(let pe=0;pe<Y+1;pe++)Z.push(K)}}return Z}function Ee(B,N,Z,P,G,V){let Y=new DataView(V.buffer);const K=Z[B.idx[0]].width,pe=Z[B.idx[0]].height,he=3,be=Math.floor(K/8),Be=Math.ceil(K/8),Oe=Math.ceil(pe/8),je=K-(Be-1)*8,Je=pe-(Oe-1)*8,et={value:0},ht=new Array(he),Mt=new Array(he),_i=new Array(he),Qt=new Array(he),Pt=new Array(he);for(let Ct=0;Ct<he;++Ct)Pt[Ct]=N[B.idx[Ct]],ht[Ct]=Ct<1?0:ht[Ct-1]+Be*Oe,Mt[Ct]=new Float32Array(64),_i[Ct]=new Uint16Array(64),Qt[Ct]=new Uint16Array(Be*64);for(let Ct=0;Ct<Oe;++Ct){let Hi=8;Ct==Oe-1&&(Hi=Je);let Gr=8;for(let vi=0;vi<Be;++vi){vi==Be-1&&(Gr=je);for(let Wt=0;Wt<he;++Wt)_i[Wt].fill(0),_i[Wt][0]=G[ht[Wt]++],tt(et,P,_i[Wt]),$e(_i[Wt],Mt[Wt]),at(Mt[Wt]);Ft(Mt);for(let Wt=0;Wt<he;++Wt)H(Mt[Wt],Qt[Wt],vi*64)}let an=0;for(let vi=0;vi<he;++vi){const Wt=Z[B.idx[vi]].type;for(let zs=8*Ct;zs<8*Ct+Hi;++zs){an=Pt[vi][zs];for(let zc=0;zc<be;++zc){const _n=zc*64+(zs&7)*8;Y.setUint16(an+0*2*Wt,Qt[vi][_n+0],!0),Y.setUint16(an+1*2*Wt,Qt[vi][_n+1],!0),Y.setUint16(an+2*2*Wt,Qt[vi][_n+2],!0),Y.setUint16(an+3*2*Wt,Qt[vi][_n+3],!0),Y.setUint16(an+4*2*Wt,Qt[vi][_n+4],!0),Y.setUint16(an+5*2*Wt,Qt[vi][_n+5],!0),Y.setUint16(an+6*2*Wt,Qt[vi][_n+6],!0),Y.setUint16(an+7*2*Wt,Qt[vi][_n+7],!0),an+=8*2*Wt}}if(be!=Be)for(let zs=8*Ct;zs<8*Ct+Hi;++zs){const zc=Pt[vi][zs]+8*be*2*Wt,_n=be*64+(zs&7)*8;for(let tu=0;tu<Gr;++tu)Y.setUint16(zc+tu*2*Wt,Qt[vi][_n+tu],!0)}}}const Oi=new Uint16Array(K);Y=new DataView(V.buffer);for(let Ct=0;Ct<he;++Ct){Z[B.idx[Ct]].decoded=!0;const Hi=Z[B.idx[Ct]].type;if(Z[Ct].type==2)for(let Gr=0;Gr<pe;++Gr){const an=Pt[Ct][Gr];for(let vi=0;vi<K;++vi)Oi[vi]=Y.getUint16(an+vi*2*Hi,!0);for(let vi=0;vi<K;++vi)Y.setFloat32(an+vi*2*Hi,ae(Oi[vi]),!0)}}}function tt(B,N,Z){let P,G=1;for(;G<64;)P=N[B.value],P==65280?G=64:P>>8==255?G+=P&255:(Z[G]=P,G++),B.value++}function $e(B,N){N[0]=ae(B[0]),N[1]=ae(B[1]),N[2]=ae(B[5]),N[3]=ae(B[6]),N[4]=ae(B[14]),N[5]=ae(B[15]),N[6]=ae(B[27]),N[7]=ae(B[28]),N[8]=ae(B[2]),N[9]=ae(B[4]),N[10]=ae(B[7]),N[11]=ae(B[13]),N[12]=ae(B[16]),N[13]=ae(B[26]),N[14]=ae(B[29]),N[15]=ae(B[42]),N[16]=ae(B[3]),N[17]=ae(B[8]),N[18]=ae(B[12]),N[19]=ae(B[17]),N[20]=ae(B[25]),N[21]=ae(B[30]),N[22]=ae(B[41]),N[23]=ae(B[43]),N[24]=ae(B[9]),N[25]=ae(B[11]),N[26]=ae(B[18]),N[27]=ae(B[24]),N[28]=ae(B[31]),N[29]=ae(B[40]),N[30]=ae(B[44]),N[31]=ae(B[53]),N[32]=ae(B[10]),N[33]=ae(B[19]),N[34]=ae(B[23]),N[35]=ae(B[32]),N[36]=ae(B[39]),N[37]=ae(B[45]),N[38]=ae(B[52]),N[39]=ae(B[54]),N[40]=ae(B[20]),N[41]=ae(B[22]),N[42]=ae(B[33]),N[43]=ae(B[38]),N[44]=ae(B[46]),N[45]=ae(B[51]),N[46]=ae(B[55]),N[47]=ae(B[60]),N[48]=ae(B[21]),N[49]=ae(B[34]),N[50]=ae(B[37]),N[51]=ae(B[47]),N[52]=ae(B[50]),N[53]=ae(B[56]),N[54]=ae(B[59]),N[55]=ae(B[61]),N[56]=ae(B[35]),N[57]=ae(B[36]),N[58]=ae(B[48]),N[59]=ae(B[49]),N[60]=ae(B[57]),N[61]=ae(B[58]),N[62]=ae(B[62]),N[63]=ae(B[63])}function at(B){const N=.5*Math.cos(.7853975),Z=.5*Math.cos(3.14159/16),P=.5*Math.cos(3.14159/8),G=.5*Math.cos(3*3.14159/16),V=.5*Math.cos(5*3.14159/16),Y=.5*Math.cos(3*3.14159/8),K=.5*Math.cos(7*3.14159/16),pe=new Array(4),he=new Array(4),be=new Array(4),Be=new Array(4);for(let Oe=0;Oe<8;++Oe){const je=Oe*8;pe[0]=P*B[je+2],pe[1]=Y*B[je+2],pe[2]=P*B[je+6],pe[3]=Y*B[je+6],he[0]=Z*B[je+1]+G*B[je+3]+V*B[je+5]+K*B[je+7],he[1]=G*B[je+1]-K*B[je+3]-Z*B[je+5]-V*B[je+7],he[2]=V*B[je+1]-Z*B[je+3]+K*B[je+5]+G*B[je+7],he[3]=K*B[je+1]-V*B[je+3]+G*B[je+5]-Z*B[je+7],be[0]=N*(B[je+0]+B[je+4]),be[3]=N*(B[je+0]-B[je+4]),be[1]=pe[0]+pe[3],be[2]=pe[1]-pe[2],Be[0]=be[0]+be[1],Be[1]=be[3]+be[2],Be[2]=be[3]-be[2],Be[3]=be[0]-be[1],B[je+0]=Be[0]+he[0],B[je+1]=Be[1]+he[1],B[je+2]=Be[2]+he[2],B[je+3]=Be[3]+he[3],B[je+4]=Be[3]-he[3],B[je+5]=Be[2]-he[2],B[je+6]=Be[1]-he[1],B[je+7]=Be[0]-he[0]}for(let Oe=0;Oe<8;++Oe)pe[0]=P*B[16+Oe],pe[1]=Y*B[16+Oe],pe[2]=P*B[48+Oe],pe[3]=Y*B[48+Oe],he[0]=Z*B[8+Oe]+G*B[24+Oe]+V*B[40+Oe]+K*B[56+Oe],he[1]=G*B[8+Oe]-K*B[24+Oe]-Z*B[40+Oe]-V*B[56+Oe],he[2]=V*B[8+Oe]-Z*B[24+Oe]+K*B[40+Oe]+G*B[56+Oe],he[3]=K*B[8+Oe]-V*B[24+Oe]+G*B[40+Oe]-Z*B[56+Oe],be[0]=N*(B[Oe]+B[32+Oe]),be[3]=N*(B[Oe]-B[32+Oe]),be[1]=pe[0]+pe[3],be[2]=pe[1]-pe[2],Be[0]=be[0]+be[1],Be[1]=be[3]+be[2],Be[2]=be[3]-be[2],Be[3]=be[0]-be[1],B[0+Oe]=Be[0]+he[0],B[8+Oe]=Be[1]+he[1],B[16+Oe]=Be[2]+he[2],B[24+Oe]=Be[3]+he[3],B[32+Oe]=Be[3]-he[3],B[40+Oe]=Be[2]-he[2],B[48+Oe]=Be[1]-he[1],B[56+Oe]=Be[0]-he[0]}function Ft(B){for(let N=0;N<64;++N){const Z=B[0][N],P=B[1][N],G=B[2][N];B[0][N]=Z+1.5747*G,B[1][N]=Z-.1873*P-.4682*G,B[2][N]=Z+1.8556*P}}function H(B,N,Z){for(let P=0;P<64;++P)N[Z+P]=Ff.toHalfFloat(L(B[P]))}function L(B){return B<=1?Math.sign(B)*Math.pow(Math.abs(B),2.2):Math.sign(B)*Math.pow(R,Math.abs(B)-1)}function me(B){return new DataView(B.array.buffer,B.offset.value,B.size)}function _e(B){const N=B.viewer.buffer.slice(B.offset.value,B.offset.value+B.size),Z=new Uint8Array(Ne(N)),P=new Uint8Array(Z.length);return Ge(Z),xe(Z,P),new DataView(P.buffer)}function Pe(B){const N=B.array.slice(B.offset.value,B.offset.value+B.size),Z=gA(N),P=new Uint8Array(Z.length);return Ge(Z),xe(Z,P),new DataView(P.buffer)}function Te(B){const N=B.viewer,Z={value:B.offset.value},P=new Uint16Array(B.width*B.scanlineBlockSize*(B.channels*B.type)),G=new Uint8Array(8192);let V=0;const Y=new Array(B.channels);for(let Je=0;Je<B.channels;Je++)Y[Je]={},Y[Je].start=V,Y[Je].end=Y[Je].start,Y[Je].nx=B.width,Y[Je].ny=B.lines,Y[Je].size=B.type,V+=Y[Je].nx*Y[Je].ny*Y[Je].size;const K=$(N,Z),pe=$(N,Z);if(pe>=8192)throw new Error("Something is wrong with PIZ_COMPRESSION BITMAP_SIZE");if(K<=pe)for(let Je=0;Je<pe-K+1;Je++)G[Je+K]=pt(N,Z);const he=new Uint16Array(65536),be=C(G,he),Be=ft(N,Z);st(B.array,N,Z,Be,P,V);for(let Je=0;Je<B.channels;++Je){const et=Y[Je];for(let ht=0;ht<Y[Je].size;++ht)Ve(P,et.start+ht,et.nx,et.size,et.ny,et.nx*et.size,be)}W(he,P,V);let Oe=0;const je=new Uint8Array(P.buffer.byteLength);for(let Je=0;Je<B.lines;Je++)for(let et=0;et<B.channels;et++){const ht=Y[et],Mt=ht.nx*ht.size,_i=new Uint8Array(P.buffer,ht.end*2,Mt*2);je.set(_i,Oe),Oe+=Mt*2,ht.end+=Mt}return new DataView(je.buffer)}function bt(B){const N=B.array.slice(B.offset.value,B.offset.value+B.size),Z=gA(N),P=B.lines*B.channels*B.width,G=B.type==1?new Uint16Array(P):new Uint32Array(P);let V=0,Y=0;const K=new Array(4);for(let pe=0;pe<B.lines;pe++)for(let he=0;he<B.channels;he++){let be=0;switch(B.type){case 1:K[0]=V,K[1]=K[0]+B.width,V=K[1]+B.width;for(let Be=0;Be<B.width;++Be){const Oe=Z[K[0]++]<<8|Z[K[1]++];be+=Oe,G[Y]=be,Y++}break;case 2:K[0]=V,K[1]=K[0]+B.width,K[2]=K[1]+B.width,V=K[2]+B.width;for(let Be=0;Be<B.width;++Be){const Oe=Z[K[0]++]<<24|Z[K[1]++]<<16|Z[K[2]++]<<8;be+=Oe,G[Y]=be,Y++}break}}return new DataView(G.buffer)}function dt(B){const N=B.viewer,Z={value:B.offset.value},P=new Uint8Array(B.width*B.lines*(B.channels*B.type*2)),G={version:rt(N,Z),unknownUncompressedSize:rt(N,Z),unknownCompressedSize:rt(N,Z),acCompressedSize:rt(N,Z),dcCompressedSize:rt(N,Z),rleCompressedSize:rt(N,Z),rleUncompressedSize:rt(N,Z),rleRawSize:rt(N,Z),totalAcUncompressedCount:rt(N,Z),totalDcUncompressedCount:rt(N,Z),acCompression:rt(N,Z)};if(G.version<2)throw new Error("EXRLoader.parse: "+eu.compression+" version "+G.version+" is unsupported");const V=new Array;let Y=$(N,Z)-2;for(;Y>0;){const et=ke(N.buffer,Z),ht=pt(N,Z),Mt=ht>>2&3,_i=(ht>>4)-1,Qt=new Int8Array([_i])[0],Pt=pt(N,Z);V.push({name:et,index:Qt,type:Pt,compression:Mt}),Y-=et.length+3}const K=eu.channels,pe=new Array(B.channels);for(let et=0;et<B.channels;++et){const ht=pe[et]={},Mt=K[et];ht.name=Mt.name,ht.compression=0,ht.decoded=!1,ht.type=Mt.pixelType,ht.pLinear=Mt.pLinear,ht.width=B.width,ht.height=B.lines}const he={idx:new Array(3)};for(let et=0;et<B.channels;++et){const ht=pe[et];for(let Mt=0;Mt<V.length;++Mt){const _i=V[Mt];ht.name==_i.name&&(ht.compression=_i.compression,_i.index>=0&&(he.idx[_i.index]=et),ht.offset=et)}}let be,Be,Oe;if(G.acCompressedSize>0)switch(G.acCompression){case 0:be=new Uint16Array(G.totalAcUncompressedCount),st(B.array,N,Z,G.acCompressedSize,be,G.totalAcUncompressedCount);break;case 1:const et=B.array.slice(Z.value,Z.value+G.totalAcUncompressedCount),ht=gA(et);be=new Uint16Array(ht.buffer),Z.value+=G.totalAcUncompressedCount;break}if(G.dcCompressedSize>0){const et={array:B.array,offset:Z,size:G.dcCompressedSize};Be=new Uint16Array(Pe(et).buffer),Z.value+=G.dcCompressedSize}if(G.rleRawSize>0){const et=B.array.slice(Z.value,Z.value+G.rleCompressedSize),ht=gA(et);Oe=Ne(ht.buffer),Z.value+=G.rleCompressedSize}let je=0;const Je=new Array(pe.length);for(let et=0;et<Je.length;++et)Je[et]=new Array;for(let et=0;et<B.lines;++et)for(let ht=0;ht<pe.length;++ht)Je[ht].push(je),je+=pe[ht].width*B.type*2;Ee(he,Je,pe,be,Be,P);for(let et=0;et<pe.length;++et){const ht=pe[et];if(!ht.decoded)switch(ht.compression){case 2:let Mt=0,_i=0;for(let Qt=0;Qt<B.lines;++Qt){let Pt=Je[et][Mt];for(let Oi=0;Oi<ht.width;++Oi){for(let Ct=0;Ct<2*ht.type;++Ct)P[Pt++]=Oe[_i+Ct*ht.width*ht.height];_i++}Mt++}break;case 1:default:throw new Error("EXRLoader.parse: unsupported channel compression")}}return new DataView(P.buffer)}function ke(B,N){const Z=new Uint8Array(B);let P=0;for(;Z[N.value+P]!=0;)P+=1;const G=new TextDecoder().decode(Z.slice(N.value,N.value+P));return N.value=N.value+P+1,G}function Qe(B,N,Z){const P=new TextDecoder().decode(new Uint8Array(B).slice(N.value,N.value+Z));return N.value=N.value+Z,P}function St(B,N){const Z=ei(B,N),P=ft(B,N);return[Z,P]}function Fe(B,N){const Z=ft(B,N),P=ft(B,N);return[Z,P]}function ei(B,N){const Z=B.getInt32(N.value,!0);return N.value=N.value+4,Z}function ft(B,N){const Z=B.getUint32(N.value,!0);return N.value=N.value+4,Z}function Xe(B,N){const Z=B[N.value];return N.value=N.value+1,Z}function pt(B,N){const Z=B.getUint8(N.value);return N.value=N.value+1,Z}const rt=function(B,N){let Z;return"getBigInt64"in DataView.prototype?Z=Number(B.getBigInt64(N.value,!0)):Z=B.getUint32(N.value+4,!0)+Number(B.getUint32(N.value,!0)<<32),N.value+=8,Z};function Bt(B,N){const Z=B.getFloat32(N.value,!0);return N.value+=4,Z}function j(B,N){return Ff.toHalfFloat(Bt(B,N))}function ae(B){const N=(B&31744)>>10,Z=B&1023;return(B>>15?-1:1)*(N?N===31?Z?NaN:1/0:Math.pow(2,N-15)*(1+Z/1024):6103515625e-14*(Z/1024))}function $(B,N){const Z=B.getUint16(N.value,!0);return N.value+=2,Z}function De(B,N){return ae($(B,N))}function ce(B,N,Z,P){const G=Z.value,V=[];for(;Z.value<G+P-1;){const Y=ke(N,Z),K=ei(B,Z),pe=pt(B,Z);Z.value+=3;const he=ei(B,Z),be=ei(B,Z);V.push({name:Y,pixelType:K,pLinear:pe,xSampling:he,ySampling:be})}return Z.value+=1,V}function He(B,N){const Z=Bt(B,N),P=Bt(B,N),G=Bt(B,N),V=Bt(B,N),Y=Bt(B,N),K=Bt(B,N),pe=Bt(B,N),he=Bt(B,N);return{redX:Z,redY:P,greenX:G,greenY:V,blueX:Y,blueY:K,whiteX:pe,whiteY:he}}function Ye(B,N){const Z=["NO_COMPRESSION","RLE_COMPRESSION","ZIPS_COMPRESSION","ZIP_COMPRESSION","PIZ_COMPRESSION","PXR24_COMPRESSION","B44_COMPRESSION","B44A_COMPRESSION","DWAA_COMPRESSION","DWAB_COMPRESSION"],P=pt(B,N);return Z[P]}function ti(B,N){const Z=ft(B,N),P=ft(B,N),G=ft(B,N),V=ft(B,N);return{xMin:Z,yMin:P,xMax:G,yMax:V}}function Ti(B,N){const Z=["INCREASING_Y"],P=pt(B,N);return Z[P]}function rn(B,N){const Z=Bt(B,N),P=Bt(B,N);return[Z,P]}function on(B,N){const Z=Bt(B,N),P=Bt(B,N),G=Bt(B,N);return[Z,P,G]}function si(B,N,Z,P,G){if(P==="string"||P==="stringvector"||P==="iccProfile")return Qe(N,Z,G);if(P==="chlist")return ce(B,N,Z,G);if(P==="chromaticities")return He(B,Z);if(P==="compression")return Ye(B,Z);if(P==="box2i")return ti(B,Z);if(P==="lineOrder")return Ti(B,Z);if(P==="float")return Bt(B,Z);if(P==="v2f")return rn(B,Z);if(P==="v3f")return on(B,Z);if(P==="int")return ei(B,Z);if(P==="rational")return St(B,Z);if(P==="timecode")return Fe(B,Z);if(P==="preview")return Z.value+=G,"skipped";Z.value+=G}function An(B,N,Z){const P={};if(B.getUint32(0,!0)!=20000630)throw new Error("THREE.EXRLoader: Provided file doesn't appear to be in OpenEXR format.");P.version=B.getUint8(4);const G=B.getUint8(5);P.spec={singleTile:!!(G&2),longName:!!(G&4),deepFormat:!!(G&8),multiPart:!!(G&16)},Z.value=8;let V=!0;for(;V;){const Y=ke(N,Z);if(Y==0)V=!1;else{const K=ke(N,Z),pe=ft(B,Z),he=si(B,N,Z,K,pe);he===void 0?console.warn(`THREE.EXRLoader: Skipped unknown header attribute type '${K}'.`):P[Y]=he}}if(G&-5)throw console.error("THREE.EXRHeader:",P),new Error("THREE.EXRLoader: Provided file is currently unsupported.");return P}function In(B,N,Z,P,G){const V={size:0,viewer:N,array:Z,offset:P,width:B.dataWindow.xMax-B.dataWindow.xMin+1,height:B.dataWindow.yMax-B.dataWindow.yMin+1,channels:B.channels.length,bytesPerLine:null,lines:null,inputSize:null,type:B.channels[0].pixelType,uncompress:null,getter:null,format:null,colorSpace:Fi};switch(B.compression){case"NO_COMPRESSION":V.lines=1,V.uncompress=me;break;case"RLE_COMPRESSION":V.lines=1,V.uncompress=_e;break;case"ZIPS_COMPRESSION":V.lines=1,V.uncompress=Pe;break;case"ZIP_COMPRESSION":V.lines=16,V.uncompress=Pe;break;case"PIZ_COMPRESSION":V.lines=32,V.uncompress=Te;break;case"PXR24_COMPRESSION":V.lines=16,V.uncompress=bt;break;case"DWAA_COMPRESSION":V.lines=32,V.uncompress=dt;break;case"DWAB_COMPRESSION":V.lines=256,V.uncompress=dt;break;default:throw new Error("EXRLoader.parse: "+B.compression+" is unsupported")}if(V.scanlineBlockSize=V.lines,V.type==1)switch(G){case Wn:V.getter=De,V.inputSize=2;break;case ms:V.getter=$,V.inputSize=2;break}else if(V.type==2)switch(G){case Wn:V.getter=Bt,V.inputSize=4;break;case ms:V.getter=j,V.inputSize=4}else throw new Error("EXRLoader.parse: unsupported pixelType "+V.type+" for "+B.compression+".");V.blockCount=(B.dataWindow.yMax+1)/V.scanlineBlockSize;for(let K=0;K<V.blockCount;K++)rt(N,P);V.outputChannels=V.channels==3?4:V.channels;const Y=V.width*V.height*V.outputChannels;switch(G){case Wn:V.byteArray=new Float32Array(Y),V.channels<V.outputChannels&&V.byteArray.fill(1,0,Y);break;case ms:V.byteArray=new Uint16Array(Y),V.channels<V.outputChannels&&V.byteArray.fill(15360,0,Y);break;default:console.error("THREE.EXRLoader: unsupported type: ",G);break}return V.bytesPerLine=V.width*V.inputSize*V.channels,V.outputChannels==4?(V.format=nn,V.colorSpace=Fi):(V.format=Sy,V.colorSpace=vo),V}const Bo=new DataView(e),$h=new Uint8Array(e),Do={value:0},eu=An(Bo,e,Do),$t=In(eu,Bo,$h,Do,this.type),fv={value:0},Db={R:0,G:1,B:2,A:3,Y:0};for(let B=0;B<$t.height/$t.scanlineBlockSize;B++){const N=ft(Bo,Do);$t.size=ft(Bo,Do),$t.lines=N+$t.scanlineBlockSize>$t.height?$t.height-N:$t.scanlineBlockSize;const P=$t.size<$t.lines*$t.bytesPerLine?$t.uncompress($t):me($t);Do.value+=$t.size;for(let G=0;G<$t.scanlineBlockSize;G++){const V=G+B*$t.scanlineBlockSize;if(V>=$t.height)break;for(let Y=0;Y<$t.channels;Y++){const K=Db[eu.channels[Y].name];for(let pe=0;pe<$t.width;pe++){fv.value=(G*($t.channels*$t.width)+Y*$t.width+pe)*$t.inputSize;const he=($t.height-1-V)*($t.width*$t.outputChannels)+pe*$t.outputChannels+K;$t.byteArray[he]=$t.getter(P,fv)}}}}return{header:eu,width:$t.width,height:$t.height,data:$t.byteArray,format:$t.format,colorSpace:$t.colorSpace,type:this.type}}setDataType(e){return this.type=e,this}load(e,t,i,n){function r(o,a){o.colorSpace=a.colorSpace,o.minFilter=Lt,o.magFilter=Lt,o.generateMipmaps=!1,o.flipY=!1,t&&t(o,a)}return super.load(e,r,i,n)}}const xde=Object.freeze(Object.defineProperty({__proto__:null,EXRLoader:W0},Symbol.toStringTag,{value:"Module"}));class PC extends $2{constructor(e){super(e),this.type=ms}parse(e){const o=function(T,R){switch(T){case 1:throw new Error("THREE.RGBELoader: Read Error: "+(R||""));case 2:throw new Error("THREE.RGBELoader: Write Error: "+(R||""));case 3:throw new Error("THREE.RGBELoader: Bad File Format: "+(R||""));default:case 4:throw new Error("THREE.RGBELoader: Memory Error: "+(R||""))}},h=`
|
|
5237
5237
|
`,u=function(T,R,C){R=R||1024;let F=T.pos,U=-1,O=0,Q="",D=String.fromCharCode.apply(null,new Uint16Array(T.subarray(F,F+128)));for(;0>(U=D.indexOf(h))&&O<R&&F<T.byteLength;)Q+=D,O+=D.length,F+=128,D+=String.fromCharCode.apply(null,new Uint16Array(T.subarray(F,F+128)));return-1<U?(C!==!1&&(T.pos+=O+U+1),Q+D.slice(0,U)):!1},f=function(T){const R=/^#\?(\S+)/,C=/^\s*GAMMA\s*=\s*(\d+(\.\d+)?)\s*$/,I=/^\s*EXPOSURE\s*=\s*(\d+(\.\d+)?)\s*$/,F=/^\s*FORMAT=(\S+)\s*$/,U=/^\s*\-Y\s+(\d+)\s+\+X\s+(\d+)\s*$/,O={valid:0,string:"",comments:"",programtype:"RGBE",format:"",gamma:1,exposure:1,width:0,height:0};let Q,D;for((T.pos>=T.byteLength||!(Q=u(T)))&&o(1,"no header found"),(D=Q.match(R))||o(3,"bad initial token"),O.valid|=1,O.programtype=D[1],O.string+=Q+`
|
|
5238
5238
|
`;Q=u(T),Q!==!1;){if(O.string+=Q+`
|
|
@@ -5266,7 +5266,7 @@ TEX `+i.texture_lod;if(II=="density"&&(_+=`
|
|
|
5266
5266
|
`+(v/n.lastScreenCoverage).toFixed(0)+` dens
|
|
5267
5267
|
`+(n.lastScreenCoverage*100).toFixed(1)+`% cov
|
|
5268
5268
|
`+(n.lastCentrality*100).toFixed(1)+`% centr
|
|
5269
|
-
`+(bw.min.x.toFixed(2)+"-"+bw.max.x.toFixed(2)+"x"+bw.min.y.toFixed(2)+"-"+bw.max.y.toFixed(2))+" scr"),n.lastScreenCoverage>.1){const A=e,b=A.worldForward,S=A.worldPosition,M=pi(b).multiplyScalar(f*.7).add(u),T=M.distanceTo(S),R=p[Math.min(p.length-1,Math.max(0,r))]+"88",C=this.context.domHeight>0?screen.height/this.context.domHeight:1,I=e.isPerspectiveCamera?Math.tan(e.fov*Math.PI/180/2):1;_t.DrawLabel(M,_,T*.012*C*I,void 0,16777215,R)}}}}}const ww=ie("debugphysics"),fz=new Rr;class Il{constructor(){d(this,"ray");d(this,"cam");d(this,"screenPoint");d(this,"raycaster");d(this,"results");d(this,"targets");d(this,"recursive",!0);d(this,"minDistance");d(this,"maxDistance");d(this,"lineThreshold");d(this,"layerMask");d(this,"ignore");d(this,"testObject")}screenPointFromOffset(e,t){this.screenPoint===void 0&&(this.screenPoint=new ee),this.screenPoint.x=e/window.innerWidth*2-1,this.screenPoint.y=-(t/window.innerHeight)*2+1}setLayer(e){fz.set(e),this.layerMask=fz}setMask(e){this.layerMask||(this.layerMask=new Rr);const t=this.layerMask;t?t.mask=e:this.layerMask=e}}d(Il,"AllLayers",4294967295);class H6{constructor(e,t,i){d(this,"distance");d(this,"point");d(this,"object");this.object=e,this.distance=t,this.point=i}}class V6{constructor(e){d(this,"context");d(this,"engine");d(this,"raycaster",new Pp);d(this,"defaultRaycastOptions",new Il);d(this,"targetBuffer",new Array(1));d(this,"defaultThresholds",{Mesh:{},Line:{threshold:-1},LOD:{},Points:{threshold:0},Sprite:{}});d(this,"sphereResults",new Array);d(this,"sphereMask",new Rr);d(this,"tempBoundingBox",new Ei);this.context=e}raycastPhysicsFast(e,t=void 0,i=1/0,n=!0){var r;return((r=this.context.physics.engine)==null?void 0:r.raycast(e,t,{maxDistance:i,solid:n}))??null}raycastPhysicsFastAndGetNormal(e,t=void 0,i=1/0,n=!0){var r;return((r=this.context.physics.engine)==null?void 0:r.raycastAndGetNormal(e,t,{maxDistance:i,solid:n}))??null}sphereOverlapPhysics(e,t){var i;return((i=this.context.physics.engine)==null?void 0:i.sphereOverlap(e,t))??null}sphereOverlap(e,t,i=!0){if(this.sphereResults.length=0,!this.context.scene)return this.sphereResults;const n=new kn(e,t),r=this.sphereMask;r.enableAll(),r.disable(2);for(const o of this.context.scene.children)this.onSphereOverlap(o,n,r,this.sphereResults,i);return this.sphereResults.sort((o,a)=>o.distance-a.distance)}onSphereOverlap(e,t,i,n,r){if(e.type==="Mesh"&&e.layers.test(i)&&!_t.isGizmo(e)){const o=e,a=o.geometry;if(a&&(a.boundingBox||a.computeBoundingBox(),a.boundingBox)){o.matrixWorldNeedsUpdate&&o.updateMatrixWorld();const l=this.tempBoundingBox.copy(a.boundingBox).applyMatrix4(o.matrixWorld);if(t.intersectsBox(l)){const c=kt(e),h=c.distanceTo(t.center),u=new H6(e,h,c);if(n.push(u),!r)return}}}if(e.children)for(const o of e.children){const a=n.length;if(this.onSphereOverlap(o,t,i,n,r),a!=n.length&&!r)return}}raycastFromRay(e,t=null){const i=t??this.defaultRaycastOptions;i.ray=e;const n=this.raycast(i);return i===this.defaultRaycastOptions&&(i.ray=void 0),n}raycast(e=null){e||(e=this.defaultRaycastOptions);const t=e.screenPoint??this.context.input.mousePositionRC,i=e.raycaster??this.raycaster;if(i.near=e.minDistance??0,i.far=e.maxDistance??1/0,i.params=this.defaultThresholds,e.lineThreshold===void 0&&(e.lineThreshold=-1),i.params.Line={threshold:e.lineThreshold},e.ray)i.ray.copy(e.ray);else{const a=e.cam??this.context.mainCamera;if(!a)return ww&&console.error("Can not perform raycast - no main camera found"),this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),this.defaultRaycastOptions.results??[];const l=this.context.xrCamera;this.context.isInXR&&l instanceof k2&&l.cameras.length>0?i.setFromCamera(t,l.cameras[0]):i.setFromCamera(t,a)}let n=e.targets;n||(n=this.targetBuffer,n.length=1,n[0]=this.context.scene);let r=e.results;this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),r||(this.defaultRaycastOptions.results||(this.defaultRaycastOptions.results=new Array),r=this.defaultRaycastOptions.results),e.layerMask!==void 0?e.layerMask instanceof Rr?i.layers.mask=e.layerMask.mask:i.layers.mask=e.layerMask:(i.layers.enableAll(),i.layers.disable(2)),ww&&(_t.DrawRay(i.ray.origin,i.ray.direction,16711680,2),console.time("raycast")),r.length=0,this.intersect(this.raycaster,n,r,e),r.sort((a,l)=>a.distance-l.distance);const o=e.ignore;return o!==void 0&&o.length>0&&(r=r.filter(a=>!o.includes(a.object))),ww&&(console.timeEnd("raycast"),console.warn("#"+this.context.time.frame+", hits:",r!=null&&r.length?[...r]:"nothing")),r}intersect(e,t,i,n){var r;for(const o of t){if(o.visible===!1||_t.isGizmo(o)||n.lineThreshold!==void 0&&n.lineThreshold<0&&o instanceof Dn)continue;const a=(r=n.testObject)==null?void 0:r.call(n,o);if(a===!1)continue;if(a!=="continue in children"){const c=o,h=c.geometry;if(h){const u=O_(o);u&&(c.geometry=u);const f=i.length;e.intersectObject(o,!1,i),ww&&i.length!=f&&_t.DrawWireMesh({mesh:o,depthTest:!1,duration:.2,color:u?8969557:7798784}),c.geometry=h}}n.recursive!==!1&&this.intersect(e,o.children,i,n)}return i}}const Mde=ie("debugplayerview");var sd=(s=>(s.Browser="browser",s.Headset="headset",s.Handheld="handheld",s))(sd||{});class Q6{constructor(e,t){d(this,"userId");d(this,"context");d(this,"viewDevice","browser");d(this,"removed",!1);d(this,"_object");this.userId=e,this.context=t}get currentObject(){return this._object}set currentObject(e){this._object=e}get isConnected(){return this.context.connection.userIsInRoom(this.userId)}}class j6{constructor(e){d(this,"context");d(this,"playerViews",new Map);this.context=e}setPlayerView(e,t,i){let n=this.playerViews.get(e);n||(n=new Q6(e,this.context),this.playerViews.set(e,n)),n.viewDevice=i,n.currentObject=t,n.removed=!1}getPlayerView(e){if(!e)return;if(!this.context.connection.userIsInRoom(e)){this.playerViews.delete(e);return}return this.playerViews.get(e)}removePlayerView(e,t){const i=this.playerViews.get(e);(i==null?void 0:i.viewDevice)===t&&(Mde&&console.log("REMOVE",e),i.removed=!0,this.playerViews.delete(e))}}new Or;const G_=new Uint8Array(4);G_[0]=255;G_[1]=255;G_[2]=255;G_[3]=255;const Tde=new $o(G_,1,1,nn);function QO(s,e=1){const t="alpha"in s,i=e*e,n=new Uint8Array(4*i),r=Math.floor(s.r*255),o=Math.floor(s.g*255),a=Math.floor(s.b*255);for(let c=0;c<i;c++){const h=c*4;n[h+0]=r,n[h+1]=o,n[h+2]=a,t?n[h+3]=Math.floor(s.alpha*255):n[h+3]=255}const l=new $o(n,e,e);return l.needsUpdate=!0,l}function Ide(s,e,t,i=1,n=3){const o=i*n,a=[s,e,t],l=a.length,c=new Uint8Array(4*l*o),h=new Ae;for(let f=0;f<n;f++){const p=Math.floor(f/n*l),m=it.clamp(p+1,0,l-1),y=a[p],g=a[m],v=f/n*l%1;h.lerpColors(y,g,v);const _=Math.floor(h.r*255),A=Math.floor(h.g*255),b=Math.floor(h.b*255);for(let S=0;S<i;S++){const E=(f*i+S)*4;c[E+0]=_,c[E+1]=A,c[E+2]=b,c[E+3]=255}}const u=new $o(c,i,n);return u.needsUpdate=!0,u}function BC(s,e){const t=s.elements;e||(e=[]),e.length=0;for(let i=0;i<16;i+=4){const n=t[i],r=t[i+1],o=t[i+2],a=t[i+3],l=new Ze(n,r,o,a);e.push(l)}return e}const RI=[],pz=[];function Rde(s,e){if(RI.length===0)for(let t=0;t<27;t++)RI.push(0);e||(e=RI);for(let t=0;t<27;t++)pz[t]=e[t];e=pz,s.unity_SHAr={value:new Ze(e[9],e[3],e[6],e[0])},s.unity_SHBr={value:new Ze(e[12],e[15],e[18],e[21])},s.unity_SHAg={value:new Ze(e[10],e[4],e[7],e[1])},s.unity_SHBg={value:new Ze(e[13],e[16],e[19],e[22])},s.unity_SHAb={value:new Ze(e[11],e[5],e[8],e[2])},s.unity_SHBb={value:new Ze(e[14],e[17],e[20],e[23])},s.unity_SHC={value:new Ze(e[24],e[25],e[26],1)}}class Pde{constructor(e,t,i){d(this,"vertexShader");d(this,"fragmentShader");d(this,"technique");this.vertexShader=e,this.fragmentShader=t,this.technique=i}}async function Bde(s,e){if(!s)return console.error("Can not find technique: no shader data"),null;const t=s.programs[e],i=t.vertexShader,n=t.fragmentShader;if(i!==void 0&&n!==void 0){const r=s.shaders[i],o=s.shaders[n];if(r.uri&&o.uri||r.code&&o.code){if(!r.code&&r.uri&&await mz(r),!o.code&&o.uri&&await mz(o),!r.code||!o.code)return null;const a=s.techniques[e];return new Pde(r.code,o.code,a)}}return console.error("Shader technique not found",e),null}async function mz(s){const e=s.uri;if(e)if(e.endsWith(".glsl")){const i=await new Or().loadAsync(e);s.code=i.toString()}else s.code=Dde(s.uri)}function Dde(s){return decodeURIComponent(Array.prototype.map.call(atob(s),function(e){return"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)}).join(""))}const hl=ie("debugenvlight");var Yg=(s=>(s[s.Skybox=0]="Skybox",s[s.Trilight=1]="Trilight",s[s.Flat=3]="Flat",s[s.Custom=4]="Custom",s))(Yg||{}),DC=(s=>(s[s.Skybox=0]="Skybox",s[s.Custom=1]="Custom",s))(DC||{});class W6{constructor(e){d(this,"context");d(this,"_currentLightSettingsId");d(this,"_sceneLightSettings");d(this,"_timevec4",new Ze);d(this,"__currentReflectionId",null);d(this,"_lighting",{});this.context=e,this.context.pre_update_callbacks.push(this.preUpdate.bind(this))}preUpdate(){const e=this.context.time;this._timevec4.x=e.time,this._timevec4.y=Math.sin(e.time),this._timevec4.z=Math.cos(e.time),this._timevec4.w=e.deltaTime}get timeVec4(){return this._timevec4}get environmentIntensity(){if(!this._sceneLightSettings||!this._currentLightSettingsId)return 1;const e=this._sceneLightSettings.get(this._currentLightSettingsId);return e?e.ambientIntensity:1}get sceneLightSettings(){var e;return(e=this._sceneLightSettings)==null?void 0:e.values()}enable(e){var i;e instanceof Zt&&(e=e.uri);const t=(i=this._sceneLightSettings)==null?void 0:i.get(e);return t?(hl&&console.log("Enable scene light settings",e,t),e!==this._currentLightSettingsId&&this._currentLightSettingsId&&this.disable(this._currentLightSettingsId),this._currentLightSettingsId=e,t.enabled=!0,!0):(hl&&console.warn("No light settings found for",e),!1)}disable(e){var i;if(e instanceof Zt&&(e=e.uri),e==null)return!1;const t=(i=this._sceneLightSettings)==null?void 0:i.get(e);return t?(hl&&console.log("Disable scene light settings",e,t),t.enabled=!1,!0):!1}disableCurrent(){if(this._currentLightSettingsId){const e=this._currentLightSettingsId;return this.disable(this._currentLightSettingsId),e}return null}internalRegisterSceneLightSettings(e){const t=e.sourceId;if(!t){console.error("Missing source id for scene light settings, can not register:",e);return}hl&&console.log("Register "+(e==null?void 0:e.sourceId)+" lighting",e),this._sceneLightSettings||(this._sceneLightSettings=new Map),this._sceneLightSettings.set(t,e)}internalUnregisterSceneLightSettings(e){const t=e.sourceId;if(!t){console.error("Missing source id for scene light settings, can not unregister:",e);return}hl&&console.log("Unregister "+(e==null?void 0:e.sourceId)+" lighting",e),this._sceneLightSettings&&this._sceneLightSettings.delete(t)}internalRegisterReflection(e,t){hl&&console.log("Register reflection",e,t);const i=new q6(this.context,t,1);this._lighting[e]=i}internalGetReflection(e){return this._lighting[e]}internalEnableReflection(e){var i;this.__currentReflectionId=e;const t=(i=this._sceneLightSettings)==null?void 0:i.get(e);switch(hl&&console.log("Enable reflection",e,t?Yg[t.ambientMode]:"Unknown ambient mode",t),t==null?void 0:t.ambientMode){case 0:case 4:const n=this.internalGetReflection(e);if(n&&n.Source){hl&&console.log("Setting environment reflection",n);const r=this.context.scene,o=n.Source;o.mapping=xo,r.environment=o;return}else hl&&console.warn("Could not find reflection for source",e);break}if((t==null?void 0:t.environmentReflectionSource)===1)switch(t==null?void 0:t.ambientMode){case 1:if(t.ambientTrilight){const n=t.ambientTrilight,r=Ide(n[0],n[1],n[2],64,64);r.colorSpace=At,r.mapping=xo,this.context.scene.environment=r}else console.error("Missing ambient trilight",t.sourceId);return;case 3:if(t.ambientLight){const n=QO(t.ambientLight,64);n.colorSpace=At,n.mapping=xo,this.context.scene.environment=n}else console.error("Missing ambientlight",t.sourceId);return;default:return}}internalDisableReflection(e){if(e&&e!==this.__currentReflectionId){hl&&console.log("Not disabling reflection for",e,"because it is not the current light settings id",this.__currentReflectionId);return}hl&&console.log("Disable reflection",e);const t=this.context.scene;t.environment=null}}class q6{constructor(e,t,i=1){d(this,"_source");this._source=t,t.mapping=xo}get Source(){return this._source}}const gz=ie("timescale");let EB=1;typeof gz=="number"&&(EB=gz);class X6{constructor(){d(this,"_time",0);d(this,"_deltaTime",0);d(this,"_deltaTimeUnscaled",0);d(this,"timeScale",1);d(this,"_frame",0);d(this,"clock",new iD);d(this,"_smoothedFps",0);d(this,"_smoothedDeltaTime",0);d(this,"_fpsSamples",[]);d(this,"_fpsSampleIndex",0);typeof EB=="number"&&(this.timeScale=EB)}get time(){return this._time}set time(e){this._time=e}get deltaTime(){return this._deltaTime}set deltaTime(e){this._deltaTime=e}get deltaTimeUnscaled(){return this._deltaTimeUnscaled}get frame(){return this._frame}set frame(e){this._frame=e}get frameCount(){return this.frame}get realtimeSinceStartup(){return this.clock.elapsedTime}get smoothedFps(){return this._smoothedFps}get smoothedDeltaTime(){return 1/this._smoothedFps}update(){this.deltaTime=this.clock.getDelta(),this.deltaTime=Math.min(.1,this.deltaTime),this._deltaTimeUnscaled=this.deltaTime,this.deltaTime<=0&&(this.deltaTime=1e-12),this.deltaTime*=this.timeScale,this.frame+=1,this.time+=this.deltaTime,this._fpsSamples.length<60?this._fpsSamples.push(this.deltaTime):this._fpsSamples[this._fpsSampleIndex++%60]=this.deltaTime;let e=0;for(let t=0;t<this._fpsSamples.length;t++)e+=this._fpsSamples[t];this._smoothedDeltaTime=e/this._fpsSamples.length,this._smoothedFps=1/this._smoothedDeltaTime}}let yz=!1;function Y6(s){yz||(yz=!0,Ode(),Lde())}Y6();function Ode(){const s=`
|
|
5269
|
+
`+(bw.min.x.toFixed(2)+"-"+bw.max.x.toFixed(2)+"x"+bw.min.y.toFixed(2)+"-"+bw.max.y.toFixed(2))+" scr"),n.lastScreenCoverage>.1){const A=e,b=A.worldForward,S=A.worldPosition,M=pi(b).multiplyScalar(f*.7).add(u),T=M.distanceTo(S),R=p[Math.min(p.length-1,Math.max(0,r))]+"88",C=this.context.domHeight>0?screen.height/this.context.domHeight:1,I=e.isPerspectiveCamera?Math.tan(e.fov*Math.PI/180/2):1;_t.DrawLabel(M,_,T*.012*C*I,void 0,16777215,R)}}}}}const ww=ie("debugphysics"),fz=new Rr;class Il{constructor(){d(this,"ray");d(this,"cam");d(this,"screenPoint");d(this,"raycaster");d(this,"results");d(this,"targets");d(this,"recursive",!0);d(this,"minDistance");d(this,"maxDistance");d(this,"lineThreshold");d(this,"layerMask");d(this,"ignore");d(this,"testObject")}screenPointFromOffset(e,t){this.screenPoint===void 0&&(this.screenPoint=new ee),this.screenPoint.x=e/window.innerWidth*2-1,this.screenPoint.y=-(t/window.innerHeight)*2+1}setLayer(e){fz.set(e),this.layerMask=fz}setMask(e){this.layerMask||(this.layerMask=new Rr);const t=this.layerMask;t?t.mask=e:this.layerMask=e}}d(Il,"AllLayers",4294967295);class H6{constructor(e,t,i){d(this,"distance");d(this,"point");d(this,"object");this.object=e,this.distance=t,this.point=i}}class V6{constructor(e){d(this,"context");d(this,"engine");d(this,"raycaster",new Pp);d(this,"defaultRaycastOptions",new Il);d(this,"targetBuffer",new Array(1));d(this,"defaultThresholds",{Mesh:{},Line:{threshold:-1},LOD:{},Points:{threshold:0},Sprite:{}});d(this,"sphereResults",new Array);d(this,"sphereMask",new Rr);d(this,"tempBoundingBox",new Ei);this.context=e}raycastPhysicsFast(e,t=void 0,i=1/0,n=!0){var r;return((r=this.context.physics.engine)==null?void 0:r.raycast(e,t,{maxDistance:i,solid:n}))??null}raycastPhysicsFastAndGetNormal(e,t=void 0,i=1/0,n=!0){var r;return((r=this.context.physics.engine)==null?void 0:r.raycastAndGetNormal(e,t,{maxDistance:i,solid:n}))??null}sphereOverlapPhysics(e,t){var i;return((i=this.context.physics.engine)==null?void 0:i.sphereOverlap(e,t))??null}sphereOverlap(e,t,i=!0){if(this.sphereResults.length=0,!this.context.scene)return this.sphereResults;const n=new kn(e,t),r=this.sphereMask;r.enableAll(),r.disable(2);for(const o of this.context.scene.children)this.onSphereOverlap(o,n,r,this.sphereResults,i);return this.sphereResults.sort((o,a)=>o.distance-a.distance)}onSphereOverlap(e,t,i,n,r){if(e.type==="Mesh"&&e.layers.test(i)&&!_t.isGizmo(e)){const o=e,a=o.geometry;if(a&&(a.boundingBox||a.computeBoundingBox(),a.boundingBox)){o.matrixWorldNeedsUpdate&&o.updateMatrixWorld();const l=this.tempBoundingBox.copy(a.boundingBox).applyMatrix4(o.matrixWorld);if(t.intersectsBox(l)){const c=kt(e),h=c.distanceTo(t.center),u=new H6(e,h,c);if(n.push(u),!r)return}}}if(e.children)for(const o of e.children){const a=n.length;if(this.onSphereOverlap(o,t,i,n,r),a!=n.length&&!r)return}}raycastFromRay(e,t=null){const i=t??this.defaultRaycastOptions;i.ray=e;const n=this.raycast(i);return i===this.defaultRaycastOptions&&(i.ray=void 0),n}raycast(e=null){e||(e=this.defaultRaycastOptions);const t=e.screenPoint??this.context.input.mousePositionRC,i=e.raycaster??this.raycaster;if(i.near=e.minDistance??0,i.far=e.maxDistance??1/0,i.params=this.defaultThresholds,e.lineThreshold===void 0&&(e.lineThreshold=-1),i.params.Line={threshold:e.lineThreshold},e.ray)i.ray.copy(e.ray);else{const a=e.cam??this.context.mainCamera;if(!a)return ww&&console.error("Can not perform raycast - no main camera found"),this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),this.defaultRaycastOptions.results??[];const l=this.context.xrCamera;this.context.isInXR&&l instanceof k2&&l.cameras.length>0?i.setFromCamera(t,l.cameras[0]):i.setFromCamera(t,a)}let n=e.targets;n||(n=this.targetBuffer,n.length=1,n[0]=this.context.scene);let r=e.results;this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),r||(this.defaultRaycastOptions.results||(this.defaultRaycastOptions.results=new Array),r=this.defaultRaycastOptions.results),e.layerMask!==void 0?e.layerMask instanceof Rr?i.layers.mask=e.layerMask.mask:i.layers.mask=e.layerMask:(i.layers.enableAll(),i.layers.disable(2)),ww&&(_t.DrawRay(i.ray.origin,i.ray.direction,16711680,2),console.time("raycast")),r.length=0,this.intersect(this.raycaster,n,r,e),r.sort((a,l)=>a.distance-l.distance);const o=e.ignore;return o!==void 0&&o.length>0&&(r=r.filter(a=>!o.includes(a.object))),ww&&(console.timeEnd("raycast"),console.warn("#"+this.context.time.frame+", hits:",r!=null&&r.length?[...r]:"nothing")),r}intersect(e,t,i,n){var r;for(const o of t){if(!o||o.visible===!1||_t.isGizmo(o)||n.lineThreshold!==void 0&&n.lineThreshold<0&&o instanceof Dn)continue;const a=(r=n.testObject)==null?void 0:r.call(n,o);if(a===!1)continue;if(a!=="continue in children"){const c=o,h=c.geometry;if(h){const u=O_(o);u&&(c.geometry=u);const f=i.length;e.intersectObject(o,!1,i),ww&&i.length!=f&&_t.DrawWireMesh({mesh:o,depthTest:!1,duration:.2,color:u?8969557:7798784}),c.geometry=h}}n.recursive!==!1&&this.intersect(e,o.children,i,n)}return i}}const Mde=ie("debugplayerview");var sd=(s=>(s.Browser="browser",s.Headset="headset",s.Handheld="handheld",s))(sd||{});class Q6{constructor(e,t){d(this,"userId");d(this,"context");d(this,"viewDevice","browser");d(this,"removed",!1);d(this,"_object");this.userId=e,this.context=t}get currentObject(){return this._object}set currentObject(e){this._object=e}get isConnected(){return this.context.connection.userIsInRoom(this.userId)}}class j6{constructor(e){d(this,"context");d(this,"playerViews",new Map);this.context=e}setPlayerView(e,t,i){let n=this.playerViews.get(e);n||(n=new Q6(e,this.context),this.playerViews.set(e,n)),n.viewDevice=i,n.currentObject=t,n.removed=!1}getPlayerView(e){if(!e)return;if(!this.context.connection.userIsInRoom(e)){this.playerViews.delete(e);return}return this.playerViews.get(e)}removePlayerView(e,t){const i=this.playerViews.get(e);(i==null?void 0:i.viewDevice)===t&&(Mde&&console.log("REMOVE",e),i.removed=!0,this.playerViews.delete(e))}}new Or;const G_=new Uint8Array(4);G_[0]=255;G_[1]=255;G_[2]=255;G_[3]=255;const Tde=new $o(G_,1,1,nn);function QO(s,e=1){const t="alpha"in s,i=e*e,n=new Uint8Array(4*i),r=Math.floor(s.r*255),o=Math.floor(s.g*255),a=Math.floor(s.b*255);for(let c=0;c<i;c++){const h=c*4;n[h+0]=r,n[h+1]=o,n[h+2]=a,t?n[h+3]=Math.floor(s.alpha*255):n[h+3]=255}const l=new $o(n,e,e);return l.needsUpdate=!0,l}function Ide(s,e,t,i=1,n=3){const o=i*n,a=[s,e,t],l=a.length,c=new Uint8Array(4*l*o),h=new Ae;for(let f=0;f<n;f++){const p=Math.floor(f/n*l),m=it.clamp(p+1,0,l-1),y=a[p],g=a[m],v=f/n*l%1;h.lerpColors(y,g,v);const _=Math.floor(h.r*255),A=Math.floor(h.g*255),b=Math.floor(h.b*255);for(let S=0;S<i;S++){const E=(f*i+S)*4;c[E+0]=_,c[E+1]=A,c[E+2]=b,c[E+3]=255}}const u=new $o(c,i,n);return u.needsUpdate=!0,u}function BC(s,e){const t=s.elements;e||(e=[]),e.length=0;for(let i=0;i<16;i+=4){const n=t[i],r=t[i+1],o=t[i+2],a=t[i+3],l=new Ze(n,r,o,a);e.push(l)}return e}const RI=[],pz=[];function Rde(s,e){if(RI.length===0)for(let t=0;t<27;t++)RI.push(0);e||(e=RI);for(let t=0;t<27;t++)pz[t]=e[t];e=pz,s.unity_SHAr={value:new Ze(e[9],e[3],e[6],e[0])},s.unity_SHBr={value:new Ze(e[12],e[15],e[18],e[21])},s.unity_SHAg={value:new Ze(e[10],e[4],e[7],e[1])},s.unity_SHBg={value:new Ze(e[13],e[16],e[19],e[22])},s.unity_SHAb={value:new Ze(e[11],e[5],e[8],e[2])},s.unity_SHBb={value:new Ze(e[14],e[17],e[20],e[23])},s.unity_SHC={value:new Ze(e[24],e[25],e[26],1)}}class Pde{constructor(e,t,i){d(this,"vertexShader");d(this,"fragmentShader");d(this,"technique");this.vertexShader=e,this.fragmentShader=t,this.technique=i}}async function Bde(s,e){if(!s)return console.error("Can not find technique: no shader data"),null;const t=s.programs[e],i=t.vertexShader,n=t.fragmentShader;if(i!==void 0&&n!==void 0){const r=s.shaders[i],o=s.shaders[n];if(r.uri&&o.uri||r.code&&o.code){if(!r.code&&r.uri&&await mz(r),!o.code&&o.uri&&await mz(o),!r.code||!o.code)return null;const a=s.techniques[e];return new Pde(r.code,o.code,a)}}return console.error("Shader technique not found",e),null}async function mz(s){const e=s.uri;if(e)if(e.endsWith(".glsl")){const i=await new Or().loadAsync(e);s.code=i.toString()}else s.code=Dde(s.uri)}function Dde(s){return decodeURIComponent(Array.prototype.map.call(atob(s),function(e){return"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)}).join(""))}const hl=ie("debugenvlight");var Yg=(s=>(s[s.Skybox=0]="Skybox",s[s.Trilight=1]="Trilight",s[s.Flat=3]="Flat",s[s.Custom=4]="Custom",s))(Yg||{}),DC=(s=>(s[s.Skybox=0]="Skybox",s[s.Custom=1]="Custom",s))(DC||{});class W6{constructor(e){d(this,"context");d(this,"_currentLightSettingsId");d(this,"_sceneLightSettings");d(this,"_timevec4",new Ze);d(this,"__currentReflectionId",null);d(this,"_lighting",{});this.context=e,this.context.pre_update_callbacks.push(this.preUpdate.bind(this))}preUpdate(){const e=this.context.time;this._timevec4.x=e.time,this._timevec4.y=Math.sin(e.time),this._timevec4.z=Math.cos(e.time),this._timevec4.w=e.deltaTime}get timeVec4(){return this._timevec4}get environmentIntensity(){if(!this._sceneLightSettings||!this._currentLightSettingsId)return 1;const e=this._sceneLightSettings.get(this._currentLightSettingsId);return e?e.ambientIntensity:1}get sceneLightSettings(){var e;return(e=this._sceneLightSettings)==null?void 0:e.values()}enable(e){var i;e instanceof Zt&&(e=e.uri);const t=(i=this._sceneLightSettings)==null?void 0:i.get(e);return t?(hl&&console.log("Enable scene light settings",e,t),e!==this._currentLightSettingsId&&this._currentLightSettingsId&&this.disable(this._currentLightSettingsId),this._currentLightSettingsId=e,t.enabled=!0,!0):(hl&&console.warn("No light settings found for",e),!1)}disable(e){var i;if(e instanceof Zt&&(e=e.uri),e==null)return!1;const t=(i=this._sceneLightSettings)==null?void 0:i.get(e);return t?(hl&&console.log("Disable scene light settings",e,t),t.enabled=!1,!0):!1}disableCurrent(){if(this._currentLightSettingsId){const e=this._currentLightSettingsId;return this.disable(this._currentLightSettingsId),e}return null}internalRegisterSceneLightSettings(e){const t=e.sourceId;if(!t){console.error("Missing source id for scene light settings, can not register:",e);return}hl&&console.log("Register "+(e==null?void 0:e.sourceId)+" lighting",e),this._sceneLightSettings||(this._sceneLightSettings=new Map),this._sceneLightSettings.set(t,e)}internalUnregisterSceneLightSettings(e){const t=e.sourceId;if(!t){console.error("Missing source id for scene light settings, can not unregister:",e);return}hl&&console.log("Unregister "+(e==null?void 0:e.sourceId)+" lighting",e),this._sceneLightSettings&&this._sceneLightSettings.delete(t)}internalRegisterReflection(e,t){hl&&console.log("Register reflection",e,t);const i=new q6(this.context,t,1);this._lighting[e]=i}internalGetReflection(e){return this._lighting[e]}internalEnableReflection(e){var i;this.__currentReflectionId=e;const t=(i=this._sceneLightSettings)==null?void 0:i.get(e);switch(hl&&console.log("Enable reflection",e,t?Yg[t.ambientMode]:"Unknown ambient mode",t),t==null?void 0:t.ambientMode){case 0:case 4:const n=this.internalGetReflection(e);if(n&&n.Source){hl&&console.log("Setting environment reflection",n);const r=this.context.scene,o=n.Source;o.mapping=xo,r.environment=o;return}else hl&&console.warn("Could not find reflection for source",e);break}if((t==null?void 0:t.environmentReflectionSource)===1)switch(t==null?void 0:t.ambientMode){case 1:if(t.ambientTrilight){const n=t.ambientTrilight,r=Ide(n[0],n[1],n[2],64,64);r.colorSpace=At,r.mapping=xo,this.context.scene.environment=r}else console.error("Missing ambient trilight",t.sourceId);return;case 3:if(t.ambientLight){const n=QO(t.ambientLight,64);n.colorSpace=At,n.mapping=xo,this.context.scene.environment=n}else console.error("Missing ambientlight",t.sourceId);return;default:return}}internalDisableReflection(e){if(e&&e!==this.__currentReflectionId){hl&&console.log("Not disabling reflection for",e,"because it is not the current light settings id",this.__currentReflectionId);return}hl&&console.log("Disable reflection",e);const t=this.context.scene;t.environment=null}}class q6{constructor(e,t,i=1){d(this,"_source");this._source=t,t.mapping=xo}get Source(){return this._source}}const gz=ie("timescale");let EB=1;typeof gz=="number"&&(EB=gz);class X6{constructor(){d(this,"_time",0);d(this,"_deltaTime",0);d(this,"_deltaTimeUnscaled",0);d(this,"timeScale",1);d(this,"_frame",0);d(this,"clock",new iD);d(this,"_smoothedFps",0);d(this,"_smoothedDeltaTime",0);d(this,"_fpsSamples",[]);d(this,"_fpsSampleIndex",0);typeof EB=="number"&&(this.timeScale=EB)}get time(){return this._time}set time(e){this._time=e}get deltaTime(){return this._deltaTime}set deltaTime(e){this._deltaTime=e}get deltaTimeUnscaled(){return this._deltaTimeUnscaled}get frame(){return this._frame}set frame(e){this._frame=e}get frameCount(){return this.frame}get realtimeSinceStartup(){return this.clock.elapsedTime}get smoothedFps(){return this._smoothedFps}get smoothedDeltaTime(){return 1/this._smoothedFps}update(){this.deltaTime=this.clock.getDelta(),this.deltaTime=Math.min(.1,this.deltaTime),this._deltaTimeUnscaled=this.deltaTime,this.deltaTime<=0&&(this.deltaTime=1e-12),this.deltaTime*=this.timeScale,this.frame+=1,this.time+=this.deltaTime,this._fpsSamples.length<60?this._fpsSamples.push(this.deltaTime):this._fpsSamples[this._fpsSampleIndex++%60]=this.deltaTime;let e=0;for(let t=0;t<this._fpsSamples.length;t++)e+=this._fpsSamples[t];this._smoothedDeltaTime=e/this._fpsSamples.length,this._smoothedFps=1/this._smoothedDeltaTime}}let yz=!1;function Y6(s){yz||(yz=!0,Ode(),Lde())}Y6();function Ode(){const s=`
|
|
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 ${h.method} on object ${f.name}`,f,typeof f[h.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 Efe=Object.defineProperty,Mfe=Object.getOwnPropertyDescriptor,XO=(s,e,t,i)=>{for(var n=i>1?void 0:i?Mfe(e,t):e,r=s.length-1,o;r>=0;r--)(o=s[r])&&(n=(i?o(e,t,n):o(n))||n);return i&&n&&Efe(e,t,n),n};class Up extends Ie{constructor(){super(...arguments);d(this,"constraintActive",!0);d(this,"locked",!1);d(this,"sources",[])}}XO([x()],Up.prototype,"constraintActive",2);XO([x()],Up.prototype,"locked",2);XO([x(ve)],Up.prototype,"sources",2);function Tfe(s,e){return Ed(s,Ii.ContextCreated,e),()=>Md(s,Ii.ContextCreated)}function Ife(s,e){return Ed(s,Ii.ContextClearing,e),()=>Md(s,Ii.ContextClearing)}function Rfe(s,e){return Ed(s,Ii.ContextDestroying,e),()=>Md(s,Ii.ContextDestroying)}function Sj(s,e){return Ed(s,$i.Start,e),()=>Md(s,$i.Start)}function Cj(s,e){return Ed(s,$i.Update,e),()=>Md(s,$i.Update)}function Pfe(s,e){return Ed(s,$i.OnBeforeRender,e),()=>Md(s,$i.OnBeforeRender)}function Bfe(s,e){return Ed(s,$i.OnAfterRender,e),()=>Md(s,$i.OnAfterRender)}class sp{constructor(){d(this,"bb",null);d(this,"bb_pos",0)}__init(e,t){return this.bb_pos=e,this.bb=t,this}x(){return this.bb.readFloat32(this.bb_pos)}y(){return this.bb.readFloat32(this.bb_pos+4)}z(){return this.bb.readFloat32(this.bb_pos+8)}static sizeOf(){return 12}static createVec3(e,t,i,n){return e.prep(4,12),e.writeFloat32(n),e.writeFloat32(i),e.writeFloat32(t),e.offset()}}class Ej{constructor(){d(this,"bb",null);d(this,"bb_pos",0)}__init(e,t){return this.bb_pos=e,this.bb=t,this}position(e){return(e||new sp).__init(this.bb_pos,this.bb)}rotation(e){return(e||new sp).__init(this.bb_pos+12,this.bb)}scale(e){return(e||new sp).__init(this.bb_pos+24,this.bb)}static sizeOf(){return 36}static createTransform(e,t,i,n,r,o,a,l,c,h){return e.prep(4,36),e.prep(4,12),e.writeFloat32(h),e.writeFloat32(c),e.writeFloat32(l),e.prep(4,12),e.writeFloat32(a),e.writeFloat32(o),e.writeFloat32(r),e.prep(4,12),e.writeFloat32(n),e.writeFloat32(i),e.writeFloat32(t),e.offset()}}class Sh{constructor(){d(this,"bb",null);d(this,"bb_pos",0)}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsSyncedTransformModel(e,t){return(t||new Sh).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSyncedTransformModel(e,t){return e.setPosition(e.position()+OO),(t||new Sh).__init(e.readInt32(e.position())+e.position(),e)}guid(e){const t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}fast(){const e=this.bb.__offset(this.bb_pos,6);return e?!!this.bb.readInt8(this.bb_pos+e):!1}transform(e){const t=this.bb.__offset(this.bb_pos,8);return t?(e||new Ej).__init(this.bb_pos+t,this.bb):null}dontSave(){const e=this.bb.__offset(this.bb_pos,10);return e?!!this.bb.readInt8(this.bb_pos+e):!1}static startSyncedTransformModel(e){e.startObject(4)}static addGuid(e,t){e.addFieldOffset(0,t,0)}static addFast(e,t){e.addFieldInt8(1,+t,0)}static addTransform(e,t){e.addFieldStruct(2,t,0)}static addDontSave(e,t){e.addFieldInt8(3,+t,0)}static endSyncedTransformModel(e){return e.endObject()}static finishSyncedTransformModelBuffer(e,t){e.finish(t)}static finishSizePrefixedSyncedTransformModelBuffer(e,t){e.finish(t,void 0,!0)}}var Ts=(s=>(s[s.Average=0]="Average",s[s.Multiply=1]="Multiply",s[s.Minimum=2]="Minimum",s[s.Maximum=3]="Maximum",s))(Ts||{}),wE=(s=>(s[s.Discrete=0]="Discrete",s[s.Continuous=1]="Continuous",s))(wE||{}),Gn=(s=>(s[s.None=0]="None",s[s.FreezePositionX=2]="FreezePositionX",s[s.FreezePositionY=4]="FreezePositionY",s[s.FreezePositionZ=8]="FreezePositionZ",s[s.FreezePosition=14]="FreezePosition",s[s.FreezeRotationX=16]="FreezeRotationX",s[s.FreezeRotationY=32]="FreezeRotationY",s[s.FreezeRotationZ=64]="FreezeRotationZ",s[s.FreezeRotation=112]="FreezeRotation",s[s.FreezeAll=126]="FreezeAll",s))(Gn||{}),Bg=(s=>(s[s.None=0]="None",s[s.X=2]="X",s[s.Y=4]="Y",s[s.Z=8]="Z",s[s.All=-1]="All",s))(Bg||{});const ur=function(s,e){return function(t,i,n){Dfe(t,i,n,s,e)}};function Dfe(s,e,t,i,n){if(!n&&!i&&!s.onValidate)return;if(t!==void 0){console.error("Invalid usage of validate decorator. Only fields can be validated.",s,e,t),pn("Invalid usage of validate decorator. Only fields can be validated. Property: "+e,Yo.Error);return}let r="";if(typeof e=="string"?r=e:r=e.name,s.__internalAwake){const o=Symbol(r),a=s.__internalAwake;s.__internalAwake=function(){var l;if(!this.onValidate){lt()&&console.warn('Usage of @validate decorate detected but there is no onValidate method in your class: "'+((l=s.constructor)==null?void 0:l.name)+'"');return}if(this[o]===void 0){this[o]=this[r];const c=this[r];if(c instanceof ee||c instanceof w||c instanceof Ze||c instanceof Ce){const h=this[r];G1(h,()=>{this.onValidate(r)})}Object.defineProperty(this,r,{set:function(h){var u;if(this[uB]===!0)this[o]=h;else{i==null||i.call(this,h);const f=this[o];this[o]=h,(u=this.onValidate)==null||u.call(this,r,f)}},get:function(){return n==null||n.call(this),this[o]}})}a.call(this)}}}const Ofe=function(s){return function(e,t,i){let n="";typeof t=="string"?n=t:n=t.name;const r=s.prototype,o=Object.getOwnPropertyDescriptor(r,n);if(!(o!=null&&o.value)){console.warn("Can not apply prefix: type does not have method named",t,s);return}const a=o.value,l=e[n];Object.defineProperty(r,n,{value:function(...c){const h=l==null?void 0:l.call(this,...c);if(h instanceof Promise){h.then(u=>{if(u!==!1)return a.call(this,...c)});return}if(h!==!1)return a.call(this,...c)}})}};var Lfe=Object.defineProperty,kfe=Object.getOwnPropertyDescriptor,ra=(s,e,t,i)=>{for(var n=i>1?void 0:i?kfe(e,t):e,r=s.length-1,o;r>=0;r--)(o=s[r])&&(n=(i?o(e,t,n):o(n))||n);return i&&n&&Lfe(e,t,n),n};class Ffe{constructor(e,t){d(this,"positionChanged",!1);d(this,"rotationChanged",!1);d(this,"position");d(this,"quaternion");d(this,"_positionKeys",["x","y","z"]);d(this,"_quaternionKeys",["_x","_y","_z","_w"]);d(this,"mute",!1);d(this,"context");d(this,"obj");d(this,"_positionWatch");d(this,"_rotationWatch");this.context=t,this.obj=e}get isDirty(){return this.positionChanged||this.rotationChanged}reset(e=!1){if(this.positionChanged=!1,this.rotationChanged=!1,this.mute=!1,e){if(this.position)for(const t of this._positionKeys)delete this.position[t];if(this.quaternion)for(const t of this._quaternionKeys)delete this.quaternion[t]}}syncValues(){for(const e of this._positionKeys)this.position[e]=this.obj.position[e];for(const e of this._quaternionKeys)this.quaternion[e]=this.obj.quaternion[e]}applyValues(){if(this.positionChanged&&this.position)for(const e of this._positionKeys){const t=this.position[e];t!==void 0&&(this.obj.position[e]=t)}if(this.rotationChanged&&this.quaternion)for(const e of this._quaternionKeys){const t=this.quaternion[e];t!==void 0&&(this.obj.quaternion[e]=t)}}start(e,t){this.reset(),e&&(this._positionWatch||(this._positionWatch=new Dh(this.obj.position,["x","y","z"])),this._positionWatch.apply(),this.position={},this._positionWatch.subscribeWrite((r,o)=>{var l;if((l=this.context.physics.engine)!=null&&l.isUpdating||this.mute)return;const a=this.position[o];Math.abs(a-r)<1e-5||(this.position[o]=r,this.positionChanged=!0)})),t&&(this._rotationWatch||(this._rotationWatch=new Dh(this.obj.quaternion,["_x","_y","_z","_w"])),this._rotationWatch.apply(),this.quaternion={},this._rotationWatch.subscribeWrite((r,o)=>{var l;if((l=this.context.physics.engine)!=null&&l.isUpdating||this.mute)return;const a=this.quaternion[o];Math.abs(a-r)<1e-5||(this.quaternion[o]=r,this.rotationChanged=!0)}));const i=this.obj.matrixWorld.multiplyMatrices.bind(this.obj.matrixWorld),n=new ye;this.obj.matrixWorld.multiplyMatrices=(r,o)=>{var a;return(a=this.context.physics.engine)!=null&&a.isUpdating||this.mute||n.equals(r)||(this.positionChanged=!0,this.rotationChanged=!0,n.copy(r)),i(r,o)}}stop(){var e,t;(e=this._positionWatch)==null||e.revoke(),(t=this._rotationWatch)==null||t.revoke()}}var AR;const DB=(AR=class extends Ie{constructor(){super(...arguments);d(this,"autoMass",!0);d(this,"_mass",0);d(this,"useGravity",!0);d(this,"centerOfMass",new w(0,0,0));d(this,"constraints",Gn.None);d(this,"isKinematic",!1);d(this,"drag",0);d(this,"angularDrag",1);d(this,"detectCollisions",!0);d(this,"sleepThreshold",.01);d(this,"collisionDetectionMode",wE.Discrete);d(this,"_gravityScale",1);d(this,"dominanceGroup",0);d(this,"_propertiesChanged",!1);d(this,"_currentVelocity",new w);d(this,"_smoothedVelocity",new w);d(this,"_smoothedVelocityGetter",new w);d(this,"_lastPosition",new w);d(this,"_watch")}set mass(e){e!==this._mass&&(this._mass=e,this._propertiesChanged=!0,this.__didAwake&&(this.autoMass=!1))}get mass(){var e,t;return this.autoMass?((t=(e=this.context.physics.engine)==null?void 0:e.getBody(this))==null?void 0:t.mass())??-1:this._mass}get lockPositionX(){return(this.constraints&Gn.FreezePositionX)!==0}get lockPositionY(){return(this.constraints&Gn.FreezePositionY)!==0}get lockPositionZ(){return(this.constraints&Gn.FreezePositionZ)!==0}get lockRotationX(){return(this.constraints&Gn.FreezeRotationX)!==0}get lockRotationY(){return(this.constraints&Gn.FreezeRotationY)!==0}get lockRotationZ(){return(this.constraints&Gn.FreezeRotationZ)!==0}set lockPositionX(e){e?this.constraints|=Gn.FreezePositionX:this.constraints&=~Gn.FreezePositionX}set lockPositionY(e){e?this.constraints|=Gn.FreezePositionY:this.constraints&=~Gn.FreezePositionY}set lockPositionZ(e){e?this.constraints|=Gn.FreezePositionZ:this.constraints&=~Gn.FreezePositionZ}set lockRotationX(e){e?this.constraints|=Gn.FreezeRotationX:this.constraints&=~Gn.FreezeRotationX}set lockRotationY(e){e?this.constraints|=Gn.FreezeRotationY:this.constraints&=~Gn.FreezeRotationY}set lockRotationZ(e){e?this.constraints|=Gn.FreezeRotationZ:this.constraints&=~Gn.FreezeRotationZ}set gravityScale(e){this._gravityScale=e}get gravityScale(){return this._gravityScale}awake(){this._watch=void 0,this._propertiesChanged=!1}onEnable(){this._watch||(this._watch=new Ffe(this.gameObject,this.context)),this._watch.start(!0,!0),this.startCoroutine(this.beforePhysics(),$i.LateUpdate)}onDisable(){var e,t;(e=this._watch)==null||e.stop(),(t=this.context.physics.engine)==null||t.removeBody(this)}onDestroy(){var e;(e=this.context.physics.engine)==null||e.removeBody(this)}onValidate(){this._propertiesChanged=!0}*beforePhysics(){var e,t,i,n;for(;;)this._propertiesChanged&&(this._propertiesChanged=!1,(e=this.context.physics.engine)==null||e.updateProperties(this)),(t=this._watch)!=null&&t.isDirty?(this._watch.mute=!0,this._watch.applyValues(),(i=this.context.physics.engine)==null||i.updateBody(this,this._watch.positionChanged,this._watch.rotationChanged),this._watch.reset()):(n=this._watch)==null||n.syncValues(),this.captureVelocity(),yield}teleport(e,t=!0){var i;(i=this._watch)==null||i.reset(!0),t?this.gameObject.position.set(e.x,e.y,e.z):this.setWorldPosition(e.x,e.y,e.z),this.resetForcesAndTorques(),this.resetVelocities()}resetForces(e=!0){var t;(t=this.context.physics.engine)==null||t.resetForces(this,e)}resetTorques(e=!0){var t;(t=this.context.physics.engine)==null||t.resetTorques(this,e)}resetVelocities(){this.setVelocity(0,0,0),this.setAngularVelocity(0,0,0)}resetForcesAndTorques(){this.resetForces(),this.resetTorques()}wakeUp(){var e;(e=this.context.physics.engine)==null||e.wakeup(this)}get isSleeping(){var e;return(e=this.context.physics.engine)==null?void 0:e.isSleeping(this)}updateProperties(){var e;return this._propertiesChanged=!1,(e=this.context.physics.engine)==null?void 0:e.updateProperties(this)}applyForce(e,t,i=!0){var n;this._propertiesChanged&&this.updateProperties(),(n=this.context.physics.engine)==null||n.addForce(this,e,i)}applyImpulse(e,t=!0){var i;this._propertiesChanged&&this.updateProperties(),(i=this.context.physics.engine)==null||i.applyImpulse(this,e,t)}setForce(e,t,i,n=!0){var r,o,a;(r=this.context.physics.engine)==null||r.resetForces(this,n),typeof e=="number"?(t??(t=0),i??(i=0),(o=this.context.physics.engine)==null||o.addForce(this,{x:e,y:t,z:i},n)):(a=this.context.physics.engine)==null||a.addForce(this,e,n)}getVelocity(){var t;const e=(t=this.context.physics.engine)==null?void 0:t.getLinearVelocity(this);return e?(this._currentVelocity.x=e.x,this._currentVelocity.y=e.y,this._currentVelocity.z=e.z,this._currentVelocity):this._currentVelocity.set(0,0,0)}setVelocity(e,t,i,n=!0){var r,o;if(e instanceof w){const a=e;(r=this.context.physics.engine)==null||r.setLinearVelocity(this,a,n);return}t===void 0||i===void 0||(o=this.context.physics.engine)==null||o.setLinearVelocity(this,{x:e,y:t,z:i},n)}getAngularVelocity(){var t;const e=(t=this.context.physics.engine)==null?void 0:t.getAngularVelocity(this);return e?(this._currentVelocity.x=e.x,this._currentVelocity.y=e.y,this._currentVelocity.z=e.z,this._currentVelocity):this._currentVelocity.set(0,0,0)}setAngularVelocity(e,t,i,n=!0){var r,o;if(e instanceof w){const a=e;(r=this.context.physics.engine)==null||r.setAngularVelocity(this,a,n);return}t===void 0||i===void 0||(o=this.context.physics.engine)==null||o.setAngularVelocity(this,{x:e,y:t,z:i},n)}setTorque(e,t,i){this.setAngularVelocity(e,t,i)}get smoothedVelocity(){return this._smoothedVelocityGetter.copy(this._smoothedVelocity),this._smoothedVelocityGetter.multiplyScalar(1/this.context.time.deltaTime)}setBodyFromGameObject(e=null){}captureVelocity(){const e=kt(this.gameObject);DB.tempPosition.copy(e);const t=e.sub(this._lastPosition);this._lastPosition.copy(DB.tempPosition),this._smoothedVelocity.lerp(t,this.context.time.deltaTime/.1)}},d(AR,"tempPosition",new w),AR);let zi=DB;ra([ur()],zi.prototype,"autoMass",2);ra([x()],zi.prototype,"mass",1);ra([ur(),x()],zi.prototype,"useGravity",2);ra([x(w)],zi.prototype,"centerOfMass",2);ra([ur(),x()],zi.prototype,"constraints",2);ra([ur(),x()],zi.prototype,"isKinematic",2);ra([ur(),x()],zi.prototype,"drag",2);ra([ur(),x()],zi.prototype,"angularDrag",2);ra([ur(),x()],zi.prototype,"detectCollisions",2);ra([ur(),x()],zi.prototype,"sleepThreshold",2);ra([ur(),x()],zi.prototype,"collisionDetectionMode",2);ra([ur()],zi.prototype,"_gravityScale",2);ra([ur()],zi.prototype,"dominanceGroup",2);const Pu=ie("debugsync"),X0="STRS";kO(X0,Sh.getRootAsSyncedTransformModel);const zl=new U_;function Mj(s,e,t=!0){zl.clear();const i=zl.createString(s);Sh.startSyncedTransformModel(zl),Sh.addGuid(zl,i),Sh.addFast(zl,t);const n=e.worldPosition,r=e.worldEuler,o=e.gameObject.scale;Sh.addTransform(zl,Ej.createTransform(zl,n.x,n.y,n.z,r.x,r.y,r.z,o.x,o.y,o.z));const a=Sh.endSyncedTransformModel(zl);return zl.finish(a,X0),zl.asUint8Array()}let OB=0,i0=0;Cj(s=>{var i;const t=((i=s.connection.currentServerUrl)==null?void 0:i.includes("glitch"))?10:40;i0=Math.floor(OB/t),OB=0,Pu&&i0>0&&console.log("Sync Transform Fast Interval",i0)});class pd extends Ie{constructor(){super(...arguments);d(this,"overridePhysics",!0);d(this,"interpolatePosition",!0);d(this,"interpolateRotation",!0);d(this,"fastMode",!1);d(this,"syncDestroy",!1);d(this,"_model",null);d(this,"_needsUpdate",!0);d(this,"rb",null);d(this,"_wasKinematic",!1);d(this,"_receivedDataBefore",!1);d(this,"_targetPosition");d(this,"_targetRotation");d(this,"_receivedFastUpdate",!1);d(this,"_shouldRequestOwnership",!1);d(this,"joinedRoomCallback",null);d(this,"receivedDataCallback",null);d(this,"tempEuler",new oi);d(this,"receivedUpdate",!1);d(this,"lastWorldPos");d(this,"lastWorldRotation")}requestOwnership(){Pu&&console.log("Request ownership"),this._model?this._model.requestOwnership():(this._shouldRequestOwnership=!0,this._needsUpdate=!0)}hasOwnership(){var t;return((t=this._model)==null?void 0:t.hasOwnership)??void 0}isOwned(){var t;return(t=this._model)==null?void 0:t.isOwned}awake(){Pu&&console.log("new instance",this.guid,this),this._receivedDataBefore=!1,this._targetPosition=new w,this._targetRotation=new Ce,this.lastWorldPos=new w,this.lastWorldRotation=new Ce,this.rb=re.getComponentInChildren(this.gameObject,zi),this.rb&&(this._wasKinematic=this.rb.isKinematic),this.receivedUpdate=!0,this._model=new HO(this.context.connection,this.guid),this.context.connection.isConnected&&this.tryGetLastState(),this.joinedRoomCallback=this.tryGetLastState.bind(this),this.context.connection.beginListen(Xt.JoinedRoom,this.joinedRoomCallback),this.receivedDataCallback=this.onReceivedData.bind(this),this.context.connection.beginListenBinary(X0,this.receivedDataCallback)}onDestroy(){this.syncDestroy&&jO(this.guid,this.context.connection),this._model=null,this.context.connection.stopListen(Xt.JoinedRoom,this.joinedRoomCallback),this.context.connection.stopListenBinary(X0,this.receivedDataCallback)}tryGetLastState(){const t=this.context.connection.tryGetState(this.guid);t&&this.onReceivedData(t)}onReceivedData(t){var i;if(!this.destroyed&&typeof t.guid=="function"&&t.guid()===this.guid){Pu&&console.log("new data",this.context.connection.connectionId,this.context.time.frameCount,this.guid,t),this.receivedUpdate=!0,this._receivedFastUpdate=t.fast();const n=t.transform();if(n){Fa.markDirty(this.gameObject,!0);const r=n.position();r&&(this.interpolatePosition&&((i=this._targetPosition)==null||i.set(r.x(),r.y(),r.z())),(!this.interpolatePosition||!this._receivedDataBefore)&&this.setWorldPosition(r.x(),r.y(),r.z()));const o=n.rotation();o&&(this.tempEuler.set(o.x(),o.y(),o.z()),this.interpolateRotation&&this._targetRotation.setFromEuler(this.tempEuler),(!this.interpolateRotation||!this._receivedDataBefore)&&HD(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){Pu&&console.log("no model or room",this.name,this.guid,this.context.connection.isInRoom);return}this._shouldRequestOwnership&&(this._shouldRequestOwnership=!1,this._model.requestOwnership());const t=this.worldPosition,i=this.worldQuaternion;if(this._model.isOwned&&!this.receivedUpdate){const o=t.distanceTo(this.lastWorldPos),a=i.angleTo(this.lastWorldRotation),l=this._model.hasOwnership||this.fastMode?1e-4:.001;(o>l||a>l)&&(this._model.hasOwnership?this._needsUpdate=!0:(Pu&&console.log(this.guid,"reset because not owned but",this.gameObject.name,this.lastWorldPos),this.worldPosition=this.lastWorldPos,t.copy(this.lastWorldPos),this.worldQuaternion=this.lastWorldRotation,i.copy(this.lastWorldRotation),Fa.markDirty(this.gameObject,!0),this._needsUpdate=!1))}if(this._model&&!this._model.hasOwnership&&this._model.isOwned&&this._receivedDataBefore){const a=this._receivedFastUpdate||this.fastMode?.5:.3;let l=!1;if(this.interpolatePosition&&this._targetPosition){const c=this.worldPosition;c.lerp(this._targetPosition,a),this.worldPosition=c,l=!0}if(this.interpolateRotation&&this._targetRotation){const c=this.worldQuaternion;c.slerp(this._targetRotation,a),this.worldQuaternion=c,l=!0}l&&Fa.markDirty(this.gameObject,!0)}if(this.receivedUpdate=!1,this.lastWorldPos.copy(t),this.lastWorldRotation.copy(i),!this._model||!this._model||this._model.hasOwnership===void 0||!this._model.hasOwnership)return;this.rb&&this.overridePhysics&&this._wasKinematic!==void 0&&(Pu&&console.log("reset kinematic",this.rb.name,this._wasKinematic),this.rb.isKinematic=this._wasKinematic);const n=10,r=this.rb||this.fastMode;if(this._needsUpdate&&(this.context.time.frameCount%n===0||r)){if(OB++,r&&i0>0&&this.context.time.frameCount%i0!==0)return;Pu&&console.log("send update",this.context.connection.connectionId,this.guid,this.gameObject.name,this.gameObject.guid),this._needsUpdate=!1;const o=Mj(this.guid,this,!!r);this.context.connection.sendBinary(o)}}}const Ufe=ie("debugshadowcomponents");LD.prototype.interactable={get(){return this.interactive},set(s){this.interactable=s}};const Da=Symbol("shadowDomOwner");class Ha extends Ie{constructor(){super(...arguments);d(this,"_shadowComponent",null);d(this,"_controlsChildLayout",!0);d(this,"_root");d(this,"_parentComponent")}isRoot(){var t;return((t=this.Root)==null?void 0:t.gameObject)===this.gameObject}get canvas(){const t=this.Root;return t!=null&&t.isCanvas?t:null}get Canvas(){return this.canvas}markDirty(){bo.markUIDirty(this.context)}get shadowComponent(){return this._shadowComponent}set shadowComponent(t){this._shadowComponent=t}get controlsChildLayout(){return this._controlsChildLayout}set controlsChildLayout(t){this._controlsChildLayout=t,this.shadowComponent&&(this.shadowComponent.autoLayout=t)}get Root(){return this._root===void 0&&(this._root=re.getComponentInParent(this.gameObject,X_)),this._root}__internalNewInstanceCreated(t){return super.__internalNewInstanceCreated(t),this.shadowComponent=null,this._root=void 0,this._parentComponent=void 0,this}onEnable(){super.onEnable()}addShadowComponent(t,i){var o;if(!t)return;this.removeShadowComponent();const n=this.isRoot()?this.gameObject:this.gameObject.parent;if(this._parentComponent=re.getComponentInParent(n,Ha),!this._parentComponent){console.warn(`Component "${this.name}" doesn't have a UI parent anywhere. Do you have an UI element outside a Canvas? UI components must be a child of a Canvas component`,this);return}t.name=this.name+" ("+(this.constructor.name??"UI")+")",t.autoLayout=this._parentComponent.controlsChildLayout,t[Da]=this,this.setShadowComponentOwner(t);let r=!1;if(((o=this.Root)==null?void 0:o.gameObject)===this.gameObject)this.gameObject.add(t);else{const a=this._parentComponent.shadowComponent;a&&(a==null||a.add(t),r=!0)}this.shadowComponent=t,i&&i.shadowComponent&&this.shadowComponent&&i.shadowComponent.add(this.shadowComponent),F_&&t.add(new na(.5)),this.onAfterAddedToScene(),r&&C5(),Ufe&&console.warn("Added shadow component",this.shadowComponent)}setShadowComponentOwner(t){if(t&&(t[Da]===void 0||t[Da]===this)&&(t[Da]=this,t.children))for(const i of t.children)this.setShadowComponentOwner(i)}traverseOwnedShadowComponents(t,i,n){if(t&&t[Da]===i){n(t);for(const r of t.children)this.traverseOwnedShadowComponents(r,i,n)}}removeShadowComponent(){this.shadowComponent&&this.shadowComponent.removeFromParent()}onAfterAddedToScene(){}setInteractable(t){this.shadowComponent&&(this.shadowComponent.interactable=t)}}class X_ extends Ha{awake(){super.awake()}}class zy{constructor(e,t){d(this,"event");d(this,"button");d(this,"buttonName");d(this,"_used",!1);d(this,"_propagationStopped",!1);d(this,"z__pointer_ctured",!1);d(this,"z__pointer_cture_rleased",!1);d(this,"inputSource");d(this,"object");d(this,"point");d(this,"normal");d(this,"face");d(this,"distance");d(this,"instanceId");d(this,"intersection");d(this,"isDown");d(this,"isUp");d(this,"isPressed");d(this,"isClick");d(this,"isDoubleClick");d(this,"input");this.event=t,this.input=e,this.button=t.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 e=new zy(this.input,this.event);return Object.assign(e,this),e}Use(){this.use()}StopPropagation(){this.event.stopImmediatePropagation()}}function LB(s,e){return re.foreachComponent(s,i=>{if(!i.enabled)return;const n=i;if(e)switch(e){case"pointerdown":if(n.onPointerDown)return!0;break;case"pointerup":if(n.onPointerUp||n.onPointerClick)return!0;break;case"pointermove":if(n.onPointerEnter||n.onPointerExit||n.onPointerMove)return!0;break}else if(n.onPointerDown||n.onPointerUp||n.onPointerEnter||n.onPointerExit||n.onPointerClick)return!0},!1)===!0}var Nfe=Object.defineProperty,zfe=Object.getOwnPropertyDescriptor,Gfe=(s,e,t,i)=>{for(var n=i>1?void 0:i?zfe(e,t):e,r=s.length-1,o;r>=0;r--)(o=s[r])&&(n=(i?o(e,t,n):o(n))||n);return i&&n&&Nfe(e,t,n),n};class Y_ extends Ie{awake(){bo.createIfNoneExists(this.context)}onEnable(){var e;(e=bo.get(this.context))==null||e.register(this)}onDisable(){var e;(e=bo.get(this.context))==null||e.unregister(this)}}class sa extends Y_{constructor(){super(...arguments);d(this,"targets",null);d(this,"raycastHits",[]);d(this,"ignoreSkinnedMeshes",!1)}start(){this.targets=[this.gameObject]}performRaycast(t=null){if(!this.targets)return null;t??(t=new Il),t.targets=this.targets,t.results=this.raycastHits;const i=t.testObject;this.ignoreSkinnedMeshes&&(t.testObject=r=>r instanceof wo?"continue in children":i?i(r):!0);const n=this.context.physics.raycast(t);return t.testObject=i,n}}Gfe([x()],sa.prototype,"ignoreSkinnedMeshes",2);class SE extends sa{constructor(){super(),this.ignoreSkinnedMeshes=!0}}class Y0 extends Y_{performRaycast(e){if(!xt.active||!(e!=null&&e.ray))return null;const t=e.ray.origin,i=.01;return this.context.physics.sphereOverlap(t,i)}}class CE{static getObject(e){const t=e[Da];return t&&(t.isComponent===!0?e=t.gameObject:e=t),e}static isInteractable(e,t){if(t&&(t.canvasGroup=void 0,t.graphic=void 0),e==null||!e.visible||(e=this.getObject(e),!e.visible))return!1;const i=this.tryFindCanvasGroup(e);if((i==null?void 0:i.isCanvasGroup)===!0&&(t&&(t.canvasGroup=i),i.blocksRaycasts===!1||i.interactable===!1))return!1;const n=Ep(e,r=>{if(r.isGraphic===!0)return r},!1);return t&&(n==null?void 0:n.isGraphic)===!0&&(t.graphic=n),!((n==null?void 0:n.raycastTarget)===!1||(n==null?void 0:n.layer)===2)}static tryFindCanvasGroup(e){if(!e)return null;const t=Ep(e,i=>{const n=i;if(n.blocksRaycasts!==void 0&&n.interactable!==void 0)return n},!1);return t!==void 0?t:this.tryFindCanvasGroup(e.parent)}}function YO(s){const e=s[Da];return e||(s.parent?YO(s.parent):null)}function Hfe(s){return s.isUI===!0||typeof s[Da]=="object"}function FC(s,e){if(!s)return;const t=s.material;if((t==null?void 0:t.isMaterial)===!0){const i=s.parent;i&&i.isText,t.side=e.doubleSided??!0?xi:ys,t.shadowSide=e.doubleSided?xi:ys,s.castShadow=e.castShadows?e.castShadows:!1,s.receiveShadow=e.receiveShadows?e.receiveShadows:!1}for(const i of s.children)FC(i,e)}function pg(s,e,t){s[e]===void 0&&console.warn("Field",e,"is undefined on",s);const i=Proxy.revocable(s[e],{set(o,a,l,c){const h=o[a],u=Reflect.set(o,a,l,c);return t(l,h),u}}),n=i.revoke,r=s[e];return i.revoke=()=>{s[e]=r,n()},s[e]=i.proxy,i}const Iz=Symbol("Scheduled action");function Vfe(s,e,t=$i.OnBeforeRender){let i=s[Iz];i||(i=s[Iz]={});const n=e.name;i[t]||(i[t]={});const r=i[t];if(r[n])return;function*a(){e==null||e.call(s),r[n]=null}const l=s.startCoroutine(a(),t);r[n]=l}const rh=ie("debugeventsystem");var kB=(s=>(s.BeforeHandleInput="BeforeHandleInput",s.AfterHandleInput="AfterHandleInput",s))(kB||{});const Jl=class extends Ie{constructor(){super();d(this,"raycaster",[]);d(this,"_handleInputFn");d(this,"pressedByID",new Map);d(this,"hoveredByID",new Map);d(this,"_sortedHits",[]);d(this,"_testObjectsCache",new Map);d(this,"_currentlyActiveRaycaster",null);d(this,"_currentPointerEventName",null);d(this,"shouldRaycastObject",t=>{var r;let i=null;if(Hfe(t)&&(i=(r=t[Da])==null?void 0:r.gameObject),this._testObjectsCache.has(t)||i&&this._testObjectsCache.has(i))return this._testObjectsCache.get(t)===!1?"continue in children":!0;{let o=LB(t,this._currentPointerEventName);if(!o&&i&&(o=LB(i,this._currentPointerEventName)),o){this._testObjectsCache.set(t,!0);for(const a of t.children)this.shouldRaycastObject_AddToYesCache(a);return!0}return this._testObjectsCache.set(t,!1),"continue in children"}});d(this,"_sortingBuffer",[]);d(this,"_noDepthTestingResults",[]);d(this,"out",{});d(this,"_capturedPointer",{});d(this,"pointerEnterSymbol",Symbol("pointerEnter"));d(this,"pointerExitSymbol",Symbol("pointerExit"));d(this,"currentActiveMeshUIComponents",[]);Jl.systems.push(this)}static createIfNoneExists(t){this.didSearchEventSystem||(this.didSearchEventSystem=!0,Jl.systems.length<=0&&Jl.systems.push(...re.findObjectsOfType(Jl,t)));for(const n of Jl.systems)if(n.context===t)return;const i=new ve;re.addNewComponent(i,Jl),t.scene.add(i)}static get systems(){const t=Ot.Current;return this._eventSystemMap.has(t)||this._eventSystemMap.set(t,[]),this._eventSystemMap.get(t)}static get(t){const i=this._eventSystemMap.get(t);return i&&i.length>0?i[0]:null}static get instance(){return this.systems[0]}static ensureUpdateMeshUI(t,i,n=!1){zu.update(t,i,n)}static markUIDirty(t){zu.markDirty()}get hasActiveUI(){return this.currentActiveMeshUIComponents.length>0}get isHoveringObjects(){return this.hoveredByID.size>0}onDestroy(){Jl.systems.splice(Jl.systems.indexOf(this),1)}start(){if(this.raycaster.length<=0&&!re.findObjectOfType(Y_,this.context)){const i=re.addNewComponent(this.context.scene,sa);this.raycaster.push(i),(lt()||rh)&&console.warn("Added an ObjectRaycaster to the scene because no raycaster was found.")}}register(t){var i;t&&this.raycaster&&!this.raycaster.includes(t)&&((i=this.raycaster)==null||i.push(t))}unregister(t){var n,r;const i=(n=this.raycaster)==null?void 0:n.indexOf(t);i!==void 0&&i!==-1&&((r=this.raycaster)==null||r.splice(i,1))}onEnable(){this._handleInputFn??(this._handleInputFn=this.onPointerEvent.bind(this)),this.context.input.addEventListener(fn.PointerDown,this._handleInputFn),this.context.input.addEventListener(fn.PointerUp,this._handleInputFn),this.context.input.addEventListener(fn.PointerMove,this._handleInputFn)}onDisable(){this.context.input.removeEventListener(fn.PointerDown,this._handleInputFn),this.context.input.removeEventListener(fn.PointerUp,this._handleInputFn),this.context.input.removeEventListener(fn.PointerMove,this._handleInputFn)}onBeforeRender(){this.resetMeshUIStates()}onPointerEvent(t){if(t===void 0||t.propagationStopped)return;const i=new zy(this.context.input,t);this._currentPointerEventName=t.type,i.inputSource=this.context.input,i.isClick=t.isClick,i.isDoubleClick=t.isDoubleClick,i.isDown=t.type==fn.PointerDown,i.isUp=t.type==fn.PointerUp,i.isPressed=this.context.input.getPointerPressed(t.pointerId),rh&&(i.isDown?console.log("DOWN",i.pointerId):i.isUp&&console.log("UP",i.pointerId),i.isClick&&console.log("CLICK",i.pointerId));const n=new Il;t.hasRay?n.ray=t.ray:n.screenPoint=this.context.input.getPointerPositionRC(t.pointerId);const r=this.performRaycast(n);if(r){for(const a of r)a.event=t,t.intersections.push(a);t.origin.onPointerHits&&t.origin.onPointerHits({sender:this,event:t,hits:r})}rh&&i.isClick&&pn("EventSystem: "+i.pointerId+" - "+this.context.time.frame+" - Up:"+i.isUp+", Down:"+i.isDown);const o={sender:this,args:i,hasActiveUI:this.currentActiveMeshUIComponents.length>0};this.dispatchEvent(new CustomEvent("BeforeHandleInput",{detail:o})),this.handleIntersections(r,i),this.dispatchEvent(new CustomEvent("AfterHandleInput",{detail:o}))}shouldRaycastObject_AddToYesCache(t){this._testObjectsCache.set(t,!0);for(const i of t.children)this.shouldRaycastObject_AddToYesCache(i)}performRaycast(t){if(!this.raycaster)return null;this._testObjectsCache.clear(),this._sortedHits.length=0,t||(t=new Il),t.testObject=this.shouldRaycastObject;for(const i of this.raycaster){if(!i.activeAndEnabled)continue;this._currentlyActiveRaycaster=i;const n=i.performRaycast(t);this._currentlyActiveRaycaster=null,n&&n.length>0&&this._sortedHits.push(...n)}return this._sortedHits.sort((i,n)=>i.distance-n.distance),this._sortedHits}assignHitInformation(t,i){i?(t.intersection=i,t.point=i.point,t.normal=i.normal,t.face=i.face,t.distance=i.distance,t.instanceId=i.instanceId):(t.intersection=void 0,t.point=void 0,t.normal=void 0,t.face=void 0,t.distance=void 0,t.instanceId=void 0)}handleIntersections(t,i){var r;if(t!=null&&t.length){t=this.sortCandidates(t);for(const o of t){if(i.event.immediatePropagationStopped)return!1;if(this.assignHitInformation(i,o),this.handleEventOnObject(o.object,i))return!0}}this.assignHitInformation(i,t==null?void 0:t[0]),this.invokePointerCapture(i);const n=this.hoveredByID.get(i.pointerId);return n&&this.propagatePointerExit(n.obj,n.data,null),this.hoveredByID.delete(i.pointerId),i.isUp&&((r=this.pressedByID.get(i.pointerId))==null||r.handlers.forEach(o=>this.invokeOnPointerUp(i,o)),this.pressedByID.delete(i.pointerId)),!1}sortCandidates(t){this._sortingBuffer.length=0,this._noDepthTestingResults.length=0;for(let i=0;i<t.length;i++){const n=t[i],r=n.object;if(r.material&&r.material.depthTest===!1){this._noDepthTestingResults.push(n);continue}this._sortingBuffer.push(n)}for(const i of this._sortingBuffer)this._noDepthTestingResults.push(i);return this._noDepthTestingResults}handleEventOnObject(t,i){if(!this.testIsVisible(t))return i.isClick&&rh&&console.log("not allowed",t),!1;if(i.pointerId===void 0)return rh&&console.error("Event without pointer can't be handled",i),!1;i.object=t;const n=t.parent,r=i.isClick??!1;let o=null;if(n&&n.isUI){const u=(i.isPressed||i.isClick)??!1;if(n[Da]){const f=n[Da].gameObject;if(f){if(!CE.isInteractable(f,this.out))return!1;o=this.out.canvasGroup??null,this.handleMeshUIIntersection(t,u),t=f}}}r&&rh&&console.log(this.context.time.frame,t);const a=this.hoveredByID.get(i.pointerId),l=a==null?void 0:a.obj;l!==t&&l&&this.propagatePointerExit(l,a.data,t);const h=this.hoveredByID.get(i.pointerId);if(h?(h.obj=t,h.data=i):this.hoveredByID.set(i.pointerId,{obj:t,data:i}),i.isDown){const u=this.pressedByID.get(i.pointerId);u?(u.obj=t,u.data=i):this.pressedByID.set(i.pointerId,{obj:t,data:i,handlers:new Set})}return(o===null||o.interactable)&&this.handleMainInteraction(t,i,l??null),!0}propagate(t,i){for(;t;)re.foreachComponent(t,n=>{i(n)},!1),t=t.parent}handleMainInteraction(t,i,n){const r=this.pressedByID.get(i.pointerId),o=n!==t;let a=!0;switch(i.event.pointerType){case"mouse":case"touch":const l=this.context.input.getPointerPositionLastFrame(i.pointerId),c=this.context.input.getPointerPosition(i.pointerId);a=l&&!it.approximately(l,c);break}this.propagate(t,l=>{var h;const c=l;c.interactable!==!1&&(!c.activeAndEnabled||!c.enabled||(c.onPointerEnter&&o&&this.handlePointerEnter(c,i),i.isDown&&c.onPointerDown&&(c.onPointerDown(i),r==null||r.handlers.add(c),this.handlePointerCapture(i,c)),c.onPointerMove&&(a&&c.onPointerMove(i),this.handlePointerCapture(i,c)),i.isUp&&(c.onPointerUp&&(this.invokeOnPointerUp(i,c),r==null||r.handlers.delete(c)),c.onPointerExit&&((h=i.event)==null?void 0:h.pointerType)===uE.Touch&&(this.handlePointerExit(c,i),this.hoveredByID.delete(i.pointerId))),i.isClick&&c.onPointerClick&&c.onPointerClick(i)))}),i.isUp&&(r==null||r.handlers.forEach(l=>{this.invokeOnPointerUp(i,l)}),this.pressedByID.delete(i.pointerId))}propagatePointerExit(t,i,n){this.propagate(t,r=>{if(!r.gameObject||r.destroyed)return;const o=r;if(o.onPointerExit){if(n&&this.isChild(n,r.gameObject))return;this.handlePointerExit(o,i)}})}invokeOnPointerUp(t,i){var n;(n=i.onPointerUp)==null||n.call(i,t),this.releasePointerCapture(t,i)}handlePointerEnter(t,i){t.onPointerEnter&&this.updatePointerState(t,i.pointerId,this.pointerEnterSymbol,!0)&&t.onPointerEnter(i),this.updatePointerState(t,i.pointerId,this.pointerExitSymbol,!1)}handlePointerExit(t,i){t.onPointerExit&&this.updatePointerState(t,i.pointerId,this.pointerExitSymbol,!0)&&t.onPointerExit(i),this.updatePointerState(t,i.pointerId,this.pointerEnterSymbol,!1)}updatePointerState(t,i,n,r){let o=t[n];if(r)return o&&o.includes(i)?!1:(o=o||[],o.push(i),t[n]=o,!0);{if(!o||!o.includes(i))return!1;const a=o.indexOf(i);return a!==-1&&o.splice(a,1),!0}}handlePointerCapture(t,i){if(t.z__pointer_ctured){t.z__pointer_ctured=!1;const n=t.pointerId;if(i.onPointerMove){const r=this._capturedPointer[n]||[];r.push(i),this._capturedPointer[n]=r}else lt()&&!i.z__warned_no_pointermove&&(i.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 t.z__pointer_cture_rleased&&(t.z__pointer_cture_rleased=!1,this.releasePointerCapture(t,i))}releasePointerCapture(t,i){const n=t.pointerId;if(this._capturedPointer[n]){const r=this._capturedPointer[n].indexOf(i);r!==-1&&(this._capturedPointer[n].splice(r,1),rh&&console.log("released pointer capture",n,i,this._capturedPointer))}}invokePointerCapture(t){var i;if(t.event.type===fn.PointerMove){const n=t.pointerId,r=this._capturedPointer[n];if(r){rh&&console.log("Captured",n,r);for(let o=0;o<r.length;o++){const a=r[o];if(a.destroyed){r.splice(o,1),o--;continue}(i=a.onPointerMove)==null||i.call(a,t)}}}}isChild(t,i){return!t||!i?!1:t===i?!0:t.parent?this.isChild(t.parent,i):!1}handleMeshUiObjectWithoutShadowDom(t,i){return!t||!t.isUI?!0:this.handleMeshUIIntersection(t,i)}handleMeshUIIntersection(t,i){const n=zu.updateState(t,i);return n&&this.currentActiveMeshUIComponents.push(n),n!==null}resetMeshUIStates(){if(this.context.input.getPointerPressedCount()>0&&zu.resetLastSelected(),!(!this.currentActiveMeshUIComponents||this.currentActiveMeshUIComponents.length<=0)){for(let t=0;t<this.currentActiveMeshUIComponents.length;t++){const i=this.currentActiveMeshUIComponents[t];zu.resetState(i)}this.currentActiveMeshUIComponents.length=0}}testIsVisible(t){return t?re.isActiveSelf(t)?this.testIsVisible(t.parent):!1:!0}};let bo=Jl;d(bo,"_eventSystemMap",new Map),d(bo,"didSearchEventSystem",!1);class zu{static markDirty(){this.needsUpdate=!0}static update(e,t,i=!1){if(i){e.update();return}const n=t.time.frameCount;for(const r of this.lastUpdateFrame)if(r.context===t){if(n===r.frame)return;r.frame=n;let o=this.needsUpdate||n<1;r.nextUpdate===t.time.frameCount&&(o=!0),o&&(rh&&console.log("Update threemeshui"),this.needsUpdate=!1,e.update());return}this.lastUpdateFrame=[{context:t,frame:n,nextUpdate:n}],e.update()}static updateState(e,t){let i=null;if(e&&(i=this.findBlockInParent(e),i&&i!==this.lastSelected)){if(i.interactable===!1)return null;this.needsUpdate=!0}return i}static resetLastSelected(){const e=this.lastSelected;e&&(this.lastSelected=null,this.resetState(e))}static resetState(e){e&&(this.needsUpdate=!0)}static findBlockInParent(e){return e?e.isBlock?e:this.findBlockInParent(e.parent):null}}d(zu,"lastSelected",null),d(zu,"lastUpdateFrame",[]),d(zu,"needsUpdate",!1);var Qfe=Object.defineProperty,jfe=Object.getOwnPropertyDescriptor,yn=(s,e,t,i)=>{for(var n=i>1?void 0:i?jfe(e,t):e,r=s.length-1,o;r>=0;r--)(o=s[r])&&(n=(i?o(e,t,n):o(n))||n);return i&&n&&Qfe(e,t,n),n};const DI=ie("debugorbit"),Ew=ie("freecam"),Mw=ie("debugcamerafit"),Tw=ie("smoothcam"),Wfe={LEFT:"",UP:"",RIGHT:"",BOTTOM:""};let OI;class K0 extends CustomEvent{constructor(e,t){super("target-reached",{detail:{controls:e,type:t}})}}class wi extends Ie{constructor(){super(...arguments);d(this,"autoTarget",!0);d(this,"autoFit",!1);d(this,"enableRotate",!0);d(this,"autoRotate",!1);d(this,"autoRotateSpeed",1);d(this,"minAzimuthAngle",1/0);d(this,"maxAzimuthAngle",1/0);d(this,"minPolarAngle",0);d(this,"maxPolarAngle",Math.PI);d(this,"enableKeys",!0);d(this,"enableDamping",!0);d(this,"dampingFactor",.1);d(this,"enableZoom",!0);d(this,"minZoom",0);d(this,"maxZoom",1/0);d(this,"zoomSpeed",1);d(this,"zoomToCursor",!1);d(this,"enablePan",!0);d(this,"lookAtConstraint",null);d(this,"lookAtConstraint01",1);d(this,"allowInterrupt",!0);d(this,"middleClickToFocus",!0);d(this,"doubleClickToFocus",!0);d(this,"clickBackgroundToFitScene",2);d(this,"debugLog",!1);d(this,"targetLerpDuration",1);d(this,"_controls",null);d(this,"_cameraObject",null);d(this,"_lookTargetLerpActive",!1);d(this,"_lookTargetStartPosition",new w);d(this,"_lookTargetEndPosition",new w);d(this,"_lookTargetLerp01",0);d(this,"_lookTargetLerpDuration",0);d(this,"_cameraLerpActive",!1);d(this,"_cameraStartPosition",new w);d(this,"_cameraEndPosition",new w);d(this,"_cameraLerp01",0);d(this,"_cameraLerpDuration",0);d(this,"_inputs",0);d(this,"_enableTime",0);d(this,"_startedListeningToKeyEvents",!1);d(this,"_eventSystem");d(this,"_afterHandleInputFn");d(this,"_camera",null);d(this,"_syncedTransform");d(this,"_didSetTarget",0);d(this,"targetElement",null);d(this,"_lastTimeClickOnBackground",-1);d(this,"_clickOnBackgroundCount",0);d(this,"_onPointerDown",t=>{if(this.clickBackgroundToFitScene>0&&t.isClick&&t.button===0){if(t.hasRay||t.intersections.push(...this.context.physics.raycast()),t.intersections.length<=0){const i=this.context.time.time-this._lastTimeClickOnBackground;this._lastTimeClickOnBackground=this.context.time.time,this.clickBackgroundToFitScene<=1||i<this.clickBackgroundToFitScene*.15?(this._clickOnBackgroundCount+=1,this._clickOnBackgroundCount>=this.clickBackgroundToFitScene-1&&this.fitCamera(this.context.scene.children,{immediate:!1})):this._clickOnBackgroundCount=0}DI&&console.log(this.clickBackgroundToFitScene,t.intersections.length,this._clickOnBackgroundCount)}});d(this,"onControlsChangeStarted",()=>{this._syncedTransform&&this._syncedTransform.requestOwnership()});d(this,"_shouldDisable",!1);d(this,"__onPreRender",()=>{const t=this.context.pre_render_callbacks.indexOf(this.__onPreRender);t>=0&&this.context.pre_render_callbacks.splice(t,1),this.autoFit&&(this.autoFit=!1,this.fitCamera(this.scene.children,{centerCamera:"y",immediate:!0}))});d(this,"_haveAttachedKeyboardEvents",!1)}get isCameraController(){return!0}get controls(){return this._controls}get controllerObject(){return this._cameraObject}onStartInteraction(t){var i;(i=this.controls)==null||i.addEventListener("start",t)}get targetLerpSpeed(){return 5}set targetLerpSpeed(t){this.targetLerpDuration=1/t}awake(){this._didSetTarget=0,this._startedListeningToKeyEvents=!1}start(){this._eventSystem=bo.get(this.context)??void 0,this._eventSystem&&(this._afterHandleInputFn=this.afterHandleInput.bind(this),this._eventSystem.addEventListener(kB.AfterHandleInput,this._afterHandleInputFn))}onDestroy(){var t,i;(t=this._controls)==null||t.dispose(),(i=this._eventSystem)==null||i.removeEventListener(kB.AfterHandleInput,this._afterHandleInputFn)}onEnable(){this._didSetTarget=0,this._enableTime=this.context.time.time;const t=re.getComponent(this.gameObject,Gi);this._camera=t;let i=t==null?void 0:t.cam;if(!i&&this.gameObject instanceof Gt&&(i=this.gameObject),i&&TP(i,this,!0),!this._controls&&i instanceof Gt){this._cameraObject=i;const n=this.targetElement??this.context.renderer.domElement,r=i==null?void 0:i.quaternion.clone();this._controls=new wj(i,n),i==null||i.quaternion.copy(r),OI===void 0&&(OI={...this._controls.keys})}this._controls&&(Ew&&(this.enablePan=!0,this.enableZoom=!0,this.middleClickToFocus=!0,qa()&&(this.doubleClickToFocus=!0)),this._controls.addEventListener("start",this.onControlsChangeStarted),(i==null?void 0:i.type)==="PerspectiveCamera"?Ew||(this._controls.minDistance=this.minZoom,this._controls.maxDistance=this.maxZoom):Ew||(this._controls.minZoom=this.minZoom,this._controls.maxZoom=this.maxZoom),this._startedListeningToKeyEvents||(this._startedListeningToKeyEvents=!0,this._controls.listenToKeyEvents(window.document.body))),this._syncedTransform=re.getComponent(this.gameObject,pd)??void 0,this.context.input.addEventListener("pointerup",this._onPointerDown),this.context.pre_render_callbacks.push(this.__onPreRender)}onDisable(){var t;(t=this._camera)!=null&&t.cam&&TP(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(t){t.detail.args.pointerId===0&&(t.detail.args.isDown?this._controls&&this._eventSystem&&(this._shouldDisable=this._eventSystem.hasActiveUI):(!t.detail.args.isPressed||t.detail.args.isUp)&&(this._shouldDisable=!1))}onBeforeRender(){var i,n;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)&&((i=this.context.input.getPointerPositionDelta(0))!=null&&i.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 r=re.getComponent(this.gameObject,Gi);if(r&&!this.setLookTargetFromConstraint()){this.debugLog&&console.log("NO TARGET");const o=kt(r.cam),a=Math.max(.01,o.length()),l=new w(0,0,-a).applyMatrix4(r.cam.matrixWorld);this.setLookTargetPosition(l,!0)}if(!this.setLookTargetFromConstraint()){const o=new Il;o.screenPoint=new ee(0,0),o.lineThreshold=.1;const a=this.context.physics.raycast(o);a.length>0&&this.setLookTargetPosition(a[0].point,!0),Mw&&console.log("OrbitControls hits",...a)}}let t=this.middleClickToFocus&&this.context.input.getPointerClicked(1);if(t||(t=this.doubleClickToFocus&&this.context.input.getPointerDoubleClicked(0)&&this.context.time.time-this._enableTime>.3),t&&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 K0(this,"camera"));else{const r=it.easeInOutCubic(this._cameraLerp01);this._cameraObject.position.lerpVectors(this._cameraStartPosition,this._cameraEndPosition,r)}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 K0(this,"lookat"));else{const r=it.easeInOutCubic(this._lookTargetLerp01);this._controls.target.lerpVectors(this._lookTargetStartPosition,this._lookTargetEndPosition,r)}}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?OI:Wfe,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 Tw=="number"||Tw===!0){this._controls.enableDamping=!0;const r=typeof Tw=="number"?Tw:.99;this._controls.dampingFactor=Math.max(.001,1-Math.min(1,r))}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||(!Ew&&((n=this.lookAtConstraint)!=null&&n.locked)&&this.setLookTargetFromConstraint(0,this.lookAtConstraint01),this._controls.update(),DI&&_t.DrawWireSphere(this._controls.target,.1,65280))}}setCameraAndLookTarget(t){if(!t||!(t instanceof ve))return;const i=kt(t),n=zD(t);this.setTargetFromRaycast(new Mo(i,n)),this.setCameraTargetPosition(i)}setCameraTargetPosition(t,i=!1){var n,r;t&&(t instanceof ve&&(t=kt(t)),this._cameraEndPosition||(this._cameraEndPosition=new w),this._cameraEndPosition.copy(t),i===!0?(this._cameraLerpActive=!1,(n=this.controllerObject)==null||n.position.copy(this._cameraEndPosition)):this._cameraObject&&(this._cameraLerpActive=!0,this._cameraLerp01=0,this._cameraStartPosition.copy((r=this._cameraObject)==null?void 0:r.position),typeof i=="number"?this._cameraLerpDuration=i:this._cameraLerpDuration=this.targetLerpDuration))}get cameraLerpActive(){return this._cameraLerpActive}stopCameraLerp(){this._cameraLerpActive=!1}setLookTargetPosition(t=null,i=!1){this._controls&&t&&(t instanceof ve&&(t=kt(t)),this._lookTargetEndPosition.copy(t),DI&&(console.warn("OrbitControls: setLookTargetPosition",t,i),_t.DrawWireSphere(this._lookTargetEndPosition,.2,16711680,2)),i===!0?this._controls.target.copy(this._lookTargetEndPosition):(this._lookTargetLerpActive=!0,this._lookTargetLerp01=0,this._lookTargetStartPosition.copy(this._controls.target),typeof i=="number"?this._lookTargetLerpDuration=i:this._lookTargetLerpDuration=this.targetLerpDuration))}get lookTargetLerpActive(){return this._lookTargetLerpActive}stopLookTargetLerp(){this._lookTargetLerpActive=!1}setLookTargetFromConstraint(t=0,i=1){var r;if(!this._controls)return!1;const n=(r=this.lookAtConstraint)==null?void 0:r.sources;if(n&&n.length>0){const o=n[t];if(o)return o.getWorldPosition(this._lookTargetEndPosition),this.lerpLookTarget(this._lookTargetEndPosition,i),!0}return!1}lerpTarget(t,i){return this.lerpLookTarget(t,i)}lerpLookTarget(t,i){this._controls&&(i>=1?this._controls.target.copy(t):this._controls.target.lerp(t,i))}setTargetFromRaycast(t){if(!this.controls)return;const i=t?this.context.physics.raycastFromRay(t):this.context.physics.raycast();for(const n of i)if(n.distance>0&&re.isActiveInHierarchy(n.object)){const r=YO(n.object);if(r){const o=r.canvas;if(o!=null&&o.screenspace)break}this.setLookTargetPosition(n.point);break}}fitCamera(t,i={fitOffset:void 0,immediate:!1}){if(this.context.isInXR)return;const{immediate:n=!1,centerCamera:r}=i;let{fitOffset:o}=i;o==null&&(o=1.1);const a=this._cameraObject,l=this._controls;if(t!=null&&t.length||(t=this.context.scene.children),t.length<=0){console.warn("No objects to fit camera to...");return}if(!a||!l){console.warn("No camera or controls found to fit camera to objects...");return}const c=new w,h=new w,u=Sc(t,void 0);a.updateMatrixWorld(),a.updateProjectionMatrix(),u.getCenter(h);const f=new w;if(u.getSize(f),u.applyMatrix4(a.matrixWorldInverse),u.getSize(c),u.setFromCenterAndSize(h,c),Number.isNaN(c.x)||Number.isNaN(c.y)||Number.isNaN(c.z)){console.warn("Camera fit size resultet in NaN",a,u,[...t]);return}if(c.length()<=1e-10){Mw&&console.warn("Camera fit size is zero",u,[...t]);return}const p=a.fov,m=2*Math.atan(Math.tan(p*Math.PI/360/2)*a.aspect)/Math.PI*360,y=c.y/(2*Math.atan(Math.PI*p/360)),g=c.x/(2*Math.atan(Math.PI*m/360)),v=o*Math.max(y,g)+c.z/2;Mw&&console.log("Fit camera to objects",y,g,"distance",v),l.maxDistance=v*10,l.minDistance=v*.01;const _=.05,A=h.clone();A.y-=c.y*_,this.setLookTargetPosition(A,n),this.autoTarget=!1;const b=re.findObjectOfType(Id),S=b?b.radius:0,E=Math.max(f.x,f.y,f.z,S);a.near=v/100,a.far=E+v*10,a.updateMatrixWorld(),a.updateProjectionMatrix();const M=kt(a),T=h.clone();if(T.sub(M),r==="y"&&(T.y=0),T.normalize(),T.multiplyScalar(v),r==="y"&&(T.y+=-_*4*c.y),a.parent){const R=a.parent.worldToLocal(h.clone().sub(T));this.setCameraTargetPosition(R,n)}else console.error(`Can not fit camera ${a.name} because it has no parent`);if(Mw){const R=new aD(u);this.context.scene.add(R),VD(R,R_(a)),setTimeout(()=>{this.context.scene.remove(R)},1e4),this._haveAttachedKeyboardEvents||(this._haveAttachedKeyboardEvents=!0,document.body.addEventListener("keydown",C=>{C.code==="KeyF"&&this.fitCamera(t,{fitOffset:o,immediate:n})}))}l.update()}}yn([x()],wi.prototype,"autoTarget",2);yn([x()],wi.prototype,"autoFit",2);yn([x()],wi.prototype,"enableRotate",2);yn([x()],wi.prototype,"autoRotate",2);yn([x()],wi.prototype,"autoRotateSpeed",2);yn([x()],wi.prototype,"minAzimuthAngle",2);yn([x()],wi.prototype,"maxAzimuthAngle",2);yn([x()],wi.prototype,"minPolarAngle",2);yn([x()],wi.prototype,"maxPolarAngle",2);yn([x()],wi.prototype,"enableKeys",2);yn([x()],wi.prototype,"enableDamping",2);yn([x()],wi.prototype,"dampingFactor",2);yn([x()],wi.prototype,"enableZoom",2);yn([x()],wi.prototype,"minZoom",2);yn([x()],wi.prototype,"maxZoom",2);yn([x()],wi.prototype,"zoomSpeed",2);yn([x()],wi.prototype,"enablePan",2);yn([x(Up)],wi.prototype,"lookAtConstraint",2);yn([x()],wi.prototype,"lookAtConstraint01",2);yn([x()],wi.prototype,"allowInterrupt",2);yn([x()],wi.prototype,"middleClickToFocus",2);yn([x()],wi.prototype,"doubleClickToFocus",2);yn([x()],wi.prototype,"clickBackgroundToFitScene",2);yn([x()],wi.prototype,"targetLerpDuration",2);var qfe=Object.defineProperty,Xfe=Object.getOwnPropertyDescriptor,lo=(s,e,t,i)=>{for(var n=i>1?void 0:i?Xfe(e,t):e,r=s.length-1,o;r>=0;r--)(o=s[r])&&(n=(i?o(e,t,n):o(n))||n);return i&&n&&qfe(e,t,n),n},od=(s=>(s[s.Skybox=1]="Skybox",s[s.SolidColor=2]="SolidColor",s[s.Uninitialized=4]="Uninitialized",s))(od||{});const dh=ie("debugcam"),Rz=ie("debugscreenpointtoray");var $w;const MA=($w=class extends Ie{constructor(){super(...arguments);d(this,"_nearClipPlane",.1);d(this,"_farClipPlane",1e3);d(this,"orthographic",!1);d(this,"orthographicSize",5);d(this,"ARBackgroundAlpha",0);d(this,"_cullingMask",4294967295);d(this,"_backgroundBlurriness",0);d(this,"_backgroundIntensity",1);d(this,"_backgroundRotation");d(this,"_environmentIntensity");d(this,"_targetTexture",null);d(this,"_backgroundColor");d(this,"_fov");d(this,"_cam",null);d(this,"_clearFlags",2);d(this,"_skybox");d(this,"_frustum");d(this,"_projScreenMatrix",new ye)}get isCamera(){return!0}get aspect(){return this._cam instanceof Gt?this._cam.aspect:this.context.domWidth/this.context.domHeight}set aspect(e){this._cam instanceof Gt&&this._cam.aspect!==e&&(this._cam.aspect=e,this._cam.updateProjectionMatrix())}get fieldOfView(){return this._cam instanceof Gt?this._cam.fov:this._fov}set fieldOfView(e){const t=this.fieldOfView!=e;if(this._fov=e,t&&this._cam&&this._cam instanceof Gt){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(e){const t=this._nearClipPlane!=e;this._nearClipPlane=e,this._cam&&t&&(this._cam.near=e,this._cam.updateProjectionMatrix())}get farClipPlane(){return this._farClipPlane}set farClipPlane(e){const t=this._farClipPlane!=e;this._farClipPlane=e,this._cam&&t&&(this._cam.far=e,this._cam.updateProjectionMatrix())}get clearFlags(){return this._clearFlags}set clearFlags(e){e!==this._clearFlags&&(this._clearFlags=e,this.applyClearFlagsIfIsActiveCamera())}set cullingMask(e){this._cullingMask=e,this._cam&&(this._cam.layers.mask=e)}get cullingMask(){return this._cam?this._cam.layers.mask:this._cullingMask}set cullingLayer(e){this.cullingMask=(1<<e|0)>>>0}set backgroundBlurriness(e){e!==this._backgroundBlurriness&&(e===void 0?this._backgroundBlurriness=void 0:this._backgroundBlurriness=Math.min(Math.max(e,0),1),this.applyClearFlagsIfIsActiveCamera())}get backgroundBlurriness(){return this._backgroundBlurriness}set backgroundIntensity(e){e!==this._backgroundIntensity&&(e===void 0?this._backgroundIntensity=void 0:this._backgroundIntensity=Math.min(Math.max(e,0),10),this.applyClearFlagsIfIsActiveCamera())}get backgroundIntensity(){return this._backgroundIntensity}set backgroundRotation(e){e!==this._backgroundRotation&&(e===void 0?this._backgroundRotation=void 0:this._backgroundRotation=e,this.applyClearFlagsIfIsActiveCamera())}get backgroundRotation(){return this._backgroundRotation}set environmentIntensity(e){this._environmentIntensity=e}get environmentIntensity(){return this._environmentIntensity}get backgroundColor(){return this._backgroundColor??null}set backgroundColor(e){if(e){if(this._backgroundColor)this._backgroundColor.copy(e);else{if(!e.clone)return;this._backgroundColor=e.clone()}e.alpha===void 0&&(this._backgroundColor.alpha=1),this.applyClearFlagsIfIsActiveCamera()}}set targetTexture(e){this._targetTexture=e}get targetTexture(){return this._targetTexture}get cam(){return this.activeAndEnabled&&this.buildCamera(),this._cam}screenPointToRay(e,t,i){const n=this.cam,r=MA._origin;r.set(e,t,-1),this.context.input.convertScreenspaceToRaycastSpace(r),Rz&&console.log("screenPointToRay",e.toFixed(2),t.toFixed(2),"now:",r.x.toFixed(2),r.y.toFixed(2),"isInXR:"+this.context.isInXR),r.z=-1,r.unproject(n);const o=MA._direction.set(r.x,r.y,r.z),a=kt(n);return o.sub(a),o.normalize(),i?(i.set(a,o),i):new Mo(a.clone(),o.clone())}getFrustum(){return this._frustum||(this._frustum=new mp,this.updateFrustum()),this._frustum}updateFrustum(){this._frustum||(this._frustum=new mp),this._frustum.setFromProjectionMatrix(this.getProjectionScreenMatrix(this._projScreenMatrix,!0),this.context.renderer.coordinateSystem)}getProjectionScreenMatrix(e,t){return t&&this._projScreenMatrix.multiplyMatrices(this.cam.projectionMatrix,this.cam.matrixWorldInverse),e===this._projScreenMatrix?e:e.copy(this._projScreenMatrix)}awake(){Rz&&window.addEventListener("pointerdown",e=>{const t=e.clientX,i=e.clientY;console.log("touch",t.toFixed(2),i.toFixed(2));const n=this.screenPointToRay(t,i),r="#"+Math.floor(Math.random()*16777215).toString(16);_t.DrawRay(n.origin,n.direction,r,10)})}onEnable(){dh&&console.log(`Camera enabled: "${this.name}". ClearFlags=${od[this._clearFlags]}`,this),this.buildCamera(),(this.tag=="MainCamera"||!this.context.mainCameraComponent)&&(this.context.setCurrentCamera(this),Kfe(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 e=this.context.renderer;if(e){const t=this.context.mainCameraComponent;this.applyClearFlags(),this._targetTexture.render(this.context.scene,this._cam,e),t==null||t.applyClearFlags()}}}buildCamera(){if(this._cam)return;const e=this.gameObject.isCamera;let t=null;if(e?(t=this.gameObject,t==null||t.layers.enableAll(),t instanceof Gt&&(this._fov=t.fov)):t=this.gameObject.children[0],t&&t.isCamera)t instanceof Gt&&(this._fov&&(t.fov=this._fov),t.near=this._nearClipPlane,t.far=this._farClipPlane,t.updateProjectionMatrix());else if(!this.orthographic)t=new Gt(this.fieldOfView,window.innerWidth/window.innerHeight,this._nearClipPlane,this._farClipPlane),this.fieldOfView&&(t.fov=this.fieldOfView),this.gameObject.add(t);else{const i=this.orthographicSize*100;t=new Mc(window.innerWidth/-i,window.innerWidth/i,window.innerHeight/i,window.innerHeight/-i,this._nearClipPlane,this._farClipPlane),this.gameObject.add(t)}this._cam=t,this._cam.layers.mask=this._cullingMask,this.tag=="MainCamera"&&this.context.setCurrentCamera(this)}applyClearFlagsIfIsActiveCamera(e){this.context.mainCameraComponent===this&&this.applyClearFlags(e)}applyClearFlags(e){if(!this._cam){dh&&console.log("Camera does not exist (apply clear flags)");return}if(this.fieldOfView=this._fov,dh){const t=`Camera "${this.name}" clear flags: ${od[this._clearFlags]}`;console.debug(t)}switch(this._clearFlags){case 1:if(MA.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||(e==null?void 0:e.applySkybox)===!0)&&this.applySceneSkybox(),this._backgroundBlurriness!==void 0?this.context.scene.backgroundBlurriness=this._backgroundBlurriness:dh&&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:dh&&console.warn(`Camera "${this.name}" has no background intensity`);break;case 2:if(this._backgroundColor){let t=this._backgroundColor.alpha;MA.backgroundShouldBeTransparent(this.context)&&(t=this.ARBackgroundAlpha??0),this.context.scene.background=null,this.context.renderer.setClearColor(this._backgroundColor,t)}else dh&&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 Yfe(this)),this._skybox.apply()}static backgroundShouldBeTransparent(e){var r,o,a,l;const t=(r=e.renderer.xr)==null?void 0:r.getSession();if(!t)return!1;if(typeof t._transparent=="boolean")return t._transparent;const i=t.environmentBlendMode;dh&&pn("Environment blend mode: "+i+" on "+navigator.userAgent);let n=i==="additive"||i==="alpha-blend";return e.isInAR&&i==="opaque"&&((o=navigator.userAgent)!=null&&o.includes("OculusBrowser")||(a=navigator.userAgent)!=null&&a.includes("Mozilla")&&((l=navigator.userAgent)!=null&&l.includes("Mobile WebXRViewer/v2")))&&(n=!0),t._transparent=n,n}},d($w,"_origin",new w),d($w,"_direction",new w),$w);let Gi=MA;lo([x()],Gi.prototype,"aspect",1);lo([x()],Gi.prototype,"fieldOfView",1);lo([x()],Gi.prototype,"nearClipPlane",1);lo([x()],Gi.prototype,"farClipPlane",1);lo([x()],Gi.prototype,"clearFlags",1);lo([x()],Gi.prototype,"orthographic",2);lo([x()],Gi.prototype,"orthographicSize",2);lo([x()],Gi.prototype,"ARBackgroundAlpha",2);lo([x()],Gi.prototype,"cullingMask",1);lo([x()],Gi.prototype,"backgroundBlurriness",1);lo([x()],Gi.prototype,"backgroundIntensity",1);lo([x(oi)],Gi.prototype,"backgroundRotation",1);lo([x()],Gi.prototype,"environmentIntensity",1);lo([x(Mi)],Gi.prototype,"backgroundColor",1);lo([x(rd)],Gi.prototype,"targetTexture",1);class Yfe{constructor(e){d(this,"_camera");d(this,"_skybox");this._camera=e}get context(){var e;return(e=this._camera)==null?void 0:e.context}apply(){this._skybox=this.context.lightmaps.tryGetSkybox(this._camera.sourceId),this._skybox?this.context.scene.background!==this._skybox&&(dh&&console.log(`Camera "${this._camera.name}" set skybox`,this._camera,this._skybox),this._skybox.mapping=xo,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)),(dh||lt())&&Ni(`Camera "${this._camera.name}" has no skybox texture`))}}function Kfe(s){ie("freecam")&&s.context.mainCameraComponent===s&&re.getOrAddComponent(s.gameObject,wi)}class ad extends Ie{constructor(){super(...arguments);d(this,"_listener",null);d(this,"onInteraction",()=>{this.destroyed||this.listener==null||this.addListenerIfItExists()})}get listener(){return this._listener==null&&(this._listener=new dV),this._listener}onEnable(){vc.registerWaitForInteraction(this.onInteraction),this.addListenerIfItExists()}onDisable(){vc.unregisterWaitForInteraction(this.onInteraction),this.removeListenerIfItExists()}addListenerIfItExists(){const t=this._listener;if(!t||t!=null&&t.parent)return;const i=this.context.mainCameraComponent||re.getComponentInParent(this.gameObject,Gi);i!=null&&i.cam?i.cam.add(t):this.gameObject.add(t),t.filter?(t.gain.connect(t.filter),t.filter.connect(t.context.destination)):t.gain.connect(t.context.destination)}removeListenerIfItExists(){const t=this._listener;t&&(t.removeFromParent(),t.filter&&t.filter.disconnect(),t.gain&&t.gain.disconnect())}}class Jfe extends Dn{constructor(e,t=1,i=16,n=2){const r=new wt,o=i+n*2,a=new Float32Array((o*3+3)*3);r.setAttribute("position",new ot(a,3));const l=new Zi({color:65280}),c=new Zi({color:16776960});super(r,[c,l]),this.audio=e,this.range=t,this.divisionsInnerAngle=i,this.divisionsOuterAngle=n,this.type="PositionalAudioHelper",this.update()}update(){const e=this.audio,t=this.range,i=this.divisionsInnerAngle,n=this.divisionsOuterAngle,r=fi.degToRad(e.panner.coneInnerAngle),o=fi.degToRad(e.panner.coneOuterAngle),a=r/2,l=o/2;let c=0,h=0,u,f;const p=this.geometry,m=p.attributes.position;p.clearGroups();function y(g,v,_,A){const b=(v-g)/_;for(m.setXYZ(c,0,0,0),h++,u=g;u<v;u+=b)f=c+h,m.setXYZ(f,Math.sin(u)*t,0,Math.cos(u)*t),m.setXYZ(f+1,Math.sin(Math.min(u+b,v))*t,0,Math.cos(Math.min(u+b,v))*t),m.setXYZ(f+2,0,0,0),h+=3;p.addGroup(c,h,A),c+=h,h=0}y(-l,-a,n,0),y(-a,a,i,1),y(a,l,n,0),m.needsUpdate=!0,r===o&&(this.material[0].visible=!1)}dispose(){this.geometry.dispose(),this.material[0].dispose(),this.material[1].dispose()}}var Zfe=Object.defineProperty,$fe=Object.getOwnPropertyDescriptor,Pc=(s,e,t,i)=>{for(var n=i>1?void 0:i?$fe(e,t):e,r=s.length-1,o;r>=0;r--)(o=s[r])&&(n=(i?o(e,t,n):o(n))||n);return i&&n&&Zfe(e,t,n),n};const br=ie("debugaudio"),Bu=class extends Ie{constructor(){super(...arguments);d(this,"clip","");d(this,"playOnAwake",!1);d(this,"preload",!1);d(this,"_spatialBlend",0);d(this,"_minDistance",1);d(this,"_maxDistance",100);d(this,"_volume",1);d(this,"rollOffMode",0);d(this,"playInBackground",!0);d(this,"_loop",!1);d(this,"sound",null);d(this,"helper",null);d(this,"wasPlaying",!1);d(this,"audioLoader",null);d(this,"shouldPlay",!1);d(this,"_lastClipStartedLoading",null);d(this,"_audioElement",null);d(this,"onVisibilityChanged",()=>{switch(document.visibilityState){case"hidden":(this.playInBackground===!1||qa())&&(this.wasPlaying=this.isPlaying,this.isPlaying&&this.pause());break;case"visible":br&&console.log("visible",this.enabled,this.playOnAwake,!this.isPlaying,Bu.userInteractionRegistered,this.wasPlaying),this.enabled&&this.playOnAwake&&!this.isPlaying&&Bu.userInteractionRegistered&&this.wasPlaying&&this.play();break}});d(this,"onApplicationMuteChanged",()=>{var e,t;this.context.application.muted?(e=this.sound)==null||e.setVolume(0):(t=this.sound)==null||t.setVolume(this.volume)});d(this,"createAudio",e=>{br&&console.log("AudioBuffer finished loading",e);const t=this.Sound;if(!t){br&&console.warn("Failed getting sound?",this.name);return}t.isPlaying&&t.stop(),e&&t.setBuffer(e),t.loop=this._loop,this.context.application.muted?t.setVolume(0):t.setVolume(this.volume),t.autoplay=this.shouldPlay&&Bu.userInteractionRegistered,this.applySpatialDistanceSettings(),t.isPlaying&&t.stop(),Bu.registerWaitForAllowAudio(this.__onAllowAudioCallback)});d(this,"__onAllowAudioCallback",()=>{this.shouldPlay&&this.play()});d(this,"_lastContextTime",0);d(this,"_hasEnded",!0);d(this,"_needUpdateSpatialDistanceSettings",!1)}static get userInteractionRegistered(){return vc.userInteractionRegistered}static registerWaitForAllowAudio(e){vc.registerWaitForAllowAudio(e)}get loop(){return this.sound&&(this._loop=this.sound.getLoop()),this._loop}set loop(e){this._loop=e,this.sound&&this.sound.setLoop(e)}get spatialBlend(){return this._spatialBlend}set spatialBlend(e){e!==this._spatialBlend&&(this._spatialBlend=e,this._needUpdateSpatialDistanceSettings=!0)}get minDistance(){return this._minDistance}set minDistance(e){this._minDistance!==e&&(this._minDistance=e,this._needUpdateSpatialDistanceSettings=!0)}get maxDistance(){return this._maxDistance}set maxDistance(e){this._maxDistance!==e&&(this._maxDistance=e,this._needUpdateSpatialDistanceSettings=!0)}get volume(){return this._volume}set volume(e){this._volume=e,this.sound&&!this.context.application.muted&&(br&&console.log(this.name,"audio set volume",e),this.sound.setVolume(e))}get Sound(){var e;if(!this.sound&&Bu.userInteractionRegistered){let t=re.getComponent(this.context.mainCamera,ad)??re.findObjectOfType(ad,this.context);!t&&this.context.mainCamera&&(t=re.addNewComponent(this.context.mainCamera,ad)),t!=null&&t.listener?(this.sound=new fV(t.listener),(e=this.gameObject)==null||e.add(this.sound)):br&&console.warn("No audio listener found in scene - can not play audio")}return this.sound}get ShouldPlay(){return this.shouldPlay}get audioContext(){var e;return(e=this.sound)==null?void 0:e.context}awake(){br&&console.log(this),this.audioLoader=new rC,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),Bu.userInteractionRegistered?this.playOnAwake&&this.context.application.isVisible&&this.play():Bu.registerWaitForAllowAudio(()=>{this.enabled&&!this.destroyed&&this.shouldPlay&&this.onNewClip(this.clip)}),globalThis.addEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.addEventListener(IC.MuteChanged,this.onApplicationMuteChanged)}onDisable(){globalThis.removeEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.removeEventListener(IC.MuteChanged,this.onApplicationMuteChanged),this.pause()}applySpatialDistanceSettings(){const e=this.sound;if(!e)return;this._needUpdateSpatialDistanceSettings=!1;const t=it.lerp(10*this._maxDistance/Math.max(1e-4,this.spatialBlend),this._minDistance,this.spatialBlend);switch(br&&console.log(this.name,this._minDistance,this._maxDistance,this.spatialBlend,"Ref distance="+t),e.setRefDistance(t),e.setMaxDistance(Math.max(.01,this._maxDistance)),this.rollOffMode){case 0:e.setDistanceModel("exponential");break;case 1:e.setDistanceModel("linear");break;case 2:console.warn("Custom rolloff for AudioSource is not supported: "+this.name);break}this.spatialBlend>0?br&&!this.helper&&(this.helper=new Jfe(e,e.getRefDistance()),e.add(this.helper)):this.helper&&this.helper.parent&&this.helper.removeFromParent()}async onNewClip(e){if(e&&(this.clip=e),typeof e=="string")if(br&&console.log(e),e.endsWith(".mp3")||e.endsWith(".wav")){if(this.audioLoader||(this.audioLoader=new rC),this.shouldPlay=!0,this._lastClipStartedLoading===e){br&&console.log("Is currently loading:",this._lastClipStartedLoading,this);return}this._lastClipStartedLoading=e,br&&console.log("load audio",e);const t=await this.audioLoader.loadAsync(e).catch(console.error);this._lastClipStartedLoading=null,t&&this.createAudio(t)}else console.warn("Unsupported audio clip type",e);else this.shouldPlay=!0,this.createAudio()}play(e=void 0){var i,n,r;!e&&this.clip&&(e=this.clip),e!==void 0&&typeof e!="string"&&!(e instanceof MediaStream)&&(lt()&&console.warn("Called play on AudioSource with unknown argument type:",e+`
|
|
5732
|
+
`;var Efe=Object.defineProperty,Mfe=Object.getOwnPropertyDescriptor,XO=(s,e,t,i)=>{for(var n=i>1?void 0:i?Mfe(e,t):e,r=s.length-1,o;r>=0;r--)(o=s[r])&&(n=(i?o(e,t,n):o(n))||n);return i&&n&&Efe(e,t,n),n};class Up extends Ie{constructor(){super(...arguments);d(this,"constraintActive",!0);d(this,"locked",!1);d(this,"sources",[])}}XO([x()],Up.prototype,"constraintActive",2);XO([x()],Up.prototype,"locked",2);XO([x(ve)],Up.prototype,"sources",2);function Tfe(s,e){return Ed(s,Ii.ContextCreated,e),()=>Md(s,Ii.ContextCreated)}function Ife(s,e){return Ed(s,Ii.ContextClearing,e),()=>Md(s,Ii.ContextClearing)}function Rfe(s,e){return Ed(s,Ii.ContextDestroying,e),()=>Md(s,Ii.ContextDestroying)}function Sj(s,e){return Ed(s,$i.Start,e),()=>Md(s,$i.Start)}function Cj(s,e){return Ed(s,$i.Update,e),()=>Md(s,$i.Update)}function Pfe(s,e){return Ed(s,$i.OnBeforeRender,e),()=>Md(s,$i.OnBeforeRender)}function Bfe(s,e){return Ed(s,$i.OnAfterRender,e),()=>Md(s,$i.OnAfterRender)}class sp{constructor(){d(this,"bb",null);d(this,"bb_pos",0)}__init(e,t){return this.bb_pos=e,this.bb=t,this}x(){return this.bb.readFloat32(this.bb_pos)}y(){return this.bb.readFloat32(this.bb_pos+4)}z(){return this.bb.readFloat32(this.bb_pos+8)}static sizeOf(){return 12}static createVec3(e,t,i,n){return e.prep(4,12),e.writeFloat32(n),e.writeFloat32(i),e.writeFloat32(t),e.offset()}}class Ej{constructor(){d(this,"bb",null);d(this,"bb_pos",0)}__init(e,t){return this.bb_pos=e,this.bb=t,this}position(e){return(e||new sp).__init(this.bb_pos,this.bb)}rotation(e){return(e||new sp).__init(this.bb_pos+12,this.bb)}scale(e){return(e||new sp).__init(this.bb_pos+24,this.bb)}static sizeOf(){return 36}static createTransform(e,t,i,n,r,o,a,l,c,h){return e.prep(4,36),e.prep(4,12),e.writeFloat32(h),e.writeFloat32(c),e.writeFloat32(l),e.prep(4,12),e.writeFloat32(a),e.writeFloat32(o),e.writeFloat32(r),e.prep(4,12),e.writeFloat32(n),e.writeFloat32(i),e.writeFloat32(t),e.offset()}}class Sh{constructor(){d(this,"bb",null);d(this,"bb_pos",0)}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsSyncedTransformModel(e,t){return(t||new Sh).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSyncedTransformModel(e,t){return e.setPosition(e.position()+OO),(t||new Sh).__init(e.readInt32(e.position())+e.position(),e)}guid(e){const t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}fast(){const e=this.bb.__offset(this.bb_pos,6);return e?!!this.bb.readInt8(this.bb_pos+e):!1}transform(e){const t=this.bb.__offset(this.bb_pos,8);return t?(e||new Ej).__init(this.bb_pos+t,this.bb):null}dontSave(){const e=this.bb.__offset(this.bb_pos,10);return e?!!this.bb.readInt8(this.bb_pos+e):!1}static startSyncedTransformModel(e){e.startObject(4)}static addGuid(e,t){e.addFieldOffset(0,t,0)}static addFast(e,t){e.addFieldInt8(1,+t,0)}static addTransform(e,t){e.addFieldStruct(2,t,0)}static addDontSave(e,t){e.addFieldInt8(3,+t,0)}static endSyncedTransformModel(e){return e.endObject()}static finishSyncedTransformModelBuffer(e,t){e.finish(t)}static finishSizePrefixedSyncedTransformModelBuffer(e,t){e.finish(t,void 0,!0)}}var Ts=(s=>(s[s.Average=0]="Average",s[s.Multiply=1]="Multiply",s[s.Minimum=2]="Minimum",s[s.Maximum=3]="Maximum",s))(Ts||{}),wE=(s=>(s[s.Discrete=0]="Discrete",s[s.Continuous=1]="Continuous",s))(wE||{}),Gn=(s=>(s[s.None=0]="None",s[s.FreezePositionX=2]="FreezePositionX",s[s.FreezePositionY=4]="FreezePositionY",s[s.FreezePositionZ=8]="FreezePositionZ",s[s.FreezePosition=14]="FreezePosition",s[s.FreezeRotationX=16]="FreezeRotationX",s[s.FreezeRotationY=32]="FreezeRotationY",s[s.FreezeRotationZ=64]="FreezeRotationZ",s[s.FreezeRotation=112]="FreezeRotation",s[s.FreezeAll=126]="FreezeAll",s))(Gn||{}),Bg=(s=>(s[s.None=0]="None",s[s.X=2]="X",s[s.Y=4]="Y",s[s.Z=8]="Z",s[s.All=-1]="All",s))(Bg||{});const ur=function(s,e){return function(t,i,n){Dfe(t,i,n,s,e)}};function Dfe(s,e,t,i,n){if(!n&&!i&&!s.onValidate)return;if(t!==void 0){console.error("Invalid usage of validate decorator. Only fields can be validated.",s,e,t),pn("Invalid usage of validate decorator. Only fields can be validated. Property: "+e,Yo.Error);return}let r="";if(typeof e=="string"?r=e:r=e.name,s.__internalAwake){const o=Symbol(r),a=s.__internalAwake;s.__internalAwake=function(){var l;if(!this.onValidate){lt()&&console.warn('Usage of @validate decorate detected but there is no onValidate method in your class: "'+((l=s.constructor)==null?void 0:l.name)+'"');return}if(this[o]===void 0){this[o]=this[r];const c=this[r];if(c instanceof ee||c instanceof w||c instanceof Ze||c instanceof Ce){const h=this[r];G1(h,()=>{this.onValidate(r)})}Object.defineProperty(this,r,{set:function(h){var u;if(this[uB]===!0)this[o]=h;else{i==null||i.call(this,h);const f=this[o];this[o]=h,(u=this.onValidate)==null||u.call(this,r,f)}},get:function(){return n==null||n.call(this),this[o]}})}a.call(this)}}}const Ofe=function(s){return function(e,t,i){let n="";typeof t=="string"?n=t:n=t.name;const r=s.prototype,o=Object.getOwnPropertyDescriptor(r,n);if(!(o!=null&&o.value)){console.warn("Can not apply prefix: type does not have method named",t,s);return}const a=o.value,l=e[n];Object.defineProperty(r,n,{value:function(...c){const h=l==null?void 0:l.call(this,...c);if(h instanceof Promise){h.then(u=>{if(u!==!1)return a.call(this,...c)});return}if(h!==!1)return a.call(this,...c)}})}};var Lfe=Object.defineProperty,kfe=Object.getOwnPropertyDescriptor,ra=(s,e,t,i)=>{for(var n=i>1?void 0:i?kfe(e,t):e,r=s.length-1,o;r>=0;r--)(o=s[r])&&(n=(i?o(e,t,n):o(n))||n);return i&&n&&Lfe(e,t,n),n};class Ffe{constructor(e,t){d(this,"positionChanged",!1);d(this,"rotationChanged",!1);d(this,"position");d(this,"quaternion");d(this,"_positionKeys",["x","y","z"]);d(this,"_quaternionKeys",["_x","_y","_z","_w"]);d(this,"mute",!1);d(this,"context");d(this,"obj");d(this,"_positionWatch");d(this,"_rotationWatch");this.context=t,this.obj=e}get isDirty(){return this.positionChanged||this.rotationChanged}reset(e=!1){if(this.positionChanged=!1,this.rotationChanged=!1,this.mute=!1,e){if(this.position)for(const t of this._positionKeys)delete this.position[t];if(this.quaternion)for(const t of this._quaternionKeys)delete this.quaternion[t]}}syncValues(){for(const e of this._positionKeys)this.position[e]=this.obj.position[e];for(const e of this._quaternionKeys)this.quaternion[e]=this.obj.quaternion[e]}applyValues(){if(this.positionChanged&&this.position)for(const e of this._positionKeys){const t=this.position[e];t!==void 0&&(this.obj.position[e]=t)}if(this.rotationChanged&&this.quaternion)for(const e of this._quaternionKeys){const t=this.quaternion[e];t!==void 0&&(this.obj.quaternion[e]=t)}}start(e,t){this.reset(),e&&(this._positionWatch||(this._positionWatch=new Dh(this.obj.position,["x","y","z"])),this._positionWatch.apply(),this.position={},this._positionWatch.subscribeWrite((r,o)=>{var l;if((l=this.context.physics.engine)!=null&&l.isUpdating||this.mute)return;const a=this.position[o];Math.abs(a-r)<1e-5||(this.position[o]=r,this.positionChanged=!0)})),t&&(this._rotationWatch||(this._rotationWatch=new Dh(this.obj.quaternion,["_x","_y","_z","_w"])),this._rotationWatch.apply(),this.quaternion={},this._rotationWatch.subscribeWrite((r,o)=>{var l;if((l=this.context.physics.engine)!=null&&l.isUpdating||this.mute)return;const a=this.quaternion[o];Math.abs(a-r)<1e-5||(this.quaternion[o]=r,this.rotationChanged=!0)}));const i=this.obj.matrixWorld.multiplyMatrices.bind(this.obj.matrixWorld),n=new ye;this.obj.matrixWorld.multiplyMatrices=(r,o)=>{var a;return(a=this.context.physics.engine)!=null&&a.isUpdating||this.mute||n.equals(r)||(this.positionChanged=!0,this.rotationChanged=!0,n.copy(r)),i(r,o)}}stop(){var e,t;(e=this._positionWatch)==null||e.revoke(),(t=this._rotationWatch)==null||t.revoke()}}var AR;const DB=(AR=class extends Ie{constructor(){super(...arguments);d(this,"autoMass",!0);d(this,"_mass",0);d(this,"useGravity",!0);d(this,"centerOfMass",new w(0,0,0));d(this,"constraints",Gn.None);d(this,"isKinematic",!1);d(this,"drag",0);d(this,"angularDrag",1);d(this,"detectCollisions",!0);d(this,"sleepThreshold",.01);d(this,"collisionDetectionMode",wE.Discrete);d(this,"_gravityScale",1);d(this,"dominanceGroup",0);d(this,"_propertiesChanged",!1);d(this,"_currentVelocity",new w);d(this,"_smoothedVelocity",new w);d(this,"_smoothedVelocityGetter",new w);d(this,"_lastPosition",new w);d(this,"_watch")}set mass(e){e!==this._mass&&(this._mass=e,this._propertiesChanged=!0,this.__didAwake&&(this.autoMass=!1))}get mass(){var e,t;return this.autoMass?((t=(e=this.context.physics.engine)==null?void 0:e.getBody(this))==null?void 0:t.mass())??-1:this._mass}get lockPositionX(){return(this.constraints&Gn.FreezePositionX)!==0}get lockPositionY(){return(this.constraints&Gn.FreezePositionY)!==0}get lockPositionZ(){return(this.constraints&Gn.FreezePositionZ)!==0}get lockRotationX(){return(this.constraints&Gn.FreezeRotationX)!==0}get lockRotationY(){return(this.constraints&Gn.FreezeRotationY)!==0}get lockRotationZ(){return(this.constraints&Gn.FreezeRotationZ)!==0}set lockPositionX(e){e?this.constraints|=Gn.FreezePositionX:this.constraints&=~Gn.FreezePositionX}set lockPositionY(e){e?this.constraints|=Gn.FreezePositionY:this.constraints&=~Gn.FreezePositionY}set lockPositionZ(e){e?this.constraints|=Gn.FreezePositionZ:this.constraints&=~Gn.FreezePositionZ}set lockRotationX(e){e?this.constraints|=Gn.FreezeRotationX:this.constraints&=~Gn.FreezeRotationX}set lockRotationY(e){e?this.constraints|=Gn.FreezeRotationY:this.constraints&=~Gn.FreezeRotationY}set lockRotationZ(e){e?this.constraints|=Gn.FreezeRotationZ:this.constraints&=~Gn.FreezeRotationZ}set gravityScale(e){this._gravityScale=e}get gravityScale(){return this._gravityScale}awake(){this._watch=void 0,this._propertiesChanged=!1}onEnable(){this._watch||(this._watch=new Ffe(this.gameObject,this.context)),this._watch.start(!0,!0),this.startCoroutine(this.beforePhysics(),$i.LateUpdate)}onDisable(){var e,t;(e=this._watch)==null||e.stop(),(t=this.context.physics.engine)==null||t.removeBody(this)}onDestroy(){var e;(e=this.context.physics.engine)==null||e.removeBody(this)}onValidate(){this._propertiesChanged=!0}*beforePhysics(){var e,t,i,n;for(;;)this._propertiesChanged&&(this._propertiesChanged=!1,(e=this.context.physics.engine)==null||e.updateProperties(this)),(t=this._watch)!=null&&t.isDirty?(this._watch.mute=!0,this._watch.applyValues(),(i=this.context.physics.engine)==null||i.updateBody(this,this._watch.positionChanged,this._watch.rotationChanged),this._watch.reset()):(n=this._watch)==null||n.syncValues(),this.captureVelocity(),yield}teleport(e,t=!0){var i;(i=this._watch)==null||i.reset(!0),t?this.gameObject.position.set(e.x,e.y,e.z):this.setWorldPosition(e.x,e.y,e.z),this.resetForcesAndTorques(),this.resetVelocities()}resetForces(e=!0){var t;(t=this.context.physics.engine)==null||t.resetForces(this,e)}resetTorques(e=!0){var t;(t=this.context.physics.engine)==null||t.resetTorques(this,e)}resetVelocities(){this.setVelocity(0,0,0),this.setAngularVelocity(0,0,0)}resetForcesAndTorques(){this.resetForces(),this.resetTorques()}wakeUp(){var e;(e=this.context.physics.engine)==null||e.wakeup(this)}get isSleeping(){var e;return(e=this.context.physics.engine)==null?void 0:e.isSleeping(this)}updateProperties(){var e;return this._propertiesChanged=!1,(e=this.context.physics.engine)==null?void 0:e.updateProperties(this)}applyForce(e,t,i=!0){var n;this._propertiesChanged&&this.updateProperties(),(n=this.context.physics.engine)==null||n.addForce(this,e,i)}applyImpulse(e,t=!0){var i;this._propertiesChanged&&this.updateProperties(),(i=this.context.physics.engine)==null||i.applyImpulse(this,e,t)}setForce(e,t,i,n=!0){var r,o,a;(r=this.context.physics.engine)==null||r.resetForces(this,n),typeof e=="number"?(t??(t=0),i??(i=0),(o=this.context.physics.engine)==null||o.addForce(this,{x:e,y:t,z:i},n)):(a=this.context.physics.engine)==null||a.addForce(this,e,n)}getVelocity(){var t;const e=(t=this.context.physics.engine)==null?void 0:t.getLinearVelocity(this);return e?(this._currentVelocity.x=e.x,this._currentVelocity.y=e.y,this._currentVelocity.z=e.z,this._currentVelocity):this._currentVelocity.set(0,0,0)}setVelocity(e,t,i,n=!0){var r,o;if(e instanceof w){const a=e;(r=this.context.physics.engine)==null||r.setLinearVelocity(this,a,n);return}t===void 0||i===void 0||(o=this.context.physics.engine)==null||o.setLinearVelocity(this,{x:e,y:t,z:i},n)}getAngularVelocity(){var t;const e=(t=this.context.physics.engine)==null?void 0:t.getAngularVelocity(this);return e?(this._currentVelocity.x=e.x,this._currentVelocity.y=e.y,this._currentVelocity.z=e.z,this._currentVelocity):this._currentVelocity.set(0,0,0)}setAngularVelocity(e,t,i,n=!0){var r,o;if(e instanceof w){const a=e;(r=this.context.physics.engine)==null||r.setAngularVelocity(this,a,n);return}t===void 0||i===void 0||(o=this.context.physics.engine)==null||o.setAngularVelocity(this,{x:e,y:t,z:i},n)}setTorque(e,t,i){this.setAngularVelocity(e,t,i)}get smoothedVelocity(){return this._smoothedVelocityGetter.copy(this._smoothedVelocity),this._smoothedVelocityGetter.multiplyScalar(1/this.context.time.deltaTime)}setBodyFromGameObject(e=null){}captureVelocity(){const e=kt(this.gameObject);DB.tempPosition.copy(e);const t=e.sub(this._lastPosition);this._lastPosition.copy(DB.tempPosition),this._smoothedVelocity.lerp(t,this.context.time.deltaTime/.1)}},d(AR,"tempPosition",new w),AR);let zi=DB;ra([ur()],zi.prototype,"autoMass",2);ra([x()],zi.prototype,"mass",1);ra([ur(),x()],zi.prototype,"useGravity",2);ra([x(w)],zi.prototype,"centerOfMass",2);ra([ur(),x()],zi.prototype,"constraints",2);ra([ur(),x()],zi.prototype,"isKinematic",2);ra([ur(),x()],zi.prototype,"drag",2);ra([ur(),x()],zi.prototype,"angularDrag",2);ra([ur(),x()],zi.prototype,"detectCollisions",2);ra([ur(),x()],zi.prototype,"sleepThreshold",2);ra([ur(),x()],zi.prototype,"collisionDetectionMode",2);ra([ur()],zi.prototype,"_gravityScale",2);ra([ur()],zi.prototype,"dominanceGroup",2);const Pu=ie("debugsync"),X0="STRS";kO(X0,Sh.getRootAsSyncedTransformModel);const zl=new U_;function Mj(s,e,t=!0){zl.clear();const i=zl.createString(s);Sh.startSyncedTransformModel(zl),Sh.addGuid(zl,i),Sh.addFast(zl,t);const n=e.worldPosition,r=e.worldEuler,o=e.gameObject.scale;Sh.addTransform(zl,Ej.createTransform(zl,n.x,n.y,n.z,r.x,r.y,r.z,o.x,o.y,o.z));const a=Sh.endSyncedTransformModel(zl);return zl.finish(a,X0),zl.asUint8Array()}let OB=0,i0=0;Cj(s=>{var i;const t=((i=s.connection.currentServerUrl)==null?void 0:i.includes("glitch"))?10:40;i0=Math.floor(OB/t),OB=0,Pu&&i0>0&&console.log("Sync Transform Fast Interval",i0)});class pd extends Ie{constructor(){super(...arguments);d(this,"overridePhysics",!0);d(this,"interpolatePosition",!0);d(this,"interpolateRotation",!0);d(this,"fastMode",!1);d(this,"syncDestroy",!1);d(this,"_model",null);d(this,"_needsUpdate",!0);d(this,"rb",null);d(this,"_wasKinematic",!1);d(this,"_receivedDataBefore",!1);d(this,"_targetPosition");d(this,"_targetRotation");d(this,"_receivedFastUpdate",!1);d(this,"_shouldRequestOwnership",!1);d(this,"joinedRoomCallback",null);d(this,"receivedDataCallback",null);d(this,"tempEuler",new oi);d(this,"receivedUpdate",!1);d(this,"lastWorldPos");d(this,"lastWorldRotation")}requestOwnership(){Pu&&console.log("Request ownership"),this._model?this._model.requestOwnership():(this._shouldRequestOwnership=!0,this._needsUpdate=!0)}hasOwnership(){var t;return((t=this._model)==null?void 0:t.hasOwnership)??void 0}isOwned(){var t;return(t=this._model)==null?void 0:t.isOwned}awake(){Pu&&console.log("new instance",this.guid,this),this._receivedDataBefore=!1,this._targetPosition=new w,this._targetRotation=new Ce,this.lastWorldPos=new w,this.lastWorldRotation=new Ce,this.rb=re.getComponentInChildren(this.gameObject,zi),this.rb&&(this._wasKinematic=this.rb.isKinematic),this.receivedUpdate=!0,this._model=new HO(this.context.connection,this.guid),this.context.connection.isConnected&&this.tryGetLastState(),this.joinedRoomCallback=this.tryGetLastState.bind(this),this.context.connection.beginListen(Xt.JoinedRoom,this.joinedRoomCallback),this.receivedDataCallback=this.onReceivedData.bind(this),this.context.connection.beginListenBinary(X0,this.receivedDataCallback)}onDestroy(){this.syncDestroy&&jO(this.guid,this.context.connection),this._model=null,this.context.connection.stopListen(Xt.JoinedRoom,this.joinedRoomCallback),this.context.connection.stopListenBinary(X0,this.receivedDataCallback)}tryGetLastState(){const t=this.context.connection.tryGetState(this.guid);t&&this.onReceivedData(t)}onReceivedData(t){var i;if(!this.destroyed&&typeof t.guid=="function"&&t.guid()===this.guid){Pu&&console.log("new data",this.context.connection.connectionId,this.context.time.frameCount,this.guid,t),this.receivedUpdate=!0,this._receivedFastUpdate=t.fast();const n=t.transform();if(n){Fa.markDirty(this.gameObject,!0);const r=n.position();r&&(this.interpolatePosition&&((i=this._targetPosition)==null||i.set(r.x(),r.y(),r.z())),(!this.interpolatePosition||!this._receivedDataBefore)&&this.setWorldPosition(r.x(),r.y(),r.z()));const o=n.rotation();o&&(this.tempEuler.set(o.x(),o.y(),o.z()),this.interpolateRotation&&this._targetRotation.setFromEuler(this.tempEuler),(!this.interpolateRotation||!this._receivedDataBefore)&&HD(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){Pu&&console.log("no model or room",this.name,this.guid,this.context.connection.isInRoom);return}this._shouldRequestOwnership&&(this._shouldRequestOwnership=!1,this._model.requestOwnership());const t=this.worldPosition,i=this.worldQuaternion;if(this._model.isOwned&&!this.receivedUpdate){const o=t.distanceTo(this.lastWorldPos),a=i.angleTo(this.lastWorldRotation),l=this._model.hasOwnership||this.fastMode?1e-4:.001;(o>l||a>l)&&(this._model.hasOwnership?this._needsUpdate=!0:(Pu&&console.log(this.guid,"reset because not owned but",this.gameObject.name,this.lastWorldPos),this.worldPosition=this.lastWorldPos,t.copy(this.lastWorldPos),this.worldQuaternion=this.lastWorldRotation,i.copy(this.lastWorldRotation),Fa.markDirty(this.gameObject,!0),this._needsUpdate=!1))}if(this._model&&!this._model.hasOwnership&&this._model.isOwned&&this._receivedDataBefore){const a=this._receivedFastUpdate||this.fastMode?.5:.3;let l=!1;if(this.interpolatePosition&&this._targetPosition){const c=this.worldPosition;c.lerp(this._targetPosition,a),this.worldPosition=c,l=!0}if(this.interpolateRotation&&this._targetRotation){const c=this.worldQuaternion;c.slerp(this._targetRotation,a),this.worldQuaternion=c,l=!0}l&&Fa.markDirty(this.gameObject,!0)}if(this.receivedUpdate=!1,this.lastWorldPos.copy(t),this.lastWorldRotation.copy(i),!this._model||!this._model||this._model.hasOwnership===void 0||!this._model.hasOwnership)return;this.rb&&this.overridePhysics&&this._wasKinematic!==void 0&&(Pu&&console.log("reset kinematic",this.rb.name,this._wasKinematic),this.rb.isKinematic=this._wasKinematic);const n=10,r=this.rb||this.fastMode;if(this._needsUpdate&&(this.context.time.frameCount%n===0||r)){if(OB++,r&&i0>0&&this.context.time.frameCount%i0!==0)return;Pu&&console.log("send update",this.context.connection.connectionId,this.guid,this.gameObject.name,this.gameObject.guid),this._needsUpdate=!1;const o=Mj(this.guid,this,!!r);this.context.connection.sendBinary(o)}}}const Ufe=ie("debugshadowcomponents");LD.prototype.interactable={get(){return this.interactive},set(s){this.interactable=s}};const Da=Symbol("shadowDomOwner");class Ha extends Ie{constructor(){super(...arguments);d(this,"_shadowComponent",null);d(this,"_controlsChildLayout",!0);d(this,"_root");d(this,"_parentComponent")}isRoot(){var t;return((t=this.Root)==null?void 0:t.gameObject)===this.gameObject}get canvas(){const t=this.Root;return t!=null&&t.isCanvas?t:null}get Canvas(){return this.canvas}markDirty(){bo.markUIDirty(this.context)}get shadowComponent(){return this._shadowComponent}set shadowComponent(t){this._shadowComponent=t}get controlsChildLayout(){return this._controlsChildLayout}set controlsChildLayout(t){this._controlsChildLayout=t,this.shadowComponent&&(this.shadowComponent.autoLayout=t)}get Root(){return this._root===void 0&&(this._root=re.getComponentInParent(this.gameObject,X_)),this._root}__internalNewInstanceCreated(t){return super.__internalNewInstanceCreated(t),this.shadowComponent=null,this._root=void 0,this._parentComponent=void 0,this}onEnable(){super.onEnable()}addShadowComponent(t,i){var o;if(!t)return;this.removeShadowComponent();const n=this.isRoot()?this.gameObject:this.gameObject.parent;if(this._parentComponent=re.getComponentInParent(n,Ha),!this._parentComponent){console.warn(`Component "${this.name}" doesn't have a UI parent anywhere. Do you have an UI element outside a Canvas? UI components must be a child of a Canvas component`,this);return}t.name=this.name+" ("+(this.constructor.name??"UI")+")",t.autoLayout=this._parentComponent.controlsChildLayout,t[Da]=this,this.setShadowComponentOwner(t);let r=!1;if(((o=this.Root)==null?void 0:o.gameObject)===this.gameObject)this.gameObject.add(t);else{const a=this._parentComponent.shadowComponent;a&&(a==null||a.add(t),r=!0)}this.shadowComponent=t,i&&i.shadowComponent&&this.shadowComponent&&i.shadowComponent.add(this.shadowComponent),F_&&t.add(new na(.5)),this.onAfterAddedToScene(),r&&C5(),Ufe&&console.warn("Added shadow component",this.shadowComponent)}setShadowComponentOwner(t){if(t&&(t[Da]===void 0||t[Da]===this)&&(t[Da]=this,t.children))for(const i of t.children)this.setShadowComponentOwner(i)}traverseOwnedShadowComponents(t,i,n){if(t&&t[Da]===i){n(t);for(const r of t.children)this.traverseOwnedShadowComponents(r,i,n)}}removeShadowComponent(){this.shadowComponent&&this.shadowComponent.removeFromParent()}onAfterAddedToScene(){}setInteractable(t){this.shadowComponent&&(this.shadowComponent.interactable=t)}}class X_ extends Ha{awake(){super.awake()}}class zy{constructor(e,t){d(this,"event");d(this,"button");d(this,"buttonName");d(this,"_used",!1);d(this,"_propagationStopped",!1);d(this,"z__pointer_ctured",!1);d(this,"z__pointer_cture_rleased",!1);d(this,"inputSource");d(this,"object");d(this,"point");d(this,"normal");d(this,"face");d(this,"distance");d(this,"instanceId");d(this,"intersection");d(this,"isDown");d(this,"isUp");d(this,"isPressed");d(this,"isClick");d(this,"isDoubleClick");d(this,"input");this.event=t,this.input=e,this.button=t.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 e=new zy(this.input,this.event);return Object.assign(e,this),e}Use(){this.use()}StopPropagation(){this.event.stopImmediatePropagation()}}function LB(s,e){return re.foreachComponent(s,i=>{if(!i.enabled)return;const n=i;if(e)switch(e){case"pointerdown":if(n.onPointerDown)return!0;break;case"pointerup":if(n.onPointerUp||n.onPointerClick)return!0;break;case"pointermove":if(n.onPointerEnter||n.onPointerExit||n.onPointerMove)return!0;break}else if(n.onPointerDown||n.onPointerUp||n.onPointerEnter||n.onPointerExit||n.onPointerClick)return!0},!1)===!0}var Nfe=Object.defineProperty,zfe=Object.getOwnPropertyDescriptor,Gfe=(s,e,t,i)=>{for(var n=i>1?void 0:i?zfe(e,t):e,r=s.length-1,o;r>=0;r--)(o=s[r])&&(n=(i?o(e,t,n):o(n))||n);return i&&n&&Nfe(e,t,n),n};class Y_ extends Ie{awake(){bo.createIfNoneExists(this.context)}onEnable(){var e;(e=bo.get(this.context))==null||e.register(this)}onDisable(){var e;(e=bo.get(this.context))==null||e.unregister(this)}}class sa extends Y_{constructor(){super(...arguments);d(this,"targets",null);d(this,"raycastHits",[]);d(this,"ignoreSkinnedMeshes",!1)}start(){this.targets=[this.gameObject]}performRaycast(t=null){if(!this.targets)return null;t??(t=new Il),t.targets=this.targets,t.results=this.raycastHits;const i=t.testObject;this.ignoreSkinnedMeshes&&(t.testObject=r=>r instanceof wo?"continue in children":i?i(r):!0);const n=this.context.physics.raycast(t);return t.testObject=i,n}}Gfe([x()],sa.prototype,"ignoreSkinnedMeshes",2);class SE extends sa{constructor(){super(),this.ignoreSkinnedMeshes=!0}}class Y0 extends Y_{performRaycast(e){if(!xt.active||!(e!=null&&e.ray))return null;const t=e.ray.origin,i=.015;return this.context.physics.sphereOverlap(t,i)}}class CE{static getObject(e){const t=e[Da];return t&&(t.isComponent===!0?e=t.gameObject:e=t),e}static isInteractable(e,t){if(t&&(t.canvasGroup=void 0,t.graphic=void 0),e==null||!e.visible||(e=this.getObject(e),!e.visible))return!1;const i=this.tryFindCanvasGroup(e);if((i==null?void 0:i.isCanvasGroup)===!0&&(t&&(t.canvasGroup=i),i.blocksRaycasts===!1||i.interactable===!1))return!1;const n=Ep(e,r=>{if(r.isGraphic===!0)return r},!1);return t&&(n==null?void 0:n.isGraphic)===!0&&(t.graphic=n),!((n==null?void 0:n.raycastTarget)===!1||(n==null?void 0:n.layer)===2)}static tryFindCanvasGroup(e){if(!e)return null;const t=Ep(e,i=>{const n=i;if(n.blocksRaycasts!==void 0&&n.interactable!==void 0)return n},!1);return t!==void 0?t:this.tryFindCanvasGroup(e.parent)}}function YO(s){const e=s[Da];return e||(s.parent?YO(s.parent):null)}function Hfe(s){return s.isUI===!0||typeof s[Da]=="object"}function FC(s,e){if(!s)return;const t=s.material;if((t==null?void 0:t.isMaterial)===!0){const i=s.parent;i&&i.isText,t.side=e.doubleSided??!0?xi:ys,t.shadowSide=e.doubleSided?xi:ys,s.castShadow=e.castShadows?e.castShadows:!1,s.receiveShadow=e.receiveShadows?e.receiveShadows:!1}for(const i of s.children)FC(i,e)}function pg(s,e,t){s[e]===void 0&&console.warn("Field",e,"is undefined on",s);const i=Proxy.revocable(s[e],{set(o,a,l,c){const h=o[a],u=Reflect.set(o,a,l,c);return t(l,h),u}}),n=i.revoke,r=s[e];return i.revoke=()=>{s[e]=r,n()},s[e]=i.proxy,i}const Iz=Symbol("Scheduled action");function Vfe(s,e,t=$i.OnBeforeRender){let i=s[Iz];i||(i=s[Iz]={});const n=e.name;i[t]||(i[t]={});const r=i[t];if(r[n])return;function*a(){e==null||e.call(s),r[n]=null}const l=s.startCoroutine(a(),t);r[n]=l}const rh=ie("debugeventsystem");var kB=(s=>(s.BeforeHandleInput="BeforeHandleInput",s.AfterHandleInput="AfterHandleInput",s))(kB||{});const Jl=class extends Ie{constructor(){super();d(this,"raycaster",[]);d(this,"_handleInputFn");d(this,"pressedByID",new Map);d(this,"hoveredByID",new Map);d(this,"_sortedHits",[]);d(this,"_testObjectsCache",new Map);d(this,"_currentlyActiveRaycaster",null);d(this,"_currentPointerEventName",null);d(this,"shouldRaycastObject",t=>{var r;let i=null;if(Hfe(t)&&(i=(r=t[Da])==null?void 0:r.gameObject),this._testObjectsCache.has(t)||i&&this._testObjectsCache.has(i))return this._testObjectsCache.get(t)===!1?"continue in children":!0;{let o=LB(t,this._currentPointerEventName);if(!o&&i&&(o=LB(i,this._currentPointerEventName)),o){this._testObjectsCache.set(t,!0);for(const a of t.children)this.shouldRaycastObject_AddToYesCache(a);return!0}return this._testObjectsCache.set(t,!1),"continue in children"}});d(this,"_sortingBuffer",[]);d(this,"_noDepthTestingResults",[]);d(this,"out",{});d(this,"_capturedPointer",{});d(this,"pointerEnterSymbol",Symbol("pointerEnter"));d(this,"pointerExitSymbol",Symbol("pointerExit"));d(this,"currentActiveMeshUIComponents",[]);Jl.systems.push(this)}static createIfNoneExists(t){this.didSearchEventSystem||(this.didSearchEventSystem=!0,Jl.systems.length<=0&&Jl.systems.push(...re.findObjectsOfType(Jl,t)));for(const n of Jl.systems)if(n.context===t)return;const i=new ve;re.addNewComponent(i,Jl),t.scene.add(i)}static get systems(){const t=Ot.Current;return this._eventSystemMap.has(t)||this._eventSystemMap.set(t,[]),this._eventSystemMap.get(t)}static get(t){const i=this._eventSystemMap.get(t);return i&&i.length>0?i[0]:null}static get instance(){return this.systems[0]}static ensureUpdateMeshUI(t,i,n=!1){zu.update(t,i,n)}static markUIDirty(t){zu.markDirty()}get hasActiveUI(){return this.currentActiveMeshUIComponents.length>0}get isHoveringObjects(){return this.hoveredByID.size>0}onDestroy(){Jl.systems.splice(Jl.systems.indexOf(this),1)}start(){if(this.raycaster.length<=0&&!re.findObjectOfType(Y_,this.context)){const i=re.addNewComponent(this.context.scene,sa);this.raycaster.push(i),(lt()||rh)&&console.warn("Added an ObjectRaycaster to the scene because no raycaster was found.")}}register(t){var i;t&&this.raycaster&&!this.raycaster.includes(t)&&((i=this.raycaster)==null||i.push(t))}unregister(t){var n,r;const i=(n=this.raycaster)==null?void 0:n.indexOf(t);i!==void 0&&i!==-1&&((r=this.raycaster)==null||r.splice(i,1))}onEnable(){this._handleInputFn??(this._handleInputFn=this.onPointerEvent.bind(this)),this.context.input.addEventListener(fn.PointerDown,this._handleInputFn),this.context.input.addEventListener(fn.PointerUp,this._handleInputFn),this.context.input.addEventListener(fn.PointerMove,this._handleInputFn)}onDisable(){this.context.input.removeEventListener(fn.PointerDown,this._handleInputFn),this.context.input.removeEventListener(fn.PointerUp,this._handleInputFn),this.context.input.removeEventListener(fn.PointerMove,this._handleInputFn)}onBeforeRender(){this.resetMeshUIStates()}onPointerEvent(t){if(t===void 0||t.propagationStopped)return;const i=new zy(this.context.input,t);this._currentPointerEventName=t.type,i.inputSource=this.context.input,i.isClick=t.isClick,i.isDoubleClick=t.isDoubleClick,i.isDown=t.type==fn.PointerDown,i.isUp=t.type==fn.PointerUp,i.isPressed=this.context.input.getPointerPressed(t.pointerId),rh&&(i.isDown?console.log("DOWN",i.pointerId):i.isUp&&console.log("UP",i.pointerId),i.isClick&&console.log("CLICK",i.pointerId));const n=new Il;t.hasRay?n.ray=t.ray:n.screenPoint=this.context.input.getPointerPositionRC(t.pointerId);const r=this.performRaycast(n);if(r){for(const a of r)a.event=t,t.intersections.push(a);t.origin.onPointerHits&&t.origin.onPointerHits({sender:this,event:t,hits:r})}rh&&i.isClick&&pn("EventSystem: "+i.pointerId+" - "+this.context.time.frame+" - Up:"+i.isUp+", Down:"+i.isDown);const o={sender:this,args:i,hasActiveUI:this.currentActiveMeshUIComponents.length>0};this.dispatchEvent(new CustomEvent("BeforeHandleInput",{detail:o})),this.handleIntersections(r,i),this.dispatchEvent(new CustomEvent("AfterHandleInput",{detail:o}))}shouldRaycastObject_AddToYesCache(t){this._testObjectsCache.set(t,!0);for(const i of t.children)this.shouldRaycastObject_AddToYesCache(i)}performRaycast(t){if(!this.raycaster)return null;this._testObjectsCache.clear(),this._sortedHits.length=0,t||(t=new Il),t.testObject=this.shouldRaycastObject;for(const i of this.raycaster){if(!i.activeAndEnabled)continue;this._currentlyActiveRaycaster=i;const n=i.performRaycast(t);this._currentlyActiveRaycaster=null,n&&n.length>0&&this._sortedHits.push(...n)}return this._sortedHits.sort((i,n)=>i.distance-n.distance),this._sortedHits}assignHitInformation(t,i){i?(t.intersection=i,t.point=i.point,t.normal=i.normal,t.face=i.face,t.distance=i.distance,t.instanceId=i.instanceId):(t.intersection=void 0,t.point=void 0,t.normal=void 0,t.face=void 0,t.distance=void 0,t.instanceId=void 0)}handleIntersections(t,i){var r;if(t!=null&&t.length){t=this.sortCandidates(t);for(const o of t){if(i.event.immediatePropagationStopped)return!1;if(this.assignHitInformation(i,o),this.handleEventOnObject(o.object,i))return!0}}this.assignHitInformation(i,t==null?void 0:t[0]),this.invokePointerCapture(i);const n=this.hoveredByID.get(i.pointerId);return n&&this.propagatePointerExit(n.obj,n.data,null),this.hoveredByID.delete(i.pointerId),i.isUp&&((r=this.pressedByID.get(i.pointerId))==null||r.handlers.forEach(o=>this.invokeOnPointerUp(i,o)),this.pressedByID.delete(i.pointerId)),!1}sortCandidates(t){this._sortingBuffer.length=0,this._noDepthTestingResults.length=0;for(let i=0;i<t.length;i++){const n=t[i],r=n.object;if(r.material&&r.material.depthTest===!1){this._noDepthTestingResults.push(n);continue}this._sortingBuffer.push(n)}for(const i of this._sortingBuffer)this._noDepthTestingResults.push(i);return this._noDepthTestingResults}handleEventOnObject(t,i){if(!this.testIsVisible(t))return i.isClick&&rh&&console.log("not allowed",t),!1;if(i.pointerId===void 0)return rh&&console.error("Event without pointer can't be handled",i),!1;i.object=t;const n=t.parent,r=i.isClick??!1;let o=null;if(n&&n.isUI){const u=(i.isPressed||i.isClick)??!1;if(n[Da]){const f=n[Da].gameObject;if(f){if(!CE.isInteractable(f,this.out))return!1;o=this.out.canvasGroup??null,this.handleMeshUIIntersection(t,u),t=f}}}r&&rh&&console.log(this.context.time.frame,t);const a=this.hoveredByID.get(i.pointerId),l=a==null?void 0:a.obj;l!==t&&l&&this.propagatePointerExit(l,a.data,t);const h=this.hoveredByID.get(i.pointerId);if(h?(h.obj=t,h.data=i):this.hoveredByID.set(i.pointerId,{obj:t,data:i}),i.isDown){const u=this.pressedByID.get(i.pointerId);u?(u.obj=t,u.data=i):this.pressedByID.set(i.pointerId,{obj:t,data:i,handlers:new Set})}return(o===null||o.interactable)&&this.handleMainInteraction(t,i,l??null),!0}propagate(t,i){for(;t;)re.foreachComponent(t,n=>{i(n)},!1),t=t.parent}handleMainInteraction(t,i,n){const r=this.pressedByID.get(i.pointerId),o=n!==t;let a=!0;switch(i.event.pointerType){case"mouse":case"touch":const l=this.context.input.getPointerPositionLastFrame(i.pointerId),c=this.context.input.getPointerPosition(i.pointerId);a=l&&!it.approximately(l,c);break}this.propagate(t,l=>{var h;const c=l;c.interactable!==!1&&(!c.activeAndEnabled||!c.enabled||(c.onPointerEnter&&o&&this.handlePointerEnter(c,i),i.isDown&&c.onPointerDown&&(c.onPointerDown(i),r==null||r.handlers.add(c),this.handlePointerCapture(i,c)),c.onPointerMove&&(a&&c.onPointerMove(i),this.handlePointerCapture(i,c)),i.isUp&&(c.onPointerUp&&(this.invokeOnPointerUp(i,c),r==null||r.handlers.delete(c)),c.onPointerExit&&((h=i.event)==null?void 0:h.pointerType)===uE.Touch&&(this.handlePointerExit(c,i),this.hoveredByID.delete(i.pointerId))),i.isClick&&c.onPointerClick&&c.onPointerClick(i)))}),i.isUp&&(r==null||r.handlers.forEach(l=>{this.invokeOnPointerUp(i,l)}),this.pressedByID.delete(i.pointerId))}propagatePointerExit(t,i,n){this.propagate(t,r=>{if(!r.gameObject||r.destroyed)return;const o=r;if(o.onPointerExit){if(n&&this.isChild(n,r.gameObject))return;this.handlePointerExit(o,i)}})}invokeOnPointerUp(t,i){var n;(n=i.onPointerUp)==null||n.call(i,t),this.releasePointerCapture(t,i)}handlePointerEnter(t,i){t.onPointerEnter&&this.updatePointerState(t,i.pointerId,this.pointerEnterSymbol,!0)&&t.onPointerEnter(i),this.updatePointerState(t,i.pointerId,this.pointerExitSymbol,!1)}handlePointerExit(t,i){t.onPointerExit&&this.updatePointerState(t,i.pointerId,this.pointerExitSymbol,!0)&&t.onPointerExit(i),this.updatePointerState(t,i.pointerId,this.pointerEnterSymbol,!1)}updatePointerState(t,i,n,r){let o=t[n];if(r)return o&&o.includes(i)?!1:(o=o||[],o.push(i),t[n]=o,!0);{if(!o||!o.includes(i))return!1;const a=o.indexOf(i);return a!==-1&&o.splice(a,1),!0}}handlePointerCapture(t,i){if(t.z__pointer_ctured){t.z__pointer_ctured=!1;const n=t.pointerId;if(i.onPointerMove){const r=this._capturedPointer[n]||[];r.push(i),this._capturedPointer[n]=r}else lt()&&!i.z__warned_no_pointermove&&(i.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 t.z__pointer_cture_rleased&&(t.z__pointer_cture_rleased=!1,this.releasePointerCapture(t,i))}releasePointerCapture(t,i){const n=t.pointerId;if(this._capturedPointer[n]){const r=this._capturedPointer[n].indexOf(i);r!==-1&&(this._capturedPointer[n].splice(r,1),rh&&console.log("released pointer capture",n,i,this._capturedPointer))}}invokePointerCapture(t){var i;if(t.event.type===fn.PointerMove){const n=t.pointerId,r=this._capturedPointer[n];if(r){rh&&console.log("Captured",n,r);for(let o=0;o<r.length;o++){const a=r[o];if(a.destroyed){r.splice(o,1),o--;continue}(i=a.onPointerMove)==null||i.call(a,t)}}}}isChild(t,i){return!t||!i?!1:t===i?!0:t.parent?this.isChild(t.parent,i):!1}handleMeshUiObjectWithoutShadowDom(t,i){return!t||!t.isUI?!0:this.handleMeshUIIntersection(t,i)}handleMeshUIIntersection(t,i){const n=zu.updateState(t,i);return n&&this.currentActiveMeshUIComponents.push(n),n!==null}resetMeshUIStates(){if(this.context.input.getPointerPressedCount()>0&&zu.resetLastSelected(),!(!this.currentActiveMeshUIComponents||this.currentActiveMeshUIComponents.length<=0)){for(let t=0;t<this.currentActiveMeshUIComponents.length;t++){const i=this.currentActiveMeshUIComponents[t];zu.resetState(i)}this.currentActiveMeshUIComponents.length=0}}testIsVisible(t){return t?re.isActiveSelf(t)?this.testIsVisible(t.parent):!1:!0}};let bo=Jl;d(bo,"_eventSystemMap",new Map),d(bo,"didSearchEventSystem",!1);class zu{static markDirty(){this.needsUpdate=!0}static update(e,t,i=!1){if(i){e.update();return}const n=t.time.frameCount;for(const r of this.lastUpdateFrame)if(r.context===t){if(n===r.frame)return;r.frame=n;let o=this.needsUpdate||n<1;r.nextUpdate===t.time.frameCount&&(o=!0),o&&(rh&&console.log("Update threemeshui"),this.needsUpdate=!1,e.update());return}this.lastUpdateFrame=[{context:t,frame:n,nextUpdate:n}],e.update()}static updateState(e,t){let i=null;if(e&&(i=this.findBlockInParent(e),i&&i!==this.lastSelected)){if(i.interactable===!1)return null;this.needsUpdate=!0}return i}static resetLastSelected(){const e=this.lastSelected;e&&(this.lastSelected=null,this.resetState(e))}static resetState(e){e&&(this.needsUpdate=!0)}static findBlockInParent(e){return e?e.isBlock?e:this.findBlockInParent(e.parent):null}}d(zu,"lastSelected",null),d(zu,"lastUpdateFrame",[]),d(zu,"needsUpdate",!1);var Qfe=Object.defineProperty,jfe=Object.getOwnPropertyDescriptor,yn=(s,e,t,i)=>{for(var n=i>1?void 0:i?jfe(e,t):e,r=s.length-1,o;r>=0;r--)(o=s[r])&&(n=(i?o(e,t,n):o(n))||n);return i&&n&&Qfe(e,t,n),n};const DI=ie("debugorbit"),Ew=ie("freecam"),Mw=ie("debugcamerafit"),Tw=ie("smoothcam"),Wfe={LEFT:"",UP:"",RIGHT:"",BOTTOM:""};let OI;class K0 extends CustomEvent{constructor(e,t){super("target-reached",{detail:{controls:e,type:t}})}}class wi extends Ie{constructor(){super(...arguments);d(this,"autoTarget",!0);d(this,"autoFit",!1);d(this,"enableRotate",!0);d(this,"autoRotate",!1);d(this,"autoRotateSpeed",1);d(this,"minAzimuthAngle",1/0);d(this,"maxAzimuthAngle",1/0);d(this,"minPolarAngle",0);d(this,"maxPolarAngle",Math.PI);d(this,"enableKeys",!0);d(this,"enableDamping",!0);d(this,"dampingFactor",.1);d(this,"enableZoom",!0);d(this,"minZoom",0);d(this,"maxZoom",1/0);d(this,"zoomSpeed",1);d(this,"zoomToCursor",!1);d(this,"enablePan",!0);d(this,"lookAtConstraint",null);d(this,"lookAtConstraint01",1);d(this,"allowInterrupt",!0);d(this,"middleClickToFocus",!0);d(this,"doubleClickToFocus",!0);d(this,"clickBackgroundToFitScene",2);d(this,"debugLog",!1);d(this,"targetLerpDuration",1);d(this,"_controls",null);d(this,"_cameraObject",null);d(this,"_lookTargetLerpActive",!1);d(this,"_lookTargetStartPosition",new w);d(this,"_lookTargetEndPosition",new w);d(this,"_lookTargetLerp01",0);d(this,"_lookTargetLerpDuration",0);d(this,"_cameraLerpActive",!1);d(this,"_cameraStartPosition",new w);d(this,"_cameraEndPosition",new w);d(this,"_cameraLerp01",0);d(this,"_cameraLerpDuration",0);d(this,"_inputs",0);d(this,"_enableTime",0);d(this,"_startedListeningToKeyEvents",!1);d(this,"_eventSystem");d(this,"_afterHandleInputFn");d(this,"_camera",null);d(this,"_syncedTransform");d(this,"_didSetTarget",0);d(this,"targetElement",null);d(this,"_lastTimeClickOnBackground",-1);d(this,"_clickOnBackgroundCount",0);d(this,"_onPointerDown",t=>{if(this.clickBackgroundToFitScene>0&&t.isClick&&t.button===0){if(t.hasRay||t.intersections.push(...this.context.physics.raycast()),t.intersections.length<=0){const i=this.context.time.time-this._lastTimeClickOnBackground;this._lastTimeClickOnBackground=this.context.time.time,this.clickBackgroundToFitScene<=1||i<this.clickBackgroundToFitScene*.15?(this._clickOnBackgroundCount+=1,this._clickOnBackgroundCount>=this.clickBackgroundToFitScene-1&&this.fitCamera(this.context.scene.children,{immediate:!1})):this._clickOnBackgroundCount=0}DI&&console.log(this.clickBackgroundToFitScene,t.intersections.length,this._clickOnBackgroundCount)}});d(this,"onControlsChangeStarted",()=>{this._syncedTransform&&this._syncedTransform.requestOwnership()});d(this,"_shouldDisable",!1);d(this,"__onPreRender",()=>{const t=this.context.pre_render_callbacks.indexOf(this.__onPreRender);t>=0&&this.context.pre_render_callbacks.splice(t,1),this.autoFit&&(this.autoFit=!1,this.fitCamera(this.scene.children,{centerCamera:"y",immediate:!0}))});d(this,"_haveAttachedKeyboardEvents",!1)}get isCameraController(){return!0}get controls(){return this._controls}get controllerObject(){return this._cameraObject}onStartInteraction(t){var i;(i=this.controls)==null||i.addEventListener("start",t)}get targetLerpSpeed(){return 5}set targetLerpSpeed(t){this.targetLerpDuration=1/t}awake(){this._didSetTarget=0,this._startedListeningToKeyEvents=!1}start(){this._eventSystem=bo.get(this.context)??void 0,this._eventSystem&&(this._afterHandleInputFn=this.afterHandleInput.bind(this),this._eventSystem.addEventListener(kB.AfterHandleInput,this._afterHandleInputFn))}onDestroy(){var t,i;(t=this._controls)==null||t.dispose(),(i=this._eventSystem)==null||i.removeEventListener(kB.AfterHandleInput,this._afterHandleInputFn)}onEnable(){this._didSetTarget=0,this._enableTime=this.context.time.time;const t=re.getComponent(this.gameObject,Gi);this._camera=t;let i=t==null?void 0:t.cam;if(!i&&this.gameObject instanceof Gt&&(i=this.gameObject),i&&TP(i,this,!0),!this._controls&&i instanceof Gt){this._cameraObject=i;const n=this.targetElement??this.context.renderer.domElement,r=i==null?void 0:i.quaternion.clone();this._controls=new wj(i,n),i==null||i.quaternion.copy(r),OI===void 0&&(OI={...this._controls.keys})}this._controls&&(Ew&&(this.enablePan=!0,this.enableZoom=!0,this.middleClickToFocus=!0,qa()&&(this.doubleClickToFocus=!0)),this._controls.addEventListener("start",this.onControlsChangeStarted),(i==null?void 0:i.type)==="PerspectiveCamera"?Ew||(this._controls.minDistance=this.minZoom,this._controls.maxDistance=this.maxZoom):Ew||(this._controls.minZoom=this.minZoom,this._controls.maxZoom=this.maxZoom),this._startedListeningToKeyEvents||(this._startedListeningToKeyEvents=!0,this._controls.listenToKeyEvents(window.document.body))),this._syncedTransform=re.getComponent(this.gameObject,pd)??void 0,this.context.input.addEventListener("pointerup",this._onPointerDown),this.context.pre_render_callbacks.push(this.__onPreRender)}onDisable(){var t;(t=this._camera)!=null&&t.cam&&TP(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(t){t.detail.args.pointerId===0&&(t.detail.args.isDown?this._controls&&this._eventSystem&&(this._shouldDisable=this._eventSystem.hasActiveUI):(!t.detail.args.isPressed||t.detail.args.isUp)&&(this._shouldDisable=!1))}onBeforeRender(){var i,n;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)&&((i=this.context.input.getPointerPositionDelta(0))!=null&&i.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 r=re.getComponent(this.gameObject,Gi);if(r&&!this.setLookTargetFromConstraint()){this.debugLog&&console.log("NO TARGET");const o=kt(r.cam),a=Math.max(.01,o.length()),l=new w(0,0,-a).applyMatrix4(r.cam.matrixWorld);this.setLookTargetPosition(l,!0)}if(!this.setLookTargetFromConstraint()){const o=new Il;o.screenPoint=new ee(0,0),o.lineThreshold=.1;const a=this.context.physics.raycast(o);a.length>0&&this.setLookTargetPosition(a[0].point,!0),Mw&&console.log("OrbitControls hits",...a)}}let t=this.middleClickToFocus&&this.context.input.getPointerClicked(1);if(t||(t=this.doubleClickToFocus&&this.context.input.getPointerDoubleClicked(0)&&this.context.time.time-this._enableTime>.3),t&&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 K0(this,"camera"));else{const r=it.easeInOutCubic(this._cameraLerp01);this._cameraObject.position.lerpVectors(this._cameraStartPosition,this._cameraEndPosition,r)}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 K0(this,"lookat"));else{const r=it.easeInOutCubic(this._lookTargetLerp01);this._controls.target.lerpVectors(this._lookTargetStartPosition,this._lookTargetEndPosition,r)}}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?OI:Wfe,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 Tw=="number"||Tw===!0){this._controls.enableDamping=!0;const r=typeof Tw=="number"?Tw:.99;this._controls.dampingFactor=Math.max(.001,1-Math.min(1,r))}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||(!Ew&&((n=this.lookAtConstraint)!=null&&n.locked)&&this.setLookTargetFromConstraint(0,this.lookAtConstraint01),this._controls.update(),DI&&_t.DrawWireSphere(this._controls.target,.1,65280))}}setCameraAndLookTarget(t){if(!t||!(t instanceof ve))return;const i=kt(t),n=zD(t);this.setTargetFromRaycast(new Mo(i,n)),this.setCameraTargetPosition(i)}setCameraTargetPosition(t,i=!1){var n,r;t&&(t instanceof ve&&(t=kt(t)),this._cameraEndPosition||(this._cameraEndPosition=new w),this._cameraEndPosition.copy(t),i===!0?(this._cameraLerpActive=!1,(n=this.controllerObject)==null||n.position.copy(this._cameraEndPosition)):this._cameraObject&&(this._cameraLerpActive=!0,this._cameraLerp01=0,this._cameraStartPosition.copy((r=this._cameraObject)==null?void 0:r.position),typeof i=="number"?this._cameraLerpDuration=i:this._cameraLerpDuration=this.targetLerpDuration))}get cameraLerpActive(){return this._cameraLerpActive}stopCameraLerp(){this._cameraLerpActive=!1}setLookTargetPosition(t=null,i=!1){this._controls&&t&&(t instanceof ve&&(t=kt(t)),this._lookTargetEndPosition.copy(t),DI&&(console.warn("OrbitControls: setLookTargetPosition",t,i),_t.DrawWireSphere(this._lookTargetEndPosition,.2,16711680,2)),i===!0?this._controls.target.copy(this._lookTargetEndPosition):(this._lookTargetLerpActive=!0,this._lookTargetLerp01=0,this._lookTargetStartPosition.copy(this._controls.target),typeof i=="number"?this._lookTargetLerpDuration=i:this._lookTargetLerpDuration=this.targetLerpDuration))}get lookTargetLerpActive(){return this._lookTargetLerpActive}stopLookTargetLerp(){this._lookTargetLerpActive=!1}setLookTargetFromConstraint(t=0,i=1){var r;if(!this._controls)return!1;const n=(r=this.lookAtConstraint)==null?void 0:r.sources;if(n&&n.length>0){const o=n[t];if(o)return o.getWorldPosition(this._lookTargetEndPosition),this.lerpLookTarget(this._lookTargetEndPosition,i),!0}return!1}lerpTarget(t,i){return this.lerpLookTarget(t,i)}lerpLookTarget(t,i){this._controls&&(i>=1?this._controls.target.copy(t):this._controls.target.lerp(t,i))}setTargetFromRaycast(t){if(!this.controls)return;const i=t?this.context.physics.raycastFromRay(t):this.context.physics.raycast();for(const n of i)if(n.distance>0&&re.isActiveInHierarchy(n.object)){const r=YO(n.object);if(r){const o=r.canvas;if(o!=null&&o.screenspace)break}this.setLookTargetPosition(n.point);break}}fitCamera(t,i={fitOffset:void 0,immediate:!1}){if(this.context.isInXR)return;const{immediate:n=!1,centerCamera:r}=i;let{fitOffset:o}=i;o==null&&(o=1.1);const a=this._cameraObject,l=this._controls;if(t!=null&&t.length||(t=this.context.scene.children),t.length<=0){console.warn("No objects to fit camera to...");return}if(!a||!l){console.warn("No camera or controls found to fit camera to objects...");return}const c=new w,h=new w,u=Sc(t,void 0);a.updateMatrixWorld(),a.updateProjectionMatrix(),u.getCenter(h);const f=new w;if(u.getSize(f),u.applyMatrix4(a.matrixWorldInverse),u.getSize(c),u.setFromCenterAndSize(h,c),Number.isNaN(c.x)||Number.isNaN(c.y)||Number.isNaN(c.z)){console.warn("Camera fit size resultet in NaN",a,u,[...t]);return}if(c.length()<=1e-10){Mw&&console.warn("Camera fit size is zero",u,[...t]);return}const p=a.fov,m=2*Math.atan(Math.tan(p*Math.PI/360/2)*a.aspect)/Math.PI*360,y=c.y/(2*Math.atan(Math.PI*p/360)),g=c.x/(2*Math.atan(Math.PI*m/360)),v=o*Math.max(y,g)+c.z/2;Mw&&console.log("Fit camera to objects",y,g,"distance",v),l.maxDistance=v*10,l.minDistance=v*.01;const _=.05,A=h.clone();A.y-=c.y*_,this.setLookTargetPosition(A,n),this.autoTarget=!1;const b=re.findObjectOfType(Id),S=b?b.radius:0,E=Math.max(f.x,f.y,f.z,S);a.near=v/100,a.far=E+v*10,a.updateMatrixWorld(),a.updateProjectionMatrix();const M=kt(a),T=h.clone();if(T.sub(M),r==="y"&&(T.y=0),T.normalize(),T.multiplyScalar(v),r==="y"&&(T.y+=-_*4*c.y),a.parent){const R=a.parent.worldToLocal(h.clone().sub(T));this.setCameraTargetPosition(R,n)}else console.error(`Can not fit camera ${a.name} because it has no parent`);if(Mw){const R=new aD(u);this.context.scene.add(R),VD(R,R_(a)),setTimeout(()=>{this.context.scene.remove(R)},1e4),this._haveAttachedKeyboardEvents||(this._haveAttachedKeyboardEvents=!0,document.body.addEventListener("keydown",C=>{C.code==="KeyF"&&this.fitCamera(t,{fitOffset:o,immediate:n})}))}l.update()}}yn([x()],wi.prototype,"autoTarget",2);yn([x()],wi.prototype,"autoFit",2);yn([x()],wi.prototype,"enableRotate",2);yn([x()],wi.prototype,"autoRotate",2);yn([x()],wi.prototype,"autoRotateSpeed",2);yn([x()],wi.prototype,"minAzimuthAngle",2);yn([x()],wi.prototype,"maxAzimuthAngle",2);yn([x()],wi.prototype,"minPolarAngle",2);yn([x()],wi.prototype,"maxPolarAngle",2);yn([x()],wi.prototype,"enableKeys",2);yn([x()],wi.prototype,"enableDamping",2);yn([x()],wi.prototype,"dampingFactor",2);yn([x()],wi.prototype,"enableZoom",2);yn([x()],wi.prototype,"minZoom",2);yn([x()],wi.prototype,"maxZoom",2);yn([x()],wi.prototype,"zoomSpeed",2);yn([x()],wi.prototype,"enablePan",2);yn([x(Up)],wi.prototype,"lookAtConstraint",2);yn([x()],wi.prototype,"lookAtConstraint01",2);yn([x()],wi.prototype,"allowInterrupt",2);yn([x()],wi.prototype,"middleClickToFocus",2);yn([x()],wi.prototype,"doubleClickToFocus",2);yn([x()],wi.prototype,"clickBackgroundToFitScene",2);yn([x()],wi.prototype,"targetLerpDuration",2);var qfe=Object.defineProperty,Xfe=Object.getOwnPropertyDescriptor,lo=(s,e,t,i)=>{for(var n=i>1?void 0:i?Xfe(e,t):e,r=s.length-1,o;r>=0;r--)(o=s[r])&&(n=(i?o(e,t,n):o(n))||n);return i&&n&&qfe(e,t,n),n},od=(s=>(s[s.Skybox=1]="Skybox",s[s.SolidColor=2]="SolidColor",s[s.Uninitialized=4]="Uninitialized",s))(od||{});const dh=ie("debugcam"),Rz=ie("debugscreenpointtoray");var $w;const MA=($w=class extends Ie{constructor(){super(...arguments);d(this,"_nearClipPlane",.1);d(this,"_farClipPlane",1e3);d(this,"orthographic",!1);d(this,"orthographicSize",5);d(this,"ARBackgroundAlpha",0);d(this,"_cullingMask",4294967295);d(this,"_backgroundBlurriness",0);d(this,"_backgroundIntensity",1);d(this,"_backgroundRotation");d(this,"_environmentIntensity");d(this,"_targetTexture",null);d(this,"_backgroundColor");d(this,"_fov");d(this,"_cam",null);d(this,"_clearFlags",2);d(this,"_skybox");d(this,"_frustum");d(this,"_projScreenMatrix",new ye)}get isCamera(){return!0}get aspect(){return this._cam instanceof Gt?this._cam.aspect:this.context.domWidth/this.context.domHeight}set aspect(e){this._cam instanceof Gt&&this._cam.aspect!==e&&(this._cam.aspect=e,this._cam.updateProjectionMatrix())}get fieldOfView(){return this._cam instanceof Gt?this._cam.fov:this._fov}set fieldOfView(e){const t=this.fieldOfView!=e;if(this._fov=e,t&&this._cam&&this._cam instanceof Gt){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(e){const t=this._nearClipPlane!=e;this._nearClipPlane=e,this._cam&&t&&(this._cam.near=e,this._cam.updateProjectionMatrix())}get farClipPlane(){return this._farClipPlane}set farClipPlane(e){const t=this._farClipPlane!=e;this._farClipPlane=e,this._cam&&t&&(this._cam.far=e,this._cam.updateProjectionMatrix())}get clearFlags(){return this._clearFlags}set clearFlags(e){e!==this._clearFlags&&(this._clearFlags=e,this.applyClearFlagsIfIsActiveCamera())}set cullingMask(e){this._cullingMask=e,this._cam&&(this._cam.layers.mask=e)}get cullingMask(){return this._cam?this._cam.layers.mask:this._cullingMask}set cullingLayer(e){this.cullingMask=(1<<e|0)>>>0}set backgroundBlurriness(e){e!==this._backgroundBlurriness&&(e===void 0?this._backgroundBlurriness=void 0:this._backgroundBlurriness=Math.min(Math.max(e,0),1),this.applyClearFlagsIfIsActiveCamera())}get backgroundBlurriness(){return this._backgroundBlurriness}set backgroundIntensity(e){e!==this._backgroundIntensity&&(e===void 0?this._backgroundIntensity=void 0:this._backgroundIntensity=Math.min(Math.max(e,0),10),this.applyClearFlagsIfIsActiveCamera())}get backgroundIntensity(){return this._backgroundIntensity}set backgroundRotation(e){e!==this._backgroundRotation&&(e===void 0?this._backgroundRotation=void 0:this._backgroundRotation=e,this.applyClearFlagsIfIsActiveCamera())}get backgroundRotation(){return this._backgroundRotation}set environmentIntensity(e){this._environmentIntensity=e}get environmentIntensity(){return this._environmentIntensity}get backgroundColor(){return this._backgroundColor??null}set backgroundColor(e){if(e){if(this._backgroundColor)this._backgroundColor.copy(e);else{if(!e.clone)return;this._backgroundColor=e.clone()}e.alpha===void 0&&(this._backgroundColor.alpha=1),this.applyClearFlagsIfIsActiveCamera()}}set targetTexture(e){this._targetTexture=e}get targetTexture(){return this._targetTexture}get cam(){return this.activeAndEnabled&&this.buildCamera(),this._cam}screenPointToRay(e,t,i){const n=this.cam,r=MA._origin;r.set(e,t,-1),this.context.input.convertScreenspaceToRaycastSpace(r),Rz&&console.log("screenPointToRay",e.toFixed(2),t.toFixed(2),"now:",r.x.toFixed(2),r.y.toFixed(2),"isInXR:"+this.context.isInXR),r.z=-1,r.unproject(n);const o=MA._direction.set(r.x,r.y,r.z),a=kt(n);return o.sub(a),o.normalize(),i?(i.set(a,o),i):new Mo(a.clone(),o.clone())}getFrustum(){return this._frustum||(this._frustum=new mp,this.updateFrustum()),this._frustum}updateFrustum(){this._frustum||(this._frustum=new mp),this._frustum.setFromProjectionMatrix(this.getProjectionScreenMatrix(this._projScreenMatrix,!0),this.context.renderer.coordinateSystem)}getProjectionScreenMatrix(e,t){return t&&this._projScreenMatrix.multiplyMatrices(this.cam.projectionMatrix,this.cam.matrixWorldInverse),e===this._projScreenMatrix?e:e.copy(this._projScreenMatrix)}awake(){Rz&&window.addEventListener("pointerdown",e=>{const t=e.clientX,i=e.clientY;console.log("touch",t.toFixed(2),i.toFixed(2));const n=this.screenPointToRay(t,i),r="#"+Math.floor(Math.random()*16777215).toString(16);_t.DrawRay(n.origin,n.direction,r,10)})}onEnable(){dh&&console.log(`Camera enabled: "${this.name}". ClearFlags=${od[this._clearFlags]}`,this),this.buildCamera(),(this.tag=="MainCamera"||!this.context.mainCameraComponent)&&(this.context.setCurrentCamera(this),Kfe(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 e=this.context.renderer;if(e){const t=this.context.mainCameraComponent;this.applyClearFlags(),this._targetTexture.render(this.context.scene,this._cam,e),t==null||t.applyClearFlags()}}}buildCamera(){if(this._cam)return;const e=this.gameObject.isCamera;let t=null;if(e?(t=this.gameObject,t==null||t.layers.enableAll(),t instanceof Gt&&(this._fov=t.fov)):t=this.gameObject.children[0],t&&t.isCamera)t instanceof Gt&&(this._fov&&(t.fov=this._fov),t.near=this._nearClipPlane,t.far=this._farClipPlane,t.updateProjectionMatrix());else if(!this.orthographic)t=new Gt(this.fieldOfView,window.innerWidth/window.innerHeight,this._nearClipPlane,this._farClipPlane),this.fieldOfView&&(t.fov=this.fieldOfView),this.gameObject.add(t);else{const i=this.orthographicSize*100;t=new Mc(window.innerWidth/-i,window.innerWidth/i,window.innerHeight/i,window.innerHeight/-i,this._nearClipPlane,this._farClipPlane),this.gameObject.add(t)}this._cam=t,this._cam.layers.mask=this._cullingMask,this.tag=="MainCamera"&&this.context.setCurrentCamera(this)}applyClearFlagsIfIsActiveCamera(e){this.context.mainCameraComponent===this&&this.applyClearFlags(e)}applyClearFlags(e){if(!this._cam){dh&&console.log("Camera does not exist (apply clear flags)");return}if(this.fieldOfView=this._fov,dh){const t=`Camera "${this.name}" clear flags: ${od[this._clearFlags]}`;console.debug(t)}switch(this._clearFlags){case 1:if(MA.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||(e==null?void 0:e.applySkybox)===!0)&&this.applySceneSkybox(),this._backgroundBlurriness!==void 0?this.context.scene.backgroundBlurriness=this._backgroundBlurriness:dh&&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:dh&&console.warn(`Camera "${this.name}" has no background intensity`);break;case 2:if(this._backgroundColor){let t=this._backgroundColor.alpha;MA.backgroundShouldBeTransparent(this.context)&&(t=this.ARBackgroundAlpha??0),this.context.scene.background=null,this.context.renderer.setClearColor(this._backgroundColor,t)}else dh&&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 Yfe(this)),this._skybox.apply()}static backgroundShouldBeTransparent(e){var r,o,a,l;const t=(r=e.renderer.xr)==null?void 0:r.getSession();if(!t)return!1;if(typeof t._transparent=="boolean")return t._transparent;const i=t.environmentBlendMode;dh&&pn("Environment blend mode: "+i+" on "+navigator.userAgent);let n=i==="additive"||i==="alpha-blend";return e.isInAR&&i==="opaque"&&((o=navigator.userAgent)!=null&&o.includes("OculusBrowser")||(a=navigator.userAgent)!=null&&a.includes("Mozilla")&&((l=navigator.userAgent)!=null&&l.includes("Mobile WebXRViewer/v2")))&&(n=!0),t._transparent=n,n}},d($w,"_origin",new w),d($w,"_direction",new w),$w);let Gi=MA;lo([x()],Gi.prototype,"aspect",1);lo([x()],Gi.prototype,"fieldOfView",1);lo([x()],Gi.prototype,"nearClipPlane",1);lo([x()],Gi.prototype,"farClipPlane",1);lo([x()],Gi.prototype,"clearFlags",1);lo([x()],Gi.prototype,"orthographic",2);lo([x()],Gi.prototype,"orthographicSize",2);lo([x()],Gi.prototype,"ARBackgroundAlpha",2);lo([x()],Gi.prototype,"cullingMask",1);lo([x()],Gi.prototype,"backgroundBlurriness",1);lo([x()],Gi.prototype,"backgroundIntensity",1);lo([x(oi)],Gi.prototype,"backgroundRotation",1);lo([x()],Gi.prototype,"environmentIntensity",1);lo([x(Mi)],Gi.prototype,"backgroundColor",1);lo([x(rd)],Gi.prototype,"targetTexture",1);class Yfe{constructor(e){d(this,"_camera");d(this,"_skybox");this._camera=e}get context(){var e;return(e=this._camera)==null?void 0:e.context}apply(){this._skybox=this.context.lightmaps.tryGetSkybox(this._camera.sourceId),this._skybox?this.context.scene.background!==this._skybox&&(dh&&console.log(`Camera "${this._camera.name}" set skybox`,this._camera,this._skybox),this._skybox.mapping=xo,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)),(dh||lt())&&Ni(`Camera "${this._camera.name}" has no skybox texture`))}}function Kfe(s){ie("freecam")&&s.context.mainCameraComponent===s&&re.getOrAddComponent(s.gameObject,wi)}class ad extends Ie{constructor(){super(...arguments);d(this,"_listener",null);d(this,"onInteraction",()=>{this.destroyed||this.listener==null||this.addListenerIfItExists()})}get listener(){return this._listener==null&&(this._listener=new dV),this._listener}onEnable(){vc.registerWaitForInteraction(this.onInteraction),this.addListenerIfItExists()}onDisable(){vc.unregisterWaitForInteraction(this.onInteraction),this.removeListenerIfItExists()}addListenerIfItExists(){const t=this._listener;if(!t||t!=null&&t.parent)return;const i=this.context.mainCameraComponent||re.getComponentInParent(this.gameObject,Gi);i!=null&&i.cam?i.cam.add(t):this.gameObject.add(t),t.filter?(t.gain.connect(t.filter),t.filter.connect(t.context.destination)):t.gain.connect(t.context.destination)}removeListenerIfItExists(){const t=this._listener;t&&(t.removeFromParent(),t.filter&&t.filter.disconnect(),t.gain&&t.gain.disconnect())}}class Jfe extends Dn{constructor(e,t=1,i=16,n=2){const r=new wt,o=i+n*2,a=new Float32Array((o*3+3)*3);r.setAttribute("position",new ot(a,3));const l=new Zi({color:65280}),c=new Zi({color:16776960});super(r,[c,l]),this.audio=e,this.range=t,this.divisionsInnerAngle=i,this.divisionsOuterAngle=n,this.type="PositionalAudioHelper",this.update()}update(){const e=this.audio,t=this.range,i=this.divisionsInnerAngle,n=this.divisionsOuterAngle,r=fi.degToRad(e.panner.coneInnerAngle),o=fi.degToRad(e.panner.coneOuterAngle),a=r/2,l=o/2;let c=0,h=0,u,f;const p=this.geometry,m=p.attributes.position;p.clearGroups();function y(g,v,_,A){const b=(v-g)/_;for(m.setXYZ(c,0,0,0),h++,u=g;u<v;u+=b)f=c+h,m.setXYZ(f,Math.sin(u)*t,0,Math.cos(u)*t),m.setXYZ(f+1,Math.sin(Math.min(u+b,v))*t,0,Math.cos(Math.min(u+b,v))*t),m.setXYZ(f+2,0,0,0),h+=3;p.addGroup(c,h,A),c+=h,h=0}y(-l,-a,n,0),y(-a,a,i,1),y(a,l,n,0),m.needsUpdate=!0,r===o&&(this.material[0].visible=!1)}dispose(){this.geometry.dispose(),this.material[0].dispose(),this.material[1].dispose()}}var Zfe=Object.defineProperty,$fe=Object.getOwnPropertyDescriptor,Pc=(s,e,t,i)=>{for(var n=i>1?void 0:i?$fe(e,t):e,r=s.length-1,o;r>=0;r--)(o=s[r])&&(n=(i?o(e,t,n):o(n))||n);return i&&n&&Zfe(e,t,n),n};const br=ie("debugaudio"),Bu=class extends Ie{constructor(){super(...arguments);d(this,"clip","");d(this,"playOnAwake",!1);d(this,"preload",!1);d(this,"_spatialBlend",0);d(this,"_minDistance",1);d(this,"_maxDistance",100);d(this,"_volume",1);d(this,"rollOffMode",0);d(this,"playInBackground",!0);d(this,"_loop",!1);d(this,"sound",null);d(this,"helper",null);d(this,"wasPlaying",!1);d(this,"audioLoader",null);d(this,"shouldPlay",!1);d(this,"_lastClipStartedLoading",null);d(this,"_audioElement",null);d(this,"onVisibilityChanged",()=>{switch(document.visibilityState){case"hidden":(this.playInBackground===!1||qa())&&(this.wasPlaying=this.isPlaying,this.isPlaying&&this.pause());break;case"visible":br&&console.log("visible",this.enabled,this.playOnAwake,!this.isPlaying,Bu.userInteractionRegistered,this.wasPlaying),this.enabled&&this.playOnAwake&&!this.isPlaying&&Bu.userInteractionRegistered&&this.wasPlaying&&this.play();break}});d(this,"onApplicationMuteChanged",()=>{var e,t;this.context.application.muted?(e=this.sound)==null||e.setVolume(0):(t=this.sound)==null||t.setVolume(this.volume)});d(this,"createAudio",e=>{br&&console.log("AudioBuffer finished loading",e);const t=this.Sound;if(!t){br&&console.warn("Failed getting sound?",this.name);return}t.isPlaying&&t.stop(),e&&t.setBuffer(e),t.loop=this._loop,this.context.application.muted?t.setVolume(0):t.setVolume(this.volume),t.autoplay=this.shouldPlay&&Bu.userInteractionRegistered,this.applySpatialDistanceSettings(),t.isPlaying&&t.stop(),Bu.registerWaitForAllowAudio(this.__onAllowAudioCallback)});d(this,"__onAllowAudioCallback",()=>{this.shouldPlay&&this.play()});d(this,"_lastContextTime",0);d(this,"_hasEnded",!0);d(this,"_needUpdateSpatialDistanceSettings",!1)}static get userInteractionRegistered(){return vc.userInteractionRegistered}static registerWaitForAllowAudio(e){vc.registerWaitForAllowAudio(e)}get loop(){return this.sound&&(this._loop=this.sound.getLoop()),this._loop}set loop(e){this._loop=e,this.sound&&this.sound.setLoop(e)}get spatialBlend(){return this._spatialBlend}set spatialBlend(e){e!==this._spatialBlend&&(this._spatialBlend=e,this._needUpdateSpatialDistanceSettings=!0)}get minDistance(){return this._minDistance}set minDistance(e){this._minDistance!==e&&(this._minDistance=e,this._needUpdateSpatialDistanceSettings=!0)}get maxDistance(){return this._maxDistance}set maxDistance(e){this._maxDistance!==e&&(this._maxDistance=e,this._needUpdateSpatialDistanceSettings=!0)}get volume(){return this._volume}set volume(e){this._volume=e,this.sound&&!this.context.application.muted&&(br&&console.log(this.name,"audio set volume",e),this.sound.setVolume(e))}get Sound(){var e;if(!this.sound&&Bu.userInteractionRegistered){let t=re.getComponent(this.context.mainCamera,ad)??re.findObjectOfType(ad,this.context);!t&&this.context.mainCamera&&(t=re.addNewComponent(this.context.mainCamera,ad)),t!=null&&t.listener?(this.sound=new fV(t.listener),(e=this.gameObject)==null||e.add(this.sound)):br&&console.warn("No audio listener found in scene - can not play audio")}return this.sound}get ShouldPlay(){return this.shouldPlay}get audioContext(){var e;return(e=this.sound)==null?void 0:e.context}awake(){br&&console.log(this),this.audioLoader=new rC,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),Bu.userInteractionRegistered?this.playOnAwake&&this.context.application.isVisible&&this.play():Bu.registerWaitForAllowAudio(()=>{this.enabled&&!this.destroyed&&this.shouldPlay&&this.onNewClip(this.clip)}),globalThis.addEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.addEventListener(IC.MuteChanged,this.onApplicationMuteChanged)}onDisable(){globalThis.removeEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.removeEventListener(IC.MuteChanged,this.onApplicationMuteChanged),this.pause()}applySpatialDistanceSettings(){const e=this.sound;if(!e)return;this._needUpdateSpatialDistanceSettings=!1;const t=it.lerp(10*this._maxDistance/Math.max(1e-4,this.spatialBlend),this._minDistance,this.spatialBlend);switch(br&&console.log(this.name,this._minDistance,this._maxDistance,this.spatialBlend,"Ref distance="+t),e.setRefDistance(t),e.setMaxDistance(Math.max(.01,this._maxDistance)),this.rollOffMode){case 0:e.setDistanceModel("exponential");break;case 1:e.setDistanceModel("linear");break;case 2:console.warn("Custom rolloff for AudioSource is not supported: "+this.name);break}this.spatialBlend>0?br&&!this.helper&&(this.helper=new Jfe(e,e.getRefDistance()),e.add(this.helper)):this.helper&&this.helper.parent&&this.helper.removeFromParent()}async onNewClip(e){if(e&&(this.clip=e),typeof e=="string")if(br&&console.log(e),e.endsWith(".mp3")||e.endsWith(".wav")){if(this.audioLoader||(this.audioLoader=new rC),this.shouldPlay=!0,this._lastClipStartedLoading===e){br&&console.log("Is currently loading:",this._lastClipStartedLoading,this);return}this._lastClipStartedLoading=e,br&&console.log("load audio",e);const t=await this.audioLoader.loadAsync(e).catch(console.error);this._lastClipStartedLoading=null,t&&this.createAudio(t)}else console.warn("Unsupported audio clip type",e);else this.shouldPlay=!0,this.createAudio()}play(e=void 0){var i,n,r;!e&&this.clip&&(e=this.clip),e!==void 0&&typeof e!="string"&&!(e instanceof MediaStream)&&(lt()&&console.warn("Called play on AudioSource with unknown argument type:",e+`
|
|
5733
5733
|
Using the assigned clip instead:`,this.clip),e=this.clip);let t=!this.sound||e&&e!==this.clip;if(typeof e=="string"&&!this.audioLoader&&(t=!0),(e instanceof MediaStream||typeof e=="string")&&(this.clip=e),t){this.shouldPlay=!0,this.onNewClip(e);return}if(this.shouldPlay=!0,this._hasEnded=!1,br&&console.log("play",(i=this.sound)==null?void 0:i.getVolume(),this.sound),this.sound&&!this.sound.isPlaying){const o=this.context.application.muted;o&&this.sound.setVolume(0),(n=this.gameObject)==null||n.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||(r=this.context.domElement.shadowRoot)==null||r.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 e,t;br&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.isPlaying&&this.sound.source&&(this._lastContextTime=(e=this.sound)==null?void 0:e.context.currentTime,this.sound.pause()),(t=this._audioElement)==null||t.remove()}stop(){var e,t;br&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.source&&(this._lastContextTime=(e=this.sound)==null?void 0:e.context.currentTime,br&&console.log(this._lastContextTime),this.sound.stop()),(t=this._audioElement)==null||t.remove()}get isPlaying(){var e;return((e=this.sound)==null?void 0:e.isPlaying)??!1}set isPlaying(e){}get time(){var e,t;return(e=this.sound)!=null&&e.source?((t=this.sound.source)==null?void 0:t.context.currentTime)-this._lastContextTime+this.sound.offset:0}set time(e){if(this.sound){if(e===this.sound.offset)return;const t=this.isPlaying;this.stop(),this.sound.offset=e,t&&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,br&&console.log("Audio clip ended",this.clip),this.dispatchEvent(new CustomEvent("ended",{detail:this})))}};let Un=Bu;Pc([x(URL)],Un.prototype,"clip",2);Pc([x()],Un.prototype,"playOnAwake",2);Pc([x()],Un.prototype,"preload",2);Pc([x()],Un.prototype,"loop",1);Pc([x()],Un.prototype,"spatialBlend",1);Pc([x()],Un.prototype,"minDistance",1);Pc([x()],Un.prototype,"maxDistance",1);Pc([x()],Un.prototype,"volume",1);Pc([x()],Un.prototype,"rollOffMode",2);Pc([x()],Un.prototype,"playInBackground",2);var epe=Object.defineProperty,tpe=Object.getOwnPropertyDescriptor,EE=(s,e,t,i)=>{for(var n=i>1?void 0:i?tpe(e,t):e,r=s.length-1,o;r>=0;r--)(o=s[r])&&(n=(i?o(e,t,n):o(n))||n);return i&&n&&epe(e,t,n),n};const ipe=ie("debugsignals");class K_{constructor(){d(this,"guid")}}EE([x()],K_.prototype,"guid",2);class Gy{constructor(){d(this,"signal");d(this,"reaction")}}EE([x(K_)],Gy.prototype,"signal",2);EE([x(Xn)],Gy.prototype,"reaction",2);var _R;const oh=(_R=class extends Ie{constructor(){super(...arguments);d(this,"events")}static invoke(e){if(oh.receivers[e]){const t=oh.receivers[e];if(!t)return;for(const i of t)i.invoke(e)}}awake(){ipe&&console.log("SignalReceiver awake",this)}onEnable(){if(this.events)for(const e of this.events)oh.receivers[e.signal.guid]||(oh.receivers[e.signal.guid]=[]),oh.receivers[e.signal.guid].push(this)}onDisable(){if(this.events){for(const e of this.events)if(oh.receivers[e.signal.guid]){const t=oh.receivers[e.signal.guid].indexOf(this);t>=0&&oh.receivers[e.signal.guid].splice(t,1)}}}invoke(e){if(!this.events||!Array.isArray(this.events))return;const t=typeof e=="object"?e.guid:e;for(const i of this.events)if(i.signal.guid===t)try{if(i.reaction){if(!i.reaction.invoke){console.warn("Missing invoke - possibly a serialization error",i,this);continue}}else{console.warn("Missing reaction for signal",i,this);continue}i.reaction.invoke()}catch(n){console.error(n)}}},d(_R,"receivers",{}),_R);let Hy=oh;EE([x(Gy)],Hy.prototype,"events",2);var zo=(s=>(s.Activation="ActivationTrack",s.Animation="AnimationTrack",s.Audio="AudioTrack",s.Control="ControlTrack",s.Marker="MarkerTrack",s.Signal="SignalTrack",s))(zo||{}),Kl=(s=>(s[s.None=0]="None",s[s.Hold=1]="Hold",s[s.Loop=2]="Loop",s[s.PingPong=3]="PingPong",s[s.Continue=4]="Continue",s))(Kl||{}),KO=(s=>(s.Signal="SignalEmitter",s))(KO||{});const dc=ie("debugtimeline");class J_{constructor(){d(this,"director");d(this,"track")}get muted(){return this.track.muted}set muted(e){var t;e!==this.track.muted&&(this.track.muted=e,(t=this.onMuteChanged)==null||t.call(this))}*forEachClip(e=!1){var t;if((t=this.track)!=null&&t.clips)if(e)for(let i=this.track.clips.length-1;i>=0;i--)yield this.track.clips[i];else for(const i of this.track.clips)yield i}getClipTime(e,t){return t.clipIn+(e-t.start)*t.timeScale}getClipTimeNormalized(e,t){return(e-t.start)/t.duration}evaluateWeight(e,t,i,n=!0){if(t<0||t>=i.length)return 0;const r=i[t];if(n||e>=r.start&&e<=r.end){let o=1;const a=!1;if(r.easeInDuration>0){const l=Math.min((e-r.start)/r.easeInDuration,1);o*=l}if(r.easeOutDuration>0&&!a){const l=Math.min((r.end-e)/r.easeOutDuration,1);o*=l}return o}return 0}}class npe{constructor(e){d(this,"clip");d(this,"rootPositionOffset");d(this,"rootQuaternionOffset");d(this,"rootStartPosition");d(this,"rootEndPosition");d(this,"rootStartQuaternion");d(this,"rootEndQuaternion");const t=e.getClip();this.clip=t;const i=e.getRoot(),n=i.name+".position",r=i.name+".quaternion";dc&&console.log(t.name,t.tracks,n);for(const o of t.tracks)if(!(o.times.length<=0)){if(o.name.endsWith(n))this.rootStartPosition=new w().fromArray(o.values,0),this.rootEndPosition=new w().fromArray(o.values,o.values.length-3),this.rootPositionOffset=this.rootEndPosition.clone().sub(this.rootStartPosition),dc&&console.log(this.rootPositionOffset);else if(o.name.endsWith(r)&&(this.rootStartQuaternion=new Ce().fromArray(o.values,0),this.rootEndQuaternion=new Ce().fromArray(o.values,o.values.length-4),this.rootQuaternionOffset=this.rootEndQuaternion.clone().multiply(this.rootStartQuaternion),dc)){const a=new oi().setFromQuaternion(this.rootQuaternionOffset);console.log("ROT",a)}}}get hasOffsets(){return this.rootPositionOffset!==void 0||this.rootQuaternionOffset!==void 0}}class ME extends J_{constructor(){super(...arguments);d(this,"models",[]);d(this,"trackOffset");d(this,"target");d(this,"mixer");d(this,"clips",[]);d(this,"actions",[]);d(this,"_actionOffsets",[]);d(this,"_didBind",!1);d(this,"_animator",null);d(this,"_useclipOffsets",!0);d(this,"_totalOffsetPosition",new w);d(this,"_totalOffsetRotation",new Ce);d(this,"_totalOffsetPosition2",new w);d(this,"_totalOffsetRotation2",new Ce);d(this,"_summedPos",new w);d(this,"_tempPos",new w);d(this,"_summedRot",new Ce);d(this,"_tempRot",new Ce);d(this,"_clipRotQuat",new Ce)}onDisable(){var t;(t=this.mixer)==null||t.stopAllAction()}onDestroy(){this.director.context.animations.unregisterAnimationMixer(this.mixer)}onStateChanged(){this._animator&&Pz(this._animator.gameObject,this,this.director.isPlaying)}createHooks(t,i){var h,u;if(((h=i.tracks)==null?void 0:h.length)<=0){console.warn("No tracks in AnimationClip",i);return}const n=i.tracks[0].name.split("."),r=n[n.length-2],o=r+".position",a=r+".quaternion";let l=!1,c=!1;for(const f of i.tracks)f.name.endsWith(o)?(l=!0,this.createPositionInterpolant(i,t,f)):f.name.endsWith(a)&&(c=!0,this.createRotationInterpolant(i,t,f));if(!l||!c){const f=(u=this.mixer)==null?void 0:u.getRoot(),p=i.tracks[0],m=p.name.lastIndexOf("."),y=p.name.substring(0,m),g=y.substring(y.lastIndexOf(".")+1),v=f.getObjectByName(g);if(v)if(l){if(!c){const _=i.tracks[0].name.substring(0,m)+".quaternion";dc&&console.warn("Create quaternion track",g,v);const A=v.quaternion,b=new Ua(_,[0,i.duration],[A.x,A.y,A.z,A.w,A.x,A.y,A.z,A.w]);i.tracks.push(b),this.createRotationInterpolant(i,t,b)}}else{const _=y+".position";dc&&console.warn("Create position track",g,v);const A=v.position,b=new xc(_,[0,i.duration],[A.x,A.y,A.z,A.x,A.y,A.z]);i.tracks.push(b),this.createPositionInterpolant(i,t,b)}}}bind(){if(!this._didBind){this._didBind=!0,dc&&console.log(this.models),this.mixer?this.target=this.mixer.getRoot():console.warn("No mixer was assigned to animation track");for(const t of this.actions){const i=new npe(t);this._actionOffsets.push(i)}this.target&&(this._animator=re.getComponent(this.target,or)??null,this._animator&&Pz(this._animator.gameObject,this,!0));for(const t of this.models){const i=t.asset,n=i.position,r=i.rotation;n&&n.x!==void 0&&(n.isVector3||(i.position=new w(n.x,n.y,n.z)),r.isQuaternion||(i.rotation=new Ce(r.x,r.y,r.z,r.w)))}this.ensureTrackOffsets()}}ensureTrackOffsets(){if(this.trackOffset){const t=this.trackOffset.position;t&&(t.isVector3||(this.trackOffset.position=new w(t.x,t.y,t.z)));const i=this.trackOffset.rotation;i&&(i.isQuaternion||(this.trackOffset.rotation=new Ce(i.x,i.y,i.z,i.w)))}}evaluate(t){var l,c,h,u,f,p,m;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 i=0,n=0,r=!1,o=!1,a=0;for(let y=0;y<this.clips.length;y++){const g=this.models[y],v=this.actions[y],_=g.asset;v.weight=0;const A=t>=g.start&&t<=g.end,b=g.preExtrapolationMode,S=g.postExtrapolationMode,E=y<this.clips.length-1?this.models[y+1]:null;let M=A,T=!1;if(!M&&!r&&g.end<t&&S!==Kl.None?(!E||E.start>t)&&(M=!0,r=!0):y==0&&!M&&!o&&g.start>t&&b!==Kl.None&&(!E||E.start<t)&&(M=!0,T=!0,o=!0),M){let R=1;R*=this.evaluateWeight(t,y,this.models,M),R*=this.director.weight;let C=A;if(T)switch(b){case Kl.Hold:break;case Kl.Loop:t+=g.start,C=!0;break;default:t+=g.start,C=!0;break}let I=this.getClipTime(t,g),F=0;const U=_.duration;if(T&&b===Kl.Hold&&(I=0),C){if(_.loop)for(F+=Math.floor(I/(U+1e-6));I>U;)I-=U}else if(!A&&r)switch(S){case Kl.Hold:I=this.getClipTime(g.end,g);break;case Kl.Loop:I%=U;break;case Kl.PingPong:const D=Math.floor(I/U)%2!==0;I%=U,D&&(I=U-I);break}g.reversed===!0?v.time=v.getClip().duration-I:v.time=I,v.timeScale=0;const O=Math.max(0,R);if(v.weight=O,a+=O,v.clampWhenFinished=!1,v.isRunning()||v.play(),this._useclipOffsets){const Q=i==0?this._totalOffsetPosition:this._totalOffsetPosition2,D=i==0?this._totalOffsetRotation:this._totalOffsetRotation2;i<1&&(n=1-R),i+=1;const k=this._summedPos.set(0,0,0),z=this._tempPos.set(0,0,0),q=this._summedRot.identity(),X=this._tempRot.identity(),se=_.rotation;se&&(this._clipRotQuat.identity(),this._clipRotQuat.slerp(se,R));const le=this._actionOffsets[y];if(le.hasOffsets)for(let Me=0;Me<F;Me++)le.rootPositionOffset?z.copy(le.rootPositionOffset):z.set(0,0,0),z.applyQuaternion(q),this._clipRotQuat&&z.applyQuaternion(this._clipRotQuat),le.rootQuaternionOffset&&(X.copy(le.rootQuaternionOffset),q.multiply(X)),k.add(z);this._clipRotQuat&&D.multiply(this._clipRotQuat),D.multiply(q),_.position&&k.add(_.position),Q.add(k)}}}if(this._useclipOffsets&&(this._totalOffsetPosition.lerp(this._totalOffsetPosition2,n),this._totalOffsetRotation.slerp(this._totalOffsetRotation2,n)),this.__mixerError===void 0&&(dc||lt())&&((c=(l=this._animator)==null?void 0:l.runtimeAnimatorController)!=null&&c.mixer)&&this.mixer!==((u=(h=this._animator)==null?void 0:h.runtimeAnimatorController)==null?void 0:u.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)),(f=this._animator)!=null&&f.runtimeAnimatorController){const y=Math.max(0,1-a);(m=(p=this._animator)==null?void 0:p.runtimeAnimatorController)==null||m.update(y)}else this.mixer.update(t)}createRotationInterpolant(t,i,n){var l;const r=n.createInterpolant.bind(n),o=new Ce;this.ensureTrackOffsets();const a=(l=this.trackOffset)==null?void 0:l.rotation;n.createInterpolant=()=>{const c=r(),h=c.evaluate.bind(c);return c.evaluate=u=>{var p;const f=h(u);if(o.set(f[0],f[1],f[2],f[3]),o.premultiply(this._totalOffsetRotation),a&&o.premultiply(a),this.director.animationCallbackReceivers)for(const m of this.director.animationCallbackReceivers)(p=m==null?void 0:m.onTimelineRotation)==null||p.call(m,this.director,this.target,u,o);return f[0]=o.x,f[1]=o.y,f[2]=o.z,f[3]=o.w,f},c}}createPositionInterpolant(t,i,n){var h,u;const r=n.createInterpolant.bind(n),o=new w;this.ensureTrackOffsets();const a=(h=this.trackOffset)==null?void 0:h.rotation,l=(u=this.trackOffset)==null?void 0:u.position;let c;n.createInterpolant=()=>{const f=r(),p=f.evaluate.bind(f);return f.evaluate=m=>{var g,v,_;const y=p(m);if(o.set(y[0],y[1],y[2]),i.removeStartOffset&&(c===void 0?(c=null,c=(v=(g=this._actionOffsets.find(A=>A.clip===t))==null?void 0:g.rootStartPosition)==null?void 0:v.clone()):c!=null&&c.isVector3&&o.sub(c)),o.applyQuaternion(this._totalOffsetRotation),o.add(this._totalOffsetPosition),a&&o.applyQuaternion(a),l&&(o.x-=l.x,o.y+=l.y,o.z+=l.z),this.director.animationCallbackReceivers)for(const A of this.director.animationCallbackReceivers)(_=A==null?void 0:A.onTimelinePosition)==null||_.call(A,this.director,this.target,m,o);return y[0]=o.x,y[1]=o.y,y[2]=o.z,y},f}}}const spe=ie("mutetimeline"),Fg=class extends J_{constructor(){super(...arguments);d(this,"models",[]);d(this,"listener");d(this,"audio",[]);d(this,"audioContextTimeOffset",[]);d(this,"lastTime",0);d(this,"audioSource");d(this,"_audioLoader",null);d(this,"_playableDirectorResumed",!1)}getAudioFilePath(t){const i=this.director.sourceId;return wd(i,t)}onAllowAudioChanged(t){for(let i=0;i<this.models.length;i++){const n=this.models[i];this.audio[i].setVolume(t?n.asset.volume:0)}}addModel(t){const i=new nD(this.listener);this.audio.push(i);const n=t;n._didTriggerPlay=!1,this.models.push(n)}onDisable(){for(const t of this.audio)t.isPlaying&&t.stop();for(const t of this.models)t._didTriggerPlay=!1}onDestroy(){for(const t of this.audio)t.source&&(t==null||t.disconnect());this.audio.length=0}onMuteChanged(){if(this.muted)for(let t=0;t<this.audio.length;t++){const i=this.audio[t];i!=null&&i.isPlaying&&i.stop()}}stop(){for(let t=0;t<this.audio.length;t++){const i=this.audio[t];i!=null&&i.isPlaying&&i.stop()}for(const t of this.models)t._didTriggerPlay=!1}onPauseChanged(){for(let t=0;t<this.audio.length;t++){const i=this.audio[t];i!=null&&i.isPlaying&&i.stop()}this._playableDirectorResumed=this.director.isPlaying}evaluate(t){if(spe||this.track.muted||this.director.speed<0)return;const i=this.director.context.application.muted,n=this._playableDirectorResumed;this._playableDirectorResumed=!1;const r=i?.1:0;for(let o=0;o<this.models.length;o++){const a=this.models[o],l=this.audio[o],c=a.asset;if((!l||!l.buffer)&&this.isInTimeRange(a,t-1,t+1)&&this.handleAudioLoading(a,l),Un.userInteractionRegistered!==!1&&!(l===null||!l.buffer))if(l.playbackRate=this.director.context.time.timeScale*this.director.speed,l.loop=c.loop,t>=a.start&&t<=a.end&&t<this.director.duration){if(!l.isPlaying||!this.director.isPlaying)(n||!a._didTriggerPlay&&this.lastTime<t)&&(a.duration*a.timeScale>.3?l.offset=a.clipIn+(t-a.start)*a.timeScale:l.offset=0,dc&&console.log("Timeline Audio ("+this.track.name+") play with offset "+l.offset+" - "+a.asset.clip),l.play(r),a._didTriggerPlay=!0);else{const u=a.clipIn+(t-a.start)*a.timeScale,f=l.context.currentTime-l._startedAt+l.offset;Math.abs(u-f)>.3&&(l.offset=u,l.stop(),l.play(r))}let h=c.volume;if(this.track.volume!==void 0&&(h*=this.track.volume),i&&(h=0),a.easeInDuration>0){const u=Math.min((t-a.start)/a.easeInDuration,1);h*=u}if(a.easeOutDuration>0){const u=Math.min((a.end-t)/a.easeOutDuration,1);h*=u}l.setVolume(h*this.director.weight)}else a._didTriggerPlay=!1,this.director.isPlaying&&l.isPlaying&&l.stop()}this.lastTime=t}loadAudio(t,i=0,n=0){let r=null;const o=t-n,a=t+i;for(const l of this.models)if(this.isInTimeRange(l,o,a)){const c=this.audio[this.models.indexOf(l)],h=this.handleAudioLoading(l,c);h!==null&&(r===null&&(r=[]),r.push(h))}return r!==null?Promise.all(r):null}isInTimeRange(t,i,n){return i<=t.start&&n>=t.end||i>=t.start&&i<=t.end||n>=t.start&&n<=t.end}static dispose(){Fg._audioBuffers.clear()}handleAudioLoading(t,i){this._audioLoader||(this._audioLoader=new rC);const n=this.getAudioFilePath(t.asset.clip);if(Fg._audioBuffers.get(n)){const o=Fg._audioBuffers.get(n);return o.then(a=>{a&&i.setBuffer(a)}),o}dc&&console.warn("LOAD audio track",n,this.director.sourceId);const r=new Promise((o,a)=>{this._audioLoader.load(n,l=>{i.setBuffer(l),o(l)},void 0,l=>{console.error("Error loading audio",l),o(null)})});return Fg._audioBuffers.set(n,r),r}};let rp=Fg;d(rp,"_audioBuffers",new Map);class J0 extends J_{constructor(){super(...arguments);d(this,"models",[]);d(this,"didTrigger",[]);d(this,"receivers",[])}evaluate(t){var n;if(this.track.muted)return;const i=this.director.context.time.deltaTime*1.5;for(let r=0;r<this.models.length;r++){const o=this.models[r],a=this.didTrigger[r],l=o.time-t;let c=!1;if(o.retroActive)c=l<=1e-6;else{const h=Math.abs(l);(h===0||h>=1e-5&&h<i)&&(c=!0)}if(c){if(!a)if(dc&&console.log("Trigger signal",t,o.time,o),this.didTrigger[r]=!0,((n=this.receivers)==null?void 0:n.length)<=0)Hy.invoke(o.asset);else for(const h of this.receivers)h&&h.invoke(o.asset)}else o.emitOnce||(this.didTrigger[r]=!1)}}}class TE extends J_{constructor(){super(...arguments);d(this,"models",[]);d(this,"timelines",[]);d(this,"_previousActiveModel",null)}resolveSourceObjects(t){for(let i=this.models.length-1;i>=0;i--){const r=this.models[i].asset;if(!r.sourceObject||typeof r.sourceObject!="object"){console.log("no source object, removing model",i,r),this.models.splice(i,1);continue}else{const o=re.getComponent(r.sourceObject,md);this.timelines.push(o),o&&r.updateDirector&&(o.playOnAwake=!1)}}}evaluate(t){var i;this._previousActiveModel=null;for(let n=0;n<this.models.length;n++){const r=this.models[n],o=r.asset;if(t>=r.start&&t<=r.end){this._previousActiveModel=r;const a=this.getClipTime(t,r);if(o.controlActivation){const l=o.sourceObject;l.visible=!0}if(o.updateDirector){const l=this.timelines[n];l&&(l.isPlaying&&l.pause(),l.time=a,l.evaluate())}}else{const a=(i=this._previousActiveModel)==null?void 0:i.asset;if(o.controlActivation){const l=o.sourceObject;(a==null?void 0:a.sourceObject)!==l&&(l.visible=!1)}}}}}var rpe=Object.defineProperty,ope=Object.getOwnPropertyDescriptor,Tj=(s,e,t,i)=>{for(var n=i>1?void 0:i?ope(e,t):e,r=s.length-1,o;r>=0;r--)(o=s[r])&&(n=(i?o(e,t,n):o(n))||n);return i&&n&&rpe(e,t,n),n};const Jm=ie("debugtimeline");var bR;const FB=(bR=class extends Ie{constructor(){super(...arguments);d(this,"playableAsset");d(this,"playOnAwake");d(this,"extrapolationMode",1);d(this,"waitForAudio",!0);d(this,"_visibilityChangeEvt");d(this,"_clonedPlayableAsset",!1);d(this,"_speed",1);d(this,"_guidsMap");d(this,"_isPlaying",!1);d(this,"_internalUpdateRoutine");d(this,"_isPaused",!1);d(this,"_isStopping",!1);d(this,"_time",0);d(this,"_duration",0);d(this,"_weight",1);d(this,"_animationTracks",[]);d(this,"_audioTracks",[]);d(this,"_signalTracks",[]);d(this,"_controlTracks",[]);d(this,"_customTracks",[]);d(this,"_allTracks",[this._animationTracks,this._audioTracks,this._signalTracks,this._controlTracks,this._customTracks]);d(this,"animationCallbackReceivers",[])}static registerCreateTrack(e,t){this.createTrackFunctions[e]=t}get isPlaying(){return this._isPlaying}get isPaused(){return this._isPaused}get time(){return this._time}set time(e){typeof e=="number"&&!Number.isNaN(e)?this._time=e:(Jm||so())&&console.error("INVALID TIMELINE.TIME VALUE",e,this.name)}get duration(){return this._duration}set duration(e){this._duration=e}get weight(){return this._weight}set weight(e){this._weight=e}get speed(){return this._speed}set speed(e){this._speed=e}awake(){var e,t,i;Jm&&console.log(this,(e=this.playableAsset)==null?void 0:e.tracks),this.rebuildGraph(),this.isValid()||console.warn("PlayableDirector is not valid",this.playableAsset,(t=this.playableAsset)==null?void 0:t.tracks,Array.isArray((i=this.playableAsset)==null?void 0:i.tracks),this)}onEnable(){var e,t,i;for(const n of this._audioTracks)(e=n.onEnable)==null||e.call(n);for(const n of this._customTracks)(t=n.onEnable)==null||t.call(n);for(const n of this._animationTracks)(i=n.onEnable)==null||i.call(n);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 e,t,i;this.stop();for(const n of this._audioTracks)(e=n.onDisable)==null||e.call(n);for(const n of this._customTracks)(t=n.onDisable)==null||t.call(n);for(const n of this._animationTracks)(i=n.onDisable)==null||i.call(n);this._visibilityChangeEvt&&window.removeEventListener("visibilitychange",this._visibilityChangeEvt)}onDestroy(){var e;for(const t of this._allTracks)for(const i of t)(e=i.onDestroy)==null||e.call(i)}rebuildGraph(){this.isValid()&&(this.resolveBindings(),this.updateTimelineDuration(),this.setupAndCreateTrackHandlers())}async play(){if(!this.isValid())return;const e=this._isPaused==!0;if(this._isPaused=!1,!this._isPlaying){if(this._isPlaying=!0,e&&this.invokePauseChangedMethodsOnTracks(),this.waitForAudio){const t=[];for(const i of this._audioTracks){const n=i.loadAudio(this._time,1,0);n&&t.push(n)}if(t.length>0&&(await Promise.all(t),!this._isPlaying))return;for(;this._audioTracks.length>0&&this._isPlaying&&!Un.userInteractionRegistered&&this.waitForAudio;)await wc(200)}this.invokeStateChangedMethodsOnTracks(),this._internalUpdateRoutine=this.startCoroutine(this.internalUpdate(),$i.LateUpdate)}}pause(){this.isValid()&&(this._isPlaying=!1,!this._isPaused&&(this._isPaused=!0,this.internalEvaluate(),this.invokePauseChangedMethodsOnTracks(),this.invokeStateChangedMethodsOnTracks()))}stop(){this._isStopping=!0;for(const i of this._audioTracks)i.stop();const e=this._isPaused==!0,t=this._isPlaying;this._isPlaying&&(this._time=0,this._isPlaying=!1,this._isPaused=!1,this.internalEvaluate(),e&&this.invokePauseChangedMethodsOnTracks()),this._isPlaying=!1,this._isPaused=!1,e&&!t&&this.invokePauseChangedMethodsOnTracks(),t&&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 e of this._allTracks)for(const t of e)yield t}get audioTracks(){return this._audioTracks}resolveGuids(e){this._guidsMap=e}invokePauseChangedMethodsOnTracks(){var e;for(const t of this.forEachTrack())(e=t.onPauseChanged)==null||e.call(t)}invokeStateChangedMethodsOnTracks(){var e;for(const t of this.forEachTrack())(e=t.onStateChanged)==null||e.call(t,this._isPlaying)}*internalUpdate(){for(;this._isPlaying&&this.activeAndEnabled;)!this._isPaused&&this._isPlaying&&(this._time+=this.context.time.deltaTime*this.speed,this.internalEvaluate()),yield}internalEvaluate(e=!1){if(!this.isValid())return;let t=this._time;switch(this.extrapolationMode){case 0:this._speed>0?t=Math.min(t,this._duration):this._speed<0&&(t=Math.max(t,0)),this._time=t;break;case 1:t%=this._duration,this._time=t;break;case 2:if(t>this._duration){this.stop();return}break}const i=this._time;for(const n of this.playableAsset.tracks)if(!n.muted)switch(n.type){case zo.Activation:if(!e&&!this._isPlaying)continue;for(let r=0;r<n.outputs.length;r++){const o=n.outputs[r];if(typeof o=="object"){let a=!1;if(n.clips)for(const c of n.clips)c.start<=i&&i<=c.end&&(a=!0);const l=o;l.visible!==void 0&&l.visible!==a&&(l.visible=a,Jm&&console.warn(this.name,"set ActivationTrack-"+r,l.name,a,i))}}break}if(!this._isStopping)for(const n of this._animationTracks)n.evaluate(i);for(const n of this._audioTracks)n.evaluate(i);for(const n of this._signalTracks)n.evaluate(i);for(const n of this._controlTracks)n.evaluate(i);for(const n of this._customTracks)n.evaluate(i)}resolveBindings(){if(this._clonedPlayableAsset||(this._clonedPlayableAsset=!0,this.playableAsset=E_(this.playableAsset)),!this.playableAsset||!this.playableAsset.tracks)return;const e=this.findRoot(this.gameObject);for(const t of this.playableAsset.tracks){for(let i=t.outputs.length-1;i>=0;i--){let n=t.outputs[i];if(typeof n=="string"){this._guidsMap&&this._guidsMap[n]&&(n=this._guidsMap[n]);const r=re.findByGuid(n,e);r===null||typeof r!="object"?(t.outputs.splice(i,1),console.warn("Failed to resolve binding",n,t.name,t.type)):(Jm&&console.log("Resolved binding",n,"to",r),t.outputs[i]=r)}else if(n===null){if(t.outputs.splice(i,1),FB.createTrackFunctions[t.type])continue;t.type!==zo.Audio&&t.type!==zo.Control&&t.type!==zo.Marker&&t.type!==zo.Signal&&console.warn("Missing binding",n,t.name,t.type,this.name,this.playableAsset.name)}}if(t.type===zo.Control&&t.clips)for(let i=0;i<t.clips.length;i++){const n=t.clips[i];let r=n.asset.sourceObject;if(typeof r=="string"){this._guidsMap&&this._guidsMap[r]&&(r=this._guidsMap[r]);const o=re.findByGuid(r,e);o===null||typeof o!="object"?console.warn("Failed to resolve sourceObject binding",r,t.name,n):(Jm&&console.log("Resolved binding",r,"to",o),n.asset.sourceObject=o)}}}}findRoot(e){return e.parent?this.findRoot(e.parent):e}updateTimelineDuration(){if(this._duration=0,!(!this.playableAsset||!this.playableAsset.tracks)){for(const e of this.playableAsset.tracks)if(e.muted!==!0){if(e.clips)for(const t of e.clips)t.end>this._duration&&(this._duration=t.end);if(e.markers)for(const t of e.markers)t.time>this._duration&&(this._duration=t.time+.001)}}}setupAndCreateTrackHandlers(){var t,i,n;if(this._animationTracks.length=0,this._audioTracks.length=0,this._signalTracks.length=0,!this.playableAsset)return;let e=re.findObjectOfType(ad,this.context);for(const r of this.playableAsset.tracks){const o=r.type,a=FB.createTrackFunctions[o];if(a!=null){const l=a(this,r);if(typeof l.evaluate=="function"){l.director=this,l.track=r,this._customTracks.push(l);continue}}if(r.type===zo.Animation){if(!r.clips||r.clips.length<=0){Jm&&console.warn("Animation track has no clips",r);continue}for(let l=r.outputs.length-1;l>=0;l--){let c=r.outputs[l];if(c instanceof ve){const u=re.getOrAddComponent(c,or);u&&(c=u)}const h=(t=c==null?void 0:c.gameObject)==null?void 0:t.animations;if(h){const u=new ME;u.trackOffset=r.trackOffset,u.director=this,u.track=r;for(let f=0;f<r.clips.length;f++){const p=r.clips[f],m=p.asset;if(!m){console.error(`Timeline ${this.name}: clip #${f} on track "${r.name}" has no animation data`);continue}const y=m.clip;let g=y;if((typeof g=="string"||typeof g=="number")&&(g=h.find(_=>_.name===y)),!g){console.warn("Could not find animationClip for model",p,r.name,this.name,(i=this.playableAsset)==null?void 0:i.name);continue}c instanceof or&&c.runtimeAnimatorController&&(c.__internalDidAwakeAndStart||c.initializeRuntimeAnimatorController(),c.runtimeAnimatorController.mixer||c.runtimeAnimatorController.bind(c),u.mixer=c.runtimeAnimatorController.mixer),u.mixer||(u.mixer=new U1(c.gameObject),this.context.animations.registerAnimationMixer(u.mixer)),u.clips.push(g),u.mixer.uncacheAction(g),u.createHooks(p.asset,g);const v=u.mixer.clipAction(g);u.actions.push(v),u.models.push(p)}this._animationTracks.push(u)}}}else if(r.type===zo.Audio){if(!r.clips||r.clips.length<=0)continue;const l=new rp;l.director=this,l.track=r,l.audioSource=r.outputs.find(c=>c instanceof Un),this._audioTracks.push(l),e||(e=(n=this.context.mainCameraComponent)==null?void 0:n.gameObject.addNewComponent(ad)),l.listener=e.listener;for(let c=0;c<r.clips.length;c++){const h=r.clips[c];l.addModel(h)}}else if(r.type===zo.Marker){const l=new J0;if(l.director=this,l.track=r,r.markers)for(const c of r.markers)switch(c.type){case KO.Signal:l.models.push(c),l.didTrigger.push(!1);break}if(l!==null&&l.models.length>0){const c=re.getComponent(this.gameObject,Hy);c&&(l.receivers.push(c),this._signalTracks.push(l))}}else if(r.type===zo.Signal){const l=new J0;if(l.director=this,l.track=r,r.markers)for(const c of r.markers)l.models.push(c),l.didTrigger.push(!1);for(const c of r.outputs)l.receivers.push(c);this._signalTracks.push(l)}else if(r.type===zo.Control){const l=new TE;if(l.director=this,l.track=r,r.clips)for(const c of r.clips)l.models.push(c);l.resolveSourceObjects(this.context),this._controlTracks.push(l)}}}setAudioTracksAllowPlaying(e){for(const t of this._audioTracks)t.onAllowAudioChanged(e)}registerAnimationCallback(e){this.animationCallbackReceivers.push(e)}unregisterAnimationCallback(e){const t=this.animationCallbackReceivers.indexOf(e);t!==-1&&this.animationCallbackReceivers.splice(t,1)}},d(bR,"createTrackFunctions",{}),bR);let md=FB;Tj([x()],md.prototype,"playOnAwake",2);Tj([x()],md.prototype,"extrapolationMode",2);const NS=Symbol("objectIsAnimatedData");function Pz(s,e,t){if(!s)return;if(s[NS]===void 0){if(!t)return;s[NS]=new Set}const i=s[NS];t?i.add(e):i.has(e)&&i.delete(e)}function ape(s){if(!s)return!1;const e=s[NS];return e!==void 0&&e.size>0}di.registerCallback(Ii.ContextCreated,s=>{const e=s.context.domElement.getAttribute("autoplay");if(e!==void 0&&(e===""||e==="true"||e==="1")&&s.files)for(const t of s.files)re.foreachComponent(t.file.scene,n=>{if(n.enabled!==!1){if(n instanceof Br&&n.playAutomatically||n instanceof or||n instanceof md&&n.playOnAwake===!0)return!0;if(n instanceof Br)return n.playAutomatically=!0,!0;if(n instanceof md)return n.playOnAwake=!0,!0}},!0)!==!0&&my.assignAnimationsFromFile(t.file,{createAnimationComponent:(n,r)=>Sl(n,Br)})});class lpe{constructor(){d(this,"_context")}get context(){return this._context??Ot.Current}get isStateMachineBehaviour(){return!0}}class TA{constructor(e,t,i,n){d(this,"name");d(this,"nameHash");d(this,"normalizedTime");d(this,"length");d(this,"speed");d(this,"action");d(this,"hasTransitions");var r;this.name=e.name,this.nameHash=e.hash,this.normalizedTime=t,this.length=i,this.speed=n,this.action=e.motion.action||null,this.hasTransitions=((r=e.transitions)==null?void 0:r.length)>0||!1}}function Ij(s,e){return{name:"Empty",isLooping:!1,guid:(e==null?void 0:e.generateUUID())??fi.generateUUID(),index:-1,clip:new no(s,0,[])}}var Fu=(s=>(s[s.If=1]="If",s[s.IfNot=2]="IfNot",s[s.Greater=3]="Greater",s[s.Less=4]="Less",s[s.Equals=6]="Equals",s[s.NotEqual=7]="NotEqual",s))(Fu||{}),JO=(s=>(s[s.Float=1]="Float",s[s.Int=3]="Int",s[s.Bool=4]="Bool",s[s.Trigger=9]="Trigger",s))(JO||{});const Cs=ie("debuganimatorcontroller"),Iw=ie("debugrootmotion");class ia{constructor(e){d(this,"_speed",1);d(this,"normalizedStartOffset",0);d(this,"animator");d(this,"model");d(this,"_mixer");d(this,"_activeState");d(this,"_activeStates",[]);d(this,"_heldActions",[]);d(this,"rootMotionHandler");this.model=e,Cs&&console.log(this)}static createFromClips(e,t={looping:!1,autoTransition:!0,transitionDuration:0}){const i=[];for(let o=0;o<e.length;o++){const a=e[o],l=[];if(t.autoTransition!==!1){const h=t.transitionDuration??0,u=h/a.duration;let f=o;(t.autoTransition===void 0||t.autoTransition===!0)&&(f=(o+1)%e.length),l.push({exitTime:1-u,offset:0,duration:h,hasExitTime:!0,destinationState:f,conditions:[]})}const c={name:a.name,hash:o,motion:{name:a.name,clip:a,isLooping:(t==null?void 0:t.looping)??!1},transitions:l,behaviours:[]};i.push(c)}const n={name:"AnimatorController",guid:new ks(Date.now()).generateUUID(),parameters:[],layers:[{name:"Base Layer",stateMachine:{defaultState:0,states:i}}]};return new ia(n)}play(e,t=-1,i=Number.NEGATIVE_INFINITY,n=0){if(t<0)t=0;else if(t>=this.model.layers.length){console.warn("invalid layer");return}const o=this.model.layers[t].stateMachine;for(const a of o.states)if(a.name===e||a.hash===e){Cs&&console.log("transition to ",a),this.transitionTo(a,n,i);return}console.warn("Could not find "+e+" to play")}reset(){this.setStartTransition()}setBool(e,t){var n,r;const i=typeof e=="string"?"name":"hash";return(r=(n=this.model)==null?void 0:n.parameters)==null?void 0:r.filter(o=>o[i]===e).forEach(o=>o.value=t)}getBool(e){var i,n,r;const t=typeof e=="string"?"name":"hash";return((r=(n=(i=this.model)==null?void 0:i.parameters)==null?void 0:n.find(o=>o[t]===e))==null?void 0:r.value)??!1}setFloat(e,t){var r,o;const i=typeof e=="string"?"name":"hash",n=(o=(r=this.model)==null?void 0:r.parameters)==null?void 0:o.filter(a=>a[i]===e);return n.forEach(a=>a.value=t),(n==null?void 0:n.length)>0}getFloat(e){var i,n,r;const t=typeof e=="string"?"name":"hash";return((r=(n=(i=this.model)==null?void 0:i.parameters)==null?void 0:n.find(o=>o[t]===e))==null?void 0:r.value)??0}setInteger(e,t){var n,r;const i=typeof e=="string"?"name":"hash";return(r=(n=this.model)==null?void 0:n.parameters)==null?void 0:r.filter(o=>o[i]===e).forEach(o=>o.value=t)}getInteger(e){var i,n,r;const t=typeof e=="string"?"name":"hash";return((r=(n=(i=this.model)==null?void 0:i.parameters)==null?void 0:n.find(o=>o[t]===e))==null?void 0:r.value)??0}setTrigger(e){var i,n;Cs&&console.log("SET TRIGGER",e);const t=typeof e=="string"?"name":"hash";return(n=(i=this.model)==null?void 0:i.parameters)==null?void 0:n.filter(r=>r[t]===e).forEach(r=>r.value=!0)}resetTrigger(e){var i,n;const t=typeof e=="string"?"name":"hash";return(n=(i=this.model)==null?void 0:i.parameters)==null?void 0:n.filter(r=>r[t]===e).forEach(r=>r.value=!1)}getTrigger(e){var i,n,r;const t=typeof e=="string"?"name":"hash";return((r=(n=(i=this.model)==null?void 0:i.parameters)==null?void 0:n.find(o=>o[t]===e))==null?void 0:r.value)??!1}isInTransition(){return this._activeStates.length>1}setSpeed(e){this._speed=e}FindState(e){return this.findState(e)}findState(e){if(!e)return null;if(Array.isArray(this.model.layers)){for(const t of this.model.layers)for(const i of t.stateMachine.states)if(i.name===e||i.hash==e)return i}return null}getCurrentStateInfo(){if(!this._activeState)return null;const e=this._activeState.motion.action;if(!e)return null;const t=this._activeState.motion.clip.duration,i=t<=0?0:Math.abs(e.time/t);return new TA(this._activeState,i,t,this._speed)}get currentAction(){if(!this._activeState)return null;const e=this._activeState.motion.action;return e||null}get context(){var e;return(e=this.animator)==null?void 0:e.context}get mixer(){return this._mixer}dispose(){var e;if(this._mixer.stopAllAction(),this.animator){this._mixer.uncacheRoot(this.animator.gameObject);for(const t of this._activeStates)t.motion.clip&&this.mixer.uncacheAction(t.motion.clip,this.animator.gameObject)}(e=this.context)==null||e.animations.unregisterAnimationMixer(this._mixer)}bind(e){var t,i;e?this.animator!==e&&(this._mixer&&(this._mixer.stopAllAction(),(t=this.context)==null||t.animations.unregisterAnimationMixer(this._mixer)),this.animator=e,this._mixer=new U1(this.animator.gameObject),(i=this.context)==null||i.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;Cs&&console.warn("AnimatorController clone()",this.model);const e=E_(this.model,(i,n,r)=>r==null?!0:!(r.type==="Object3D"||r.isObject3D===!0||I5(r)||r.tracks!==void 0||r instanceof ia));return console.assert(e!==this.model),new ia(e)}update(e){var i,n;if(!this.animator)return;this.evaluateTransitions(),this.updateActiveStates(e);const t=this.animator.context.time.deltaTime;this.animator.applyRootMotion&&((i=this.rootMotionHandler)==null||i.onBeforeUpdate(e)),this._mixer.update(t),this.animator.applyRootMotion&&((n=this.rootMotionHandler)==null||n.onAfterUpdate(e))}get activeState(){return this._activeState}updateActiveStates(e){for(let t=0;t<this._activeStates.length;t++){const i=this._activeStates[t],n=i.motion;if(!n.action)this._activeStates.splice(t,1),t--;else{const r=n.action;r.weight=e,r.getEffectiveWeight()<=0&&!r.isRunning()&&(Cs&&console.debug("REMOVE",i.name,r.getEffectiveWeight(),r.isRunning(),r.isScheduled()),this._activeStates.splice(t,1),t--)}}}setStartTransition(){var e;this.model.layers.length>1&&(Cs||lt())&&console.warn("Multiple layers are not supported yet "+((e=this.animator)==null?void 0:e.name));for(const t of this.model.layers){const i=t.stateMachine;i.defaultState===void 0&&(Cs&&console.warn("AnimatorController default state is undefined, will assign state 0 as default",t),i.defaultState=0);const n=i.states[i.defaultState];this.transitionTo(n,0,this.normalizedStartOffset);break}}evaluateTransitions(){var r;let e=!1;if(!this._activeState){if(this.setStartTransition(),!this._activeState)return;e=!0}const t=this._activeState,i=t.motion.action;for(const o of t.transitions){if(!o.hasExitTime&&o.conditions.length<=0)continue;let a=!0;for(const l of o.conditions)if(!this.evaluateCondition(l)){a=!1;break}if(a)if(i){const l=t.motion.clip.duration,c=l<=0?1:Math.abs(i.time/l);let h=o.exitTime;i.timeScale<0&&(h=1-h);let u=!1;if(o.hasExitTime?i.timeScale>0?u=c>=o.exitTime:i.timeScale<0&&(u=1-c>=o.exitTime):u=!0,u){for(const f of o.conditions){const p=this.model.parameters.find(m=>m.name===f.parameter);(p==null?void 0:p.type)===JO.Trigger&&p.value&&(p.value=!1)}if(i.clampWhenFinished=!0,Cs){const f=this.getState(o.destinationState,0);console.log(`Transition to ${o.destinationState} / ${f==null?void 0:f.name}`,o,`
|
|
5734
5734
|
Timescale: `+i.timeScale,`
|
|
5735
5735
|
Normalized time: `+c.toFixed(3),`
|
|
@@ -6212,7 +6212,7 @@ Texture:`,i),this.setLightmapDebugMaterial()):$m&&console.log("Use debuglightmap
|
|
|
6212
6212
|
}
|
|
6213
6213
|
`};class wL extends Dt{constructor(e){super({type:"LineMaterial",uniforms:Cy.clone(er.line.uniforms),vertexShader:er.line.vertexShader,fragmentShader:er.line.fragmentShader,clipping:!0}),this.isLineMaterial=!0,this.setValues(e)}get color(){return this.uniforms.diffuse.value}set color(e){this.uniforms.diffuse.value=e}get worldUnits(){return"WORLD_UNITS"in this.defines}set worldUnits(e){e===!0?this.defines.WORLD_UNITS="":delete this.defines.WORLD_UNITS}get linewidth(){return this.uniforms.linewidth.value}set linewidth(e){this.uniforms.linewidth&&(this.uniforms.linewidth.value=e)}get dashed(){return"USE_DASH"in this.defines}set dashed(e){e===!0!==this.dashed&&(this.needsUpdate=!0),e===!0?this.defines.USE_DASH="":delete this.defines.USE_DASH}get dashScale(){return this.uniforms.dashScale.value}set dashScale(e){this.uniforms.dashScale.value=e}get dashSize(){return this.uniforms.dashSize.value}set dashSize(e){this.uniforms.dashSize.value=e}get dashOffset(){return this.uniforms.dashOffset.value}set dashOffset(e){this.uniforms.dashOffset.value=e}get gapSize(){return this.uniforms.gapSize.value}set gapSize(e){this.uniforms.gapSize.value=e}get opacity(){return this.uniforms.opacity.value}set opacity(e){this.uniforms&&(this.uniforms.opacity.value=e)}get resolution(){return this.uniforms.resolution.value}set resolution(e){this.uniforms.resolution.value.copy(e)}get alphaToCoverage(){return"USE_ALPHA_TO_COVERAGE"in this.defines}set alphaToCoverage(e){this.defines&&(e===!0!==this.alphaToCoverage&&(this.needsUpdate=!0),e===!0?(this.defines.USE_ALPHA_TO_COVERAGE="",this.extensions.derivatives=!0):(delete this.defines.USE_ALPHA_TO_COVERAGE,this.extensions.derivatives=!1))}}const Yz=new w,Kz=new w,Hs=new Ze,Vs=new Ze,Hl=new Ze,jI=new w,WI=new ye,Js=new N1,Jz=new w,Uw=new Ei,Nw=new kn,Vl=new Ze;let oc,cp;function Zz(s,e,t){return Vl.set(0,0,-e,1).applyMatrix4(s.projectionMatrix),Vl.multiplyScalar(1/Vl.w),Vl.x=cp/t.width,Vl.y=cp/t.height,Vl.applyMatrix4(s.projectionMatrixInverse),Vl.multiplyScalar(1/Vl.w),Math.abs(Math.max(Vl.x,Vl.y))}function eye(s,e){const t=s.matrixWorld,i=s.geometry,n=i.attributes.instanceStart,r=i.attributes.instanceEnd,o=Math.min(i.instanceCount,n.count);for(let a=0,l=o;a<l;a++){Js.start.fromBufferAttribute(n,a),Js.end.fromBufferAttribute(r,a),Js.applyMatrix4(t);const c=new w,h=new w;oc.distanceSqToSegment(Js.start,Js.end,h,c),h.distanceTo(c)<cp*.5&&e.push({point:h,pointOnLine:c,distance:oc.origin.distanceTo(h),object:s,face:null,faceIndex:a,uv:null,uv1:null})}}function tye(s,e,t){const i=e.projectionMatrix,r=s.material.resolution,o=s.matrixWorld,a=s.geometry,l=a.attributes.instanceStart,c=a.attributes.instanceEnd,h=Math.min(a.instanceCount,l.count),u=-e.near;oc.at(1,Hl),Hl.w=1,Hl.applyMatrix4(e.matrixWorldInverse),Hl.applyMatrix4(i),Hl.multiplyScalar(1/Hl.w),Hl.x*=r.x/2,Hl.y*=r.y/2,Hl.z=0,jI.copy(Hl),WI.multiplyMatrices(e.matrixWorldInverse,o);for(let f=0,p=h;f<p;f++){if(Hs.fromBufferAttribute(l,f),Vs.fromBufferAttribute(c,f),Hs.w=1,Vs.w=1,Hs.applyMatrix4(WI),Vs.applyMatrix4(WI),Hs.z>u&&Vs.z>u)continue;if(Hs.z>u){const A=Hs.z-Vs.z,b=(Hs.z-u)/A;Hs.lerp(Vs,b)}else if(Vs.z>u){const A=Vs.z-Hs.z,b=(Vs.z-u)/A;Vs.lerp(Hs,b)}Hs.applyMatrix4(i),Vs.applyMatrix4(i),Hs.multiplyScalar(1/Hs.w),Vs.multiplyScalar(1/Vs.w),Hs.x*=r.x/2,Hs.y*=r.y/2,Vs.x*=r.x/2,Vs.y*=r.y/2,Js.start.copy(Hs),Js.start.z=0,Js.end.copy(Vs),Js.end.z=0;const y=Js.closestPointToPointParameter(jI,!0);Js.at(y,Jz);const g=fi.lerp(Hs.z,Vs.z,y),v=g>=-1&&g<=1,_=jI.distanceTo(Jz)<cp*.5;if(v&&_){Js.start.fromBufferAttribute(l,f),Js.end.fromBufferAttribute(c,f),Js.start.applyMatrix4(o),Js.end.applyMatrix4(o);const A=new w,b=new w;oc.distanceSqToSegment(Js.start,Js.end,b,A),t.push({point:b,pointOnLine:A,distance:oc.origin.distanceTo(b),object:s,face:null,faceIndex:f,uv:null,uv1:null})}}}class iye extends fe{constructor(e=new nW,t=new wL({color:Math.random()*16777215})){super(e,t),this.isLineSegments2=!0,this.type="LineSegments2"}computeLineDistances(){const e=this.geometry,t=e.attributes.instanceStart,i=e.attributes.instanceEnd,n=new Float32Array(2*t.count);for(let o=0,a=0,l=t.count;o<l;o++,a+=2)Yz.fromBufferAttribute(t,o),Kz.fromBufferAttribute(i,o),n[a]=a===0?0:n[a-1],n[a+1]=n[a]+Yz.distanceTo(Kz);const r=new oC(n,2,1);return e.setAttribute("instanceDistanceStart",new Xo(r,1,0)),e.setAttribute("instanceDistanceEnd",new Xo(r,1,1)),this}raycast(e,t){const i=this.material.worldUnits,n=e.camera;n===null&&!i&&console.error('LineSegments2: "Raycaster.camera" needs to be set in order to raycast against LineSegments2 while worldUnits is set to false.');const r=e.params.Line2!==void 0&&e.params.Line2.threshold||0;oc=e.ray;const o=this.matrixWorld,a=this.geometry,l=this.material;cp=l.linewidth+r,a.boundingSphere===null&&a.computeBoundingSphere(),Nw.copy(a.boundingSphere).applyMatrix4(o);let c;if(i)c=cp*.5;else{const u=Math.max(n.near,Nw.distanceToPoint(oc.origin));c=Zz(n,u,l.resolution)}if(Nw.radius+=c,oc.intersectsSphere(Nw)===!1)return;a.boundingBox===null&&a.computeBoundingBox(),Uw.copy(a.boundingBox).applyMatrix4(o);let h;if(i)h=cp*.5;else{const u=Math.max(n.near,Uw.distanceToPoint(oc.origin));h=Zz(n,u,l.resolution)}Uw.expandByScalar(h),oc.intersectsBox(Uw)!==!1&&(i?eye(this,t):tye(this,n,t))}}class sW extends nW{constructor(){super(),this.isLineGeometry=!0,this.type="LineGeometry"}setPositions(e){const t=e.length-3,i=new Float32Array(2*t);for(let n=0;n<t;n+=3)i[2*n]=e[n],i[2*n+1]=e[n+1],i[2*n+2]=e[n+2],i[2*n+3]=e[n+3],i[2*n+4]=e[n+4],i[2*n+5]=e[n+5];return super.setPositions(i),this}setColors(e){const t=e.length-3,i=new Float32Array(2*t);for(let n=0;n<t;n+=3)i[2*n]=e[n],i[2*n+1]=e[n+1],i[2*n+2]=e[n+2],i[2*n+3]=e[n+3],i[2*n+4]=e[n+4],i[2*n+5]=e[n+5];return super.setColors(i),this}fromLine(e){const t=e.geometry;return this.setPositions(t.attributes.position.array),this}}class nye extends iye{constructor(e=new sW,t=new wL({color:Math.random()*16777215})){super(e,t),this.isLine2=!0,this.type="Line2"}}class NE extends Ie{}var sye=Object.defineProperty,rye=Object.getOwnPropertyDescriptor,Yp=(s,e,t,i)=>{for(var n=i>1?void 0:i?rye(e,t):e,r=s.length-1,o;r>=0;r--)(o=s[r])&&(n=(i?o(e,t,n):o(n))||n);return i&&n&&sye(e,t,n),n};const $z=ie("debugwebxr");class Va extends Ie{constructor(){super(...arguments);d(this,"movementSpeed",1.5);d(this,"rotationStep",30);d(this,"useTeleport",!0);d(this,"useTeleportTarget",!1);d(this,"useTeleportFade",!1);d(this,"showRays",!0);d(this,"showHits",!1);d(this,"isXRMovementHandler",!0);d(this,"xrSessionMode","immersive-vr");d(this,"_didApplyRotation",!1);d(this,"_didTeleport",!1);d(this,"_plane",null);d(this,"_lines",[]);d(this,"_hitDiscs",[]);d(this,"_hitDistances",[]);d(this,"hitPointRaycastFilter",t=>t.type==="SkinnedMesh"?"continue in children":!0)}onUpdateXR(t){const i=t.xr.rig;if(!(i!=null&&i.gameObject)||t.xr.isPassThrough)return;const n=t.xr.leftController,r=t.xr.rightController;n&&this.onHandleMovement(n,i.gameObject),r&&(this.onHandleRotation(r,i.gameObject),this.useTeleport&&this.onHandleTeleport(r,i.gameObject))}onLeaveXR(t){for(const i of this._lines)i.removeFromParent();for(const i of this._hitDiscs)i==null||i.removeFromParent()}onBeforeRender(){var t;(t=this.context.xr)!=null&&t.running&&(this.showRays&&this.renderRays(this.context.xr),this.showHits&&this.renderHits(this.context.xr))}onHandleMovement(t,i){const n=t.getStick("xr-standard-thumbstick"),r=new w(n.x,0,n.y);r.multiplyScalar(this.context.time.deltaTimeUnscaled*this.movementSpeed);const o=Ki(i);r.multiplyScalar(o.x),r.applyQuaternion(t.xr.poseOrientation),r.y=0,r.applyQuaternion(i.worldQuaternion),i.position.add(r),i.updateMatrixWorld()}onHandleRotation(t,i){const r=t.getStick("xr-standard-thumbstick").x;if(this._didApplyRotation)Math.abs(r)<.3&&(this._didApplyRotation=!1);else if(Math.abs(r)>.5){this._didApplyRotation=!0;const o=r>0?1:-1;i.rotateY(o*it.toRadians(this.rotationStep))}}onHandleTeleport(t,i){var r;const n=t.getStick("xr-standard-thumbstick");if(this._didTeleport)n.y<.2&&(this._didTeleport=!1);else if(n.y>.8){this._didTeleport=!0;const o=this.context.physics.raycastFromRay(t.ray)[0];let a=o==null?void 0:o.point;if(!a){this._plane||(this._plane=new Tr(new w(0,1,0),0));const l=i.worldPosition;this._plane.setFromNormalAndCoplanarPoint(new w(0,1,0),l);const c=t.ray;a=l.clone(),this._plane.intersectLine(new N1(c.origin,pi(c.direction).multiplyScalar(1e4).add(c.origin)),a),a.distanceTo(l)>i.scale.x*10&&(a=null)}if(a){if(this.useTeleportTarget&&!re.getComponentInParent(o.object,NE))return;$z&&_t.DrawSphere(a,.025,16711680,5);const l=a.clone();this.useTeleportFade?(r=t.xr.fadeTransition())==null||r.then(()=>{i.worldPosition=l}):i.worldPosition=l}}}renderRays(t){for(let i=0;i<this._lines.length;i++){const n=this._lines[i];n&&(n.visible=!1)}for(let i=0;i<t.controllers.length;i++){const n=t.controllers[i];let r=this._lines[i];if(!n.connected||!n.isTracking||!n.ray||n.targetRayMode==="transient-pointer"||!n.hasSelectEvent){r&&(r.visible=!1);continue}r||(r=this.createRayLineObject(),r.scale.z=.5,this._lines[i]=r),n.updateRayWorldPosition(),n.updateRayWorldQuaternion();const o=n.rayWorldPosition,a=n.rayWorldQuaternion;r.position.copy(o),r.quaternion.copy(a);const l=t.rigScale,c=this._hitDistances[i]??l;r.scale.set(l,l,c),r.visible=!0,r.layers.disableAll(),r.layers.enable(2),r.parent!==this.context.scene&&this.context.scene.add(r)}}renderHits(t){for(const i of this._hitDiscs){if(!i)continue;const n=i.controller;if(!n||!n.connected||!n.isTracking){i.visible=!1;continue}}for(let i=0;i<t.controllers.length;i++){const n=t.controllers[i];if(!n.connected||!n.isTracking||!n.ray||!n.hasSelectEvent)continue;const r=this.context.time.smoothedFps>=59?1:10;if((this.context.time.frame+n.index)%r!==0){const l=this._hitDiscs[i];l&&l.hit&&(l.visible=!0,this.hitPointerSetPosition(n,l,l.hit.distance));continue}const o=this.context.physics.raycastFromRay(n.ray,{testObject:this.hitPointRaycastFilter})[0];this._hitDistances[i]=o==null?void 0:o.distance;let a=this._hitDiscs[i];if(a&&(a.controller=n,a.hit=o),o){const l=t.rigScale??1;$z&&(_t.DrawWireSphere(o.point,.025*l,16711680),_t.DrawLabel(pi(0,.2,0).add(o.point),o.object.name,.02,0)),a||(a=this.createHitPointObject(),this._hitDiscs[i]=a),a.visible=!0;const c=.01*(l+o.distance);if(a.scale.set(c,c,c),a.layers.disableAll(),a.layers.enable(2),a.hit=o,o.normal){this.hitPointerSetPosition(n,a,o.distance);const h=o.normal.applyQuaternion(Ri(o.object));a.quaternion.setFromUnitVectors(oye,h)}else this.hitPointerSetPosition(n,a,o.distance);a.parent!==this.context.scene&&this.context.scene.add(a)}else this._hitDiscs[i]&&(this._hitDiscs[i].visible=!1)}}hitPointerSetPosition(t,i,n){i.position.copy(t.rayWorldPosition),i.position.add(pi(0,0,n-.01).applyQuaternion(t.rayWorldQuaternion))}createHitPointObject(){var t=new ve;const i=new fe(new Wa(.3,6,6),new ni({color:15658734,opacity:.7,transparent:!0,depthTest:!1,side:xi}));return i.layers.disableAll(),i.layers.enable(2),t.add(i),t}createRayLineObject(){const t=new nye;t.layers.disableAll(),t.layers.enable(2);const i=new sW;t.geometry=i;const n=new Float32Array(9);n.set([0,0,.02,0,0,.4,0,0,1]),i.setPositions(n);const r=new Float32Array(9);r.set([1,1,1,.1,.1,.1,0,0,0]),i.setColors(r);const o=new wL({color:16777215,vertexColors:!0,worldUnits:!0,linewidth:.004,transparent:!0,blending:up,dashed:!1,alphaToCoverage:!0});return t.material=o,t}}Yp([x()],Va.prototype,"movementSpeed",2);Yp([x()],Va.prototype,"rotationStep",2);Yp([x()],Va.prototype,"useTeleport",2);Yp([x()],Va.prototype,"useTeleportTarget",2);Yp([x()],Va.prototype,"useTeleportFade",2);Yp([x()],Va.prototype,"showRays",2);Yp([x()],Va.prototype,"showHits",2);const oye=new w(0,1,0);var aye=Object.defineProperty,lye=Object.getOwnPropertyDescriptor,Ro=(s,e,t,i)=>{for(var n=i>1?void 0:i?lye(e,t):e,r=s.length-1,o;r>=0;r--)(o=s[r])&&(n=(i?o(e,t,n):o(n))||n);return i&&n&&aye(e,t,n),n};const eA=ie("debugwebxr"),cye=ie("debugusdz");class Us extends Ie{constructor(){super(...arguments);d(this,"createVRButton",!0);d(this,"createARButton",!0);d(this,"createSendToQuestButton",!0);d(this,"createQRCode",!0);d(this,"useDefaultControls",!0);d(this,"showControllerModels",!0);d(this,"showHandModels",!0);d(this,"usePlacementReticle",!0);d(this,"usePlacementAdjustment",!0);d(this,"arSceneScale",1);d(this,"useXRAnchor",!1);d(this,"useQuicklookExport",!1);d(this,"useDepthSensing",!1);d(this,"defaultAvatar");d(this,"_playerSync");d(this,"_createdComponentsInSession",[]);d(this,"_usdzExporter");d(this,"_previousXRState",0);d(this,"onAvatarSpawned",t=>{eA&&console.log("WebXR.onAvatarSpawned",t),re.getComponentInChildren(t,gd)??(i=re.addComponent(t,gd))});d(this,"_buttonFactory");d(this,"_buttons",[])}awake(){xt.getXRSync(this.context)}onEnable(){var t,i;window.location.protocol!=="https:"&&Ni('<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&&(re.findObjectOfType(Fn)||(eA&&console.log("WebXR: Adding USDZExporter"),this._usdzExporter=re.addComponent(this.gameObject,Fn),this._usdzExporter.objectToExport=this.context.scene,this._usdzExporter.autoExportAnimations=!0,this._usdzExporter.autoExportAudioSources=!0)),this.handleCreatingHTML(),this.handleOfferSession(),this.defaultAvatar||(eA&&console.warn("WebXR: No default avatar set, using static default avatar"),this.defaultAvatar=new Zt("https://cdn.needle.tools/static/avatars/DefaultAvatar.glb")),this.defaultAvatar&&(this._playerSync=this.gameObject.getOrAddComponent(Vy),this._playerSync.autoSync=!1),this._playerSync&&(this._playerSync.asset=this.defaultAvatar,(t=this._playerSync.onPlayerSpawned)==null||t.removeEventListener(this.onAvatarSpawned),(i=this._playerSync.onPlayerSpawned)==null||i.addEventListener(this.onAvatarSpawned))}onDisable(){var t;(t=this._usdzExporter)==null||t.destroy(),this.removeButtons()}async handleOfferSession(){return this.createVRButton&&await xt.isVRSupported()&&this.createVRButton?xt.offerSession("immersive-vr","default",this.context):this.createARButton&&await xt.isARSupported()&&this.createARButton?xt.offerSession("immersive-ar","default",this.context):!1}get session(){return xt.active??null}get sessionMode(){return xt.activeMode??null}async enterVR(t){return xt.start("immersive-vr",t,this.context)}async enterAR(t){return xt.start("immersive-ar",t,this.context)}exitXR(){xt.stop()}onBeforeXR(t,i){t=="immersive-ar"&&this.useDepthSensing&&(i.optionalFeatures=i.optionalFeatures||[],i.optionalFeatures.push("depth-sensing"))}async onEnterXR(t){eA&&console.log("WebXR onEnterXR"),this._previousXRState=tr.Global.Mask;const i=t.xr.isVR;if(tr.Global.Set(i?rc.VR:rc.AR),this.usePlacementReticle&&t.xr.isAR){let r=re.findObjectOfType(ao);if(r)eA&&console.log("WebXR: WebARSessionRoot already exists, not creating a new one");else{const o=new ve;for(const a of this.context.scene.children)o.add(a);this.context.scene.add(o),r=re.addComponent(o,ao),this._createdComponentsInSession.push(r),r.arScale=this.arSceneScale,r.arTouchTransform=this.usePlacementAdjustment,r.useXRAnchor=this.useXRAnchor}}this.useDefaultControls&&this.setDefaultMovementEnabled(!0),(this.showControllerModels||this.showHandModels)&&this.setDefaultControllerRenderingEnabled(!0);let n=re.findObjectOfType(Y0);n||(n=this.gameObject.addNewComponent(Y0)),this.createLocalAvatar(t.xr)}onLeaveXR(t){var i;tr.Global.Set(this._previousXRState),(i=this._playerSync)==null||i.destroyInstance();for(const n of this._createdComponentsInSession)n.destroy();this._createdComponentsInSession.length=0,this.handleOfferSession()}setDefaultMovementEnabled(t){let i=this.gameObject.getComponent(Va);return!i&&t&&(i=this.gameObject.addComponent(Va),this._createdComponentsInSession.push(i)),i&&(i.enabled=t),i}setDefaultControllerRenderingEnabled(t){let i=this.gameObject.getComponent(Cc);return!i&&t&&(i=this.gameObject.addComponent(Cc),this._createdComponentsInSession.push(i),i.createControllerModel=this.showControllerModels,i.createHandModel==this.showHandModels),i&&(i.enabled=t),i}async createLocalAvatar(t){this._playerSync&&t.running&&(this._playerSync.asset=this.defaultAvatar,await this._playerSync.getInstance())}getButtonsContainer(){return this.getButtonsFactory()}getButtonsFactory(){return this._buttonFactory||(this._buttonFactory=Uh.getOrCreate()),this._buttonFactory}handleCreatingHTML(){if(this.createARButton||this.createVRButton||this.useQuicklookExport){if((bp()&&Hg()||cye)&&this.useQuicklookExport){const i=re.findObjectOfType(Fn);if(!i||i&&i.allowCreateQuicklookButton){const n=this.getButtonsFactory().createQuicklookButton();this.addButton(n,50)}}if(this.createARButton){const i=this.getButtonsFactory().createARButton();this.addButton(i,50)}if(this.createVRButton){const i=this.getButtonsFactory().createVRButton();this.addButton(i,50)}}if(this.createSendToQuestButton&&!H1()&&xt.isVRSupported().then(i=>{if(!i){const n=this.getButtonsFactory().createSendToQuestButton();this.addButton(n,50)}}),this.createQRCode&&!qa()){const i=_E(Lc);i&&i.createQRCodeButton===!1?lt()&&console.warn("WebXR: QRCode button is disabled in the Needle Menu component"):xt.isXRSupported().then(n=>{if(_p()||!n){const r=_l.getOrCreate().createQRCode();this.addButton(r,50)}})}}addButton(t,i){this._buttons.push(t),t.setAttribute("priority",i.toString()),this.context.menu.appendChild(t)}removeButtons(){for(const t of this._buttons)t.remove();this._buttons.length=0}}Ro([x()],Us.prototype,"createVRButton",2);Ro([x()],Us.prototype,"createARButton",2);Ro([x()],Us.prototype,"createSendToQuestButton",2);Ro([x()],Us.prototype,"createQRCode",2);Ro([x()],Us.prototype,"useDefaultControls",2);Ro([x()],Us.prototype,"showControllerModels",2);Ro([x()],Us.prototype,"showHandModels",2);Ro([x()],Us.prototype,"usePlacementReticle",2);Ro([x()],Us.prototype,"usePlacementAdjustment",2);Ro([x()],Us.prototype,"arSceneScale",2);Ro([x()],Us.prototype,"useXRAnchor",2);Ro([x()],Us.prototype,"useQuicklookExport",2);Ro([x()],Us.prototype,"useDepthSensing",2);Ro([x(Zt)],Us.prototype,"defaultAvatar",2);class zE{get extensionName(){return"Physics"}onExportObject(e,t,i){const n=re.getComponents(e,zi).filter(l=>l.enabled),r=re.getComponents(e,oa).filter(l=>l.enabled&&!l.isTrigger);let o=n.length>0?n[0]:null;const a=r.length>0?r[0]:null;a&&!o&&(o=new zi,o.isKinematic=!0),o&&t.addEventListener("serialize",(l,c)=>{var h,u,f;if(o){if(l.appendLine(),l.beginBlock('def RealityKitComponent "RigidBody"',"{",!0),o.useGravity||l.appendLine("bool gravityEnabled = 0"),l.appendLine('uniform token info:id = "RealityKit.RigidBody"'),o.isKinematic&&l.appendLine('token motionType = "Kinematic"'),l.beginBlock('def RealityKitStruct "massFrame"',"{",!0),l.appendLine(`float m_mass = ${o.mass}`),l.beginBlock('def RealityKitStruct "m_pose"',"{",!0),l.appendLine(`float3 position = (${o.centerOfMass.x}, ${o.centerOfMass.y}, ${o.centerOfMass.z})`),l.closeBlock("}"),l.closeBlock("}"),r.length>0){const p=r[0];l.beginBlock('def RealityKitStruct "material"',"{",!0);const m=p.sharedMaterial;m&&m.dynamicFriction!==void 0&&l.appendLine(`double dynamicFriction = ${(h=p.sharedMaterial)==null?void 0:h.dynamicFriction}`),m&&m.bounciness!==void 0&&l.appendLine(`double restitution = ${(u=p.sharedMaterial)==null?void 0:u.bounciness}`),m&&m.staticFriction!==void 0&&l.appendLine(`double staticFriction = ${(f=p.sharedMaterial)==null?void 0:f.staticFriction}`),l.closeBlock("}")}l.closeBlock("}")}}),a&&(t.addEventListener("serialize",(l,c)=>{var f;l.beginBlock('def RealityKitComponent "Collider"',"{",!0),l.appendLine("uint group = 1"),l.appendLine('uniform token info:id = "RealityKit.Collider"'),l.appendLine("uint mask = 4294967295");const u=a.isTrigger?"Trigger":"Default";if(l.appendLine(`token type = "${u}"`),l.beginBlock('def RealityKitStruct "Shape"',"{",!0),a instanceof Wy){const p=a;l.appendLine('token shapeType = "Sphere"'),l.appendLine(`float radius = ${p.radius}`)}else if(a instanceof qy){const p=a;l.appendLine('token shapeType = "Box"'),l.appendLine(`float3 extent = (${p.size.x}, ${p.size.y}, ${p.size.z})`)}else if(a instanceof Hh){const p=a;l.appendLine('token shapeType = "Capsule"'),l.appendLine(`float radius = ${p.radius}`),l.appendLine(`float height = ${p.height}`)}else if(a instanceof Hp&&((f=a.sharedMesh)!=null&&f.geometry)){const p=a.sharedMesh.geometry;p.boundingBox||p.computeBoundingBox();const m=a.sharedMesh.geometry.boundingBox;m&&(l.appendLine('token shapeType = "Box"'),l.appendLine(`float3 extent = (${m.max.x-m.min.x}, ${m.max.y-m.min.y}, ${m.max.z-m.min.z})`),console.log("[USDZ] Only Box, Sphere, and Capsule colliders are supported in visionOS/iOS. MeshCollider will be exported as Box",a))}else console.warn("[USDZ] Only Box, Sphere, and Capsule colliders are supported in visionOS/iOS. Ignoring collider:",a);l.beginBlock('def RealityKitStruct "pose"',"{",!0),l.closeBlock("}"),l.closeBlock("}"),l.closeBlock("}")}),r.length>1&&console.log("WARNING: Multiple colliders detected. visionOS / iOS can only support objects with a single collider, only exporting the first collider: ",a))}}var hye=Object.defineProperty,uye=Object.getOwnPropertyDescriptor,Kh=(s,e,t,i)=>{for(var n=i>1?void 0:i?uye(e,t):e,r=s.length-1,o;r>=0;r--)(o=s[r])&&(n=(i?o(e,t,n):o(n))||n);return i&&n&&hye(e,t,n),n};const pf=ie("debugtext");var us=(s=>(s[s.UpperLeft=0]="UpperLeft",s[s.UpperCenter=1]="UpperCenter",s[s.UpperRight=2]="UpperRight",s[s.MiddleLeft=3]="MiddleLeft",s[s.MiddleCenter=4]="MiddleCenter",s[s.MiddleRight=5]="MiddleRight",s[s.LowerLeft=6]="LowerLeft",s[s.LowerCenter=7]="LowerCenter",s[s.LowerRight=8]="LowerRight",s))(us||{}),rW=(s=>(s[s.Normal=0]="Normal",s[s.Bold=1]="Bold",s[s.Italic=2]="Italic",s[s.BoldAndItalic=3]="BoldAndItalic",s))(rW||{});class Ur extends Qp{constructor(){super(...arguments);d(this,"alignment",0);d(this,"verticalOverflow",0);d(this,"horizontalOverflow",0);d(this,"lineSpacing",1);d(this,"supportRichText",!1);d(this,"font");d(this,"fontStyle",0);d(this,"sRGBTextColor",new Ae(1,0,1));d(this,"_text","");d(this,"_fontSize",12);d(this,"_textMeshUi",null);d(this,"_didHandleTextRenderOnTop",!1)}setAlphaFactor(t){var i;super.setAlphaFactor(t),(i=this.uiObject)==null||i.set({fontOpacity:this.color.alpha*this.alphaFactor}),this.markDirty()}get text(){return this._text}set text(t){t!==this._text&&(this._text=t,this.feedText(this.text,this.supportRichText),this.markDirty())}set_text(t){this.text=t}get fontSize(){return this._fontSize}set fontSize(t){var i;this._fontSize=t,(i=this.uiObject)==null||i.set({fontSize:t})}onColorChanged(){var t;this.sRGBTextColor.copy(this.color),this.sRGBTextColor.convertLinearToSRGB(),(t=this.uiObject)==null||t.set({color:this.sRGBTextColor,fontOpacity:this.color.alpha})}onParentRectTransformChanged(){super.onParentRectTransformChanged(),this.uiObject&&this.updateOverflow()}onBeforeCanvasRender(t){this.updateOverflow()}updateOverflow(){var i;const t=(i=this.uiObject)==null?void 0:i._overflow;t&&(t._needsUpdate=!0,this.markDirty())}onCreate(t){pf&&console.log(this),this.horizontalOverflow==1&&(t.whiteSpace="pre"),this.verticalOverflow==0&&(this.context.renderer.localClippingEnabled=!0,t.overflow="hidden"),this.horizontalOverflow==1&&this.verticalOverflow==0,t.lineHeight=this.lineSpacing,delete t.backgroundOpacity,delete t.backgroundColor,pf&&(t.backgroundColor=16750848,t.backgroundOpacity=.5);const i=this.rectTransform;t={...t,...this.getTextOpts()},this.getAlignment(t),pf&&(t.backgroundColor=Math.random()*16777215,t.backgroundOpacity=.1),this.uiObject=i.createNewText(t),this.feedText(this.text,this.supportRichText)}onAfterAddedToScene(){super.onAfterAddedToScene(),this.handleTextRenderOnTop()}getTextOpts(){const t=this.fontSize,i={color:this.color,fontOpacity:this.color.alpha,fontSize:t,fontKerning:"normal"};return this.setFont(i,this.fontStyle),i}onEnable(){var t;super.onEnable(),this._didHandleTextRenderOnTop=!1,this.uiObject&&this.uiObject.addAfterUpdate(()=>{this.setShadowComponentOwner(this.uiObject),this.markDirty()}),setTimeout(()=>this.markDirty(),10),(t=this.canvas)==null||t.registerEventReceiver(this)}onDisable(){var t;super.onDisable(),(t=this.canvas)==null||t.unregisterEventReceiver(this)}getAlignment(t){switch(t.flexDirection="column",this.alignment){case 0:case 3:case 6:t.textAlign="left";break;case 1:case 4:case 7:t.textAlign="center";break;case 2:case 5:case 8:t.textAlign="right";break}switch(this.alignment){default:case 0:case 1:case 2:t.alignItems="start";break;case 3:case 4:case 5:t.alignItems="center";break;case 6:case 7:case 8:t.alignItems="end";break}return t}feedText(t,i){var n,r,o;if(pf&&console.log("feedText",this.uiObject,t,i),!!this.uiObject)if(this._textMeshUi||(this._textMeshUi=[]),this.uiObject.children.length=0,!i||t.length===0)this.uiObject.textContent=t;else{let a=this.getNextTag(t);if(a){if(a.startIndex>0){for(let h=this.uiObject.children.length-1;h>=0;h--){const u=this.uiObject.children[h];u.isUI&&(this.uiObject.remove(u),u.clear())}const c=new yS({textContent:t.substring(0,a.startIndex),color:"inherit"});this.uiObject.add(c)}}else{this.uiObject.textContent="",this.setOptions({textContent:t});return}const l=[];for(;a;){const c=this.getNextTag(t,a.endIndex),h={fontFamily:(n=this.uiObject)==null?void 0:n.get("fontFamily"),color:"inherit",textContent:""};if(c){h.textContent=this.getText(t,a,c),this.handleTag(a,h,l);const u=new yS(h);(r=this.uiObject)==null||r.add(u)}else{h.textContent=t.substring(a.endIndex),this.handleTag(a,h,l);const u=new yS(h);(o=this.uiObject)==null||o.add(u)}a=c}}}handleTextRenderOnTop(){this._didHandleTextRenderOnTop||(this._didHandleTextRenderOnTop=!0,this.startCoroutine(this.renderOnTopCoroutine()))}*renderOnTopCoroutine(){if(!this.canvas)return;const t=[],i=this.canvas,n={renderOnTop:i.renderOnTop,depthWrite:i.depthWrite,doubleSided:i.doubleSided};for(;;){let r=!1;if(this._textMeshUi)for(let o=0;o<this._textMeshUi.length;o++){if(t[o]===!0)continue;r=!0;const a=this._textMeshUi[o];a.textContent&&(FC(a,n),t[o]=!0)}if(!r)break;yield}}handleTag(t,i,n){if(!t.isEndTag){if(t.type.includes("color")){const r=new qI(t,{color:i.color});if(n.push(r),t.type.length>6){const o=parseInt("0x"+t.type.substring(7));i.color=o}else i.color=new Ae(1,1,1)}else if(t.type=="b"){this.setFont(i,1);const r=new qI(t,{fontWeight:700});n.push(r)}else if(t.type=="i"){this.setFont(i,2);const r=new qI(t,{fontStyle:"italic"});n.push(r)}}}getText(t,i,n){return t.substring(i.endIndex,n.startIndex)}getNextTag(t,i=0){const n=t.indexOf("<",i),r=t.indexOf(">",n);if(n>=0&&r>=0){const o=t.substring(n+1,r);return{type:o,startIndex:n,endIndex:r+1,isEndTag:o.startsWith("/")}}return null}setFont(t,i){if(!this.font)return;const n=this.font,r=this.getFamilyNameWithCorrectSuffix(n,i);pf&&console.log("Selected font family:"+r);let o=MP.getFontFamily(r);switch(o||(o=MP.addFontFamily(r)),t.fontFamily=o,i){default:case 0:t.fontWeight=400,t.fontStyle="normal";break;case 1:t.fontWeight=700,t.fontStyle="normal";break;case 2:t.fontWeight=400,t.fontStyle="italic";break;case 3:t.fontStyle="italic",t.fontWeight=400}let a=o.getVariant(t.fontWeight,t.fontStyle);if(!a){let l=r;l!=null&&l.endsWith("-msdf.json")||(l+="-msdf.json");let c=r;c!=null&&c.endsWith(".png")||(c+=".png"),a=o.addVariant(t.fontWeight,t.fontStyle,l,c),a==null||a.addEventListener("ready",()=>{this.markDirty()})}}getFamilyNameWithCorrectSuffix(t,i){var h;const n=t.lastIndexOf("-");if(n<0)return t;const r=(h=t.substring(n+1))==null?void 0:h.toLowerCase();if(dye.includes(r))return pf&&console.warn("Unsupported font style: "+r),t;const o=t.lastIndexOf("/");let a=t;o>=0&&(a=a.substring(o+1));const l=a[0]===a[0].toUpperCase(),c=t.substring(0,n);switch(pf&&console.log("Select font: ",t,rW[i],a,l,c),i){case 0:return l?c+"-Regular":c+"-regular";case 1:return l?c+"-Bold":c+"-bold";case 2:return l?c+"-Italic":c+"-italic";case 3:return l?c+"-BoldItalic":c+"-bolditalic";default:return t}}}Kh([x()],Ur.prototype,"alignment",2);Kh([x()],Ur.prototype,"verticalOverflow",2);Kh([x()],Ur.prototype,"horizontalOverflow",2);Kh([x()],Ur.prototype,"lineSpacing",2);Kh([x()],Ur.prototype,"supportRichText",2);Kh([x(URL)],Ur.prototype,"font",2);Kh([x()],Ur.prototype,"fontStyle",2);Kh([x()],Ur.prototype,"text",1);Kh([x()],Ur.prototype,"fontSize",1);class qI{constructor(e,t){d(this,"tag");d(this,"previousValues");this.tag=e,this.previousValues=t}}const dye=["medium","mediumitalic","black","blackitalic","thin","thinitalic","extrabold","light","lightitalic","semibold"];class Yu{constructor(e){d(this,"id");d(this,"content","");d(this,"font",[]);d(this,"pointSize",144);d(this,"width");d(this,"height");d(this,"depth");d(this,"wrapMode");d(this,"horizontalAlignment");d(this,"verticalAlignment");d(this,"material");this.id=e}static getId(){return this.global_id++}setDepth(e){return this.depth=e,this}setPointSize(e){return this.pointSize=e,this}setHorizontalAlignment(e){return this.horizontalAlignment=e,this}setVerticalAlignment(e){return this.verticalAlignment=e,this}writeTo(e,t){var n;t.beginBlock(`def Preliminary_Text "${this.id}"`,"(",!1),t.appendLine('prepend apiSchemas = ["MaterialBindingAPI"]'),t.closeBlock(")"),t.beginBlock(),this.content&&t.appendLine(`string content = "${this.content}"`),(!this.font||this.font.length<=0)&&(this.font||(this.font=[]),(n=this.font)==null||n.push("sans-serif"));const i=this.font.map(r=>`"${r}"`).join(", ");t.appendLine(`string[] font = [ ${i} ]`),t.appendLine(`double pointSize = ${this.pointSize}`),typeof this.width=="number"&&t.appendLine(`double width = ${this.width}`),typeof this.height=="number"&&t.appendLine(`double height = ${this.height}`),typeof this.depth=="number"&&t.appendLine(`double depth = ${this.depth}`),this.wrapMode&&t.appendLine(`token wrapMode = "${this.wrapMode}"`),this.horizontalAlignment&&t.appendLine(`token horizontalAlignment = "${this.horizontalAlignment}"`),this.verticalAlignment&&t.appendLine(`token verticalAlignment = "${this.verticalAlignment}"`),this.material!==void 0&&t.appendLine(`rel material:binding = </StageRoot/Materials/${fO(this.material)}>`),t.closeBlock()}}d(Yu,"global_id",0);class GE{static singleLine(e,t,i){const n=new Yu("text_"+Yu.getId());return n.content=e,t&&(n.pointSize=t),i&&(n.depth=i),n}static multiLine(e,t,i,n,r,o){const a=new Yu("text_"+Yu.getId());return a.content=e,a.width=t,a.height=i,a.horizontalAlignment=n,a.verticalAlignment=r,o!==void 0&&(a.wrapMode=o),a}}const fye=new ye().makeRotationY(Math.PI),pye=new ye().makeScale(-1,1,-1);class db{get extensionName(){return"text"}exportText(e,t,i){const n=re.getComponent(e,Ur);if(!n)return;const r=re.getComponent(e,kr);let o=100,a=100;r&&(o=r.width,a=r.height),t.matrix=fye.clone(),r&&t.matrix.premultiply(pye);const l=n.color.clone();t.material=new Pr({color:l,emissive:l}),t.addEventListener("serialize",(c,h)=>{let u=n.text;u=u.replace(/\r/g,""),u=u.replace(/\n/g,"\\n");const f=GE.multiLine(u,o,a,"center","bottom","flowing");this.setTextAlignment(f,n.alignment),this.setOverflow(f,n),t.material&&(f.material=t.material),f.pointSize=this.convertToTextSize(n.fontSize),f.depth=.001,f.writeTo(void 0,c)})}convertToTextSize(e){return 1/.0502*144*e}setOverflow(e,t){t.horizontalOverflow?e.wrapMode="singleLine":e.wrapMode="flowing"}setTextAlignment(e,t){switch(t){case us.LowerLeft:case us.MiddleLeft:case us.UpperLeft:e.horizontalAlignment="left";break;case us.LowerCenter:case us.MiddleCenter:case us.UpperCenter:e.horizontalAlignment="center";break;case us.LowerRight:case us.MiddleRight:case us.UpperRight:e.horizontalAlignment="right";break}switch(t){case us.LowerLeft:case us.LowerCenter:case us.LowerRight:e.verticalAlignment="bottom";break;case us.MiddleLeft:case us.MiddleCenter:case us.MiddleRight:e.verticalAlignment="middle";break;case us.UpperLeft:case us.UpperCenter:case us.UpperRight:e.verticalAlignment="top";break}}}class HE{get extensionName(){return"tmui"}onExportObject(e,t,i){const n=re.getComponent(e,ar);if(n&&n.enabled&&n.renderMode===jj.WorldSpace){const r=new db,o=re.getComponent(e,kr),a=re.getComponent(e,yd),l=new Array;if(o){if(!re.isActiveSelf(e)){const u=re.isActiveSelf(e);re.setActive(e,!0),o.onEnable(),o.updateTransform(),l.push(()=>{o.onDisable(),re.setActive(e,u)})}e.traverse(u=>{if(!re.isActiveInHierarchy(u)){const f=re.isActiveSelf(u);re.setActive(u,!0);const p=re.getComponent(u,Ha);p&&(p.onEnable(),l.push(()=>{p.onDisable()}));const m=re.getComponent(u,kr);m&&(m.onEnable(),m.updateTransform(),m.onApplyTransform(),l.push(()=>{m.onDisable()}));const y=re.getComponent(u,Ur);y&&(y.onEnable(),l.push(()=>{y.onDisable()})),l.push(()=>{re.setActive(u,f)})}}),o.width,o.height;const c=nr.createEmpty(),h=o.shadowComponent;if(t.add(c),h){const u=h.matrix;c.matrix.copy(u);const f=new Map,p=new Map;f.set(h,c),p.set(h,a?a.alpha:1),h.traverse(m=>{if(m===h)return;const y=nr.createEmpty();y.matrix.copy(m.matrix);const g=m.parent,v=!!g&&typeof g.textContent=="string"&&g.textContent.length>0;let _=p.get(g)||1;const A=re.getComponent(m,yd);if(A&&(_*=A.alpha),m instanceof fe&&v){const S=m[Da];S?r.exportText(S.gameObject,y,i):console.error("Error when exporting UI: shadow component owner not found. This is likely a bug.",m)}if(m instanceof fe&&!v){const S=m.geometry.clone();S.scale(1,1,-1),this.flipWindingOrder(S),y.geometry=S;const E=new Ae,M=m.material.opacity;E.copy(m.material.color),y.material=new ni({color:E,opacity:M*_,map:m.material.map,transparent:!0})}f.set(m,y),p.set(m,_);const b=f.get(g);if(!b){console.error("Error when exporting UI: shadow component parent not found!",m,m.parent);return}b.add(y)})}}for(const c of l)c()}}flipWindingOrder(e){const t=e.index.array;for(let i=0,n=t.length/3;i<n;i++){const r=t[i*3];t[i*3]=t[i*3+2],t[i*3+2]=r}e.index.needsUpdate=!0}}const BA=ie("debugusdz");function mye(s,e){var a;const t=[],i=re.getComponentsInChildren(s,or),n=re.getComponentsInChildren(s,Br),r=new Array,o=new Array;if(e.injectImplicitBehaviours)for(const l of i){if(!l||!l.runtimeAnimatorController||!l.enabled)continue;const c=l.runtimeAnimatorController.activeState;if(!c||!c.motion||!c.motion.clip||((a=c.motion.clip.tracks)==null?void 0:a.length)<1||r.includes(l))continue;const h=new Mp;h.animator=l,h.stateName=c.name,h.trigger="start",h.name="PlayAnimationOnClick_implicitAtStart_"+h.stateName;const u=new ve;re.addComponent(u,h),o.push(u),r.push(l),s.add(u)}else for(const l of i){if(!l||!l.runtimeAnimatorController||!l.enabled)continue;BA&&console.log(l);const c=[];for(const h of l.runtimeAnimatorController.enumerateActions()){BA&&console.log(h);const u=h.getClip();c.includes(u)||c.push(u)}t.push({root:l.gameObject,clips:c})}if(e.injectImplicitBehaviours)for(const l of n){if(!l||!l.clip||!l.enabled||!l.playAutomatically||r.includes(l))continue;const c=new Mp;c.animation=l,c.stateName=l.clip.name,c.trigger="start",c.name="PlayAnimationOnClick_implicitAtStart_"+c.stateName;const h=new ve;re.addComponent(h,c),o.push(h),r.push(l),s.add(h)}else for(const l of n){BA&&console.log(l);const c=[];for(const h of l.animations)c.includes(h)||c.push(h);t.push({root:l.gameObject,clips:c})}BA&&(t==null?void 0:t.length)>0&&console.log("USDZ Animation Clips without behaviours",t);for(const l of t)for(const c of l.clips)e.registerAnimation(l.root,c);return o}function gye(s,e){const t=re.getComponentsInChildren(s,Un),i=re.getComponentsInChildren(s,vd),n=new Array,r=new Array;BA&&console.log({audioSources:t,playAudioOnClicks:i});for(const o of i){if(!o.target)continue;const a=t.indexOf(o.target);a>-1&&t.splice(a,1)}for(const o of t){if(!o||!o.clip||o.volume<=0||n.includes(o))continue;const a=new vd;a.target=o,a.name="PlayAudioOnClick_implicitAtStart_",a.trigger="start";const l=new ve;re.addComponent(l,a),console.log("implicit PlayAudioOnStart",l,a),r.push(l),n.push(o),s.add(l)}return r}function yye(s){return new ns("DisableAtStart",Ls.sceneStartTrigger(),gi.fadeAction(s,0,!1))}function e4(s){const e=s.domElement.shadowRoot.querySelector("link[rel='ar']");if(e)return e;const t=document.createElement("div");t.classList.add("menu"),t.classList.add("quicklook-menu"),t.style.display="none",t.style.visibility="hidden";const i=document.createElement("button");i.id="open-in-ar",i.innerText="Open in QuickLook",t.appendChild(i);const n=document.createElement("a");n.id="needle-usdz-link",n.style.display="none",n.rel="ar",n.href="",t.appendChild(n);const r=document.createElement("img");return r.id="button",n.appendChild(r),s.domElement.shadowRoot.appendChild(t),n}var vye=Object.defineProperty,Aye=Object.getOwnPropertyDescriptor,Nr=(s,e,t,i)=>{for(var n=i>1?void 0:i?Aye(e,t):e,r=s.length-1,o;r>=0;r--)(o=s[r])&&(n=(i?o(e,t,n):o(n))||n);return i&&n&&vye(e,t,n),n};const ya=ie("debugusdz");class Ud{constructor(){d(this,"callToAction");d(this,"checkoutTitle");d(this,"checkoutSubtitle");d(this,"callToActionURL")}}Nr([x()],Ud.prototype,"callToAction",2);Nr([x()],Ud.prototype,"checkoutTitle",2);Nr([x()],Ud.prototype,"checkoutSubtitle",2);Nr([x()],Ud.prototype,"callToActionURL",2);var rS;const HB=(rS=class extends Ie{constructor(){super(...arguments);d(this,"objectToExport");d(this,"autoExportAnimations",!0);d(this,"autoExportAudioSources",!0);d(this,"exportFileName");d(this,"customUsdzFile");d(this,"customBranding");d(this,"anchoringType","plane");d(this,"maxTextureSize",2048);d(this,"planeAnchoringAlignment","horizontal");d(this,"interactive",!0);d(this,"allowCreateQuicklookButton",!0);d(this,"quickLookCompatible",!0);d(this,"extensions",[]);d(this,"link");d(this,"button");d(this,"onClickedOpenInARElement",e=>{e.preventDefault(),this.exportAndOpen()});d(this,"_currentExportTasks",new Map);d(this,"_previousTimeScale",1);d(this,"lastCallback");d(this,"_rootSessionRootWasAppliedTo",null);d(this,"_rootPositionBeforeExport",new w);d(this,"_rootRotationBeforeExport",new Ce);d(this,"_rootScaleBeforeExport",new w)}start(){var e,t,i;ya&&(console.log("USDZExporter",this),console.log("Debug USDZ Mode. Press 'T' to export"),window.addEventListener("keydown",n=>{switch(n.key){case"t":this.exportAsync();break}}),qa()&&setTimeout(()=>{this.exportAsync()},2e3)),this.objectToExport||(this.objectToExport=this.gameObject),!((t=(e=this.objectToExport)==null?void 0:e.children)!=null&&t.length)&&!((i=this.objectToExport)!=null&&i.isMesh)&&(this.objectToExport=this.context.scene),this.interactive&&(this.extensions.push(new OE),this.extensions.push(new Rd),this.extensions.push(new zE),this.extensions.push(new db),this.extensions.push(new HE))}onEnable(){var i;const e=bp(),t=Hg();(ya||e&&t)&&(this.allowCreateQuicklookButton&&(this.button=this.createQuicklookButton()),this.lastCallback=this.quicklookCallback.bind(this),this.link=e4(this.context),this.link.addEventListener("message",this.lastCallback)),ya&&pn("USDZ Exporter enabled: "+this.name),(i=document.getElementById("open-in-ar"))==null||i.addEventListener("click",this.onClickedOpenInARElement)}onDisable(){var e,t,i;(e=this.button)==null||e.remove(),(t=this.link)==null||t.removeEventListener("message",this.lastCallback),ya&&pn("USDZ Exporter disabled: "+this.name),(i=document.getElementById("open-in-ar"))==null||i.removeEventListener("click",this.onClickedOpenInARElement)}async exportAsync(){return this.exportAndOpen()}async exportAndOpen(){var i;let e=this.exportFileName??((i=this.objectToExport)==null?void 0:i.name)??this.name;if(e+="-"+F8(),ed()||(e!==""&&(e+="-"),e+="MadeWithNeedle"),this.link||(this.link=e4(this.context)),this.customUsdzFile)return ya&&console.log("Exporting custom usdz",this.customUsdzFile),this.openInQuickLook(this.customUsdzFile,e),null;if(!this.objectToExport)return console.warn("No object to export",this),null;const t=await this.export(this.objectToExport);return t?(ya&&console.log("USDZ generation done. Downloading as "+e),this.openInQuickLook(t,e),t):(console.error("USDZ generation failed. Please report a bug",this),null)}async export(e){if(!e)return console.warn("No object to export"),null;const t=this._currentExportTasks.get(e);if(t)return t;const i=this.internalExport(e);return i instanceof Promise?(this._currentExportTasks.set(e,i),i.then(n=>(this._currentExportTasks.delete(e),n)).catch(n=>(this._currentExportTasks.delete(e),console.error("Error during USDZ export – please report a bug!",n),null))):i}async internalExport(e){ri.start("export-usdz",{onProgress:_=>{this.dispatchEvent(new CustomEvent("export-progress",{detail:{progress:_}}))}}),ri.report("export-usdz",{message:"Starting export",totalSteps:40,currentStep:0}),ri.report("export-usdz",{message:"Load progressive textures",autoStep:5}),ri.start("export-usdz-textures","export-usdz");const t=re.getComponentsInChildren(e,Za);for(const _ of t)_&&_.enabled&&_.start&&_.start();const i=re.getComponentsInChildren(e,Nn),n=new Array;let r=0;for(const _ of i){for(const A of _.sharedMeshes)if(A){const b=yi.assignMeshLOD(A,0);b instanceof Promise&&n.push(new Promise((S,E)=>{b.then(()=>{r++,ri.report("export-usdz-textures",{message:"Loaded progressive mesh",currentStep:r,totalSteps:n.length}),S()}).catch(M=>E(M))}))}for(const A of _.sharedMaterials)if(A){const b=yi.assignTextureLOD(A,0);b instanceof Promise&&n.push(new Promise((S,E)=>{b.then(()=>{r++,ri.report("export-usdz-textures",{message:"Loaded progressive texture",currentStep:r,totalSteps:n.length}),S()}).catch(M=>E(M))}))}}ya&&pn("Progressive Loading: "+n.length),await Promise.all(n),ya&&pn("Progressive Loading: done"),ri.end("export-usdz-textures");const o=tr.Global.Mask;tr.Global.Set(rc.AR);const a=new H8,l=new Z_(this.quickLookCompatible),c=[l,...this.extensions],h={self:this,exporter:a,extensions:c,object:e};ri.report("export-usdz","Invoking before-export"),this.dispatchEvent(new CustomEvent("before-export",{detail:h})),this.applyWebARSessionRoot(),this._previousTimeScale=this.context.time.timeScale,this.context.time.timeScale=0,ri.report("export-usdz","auto export animations and audio sources");const u=new Array;this.autoExportAnimations&&u.push(...mye(e,l)),this.extensions.find(_=>_.extensionName==="Audio")&&this.autoExportAudioSources&&u.push(...gye(e)),a.debug=ya,a.keepObject=_=>{const A=re.getComponent(_,Nn);return!(A&&!A.enabled)};const p=new Array;this.objectToExport&&this.quickLookCompatible&&this.interactive&&this.objectToExport.traverse(_=>{_.visible||p.push(_)});const m=this.extensions.find(_=>_.extensionName==="Behaviour");this.interactive&&m&&p.length>0&&m.addBehavior(yye(p));let y=!0;this.quickLookCompatible&&!this.interactive&&(y=!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"),ri.report("export-usdz","Invoking exporter.parse");const g=await a.parse(this.objectToExport,{ar:{anchoring:{type:this.anchoringType},planeAnchoring:{alignment:this.planeAnchoringAlignment}},extensions:c,quickLookCompatible:this.quickLookCompatible,maxTextureSize:this.maxTextureSize,exportInvisible:y}),v=new Blob([g],{type:"model/vnd.usdz+zip"});this.revertWebARSessionRoot(),this.context.time.timeScale=this._previousTimeScale,ri.report("export-usdz","Invoking after-export"),this.dispatchEvent(new CustomEvent("after-export",{detail:h}));for(const _ of u)re.destroy(_);return tr.Global.Set(o),ri.end("export-usdz"),v}openInQuickLook(e,t){const i=e instanceof Blob?URL.createObjectURL(e):e,n=this.buildQuicklookOverlay();ya&&console.log("QuickLook Overlay",n);const r=n.callToAction?encodeURIComponent(n.callToAction):"",o=n.checkoutTitle?encodeURIComponent(n.checkoutTitle):"",a=n.checkoutSubtitle?encodeURIComponent(n.checkoutSubtitle):"";this.link.href=i+`#callToAction=${r}&checkoutTitle=${o}&checkoutSubtitle=${a}&callToActionURL=${n.callToActionURL}`,this.lastCallback||(this.lastCallback=this.quicklookCallback.bind(this),this.link.addEventListener("message",this.lastCallback)),this.link.download=t+".usdz",this.link.click()}download(e,t){HB.save(e,t)}static save(e,t){const i=document.createElement("a");i.style.display="none",document.body.appendChild(i),typeof e=="string"?i.href=e:i.href=URL.createObjectURL(e),i.download=t,i.click(),i.remove()}quicklookCallback(e){if((e==null?void 0:e.data)=="_apple_ar_quicklook_button_tapped"){ya&&Ni("Quicklook closed via call to action button");var t=new CustomEvent("quicklook-button-tapped",{detail:this});if(this.dispatchEvent(t),!t.defaultPrevented){const i=new URLSearchParams(this.link.href);if(i){const n=i.get("callToActionURL");ya&&pn("Quicklook url: "+n),n&&(ed()?globalThis.open(n,"_blank"):console.warn("Quicklook closed: custom redirects require a Needle Engine Pro license: https://needle.tools/pricing",n))}}}}buildQuicklookOverlay(){var i,n,r,o,a,l;const e={};return this.customBranding&&Object.assign(e,this.customBranding),ed()||(console.log("Custom Quicklook banner text requires pro license: https://needle.tools/pricing"),e.callToAction="Close",e.checkoutTitle="🌵 Made with Needle",e.checkoutSubtitle="_"),(((i=e.callToAction)==null?void 0:i.length)||((n=e.checkoutTitle)==null?void 0:n.length)||((r=e.checkoutSubtitle)==null?void 0:r.length))&&((o=e.callToAction)!=null&&o.length||(e.callToAction="\0"),(a=e.checkoutTitle)!=null&&a.length||(e.checkoutTitle="\0"),(l=e.checkoutSubtitle)!=null&&l.length||(e.checkoutSubtitle="\0")),this.dispatchEvent(new CustomEvent("quicklook-overlay",{detail:e})),e}getARScaleAndTarget(){if(!this.objectToExport)return{scale:1,_invertForward:!1,target:this.gameObject,sessionRoot:null};let e=re.getComponentInParent(this.objectToExport,ao);e||(e=re.getComponentInChildren(this.objectToExport,ao));let t=1,i=!1;const n=this.objectToExport;if(e)t=e.arScale,i=e.invertForward;else{const a=re.findObjectOfType(Us);a&&(t=a.arSceneScale)}return{scale:1/t,_invertForward:i,target:n,sessionRoot:(e==null?void 0:e.gameObject)??null}}applyWebARSessionRoot(){if(!this.objectToExport)return;const{scale:e,_invertForward:t,target:i,sessionRoot:n}=this.getARScaleAndTarget(),r=n==null?void 0:n.matrixWorld.clone().invert();this._rootSessionRootWasAppliedTo=i,this._rootPositionBeforeExport.copy(i.position),this._rootRotationBeforeExport.copy(i.quaternion),this._rootScaleBeforeExport.copy(i.scale),i.scale.multiplyScalar(e),t&&i.quaternion.multiply(HB.invertForwardQuaternion),i.updateMatrix(),i.updateMatrixWorld(!0),n&&r&&i.matrix.premultiply(r)}revertWebARSessionRoot(){if(!this.objectToExport||!this._rootSessionRootWasAppliedTo)return;const e=this._rootSessionRootWasAppliedTo;e.position.copy(this._rootPositionBeforeExport),e.quaternion.copy(this._rootRotationBeforeExport),e.scale.copy(this._rootScaleBeforeExport),e.updateMatrix(),e.updateMatrixWorld(!0),this._rootSessionRootWasAppliedTo=null}createQuicklookButton(){const t=Uh.getOrCreate().createQuicklookButton();return t.parentNode||this.context.menu.appendChild(t),t}},d(rS,"invertForwardMatrix",new ye().makeRotationY(Math.PI)),d(rS,"invertForwardQuaternion",new Ce().setFromEuler(new oi(0,Math.PI,0))),rS);let Fn=HB;Nr([x(ve)],Fn.prototype,"objectToExport",2);Nr([x()],Fn.prototype,"autoExportAnimations",2);Nr([x()],Fn.prototype,"autoExportAudioSources",2);Nr([x()],Fn.prototype,"exportFileName",2);Nr([x(URL)],Fn.prototype,"customUsdzFile",2);Nr([x(Ud)],Fn.prototype,"customBranding",2);Nr([x()],Fn.prototype,"anchoringType",2);Nr([x()],Fn.prototype,"maxTextureSize",2);Nr([x()],Fn.prototype,"planeAnchoringAlignment",2);Nr([x()],Fn.prototype,"interactive",2);Nr([x()],Fn.prototype,"allowCreateQuicklookButton",2);Nr([x()],Fn.prototype,"quickLookCompatible",2);class fb extends Ie{constructor(){super(...arguments);d(this,"isUsed",!0);d(this,"usedBy",null)}}class SL extends Ie{}const t4=ie("debugdeletable");class VE extends Oa{}class CL extends Ie{constructor(){super(...arguments);d(this,"deleteBoxes",[])}awake(){this.deleteBoxes=re.findObjectsOfType(VE,this.context)}update(){for(const t of this.deleteBoxes){const i=this.gameObject;if(t.isInBox(i)===!0){const r=re.getComponentInParent(this.gameObject,fb);r?t4&&console.warn("Can not delete object with usage marker",this.guid,r):(t4&&console.log("DESTROY",this.gameObject),H_(this.gameObject,this.context.connection))}}}}var _ye=Object.defineProperty,bye=Object.getOwnPropertyDescriptor,Kp=(s,e,t,i)=>{for(var n=i>1?void 0:i?bye(e,t):e,r=s.length-1,o;r>=0;r--)(o=s[r])&&(n=(i?o(e,t,n):o(n))||n);return i&&n&&_ye(e,t,n),n};const xye=ie("debugpost");class Dl extends dr{constructor(){super(...arguments);d(this,"mode");d(this,"focusDistance",new Ke(1));d(this,"focalLength",new Ke(.2));d(this,"aperture",new Ke(20));d(this,"gaussianMaxRadius",new Ke);d(this,"resolutionScale",new Ke(1*1/window.devicePixelRatio));d(this,"bokehScale",new Ke)}get typeName(){return"DepthOfField"}init(){this.focalLength.valueProcessor=i=>{const n=i/300,r=2;return it.lerp(r,.01,n)};const t=20;this.aperture.valueProcessor=i=>{const n=1-i/32;return it.lerp(1,t,n)}}onCreateEffect(){if(this.mode===0){xye&&console.warn("DepthOfField: Mode is set to Off");return}const t=new gQ(this.context.mainCamera,{worldFocusRange:.2,focalLength:1,bokehScale:20,resolutionScale:this.resolutionScale.value});return this.focusDistance.onValueChanged=i=>{t.cocMaterial.worldFocusDistance=i},this.focalLength.onValueChanged=i=>t.cocMaterial.worldFocusRange=i,this.aperture.onValueChanged=i=>t.bokehScale=i,this.resolutionScale&&(this.resolutionScale.onValueChanged=i=>t.resolution.scale=i),[t]}unapply(){}}Kp([x()],Dl.prototype,"mode",2);Kp([x(Ke)],Dl.prototype,"focusDistance",2);Kp([x(Ke)],Dl.prototype,"focalLength",2);Kp([x(Ke)],Dl.prototype,"aperture",2);Kp([x(Ke)],Dl.prototype,"gaussianMaxRadius",2);Kp([x(Ke)],Dl.prototype,"resolutionScale",2);Kp([x(Ke)],Dl.prototype,"bokehScale",2);Ka("DepthOfField",Dl);var wye=Object.defineProperty,Sye=Object.getOwnPropertyDescriptor,Cye=(s,e,t,i)=>{for(var n=i>1?void 0:i?Sye(e,t):e,r=s.length-1,o;r>=0;r--)(o=s[r])&&(n=(i?o(e,t,n):o(n))||n);return i&&n&&wye(e,t,n),n};class QE extends Ie{constructor(){super(...arguments);d(this,"visibleOn")}onEnable(){this.apply()}apply(){this.test()||re.setActive(this.gameObject,!1)}test(){return this.visibleOn<0?!0:qa()?(this.visibleOn&2)!==0:(this.visibleOn&1)!==0}}Cye([x()],QE.prototype,"visibleOn",2);class EL{get extensionName(){return"DocumentExtension"}onAfterBuildDocument(e){}}var Eye=Object.defineProperty,Mye=Object.getOwnPropertyDescriptor,Jp=(s,e,t,i)=>{for(var n=i>1?void 0:i?Mye(e,t):e,r=s.length-1,o;r>=0;r--)(o=s[r])&&(n=(i?o(e,t,n):o(n))||n);return i&&n&&Eye(e,t,n),n};const pc=ie("debugdrag");var oW=(s=>(s[s.XZPlane=0]="XZPlane",s[s.Attached=1]="Attached",s[s.HitNormal=2]="HitNormal",s[s.DynamicViewAngle=3]="DynamicViewAngle",s[s.SnapToSurfaces=4]="SnapToSurfaces",s[s.None=5]="None",s))(oW||{}),oS;const Xl=(oS=class extends Ie{constructor(){super(...arguments);d(this,"dragMode",3);d(this,"snapGridResolution",0);d(this,"keepRotation",!0);d(this,"xrDragMode",1);d(this,"xrKeepRotation",!1);d(this,"xrDistanceDragFactor",1);d(this,"showGizmo",!1);d(this,"targetObject",null);d(this,"orbit",null);d(this,"_dragHelper",null);d(this,"_draggingRigidbodies",[]);d(this,"_potentialDragStartEvt",null);d(this,"_dragHandlers",new Map);d(this,"_totalMovement",new w);d(this,"_marker",null);d(this,"_isDragging",!1);d(this,"_didDrag",!1)}static get HasAnySelected(){return this._active>0}setTargetObject(e){this.targetObject=e;for(const t of this._dragHandlers.values())t.setTargetObject(e)}awake(){this._potentialDragStartEvt=null,this._dragHandlers=new Map,this._totalMovement=new w,this._marker=null,this._isDragging=!1,this._didDrag=!1,this._dragHelper=null,this._draggingRigidbodies=[]}start(){this.orbit=re.findObjectOfType(wi,this.context),this.gameObject.getComponentInParent(sa)||this.gameObject.addComponent(sa)}allowEdit(e=null){return this.context.connection.allowEditing}onPointerEnter(e){if(!this.allowEdit(this.gameObject)||e.mode!=="screen"||(e.event.mode==="tracked-pointer"||e.event.mode==="transient-pointer"?this.xrDragMode:this.dragMode)===5)return;const n=re.getComponentInParent(e.object,Xl);!n||n!==this||(Xl.lastHovered=e.object,this.context.domElement.style.cursor="pointer")}onPointerExit(e){this.allowEdit(this.gameObject)&&e.mode==="screen"&&Xl.lastHovered===e.object&&(this.context.domElement.style.cursor="auto")}onPointerDown(e){if(!(!this.allowEdit(this.gameObject)||e.used||(e.mode==="tracked-pointer"||e.mode==="transient-pointer"?this.xrDragMode:this.dragMode)===5)&&(Xl.lastHovered=e.object,e.button===0)){this._dragHandlers.size===0&&(this._didDrag=!1,this._totalMovement.set(0,0,0),this._potentialDragStartEvt=e),Xl._active+=1;const n=new Iye(this,this.targetObject||this.gameObject);if(this._dragHandlers.set(e.event.space,n),this.orbit&&(this.orbit.enabled=!1),n.onDragStart(e),this._dragHandlers.size===2){const r=this._dragHandlers.values(),o=r.next().value,a=r.next().value,l=new Tye(this,this.targetObject||this.gameObject,o,a);this._dragHandlers.set(this.gameObject,l),l.onDragStart(e)}e.use()}}onPointerMove(e){(this._isDragging||this._potentialDragStartEvt!==null)&&e.use()}onPointerUp(e){if(pc&&_t.DrawLabel(e.point??this.gameObject.worldPosition,"POINTERUP:"+e.pointerId+", "+e.button,.03,3),!this.allowEdit(this.gameObject)||e.button!==0)return;this._potentialDragStartEvt=null;const t=this._dragHandlers.get(e.event.space),i=this._dragHandlers.get(this.gameObject);i&&(i.handlerA===t||i.handlerB===t)&&(this._dragHandlers.delete(this.gameObject),i.onDragEnd(e)),t&&(Xl._active>0&&(Xl._active-=1),t.onDragEnd&&t.onDragEnd(e),this._dragHandlers.delete(e.event.space),this._dragHandlers.size===0&&this.onLastDragEnd(e),e.use()),Xl._active===0&&this.orbit&&(this.orbit.enabled=!0)}update(){for(const e of this._dragHandlers.values())e.collectMovementInfo&&e.collectMovementInfo(),e.getTotalMovement&&this._totalMovement.add(e.getTotalMovement());if(this._potentialDragStartEvt){if(!this._didDrag)if(this._totalMovement.length()>3e-4)this._didDrag=!0;else return;const e=this._potentialDragStartEvt;this._potentialDragStartEvt=null,this.onFirstDragStart(e)}for(const e of this._dragHandlers.values())e.onDragUpdate&&e.onDragUpdate(this._dragHandlers.size);this._dragHelper&&this._dragHelper.hasSelected&&this.onAnyDragUpdate()}onFirstDragStart(e){if(!this._dragHelper)if(this.context.mainCamera)this._dragHelper=new HS(this.context.mainCamera);else return;if(!e||!e.object)return;const t=re.getComponentInParent(e.object,Xl);if(!t||t!==this&&t._isDragging)return;const i=this.targetObject||this.gameObject;if(!i)return;this._isDragging=!0,this._dragHelper.setSelected(i,this.context),this.orbit&&(this.orbit.enabled=!1);const n=re.getComponentInChildren(i,pd);pc&&console.log("DRAG START",n,i),n&&(n.fastMode=!0,n==null||n.requestOwnership()),this._marker=re.addComponent(i,fb),this._draggingRigidbodies.length=0;const r=re.getComponentsInChildren(i,zi);r&&this._draggingRigidbodies.push(...r)}onAnyDragUpdate(){if(!this._dragHelper)return;this._dragHelper.showGizmo=this.showGizmo,this._dragHelper.onUpdate(this.context);for(const t of this._draggingRigidbodies)t.wakeUp(),t.resetVelocities(),t.resetForcesAndTorques();const e=this.targetObject||this.gameObject;Fa.markDirty(e)}onLastDragEnd(e){if(!this||!this._isDragging||(this._isDragging=!1,!this._dragHelper))return;for(const i of this._draggingRigidbodies)i.setVelocity(i.smoothedVelocity);this._draggingRigidbodies.length=0;const t=this._dragHelper.selected;if(pc&&console.log("DRAG END",t,t==null?void 0:t.visible),this._dragHelper.setSelected(null,this.context),this.orbit&&(this.orbit.enabled=!0),e!=null&&e.object){const i=re.getComponentInChildren(e.object,pd);i&&(i.fastMode=!1)}this._marker&&this._marker.destroy()}},d(oS,"_active",0),d(oS,"lastHovered"),oS);let Qa=Xl;Jp([x()],Qa.prototype,"dragMode",2);Jp([x()],Qa.prototype,"snapGridResolution",2);Jp([x()],Qa.prototype,"keepRotation",2);Jp([x()],Qa.prototype,"xrDragMode",2);Jp([x()],Qa.prototype,"xrKeepRotation",2);Jp([x()],Qa.prototype,"xrDistanceDragFactor",2);Jp([x()],Qa.prototype,"showGizmo",2);class Tye{constructor(e,t,i,n){d(this,"handlerA");d(this,"handlerB");d(this,"context");d(this,"settings");d(this,"gameObject");d(this,"_handlerAAttachmentPoint",new w);d(this,"_handlerBAttachmentPoint",new w);d(this,"_followObject");d(this,"_manipulatorObject");d(this,"_deviceMode");d(this,"_followObjectStartWorldQuaternion",new Ce);d(this,"_manipulatorPosOffset",new w);d(this,"_manipulatorRotOffset",new Ce);d(this,"_manipulatorScaleOffset",new w);d(this,"_tempVec1",new w);d(this,"_tempVec2",new w);d(this,"_tempVec3",new w);d(this,"tempLookMatrix",new ye);d(this,"_initialScale",new w);d(this,"_initialDistance",0);var o,a;this.context=e.context,this.settings=e,this.gameObject=t,this.handlerA=i,this.handlerB=n,this._followObject=new ve,this._manipulatorObject=new ve,this.context.scene.add(this._manipulatorObject);const r=(a=(o=xt.active)==null?void 0:o.rig)==null?void 0:a.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),r&&(r.worldToLocal(this._tempVec1),r.worldToLocal(this._tempVec2)),this._initialDistance=this._tempVec1.distanceTo(this._tempVec2),this._initialDistance<.02?(pc&&console.log("Finding alternative drag attachment points since initial distance is too low: "+this._initialDistance.toFixed(2)),this.handlerA.followObject.parent.getWorldPosition(this._tempVec1),this.handlerB.followObject.parent.getWorldPosition(this._tempVec2),this._handlerAAttachmentPoint.copy(this._tempVec1),this._handlerBAttachmentPoint.copy(this._tempVec2),this.gameObject.worldToLocal(this._handlerAAttachmentPoint),this.gameObject.worldToLocal(this._handlerBAttachmentPoint),this._initialDistance=this._tempVec1.distanceTo(this._tempVec2),this._initialDistance<.001&&(console.warn("Not supported right now – controller drag points for multitouch are too close!"),this._initialDistance=1)):(this._handlerAAttachmentPoint.copy(this.handlerA.hitPointInLocalSpace),this._handlerBAttachmentPoint.copy(this.handlerB.hitPointInLocalSpace)),this._tempVec3.lerpVectors(this._tempVec1,this._tempVec2,.5),this._initialScale.copy(t.scale),pc){this._followObject.add(new na(2)),this._manipulatorObject.add(new na(5));const l=c=>`${c.x.toFixed(2)}, ${c.y.toFixed(2)}, ${c.z.toFixed(2)}`;_t.DrawLine(this._tempVec1,this._tempVec2,65535,0,!1),_t.DrawLabel(this._tempVec3,"A:B "+this._initialDistance.toFixed(2)+`
|
|
6214
6214
|
`+l(this._tempVec1)+`
|
|
6215
|
-
`+l(this._tempVec2),.03,5)}}onDragStart(e){this.gameObject.add(this._followObject),this._followObject.matrixAutoUpdate=!1,this._followObject.matrix.identity(),this._deviceMode=e.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(e){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 e=this.context.mainCamera;this.tempLookMatrix.lookAt(this._tempVec3,this._tempVec2,e.worldUp),this._manipulatorObject.quaternion.setFromRotationMatrix(this.tempLookMatrix);const t=this._tempVec1.distanceTo(this._tempVec2);this._manipulatorObject.scale.copy(this._initialScale).multiplyScalar(t/this._initialDistance),this._manipulatorObject.updateMatrix(),this._manipulatorObject.updateMatrixWorld(!0),pc&&(_t.DrawLabel(this._tempVec3.clone().add(new w(0,.2,0)),"A:B "+t.toFixed(2),.03),_t.DrawLine(this._tempVec1,this._tempVec2,65280,0,!1))}onDragUpdate(){this.alignManipulator();const e=30,t=1;this._followObject.position.copy(this._manipulatorPosOffset),this._followObject.quaternion.copy(this._manipulatorRotOffset),this._followObject.scale.copy(this._manipulatorScaleOffset);const i=this.gameObject,n=this._followObject;n.updateMatrix(),n.updateMatrixWorld(!0);const o=this._deviceMode==="tracked-pointer"||this._deviceMode==="transient-pointer"?this.settings.xrKeepRotation:this.settings.keepRotation;if(this.settings.snapGridResolution>0){const u=this._followObject.worldPosition,f=this.settings.snapGridResolution;u.x=Math.round(u.x/f)*f,u.y=Math.round(u.y/f)*f,u.z=Math.round(u.z/f)*f,this._followObject.worldPosition=u,this._followObject.updateMatrix()}o&&(this._followObject.worldQuaternion=this._followObjectStartWorldQuaternion,this._followObject.updateMatrix());const a=it.clamp01(this.context.time.deltaTime*e*t),l=i.worldPosition;l.lerp(n.worldPosition,a),i.worldPosition=l;const c=i.worldQuaternion;c.slerp(n.worldQuaternion,a),i.worldQuaternion=c;const h=i.worldScale;h.lerp(n.worldScale,a),i.worldScale=h}setTargetObject(e){this.gameObject=e}}class Iye{constructor(e,t){d(this,"context");d(this,"gameObject");d(this,"settings");d(this,"_lastRig");d(this,"_followObject");d(this,"_totalMovement",new w);d(this,"_totalMovementAlongRayDirection",0);d(this,"_grabStartDistance",0);d(this,"_deviceMode");d(this,"_followObjectStartPosition",new w);d(this,"_followObjectStartQuaternion",new Ce);d(this,"_followObjectStartWorldQuaternion",new Ce);d(this,"_lastDragPosRigSpace");d(this,"_tempVec",new w);d(this,"_tempMat",new ye);d(this,"_hitPointInLocalSpace",new w);d(this,"_hitNormalInLocalSpace",new w);d(this,"_bottomCenter",new w);d(this,"_backCenter",new w);d(this,"_backBottomCenter",new w);d(this,"_bounds",new Ei);d(this,"_dragPlane",new Tr(new w(0,1,0)));d(this,"_draggedOverObject",null);d(this,"_draggedOverObjectLastSetUp",null);d(this,"_draggedOverObjectLastNormal",new w);d(this,"_draggedOverObjectDuration",0);this.settings=e,this.context=e.context,this.gameObject=t,this._followObject=new ve}getTotalMovement(){return this._totalMovement}get followObject(){return this._followObject}get hitPointInLocalSpace(){return this._hitPointInLocalSpace}setTargetObject(e){this.gameObject=e}recenter(){var r,o;if(!this._followObject.parent){console.warn("Error: space follow object doesn't have parent but recenter() is called. This is likely a bug");return}const e=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),e.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 t=this._hitPointInLocalSpace.clone();this.gameObject.localToWorld(t),this._grabStartDistance=t.distanceTo(e.worldPosition);const i=(o=(r=xt.active)==null?void 0:r.rig)==null?void 0:o.gameObject,n=(i==null?void 0:i.worldScale.x)||1;this._grabStartDistance/=n,this._totalMovementAlongRayDirection=0,this._lastDragPosRigSpace=void 0,pc&&(_t.DrawLine(t,e.worldPosition,65280,.5,!1),_t.DrawLabel(e.worldPosition.add(new w(0,.1,0)),this._grabStartDistance.toFixed(2),.03,.5))}onDragStart(e){if(e.event.space.add(this._followObject),this._lastDragPosRigSpace=void 0,e.point&&e.normal)this._hitPointInLocalSpace.copy(e.point),this.gameObject.worldToLocal(this._hitPointInLocalSpace),this._hitNormalInLocalSpace.copy(e.normal);else if(e){const y=e.event.space,g=y.worldPosition;this.gameObject.worldToLocal(g),this._hitPointInLocalSpace.copy(g);const v=y.worldUp;this._tempMat.copy(this.gameObject.matrixWorld).invert(),v.transformDirection(this._tempMat),this._hitNormalInLocalSpace.copy(v)}this.recenter(),this._totalMovement.set(0,0,0),this._deviceMode=e.mode;const i=this._followObject.parent.worldForward,r=this._deviceMode==="tracked-pointer"||this._deviceMode==="transient-pointer"?this.settings.xrDragMode:this.settings.dragMode,o=this._hitPointInLocalSpace.clone();switch(this.gameObject.localToWorld(o),r){case 0:const y=new w(0,1,0);this.gameObject.parent&&y.transformDirection(this.gameObject.parent.matrixWorld.clone().invert()),this._dragPlane.setFromNormalAndCoplanarPoint(y,o);break;case 2:const g=this._hitNormalInLocalSpace.clone();g.transformDirection(this.gameObject.matrixWorld),this._dragPlane.setFromNormalAndCoplanarPoint(g,o);break;case 1:this._dragPlane.setFromNormalAndCoplanarPoint(i,o);break;case 3:const v=new w(0,1,0),_=i,A=v.angleTo(_),b=.5;A>Math.PI/2+b||A<Math.PI/2-b?this._dragPlane.setFromNormalAndCoplanarPoint(new w(0,1,0),o):this._dragPlane.setFromNormalAndCoplanarPoint(i,o);break}const a=this.gameObject.parent,l=this.gameObject.position.clone(),c=this.gameObject.quaternion.clone(),h=this.gameObject.scale.clone(),u=this.gameObject.matrixWorld.clone();a&&a.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 f=Sc([this.gameObject]);f.expandByPoint(this.gameObject.worldPosition);const p=new w;f.getCenter(p);const m=new w;f.getSize(m),this._bottomCenter.copy(p.clone().add(new w(0,-m.y/2,0))),this._backCenter.copy(p.clone().add(new w(0,0,m.z/2))),this._backBottomCenter.copy(p.clone().add(new w(0,-m.y/2,m.z/2))),this._bounds.copy(f),a&&a.add(this.gameObject),this.gameObject.position.copy(l),this.gameObject.quaternion.copy(c),this.gameObject.scale.copy(h),this.gameObject.matrixWorld.copy(u),this._draggedOverObject=null,this._draggedOverObjectLastSetUp=null,this._draggedOverObjectLastNormal.set(0,1,0),this._draggedOverObjectDuration=0}collectMovementInfo(){var r,o;if(!this._followObject.parent)return;const e=this._followObject.parent;this._followObject.updateMatrix();const t=e.worldPosition,i=(o=(r=xt.active)==null?void 0:r.rig)==null?void 0:o.gameObject;i&&i.worldToLocal(t),(this._lastDragPosRigSpace===void 0||i!=this._lastRig)&&(this._lastDragPosRigSpace=t.clone(),this._lastRig=i),this._tempVec.copy(t).sub(this._lastDragPosRigSpace);const n=e.worldForward;if(i&&(this._tempMat.copy(i.matrixWorld).invert(),n.transformDirection(this._tempMat)),this._totalMovementAlongRayDirection+=n.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(t),pc){let a=t;i&&(a=a.clone(),a.transformDirection(i.matrixWorld)),_t.DrawRay(a,n,255)}}onDragUpdate(e){if(e>1)return;const t=this.gameObject,i=this._followObject.parent;this._followObject.updateMatrix();const n=i.worldPosition,r=i.worldForward,o=this._deviceMode==="tracked-pointer"||this._deviceMode==="transient-pointer",a=o?this.settings.xrKeepRotation:this.settings.keepRotation,l=o?this.settings.xrDragMode:this.settings.dragMode;if(l===5)return;const c=10;a&&(this._followObject.worldQuaternion=this._followObjectStartWorldQuaternion),this._followObject.updateMatrix(),this._followObject.updateMatrixWorld(!0);let h=1,u=2;if(o&&this._grabStartDistance>.5){const g=1+this._totalMovementAlongRayDirection*(2*this.settings.xrDistanceDragFactor);h=Math.max(0,g),h=h*h*h}else this._grabStartDistance<=.5&&(u=3);this._followObject.position.copy(this._followObjectStartPosition),a||this._followObject.quaternion.copy(this._followObjectStartQuaternion),this._followObject.position.multiplyScalar(h),this._followObject.updateMatrix();const f=new Mo(n,r);if(l==4){const g=new Il;g.testObject=_=>_!==this.followObject&&_!==i&&_!==t;const v=this.context.physics.raycastFromRay(f,g);if(v.length>0){const _=v[0];if(this._draggedOverObject===_.object?this._draggedOverObjectDuration+=this.context.time.deltaTime:(this._draggedOverObject=_.object,this._draggedOverObjectDuration=0),_.face){const b=this._draggedOverObjectDuration>=.15,S=.001,E=this._totalMovement.length()>=S;if((b||E)&&(this._draggedOverObjectLastSetUp!==this._draggedOverObject||this._draggedOverObjectLastNormal.dot(_.face.normal)<.999999||this.context.time.frame%60===0)){this._draggedOverObjectLastSetUp=this._draggedOverObject,this._draggedOverObjectLastNormal.copy(_.face.normal);const M=pi(),T=pi();this._bounds.getCenter(M),this._bounds.getSize(T),M.sub(T.multiplyScalar(.5).multiply(_.face.normal)),this._hitPointInLocalSpace.copy(M),this._hitNormalInLocalSpace.copy(_.face.normal),this._bounds.getCenter(M),this._bounds.getSize(T),M.add(T.multiplyScalar(.5).multiply(_.face.normal));const R=pi(this._hitPointInLocalSpace).add(M);this._followObject.localToWorld(R);const C=_.point;this._dragPlane.setFromNormalAndCoplanarPoint(_.face.normal,C)}else if(!(b||E))return}}}if(l!==1&&f.intersectPlane(this._dragPlane,this._tempVec)){this._followObject.worldPosition=this._tempVec,this._followObject.updateMatrix(),this._followObject.updateMatrixWorld(!0);const g=this._hitPointInLocalSpace.clone();this._followObject.localToWorld(g),pc&&_t.DrawLine(g,this._tempVec,65535,0,!1),this._followObject.worldPosition=this._tempVec.multiplyScalar(2).sub(g),this._followObject.updateMatrix(),this._followObject.updateMatrix()}if(this.settings.snapGridResolution>0){const g=this._followObject.worldPosition,v=this.settings.snapGridResolution;g.x=Math.round(g.x/v)*v,g.y=Math.round(g.y/v)*v,g.z=Math.round(g.z/v)*v,this._followObject.worldPosition=g,this._followObject.updateMatrix()}a&&(this._followObject.worldQuaternion=this._followObjectStartWorldQuaternion,this._followObject.updateMatrix());const p=it.clamp01(this.context.time.deltaTime*c*u),m=t.worldPosition;m.lerp(this._followObject.worldPosition,p),t.worldPosition=m;const y=t.worldQuaternion;if(y.slerp(this._followObject.worldQuaternion,p),t.worldQuaternion=y,pc){const g=this._hitPointInLocalSpace.clone();t.localToWorld(g),_t.DrawSphere(g,.02,16711680);const v=this._hitNormalInLocalSpace.clone();v.applyQuaternion(y),_t.DrawRay(g,v,16711680),_t.DrawLabel(m.add(new w(0,.25,0)),`Distance: ${this._totalMovement.length().toFixed(2)}
|
|
6215
|
+
`+l(this._tempVec2),.03,5)}}onDragStart(e){this.gameObject.add(this._followObject),this._followObject.matrixAutoUpdate=!1,this._followObject.matrix.identity(),this._deviceMode=e.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(e){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 e=this.context.mainCamera;this.tempLookMatrix.lookAt(this._tempVec3,this._tempVec2,e.worldUp),this._manipulatorObject.quaternion.setFromRotationMatrix(this.tempLookMatrix);const t=this._tempVec1.distanceTo(this._tempVec2);this._manipulatorObject.scale.copy(this._initialScale).multiplyScalar(t/this._initialDistance),this._manipulatorObject.updateMatrix(),this._manipulatorObject.updateMatrixWorld(!0),pc&&(_t.DrawLabel(this._tempVec3.clone().add(new w(0,.2,0)),"A:B "+t.toFixed(2),.03),_t.DrawLine(this._tempVec1,this._tempVec2,65280,0,!1))}onDragUpdate(){this.alignManipulator();const e=30,t=1;this._followObject.position.copy(this._manipulatorPosOffset),this._followObject.quaternion.copy(this._manipulatorRotOffset),this._followObject.scale.copy(this._manipulatorScaleOffset);const i=this.gameObject,n=this._followObject;n.updateMatrix(),n.updateMatrixWorld(!0);const o=this._deviceMode==="tracked-pointer"||this._deviceMode==="transient-pointer"?this.settings.xrKeepRotation:this.settings.keepRotation;if(this.settings.snapGridResolution>0){const u=this._followObject.worldPosition,f=this.settings.snapGridResolution;u.x=Math.round(u.x/f)*f,u.y=Math.round(u.y/f)*f,u.z=Math.round(u.z/f)*f,this._followObject.worldPosition=u,this._followObject.updateMatrix()}o&&(this._followObject.worldQuaternion=this._followObjectStartWorldQuaternion,this._followObject.updateMatrix());const a=it.clamp01(this.context.time.deltaTime*e*t),l=i.worldPosition;l.lerp(n.worldPosition,a),i.worldPosition=l;const c=i.worldQuaternion;c.slerp(n.worldQuaternion,a),i.worldQuaternion=c;const h=i.worldScale;h.lerp(n.worldScale,a),i.worldScale=h}setTargetObject(e){this.gameObject=e}}class Iye{constructor(e,t){d(this,"context");d(this,"gameObject");d(this,"settings");d(this,"_lastRig");d(this,"_followObject");d(this,"_totalMovement",new w);d(this,"_totalMovementAlongRayDirection",0);d(this,"_grabStartDistance",0);d(this,"_deviceMode");d(this,"_followObjectStartPosition",new w);d(this,"_followObjectStartQuaternion",new Ce);d(this,"_followObjectStartWorldQuaternion",new Ce);d(this,"_lastDragPosRigSpace");d(this,"_tempVec",new w);d(this,"_tempMat",new ye);d(this,"_hitPointInLocalSpace",new w);d(this,"_hitNormalInLocalSpace",new w);d(this,"_bottomCenter",new w);d(this,"_backCenter",new w);d(this,"_backBottomCenter",new w);d(this,"_bounds",new Ei);d(this,"_dragPlane",new Tr(new w(0,1,0)));d(this,"_draggedOverObject",null);d(this,"_draggedOverObjectLastSetUp",null);d(this,"_draggedOverObjectLastNormal",new w);d(this,"_draggedOverObjectDuration",0);this.settings=e,this.context=e.context,this.gameObject=t,this._followObject=new ve}getTotalMovement(){return this._totalMovement}get followObject(){return this._followObject}get hitPointInLocalSpace(){return this._hitPointInLocalSpace}setTargetObject(e){this.gameObject=e}recenter(){var r,o;if(!this._followObject.parent){console.warn("Error: space follow object doesn't have parent but recenter() is called. This is likely a bug");return}const e=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),e.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 t=this._hitPointInLocalSpace.clone();this.gameObject.localToWorld(t),this._grabStartDistance=t.distanceTo(e.worldPosition);const i=(o=(r=xt.active)==null?void 0:r.rig)==null?void 0:o.gameObject,n=(i==null?void 0:i.worldScale.x)||1;this._grabStartDistance/=n,this._totalMovementAlongRayDirection=0,this._lastDragPosRigSpace=void 0,pc&&(_t.DrawLine(t,e.worldPosition,65280,.5,!1),_t.DrawLabel(e.worldPosition.add(new w(0,.1,0)),this._grabStartDistance.toFixed(2),.03,.5))}onDragStart(e){if(e.event.space.add(this._followObject),this._lastDragPosRigSpace=void 0,e.point&&e.normal)this._hitPointInLocalSpace.copy(e.point),this.gameObject.worldToLocal(this._hitPointInLocalSpace),this._hitNormalInLocalSpace.copy(e.normal);else if(e){const y=e.event.space,g=y.worldPosition;this.gameObject.worldToLocal(g),this._hitPointInLocalSpace.copy(g);const v=y.worldUp;this._tempMat.copy(this.gameObject.matrixWorld).invert(),v.transformDirection(this._tempMat),this._hitNormalInLocalSpace.copy(v)}this.recenter(),this._totalMovement.set(0,0,0),this._deviceMode=e.mode;const i=this._followObject.parent.worldForward,r=this._deviceMode==="tracked-pointer"||this._deviceMode==="transient-pointer"?this.settings.xrDragMode:this.settings.dragMode,o=this._hitPointInLocalSpace.clone();switch(this.gameObject.localToWorld(o),r){case 0:const y=new w(0,1,0);this.gameObject.parent&&y.transformDirection(this.gameObject.parent.matrixWorld.clone().invert()),this._dragPlane.setFromNormalAndCoplanarPoint(y,o);break;case 2:const g=this._hitNormalInLocalSpace.clone();g.transformDirection(this.gameObject.matrixWorld),this._dragPlane.setFromNormalAndCoplanarPoint(g,o);break;case 1:this._dragPlane.setFromNormalAndCoplanarPoint(i,o);break;case 4:case 3:const v=new w(0,1,0),_=i,A=v.angleTo(_),b=.5;A>Math.PI/2+b||A<Math.PI/2-b?this._dragPlane.setFromNormalAndCoplanarPoint(new w(0,1,0),o):this._dragPlane.setFromNormalAndCoplanarPoint(i,o);break}const a=this.gameObject.parent,l=this.gameObject.position.clone(),c=this.gameObject.quaternion.clone(),h=this.gameObject.scale.clone(),u=this.gameObject.matrixWorld.clone();a&&a.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 f=Sc([this.gameObject]);f.expandByPoint(this.gameObject.worldPosition);const p=new w;f.getCenter(p);const m=new w;f.getSize(m),this._bottomCenter.copy(p.clone().add(new w(0,-m.y/2,0))),this._backCenter.copy(p.clone().add(new w(0,0,m.z/2))),this._backBottomCenter.copy(p.clone().add(new w(0,-m.y/2,m.z/2))),this._bounds.copy(f),a&&a.add(this.gameObject),this.gameObject.position.copy(l),this.gameObject.quaternion.copy(c),this.gameObject.scale.copy(h),this.gameObject.matrixWorld.copy(u),this._draggedOverObject=null,this._draggedOverObjectLastSetUp=null,this._draggedOverObjectLastNormal.set(0,1,0),this._draggedOverObjectDuration=0}collectMovementInfo(){var r,o;if(!this._followObject.parent)return;const e=this._followObject.parent;this._followObject.updateMatrix();const t=e.worldPosition,i=(o=(r=xt.active)==null?void 0:r.rig)==null?void 0:o.gameObject;i&&i.worldToLocal(t),(this._lastDragPosRigSpace===void 0||i!=this._lastRig)&&(this._lastDragPosRigSpace=t.clone(),this._lastRig=i),this._tempVec.copy(t).sub(this._lastDragPosRigSpace);const n=e.worldForward;if(i&&(this._tempMat.copy(i.matrixWorld).invert(),n.transformDirection(this._tempMat)),this._totalMovementAlongRayDirection+=n.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(t),pc){let a=t;i&&(a=a.clone(),a.transformDirection(i.matrixWorld)),_t.DrawRay(a,n,255)}}onDragUpdate(e){if(e>1)return;const t=this.gameObject,i=this._followObject.parent;this._followObject.updateMatrix();const n=i.worldPosition,r=i.worldForward,o=this._deviceMode==="tracked-pointer"||this._deviceMode==="transient-pointer",a=o?this.settings.xrKeepRotation:this.settings.keepRotation,l=o?this.settings.xrDragMode:this.settings.dragMode;if(l===5)return;const c=10;a&&(this._followObject.worldQuaternion=this._followObjectStartWorldQuaternion),this._followObject.updateMatrix(),this._followObject.updateMatrixWorld(!0);let h=1,u=2;if(o&&this._grabStartDistance>.5){const g=1+this._totalMovementAlongRayDirection*(2*this.settings.xrDistanceDragFactor);h=Math.max(0,g),h=h*h*h}else this._grabStartDistance<=.5&&(u=3);this._followObject.position.copy(this._followObjectStartPosition),a||this._followObject.quaternion.copy(this._followObjectStartQuaternion),this._followObject.position.multiplyScalar(h),this._followObject.updateMatrix();const f=new Mo(n,r);if(l==4){const g=new Il;g.testObject=_=>_!==this.followObject&&_!==i&&_!==t;const v=this.context.physics.raycastFromRay(f,g);if(v.length>0){const _=v[0];if(this._draggedOverObject===_.object?this._draggedOverObjectDuration+=this.context.time.deltaTime:(this._draggedOverObject=_.object,this._draggedOverObjectDuration=0),_.face){const b=this._draggedOverObjectDuration>=.15,S=.001,E=this._totalMovement.length()>=S;if((b||E)&&(this._draggedOverObjectLastSetUp!==this._draggedOverObject||this._draggedOverObjectLastNormal.dot(_.face.normal)<.999999||this.context.time.frame%60===0)){this._draggedOverObjectLastSetUp=this._draggedOverObject,this._draggedOverObjectLastNormal.copy(_.face.normal);const M=pi(),T=pi();this._bounds.getCenter(M),this._bounds.getSize(T),M.sub(T.multiplyScalar(.5).multiply(_.face.normal)),this._hitPointInLocalSpace.copy(M),this._hitNormalInLocalSpace.copy(_.face.normal),this._bounds.getCenter(M),this._bounds.getSize(T),M.add(T.multiplyScalar(.5).multiply(_.face.normal));const R=pi(this._hitPointInLocalSpace).add(M);this._followObject.localToWorld(R);const C=_.point;this._dragPlane.setFromNormalAndCoplanarPoint(_.face.normal,C)}else if(!(b||E))return}}}if(l!==1&&f.intersectPlane(this._dragPlane,this._tempVec)){this._followObject.worldPosition=this._tempVec,this._followObject.updateMatrix(),this._followObject.updateMatrixWorld(!0);const g=this._hitPointInLocalSpace.clone();this._followObject.localToWorld(g),pc&&_t.DrawLine(g,this._tempVec,65535,0,!1),this._followObject.worldPosition=this._tempVec.multiplyScalar(2).sub(g),this._followObject.updateMatrix(),this._followObject.updateMatrix()}if(this.settings.snapGridResolution>0){const g=this._followObject.worldPosition,v=this.settings.snapGridResolution;g.x=Math.round(g.x/v)*v,g.y=Math.round(g.y/v)*v,g.z=Math.round(g.z/v)*v,this._followObject.worldPosition=g,this._followObject.updateMatrix()}a&&(this._followObject.worldQuaternion=this._followObjectStartWorldQuaternion,this._followObject.updateMatrix());const p=it.clamp01(this.context.time.deltaTime*c*u),m=t.worldPosition;m.lerp(this._followObject.worldPosition,p),t.worldPosition=m;const y=t.worldQuaternion;if(y.slerp(this._followObject.worldQuaternion,p),t.worldQuaternion=y,pc){const g=this._hitPointInLocalSpace.clone();t.localToWorld(g),_t.DrawSphere(g,.02,16711680);const v=this._hitNormalInLocalSpace.clone();v.applyQuaternion(y),_t.DrawRay(g,v,16711680),_t.DrawLabel(m.add(new w(0,.25,0)),`Distance: ${this._totalMovement.length().toFixed(2)}
|
|
6216
6216
|
|
|
6217
6217
|
Along Ray: ${this._totalMovementAlongRayDirection.toFixed(2)}
|
|
6218
6218
|
|