@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 n=aa()||ew()&&st();if((
|
|
|
4344
4344
|
#__vconsole .vc-mask {
|
|
4345
4345
|
overflow: hidden;
|
|
4346
4346
|
}
|
|
4347
|
-
`,da?.prepend(r),n===!0&&OI()<=0&&pz(),console.log("\u{1F335} Debug console has loaded")}},e.src="https://unpkg.com/vconsole@latest/dist/vconsole.min.js",document.body.appendChild(e)}function one(){const n=new VConsole.VConsolePlugin("needle-console","\u{1F335} Inspect glTF"),e=()=>document.querySelector("#__vc_plug_"+n._id+" iframe");return n.on("renderTab",function(t){const r=globalThis["needle:codegen_files"];if(!r||r.length===0)return;let s=globalThis["needle:codegen_files"][0];const o=s.indexOf("?");o>-1&&(s=s.substring(0,o));const a=location.protocol+"//"+location.host+location.pathname+"/"+s,l=encodeURIComponent(a);n.fullUrl="https://viewer.needle.tools?inspect&file="+l;var c='<iframe src="" style="width: 100%; height: 99%; border: none;"></iframe>';t(c)}),n.on("show",function(){const t=e();t&&t.src!==n.fullUrl&&(t.src=n.fullUrl)}),n.on("hide",function(){const t=e();t&&(t.src="")}),n.on("addTopBar",function(t){var r=new Array;r.push({name:"Open in new window \u2197",onClick:function(s){window.open(n.fullUrl,"_blank"),ua?.hide()}}),r.push({name:"Reload",onClick:function(s){const o=e();o&&(o.src=n.fullUrl)}}),r.push({name:"Fullscreen",onClick:function(s){const o=e();o.requestFullscreen?o.requestFullscreen():o.webkitRequestFullscreen instanceof Function&&o.webkitRequestFullscreen()}}),t(r)}),n}function ane(){return document.querySelector("#__vconsole .vc-switch")||null}function lne(){return document.querySelector("#__vconsole")||null}const vz=te("debugdefines");zf('if(!globalThis[""3.45.2-beta.
|
|
4347
|
+
`,da?.prepend(r),n===!0&&OI()<=0&&pz(),console.log("\u{1F335} Debug console has loaded")}},e.src="https://unpkg.com/vconsole@latest/dist/vconsole.min.js",document.body.appendChild(e)}function one(){const n=new VConsole.VConsolePlugin("needle-console","\u{1F335} Inspect glTF"),e=()=>document.querySelector("#__vc_plug_"+n._id+" iframe");return n.on("renderTab",function(t){const r=globalThis["needle:codegen_files"];if(!r||r.length===0)return;let s=globalThis["needle:codegen_files"][0];const o=s.indexOf("?");o>-1&&(s=s.substring(0,o));const a=location.protocol+"//"+location.host+location.pathname+"/"+s,l=encodeURIComponent(a);n.fullUrl="https://viewer.needle.tools?inspect&file="+l;var c='<iframe src="" style="width: 100%; height: 99%; border: none;"></iframe>';t(c)}),n.on("show",function(){const t=e();t&&t.src!==n.fullUrl&&(t.src=n.fullUrl)}),n.on("hide",function(){const t=e();t&&(t.src="")}),n.on("addTopBar",function(t){var r=new Array;r.push({name:"Open in new window \u2197",onClick:function(s){window.open(n.fullUrl,"_blank"),ua?.hide()}}),r.push({name:"Reload",onClick:function(s){const o=e();o&&(o.src=n.fullUrl)}}),r.push({name:"Fullscreen",onClick:function(s){const o=e();o.requestFullscreen?o.requestFullscreen():o.webkitRequestFullscreen instanceof Function&&o.webkitRequestFullscreen()}}),t(r)}),n}function ane(){return document.querySelector("#__vconsole .vc-switch")||null}function lne(){return document.querySelector("#__vconsole")||null}const vz=te("debugdefines");zf('if(!globalThis[""3.45.2-beta.4""]) globalThis[""3.45.2-beta.4""] = "0.0.0";'),zf('if(!globalThis[""undefined""]) globalThis[""undefined""] = "unknown";'),zf('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";'),zf('globalThis["__NEEDLE_ENGINE_VERSION__"] = "3.45.2-beta.4";'),zf('globalThis["__NEEDLE_ENGINE_GENERATOR__"] = "undefined";'),zf('globalThis["__NEEDLE_PROJECT_BUILD_TIME__"] = "Fri Jul 19 2024 19:15:17 GMT+0200 (Central European Summer Time)";');const el="3.45.2-beta.4",bw="undefined",DR="Fri Jul 19 2024 19:15:17 GMT+0200 (Central European Summer Time)";vz&&console.log(`Engine version: ${el} (generator: ${bw})
|
|
4348
4348
|
Project built at ${DR}`);const $c="needle_isActiveInHierarchy",wp="builtin_components",Kv="needle_editor_guid";function zf(n){try{(0,eval)(n)}catch(e){vz&&console.error(e)}}const cne='<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 160 187.74"><defs><linearGradient id="a" x1="89.64" y1="184.81" x2="90.48" y2="21.85" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#62d399"/><stop offset=".51" stop-color="#acd842"/><stop offset=".9" stop-color="#d7db0a"/></linearGradient><linearGradient id="b" x1="69.68" y1="178.9" x2="68.08" y2="16.77" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#0ba398"/><stop offset=".5" stop-color="#4ca352"/><stop offset="1" stop-color="#76a30a"/></linearGradient><linearGradient id="c" x1="36.6" y1="152.17" x2="34.7" y2="84.19" gradientUnits="userSpaceOnUse"><stop offset=".19" stop-color="#36a382"/><stop offset=".54" stop-color="#49a459"/><stop offset="1" stop-color="#76a30b"/></linearGradient><linearGradient id="d" x1="15.82" y1="153.24" x2="18" y2="90.86" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#267880"/><stop offset=".51" stop-color="#457a5c"/><stop offset="1" stop-color="#717516"/></linearGradient><linearGradient id="e" x1="135.08" y1="135.43" x2="148.93" y2="63.47" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#b0d939"/><stop offset="1" stop-color="#eadb04"/></linearGradient><linearGradient id="f" x1="-4163.25" y1="2285.12" x2="-4160.81" y2="2215.34" gradientTransform="rotate(20 4088.49 13316.712)" gradientUnits="userSpaceOnUse"><stop offset=".17" stop-color="#74af52"/><stop offset=".48" stop-color="#99be32"/><stop offset="1" stop-color="#c0c40a"/></linearGradient><symbol id="g" viewBox="0 0 160 187.74"><path style="fill:url(#a)" d="M79.32 36.98v150.76L95 174.54l6.59-156.31-22.27 18.75z"/><path style="fill:url(#b)" d="M79.32 36.98 57.05 18.23l6.59 156.31 15.68 13.2V36.98z"/><path style="fill:url(#c)" d="m25.19 104.83 8.63 49.04 12.5-14.95-2.46-56.42-18.67 22.33z"/><path style="fill:url(#d)" d="M25.19 104.83 0 90.24l16.97 53.86 16.85 9.77-8.63-49.04z"/><path style="fill:#9c3" d="M43.86 82.5 18.69 67.98 0 90.24l25.18 14.59L43.86 82.5z"/><path style="fill:url(#e)" d="m134.82 78.69-9.97 56.5 15.58-9.04L160 64.1l-25.18 14.59z"/><path style="fill:url(#f)" d="m134.82 78.69-18.68-22.33-2.86 65 11.57 13.83 9.97-56.5z"/><path style="fill:#ffe113" d="m160 64.1-18.69-22.26-25.17 14.52 18.67 22.33L160 64.1z"/><path style="fill:#f3e600" d="M101.59 18.23 79.32 0 57.05 18.23l22.27 18.75 22.27-18.75z"/></symbol></defs><use width="160" height="187.74" xlink:href="#g"/></svg>',hne=btoa(cne),une="data:image/svg+xml;base64,"+hne,dne=une,pne=`<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN' 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'> <svg clip-rule="evenodd" fill-rule="evenodd" stroke-linejoin="round" stroke-miterlimit="2" version="1.1" viewBox="0 0 1014 282" xml:space="preserve" xmlns="http://www.w3.org/2000/svg"> <g transform="matrix(1.008 0 0 1.008 -2.239 .61874)"> <path d="m665.95 132.73v44.88l-10.56-8.4c-0.8-0.64-1.2-1.44-1.2-2.4v-32.4c0-6.48-4.12-9.72-12.36-9.72-2.16 0-4.18 0.4-6.06 1.2s-3.54 1.8-4.98 3-2.56 2.5-3.36 3.9-1.2 2.7-1.2 3.9v40.92l-10.68-8.4c-0.72-0.64-1.08-1.44-1.08-2.4v-53.76l10.92 8.52c0.32 0.24 0.56 0.44 0.72 0.6s0.36 0.32 0.6 0.48c0.96-1.2 2.14-2.28 3.54-3.24s2.92-1.76 4.56-2.4 3.34-1.14 5.1-1.5 3.44-0.54 5.04-0.54c1.44 0 2.92 0.04 4.44 0.12s2.84 0.28 3.96 0.6c4.56 1.12 7.8 3.12 9.72 6s2.88 6.56 2.88 11.04z" fill-rule="nonzero"/> </g> <g transform="matrix(1.008 0 0 1.008 -2.239 .61874)"> <path d="m732.38 146.05c0 0.88 0.02 1.5 0.06 1.86s-0.02 0.98-0.18 1.86h-7.08c-2.08 0-4.44-0.02-7.08-0.06s-5.36-0.06-8.16-0.06h-22.08c0 2.88 0.56 5.36 1.68 7.44s2.6 3.8 4.44 5.16 3.94 2.36 6.3 3 4.74 0.96 7.14 0.96c3.04 0 5.9-0.76 8.58-2.28s4.94-3.52 6.78-6c0.64 0.56 1.54 1.48 2.7 2.76s2.94 3.2 5.34 5.76c-2.8 3.36-6.22 6.02-10.26 7.98s-8.42 2.94-13.14 2.94-8.92-0.64-12.84-1.92-7.32-3.24-10.2-5.88-5.12-5.98-6.72-10.02-2.4-8.82-2.4-14.34c0-4.96 0.66-9.42 1.98-13.38s3.22-7.32 5.7-10.08 5.44-4.9 8.88-6.42 7.32-2.28 11.64-2.28c5.76 0 10.52 0.88 14.28 2.64s6.72 4.16 8.88 7.2 3.66 6.54 4.5 10.5 1.26 8.18 1.26 12.66zm-29.4-22.8c-2.16 0.16-4.16 0.72-6 1.68s-3.42 2.2-4.74 3.72-2.36 3.28-3.12 5.28-1.14 4.12-1.14 6.36h33.12c0-2-0.22-4.06-0.66-6.18s-1.3-4.02-2.58-5.7-3.1-3.02-5.46-4.02-5.5-1.38-9.42-1.14z" fill-rule="nonzero"/> </g> <g transform="matrix(1.008 0 0 1.008 -2.239 .61874)"> <path d="m795.93 146.05c0 0.88 0.02 1.5 0.06 1.86s-0.02 0.98-0.18 1.86h-7.08c-2.08 0-4.44-0.02-7.08-0.06s-5.36-0.06-8.16-0.06h-22.08c0 2.88 0.56 5.36 1.68 7.44s2.6 3.8 4.44 5.16 3.94 2.36 6.3 3 4.74 0.96 7.14 0.96c3.04 0 5.9-0.76 8.58-2.28s4.94-3.52 6.78-6c0.64 0.56 1.54 1.48 2.7 2.76s2.94 3.2 5.34 5.76c-2.8 3.36-6.22 6.02-10.26 7.98s-8.42 2.94-13.14 2.94-8.92-0.64-12.84-1.92-7.32-3.24-10.2-5.88-5.12-5.98-6.72-10.02-2.4-8.82-2.4-14.34c0-4.96 0.66-9.42 1.98-13.38s3.22-7.32 5.7-10.08 5.44-4.9 8.88-6.42 7.32-2.28 11.64-2.28c5.76 0 10.52 0.88 14.28 2.64s6.72 4.16 8.88 7.2 3.66 6.54 4.5 10.5 1.26 8.18 1.26 12.66zm-29.4-22.8c-2.16 0.16-4.16 0.72-6 1.68s-3.42 2.2-4.74 3.72-2.36 3.28-3.12 5.28-1.14 4.12-1.14 6.36h33.12c0-2-0.22-4.06-0.66-6.18s-1.3-4.02-2.58-5.7-3.1-3.02-5.46-4.02-5.5-1.38-9.42-1.14z" fill-rule="nonzero"/> </g> <g transform="matrix(1.008 0 0 1.008 -2.239 .61874)"> <path d="m858.57 97.21c0.64 0.48 0.96 1.16 0.96 2.04v74.88c-0.08 1.04-0.12 2.12-0.12 3.24-1.84-1.52-3.56-2.92-5.16-4.2-1.36-1.12-2.66-2.18-3.9-3.18s-2.06-1.66-2.46-1.98c-1.76 2.48-4.26 4.44-7.5 5.88s-7.02 2.16-11.34 2.16c-3.84 0-7.4-0.7-10.68-2.1s-6.14-3.44-8.58-6.12-4.34-5.94-5.7-9.78-2.04-8.16-2.04-12.96c0-4.32 0.78-8.34 2.34-12.06s3.6-6.92 6.12-9.6 5.38-4.78 8.58-6.3 6.48-2.28 9.84-2.28c2.56 0 4.82 0.22 6.78 0.66s3.68 1.06 5.16 1.86 2.78 1.74 3.9 2.82 2.16 2.22 3.12 3.42v-35.04l10.68 8.64zm-27.96 67.92c3.6 0 6.52-0.68 8.76-2.04s3.98-3.06 5.22-5.1 2.1-4.22 2.58-6.54 0.72-4.44 0.72-6.36v-1.2c0-1.12-0.22-2.7-0.66-4.74s-1.28-4.06-2.52-6.06-3-3.7-5.28-5.1-5.22-2.02-8.82-1.86c-3.44 0-6.26 0.74-8.46 2.22s-3.96 3.26-5.28 5.34-2.24 4.2-2.76 6.36-0.78 3.92-0.78 5.28c0 1.84 0.24 3.92 0.72 6.24s1.36 4.48 2.64 6.48 3.04 3.68 5.28 5.04 5.12 2.04 8.64 2.04z" fill-rule="nonzero"/> </g> <g transform="matrix(1.008 0 0 1.008 -2.239 .61874)"> <path d="m882.81 97.09c0.64 0.48 0.96 1.12 0.96 1.92l-0.12 41.04v37.08l-10.56-8.4c-0.72-0.64-1.08-1.44-1.08-2.4v-77.88l10.8 8.64z" fill-rule="nonzero"/> </g> <g transform="matrix(1.008 0 0 1.008 -2.239 .61874)"> <path d="m950.36 146.05c0 0.88 0.02 1.5 0.06 1.86s-0.02 0.98-0.18 1.86h-7.08c-2.08 0-4.44-0.02-7.08-0.06s-5.36-0.06-8.16-0.06h-22.08c0 2.88 0.56 5.36 1.68 7.44s2.6 3.8 4.44 5.16 3.94 2.36 6.3 3 4.74 0.96 7.14 0.96c3.04 0 5.9-0.76 8.58-2.28s4.94-3.52 6.78-6c0.64 0.56 1.54 1.48 2.7 2.76s2.94 3.2 5.34 5.76c-2.8 3.36-6.22 6.02-10.26 7.98s-8.42 2.94-13.14 2.94-8.92-0.64-12.84-1.92-7.32-3.24-10.2-5.88-5.12-5.98-6.72-10.02-2.4-8.82-2.4-14.34c0-4.96 0.66-9.42 1.98-13.38s3.22-7.32 5.7-10.08 5.44-4.9 8.88-6.42 7.32-2.28 11.64-2.28c5.76 0 10.52 0.88 14.28 2.64s6.72 4.16 8.88 7.2 3.66 6.54 4.5 10.5 1.26 8.18 1.26 12.66zm-29.4-22.8c-2.16 0.16-4.16 0.72-6 1.68s-3.42 2.2-4.74 3.72-2.36 3.28-3.12 5.28-1.14 4.12-1.14 6.36h33.12c0-2-0.22-4.06-0.66-6.18s-1.3-4.02-2.58-5.7-3.1-3.02-5.46-4.02-5.5-1.38-9.42-1.14z" fill-rule="nonzero"/> </g> <g transform="matrix(1.8559 0 0 .7642 45.348 36.475)"> <g transform="translate(2.7114)"> <path d="m3.935 173.02c-0.331 0-0.497-0.402-0.497-1.207v-51.002c0-0.738 0.138-1.107 0.414-1.107h1.781c0.277 0 0.415 0.335 0.415 1.006v5.935c0 0.336 0.027 0.553 0.083 0.654 0.055 0.101 0.151-0.017 0.289-0.352 0.912-1.744 1.754-3.236 2.527-4.477 0.773-1.24 1.554-2.179 2.341-2.816s1.65-0.956 2.588-0.956c1.685 0 3.011 0.922 3.977 2.766 0.967 1.845 1.602 3.84 1.905 5.986 0.056 0.268 0.139 0.369 0.249 0.302s0.221-0.235 0.331-0.503c0.939-1.811 1.802-3.353 2.589-4.628 0.787-1.274 1.581-2.246 2.382-2.917s1.671-1.006 2.61-1.006c2.016 0 3.569 1.392 4.66 4.175 1.09 2.783 1.636 6.421 1.636 10.915v37.925c0 0.871-0.18 1.307-0.539 1.307h-1.739c-0.138 0-0.249-0.1-0.332-0.301-0.083-0.202-0.124-0.503-0.124-0.906v-36.315c0-3.555-0.338-6.321-1.015-8.3-0.676-1.978-1.76-2.967-3.251-2.967-0.884 0-1.726 0.386-2.527 1.157s-1.519 1.727-2.154 2.867-1.201 2.213-1.699 3.219c-0.248 0.469-0.421 0.905-0.517 1.308-0.097 0.402-0.145 0.972-0.145 1.71v37.221c0 0.871-0.166 1.307-0.497 1.307h-1.74c-0.166 0-0.29-0.1-0.373-0.301-0.083-0.202-0.124-0.503-0.124-0.906v-36.315c0-3.555-0.332-6.321-0.994-8.3-0.663-1.978-1.754-2.967-3.273-2.967-1.242 0-2.375 0.704-3.396 2.112-1.022 1.409-2.223 3.555-3.604 6.439v39.031c0 0.805-0.18 1.207-0.539 1.207h-1.698z" fill-rule="nonzero" stroke="#000" stroke-width=".7px"/> </g> <g transform="translate(2.7114)"> <path d="m53.642 166.28c-1.077 2.549-2.237 4.477-3.479 5.785-1.243 1.307-2.61 1.961-4.101 1.961-2.154 0-3.853-1.324-5.095-3.973-1.243-2.649-1.864-6.187-1.864-10.613 0-3.488 0.4-6.489 1.201-9.004s1.988-4.51 3.562-5.985c1.574-1.476 3.521-2.414 5.841-2.817l3.686-0.704c0.221-0.067 0.394-0.218 0.518-0.453 0.124-0.234 0.187-0.587 0.187-1.056v-2.917c0-3.89-0.504-6.975-1.512-9.255s-2.354-3.42-4.039-3.42c-1.298 0-2.472 0.72-3.521 2.162s-2.002 3.572-2.858 6.388c-0.083 0.268-0.159 0.453-0.228 0.554-0.069 0.1-0.172 0.083-0.311-0.051l-1.698-1.71c-0.083-0.134-0.138-0.285-0.166-0.453-0.027-0.167 0.014-0.452 0.125-0.855 0.856-3.353 2.009-6.052 3.459-8.098 1.449-2.045 3.224-3.068 5.322-3.068 1.74 0 3.211 0.687 4.412 2.062s2.112 3.37 2.734 5.986c0.621 2.615 0.932 5.7 0.932 9.255v35.712c0 0.536-0.035 0.888-0.104 1.056s-0.2 0.251-0.393 0.251h-1.533c-0.166 0-0.29-0.117-0.373-0.352-0.083-0.234-0.124-0.553-0.124-0.955l-0.083-5.231c-0.055-0.939-0.221-1.006-0.497-0.202zm0.456-19.314c0-1.14-0.194-1.643-0.58-1.509l-3.107 0.603c-1.436 0.202-2.686 0.638-3.749 1.308-1.063 0.671-1.953 1.543-2.671 2.616s-1.257 2.33-1.616 3.772-0.538 3.102-0.538 4.98c0 3.152 0.455 5.616 1.367 7.393 0.911 1.778 2.14 2.666 3.686 2.666 0.939 0 1.85-0.419 2.734-1.257s1.671-1.895 2.361-3.169c0.663-1.408 1.181-2.85 1.553-4.326 0.373-1.475 0.56-2.883 0.56-4.225v-8.852z" fill-rule="nonzero" stroke="#000" stroke-width=".7px"/> </g> <g transform="translate(2.7114)"> <path d="m79.034 173.02c-0.166 0-0.297-0.117-0.394-0.352-0.096-0.234-0.145-0.553-0.145-0.955v-4.628c0-0.536-0.041-0.838-0.124-0.905s-0.207 0.1-0.373 0.503c-0.276 0.67-0.69 1.593-1.242 2.766-0.553 1.174-1.271 2.23-2.154 3.169-0.884 0.939-1.961 1.408-3.231 1.408-1.74 0-3.314-0.989-4.722-2.967-1.409-1.979-2.534-4.963-3.376-8.953-0.843-3.991-1.264-8.937-1.264-14.838 0-5.701 0.415-10.68 1.243-14.939s1.988-7.595 3.479-10.009c1.492-2.415 3.204-3.622 5.137-3.622 1.436 0 2.616 0.57 3.541 1.71 0.926 1.14 1.719 2.381 2.382 3.722 0.249 0.47 0.414 0.637 0.497 0.503s0.125-0.536 0.125-1.207v-23.841c0-0.805 0.151-1.208 0.455-1.208h1.864c0.276 0 0.414 0.369 0.414 1.107v72.128c0 0.537-0.041 0.905-0.124 1.107-0.083 0.201-0.235 0.301-0.455 0.301h-1.533zm-0.621-42.049c-0.939-2.213-1.885-3.94-2.838-5.181s-2.009-1.861-3.169-1.861c-1.463 0-2.768 0.889-3.914 2.666s-2.044 4.376-2.693 7.796-0.973 7.578-0.973 12.474c0 5.097 0.338 9.272 1.015 12.524 0.676 3.253 1.567 5.651 2.672 7.193 1.104 1.543 2.305 2.314 3.603 2.314 1.188 0 2.258-0.704 3.211-2.113 0.952-1.408 1.705-3.118 2.257-5.13s0.829-3.957 0.829-5.835v-24.847z" fill-rule="nonzero" stroke="#000" stroke-width=".7px"/> </g> <g transform="translate(2.7114)"> <path d="m89.514 149.38c0 3.42 0.345 6.606 1.035 9.557 0.691 2.951 1.609 5.315 2.755 7.092s2.437 2.666 3.873 2.666c1.519 0 2.837-0.738 3.956-2.213 1.118-1.476 2.064-3.655 2.837-6.539 0.083-0.336 0.166-0.52 0.249-0.554 0.083-0.033 0.179 0.017 0.29 0.151l1.408 1.912c0.221 0.268 0.235 0.67 0.041 1.207-0.69 2.548-1.47 4.661-2.34 6.337-0.87 1.677-1.857 2.935-2.962 3.773-1.104 0.838-2.319 1.257-3.645 1.257-2.043 0-3.838-1.14-5.385-3.42-1.546-2.28-2.761-5.482-3.645-9.607-0.884-4.124-1.325-8.836-1.325-14.134 0-5.901 0.455-10.931 1.367-15.089 0.911-4.158 2.14-7.377 3.686-9.658 1.547-2.28 3.3-3.42 5.261-3.42 1.988 0 3.714 1.073 5.178 3.219 1.463 2.146 2.595 5.231 3.396 9.255s1.201 8.886 1.201 14.587c0 0.469-0.02 0.939-0.062 1.408-0.041 0.469-0.214 0.704-0.517 0.704h-16.362c-0.083 0-0.152 0.151-0.207 0.453-0.056 0.302-0.083 0.654-0.083 1.056zm13.752-6.237c0.304 0 0.497-0.1 0.58-0.302 0.083-0.201 0.124-0.57 0.124-1.106 0-3.219-0.283-6.187-0.849-8.903s-1.367-4.896-2.402-6.539c-1.036-1.643-2.272-2.464-3.708-2.464-1.629 0-2.996 0.955-4.101 2.867-1.104 1.911-1.94 4.342-2.506 7.293s-0.849 6.002-0.849 9.154h13.711z" fill-rule="nonzero" stroke="#000" stroke-width=".7px"/> </g> <g transform="translate(2.7114)"> <path d="m148.54 119.7c0.165 0 0.283 0.117 0.352 0.352s0.076 0.52 0.02 0.855l-6.254 50.902c-0.028 0.47-0.104 0.788-0.228 0.956s-0.297 0.251-0.518 0.251h-1.615c-0.442 0-0.718-0.402-0.829-1.207l-5.26-40.138c-0.111-0.604-0.201-0.905-0.27-0.905s-0.131 0.301-0.186 0.905l-5.012 40.138c-0.028 0.47-0.097 0.788-0.207 0.956-0.111 0.168-0.277 0.251-0.497 0.251h-1.74c-0.442 0-0.718-0.402-0.829-1.207l-6.503-50.801c-0.055-0.403-0.048-0.721 0.021-0.956s0.2-0.352 0.393-0.352h1.823c0.166 0 0.297 0.067 0.393 0.201 0.097 0.134 0.159 0.403 0.187 0.805l5.302 41.848c0.083 0.671 0.179 0.989 0.29 0.956 0.11-0.034 0.207-0.386 0.29-1.056l5.219-41.949c0.055-0.268 0.124-0.47 0.207-0.604s0.193-0.201 0.331-0.201h1.533c0.138 0 0.262 0.067 0.373 0.201 0.11 0.134 0.179 0.403 0.207 0.805l5.468 41.848c0.083 0.671 0.179 0.989 0.29 0.956 0.11-0.034 0.207-0.386 0.29-1.056l5.053-41.849c0.055-0.335 0.138-0.57 0.249-0.704 0.11-0.134 0.234-0.201 0.373-0.201h1.284z" fill-rule="nonzero" stroke="#000" stroke-width=".7px"/> </g> <g transform="translate(2.7114)"> <path d="m156.49 171.51c0 0.604-0.042 1.006-0.125 1.208-0.082 0.201-0.262 0.301-0.538 0.301h-1.533c-0.221 0-0.366-0.083-0.435-0.251s-0.103-0.486-0.103-0.956v-50.902c0-0.805 0.152-1.207 0.456-1.207h1.822c0.304 0 0.456 0.402 0.456 1.207v50.6zm0.165-63.979c0 1.207-0.207 1.811-0.621 1.811h-1.905c-0.221 0-0.366-0.135-0.435-0.403s-0.104-0.67-0.104-1.207v-7.847c0-1.006 0.18-1.509 0.539-1.509h1.988c0.359 0 0.538 0.47 0.538 1.409v7.746z" fill-rule="nonzero" stroke="#000" stroke-width=".7px"/> </g> <g transform="translate(2.7114)"> <path d="m168.3 124.83c-0.221 0-0.331 0.269-0.331 0.805v33.801c0 3.42 0.221 5.667 0.663 6.74 0.441 1.073 1.09 1.609 1.946 1.609h3.024c0.138 0 0.242 0.084 0.311 0.252 0.069 0.167 0.103 0.419 0.103 0.754v2.716c0 0.537-0.138 0.906-0.414 1.107-0.248 0.067-0.614 0.134-1.098 0.201-0.483 0.067-0.959 0.118-1.429 0.151-0.469 0.034-0.828 0.05-1.077 0.05-1.712 0-2.934-0.955-3.665-2.867-0.732-1.911-1.098-5.013-1.098-9.305v-35.108c0-0.604-0.124-0.906-0.373-0.906h-3.521c-0.248 0-0.373-0.268-0.373-0.804v-3.521c0-0.537 0.111-0.805 0.332-0.805h3.686c0.166 0 0.263-0.268 0.29-0.805l0.415-16.095c0-0.805 0.124-1.207 0.372-1.207h1.492c0.303 0 0.455 0.436 0.455 1.307v15.995c0 0.537 0.097 0.805 0.29 0.805h5.468c0.221 0 0.331 0.268 0.331 0.805v3.521c0 0.536-0.124 0.804-0.373 0.804h-5.426z" fill-rule="nonzero" stroke="#000" stroke-width=".7px"/> </g> <g transform="translate(2.7114)"> <path d="m179.4 173.02c-0.331 0-0.497-0.402-0.497-1.207v-72.329c0-0.738 0.138-1.107 0.414-1.107h1.782c0.276 0 0.414 0.336 0.414 1.006v27.162c0 0.335 0.034 0.536 0.103 0.603s0.159-0.033 0.27-0.302c0.994-1.81 1.898-3.319 2.713-4.526 0.814-1.208 1.629-2.113 2.444-2.717 0.814-0.603 1.691-0.905 2.63-0.905 2.182 0 3.839 1.375 4.971 4.125 1.132 2.749 1.698 6.404 1.698 10.965v37.925c0 0.871-0.166 1.307-0.497 1.307h-1.74c-0.165 0-0.29-0.1-0.373-0.301-0.082-0.202-0.124-0.503-0.124-0.906v-36.315c0-3.555-0.366-6.321-1.097-8.3-0.732-1.978-1.899-2.967-3.501-2.967-0.883 0-1.705 0.318-2.464 0.956-0.76 0.637-1.526 1.576-2.299 2.816-0.773 1.241-1.643 2.834-2.61 4.779v39.031c0 0.805-0.179 1.207-0.538 1.207h-1.699z" fill-rule="nonzero" stroke="#000" stroke-width=".7px"/> </g> </g> <g transform="matrix(.80638 0 0 .80638 452.53 65.421)" fill-rule="nonzero"> <path d="m79.32 36.98v150.76l15.68-13.2 6.59-156.31-22.27 18.75z" fill="url(#f)"/> <path d="m79.32 36.98-22.27-18.75 6.59 156.31 15.68 13.2v-150.76z" fill="url(#e)"/> <path d="m25.19 104.83 8.63 49.04 12.5-14.95-2.46-56.42-18.67 22.33z" fill="url(#d)"/> <path d="m25.19 104.83-25.19-14.59 16.97 53.86 16.85 9.77-8.63-49.04z" fill="url(#c)"/> <path d="M43.86,82.5L18.69,67.98L0,90.24L25.18,104.83L43.86,82.5Z" fill="#9c3"/> <path d="m134.82 78.69-9.97 56.5 15.58-9.04 19.57-62.05-25.18 14.59z" fill="url(#b)"/> <path d="m134.82 78.69-18.68-22.33-2.86 65 11.57 13.83 9.97-56.5z" fill="url(#a)"/> <path d="m160 64.1-18.69-22.26-25.17 14.52 18.67 22.33 25.19-14.59z" fill="#ffe113"/> <path d="M101.59,18.23L79.32,0L57.05,18.23L79.32,36.98L101.59,18.23Z" fill="#f3e600"/> </g> <defs> <linearGradient id="f" x2="1" gradientTransform="matrix(.84 -162.96 162.96 .84 89.64 184.81)" gradientUnits="userSpaceOnUse"><stop stop-color="#62d399" offset="0"/><stop stop-color="#acd842" offset=".51"/><stop stop-color="#d7db0a" offset=".9"/><stop stop-color="#d7db0a" offset="1"/></linearGradient> <linearGradient id="e" x2="1" gradientTransform="matrix(-1.6,-162.13,162.13,-1.6,69.68,178.9)" gradientUnits="userSpaceOnUse"><stop stop-color="#0ba398" offset="0"/><stop stop-color="#4ca352" offset=".5"/><stop stop-color="#76a30a" offset="1"/></linearGradient> <linearGradient id="d" x2="1" gradientTransform="matrix(-1.9,-67.98,67.98,-1.9,36.6,152.17)" gradientUnits="userSpaceOnUse"><stop stop-color="#36a382" offset="0"/><stop stop-color="#36a382" offset=".19"/><stop stop-color="#49a459" offset=".54"/><stop stop-color="#76a30b" offset="1"/></linearGradient> <linearGradient id="c" x2="1" gradientTransform="matrix(2.18,-62.38,62.38,2.18,15.82,153.24)" gradientUnits="userSpaceOnUse"><stop stop-color="#267880" offset="0"/><stop stop-color="#457a5c" offset=".51"/><stop stop-color="#717516" offset="1"/></linearGradient> <linearGradient id="b" x2="1" gradientTransform="matrix(13.85,-71.96,71.96,13.85,135.08,135.43)" gradientUnits="userSpaceOnUse"><stop stop-color="#b0d939" offset="0"/><stop stop-color="#eadb04" offset="1"/></linearGradient> <linearGradient id="a" x2="1" gradientTransform="matrix(26.159 -64.737 64.737 26.159 107.42 128.14)" gradientUnits="userSpaceOnUse"><stop stop-color="#74af52" offset="0"/><stop stop-color="#74af52" offset=".17"/><stop stop-color="#99be32" offset=".48"/><stop stop-color="#c0c40a" offset="1"/></linearGradient> </defs> </svg>`;btoa(pne);const mne='<svg viewBox="0 0 509 154" xmlns="http://www.w3.org/2000/svg" xml:space="preserve" style="fill-rule:evenodd;clip-rule:evenodd;stroke-linejoin:round;stroke-miterlimit:2"><path d="M665.95 132.73v44.88l-10.56-8.4c-.8-.64-1.2-1.44-1.2-2.4v-32.4c0-6.48-4.12-9.72-12.36-9.72-2.16 0-4.18.4-6.06 1.2-1.88.8-3.54 1.8-4.98 3-1.44 1.2-2.56 2.5-3.36 3.9-.8 1.4-1.2 2.7-1.2 3.9v40.92l-10.68-8.4c-.72-.64-1.08-1.44-1.08-2.4v-53.76l10.92 8.52c.32.24.56.44.72.6.16.16.36.32.6.48.96-1.2 2.14-2.28 3.54-3.24 1.4-.96 2.92-1.76 4.56-2.4 1.64-.64 3.34-1.14 5.1-1.5 1.76-.36 3.44-.54 5.04-.54 1.44 0 2.92.04 4.44.12 1.52.08 2.84.28 3.96.6 4.56 1.12 7.8 3.12 9.72 6 1.92 2.88 2.88 6.56 2.88 11.04ZM732.38 146.05c0 .88.02 1.5.06 1.86.04.36-.02.98-.18 1.86h-7.08c-2.08 0-4.44-.02-7.08-.06-2.64-.04-5.36-.06-8.16-.06h-22.08c0 2.88.56 5.36 1.68 7.44 1.12 2.08 2.6 3.8 4.44 5.16 1.84 1.36 3.94 2.36 6.3 3 2.36.64 4.74.96 7.14.96 3.04 0 5.9-.76 8.58-2.28 2.68-1.52 4.94-3.52 6.78-6 .64.56 1.54 1.48 2.7 2.76 1.16 1.28 2.94 3.2 5.34 5.76-2.8 3.36-6.22 6.02-10.26 7.98-4.04 1.96-8.42 2.94-13.14 2.94-4.72 0-8.92-.64-12.84-1.92-3.92-1.28-7.32-3.24-10.2-5.88-2.88-2.64-5.12-5.98-6.72-10.02-1.6-4.04-2.4-8.82-2.4-14.34 0-4.96.66-9.42 1.98-13.38 1.32-3.96 3.22-7.32 5.7-10.08s5.44-4.9 8.88-6.42c3.44-1.52 7.32-2.28 11.64-2.28 5.76 0 10.52.88 14.28 2.64 3.76 1.76 6.72 4.16 8.88 7.2 2.16 3.04 3.66 6.54 4.5 10.5.84 3.96 1.26 8.18 1.26 12.66Zm-29.4-22.8c-2.16.16-4.16.72-6 1.68-1.84.96-3.42 2.2-4.74 3.72-1.32 1.52-2.36 3.28-3.12 5.28-.76 2-1.14 4.12-1.14 6.36h33.12c0-2-.22-4.06-.66-6.18-.44-2.12-1.3-4.02-2.58-5.7-1.28-1.68-3.1-3.02-5.46-4.02-2.36-1-5.5-1.38-9.42-1.14ZM795.93 146.05c0 .88.02 1.5.06 1.86.04.36-.02.98-.18 1.86h-7.08c-2.08 0-4.44-.02-7.08-.06-2.64-.04-5.36-.06-8.16-.06h-22.08c0 2.88.56 5.36 1.68 7.44 1.12 2.08 2.6 3.8 4.44 5.16 1.84 1.36 3.94 2.36 6.3 3 2.36.64 4.74.96 7.14.96 3.04 0 5.9-.76 8.58-2.28 2.68-1.52 4.94-3.52 6.78-6 .64.56 1.54 1.48 2.7 2.76 1.16 1.28 2.94 3.2 5.34 5.76-2.8 3.36-6.22 6.02-10.26 7.98-4.04 1.96-8.42 2.94-13.14 2.94-4.72 0-8.92-.64-12.84-1.92-3.92-1.28-7.32-3.24-10.2-5.88-2.88-2.64-5.12-5.98-6.72-10.02-1.6-4.04-2.4-8.82-2.4-14.34 0-4.96.66-9.42 1.98-13.38 1.32-3.96 3.22-7.32 5.7-10.08s5.44-4.9 8.88-6.42c3.44-1.52 7.32-2.28 11.64-2.28 5.76 0 10.52.88 14.28 2.64 3.76 1.76 6.72 4.16 8.88 7.2 2.16 3.04 3.66 6.54 4.5 10.5.84 3.96 1.26 8.18 1.26 12.66Zm-29.4-22.8c-2.16.16-4.16.72-6 1.68-1.84.96-3.42 2.2-4.74 3.72-1.32 1.52-2.36 3.28-3.12 5.28-.76 2-1.14 4.12-1.14 6.36h33.12c0-2-.22-4.06-.66-6.18-.44-2.12-1.3-4.02-2.58-5.7-1.28-1.68-3.1-3.02-5.46-4.02-2.36-1-5.5-1.38-9.42-1.14ZM858.57 97.21c.64.48.96 1.16.96 2.04v74.88c-.08 1.04-.12 2.12-.12 3.24-1.84-1.52-3.56-2.92-5.16-4.2-1.36-1.12-2.66-2.18-3.9-3.18-1.24-1-2.06-1.66-2.46-1.98-1.76 2.48-4.26 4.44-7.5 5.88-3.24 1.44-7.02 2.16-11.34 2.16-3.84 0-7.4-.7-10.68-2.1-3.28-1.4-6.14-3.44-8.58-6.12-2.44-2.68-4.34-5.94-5.7-9.78-1.36-3.84-2.04-8.16-2.04-12.96 0-4.32.78-8.34 2.34-12.06 1.56-3.72 3.6-6.92 6.12-9.6 2.52-2.68 5.38-4.78 8.58-6.3 3.2-1.52 6.48-2.28 9.84-2.28 2.56 0 4.82.22 6.78.66 1.96.44 3.68 1.06 5.16 1.86s2.78 1.74 3.9 2.82a35.92 35.92 0 0 1 3.12 3.42V88.57l10.68 8.64Zm-27.96 67.92c3.6 0 6.52-.68 8.76-2.04 2.24-1.36 3.98-3.06 5.22-5.1a20.5 20.5 0 0 0 2.58-6.54c.48-2.32.72-4.44.72-6.36v-1.2c0-1.12-.22-2.7-.66-4.74-.44-2.04-1.28-4.06-2.52-6.06s-3-3.7-5.28-5.1c-2.28-1.4-5.22-2.02-8.82-1.86-3.44 0-6.26.74-8.46 2.22-2.2 1.48-3.96 3.26-5.28 5.34-1.32 2.08-2.24 4.2-2.76 6.36-.52 2.16-.78 3.92-.78 5.28 0 1.84.24 3.92.72 6.24.48 2.32 1.36 4.48 2.64 6.48s3.04 3.68 5.28 5.04c2.24 1.36 5.12 2.04 8.64 2.04ZM882.81 97.09c.64.48.96 1.12.96 1.92l-.12 41.04v37.08l-10.56-8.4c-.72-.64-1.08-1.44-1.08-2.4V88.45l10.8 8.64ZM950.36 146.05c0 .88.02 1.5.06 1.86.04.36-.02.98-.18 1.86h-7.08c-2.08 0-4.44-.02-7.08-.06-2.64-.04-5.36-.06-8.16-.06h-22.08c0 2.88.56 5.36 1.68 7.44 1.12 2.08 2.6 3.8 4.44 5.16 1.84 1.36 3.94 2.36 6.3 3 2.36.64 4.74.96 7.14.96 3.04 0 5.9-.76 8.58-2.28 2.68-1.52 4.94-3.52 6.78-6 .64.56 1.54 1.48 2.7 2.76 1.16 1.28 2.94 3.2 5.34 5.76-2.8 3.36-6.22 6.02-10.26 7.98-4.04 1.96-8.42 2.94-13.14 2.94-4.72 0-8.92-.64-12.84-1.92-3.92-1.28-7.32-3.24-10.2-5.88-2.88-2.64-5.12-5.98-6.72-10.02-1.6-4.04-2.4-8.82-2.4-14.34 0-4.96.66-9.42 1.98-13.38 1.32-3.96 3.22-7.32 5.7-10.08s5.44-4.9 8.88-6.42c3.44-1.52 7.32-2.28 11.64-2.28 5.76 0 10.52.88 14.28 2.64 3.76 1.76 6.72 4.16 8.88 7.2 2.16 3.04 3.66 6.54 4.5 10.5.84 3.96 1.26 8.18 1.26 12.66Zm-29.4-22.8c-2.16.16-4.16.72-6 1.68-1.84.96-3.42 2.2-4.74 3.72-1.32 1.52-2.36 3.28-3.12 5.28-.76 2-1.14 4.12-1.14 6.36h33.12c0-2-.22-4.06-.66-6.18-.44-2.12-1.3-4.02-2.58-5.7-1.28-1.68-3.1-3.02-5.46-4.02-2.36-1-5.5-1.38-9.42-1.14Z" style="fill-rule:nonzero" transform="translate(-452.406 -63.709) scale(1.00797)"/><path d="M79.32 36.98v150.76L95 174.54l6.59-156.31-22.27 18.75Z" style="fill:url(#a);fill-rule:nonzero" transform="matrix(.80638 0 0 .80638 2.361 1.094)"/><path d="M79.32 36.98 57.05 18.23l6.59 156.31 15.68 13.2V36.98Z" style="fill:url(#b);fill-rule:nonzero" transform="matrix(.80638 0 0 .80638 2.361 1.094)"/><path d="m25.19 104.83 8.63 49.04 12.5-14.95-2.46-56.42-18.67 22.33Z" style="fill:url(#c);fill-rule:nonzero" transform="matrix(.80638 0 0 .80638 2.361 1.094)"/><path d="M25.19 104.83 0 90.24l16.97 53.86 16.85 9.77-8.63-49.04Z" style="fill:url(#d);fill-rule:nonzero" transform="matrix(.80638 0 0 .80638 2.361 1.094)"/><path d="M43.86 82.5 18.69 67.98 0 90.24l25.18 14.59L43.86 82.5Z" style="fill:#9c3;fill-rule:nonzero" transform="matrix(.80638 0 0 .80638 2.361 1.094)"/><path d="m134.82 78.69-9.97 56.5 15.58-9.04L160 64.1l-25.18 14.59Z" style="fill:url(#e);fill-rule:nonzero" transform="matrix(.80638 0 0 .80638 2.361 1.094)"/><path d="m134.82 78.69-18.68-22.33-2.86 65 11.57 13.83 9.97-56.5Z" style="fill:url(#f);fill-rule:nonzero" transform="matrix(.80638 0 0 .80638 2.361 1.094)"/><path d="m160 64.1-18.69-22.26-25.17 14.52 18.67 22.33L160 64.1Z" style="fill:#ffe113;fill-rule:nonzero" transform="matrix(.80638 0 0 .80638 2.361 1.094)"/><path d="M101.59 18.23 79.32 0 57.05 18.23l22.27 18.75 22.27-18.75Z" style="fill:#f3e600;fill-rule:nonzero" transform="matrix(.80638 0 0 .80638 2.361 1.094)"/><defs><linearGradient id="a" x1="0" y1="0" x2="1" y2="0" gradientUnits="userSpaceOnUse" gradientTransform="matrix(.84 -162.96 162.96 .84 89.64 184.81)"><stop offset="0" style="stop-color:#62d399;stop-opacity:1"/><stop offset=".51" style="stop-color:#acd842;stop-opacity:1"/><stop offset=".9" style="stop-color:#d7db0a;stop-opacity:1"/><stop offset="1" style="stop-color:#d7db0a;stop-opacity:1"/></linearGradient><linearGradient id="b" x1="0" y1="0" x2="1" y2="0" gradientUnits="userSpaceOnUse" gradientTransform="rotate(-90.565 123.412 54.953) scale(162.14)"><stop offset="0" style="stop-color:#0ba398;stop-opacity:1"/><stop offset=".5" style="stop-color:#4ca352;stop-opacity:1"/><stop offset="1" style="stop-color:#76a30a;stop-opacity:1"/></linearGradient><linearGradient id="c" x1="0" y1="0" x2="1" y2="0" gradientUnits="userSpaceOnUse" gradientTransform="scale(-68) rotate(88.4 .881 -1.396)"><stop offset="0" style="stop-color:#36a382;stop-opacity:1"/><stop offset=".19" style="stop-color:#36a382;stop-opacity:1"/><stop offset=".54" style="stop-color:#49a459;stop-opacity:1"/><stop offset="1" style="stop-color:#76a30b;stop-opacity:1"/></linearGradient><linearGradient id="d" x1="0" y1="0" x2="1" y2="0" gradientUnits="userSpaceOnUse" gradientTransform="rotate(-88 87.255 68.431) scale(62.42)"><stop offset="0" style="stop-color:#267880;stop-opacity:1"/><stop offset=".51" style="stop-color:#457a5c;stop-opacity:1"/><stop offset="1" style="stop-color:#717516;stop-opacity:1"/></linearGradient><linearGradient id="e" x1="0" y1="0" x2="1" y2="0" gradientUnits="userSpaceOnUse" gradientTransform="rotate(-79.1 149.53 -14.065) scale(73.28)"><stop offset="0" style="stop-color:#b0d939;stop-opacity:1"/><stop offset="1" style="stop-color:#eadb04;stop-opacity:1"/></linearGradient><linearGradient id="f" x1="0" y1="0" x2="1" y2="0" gradientUnits="userSpaceOnUse" gradientTransform="rotate(-67.997 148.705 -15.558) scale(69.8226)"><stop offset="0" style="stop-color:#74af52;stop-opacity:1"/><stop offset=".17" style="stop-color:#74af52;stop-opacity:1"/><stop offset=".48" style="stop-color:#99be32;stop-opacity:1"/><stop offset="1" style="stop-color:#c0c40a;stop-opacity:1"/></linearGradient></defs></svg>',fne=btoa(mne),gne="data:image/svg+xml;charset=utf-8;base64,"+fne,vne=gne,pa=te("debuglicense");let Sp="basic";pa&&console.log("License Type: "+Sp);function uu(){switch(Sp){case"pro":case"enterprise":return!0}return!1}function OR(){switch(Sp){case"indie":return!0}return!1}function eh(){return uu()||OR()}const yz=[];function yne(n){if(uu()||OR())return n(!0);yz.push(n)}function Ane(n){for(const e of yz)try{e(n)}catch{}}di.registerCallback(Ci.ContextRegistered,n=>{xne(n.context),Sne(),_ne(n.context)});let Cp,LR=!1,_w="";async function bne(){if(Cp)return Cp;if(Sp==="basic")try{const n="https://engine.needle.tools/licensing/check?location="+encodeURIComponent(window.location.href)+"&version="+el+"&generator="+encodeURIComponent(bw),e=await fetch(n,{method:"GET"}).catch(t=>{pa&&console.error("License check failed",t)});e?.status===200?(LR=!1,pa&&console.log("License check succeeded"),Sp="pro",Ane(!0)):e?.status===403?(LR=!0,_w=await e.text()):pa&&console.log("License check failed with status "+e?.status)}catch(n){pa&&console.error("License check failed",n)}else pa&&console.log('Runtime license check is skipped because license is already applied as "'+Sp+'"')}Cp=bne();async function _ne(n){function e(){const s=document.createElement("div");s.className="needle-forbidden",s.style.cssText=`
|
|
4349
4349
|
position: fixed;
|
|
4350
4350
|
top: 0;
|
|
@@ -5148,7 +5148,7 @@ in script ${o}.ts
|
|
|
5148
5148
|
*
|
|
5149
5149
|
* @author Feross Aboukhadijeh <https://feross.org>
|
|
5150
5150
|
* @license MIT
|
|
5151
|
-
*/var rue=function(n){return n!=null&&(w6(n)||sue(n)||!!n._isBuffer)};function w6(n){return!!n.constructor&&typeof n.constructor.isBuffer=="function"&&n.constructor.isBuffer(n)}function sue(n){return typeof n.readFloatLE=="function"&&typeof n.slice=="function"&&w6(n.slice(0,0))}(function(){var n=nue,e=x6.utf8,t=rue,r=x6.bin,s=function(o,a){o.constructor==String?a&&a.encoding==="binary"?o=r.stringToBytes(o):o=e.stringToBytes(o):t(o)?o=Array.prototype.slice.call(o,0):!Array.isArray(o)&&o.constructor!==Uint8Array&&(o=o.toString());for(var l=n.bytesToWords(o),c=o.length*8,h=1732584193,u=-271733879,p=-1732584194,m=271733878,f=0;f<l.length;f++)l[f]=(l[f]<<8|l[f]>>>24)&16711935|(l[f]<<24|l[f]>>>8)&4278255360;l[c>>>5]|=128<<c%32,l[(c+64>>>9<<4)+14]=c;for(var g=s._ff,v=s._gg,y=s._hh,A=s._ii,f=0;f<l.length;f+=16){var _=h,b=u,x=p,E=m;h=g(h,u,p,m,l[f+0],7,-680876936),m=g(m,h,u,p,l[f+1],12,-389564586),p=g(p,m,h,u,l[f+2],17,606105819),u=g(u,p,m,h,l[f+3],22,-1044525330),h=g(h,u,p,m,l[f+4],7,-176418897),m=g(m,h,u,p,l[f+5],12,1200080426),p=g(p,m,h,u,l[f+6],17,-1473231341),u=g(u,p,m,h,l[f+7],22,-45705983),h=g(h,u,p,m,l[f+8],7,1770035416),m=g(m,h,u,p,l[f+9],12,-1958414417),p=g(p,m,h,u,l[f+10],17,-42063),u=g(u,p,m,h,l[f+11],22,-1990404162),h=g(h,u,p,m,l[f+12],7,1804603682),m=g(m,h,u,p,l[f+13],12,-40341101),p=g(p,m,h,u,l[f+14],17,-1502002290),u=g(u,p,m,h,l[f+15],22,1236535329),h=v(h,u,p,m,l[f+1],5,-165796510),m=v(m,h,u,p,l[f+6],9,-1069501632),p=v(p,m,h,u,l[f+11],14,643717713),u=v(u,p,m,h,l[f+0],20,-373897302),h=v(h,u,p,m,l[f+5],5,-701558691),m=v(m,h,u,p,l[f+10],9,38016083),p=v(p,m,h,u,l[f+15],14,-660478335),u=v(u,p,m,h,l[f+4],20,-405537848),h=v(h,u,p,m,l[f+9],5,568446438),m=v(m,h,u,p,l[f+14],9,-1019803690),p=v(p,m,h,u,l[f+3],14,-187363961),u=v(u,p,m,h,l[f+8],20,1163531501),h=v(h,u,p,m,l[f+13],5,-1444681467),m=v(m,h,u,p,l[f+2],9,-51403784),p=v(p,m,h,u,l[f+7],14,1735328473),u=v(u,p,m,h,l[f+12],20,-1926607734),h=y(h,u,p,m,l[f+5],4,-378558),m=y(m,h,u,p,l[f+8],11,-2022574463),p=y(p,m,h,u,l[f+11],16,1839030562),u=y(u,p,m,h,l[f+14],23,-35309556),h=y(h,u,p,m,l[f+1],4,-1530992060),m=y(m,h,u,p,l[f+4],11,1272893353),p=y(p,m,h,u,l[f+7],16,-155497632),u=y(u,p,m,h,l[f+10],23,-1094730640),h=y(h,u,p,m,l[f+13],4,681279174),m=y(m,h,u,p,l[f+0],11,-358537222),p=y(p,m,h,u,l[f+3],16,-722521979),u=y(u,p,m,h,l[f+6],23,76029189),h=y(h,u,p,m,l[f+9],4,-640364487),m=y(m,h,u,p,l[f+12],11,-421815835),p=y(p,m,h,u,l[f+15],16,530742520),u=y(u,p,m,h,l[f+2],23,-995338651),h=A(h,u,p,m,l[f+0],6,-198630844),m=A(m,h,u,p,l[f+7],10,1126891415),p=A(p,m,h,u,l[f+14],15,-1416354905),u=A(u,p,m,h,l[f+5],21,-57434055),h=A(h,u,p,m,l[f+12],6,1700485571),m=A(m,h,u,p,l[f+3],10,-1894986606),p=A(p,m,h,u,l[f+10],15,-1051523),u=A(u,p,m,h,l[f+1],21,-2054922799),h=A(h,u,p,m,l[f+8],6,1873313359),m=A(m,h,u,p,l[f+15],10,-30611744),p=A(p,m,h,u,l[f+6],15,-1560198380),u=A(u,p,m,h,l[f+13],21,1309151649),h=A(h,u,p,m,l[f+4],6,-145523070),m=A(m,h,u,p,l[f+11],10,-1120210379),p=A(p,m,h,u,l[f+2],15,718787259),u=A(u,p,m,h,l[f+9],21,-343485551),h=h+_>>>0,u=u+b>>>0,p=p+x>>>0,m=m+E>>>0}return n.endian([h,u,p,m])};s._ff=function(o,a,l,c,h,u,p){var m=o+(a&l|~a&c)+(h>>>0)+p;return(m<<u|m>>>32-u)+a},s._gg=function(o,a,l,c,h,u,p){var m=o+(a&c|l&~c)+(h>>>0)+p;return(m<<u|m>>>32-u)+a},s._hh=function(o,a,l,c,h,u,p){var m=o+(a^l^c)+(h>>>0)+p;return(m<<u|m>>>32-u)+a},s._ii=function(o,a,l,c,h,u,p){var m=o+(l^(a|~c))+(h>>>0)+p;return(m<<u|m>>>32-u)+a},s._blocksize=16,s._digestsize=16,b6.exports=function(o,a){if(o==null)throw new Error("Illegal argument "+o);var l=n.wordsToBytes(s(o,a));return a&&a.asBytes?l:a&&a.asString?r.bytesToString(l):n.bytesToHex(l)}})();var oue=b6.exports;const aue=G1(oue);class hB{constructor(e,t,r,s){d(this,"success"),d(this,"filename"),d(this,"hash"),d(this,"size"),d(this,"url"),this.success=e,this.filename=t,this.hash=r,this.size=s}}async function S6(n,e){const t=await n.arrayBuffer(),r=uB(t),s=n.name.split(".").pop(),o=r+"."+s,a=n.name.split(".").shift();console.assert(a!==void 0);const l={alias:a,filename:o},c=await(await fetch(e+"/exists",{method:"POST",body:JSON.stringify(l)})).json();if(c.success||console.warn("exists check did fail"),c.exists)return console.log("file already exists",r),new hB(!0,o,r,n.size);console.log("begin uploading file",a,n.size);const h=new FormData;h.append("file",n);const u={};u.filesize=n.size,a&&(u.alias=a);const p=await(await fetch(e+"/upload/file",{method:"POST",body:h,headers:u})).json();if(p?.success===!1)return p.message!==void 0?console.error("Upload failed:",p.message):console.error("Upload failed"),null;console.assert(p.hash_sum===r,"hash sum did not match","received:",p.hash_sum,"expected:",r),p.success&&console.log("successfully uploaded",r,p.id);const m=new hB(p.success,o,r,n.size);return m.url=e,m}function uB(n){return aue(new Uint8Array(n))}async function dB(n,e,t,r,s=!1){try{const o=await fetch(r+"/download/file",{method:"POST",body:n});if(o.status!==200)return console.error("download failed",o),null;const a=await o.blob(),l=await a.arrayBuffer();s||console.assert(a.size===t,"size mismatch","expected:",t,"got:",a.size);const c=uB(l);return s||console.assert(c===e,"hash mismatch, downloaded file is invalid"),a.arrayBuffer()}catch(o){console.error(o)}return null}async function C6(n,e){var t;const r=await fetch(n),s=(t=r.body)==null?void 0:t.getReader(),o=r.headers.get("Content-Length"),a=o?parseInt(o):0;if(!s)return null;let l=0;const c=[];for(;;){const{done:p,value:m}=await s.read();if(m&&(c.push(m),l+=m.length,e.call(null,new ProgressEvent("progress",{loaded:l,total:a}))),p)break}const h=new Uint8Array(l);let u=0;for(const p of c)h.set(p,u),u+=p.length;return h}const Fu=te("debugaddressables");class E6{constructor(e){d(this,"_context"),d(this,"_assetReferences",{}),d(this,"preUpdate",()=>{}),this._context=e,this._context.pre_update_callbacks.push(this.preUpdate)}dispose(){const e=this._context.pre_update_callbacks.indexOf(this.preUpdate);e>=0&&this._context.pre_update_callbacks.splice(e,1);for(const t in this._assetReferences){const r=this._assetReferences[t];r?.unload()}this._assetReferences={}}findAssetReference(e){return this._assetReferences[e]||null}registerAssetReference(e){return e.uri&&(this._assetReferences[e.uri]?console.warn("Asset reference already registered",e):this._assetReferences[e.uri]=e),e}unregisterAssetReference(e){e.uri&&delete this._assetReferences[e.uri]}}const pB=Symbol("assetReference"),Pg=class{constructor(n,e,t=null){d(this,"_loading"),d(this,"_asset"),d(this,"_glbRoot"),d(this,"_url"),d(this,"_progressListeners",[]),d(this,"_hash"),d(this,"_hashedUri"),d(this,"_isLoadingRawBinary",!1),d(this,"_rawBinary"),this._url=n,this._hash=e,n.includes("?v=")?this._hashedUri=n:this._hashedUri=e?n+"?v="+e:n,t!==null&&(this.asset=t),jV(this._url,this.onResolvePrefab.bind(this))}static getOrCreateFromUrl(n,e){if(!e&&(e=kt.Current,!e))throw new Error('Context is required when sourceId is a string. When you call this method from a component you can call it with "getOrCreate(this, url)" where "this" is the component.');const t=e.addressables,r=t.findAssetReference(n);if(r)return r;const s=new Pg(n,e.hash);return t.registerAssetReference(s),s}static getOrCreate(n,e,t){if(typeof n=="string"){if(!t&&(t=kt.Current,!t))throw new Error('Context is required when sourceId is a string. When you call this method from a component you can call it with "getOrCreate(this, url)" where "this" is the component.')}else t=n.context,n=n.sourceId;const r=cu(n,e);Fu&&console.log("GetOrCreate Addressable from",n,e,"FinalPath=",r);const s=t.addressables,o=s.findAssetReference(r);if(o)return o;const a=new Pg(r,t.hash);return s.registerAssetReference(a),a}get asset(){return this._glbRoot??this._asset}set asset(n){this._asset=n}get uri(){return this._url}get url(){return this._url}get hasUrl(){return this._url!==void 0&&(this._url.startsWith("http")||this._url.startsWith("blob:")||this._url.startsWith("www.")||this._url.includes("/"))}get rawAsset(){return this._asset}async onResolvePrefab(n){return n===this.uri&&(this.mustLoad&&await this.loadAssetAsync(),this.asset)?this.asset:null}get mustLoad(){return!this.asset||this.asset.__destroyed===!0||Jp(this.asset)===!0}isLoaded(){return this._rawBinary||this.asset!==void 0}unload(){this.asset&&(Fu&&console.log("Unload",this.asset),this.asset.scene&&Ca(this.asset.scene,!0,!0),Ca(this.asset,!0,!0)),this.asset=null,this._rawBinary=void 0,this._glbRoot=null,this._loading=void 0,kt.Current&&kt.Current.addressables.unregisterAssetReference(this)}async preload(){if(!this.mustLoad||this._isLoadingRawBinary)return null;if(this._rawBinary!==void 0)return this._rawBinary;this._isLoadingRawBinary=!0,Fu&&console.log("Preload",this._hashedUri);const n=await C6(this._hashedUri,e=>{this.raiseProgressEvent(e)});return this._rawBinary=n?.buffer??null,this._isLoadingRawBinary=!1,this._rawBinary}async loadAssetAsync(n){if(Fu&&console.log("loadAssetAsync",this.uri),!this.mustLoad)return this.asset;if(n&&this._progressListeners.push(n),this._loading!==void 0)return this._loading.then(r=>this.asset);const e=kt.Current;this._rawBinary?(this._loading=Ka().parseSync(e,this._rawBinary,this.uri,null),this.raiseProgressEvent(new ProgressEvent("progress",{loaded:this._rawBinary.byteLength,total:this._rawBinary.byteLength}))):(Fu&&console.log("Load async",this.uri),this._loading=Ka().loadSync(e,this._hashedUri,this.uri,null,r=>{this.raiseProgressEvent(r)}));const t=await this._loading;if(this._progressListeners.length=0,this._glbRoot=this.tryGetActualGameObjectRoot(t),this._loading=void 0,t)return t[pB]=this,this._glbRoot&&(this._glbRoot[pB]=this),this.asset&&(this.asset[pB]=this),B1(e),t.scene!==void 0&&(this.asset=t),this.asset}async instantiate(n){return this.onInstantiate(n,!1)}async instantiateSynced(n,e=!0){return this.onInstantiate(n,!0,e)}beginListenDownload(n){this._progressListeners.indexOf(n)<0&&this._progressListeners.push(n)}endListenDownload(n){const e=this._progressListeners.indexOf(n);e>=0&&this._progressListeners.splice(e,1)}raiseProgressEvent(n){for(const e of this._progressListeners)e(this,n)}async onInstantiate(n,e=!1,t){const r=kt.Current,s=new Ml;if(n instanceof ye?s.parent=n:n&&(Object.assign(s,n),s.cloneAssign(n)),s.parent||(s.parent=r.scene),this.mustLoad&&await this.loadAssetAsync(),Fu&&console.log("Instantiate",this.uri,"parent:",n),this.asset){Fu&&console.log("Add to scene",this.asset);let o=Pg.currentlyInstantiating.get(this.uri);if(o!==void 0&&o>=1e4)return console.error("Recursive or too many instantiations of "+this.uri+" in the same frame ("+o+")"),null;try{if(o===void 0&&(o=0),o+=1,Pg.currentlyInstantiating.set(this.uri,o),e){s.context=r;const a=this.asset;a.guid=this.uri;const l=ek(a,s,void 0,t);if(l)return l}else{const a=Gg(this.asset,s);if(a)return a}}finally{r.post_render_callbacks.push(()=>{o===void 0||o<0?o=0:o-=1,Pg.currentlyInstantiating.set(this.uri,o)})}}else Fu&&console.warn("Failed to load asset",this.uri);return null}tryGetActualGameObjectRoot(n){if(n&&n.scene){const e=n.scene;return e.isGroup&&e.children.length===1&&e.children[0].name+"glb"===e.name?e.children[0]:e}return null}};let ti=Pg;d(ti,"currentlyInstantiating",new Map);class lue extends wa{constructor(){super([ti],"AssetReferenceSerializer")}onSerialize(e,t){if(e&&e.uri!==void 0&&typeof e.uri=="string")return e.uri}onDeserialize(e,t){if(typeof e=="string")return t.context?t.gltfId?ti.getOrCreate(t.gltfId,e,t.context):(console.error("Missing source id"),null):(console.error("Missing context"),null);if(e instanceof ye){if(!t.context)return console.error("Missing context"),null;if(!t.gltfId)return console.error("Missing source id"),null;const r=e,s=t.context,o=r.guid??r.uuid,a=s.addressables.findAssetReference(o);if(a)return a;const l=new ti(o,void 0,r);return s.addressables.registerAssetReference(l),l}return null}}new lue;const cue=Promise.resolve(null),V1=class{constructor(n){d(this,"url"),d(this,"_bitmap"),d(this,"_bitmapObject"),d(this,"loader",null),this.url=n}static getOrCreate(n){let e=V1.imageReferences.get(n);return e||(e=new V1(n),V1.imageReferences.set(n,e)),e}dispose(){this._bitmapObject&&this._bitmapObject.close(),this._bitmap=void 0}createHTMLImage(){const n=new Image;return n.src=this.url,n}createTexture(){return this.url?(this.loader||(this.loader=new Dl),this.loader.setCrossOrigin("anonymous"),this.loader.loadAsync(this.url)):cue}getBitmap(){return this._bitmap?this._bitmap:(this._bitmap=new Promise((n,e)=>{const t=document.createElement("img");t.addEventListener("load",()=>{this._bitmap=createImageBitmap(t).then(r=>(this._bitmapObject=r,n(r),r))}),t.addEventListener("error",r=>{console.error("Failed to load image:"+this.url,r),n(null)}),t.src=this.url}),this._bitmap)}};let Q1=V1;d(Q1,"imageReferences",new Map);class M6 extends wa{constructor(){super([Q1],"ImageReferenceSerializer")}onSerialize(e,t){return null}onDeserialize(e,t){if(typeof e=="string"){const r=cu(t.gltfId,e);return Q1.getOrCreate(r)}}}new M6;const H1=class{constructor(n){d(this,"url"),d(this,"res"),this.url=n}static getOrCreate(n){let e=H1.cache.get(n);return e||(e=new H1(n),H1.cache.set(n,e)),e}async loadRaw(){return this.res||(this.res=fetch(this.url)),this.res.then(n=>n.blob())}async loadText(){return this.res||(this.res=fetch(this.url)),this.res.then(n=>n.text())}};let W1=H1;d(W1,"cache",new Map);class T6 extends wa{constructor(){super([W1],"FileReferenceSerializer")}onSerialize(e,t){return null}onDeserialize(e,t){if(typeof e=="string"){const r=cu(t.gltfId,e);return W1.getOrCreate(r)}}}new T6;class hue{constructor(e){d(this,"context"),d(this,"mixers",[]),this.context=e}onDestroy(){this.mixers.forEach(e=>e.stopAllAction()),this.mixers.length=0}registerAnimationMixer(e){if(!e){console.warn("AnimationsRegistry.registerAnimationMixer called with null or undefined mixer");return}this.mixers.includes(e)||this.mixers.push(e)}unregisterAnimationMixer(e){if(!e)return;const t=this.mixers.indexOf(e);t!==-1&&this.mixers.splice(t,1)}}class Bg{static tryGetActionsFromMixer(e){return e._actions||null}static tryGetAnimationClipsFromObjectHierarchy(e,t){if(t||(t=new Array),e)e.animations&&t.push(...e.animations);else return t;if(e.children)for(const r of e.children)this.tryGetAnimationClipsFromObjectHierarchy(r,t);return t}static assignAnimationsFromFile(e,t){if(!e||!e.animations)return;for(let s=0;s<e.animations.length;s++){const o=e.animations[s];if(!(!o.tracks||o.tracks.length<=0))for(const a in o.tracks){const l=o.tracks[a],c=Xt.parseTrackName(l.name);let h=Xt.findNode(e.scene,c.nodeName);if(!h){const p=l.__objectName??l.name.substring(0,l.name.indexOf("."));if(h=e.scene.getObjectByProperty("uuid",p),!h)continue}let u=r(h);if(!u){if(!(t!=null&&t.createAnimationComponent)){console.warn("No AnimationComponent found in parent hierarchy of object and no 'createAnimationComponent' callback was provided in options.");continue}u=t.createAnimationComponent(e.scene,o)}u.addClip&&u.addClip(o)}}function r(s){var o;if(!s)return null;const a=(o=s.userData)==null?void 0:o.components;if(a&&a.length>0){for(let l=0;l<a.length;l++)if(a[l].isAnimationComponent===!0)return s}return r(s.parent)}}}const kg=[];function X1(n){kg.indexOf(n)===-1&&kg.push(n)}function uue(n){const e=kg.indexOf(n);e!==-1&&kg.splice(e,1)}const Dg=[];function mB(n){Dg.indexOf(n)===-1&&Dg.push(n)}function due(n){const e=Dg.indexOf(n);e!==-1&&Dg.splice(e,1)}function I6(n){globalThis.dispatchEvent(new CustomEvent("needle-xrsession-start",{detail:n}));for(let e=0;e<kg.length;e++)kg[e](n)}function R6(n){globalThis.dispatchEvent(new CustomEvent("needle-xrsession-end",{detail:n}));for(let e=0;e<Dg.length;e++)Dg[e](n)}const wr={Handedness:Object.freeze({NONE:"none",LEFT:"left",RIGHT:"right"}),ComponentState:Object.freeze({DEFAULT:"default",TOUCHED:"touched",PRESSED:"pressed"}),ComponentProperty:Object.freeze({BUTTON:"button",X_AXIS:"xAxis",Y_AXIS:"yAxis",STATE:"state"}),ComponentType:Object.freeze({TRIGGER:"trigger",SQUEEZE:"squeeze",TOUCHPAD:"touchpad",THUMBSTICK:"thumbstick",BUTTON:"button"}),ButtonTouchThreshold:.05,AxisTouchThreshold:.1,VisualResponseProperty:Object.freeze({TRANSFORM:"transform",VISIBILITY:"visibility"})};async function P6(n){const e=await fetch(n);if(e.ok)return e.json();throw new Error(e.statusText)}async function pue(n){if(!n)throw new Error("No basePath supplied");return await P6(`${n}/profilesList.json`)}async function mue(n,e,t=null,r=!0){if(!n)throw new Error("No xrInputSource supplied");if(!e)throw new Error("No basePath supplied");const s=await pue(e);let o;if(n.profiles.some(c=>{const h=s[c];return h&&(o={profileId:c,profilePath:`${e}/${h.path}`,deprecated:!!h.deprecated}),!!o}),!o){if(!t)throw new Error("No matching profile name found");const c=s[t];if(!c)throw new Error(`No matching profile name found and default profile "${t}" missing.`);o={profileId:t,profilePath:`${e}/${c.path}`,deprecated:!!c.deprecated}}const a=await P6(o.profilePath);let l;if(r){let c;if(n.handedness==="any"?c=a.layouts[Object.keys(a.layouts)[0]]:c=a.layouts[n.handedness],!c)throw new Error(`No matching handedness, ${n.handedness}, in profile ${o.profileId}`);c.assetPath&&(l=o.profilePath.replace("profile.json",c.assetPath))}return{profile:a,assetPath:l}}const fue={xAxis:0,yAxis:0,button:0,state:wr.ComponentState.DEFAULT};function gue(n=0,e=0){let t=n,r=e;if(Math.sqrt(n*n+e*e)>1){const s=Math.atan2(e,n);t=Math.cos(s),r=Math.sin(s)}return{normalizedXAxis:t*.5+.5,normalizedYAxis:r*.5+.5}}let vue=class{constructor(n){this.componentProperty=n.componentProperty,this.states=n.states,this.valueNodeName=n.valueNodeName,this.valueNodeProperty=n.valueNodeProperty,this.valueNodeProperty===wr.VisualResponseProperty.TRANSFORM&&(this.minNodeName=n.minNodeName,this.maxNodeName=n.maxNodeName),this.value=0,this.updateFromComponent(fue)}updateFromComponent({xAxis:n,yAxis:e,button:t,state:r}){const{normalizedXAxis:s,normalizedYAxis:o}=gue(n,e);switch(this.componentProperty){case wr.ComponentProperty.X_AXIS:this.value=this.states.includes(r)?s:.5;break;case wr.ComponentProperty.Y_AXIS:this.value=this.states.includes(r)?o:.5;break;case wr.ComponentProperty.BUTTON:this.value=this.states.includes(r)?t:0;break;case wr.ComponentProperty.STATE:this.valueNodeProperty===wr.VisualResponseProperty.VISIBILITY?this.value=this.states.includes(r):this.value=this.states.includes(r)?1:0;break;default:throw new Error(`Unexpected visualResponse componentProperty ${this.componentProperty}`)}}},yue=class{constructor(n,e){if(!n||!e||!e.visualResponses||!e.gamepadIndices||Object.keys(e.gamepadIndices).length===0)throw new Error("Invalid arguments supplied");this.id=n,this.type=e.type,this.rootNodeName=e.rootNodeName,this.touchPointNodeName=e.touchPointNodeName,this.visualResponses={},Object.keys(e.visualResponses).forEach(t=>{const r=new vue(e.visualResponses[t]);this.visualResponses[t]=r}),this.gamepadIndices=Object.assign({},e.gamepadIndices),this.values={state:wr.ComponentState.DEFAULT,button:this.gamepadIndices.button!==void 0?0:void 0,xAxis:this.gamepadIndices.xAxis!==void 0?0:void 0,yAxis:this.gamepadIndices.yAxis!==void 0?0:void 0}}get data(){return{id:this.id,...this.values}}updateFromGamepad(n){if(this.values.state=wr.ComponentState.DEFAULT,this.gamepadIndices.button!==void 0&&n.buttons.length>this.gamepadIndices.button){const e=n.buttons[this.gamepadIndices.button];this.values.button=e.value,this.values.button=this.values.button<0?0:this.values.button,this.values.button=this.values.button>1?1:this.values.button,e.pressed||this.values.button===1?this.values.state=wr.ComponentState.PRESSED:(e.touched||this.values.button>wr.ButtonTouchThreshold)&&(this.values.state=wr.ComponentState.TOUCHED)}this.gamepadIndices.xAxis!==void 0&&n.axes.length>this.gamepadIndices.xAxis&&(this.values.xAxis=n.axes[this.gamepadIndices.xAxis],this.values.xAxis=this.values.xAxis<-1?-1:this.values.xAxis,this.values.xAxis=this.values.xAxis>1?1:this.values.xAxis,this.values.state===wr.ComponentState.DEFAULT&&Math.abs(this.values.xAxis)>wr.AxisTouchThreshold&&(this.values.state=wr.ComponentState.TOUCHED)),this.gamepadIndices.yAxis!==void 0&&n.axes.length>this.gamepadIndices.yAxis&&(this.values.yAxis=n.axes[this.gamepadIndices.yAxis],this.values.yAxis=this.values.yAxis<-1?-1:this.values.yAxis,this.values.yAxis=this.values.yAxis>1?1:this.values.yAxis,this.values.state===wr.ComponentState.DEFAULT&&Math.abs(this.values.yAxis)>wr.AxisTouchThreshold&&(this.values.state=wr.ComponentState.TOUCHED)),Object.values(this.visualResponses).forEach(e=>{e.updateFromComponent(this.values)})}},Aue=class{constructor(n,e,t){if(!n)throw new Error("No xrInputSource supplied");if(!e)throw new Error("No profile supplied");this.xrInputSource=n,this.assetUrl=t,this.id=e.profileId,this.layoutDescription=e.layouts[n.handedness],this.components={},Object.keys(this.layoutDescription.components).forEach(r=>{const s=this.layoutDescription.components[r];this.components[r]=new yue(r,s)}),this.updateFromGamepad()}get gripSpace(){return this.xrInputSource.gripSpace}get targetRaySpace(){return this.xrInputSource.targetRaySpace}get data(){const n=[];return Object.values(this.components).forEach(e=>{n.push(e.data)}),n}updateFromGamepad(){Object.values(this.components).forEach(n=>{n.updateFromGamepad(this.xrInputSource.gamepad)})}};const Js=new C,B6=new C,k6=new Ce,bue=te("debuggizmos"),Wl=8947848,Xl=class{constructor(){}static isGizmo(n){return n[gB]!==void 0}static DrawLabel(n,e,t=.05,r=0,s,o,a){var l;if(!Xl.enabled)return null;s||(s=Wl);const c=((l=wt.active)==null?void 0:l.rigScale)??1,h=En.getTextLabel(r,e,t*c,s,o);return a instanceof ye&&a.add(h),h.position.x=n.x,h.position.y=n.y,h.position.z=n.z,h}static DrawRay(n,e,t=Wl,r=0,s=!0){if(!Xl.enabled)return;const o=En.getLine(r),a=o.geometry.getAttribute("position");a.setXYZ(0,n.x,n.y,n.z),Js.set(e.x,e.y,e.z).multiplyScalar(999999999),a.setXYZ(1,n.x+Js.x,n.y+Js.y,n.z+Js.z),a.needsUpdate=!0,o.material.color.set(t),o.material.depthTest=s,o.material.depthWrite=!1}static DrawDirection(n,e,t=Wl,r=0,s=!0,o=1){if(!Xl.enabled)return;const a=En.getLine(r),l=a.geometry.getAttribute("position");l.setXYZ(0,n.x,n.y,n.z),e.w!==void 0?(Js.set(0,0,-o),k6.set(e.x,e.y,e.z,e.w),Js.applyQuaternion(k6)):(Js.set(e.x,e.y,e.z),Js.multiplyScalar(o)),l.setXYZ(1,n.x+Js.x,n.y+Js.y,n.z+Js.z),l.needsUpdate=!0,a.material.color.set(t),a.material.depthTest=s,a.material.depthWrite=!1}static DrawLine(n,e,t=Wl,r=0,s=!0){if(!Xl.enabled)return;const o=En.getLine(r),a=o.geometry.getAttribute("position");a.setXYZ(0,n.x,n.y,n.z),a.setXYZ(1,e.x,e.y,e.z),a.needsUpdate=!0,o.material.color.set(t),o.material.depthTest=s,o.material.depthWrite=!1,o.material.fog=!1}static DrawWireSphere(n,e,t=Wl,r=0,s=!0){if(!Xl.enabled)return;const o=En.getSphere(e,r,!0);_p(o,n.x,n.y,n.z),o.material.color.set(t),o.material.depthTest=s,o.material.depthWrite=!1,o.material.fog=!1}static DrawSphere(n,e,t=Wl,r=0,s=!0){if(!Xl.enabled)return;const o=En.getSphere(e,r,!1);_p(o,n.x,n.y,n.z),o.material.color.set(t),o.material.depthTest=s,o.material.depthWrite=!1}static DrawWireBox(n,e,t=Wl,r=0,s=!0){if(!Xl.enabled)return;const o=En.getBox(r);o.position.set(n.x,n.y,n.z),o.scale.set(e.x,e.y,e.z),o.material.color.set(t),o.material.depthTest=s,o.material.wireframe=!0,o.material.depthWrite=!1,o.material.fog=!1}static DrawWireBox3(n,e=Wl,t=0,r=!0){if(!Xl.enabled)return;const s=En.getBox(t);s.position.copy(n.getCenter(Js)),s.scale.copy(n.getSize(Js)),s.material.color.set(e),s.material.depthTest=r,s.material.wireframe=!0,s.material.depthWrite=!1,s.material.fog=!1}static DrawArrow(n,e,t=Wl,r=0,s=!0,o=!1){if(!Xl.enabled)return;const a=En.getArrowHead(r);a.position.set(e.x,e.y,e.z),a.quaternion.setFromUnitVectors(this._up.set(0,1,0),Js.set(e.x,e.y,e.z).sub(B6.set(n.x,n.y,n.z)).normalize());const l=Js.set(e.x,e.y,e.z).sub(B6.set(n.x,n.y,n.z)).length()*.1;a.scale.set(l,l,l),a.material.color.set(t),a.material.depthTest=s,a.material.wireframe=o,this.DrawLine(n,e,t,r,s)}static DrawWireMesh(n){const e=En.getMesh(n.duration??0);"mesh"in n?(e.geometry=n.mesh.geometry,e.matrix.copy(n.mesh.matrixWorld)):(e.geometry=n.geometry,e.matrix.copy(n.matrix)),e.matrixAutoUpdate=!1,e.matrixWorldAutoUpdate=!1,e.material.color.set(n.color??Wl),e.material.depthTest=n.depthTest??!0,e.material.wireframe=!0}};let At=Xl;d(At,"enabled",!0),d(At,"_up",new C(0,1,0));const _ue=new qi(1,1,1);function fB(n=null){const e=new xe(n??14540253),t=new iI(_ue);return new gs(t,new Gi({color:e}))}const gB=Symbol("GizmoCache");class En{static ensureFont(){let e=Ni.FontLibrary.getFontFamily(this.familyName);if(!e){e=Ni.FontLibrary.addFontFamily(this.familyName);const t=e.addVariant("normal","normal","https://uploads.needle.tools/include/font-msdf.json","https://uploads.needle.tools/include/font.png");t?.addEventListener("ready",()=>{Ni.update()})}}static getTextLabel(e,t,r,s,o){this.ensureFont();let a=this.textLabelCache.pop(),l=1;o&&typeof o=="string"&&o?.length>=8&&o.startsWith("#")?(l=parseInt(o.substring(7),16)/255,o=o.substring(0,7),bue&&console.log(o,l)):typeof o=="object"&&o.a!==void 0&&(l=o.a);const c={boxSizing:"border-box",fontFamily:this.familyName,width:"auto",fontSize:r,color:s,lineHeight:1,backgroundColor:o??void 0,backgroundOpacity:l,textContent:t,borderRadius:.5*r,padding:.8*r,whiteSpace:"pre"};if(a)a.set(c);else{a=new fR(c);const h=this,u=a;u.setText=function(p){this.set({textContent:p}),h.tmuiNeedsUpdate=!0}}return this.tmuiNeedsUpdate=!0,this.registerTimedObject(kt.Current,a,e,this.textLabelCache),a}static getBox(e){let t=this.boxesCache.pop();if(!t){const r=new qi(1,1,1);t=new me(r)}return this.registerTimedObject(kt.Current,t,e,this.boxesCache),t}static getLine(e){let t=this.linesCache.pop();if(!t){t=new Sn;let r=t.geometry.getAttribute("position");r||(r=new nt(new Float32Array(2*3),3),t.geometry.setAttribute("position",r))}return t.frustumCulled=!1,this.registerTimedObject(kt.Current,t,e,this.linesCache),t}static getSphere(e,t,r){let s=this.spheresCache.pop();return s||(s=new me(new ja(1,8,8))),s.scale.set(e,e,e),s.material.wireframe=r,this.registerTimedObject(kt.Current,s,t,this.spheresCache),s}static getArrowHead(e){let t=this.arrowHeadsCache.pop();return t||(t=new me(new jn(0,.5,1,8))),this.registerTimedObject(kt.Current,t,e,this.arrowHeadsCache),t}static getMesh(e){let t=this.mesh.pop();return t||(t=new me,t.material=new $t),this.registerTimedObject(kt.Current,t,e,this.mesh),t}static registerTimedObject(e,t,r,s){const o=this.contextBeforeRenderCallbacks.get(e),a=this.contextPostRenderCallbacks.get(e);if(o){if(e.pre_render_callbacks[e.pre_render_callbacks.length-1]!==o){const l=e.pre_render_callbacks.indexOf(o);l>=0&&e.pre_render_callbacks.splice(l,1),e.pre_render_callbacks.push(o)}}else{const l=()=>{this.onBeforeRender(e,this.timedObjectsBuffer)};this.contextBeforeRenderCallbacks.set(e,l),e.pre_render_callbacks.push(l)}if(a){if(e.post_render_callbacks[e.post_render_callbacks.length-1]!==a){const l=e.post_render_callbacks.indexOf(a);l>=0&&e.post_render_callbacks.splice(l,1),e.post_render_callbacks.push(a)}}else{const l=()=>{this.onPostRender(e,this.timedObjectsBuffer,this.timesBuffer)};this.contextPostRenderCallbacks.set(e,l),e.post_render_callbacks.push(l)}t.traverse(l=>{l.layers.disableAll(),l.layers.enable(2)}),t.renderOrder=999999,t[gB]=s,t.isGizmo=!0,this.timedObjectsBuffer.push(t),r<=0&&e.currentFrameEvent>=Hi.OnBeforeRender?this.timesBuffer.push(0):this.timesBuffer.push(kt.Current.time.realtimeSinceStartup+r),e.scene.add(t)}static onBeforeRender(e,t){this.tmuiNeedsUpdate&&Ni.update();for(let r=0;r<t.length;r++){const s=t[r];if(e.mainCamera&&s instanceof Ni.MeshUIBaseElement){if(Jp(s))continue;const o=e.isInVR,a=!1,l=!o;Hv(s,e.mainCamera,a,l)}}}static onPostRender(e,t,r){const s=e.time.realtimeSinceStartup;for(let o=t.length-1;o>=0;o--){const a=t[o];s>r[o]&&(t.splice(o,1),r.splice(o,1),a.removeFromParent(),Jp(a)!=!0&&a[gB].push(a))}}}d(En,"familyName","needle-gizmos"),d(En,"linesCache",[]),d(En,"spheresCache",[]),d(En,"boxesCache",[]),d(En,"arrowHeadsCache",[]),d(En,"mesh",[]),d(En,"textLabelCache",[]),d(En,"timedObjectsBuffer",new Array),d(En,"timesBuffer",new Array),d(En,"contextPostRenderCallbacks",new Map),d(En,"contextBeforeRenderCallbacks",new Map),d(En,"tmuiNeedsUpdate",!1);const cr=te("debuginput");var q1=(n=>(n.Mouse="mouse",n.Touch="touch",n.Controller="controller",n.Hand="hand",n))(q1||{}),an=(n=>(n.PointerDown="pointerdown",n.PointerUp="pointerup",n.PointerMove="pointermove",n.KeyDown="keydown",n.KeyUp="keyup",n.KeyPressed="keypress",n))(an||{});class mh extends PointerEvent{constructor(e,t,r){super(e,r),d(this,"deviceIndex"),d(this,"origin"),d(this,"source"),d(this,"mode"),d(this,"_ray"),d(this,"space"),d(this,"isClick",!1),d(this,"isDoubleClick",!1),d(this,"_used",!1),d(this,"_pointerid"),d(this,"_pointerType"),d(this,"_type"),d(this,"metadata",{}),d(this,"intersections",new Array),d(this,"_immediatePropagationStopped",!1),d(this,"_propagationStopped",!1),this._pointerid=r.pointerId,this._pointerType=r.pointerType,this._type=e,this.deviceIndex=r.deviceIndex,this.origin=r.origin,this.source=t,this.mode=r.mode,this._ray=r.ray,this.space=r.device}get ray(){return this._ray||(this._ray=new co(this.space.worldPosition.clone(),this.space.worldForward.clone())),this._ray}set ray(e){this._ray=e}get hasRay(){return this._ray!==void 0}get used(){return this._used}use(){this._used=!0}get pointerId(){return this._pointerid}get pointerType(){return this._pointerType}get type(){return this._type}get immediatePropagationStopped(){return this._immediatePropagationStopped}get propagationStopped(){return this._immediatePropagationStopped||this._propagationStopped}stopImmediatePropagation(){var e;this._immediatePropagationStopped=!0,super.stopImmediatePropagation(),(e=this.source)==null||e.stopImmediatePropagation()}stopPropagation(){var e;this._propagationStopped=!0,super.stopPropagation(),(e=this.source)==null||e.stopPropagation(),cr&&console.warn("Stop propagation...",this.pointerId,this.pointerType)}}class Xy extends KeyboardEvent{constructor(e,t,r){super(e,r),d(this,"source"),this.source=t}stopImmediatePropagation(){var e;super.stopImmediatePropagation(),(e=this.source)==null||e.stopImmediatePropagation()}}class xue{constructor(e){d(this,"key"),d(this,"keyType"),d(this,"source"),this.key=e.key,this.keyType=e.type,this.source=e}}var ql=(n=>(n[n.Early=-100]="Early",n[n.Default=0]="Default",n[n.Late=100]="Late",n))(ql||{});class D6{constructor(e){d(this,"_eventListeners",{}),d(this,"_doubleClickTimeThreshold",.2),d(this,"_longPressTimeThreshold",1),d(this,"_specialCursorTrigger",0),d(this,"context"),d(this,"_pointerDown",[!1]),d(this,"_pointerUp",[!1]),d(this,"_pointerClick",[!1]),d(this,"_pointerDoubleClick",[!1]),d(this,"_pointerPressed",[!1]),d(this,"_pointerPositions",[new Z]),d(this,"_pointerPositionsLastFrame",[new Z]),d(this,"_pointerPositionsDelta",[new Z]),d(this,"_pointerPositionsRC",[new Z]),d(this,"_pointerPositionDown",[new Z]),d(this,"_pointerDownTime",[]),d(this,"_pointerUpTime",[]),d(this,"_pointerUpTimestamp",[]),d(this,"_pointerIds",[]),d(this,"_pointerTypes",[""]),d(this,"_mouseWheelChanged",[!1]),d(this,"_mouseWheelDeltaY",[0]),d(this,"_pointerEvent",[]),d(this,"_pointerUsed",[]),d(this,"_pointerSpace",[]),d(this,"_pressedStack",new Map),d(this,"_htmlEventSource"),d(this,"onLostFocus",()=>{for(const t in this.keysPressed)this.keysPressed[t].pressed=!1}),d(this,"onEndOfFrame",()=>{for(let t=0;t<this._pointerUp.length;t++)this._pointerUp[t]=!1;for(let t=0;t<this._pointerDown.length;t++)this._pointerDown[t]=!1;for(let t=0;t<this._pointerClick.length;t++)this._pointerClick[t]=!1;for(let t=0;t<this._pointerDoubleClick.length;t++)this._pointerDoubleClick[t]=!1;for(const t of this._pointerPositionsDelta)t.set(0,0);for(let t=0;t<this._mouseWheelChanged.length;t++)this._mouseWheelChanged[t]=!1;for(let t=0;t<this._mouseWheelDeltaY.length;t++)this._mouseWheelDeltaY[t]=0}),d(this,"onContextMenu",t=>{this.canReceiveInput(t)!==!1&&t instanceof PointerEvent&&t.pointerType}),d(this,"keysPressed",{}),d(this,"onKeyDown",t=>{if(cr&&console.log(`key down ${t.code}, ${this.context.application.hasFocus}`,t),!this.context.application.hasFocus)return;const r=this.keysPressed[t.code];if(r&&r.pressed)return;this.keysPressed[t.code]={pressed:!0,frame:this.context.time.frameCount+1,startFrame:this.context.time.frameCount+1,key:t.key,code:t.code};const s=new Xy("keydown",t,t);this.onDispatchEvent(s)}),d(this,"onKeyPressed",t=>{if(!this.context.application.hasFocus)return;const r=this.keysPressed[t.code];if(!r)return;r.pressed=!0,r.frame=this.context.time.frameCount+1;const s=new Xy("keypress",t,t);this.onDispatchEvent(s)}),d(this,"onKeyUp",t=>{if(!this.context.application.hasFocus)return;const r=this.keysPressed[t.code];if(!r)return;r.pressed=!1,r.frame=this.context.time.frameCount+1;const s=new Xy("keyup",t,t);this.onDispatchEvent(s)}),d(this,"onWheelWindow",t=>{document.pointerLockElement&&this.onMouseWheel(t)}),d(this,"onMouseWheel",t=>{if(this.canReceiveInput(t)===!1)return;this._mouseWheelDeltaY.length<=0&&this._mouseWheelDeltaY.push(0),this._mouseWheelChanged.length<=0&&this._mouseWheelChanged.push(!1),this._mouseWheelChanged[0]=!0;const r=this._mouseWheelDeltaY[0];this._mouseWheelDeltaY[0]=r+t.deltaY}),d(this,"onPointerDown",t=>{if(this.context.isInAR||this.canReceiveInput(t)===!1)return;t.target instanceof HTMLElement&&t.target.setPointerCapture(t.pointerId);const r=this.getPointerId(t);cr&&rn(`pointer down #${r}, identifier:${t.pointerId}`);const s=this.getAndUpdateSpatialObjectForScreenPosition(r,t.clientX,t.clientY),o=new mh("pointerdown",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:r,button:t.button,clientX:t.clientX,clientY:t.clientY,pointerType:t.pointerType,buttonName:this.getButtonName(t),device:s,pressure:t.pressure});this.onDown(o)}),d(this,"onPointerMove",t=>{if(this.context.isInAR)return;let r=t.button;t.pointerType==="mouse"&&(r=this.getFirstPressedButtonForPointer(0)??0);const s=this.getPointerId(t,r);r===-1&&(r=s);const o=this.getAndUpdateSpatialObjectForScreenPosition(s,t.clientX,t.clientY),a=new mh("pointermove",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:s,button:r,clientX:t.clientX,clientY:t.clientY,pointerType:t.pointerType,buttonName:this.getButtonName(t),device:o,pressure:t.pressure});this.onMove(a)}),d(this,"onPointerCancel",t=>{this.context.isInAR||(cr&&console.log("Pointer cancel",t),this.onPointerUp(t))}),d(this,"onPointerUp",t=>{if(this.context.isInAR)return;t.target instanceof HTMLElement&&t.target.releasePointerCapture(t.pointerId);const r=this.getPointerId(t),s=new mh("pointerup",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:r,button:t.button,clientX:t.clientX,clientY:t.clientY,pointerType:t.pointerType,buttonName:this.getButtonName(t),device:this.getAndUpdateSpatialObjectForScreenPosition(r,t.clientX,t.clientY),pressure:t.pressure});this.onUp(s),this._pointerIds[r]=-1,cr&&console.log("ID="+r,"PointerId="+t.pointerId,"ALL:",[...this._pointerIds])}),d(this,"onTouchStart",t=>{if(this.context.isInAR)for(let r=0;r<t.changedTouches.length;r++){const s=t.changedTouches[r],o=this.getPointerIndex(s.identifier),a=this.getAndUpdateSpatialObjectForScreenPosition(o,s.clientX,s.clientY),l=new mh("pointerdown",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:o,button:0,clientX:s.clientX,clientY:s.clientY,pointerType:"touch",buttonName:"unknown",device:a,pressure:s.force});this.onDown(l)}}),d(this,"onTouchMove",t=>{if(this.context.isInAR)for(let r=0;r<t.changedTouches.length;r++){const s=t.changedTouches[r],o=this.getPointerIndex(s.identifier),a=this.getAndUpdateSpatialObjectForScreenPosition(o,s.clientX,s.clientY),l=new mh("pointermove",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:o,button:0,clientX:s.clientX,clientY:s.clientY,pointerType:"touch",buttonName:"unknown",device:a,pressure:s.force});this.onMove(l)}}),d(this,"onTouchEnd",t=>{if(this.context.isInAR)for(let r=0;r<t.changedTouches.length;r++){const s=t.changedTouches[r],o=this.getPointerIndex(s.identifier),a=new mh("pointerup",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:o,button:0,clientX:s.clientX,clientY:s.clientY,pointerType:"touch",buttonName:"unknown",device:this.getAndUpdateSpatialObjectForScreenPosition(o,s.clientX,s.clientY),pressure:s.force});this.onUp(a),this._pointerIds[o]=-1}}),d(this,"tempNearPlaneVector",new C),d(this,"tempFarPlaneVector",new C),d(this,"tempLookMatrix",new ve),this.context=e,this.context.post_render_callbacks.push(this.onEndOfFrame)}addEventListener(e,t,r){if(this._eventListeners[e]||(this._eventListeners[e]=[]),!t||typeof t!="function"){console.error("Invalid call to addEventListener: callback is required and must be a function!");return}r?r={...r}:r={};let s=0;r?.queue!=null&&(s=r.queue);const o=this._eventListeners[e],a=o.find(l=>l.priority===s);a?a.listeners.push({callback:t,options:r}):(o.push({priority:s,listeners:[{callback:t,options:r}]}),o.sort((l,c)=>l.priority-c.priority))}removeEventListener(e,t,r){if(!this._eventListeners[e]||!t)return;const s=this._eventListeners[e];if(r?.queue!=null){const o=s.find(l=>l.priority===r.queue);if(!o)return;const a=o.listeners.findIndex(l=>l.callback===t);a>=0&&o.listeners.splice(a,1)}else for(const o of s){const a=o.listeners.findIndex(l=>l.callback===t);a>=0&&o.listeners.splice(a,1)}}dispatchEvent(e){var t,r,s,o;let a=!1;if(e instanceof Xy){const l=this._eventListeners[e.type];if(l)for(const c of l)for(let h=0;h<c.listeners.length;h++){const u=c.listeners[h];if((r=(t=u.options)==null?void 0:t.signal)!=null&&r.aborted){c.listeners.splice(h,1),h--;continue}u.options.once&&(c.listeners.splice(h,1),h--),u.callback(e)}}if(e instanceof mh){const l=this._eventListeners[e.type];if(l)for(const c of l){if(a)break;for(let h=0;h<c.listeners.length;h++){const u=c.listeners[h];if((o=(s=u.options)==null?void 0:s.signal)!=null&&o.aborted){c.listeners.splice(h,1),h--;continue}if(e.immediatePropagationStopped){a=!0,cr&&console.log("immediatePropagationStopped",e.type);break}else e.propagationStopped&&(a=!0,cr&&console.log("propagationStopped",e.type));u.options.once&&(c.listeners.splice(h,1),h--),u.callback(e)}}}}get mousePosition(){return this._pointerPositions[0]}get mousePositionRC(){return this._pointerPositionsRC[0]}get mouseDown(){return this._pointerDown[0]}get mouseUp(){return this._pointerUp[0]}get mouseClick(){return this._pointerClick[0]}get mouseDoubleClick(){return this._pointerDoubleClick[0]}get mousePressed(){return this._pointerPressed[0]}get mouseWheelChanged(){return this.getMouseWheelChanged(0)}setCursorPointer(){this._specialCursorTrigger+=1,this.context.domElement.style.cursor="pointer"}setCursorNormal(){this._specialCursorTrigger-=1,this._specialCursorTrigger=Math.max(0,this._specialCursorTrigger),this._specialCursorTrigger===0&&(this.context.domElement.style.cursor="default")}setPointerUsed(e,t=!0){if(e>=this._pointerUsed.length){if(e>=this._pointerIds.length)return;for(;this._pointerUsed.length<=e;)this._pointerUsed.push(!1)}this._pointerUsed[e]=t}getPointerUsed(e){return e>=this._pointerUsed.length?!1:this._pointerUsed[e]}getPointerPressedCount(){let e=0;for(let t=0;t<this._pointerPressed.length;t++)this._pointerPressed[t]&&e++;return e}getPointerPosition(e){return e>=this._pointerPositions.length?null:this._pointerPositions[e]}getPointerPositionLastFrame(e){return e>=this._pointerPositionsLastFrame.length?null:this._pointerPositionsLastFrame[e]}getPointerPositionDelta(e){return e>=this._pointerPositionsDelta.length?null:this._pointerPositionsDelta[e]}getPointerPositionRC(e){return e>=this._pointerPositionsRC.length?null:this._pointerPositionsRC[e]}getPointerDown(e){return e>=this._pointerDown.length?!1:this._pointerDown[e]}getPointerUp(e){return e>=this._pointerUp.length?!1:this._pointerUp[e]}getPointerPressed(e){return e>=this._pointerPressed.length?!1:this._pointerPressed[e]}getPointerClicked(e){return e>=this._pointerClick.length?!1:this._pointerClick[e]}getPointerDoubleClicked(e){return e>=this._pointerDoubleClick.length?!1:this._pointerDoubleClick[e]}getPointerDownTime(e){return e>=this._pointerDownTime.length?-1:this._pointerDownTime[e]}getPointerUpTime(e){return e>=this._pointerUpTime.length?-1:this._pointerUpTime[e]}getPointerLongPress(e){return e>=this._pointerDownTime.length?!1:this.getPointerPressed(e)&&this.context.time.time-this._pointerDownTime[e]>this._longPressTimeThreshold}getIsMouse(e){return e<0||e>=this._pointerTypes.length?!1:this._pointerTypes[e]==="mouse"}getIsTouch(e){return e<0||e>=this._pointerTypes.length?!1:this._pointerTypes[e]==="touch"}getTouchesPressedCount(){let e=0;for(let t=0;t<this._pointerPressed.length;t++)this._pointerPressed[t]&&this.getIsTouch(t)&&e++;return e}getMouseWheelChanged(e=0){return e>=this._mouseWheelChanged.length?!1:this._mouseWheelChanged[e]}getMouseWheelDeltaY(e=0){return e>=this._mouseWheelDeltaY.length?0:this._mouseWheelDeltaY[e]}getPointerEvent(e){if(!(e>=this._pointerEvent.length))return this._pointerEvent[e]??void 0}*foreachPointerId(e){for(let t=0;t<this._pointerTypes.length;t++)if(this._pointerIsActive(t)){if(e!==void 0){const r=this._pointerTypes[t];if(Array.isArray(e)){let s=!1;for(const o of e)if(r===o){s=!0;break}if(!s)continue}else if(e!==r)continue}yield t}}*foreachTouchId(){for(let e=0;e<this._pointerTypes.length;e++)this._pointerTypes[e]==="touch"&&this._pointerIsActive[e]&&(yield e)}_pointerIsActive(e){return e<0?!1:this._pointerPressed[e]||this._pointerDown[e]||this._pointerUp[e]}onDownButton(e,t){let r=this._pressedStack.get(e);r||(r=[],this._pressedStack.set(e,r)),r.push(t)}onReleaseButton(e,t){const r=this._pressedStack.get(e);if(!r)return;const s=r.indexOf(t);s>=0&&r.splice(s,1)}getFirstPressedButtonForPointer(e){const t=this._pressedStack.get(e);if(t)return t[0]}getLatestPressedButtonForPointer(e){const t=this._pressedStack.get(e);if(t)return t[t.length-1]}getKeyDown(){for(const e in this.keysPressed){const t=this.keysPressed[e];if(t.startFrame===this.context.time.frameCount)return t.key}return null}getKeyPressed(){for(const e in this.keysPressed){const t=this.keysPressed[e];if(t.pressed)return t.key}return null}isKeyDown(e){var t;if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const r=this.getCodeForCommonKeyName(e);if(r!==null){for(const s of r)if(this.isKeyDown(s))return!0;return!1}return((t=this.keysPressed[e])==null?void 0:t.startFrame)===this.context.time.frameCount&&this.keysPressed[e].pressed}isKeyUp(e){var t;if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const r=this.getCodeForCommonKeyName(e);if(r!==null){for(const s of r)if(this.isKeyUp(s))return!0;return!1}return((t=this.keysPressed[e])==null?void 0:t.frame)===this.context.time.frameCount&&!this.keysPressed[e].pressed}isKeyPressed(e){var t;if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const r=this.getCodeForCommonKeyName(e);if(r!==null){for(const s of r)if(this.isKeyPressed(s))return!0;return!1}return(t=this.keysPressed[e])==null?void 0:t.pressed}getCodeForCommonKeyName(e){if(e.length===1){if(e>="0"&&e<="9")return["Digit"+e];if(e>="a"&&e<="z")return["Key"+e.toUpperCase()];if(e==" ")return["Space"]}switch(e){case"shift":case"Shift":return["ShiftLeft","ShiftRight"];case"control":case"Control":return["ControlLeft","ControlRight"];case"alt":case"Alt":return["AltLeft","AltRight"]}return null}createInputEvent(e){switch(e.type){case"pointerdown":cr&&rn("Create Pointer down"),this.onDownButton(e.deviceIndex,e.button),this.onDown(e);break;case"pointermove":cr&&rn("Create Pointer move"),this.onMove(e);break;case"pointerup":cr&&rn("Create Pointer up"),this.onUp(e),this.onReleaseButton(e.deviceIndex,e.button);break}}convertScreenspaceToRaycastSpace(e){return e.x=(e.x-this.context.domX)/this.context.domWidth*2-1,e.y=-((e.y-this.context.domY)/this.context.domHeight)*2+1,e}bindEvents(){this.unbindEvents(),this._htmlEventSource=this.context.renderer.domElement,window.addEventListener("contextmenu",this.onContextMenu),this._htmlEventSource.addEventListener("pointerdown",this.onPointerDown,{passive:!0}),window.addEventListener("pointermove",this.onPointerMove,{passive:!0,capture:!0}),window.addEventListener("pointerup",this.onPointerUp,{passive:!0}),window.addEventListener("pointercancel",this.onPointerCancel,{passive:!0}),window.addEventListener("touchstart",this.onTouchStart,{passive:!0}),window.addEventListener("touchmove",this.onTouchMove,{passive:!0}),window.addEventListener("touchend",this.onTouchEnd,{passive:!0}),this._htmlEventSource.addEventListener("wheel",this.onMouseWheel,{passive:!0}),window.addEventListener("wheel",this.onWheelWindow,{passive:!0}),window.addEventListener("keydown",this.onKeyDown,!1),window.addEventListener("keypress",this.onKeyPressed,!1),window.addEventListener("keyup",this.onKeyUp,!1),window.addEventListener("blur",this.onLostFocus)}unbindEvents(){var e,t;window.removeEventListener("contextmenu",this.onContextMenu),(e=this._htmlEventSource)==null||e.removeEventListener("pointerdown",this.onPointerDown),window.removeEventListener("pointermove",this.onPointerMove),window.removeEventListener("pointerup",this.onPointerUp),window.removeEventListener("pointercancel",this.onPointerCancel),(t=this._htmlEventSource)==null||t.removeEventListener("wheel",this.onMouseWheel,!1),window.removeEventListener("wheel",this.onWheelWindow,!1),window.removeEventListener("keydown",this.onKeyDown,!1),window.removeEventListener("keypress",this.onKeyPressed,!1),window.removeEventListener("keyup",this.onKeyUp,!1),window.removeEventListener("blur",this.onLostFocus)}dispose(){const e=this.context.post_render_callbacks.indexOf(this.onEndOfFrame);e>=0&&this.context.post_render_callbacks.splice(e,1),this.unbindEvents()}canReceiveInput(e){var t;return e.target===((t=this.context.renderer)==null?void 0:t.domElement)||e.target===this.context.domElement||this.context.isInAR||this.context.isInAR&&e.target===document.body&&gp()?!0:(cr&&console.warn("CanReceiveInput:False for",e.target),!1)}getPointerId(e,t){return e.pointerType==="mouse"?0+(t??e.button):this.getPointerIndex(e.pointerId)}getButtonName(e){const t=e.button;if(e.pointerType==="mouse")switch(t){case 0:return"left";case 1:return"middle";case 2:return"right"}return"unknown"}getAndUpdateSpatialObjectForScreenPosition(e,t,r){let s=this._pointerSpace[e];s||(s=new ye,this._pointerSpace[e]=s),this._pointerSpace[e]=s;const o=this.context.mainCamera;if(o){const a=this.tempNearPlaneVector.set(t,r,-1);this.convertScreenspaceToRaycastSpace(a);const l=this.tempFarPlaneVector.set(a.x,a.y,1);a.unproject(o),l.unproject(o);const c=o.worldUp||pi(0,1,0).applyQuaternion(Mi(o));this.tempLookMatrix.lookAt(l,a,c),s.position.set(a.x,a.y,a.z),s.quaternion.setFromRotationMatrix(this.tempLookMatrix)}return s}isInRect(e){if(this.context.isInXR)return!0;const t=this.context.domElement.getBoundingClientRect(),r=e.clientX,s=e.clientY,o=r>=t.x&&r<=t.right&&s>=t.y&&s<=t.bottom;return cr&&!o&&console.log("Not in rect",t,r,s),o}onDown(e){const t=e.pointerId;if(this.getPointerPressed(t)&&console.warn(`pointerId is already pressed: ${t}`,cr?e:""),cr&&console.log(e.pointerType,"DOWN",t),!!this.isInRect(e)){for(this.setPointerState(t,this._pointerPressed,!0),this.setPointerState(t,this._pointerDown,!0),this.setPointerStateT(t,this._pointerEvent,e.source);t>=this._pointerTypes.length;)this._pointerTypes.push(e.pointerType);for(this._pointerTypes[t]=e.pointerType;t>=this._pointerPositionDown.length;)this._pointerPositionDown.push(new Z);for(this._pointerPositionDown[t].set(e.clientX,e.clientY);t>=this._pointerPositions.length;)this._pointerPositions.push(new Z);this._pointerPositions[t].set(e.clientX,e.clientY),t>=this._pointerDownTime.length&&this._pointerDownTime.push(0),this._pointerDownTime[t]=this.context.time.time,this.updatePointerPosition(e),this.onDispatchEvent(e)}}onMove(e){const t=e.pointerId,r=this.getPointerPressed(t);r===!1&&!this.isInRect(e)||e.pointerType==="touch"&&!r||(this.updatePointerPosition(e),this.setPointerStateT(t,this._pointerEvent,e.source),this.onDispatchEvent(e))}onUp(e){const t=e.pointerId;if(!this.getPointerPressed(t)){cr&&console.log(e.pointerType,"UP",t,"was not down");return}for(cr&&console.log(e.pointerType,"UP",t),this.setPointerState(t,this._pointerPressed,!1),this.setPointerStateT(t,this._pointerEvent,e.source),this.setPointerState(t,this._pointerUp,!0);t>=this._pointerUsed.length;)this._pointerUsed.push(!1);if(this.setPointerState(t,this._pointerUsed,!1),this.updatePointerPosition(e),!this._pointerPositionDown[t]){cr&&Di("Received pointer up event without matching down event for button: "+t),console.warn("Received pointer up event without matching down event for button: "+t);return}const r=e.clientX-this._pointerPositionDown[t].x,s=e.clientY-this._pointerPositionDown[t].y;if(t>=this._pointerUpTime.length&&this._pointerUpTime.push(-99),Math.abs(r)<5&&Math.abs(s)<5){cr&&console.log("CLICK",t),this.setPointerState(t,this._pointerClick,!0),e.isClick=!0;const o=this._pointerUpTime[t],a=this.context.time.time-o;a<this._doubleClickTimeThreshold&&a>0&&(this.setPointerState(t,this._pointerDoubleClick,!0),e.isDoubleClick=!0)}this._pointerUpTime[t]=this.context.time.time,this.onDispatchEvent(e)}updatePointerPosition(e){const t=e.pointerId;for(;t>=this._pointerPositions.length;)this._pointerPositions.push(new Z);for(;t>=this._pointerPositionsLastFrame.length;)this._pointerPositionsLastFrame.push(new Z);for(;t>=this._pointerPositionsDelta.length;)this._pointerPositionsDelta.push(new Z);const r=this._pointerPositionsLastFrame[t];r.copy(this._pointerPositions[t]);const s=this._pointerPositionsDelta[t];let o=e.clientX-r.x,a=e.clientY-r.y;if(e.source instanceof MouseEvent||e.source instanceof TouchEvent){const u=e.source;o===0&&u.movementX!==0&&(o=u.movementX||0),a===0&&u.movementY!==0&&(a=u.movementY||0)}s.x+=o,s.y+=a,this._pointerPositions[t].x=e.clientX,this._pointerPositions[t].y=e.clientY;const l=e.clientX,c=e.clientY;for(;t>=this._pointerPositionsRC.length;)this._pointerPositionsRC.push(new Z);const h=this._pointerPositionsRC[t];h.set(l,c),this.convertScreenspaceToRaycastSpace(h)}getPointerIndex(e){let t=-1;for(let r=0;r<this._pointerIds.length;r++){if(this._pointerIds[r]===e)return r;t===-1&&this._pointerIds[r]===-1&&(t=r)}return t!==-1?(this._pointerIds[t]=e,t):(cr&&console.log("PUSH pointerId:",e),this._pointerIds.push(e),this._pointerIds.length-1)}setPointerState(e,t,r){t[e]=r}setPointerStateT(e,t,r){return t[e]=r,r}onDispatchEvent(e){const t=kt.Current;try{kt.Current=this.context,this.dispatchEvent(e)}finally{kt.Current=t}}}const Y1=new ve().makeRotationY(Math.PI),Sa=new Ce().setFromAxisAngle(new C(0,1,0),Math.PI),wue=te("debugwebxr");class Sue{constructor(){if(d(this,"priority",-1e5),d(this,"gameObject"),this.gameObject=new ye,this.gameObject.name="Implicit XR Rig",wue){const e=fB(16733661);e.position.y+=.5,this.gameObject.add(e)}}isXRRig(){return!0}get isActive(){return this.gameObject.visible}}const Uu=te("debugwebxr"),J1=te("debugcustomgesture"),Cue="https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles",Eue="generic-trigger";class vB{constructor(e,t,r){d(this,"xr"),d(this,"inputSource"),d(this,"index",0),d(this,"emitEvents",!0),d(this,"_connected",!0),d(this,"_isTracking",!1),d(this,"_hitTestSource"),d(this,"_hasSelectEvent",!1),d(this,"_handJointPoses",new Map),d(this,"_gripPosition",new C),d(this,"_gripQuaternion",new Ce),d(this,"_linearVelocity",new C),d(this,"_rayPosition",new C),d(this,"_rayQuaternion",new Ce),d(this,"_gripWorldPosition",new C),d(this,"_gripWorldQuaternion",new Ce),d(this,"_rayWorldPosition",new C),d(this,"_rayWorldQuaternion",new Ce),d(this,"_ray"),d(this,"_object"),d(this,"model",null),d(this,"_debugAxesHelper",new Po(.2)),d(this,"onPointerHits",l=>{}),d(this,"_needleGamepadButtons",{}),d(this,"_buttonMap",new Map),d(this,"_motioncontroller"),d(this,"_layout"),d(this,"getMotionController"),d(this,"_selectButtonIndex"),d(this,"_squeezeButtonIndex"),d(this,"onSelectStart",l=>{var c,h,u,p;if(this.inputSource!==l.inputSource)return;this.onUpdateFrame(l.frame),this._hasSelectEvent=!0;const m=(c=this._layout)==null?void 0:c.selectComponentId,f=(p=(u=(h=this._layout)==null?void 0:h.components[m])==null?void 0:u.gamepadIndices)==null?void 0:p.button;f!==void 0&&(this._selectButtonIndex=f),!J1&&(Uu&&At.DrawDirection(this.rayWorldPosition,pi(0,.01,1).applyQuaternion(this.rayWorldQuaternion),16711680,10),this.emitPointerEvent(an.PointerDown,this._selectButtonIndex||0,"xr-standard-trigger",!0,l))}),d(this,"onSelectEnd",l=>{J1||this.inputSource===l.inputSource&&this.emitPointerEvent(an.PointerUp,this._selectButtonIndex||0,"xr-standard-trigger",!0,l)}),d(this,"onSequeezeStart",l=>{var c,h,u;this.inputSource===l.inputSource&&(this._squeezeButtonIndex=(u=(h=(c=this._layout)==null?void 0:c.components["xr-standard-squeeze"])==null?void 0:h.gamepadIndices)==null?void 0:u.button,this._squeezeButtonIndex!==void 0&&(Uu&&At.DrawDirection(this.rayWorldPosition,pi(0,.01,1).applyQuaternion(this.rayWorldQuaternion),255,10),this.emitPointerEvent(an.PointerDown,this._squeezeButtonIndex||0,"xr-standard-squeeze",!0,l)))}),d(this,"onSequeezeEnd",l=>{this.inputSource===l.inputSource&&this._squeezeButtonIndex!==void 0&&this.emitPointerEvent(an.PointerUp,this._squeezeButtonIndex||0,"xr-standard-squeeze",!0,l)}),d(this,"states",{}),d(this,"_didMoveLastFrame",!1),d(this,"_lastPointerMovePosition",new C),d(this,"_lastPointerMoveQuaternion",new Ce),d(this,"pointerInit");var s,o,a;this.xr=e,this.inputSource=t,this.index=r,this._object=new ye,Uu&&this._object.add(this._debugAxesHelper),this.xr.context.scene.add(this._object),this._ray=new co,this.pointerInit={origin:this,pointerType:this.hand?"hand":"controller",deviceIndex:this.index,pointerId:-1,mode:this.inputSource.targetRayMode,ray:this._ray,device:this._object,buttonName:"none"},this.initialize(),this.subscribeEvents(),this.xr.mode==="immersive-ar"&&this.inputSource.targetRayMode==="tracked-pointer"&&((a=(o=(s=this.xr.session).requestHitTestSourceForTransientInput)==null?void 0:o.call(s,{profile:this.inputSource.profiles[0],offsetRay:new XRRay}))==null||a.then(l=>this._hitTestSource=l))}get context(){return this.xr.context}get connected(){return this._connected}get isTracking(){return this._isTracking}get gamepad(){return this.inputSource.gamepad}get isHand(){return this.inputSource.hand!=null}get hand(){return this.inputSource.hand}get handObject(){return this.context.renderer.xr.getHand(this.index)}get profiles(){return this.inputSource.profiles}get layout(){return this._layout}get targetRayMode(){return this.inputSource.targetRayMode}get targetRaySpace(){return this.inputSource.targetRaySpace}get gripSpace(){return this.inputSource.gripSpace}get side(){return this.inputSource.handedness}get isRight(){return this.side==="right"}get isLeft(){return this.side==="left"}get hitTestSource(){return this._hitTestSource}get hasSelectEvent(){return this._hasSelectEvent}getHitTest(){return this.xr.getHitTest(this)}getHandJointPose(e){var t,r;if(!this.hand||!((t=this.xr.frame)!=null&&t.getJointPose)||!this.xr.referenceSpace)return null;let s=(r=this._handJointPoses)==null?void 0:r.get(e);return s||(s=this.xr.frame.getJointPose(e,this.xr.referenceSpace),s&&this._handJointPoses.set(e,s),s)}get gripPosition(){return pi(this._gripPosition).applyMatrix4(Y1)}get gripQuaternion(){return bp(this._gripQuaternion).premultiply(Sa)}get gripLinearVelocity(){return pi(this._linearVelocity).applyQuaternion(Sa)}get rayPosition(){return pi(this._rayPosition).applyMatrix4(Y1)}get rayQuaternion(){return bp(this._rayQuaternion).premultiply(Sa)}get gripWorldPosition(){return pi(this._gripWorldPosition)}get gripWorldQuaternion(){return bp(this._gripWorldQuaternion)}get rayWorldPosition(){return pi(this._rayWorldPosition)}updateRayWorldPosition(){var e;const t=(e=this.xr.context.mainCamera)==null?void 0:e.parent;this._rayWorldPosition.copy(this._rayPosition),t&&this._rayWorldPosition.applyMatrix4(t.matrixWorld)}get rayWorldQuaternion(){return bp(this._rayWorldQuaternion)}updateRayWorldQuaternion(){var e;const t=(e=this.xr.context.mainCamera)==null?void 0:e.parent,r=t?Mi(t):void 0;this._rayWorldQuaternion.copy(this._rayQuaternion).multiply(Sa),r&&this._rayWorldQuaternion.premultiply(r)}get ray(){return this._ray.origin.copy(this.rayWorldPosition),this._ray.direction.copy(pi(0,0,1).applyQuaternion(this.rayWorldQuaternion)),this._ray}get object(){return this._object}async getModelUrl(){var e;return(e=this.getMotionController)==null?void 0:e.then(t=>t?.assetUrl||null)}onUpdate(e){this.onUpdateFrame(e),this.updateInputEvents(),this.onUpdateMove()}onRenderDebug(){var e;At.DrawWireSphere(this.rayWorldPosition,.02),At.DrawDirection(this.rayWorldPosition,pi(0,0,10).applyQuaternion(this.rayWorldQuaternion));const t=this.gripWorldPosition.sub(this.object.worldForward.multiplyScalar(.1)),r=this.inputSource.profiles.join(`
|
|
5151
|
+
*/var rue=function(n){return n!=null&&(w6(n)||sue(n)||!!n._isBuffer)};function w6(n){return!!n.constructor&&typeof n.constructor.isBuffer=="function"&&n.constructor.isBuffer(n)}function sue(n){return typeof n.readFloatLE=="function"&&typeof n.slice=="function"&&w6(n.slice(0,0))}(function(){var n=nue,e=x6.utf8,t=rue,r=x6.bin,s=function(o,a){o.constructor==String?a&&a.encoding==="binary"?o=r.stringToBytes(o):o=e.stringToBytes(o):t(o)?o=Array.prototype.slice.call(o,0):!Array.isArray(o)&&o.constructor!==Uint8Array&&(o=o.toString());for(var l=n.bytesToWords(o),c=o.length*8,h=1732584193,u=-271733879,p=-1732584194,m=271733878,f=0;f<l.length;f++)l[f]=(l[f]<<8|l[f]>>>24)&16711935|(l[f]<<24|l[f]>>>8)&4278255360;l[c>>>5]|=128<<c%32,l[(c+64>>>9<<4)+14]=c;for(var g=s._ff,v=s._gg,y=s._hh,A=s._ii,f=0;f<l.length;f+=16){var _=h,b=u,x=p,E=m;h=g(h,u,p,m,l[f+0],7,-680876936),m=g(m,h,u,p,l[f+1],12,-389564586),p=g(p,m,h,u,l[f+2],17,606105819),u=g(u,p,m,h,l[f+3],22,-1044525330),h=g(h,u,p,m,l[f+4],7,-176418897),m=g(m,h,u,p,l[f+5],12,1200080426),p=g(p,m,h,u,l[f+6],17,-1473231341),u=g(u,p,m,h,l[f+7],22,-45705983),h=g(h,u,p,m,l[f+8],7,1770035416),m=g(m,h,u,p,l[f+9],12,-1958414417),p=g(p,m,h,u,l[f+10],17,-42063),u=g(u,p,m,h,l[f+11],22,-1990404162),h=g(h,u,p,m,l[f+12],7,1804603682),m=g(m,h,u,p,l[f+13],12,-40341101),p=g(p,m,h,u,l[f+14],17,-1502002290),u=g(u,p,m,h,l[f+15],22,1236535329),h=v(h,u,p,m,l[f+1],5,-165796510),m=v(m,h,u,p,l[f+6],9,-1069501632),p=v(p,m,h,u,l[f+11],14,643717713),u=v(u,p,m,h,l[f+0],20,-373897302),h=v(h,u,p,m,l[f+5],5,-701558691),m=v(m,h,u,p,l[f+10],9,38016083),p=v(p,m,h,u,l[f+15],14,-660478335),u=v(u,p,m,h,l[f+4],20,-405537848),h=v(h,u,p,m,l[f+9],5,568446438),m=v(m,h,u,p,l[f+14],9,-1019803690),p=v(p,m,h,u,l[f+3],14,-187363961),u=v(u,p,m,h,l[f+8],20,1163531501),h=v(h,u,p,m,l[f+13],5,-1444681467),m=v(m,h,u,p,l[f+2],9,-51403784),p=v(p,m,h,u,l[f+7],14,1735328473),u=v(u,p,m,h,l[f+12],20,-1926607734),h=y(h,u,p,m,l[f+5],4,-378558),m=y(m,h,u,p,l[f+8],11,-2022574463),p=y(p,m,h,u,l[f+11],16,1839030562),u=y(u,p,m,h,l[f+14],23,-35309556),h=y(h,u,p,m,l[f+1],4,-1530992060),m=y(m,h,u,p,l[f+4],11,1272893353),p=y(p,m,h,u,l[f+7],16,-155497632),u=y(u,p,m,h,l[f+10],23,-1094730640),h=y(h,u,p,m,l[f+13],4,681279174),m=y(m,h,u,p,l[f+0],11,-358537222),p=y(p,m,h,u,l[f+3],16,-722521979),u=y(u,p,m,h,l[f+6],23,76029189),h=y(h,u,p,m,l[f+9],4,-640364487),m=y(m,h,u,p,l[f+12],11,-421815835),p=y(p,m,h,u,l[f+15],16,530742520),u=y(u,p,m,h,l[f+2],23,-995338651),h=A(h,u,p,m,l[f+0],6,-198630844),m=A(m,h,u,p,l[f+7],10,1126891415),p=A(p,m,h,u,l[f+14],15,-1416354905),u=A(u,p,m,h,l[f+5],21,-57434055),h=A(h,u,p,m,l[f+12],6,1700485571),m=A(m,h,u,p,l[f+3],10,-1894986606),p=A(p,m,h,u,l[f+10],15,-1051523),u=A(u,p,m,h,l[f+1],21,-2054922799),h=A(h,u,p,m,l[f+8],6,1873313359),m=A(m,h,u,p,l[f+15],10,-30611744),p=A(p,m,h,u,l[f+6],15,-1560198380),u=A(u,p,m,h,l[f+13],21,1309151649),h=A(h,u,p,m,l[f+4],6,-145523070),m=A(m,h,u,p,l[f+11],10,-1120210379),p=A(p,m,h,u,l[f+2],15,718787259),u=A(u,p,m,h,l[f+9],21,-343485551),h=h+_>>>0,u=u+b>>>0,p=p+x>>>0,m=m+E>>>0}return n.endian([h,u,p,m])};s._ff=function(o,a,l,c,h,u,p){var m=o+(a&l|~a&c)+(h>>>0)+p;return(m<<u|m>>>32-u)+a},s._gg=function(o,a,l,c,h,u,p){var m=o+(a&c|l&~c)+(h>>>0)+p;return(m<<u|m>>>32-u)+a},s._hh=function(o,a,l,c,h,u,p){var m=o+(a^l^c)+(h>>>0)+p;return(m<<u|m>>>32-u)+a},s._ii=function(o,a,l,c,h,u,p){var m=o+(l^(a|~c))+(h>>>0)+p;return(m<<u|m>>>32-u)+a},s._blocksize=16,s._digestsize=16,b6.exports=function(o,a){if(o==null)throw new Error("Illegal argument "+o);var l=n.wordsToBytes(s(o,a));return a&&a.asBytes?l:a&&a.asString?r.bytesToString(l):n.bytesToHex(l)}})();var oue=b6.exports;const aue=G1(oue);class hB{constructor(e,t,r,s){d(this,"success"),d(this,"filename"),d(this,"hash"),d(this,"size"),d(this,"url"),this.success=e,this.filename=t,this.hash=r,this.size=s}}async function S6(n,e){const t=await n.arrayBuffer(),r=uB(t),s=n.name.split(".").pop(),o=r+"."+s,a=n.name.split(".").shift();console.assert(a!==void 0);const l={alias:a,filename:o},c=await(await fetch(e+"/exists",{method:"POST",body:JSON.stringify(l)})).json();if(c.success||console.warn("exists check did fail"),c.exists)return console.log("file already exists",r),new hB(!0,o,r,n.size);console.log("begin uploading file",a,n.size);const h=new FormData;h.append("file",n);const u={};u.filesize=n.size,a&&(u.alias=a);const p=await(await fetch(e+"/upload/file",{method:"POST",body:h,headers:u})).json();if(p?.success===!1)return p.message!==void 0?console.error("Upload failed:",p.message):console.error("Upload failed"),null;console.assert(p.hash_sum===r,"hash sum did not match","received:",p.hash_sum,"expected:",r),p.success&&console.log("successfully uploaded",r,p.id);const m=new hB(p.success,o,r,n.size);return m.url=e,m}function uB(n){return aue(new Uint8Array(n))}async function dB(n,e,t,r,s=!1){try{const o=await fetch(r+"/download/file",{method:"POST",body:n});if(o.status!==200)return console.error("download failed",o),null;const a=await o.blob(),l=await a.arrayBuffer();s||console.assert(a.size===t,"size mismatch","expected:",t,"got:",a.size);const c=uB(l);return s||console.assert(c===e,"hash mismatch, downloaded file is invalid"),a.arrayBuffer()}catch(o){console.error(o)}return null}async function C6(n,e){var t;const r=await fetch(n),s=(t=r.body)==null?void 0:t.getReader(),o=r.headers.get("Content-Length"),a=o?parseInt(o):0;if(!s)return null;let l=0;const c=[];for(;;){const{done:p,value:m}=await s.read();if(m&&(c.push(m),l+=m.length,e.call(null,new ProgressEvent("progress",{loaded:l,total:a}))),p)break}const h=new Uint8Array(l);let u=0;for(const p of c)h.set(p,u),u+=p.length;return h}const Fu=te("debugaddressables");class E6{constructor(e){d(this,"_context"),d(this,"_assetReferences",{}),d(this,"preUpdate",()=>{}),this._context=e,this._context.pre_update_callbacks.push(this.preUpdate)}dispose(){const e=this._context.pre_update_callbacks.indexOf(this.preUpdate);e>=0&&this._context.pre_update_callbacks.splice(e,1);for(const t in this._assetReferences){const r=this._assetReferences[t];r?.unload()}this._assetReferences={}}findAssetReference(e){return this._assetReferences[e]||null}registerAssetReference(e){return e.uri&&(this._assetReferences[e.uri]?console.warn("Asset reference already registered",e):this._assetReferences[e.uri]=e),e}unregisterAssetReference(e){e.uri&&delete this._assetReferences[e.uri]}}const pB=Symbol("assetReference"),Pg=class{constructor(n,e,t=null){d(this,"_loading"),d(this,"_asset"),d(this,"_glbRoot"),d(this,"_url"),d(this,"_progressListeners",[]),d(this,"_hash"),d(this,"_hashedUri"),d(this,"_isLoadingRawBinary",!1),d(this,"_rawBinary"),this._url=n,this._hash=e,n.includes("?v=")?this._hashedUri=n:this._hashedUri=e?n+"?v="+e:n,t!==null&&(this.asset=t),jV(this._url,this.onResolvePrefab.bind(this))}static getOrCreateFromUrl(n,e){if(!e&&(e=kt.Current,!e))throw new Error('Context is required when sourceId is a string. When you call this method from a component you can call it with "getOrCreate(this, url)" where "this" is the component.');const t=e.addressables,r=t.findAssetReference(n);if(r)return r;const s=new Pg(n,e.hash);return t.registerAssetReference(s),s}static getOrCreate(n,e,t){if(typeof n=="string"){if(!t&&(t=kt.Current,!t))throw new Error('Context is required when sourceId is a string. When you call this method from a component you can call it with "getOrCreate(this, url)" where "this" is the component.')}else t=n.context,n=n.sourceId;const r=cu(n,e);Fu&&console.log("GetOrCreate Addressable from",n,e,"FinalPath=",r);const s=t.addressables,o=s.findAssetReference(r);if(o)return o;const a=new Pg(r,t.hash);return s.registerAssetReference(a),a}get asset(){return this._glbRoot??this._asset}set asset(n){this._asset=n}get uri(){return this._url}get url(){return this._url}get hasUrl(){return this._url!==void 0&&(this._url.startsWith("http")||this._url.startsWith("blob:")||this._url.startsWith("www.")||this._url.includes("/"))}get rawAsset(){return this._asset}async onResolvePrefab(n){return n===this.uri&&(this.mustLoad&&await this.loadAssetAsync(),this.asset)?this.asset:null}get mustLoad(){return!this.asset||this.asset.__destroyed===!0||Jp(this.asset)===!0}isLoaded(){return this._rawBinary||this.asset!==void 0}unload(){this.asset&&(Fu&&console.log("Unload",this.asset),this.asset.scene&&Ca(this.asset.scene,!0,!0),Ca(this.asset,!0,!0)),this.asset=null,this._rawBinary=void 0,this._glbRoot=null,this._loading=void 0,kt.Current&&kt.Current.addressables.unregisterAssetReference(this)}async preload(){if(!this.mustLoad||this._isLoadingRawBinary)return null;if(this._rawBinary!==void 0)return this._rawBinary;this._isLoadingRawBinary=!0,Fu&&console.log("Preload",this._hashedUri);const n=await C6(this._hashedUri,e=>{this.raiseProgressEvent(e)});return this._rawBinary=n?.buffer??null,this._isLoadingRawBinary=!1,this._rawBinary}async loadAssetAsync(n){if(Fu&&console.log("loadAssetAsync",this.uri),!this.mustLoad)return this.asset;if(n&&this._progressListeners.push(n),this._loading!==void 0)return this._loading.then(r=>this.asset);const e=kt.Current;this._rawBinary?(this._loading=Ka().parseSync(e,this._rawBinary,this.uri,null),this.raiseProgressEvent(new ProgressEvent("progress",{loaded:this._rawBinary.byteLength,total:this._rawBinary.byteLength}))):(Fu&&console.log("Load async",this.uri),this._loading=Ka().loadSync(e,this._hashedUri,this.uri,null,r=>{this.raiseProgressEvent(r)}));const t=await this._loading;if(this._progressListeners.length=0,this._glbRoot=this.tryGetActualGameObjectRoot(t),this._loading=void 0,t)return t[pB]=this,this._glbRoot&&(this._glbRoot[pB]=this),this.asset&&(this.asset[pB]=this),B1(e),t.scene!==void 0&&(this.asset=t),this.asset}async instantiate(n){return this.onInstantiate(n,!1)}async instantiateSynced(n,e=!0){return this.onInstantiate(n,!0,e)}beginListenDownload(n){this._progressListeners.indexOf(n)<0&&this._progressListeners.push(n)}endListenDownload(n){const e=this._progressListeners.indexOf(n);e>=0&&this._progressListeners.splice(e,1)}raiseProgressEvent(n){for(const e of this._progressListeners)e(this,n)}async onInstantiate(n,e=!1,t){const r=kt.Current,s=new Ml;if(n instanceof ye?s.parent=n:n&&(Object.assign(s,n),s.cloneAssign(n)),s.parent||(s.parent=r.scene),this.mustLoad&&await this.loadAssetAsync(),Fu&&console.log("Instantiate",this.uri,"parent:",n),this.asset){Fu&&console.log("Add to scene",this.asset);let o=Pg.currentlyInstantiating.get(this.uri);if(o!==void 0&&o>=1e4)return console.error("Recursive or too many instantiations of "+this.uri+" in the same frame ("+o+")"),null;try{if(o===void 0&&(o=0),o+=1,Pg.currentlyInstantiating.set(this.uri,o),e){s.context=r;const a=this.asset;a.guid=this.uri;const l=ek(a,s,void 0,t);if(l)return l}else{const a=Gg(this.asset,s);if(a)return a}}finally{r.post_render_callbacks.push(()=>{o===void 0||o<0?o=0:o-=1,Pg.currentlyInstantiating.set(this.uri,o)})}}else Fu&&console.warn("Failed to load asset",this.uri);return null}tryGetActualGameObjectRoot(n){if(n&&n.scene){const e=n.scene;return e.isGroup&&e.children.length===1&&e.children[0].name+"glb"===e.name?e.children[0]:e}return null}};let ti=Pg;d(ti,"currentlyInstantiating",new Map);class lue extends wa{constructor(){super([ti],"AssetReferenceSerializer")}onSerialize(e,t){if(e&&e.uri!==void 0&&typeof e.uri=="string")return e.uri}onDeserialize(e,t){if(typeof e=="string")return t.context?t.gltfId?ti.getOrCreate(t.gltfId,e,t.context):(console.error("Missing source id"),null):(console.error("Missing context"),null);if(e instanceof ye){if(!t.context)return console.error("Missing context"),null;if(!t.gltfId)return console.error("Missing source id"),null;const r=e,s=t.context,o=r.guid??r.uuid,a=s.addressables.findAssetReference(o);if(a)return a;const l=new ti(o,void 0,r);return s.addressables.registerAssetReference(l),l}return null}}new lue;const cue=Promise.resolve(null),V1=class{constructor(n){d(this,"url"),d(this,"_bitmap"),d(this,"_bitmapObject"),d(this,"loader",null),this.url=n}static getOrCreate(n){let e=V1.imageReferences.get(n);return e||(e=new V1(n),V1.imageReferences.set(n,e)),e}dispose(){this._bitmapObject&&this._bitmapObject.close(),this._bitmap=void 0}createHTMLImage(){const n=new Image;return n.src=this.url,n}createTexture(){return this.url?(this.loader||(this.loader=new Dl),this.loader.setCrossOrigin("anonymous"),this.loader.loadAsync(this.url)):cue}getBitmap(){return this._bitmap?this._bitmap:(this._bitmap=new Promise((n,e)=>{const t=document.createElement("img");t.addEventListener("load",()=>{this._bitmap=createImageBitmap(t).then(r=>(this._bitmapObject=r,n(r),r))}),t.addEventListener("error",r=>{console.error("Failed to load image:"+this.url,r),n(null)}),t.src=this.url}),this._bitmap)}};let Q1=V1;d(Q1,"imageReferences",new Map);class M6 extends wa{constructor(){super([Q1],"ImageReferenceSerializer")}onSerialize(e,t){return null}onDeserialize(e,t){if(typeof e=="string"){const r=cu(t.gltfId,e);return Q1.getOrCreate(r)}}}new M6;const H1=class{constructor(n){d(this,"url"),d(this,"res"),this.url=n}static getOrCreate(n){let e=H1.cache.get(n);return e||(e=new H1(n),H1.cache.set(n,e)),e}async loadRaw(){return this.res||(this.res=fetch(this.url)),this.res.then(n=>n.blob())}async loadText(){return this.res||(this.res=fetch(this.url)),this.res.then(n=>n.text())}};let W1=H1;d(W1,"cache",new Map);class T6 extends wa{constructor(){super([W1],"FileReferenceSerializer")}onSerialize(e,t){return null}onDeserialize(e,t){if(typeof e=="string"){const r=cu(t.gltfId,e);return W1.getOrCreate(r)}}}new T6;class hue{constructor(e){d(this,"context"),d(this,"mixers",[]),this.context=e}onDestroy(){this.mixers.forEach(e=>e.stopAllAction()),this.mixers.length=0}registerAnimationMixer(e){if(!e){console.warn("AnimationsRegistry.registerAnimationMixer called with null or undefined mixer");return}this.mixers.includes(e)||this.mixers.push(e)}unregisterAnimationMixer(e){if(!e)return;const t=this.mixers.indexOf(e);t!==-1&&this.mixers.splice(t,1)}}class Bg{static tryGetActionsFromMixer(e){return e._actions||null}static tryGetAnimationClipsFromObjectHierarchy(e,t){if(t||(t=new Array),e)e.animations&&t.push(...e.animations);else return t;if(e.children)for(const r of e.children)this.tryGetAnimationClipsFromObjectHierarchy(r,t);return t}static assignAnimationsFromFile(e,t){if(!e||!e.animations)return;for(let s=0;s<e.animations.length;s++){const o=e.animations[s];if(!(!o.tracks||o.tracks.length<=0))for(const a in o.tracks){const l=o.tracks[a],c=Xt.parseTrackName(l.name);let h=Xt.findNode(e.scene,c.nodeName);if(!h){const p=l.__objectName??l.name.substring(0,l.name.indexOf("."));if(h=e.scene.getObjectByProperty("uuid",p),!h)continue}let u=r(h);if(!u){if(!(t!=null&&t.createAnimationComponent)){console.warn("No AnimationComponent found in parent hierarchy of object and no 'createAnimationComponent' callback was provided in options.");continue}u=t.createAnimationComponent(e.scene,o)}u.addClip&&u.addClip(o)}}function r(s){var o;if(!s)return null;const a=(o=s.userData)==null?void 0:o.components;if(a&&a.length>0){for(let l=0;l<a.length;l++)if(a[l].isAnimationComponent===!0)return s}return r(s.parent)}}}const kg=[];function X1(n){kg.indexOf(n)===-1&&kg.push(n)}function uue(n){const e=kg.indexOf(n);e!==-1&&kg.splice(e,1)}const Dg=[];function mB(n){Dg.indexOf(n)===-1&&Dg.push(n)}function due(n){const e=Dg.indexOf(n);e!==-1&&Dg.splice(e,1)}function I6(n){globalThis.dispatchEvent(new CustomEvent("needle-xrsession-start",{detail:n}));for(let e=0;e<kg.length;e++)kg[e](n)}function R6(n){globalThis.dispatchEvent(new CustomEvent("needle-xrsession-end",{detail:n}));for(let e=0;e<Dg.length;e++)Dg[e](n)}const wr={Handedness:Object.freeze({NONE:"none",LEFT:"left",RIGHT:"right"}),ComponentState:Object.freeze({DEFAULT:"default",TOUCHED:"touched",PRESSED:"pressed"}),ComponentProperty:Object.freeze({BUTTON:"button",X_AXIS:"xAxis",Y_AXIS:"yAxis",STATE:"state"}),ComponentType:Object.freeze({TRIGGER:"trigger",SQUEEZE:"squeeze",TOUCHPAD:"touchpad",THUMBSTICK:"thumbstick",BUTTON:"button"}),ButtonTouchThreshold:.05,AxisTouchThreshold:.1,VisualResponseProperty:Object.freeze({TRANSFORM:"transform",VISIBILITY:"visibility"})};async function P6(n){const e=await fetch(n);if(e.ok)return e.json();throw new Error(e.statusText)}async function pue(n){if(!n)throw new Error("No basePath supplied");return await P6(`${n}/profilesList.json`)}async function mue(n,e,t=null,r=!0){if(!n)throw new Error("No xrInputSource supplied");if(!e)throw new Error("No basePath supplied");const s=await pue(e);let o;if(n.profiles.some(c=>{const h=s[c];return h&&(o={profileId:c,profilePath:`${e}/${h.path}`,deprecated:!!h.deprecated}),!!o}),!o){if(!t)throw new Error("No matching profile name found");const c=s[t];if(!c)throw new Error(`No matching profile name found and default profile "${t}" missing.`);o={profileId:t,profilePath:`${e}/${c.path}`,deprecated:!!c.deprecated}}const a=await P6(o.profilePath);let l;if(r){let c;if(n.handedness==="any"?c=a.layouts[Object.keys(a.layouts)[0]]:c=a.layouts[n.handedness],!c)throw new Error(`No matching handedness, ${n.handedness}, in profile ${o.profileId}`);c.assetPath&&(l=o.profilePath.replace("profile.json",c.assetPath))}return{profile:a,assetPath:l}}const fue={xAxis:0,yAxis:0,button:0,state:wr.ComponentState.DEFAULT};function gue(n=0,e=0){let t=n,r=e;if(Math.sqrt(n*n+e*e)>1){const s=Math.atan2(e,n);t=Math.cos(s),r=Math.sin(s)}return{normalizedXAxis:t*.5+.5,normalizedYAxis:r*.5+.5}}let vue=class{constructor(n){this.componentProperty=n.componentProperty,this.states=n.states,this.valueNodeName=n.valueNodeName,this.valueNodeProperty=n.valueNodeProperty,this.valueNodeProperty===wr.VisualResponseProperty.TRANSFORM&&(this.minNodeName=n.minNodeName,this.maxNodeName=n.maxNodeName),this.value=0,this.updateFromComponent(fue)}updateFromComponent({xAxis:n,yAxis:e,button:t,state:r}){const{normalizedXAxis:s,normalizedYAxis:o}=gue(n,e);switch(this.componentProperty){case wr.ComponentProperty.X_AXIS:this.value=this.states.includes(r)?s:.5;break;case wr.ComponentProperty.Y_AXIS:this.value=this.states.includes(r)?o:.5;break;case wr.ComponentProperty.BUTTON:this.value=this.states.includes(r)?t:0;break;case wr.ComponentProperty.STATE:this.valueNodeProperty===wr.VisualResponseProperty.VISIBILITY?this.value=this.states.includes(r):this.value=this.states.includes(r)?1:0;break;default:throw new Error(`Unexpected visualResponse componentProperty ${this.componentProperty}`)}}},yue=class{constructor(n,e){if(!n||!e||!e.visualResponses||!e.gamepadIndices||Object.keys(e.gamepadIndices).length===0)throw new Error("Invalid arguments supplied");this.id=n,this.type=e.type,this.rootNodeName=e.rootNodeName,this.touchPointNodeName=e.touchPointNodeName,this.visualResponses={},Object.keys(e.visualResponses).forEach(t=>{const r=new vue(e.visualResponses[t]);this.visualResponses[t]=r}),this.gamepadIndices=Object.assign({},e.gamepadIndices),this.values={state:wr.ComponentState.DEFAULT,button:this.gamepadIndices.button!==void 0?0:void 0,xAxis:this.gamepadIndices.xAxis!==void 0?0:void 0,yAxis:this.gamepadIndices.yAxis!==void 0?0:void 0}}get data(){return{id:this.id,...this.values}}updateFromGamepad(n){if(this.values.state=wr.ComponentState.DEFAULT,this.gamepadIndices.button!==void 0&&n.buttons.length>this.gamepadIndices.button){const e=n.buttons[this.gamepadIndices.button];this.values.button=e.value,this.values.button=this.values.button<0?0:this.values.button,this.values.button=this.values.button>1?1:this.values.button,e.pressed||this.values.button===1?this.values.state=wr.ComponentState.PRESSED:(e.touched||this.values.button>wr.ButtonTouchThreshold)&&(this.values.state=wr.ComponentState.TOUCHED)}this.gamepadIndices.xAxis!==void 0&&n.axes.length>this.gamepadIndices.xAxis&&(this.values.xAxis=n.axes[this.gamepadIndices.xAxis],this.values.xAxis=this.values.xAxis<-1?-1:this.values.xAxis,this.values.xAxis=this.values.xAxis>1?1:this.values.xAxis,this.values.state===wr.ComponentState.DEFAULT&&Math.abs(this.values.xAxis)>wr.AxisTouchThreshold&&(this.values.state=wr.ComponentState.TOUCHED)),this.gamepadIndices.yAxis!==void 0&&n.axes.length>this.gamepadIndices.yAxis&&(this.values.yAxis=n.axes[this.gamepadIndices.yAxis],this.values.yAxis=this.values.yAxis<-1?-1:this.values.yAxis,this.values.yAxis=this.values.yAxis>1?1:this.values.yAxis,this.values.state===wr.ComponentState.DEFAULT&&Math.abs(this.values.yAxis)>wr.AxisTouchThreshold&&(this.values.state=wr.ComponentState.TOUCHED)),Object.values(this.visualResponses).forEach(e=>{e.updateFromComponent(this.values)})}},Aue=class{constructor(n,e,t){if(!n)throw new Error("No xrInputSource supplied");if(!e)throw new Error("No profile supplied");this.xrInputSource=n,this.assetUrl=t,this.id=e.profileId,this.layoutDescription=e.layouts[n.handedness],this.components={},Object.keys(this.layoutDescription.components).forEach(r=>{const s=this.layoutDescription.components[r];this.components[r]=new yue(r,s)}),this.updateFromGamepad()}get gripSpace(){return this.xrInputSource.gripSpace}get targetRaySpace(){return this.xrInputSource.targetRaySpace}get data(){const n=[];return Object.values(this.components).forEach(e=>{n.push(e.data)}),n}updateFromGamepad(){Object.values(this.components).forEach(n=>{n.updateFromGamepad(this.xrInputSource.gamepad)})}};const Js=new C,B6=new C,k6=new Ce,bue=te("debuggizmos"),Wl=8947848,Xl=class{constructor(){}static isGizmo(n){return n[gB]!==void 0}static DrawLabel(n,e,t=.05,r=0,s,o,a){var l;if(!Xl.enabled)return null;s||(s=Wl);const c=((l=wt.active)==null?void 0:l.rigScale)??1,h=En.getTextLabel(r,e,t*c,s,o);return a instanceof ye&&a.add(h),h.position.x=n.x,h.position.y=n.y,h.position.z=n.z,h}static DrawRay(n,e,t=Wl,r=0,s=!0){if(!Xl.enabled)return;const o=En.getLine(r),a=o.geometry.getAttribute("position");a.setXYZ(0,n.x,n.y,n.z),Js.set(e.x,e.y,e.z).multiplyScalar(999999999),a.setXYZ(1,n.x+Js.x,n.y+Js.y,n.z+Js.z),a.needsUpdate=!0,o.material.color.set(t),o.material.depthTest=s,o.material.depthWrite=!1}static DrawDirection(n,e,t=Wl,r=0,s=!0,o=1){if(!Xl.enabled)return;const a=En.getLine(r),l=a.geometry.getAttribute("position");l.setXYZ(0,n.x,n.y,n.z),e.w!==void 0?(Js.set(0,0,-o),k6.set(e.x,e.y,e.z,e.w),Js.applyQuaternion(k6)):(Js.set(e.x,e.y,e.z),Js.multiplyScalar(o)),l.setXYZ(1,n.x+Js.x,n.y+Js.y,n.z+Js.z),l.needsUpdate=!0,a.material.color.set(t),a.material.depthTest=s,a.material.depthWrite=!1}static DrawLine(n,e,t=Wl,r=0,s=!0){if(!Xl.enabled)return;const o=En.getLine(r),a=o.geometry.getAttribute("position");a.setXYZ(0,n.x,n.y,n.z),a.setXYZ(1,e.x,e.y,e.z),a.needsUpdate=!0,o.material.color.set(t),o.material.depthTest=s,o.material.depthWrite=!1,o.material.fog=!1}static DrawWireSphere(n,e,t=Wl,r=0,s=!0){if(!Xl.enabled)return;const o=En.getSphere(e,r,!0);_p(o,n.x,n.y,n.z),o.material.color.set(t),o.material.depthTest=s,o.material.depthWrite=!1,o.material.fog=!1}static DrawSphere(n,e,t=Wl,r=0,s=!0){if(!Xl.enabled)return;const o=En.getSphere(e,r,!1);_p(o,n.x,n.y,n.z),o.material.color.set(t),o.material.depthTest=s,o.material.depthWrite=!1}static DrawWireBox(n,e,t=Wl,r=0,s=!0){if(!Xl.enabled)return;const o=En.getBox(r);o.position.set(n.x,n.y,n.z),o.scale.set(e.x,e.y,e.z),o.material.color.set(t),o.material.depthTest=s,o.material.wireframe=!0,o.material.depthWrite=!1,o.material.fog=!1}static DrawWireBox3(n,e=Wl,t=0,r=!0){if(!Xl.enabled)return;const s=En.getBox(t);s.position.copy(n.getCenter(Js)),s.scale.copy(n.getSize(Js)),s.material.color.set(e),s.material.depthTest=r,s.material.wireframe=!0,s.material.depthWrite=!1,s.material.fog=!1}static DrawArrow(n,e,t=Wl,r=0,s=!0,o=!1){if(!Xl.enabled)return;const a=En.getArrowHead(r);a.position.set(e.x,e.y,e.z),a.quaternion.setFromUnitVectors(this._up.set(0,1,0),Js.set(e.x,e.y,e.z).sub(B6.set(n.x,n.y,n.z)).normalize());const l=Js.set(e.x,e.y,e.z).sub(B6.set(n.x,n.y,n.z)).length()*.1;a.scale.set(l,l,l),a.material.color.set(t),a.material.depthTest=s,a.material.wireframe=o,this.DrawLine(n,e,t,r,s)}static DrawWireMesh(n){const e=En.getMesh(n.duration??0);"mesh"in n?(e.geometry=n.mesh.geometry,e.matrix.copy(n.mesh.matrixWorld)):(e.geometry=n.geometry,e.matrix.copy(n.matrix)),e.matrixAutoUpdate=!1,e.matrixWorldAutoUpdate=!1,e.material.color.set(n.color??Wl),e.material.depthTest=n.depthTest??!0,e.material.wireframe=!0}};let At=Xl;d(At,"enabled",!0),d(At,"_up",new C(0,1,0));const _ue=new qi(1,1,1);function fB(n=null){const e=new xe(n??14540253),t=new iI(_ue);return new gs(t,new Gi({color:e}))}const gB=Symbol("GizmoCache");class En{static ensureFont(){let e=Ni.FontLibrary.getFontFamily(this.familyName);if(!e){e=Ni.FontLibrary.addFontFamily(this.familyName);const t=e.addVariant("normal","normal","https://uploads.needle.tools/include/font-msdf.json","https://uploads.needle.tools/include/font.png");t?.addEventListener("ready",()=>{Ni.update()})}}static getTextLabel(e,t,r,s,o){this.ensureFont();let a=this.textLabelCache.pop(),l=1;o&&typeof o=="string"&&o?.length>=8&&o.startsWith("#")?(l=parseInt(o.substring(7),16)/255,o=o.substring(0,7),bue&&console.log(o,l)):typeof o=="object"&&o.a!==void 0&&(l=o.a);const c={boxSizing:"border-box",fontFamily:this.familyName,width:"auto",fontSize:r,color:s,lineHeight:1,backgroundColor:o??void 0,backgroundOpacity:l,textContent:t,borderRadius:.5*r,padding:.8*r,whiteSpace:"pre"};if(a)a.set(c);else{a=new fR(c);const h=this,u=a;u.setText=function(p){this.set({textContent:p}),h.tmuiNeedsUpdate=!0}}return this.tmuiNeedsUpdate=!0,this.registerTimedObject(kt.Current,a,e,this.textLabelCache),a}static getBox(e){let t=this.boxesCache.pop();if(!t){const r=new qi(1,1,1);t=new me(r)}return this.registerTimedObject(kt.Current,t,e,this.boxesCache),t}static getLine(e){let t=this.linesCache.pop();if(!t){t=new Sn;let r=t.geometry.getAttribute("position");r||(r=new nt(new Float32Array(2*3),3),t.geometry.setAttribute("position",r))}return t.frustumCulled=!1,this.registerTimedObject(kt.Current,t,e,this.linesCache),t}static getSphere(e,t,r){let s=this.spheresCache.pop();return s||(s=new me(new ja(1,8,8))),s.scale.set(e,e,e),s.material.wireframe=r,this.registerTimedObject(kt.Current,s,t,this.spheresCache),s}static getArrowHead(e){let t=this.arrowHeadsCache.pop();return t||(t=new me(new jn(0,.5,1,8))),this.registerTimedObject(kt.Current,t,e,this.arrowHeadsCache),t}static getMesh(e){let t=this.mesh.pop();return t||(t=new me,t.material=new $t),this.registerTimedObject(kt.Current,t,e,this.mesh),t}static registerTimedObject(e,t,r,s){const o=this.contextBeforeRenderCallbacks.get(e),a=this.contextPostRenderCallbacks.get(e);if(o){if(e.pre_render_callbacks[e.pre_render_callbacks.length-1]!==o){const l=e.pre_render_callbacks.indexOf(o);l>=0&&e.pre_render_callbacks.splice(l,1),e.pre_render_callbacks.push(o)}}else{const l=()=>{this.onBeforeRender(e,this.timedObjectsBuffer)};this.contextBeforeRenderCallbacks.set(e,l),e.pre_render_callbacks.push(l)}if(a){if(e.post_render_callbacks[e.post_render_callbacks.length-1]!==a){const l=e.post_render_callbacks.indexOf(a);l>=0&&e.post_render_callbacks.splice(l,1),e.post_render_callbacks.push(a)}}else{const l=()=>{this.onPostRender(e,this.timedObjectsBuffer,this.timesBuffer)};this.contextPostRenderCallbacks.set(e,l),e.post_render_callbacks.push(l)}t.traverse(l=>{l.layers.disableAll(),l.layers.enable(2)}),t.renderOrder=999999,t[gB]=s,t.isGizmo=!0,this.timedObjectsBuffer.push(t),r<=0&&e.currentFrameEvent>=Hi.OnBeforeRender?this.timesBuffer.push(0):this.timesBuffer.push(kt.Current.time.realtimeSinceStartup+r),e.scene.add(t)}static onBeforeRender(e,t){this.tmuiNeedsUpdate&&Ni.update();for(let r=0;r<t.length;r++){const s=t[r];if(e.mainCamera&&s instanceof Ni.MeshUIBaseElement){if(Jp(s))continue;const o=e.isInVR,a=!1,l=!o;Hv(s,e.mainCamera,a,l)}}}static onPostRender(e,t,r){const s=e.time.realtimeSinceStartup;for(let o=t.length-1;o>=0;o--){const a=t[o];s>r[o]&&(t.splice(o,1),r.splice(o,1),a.removeFromParent(),Jp(a)!=!0&&a[gB].push(a))}}}d(En,"familyName","needle-gizmos"),d(En,"linesCache",[]),d(En,"spheresCache",[]),d(En,"boxesCache",[]),d(En,"arrowHeadsCache",[]),d(En,"mesh",[]),d(En,"textLabelCache",[]),d(En,"timedObjectsBuffer",new Array),d(En,"timesBuffer",new Array),d(En,"contextPostRenderCallbacks",new Map),d(En,"contextBeforeRenderCallbacks",new Map),d(En,"tmuiNeedsUpdate",!1);const cr=te("debuginput");var q1=(n=>(n.Mouse="mouse",n.Touch="touch",n.Controller="controller",n.Hand="hand",n))(q1||{}),an=(n=>(n.PointerDown="pointerdown",n.PointerUp="pointerup",n.PointerMove="pointermove",n.KeyDown="keydown",n.KeyUp="keyup",n.KeyPressed="keypress",n))(an||{});class mh extends PointerEvent{constructor(e,t,r){super(e,r),d(this,"deviceIndex"),d(this,"origin"),d(this,"source"),d(this,"mode"),d(this,"_ray"),d(this,"space"),d(this,"isClick",!1),d(this,"isDoubleClick",!1),d(this,"_used",!1),d(this,"_pointerid"),d(this,"_pointerType"),d(this,"_type"),d(this,"metadata",{}),d(this,"intersections",new Array),d(this,"_immediatePropagationStopped",!1),d(this,"_propagationStopped",!1),this._pointerid=r.pointerId,this._pointerType=r.pointerType,this._type=e,this.deviceIndex=r.deviceIndex,this.origin=r.origin,this.source=t,this.mode=r.mode,this._ray=r.ray,this.space=r.device}get isSpatial(){return this.mode!="screen"}get ray(){return this._ray||(this._ray=new co(this.space.worldPosition.clone(),this.space.worldForward.clone())),this._ray}set ray(e){this._ray=e}get hasRay(){return this._ray!==void 0}get used(){return this._used}use(){this._used=!0}get pointerId(){return this._pointerid}get pointerType(){return this._pointerType}get type(){return this._type}get immediatePropagationStopped(){return this._immediatePropagationStopped}get propagationStopped(){return this._immediatePropagationStopped||this._propagationStopped}stopImmediatePropagation(){var e;this._immediatePropagationStopped=!0,super.stopImmediatePropagation(),(e=this.source)==null||e.stopImmediatePropagation()}stopPropagation(){var e;this._propagationStopped=!0,super.stopPropagation(),(e=this.source)==null||e.stopPropagation(),cr&&console.warn("Stop propagation...",this.pointerId,this.pointerType)}}class Xy extends KeyboardEvent{constructor(e,t,r){super(e,r),d(this,"source"),this.source=t}stopImmediatePropagation(){var e;super.stopImmediatePropagation(),(e=this.source)==null||e.stopImmediatePropagation()}}class xue{constructor(e){d(this,"key"),d(this,"keyType"),d(this,"source"),this.key=e.key,this.keyType=e.type,this.source=e}}var ql=(n=>(n[n.Early=-100]="Early",n[n.Default=0]="Default",n[n.Late=100]="Late",n))(ql||{});class D6{constructor(e){d(this,"_eventListeners",{}),d(this,"_doubleClickTimeThreshold",.2),d(this,"_longPressTimeThreshold",1),d(this,"_specialCursorTrigger",0),d(this,"context"),d(this,"_pointerDown",[!1]),d(this,"_pointerUp",[!1]),d(this,"_pointerClick",[!1]),d(this,"_pointerDoubleClick",[!1]),d(this,"_pointerPressed",[!1]),d(this,"_pointerPositions",[new Z]),d(this,"_pointerPositionsLastFrame",[new Z]),d(this,"_pointerPositionsDelta",[new Z]),d(this,"_pointerPositionsRC",[new Z]),d(this,"_pointerPositionDown",[new Z]),d(this,"_pointerDownTime",[]),d(this,"_pointerUpTime",[]),d(this,"_pointerUpTimestamp",[]),d(this,"_pointerIds",[]),d(this,"_pointerTypes",[""]),d(this,"_mouseWheelChanged",[!1]),d(this,"_mouseWheelDeltaY",[0]),d(this,"_pointerEvent",[]),d(this,"_pointerUsed",[]),d(this,"_pointerSpace",[]),d(this,"_pressedStack",new Map),d(this,"_htmlEventSource"),d(this,"onLostFocus",()=>{for(const t in this.keysPressed)this.keysPressed[t].pressed=!1}),d(this,"onEndOfFrame",()=>{for(let t=0;t<this._pointerUp.length;t++)this._pointerUp[t]=!1;for(let t=0;t<this._pointerDown.length;t++)this._pointerDown[t]=!1;for(let t=0;t<this._pointerClick.length;t++)this._pointerClick[t]=!1;for(let t=0;t<this._pointerDoubleClick.length;t++)this._pointerDoubleClick[t]=!1;for(const t of this._pointerPositionsDelta)t.set(0,0);for(let t=0;t<this._mouseWheelChanged.length;t++)this._mouseWheelChanged[t]=!1;for(let t=0;t<this._mouseWheelDeltaY.length;t++)this._mouseWheelDeltaY[t]=0}),d(this,"onContextMenu",t=>{this.canReceiveInput(t)!==!1&&t instanceof PointerEvent&&t.pointerType}),d(this,"keysPressed",{}),d(this,"onKeyDown",t=>{if(cr&&console.log(`key down ${t.code}, ${this.context.application.hasFocus}`,t),!this.context.application.hasFocus)return;const r=this.keysPressed[t.code];if(r&&r.pressed)return;this.keysPressed[t.code]={pressed:!0,frame:this.context.time.frameCount+1,startFrame:this.context.time.frameCount+1,key:t.key,code:t.code};const s=new Xy("keydown",t,t);this.onDispatchEvent(s)}),d(this,"onKeyPressed",t=>{if(!this.context.application.hasFocus)return;const r=this.keysPressed[t.code];if(!r)return;r.pressed=!0,r.frame=this.context.time.frameCount+1;const s=new Xy("keypress",t,t);this.onDispatchEvent(s)}),d(this,"onKeyUp",t=>{if(!this.context.application.hasFocus)return;const r=this.keysPressed[t.code];if(!r)return;r.pressed=!1,r.frame=this.context.time.frameCount+1;const s=new Xy("keyup",t,t);this.onDispatchEvent(s)}),d(this,"onWheelWindow",t=>{document.pointerLockElement&&this.onMouseWheel(t)}),d(this,"onMouseWheel",t=>{if(this.canReceiveInput(t)===!1)return;this._mouseWheelDeltaY.length<=0&&this._mouseWheelDeltaY.push(0),this._mouseWheelChanged.length<=0&&this._mouseWheelChanged.push(!1),this._mouseWheelChanged[0]=!0;const r=this._mouseWheelDeltaY[0];this._mouseWheelDeltaY[0]=r+t.deltaY}),d(this,"onPointerDown",t=>{if(this.context.isInAR||this.canReceiveInput(t)===!1)return;t.target instanceof HTMLElement&&t.target.setPointerCapture(t.pointerId);const r=this.getPointerId(t);cr&&rn(`pointer down #${r}, identifier:${t.pointerId}`);const s=this.getAndUpdateSpatialObjectForScreenPosition(r,t.clientX,t.clientY),o=new mh("pointerdown",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:r,button:t.button,clientX:t.clientX,clientY:t.clientY,pointerType:t.pointerType,buttonName:this.getButtonName(t),device:s,pressure:t.pressure});this.onDown(o)}),d(this,"onPointerMove",t=>{if(this.context.isInAR)return;let r=t.button;t.pointerType==="mouse"&&(r=this.getFirstPressedButtonForPointer(0)??0);const s=this.getPointerId(t,r);r===-1&&(r=s);const o=this.getAndUpdateSpatialObjectForScreenPosition(s,t.clientX,t.clientY),a=new mh("pointermove",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:s,button:r,clientX:t.clientX,clientY:t.clientY,pointerType:t.pointerType,buttonName:this.getButtonName(t),device:o,pressure:t.pressure});this.onMove(a)}),d(this,"onPointerCancel",t=>{this.context.isInAR||(cr&&console.log("Pointer cancel",t),this.onPointerUp(t))}),d(this,"onPointerUp",t=>{if(this.context.isInAR)return;t.target instanceof HTMLElement&&t.target.releasePointerCapture(t.pointerId);const r=this.getPointerId(t),s=new mh("pointerup",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:r,button:t.button,clientX:t.clientX,clientY:t.clientY,pointerType:t.pointerType,buttonName:this.getButtonName(t),device:this.getAndUpdateSpatialObjectForScreenPosition(r,t.clientX,t.clientY),pressure:t.pressure});this.onUp(s),this._pointerIds[r]=-1,cr&&console.log("ID="+r,"PointerId="+t.pointerId,"ALL:",[...this._pointerIds])}),d(this,"onTouchStart",t=>{if(this.context.isInAR)for(let r=0;r<t.changedTouches.length;r++){const s=t.changedTouches[r],o=this.getPointerIndex(s.identifier),a=this.getAndUpdateSpatialObjectForScreenPosition(o,s.clientX,s.clientY),l=new mh("pointerdown",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:o,button:0,clientX:s.clientX,clientY:s.clientY,pointerType:"touch",buttonName:"unknown",device:a,pressure:s.force});this.onDown(l)}}),d(this,"onTouchMove",t=>{if(this.context.isInAR)for(let r=0;r<t.changedTouches.length;r++){const s=t.changedTouches[r],o=this.getPointerIndex(s.identifier),a=this.getAndUpdateSpatialObjectForScreenPosition(o,s.clientX,s.clientY),l=new mh("pointermove",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:o,button:0,clientX:s.clientX,clientY:s.clientY,pointerType:"touch",buttonName:"unknown",device:a,pressure:s.force});this.onMove(l)}}),d(this,"onTouchEnd",t=>{if(this.context.isInAR)for(let r=0;r<t.changedTouches.length;r++){const s=t.changedTouches[r],o=this.getPointerIndex(s.identifier),a=new mh("pointerup",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:o,button:0,clientX:s.clientX,clientY:s.clientY,pointerType:"touch",buttonName:"unknown",device:this.getAndUpdateSpatialObjectForScreenPosition(o,s.clientX,s.clientY),pressure:s.force});this.onUp(a),this._pointerIds[o]=-1}}),d(this,"tempNearPlaneVector",new C),d(this,"tempFarPlaneVector",new C),d(this,"tempLookMatrix",new ve),this.context=e,this.context.post_render_callbacks.push(this.onEndOfFrame)}addEventListener(e,t,r){if(this._eventListeners[e]||(this._eventListeners[e]=[]),!t||typeof t!="function"){console.error("Invalid call to addEventListener: callback is required and must be a function!");return}r?r={...r}:r={};let s=0;r?.queue!=null&&(s=r.queue);const o=this._eventListeners[e],a=o.find(l=>l.priority===s);a?a.listeners.push({callback:t,options:r}):(o.push({priority:s,listeners:[{callback:t,options:r}]}),o.sort((l,c)=>l.priority-c.priority))}removeEventListener(e,t,r){if(!this._eventListeners[e]||!t)return;const s=this._eventListeners[e];if(r?.queue!=null){const o=s.find(l=>l.priority===r.queue);if(!o)return;const a=o.listeners.findIndex(l=>l.callback===t);a>=0&&o.listeners.splice(a,1)}else for(const o of s){const a=o.listeners.findIndex(l=>l.callback===t);a>=0&&o.listeners.splice(a,1)}}dispatchEvent(e){var t,r,s,o;let a=!1;if(e instanceof Xy){const l=this._eventListeners[e.type];if(l)for(const c of l)for(let h=0;h<c.listeners.length;h++){const u=c.listeners[h];if((r=(t=u.options)==null?void 0:t.signal)!=null&&r.aborted){c.listeners.splice(h,1),h--;continue}u.options.once&&(c.listeners.splice(h,1),h--),u.callback(e)}}if(e instanceof mh){const l=this._eventListeners[e.type];if(l)for(const c of l){if(a)break;for(let h=0;h<c.listeners.length;h++){const u=c.listeners[h];if((o=(s=u.options)==null?void 0:s.signal)!=null&&o.aborted){c.listeners.splice(h,1),h--;continue}if(e.immediatePropagationStopped){a=!0,cr&&console.log("immediatePropagationStopped",e.type);break}else e.propagationStopped&&(a=!0,cr&&console.log("propagationStopped",e.type));u.options.once&&(c.listeners.splice(h,1),h--),u.callback(e)}}}}get mousePosition(){return this._pointerPositions[0]}get mousePositionRC(){return this._pointerPositionsRC[0]}get mouseDown(){return this._pointerDown[0]}get mouseUp(){return this._pointerUp[0]}get mouseClick(){return this._pointerClick[0]}get mouseDoubleClick(){return this._pointerDoubleClick[0]}get mousePressed(){return this._pointerPressed[0]}get mouseWheelChanged(){return this.getMouseWheelChanged(0)}setCursorPointer(){this._specialCursorTrigger+=1,this.context.domElement.style.cursor="pointer"}setCursorNormal(){this._specialCursorTrigger-=1,this._specialCursorTrigger=Math.max(0,this._specialCursorTrigger),this._specialCursorTrigger===0&&(this.context.domElement.style.cursor="default")}setPointerUsed(e,t=!0){if(e>=this._pointerUsed.length){if(e>=this._pointerIds.length)return;for(;this._pointerUsed.length<=e;)this._pointerUsed.push(!1)}this._pointerUsed[e]=t}getPointerUsed(e){return e>=this._pointerUsed.length?!1:this._pointerUsed[e]}getPointerPressedCount(){let e=0;for(let t=0;t<this._pointerPressed.length;t++)this._pointerPressed[t]&&e++;return e}getPointerPosition(e){return e>=this._pointerPositions.length?null:this._pointerPositions[e]}getPointerPositionLastFrame(e){return e>=this._pointerPositionsLastFrame.length?null:this._pointerPositionsLastFrame[e]}getPointerPositionDelta(e){return e>=this._pointerPositionsDelta.length?null:this._pointerPositionsDelta[e]}getPointerPositionRC(e){return e>=this._pointerPositionsRC.length?null:this._pointerPositionsRC[e]}getPointerDown(e){return e>=this._pointerDown.length?!1:this._pointerDown[e]}getPointerUp(e){return e>=this._pointerUp.length?!1:this._pointerUp[e]}getPointerPressed(e){return e>=this._pointerPressed.length?!1:this._pointerPressed[e]}getPointerClicked(e){return e>=this._pointerClick.length?!1:this._pointerClick[e]}getPointerDoubleClicked(e){return e>=this._pointerDoubleClick.length?!1:this._pointerDoubleClick[e]}getPointerDownTime(e){return e>=this._pointerDownTime.length?-1:this._pointerDownTime[e]}getPointerUpTime(e){return e>=this._pointerUpTime.length?-1:this._pointerUpTime[e]}getPointerLongPress(e){return e>=this._pointerDownTime.length?!1:this.getPointerPressed(e)&&this.context.time.time-this._pointerDownTime[e]>this._longPressTimeThreshold}getIsMouse(e){return e<0||e>=this._pointerTypes.length?!1:this._pointerTypes[e]==="mouse"}getIsTouch(e){return e<0||e>=this._pointerTypes.length?!1:this._pointerTypes[e]==="touch"}getTouchesPressedCount(){let e=0;for(let t=0;t<this._pointerPressed.length;t++)this._pointerPressed[t]&&this.getIsTouch(t)&&e++;return e}getMouseWheelChanged(e=0){return e>=this._mouseWheelChanged.length?!1:this._mouseWheelChanged[e]}getMouseWheelDeltaY(e=0){return e>=this._mouseWheelDeltaY.length?0:this._mouseWheelDeltaY[e]}getPointerEvent(e){if(!(e>=this._pointerEvent.length))return this._pointerEvent[e]??void 0}*foreachPointerId(e){for(let t=0;t<this._pointerTypes.length;t++)if(this._pointerIsActive(t)){if(e!==void 0){const r=this._pointerTypes[t];if(Array.isArray(e)){let s=!1;for(const o of e)if(r===o){s=!0;break}if(!s)continue}else if(e!==r)continue}yield t}}*foreachTouchId(){for(let e=0;e<this._pointerTypes.length;e++)this._pointerTypes[e]==="touch"&&this._pointerIsActive[e]&&(yield e)}_pointerIsActive(e){return e<0?!1:this._pointerPressed[e]||this._pointerDown[e]||this._pointerUp[e]}onDownButton(e,t){let r=this._pressedStack.get(e);r||(r=[],this._pressedStack.set(e,r)),r.push(t)}onReleaseButton(e,t){const r=this._pressedStack.get(e);if(!r)return;const s=r.indexOf(t);s>=0&&r.splice(s,1)}getFirstPressedButtonForPointer(e){const t=this._pressedStack.get(e);if(t)return t[0]}getLatestPressedButtonForPointer(e){const t=this._pressedStack.get(e);if(t)return t[t.length-1]}getKeyDown(){for(const e in this.keysPressed){const t=this.keysPressed[e];if(t.startFrame===this.context.time.frameCount)return t.key}return null}getKeyPressed(){for(const e in this.keysPressed){const t=this.keysPressed[e];if(t.pressed)return t.key}return null}isKeyDown(e){var t;if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const r=this.getCodeForCommonKeyName(e);if(r!==null){for(const s of r)if(this.isKeyDown(s))return!0;return!1}return((t=this.keysPressed[e])==null?void 0:t.startFrame)===this.context.time.frameCount&&this.keysPressed[e].pressed}isKeyUp(e){var t;if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const r=this.getCodeForCommonKeyName(e);if(r!==null){for(const s of r)if(this.isKeyUp(s))return!0;return!1}return((t=this.keysPressed[e])==null?void 0:t.frame)===this.context.time.frameCount&&!this.keysPressed[e].pressed}isKeyPressed(e){var t;if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const r=this.getCodeForCommonKeyName(e);if(r!==null){for(const s of r)if(this.isKeyPressed(s))return!0;return!1}return(t=this.keysPressed[e])==null?void 0:t.pressed}getCodeForCommonKeyName(e){if(e.length===1){if(e>="0"&&e<="9")return["Digit"+e];if(e>="a"&&e<="z")return["Key"+e.toUpperCase()];if(e==" ")return["Space"]}switch(e){case"shift":case"Shift":return["ShiftLeft","ShiftRight"];case"control":case"Control":return["ControlLeft","ControlRight"];case"alt":case"Alt":return["AltLeft","AltRight"]}return null}createInputEvent(e){switch(e.type){case"pointerdown":cr&&rn("Create Pointer down"),this.onDownButton(e.deviceIndex,e.button),this.onDown(e);break;case"pointermove":cr&&rn("Create Pointer move"),this.onMove(e);break;case"pointerup":cr&&rn("Create Pointer up"),this.onUp(e),this.onReleaseButton(e.deviceIndex,e.button);break}}convertScreenspaceToRaycastSpace(e){return e.x=(e.x-this.context.domX)/this.context.domWidth*2-1,e.y=-((e.y-this.context.domY)/this.context.domHeight)*2+1,e}bindEvents(){this.unbindEvents(),this._htmlEventSource=this.context.renderer.domElement,window.addEventListener("contextmenu",this.onContextMenu),this._htmlEventSource.addEventListener("pointerdown",this.onPointerDown,{passive:!0}),window.addEventListener("pointermove",this.onPointerMove,{passive:!0,capture:!0}),window.addEventListener("pointerup",this.onPointerUp,{passive:!0}),window.addEventListener("pointercancel",this.onPointerCancel,{passive:!0}),window.addEventListener("touchstart",this.onTouchStart,{passive:!0}),window.addEventListener("touchmove",this.onTouchMove,{passive:!0}),window.addEventListener("touchend",this.onTouchEnd,{passive:!0}),this._htmlEventSource.addEventListener("wheel",this.onMouseWheel,{passive:!0}),window.addEventListener("wheel",this.onWheelWindow,{passive:!0}),window.addEventListener("keydown",this.onKeyDown,!1),window.addEventListener("keypress",this.onKeyPressed,!1),window.addEventListener("keyup",this.onKeyUp,!1),window.addEventListener("blur",this.onLostFocus)}unbindEvents(){var e,t;window.removeEventListener("contextmenu",this.onContextMenu),(e=this._htmlEventSource)==null||e.removeEventListener("pointerdown",this.onPointerDown),window.removeEventListener("pointermove",this.onPointerMove),window.removeEventListener("pointerup",this.onPointerUp),window.removeEventListener("pointercancel",this.onPointerCancel),(t=this._htmlEventSource)==null||t.removeEventListener("wheel",this.onMouseWheel,!1),window.removeEventListener("wheel",this.onWheelWindow,!1),window.removeEventListener("keydown",this.onKeyDown,!1),window.removeEventListener("keypress",this.onKeyPressed,!1),window.removeEventListener("keyup",this.onKeyUp,!1),window.removeEventListener("blur",this.onLostFocus)}dispose(){const e=this.context.post_render_callbacks.indexOf(this.onEndOfFrame);e>=0&&this.context.post_render_callbacks.splice(e,1),this.unbindEvents()}canReceiveInput(e){var t;return e.target===((t=this.context.renderer)==null?void 0:t.domElement)||e.target===this.context.domElement||this.context.isInAR||this.context.isInAR&&e.target===document.body&&gp()?!0:(cr&&console.warn("CanReceiveInput:False for",e.target),!1)}getPointerId(e,t){return e.pointerType==="mouse"?0+(t??e.button):this.getPointerIndex(e.pointerId)}getButtonName(e){const t=e.button;if(e.pointerType==="mouse")switch(t){case 0:return"left";case 1:return"middle";case 2:return"right"}return"unknown"}getAndUpdateSpatialObjectForScreenPosition(e,t,r){let s=this._pointerSpace[e];s||(s=new ye,this._pointerSpace[e]=s),this._pointerSpace[e]=s;const o=this.context.mainCamera;if(o){const a=this.tempNearPlaneVector.set(t,r,-1);this.convertScreenspaceToRaycastSpace(a);const l=this.tempFarPlaneVector.set(a.x,a.y,1);a.unproject(o),l.unproject(o);const c=o.worldUp||pi(0,1,0).applyQuaternion(Mi(o));this.tempLookMatrix.lookAt(l,a,c),s.position.set(a.x,a.y,a.z),s.quaternion.setFromRotationMatrix(this.tempLookMatrix)}return s}isInRect(e){if(this.context.isInXR)return!0;const t=this.context.domElement.getBoundingClientRect(),r=e.clientX,s=e.clientY,o=r>=t.x&&r<=t.right&&s>=t.y&&s<=t.bottom;return cr&&!o&&console.log("Not in rect",t,r,s),o}onDown(e){const t=e.pointerId;if(this.getPointerPressed(t)&&console.warn(`pointerId is already pressed: ${t}`,cr?e:""),cr&&console.log(e.pointerType,"DOWN",t),!!this.isInRect(e)){for(this.setPointerState(t,this._pointerPressed,!0),this.setPointerState(t,this._pointerDown,!0),this.setPointerStateT(t,this._pointerEvent,e.source);t>=this._pointerTypes.length;)this._pointerTypes.push(e.pointerType);for(this._pointerTypes[t]=e.pointerType;t>=this._pointerPositionDown.length;)this._pointerPositionDown.push(new Z);for(this._pointerPositionDown[t].set(e.clientX,e.clientY);t>=this._pointerPositions.length;)this._pointerPositions.push(new Z);this._pointerPositions[t].set(e.clientX,e.clientY),t>=this._pointerDownTime.length&&this._pointerDownTime.push(0),this._pointerDownTime[t]=this.context.time.time,this.updatePointerPosition(e),this.onDispatchEvent(e)}}onMove(e){const t=e.pointerId,r=this.getPointerPressed(t);r===!1&&!this.isInRect(e)||e.pointerType==="touch"&&!r||(this.updatePointerPosition(e),this.setPointerStateT(t,this._pointerEvent,e.source),this.onDispatchEvent(e))}onUp(e){const t=e.pointerId;if(!this.getPointerPressed(t)){cr&&console.log(e.pointerType,"UP",t,"was not down");return}for(cr&&console.log(e.pointerType,"UP",t),this.setPointerState(t,this._pointerPressed,!1),this.setPointerStateT(t,this._pointerEvent,e.source),this.setPointerState(t,this._pointerUp,!0);t>=this._pointerUsed.length;)this._pointerUsed.push(!1);if(this.setPointerState(t,this._pointerUsed,!1),this.updatePointerPosition(e),!this._pointerPositionDown[t]){cr&&Di("Received pointer up event without matching down event for button: "+t),console.warn("Received pointer up event without matching down event for button: "+t);return}const r=e.clientX-this._pointerPositionDown[t].x,s=e.clientY-this._pointerPositionDown[t].y;if(t>=this._pointerUpTime.length&&this._pointerUpTime.push(-99),Math.abs(r)<5&&Math.abs(s)<5){cr&&console.log("CLICK",t),this.setPointerState(t,this._pointerClick,!0),e.isClick=!0;const o=this._pointerUpTime[t],a=this.context.time.time-o;a<this._doubleClickTimeThreshold&&a>0&&(this.setPointerState(t,this._pointerDoubleClick,!0),e.isDoubleClick=!0)}this._pointerUpTime[t]=this.context.time.time,this.onDispatchEvent(e)}updatePointerPosition(e){const t=e.pointerId;for(;t>=this._pointerPositions.length;)this._pointerPositions.push(new Z);for(;t>=this._pointerPositionsLastFrame.length;)this._pointerPositionsLastFrame.push(new Z);for(;t>=this._pointerPositionsDelta.length;)this._pointerPositionsDelta.push(new Z);const r=this._pointerPositionsLastFrame[t];r.copy(this._pointerPositions[t]);const s=this._pointerPositionsDelta[t];let o=e.clientX-r.x,a=e.clientY-r.y;if(e.source instanceof MouseEvent||e.source instanceof TouchEvent){const u=e.source;o===0&&u.movementX!==0&&(o=u.movementX||0),a===0&&u.movementY!==0&&(a=u.movementY||0)}s.x+=o,s.y+=a,this._pointerPositions[t].x=e.clientX,this._pointerPositions[t].y=e.clientY;const l=e.clientX,c=e.clientY;for(;t>=this._pointerPositionsRC.length;)this._pointerPositionsRC.push(new Z);const h=this._pointerPositionsRC[t];h.set(l,c),this.convertScreenspaceToRaycastSpace(h)}getPointerIndex(e){let t=-1;for(let r=0;r<this._pointerIds.length;r++){if(this._pointerIds[r]===e)return r;t===-1&&this._pointerIds[r]===-1&&(t=r)}return t!==-1?(this._pointerIds[t]=e,t):(cr&&console.log("PUSH pointerId:",e),this._pointerIds.push(e),this._pointerIds.length-1)}setPointerState(e,t,r){t[e]=r}setPointerStateT(e,t,r){return t[e]=r,r}onDispatchEvent(e){const t=kt.Current;try{kt.Current=this.context,this.dispatchEvent(e)}finally{kt.Current=t}}}const Y1=new ve().makeRotationY(Math.PI),Sa=new Ce().setFromAxisAngle(new C(0,1,0),Math.PI),wue=te("debugwebxr");class Sue{constructor(){if(d(this,"priority",-1e5),d(this,"gameObject"),this.gameObject=new ye,this.gameObject.name="Implicit XR Rig",wue){const e=fB(16733661);e.position.y+=.5,this.gameObject.add(e)}}isXRRig(){return!0}get isActive(){return this.gameObject.visible}}const Uu=te("debugwebxr"),J1=te("debugcustomgesture"),Cue="https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles",Eue="generic-trigger";class vB{constructor(e,t,r){d(this,"xr"),d(this,"inputSource"),d(this,"index",0),d(this,"emitEvents",!0),d(this,"_connected",!0),d(this,"_isTracking",!1),d(this,"_hitTestSource"),d(this,"_hasSelectEvent",!1),d(this,"_handJointPoses",new Map),d(this,"_gripPosition",new C),d(this,"_gripQuaternion",new Ce),d(this,"_linearVelocity",new C),d(this,"_rayPosition",new C),d(this,"_rayQuaternion",new Ce),d(this,"_gripWorldPosition",new C),d(this,"_gripWorldQuaternion",new Ce),d(this,"_rayWorldPosition",new C),d(this,"_rayWorldQuaternion",new Ce),d(this,"_ray"),d(this,"_object"),d(this,"model",null),d(this,"_debugAxesHelper",new Po(.2)),d(this,"onPointerHits",l=>{}),d(this,"_needleGamepadButtons",{}),d(this,"_buttonMap",new Map),d(this,"_motioncontroller"),d(this,"_layout"),d(this,"getMotionController"),d(this,"_selectButtonIndex"),d(this,"_squeezeButtonIndex"),d(this,"onSelectStart",l=>{var c,h,u,p;if(this.inputSource!==l.inputSource)return;this.onUpdateFrame(l.frame),this._hasSelectEvent=!0;const m=(c=this._layout)==null?void 0:c.selectComponentId,f=(p=(u=(h=this._layout)==null?void 0:h.components[m])==null?void 0:u.gamepadIndices)==null?void 0:p.button;f!==void 0&&(this._selectButtonIndex=f),!J1&&(Uu&&At.DrawDirection(this.rayWorldPosition,pi(0,.01,1).applyQuaternion(this.rayWorldQuaternion),16711680,10),this.emitPointerEvent(an.PointerDown,this._selectButtonIndex||0,"xr-standard-trigger",!0,l))}),d(this,"onSelectEnd",l=>{J1||this.inputSource===l.inputSource&&this.emitPointerEvent(an.PointerUp,this._selectButtonIndex||0,"xr-standard-trigger",!0,l)}),d(this,"onSequeezeStart",l=>{var c,h,u;this.inputSource===l.inputSource&&(this._squeezeButtonIndex=(u=(h=(c=this._layout)==null?void 0:c.components["xr-standard-squeeze"])==null?void 0:h.gamepadIndices)==null?void 0:u.button,this._squeezeButtonIndex!==void 0&&(Uu&&At.DrawDirection(this.rayWorldPosition,pi(0,.01,1).applyQuaternion(this.rayWorldQuaternion),255,10),this.emitPointerEvent(an.PointerDown,this._squeezeButtonIndex||0,"xr-standard-squeeze",!0,l)))}),d(this,"onSequeezeEnd",l=>{this.inputSource===l.inputSource&&this._squeezeButtonIndex!==void 0&&this.emitPointerEvent(an.PointerUp,this._squeezeButtonIndex||0,"xr-standard-squeeze",!0,l)}),d(this,"states",{}),d(this,"_didMoveLastFrame",!1),d(this,"_lastPointerMovePosition",new C),d(this,"_lastPointerMoveQuaternion",new Ce),d(this,"pointerInit");var s,o,a;this.xr=e,this.inputSource=t,this.index=r,this._object=new ye,Uu&&this._object.add(this._debugAxesHelper),this.xr.context.scene.add(this._object),this._ray=new co,this.pointerInit={origin:this,pointerType:this.hand?"hand":"controller",deviceIndex:this.index,pointerId:-1,mode:this.inputSource.targetRayMode,ray:this._ray,device:this._object,buttonName:"none"},this.initialize(),this.subscribeEvents(),this.xr.mode==="immersive-ar"&&this.inputSource.targetRayMode==="tracked-pointer"&&((a=(o=(s=this.xr.session).requestHitTestSourceForTransientInput)==null?void 0:o.call(s,{profile:this.inputSource.profiles[0],offsetRay:new XRRay}))==null||a.then(l=>this._hitTestSource=l))}get context(){return this.xr.context}get connected(){return this._connected}get isTracking(){return this._isTracking}get gamepad(){return this.inputSource.gamepad}get isHand(){return this.inputSource.hand!=null}get hand(){return this.inputSource.hand}get handObject(){return this.context.renderer.xr.getHand(this.index)}get profiles(){return this.inputSource.profiles}get layout(){return this._layout}get targetRayMode(){return this.inputSource.targetRayMode}get targetRaySpace(){return this.inputSource.targetRaySpace}get gripSpace(){return this.inputSource.gripSpace}get side(){return this.inputSource.handedness}get isRight(){return this.side==="right"}get isLeft(){return this.side==="left"}get hitTestSource(){return this._hitTestSource}get hasSelectEvent(){return this._hasSelectEvent}getHitTest(){return this.xr.getHitTest(this)}getHandJointPose(e){var t,r;if(!this.hand||!((t=this.xr.frame)!=null&&t.getJointPose)||!this.xr.referenceSpace)return null;let s=(r=this._handJointPoses)==null?void 0:r.get(e);return s||(s=this.xr.frame.getJointPose(e,this.xr.referenceSpace),s&&this._handJointPoses.set(e,s),s)}get gripPosition(){return pi(this._gripPosition).applyMatrix4(Y1)}get gripQuaternion(){return bp(this._gripQuaternion).premultiply(Sa)}get gripLinearVelocity(){return pi(this._linearVelocity).applyQuaternion(Sa)}get rayPosition(){return pi(this._rayPosition).applyMatrix4(Y1)}get rayQuaternion(){return bp(this._rayQuaternion).premultiply(Sa)}get gripWorldPosition(){return pi(this._gripWorldPosition)}get gripWorldQuaternion(){return bp(this._gripWorldQuaternion)}get rayWorldPosition(){return pi(this._rayWorldPosition)}updateRayWorldPosition(){var e;const t=(e=this.xr.context.mainCamera)==null?void 0:e.parent;this._rayWorldPosition.copy(this._rayPosition),t&&this._rayWorldPosition.applyMatrix4(t.matrixWorld)}get rayWorldQuaternion(){return bp(this._rayWorldQuaternion)}updateRayWorldQuaternion(){var e;const t=(e=this.xr.context.mainCamera)==null?void 0:e.parent,r=t?Mi(t):void 0;this._rayWorldQuaternion.copy(this._rayQuaternion).multiply(Sa),r&&this._rayWorldQuaternion.premultiply(r)}get ray(){return this._ray.origin.copy(this.rayWorldPosition),this._ray.direction.copy(pi(0,0,1).applyQuaternion(this.rayWorldQuaternion)),this._ray}get object(){return this._object}async getModelUrl(){var e;return(e=this.getMotionController)==null?void 0:e.then(t=>t?.assetUrl||null)}onUpdate(e){this.onUpdateFrame(e),this.updateInputEvents(),this.onUpdateMove()}onRenderDebug(){var e;At.DrawWireSphere(this.rayWorldPosition,.02),At.DrawDirection(this.rayWorldPosition,pi(0,0,10).applyQuaternion(this.rayWorldQuaternion));const t=this.gripWorldPosition.sub(this.object.worldForward.multiplyScalar(.1)),r=this.inputSource.profiles.join(`
|
|
5152
5152
|
`);let s=`Controller[${this.index}] ${this.side}
|
|
5153
5153
|
C:${this.connected?"yes":"no"} T:${this.isTracking?"yes":"no"} Hand:${this.inputSource.hand?"yes":"no"}`;this.inputSource.hand&&(s+=`
|
|
5154
5154
|
Pinch: ${(e=this.getGesture("pinch"))==null?void 0:e.value.toFixed(3)}`),s+=`
|
|
@@ -5232,7 +5232,7 @@ a=extmap-allow-mixed`)!==-1){const s=r.sdp.split(`
|
|
|
5232
5232
|
isUnifiedPlanSupported:`).concat(this.isUnifiedPlanSupported())},n}()),FG={iceServers:[{urls:"stun:stun.l.google.com:19302"},{urls:["turn:eu-0.turn.peerjs.com:3478","turn:us-0.turn.peerjs.com:3478"],username:"peerjs",credential:"peerjsp"}],sdpSemantics:"unified-plan"},Hue=function(){function n(){this.CLOUD_HOST="0.peerjs.com",this.CLOUD_PORT=443,this.chunkedBrowsers={Chrome:1,chrome:1},this.chunkedMTU=16300,this.defaultConfig=FG,this.browser=Zy.getBrowser(),this.browserVersion=Zy.getVersion(),this.supports=function(){var e={browser:Zy.isBrowserSupported(),webRTC:Zy.isWebRTCSupported(),audioVideo:!1,data:!1,binaryBlob:!1,reliable:!1};if(!e.webRTC)return e;var t;try{t=new RTCPeerConnection(FG),e.audioVideo=!0;var r=void 0;try{r=t.createDataChannel("_PEERJSTEST",{ordered:!0}),e.data=!0,e.reliable=!!r.ordered;try{r.binaryType="blob",e.binaryBlob=!Zy.isIOS}catch{}}catch{}finally{r&&r.close()}}catch{}finally{t&&t.close()}return e}(),this.pack=Q6.pack,this.unpack=Q6.unpack,this._dataCount=1}return n.prototype.noop=function(){},n.prototype.validateId=function(e){return!e||/^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/.test(e)},n.prototype.chunk=function(e){for(var t=[],r=e.size,s=Math.ceil(r/wi.chunkedMTU),o=0,a=0;a<r;){var l=Math.min(r,a+wi.chunkedMTU),c=e.slice(a,l),h={__peerData:this._dataCount,n:o,data:c,total:s};t.push(h),a=l,o++}return this._dataCount++,t},n.prototype.blobToArrayBuffer=function(e,t){var r=new FileReader;return r.onload=function(s){s.target&&t(s.target.result)},r.readAsArrayBuffer(e),r},n.prototype.binaryStringToArrayBuffer=function(e){for(var t=new Uint8Array(e.length),r=0;r<e.length;r++)t[r]=e.charCodeAt(r)&255;return t.buffer},n.prototype.randomToken=function(){return Math.random().toString(36).slice(2)},n.prototype.isSecure=function(){return location.protocol==="https:"},n}(),wi=new Hue,UG={};Kl(UG,"Peer",()=>UB,n=>UB=n);var $y={},Wue=Object.prototype.hasOwnProperty,Ks="~";function eA(){}Object.create&&(eA.prototype=Object.create(null),new eA().__proto__||(Ks=!1));function Xue(n,e,t){this.fn=n,this.context=e,this.once=t||!1}function NG(n,e,t,r,s){if(typeof t!="function")throw new TypeError("The listener must be a function");var o=new Xue(t,r||n,s),a=Ks?Ks+e:e;return n._events[a]?n._events[a].fn?n._events[a]=[n._events[a],o]:n._events[a].push(o):(n._events[a]=o,n._eventsCount++),n}function rS(n,e){--n._eventsCount===0?n._events=new eA:delete n._events[e]}function Cs(){this._events=new eA,this._eventsCount=0}Cs.prototype.eventNames=function(){var n=[],e,t;if(this._eventsCount===0)return n;for(t in e=this._events)Wue.call(e,t)&&n.push(Ks?t.slice(1):t);return Object.getOwnPropertySymbols?n.concat(Object.getOwnPropertySymbols(e)):n},Cs.prototype.listeners=function(n){var e=Ks?Ks+n:n,t=this._events[e];if(!t)return[];if(t.fn)return[t.fn];for(var r=0,s=t.length,o=new Array(s);r<s;r++)o[r]=t[r].fn;return o},Cs.prototype.listenerCount=function(n){var e=Ks?Ks+n:n,t=this._events[e];return t?t.fn?1:t.length:0},Cs.prototype.emit=function(n,e,t,r,s,o){var a=Ks?Ks+n:n;if(!this._events[a])return!1;var l=this._events[a],c=arguments.length,h,u;if(l.fn){switch(l.once&&this.removeListener(n,l.fn,void 0,!0),c){case 1:return l.fn.call(l.context),!0;case 2:return l.fn.call(l.context,e),!0;case 3:return l.fn.call(l.context,e,t),!0;case 4:return l.fn.call(l.context,e,t,r),!0;case 5:return l.fn.call(l.context,e,t,r,s),!0;case 6:return l.fn.call(l.context,e,t,r,s,o),!0}for(u=1,h=new Array(c-1);u<c;u++)h[u-1]=arguments[u];l.fn.apply(l.context,h)}else{var p=l.length,m;for(u=0;u<p;u++)switch(l[u].once&&this.removeListener(n,l[u].fn,void 0,!0),c){case 1:l[u].fn.call(l[u].context);break;case 2:l[u].fn.call(l[u].context,e);break;case 3:l[u].fn.call(l[u].context,e,t);break;case 4:l[u].fn.call(l[u].context,e,t,r);break;default:if(!h)for(m=1,h=new Array(c-1);m<c;m++)h[m-1]=arguments[m];l[u].fn.apply(l[u].context,h)}}return!0},Cs.prototype.on=function(n,e,t){return NG(this,n,e,t,!1)},Cs.prototype.once=function(n,e,t){return NG(this,n,e,t,!0)},Cs.prototype.removeListener=function(n,e,t,r){var s=Ks?Ks+n:n;if(!this._events[s])return this;if(!e)return rS(this,s),this;var o=this._events[s];if(o.fn)o.fn===e&&(!r||o.once)&&(!t||o.context===t)&&rS(this,s);else{for(var a=0,l=[],c=o.length;a<c;a++)(o[a].fn!==e||r&&!o[a].once||t&&o[a].context!==t)&&l.push(o[a]);l.length?this._events[s]=l.length===1?l[0]:l:rS(this,s)}return this},Cs.prototype.removeAllListeners=function(n){var e;return n?(e=Ks?Ks+n:n,this._events[e]&&rS(this,e)):(this._events=new eA,this._eventsCount=0),this},Cs.prototype.off=Cs.prototype.removeListener,Cs.prototype.addListener=Cs.prototype.on,Cs.prefixed=Ks,Cs.EventEmitter=Cs,$y=Cs;var dt={};Kl(dt,"LogLevel",()=>yo,n=>yo=n),Kl(dt,"default",()=>zG,n=>zG=n);var Xp=function(n,e){var t=typeof Symbol=="function"&&n[Symbol.iterator];if(!t)return n;var r=t.call(n),s,o=[],a;try{for(;(e===void 0||e-- >0)&&!(s=r.next()).done;)o.push(s.value)}catch(l){a={error:l}}finally{try{s&&!s.done&&(t=r.return)&&t.call(r)}finally{if(a)throw a.error}}return o},qp=function(n,e,t){if(t||arguments.length===2)for(var r=0,s=e.length,o;r<s;r++)(o||!(r in e))&&(o||(o=Array.prototype.slice.call(e,0,r)),o[r]=e[r]);return n.concat(o||Array.prototype.slice.call(e))},que="PeerJS: ",yo;(function(n){n[n.Disabled=0]="Disabled",n[n.Errors=1]="Errors",n[n.Warnings=2]="Warnings",n[n.All=3]="All"})(yo||(yo={}));var Yue=function(){function n(){this._logLevel=yo.Disabled}return Object.defineProperty(n.prototype,"logLevel",{get:function(){return this._logLevel},set:function(e){this._logLevel=e},enumerable:!1,configurable:!0}),n.prototype.log=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this._logLevel>=yo.All&&this._print.apply(this,qp([yo.All],Xp(e),!1))},n.prototype.warn=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this._logLevel>=yo.Warnings&&this._print.apply(this,qp([yo.Warnings],Xp(e),!1))},n.prototype.error=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this._logLevel>=yo.Errors&&this._print.apply(this,qp([yo.Errors],Xp(e),!1))},n.prototype.setLogFunction=function(e){this._print=e},n.prototype._print=function(e){for(var t=[],r=1;r<arguments.length;r++)t[r-1]=arguments[r];var s=qp([que],Xp(t),!1);for(var o in s)s[o]instanceof Error&&(s[o]="("+s[o].name+") "+s[o].message);e>=yo.All?console.log.apply(console,qp([],Xp(s),!1)):e>=yo.Warnings?console.warn.apply(console,qp(["WARNING"],Xp(s),!1)):e>=yo.Errors&&console.error.apply(console,qp(["ERROR"],Xp(s),!1))},n}(),zG=new Yue,jG={};Kl(jG,"Socket",()=>GG,n=>GG=n);var pl;(function(n){n.Data="data",n.Media="media"})(pl||(pl={}));var Fn;(function(n){n.BrowserIncompatible="browser-incompatible",n.Disconnected="disconnected",n.InvalidID="invalid-id",n.InvalidKey="invalid-key",n.Network="network",n.PeerUnavailable="peer-unavailable",n.SslUnavailable="ssl-unavailable",n.ServerError="server-error",n.SocketError="socket-error",n.SocketClosed="socket-closed",n.UnavailableID="unavailable-id",n.WebRTC="webrtc"})(Fn||(Fn={}));var gh;(function(n){n.Binary="binary",n.BinaryUTF8="binary-utf8",n.JSON="json"})(gh||(gh={}));var vh;(function(n){n.Message="message",n.Disconnected="disconnected",n.Error="error",n.Close="close"})(vh||(vh={}));var Qr;(function(n){n.Heartbeat="HEARTBEAT",n.Candidate="CANDIDATE",n.Offer="OFFER",n.Answer="ANSWER",n.Open="OPEN",n.Error="ERROR",n.IdTaken="ID-TAKEN",n.InvalidKey="INVALID-KEY",n.Leave="LEAVE",n.Expire="EXPIRE"})(Qr||(Qr={}));var kB={};kB=JSON.parse('{"name":"peerjs","version":"1.4.7","keywords":["peerjs","webrtc","p2p","rtc"],"description":"PeerJS client","homepage":"https://peerjs.com","bugs":{"url":"https://github.com/peers/peerjs/issues"},"repository":{"type":"git","url":"https://github.com/peers/peerjs"},"license":"MIT","contributors":["Michelle Bu <michelle@michellebu.com>","afrokick <devbyru@gmail.com>","ericz <really.ez@gmail.com>","Jairo <kidandcat@gmail.com>","Jonas Gloning <34194370+jonasgloning@users.noreply.github.com>","Jairo Caro-Accino Viciana <jairo@galax.be>","Carlos Caballero <carlos.caballero.gonzalez@gmail.com>","hc <hheennrryy@gmail.com>","Muhammad Asif <capripio@gmail.com>","PrashoonB <prashoonbhattacharjee@gmail.com>","Harsh Bardhan Mishra <47351025+HarshCasper@users.noreply.github.com>","akotynski <aleksanderkotbury@gmail.com>","lmb <i@lmb.io>","Jairooo <jairocaro@msn.com>","Moritz St\xFCckler <moritz.stueckler@gmail.com>","Simon <crydotsnakegithub@gmail.com>","Denis Lukov <denismassters@gmail.com>","Philipp Hancke <fippo@andyet.net>","Hans Oksendahl <hansoksendahl@gmail.com>","Jess <jessachandler@gmail.com>","khankuan <khankuan@gmail.com>","DUODVK <kurmanov.work@gmail.com>","XiZhao <kwang1imsa@gmail.com>","Matthias Lohr <matthias@lohr.me>","=frank tree <=frnktrb@googlemail.com>","Andre Eckardt <aeckardt@outlook.com>","Chris Cowan <agentme49@gmail.com>","Alex Chuev <alex@chuev.com>","alxnull <alxnull@e.mail.de>","Yemel Jardi <angel.jardi@gmail.com>","Ben Parnell <benjaminparnell.94@gmail.com>","Benny Lichtner <bennlich@gmail.com>","fresheneesz <bitetrudpublic@gmail.com>","bob.barstead@exaptive.com <bob.barstead@exaptive.com>","chandika <chandika@gmail.com>","emersion <contact@emersion.fr>","Christopher Van <cvan@users.noreply.github.com>","eddieherm <edhermoso@gmail.com>","Eduardo Pinho <enet4mikeenet@gmail.com>","Evandro Zanatta <ezanatta@tray.net.br>","Gardner Bickford <gardner@users.noreply.github.com>","Gian Luca <gianluca.cecchi@cynny.com>","PatrickJS <github@gdi2290.com>","jonnyf <github@jonathanfoss.co.uk>","Hizkia Felix <hizkifw@gmail.com>","Hristo Oskov <hristo.oskov@gmail.com>","Isaac Madwed <i.madwed@gmail.com>","Ilya Konanykhin <ilya.konanykhin@gmail.com>","jasonbarry <jasbarry@me.com>","Jonathan Burke <jonathan.burke.1311@googlemail.com>","Josh Hamit <josh.hamit@gmail.com>","Jordan Austin <jrax86@gmail.com>","Joel Wetzell <jwetzell@yahoo.com>","xizhao <kevin.wang@cloudera.com>","Alberto Torres <kungfoobar@gmail.com>","Jonathan Mayol <mayoljonathan@gmail.com>","Jefferson Felix <me@jsfelix.dev>","Rolf Erik Lekang <me@rolflekang.com>","Kevin Mai-Husan Chia <mhchia@users.noreply.github.com>","Pepijn de Vos <pepijndevos@gmail.com>","JooYoung <qkdlql@naver.com>","Tobias Speicher <rootcommander@gmail.com>","Steve Blaurock <sblaurock@gmail.com>","Kyrylo Shegeda <shegeda@ualberta.ca>","Diwank Singh Tomer <singh@diwank.name>","So\u0308ren Balko <Soeren.Balko@gmail.com>","Arpit Solanki <solankiarpit1997@gmail.com>","Yuki Ito <yuki@gnnk.net>","Artur Zayats <zag2art@gmail.com>"],"funding":{"type":"opencollective","url":"https://opencollective.com/peer"},"collective":{"type":"opencollective","url":"https://opencollective.com/peer"},"files":["dist/*"],"sideEffects":["lib/global.ts","lib/supports.ts"],"main":"dist/bundler.cjs","module":"dist/bundler.mjs","browser-minified":"dist/peerjs.min.js","browser-unminified":"dist/peerjs.js","types":"dist/types.d.ts","engines":{"node":">= 10"},"targets":{"types":{"source":"lib/exports.ts"},"main":{"source":"lib/exports.ts","sourceMap":{"inlineSources":true}},"module":{"source":"lib/exports.ts","includeNodeModules":["eventemitter3"],"sourceMap":{"inlineSources":true}},"browser-minified":{"context":"browser","outputFormat":"global","optimize":true,"engines":{"browsers":"cover 99%, not dead"},"source":"lib/global.ts"},"browser-unminified":{"context":"browser","outputFormat":"global","optimize":false,"engines":{"browsers":"cover 99%, not dead"},"source":"lib/global.ts"}},"scripts":{"contributors":"git-authors-cli --print=false && prettier --write package.json && git add package.json package-lock.json && git commit -m \\"chore(contributors): update and sort contributors list\\"","check":"tsc --noEmit","watch":"parcel watch","build":"rm -rf dist && parcel build","prepublishOnly":"npm run build","test":"mocha -r ts-node/register -r jsdom-global/register test/**/*.ts","format":"prettier --write .","semantic-release":"semantic-release"},"devDependencies":{"@parcel/config-default":"^2.5.0","@parcel/packager-ts":"^2.5.0","@parcel/transformer-typescript-tsc":"^2.5.0","@parcel/transformer-typescript-types":"^2.5.0","@semantic-release/changelog":"^6.0.1","@semantic-release/git":"^10.0.1","@types/chai":"^4.3.0","@types/mocha":"^9.1.0","@types/node":"^17.0.18","chai":"^4.3.6","git-authors-cli":"^1.0.40","jsdom":"^19.0.0","jsdom-global":"^3.0.2","mocha":"^9.2.0","mock-socket":"8.0.5","parcel":"^2.5.0","parcel-transformer-tsc-sourcemaps":"^1.0.2","prettier":"^2.6.2","semantic-release":"^19.0.2","standard":"^16.0.4","ts-node":"^10.5.0","typescript":"^4.5.5"},"dependencies":{"@swc/helpers":"^0.3.13","eventemitter3":"^4.0.7","peerjs-js-binarypack":"1.0.1","webrtc-adapter":"^7.7.1"}}');var Jue=function(){var n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,s){r.__proto__=s}||function(r,s){for(var o in s)Object.prototype.hasOwnProperty.call(s,o)&&(r[o]=s[o])},n(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");n(e,t);function r(){this.constructor=e}e.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}}(),Kue=function(n,e){var t=typeof Symbol=="function"&&n[Symbol.iterator];if(!t)return n;var r=t.call(n),s,o=[],a;try{for(;(e===void 0||e-- >0)&&!(s=r.next()).done;)o.push(s.value)}catch(l){a={error:l}}finally{try{s&&!s.done&&(t=r.return)&&t.call(r)}finally{if(a)throw a.error}}return o},Zue=function(n,e,t){if(t||arguments.length===2)for(var r=0,s=e.length,o;r<s;r++)(o||!(r in e))&&(o||(o=Array.prototype.slice.call(e,0,r)),o[r]=e[r]);return n.concat(o||Array.prototype.slice.call(e))},$ue=function(n){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&n[e],r=0;if(t)return t.call(n);if(n&&typeof n.length=="number")return{next:function(){return n&&r>=n.length&&(n=void 0),{value:n&&n[r++],done:!n}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},GG=function(n){Jue(e,n);function e(t,r,s,o,a,l){l===void 0&&(l=5e3);var c=n.call(this)||this;c.pingInterval=l,c._disconnected=!0,c._messagesQueue=[];var h=t?"wss://":"ws://";return c._baseUrl=h+r+":"+s+o+"peerjs?key="+a,c}return e.prototype.start=function(t,r){var s=this;this._id=t;var o="".concat(this._baseUrl,"&id=").concat(t,"&token=").concat(r);this._socket||!this._disconnected||(this._socket=new WebSocket(o+"&version="+kB.version),this._disconnected=!1,this._socket.onmessage=function(a){var l;try{l=JSON.parse(a.data),dt.default.log("Server message received:",l)}catch{dt.default.log("Invalid server message",a.data);return}s.emit(vh.Message,l)},this._socket.onclose=function(a){s._disconnected||(dt.default.log("Socket closed.",a),s._cleanup(),s._disconnected=!0,s.emit(vh.Disconnected))},this._socket.onopen=function(){s._disconnected||(s._sendQueuedMessages(),dt.default.log("Socket open"),s._scheduleHeartbeat())})},e.prototype._scheduleHeartbeat=function(){var t=this;this._wsPingTimer=setTimeout(function(){t._sendHeartbeat()},this.pingInterval)},e.prototype._sendHeartbeat=function(){if(!this._wsOpen()){dt.default.log("Cannot send heartbeat, because socket closed");return}var t=JSON.stringify({type:Qr.Heartbeat});this._socket.send(t),this._scheduleHeartbeat()},e.prototype._wsOpen=function(){return!!this._socket&&this._socket.readyState===1},e.prototype._sendQueuedMessages=function(){var t,r,s=Zue([],Kue(this._messagesQueue),!1);this._messagesQueue=[];try{for(var o=$ue(s),a=o.next();!a.done;a=o.next()){var l=a.value;this.send(l)}}catch(c){t={error:c}}finally{try{a&&!a.done&&(r=o.return)&&r.call(o)}finally{if(t)throw t.error}}},e.prototype.send=function(t){if(!this._disconnected){if(!this._id){this._messagesQueue.push(t);return}if(!t.type){this.emit(vh.Error,"Invalid message");return}if(this._wsOpen()){var r=JSON.stringify(t);this._socket.send(r)}}},e.prototype.close=function(){this._disconnected||(this._cleanup(),this._disconnected=!0)},e.prototype._cleanup=function(){this._socket&&(this._socket.onopen=this._socket.onmessage=this._socket.onclose=null,this._socket.close(),this._socket=void 0),clearTimeout(this._wsPingTimer)},e}($y.EventEmitter),DB={};Kl(DB,"MediaConnection",()=>HG,n=>HG=n);var OB={};Kl(OB,"Negotiator",()=>VG,n=>VG=n);var sS=function(){return sS=Object.assign||function(n){for(var e,t=1,r=arguments.length;t<r;t++){e=arguments[t];for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&(n[s]=e[s])}return n},sS.apply(this,arguments)},oS=function(n,e,t,r){function s(o){return o instanceof t?o:new t(function(a){a(o)})}return new(t||(t=Promise))(function(o,a){function l(u){try{h(r.next(u))}catch(p){a(p)}}function c(u){try{h(r.throw(u))}catch(p){a(p)}}function h(u){u.done?o(u.value):s(u.value).then(l,c)}h((r=r.apply(n,e||[])).next())})},aS=function(n,e){var t={label:0,sent:function(){if(o[0]&1)throw o[1];return o[1]},trys:[],ops:[]},r,s,o,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(h){return function(u){return c([h,u])}}function c(h){if(r)throw new TypeError("Generator is already executing.");for(;t;)try{if(r=1,s&&(o=h[0]&2?s.return:h[0]?s.throw||((o=s.return)&&o.call(s),0):s.next)&&!(o=o.call(s,h[1])).done)return o;switch(s=0,o&&(h=[h[0]&2,o.value]),h[0]){case 0:case 1:o=h;break;case 4:return t.label++,{value:h[1],done:!1};case 5:t.label++,s=h[1],h=[0];continue;case 7:h=t.ops.pop(),t.trys.pop();continue;default:if(o=t.trys,!(o=o.length>0&&o[o.length-1])&&(h[0]===6||h[0]===2)){t=0;continue}if(h[0]===3&&(!o||h[1]>o[0]&&h[1]<o[3])){t.label=h[1];break}if(h[0]===6&&t.label<o[1]){t.label=o[1],o=h;break}if(o&&t.label<o[2]){t.label=o[2],t.ops.push(h);break}o[2]&&t.ops.pop(),t.trys.pop();continue}h=e.call(n,t)}catch(u){h=[6,u],s=0}finally{r=o=0}if(h[0]&5)throw h[1];return{value:h[0]?h[1]:void 0,done:!0}}},VG=function(){function n(e){this.connection=e}return n.prototype.startConnection=function(e){var t=this._startPeerConnection();if(this.connection.peerConnection=t,this.connection.type===pl.Media&&e._stream&&this._addTracksToConnection(e._stream,t),e.originator){if(this.connection.type===pl.Data){var r=this.connection,s={ordered:!!e.reliable},o=t.createDataChannel(r.label,s);r.initialize(o)}this._makeOffer()}else this.handleSDP("OFFER",e.sdp)},n.prototype._startPeerConnection=function(){dt.default.log("Creating RTCPeerConnection.");var e=new RTCPeerConnection(this.connection.provider.options.config);return this._setupListeners(e),e},n.prototype._setupListeners=function(e){var t=this,r=this.connection.peer,s=this.connection.connectionId,o=this.connection.type,a=this.connection.provider;dt.default.log("Listening for ICE candidates."),e.onicecandidate=function(l){!l.candidate||!l.candidate.candidate||(dt.default.log("Received ICE candidates for ".concat(r,":"),l.candidate),a.socket.send({type:Qr.Candidate,payload:{candidate:l.candidate,type:o,connectionId:s},dst:r}))},e.oniceconnectionstatechange=function(){switch(e.iceConnectionState){case"failed":dt.default.log("iceConnectionState is failed, closing connections to "+r),t.connection.emit("error",new Error("Negotiation of connection to "+r+" failed.")),t.connection.close();break;case"closed":dt.default.log("iceConnectionState is closed, closing connections to "+r),t.connection.emit("error",new Error("Connection to "+r+" closed.")),t.connection.close();break;case"disconnected":dt.default.log("iceConnectionState changed to disconnected on the connection with "+r);break;case"completed":e.onicecandidate=wi.noop;break}t.connection.emit("iceStateChanged",e.iceConnectionState)},dt.default.log("Listening for data channel"),e.ondatachannel=function(l){dt.default.log("Received data channel");var c=l.channel,h=a.getConnection(r,s);h.initialize(c)},dt.default.log("Listening for remote stream"),e.ontrack=function(l){dt.default.log("Received remote stream");var c=l.streams[0],h=a.getConnection(r,s);if(h.type===pl.Media){var u=h;t._addStreamToMediaConnection(c,u)}}},n.prototype.cleanup=function(){dt.default.log("Cleaning up PeerConnection to "+this.connection.peer);var e=this.connection.peerConnection;if(e){this.connection.peerConnection=null,e.onicecandidate=e.oniceconnectionstatechange=e.ondatachannel=e.ontrack=function(){};var t=e.signalingState!=="closed",r=!1;if(this.connection.type===pl.Data){var s=this.connection,o=s.dataChannel;o&&(r=!!o.readyState&&o.readyState!=="closed")}(t||r)&&e.close()}},n.prototype._makeOffer=function(){return oS(this,void 0,Promise,function(){var e,t,r,s,o,a,l;return aS(this,function(c){switch(c.label){case 0:e=this.connection.peerConnection,t=this.connection.provider,c.label=1;case 1:return c.trys.push([1,7,,8]),[4,e.createOffer(this.connection.options.constraints)];case 2:r=c.sent(),dt.default.log("Created offer."),this.connection.options.sdpTransform&&typeof this.connection.options.sdpTransform=="function"&&(r.sdp=this.connection.options.sdpTransform(r.sdp)||r.sdp),c.label=3;case 3:return c.trys.push([3,5,,6]),[4,e.setLocalDescription(r)];case 4:return c.sent(),dt.default.log("Set localDescription:",r,"for:".concat(this.connection.peer)),s={sdp:r,type:this.connection.type,connectionId:this.connection.connectionId,metadata:this.connection.metadata,browser:wi.browser},this.connection.type===pl.Data&&(o=this.connection,s=sS(sS({},s),{label:o.label,reliable:o.reliable,serialization:o.serialization})),t.socket.send({type:Qr.Offer,payload:s,dst:this.connection.peer}),[3,6];case 5:return a=c.sent(),a!="OperationError: Failed to set local offer sdp: Called in wrong state: kHaveRemoteOffer"&&(t.emitError(Fn.WebRTC,a),dt.default.log("Failed to setLocalDescription, ",a)),[3,6];case 6:return[3,8];case 7:return l=c.sent(),t.emitError(Fn.WebRTC,l),dt.default.log("Failed to createOffer, ",l),[3,8];case 8:return[2]}})})},n.prototype._makeAnswer=function(){return oS(this,void 0,Promise,function(){var e,t,r,s,o;return aS(this,function(a){switch(a.label){case 0:e=this.connection.peerConnection,t=this.connection.provider,a.label=1;case 1:return a.trys.push([1,7,,8]),[4,e.createAnswer()];case 2:r=a.sent(),dt.default.log("Created answer."),this.connection.options.sdpTransform&&typeof this.connection.options.sdpTransform=="function"&&(r.sdp=this.connection.options.sdpTransform(r.sdp)||r.sdp),a.label=3;case 3:return a.trys.push([3,5,,6]),[4,e.setLocalDescription(r)];case 4:return a.sent(),dt.default.log("Set localDescription:",r,"for:".concat(this.connection.peer)),t.socket.send({type:Qr.Answer,payload:{sdp:r,type:this.connection.type,connectionId:this.connection.connectionId,browser:wi.browser},dst:this.connection.peer}),[3,6];case 5:return s=a.sent(),t.emitError(Fn.WebRTC,s),dt.default.log("Failed to setLocalDescription, ",s),[3,6];case 6:return[3,8];case 7:return o=a.sent(),t.emitError(Fn.WebRTC,o),dt.default.log("Failed to create answer, ",o),[3,8];case 8:return[2]}})})},n.prototype.handleSDP=function(e,t){return oS(this,void 0,Promise,function(){var r,s,o,a;return aS(this,function(l){switch(l.label){case 0:t=new RTCSessionDescription(t),r=this.connection.peerConnection,s=this.connection.provider,dt.default.log("Setting remote description",t),o=this,l.label=1;case 1:return l.trys.push([1,5,,6]),[4,r.setRemoteDescription(t)];case 2:return l.sent(),dt.default.log("Set remoteDescription:".concat(e," for:").concat(this.connection.peer)),e!=="OFFER"?[3,4]:[4,o._makeAnswer()];case 3:l.sent(),l.label=4;case 4:return[3,6];case 5:return a=l.sent(),s.emitError(Fn.WebRTC,a),dt.default.log("Failed to setRemoteDescription, ",a),[3,6];case 6:return[2]}})})},n.prototype.handleCandidate=function(e){return oS(this,void 0,Promise,function(){var t,r,s,o,a,l;return aS(this,function(c){switch(c.label){case 0:dt.default.log("handleCandidate:",e),t=e.candidate,r=e.sdpMLineIndex,s=e.sdpMid,o=this.connection.peerConnection,a=this.connection.provider,c.label=1;case 1:return c.trys.push([1,3,,4]),[4,o.addIceCandidate(new RTCIceCandidate({sdpMid:s,sdpMLineIndex:r,candidate:t}))];case 2:return c.sent(),dt.default.log("Added ICE candidate for:".concat(this.connection.peer)),[3,4];case 3:return l=c.sent(),a.emitError(Fn.WebRTC,l),dt.default.log("Failed to handleCandidate, ",l),[3,4];case 4:return[2]}})})},n.prototype._addTracksToConnection=function(e,t){if(dt.default.log("add tracks from stream ".concat(e.id," to peer connection")),!t.addTrack)return dt.default.error("Your browser does't support RTCPeerConnection#addTrack. Ignored.");e.getTracks().forEach(function(r){t.addTrack(r,e)})},n.prototype._addStreamToMediaConnection=function(e,t){dt.default.log("add stream ".concat(e.id," to media connection ").concat(t.connectionId)),t.addStream(e)},n}(),LB={};Kl(LB,"BaseConnection",()=>QG,n=>QG=n);var ede=function(){var n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,s){r.__proto__=s}||function(r,s){for(var o in s)Object.prototype.hasOwnProperty.call(s,o)&&(r[o]=s[o])},n(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");n(e,t);function r(){this.constructor=e}e.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}}(),QG=function(n){ede(e,n);function e(t,r,s){var o=n.call(this)||this;return o.peer=t,o.provider=r,o.options=s,o._open=!1,o.metadata=s.metadata,o}return Object.defineProperty(e.prototype,"open",{get:function(){return this._open},enumerable:!1,configurable:!0}),e}($y.EventEmitter),tde=function(){var n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,s){r.__proto__=s}||function(r,s){for(var o in s)Object.prototype.hasOwnProperty.call(s,o)&&(r[o]=s[o])},n(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");n(e,t);function r(){this.constructor=e}e.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}}(),lS=function(){return lS=Object.assign||function(n){for(var e,t=1,r=arguments.length;t<r;t++){e=arguments[t];for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&(n[s]=e[s])}return n},lS.apply(this,arguments)},ide=function(n){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&n[e],r=0;if(t)return t.call(n);if(n&&typeof n.length=="number")return{next:function(){return n&&r>=n.length&&(n=void 0),{value:n&&n[r++],done:!n}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},HG=function(n){tde(e,n);function e(t,r,s){var o=n.call(this,t,r,s)||this;return o._localStream=o.options._stream,o.connectionId=o.options.connectionId||e.ID_PREFIX+wi.randomToken(),o._negotiator=new OB.Negotiator(o),o._localStream&&o._negotiator.startConnection({_stream:o._localStream,originator:!0}),o}return Object.defineProperty(e.prototype,"type",{get:function(){return pl.Media},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"localStream",{get:function(){return this._localStream},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"remoteStream",{get:function(){return this._remoteStream},enumerable:!1,configurable:!0}),e.prototype.addStream=function(t){dt.default.log("Receiving stream",t),this._remoteStream=t,n.prototype.emit.call(this,"stream",t)},e.prototype.handleMessage=function(t){var r=t.type,s=t.payload;switch(t.type){case Qr.Answer:this._negotiator.handleSDP(r,s.sdp),this._open=!0;break;case Qr.Candidate:this._negotiator.handleCandidate(s.candidate);break;default:dt.default.warn("Unrecognized message type:".concat(r," from peer:").concat(this.peer));break}},e.prototype.answer=function(t,r){var s,o;if(r===void 0&&(r={}),this._localStream){dt.default.warn("Local stream already exists on this MediaConnection. Are you answering a call twice?");return}this._localStream=t,r&&r.sdpTransform&&(this.options.sdpTransform=r.sdpTransform),this._negotiator.startConnection(lS(lS({},this.options._payload),{_stream:t}));var a=this.provider._getMessages(this.connectionId);try{for(var l=ide(a),c=l.next();!c.done;c=l.next()){var h=c.value;this.handleMessage(h)}}catch(u){s={error:u}}finally{try{c&&!c.done&&(o=l.return)&&o.call(l)}finally{if(s)throw s.error}}this._open=!0},e.prototype.close=function(){this._negotiator&&(this._negotiator.cleanup(),this._negotiator=null),this._localStream=null,this._remoteStream=null,this.provider&&(this.provider._removeConnection(this),this.provider=null),this.options&&this.options._stream&&(this.options._stream=null),this.open&&(this._open=!1,n.prototype.emit.call(this,"close"))},e.ID_PREFIX="mc_",e}(LB.BaseConnection),FB={};Kl(FB,"DataConnection",()=>qG,n=>qG=n);var WG={};Kl(WG,"EncodingQueue",()=>XG,n=>XG=n);var nde=function(){var n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,s){r.__proto__=s}||function(r,s){for(var o in s)Object.prototype.hasOwnProperty.call(s,o)&&(r[o]=s[o])},n(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");n(e,t);function r(){this.constructor=e}e.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}}(),XG=function(n){nde(e,n);function e(){var t=n.call(this)||this;return t.fileReader=new FileReader,t._queue=[],t._processing=!1,t.fileReader.onload=function(r){t._processing=!1,r.target&&t.emit("done",r.target.result),t.doNextTask()},t.fileReader.onerror=function(r){dt.default.error("EncodingQueue error:",r),t._processing=!1,t.destroy(),t.emit("error",r)},t}return Object.defineProperty(e.prototype,"queue",{get:function(){return this._queue},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"size",{get:function(){return this.queue.length},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"processing",{get:function(){return this._processing},enumerable:!1,configurable:!0}),e.prototype.enque=function(t){this.queue.push(t),!this.processing&&this.doNextTask()},e.prototype.destroy=function(){this.fileReader.abort(),this._queue=[]},e.prototype.doNextTask=function(){this.size!==0&&(this.processing||(this._processing=!0,this.fileReader.readAsArrayBuffer(this.queue.shift())))},e}($y.EventEmitter),rde=function(){var n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,s){r.__proto__=s}||function(r,s){for(var o in s)Object.prototype.hasOwnProperty.call(s,o)&&(r[o]=s[o])},n(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");n(e,t);function r(){this.constructor=e}e.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}}(),sde=function(n){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&n[e],r=0;if(t)return t.call(n);if(n&&typeof n.length=="number")return{next:function(){return n&&r>=n.length&&(n=void 0),{value:n&&n[r++],done:!n}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},qG=function(n){rde(e,n);function e(t,r,s){var o=n.call(this,t,r,s)||this;return o.stringify=JSON.stringify,o.parse=JSON.parse,o._buffer=[],o._bufferSize=0,o._buffering=!1,o._chunkedData={},o._encodingQueue=new WG.EncodingQueue,o.connectionId=o.options.connectionId||e.ID_PREFIX+wi.randomToken(),o.label=o.options.label||o.connectionId,o.serialization=o.options.serialization||gh.Binary,o.reliable=!!o.options.reliable,o._encodingQueue.on("done",function(a){o._bufferedSend(a)}),o._encodingQueue.on("error",function(){dt.default.error("DC#".concat(o.connectionId,": Error occured in encoding from blob to arraybuffer, close DC")),o.close()}),o._negotiator=new OB.Negotiator(o),o._negotiator.startConnection(o.options._payload||{originator:!0}),o}return Object.defineProperty(e.prototype,"type",{get:function(){return pl.Data},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"dataChannel",{get:function(){return this._dc},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"bufferSize",{get:function(){return this._bufferSize},enumerable:!1,configurable:!0}),e.prototype.initialize=function(t){this._dc=t,this._configureDataChannel()},e.prototype._configureDataChannel=function(){var t=this;(!wi.supports.binaryBlob||wi.supports.reliable)&&(this.dataChannel.binaryType="arraybuffer"),this.dataChannel.onopen=function(){dt.default.log("DC#".concat(t.connectionId," dc connection success")),t._open=!0,t.emit("open")},this.dataChannel.onmessage=function(r){dt.default.log("DC#".concat(t.connectionId," dc onmessage:"),r.data),t._handleDataMessage(r)},this.dataChannel.onclose=function(){dt.default.log("DC#".concat(t.connectionId," dc closed for:"),t.peer),t.close()}},e.prototype._handleDataMessage=function(t){var r=this,s=t.data,o=s.constructor,a=this.serialization===gh.Binary||this.serialization===gh.BinaryUTF8,l=s;if(a){if(o===Blob){wi.blobToArrayBuffer(s,function(h){var u=wi.unpack(h);r.emit("data",u)});return}else if(o===ArrayBuffer)l=wi.unpack(s);else if(o===String){var c=wi.binaryStringToArrayBuffer(s);l=wi.unpack(c)}}else this.serialization===gh.JSON&&(l=this.parse(s));if(l.__peerData){this._handleChunk(l);return}n.prototype.emit.call(this,"data",l)},e.prototype._handleChunk=function(t){var r=t.__peerData,s=this._chunkedData[r]||{data:[],count:0,total:t.total};if(s.data[t.n]=t.data,s.count++,this._chunkedData[r]=s,s.total===s.count){delete this._chunkedData[r];var o=new Blob(s.data);this._handleDataMessage({data:o})}},e.prototype.close=function(){this._buffer=[],this._bufferSize=0,this._chunkedData={},this._negotiator&&(this._negotiator.cleanup(),this._negotiator=null),this.provider&&(this.provider._removeConnection(this),this.provider=null),this.dataChannel&&(this.dataChannel.onopen=null,this.dataChannel.onmessage=null,this.dataChannel.onclose=null,this._dc=null),this._encodingQueue&&(this._encodingQueue.destroy(),this._encodingQueue.removeAllListeners(),this._encodingQueue=null),this.open&&(this._open=!1,n.prototype.emit.call(this,"close"))},e.prototype.send=function(t,r){if(!this.open){n.prototype.emit.call(this,"error",new Error("Connection is not open. You should listen for the `open` event before sending messages."));return}if(this.serialization===gh.JSON)this._bufferedSend(this.stringify(t));else if(this.serialization===gh.Binary||this.serialization===gh.BinaryUTF8){var s=wi.pack(t);if(!r&&s.size>wi.chunkedMTU){this._sendChunks(s);return}wi.supports.binaryBlob?this._bufferedSend(s):this._encodingQueue.enque(s)}else this._bufferedSend(t)},e.prototype._bufferedSend=function(t){(this._buffering||!this._trySend(t))&&(this._buffer.push(t),this._bufferSize=this._buffer.length)},e.prototype._trySend=function(t){var r=this;if(!this.open)return!1;if(this.dataChannel.bufferedAmount>e.MAX_BUFFERED_AMOUNT)return this._buffering=!0,setTimeout(function(){r._buffering=!1,r._tryBuffer()},50),!1;try{this.dataChannel.send(t)}catch(s){return dt.default.error("DC#:".concat(this.connectionId," Error when sending:"),s),this._buffering=!0,this.close(),!1}return!0},e.prototype._tryBuffer=function(){if(this.open&&this._buffer.length!==0){var t=this._buffer[0];this._trySend(t)&&(this._buffer.shift(),this._bufferSize=this._buffer.length,this._tryBuffer())}},e.prototype._sendChunks=function(t){var r,s,o=wi.chunk(t);dt.default.log("DC#".concat(this.connectionId," Try to send ").concat(o.length," chunks..."));try{for(var a=sde(o),l=a.next();!l.done;l=a.next()){var c=l.value;this.send(c,!0)}}catch(h){r={error:h}}finally{try{l&&!l.done&&(s=a.return)&&s.call(a)}finally{if(r)throw r.error}}},e.prototype.handleMessage=function(t){var r=t.payload;switch(t.type){case Qr.Answer:this._negotiator.handleSDP(t.type,r.sdp);break;case Qr.Candidate:this._negotiator.handleCandidate(r.candidate);break;default:dt.default.warn("Unrecognized message type:",t.type,"from peer:",this.peer);break}},e.ID_PREFIX="dc_",e.MAX_BUFFERED_AMOUNT=8388608,e}(LB.BaseConnection),YG={};Kl(YG,"API",()=>ZG,n=>ZG=n);var JG=function(n,e,t,r){function s(o){return o instanceof t?o:new t(function(a){a(o)})}return new(t||(t=Promise))(function(o,a){function l(u){try{h(r.next(u))}catch(p){a(p)}}function c(u){try{h(r.throw(u))}catch(p){a(p)}}function h(u){u.done?o(u.value):s(u.value).then(l,c)}h((r=r.apply(n,e||[])).next())})},KG=function(n,e){var t={label:0,sent:function(){if(o[0]&1)throw o[1];return o[1]},trys:[],ops:[]},r,s,o,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(h){return function(u){return c([h,u])}}function c(h){if(r)throw new TypeError("Generator is already executing.");for(;t;)try{if(r=1,s&&(o=h[0]&2?s.return:h[0]?s.throw||((o=s.return)&&o.call(s),0):s.next)&&!(o=o.call(s,h[1])).done)return o;switch(s=0,o&&(h=[h[0]&2,o.value]),h[0]){case 0:case 1:o=h;break;case 4:return t.label++,{value:h[1],done:!1};case 5:t.label++,s=h[1],h=[0];continue;case 7:h=t.ops.pop(),t.trys.pop();continue;default:if(o=t.trys,!(o=o.length>0&&o[o.length-1])&&(h[0]===6||h[0]===2)){t=0;continue}if(h[0]===3&&(!o||h[1]>o[0]&&h[1]<o[3])){t.label=h[1];break}if(h[0]===6&&t.label<o[1]){t.label=o[1],o=h;break}if(o&&t.label<o[2]){t.label=o[2],t.ops.push(h);break}o[2]&&t.ops.pop(),t.trys.pop();continue}h=e.call(n,t)}catch(u){h=[6,u],s=0}finally{r=o=0}if(h[0]&5)throw h[1];return{value:h[0]?h[1]:void 0,done:!0}}},ZG=function(){function n(e){this._options=e}return n.prototype._buildRequest=function(e){var t=this._options.secure?"https":"http",r=this._options,s=r.host,o=r.port,a=r.path,l=r.key,c=new URL("".concat(t,"://").concat(s,":").concat(o).concat(a).concat(l,"/").concat(e));return c.searchParams.set("ts","".concat(Date.now()).concat(Math.random())),c.searchParams.set("version",kB.version),fetch(c.href,{referrerPolicy:this._options.referrerPolicy})},n.prototype.retrieveId=function(){return JG(this,void 0,Promise,function(){var e,t,r;return KG(this,function(s){switch(s.label){case 0:return s.trys.push([0,2,,3]),[4,this._buildRequest("id")];case 1:if(e=s.sent(),e.status!==200)throw new Error("Error. Status:".concat(e.status));return[2,e.text()];case 2:throw t=s.sent(),dt.default.error("Error retrieving ID",t),r="",this._options.path==="/"&&this._options.host!==wi.CLOUD_HOST&&(r=" If you passed in a `path` to your self-hosted PeerServer, you'll also need to pass in that same path when creating a new Peer."),new Error("Could not get an ID from the server."+r);case 3:return[2]}})})},n.prototype.listAllPeers=function(){return JG(this,void 0,Promise,function(){var e,t,r;return KG(this,function(s){switch(s.label){case 0:return s.trys.push([0,2,,3]),[4,this._buildRequest("peers")];case 1:if(e=s.sent(),e.status!==200)throw e.status===401?(t="",this._options.host===wi.CLOUD_HOST?t="It looks like you're using the cloud server. You can email team@peerjs.com to enable peer listing for your API key.":t="You need to enable `allow_discovery` on your self-hosted PeerServer to use this feature.",new Error("It doesn't look like you have permission to list peers IDs. "+t)):new Error("Error. Status:".concat(e.status));return[2,e.json()];case 2:throw r=s.sent(),dt.default.error("Error retrieving list peers",r),new Error("Could not get list peers from the server."+r);case 3:return[2]}})})},n}(),ode=function(){var n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,s){r.__proto__=s}||function(r,s){for(var o in s)Object.prototype.hasOwnProperty.call(s,o)&&(r[o]=s[o])},n(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");n(e,t);function r(){this.constructor=e}e.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}}(),tA=function(){return tA=Object.assign||function(n){for(var e,t=1,r=arguments.length;t<r;t++){e=arguments[t];for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&(n[s]=e[s])}return n},tA.apply(this,arguments)},iA=function(n){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&n[e],r=0;if(t)return t.call(n);if(n&&typeof n.length=="number")return{next:function(){return n&&r>=n.length&&(n=void 0),{value:n&&n[r++],done:!n}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},ade=function(n,e){var t=typeof Symbol=="function"&&n[Symbol.iterator];if(!t)return n;var r=t.call(n),s,o=[],a;try{for(;(e===void 0||e-- >0)&&!(s=r.next()).done;)o.push(s.value)}catch(l){a={error:l}}finally{try{s&&!s.done&&(t=r.return)&&t.call(r)}finally{if(a)throw a.error}}return o},UB=function(n){ode(e,n);function e(t,r){var s=n.call(this)||this;s._id=null,s._lastServerId=null,s._destroyed=!1,s._disconnected=!1,s._open=!1,s._connections=new Map,s._lostMessages=new Map;var o;return t&&t.constructor==Object?r=t:t&&(o=t.toString()),r=tA({debug:0,host:wi.CLOUD_HOST,port:wi.CLOUD_PORT,path:"/",key:e.DEFAULT_KEY,token:wi.randomToken(),config:wi.defaultConfig,referrerPolicy:"strict-origin-when-cross-origin"},r),s._options=r,s._options.host==="/"&&(s._options.host=window.location.hostname),s._options.path&&(s._options.path[0]!=="/"&&(s._options.path="/"+s._options.path),s._options.path[s._options.path.length-1]!=="/"&&(s._options.path+="/")),s._options.secure===void 0&&s._options.host!==wi.CLOUD_HOST?s._options.secure=wi.isSecure():s._options.host==wi.CLOUD_HOST&&(s._options.secure=!0),s._options.logFunction&&dt.default.setLogFunction(s._options.logFunction),dt.default.logLevel=s._options.debug||0,s._api=new YG.API(r),s._socket=s._createServerConnection(),!wi.supports.audioVideo&&!wi.supports.data?(s._delayedAbort(Fn.BrowserIncompatible,"The current browser does not support WebRTC"),s):o&&!wi.validateId(o)?(s._delayedAbort(Fn.InvalidID,'ID "'.concat(o,'" is invalid')),s):(o?s._initialize(o):s._api.retrieveId().then(function(a){return s._initialize(a)}).catch(function(a){return s._abort(Fn.ServerError,a)}),s)}return Object.defineProperty(e.prototype,"id",{get:function(){return this._id},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"options",{get:function(){return this._options},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"open",{get:function(){return this._open},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"socket",{get:function(){return this._socket},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"connections",{get:function(){var t,r,s=Object.create(null);try{for(var o=iA(this._connections),a=o.next();!a.done;a=o.next()){var l=ade(a.value,2),c=l[0],h=l[1];s[c]=h}}catch(u){t={error:u}}finally{try{a&&!a.done&&(r=o.return)&&r.call(o)}finally{if(t)throw t.error}}return s},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"destroyed",{get:function(){return this._destroyed},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"disconnected",{get:function(){return this._disconnected},enumerable:!1,configurable:!0}),e.prototype._createServerConnection=function(){var t=this,r=new jG.Socket(this._options.secure,this._options.host,this._options.port,this._options.path,this._options.key,this._options.pingInterval);return r.on(vh.Message,function(s){t._handleMessage(s)}),r.on(vh.Error,function(s){t._abort(Fn.SocketError,s)}),r.on(vh.Disconnected,function(){t.disconnected||(t.emitError(Fn.Network,"Lost connection to server."),t.disconnect())}),r.on(vh.Close,function(){t.disconnected||t._abort(Fn.SocketClosed,"Underlying socket is already closed.")}),r},e.prototype._initialize=function(t){this._id=t,this.socket.start(t,this._options.token)},e.prototype._handleMessage=function(t){var r,s,o=t.type,a=t.payload,l=t.src;switch(o){case Qr.Open:this._lastServerId=this.id,this._open=!0,this.emit("open",this.id);break;case Qr.Error:this._abort(Fn.ServerError,a.msg);break;case Qr.IdTaken:this._abort(Fn.UnavailableID,'ID "'.concat(this.id,'" is taken'));break;case Qr.InvalidKey:this._abort(Fn.InvalidKey,'API KEY "'.concat(this._options.key,'" is invalid'));break;case Qr.Leave:dt.default.log("Received leave message from ".concat(l)),this._cleanupPeer(l),this._connections.delete(l);break;case Qr.Expire:this.emitError(Fn.PeerUnavailable,"Could not connect to peer ".concat(l));break;case Qr.Offer:var g=a.connectionId,v=this.getConnection(l,g);if(v&&(v.close(),dt.default.warn("Offer received for existing Connection ID:".concat(g))),a.type===pl.Media){var c=new DB.MediaConnection(l,this,{connectionId:g,_payload:a,metadata:a.metadata});v=c,this._addConnection(l,v),this.emit("call",c)}else if(a.type===pl.Data){var h=new FB.DataConnection(l,this,{connectionId:g,_payload:a,metadata:a.metadata,label:a.label,serialization:a.serialization,reliable:a.reliable});v=h,this._addConnection(l,v),this.emit("connection",h)}else{dt.default.warn("Received malformed connection type:".concat(a.type));return}var u=this._getMessages(g);try{for(var p=iA(u),m=p.next();!m.done;m=p.next()){var f=m.value;v.handleMessage(f)}}catch(y){r={error:y}}finally{try{m&&!m.done&&(s=p.return)&&s.call(p)}finally{if(r)throw r.error}}break;default:if(!a){dt.default.warn("You received a malformed message from ".concat(l," of type ").concat(o));return}var g=a.connectionId,v=this.getConnection(l,g);v&&v.peerConnection?v.handleMessage(t):g?this._storeMessage(g,t):dt.default.warn("You received an unrecognized message:",t);break}},e.prototype._storeMessage=function(t,r){this._lostMessages.has(t)||this._lostMessages.set(t,[]),this._lostMessages.get(t).push(r)},e.prototype._getMessages=function(t){var r=this._lostMessages.get(t);return r?(this._lostMessages.delete(t),r):[]},e.prototype.connect=function(t,r){if(r===void 0&&(r={}),this.disconnected){dt.default.warn("You cannot connect to a new Peer because you called .disconnect() on this Peer and ended your connection with the server. You can create a new Peer to reconnect, or call reconnect on this peer if you believe its ID to still be available."),this.emitError(Fn.Disconnected,"Cannot connect to new Peer after disconnecting from server.");return}var s=new FB.DataConnection(t,this,r);return this._addConnection(t,s),s},e.prototype.call=function(t,r,s){if(s===void 0&&(s={}),this.disconnected){dt.default.warn("You cannot connect to a new Peer because you called .disconnect() on this Peer and ended your connection with the server. You can create a new Peer to reconnect."),this.emitError(Fn.Disconnected,"Cannot connect to new Peer after disconnecting from server.");return}if(!r){dt.default.error("To call a peer, you must provide a stream from your browser's `getUserMedia`.");return}var o=new DB.MediaConnection(t,this,tA(tA({},s),{_stream:r}));return this._addConnection(t,o),o},e.prototype._addConnection=function(t,r){dt.default.log("add connection ".concat(r.type,":").concat(r.connectionId," to peerId:").concat(t)),this._connections.has(t)||this._connections.set(t,[]),this._connections.get(t).push(r)},e.prototype._removeConnection=function(t){var r=this._connections.get(t.peer);if(r){var s=r.indexOf(t);s!==-1&&r.splice(s,1)}this._lostMessages.delete(t.connectionId)},e.prototype.getConnection=function(t,r){var s,o,a=this._connections.get(t);if(!a)return null;try{for(var l=iA(a),c=l.next();!c.done;c=l.next()){var h=c.value;if(h.connectionId===r)return h}}catch(u){s={error:u}}finally{try{c&&!c.done&&(o=l.return)&&o.call(l)}finally{if(s)throw s.error}}return null},e.prototype._delayedAbort=function(t,r){var s=this;setTimeout(function(){s._abort(t,r)},0)},e.prototype._abort=function(t,r){dt.default.error("Aborting!"),this.emitError(t,r),this._lastServerId?this.disconnect():this.destroy()},e.prototype.emitError=function(t,r){dt.default.error("Error:",r);var s;typeof r=="string"?s=new Error(r):s=r,s.type=t,this.emit("error",s)},e.prototype.destroy=function(){this.destroyed||(dt.default.log("Destroy peer with ID:".concat(this.id)),this.disconnect(),this._cleanup(),this._destroyed=!0,this.emit("close"))},e.prototype._cleanup=function(){var t,r;try{for(var s=iA(this._connections.keys()),o=s.next();!o.done;o=s.next()){var a=o.value;this._cleanupPeer(a),this._connections.delete(a)}}catch(l){t={error:l}}finally{try{o&&!o.done&&(r=s.return)&&r.call(s)}finally{if(t)throw t.error}}this.socket.removeAllListeners()},e.prototype._cleanupPeer=function(t){var r,s,o=this._connections.get(t);if(o)try{for(var a=iA(o),l=a.next();!l.done;l=a.next()){var c=l.value;c.close()}}catch(h){r={error:h}}finally{try{l&&!l.done&&(s=a.return)&&s.call(a)}finally{if(r)throw r.error}}},e.prototype.disconnect=function(){if(!this.disconnected){var t=this.id;dt.default.log("Disconnect peer with ID:".concat(t)),this._disconnected=!0,this._open=!1,this.socket.close(),this._lastServerId=t,this._id=null,this.emit("disconnected",t)}},e.prototype.reconnect=function(){if(this.disconnected&&!this.destroyed)dt.default.log("Attempting reconnection to server with ID ".concat(this._lastServerId)),this._disconnected=!1,this._initialize(this._lastServerId);else{if(this.destroyed)throw new Error("This peer cannot reconnect to the server. It has already been destroyed.");if(!this.disconnected&&!this.open)dt.default.error("In a hurry? We're still trying to make the initial connection!");else throw new Error("Peer ".concat(this.id," cannot reconnect because it is not disconnected from the server!"))}},e.prototype.listAllPeers=function(t){var r=this;t===void 0&&(t=function(s){}),this._api.listAllPeers().then(function(s){return t(s)}).catch(function(s){return r._abort(Fn.ServerError,s)})},e.DEFAULT_KEY="peerjs",e}($y.EventEmitter),NB=UG.Peer;const lde=Object.freeze(Object.defineProperty({__proto__:null,get Peer(){return UB},default:NB,util:wi},Symbol.toStringTag,{value:"Module"}));let zB;function cde(){return zB}function hde(n){zB=n}function $G(n,e){return e||(e={}),e={...zB,...e},n?new NB(n,e):new NB(e)}async function eV(){const n=await Promise.resolve().then(()=>lde);return console.log(n),n.default===void 0?n:n.default}class tV{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 eV(),r=new t(e);r.on("error",s=>{console.error(s),this._host=void 0,this.trySetupClient(e)}),r.on("open",s=>{this._host=new dde(r)})}async trySetupClient(e){const t=await eV();this._client=new t,this._client.on("error",r=>{console.error("Client error",r)}),this._client.on("open",r=>{console.log("client connected",r),this._clientData=this._client.connect(e,{metadata:{id:r}}),this._clientData.on("open",()=>{console.log("Connected to host")}),this._clientData.on("data",s=>{console.log("<<",s)})})}}class ude{constructor(e){d(this,"_peer"),this._peer=e}}class dde extends ude{constructor(e){var t;super(e),d(this,"_connections",[]),console.log("I AM THE HOST"),(t=this._peer)==null||t.on("connection",this.onConnection.bind(this)),this._peer.on("close",()=>{this.broadcast("BYE")}),setInterval(()=>{this.broadcast("HELLO")},2e3)}get isHost(){return!0}onConnection(e){console.log("host connection",e),e.on("open",()=>{this._connections.push(e),this.broadcastConnection(e)})}broadcastConnection(e){const t=this._connections.map(r=>{var s;return(s=r.metadata)==null?void 0:s.id}).filter(r=>r!==void 0);this.broadcast({type:"connection-list",connections:t})}broadcast(e){if(e!=null){console.log(">>",e);for(const t in this._peer.connections){const r=this._peer.connections[t];if(r)if(Array.isArray(r))for(const s of r)s&&s.send(e);else console.warn(r)}}}}const iV="https://urls.needle.tools/default-networking-backend/index";let Gu="wss://needle-tiny-starter.glitch.me/socket";const Zs=!!te("debugnet"),nA=!!(Zs||te("debugowner")),nV=te("debugnetbin");var rV=(n=>(n.ConnectionInfo="connection-start-info",n))(rV||{}),Vt=(n=>(n.Join="join-room",n.Leave="leave-room",n.JoinedRoom="joined-room",n.LeftRoom="left-room",n.UserJoinedRoom="user-joined-room",n.UserLeftRoom="user-left-room",n.RoomStateSent="room-state-sent",n))(Vt||{});class pde{constructor(){d(this,"room"),d(this,"viewId"),d(this,"allowEditing"),d(this,"inRoom")}}class mde{constructor(){d(this,"room")}}class fde{constructor(){d(this,"userId")}}var sV=(n=>(n.RequestHasOwner="request-has-owner",n.ResponseHasOwner="response-has-owner",n.RequestIsOwner="request-is-owner",n.ResponseIsOwner="response-is-owner",n.RequestOwnership="request-ownership",n.GainedOwnership="gained-ownership",n.RemoveOwnership="remove-ownership",n.LostOwnership="lost-ownership",n.GainedOwnershipBroadcast="gained-ownership-broadcast",n.LostOwnershipBroadcast="lost-ownership-broadcast",n))(sV||{});class jB{constructor(e,t){d(this,"guid"),d(this,"connection"),d(this,"_hasOwnership",!1),d(this,"_isOwned"),d(this,"_gainSubscription"),d(this,"_lostSubscription"),d(this,"_hasOwnerResponse"),d(this,"_isWaitingForOwnershipResponseCallback",null),this.connection=e,this.guid=t,this._gainSubscription=this.onGainedOwnership.bind(this),this._lostSubscription=this.onLostOwnership.bind(this),e.beginListen("lost-ownership",this._lostSubscription),e.beginListen("gained-ownership-broadcast",this._gainSubscription),this._hasOwnerResponse=this.onHasOwnerResponse.bind(this),e.beginListen("response-has-owner",this._hasOwnerResponse)}get hasOwnership(){return this._hasOwnership}get isOwned(){return this._isOwned}get isConnected(){return this.connection.isConnected}updateIsOwned(){this.connection.send("request-has-owner",{guid:this.guid})}onHasOwnerResponse(e){e.guid===this.guid&&(this._isOwned=e.value)}requestOwnershipIfNotOwned(){return this._isWaitingForOwnershipResponseCallback!==null?this:(this._isWaitingForOwnershipResponseCallback=this.waitForHasOwnershipRequestResponse.bind(this),this.connection.beginListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this.connection.send("request-has-owner",{guid:this.guid}),this)}waitForHasOwnershipRequestResponse(e){e.guid===this.guid&&(this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this._isOwned=e.value,e.value||(nA&&console.log("request ownership",this.guid),this.requestOwnership()))}requestOwnershipAsync(){return new Promise((e,t)=>{this.requestOwnership();let r=0;const s=()=>{if(r++>10)return t("Timeout");setTimeout(()=>{this.hasOwnership?e(this):s()},100)};s()})}requestOwnership(){return nA&&console.log("Request ownership",this.guid),this.connection.send("request-ownership",{guid:this.guid}),this}freeOwnership(){return this.connection.send("remove-ownership",{guid:this.guid}),this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this}destroy(){this.connection.stopListen("gained-ownership",this._gainSubscription),this.connection.stopListen("lost-ownership",this._lostSubscription),this.connection.stopListen("response-has-owner",this._hasOwnerResponse),this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null)}onGainedOwnership(e){e.guid===this.guid&&(this._isOwned=!0,this.connection.connectionId===e.owner?(nA&&console.log("GAINED OWNERSHIP",this.guid),this._hasOwnership=!0):this._hasOwnership=!1)}onLostOwnership(e){e===this.guid&&(nA&&console.log("LOST OWNERSHIP",this.guid),this._hasOwnership=!1,this._isOwned=!1)}}class oV{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 tV),this._peer}tryGetState(e){return e==="invalid"?null:this._state[e]}get connectionId(){return this._connectionId}get isDebugEnabled(){return Zs}get isConnected(){return this.connected}get currentRoomName(){return this._currentRoomName}get allowEditing(){return this._currentRoomAllowEditing}get currentRoomViewId(){return this._currentRoomViewId}getViewOnlyUrl(){if(this.currentRoomViewId===null)return null;const e=new URL(window.location.href);return e.searchParams.set("view",this.currentRoomViewId),e.href}get isInRoom(){return this._isInRoom}get currentLatency(){return this._currentDelay}get currentServerUrl(){var e;return((e=this._ws)==null?void 0:e.url)??null}sendPing(){this.send("ping",{time:this.context.time.time})}userIsInRoom(e){return this._currentInRoom.indexOf(e)!==-1}usersInRoom(e=null){e||(e=this._usersInRoomCopy),e.length=0;for(const t of this._currentInRoom)e.push(t);return e}joinRoom(e,t=!1){return e?e.length>1024?(console.error('Room name too long, can not join: "'+e+'". Max length is 1024 characters.'),!1):(this.connect(),Zs&&console.log("join: "+e),this.send("join-room",{room:e,viewOnly:t},dl.OnConnection),!0):(console.error('Missing room name, can not join: "'+e+'"'),!1)}leaveRoom(e=null){return e||(e=this.currentRoomName),e?(this.send("leave-room",{room:e}),!0):(console.error('Missing room name, can not join: "'+e+'"'),!1)}send(e,t=null,r=dl.Queued){if(t===null&&(t={}),r===dl.Queued){this._defaultMessagesBuffer.push({key:e,value:t});return}return this.sendWithWebsocket(e,t,r)}sendDeleteRemoteState(e){this.send("delete-state",{guid:e,dontSave:!0}),delete this._state[e]}sendDeleteRemoteStateAll(){this.send("delete-all-state"),this._state={}}sendBinary(e){var t;nV&&console.log("<< send binary",this.context.time.frame,e.length/1024+" KB"),(t=this._ws)==null||t.send(e)}sendBufferedMessagesNow(){var e;if(!this._ws)return;this._defaultMessagesBufferArray.length=0;const t=Object.keys(this._defaultMessagesBuffer).length;for(const s in this._defaultMessagesBuffer){const o=this._defaultMessagesBuffer[s];if(t<=1){this.sendWithWebsocket(o.key,o.value,dl.Immediate);break}const a=this.toMessage(o.key,o.value);this._defaultMessagesBufferArray.push(a)}if(this._defaultMessagesBuffer.length=0,this._defaultMessagesBufferArray.length>0&&Zs&&console.log("SEND BUFFERED",this._defaultMessagesBufferArray.length),this._defaultMessagesBufferArray.length<=0)return;const r=JSON.stringify(this._defaultMessagesBufferArray);(e=this._ws)==null||e.send(r)}beginListen(e,t){return this._listeners[e]||(this._listeners[e]=[]),this._listeners[e].push(t),t}stopListening(e,t){return this.stopListen(e,t)}stopListen(e,t){if(!t||!this._listeners[e])return;const r=this._listeners[e].indexOf(t);r>=0&&this._listeners[e].splice(r,1)}beginListenBinary(e,t){return this._listenersBinary[e]||(this._listenersBinary[e]=[]),this._listenersBinary[e].push(t),t}stopListenBinary(e,t){if(!this._listenersBinary[e])return;const r=this._listenersBinary[e].indexOf(t);r>=0&&this._listenersBinary[e].splice(r,1)}registerProvider(e){this.netWebSocketUrlProvider=e}async connect(){var e;if(this.connected)return Promise.resolve(!0);Zs&&console.log("connecting");const t=(e=this.netWebSocketUrlProvider)==null?void 0:e.getWebsocketUrl();return t?Gu=t:kU()&&(Gu="wss://"+window.location.host+"/socket"),this.connectWebsocket()}disconnect(){var e;(e=this._ws)==null||e.close(),this._ws=void 0}connectWebsocket(){return this._connectingToWebsocketPromise?this._connectingToWebsocketPromise:this._connectingToWebsocketPromise=new Promise(async(e,t)=>{var r,s;let o=!1;const a=p=>{o||(o=!0,e(p))};if(Gu===void 0&&(console.log("Fetch default backend url: "+iV),Gu=await(await fetch(iV)).text()),Gu===void 0){a(!1);return}console.log(`\u22A1 Connecting to networking backend on
|
|
5233
5233
|
`+Gu);const l=await Promise.resolve().then(()=>K_e),c=((r=l.default)==null?void 0:r.WebsocketBuilder)??l.WebsocketBuilder,h=((s=l.default)==null?void 0:s.ExponentialBackoff)??l.ExponentialBackoff,u=new c(Gu).withMaxRetries(3).withBackoff(new h(2e3,2)).onOpen(()=>{this._connectingToWebsocketPromise=null,this._ws=u,this.connected=!0,console.log(`\u229E Connected to networking backend
|
|
5234
5234
|
`+Gu),a(!0),this.onSendQueued(dl.OnConnection)}).onClose(p=>{this._connectingToWebsocketPromise=null,this.connected=!1,this._isInRoom=!1,a(!1)}).onError(p=>{console.error("\u22A0 Websocket error"),a(!1)}).onRetry(()=>{console.log("Retry connecting to networking websocket")}).build();u.addEventListener(l.WebsocketEvent.message,(p,m)=>{this.onMessage(p,m)})})}onMessage(e,t){const r=t.data;try{if(typeof r!="string"){r.size&&this.handleIncomingBinaryMessage(r);return}const s=JSON.parse(r);if(Array.isArray(s))for(const o of s)this.handleIncomingStringMessage(o);else this.handleIncomingStringMessage(s);return}catch(s){Zs&&r==="pong"?console.log("<<",r):st()&&console.error("Failed to parse message",s)}}async handleIncomingBinaryMessage(e){nV&&console.log("<< bin",this.context.time.frame);const t=await e.arrayBuffer();var r=new Uint8Array(t);const s=new r_(r),o=s.getBufferIdentifier(),a=this._listenersBinary[o],l=N6(s),c=z6(l);if(c&&typeof c=="string"&&(this._state[c]=l),!a)return;const h=l??s;for(const u of a)u(h)}handleIncomingStringMessage(e){var t,r;if(Zs&&console.log("<<",e.key??e),e.key)switch(e.key){case"connection-start-info":if(e.data){const l=e.data;l&&(console.assert(l.id!==void 0&&l.id!==null&&l.id.length>0,"server did not send connection id",l.id),console.log("Your id is: "+l.id,this.context.alias??""),this._connectionId=l.id)}else console.warn("Expected connection id in "+e.key);break;case"joined-room":if(Zs&&console.log(e),e){this._isInRoom=!0;const l=e;this._currentRoomName=l.room,this._currentRoomViewId=l.viewId,this._currentRoomAllowEditing=l.allowEditing??!0,this._currentInRoom.length=0,this._currentInRoom.push(...l.inRoom),Zs&&console.log("joined room with",this._currentInRoom,this.context.alias??"");const c=new URL(window.location.href);c.searchParams.has("room")&&c.searchParams.delete("room"),c.searchParams.set("view",this._currentRoomViewId),console.log("Room view id: "+this._currentRoomViewId+`
|
|
5235
|
-
`+c.href)}this.onSendQueued(dl.OnRoomJoin);break;case"left-room":e.room===this.currentRoomName&&(this._isInRoom=!1,this._currentRoomName=null,this._currentInRoom.length=0);break;case"user-joined-room":if(e.data){const l=e.data;this._currentInRoom.push(l.userId),Zs&&console.log(l.userId+" joined","now in room:",this._currentInRoom)}break;case"user-left-room":if(e.data){const l=e.data,c=this._currentInRoom.indexOf(l.userId);c>=0&&(Zs&&console.log(l.userId+" left","now in room:",this._currentInRoom),this._currentInRoom.splice(c,1)),l.userId===this.connectionId&&console.log("you left the room")}break;case"all-room-state-deleted":Zs&&console.log("RECEIVED all-room-state-deleted"),this._state={};break;case"ping":case"pong":const a=(t=e.data)==null?void 0:t.time;a&&(this._currentDelay=this.context.time.time-a),Zs&&console.log("Current latency: "+this._currentDelay.toFixed(4)+" sec","Clients in room: "+((r=this._currentInRoom)==null?void 0:r.length));break}const s=e.data;s&&(this._state[s.guid]=s);let o=this._listeners[e.key];if(o){o=[...o];for(const a of o)try{a(e.data)}catch(l){console.error('Error invoking callback for "'+e.key+'"',l)}}}toMessage(e,t){return{key:e,data:t}}sendWithWebsocket(e,t,r=dl.OnRoomJoin){if(!this._ws){const o=this._waitingForSocket[r]||[];o.push(()=>this.sendWithWebsocket(e,t,r)),this._waitingForSocket[r]=o;return}const s=JSON.stringify(this.toMessage(e,t));Zs&&console.log(">>",e),this._ws.send(s)}onSendQueued(e){const t=this._waitingForSocket[e];if(t){for(const r of t)r();t.length=0}}}const rA=te("debugwebxr");class GB{constructor(e,t){d(this,"controllerStates",[]),d(this,"userId"),d(this,"context"),d(this,"userStateEvtName"),d(this,"onReceivedControllerState",r=>{rA&&console.log(`XRSync: Received change for ${this.userId}: ${r.type} ${r.handedness}; tracked=${r.isTracking}`);let s=!1;for(let o=0;o<this.controllerStates.length;o++)if(this.controllerStates[o].index===r.index){this.controllerStates[o]=r,s=!0;break}s||this.controllerStates.push(r)}),this.userId=e,this.context=t,this.userStateEvtName="xr-sync-user-state-"+e,this.context.connection.beginListen(this.userStateEvtName,this.onReceivedControllerState)}dispose(){this.context.connection.stopListen(this.userStateEvtName,this.onReceivedControllerState)}update(e){if(this.context.connection.isConnected!=!1){for(let t=this.controllerStates.length-1;t>=0;t--){const r=this.controllerStates[t];let s=!1;for(let o=0;o<e.controllers.length;o++)e.controllers[o].index===r.index&&(s=!0);s||(rA&&console.log(`XRSync: ${r.type} ${r.handedness} removed`,r.index),this.controllerStates.splice(t,1),this.sendControllerRemoved(r))}for(const t of e.controllers)this.updateControllerStates(t)}}onExitXR(e){for(const t of this.controllerStates)this.sendControllerRemoved(t);this.controllerStates.length=0}sendControllerRemoved(e){e.isTracking=!1,e.guid="",this.context.connection.send(this.userStateEvtName,e),this.context.connection.sendDeleteRemoteState(e.guid)}updateControllerStates(e){const t=this.controllerStates.find(r=>r.index===e.index);if(t){let r=!1;r||(r=t.isTracking!=e.isTracking),r&&(t.isTracking=e.isTracking,this.context.connection.send(this.userStateEvtName,t))}else{const r={guid:this.userId+"-"+e.index,isTracking:e.isTracking,handedness:e.side,index:e.index,type:e.hand?"hand":"controller"};this.controllerStates.push(r),this.context.connection.send(this.userStateEvtName,r),rA&&console.log(`XRSync: ${r.type} ${r.handedness} added`,r.index)}}}class aV{constructor(e){d(this,"context"),d(this,"onJoinedRoom",()=>{if(this.context.connection.connectionId){this._states.has(this.context.connection.connectionId)||(rA&&console.log("XRSync: Local user joined room",this.context.connection.connectionId),this._states.set(this.context.connection.connectionId,new GB(this.context.connection.connectionId,this.context)));for(const t of this.context.connection.usersInRoom())this._states.has(t)||this._states.set(t,new GB(t,this.context))}}),d(this,"onLeftRoom",()=>{if(this.context.connection.connectionId&&!this._states.has(this.context.connection.connectionId)){const t=this._states.get(this.context.connection.connectionId);t?.dispose(),this._states.delete(this.context.connection.connectionId)}}),d(this,"onOtherUserJoinedRoom",t=>{const r=t.userId;this._states.has(r)||(rA&&console.log("XRSync: Remote user joined room",r),this._states.set(r,new GB(r,this.context)))}),d(this,"onOtherUserLeftRoom",t=>{const r=t.userId;if(!this._states.has(r)){const s=this._states.get(r);s?.dispose(),this._states.delete(r)}}),d(this,"_states",new Map),this.context=e,this.context.connection.beginListen(Vt.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(Vt.LeftRoom,this.onLeftRoom),this.context.connection.beginListen(Vt.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.beginListen(Vt.UserLeftRoom,this.onOtherUserLeftRoom)}hasState(e){return e?this._states.has(e):!1}isTracking(e,t){if(!e)return;const r=this._states.get(e);if(!r)return;const s=r.controllerStates.find(o=>o.handedness===t);return s?.isTracking||!1}getDeviceType(e,t){if(!e)return;const r=this._states.get(e);if(!r)return;const s=r.controllerStates.find(o=>o.handedness===t);return s?.type||"unknown"}destroy(){this.context.connection.stopListen(Vt.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(Vt.LeftRoom,this.onLeftRoom),this.context.connection.stopListen(Vt.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.stopListen(Vt.UserLeftRoom,this.onOtherUserLeftRoom)}onUpdate(e){if(this.context.connection.isConnected&&this.context.connection.connectionId){const t=this._states.get(this.context.connection.connectionId);t?.update(e)}}onExitXR(e){if(this.context.connection.isConnected&&this.context.connection.connectionId){const t=this._states.get(this.context.connection.connectionId);t?.onExitXR(e)}}}class lV{constructor(){d(this,"_fadeToColorQuad"),d(this,"_fadeToColorMaterial"),d(this,"_requestedFadeValue",0),d(this,"_transitionPromise",null),d(this,"_transitionResolve",null),this._fadeToColorMaterial=new $t({color:0,transparent:!0,depthTest:!1,fog:!1,side:yi}),this._fadeToColorQuad=new me(new tr(10,10),this._fadeToColorMaterial)}dispose(){this._fadeToColorQuad.geometry.dispose(),this._fadeToColorMaterial.dispose()}update(e,t){const r=this._fadeToColorQuad,s=this._fadeToColorMaterial;r.parent!==e&&s.opacity>0?e.add(r):s.opacity===0&&r.removeFromParent(),r.layers.set(2),r.material=this._fadeToColorMaterial,r.position.z=-1,r.renderOrder=1/0;const o=this._requestedFadeValue;s.opacity=it.lerp(s.opacity,o,t/.03),Math.abs(s.opacity-o)<=.01&&this._transitionResolve&&(this._transitionResolve(),this._transitionResolve=null,this._transitionPromise=null,this._requestedFadeValue=0)}remove(){this._fadeToColorQuad.removeFromParent()}fadeTransition(){if(this._transitionPromise)return this._transitionPromise;this._requestedFadeValue=1;const e=new Promise(t=>{this._transitionResolve=t});return this._transitionPromise=e,e}}var Yp=(n=>(n[n.Quad=0]="Quad",n[n.Cube=1]="Cube",n[n.Sphere=2]="Sphere",n))(Yp||{});class sA{static createPrimitive(e,t){let r;switch(e){case"Quad":case 0:{const s=new tr(1,1,1,1),o=t?.material??new vs({color:16777215});t!=null&&t.texture&&"map"in o&&(o.map=t.texture),r=new me(s,o)}break;case"Cube":case 1:{const s=new qi(1,1,1),o=t?.material??new vs({color:16777215});t!=null&&t.texture&&"map"in o&&(o.map=t.texture),r=new me(s,o)}break;case"Sphere":case 2:{const s=new ja(.5,16,16),o=t?.material??new vs({color:16777215});t!=null&&t.texture&&"map"in o&&(o.map=t.texture),r=new me(s,o)}break}return this.applyDefaultObjectOptions(r,t),r}static createSprite(e){const t=new lx({color:16777215});e!=null&&e.texture&&"map"in t&&(t.map=e.texture);const r=new OT(t);return this.applyDefaultObjectOptions(r,e),r}static applyDefaultObjectOptions(e,t){t!=null&&t.name&&(e.name=t.name),t!=null&&t.position&&e.position.set(t.position.x,t.position.y,t.position.z),t!=null&&t.rotation&&e.rotation.set(t.rotation.x,t.rotation.y,t.rotation.z),t!=null&&t.scale&&e.scale.set(t.scale.x,t.scale.y,t.scale.z)}}const cV=class{constructor(n,e,t){d(this,"_session"),d(this,"_mode"),d(this,"_init"),d(this,"_renderer"),d(this,"_camera"),d(this,"_scene"),d(this,"onEnd",()=>{var r;(r=this._session)==null||r.removeEventListener("end",this.onEnd),this._renderer.setAnimationLoop(null),this._renderer.dispose(),this._scene.clear()}),d(this,"_lastTime",0),d(this,"onFrame",(r,s)=>{const o=r-this._lastTime;this.update(r,o),this._camera.parent!==this._scene&&this._scene.add(this._camera),this._renderer.render(this._scene,this._camera)}),d(this,"_objects",[]),this._mode=n,this._init=e,this._session=t,this._session.addEventListener("end",this.onEnd),this._renderer=new Wc({alpha:!0}),this._renderer.setAnimationLoop(this.onFrame),this._renderer.xr.setSession(t),this._renderer.xr.enabled=!0,this._camera=new Lt,this._scene=new Ur,this._scene.fog=new ax(4473924,10,250),this._scene.add(this._camera),this.setupScene()}static get active(){return this._active}static async start(n,e){if(this._active)return console.error("Cannot start a new XR session while one is already active"),null;if(this._requestInFlight)return console.error("Cannot start a new XR session while a request is already in flight"),null;if("xr"in navigator&&navigator.xr){if(!e)return console.error("XRSessionInit must be provided"),null;this._requestInFlight=!0;const t=await navigator.xr.requestSession(n,e);return t.addEventListener("end",()=>{this._active=null}),this._requestInFlight?(this._requestInFlight=!1,this._active=new cV(n,e,t),this._active):(t.end(),null)}return null}static async handoff(){return this._active?this._active.handoff():null}static async stop(){this._requestInFlight=!1,this._active&&(await this._active.end(),await Ll(100)),this._active=null}get isAR(){return this._mode==="immersive-ar"}end(){return this._session?this._session.end():Promise.resolve()}async handoff(){if(!this._session)throw new Error("Cannot handoff a session that has already ended");const n={session:this._session,mode:this._mode,init:this._init};return await this.onBeforeHandoff(),this.onEnd(),this._session=null,n}async onBeforeHandoff(){await Ll(1e3),this._scene.clear()}setupScene(){this._scene.background=new xe(0),this._scene.add(new Hx(5,10,1118481,1118481));const n=new lp(16777215,1);n.position.set(0,20,0),n.castShadow=!1,this._scene.add(n);const e=new lp(16777215,1);e.position.set(0,-1,0),e.castShadow=!1,this._scene.add(e);const t=new ap(16777215,1,100,1);t.position.set(0,2,0),t.castShadow=!1,t.distance=200,this._scene.add(t);const r=50;for(let s=0;s<100;s++){const o=new vs({color:2236962,metalness:1,roughness:.8});this.isAR&&(o.emissive=new xe(Math.random(),Math.random(),Math.random()),o.emissiveIntensity=Math.random());const a=it.random(0,1)>.5?Yp.Sphere:Yp.Cube,l=sA.createPrimitive(a,{material:o});l.position.x=it.random(-r,r),l.position.y=it.random(-2,r),l.position.z=it.random(-r,r),l.rotation.x=it.random(0,Math.PI*2),l.rotation.y=it.random(0,Math.PI*2),l.rotation.z=it.random(0,Math.PI*2),l.scale.multiplyScalar(.5+Math.random()*10);const c=l.position.distanceTo(this._camera.position)-l.scale.x;c<1&&l.position.multiplyScalar(1+1/c),this._objects.push(l),this._scene.add(l)}}update(n,e){const t=n*4e-4;for(let r=0;r<this._objects.length;r++){const s=this._objects[r];s.position.y+=Math.sin(t+r*.5)*.005,s.rotateY(.002)}}};let Lg=cV;d(Lg,"_active",null),d(Lg,"_requestInFlight",!1);const Sr=te("debugwebxr"),gde=te("stats");function vde(n){let e=null;const t=n;return t.getAROverlayContainer?e=t.getAROverlayContainer():e=n,e}yde();async function yde(){var n;if(te("debugasap")){let e=globalThis["needle:XRSession"];if(e instanceof Promise){delete globalThis["needle:XRSession"],di.addContextCreatedCallback(async t=>{if(!e)return;Nf(!0);const r=await e;if(r){const s=wt.getDefaultSessionInit("immersive-vr");wt.setSession("immersive-vr",r,s,t.context)}else console.error("NeedleXRSession: ASAP session was rejected");e=void 0});return}}if("xr"in navigator){if(/WebXRViewer\//i.test(navigator.userAgent)){console.warn("WebXRViewer does not support addEventListener");return}(n=navigator.xr)==null||n.addEventListener("sessiongranted",async()=>{Nf(!0),console.log("Received Session Granted..."),await Ll(100);const e=sessionStorage.getItem("needle_xr_session_mode"),t=sessionStorage.getItem("needle_xr_session_init")??null,r=t?JSON.parse(t):null;let s=null;if(hV()&&(await Lg.start(e||"immersive-vr",r||wt.getDefaultSessionInit("immersive-vr")),await _de(),s=await Lg.handoff()),s)wt.setSession(s.mode,s.session,s.init,kt.Current);else if(e&&t){console.log("Session Granted: Restore last session");const o=JSON.parse(t);wt.start(e,o).catch(a=>console.warn(a))}else wt.start("immersive-vr").catch(o=>console.warn("Session Granted failed:",o))},{once:!0})}}function Ade(n,e){sessionStorage.setItem("needle_xr_session_mode",n),sessionStorage.setItem("needle_xr_session_init",JSON.stringify(e))}function bde(){sessionStorage.removeItem("needle_xr_session_mode"),sessionStorage.removeItem("needle_xr_session_init")}const VB=new Set;di.registerCallback(Ci.ContextCreationStart,async n=>{VB.add(n.context)}),di.registerCallback(Ci.ContextCreated,async n=>{VB.delete(n.context)});function hV(){return VB.size>0}function _de(){return new Promise(n=>{const e=Date.now(),t=setInterval(()=>{(!hV()||Date.now()-e>6e4)&&(clearInterval(t),n())},100)})}fp()&&st()&&window.addEventListener("keydown",n=>{(n.key==="x"||n.key==="Escape")&&wt.active&&wt.stop()});const Vu=class{constructor(n,e,t,r){d(this,"context"),d(this,"session"),d(this,"mode"),d(this,"controllers",[]),d(this,"_rigScale",1),d(this,"_lastRigScaleUpdate",-1),d(this,"_rigs",[]),d(this,"_viewerHitTestSource",null),d(this,"_defaultRig"),d(this,"_xr_scripts"),d(this,"_xr_update_scripts",[]),d(this,"_inactive_scripts",[]),d(this,"_controllerAdded"),d(this,"_controllerRemoved"),d(this,"_originalCameraWorldPosition"),d(this,"_originalCameraWorldRotation"),d(this,"_originalCameraWorldScale"),d(this,"_originalCameraParent"),d(this,"_mainCamera",null),d(this,"onRendererSessionSet",()=>{var a;this.running&&(this.context.renderer.xr.enabled=!0,this.context.renderer.xr.updateCamera(this.context.mainCamera),(a=this.context.mainCameraComponent)==null||a.applyClearFlags())}),d(this,"onInputSourceAdded",a=>{if(a.targetRayMode==="screen")return;let l=0;for(let h=0;h<this.session.inputSources.length;h++)if(this.session.inputSources[h]===a){l=h;break}if(this.controllers.find(h=>h.inputSource===a)){console.warn("Controller already exists for input source",l);return}Sr&&console.log("Adding controller",l);const c=new vB(this,a,l);this._newControllers.push(c)}),d(this,"_ended",!1),d(this,"_newControllers",[]),d(this,"onEnd",a=>{var l,c,h;if(this._ended)return;this._ended=!0,Sr&&console.log("XR Session ended"),bde(),this.onAfterRender(),this.revertCustomForward(),this._didStart=!1,this._previousCameraParent=null,zu(this.onBefore,Hi.LateUpdate);const u=this.context.pre_render_callbacks.indexOf(this.onBeforeRender);u>=0&&this.context.pre_render_callbacks.splice(u,1);const p=this.context.post_render_callbacks.indexOf(this.onAfterRender);p>=0&&this.context.post_render_callbacks.splice(p,1),this.context.xr=null,this.context.renderer.xr.enabled=!1,this.context.pre_update_oneshot_callbacks.push(()=>{var m;(m=this.context.mainCameraComponent)==null||m.applyClearFlags()}),R6({session:this});for(const m of Vu._xrEndListeners)m({xr:this});for(let m=0;m<this.controllers.length;m++)this.disconnectInputSource(this.controllers[m].inputSource);for(const m of this._xr_scripts)(l=m?.onLeaveXR)==null||l.call(m,{xr:this});(c=this.sync)==null||c.onExitXR(this),this.context.mainCamera&&((h=this._originalCameraParent)==null||h.add(this.context.mainCamera),this._originalCameraWorldPosition&&lr(this.context.mainCamera,this._originalCameraWorldPosition),this._originalCameraWorldRotation&&ca(this.context.mainCamera,this._originalCameraWorldRotation),this._originalCameraWorldScale&&Uf(this.context.mainCamera,this._originalCameraWorldScale)),this.context.requestSizeUpdate(),this._defaultRig.gameObject.removeFromParent(),Nf(!1)}),d(this,"_didStart",!1),d(this,"onBefore",a=>{var l,c,h,u,p,m,f,g;const v=a.xrFrame;if(!v)return;this.context.xr=this,this.context.mainCameraComponent&&this.context.mainCameraComponent!==this._mainCamera&&(this._mainCamera=this.context.mainCameraComponent),((l=this.rig)==null?void 0:l.isActive)==!1&&(Sr&&console.warn("Latest rig is not active - trying to activate a different rig",this.rig),this.updateActiveXRRig()),this.rig&&(c=this._mainCamera)!=null&&c.gameObject&&((u=(h=this._mainCamera)==null?void 0:h.gameObject)==null?void 0:u.parent)!==this.rig.gameObject&&this.rig.gameObject.add((p=this._mainCamera)==null?void 0:p.gameObject),this.internalUpdateState(),this.applyCustomForward();const y={xr:this};if(this._didStart){if(this.context.new_scripts_xr.length>0){const A=[...this.context.new_scripts_xr];for(let _=0;_<A.length;_++){const b=this.context.new_scripts_xr[_];if(!b||b.destroyed||((m=b.supportsXR)==null?void 0:m.call(b,this.mode))==!1){this.context.new_scripts_xr.splice(_,1);continue}if(!b.activeAndEnabled){this.context.new_scripts_xr.splice(_,1),this.markInactive(b);continue}if(this.addScript(b)){this.invokeCallback_EnterXR(b);for(const x of this.controllers)this.invokeCallback_ControllerAdded(b,x)}}}}else{if(this._didStart=!0,this.mode==="immersive-vr"){const _=Ul(this.context.scene.children);if(_){const b=_.getSize(pi());if(b.length()>0){const x=this._defaultRig.gameObject;x.position.set(_.min.x+b.x*.5,_.min.y,_.max.z+b.z*.5+1.5);const E=_.getCenter(pi());E.y=x.position.y,x.lookAt(E)}}}I6({session:this});for(const _ of Vu._xrStartListeners)_(y);const A=[...this._xr_scripts];Sr&&console.log("NeedleXRSession start, handle scripts:",A);for(const _ of A){if(_.destroyed){this._script_to_remove.push(_);continue}if(!_.activeAndEnabled){this.markInactive(_);continue}this.invokeCallback_EnterXR(_);for(const b of this.controllers)this.invokeCallback_ControllerAdded(_,b)}}this.syncCameraCullingMask();for(const A of this.controllers)A.onUpdate(v);if(this._newControllers.length>0){const A=[...this._newControllers];this._newControllers.length=0;for(const _ of A)if(_.connected){this.controllers.push(_);for(const b of this._xr_scripts){if(b.destroyed){this._script_to_remove.push(b);continue}b.activeAndEnabled!==!1&&this.invokeCallback_ControllerAdded(b,_)}}this.controllers.sort((_,b)=>_.index-b.index)}for(const A of this._xr_update_scripts){if(A.destroyed===!0){this._script_to_remove.push(A);continue}if(A.activeAndEnabled===!1){this.markInactive(A);continue}A.onUpdateXR&&A.onUpdateXR(y)}if(this.handleInactiveScripts(),this._script_to_remove.length>0){const A=[...new Set(this._script_to_remove)];this._script_to_remove.length=0;for(const _ of A)!_.destroyed&&this.running&&((f=_.onLeaveXR)==null||f.call(_,y)),this.removeScript(_)}(g=this.sync)==null||g.onUpdate(this),this.onRenderDebug()}),d(this,"onBeforeRender",()=>{this.context.mainCamera&&this.updateFade(this.context.mainCamera)}),d(this,"onAfterRender",()=>{if(this.onUpdateFade_PostRender(),fp()){const a=this.context.renderer;if(a.xr.isPresenting&&this.context.mainCamera){const l=a.xr.enabled,c=a.getRenderTarget();a.xr.enabled=!1,a.setRenderTarget(null),a.render(this.context.scene,this.context.mainCamera),a.xr.enabled=l,a.setRenderTarget(c)}}}),d(this,"_script_to_remove",[]),d(this,"_camera"),d(this,"_cameraRenderParent",new ye().rotateY(Math.PI)),d(this,"_previousCameraParent"),d(this,"_customforward",!0),d(this,"originalCameraNearPlane"),d(this,"_viewerPose"),d(this,"_transformOrientation",new Ce),d(this,"_transformPosition",new C),d(this,"_transition");var s,o;Ade(n,r.init),this.session=e,this.mode=n,this.context=t,(Sr||te("console"))&&Nf(!0),this._xr_scripts=[...r.scripts],this._xr_update_scripts=this._xr_scripts.filter(a=>typeof a.onUpdateXR=="function"),this._controllerAdded=r.controller_added,this._controllerRemoved=r.controller_removed,Nu(this.onBefore,Hi.LateUpdate),this.context.pre_render_callbacks.push(this.onBeforeRender),this.context.post_render_callbacks.push(this.onAfterRender),((s=r.init.optionalFeatures)!=null&&s.includes("hit-test")||(o=r.init.requiredFeatures)!=null&&o.includes("hit-test"))&&e.requestReferenceSpace("viewer").then(a=>{var l,c;return(c=(l=e.requestHitTestSource)==null?void 0:l.call(e,{space:a}))==null?void 0:c.then(h=>this._viewerHitTestSource=h)}).catch(a=>console.warn(a)),this.context.mainCamera&&(this._originalCameraWorldPosition=Bt(this.context.mainCamera,new C),this._originalCameraWorldRotation=Mi(this.context.mainCamera,new Ce),this._originalCameraWorldScale=Vi(this.context.mainCamera,new C),this._originalCameraParent=this.context.mainCamera.parent),this._defaultRig=new Sue,this.context.scene.add(this._defaultRig.gameObject),this.addRig(this._defaultRig);for(let a=0;a<e.inputSources.length;a++){const l=e.inputSources[a];if(!l.handedness){console.warn("Input source in xr session has no handedness - ignoring",a);continue}this.onInputSourceAdded(l)}this.session.addEventListener("end",this.onEnd),this.session.addEventListener("inputsourceschange",a=>{for(const l of a.removed)this.disconnectInputSource(l);for(const l of a.added)this.onInputSourceAdded(l)}),this.context.xr=this,this.context.renderer.xr.setSession(this.session).then(this.onRendererSessionSet)}static getXRSync(n){return this._sync||(this._sync=new aV(n)),this._sync}static get currentSessionRequest(){return this._currentSessionRequestMode}static get active(){return this._activeSession}static get activeMode(){var n;return((n=this._activeSession)==null?void 0:n.mode)??null}static get xrSystem(){return"xr"in navigator?navigator.xr:void 0}static isXRSupported(){return Promise.all([this.isVRSupported(),this.isARSupported()]).then(n=>n.some(e=>e)).catch(()=>!1)}static isVRSupported(){return this.isSessionSupported("immersive-vr")}static isARSupported(){return this.isSessionSupported("immersive-ar")}static isSessionSupported(n){var e;return((e=this.xrSystem)==null?void 0:e.isSessionSupported(n).catch(t=>(Sr&&console.error(t),!1)))??Promise.resolve(!1)}static onSessionRequestStart(n){this._sessionRequestStartListeners.push(n)}static offSessionRequestStart(n){const e=this._sessionRequestStartListeners.indexOf(n);e>=0&&this._sessionRequestStartListeners.splice(e,1)}static onSessionRequestEnd(n){this._sessionRequestEndListeners.push(n)}static offSessionRequestEnd(n){const e=this._sessionRequestEndListeners.indexOf(n);e>=0&&this._sessionRequestEndListeners.splice(e,1)}static onXRSessionStart(n){this._xrStartListeners.push(n)}static offXRSessionStart(n){const e=this._xrStartListeners.indexOf(n);e>=0&&this._xrStartListeners.splice(e,1)}static onXRSessionEnd(n){this._xrEndListeners.push(n)}static offXRSessionEnd(n){const e=this._xrEndListeners.indexOf(n);e>=0&&this._xrEndListeners.splice(e,1)}static onControllerAdded(n){this._controllerAddedListeners.push(n)}static offControllerAdded(n){const e=this._controllerAddedListeners.indexOf(n);e>=0&&this._controllerAddedListeners.splice(e,1)}static onControllerRemoved(n){this._controllerRemovedListeners.push(n)}static offControllerRemoved(n){const e=this._controllerRemovedListeners.indexOf(n);e>=0&&this._controllerRemovedListeners.splice(e,1)}static offerSession(n,e,t){return"xr"in navigator&&navigator.xr&&"offerSession"in navigator.xr?(typeof navigator.xr.offerSession=="function"&&(console.log("WebXR offerSession is available - requesting mode: "+n),e=="default"&&(e=this.getDefaultSessionInit(n)),navigator.xr.offerSession(n,{...e}).then(r=>Vu.setSession(n,r,e,t)).catch(r=>{console.log("XRSession offer rejected (perhaps because another call to offerSession was made or a call to requestSession was made)")})),!0):!1}static getDefaultSessionInit(n){switch(n){case"immersive-ar":return{optionalFeatures:["anchors","local-floor","hand-tracking","layers","dom-overlay","hit-test"]};case"immersive-vr":return{optionalFeatures:["local-floor","bounded-floor","hand-tracking","high-fixed-foveation-level","layers"]};default:return console.warn("No default session init for mode",n),{}}}static async start(n,e,t){var r,s,o,a;if(st()&&te("debugxrpreroom"))return console.warn("Debug: Starting temporary XR session"),await Lg.start(n,e||Vu.getDefaultSessionInit(n)),null;if(this._currentSessionRequest)return console.warn("A XRSession is already being requested"),(Sr||st())&&Di("A XRSession is already being requested"),this._currentSessionRequest.then(()=>this._activeSession);if(this._activeSession)return console.error("A XRSession is already running"),this._activeSession;if(t||(t=kt.Current),t||(t=di.All[0]),!t)throw new Error("No Needle Engine Context found");switch(e||(e={}),n){case"immersive-ar":{if(await((r=this.xrSystem)==null?void 0:r.isSessionSupported("immersive-ar"))!==!0)return console.error(n+" is not supported by this browser."),null;const h=this.getDefaultSessionInit(n),u=vde(t.domElement);u&&!ew()&&(h.domOverlay={root:u},h.optionalFeatures.push("dom-overlay")),e={...h,...e}}break;case"immersive-vr":{if(await((s=this.xrSystem)==null?void 0:s.isSessionSupported("immersive-vr"))!==!0)return console.error(n+" is not supported by this browser."),null;e={...this.getDefaultSessionInit(n),...e}}break;default:console.warn("No default session init for mode",n);break}e.optionalFeatures??(e.optionalFeatures=[]),e.requiredFeatures??(e.requiredFeatures=[]),await Lg.stop();const l=n=="immersive-ar"?t.scripts_immersive_ar:t.scripts_immersive_vr;Sr?console.log(`%cRequesting ${n} session`,"font-weight:bold;",e,l):console.log(`%cRequesting ${n} session`,"font-weight:bold;");for(const h of l)h.onBeforeXR&&h.onBeforeXR(n,e);for(const h of this._sessionRequestStartListeners)h({mode:n,init:e});Sr&&rn("Requesting "+n+" session ("+Date.now()+")"),this._currentSessionRequest=(o=navigator.xr)==null?void 0:o.requestSession(n,e),this._currentSessionRequestMode=n;const c=await((a=this._currentSessionRequest)==null?void 0:a.catch(h=>{console.error(h,"Code: "+h.code),h.code===9&&Di("Make sure your device has the required permissions (e.g. camera access)"),console.log("If the specified XR configuration is not supported (e.g. entering AR doesnt work) - make sure you access the website on a secure connection (HTTPS) and your device has the required permissions (e.g. camera access)"),location.protocol==="http:"&&Di("XR requires a secure connection (HTTPS)")}));this._currentSessionRequest=void 0,this._currentSessionRequestMode=null;for(const h of this._sessionRequestEndListeners)h({mode:n,init:e,newSession:c||null});return c?this.setSession(n,c,e,t):(console.warn("XR Session request was rejected"),null)}static setSession(n,e,t,r){if(this._activeSession)return console.error("A XRSession is already running"),this._activeSession;const s=n=="immersive-ar"?r.scripts_immersive_ar:r.scripts_immersive_vr;return this._activeSession=new Vu(n,e,r,{scripts:s,controller_added:this._controllerAddedListeners,controller_removed:this._controllerRemovedListeners,init:t}),e.addEventListener("end",this.onEnd),Sr?console.log(`%cStarted ${n} session`,"font-weight:bold;",s):console.log(`%cStarted ${n} session`,"font-weight:bold;"),this._activeSession}static stop(){var n;(n=this._activeSession)==null||n.end()}get sync(){return Vu._sync}get running(){return!this._ended&&this.session!=null}get interactionMode(){return this.session.interactionMode}get visibilityState(){return this.session.visibilityState}get environmentBlendMode(){return this.session.environmentBlendMode}get frame(){return this.context.xrFrame}get leftController(){return this.controllers.find(n=>n.isLeft)}get rightController(){return this.controllers.find(n=>n.isRight)}getController(n){return typeof n=="number"?this.controllers[n]||null:this.controllers.find(e=>e.side===n)||null}get isPassThrough(){return!!(this.environmentBlendMode!=="opaque"&&this.interactionMode==="world-space"||this.mode==="immersive-ar"&&this.environmentBlendMode!=="opaque"&&this.controllers.some(n=>n.inputSource.targetRayMode==="tracked-pointer")||st()&&fp()&&this.mode==="immersive-ar")}get isAR(){return this.mode==="immersive-ar"}get isVR(){return this.mode==="immersive-vr"}get isScreenBasedAR(){return this.isAR&&!this.isPassThrough}get posePosition(){return this._transformPosition}get poseOrientation(){return this._transformOrientation}get referenceSpace(){return this.context.renderer.xr.getReferenceSpace()}get viewerPose(){return this._viewerPose}get isTrackingImages(){if(this.frame&&"getImageTrackingResults"in this.frame&&typeof this.frame.getImageTrackingResults=="function")try{const n=this.frame.getImageTrackingResults();for(const e of n)if(e.trackingState==="tracked")return!0}catch{return!1}return!1}get rig(){const n=this._rigs[0]??null;return n!=null&&n.gameObject&&Jp(n.gameObject)||n?.isActive===!1?(this.updateActiveXRRig(),this._rigs[0]??null):n}get rigScale(){return this._rigs[0]?(this._lastRigScaleUpdate!==this.context.time.frame&&(this._lastRigScaleUpdate=this.context.time.frame,this._rigScale=this._rigs[0].gameObject.worldScale.x),this._rigScale):1}addRig(n){this._rigs.indexOf(n)>=0||(n.priority===void 0&&(n.priority=0),this._rigs.push(n),this.updateActiveXRRig())}removeRig(n){const e=this._rigs.indexOf(n);e!==-1&&(this._rigs.splice(e,1),this.updateActiveXRRig())}setRigActive(n){const e=this._rigs.indexOf(n);this._rigs.splice(e,1),this._rigs.unshift(n),this.updateActiveXRRig()}updateActiveXRRig(){const n=this._rigs[0]??null;this._defaultRig.gameObject.parent!==this.context.scene&&this.context.scene.add(this._defaultRig.gameObject),this._defaultRig.gameObject.visible=!0,this._rigs.includes(this._defaultRig)||this._rigs.push(this._defaultRig);let e=this._rigs[0];e&&e.priority===void 0&&(e.priority=0);for(let t=1;t<this._rigs.length;t++){const r=this._rigs[t];if(r.isActive){if(Jp(r.gameObject)){this._rigs.splice(t,1),t--;continue}(!e||e.isActive===!1||r.priority!==void 0&&r.priority>e.priority)&&(e=r)}}if(n!==e){const t=this._rigs.indexOf(e);t>=0&&this._rigs.splice(t,1),this._rigs.unshift(e)}Sr&&(n===e?console.log("Updated Active XR Rig:",e,"prev:",n):console.log("Updated Active XRRig:",e," (the same as before)"))}getHitTest(n){if(n)return this.getControllerHitTest(n);if(!this._viewerHitTestSource)return null;const e=this._viewerHitTestSource,t=this.frame.getHitTestResults(e);if(t.length>0){const r=t[0];return this.convertHitTestResult(r)}return null}getControllerHitTest(n){const e=n.hitTestSource;if(!e)return null;const t=this.frame.getHitTestResultsForTransientInput(e);for(const r of t)if(r.inputSource===n.inputSource)for(const s of r.results)return this.convertHitTestResult(s);return null}convertHitTestResult(n){const e=this.context.renderer.xr.getReferenceSpace(),t=e&&n.getPose(e);if(t){const r=pi(t.transform.position),s=bp(t.transform.orientation),o=this.context.mainCamera;if(o?.parent!==this._cameraRenderParent&&r.applyMatrix4(Y1),o!=null&&o.parent){r.applyMatrix4(o.parent.matrixWorld),s.multiply(Sa);const a=Mi(o.parent);a.premultiply(Sa),s.premultiply(a)}return{hit:n,position:r,quaternion:s}}return null}convertSpace(n){const e=pi(n.position);e.applyMatrix4(Y1);const t=bp(n.orientation);return t.premultiply(Sa),{position:e,quaternion:t}}disconnectInputSource(n){const e=(t,r,s)=>{if(t.inputSource===n){Sr&&console.log("Disconnecting controller",t.index),this.controllers.splice(s,1),this.invokeControllerEvent(t,this._controllerRemoved,"removed");const o={xr:this,controller:t,change:"removed"};for(const a of this._xr_scripts)a.onXRControllerRemoved&&a.onXRControllerRemoved(o);t.onDisconnected()}};for(let t=this.controllers.length-1;t>=0;t--){const r=this.controllers[t];e(r,this.controllers,t)}for(let t=this._newControllers.length-1;t>=0;t--){const r=this._newControllers[t];e(r,this._newControllers,t)}}end(){this._ended||this.session.end().catch(n=>console.warn(n))}onRenderDebug(){if(Sr)for(const n of this.controllers)n.onRenderDebug();if((Sr||gde)&&this.rig){const n=this.rig.gameObject.worldPosition,e=this.rig.gameObject.worldForward;n.add(e.multiplyScalar(1.5));const t=this.rig.gameObject.worldUp;n.add(t.multiplyScalar(2.5));let r="";if(r+=this.context.time.smoothedFps.toFixed(1),Sr)for(const s of this.controllers)r+=`
|
|
5235
|
+
`+c.href)}this.onSendQueued(dl.OnRoomJoin);break;case"left-room":e.room===this.currentRoomName&&(this._isInRoom=!1,this._currentRoomName=null,this._currentInRoom.length=0);break;case"user-joined-room":if(e.data){const l=e.data;this._currentInRoom.push(l.userId),Zs&&console.log(l.userId+" joined","now in room:",this._currentInRoom)}break;case"user-left-room":if(e.data){const l=e.data,c=this._currentInRoom.indexOf(l.userId);c>=0&&(Zs&&console.log(l.userId+" left","now in room:",this._currentInRoom),this._currentInRoom.splice(c,1)),l.userId===this.connectionId&&console.log("you left the room")}break;case"all-room-state-deleted":Zs&&console.log("RECEIVED all-room-state-deleted"),this._state={};break;case"ping":case"pong":const a=(t=e.data)==null?void 0:t.time;a&&(this._currentDelay=this.context.time.time-a),Zs&&console.log("Current latency: "+this._currentDelay.toFixed(4)+" sec","Clients in room: "+((r=this._currentInRoom)==null?void 0:r.length));break}const s=e.data;s&&(this._state[s.guid]=s);let o=this._listeners[e.key];if(o){o=[...o];for(const a of o)try{a(e.data)}catch(l){console.error('Error invoking callback for "'+e.key+'"',l)}}}toMessage(e,t){return{key:e,data:t}}sendWithWebsocket(e,t,r=dl.OnRoomJoin){if(!this._ws){const o=this._waitingForSocket[r]||[];o.push(()=>this.sendWithWebsocket(e,t,r)),this._waitingForSocket[r]=o;return}const s=JSON.stringify(this.toMessage(e,t));Zs&&console.log(">>",e),this._ws.send(s)}onSendQueued(e){const t=this._waitingForSocket[e];if(t){for(const r of t)r();t.length=0}}}const rA=te("debugwebxr");class GB{constructor(e,t){d(this,"controllerStates",[]),d(this,"userId"),d(this,"context"),d(this,"userStateEvtName"),d(this,"onReceivedControllerState",r=>{rA&&console.log(`XRSync: Received change for ${this.userId}: ${r.type} ${r.handedness}; tracked=${r.isTracking}`);let s=!1;for(let o=0;o<this.controllerStates.length;o++)if(this.controllerStates[o].index===r.index){this.controllerStates[o]=r,s=!0;break}s||this.controllerStates.push(r)}),this.userId=e,this.context=t,this.userStateEvtName="xr-sync-user-state-"+e,this.context.connection.beginListen(this.userStateEvtName,this.onReceivedControllerState)}dispose(){this.context.connection.stopListen(this.userStateEvtName,this.onReceivedControllerState)}update(e){if(this.context.connection.isConnected!=!1){for(let t=this.controllerStates.length-1;t>=0;t--){const r=this.controllerStates[t];let s=!1;for(let o=0;o<e.controllers.length;o++)e.controllers[o].index===r.index&&(s=!0);s||(rA&&console.log(`XRSync: ${r.type} ${r.handedness} removed`,r.index),this.controllerStates.splice(t,1),this.sendControllerRemoved(r))}for(const t of e.controllers)this.updateControllerStates(t)}}onExitXR(e){for(const t of this.controllerStates)this.sendControllerRemoved(t);this.controllerStates.length=0}sendControllerRemoved(e){e.isTracking=!1,e.guid="",this.context.connection.send(this.userStateEvtName,e),this.context.connection.sendDeleteRemoteState(e.guid)}updateControllerStates(e){const t=this.controllerStates.find(r=>r.index===e.index);if(t){let r=!1;r||(r=t.isTracking!=e.isTracking),r&&(t.isTracking=e.isTracking,this.context.connection.send(this.userStateEvtName,t))}else{const r={guid:this.userId+"-"+e.index,isTracking:e.isTracking,handedness:e.side,index:e.index,type:e.hand?"hand":"controller"};this.controllerStates.push(r),this.context.connection.send(this.userStateEvtName,r),rA&&console.log(`XRSync: ${r.type} ${r.handedness} added`,r.index)}}}class aV{constructor(e){d(this,"context"),d(this,"onJoinedRoom",()=>{if(this.context.connection.connectionId){this._states.has(this.context.connection.connectionId)||(rA&&console.log("XRSync: Local user joined room",this.context.connection.connectionId),this._states.set(this.context.connection.connectionId,new GB(this.context.connection.connectionId,this.context)));for(const t of this.context.connection.usersInRoom())this._states.has(t)||this._states.set(t,new GB(t,this.context))}}),d(this,"onLeftRoom",()=>{if(this.context.connection.connectionId&&!this._states.has(this.context.connection.connectionId)){const t=this._states.get(this.context.connection.connectionId);t?.dispose(),this._states.delete(this.context.connection.connectionId)}}),d(this,"onOtherUserJoinedRoom",t=>{const r=t.userId;this._states.has(r)||(rA&&console.log("XRSync: Remote user joined room",r),this._states.set(r,new GB(r,this.context)))}),d(this,"onOtherUserLeftRoom",t=>{const r=t.userId;if(!this._states.has(r)){const s=this._states.get(r);s?.dispose(),this._states.delete(r)}}),d(this,"_states",new Map),this.context=e,this.context.connection.beginListen(Vt.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(Vt.LeftRoom,this.onLeftRoom),this.context.connection.beginListen(Vt.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.beginListen(Vt.UserLeftRoom,this.onOtherUserLeftRoom)}hasState(e){return e?this._states.has(e):!1}isTracking(e,t){if(!e)return;const r=this._states.get(e);if(!r)return;const s=r.controllerStates.find(o=>o.handedness===t);return s?.isTracking||!1}getDeviceType(e,t){if(!e)return;const r=this._states.get(e);if(!r)return;const s=r.controllerStates.find(o=>o.handedness===t);return s?.type||"unknown"}destroy(){this.context.connection.stopListen(Vt.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(Vt.LeftRoom,this.onLeftRoom),this.context.connection.stopListen(Vt.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.stopListen(Vt.UserLeftRoom,this.onOtherUserLeftRoom)}onUpdate(e){if(this.context.connection.isConnected&&this.context.connection.connectionId){const t=this._states.get(this.context.connection.connectionId);t?.update(e)}}onExitXR(e){if(this.context.connection.isConnected&&this.context.connection.connectionId){const t=this._states.get(this.context.connection.connectionId);t?.onExitXR(e)}}}class lV{constructor(){d(this,"_fadeToColorQuad"),d(this,"_fadeToColorMaterial"),d(this,"_requestedFadeValue",0),d(this,"_transitionPromise",null),d(this,"_transitionResolve",null),this._fadeToColorMaterial=new $t({color:0,transparent:!0,depthTest:!1,fog:!1,side:yi}),this._fadeToColorQuad=new me(new tr(10,10),this._fadeToColorMaterial)}dispose(){this._fadeToColorQuad.geometry.dispose(),this._fadeToColorMaterial.dispose()}update(e,t){const r=this._fadeToColorQuad,s=this._fadeToColorMaterial;r.parent!==e&&s.opacity>0?e.add(r):s.opacity===0&&r.removeFromParent(),r.layers.set(2),r.material=this._fadeToColorMaterial,r.position.z=-1,r.renderOrder=1/0;const o=this._requestedFadeValue;s.opacity=it.lerp(s.opacity,o,t/.03),Math.abs(s.opacity-o)<=.01&&this._transitionResolve&&(this._transitionResolve(),this._transitionResolve=null,this._transitionPromise=null,this._requestedFadeValue=0)}remove(){this._fadeToColorQuad.removeFromParent()}fadeTransition(){if(this._transitionPromise)return this._transitionPromise;this._requestedFadeValue=1;const e=new Promise(t=>{this._transitionResolve=t});return this._transitionPromise=e,e}}var Yp=(n=>(n[n.Quad=0]="Quad",n[n.Cube=1]="Cube",n[n.Sphere=2]="Sphere",n))(Yp||{});class sA{static createPrimitive(e,t){let r;switch(e){case"Quad":case 0:{const s=new tr(1,1,1,1),o=t?.material??new vs({color:16777215});t!=null&&t.texture&&"map"in o&&(o.map=t.texture),r=new me(s,o)}break;case"Cube":case 1:{const s=new qi(1,1,1),o=t?.material??new vs({color:16777215});t!=null&&t.texture&&"map"in o&&(o.map=t.texture),r=new me(s,o)}break;case"Sphere":case 2:{const s=new ja(.5,16,16),o=t?.material??new vs({color:16777215});t!=null&&t.texture&&"map"in o&&(o.map=t.texture),r=new me(s,o)}break}return this.applyDefaultObjectOptions(r,t),r}static createSprite(e){const t=new lx({color:16777215});e!=null&&e.texture&&"map"in t&&(t.map=e.texture);const r=new OT(t);return this.applyDefaultObjectOptions(r,e),r}static applyDefaultObjectOptions(e,t){t!=null&&t.name&&(e.name=t.name),t!=null&&t.position&&e.position.set(t.position.x,t.position.y,t.position.z),t!=null&&t.rotation&&e.rotation.set(t.rotation.x,t.rotation.y,t.rotation.z),t!=null&&t.scale&&e.scale.set(t.scale.x,t.scale.y,t.scale.z)}}const cV=class{constructor(n,e,t){d(this,"_session"),d(this,"_mode"),d(this,"_init"),d(this,"_renderer"),d(this,"_camera"),d(this,"_scene"),d(this,"onEnd",()=>{var r;(r=this._session)==null||r.removeEventListener("end",this.onEnd),this._renderer.setAnimationLoop(null),this._renderer.dispose(),this._scene.clear()}),d(this,"_lastTime",0),d(this,"onFrame",(r,s)=>{const o=r-this._lastTime;this.update(r,o),this._camera.parent!==this._scene&&this._scene.add(this._camera),this._renderer.render(this._scene,this._camera)}),d(this,"_objects",[]),this._mode=n,this._init=e,this._session=t,this._session.addEventListener("end",this.onEnd),this._renderer=new Wc({alpha:!0}),this._renderer.setAnimationLoop(this.onFrame),this._renderer.xr.setSession(t),this._renderer.xr.enabled=!0,this._camera=new Lt,this._scene=new Ur,this._scene.fog=new ax(4473924,10,250),this._scene.add(this._camera),this.setupScene()}static get active(){return this._active}static async start(n,e){if(this._active)return console.error("Cannot start a new XR session while one is already active"),null;if(this._requestInFlight)return console.error("Cannot start a new XR session while a request is already in flight"),null;if("xr"in navigator&&navigator.xr){if(!e)return console.error("XRSessionInit must be provided"),null;this._requestInFlight=!0;const t=await navigator.xr.requestSession(n,e);return t.addEventListener("end",()=>{this._active=null}),this._requestInFlight?(this._requestInFlight=!1,this._active=new cV(n,e,t),this._active):(t.end(),null)}return null}static async handoff(){return this._active?this._active.handoff():null}static async stop(){this._requestInFlight=!1,this._active&&(await this._active.end(),await Ll(100)),this._active=null}get isAR(){return this._mode==="immersive-ar"}end(){return this._session?this._session.end():Promise.resolve()}async handoff(){if(!this._session)throw new Error("Cannot handoff a session that has already ended");const n={session:this._session,mode:this._mode,init:this._init};return await this.onBeforeHandoff(),this.onEnd(),this._session=null,n}async onBeforeHandoff(){await Ll(1e3),this._scene.clear()}setupScene(){this._scene.background=new xe(0),this._scene.add(new Hx(5,10,1118481,1118481));const n=new lp(16777215,1);n.position.set(0,20,0),n.castShadow=!1,this._scene.add(n);const e=new lp(16777215,1);e.position.set(0,-1,0),e.castShadow=!1,this._scene.add(e);const t=new ap(16777215,1,100,1);t.position.set(0,2,0),t.castShadow=!1,t.distance=200,this._scene.add(t);const r=50;for(let s=0;s<100;s++){const o=new vs({color:2236962,metalness:1,roughness:.8});this.isAR&&(o.emissive=new xe(Math.random(),Math.random(),Math.random()),o.emissiveIntensity=Math.random());const a=it.random(0,1)>.5?Yp.Sphere:Yp.Cube,l=sA.createPrimitive(a,{material:o});l.position.x=it.random(-r,r),l.position.y=it.random(-2,r),l.position.z=it.random(-r,r),l.rotation.x=it.random(0,Math.PI*2),l.rotation.y=it.random(0,Math.PI*2),l.rotation.z=it.random(0,Math.PI*2),l.scale.multiplyScalar(.5+Math.random()*10);const c=l.position.distanceTo(this._camera.position)-l.scale.x;c<1&&l.position.multiplyScalar(1+1/c),this._objects.push(l),this._scene.add(l)}}update(n,e){const t=n*4e-4;for(let r=0;r<this._objects.length;r++){const s=this._objects[r];s.position.y+=Math.sin(t+r*.5)*.005,s.rotateY(.002)}}};let Lg=cV;d(Lg,"_active",null),d(Lg,"_requestInFlight",!1);const Sr=te("debugwebxr"),gde=te("stats");function vde(n){let e=null;const t=n;return t.getAROverlayContainer?e=t.getAROverlayContainer():e=n,e}yde();async function yde(){var n;if(te("debugasap")){let e=globalThis["needle:XRSession"];if(e instanceof Promise){delete globalThis["needle:XRSession"],di.addContextCreatedCallback(async t=>{if(!e)return;Nf(!0);const r=await e;if(r){const s=wt.getDefaultSessionInit("immersive-vr");wt.setSession("immersive-vr",r,s,t.context)}else console.error("NeedleXRSession: ASAP session was rejected");e=void 0});return}}if("xr"in navigator){if(/WebXRViewer\//i.test(navigator.userAgent)){console.warn("WebXRViewer does not support addEventListener");return}(n=navigator.xr)==null||n.addEventListener("sessiongranted",async()=>{Nf(!0),console.log("Received Session Granted..."),await Ll(100);const e=sessionStorage.getItem("needle_xr_session_mode"),t=sessionStorage.getItem("needle_xr_session_init")??null,r=t?JSON.parse(t):null;let s=null;if(hV()&&(await Lg.start(e||"immersive-vr",r||wt.getDefaultSessionInit("immersive-vr")),await _de(),s=await Lg.handoff()),s)wt.setSession(s.mode,s.session,s.init,kt.Current);else if(e&&t){console.log("Session Granted: Restore last session");const o=JSON.parse(t);wt.start(e,o).catch(a=>console.warn(a))}else wt.start("immersive-vr").catch(o=>console.warn("Session Granted failed:",o))},{once:!0})}}function Ade(n,e){sessionStorage.setItem("needle_xr_session_mode",n),sessionStorage.setItem("needle_xr_session_init",JSON.stringify(e))}function bde(){sessionStorage.removeItem("needle_xr_session_mode"),sessionStorage.removeItem("needle_xr_session_init")}const VB=new Set;di.registerCallback(Ci.ContextCreationStart,async n=>{VB.add(n.context)}),di.registerCallback(Ci.ContextCreated,async n=>{VB.delete(n.context)});function hV(){return VB.size>0}function _de(){return new Promise(n=>{const e=Date.now(),t=setInterval(()=>{(!hV()||Date.now()-e>6e4)&&(clearInterval(t),n())},100)})}fp()&&st()&&window.addEventListener("keydown",n=>{(n.key==="x"||n.key==="Escape")&&wt.active&&wt.stop()});const Vu=class{constructor(n,e,t,r){d(this,"context"),d(this,"session"),d(this,"mode"),d(this,"controllers",[]),d(this,"_rigScale",1),d(this,"_lastRigScaleUpdate",-1),d(this,"_rigs",[]),d(this,"_viewerHitTestSource",null),d(this,"_defaultRig"),d(this,"_xr_scripts"),d(this,"_xr_update_scripts",[]),d(this,"_inactive_scripts",[]),d(this,"_controllerAdded"),d(this,"_controllerRemoved"),d(this,"_originalCameraWorldPosition"),d(this,"_originalCameraWorldRotation"),d(this,"_originalCameraWorldScale"),d(this,"_originalCameraParent"),d(this,"_mainCamera",null),d(this,"onRendererSessionSet",()=>{var a;this.running&&(this.context.renderer.xr.enabled=!0,this.context.renderer.xr.updateCamera(this.context.mainCamera),(a=this.context.mainCameraComponent)==null||a.applyClearFlags())}),d(this,"onInputSourceAdded",a=>{if(a.targetRayMode==="screen")return;let l=0;for(let h=0;h<this.session.inputSources.length;h++)if(this.session.inputSources[h]===a){l=h;break}if(this.controllers.find(h=>h.inputSource===a)){console.warn("Controller already exists for input source",l);return}Sr&&console.log("Adding controller",l);const c=new vB(this,a,l);this._newControllers.push(c)}),d(this,"_ended",!1),d(this,"_newControllers",[]),d(this,"onEnd",a=>{var l,c,h;if(this._ended)return;this._ended=!0,Sr&&console.log("XR Session ended"),bde(),this.onAfterRender(),this.revertCustomForward(),this._didStart=!1,this._previousCameraParent=null,zu(this.onBefore,Hi.LateUpdate);const u=this.context.pre_render_callbacks.indexOf(this.onBeforeRender);u>=0&&this.context.pre_render_callbacks.splice(u,1);const p=this.context.post_render_callbacks.indexOf(this.onAfterRender);p>=0&&this.context.post_render_callbacks.splice(p,1),this.context.xr=null,this.context.renderer.xr.enabled=!1,this.context.pre_update_oneshot_callbacks.push(()=>{var m;(m=this.context.mainCameraComponent)==null||m.applyClearFlags()}),R6({session:this});for(const m of Vu._xrEndListeners)m({xr:this});for(let m=0;m<this.controllers.length;m++)this.disconnectInputSource(this.controllers[m].inputSource);for(const m of this._xr_scripts)(l=m?.onLeaveXR)==null||l.call(m,{xr:this});(c=this.sync)==null||c.onExitXR(this),this.context.mainCamera&&((h=this._originalCameraParent)==null||h.add(this.context.mainCamera),this._originalCameraWorldPosition&&lr(this.context.mainCamera,this._originalCameraWorldPosition),this._originalCameraWorldRotation&&ca(this.context.mainCamera,this._originalCameraWorldRotation),this._originalCameraWorldScale&&Uf(this.context.mainCamera,this._originalCameraWorldScale)),this.context.requestSizeUpdate(),this._defaultRig.gameObject.removeFromParent(),Nf(!1)}),d(this,"_didStart",!1),d(this,"onBefore",a=>{var l,c,h,u,p,m,f,g;const v=a.xrFrame;if(!v)return;this.context.xr=this,this.context.mainCameraComponent&&this.context.mainCameraComponent!==this._mainCamera&&(this._mainCamera=this.context.mainCameraComponent),((l=this.rig)==null?void 0:l.isActive)==!1&&(Sr&&console.warn("Latest rig is not active - trying to activate a different rig",this.rig),this.updateActiveXRRig()),this.rig&&(c=this._mainCamera)!=null&&c.gameObject&&((u=(h=this._mainCamera)==null?void 0:h.gameObject)==null?void 0:u.parent)!==this.rig.gameObject&&this.rig.gameObject.add((p=this._mainCamera)==null?void 0:p.gameObject),this.internalUpdateState(),this.applyCustomForward();const y={xr:this};if(this._didStart){if(this.context.new_scripts_xr.length>0){const A=[...this.context.new_scripts_xr];for(let _=0;_<A.length;_++){const b=this.context.new_scripts_xr[_];if(!b||b.destroyed||((m=b.supportsXR)==null?void 0:m.call(b,this.mode))==!1){this.context.new_scripts_xr.splice(_,1);continue}if(!b.activeAndEnabled){this.context.new_scripts_xr.splice(_,1),this.markInactive(b);continue}if(this.addScript(b)){this.invokeCallback_EnterXR(b);for(const x of this.controllers)this.invokeCallback_ControllerAdded(b,x)}}}}else{if(this._didStart=!0,this.mode==="immersive-vr"){const _=Ul(this.context.scene.children);if(_){const b=_.getSize(pi());if(b.length()>0){const x=this._defaultRig.gameObject;x.position.set(_.min.x+b.x*.5,_.min.y,_.max.z+b.z*.5+1.5);const E=_.getCenter(pi());E.y=x.position.y,x.lookAt(E)}}}I6({session:this});for(const _ of Vu._xrStartListeners)_(y);const A=[...this._xr_scripts];Sr&&console.log("NeedleXRSession start, handle scripts:",A);for(const _ of A){if(_.destroyed){this._script_to_remove.push(_);continue}if(!_.activeAndEnabled){this.markInactive(_);continue}this.invokeCallback_EnterXR(_);for(const b of this.controllers)this.invokeCallback_ControllerAdded(_,b)}}this.syncCameraCullingMask();for(const A of this.controllers)A.onUpdate(v);if(this._newControllers.length>0){const A=[...this._newControllers];this._newControllers.length=0;for(const _ of A)if(_.connected){this.controllers.push(_);for(const b of this._xr_scripts){if(b.destroyed){this._script_to_remove.push(b);continue}b.activeAndEnabled!==!1&&this.invokeCallback_ControllerAdded(b,_)}}this.controllers.sort((_,b)=>_.index-b.index)}for(const A of this._xr_update_scripts){if(A.destroyed===!0){this._script_to_remove.push(A);continue}if(A.activeAndEnabled===!1){this.markInactive(A);continue}A.onUpdateXR&&A.onUpdateXR(y)}if(this.handleInactiveScripts(),this._script_to_remove.length>0){const A=[...new Set(this._script_to_remove)];this._script_to_remove.length=0;for(const _ of A)!_.destroyed&&this.running&&((f=_.onLeaveXR)==null||f.call(_,y)),this.removeScript(_)}(g=this.sync)==null||g.onUpdate(this),this.onRenderDebug()}),d(this,"onBeforeRender",()=>{this.context.mainCamera&&this.updateFade(this.context.mainCamera)}),d(this,"onAfterRender",()=>{if(this.onUpdateFade_PostRender(),fp()){const a=this.context.renderer;if(a.xr.isPresenting&&this.context.mainCamera){const l=a.xr.enabled,c=a.getRenderTarget();a.xr.enabled=!1,a.setRenderTarget(null),a.render(this.context.scene,this.context.mainCamera),a.xr.enabled=l,a.setRenderTarget(c)}}}),d(this,"_script_to_remove",[]),d(this,"_camera"),d(this,"_cameraRenderParent",new ye().rotateY(Math.PI)),d(this,"_previousCameraParent"),d(this,"_customforward",!0),d(this,"originalCameraNearPlane"),d(this,"_viewerPose"),d(this,"_transformOrientation",new Ce),d(this,"_transformPosition",new C),d(this,"_transition");var s,o;Ade(n,r.init),this.session=e,this.mode=n,this.context=t,(Sr||te("console"))&&Nf(!0),this._xr_scripts=[...r.scripts],this._xr_update_scripts=this._xr_scripts.filter(a=>typeof a.onUpdateXR=="function"),this._controllerAdded=r.controller_added,this._controllerRemoved=r.controller_removed,Nu(this.onBefore,Hi.LateUpdate),this.context.pre_render_callbacks.push(this.onBeforeRender),this.context.post_render_callbacks.push(this.onAfterRender),((s=r.init.optionalFeatures)!=null&&s.includes("hit-test")||(o=r.init.requiredFeatures)!=null&&o.includes("hit-test"))&&e.requestReferenceSpace("viewer").then(a=>{var l,c;return(c=(l=e.requestHitTestSource)==null?void 0:l.call(e,{space:a}))==null?void 0:c.then(h=>this._viewerHitTestSource=h)}).catch(a=>console.warn(a)),this.context.mainCamera&&(this._originalCameraWorldPosition=Bt(this.context.mainCamera,new C),this._originalCameraWorldRotation=Mi(this.context.mainCamera,new Ce),this._originalCameraWorldScale=Vi(this.context.mainCamera,new C),this._originalCameraParent=this.context.mainCamera.parent),this._defaultRig=new Sue,this.context.scene.add(this._defaultRig.gameObject),this.addRig(this._defaultRig);for(let a=0;a<e.inputSources.length;a++){const l=e.inputSources[a];if(!l.handedness){console.warn("Input source in xr session has no handedness - ignoring",a);continue}this.onInputSourceAdded(l)}this.session.addEventListener("end",this.onEnd),this.session.addEventListener("inputsourceschange",a=>{for(const l of a.removed)this.disconnectInputSource(l);for(const l of a.added)this.onInputSourceAdded(l)}),this.context.xr=this,this.context.renderer.xr.setSession(this.session).then(this.onRendererSessionSet)}static getXRSync(n){return this._sync||(this._sync=new aV(n)),this._sync}static get currentSessionRequest(){return this._currentSessionRequestMode}static get active(){return this._activeSession}static get activeMode(){var n;return((n=this._activeSession)==null?void 0:n.mode)??null}static get xrSystem(){return"xr"in navigator?navigator.xr:void 0}static isXRSupported(){return Promise.all([this.isVRSupported(),this.isARSupported()]).then(n=>n.some(e=>e)).catch(()=>!1)}static isVRSupported(){return this.isSessionSupported("immersive-vr")}static isARSupported(){return this.isSessionSupported("immersive-ar")}static isSessionSupported(n){var e;return((e=this.xrSystem)==null?void 0:e.isSessionSupported(n).catch(t=>(Sr&&console.error(t),!1)))??Promise.resolve(!1)}static onSessionRequestStart(n){this._sessionRequestStartListeners.push(n)}static offSessionRequestStart(n){const e=this._sessionRequestStartListeners.indexOf(n);e>=0&&this._sessionRequestStartListeners.splice(e,1)}static onSessionRequestEnd(n){this._sessionRequestEndListeners.push(n)}static offSessionRequestEnd(n){const e=this._sessionRequestEndListeners.indexOf(n);e>=0&&this._sessionRequestEndListeners.splice(e,1)}static onXRSessionStart(n){this._xrStartListeners.push(n)}static offXRSessionStart(n){const e=this._xrStartListeners.indexOf(n);e>=0&&this._xrStartListeners.splice(e,1)}static onXRSessionEnd(n){this._xrEndListeners.push(n)}static offXRSessionEnd(n){const e=this._xrEndListeners.indexOf(n);e>=0&&this._xrEndListeners.splice(e,1)}static onControllerAdded(n){this._controllerAddedListeners.push(n)}static offControllerAdded(n){const e=this._controllerAddedListeners.indexOf(n);e>=0&&this._controllerAddedListeners.splice(e,1)}static onControllerRemoved(n){this._controllerRemovedListeners.push(n)}static offControllerRemoved(n){const e=this._controllerRemovedListeners.indexOf(n);e>=0&&this._controllerRemovedListeners.splice(e,1)}static offerSession(n,e,t){return"xr"in navigator&&navigator.xr&&"offerSession"in navigator.xr?(typeof navigator.xr.offerSession=="function"&&(console.log("WebXR offerSession is available - requesting mode: "+n),e=="default"&&(e=this.getDefaultSessionInit(n)),navigator.xr.offerSession(n,{...e}).then(r=>Vu.setSession(n,r,e,t)).catch(r=>{console.log("XRSession offer rejected (perhaps because another call to offerSession was made or a call to requestSession was made)")})),!0):!1}static getDefaultSessionInit(n){switch(n){case"immersive-ar":return{optionalFeatures:["anchors","local-floor","hand-tracking","layers","dom-overlay","hit-test","unbounded"]};case"immersive-vr":return{optionalFeatures:["local-floor","bounded-floor","hand-tracking","high-fixed-foveation-level","layers"]};default:return console.warn("No default session init for mode",n),{}}}static async start(n,e,t){var r,s,o,a;if(st()&&te("debugxrpreroom"))return console.warn("Debug: Starting temporary XR session"),await Lg.start(n,e||Vu.getDefaultSessionInit(n)),null;if(this._currentSessionRequest)return console.warn("A XRSession is already being requested"),(Sr||st())&&Di("A XRSession is already being requested"),this._currentSessionRequest.then(()=>this._activeSession);if(this._activeSession)return console.error("A XRSession is already running"),this._activeSession;if(t||(t=kt.Current),t||(t=di.All[0]),!t)throw new Error("No Needle Engine Context found");switch(e||(e={}),n){case"immersive-ar":{if(await((r=this.xrSystem)==null?void 0:r.isSessionSupported("immersive-ar"))!==!0)return console.error(n+" is not supported by this browser."),null;const h=this.getDefaultSessionInit(n),u=vde(t.domElement);u&&!ew()&&(h.domOverlay={root:u},h.optionalFeatures.push("dom-overlay")),e={...h,...e}}break;case"immersive-vr":{if(await((s=this.xrSystem)==null?void 0:s.isSessionSupported("immersive-vr"))!==!0)return console.error(n+" is not supported by this browser."),null;e={...this.getDefaultSessionInit(n),...e}}break;default:console.warn("No default session init for mode",n);break}e.optionalFeatures??(e.optionalFeatures=[]),e.requiredFeatures??(e.requiredFeatures=[]),await Lg.stop();const l=n=="immersive-ar"?t.scripts_immersive_ar:t.scripts_immersive_vr;Sr?console.log(`%cRequesting ${n} session`,"font-weight:bold;",e,l):console.log(`%cRequesting ${n} session`,"font-weight:bold;");for(const h of l)h.onBeforeXR&&h.onBeforeXR(n,e);for(const h of this._sessionRequestStartListeners)h({mode:n,init:e});Sr&&rn("Requesting "+n+" session ("+Date.now()+")"),this._currentSessionRequest=(o=navigator.xr)==null?void 0:o.requestSession(n,e),this._currentSessionRequestMode=n;const c=await((a=this._currentSessionRequest)==null?void 0:a.catch(h=>{console.error(h,"Code: "+h.code),h.code===9&&Di("Make sure your device has the required permissions (e.g. camera access)"),console.log("If the specified XR configuration is not supported (e.g. entering AR doesnt work) - make sure you access the website on a secure connection (HTTPS) and your device has the required permissions (e.g. camera access)"),location.protocol==="http:"&&Di("XR requires a secure connection (HTTPS)")}));this._currentSessionRequest=void 0,this._currentSessionRequestMode=null;for(const h of this._sessionRequestEndListeners)h({mode:n,init:e,newSession:c||null});return c?this.setSession(n,c,e,t):(console.warn("XR Session request was rejected"),null)}static setSession(n,e,t,r){if(this._activeSession)return console.error("A XRSession is already running"),this._activeSession;const s=n=="immersive-ar"?r.scripts_immersive_ar:r.scripts_immersive_vr;return this._activeSession=new Vu(n,e,r,{scripts:s,controller_added:this._controllerAddedListeners,controller_removed:this._controllerRemovedListeners,init:t}),e.addEventListener("end",this.onEnd),Sr?console.log(`%cStarted ${n} session`,"font-weight:bold;",s):console.log(`%cStarted ${n} session`,"font-weight:bold;"),this._activeSession}static stop(){var n;(n=this._activeSession)==null||n.end()}get sync(){return Vu._sync}get running(){return!this._ended&&this.session!=null}get interactionMode(){return this.session.interactionMode}get visibilityState(){return this.session.visibilityState}get environmentBlendMode(){return this.session.environmentBlendMode}get frame(){return this.context.xrFrame}get leftController(){return this.controllers.find(n=>n.isLeft)}get rightController(){return this.controllers.find(n=>n.isRight)}getController(n){return typeof n=="number"?this.controllers[n]||null:this.controllers.find(e=>e.side===n)||null}get isPassThrough(){return!!(this.environmentBlendMode!=="opaque"&&this.interactionMode==="world-space"||this.mode==="immersive-ar"&&this.environmentBlendMode!=="opaque"&&this.controllers.some(n=>n.inputSource.targetRayMode==="tracked-pointer")||st()&&fp()&&this.mode==="immersive-ar")}get isAR(){return this.mode==="immersive-ar"}get isVR(){return this.mode==="immersive-vr"}get isScreenBasedAR(){return this.isAR&&!this.isPassThrough}get posePosition(){return this._transformPosition}get poseOrientation(){return this._transformOrientation}get referenceSpace(){return this.context.renderer.xr.getReferenceSpace()}get viewerPose(){return this._viewerPose}get isTrackingImages(){if(this.frame&&"getImageTrackingResults"in this.frame&&typeof this.frame.getImageTrackingResults=="function")try{const n=this.frame.getImageTrackingResults();for(const e of n)if(e.trackingState==="tracked")return!0}catch{return!1}return!1}get rig(){const n=this._rigs[0]??null;return n!=null&&n.gameObject&&Jp(n.gameObject)||n?.isActive===!1?(this.updateActiveXRRig(),this._rigs[0]??null):n}get rigScale(){return this._rigs[0]?(this._lastRigScaleUpdate!==this.context.time.frame&&(this._lastRigScaleUpdate=this.context.time.frame,this._rigScale=this._rigs[0].gameObject.worldScale.x),this._rigScale):1}addRig(n){this._rigs.indexOf(n)>=0||(n.priority===void 0&&(n.priority=0),this._rigs.push(n),this.updateActiveXRRig())}removeRig(n){const e=this._rigs.indexOf(n);e!==-1&&(this._rigs.splice(e,1),this.updateActiveXRRig())}setRigActive(n){const e=this._rigs.indexOf(n);this._rigs.splice(e,1),this._rigs.unshift(n),this.updateActiveXRRig()}updateActiveXRRig(){const n=this._rigs[0]??null;this._defaultRig.gameObject.parent!==this.context.scene&&this.context.scene.add(this._defaultRig.gameObject),this._defaultRig.gameObject.visible=!0,this._rigs.includes(this._defaultRig)||this._rigs.push(this._defaultRig);let e=this._rigs[0];e&&e.priority===void 0&&(e.priority=0);for(let t=1;t<this._rigs.length;t++){const r=this._rigs[t];if(r.isActive){if(Jp(r.gameObject)){this._rigs.splice(t,1),t--;continue}(!e||e.isActive===!1||r.priority!==void 0&&r.priority>e.priority)&&(e=r)}}if(n!==e){const t=this._rigs.indexOf(e);t>=0&&this._rigs.splice(t,1),this._rigs.unshift(e)}Sr&&(n===e?console.log("Updated Active XR Rig:",e,"prev:",n):console.log("Updated Active XRRig:",e," (the same as before)"))}getHitTest(n){if(n)return this.getControllerHitTest(n);if(!this._viewerHitTestSource)return null;const e=this._viewerHitTestSource,t=this.frame.getHitTestResults(e);if(t.length>0){const r=t[0];return this.convertHitTestResult(r)}return null}getControllerHitTest(n){const e=n.hitTestSource;if(!e)return null;const t=this.frame.getHitTestResultsForTransientInput(e);for(const r of t)if(r.inputSource===n.inputSource)for(const s of r.results)return this.convertHitTestResult(s);return null}convertHitTestResult(n){const e=this.context.renderer.xr.getReferenceSpace(),t=e&&n.getPose(e);if(t){const r=pi(t.transform.position),s=bp(t.transform.orientation),o=this.context.mainCamera;if(o?.parent!==this._cameraRenderParent&&r.applyMatrix4(Y1),o!=null&&o.parent){r.applyMatrix4(o.parent.matrixWorld),s.multiply(Sa);const a=Mi(o.parent);a.premultiply(Sa),s.premultiply(a)}return{hit:n,position:r,quaternion:s}}return null}convertSpace(n){const e=pi(n.position);e.applyMatrix4(Y1);const t=bp(n.orientation);return t.premultiply(Sa),{position:e,quaternion:t}}disconnectInputSource(n){const e=(t,r,s)=>{if(t.inputSource===n){Sr&&console.log("Disconnecting controller",t.index),this.controllers.splice(s,1),this.invokeControllerEvent(t,this._controllerRemoved,"removed");const o={xr:this,controller:t,change:"removed"};for(const a of this._xr_scripts)a.onXRControllerRemoved&&a.onXRControllerRemoved(o);t.onDisconnected()}};for(let t=this.controllers.length-1;t>=0;t--){const r=this.controllers[t];e(r,this.controllers,t)}for(let t=this._newControllers.length-1;t>=0;t--){const r=this._newControllers[t];e(r,this._newControllers,t)}}end(){this._ended||this.session.end().catch(n=>console.warn(n))}onRenderDebug(){if(Sr)for(const n of this.controllers)n.onRenderDebug();if((Sr||gde)&&this.rig){const n=this.rig.gameObject.worldPosition,e=this.rig.gameObject.worldForward;n.add(e.multiplyScalar(1.5));const t=this.rig.gameObject.worldUp;n.add(t.multiplyScalar(2.5));let r="";if(r+=this.context.time.smoothedFps.toFixed(1),Sr)for(const s of this.controllers)r+=`
|
|
5236
5236
|
${s.hand?"hand":"ctrl"} ${s.inputSource.handedness}[${s.index}] con:${s.connected} tr:${s.isTracking}`;At.DrawLabel(n,r)}}addScript(n){return this._xr_scripts.includes(n)?!1:(Sr&&console.log("Register new XRScript",n),this._xr_scripts.push(n),typeof n.onUpdateXR=="function"&&this._xr_update_scripts.push(n),!0)}markInactive(n){if(!(this._inactive_scripts.indexOf(n)>=0)){this.removeScript(n,!1),this._inactive_scripts.push(n);for(const e of this.controllers)this.invokeCallback_ControllerRemoved(n,e);this.invokeCallback_LeaveXR(n)}}handleInactiveScripts(){if(this._inactive_scripts.length>0)for(let n=this._inactive_scripts.length-1;n>=0;n--){const e=this._inactive_scripts[n];if(e.activeAndEnabled){this._inactive_scripts.splice(n,1),this.addScript(e),this.invokeCallback_EnterXR(e);for(const t of this.controllers)this.invokeCallback_ControllerAdded(e,t)}}}removeScript(n,e=!0){Sr&&console.log("Remove XRScript",n);const t=this._xr_scripts.indexOf(n);t>=0&&this._xr_scripts.splice(t,1);const r=this._xr_update_scripts.indexOf(n);if(r>=0&&this._xr_update_scripts.splice(r,1),e){const s=this._inactive_scripts.indexOf(n);s>=0&&this._inactive_scripts.splice(s,1)}}invokeCallback_EnterXR(n){n.onEnterXR&&n.onEnterXR({xr:this})}invokeCallback_ControllerAdded(n,e){n.onXRControllerAdded&&n.onXRControllerAdded({xr:this,controller:e,change:"added"})}invokeCallback_ControllerRemoved(n,e){n.onXRControllerRemoved&&n.onXRControllerRemoved({xr:this,controller:e,change:"removed"})}invokeCallback_LeaveXR(n){n.onLeaveXR&&!n.destroyed&&n.onLeaveXR({xr:this})}syncCameraCullingMask(){var n;const e=this.context.xrCamera,t=(n=this.context.mainCameraComponent)==null?void 0:n.cullingMask;if(e&&t!==void 0){for(const r of e.cameras)r.layers.mask=t;e.layers.mask=t}else if(e){for(const r of e.cameras)r.layers.enableAll();e.layers.enableAll()}}invokeControllerEvent(n,e,t){for(let r=e.length-1;r>=0;r--){const s=e[r];if(s)try{s({xr:this,controller:n,change:t})}catch(o){console.error(o)}}}applyCustomForward(){var n;if(this.context.mainCamera&&this._customforward){this._camera=this.context.mainCamera,this._camera.parent!==this._cameraRenderParent&&(this._previousCameraParent=this._camera.parent,(n=this._previousCameraParent)==null||n.add(this._cameraRenderParent)),this._cameraRenderParent.name="XR Camera Render Parent",this._cameraRenderParent.add(this._camera);let e=.02;if(this.rig){const t=Vi(this.rig.gameObject);e*=t.x}this._camera instanceof Lt&&this._camera.near>e&&(this.originalCameraNearPlane=this._camera.near,this._camera.near=e)}}revertCustomForward(){this._camera&&this._previousCameraParent&&this._previousCameraParent.add(this._camera),this._previousCameraParent=null,this._camera instanceof Lt&&this.originalCameraNearPlane!=null&&(this._camera.near=this.originalCameraNearPlane)}internalUpdateState(){const n=this.context.renderer.xr.getReferenceSpace();if(!n){this._viewerPose=void 0;return}if(this._viewerPose=this.frame.getViewerPose(n),this._viewerPose){const e=this._viewerPose.transform;this._transformPosition.set(e.position.x,e.position.y,e.position.z),this._transformOrientation.set(e.orientation.x,e.orientation.y,e.orientation.z,e.orientation.w)}}get transition(){return this._transition||(this._transition=new lV),this._transition}fadeTransition(){return this._transition||(this._transition=new lV),this._transition.fadeTransition()}updateFade(n){this._transition&&n instanceof Lt&&this._transition.update(n,this.context.time.deltaTime)}onUpdateFade_PostRender(){var n;(n=this._transition)==null||n.remove()}};let wt=Vu;d(wt,"_sync",null),d(wt,"_currentSessionRequestMode",null),d(wt,"_currentSessionRequest"),d(wt,"_activeSession"),d(wt,"_sessionRequestStartListeners",[]),d(wt,"_sessionRequestEndListeners",[]),d(wt,"_xrStartListeners",[]),d(wt,"_xrEndListeners",[]),d(wt,"_controllerAddedListeners",[]),d(wt,"_controllerRemovedListeners",[]),d(wt,"onEnd",()=>{Sr&&console.log("XR Session ended"),Vu._activeSession=null});const QB=te("debugwebxr");class uV{static tryFindAvatarObjects(e,t,r){if(r.head&&r.leftHand&&r.rightHand)return;const s=e.name.toLocaleLowerCase();!r.head&&s.includes("head")&&(QB&&console.log("FOUND AVATAR HEAD",e.name),r.head=new ti("",t,e)),s.includes("hand")&&(!r.leftHand&&s.includes("left")&&(QB&&console.log("FOUND AVATAR LEFT HAND",e.name),r.leftHand=new ti("",t,e)),!r.rightHand&&s.includes("right")&&(QB&&console.log("FOUND AVATAR RIGHT HAND",e.name),r.rightHand=new ti("",t,e)));for(let o=0;o<e.children.length;o++){if(r.head&&r.leftHand&&r.rightHand)return;const a=e.children[o];this.tryFindAvatarObjects(a,t,r)}}}var cS=(n=>(n.Visible="application-visible",n.Hidden="application-hidden",n.MuteChanged="application-mutechanged",n))(cS||{});let hS=!1;const Fg=[];function Ug(){if(hS)return;st()&&console.debug("User interaction registered: audio can now be played"),hS=!0;const n=[...Fg];Fg.length=0,n.forEach(e=>e())}document.addEventListener("pointerdown",Ug),document.addEventListener("click",Ug),document.addEventListener("dragstart",Ug),document.addEventListener("touchstart",Ug),document.addEventListener("keydown",Ug),wt.onXRSessionStart(()=>{Ug()});const dV=class extends EventTarget{constructor(n){super(),d(this,"_mute",!1),d(this,"context"),d(this,"_isVisible",!0),this.context=n,window.addEventListener("visibilitychange",this.onVisiblityChanged.bind(this),!1)}static get userInteractionRegistered(){return hS}static registerWaitForInteraction(n){if(n!==null){if(hS){n();return}Fg.indexOf(n)===-1&&Fg.push(n)}}static unregisterWaitForInteraction(n){const e=Fg.indexOf(n);e!==-1&&Fg.splice(e,1)}get muted(){return this._mute}set muted(n){n!==this._mute&&(this._mute=n,this.dispatchEvent(new Event("application-mutechanged")))}get hasFocus(){return document.hasFocus()}get isVisible(){return this._isVisible}onVisiblityChanged(n){switch(n.target.visibilityState){case"hidden":this._isVisible=!1,this.dispatchEvent(new Event("application-hidden"));break;case"visible":this._isVisible=!0,this.dispatchEvent(new Event("application-visible"));break}}};let Qu=dV;d(Qu,"registerWaitForAllowAudio",dV.registerWaitForInteraction);function*pV(n,e=null){const t=e?e.time:kt.Current.time,r=t.time;for(;t.time-r<n;)yield}function*xde(n){for(let e=0;e<n;e++)yield}function*mV(n){let e=!0;for(n.then(()=>e=!1),n.catch(()=>e=!1);e;)yield}class oA extends hI{constructor(e){super(e),this.type=rr}parse(e){const t=Math.pow(2.7182818,2.2);function r(S,B){let j=0;for(let N=0;N<65536;++N)(N==0||S[N>>3]&1<<(N&7))&&(B[j++]=N);const ee=j-1;for(;j<65536;)B[j++]=0;return ee}function s(S){for(let B=0;B<16384;B++)S[B]={},S[B].len=0,S[B].lit=0,S[B].p=null}const o={l:0,c:0,lc:0};function a(S,B,j,ee,N){for(;j<S;)B=B<<8|X(ee,N),j+=8;j-=S,o.l=B>>j&(1<<S)-1,o.c=B,o.lc=j}const l=new Array(59);function c(S){for(let j=0;j<=58;++j)l[j]=0;for(let j=0;j<65537;++j)l[S[j]]+=1;let B=0;for(let j=58;j>0;--j){const ee=B+l[j]>>1;l[j]=B,B=ee}for(let j=0;j<65537;++j){const ee=S[j];ee>0&&(S[j]=ee|l[ee]++<<6)}}function h(S,B,j,ee,N,Y){const W=B;let ae=0,ce=0;for(;ee<=N;ee++){if(W.value-B.value>j)return!1;a(6,ae,ce,S,W);const _e=o.l;if(ae=o.c,ce=o.lc,Y[ee]=_e,_e==63){if(W.value-B.value>j)throw new Error("Something wrong with hufUnpackEncTable");a(8,ae,ce,S,W);let Re=o.l+6;if(ae=o.c,ce=o.lc,ee+Re>N+1)throw new Error("Something wrong with hufUnpackEncTable");for(;Re--;)Y[ee++]=0;ee--}else if(_e>=59){let Re=_e-59+2;if(ee+Re>N+1)throw new Error("Something wrong with hufUnpackEncTable");for(;Re--;)Y[ee++]=0;ee--}}c(Y)}function u(S){return S&63}function p(S){return S>>6}function m(S,B,j,ee){for(;B<=j;B++){const N=p(S[B]),Y=u(S[B]);if(N>>Y)throw new Error("Invalid table entry");if(Y>14){const W=ee[N>>Y-14];if(W.len)throw new Error("Invalid table entry");if(W.lit++,W.p){const ae=W.p;W.p=new Array(W.lit);for(let ce=0;ce<W.lit-1;++ce)W.p[ce]=ae[ce]}else W.p=new Array(1);W.p[W.lit-1]=B}else if(Y){let W=0;for(let ae=1<<14-Y;ae>0;ae--){const ce=ee[(N<<14-Y)+W];if(ce.len||ce.p)throw new Error("Invalid table entry");ce.len=Y,ce.lit=B,W++}}}return!0}const f={c:0,lc:0};function g(S,B,j,ee){S=S<<8|X(j,ee),B+=8,f.c=S,f.lc=B}const v={c:0,lc:0};function y(S,B,j,ee,N,Y,W,ae,ce){if(S==B){ee<8&&(g(j,ee,N,Y),j=f.c,ee=f.lc),ee-=8;let _e=j>>ee;if(_e=new Uint8Array([_e])[0],ae.value+_e>ce)return!1;const Re=W[ae.value-1];for(;_e-- >0;)W[ae.value++]=Re}else if(ae.value<ce)W[ae.value++]=S;else return!1;v.c=j,v.lc=ee}function A(S){return S&65535}function _(S){const B=A(S);return B>32767?B-65536:B}const b={a:0,b:0};function x(S,B){const j=_(S),ee=_(B),N=j+(ee&1)+(ee>>1),Y=N,W=N-ee;b.a=Y,b.b=W}function E(S,B){const j=A(S),ee=A(B),N=j-(ee>>1)&65535,Y=ee+N-32768&65535;b.a=Y,b.b=N}function I(S,B,j,ee,N,Y,W){const ae=W<16384,ce=j>N?N:j;let _e=1,Re,Xe;for(;_e<=ce;)_e<<=1;for(_e>>=1,Re=_e,_e>>=1;_e>=1;){Xe=0;const We=Xe+Y*(N-Re),Ke=Y*_e,gt=Y*Re,rt=ee*_e,xt=ee*Re;let Jt,Ui,en,pr;for(;Xe<=We;Xe+=gt){let ki=Xe;const ai=Xe+ee*(j-Re);for(;ki<=ai;ki+=xt){const Pn=ki+rt,ro=ki+Ke,Vn=ro+rt;ae?(x(S[ki+B],S[ro+B]),Jt=b.a,en=b.b,x(S[Pn+B],S[Vn+B]),Ui=b.a,pr=b.b,x(Jt,Ui),S[ki+B]=b.a,S[Pn+B]=b.b,x(en,pr),S[ro+B]=b.a,S[Vn+B]=b.b):(E(S[ki+B],S[ro+B]),Jt=b.a,en=b.b,E(S[Pn+B],S[Vn+B]),Ui=b.a,pr=b.b,E(Jt,Ui),S[ki+B]=b.a,S[Pn+B]=b.b,E(en,pr),S[ro+B]=b.a,S[Vn+B]=b.b)}if(j&_e){const Pn=ki+Ke;ae?x(S[ki+B],S[Pn+B]):E(S[ki+B],S[Pn+B]),Jt=b.a,S[Pn+B]=b.b,S[ki+B]=Jt}}if(N&_e){let ki=Xe;const ai=Xe+ee*(j-Re);for(;ki<=ai;ki+=xt){const Pn=ki+rt;ae?x(S[ki+B],S[Pn+B]):E(S[ki+B],S[Pn+B]),Jt=b.a,S[Pn+B]=b.b,S[ki+B]=Jt}}Re=_e,_e>>=1}return Xe}function T(S,B,j,ee,N,Y,W,ae,ce){let _e=0,Re=0;const Xe=W,We=Math.trunc(ee.value+(N+7)/8);for(;ee.value<We;)for(g(_e,Re,j,ee),_e=f.c,Re=f.lc;Re>=14;){const gt=_e>>Re-14&16383,rt=B[gt];if(rt.len)Re-=rt.len,y(rt.lit,Y,_e,Re,j,ee,ae,ce,Xe),_e=v.c,Re=v.lc;else{if(!rt.p)throw new Error("hufDecode issues");let xt;for(xt=0;xt<rt.lit;xt++){const Jt=u(S[rt.p[xt]]);for(;Re<Jt&&ee.value<We;)g(_e,Re,j,ee),_e=f.c,Re=f.lc;if(Re>=Jt&&p(S[rt.p[xt]])==(_e>>Re-Jt&(1<<Jt)-1)){Re-=Jt,y(rt.p[xt],Y,_e,Re,j,ee,ae,ce,Xe),_e=v.c,Re=v.lc;break}}if(xt==rt.lit)throw new Error("hufDecode issues")}}const Ke=8-N&7;for(_e>>=Ke,Re-=Ke;Re>0;){const gt=B[_e<<14-Re&16383];if(gt.len)Re-=gt.len,y(gt.lit,Y,_e,Re,j,ee,ae,ce,Xe),_e=v.c,Re=v.lc;else throw new Error("hufDecode issues")}return!0}function R(S,B,j,ee,N,Y){const W={value:0},ae=j.value,ce=fe(B,j),_e=fe(B,j);j.value+=4;const Re=fe(B,j);if(j.value+=4,ce<0||ce>=65537||_e<0||_e>=65537)throw new Error("Something wrong with HUF_ENCSIZE");const Xe=new Array(65537),We=new Array(16384);s(We);const Ke=ee-(j.value-ae);if(h(S,j,Ke,ce,_e,Xe),Re>8*(ee-(j.value-ae)))throw new Error("Something wrong with hufUncompress");m(Xe,ce,_e,We),T(Xe,We,S,j,Re,_e,Y,N,W)}function D(S,B,j){for(let ee=0;ee<j;++ee)B[ee]=S[B[ee]]}function M(S){for(let B=1;B<S.length;B++){const j=S[B-1]+S[B]-128;S[B]=j}}function P(S,B){let j=0,ee=Math.floor((S.length+1)/2),N=0;const Y=S.length-1;for(;!(N>Y||(B[N++]=S[j++],N>Y));)B[N++]=S[ee++]}function z(S){let B=S.byteLength;const j=new Array;let ee=0;const N=new DataView(S);for(;B>0;){const Y=N.getInt8(ee++);if(Y<0){const W=-Y;B-=W+1;for(let ae=0;ae<W;ae++)j.push(N.getUint8(ee++))}else{const W=Y;B-=2;const ae=N.getUint8(ee++);for(let ce=0;ce<W+1;ce++)j.push(ae)}}return j}function V(S,B,j,ee,N,Y){let W=new DataView(Y.buffer);const ae=j[S.idx[0]].width,ce=j[S.idx[0]].height,_e=3,Re=Math.floor(ae/8),Xe=Math.ceil(ae/8),We=Math.ceil(ce/8),Ke=ae-(Xe-1)*8,gt=ce-(We-1)*8,rt={value:0},xt=new Array(_e),Jt=new Array(_e),Ui=new Array(_e),en=new Array(_e),pr=new Array(_e);for(let ai=0;ai<_e;++ai)pr[ai]=B[S.idx[ai]],xt[ai]=ai<1?0:xt[ai-1]+Xe*We,Jt[ai]=new Float32Array(64),Ui[ai]=new Uint16Array(64),en[ai]=new Uint16Array(Xe*64);for(let ai=0;ai<We;++ai){let Pn=8;ai==We-1&&(Pn=gt);let ro=8;for(let U=0;U<Xe;++U){U==Xe-1&&(ro=Ke);for(let ne=0;ne<_e;++ne)Ui[ne].fill(0),Ui[ne][0]=N[xt[ne]++],L(rt,ee,Ui[ne]),H(Ui[ne],Jt[ne]),O(Jt[ne]);F(Jt);for(let ne=0;ne<_e;++ne)G(Jt[ne],en[ne],U*64)}let Vn=0;for(let U=0;U<_e;++U){const ne=j[S.idx[U]].type;for(let pe=8*ai;pe<8*ai+Pn;++pe){Vn=pr[U][pe];for(let ge=0;ge<Re;++ge){const le=ge*64+(pe&7)*8;W.setUint16(Vn+0*2*ne,en[U][le+0],!0),W.setUint16(Vn+1*2*ne,en[U][le+1],!0),W.setUint16(Vn+2*2*ne,en[U][le+2],!0),W.setUint16(Vn+3*2*ne,en[U][le+3],!0),W.setUint16(Vn+4*2*ne,en[U][le+4],!0),W.setUint16(Vn+5*2*ne,en[U][le+5],!0),W.setUint16(Vn+6*2*ne,en[U][le+6],!0),W.setUint16(Vn+7*2*ne,en[U][le+7],!0),Vn+=8*2*ne}}if(Re!=Xe)for(let pe=8*ai;pe<8*ai+Pn;++pe){const ge=pr[U][pe]+8*Re*2*ne,le=Re*64+(pe&7)*8;for(let Ze=0;Ze<ro;++Ze)W.setUint16(ge+Ze*2*ne,en[U][le+Ze],!0)}}}const ki=new Uint16Array(ae);W=new DataView(Y.buffer);for(let ai=0;ai<_e;++ai){j[S.idx[ai]].decoded=!0;const Pn=j[S.idx[ai]].type;if(j[ai].type==2)for(let ro=0;ro<ce;++ro){const Vn=pr[ai][ro];for(let U=0;U<ae;++U)ki[U]=W.getUint16(Vn+U*2*Pn,!0);for(let U=0;U<ae;++U)W.setFloat32(Vn+U*2*Pn,Ae(ki[U]),!0)}}}function L(S,B,j){let ee,N=1;for(;N<64;)ee=B[S.value],ee==65280?N=64:ee>>8==255?N+=ee&255:(j[N]=ee,N++),S.value++}function H(S,B){B[0]=Ae(S[0]),B[1]=Ae(S[1]),B[2]=Ae(S[5]),B[3]=Ae(S[6]),B[4]=Ae(S[14]),B[5]=Ae(S[15]),B[6]=Ae(S[27]),B[7]=Ae(S[28]),B[8]=Ae(S[2]),B[9]=Ae(S[4]),B[10]=Ae(S[7]),B[11]=Ae(S[13]),B[12]=Ae(S[16]),B[13]=Ae(S[26]),B[14]=Ae(S[29]),B[15]=Ae(S[42]),B[16]=Ae(S[3]),B[17]=Ae(S[8]),B[18]=Ae(S[12]),B[19]=Ae(S[17]),B[20]=Ae(S[25]),B[21]=Ae(S[30]),B[22]=Ae(S[41]),B[23]=Ae(S[43]),B[24]=Ae(S[9]),B[25]=Ae(S[11]),B[26]=Ae(S[18]),B[27]=Ae(S[24]),B[28]=Ae(S[31]),B[29]=Ae(S[40]),B[30]=Ae(S[44]),B[31]=Ae(S[53]),B[32]=Ae(S[10]),B[33]=Ae(S[19]),B[34]=Ae(S[23]),B[35]=Ae(S[32]),B[36]=Ae(S[39]),B[37]=Ae(S[45]),B[38]=Ae(S[52]),B[39]=Ae(S[54]),B[40]=Ae(S[20]),B[41]=Ae(S[22]),B[42]=Ae(S[33]),B[43]=Ae(S[38]),B[44]=Ae(S[46]),B[45]=Ae(S[51]),B[46]=Ae(S[55]),B[47]=Ae(S[60]),B[48]=Ae(S[21]),B[49]=Ae(S[34]),B[50]=Ae(S[37]),B[51]=Ae(S[47]),B[52]=Ae(S[50]),B[53]=Ae(S[56]),B[54]=Ae(S[59]),B[55]=Ae(S[61]),B[56]=Ae(S[35]),B[57]=Ae(S[36]),B[58]=Ae(S[48]),B[59]=Ae(S[49]),B[60]=Ae(S[57]),B[61]=Ae(S[58]),B[62]=Ae(S[62]),B[63]=Ae(S[63])}function O(S){const B=.5*Math.cos(.7853975),j=.5*Math.cos(3.14159/16),ee=.5*Math.cos(3.14159/8),N=.5*Math.cos(3*3.14159/16),Y=.5*Math.cos(5*3.14159/16),W=.5*Math.cos(3*3.14159/8),ae=.5*Math.cos(7*3.14159/16),ce=new Array(4),_e=new Array(4),Re=new Array(4),Xe=new Array(4);for(let We=0;We<8;++We){const Ke=We*8;ce[0]=ee*S[Ke+2],ce[1]=W*S[Ke+2],ce[2]=ee*S[Ke+6],ce[3]=W*S[Ke+6],_e[0]=j*S[Ke+1]+N*S[Ke+3]+Y*S[Ke+5]+ae*S[Ke+7],_e[1]=N*S[Ke+1]-ae*S[Ke+3]-j*S[Ke+5]-Y*S[Ke+7],_e[2]=Y*S[Ke+1]-j*S[Ke+3]+ae*S[Ke+5]+N*S[Ke+7],_e[3]=ae*S[Ke+1]-Y*S[Ke+3]+N*S[Ke+5]-j*S[Ke+7],Re[0]=B*(S[Ke+0]+S[Ke+4]),Re[3]=B*(S[Ke+0]-S[Ke+4]),Re[1]=ce[0]+ce[3],Re[2]=ce[1]-ce[2],Xe[0]=Re[0]+Re[1],Xe[1]=Re[3]+Re[2],Xe[2]=Re[3]-Re[2],Xe[3]=Re[0]-Re[1],S[Ke+0]=Xe[0]+_e[0],S[Ke+1]=Xe[1]+_e[1],S[Ke+2]=Xe[2]+_e[2],S[Ke+3]=Xe[3]+_e[3],S[Ke+4]=Xe[3]-_e[3],S[Ke+5]=Xe[2]-_e[2],S[Ke+6]=Xe[1]-_e[1],S[Ke+7]=Xe[0]-_e[0]}for(let We=0;We<8;++We)ce[0]=ee*S[16+We],ce[1]=W*S[16+We],ce[2]=ee*S[48+We],ce[3]=W*S[48+We],_e[0]=j*S[8+We]+N*S[24+We]+Y*S[40+We]+ae*S[56+We],_e[1]=N*S[8+We]-ae*S[24+We]-j*S[40+We]-Y*S[56+We],_e[2]=Y*S[8+We]-j*S[24+We]+ae*S[40+We]+N*S[56+We],_e[3]=ae*S[8+We]-Y*S[24+We]+N*S[40+We]-j*S[56+We],Re[0]=B*(S[We]+S[32+We]),Re[3]=B*(S[We]-S[32+We]),Re[1]=ce[0]+ce[3],Re[2]=ce[1]-ce[2],Xe[0]=Re[0]+Re[1],Xe[1]=Re[3]+Re[2],Xe[2]=Re[3]-Re[2],Xe[3]=Re[0]-Re[1],S[0+We]=Xe[0]+_e[0],S[8+We]=Xe[1]+_e[1],S[16+We]=Xe[2]+_e[2],S[24+We]=Xe[3]+_e[3],S[32+We]=Xe[3]-_e[3],S[40+We]=Xe[2]-_e[2],S[48+We]=Xe[1]-_e[1],S[56+We]=Xe[0]-_e[0]}function F(S){for(let B=0;B<64;++B){const j=S[0][B],ee=S[1][B],N=S[2][B];S[0][B]=j+1.5747*N,S[1][B]=j-.1873*ee-.4682*N,S[2][B]=j+1.8556*ee}}function G(S,B,j){for(let ee=0;ee<64;++ee)B[j+ee]=Wd.toHalfFloat(J(S[ee]))}function J(S){return S<=1?Math.sign(S)*Math.pow(Math.abs(S),2.2):Math.sign(S)*Math.pow(t,Math.abs(S)-1)}function K(S){return new DataView(S.array.buffer,S.offset.value,S.size)}function oe(S){const B=S.viewer.buffer.slice(S.offset.value,S.offset.value+S.size),j=new Uint8Array(z(B)),ee=new Uint8Array(j.length);return M(j),P(j,ee),new DataView(ee.buffer)}function we(S){const B=S.array.slice(S.offset.value,S.offset.value+S.size),j=Iy(B),ee=new Uint8Array(j.length);return M(j),P(j,ee),new DataView(ee.buffer)}function De(S){const B=S.viewer,j={value:S.offset.value},ee=new Uint16Array(S.width*S.scanlineBlockSize*(S.channels*S.type)),N=new Uint8Array(8192);let Y=0;const W=new Array(S.channels);for(let gt=0;gt<S.channels;gt++)W[gt]={},W[gt].start=Y,W[gt].end=W[gt].start,W[gt].nx=S.width,W[gt].ny=S.lines,W[gt].size=S.type,Y+=W[gt].nx*W[gt].ny*W[gt].size;const ae=et(B,j),ce=et(B,j);if(ce>=8192)throw new Error("Something is wrong with PIZ_COMPRESSION BITMAP_SIZE");if(ae<=ce)for(let gt=0;gt<ce-ae+1;gt++)N[gt+ae]=ze(B,j);const _e=new Uint16Array(65536),Re=r(N,_e),Xe=fe(B,j);R(S.array,B,j,Xe,ee,Y);for(let gt=0;gt<S.channels;++gt){const rt=W[gt];for(let xt=0;xt<W[gt].size;++xt)I(ee,rt.start+xt,rt.nx,rt.size,rt.ny,rt.nx*rt.size,Re)}D(_e,ee,Y);let We=0;const Ke=new Uint8Array(ee.buffer.byteLength);for(let gt=0;gt<S.lines;gt++)for(let rt=0;rt<S.channels;rt++){const xt=W[rt],Jt=xt.nx*xt.size,Ui=new Uint8Array(ee.buffer,xt.end*2,Jt*2);Ke.set(Ui,We),We+=Jt*2,xt.end+=Jt}return new DataView(Ke.buffer)}function se(S){const B=S.array.slice(S.offset.value,S.offset.value+S.size),j=Iy(B),ee=S.lines*S.channels*S.width,N=S.type==1?new Uint16Array(ee):new Uint32Array(ee);let Y=0,W=0;const ae=new Array(4);for(let ce=0;ce<S.lines;ce++)for(let _e=0;_e<S.channels;_e++){let Re=0;switch(S.type){case 1:ae[0]=Y,ae[1]=ae[0]+S.width,Y=ae[1]+S.width;for(let Xe=0;Xe<S.width;++Xe){const We=j[ae[0]++]<<8|j[ae[1]++];Re+=We,N[W]=Re,W++}break;case 2:ae[0]=Y,ae[1]=ae[0]+S.width,ae[2]=ae[1]+S.width,Y=ae[2]+S.width;for(let Xe=0;Xe<S.width;++Xe){const We=j[ae[0]++]<<24|j[ae[1]++]<<16|j[ae[2]++]<<8;Re+=We,N[W]=Re,W++}break}}return new DataView(N.buffer)}function be(S){const B=S.viewer,j={value:S.offset.value},ee=new Uint8Array(S.width*S.lines*(S.channels*S.type*2)),N={version:Te(B,j),unknownUncompressedSize:Te(B,j),unknownCompressedSize:Te(B,j),acCompressedSize:Te(B,j),dcCompressedSize:Te(B,j),rleCompressedSize:Te(B,j),rleUncompressedSize:Te(B,j),rleRawSize:Te(B,j),totalAcUncompressedCount:Te(B,j),totalDcUncompressedCount:Te(B,j),acCompression:Te(B,j)};if(N.version<2)throw new Error("EXRLoader.parse: "+qt.compression+" version "+N.version+" is unsupported");const Y=new Array;let W=et(B,j)-2;for(;W>0;){const rt=Ie(B.buffer,j),xt=ze(B,j),Jt=xt>>2&3,Ui=(xt>>4)-1,en=new Int8Array([Ui])[0],pr=ze(B,j);Y.push({name:rt,index:en,type:pr,compression:Jt}),W-=rt.length+3}const ae=qt.channels,ce=new Array(S.channels);for(let rt=0;rt<S.channels;++rt){const xt=ce[rt]={},Jt=ae[rt];xt.name=Jt.name,xt.compression=0,xt.decoded=!1,xt.type=Jt.pixelType,xt.pLinear=Jt.pLinear,xt.width=S.width,xt.height=S.lines}const _e={idx:new Array(3)};for(let rt=0;rt<S.channels;++rt){const xt=ce[rt];for(let Jt=0;Jt<Y.length;++Jt){const Ui=Y[Jt];xt.name==Ui.name&&(xt.compression=Ui.compression,Ui.index>=0&&(_e.idx[Ui.index]=rt),xt.offset=rt)}}let Re,Xe,We;if(N.acCompressedSize>0)switch(N.acCompression){case 0:Re=new Uint16Array(N.totalAcUncompressedCount),R(S.array,B,j,N.acCompressedSize,Re,N.totalAcUncompressedCount);break;case 1:const rt=S.array.slice(j.value,j.value+N.totalAcUncompressedCount),xt=Iy(rt);Re=new Uint16Array(xt.buffer),j.value+=N.totalAcUncompressedCount;break}if(N.dcCompressedSize>0){const rt={array:S.array,offset:j,size:N.dcCompressedSize};Xe=new Uint16Array(we(rt).buffer),j.value+=N.dcCompressedSize}if(N.rleRawSize>0){const rt=S.array.slice(j.value,j.value+N.rleCompressedSize),xt=Iy(rt);We=z(xt.buffer),j.value+=N.rleCompressedSize}let Ke=0;const gt=new Array(ce.length);for(let rt=0;rt<gt.length;++rt)gt[rt]=new Array;for(let rt=0;rt<S.lines;++rt)for(let xt=0;xt<ce.length;++xt)gt[xt].push(Ke),Ke+=ce[xt].width*S.type*2;V(_e,gt,ce,Re,Xe,ee);for(let rt=0;rt<ce.length;++rt){const xt=ce[rt];if(!xt.decoded)switch(xt.compression){case 2:let Jt=0,Ui=0;for(let en=0;en<S.lines;++en){let pr=gt[rt][Jt];for(let ki=0;ki<xt.width;++ki){for(let ai=0;ai<2*xt.type;++ai)ee[pr++]=We[Ui+ai*xt.width*xt.height];Ui++}Jt++}break;case 1:default:throw new Error("EXRLoader.parse: unsupported channel compression")}}return new DataView(ee.buffer)}function Ie(S,B){const j=new Uint8Array(S);let ee=0;for(;j[B.value+ee]!=0;)ee+=1;const N=new TextDecoder().decode(j.slice(B.value,B.value+ee));return B.value=B.value+ee+1,N}function Je(S,B,j){const ee=new TextDecoder().decode(new Uint8Array(S).slice(B.value,B.value+j));return B.value=B.value+j,ee}function $e(S,B){const j=lt(S,B),ee=fe(S,B);return[j,ee]}function Oe(S,B){const j=fe(S,B),ee=fe(S,B);return[j,ee]}function lt(S,B){const j=S.getInt32(B.value,!0);return B.value=B.value+4,j}function fe(S,B){const j=S.getUint32(B.value,!0);return B.value=B.value+4,j}function X(S,B){const j=S[B.value];return B.value=B.value+1,j}function ze(S,B){const j=S.getUint8(B.value);return B.value=B.value+1,j}const Te=function(S,B){let j;return"getBigInt64"in DataView.prototype?j=Number(S.getBigInt64(B.value,!0)):j=S.getUint32(B.value+4,!0)+Number(S.getUint32(B.value,!0)<<32),B.value+=8,j};function Me(S,B){const j=S.getFloat32(B.value,!0);return B.value+=4,j}function Qe(S,B){return Wd.toHalfFloat(Me(S,B))}function Ae(S){const B=(S&31744)>>10,j=S&1023;return(S>>15?-1:1)*(B?B===31?j?NaN:1/0:Math.pow(2,B-15)*(1+j/1024):6103515625e-14*(j/1024))}function et(S,B){const j=S.getUint16(B.value,!0);return B.value+=2,j}function ct(S,B){return Ae(et(S,B))}function Tt(S,B,j,ee){const N=j.value,Y=[];for(;j.value<N+ee-1;){const W=Ie(B,j),ae=lt(S,j),ce=ze(S,j);j.value+=3;const _e=lt(S,j),Re=lt(S,j);Y.push({name:W,pixelType:ae,pLinear:ce,xSampling:_e,ySampling:Re})}return j.value+=1,Y}function Q(S,B){const j=Me(S,B),ee=Me(S,B),N=Me(S,B),Y=Me(S,B),W=Me(S,B),ae=Me(S,B),ce=Me(S,B),_e=Me(S,B);return{redX:j,redY:ee,greenX:N,greenY:Y,blueX:W,blueY:ae,whiteX:ce,whiteY:_e}}function k(S,B){const j=["NO_COMPRESSION","RLE_COMPRESSION","ZIPS_COMPRESSION","ZIP_COMPRESSION","PIZ_COMPRESSION","PXR24_COMPRESSION","B44_COMPRESSION","B44A_COMPRESSION","DWAA_COMPRESSION","DWAB_COMPRESSION"],ee=ze(S,B);return j[ee]}function he(S,B){const j=fe(S,B),ee=fe(S,B),N=fe(S,B),Y=fe(S,B);return{xMin:j,yMin:ee,xMax:N,yMax:Y}}function Ee(S,B){const j=["INCREASING_Y"],ee=ze(S,B);return j[ee]}function Le(S,B){const j=Me(S,B),ee=Me(S,B);return[j,ee]}function Pe(S,B){const j=Me(S,B),ee=Me(S,B),N=Me(S,B);return[j,ee,N]}function vt(S,B,j,ee,N){if(ee==="string"||ee==="stringvector"||ee==="iccProfile")return Je(B,j,N);if(ee==="chlist")return Tt(S,B,j,N);if(ee==="chromaticities")return Q(S,j);if(ee==="compression")return k(S,j);if(ee==="box2i")return he(S,j);if(ee==="lineOrder")return Ee(S,j);if(ee==="float")return Me(S,j);if(ee==="v2f")return Le(S,j);if(ee==="v3f")return Pe(S,j);if(ee==="int")return lt(S,j);if(ee==="rational")return $e(S,j);if(ee==="timecode")return Oe(S,j);if(ee==="preview")return j.value+=N,"skipped";j.value+=N}function ht(S,B,j){const ee={};if(S.getUint32(0,!0)!=20000630)throw new Error("THREE.EXRLoader: Provided file doesn't appear to be in OpenEXR format.");ee.version=S.getUint8(4);const N=S.getUint8(5);ee.spec={singleTile:!!(N&2),longName:!!(N&4),deepFormat:!!(N&8),multiPart:!!(N&16)},j.value=8;let Y=!0;for(;Y;){const W=Ie(B,j);if(W==0)Y=!1;else{const ae=Ie(B,j),ce=fe(S,j),_e=vt(S,B,j,ae,ce);_e===void 0?console.warn(`THREE.EXRLoader: Skipped unknown header attribute type '${ae}'.`):ee[W]=_e}}if(N&-5)throw console.error("THREE.EXRHeader:",ee),new Error("THREE.EXRLoader: Provided file is currently unsupported.");return ee}function je(S,B,j,ee,N){const Y={size:0,viewer:B,array:j,offset:ee,width:S.dataWindow.xMax-S.dataWindow.xMin+1,height:S.dataWindow.yMax-S.dataWindow.yMin+1,channels:S.channels.length,bytesPerLine:null,lines:null,inputSize:null,type:S.channels[0].pixelType,uncompress:null,getter:null,format:null,colorSpace:Ri};switch(S.compression){case"NO_COMPRESSION":Y.lines=1,Y.uncompress=K;break;case"RLE_COMPRESSION":Y.lines=1,Y.uncompress=oe;break;case"ZIPS_COMPRESSION":Y.lines=1,Y.uncompress=we;break;case"ZIP_COMPRESSION":Y.lines=16,Y.uncompress=we;break;case"PIZ_COMPRESSION":Y.lines=32,Y.uncompress=De;break;case"PXR24_COMPRESSION":Y.lines=16,Y.uncompress=se;break;case"DWAA_COMPRESSION":Y.lines=32,Y.uncompress=be;break;case"DWAB_COMPRESSION":Y.lines=256,Y.uncompress=be;break;default:throw new Error("EXRLoader.parse: "+S.compression+" is unsupported")}if(Y.scanlineBlockSize=Y.lines,Y.type==1)switch(N){case kn:Y.getter=ct,Y.inputSize=2;break;case rr:Y.getter=et,Y.inputSize=2;break}else if(Y.type==2)switch(N){case kn:Y.getter=Me,Y.inputSize=4;break;case rr:Y.getter=Qe,Y.inputSize=4}else throw new Error("EXRLoader.parse: unsupported pixelType "+Y.type+" for "+S.compression+".");Y.blockCount=(S.dataWindow.yMax+1)/Y.scanlineBlockSize;for(let ae=0;ae<Y.blockCount;ae++)Te(B,ee);Y.outputChannels=Y.channels==3?4:Y.channels;const W=Y.width*Y.height*Y.outputChannels;switch(N){case kn:Y.byteArray=new Float32Array(W),Y.channels<Y.outputChannels&&Y.byteArray.fill(1,0,W);break;case rr:Y.byteArray=new Uint16Array(W),Y.channels<Y.outputChannels&&Y.byteArray.fill(15360,0,W);break;default:console.error("THREE.EXRLoader: unsupported type: ",N);break}return Y.bytesPerLine=Y.width*Y.inputSize*Y.channels,Y.outputChannels==4?(Y.format=Yi,Y.colorSpace=Ri):(Y.format=Zm,Y.colorSpace=lo),Y}const Ve=new DataView(e),St=new Uint8Array(e),Ue={value:0},qt=ht(Ve,e,Ue),Fe=je(qt,Ve,St,Ue,this.type),_t={value:0},ut={R:0,G:1,B:2,A:3,Y:0};for(let S=0;S<Fe.height/Fe.scanlineBlockSize;S++){const B=fe(Ve,Ue);Fe.size=fe(Ve,Ue),Fe.lines=B+Fe.scanlineBlockSize>Fe.height?Fe.height-B:Fe.scanlineBlockSize;const j=Fe.size<Fe.lines*Fe.bytesPerLine?Fe.uncompress(Fe):K(Fe);Ue.value+=Fe.size;for(let ee=0;ee<Fe.scanlineBlockSize;ee++){const N=ee+S*Fe.scanlineBlockSize;if(N>=Fe.height)break;for(let Y=0;Y<Fe.channels;Y++){const W=ut[qt.channels[Y].name];for(let ae=0;ae<Fe.width;ae++){_t.value=(ee*(Fe.channels*Fe.width)+Y*Fe.width+ae)*Fe.inputSize;const ce=(Fe.height-1-N)*(Fe.width*Fe.outputChannels)+ae*Fe.outputChannels+W;Fe.byteArray[ce]=Fe.getter(j,_t)}}}}return{header:qt,width:Fe.width,height:Fe.height,data:Fe.byteArray,format:Fe.format,colorSpace:Fe.colorSpace,type:this.type}}setDataType(e){return this.type=e,this}load(e,t,r,s){function o(a,l){a.colorSpace=l.colorSpace,a.minFilter=Pt,a.magFilter=Pt,a.generateMipmaps=!1,a.flipY=!1,t&&t(a,l)}return super.load(e,o,r,s)}}const wde=Object.freeze(Object.defineProperty({__proto__:null,EXRLoader:oA},Symbol.toStringTag,{value:"Module"}));class uS extends hI{constructor(e){super(e),this.type=rr}parse(e){const t=function(A,_){switch(A){case 1:throw new Error("THREE.RGBELoader: Read Error: "+(_||""));case 2:throw new Error("THREE.RGBELoader: Write Error: "+(_||""));case 3:throw new Error("THREE.RGBELoader: Bad File Format: "+(_||""));default:case 4:throw new Error("THREE.RGBELoader: Memory Error: "+(_||""))}},r=`
|
|
5237
5237
|
`,s=function(A,_,b){_=_||1024;let x=A.pos,E=-1,I=0,T="",R=String.fromCharCode.apply(null,new Uint16Array(A.subarray(x,x+128)));for(;0>(E=R.indexOf(r))&&I<_&&x<A.byteLength;)T+=R,I+=R.length,x+=128,R+=String.fromCharCode.apply(null,new Uint16Array(A.subarray(x,x+128)));return-1<E?(b!==!1&&(A.pos+=I+E+1),T+R.slice(0,E)):!1},o=function(A){const _=/^#\?(\S+)/,b=/^\s*GAMMA\s*=\s*(\d+(\.\d+)?)\s*$/,x=/^\s*EXPOSURE\s*=\s*(\d+(\.\d+)?)\s*$/,E=/^\s*FORMAT=(\S+)\s*$/,I=/^\s*\-Y\s+(\d+)\s+\+X\s+(\d+)\s*$/,T={valid:0,string:"",comments:"",programtype:"RGBE",format:"",gamma:1,exposure:1,width:0,height:0};let R,D;for((A.pos>=A.byteLength||!(R=s(A)))&&t(1,"no header found"),(D=R.match(_))||t(3,"bad initial token"),T.valid|=1,T.programtype=D[1],T.string+=R+`
|
|
5238
5238
|
`;R=s(A),R!==!1;){if(T.string+=R+`
|
|
@@ -5266,7 +5266,7 @@ TEX `+r.texture_lod;if(HB=="density"&&(_+=`
|
|
|
5266
5266
|
`+(A/l.lastScreenCoverage).toFixed(0)+` dens
|
|
5267
5267
|
`+(l.lastScreenCoverage*100).toFixed(1)+`% cov
|
|
5268
5268
|
`+(l.lastCentrality*100).toFixed(1)+`% centr
|
|
5269
|
-
`+(dS.min.x.toFixed(2)+"-"+dS.max.x.toFixed(2)+"x"+dS.min.y.toFixed(2)+"-"+dS.max.y.toFixed(2))+" scr"),l.lastScreenCoverage>.1){const b=e,x=b.worldForward,E=b.worldPosition,I=pi(x).multiplyScalar(m*.7).add(p),T=I.distanceTo(E),R=f[Math.min(f.length-1,Math.max(0,c))]+"88",D=this.context.domHeight>0?screen.height/this.context.domHeight:1,M=e.isPerspectiveCamera?Math.tan(e.fov*Math.PI/180/2):1;At.DrawLabel(I,_,T*.012*D*M,void 0,16777215,R)}}}}}const mS=te("debugphysics"),vV=new ds;class ml{constructor(){d(this,"ray"),d(this,"cam"),d(this,"screenPoint"),d(this,"raycaster"),d(this,"results"),d(this,"targets"),d(this,"recursive",!0),d(this,"minDistance"),d(this,"maxDistance"),d(this,"lineThreshold"),d(this,"layerMask"),d(this,"ignore"),d(this,"testObject")}screenPointFromOffset(e,t){this.screenPoint===void 0&&(this.screenPoint=new Z),this.screenPoint.x=e/window.innerWidth*2-1,this.screenPoint.y=-(t/window.innerHeight)*2+1}setLayer(e){vV.set(e),this.layerMask=vV}setMask(e){this.layerMask||(this.layerMask=new ds);const t=this.layerMask;t?t.mask=e:this.layerMask=e}}d(ml,"AllLayers",4294967295);class yV{constructor(e,t,r){d(this,"distance"),d(this,"point"),d(this,"object"),this.object=e,this.distance=t,this.point=r}}class AV{constructor(e){d(this,"context"),d(this,"engine"),d(this,"raycaster",new pp),d(this,"defaultRaycastOptions",new ml),d(this,"targetBuffer",new Array(1)),d(this,"defaultThresholds",{Mesh:{},Line:{threshold:-1},LOD:{},Points:{threshold:0},Sprite:{}}),d(this,"sphereResults",new Array),d(this,"sphereMask",new ds),d(this,"tempBoundingBox",new xi),this.context=e}raycastPhysicsFast(e,t=void 0,r=1/0,s=!0){var o;return((o=this.context.physics.engine)==null?void 0:o.raycast(e,t,{maxDistance:r,solid:s}))??null}raycastPhysicsFastAndGetNormal(e,t=void 0,r=1/0,s=!0){var o;return((o=this.context.physics.engine)==null?void 0:o.raycastAndGetNormal(e,t,{maxDistance:r,solid:s}))??null}sphereOverlapPhysics(e,t){var r;return((r=this.context.physics.engine)==null?void 0:r.sphereOverlap(e,t))??null}sphereOverlap(e,t,r=!0){if(this.sphereResults.length=0,!this.context.scene)return this.sphereResults;const s=new wn(e,t),o=this.sphereMask;o.enableAll(),o.disable(2);for(const a of this.context.scene.children)this.onSphereOverlap(a,s,o,this.sphereResults,r);return this.sphereResults.sort((a,l)=>a.distance-l.distance)}onSphereOverlap(e,t,r,s,o){if(e.type==="Mesh"&&e.layers.test(r)&&!At.isGizmo(e)){const a=e,l=a.geometry;if(l&&(l.boundingBox||l.computeBoundingBox(),l.boundingBox)){a.matrixWorldNeedsUpdate&&a.updateMatrixWorld();const c=this.tempBoundingBox.copy(l.boundingBox).applyMatrix4(a.matrixWorld);if(t.intersectsBox(c)){const h=Bt(e),u=h.distanceTo(t.center),p=new yV(e,u,h);if(s.push(p),!o)return}}}if(e.children)for(const a of e.children){const l=s.length;if(this.onSphereOverlap(a,t,r,s,o),l!=s.length&&!o)return}}raycastFromRay(e,t=null){const r=t??this.defaultRaycastOptions;r.ray=e;const s=this.raycast(r);return r===this.defaultRaycastOptions&&(r.ray=void 0),s}raycast(e=null){e||(e=this.defaultRaycastOptions);const t=e.screenPoint??this.context.input.mousePositionRC,r=e.raycaster??this.raycaster;if(r.near=e.minDistance??0,r.far=e.maxDistance??1/0,r.params=this.defaultThresholds,e.lineThreshold===void 0&&(e.lineThreshold=-1),r.params.Line={threshold:e.lineThreshold},e.ray)r.ray.copy(e.ray);else{const l=e.cam??this.context.mainCamera;if(!l)return mS&&console.error("Can not perform raycast - no main camera found"),this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),this.defaultRaycastOptions.results??[];const c=this.context.xrCamera;this.context.isInXR&&c instanceof BT&&c.cameras.length>0?r.setFromCamera(t,c.cameras[0]):r.setFromCamera(t,l)}let s=e.targets;s||(s=this.targetBuffer,s.length=1,s[0]=this.context.scene);let o=e.results;this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),o||(this.defaultRaycastOptions.results||(this.defaultRaycastOptions.results=new Array),o=this.defaultRaycastOptions.results),e.layerMask!==void 0?e.layerMask instanceof ds?r.layers.mask=e.layerMask.mask:r.layers.mask=e.layerMask:(r.layers.enableAll(),r.layers.disable(2)),mS&&(At.DrawRay(r.ray.origin,r.ray.direction,16711680,2),console.time("raycast")),o.length=0,this.intersect(this.raycaster,s,o,e),o.sort((l,c)=>l.distance-c.distance);const a=e.ignore;return a!==void 0&&a.length>0&&(o=o.filter(l=>!a.includes(l.object))),mS&&(console.timeEnd("raycast"),console.warn("#"+this.context.time.frame+", hits:",o!=null&&o.length?[...o]:"nothing")),o}intersect(e,t,r,s){var o;for(const a of t){if(a.visible===!1||At.isGizmo(a)||s.lineThreshold!==void 0&&s.lineThreshold<0&&a instanceof Sn)continue;const l=(o=s.testObject)==null?void 0:o.call(s,a);if(l!==!1){if(l!=="continue in children"){const c=a,h=c.geometry;if(h){const u=wy(a);u&&(c.geometry=u);const p=r.length;e.intersectObject(a,!1,r),mS&&r.length!=p&&At.DrawWireMesh({mesh:a,depthTest:!1,duration:.2,color:u?8969557:7798784}),c.geometry=h}}s.recursive!==!1&&this.intersect(e,a.children,r,s)}}return r}}const Tde=te("debugplayerview");var Wu=(n=>(n.Browser="browser",n.Headset="headset",n.Handheld="handheld",n))(Wu||{});class bV{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 _V{constructor(e){d(this,"context"),d(this,"playerViews",new Map),this.context=e}setPlayerView(e,t,r){let s=this.playerViews.get(e);s||(s=new bV(e,this.context),this.playerViews.set(e,s)),s.viewDevice=r,s.currentObject=t,s.removed=!1}getPlayerView(e){if(!!e){if(!this.context.connection.userIsInRoom(e)){this.playerViews.delete(e);return}return this.playerViews.get(e)}}removePlayerView(e,t){const r=this.playerViews.get(e);r?.viewDevice===t&&(Tde&&console.log("REMOVE",e),r.removed=!0,this.playerViews.delete(e))}}new ys;const lA=new Uint8Array(4);lA[0]=255,lA[1]=255,lA[2]=255,lA[3]=255;const Ide=new Ro(lA,1,1,Yi);function WB(n,e=1){const t="alpha"in n,r=e*e,s=new Uint8Array(4*r),o=Math.floor(n.r*255),a=Math.floor(n.g*255),l=Math.floor(n.b*255);for(let h=0;h<r;h++){const u=h*4;s[u+0]=o,s[u+1]=a,s[u+2]=l,t?s[u+3]=Math.floor(n.alpha*255):s[u+3]=255}const c=new Ro(s,e,e);return c.needsUpdate=!0,c}function Rde(n,e,t,r=1,s=3){const o=r*s,a=[n,e,t],l=a.length,c=new Uint8Array(4*l*o),h=new xe;for(let p=0;p<s;p++){const m=Math.floor(p/s*l),f=it.clamp(m+1,0,l-1),g=a[m],v=a[f],y=p/s*l%1;h.lerpColors(g,v,y);const A=Math.floor(h.r*255),_=Math.floor(h.g*255),b=Math.floor(h.b*255);for(let x=0;x<r;x++){const E=(p*r+x)*4;c[E+0]=A,c[E+1]=_,c[E+2]=b,c[E+3]=255}}const u=new Ro(c,r,s);return u.needsUpdate=!0,u}function fS(n,e){const t=n.elements;e||(e=[]),e.length=0;for(let r=0;r<16;r+=4){const s=t[r],o=t[r+1],a=t[r+2],l=t[r+3],c=new Ye(s,o,a,l);e.push(c)}return e}const XB=[],xV=[];function Pde(n,e){if(XB.length===0)for(let t=0;t<27;t++)XB.push(0);e||(e=XB);for(let t=0;t<27;t++)xV[t]=e[t];e=xV,n.unity_SHAr={value:new Ye(e[9],e[3],e[6],e[0])},n.unity_SHBr={value:new Ye(e[12],e[15],e[18],e[21])},n.unity_SHAg={value:new Ye(e[10],e[4],e[7],e[1])},n.unity_SHBg={value:new Ye(e[13],e[16],e[19],e[22])},n.unity_SHAb={value:new Ye(e[11],e[5],e[8],e[2])},n.unity_SHBb={value:new Ye(e[14],e[17],e[20],e[23])},n.unity_SHC={value:new Ye(e[24],e[25],e[26],1)}}class Bde{constructor(e,t,r){d(this,"vertexShader"),d(this,"fragmentShader"),d(this,"technique"),this.vertexShader=e,this.fragmentShader=t,this.technique=r}}async function kde(n,e){if(!n)return console.error("Can not find technique: no shader data"),null;const t=n.programs[e],r=t.vertexShader,s=t.fragmentShader;if(r!==void 0&&s!==void 0){const o=n.shaders[r],a=n.shaders[s];if(o.uri&&a.uri||o.code&&a.code){if(!o.code&&o.uri&&await wV(o),!a.code&&a.uri&&await wV(a),!o.code||!a.code)return null;const l=n.techniques[e];return new Bde(o.code,a.code,l)}}return console.error("Shader technique not found",e),null}async function wV(n){const e=n.uri;if(e)if(e.endsWith(".glsl")){const t=await new ys().loadAsync(e);n.code=t.toString()}else n.code=Dde(n.uri)}function Dde(n){return decodeURIComponent(Array.prototype.map.call(atob(n),function(e){return"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)}).join(""))}const fl=te("debugenvlight");var Ng=(n=>(n[n.Skybox=0]="Skybox",n[n.Trilight=1]="Trilight",n[n.Flat=3]="Flat",n[n.Custom=4]="Custom",n))(Ng||{}),gS=(n=>(n[n.Skybox=0]="Skybox",n[n.Custom=1]="Custom",n))(gS||{});class SV{constructor(e){d(this,"context"),d(this,"_currentLightSettingsId"),d(this,"_sceneLightSettings"),d(this,"_timevec4",new Ye),d(this,"__currentReflectionId",null),d(this,"_lighting",{}),this.context=e,this.context.pre_update_callbacks.push(this.preUpdate.bind(this))}preUpdate(){const e=this.context.time;this._timevec4.x=e.time,this._timevec4.y=Math.sin(e.time),this._timevec4.z=Math.cos(e.time),this._timevec4.w=e.deltaTime}get timeVec4(){return this._timevec4}get environmentIntensity(){if(!this._sceneLightSettings||!this._currentLightSettingsId)return 1;const e=this._sceneLightSettings.get(this._currentLightSettingsId);return e?e.ambientIntensity:1}get sceneLightSettings(){var e;return(e=this._sceneLightSettings)==null?void 0:e.values()}enable(e){var t;e instanceof ti&&(e=e.uri);const r=(t=this._sceneLightSettings)==null?void 0:t.get(e);return r?(fl&&console.log("Enable scene light settings",e,r),e!==this._currentLightSettingsId&&this._currentLightSettingsId&&this.disable(this._currentLightSettingsId),this._currentLightSettingsId=e,r.enabled=!0,!0):(fl&&console.warn("No light settings found for",e),!1)}disable(e){var t;if(e instanceof ti&&(e=e.uri),e==null)return!1;const r=(t=this._sceneLightSettings)==null?void 0:t.get(e);return r?(fl&&console.log("Disable scene light settings",e,r),r.enabled=!1,!0):!1}disableCurrent(){if(this._currentLightSettingsId){const e=this._currentLightSettingsId;return this.disable(this._currentLightSettingsId),e}return null}internalRegisterSceneLightSettings(e){const t=e.sourceId;if(!t){console.error("Missing source id for scene light settings, can not register:",e);return}fl&&console.log("Register "+e?.sourceId+" lighting",e),this._sceneLightSettings||(this._sceneLightSettings=new Map),this._sceneLightSettings.set(t,e)}internalUnregisterSceneLightSettings(e){const t=e.sourceId;if(!t){console.error("Missing source id for scene light settings, can not unregister:",e);return}fl&&console.log("Unregister "+e?.sourceId+" lighting",e),this._sceneLightSettings&&this._sceneLightSettings.delete(t)}internalRegisterReflection(e,t){fl&&console.log("Register reflection",e,t);const r=new CV(this.context,t,1);this._lighting[e]=r}internalGetReflection(e){return this._lighting[e]}internalEnableReflection(e){var t;this.__currentReflectionId=e;const r=(t=this._sceneLightSettings)==null?void 0:t.get(e);switch(fl&&console.log("Enable reflection",e,r?Ng[r.ambientMode]:"Unknown ambient mode",r),r?.ambientMode){case 0:case 4:const s=this.internalGetReflection(e);if(s&&s.Source){fl&&console.log("Setting environment reflection",s);const o=this.context.scene,a=s.Source;a.mapping=so,o.environment=a;return}else fl&&console.warn("Could not find reflection for source",e);break}if(r?.environmentReflectionSource===1)switch(r?.ambientMode){case 1:if(r.ambientTrilight){const s=r.ambientTrilight,o=Rde(s[0],s[1],s[2],64,64);o.colorSpace=ft,o.mapping=so,this.context.scene.environment=o}else console.error("Missing ambient trilight",r.sourceId);return;case 3:if(r.ambientLight){const s=WB(r.ambientLight,64);s.colorSpace=ft,s.mapping=so,this.context.scene.environment=s}else console.error("Missing ambientlight",r.sourceId);return;default:return}}internalDisableReflection(e){if(e&&e!==this.__currentReflectionId){fl&&console.log("Not disabling reflection for",e,"because it is not the current light settings id",this.__currentReflectionId);return}fl&&console.log("Disable reflection",e);const t=this.context.scene;t.environment=null}}class CV{constructor(e,t,r=1){d(this,"_source"),this._source=t,t.mapping=so}get Source(){return this._source}}const EV=te("timescale");let qB=1;typeof EV=="number"&&(qB=EV);class MV{constructor(){d(this,"_time",0),d(this,"_deltaTime",0),d(this,"_deltaTimeUnscaled",0),d(this,"timeScale",1),d(this,"_frame",0),d(this,"clock",new fI),d(this,"_smoothedFps",0),d(this,"_smoothedDeltaTime",0),d(this,"_fpsSamples",[]),d(this,"_fpsSampleIndex",0),typeof qB=="number"&&(this.timeScale=qB)}get time(){return this._time}set time(e){this._time=e}get deltaTime(){return this._deltaTime}set deltaTime(e){this._deltaTime=e}get deltaTimeUnscaled(){return this._deltaTimeUnscaled}get frame(){return this._frame}set frame(e){this._frame=e}get frameCount(){return this.frame}get realtimeSinceStartup(){return this.clock.elapsedTime}get smoothedFps(){return this._smoothedFps}get smoothedDeltaTime(){return 1/this._smoothedFps}update(){this.deltaTime=this.clock.getDelta(),this.deltaTime=Math.min(.1,this.deltaTime),this._deltaTimeUnscaled=this.deltaTime,this.deltaTime<=0&&(this.deltaTime=1e-12),this.deltaTime*=this.timeScale,this.frame+=1,this.time+=this.deltaTime,this._fpsSamples.length<60?this._fpsSamples.push(this.deltaTime):this._fpsSamples[this._fpsSampleIndex++%60]=this.deltaTime;let e=0;for(let t=0;t<this._fpsSamples.length;t++)e+=this._fpsSamples[t];this._smoothedDeltaTime=e/this._fpsSamples.length,this._smoothedFps=1/this._smoothedDeltaTime}}let TV=!1;function IV(n){TV||(TV=!0,Ode(),Lde())}IV();function Ode(){const n=`
|
|
5269
|
+
`+(dS.min.x.toFixed(2)+"-"+dS.max.x.toFixed(2)+"x"+dS.min.y.toFixed(2)+"-"+dS.max.y.toFixed(2))+" scr"),l.lastScreenCoverage>.1){const b=e,x=b.worldForward,E=b.worldPosition,I=pi(x).multiplyScalar(m*.7).add(p),T=I.distanceTo(E),R=f[Math.min(f.length-1,Math.max(0,c))]+"88",D=this.context.domHeight>0?screen.height/this.context.domHeight:1,M=e.isPerspectiveCamera?Math.tan(e.fov*Math.PI/180/2):1;At.DrawLabel(I,_,T*.012*D*M,void 0,16777215,R)}}}}}const mS=te("debugphysics"),vV=new ds;class ml{constructor(){d(this,"ray"),d(this,"cam"),d(this,"screenPoint"),d(this,"raycaster"),d(this,"results"),d(this,"targets"),d(this,"recursive",!0),d(this,"minDistance"),d(this,"maxDistance"),d(this,"lineThreshold"),d(this,"layerMask"),d(this,"ignore"),d(this,"testObject")}screenPointFromOffset(e,t){this.screenPoint===void 0&&(this.screenPoint=new Z),this.screenPoint.x=e/window.innerWidth*2-1,this.screenPoint.y=-(t/window.innerHeight)*2+1}setLayer(e){vV.set(e),this.layerMask=vV}setMask(e){this.layerMask||(this.layerMask=new ds);const t=this.layerMask;t?t.mask=e:this.layerMask=e}}d(ml,"AllLayers",4294967295);class yV{constructor(e,t,r){d(this,"distance"),d(this,"point"),d(this,"object"),this.object=e,this.distance=t,this.point=r}}class AV{constructor(e){d(this,"context"),d(this,"engine"),d(this,"raycaster",new pp),d(this,"defaultRaycastOptions",new ml),d(this,"targetBuffer",new Array(1)),d(this,"defaultThresholds",{Mesh:{},Line:{threshold:-1},LOD:{},Points:{threshold:0},Sprite:{}}),d(this,"sphereResults",new Array),d(this,"sphereMask",new ds),d(this,"tempBoundingBox",new xi),this.context=e}raycastPhysicsFast(e,t=void 0,r=1/0,s=!0){var o;return((o=this.context.physics.engine)==null?void 0:o.raycast(e,t,{maxDistance:r,solid:s}))??null}raycastPhysicsFastAndGetNormal(e,t=void 0,r=1/0,s=!0){var o;return((o=this.context.physics.engine)==null?void 0:o.raycastAndGetNormal(e,t,{maxDistance:r,solid:s}))??null}sphereOverlapPhysics(e,t){var r;return((r=this.context.physics.engine)==null?void 0:r.sphereOverlap(e,t))??null}sphereOverlap(e,t,r=!0){if(this.sphereResults.length=0,!this.context.scene)return this.sphereResults;const s=new wn(e,t),o=this.sphereMask;o.enableAll(),o.disable(2);for(const a of this.context.scene.children)this.onSphereOverlap(a,s,o,this.sphereResults,r);return this.sphereResults.sort((a,l)=>a.distance-l.distance)}onSphereOverlap(e,t,r,s,o){if(e.type==="Mesh"&&e.layers.test(r)&&!At.isGizmo(e)){const a=e,l=a.geometry;if(l&&(l.boundingBox||l.computeBoundingBox(),l.boundingBox)){a.matrixWorldNeedsUpdate&&a.updateMatrixWorld();const c=this.tempBoundingBox.copy(l.boundingBox).applyMatrix4(a.matrixWorld);if(t.intersectsBox(c)){const h=Bt(e),u=h.distanceTo(t.center),p=new yV(e,u,h);if(s.push(p),!o)return}}}if(e.children)for(const a of e.children){const l=s.length;if(this.onSphereOverlap(a,t,r,s,o),l!=s.length&&!o)return}}raycastFromRay(e,t=null){const r=t??this.defaultRaycastOptions;r.ray=e;const s=this.raycast(r);return r===this.defaultRaycastOptions&&(r.ray=void 0),s}raycast(e=null){e||(e=this.defaultRaycastOptions);const t=e.screenPoint??this.context.input.mousePositionRC,r=e.raycaster??this.raycaster;if(r.near=e.minDistance??0,r.far=e.maxDistance??1/0,r.params=this.defaultThresholds,e.lineThreshold===void 0&&(e.lineThreshold=-1),r.params.Line={threshold:e.lineThreshold},e.ray)r.ray.copy(e.ray);else{const l=e.cam??this.context.mainCamera;if(!l)return mS&&console.error("Can not perform raycast - no main camera found"),this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),this.defaultRaycastOptions.results??[];const c=this.context.xrCamera;this.context.isInXR&&c instanceof BT&&c.cameras.length>0?r.setFromCamera(t,c.cameras[0]):r.setFromCamera(t,l)}let s=e.targets;s||(s=this.targetBuffer,s.length=1,s[0]=this.context.scene);let o=e.results;this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),o||(this.defaultRaycastOptions.results||(this.defaultRaycastOptions.results=new Array),o=this.defaultRaycastOptions.results),e.layerMask!==void 0?e.layerMask instanceof ds?r.layers.mask=e.layerMask.mask:r.layers.mask=e.layerMask:(r.layers.enableAll(),r.layers.disable(2)),mS&&(At.DrawRay(r.ray.origin,r.ray.direction,16711680,2),console.time("raycast")),o.length=0,this.intersect(this.raycaster,s,o,e),o.sort((l,c)=>l.distance-c.distance);const a=e.ignore;return a!==void 0&&a.length>0&&(o=o.filter(l=>!a.includes(l.object))),mS&&(console.timeEnd("raycast"),console.warn("#"+this.context.time.frame+", hits:",o!=null&&o.length?[...o]:"nothing")),o}intersect(e,t,r,s){var o;for(const a of t){if(!a||a.visible===!1||At.isGizmo(a)||s.lineThreshold!==void 0&&s.lineThreshold<0&&a instanceof Sn)continue;const l=(o=s.testObject)==null?void 0:o.call(s,a);if(l!==!1){if(l!=="continue in children"){const c=a,h=c.geometry;if(h){const u=wy(a);u&&(c.geometry=u);const p=r.length;e.intersectObject(a,!1,r),mS&&r.length!=p&&At.DrawWireMesh({mesh:a,depthTest:!1,duration:.2,color:u?8969557:7798784}),c.geometry=h}}s.recursive!==!1&&this.intersect(e,a.children,r,s)}}return r}}const Tde=te("debugplayerview");var Wu=(n=>(n.Browser="browser",n.Headset="headset",n.Handheld="handheld",n))(Wu||{});class bV{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 _V{constructor(e){d(this,"context"),d(this,"playerViews",new Map),this.context=e}setPlayerView(e,t,r){let s=this.playerViews.get(e);s||(s=new bV(e,this.context),this.playerViews.set(e,s)),s.viewDevice=r,s.currentObject=t,s.removed=!1}getPlayerView(e){if(!!e){if(!this.context.connection.userIsInRoom(e)){this.playerViews.delete(e);return}return this.playerViews.get(e)}}removePlayerView(e,t){const r=this.playerViews.get(e);r?.viewDevice===t&&(Tde&&console.log("REMOVE",e),r.removed=!0,this.playerViews.delete(e))}}new ys;const lA=new Uint8Array(4);lA[0]=255,lA[1]=255,lA[2]=255,lA[3]=255;const Ide=new Ro(lA,1,1,Yi);function WB(n,e=1){const t="alpha"in n,r=e*e,s=new Uint8Array(4*r),o=Math.floor(n.r*255),a=Math.floor(n.g*255),l=Math.floor(n.b*255);for(let h=0;h<r;h++){const u=h*4;s[u+0]=o,s[u+1]=a,s[u+2]=l,t?s[u+3]=Math.floor(n.alpha*255):s[u+3]=255}const c=new Ro(s,e,e);return c.needsUpdate=!0,c}function Rde(n,e,t,r=1,s=3){const o=r*s,a=[n,e,t],l=a.length,c=new Uint8Array(4*l*o),h=new xe;for(let p=0;p<s;p++){const m=Math.floor(p/s*l),f=it.clamp(m+1,0,l-1),g=a[m],v=a[f],y=p/s*l%1;h.lerpColors(g,v,y);const A=Math.floor(h.r*255),_=Math.floor(h.g*255),b=Math.floor(h.b*255);for(let x=0;x<r;x++){const E=(p*r+x)*4;c[E+0]=A,c[E+1]=_,c[E+2]=b,c[E+3]=255}}const u=new Ro(c,r,s);return u.needsUpdate=!0,u}function fS(n,e){const t=n.elements;e||(e=[]),e.length=0;for(let r=0;r<16;r+=4){const s=t[r],o=t[r+1],a=t[r+2],l=t[r+3],c=new Ye(s,o,a,l);e.push(c)}return e}const XB=[],xV=[];function Pde(n,e){if(XB.length===0)for(let t=0;t<27;t++)XB.push(0);e||(e=XB);for(let t=0;t<27;t++)xV[t]=e[t];e=xV,n.unity_SHAr={value:new Ye(e[9],e[3],e[6],e[0])},n.unity_SHBr={value:new Ye(e[12],e[15],e[18],e[21])},n.unity_SHAg={value:new Ye(e[10],e[4],e[7],e[1])},n.unity_SHBg={value:new Ye(e[13],e[16],e[19],e[22])},n.unity_SHAb={value:new Ye(e[11],e[5],e[8],e[2])},n.unity_SHBb={value:new Ye(e[14],e[17],e[20],e[23])},n.unity_SHC={value:new Ye(e[24],e[25],e[26],1)}}class Bde{constructor(e,t,r){d(this,"vertexShader"),d(this,"fragmentShader"),d(this,"technique"),this.vertexShader=e,this.fragmentShader=t,this.technique=r}}async function kde(n,e){if(!n)return console.error("Can not find technique: no shader data"),null;const t=n.programs[e],r=t.vertexShader,s=t.fragmentShader;if(r!==void 0&&s!==void 0){const o=n.shaders[r],a=n.shaders[s];if(o.uri&&a.uri||o.code&&a.code){if(!o.code&&o.uri&&await wV(o),!a.code&&a.uri&&await wV(a),!o.code||!a.code)return null;const l=n.techniques[e];return new Bde(o.code,a.code,l)}}return console.error("Shader technique not found",e),null}async function wV(n){const e=n.uri;if(e)if(e.endsWith(".glsl")){const t=await new ys().loadAsync(e);n.code=t.toString()}else n.code=Dde(n.uri)}function Dde(n){return decodeURIComponent(Array.prototype.map.call(atob(n),function(e){return"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)}).join(""))}const fl=te("debugenvlight");var Ng=(n=>(n[n.Skybox=0]="Skybox",n[n.Trilight=1]="Trilight",n[n.Flat=3]="Flat",n[n.Custom=4]="Custom",n))(Ng||{}),gS=(n=>(n[n.Skybox=0]="Skybox",n[n.Custom=1]="Custom",n))(gS||{});class SV{constructor(e){d(this,"context"),d(this,"_currentLightSettingsId"),d(this,"_sceneLightSettings"),d(this,"_timevec4",new Ye),d(this,"__currentReflectionId",null),d(this,"_lighting",{}),this.context=e,this.context.pre_update_callbacks.push(this.preUpdate.bind(this))}preUpdate(){const e=this.context.time;this._timevec4.x=e.time,this._timevec4.y=Math.sin(e.time),this._timevec4.z=Math.cos(e.time),this._timevec4.w=e.deltaTime}get timeVec4(){return this._timevec4}get environmentIntensity(){if(!this._sceneLightSettings||!this._currentLightSettingsId)return 1;const e=this._sceneLightSettings.get(this._currentLightSettingsId);return e?e.ambientIntensity:1}get sceneLightSettings(){var e;return(e=this._sceneLightSettings)==null?void 0:e.values()}enable(e){var t;e instanceof ti&&(e=e.uri);const r=(t=this._sceneLightSettings)==null?void 0:t.get(e);return r?(fl&&console.log("Enable scene light settings",e,r),e!==this._currentLightSettingsId&&this._currentLightSettingsId&&this.disable(this._currentLightSettingsId),this._currentLightSettingsId=e,r.enabled=!0,!0):(fl&&console.warn("No light settings found for",e),!1)}disable(e){var t;if(e instanceof ti&&(e=e.uri),e==null)return!1;const r=(t=this._sceneLightSettings)==null?void 0:t.get(e);return r?(fl&&console.log("Disable scene light settings",e,r),r.enabled=!1,!0):!1}disableCurrent(){if(this._currentLightSettingsId){const e=this._currentLightSettingsId;return this.disable(this._currentLightSettingsId),e}return null}internalRegisterSceneLightSettings(e){const t=e.sourceId;if(!t){console.error("Missing source id for scene light settings, can not register:",e);return}fl&&console.log("Register "+e?.sourceId+" lighting",e),this._sceneLightSettings||(this._sceneLightSettings=new Map),this._sceneLightSettings.set(t,e)}internalUnregisterSceneLightSettings(e){const t=e.sourceId;if(!t){console.error("Missing source id for scene light settings, can not unregister:",e);return}fl&&console.log("Unregister "+e?.sourceId+" lighting",e),this._sceneLightSettings&&this._sceneLightSettings.delete(t)}internalRegisterReflection(e,t){fl&&console.log("Register reflection",e,t);const r=new CV(this.context,t,1);this._lighting[e]=r}internalGetReflection(e){return this._lighting[e]}internalEnableReflection(e){var t;this.__currentReflectionId=e;const r=(t=this._sceneLightSettings)==null?void 0:t.get(e);switch(fl&&console.log("Enable reflection",e,r?Ng[r.ambientMode]:"Unknown ambient mode",r),r?.ambientMode){case 0:case 4:const s=this.internalGetReflection(e);if(s&&s.Source){fl&&console.log("Setting environment reflection",s);const o=this.context.scene,a=s.Source;a.mapping=so,o.environment=a;return}else fl&&console.warn("Could not find reflection for source",e);break}if(r?.environmentReflectionSource===1)switch(r?.ambientMode){case 1:if(r.ambientTrilight){const s=r.ambientTrilight,o=Rde(s[0],s[1],s[2],64,64);o.colorSpace=ft,o.mapping=so,this.context.scene.environment=o}else console.error("Missing ambient trilight",r.sourceId);return;case 3:if(r.ambientLight){const s=WB(r.ambientLight,64);s.colorSpace=ft,s.mapping=so,this.context.scene.environment=s}else console.error("Missing ambientlight",r.sourceId);return;default:return}}internalDisableReflection(e){if(e&&e!==this.__currentReflectionId){fl&&console.log("Not disabling reflection for",e,"because it is not the current light settings id",this.__currentReflectionId);return}fl&&console.log("Disable reflection",e);const t=this.context.scene;t.environment=null}}class CV{constructor(e,t,r=1){d(this,"_source"),this._source=t,t.mapping=so}get Source(){return this._source}}const EV=te("timescale");let qB=1;typeof EV=="number"&&(qB=EV);class MV{constructor(){d(this,"_time",0),d(this,"_deltaTime",0),d(this,"_deltaTimeUnscaled",0),d(this,"timeScale",1),d(this,"_frame",0),d(this,"clock",new fI),d(this,"_smoothedFps",0),d(this,"_smoothedDeltaTime",0),d(this,"_fpsSamples",[]),d(this,"_fpsSampleIndex",0),typeof qB=="number"&&(this.timeScale=qB)}get time(){return this._time}set time(e){this._time=e}get deltaTime(){return this._deltaTime}set deltaTime(e){this._deltaTime=e}get deltaTimeUnscaled(){return this._deltaTimeUnscaled}get frame(){return this._frame}set frame(e){this._frame=e}get frameCount(){return this.frame}get realtimeSinceStartup(){return this.clock.elapsedTime}get smoothedFps(){return this._smoothedFps}get smoothedDeltaTime(){return 1/this._smoothedFps}update(){this.deltaTime=this.clock.getDelta(),this.deltaTime=Math.min(.1,this.deltaTime),this._deltaTimeUnscaled=this.deltaTime,this.deltaTime<=0&&(this.deltaTime=1e-12),this.deltaTime*=this.timeScale,this.frame+=1,this.time+=this.deltaTime,this._fpsSamples.length<60?this._fpsSamples.push(this.deltaTime):this._fpsSamples[this._fpsSampleIndex++%60]=this.deltaTime;let e=0;for(let t=0;t<this._fpsSamples.length;t++)e+=this._fpsSamples[t];this._smoothedDeltaTime=e/this._fpsSamples.length,this._smoothedFps=1/this._smoothedDeltaTime}}let TV=!1;function IV(n){TV||(TV=!0,Ode(),Lde())}IV();function Ode(){const n=`
|
|
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 ${u.method} on object ${m.name}`,m,typeof m[u.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 Mpe=Object.defineProperty,Tpe=Object.getOwnPropertyDescriptor,ak=(n,e,t,r)=>{for(var s=r>1?void 0:r?Tpe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&Mpe(e,t,s),s};class nm extends Be{constructor(){super(...arguments),d(this,"constraintActive",!0),d(this,"locked",!1),d(this,"sources",[])}}ak([w()],nm.prototype,"constraintActive",2),ak([w()],nm.prototype,"locked",2),ak([w(ye)],nm.prototype,"sources",2);function Ipe(n,e){return Nu(n,Ci.ContextCreated,e),()=>zu(n,Ci.ContextCreated)}function Rpe(n,e){return Nu(n,Ci.ContextClearing,e),()=>zu(n,Ci.ContextClearing)}function Ppe(n,e){return Nu(n,Ci.ContextDestroying,e),()=>zu(n,Ci.ContextDestroying)}function f8(n,e){return Nu(n,Hi.Start,e),()=>zu(n,Hi.Start)}function g8(n,e){return Nu(n,Hi.Update,e),()=>zu(n,Hi.Update)}function Bpe(n,e){return Nu(n,Hi.OnBeforeRender,e),()=>zu(n,Hi.OnBeforeRender)}function kpe(n,e){return Nu(n,Hi.OnAfterRender,e),()=>zu(n,Hi.OnAfterRender)}class rm{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,r,s){return e.prep(4,12),e.writeFloat32(s),e.writeFloat32(r),e.writeFloat32(t),e.offset()}}class v8{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 rm).__init(this.bb_pos,this.bb)}rotation(e){return(e||new rm).__init(this.bb_pos+12,this.bb)}scale(e){return(e||new rm).__init(this.bb_pos+24,this.bb)}static sizeOf(){return 36}static createTransform(e,t,r,s,o,a,l,c,h,u){return e.prep(4,36),e.prep(4,12),e.writeFloat32(u),e.writeFloat32(h),e.writeFloat32(c),e.prep(4,12),e.writeFloat32(l),e.writeFloat32(a),e.writeFloat32(o),e.prep(4,12),e.writeFloat32(s),e.writeFloat32(r),e.writeFloat32(t),e.offset()}}class Vh{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 Vh).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSyncedTransformModel(e,t){return e.setPosition(e.position()+bB),(t||new Vh).__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 v8).__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 Cr=(n=>(n[n.Average=0]="Average",n[n.Multiply=1]="Multiply",n[n.Minimum=2]="Minimum",n[n.Maximum=3]="Maximum",n))(Cr||{}),LS=(n=>(n[n.Discrete=0]="Discrete",n[n.Continuous=1]="Continuous",n))(LS||{}),Nn=(n=>(n[n.None=0]="None",n[n.FreezePositionX=2]="FreezePositionX",n[n.FreezePositionY=4]="FreezePositionY",n[n.FreezePositionZ=8]="FreezePositionZ",n[n.FreezePosition=14]="FreezePosition",n[n.FreezeRotationX=16]="FreezeRotationX",n[n.FreezeRotationY=32]="FreezeRotationY",n[n.FreezeRotationZ=64]="FreezeRotationZ",n[n.FreezeRotation=112]="FreezeRotation",n[n.FreezeAll=126]="FreezeAll",n))(Nn||{}),Wg=(n=>(n[n.None=0]="None",n[n.X=2]="X",n[n.Y=4]="Y",n[n.Z=8]="Z",n[n.All=-1]="All",n))(Wg||{});const Hr=function(n,e){return function(t,r,s){Dpe(t,r,s,n,e)}};function Dpe(n,e,t,r,s){if(!s&&!r&&!n.onValidate)return;if(t!==void 0){console.error("Invalid usage of validate decorator. Only fields can be validated.",n,e,t),rn("Invalid usage of validate decorator. Only fields can be validated. Property: "+e,Bo.Error);return}let o="";if(typeof e=="string"?o=e:o=e.name,n.__internalAwake){const a=Symbol(o),l=n.__internalAwake;n.__internalAwake=function(){var c;if(!this.onValidate){st()&&console.warn('Usage of @validate decorate detected but there is no onValidate method in your class: "'+((c=n.constructor)==null?void 0:c.name)+'"');return}if(this[a]===void 0){this[a]=this[o];const h=this[o];if(h instanceof Z||h instanceof C||h instanceof Ye||h instanceof Ce){const u=this[o];Zx(u,()=>{this.onValidate(o)})}Object.defineProperty(this,o,{set:function(u){var p;if(this[lB]===!0)this[a]=u;else{r?.call(this,u);const m=this[a];this[a]=u,(p=this.onValidate)==null||p.call(this,o,m)}},get:function(){return s?.call(this),this[a]}})}l.call(this)}}}const Ope=function(n){return function(e,t,r){let s="";typeof t=="string"?s=t:s=t.name;const o=n.prototype,a=Object.getOwnPropertyDescriptor(o,s);if(!(a!=null&&a.value)){console.warn("Can not apply prefix: type does not have method named",t,n);return}const l=a.value,c=e[s];Object.defineProperty(o,s,{value:function(...h){const u=c?.call(this,...h);if(u instanceof Promise){u.then(p=>{if(p!==!1)return l.call(this,...h)});return}if(u!==!1)return l.call(this,...h)}})}};var Lpe=Object.defineProperty,Fpe=Object.getOwnPropertyDescriptor,Uo=(n,e,t,r)=>{for(var s=r>1?void 0:r?Fpe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&Lpe(e,t,s),s};class Upe{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 Nh(this.obj.position,["x","y","z"])),this._positionWatch.apply(),this.position={},this._positionWatch.subscribeWrite((o,a)=>{var l;if((l=this.context.physics.engine)!=null&&l.isUpdating||this.mute)return;const c=this.position[a];Math.abs(c-o)<1e-5||(this.position[a]=o,this.positionChanged=!0)})),t&&(this._rotationWatch||(this._rotationWatch=new Nh(this.obj.quaternion,["_x","_y","_z","_w"])),this._rotationWatch.apply(),this.quaternion={},this._rotationWatch.subscribeWrite((o,a)=>{var l;if((l=this.context.physics.engine)!=null&&l.isUpdating||this.mute)return;const c=this.quaternion[a];Math.abs(c-o)<1e-5||(this.quaternion[a]=o,this.rotationChanged=!0)}));const r=this.obj.matrixWorld.multiplyMatrices.bind(this.obj.matrixWorld),s=new ve;this.obj.matrixWorld.multiplyMatrices=(o,a)=>{var l;return(l=this.context.physics.engine)!=null&&l.isUpdating||this.mute||s.equals(o)||(this.positionChanged=!0,this.rotationChanged=!0,s.copy(o)),r(o,a)}}stop(){var e,t;(e=this._positionWatch)==null||e.revoke(),(t=this._rotationWatch)==null||t.revoke()}}var lk;const ck=(lk=class extends Be{constructor(){super(...arguments),d(this,"autoMass",!0),d(this,"_mass",0),d(this,"useGravity",!0),d(this,"centerOfMass",new C(0,0,0)),d(this,"constraints",Nn.None),d(this,"isKinematic",!1),d(this,"drag",0),d(this,"angularDrag",1),d(this,"detectCollisions",!0),d(this,"sleepThreshold",.01),d(this,"collisionDetectionMode",LS.Discrete),d(this,"_gravityScale",1),d(this,"dominanceGroup",0),d(this,"_propertiesChanged",!1),d(this,"_currentVelocity",new C),d(this,"_smoothedVelocity",new C),d(this,"_smoothedVelocityGetter",new C),d(this,"_lastPosition",new C),d(this,"_watch")}set mass(n){n!==this._mass&&(this._mass=n,this._propertiesChanged=!0,this.__didAwake&&(this.autoMass=!1))}get mass(){var n,e;return this.autoMass?((e=(n=this.context.physics.engine)==null?void 0:n.getBody(this))==null?void 0:e.mass())??-1:this._mass}get lockPositionX(){return(this.constraints&Nn.FreezePositionX)!==0}get lockPositionY(){return(this.constraints&Nn.FreezePositionY)!==0}get lockPositionZ(){return(this.constraints&Nn.FreezePositionZ)!==0}get lockRotationX(){return(this.constraints&Nn.FreezeRotationX)!==0}get lockRotationY(){return(this.constraints&Nn.FreezeRotationY)!==0}get lockRotationZ(){return(this.constraints&Nn.FreezeRotationZ)!==0}set lockPositionX(n){n?this.constraints|=Nn.FreezePositionX:this.constraints&=~Nn.FreezePositionX}set lockPositionY(n){n?this.constraints|=Nn.FreezePositionY:this.constraints&=~Nn.FreezePositionY}set lockPositionZ(n){n?this.constraints|=Nn.FreezePositionZ:this.constraints&=~Nn.FreezePositionZ}set lockRotationX(n){n?this.constraints|=Nn.FreezeRotationX:this.constraints&=~Nn.FreezeRotationX}set lockRotationY(n){n?this.constraints|=Nn.FreezeRotationY:this.constraints&=~Nn.FreezeRotationY}set lockRotationZ(n){n?this.constraints|=Nn.FreezeRotationZ:this.constraints&=~Nn.FreezeRotationZ}set gravityScale(n){this._gravityScale=n}get gravityScale(){return this._gravityScale}awake(){this._watch=void 0,this._propertiesChanged=!1}onEnable(){this._watch||(this._watch=new Upe(this.gameObject,this.context)),this._watch.start(!0,!0),this.startCoroutine(this.beforePhysics(),Hi.LateUpdate)}onDisable(){var n,e;(n=this._watch)==null||n.stop(),(e=this.context.physics.engine)==null||e.removeBody(this)}onDestroy(){var n;(n=this.context.physics.engine)==null||n.removeBody(this)}onValidate(){this._propertiesChanged=!0}*beforePhysics(){for(var n,e,t,r;;)this._propertiesChanged&&(this._propertiesChanged=!1,(n=this.context.physics.engine)==null||n.updateProperties(this)),(e=this._watch)!=null&&e.isDirty?(this._watch.mute=!0,this._watch.applyValues(),(t=this.context.physics.engine)==null||t.updateBody(this,this._watch.positionChanged,this._watch.rotationChanged),this._watch.reset()):(r=this._watch)==null||r.syncValues(),this.captureVelocity(),yield}teleport(n,e=!0){var t;(t=this._watch)==null||t.reset(!0),e?this.gameObject.position.set(n.x,n.y,n.z):this.setWorldPosition(n.x,n.y,n.z),this.resetForcesAndTorques(),this.resetVelocities()}resetForces(n=!0){var e;(e=this.context.physics.engine)==null||e.resetForces(this,n)}resetTorques(n=!0){var e;(e=this.context.physics.engine)==null||e.resetTorques(this,n)}resetVelocities(){this.setVelocity(0,0,0),this.setAngularVelocity(0,0,0)}resetForcesAndTorques(){this.resetForces(),this.resetTorques()}wakeUp(){var n;(n=this.context.physics.engine)==null||n.wakeup(this)}get isSleeping(){var n;return(n=this.context.physics.engine)==null?void 0:n.isSleeping(this)}updateProperties(){var n;return this._propertiesChanged=!1,(n=this.context.physics.engine)==null?void 0:n.updateProperties(this)}applyForce(n,e,t=!0){var r;this._propertiesChanged&&this.updateProperties(),(r=this.context.physics.engine)==null||r.addForce(this,n,t)}applyImpulse(n,e=!0){var t;this._propertiesChanged&&this.updateProperties(),(t=this.context.physics.engine)==null||t.applyImpulse(this,n,e)}setForce(n,e,t,r=!0){var s,o,a;(s=this.context.physics.engine)==null||s.resetForces(this,r),typeof n=="number"?(e??(e=0),t??(t=0),(o=this.context.physics.engine)==null||o.addForce(this,{x:n,y:e,z:t},r)):(a=this.context.physics.engine)==null||a.addForce(this,n,r)}getVelocity(){var n;const e=(n=this.context.physics.engine)==null?void 0:n.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(n,e,t,r=!0){var s,o;if(n instanceof C){const a=n;(s=this.context.physics.engine)==null||s.setLinearVelocity(this,a,r);return}e===void 0||t===void 0||(o=this.context.physics.engine)==null||o.setLinearVelocity(this,{x:n,y:e,z:t},r)}getAngularVelocity(){var n;const e=(n=this.context.physics.engine)==null?void 0:n.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(n,e,t,r=!0){var s,o;if(n instanceof C){const a=n;(s=this.context.physics.engine)==null||s.setAngularVelocity(this,a,r);return}e===void 0||t===void 0||(o=this.context.physics.engine)==null||o.setAngularVelocity(this,{x:n,y:e,z:t},r)}setTorque(n,e,t){this.setAngularVelocity(n,e,t)}get smoothedVelocity(){return this._smoothedVelocityGetter.copy(this._smoothedVelocity),this._smoothedVelocityGetter.multiplyScalar(1/this.context.time.deltaTime)}setBodyFromGameObject(n=null){}captureVelocity(){const n=Bt(this.gameObject);ck.tempPosition.copy(n);const e=n.sub(this._lastPosition);this._lastPosition.copy(ck.tempPosition),this._smoothedVelocity.lerp(e,this.context.time.deltaTime/.1)}},d(lk,"tempPosition",new C),lk);let Oi=ck;Uo([Hr()],Oi.prototype,"autoMass",2),Uo([w()],Oi.prototype,"mass",1),Uo([Hr(),w()],Oi.prototype,"useGravity",2),Uo([w(C)],Oi.prototype,"centerOfMass",2),Uo([Hr(),w()],Oi.prototype,"constraints",2),Uo([Hr(),w()],Oi.prototype,"isKinematic",2),Uo([Hr(),w()],Oi.prototype,"drag",2),Uo([Hr(),w()],Oi.prototype,"angularDrag",2),Uo([Hr(),w()],Oi.prototype,"detectCollisions",2),Uo([Hr(),w()],Oi.prototype,"sleepThreshold",2),Uo([Hr(),w()],Oi.prototype,"collisionDetectionMode",2),Uo([Hr()],Oi.prototype,"_gravityScale",2),Uo([Hr()],Oi.prototype,"dominanceGroup",2);const Ju=te("debugsync"),AA="STRS";wB(AA,Vh.getRootAsSyncedTransformModel);const Zl=new s_;function y8(n,e,t=!0){Zl.clear();const r=Zl.createString(n);Vh.startSyncedTransformModel(Zl),Vh.addGuid(Zl,r),Vh.addFast(Zl,t);const s=e.worldPosition,o=e.worldEuler,a=e.gameObject.scale;Vh.addTransform(Zl,v8.createTransform(Zl,s.x,s.y,s.z,o.x,o.y,o.z,a.x,a.y,a.z));const l=Vh.endSyncedTransformModel(Zl);return Zl.finish(l,AA),Zl.asUint8Array()}let hk=0,bA=0;g8(n=>{var e;const t=(e=n.connection.currentServerUrl)!=null&&e.includes("glitch")?10:40;bA=Math.floor(hk/t),hk=0,Ju&&bA>0&&console.log("Sync Transform Fast Interval",bA)});class Ku extends Be{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 ii),d(this,"receivedUpdate",!1),d(this,"lastWorldPos"),d(this,"lastWorldRotation")}requestOwnership(){Ju&&console.log("Request ownership"),this._model?this._model.requestOwnership():(this._shouldRequestOwnership=!0,this._needsUpdate=!0)}hasOwnership(){var e;return((e=this._model)==null?void 0:e.hasOwnership)??void 0}isOwned(){var e;return(e=this._model)==null?void 0:e.isOwned}awake(){Ju&&console.log("new instance",this.guid,this),this._receivedDataBefore=!1,this._targetPosition=new C,this._targetRotation=new Ce,this.lastWorldPos=new C,this.lastWorldRotation=new Ce,this.rb=ie.getComponentInChildren(this.gameObject,Oi),this.rb&&(this._wasKinematic=this.rb.isKinematic),this.receivedUpdate=!0,this._model=new jB(this.context.connection,this.guid),this.context.connection.isConnected&&this.tryGetLastState(),this.joinedRoomCallback=this.tryGetLastState.bind(this),this.context.connection.beginListen(Vt.JoinedRoom,this.joinedRoomCallback),this.receivedDataCallback=this.onReceivedData.bind(this),this.context.connection.beginListenBinary(AA,this.receivedDataCallback)}onDestroy(){this.syncDestroy&&$B(this.guid,this.context.connection),this._model=null,this.context.connection.stopListen(Vt.JoinedRoom,this.joinedRoomCallback),this.context.connection.stopListenBinary(AA,this.receivedDataCallback)}tryGetLastState(){const e=this.context.connection.tryGetState(this.guid);e&&this.onReceivedData(e)}onReceivedData(e){var t;if(!this.destroyed&&typeof e.guid=="function"&&e.guid()===this.guid){Ju&&console.log("new data",this.context.connection.connectionId,this.context.time.frameCount,this.guid,e),this.receivedUpdate=!0,this._receivedFastUpdate=e.fast();const r=e.transform();if(r){Qa.markDirty(this.gameObject,!0);const s=r.position();s&&(this.interpolatePosition&&((t=this._targetPosition)==null||t.set(s.x(),s.y(),s.z())),(!this.interpolatePosition||!this._receivedDataBefore)&&this.setWorldPosition(s.x(),s.y(),s.z()));const o=r.rotation();o&&(this.tempEuler.set(o.x(),o.y(),o.z()),this.interpolateRotation&&this._targetRotation.setFromEuler(this.tempEuler),(!this.interpolateRotation||!this._receivedDataBefore)&&ER(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){Ju&&console.log("no model or room",this.name,this.guid,this.context.connection.isInRoom);return}this._shouldRequestOwnership&&(this._shouldRequestOwnership=!1,this._model.requestOwnership());const e=this.worldPosition,t=this.worldQuaternion;if(this._model.isOwned&&!this.receivedUpdate){const o=e.distanceTo(this.lastWorldPos),a=t.angleTo(this.lastWorldRotation),l=this._model.hasOwnership||this.fastMode?1e-4:.001;(o>l||a>l)&&(this._model.hasOwnership?this._needsUpdate=!0:(Ju&&console.log(this.guid,"reset because not owned but",this.gameObject.name,this.lastWorldPos),this.worldPosition=this.lastWorldPos,e.copy(this.lastWorldPos),this.worldQuaternion=this.lastWorldRotation,t.copy(this.lastWorldRotation),Qa.markDirty(this.gameObject,!0),this._needsUpdate=!1))}if(this._model&&!this._model.hasOwnership&&this._model.isOwned&&this._receivedDataBefore){const o=this._receivedFastUpdate||this.fastMode?.5:.3;let a=!1;if(this.interpolatePosition&&this._targetPosition){const l=this.worldPosition;l.lerp(this._targetPosition,o),this.worldPosition=l,a=!0}if(this.interpolateRotation&&this._targetRotation){const l=this.worldQuaternion;l.slerp(this._targetRotation,o),this.worldQuaternion=l,a=!0}a&&Qa.markDirty(this.gameObject,!0)}if(this.receivedUpdate=!1,this.lastWorldPos.copy(e),this.lastWorldRotation.copy(t),!this._model||!this._model||this._model.hasOwnership===void 0||!this._model.hasOwnership)return;this.rb&&this.overridePhysics&&this._wasKinematic!==void 0&&(Ju&&console.log("reset kinematic",this.rb.name,this._wasKinematic),this.rb.isKinematic=this._wasKinematic);const r=10,s=this.rb||this.fastMode;if(this._needsUpdate&&(this.context.time.frameCount%r===0||s)){if(hk++,s&&bA>0&&this.context.time.frameCount%bA!==0)return;Ju&&console.log("send update",this.context.connection.connectionId,this.guid,this.gameObject.name,this.gameObject.guid),this._needsUpdate=!1;const o=y8(this.guid,this,!!s);this.context.connection.sendBinary(o)}}}const Npe=te("debugshadowcomponents");pR.prototype.interactable={get(){return this.interactive},set(n){this.interactable=n}};const Ma=Symbol("shadowDomOwner");class Va extends Be{constructor(){super(...arguments),d(this,"_shadowComponent",null),d(this,"_controlsChildLayout",!0),d(this,"_root"),d(this,"_parentComponent")}isRoot(){var e;return((e=this.Root)==null?void 0:e.gameObject)===this.gameObject}get canvas(){const e=this.Root;return e!=null&&e.isCanvas?e:null}get Canvas(){return this.canvas}markDirty(){Ta.markUIDirty(this.context)}get shadowComponent(){return this._shadowComponent}set shadowComponent(e){this._shadowComponent=e}get controlsChildLayout(){return this._controlsChildLayout}set controlsChildLayout(e){this._controlsChildLayout=e,this.shadowComponent&&(this.shadowComponent.autoLayout=e)}get Root(){return this._root===void 0&&(this._root=ie.getComponentInParent(this.gameObject,_A)),this._root}__internalNewInstanceCreated(e){return super.__internalNewInstanceCreated(e),this.shadowComponent=null,this._root=void 0,this._parentComponent=void 0,this}onEnable(){super.onEnable()}addShadowComponent(e,t){var r;if(!e)return;this.removeShadowComponent();const s=this.isRoot()?this.gameObject:this.gameObject.parent;if(this._parentComponent=ie.getComponentInParent(s,Va),!this._parentComponent){console.warn(`Component "${this.name}" doesn't have a UI parent anywhere. Do you have an UI element outside a Canvas? UI components must be a child of a Canvas component`,this);return}e.name=this.name+" ("+(this.constructor.name??"UI")+")",e.autoLayout=this._parentComponent.controlsChildLayout,e[Ma]=this,this.setShadowComponentOwner(e);let o=!1;if(((r=this.Root)==null?void 0:r.gameObject)===this.gameObject)this.gameObject.add(e);else{const a=this._parentComponent.shadowComponent;a&&(a?.add(e),o=!0)}this.shadowComponent=e,t&&t.shadowComponent&&this.shadowComponent&&t.shadowComponent.add(this.shadowComponent),Wy&&e.add(new Po(.5)),this.onAfterAddedToScene(),o&&YN(),Npe&&console.warn("Added shadow component",this.shadowComponent)}setShadowComponentOwner(e){if(e&&(e[Ma]===void 0||e[Ma]===this)&&(e[Ma]=this,e.children))for(const t of e.children)this.setShadowComponentOwner(t)}traverseOwnedShadowComponents(e,t,r){if(e&&e[Ma]===t){r(e);for(const s of e.children)this.traverseOwnedShadowComponents(s,t,r)}}removeShadowComponent(){this.shadowComponent&&this.shadowComponent.removeFromParent()}onAfterAddedToScene(){}setInteractable(e){this.shadowComponent&&(this.shadowComponent.interactable=e)}}class _A extends Va{awake(){super.awake()}}class q0{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 q0(this.input,this.event);return Object.assign(e,this),e}Use(){this.use()}StopPropagation(){this.event.stopImmediatePropagation()}}function uk(n,e){return ie.foreachComponent(n,t=>{if(!t.enabled)return;const r=t;if(e)switch(e){case"pointerdown":if(r.onPointerDown)return!0;break;case"pointerup":if(r.onPointerUp||r.onPointerClick)return!0;break;case"pointermove":if(r.onPointerEnter||r.onPointerExit||r.onPointerMove)return!0;break}else if(r.onPointerDown||r.onPointerUp||r.onPointerEnter||r.onPointerExit||r.onPointerClick)return!0},!1)===!0}var zpe=Object.defineProperty,jpe=Object.getOwnPropertyDescriptor,Gpe=(n,e,t,r)=>{for(var s=r>1?void 0:r?jpe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&zpe(e,t,s),s};class xA extends Be{awake(){Ta.createIfNoneExists(this.context)}onEnable(){var e;(e=Ta.get(this.context))==null||e.register(this)}onDisable(){var e;(e=Ta.get(this.context))==null||e.unregister(this)}}class No extends xA{constructor(){super(...arguments),d(this,"targets",null),d(this,"raycastHits",[]),d(this,"ignoreSkinnedMeshes",!1)}start(){this.targets=[this.gameObject]}performRaycast(e=null){if(!this.targets)return null;e??(e=new ml),e.targets=this.targets,e.results=this.raycastHits;const t=e.testObject;this.ignoreSkinnedMeshes&&(e.testObject=s=>s instanceof uo?"continue in children":t?t(s):!0);const r=this.context.physics.raycast(e);return e.testObject=t,r}}Gpe([w()],No.prototype,"ignoreSkinnedMeshes",2);class FS extends No{constructor(){super(),this.ignoreSkinnedMeshes=!0}}class wA extends xA{performRaycast(e){if(!wt.active||!(e!=null&&e.ray))return null;const t=e.ray.origin,r=.01;return this.context.physics.sphereOverlap(t,r)}}class US{static getObject(e){const t=e[Ma];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 r=this.tryFindCanvasGroup(e);if(r?.isCanvasGroup===!0&&(t&&(t.canvasGroup=r),r.blocksRaycasts===!1||r.interactable===!1))return!1;const s=Kp(e,o=>{if(o.isGraphic===!0)return o},!1);return t&&s?.isGraphic===!0&&(t.graphic=s),!(s?.raycastTarget===!1||s?.layer===2)}static tryFindCanvasGroup(e){if(!e)return null;const t=Kp(e,r=>{const s=r;if(s.blocksRaycasts!==void 0&&s.interactable!==void 0)return s},!1);return t!==void 0?t:this.tryFindCanvasGroup(e.parent)}}function dk(n){return n[Ma]||(n.parent?dk(n.parent):null)}function Vpe(n){return n.isUI===!0||typeof n[Ma]=="object"}function NS(n,e){if(!n)return;const t=n.material;if(t?.isMaterial===!0){const r=n.parent;r&&r.isText,t.side=e.doubleSided??!0?yi:nr,t.shadowSide=e.doubleSided?yi:nr,n.castShadow=e.castShadows?e.castShadows:!1,n.receiveShadow=e.receiveShadows?e.receiveShadows:!1}for(const r of n.children)NS(r,e)}function Xg(n,e,t){n[e]===void 0&&console.warn("Field",e,"is undefined on",n);const r=Proxy.revocable(n[e],{set(a,l,c,h){const u=a[l],p=Reflect.set(a,l,c,h);return t(c,u),p}}),s=r.revoke,o=n[e];return r.revoke=()=>{n[e]=o,s()},n[e]=r.proxy,r}const A8=Symbol("Scheduled action");function Qpe(n,e,t=Hi.OnBeforeRender){let r=n[A8];r||(r=n[A8]={});const s=e.name;r[t]||(r[t]={});const o=r[t];if(o[s])return;function*a(){e?.call(n),o[s]=null}const l=n.startCoroutine(a(),t);o[s]=l}const Ah=te("debugeventsystem");var pk=(n=>(n.BeforeHandleInput="BeforeHandleInput",n.AfterHandleInput="AfterHandleInput",n))(pk||{});const bh=class extends Be{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",n=>{var e;let t=null;if(Vpe(n)&&(t=(e=n[Ma])==null?void 0:e.gameObject),this._testObjectsCache.has(n)||t&&this._testObjectsCache.has(t))return this._testObjectsCache.get(n)===!1?"continue in children":!0;{let r=uk(n,this._currentPointerEventName);if(!r&&t&&(r=uk(t,this._currentPointerEventName)),r){this._testObjectsCache.set(n,!0);for(const s of n.children)this.shouldRaycastObject_AddToYesCache(s);return!0}return this._testObjectsCache.set(n,!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",[]),bh.systems.push(this)}static createIfNoneExists(n){this.didSearchEventSystem||(this.didSearchEventSystem=!0,bh.systems.length<=0&&bh.systems.push(...ie.findObjectsOfType(bh,n)));for(const t of bh.systems)if(t.context===n)return;const e=new ye;ie.addNewComponent(e,bh),n.scene.add(e)}static get systems(){const n=kt.Current;return this._eventSystemMap.has(n)||this._eventSystemMap.set(n,[]),this._eventSystemMap.get(n)}static get(n){const e=this._eventSystemMap.get(n);return e&&e.length>0?e[0]:null}static get instance(){return this.systems[0]}static ensureUpdateMeshUI(n,e,t=!1){Zu.update(n,e,t)}static markUIDirty(n){Zu.markDirty()}get hasActiveUI(){return this.currentActiveMeshUIComponents.length>0}get isHoveringObjects(){return this.hoveredByID.size>0}onDestroy(){bh.systems.splice(bh.systems.indexOf(this),1)}start(){if(this.raycaster.length<=0&&!ie.findObjectOfType(xA,this.context)){const n=ie.addNewComponent(this.context.scene,No);this.raycaster.push(n),(st()||Ah)&&console.warn("Added an ObjectRaycaster to the scene because no raycaster was found.")}}register(n){var e;n&&this.raycaster&&!this.raycaster.includes(n)&&((e=this.raycaster)==null||e.push(n))}unregister(n){var e,t;const r=(e=this.raycaster)==null?void 0:e.indexOf(n);r!==void 0&&r!==-1&&((t=this.raycaster)==null||t.splice(r,1))}onEnable(){this._handleInputFn??(this._handleInputFn=this.onPointerEvent.bind(this)),this.context.input.addEventListener(an.PointerDown,this._handleInputFn),this.context.input.addEventListener(an.PointerUp,this._handleInputFn),this.context.input.addEventListener(an.PointerMove,this._handleInputFn)}onDisable(){this.context.input.removeEventListener(an.PointerDown,this._handleInputFn),this.context.input.removeEventListener(an.PointerUp,this._handleInputFn),this.context.input.removeEventListener(an.PointerMove,this._handleInputFn)}onBeforeRender(){this.resetMeshUIStates()}onPointerEvent(n){if(n===void 0||n.propagationStopped)return;const e=new q0(this.context.input,n);this._currentPointerEventName=n.type,e.inputSource=this.context.input,e.isClick=n.isClick,e.isDoubleClick=n.isDoubleClick,e.isDown=n.type==an.PointerDown,e.isUp=n.type==an.PointerUp,e.isPressed=this.context.input.getPointerPressed(n.pointerId),Ah&&(e.isDown?console.log("DOWN",e.pointerId):e.isUp&&console.log("UP",e.pointerId),e.isClick&&console.log("CLICK",e.pointerId));const t=new ml;n.hasRay?t.ray=n.ray:t.screenPoint=this.context.input.getPointerPositionRC(n.pointerId);const r=this.performRaycast(t);if(r){for(const o of r)o.event=n,n.intersections.push(o);n.origin.onPointerHits&&n.origin.onPointerHits({sender:this,event:n,hits:r})}Ah&&e.isClick&&rn("EventSystem: "+e.pointerId+" - "+this.context.time.frame+" - Up:"+e.isUp+", Down:"+e.isDown);const s={sender:this,args:e,hasActiveUI:this.currentActiveMeshUIComponents.length>0};this.dispatchEvent(new CustomEvent("BeforeHandleInput",{detail:s})),this.handleIntersections(r,e),this.dispatchEvent(new CustomEvent("AfterHandleInput",{detail:s}))}shouldRaycastObject_AddToYesCache(n){this._testObjectsCache.set(n,!0);for(const e of n.children)this.shouldRaycastObject_AddToYesCache(e)}performRaycast(n){if(!this.raycaster)return null;this._testObjectsCache.clear(),this._sortedHits.length=0,n||(n=new ml),n.testObject=this.shouldRaycastObject;for(const e of this.raycaster){if(!e.activeAndEnabled)continue;this._currentlyActiveRaycaster=e;const t=e.performRaycast(n);this._currentlyActiveRaycaster=null,t&&t.length>0&&this._sortedHits.push(...t)}return this._sortedHits.sort((e,t)=>e.distance-t.distance),this._sortedHits}assignHitInformation(n,e){e?(n.intersection=e,n.point=e.point,n.normal=e.normal,n.face=e.face,n.distance=e.distance,n.instanceId=e.instanceId):(n.intersection=void 0,n.point=void 0,n.normal=void 0,n.face=void 0,n.distance=void 0,n.instanceId=void 0)}handleIntersections(n,e){var t;if(n!=null&&n.length){n=this.sortCandidates(n);for(const s of n){if(e.event.immediatePropagationStopped)return!1;if(this.assignHitInformation(e,s),this.handleEventOnObject(s.object,e))return!0}}this.assignHitInformation(e,n?.[0]),this.invokePointerCapture(e);const r=this.hoveredByID.get(e.pointerId);return r&&this.propagatePointerExit(r.obj,r.data,null),this.hoveredByID.delete(e.pointerId),e.isUp&&((t=this.pressedByID.get(e.pointerId))==null||t.handlers.forEach(s=>this.invokeOnPointerUp(e,s)),this.pressedByID.delete(e.pointerId)),!1}sortCandidates(n){this._sortingBuffer.length=0,this._noDepthTestingResults.length=0;for(let e=0;e<n.length;e++){const t=n[e],r=t.object;if(r.material&&r.material.depthTest===!1){this._noDepthTestingResults.push(t);continue}this._sortingBuffer.push(t)}for(const e of this._sortingBuffer)this._noDepthTestingResults.push(e);return this._noDepthTestingResults}handleEventOnObject(n,e){if(!this.testIsVisible(n))return e.isClick&&Ah&&console.log("not allowed",n),!1;if(e.pointerId===void 0)return Ah&&console.error("Event without pointer can't be handled",e),!1;e.object=n;const t=n.parent,r=e.isClick??!1;let s=null;if(t&&t.isUI){const c=(e.isPressed||e.isClick)??!1;if(t[Ma]){const h=t[Ma].gameObject;if(h){if(!US.isInteractable(h,this.out))return!1;s=this.out.canvasGroup??null,this.handleMeshUIIntersection(n,c),n=h}}}r&&Ah&&console.log(this.context.time.frame,n);const o=this.hoveredByID.get(e.pointerId),a=o?.obj;a!==n&&a&&this.propagatePointerExit(a,o.data,n);const l=this.hoveredByID.get(e.pointerId);if(l?(l.obj=n,l.data=e):this.hoveredByID.set(e.pointerId,{obj:n,data:e}),e.isDown){const c=this.pressedByID.get(e.pointerId);c?(c.obj=n,c.data=e):this.pressedByID.set(e.pointerId,{obj:n,data:e,handlers:new Set})}return(s===null||s.interactable)&&this.handleMainInteraction(n,e,a??null),!0}propagate(n,e){for(;n;)ie.foreachComponent(n,t=>{e(t)},!1),n=n.parent}handleMainInteraction(n,e,t){const r=this.pressedByID.get(e.pointerId),s=t!==n;let o=!0;switch(e.event.pointerType){case"mouse":case"touch":const a=this.context.input.getPointerPositionLastFrame(e.pointerId),l=this.context.input.getPointerPosition(e.pointerId);o=a&&!it.approximately(a,l);break}this.propagate(n,a=>{var l;const c=a;c.interactable!==!1&&(!c.activeAndEnabled||!c.enabled||(c.onPointerEnter&&s&&this.handlePointerEnter(c,e),e.isDown&&c.onPointerDown&&(c.onPointerDown(e),r?.handlers.add(c),this.handlePointerCapture(e,c)),c.onPointerMove&&(o&&c.onPointerMove(e),this.handlePointerCapture(e,c)),e.isUp&&(c.onPointerUp&&(this.invokeOnPointerUp(e,c),r?.handlers.delete(c)),c.onPointerExit&&((l=e.event)==null?void 0:l.pointerType)===q1.Touch&&(this.handlePointerExit(c,e),this.hoveredByID.delete(e.pointerId))),e.isClick&&c.onPointerClick&&c.onPointerClick(e)))}),e.isUp&&(r?.handlers.forEach(a=>{this.invokeOnPointerUp(e,a)}),this.pressedByID.delete(e.pointerId))}propagatePointerExit(n,e,t){this.propagate(n,r=>{if(!r.gameObject||r.destroyed)return;const s=r;if(s.onPointerExit){if(t&&this.isChild(t,r.gameObject))return;this.handlePointerExit(s,e)}})}invokeOnPointerUp(n,e){var t;(t=e.onPointerUp)==null||t.call(e,n),this.releasePointerCapture(n,e)}handlePointerEnter(n,e){n.onPointerEnter&&this.updatePointerState(n,e.pointerId,this.pointerEnterSymbol,!0)&&n.onPointerEnter(e),this.updatePointerState(n,e.pointerId,this.pointerExitSymbol,!1)}handlePointerExit(n,e){n.onPointerExit&&this.updatePointerState(n,e.pointerId,this.pointerExitSymbol,!0)&&n.onPointerExit(e),this.updatePointerState(n,e.pointerId,this.pointerEnterSymbol,!1)}updatePointerState(n,e,t,r){let s=n[t];if(r)return s&&s.includes(e)?!1:(s=s||[],s.push(e),n[t]=s,!0);{if(!s||!s.includes(e))return!1;const o=s.indexOf(e);return o!==-1&&s.splice(o,1),!0}}handlePointerCapture(n,e){if(n.z__pointer_ctured){n.z__pointer_ctured=!1;const t=n.pointerId;if(e.onPointerMove){const r=this._capturedPointer[t]||[];r.push(e),this._capturedPointer[t]=r}else st()&&!e.z__warned_no_pointermove&&(e.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 n.z__pointer_cture_rleased&&(n.z__pointer_cture_rleased=!1,this.releasePointerCapture(n,e))}releasePointerCapture(n,e){const t=n.pointerId;if(this._capturedPointer[t]){const r=this._capturedPointer[t].indexOf(e);r!==-1&&(this._capturedPointer[t].splice(r,1),Ah&&console.log("released pointer capture",t,e,this._capturedPointer))}}invokePointerCapture(n){var e;if(n.event.type===an.PointerMove){const t=n.pointerId,r=this._capturedPointer[t];if(r){Ah&&console.log("Captured",t,r);for(let s=0;s<r.length;s++){const o=r[s];if(o.destroyed){r.splice(s,1),s--;continue}(e=o.onPointerMove)==null||e.call(o,n)}}}}isChild(n,e){return!n||!e?!1:n===e?!0:n.parent?this.isChild(n.parent,e):!1}handleMeshUiObjectWithoutShadowDom(n,e){return!n||!n.isUI?!0:this.handleMeshUIIntersection(n,e)}handleMeshUIIntersection(n,e){const t=Zu.updateState(n,e);return t&&this.currentActiveMeshUIComponents.push(t),t!==null}resetMeshUIStates(){if(this.context.input.getPointerPressedCount()>0&&Zu.resetLastSelected(),!(!this.currentActiveMeshUIComponents||this.currentActiveMeshUIComponents.length<=0)){for(let n=0;n<this.currentActiveMeshUIComponents.length;n++){const e=this.currentActiveMeshUIComponents[n];Zu.resetState(e)}this.currentActiveMeshUIComponents.length=0}}testIsVisible(n){return n?ie.isActiveSelf(n)?this.testIsVisible(n.parent):!1:!0}};let Ta=bh;d(Ta,"_eventSystemMap",new Map),d(Ta,"didSearchEventSystem",!1);class Zu{static markDirty(){this.needsUpdate=!0}static update(e,t,r=!1){if(r){e.update();return}const s=t.time.frameCount;for(const o of this.lastUpdateFrame)if(o.context===t){if(s===o.frame)return;o.frame=s;let a=this.needsUpdate||s<1;o.nextUpdate===t.time.frameCount&&(a=!0),a&&(Ah&&console.log("Update threemeshui"),this.needsUpdate=!1,e.update());return}this.lastUpdateFrame=[{context:t,frame:s,nextUpdate:s}],e.update()}static updateState(e,t){let r=null;if(e&&(r=this.findBlockInParent(e),r&&r!==this.lastSelected)){if(r.interactable===!1)return null;this.needsUpdate=!0}return r}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 Hpe=Object.defineProperty,Wpe=Object.getOwnPropertyDescriptor,ln=(n,e,t,r)=>{for(var s=r>1?void 0:r?Wpe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&Hpe(e,t,s),s};const mk=te("debugorbit"),zS=te("freecam"),jS=te("debugcamerafit"),GS=te("smoothcam"),Xpe={LEFT:"",UP:"",RIGHT:"",BOTTOM:""};let fk;class SA extends CustomEvent{constructor(e,t){super("target-reached",{detail:{controls:e,type:t}})}}class bi extends Be{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 C),d(this,"_lookTargetEndPosition",new C),d(this,"_lookTargetLerp01",0),d(this,"_lookTargetLerpDuration",0),d(this,"_cameraLerpActive",!1),d(this,"_cameraStartPosition",new C),d(this,"_cameraEndPosition",new C),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",e=>{if(this.clickBackgroundToFitScene>0&&e.isClick&&e.button===0){if(e.hasRay||e.intersections.push(...this.context.physics.raycast()),e.intersections.length<=0){const t=this.context.time.time-this._lastTimeClickOnBackground;this._lastTimeClickOnBackground=this.context.time.time,this.clickBackgroundToFitScene<=1||t<this.clickBackgroundToFitScene*.15?(this._clickOnBackgroundCount+=1,this._clickOnBackgroundCount>=this.clickBackgroundToFitScene-1&&this.fitCamera(this.context.scene.children,{immediate:!1})):this._clickOnBackgroundCount=0}mk&&console.log(this.clickBackgroundToFitScene,e.intersections.length,this._clickOnBackgroundCount)}}),d(this,"onControlsChangeStarted",()=>{this._syncedTransform&&this._syncedTransform.requestOwnership()}),d(this,"_shouldDisable",!1),d(this,"__onPreRender",()=>{const e=this.context.pre_render_callbacks.indexOf(this.__onPreRender);e>=0&&this.context.pre_render_callbacks.splice(e,1),this.autoFit&&(this.autoFit=!1,this.fitCamera(this.scene.children,{centerCamera:"y",immediate:!0}))}),d(this,"_haveAttachedKeyboardEvents",!1)}get isCameraController(){return!0}get controls(){return this._controls}get controllerObject(){return this._cameraObject}onStartInteraction(e){var t;(t=this.controls)==null||t.addEventListener("start",e)}get targetLerpSpeed(){return 5}set targetLerpSpeed(e){this.targetLerpDuration=1/e}awake(){this._didSetTarget=0,this._startedListeningToKeyEvents=!1}start(){this._eventSystem=Ta.get(this.context)??void 0,this._eventSystem&&(this._afterHandleInputFn=this.afterHandleInput.bind(this),this._eventSystem.addEventListener(pk.AfterHandleInput,this._afterHandleInputFn))}onDestroy(){var e,t;(e=this._controls)==null||e.dispose(),(t=this._eventSystem)==null||t.removeEventListener(pk.AfterHandleInput,this._afterHandleInputFn)}onEnable(){this._didSetTarget=0,this._enableTime=this.context.time.time;const e=ie.getComponent(this.gameObject,Li);this._camera=e;let t=e?.cam;if(!t&&this.gameObject instanceof Lt&&(t=this.gameObject),t&&vR(t,this,!0),!this._controls&&t instanceof Lt){this._cameraObject=t;const r=this.targetElement??this.context.renderer.domElement,s=t?.quaternion.clone();this._controls=new p8(t,r),t?.quaternion.copy(s),fk===void 0&&(fk={...this._controls.keys})}this._controls&&(zS&&(this.enablePan=!0,this.enableZoom=!0,this.middleClickToFocus=!0,aa()&&(this.doubleClickToFocus=!0)),this._controls.addEventListener("start",this.onControlsChangeStarted),t?.type==="PerspectiveCamera"?zS||(this._controls.minDistance=this.minZoom,this._controls.maxDistance=this.maxZoom):zS||(this._controls.minZoom=this.minZoom,this._controls.maxZoom=this.maxZoom),this._startedListeningToKeyEvents||(this._startedListeningToKeyEvents=!0,this._controls.listenToKeyEvents(window.document.body))),this._syncedTransform=ie.getComponent(this.gameObject,Ku)??void 0,this.context.input.addEventListener("pointerup",this._onPointerDown),this.context.pre_render_callbacks.push(this.__onPreRender)}onDisable(){var e;(e=this._camera)!=null&&e.cam&&vR(this._camera.cam,this,!1),this._controls&&(this._controls.enabled=!1,this._controls.autoRotate=!1,this._controls.removeEventListener("start",this.onControlsChangeStarted)),this.context.input.removeEventListener("pointerup",this._onPointerDown)}afterHandleInput(e){e.detail.args.pointerId===0&&(e.detail.args.isDown?this._controls&&this._eventSystem&&(this._shouldDisable=this._eventSystem.hasActiveUI):(!e.detail.args.isPressed||e.detail.args.isUp)&&(this._shouldDisable=!1))}onBeforeRender(){var e,t;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)&&(e=this.context.input.getPointerPositionDelta(0))!=null&&e.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 s=ie.getComponent(this.gameObject,Li);if(s&&!this.setLookTargetFromConstraint()){this.debugLog&&console.log("NO TARGET");const o=Bt(s.cam),a=Math.max(.01,o.length()),l=new C(0,0,-a).applyMatrix4(s.cam.matrixWorld);this.setLookTargetPosition(l,!0)}if(!this.setLookTargetFromConstraint()){const o=new ml;o.screenPoint=new Z(0,0),o.lineThreshold=.1;const a=this.context.physics.raycast(o);a.length>0&&this.setLookTargetPosition(a[0].point,!0),jS&&console.log("OrbitControls hits",...a)}}let r=this.middleClickToFocus&&this.context.input.getPointerClicked(1);if(r||(r=this.doubleClickToFocus&&this.context.input.getPointerDoubleClicked(0)&&this.context.time.time-this._enableTime>.3),r&&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 SA(this,"camera"));else{const s=it.easeInOutCubic(this._cameraLerp01);this._cameraObject.position.lerpVectors(this._cameraStartPosition,this._cameraEndPosition,s)}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 SA(this,"lookat"));else{const s=it.easeInOutCubic(this._lookTargetLerp01);this._controls.target.lerpVectors(this._lookTargetStartPosition,this._lookTargetEndPosition,s)}}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?fk:Xpe,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 GS=="number"||GS===!0){this._controls.enableDamping=!0;const s=typeof GS=="number"?GS:.99;this._controls.dampingFactor=Math.max(.001,1-Math.min(1,s))}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||(!zS&&(t=this.lookAtConstraint)!=null&&t.locked&&this.setLookTargetFromConstraint(0,this.lookAtConstraint01),this._controls.update(),mk&&At.DrawWireSphere(this._controls.target,.1,65280))}}setCameraAndLookTarget(e){if(!e||!(e instanceof ye))return;const t=Bt(e),r=SR(e);this.setTargetFromRaycast(new co(t,r)),this.setCameraTargetPosition(t)}setCameraTargetPosition(e,t=!1){var r,s;e&&(e instanceof ye&&(e=Bt(e)),this._cameraEndPosition||(this._cameraEndPosition=new C),this._cameraEndPosition.copy(e),t===!0?(this._cameraLerpActive=!1,(r=this.controllerObject)==null||r.position.copy(this._cameraEndPosition)):this._cameraObject&&(this._cameraLerpActive=!0,this._cameraLerp01=0,this._cameraStartPosition.copy((s=this._cameraObject)==null?void 0:s.position),typeof t=="number"?this._cameraLerpDuration=t:this._cameraLerpDuration=this.targetLerpDuration))}get cameraLerpActive(){return this._cameraLerpActive}stopCameraLerp(){this._cameraLerpActive=!1}setLookTargetPosition(e=null,t=!1){this._controls&&e&&(e instanceof ye&&(e=Bt(e)),this._lookTargetEndPosition.copy(e),mk&&(console.warn("OrbitControls: setLookTargetPosition",e,t),At.DrawWireSphere(this._lookTargetEndPosition,.2,16711680,2)),t===!0?this._controls.target.copy(this._lookTargetEndPosition):(this._lookTargetLerpActive=!0,this._lookTargetLerp01=0,this._lookTargetStartPosition.copy(this._controls.target),typeof t=="number"?this._lookTargetLerpDuration=t:this._lookTargetLerpDuration=this.targetLerpDuration))}get lookTargetLerpActive(){return this._lookTargetLerpActive}stopLookTargetLerp(){this._lookTargetLerpActive=!1}setLookTargetFromConstraint(e=0,t=1){var r;if(!this._controls)return!1;const s=(r=this.lookAtConstraint)==null?void 0:r.sources;if(s&&s.length>0){const o=s[e];if(o)return o.getWorldPosition(this._lookTargetEndPosition),this.lerpLookTarget(this._lookTargetEndPosition,t),!0}return!1}lerpTarget(e,t){return this.lerpLookTarget(e,t)}lerpLookTarget(e,t){this._controls&&(t>=1?this._controls.target.copy(e):this._controls.target.lerp(e,t))}setTargetFromRaycast(e){if(!this.controls)return;const t=e?this.context.physics.raycastFromRay(e):this.context.physics.raycast();for(const r of t)if(r.distance>0&&ie.isActiveInHierarchy(r.object)){const s=dk(r.object);if(s){const o=s.canvas;if(o!=null&&o.screenspace)break}this.setLookTargetPosition(r.point);break}}fitCamera(e,t={fitOffset:void 0,immediate:!1}){if(this.context.isInXR)return;const{immediate:r=!1,centerCamera:s}=t;let{fitOffset:o}=t;o==null&&(o=1.1);const a=this._cameraObject,l=this._controls;if(e!=null&&e.length||(e=this.context.scene.children),e.length<=0){console.warn("No objects to fit camera to...");return}if(!a||!l){console.warn("No camera or controls found to fit camera to objects...");return}const c=new C,h=new C,u=Ul(e,void 0);a.updateMatrixWorld(),a.updateProjectionMatrix(),u.getCenter(h);const p=new C;if(u.getSize(p),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,[...e]);return}if(c.length()<=1e-10){jS&&console.warn("Camera fit size is zero",u,[...e]);return}const m=a.fov,f=2*Math.atan(Math.tan(m*Math.PI/360/2)*a.aspect)/Math.PI*360,g=c.y/(2*Math.atan(Math.PI*m/360)),v=c.x/(2*Math.atan(Math.PI*f/360)),y=o*Math.max(g,v)+c.z/2;jS&&console.log("Fit camera to objects",g,v,"distance",y),l.maxDistance=y*10,l.minDistance=y*.01;const A=.05,_=h.clone();_.y-=c.y*A,this.setLookTargetPosition(_,r),this.autoTarget=!1;const b=ie.findObjectOfType(Yu),x=b?b.radius:0,E=Math.max(p.x,p.y,p.z,x);a.near=y/100,a.far=E+y*10,a.updateMatrixWorld(),a.updateProjectionMatrix();const I=Bt(a),T=h.clone();if(T.sub(I),s==="y"&&(T.y=0),T.normalize(),T.multiplyScalar(y),s==="y"&&(T.y+=-A*4*c.y),a.parent){const R=a.parent.worldToLocal(h.clone().sub(T));this.setCameraTargetPosition(R,r)}else console.error(`Can not fit camera ${a.name} because it has no parent`);if(jS){const R=new wI(u);this.context.scene.add(R),MR(R,Wv(a)),setTimeout(()=>{this.context.scene.remove(R)},1e4),this._haveAttachedKeyboardEvents||(this._haveAttachedKeyboardEvents=!0,document.body.addEventListener("keydown",D=>{D.code==="KeyF"&&this.fitCamera(e,{fitOffset:o,immediate:r})}))}l.update()}}ln([w()],bi.prototype,"autoTarget",2),ln([w()],bi.prototype,"autoFit",2),ln([w()],bi.prototype,"enableRotate",2),ln([w()],bi.prototype,"autoRotate",2),ln([w()],bi.prototype,"autoRotateSpeed",2),ln([w()],bi.prototype,"minAzimuthAngle",2),ln([w()],bi.prototype,"maxAzimuthAngle",2),ln([w()],bi.prototype,"minPolarAngle",2),ln([w()],bi.prototype,"maxPolarAngle",2),ln([w()],bi.prototype,"enableKeys",2),ln([w()],bi.prototype,"enableDamping",2),ln([w()],bi.prototype,"dampingFactor",2),ln([w()],bi.prototype,"enableZoom",2),ln([w()],bi.prototype,"minZoom",2),ln([w()],bi.prototype,"maxZoom",2),ln([w()],bi.prototype,"zoomSpeed",2),ln([w()],bi.prototype,"enablePan",2),ln([w(nm)],bi.prototype,"lookAtConstraint",2),ln([w()],bi.prototype,"lookAtConstraint01",2),ln([w()],bi.prototype,"allowInterrupt",2),ln([w()],bi.prototype,"middleClickToFocus",2),ln([w()],bi.prototype,"doubleClickToFocus",2),ln([w()],bi.prototype,"clickBackgroundToFitScene",2),ln([w()],bi.prototype,"targetLerpDuration",2);var qpe=Object.defineProperty,Ype=Object.getOwnPropertyDescriptor,$s=(n,e,t,r)=>{for(var s=r>1?void 0:r?Ype(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&qpe(e,t,s),s},$u=(n=>(n[n.Skybox=1]="Skybox",n[n.SolidColor=2]="SolidColor",n[n.Uninitialized=4]="Uninitialized",n))($u||{});const _h=te("debugcam"),b8=te("debugscreenpointtoray");var VS;const CA=(VS=class extends Be{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 ve)}get isCamera(){return!0}get aspect(){return this._cam instanceof Lt?this._cam.aspect:this.context.domWidth/this.context.domHeight}set aspect(n){this._cam instanceof Lt&&this._cam.aspect!==n&&(this._cam.aspect=n,this._cam.updateProjectionMatrix())}get fieldOfView(){return this._cam instanceof Lt?this._cam.fov:this._fov}set fieldOfView(n){const e=this.fieldOfView!=n;if(this._fov=n,e&&this._cam&&this._cam instanceof Lt){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(n){const e=this._nearClipPlane!=n;this._nearClipPlane=n,this._cam&&e&&(this._cam.near=n,this._cam.updateProjectionMatrix())}get farClipPlane(){return this._farClipPlane}set farClipPlane(n){const e=this._farClipPlane!=n;this._farClipPlane=n,this._cam&&e&&(this._cam.far=n,this._cam.updateProjectionMatrix())}get clearFlags(){return this._clearFlags}set clearFlags(n){n!==this._clearFlags&&(this._clearFlags=n,this.applyClearFlagsIfIsActiveCamera())}set cullingMask(n){this._cullingMask=n,this._cam&&(this._cam.layers.mask=n)}get cullingMask(){return this._cam?this._cam.layers.mask:this._cullingMask}set cullingLayer(n){this.cullingMask=(1<<n|0)>>>0}set backgroundBlurriness(n){n!==this._backgroundBlurriness&&(n===void 0?this._backgroundBlurriness=void 0:this._backgroundBlurriness=Math.min(Math.max(n,0),1),this.applyClearFlagsIfIsActiveCamera())}get backgroundBlurriness(){return this._backgroundBlurriness}set backgroundIntensity(n){n!==this._backgroundIntensity&&(n===void 0?this._backgroundIntensity=void 0:this._backgroundIntensity=Math.min(Math.max(n,0),10),this.applyClearFlagsIfIsActiveCamera())}get backgroundIntensity(){return this._backgroundIntensity}set backgroundRotation(n){n!==this._backgroundRotation&&(n===void 0?this._backgroundRotation=void 0:this._backgroundRotation=n,this.applyClearFlagsIfIsActiveCamera())}get backgroundRotation(){return this._backgroundRotation}set environmentIntensity(n){this._environmentIntensity=n}get environmentIntensity(){return this._environmentIntensity}get backgroundColor(){return this._backgroundColor??null}set backgroundColor(n){if(n){if(this._backgroundColor)this._backgroundColor.copy(n);else{if(!n.clone)return;this._backgroundColor=n.clone()}n.alpha===void 0&&(this._backgroundColor.alpha=1),this.applyClearFlagsIfIsActiveCamera()}}set targetTexture(n){this._targetTexture=n}get targetTexture(){return this._targetTexture}get cam(){return this.activeAndEnabled&&this.buildCamera(),this._cam}screenPointToRay(n,e,t){const r=this.cam,s=CA._origin;s.set(n,e,-1),this.context.input.convertScreenspaceToRaycastSpace(s),b8&&console.log("screenPointToRay",n.toFixed(2),e.toFixed(2),"now:",s.x.toFixed(2),s.y.toFixed(2),"isInXR:"+this.context.isInXR),s.z=-1,s.unproject(r);const o=CA._direction.set(s.x,s.y,s.z),a=Bt(r);return o.sub(a),o.normalize(),t?(t.set(a,o),t):new co(a.clone(),o.clone())}getFrustum(){return this._frustum||(this._frustum=new Yd,this.updateFrustum()),this._frustum}updateFrustum(){this._frustum||(this._frustum=new Yd),this._frustum.setFromProjectionMatrix(this.getProjectionScreenMatrix(this._projScreenMatrix,!0),this.context.renderer.coordinateSystem)}getProjectionScreenMatrix(n,e){return e&&this._projScreenMatrix.multiplyMatrices(this.cam.projectionMatrix,this.cam.matrixWorldInverse),n===this._projScreenMatrix?n:n.copy(this._projScreenMatrix)}awake(){b8&&window.addEventListener("pointerdown",n=>{const e=n.clientX,t=n.clientY;console.log("touch",e.toFixed(2),t.toFixed(2));const r=this.screenPointToRay(e,t),s="#"+Math.floor(Math.random()*16777215).toString(16);At.DrawRay(r.origin,r.direction,s,10)})}onEnable(){_h&&console.log(`Camera enabled: "${this.name}". ClearFlags=${$u[this._clearFlags]}`,this),this.buildCamera(),(this.tag=="MainCamera"||!this.context.mainCameraComponent)&&(this.context.setCurrentCamera(this),Kpe(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 n=this.context.renderer;if(n){const e=this.context.mainCameraComponent;this.applyClearFlags(),this._targetTexture.render(this.context.scene,this._cam,n),e?.applyClearFlags()}}}buildCamera(){if(this._cam)return;const n=this.gameObject.isCamera;let e=null;if(n?(e=this.gameObject,e?.layers.enableAll(),e instanceof Lt&&(this._fov=e.fov)):e=this.gameObject.children[0],e&&e.isCamera)e instanceof Lt&&(this._fov&&(e.fov=this._fov),e.near=this._nearClipPlane,e.far=this._farClipPlane,e.updateProjectionMatrix());else if(!this.orthographic)e=new Lt(this.fieldOfView,window.innerWidth/window.innerHeight,this._nearClipPlane,this._farClipPlane),this.fieldOfView&&(e.fov=this.fieldOfView),this.gameObject.add(e);else{const t=this.orthographicSize*100;e=new Bl(window.innerWidth/-t,window.innerWidth/t,window.innerHeight/t,window.innerHeight/-t,this._nearClipPlane,this._farClipPlane),this.gameObject.add(e)}this._cam=e,this._cam.layers.mask=this._cullingMask,this.tag=="MainCamera"&&this.context.setCurrentCamera(this)}applyClearFlagsIfIsActiveCamera(n){this.context.mainCameraComponent===this&&this.applyClearFlags(n)}applyClearFlags(n){if(!this._cam){_h&&console.log("Camera does not exist (apply clear flags)");return}if(this.fieldOfView=this._fov,_h){const e=`Camera "${this.name}" clear flags: ${$u[this._clearFlags]}`;console.debug(e)}switch(this._clearFlags){case 1:if(CA.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||n?.applySkybox===!0)&&this.applySceneSkybox(),this._backgroundBlurriness!==void 0?this.context.scene.backgroundBlurriness=this._backgroundBlurriness:_h&&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:_h&&console.warn(`Camera "${this.name}" has no background intensity`);break;case 2:if(this._backgroundColor){let e=this._backgroundColor.alpha;CA.backgroundShouldBeTransparent(this.context)&&(e=this.ARBackgroundAlpha??0),this.context.scene.background=null,this.context.renderer.setClearColor(this._backgroundColor,e)}else _h&&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 Jpe(this)),this._skybox.apply()}static backgroundShouldBeTransparent(n){var e,t,r,s;const o=(e=n.renderer.xr)==null?void 0:e.getSession();if(!o)return!1;if(typeof o._transparent=="boolean")return o._transparent;const a=o.environmentBlendMode;_h&&rn("Environment blend mode: "+a+" on "+navigator.userAgent);let l=a==="additive"||a==="alpha-blend";return n.isInAR&&a==="opaque"&&((t=navigator.userAgent)!=null&&t.includes("OculusBrowser")||(r=navigator.userAgent)!=null&&r.includes("Mozilla")&&(s=navigator.userAgent)!=null&&s.includes("Mobile WebXRViewer/v2"))&&(l=!0),o._transparent=l,l}},d(VS,"_origin",new C),d(VS,"_direction",new C),VS);let Li=CA;$s([w()],Li.prototype,"aspect",1),$s([w()],Li.prototype,"fieldOfView",1),$s([w()],Li.prototype,"nearClipPlane",1),$s([w()],Li.prototype,"farClipPlane",1),$s([w()],Li.prototype,"clearFlags",1),$s([w()],Li.prototype,"orthographic",2),$s([w()],Li.prototype,"orthographicSize",2),$s([w()],Li.prototype,"ARBackgroundAlpha",2),$s([w()],Li.prototype,"cullingMask",1),$s([w()],Li.prototype,"backgroundBlurriness",1),$s([w()],Li.prototype,"backgroundIntensity",1),$s([w(ii)],Li.prototype,"backgroundRotation",1),$s([w()],Li.prototype,"environmentIntensity",1),$s([w(Si)],Li.prototype,"backgroundColor",1),$s([w(Hg)],Li.prototype,"targetTexture",1);class Jpe{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&&(_h&&console.log(`Camera "${this._camera.name}" set skybox`,this._camera,this._skybox),this._skybox.mapping=so,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)),(_h||st())&&Di(`Camera "${this._camera.name}" has no skybox texture`))}}function Kpe(n){te("freecam")&&n.context.mainCameraComponent===n&&ie.getOrAddComponent(n.gameObject,bi)}class ed extends Be{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 pU),this._listener}onEnable(){Qu.registerWaitForInteraction(this.onInteraction),this.addListenerIfItExists()}onDisable(){Qu.unregisterWaitForInteraction(this.onInteraction),this.removeListenerIfItExists()}addListenerIfItExists(){const e=this._listener;if(!e||e!=null&&e.parent)return;const t=this.context.mainCameraComponent||ie.getComponentInParent(this.gameObject,Li);t!=null&&t.cam?t.cam.add(e):this.gameObject.add(e),e.filter?(e.gain.connect(e.filter),e.filter.connect(e.context.destination)):e.gain.connect(e.context.destination)}removeListenerIfItExists(){const e=this._listener;e&&(e.removeFromParent(),e.filter&&e.filter.disconnect(),e.gain&&e.gain.disconnect())}}class Zpe extends Sn{constructor(e,t=1,r=16,s=2){const o=new yt,a=r+s*2,l=new Float32Array((a*3+3)*3);o.setAttribute("position",new nt(l,3));const c=new Gi({color:65280}),h=new Gi({color:16776960});super(o,[h,c]),this.audio=e,this.range=t,this.divisionsInnerAngle=r,this.divisionsOuterAngle=s,this.type="PositionalAudioHelper",this.update()}update(){const e=this.audio,t=this.range,r=this.divisionsInnerAngle,s=this.divisionsOuterAngle,o=ui.degToRad(e.panner.coneInnerAngle),a=ui.degToRad(e.panner.coneOuterAngle),l=o/2,c=a/2;let h=0,u=0,p,m;const f=this.geometry,g=f.attributes.position;f.clearGroups();function v(y,A,_,b){const x=(A-y)/_;for(g.setXYZ(h,0,0,0),u++,p=y;p<A;p+=x)m=h+u,g.setXYZ(m,Math.sin(p)*t,0,Math.cos(p)*t),g.setXYZ(m+1,Math.sin(Math.min(p+x,A))*t,0,Math.cos(Math.min(p+x,A))*t),g.setXYZ(m+2,0,0,0),u+=3;f.addGroup(h,u,b),h+=u,u=0}v(-c,-l,s,0),v(-l,l,r,1),v(l,c,s,0),g.needsUpdate=!0,o===a&&(this.material[0].visible=!1)}dispose(){this.geometry.dispose(),this.material[0].dispose(),this.material[1].dispose()}}var $pe=Object.defineProperty,eme=Object.getOwnPropertyDescriptor,$l=(n,e,t,r)=>{for(var s=r>1?void 0:r?eme(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&$pe(e,t,s),s};const Ms=te("debugaudio"),td=class extends Be{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||aa())&&(this.wasPlaying=this.isPlaying,this.isPlaying&&this.pause());break;case"visible":Ms&&console.log("visible",this.enabled,this.playOnAwake,!this.isPlaying,td.userInteractionRegistered,this.wasPlaying),this.enabled&&this.playOnAwake&&!this.isPlaying&&td.userInteractionRegistered&&this.wasPlaying&&this.play();break}}),d(this,"onApplicationMuteChanged",()=>{var n,e;this.context.application.muted?(n=this.sound)==null||n.setVolume(0):(e=this.sound)==null||e.setVolume(this.volume)}),d(this,"createAudio",n=>{Ms&&console.log("AudioBuffer finished loading",n);const e=this.Sound;if(!e){Ms&&console.warn("Failed getting sound?",this.name);return}e.isPlaying&&e.stop(),n&&e.setBuffer(n),e.loop=this._loop,this.context.application.muted?e.setVolume(0):e.setVolume(this.volume),e.autoplay=this.shouldPlay&&td.userInteractionRegistered,this.applySpatialDistanceSettings(),e.isPlaying&&e.stop(),td.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 Qu.userInteractionRegistered}static registerWaitForAllowAudio(n){Qu.registerWaitForAllowAudio(n)}get loop(){return this.sound&&(this._loop=this.sound.getLoop()),this._loop}set loop(n){this._loop=n,this.sound&&this.sound.setLoop(n)}get spatialBlend(){return this._spatialBlend}set spatialBlend(n){n!==this._spatialBlend&&(this._spatialBlend=n,this._needUpdateSpatialDistanceSettings=!0)}get minDistance(){return this._minDistance}set minDistance(n){this._minDistance!==n&&(this._minDistance=n,this._needUpdateSpatialDistanceSettings=!0)}get maxDistance(){return this._maxDistance}set maxDistance(n){this._maxDistance!==n&&(this._maxDistance=n,this._needUpdateSpatialDistanceSettings=!0)}get volume(){return this._volume}set volume(n){this._volume=n,this.sound&&!this.context.application.muted&&(Ms&&console.log(this.name,"audio set volume",n),this.sound.setVolume(n))}get Sound(){var n;if(!this.sound&&td.userInteractionRegistered){let e=ie.getComponent(this.context.mainCamera,ed)??ie.findObjectOfType(ed,this.context);!e&&this.context.mainCamera&&(e=ie.addNewComponent(this.context.mainCamera,ed)),e!=null&&e.listener?(this.sound=new fU(e.listener),(n=this.gameObject)==null||n.add(this.sound)):Ms&&console.warn("No audio listener found in scene - can not play audio")}return this.sound}get ShouldPlay(){return this.shouldPlay}get audioContext(){var n;return(n=this.sound)==null?void 0:n.context}awake(){Ms&&console.log(this),this.audioLoader=new Nx,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),td.userInteractionRegistered?this.playOnAwake&&this.context.application.isVisible&&this.play():td.registerWaitForAllowAudio(()=>{this.enabled&&!this.destroyed&&this.shouldPlay&&this.onNewClip(this.clip)}),globalThis.addEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.addEventListener(cS.MuteChanged,this.onApplicationMuteChanged)}onDisable(){globalThis.removeEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.removeEventListener(cS.MuteChanged,this.onApplicationMuteChanged),this.pause()}applySpatialDistanceSettings(){const n=this.sound;if(!n)return;this._needUpdateSpatialDistanceSettings=!1;const e=it.lerp(10*this._maxDistance/Math.max(1e-4,this.spatialBlend),this._minDistance,this.spatialBlend);switch(Ms&&console.log(this.name,this._minDistance,this._maxDistance,this.spatialBlend,"Ref distance="+e),n.setRefDistance(e),n.setMaxDistance(Math.max(.01,this._maxDistance)),this.rollOffMode){case 0:n.setDistanceModel("exponential");break;case 1:n.setDistanceModel("linear");break;case 2:console.warn("Custom rolloff for AudioSource is not supported: "+this.name);break}this.spatialBlend>0?Ms&&!this.helper&&(this.helper=new Zpe(n,n.getRefDistance()),n.add(this.helper)):this.helper&&this.helper.parent&&this.helper.removeFromParent()}async onNewClip(n){if(n&&(this.clip=n),typeof n=="string")if(Ms&&console.log(n),n.endsWith(".mp3")||n.endsWith(".wav")){if(this.audioLoader||(this.audioLoader=new Nx),this.shouldPlay=!0,this._lastClipStartedLoading===n){Ms&&console.log("Is currently loading:",this._lastClipStartedLoading,this);return}this._lastClipStartedLoading=n,Ms&&console.log("load audio",n);const e=await this.audioLoader.loadAsync(n).catch(console.error);this._lastClipStartedLoading=null,e&&this.createAudio(e)}else console.warn("Unsupported audio clip type",n);else this.shouldPlay=!0,this.createAudio()}play(n=void 0){var e,t,r;!n&&this.clip&&(n=this.clip),n!==void 0&&typeof n!="string"&&!(n instanceof MediaStream)&&(st()&&console.warn("Called play on AudioSource with unknown argument type:",n+`
|
|
5732
|
+
`;var Mpe=Object.defineProperty,Tpe=Object.getOwnPropertyDescriptor,ak=(n,e,t,r)=>{for(var s=r>1?void 0:r?Tpe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&Mpe(e,t,s),s};class nm extends Be{constructor(){super(...arguments),d(this,"constraintActive",!0),d(this,"locked",!1),d(this,"sources",[])}}ak([w()],nm.prototype,"constraintActive",2),ak([w()],nm.prototype,"locked",2),ak([w(ye)],nm.prototype,"sources",2);function Ipe(n,e){return Nu(n,Ci.ContextCreated,e),()=>zu(n,Ci.ContextCreated)}function Rpe(n,e){return Nu(n,Ci.ContextClearing,e),()=>zu(n,Ci.ContextClearing)}function Ppe(n,e){return Nu(n,Ci.ContextDestroying,e),()=>zu(n,Ci.ContextDestroying)}function f8(n,e){return Nu(n,Hi.Start,e),()=>zu(n,Hi.Start)}function g8(n,e){return Nu(n,Hi.Update,e),()=>zu(n,Hi.Update)}function Bpe(n,e){return Nu(n,Hi.OnBeforeRender,e),()=>zu(n,Hi.OnBeforeRender)}function kpe(n,e){return Nu(n,Hi.OnAfterRender,e),()=>zu(n,Hi.OnAfterRender)}class rm{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,r,s){return e.prep(4,12),e.writeFloat32(s),e.writeFloat32(r),e.writeFloat32(t),e.offset()}}class v8{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 rm).__init(this.bb_pos,this.bb)}rotation(e){return(e||new rm).__init(this.bb_pos+12,this.bb)}scale(e){return(e||new rm).__init(this.bb_pos+24,this.bb)}static sizeOf(){return 36}static createTransform(e,t,r,s,o,a,l,c,h,u){return e.prep(4,36),e.prep(4,12),e.writeFloat32(u),e.writeFloat32(h),e.writeFloat32(c),e.prep(4,12),e.writeFloat32(l),e.writeFloat32(a),e.writeFloat32(o),e.prep(4,12),e.writeFloat32(s),e.writeFloat32(r),e.writeFloat32(t),e.offset()}}class Vh{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 Vh).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSyncedTransformModel(e,t){return e.setPosition(e.position()+bB),(t||new Vh).__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 v8).__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 Cr=(n=>(n[n.Average=0]="Average",n[n.Multiply=1]="Multiply",n[n.Minimum=2]="Minimum",n[n.Maximum=3]="Maximum",n))(Cr||{}),LS=(n=>(n[n.Discrete=0]="Discrete",n[n.Continuous=1]="Continuous",n))(LS||{}),Nn=(n=>(n[n.None=0]="None",n[n.FreezePositionX=2]="FreezePositionX",n[n.FreezePositionY=4]="FreezePositionY",n[n.FreezePositionZ=8]="FreezePositionZ",n[n.FreezePosition=14]="FreezePosition",n[n.FreezeRotationX=16]="FreezeRotationX",n[n.FreezeRotationY=32]="FreezeRotationY",n[n.FreezeRotationZ=64]="FreezeRotationZ",n[n.FreezeRotation=112]="FreezeRotation",n[n.FreezeAll=126]="FreezeAll",n))(Nn||{}),Wg=(n=>(n[n.None=0]="None",n[n.X=2]="X",n[n.Y=4]="Y",n[n.Z=8]="Z",n[n.All=-1]="All",n))(Wg||{});const Hr=function(n,e){return function(t,r,s){Dpe(t,r,s,n,e)}};function Dpe(n,e,t,r,s){if(!s&&!r&&!n.onValidate)return;if(t!==void 0){console.error("Invalid usage of validate decorator. Only fields can be validated.",n,e,t),rn("Invalid usage of validate decorator. Only fields can be validated. Property: "+e,Bo.Error);return}let o="";if(typeof e=="string"?o=e:o=e.name,n.__internalAwake){const a=Symbol(o),l=n.__internalAwake;n.__internalAwake=function(){var c;if(!this.onValidate){st()&&console.warn('Usage of @validate decorate detected but there is no onValidate method in your class: "'+((c=n.constructor)==null?void 0:c.name)+'"');return}if(this[a]===void 0){this[a]=this[o];const h=this[o];if(h instanceof Z||h instanceof C||h instanceof Ye||h instanceof Ce){const u=this[o];Zx(u,()=>{this.onValidate(o)})}Object.defineProperty(this,o,{set:function(u){var p;if(this[lB]===!0)this[a]=u;else{r?.call(this,u);const m=this[a];this[a]=u,(p=this.onValidate)==null||p.call(this,o,m)}},get:function(){return s?.call(this),this[a]}})}l.call(this)}}}const Ope=function(n){return function(e,t,r){let s="";typeof t=="string"?s=t:s=t.name;const o=n.prototype,a=Object.getOwnPropertyDescriptor(o,s);if(!(a!=null&&a.value)){console.warn("Can not apply prefix: type does not have method named",t,n);return}const l=a.value,c=e[s];Object.defineProperty(o,s,{value:function(...h){const u=c?.call(this,...h);if(u instanceof Promise){u.then(p=>{if(p!==!1)return l.call(this,...h)});return}if(u!==!1)return l.call(this,...h)}})}};var Lpe=Object.defineProperty,Fpe=Object.getOwnPropertyDescriptor,Uo=(n,e,t,r)=>{for(var s=r>1?void 0:r?Fpe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&Lpe(e,t,s),s};class Upe{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 Nh(this.obj.position,["x","y","z"])),this._positionWatch.apply(),this.position={},this._positionWatch.subscribeWrite((o,a)=>{var l;if((l=this.context.physics.engine)!=null&&l.isUpdating||this.mute)return;const c=this.position[a];Math.abs(c-o)<1e-5||(this.position[a]=o,this.positionChanged=!0)})),t&&(this._rotationWatch||(this._rotationWatch=new Nh(this.obj.quaternion,["_x","_y","_z","_w"])),this._rotationWatch.apply(),this.quaternion={},this._rotationWatch.subscribeWrite((o,a)=>{var l;if((l=this.context.physics.engine)!=null&&l.isUpdating||this.mute)return;const c=this.quaternion[a];Math.abs(c-o)<1e-5||(this.quaternion[a]=o,this.rotationChanged=!0)}));const r=this.obj.matrixWorld.multiplyMatrices.bind(this.obj.matrixWorld),s=new ve;this.obj.matrixWorld.multiplyMatrices=(o,a)=>{var l;return(l=this.context.physics.engine)!=null&&l.isUpdating||this.mute||s.equals(o)||(this.positionChanged=!0,this.rotationChanged=!0,s.copy(o)),r(o,a)}}stop(){var e,t;(e=this._positionWatch)==null||e.revoke(),(t=this._rotationWatch)==null||t.revoke()}}var lk;const ck=(lk=class extends Be{constructor(){super(...arguments),d(this,"autoMass",!0),d(this,"_mass",0),d(this,"useGravity",!0),d(this,"centerOfMass",new C(0,0,0)),d(this,"constraints",Nn.None),d(this,"isKinematic",!1),d(this,"drag",0),d(this,"angularDrag",1),d(this,"detectCollisions",!0),d(this,"sleepThreshold",.01),d(this,"collisionDetectionMode",LS.Discrete),d(this,"_gravityScale",1),d(this,"dominanceGroup",0),d(this,"_propertiesChanged",!1),d(this,"_currentVelocity",new C),d(this,"_smoothedVelocity",new C),d(this,"_smoothedVelocityGetter",new C),d(this,"_lastPosition",new C),d(this,"_watch")}set mass(n){n!==this._mass&&(this._mass=n,this._propertiesChanged=!0,this.__didAwake&&(this.autoMass=!1))}get mass(){var n,e;return this.autoMass?((e=(n=this.context.physics.engine)==null?void 0:n.getBody(this))==null?void 0:e.mass())??-1:this._mass}get lockPositionX(){return(this.constraints&Nn.FreezePositionX)!==0}get lockPositionY(){return(this.constraints&Nn.FreezePositionY)!==0}get lockPositionZ(){return(this.constraints&Nn.FreezePositionZ)!==0}get lockRotationX(){return(this.constraints&Nn.FreezeRotationX)!==0}get lockRotationY(){return(this.constraints&Nn.FreezeRotationY)!==0}get lockRotationZ(){return(this.constraints&Nn.FreezeRotationZ)!==0}set lockPositionX(n){n?this.constraints|=Nn.FreezePositionX:this.constraints&=~Nn.FreezePositionX}set lockPositionY(n){n?this.constraints|=Nn.FreezePositionY:this.constraints&=~Nn.FreezePositionY}set lockPositionZ(n){n?this.constraints|=Nn.FreezePositionZ:this.constraints&=~Nn.FreezePositionZ}set lockRotationX(n){n?this.constraints|=Nn.FreezeRotationX:this.constraints&=~Nn.FreezeRotationX}set lockRotationY(n){n?this.constraints|=Nn.FreezeRotationY:this.constraints&=~Nn.FreezeRotationY}set lockRotationZ(n){n?this.constraints|=Nn.FreezeRotationZ:this.constraints&=~Nn.FreezeRotationZ}set gravityScale(n){this._gravityScale=n}get gravityScale(){return this._gravityScale}awake(){this._watch=void 0,this._propertiesChanged=!1}onEnable(){this._watch||(this._watch=new Upe(this.gameObject,this.context)),this._watch.start(!0,!0),this.startCoroutine(this.beforePhysics(),Hi.LateUpdate)}onDisable(){var n,e;(n=this._watch)==null||n.stop(),(e=this.context.physics.engine)==null||e.removeBody(this)}onDestroy(){var n;(n=this.context.physics.engine)==null||n.removeBody(this)}onValidate(){this._propertiesChanged=!0}*beforePhysics(){for(var n,e,t,r;;)this._propertiesChanged&&(this._propertiesChanged=!1,(n=this.context.physics.engine)==null||n.updateProperties(this)),(e=this._watch)!=null&&e.isDirty?(this._watch.mute=!0,this._watch.applyValues(),(t=this.context.physics.engine)==null||t.updateBody(this,this._watch.positionChanged,this._watch.rotationChanged),this._watch.reset()):(r=this._watch)==null||r.syncValues(),this.captureVelocity(),yield}teleport(n,e=!0){var t;(t=this._watch)==null||t.reset(!0),e?this.gameObject.position.set(n.x,n.y,n.z):this.setWorldPosition(n.x,n.y,n.z),this.resetForcesAndTorques(),this.resetVelocities()}resetForces(n=!0){var e;(e=this.context.physics.engine)==null||e.resetForces(this,n)}resetTorques(n=!0){var e;(e=this.context.physics.engine)==null||e.resetTorques(this,n)}resetVelocities(){this.setVelocity(0,0,0),this.setAngularVelocity(0,0,0)}resetForcesAndTorques(){this.resetForces(),this.resetTorques()}wakeUp(){var n;(n=this.context.physics.engine)==null||n.wakeup(this)}get isSleeping(){var n;return(n=this.context.physics.engine)==null?void 0:n.isSleeping(this)}updateProperties(){var n;return this._propertiesChanged=!1,(n=this.context.physics.engine)==null?void 0:n.updateProperties(this)}applyForce(n,e,t=!0){var r;this._propertiesChanged&&this.updateProperties(),(r=this.context.physics.engine)==null||r.addForce(this,n,t)}applyImpulse(n,e=!0){var t;this._propertiesChanged&&this.updateProperties(),(t=this.context.physics.engine)==null||t.applyImpulse(this,n,e)}setForce(n,e,t,r=!0){var s,o,a;(s=this.context.physics.engine)==null||s.resetForces(this,r),typeof n=="number"?(e??(e=0),t??(t=0),(o=this.context.physics.engine)==null||o.addForce(this,{x:n,y:e,z:t},r)):(a=this.context.physics.engine)==null||a.addForce(this,n,r)}getVelocity(){var n;const e=(n=this.context.physics.engine)==null?void 0:n.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(n,e,t,r=!0){var s,o;if(n instanceof C){const a=n;(s=this.context.physics.engine)==null||s.setLinearVelocity(this,a,r);return}e===void 0||t===void 0||(o=this.context.physics.engine)==null||o.setLinearVelocity(this,{x:n,y:e,z:t},r)}getAngularVelocity(){var n;const e=(n=this.context.physics.engine)==null?void 0:n.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(n,e,t,r=!0){var s,o;if(n instanceof C){const a=n;(s=this.context.physics.engine)==null||s.setAngularVelocity(this,a,r);return}e===void 0||t===void 0||(o=this.context.physics.engine)==null||o.setAngularVelocity(this,{x:n,y:e,z:t},r)}setTorque(n,e,t){this.setAngularVelocity(n,e,t)}get smoothedVelocity(){return this._smoothedVelocityGetter.copy(this._smoothedVelocity),this._smoothedVelocityGetter.multiplyScalar(1/this.context.time.deltaTime)}setBodyFromGameObject(n=null){}captureVelocity(){const n=Bt(this.gameObject);ck.tempPosition.copy(n);const e=n.sub(this._lastPosition);this._lastPosition.copy(ck.tempPosition),this._smoothedVelocity.lerp(e,this.context.time.deltaTime/.1)}},d(lk,"tempPosition",new C),lk);let Oi=ck;Uo([Hr()],Oi.prototype,"autoMass",2),Uo([w()],Oi.prototype,"mass",1),Uo([Hr(),w()],Oi.prototype,"useGravity",2),Uo([w(C)],Oi.prototype,"centerOfMass",2),Uo([Hr(),w()],Oi.prototype,"constraints",2),Uo([Hr(),w()],Oi.prototype,"isKinematic",2),Uo([Hr(),w()],Oi.prototype,"drag",2),Uo([Hr(),w()],Oi.prototype,"angularDrag",2),Uo([Hr(),w()],Oi.prototype,"detectCollisions",2),Uo([Hr(),w()],Oi.prototype,"sleepThreshold",2),Uo([Hr(),w()],Oi.prototype,"collisionDetectionMode",2),Uo([Hr()],Oi.prototype,"_gravityScale",2),Uo([Hr()],Oi.prototype,"dominanceGroup",2);const Ju=te("debugsync"),AA="STRS";wB(AA,Vh.getRootAsSyncedTransformModel);const Zl=new s_;function y8(n,e,t=!0){Zl.clear();const r=Zl.createString(n);Vh.startSyncedTransformModel(Zl),Vh.addGuid(Zl,r),Vh.addFast(Zl,t);const s=e.worldPosition,o=e.worldEuler,a=e.gameObject.scale;Vh.addTransform(Zl,v8.createTransform(Zl,s.x,s.y,s.z,o.x,o.y,o.z,a.x,a.y,a.z));const l=Vh.endSyncedTransformModel(Zl);return Zl.finish(l,AA),Zl.asUint8Array()}let hk=0,bA=0;g8(n=>{var e;const t=(e=n.connection.currentServerUrl)!=null&&e.includes("glitch")?10:40;bA=Math.floor(hk/t),hk=0,Ju&&bA>0&&console.log("Sync Transform Fast Interval",bA)});class Ku extends Be{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 ii),d(this,"receivedUpdate",!1),d(this,"lastWorldPos"),d(this,"lastWorldRotation")}requestOwnership(){Ju&&console.log("Request ownership"),this._model?this._model.requestOwnership():(this._shouldRequestOwnership=!0,this._needsUpdate=!0)}hasOwnership(){var e;return((e=this._model)==null?void 0:e.hasOwnership)??void 0}isOwned(){var e;return(e=this._model)==null?void 0:e.isOwned}awake(){Ju&&console.log("new instance",this.guid,this),this._receivedDataBefore=!1,this._targetPosition=new C,this._targetRotation=new Ce,this.lastWorldPos=new C,this.lastWorldRotation=new Ce,this.rb=ie.getComponentInChildren(this.gameObject,Oi),this.rb&&(this._wasKinematic=this.rb.isKinematic),this.receivedUpdate=!0,this._model=new jB(this.context.connection,this.guid),this.context.connection.isConnected&&this.tryGetLastState(),this.joinedRoomCallback=this.tryGetLastState.bind(this),this.context.connection.beginListen(Vt.JoinedRoom,this.joinedRoomCallback),this.receivedDataCallback=this.onReceivedData.bind(this),this.context.connection.beginListenBinary(AA,this.receivedDataCallback)}onDestroy(){this.syncDestroy&&$B(this.guid,this.context.connection),this._model=null,this.context.connection.stopListen(Vt.JoinedRoom,this.joinedRoomCallback),this.context.connection.stopListenBinary(AA,this.receivedDataCallback)}tryGetLastState(){const e=this.context.connection.tryGetState(this.guid);e&&this.onReceivedData(e)}onReceivedData(e){var t;if(!this.destroyed&&typeof e.guid=="function"&&e.guid()===this.guid){Ju&&console.log("new data",this.context.connection.connectionId,this.context.time.frameCount,this.guid,e),this.receivedUpdate=!0,this._receivedFastUpdate=e.fast();const r=e.transform();if(r){Qa.markDirty(this.gameObject,!0);const s=r.position();s&&(this.interpolatePosition&&((t=this._targetPosition)==null||t.set(s.x(),s.y(),s.z())),(!this.interpolatePosition||!this._receivedDataBefore)&&this.setWorldPosition(s.x(),s.y(),s.z()));const o=r.rotation();o&&(this.tempEuler.set(o.x(),o.y(),o.z()),this.interpolateRotation&&this._targetRotation.setFromEuler(this.tempEuler),(!this.interpolateRotation||!this._receivedDataBefore)&&ER(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){Ju&&console.log("no model or room",this.name,this.guid,this.context.connection.isInRoom);return}this._shouldRequestOwnership&&(this._shouldRequestOwnership=!1,this._model.requestOwnership());const e=this.worldPosition,t=this.worldQuaternion;if(this._model.isOwned&&!this.receivedUpdate){const o=e.distanceTo(this.lastWorldPos),a=t.angleTo(this.lastWorldRotation),l=this._model.hasOwnership||this.fastMode?1e-4:.001;(o>l||a>l)&&(this._model.hasOwnership?this._needsUpdate=!0:(Ju&&console.log(this.guid,"reset because not owned but",this.gameObject.name,this.lastWorldPos),this.worldPosition=this.lastWorldPos,e.copy(this.lastWorldPos),this.worldQuaternion=this.lastWorldRotation,t.copy(this.lastWorldRotation),Qa.markDirty(this.gameObject,!0),this._needsUpdate=!1))}if(this._model&&!this._model.hasOwnership&&this._model.isOwned&&this._receivedDataBefore){const o=this._receivedFastUpdate||this.fastMode?.5:.3;let a=!1;if(this.interpolatePosition&&this._targetPosition){const l=this.worldPosition;l.lerp(this._targetPosition,o),this.worldPosition=l,a=!0}if(this.interpolateRotation&&this._targetRotation){const l=this.worldQuaternion;l.slerp(this._targetRotation,o),this.worldQuaternion=l,a=!0}a&&Qa.markDirty(this.gameObject,!0)}if(this.receivedUpdate=!1,this.lastWorldPos.copy(e),this.lastWorldRotation.copy(t),!this._model||!this._model||this._model.hasOwnership===void 0||!this._model.hasOwnership)return;this.rb&&this.overridePhysics&&this._wasKinematic!==void 0&&(Ju&&console.log("reset kinematic",this.rb.name,this._wasKinematic),this.rb.isKinematic=this._wasKinematic);const r=10,s=this.rb||this.fastMode;if(this._needsUpdate&&(this.context.time.frameCount%r===0||s)){if(hk++,s&&bA>0&&this.context.time.frameCount%bA!==0)return;Ju&&console.log("send update",this.context.connection.connectionId,this.guid,this.gameObject.name,this.gameObject.guid),this._needsUpdate=!1;const o=y8(this.guid,this,!!s);this.context.connection.sendBinary(o)}}}const Npe=te("debugshadowcomponents");pR.prototype.interactable={get(){return this.interactive},set(n){this.interactable=n}};const Ma=Symbol("shadowDomOwner");class Va extends Be{constructor(){super(...arguments),d(this,"_shadowComponent",null),d(this,"_controlsChildLayout",!0),d(this,"_root"),d(this,"_parentComponent")}isRoot(){var e;return((e=this.Root)==null?void 0:e.gameObject)===this.gameObject}get canvas(){const e=this.Root;return e!=null&&e.isCanvas?e:null}get Canvas(){return this.canvas}markDirty(){Ta.markUIDirty(this.context)}get shadowComponent(){return this._shadowComponent}set shadowComponent(e){this._shadowComponent=e}get controlsChildLayout(){return this._controlsChildLayout}set controlsChildLayout(e){this._controlsChildLayout=e,this.shadowComponent&&(this.shadowComponent.autoLayout=e)}get Root(){return this._root===void 0&&(this._root=ie.getComponentInParent(this.gameObject,_A)),this._root}__internalNewInstanceCreated(e){return super.__internalNewInstanceCreated(e),this.shadowComponent=null,this._root=void 0,this._parentComponent=void 0,this}onEnable(){super.onEnable()}addShadowComponent(e,t){var r;if(!e)return;this.removeShadowComponent();const s=this.isRoot()?this.gameObject:this.gameObject.parent;if(this._parentComponent=ie.getComponentInParent(s,Va),!this._parentComponent){console.warn(`Component "${this.name}" doesn't have a UI parent anywhere. Do you have an UI element outside a Canvas? UI components must be a child of a Canvas component`,this);return}e.name=this.name+" ("+(this.constructor.name??"UI")+")",e.autoLayout=this._parentComponent.controlsChildLayout,e[Ma]=this,this.setShadowComponentOwner(e);let o=!1;if(((r=this.Root)==null?void 0:r.gameObject)===this.gameObject)this.gameObject.add(e);else{const a=this._parentComponent.shadowComponent;a&&(a?.add(e),o=!0)}this.shadowComponent=e,t&&t.shadowComponent&&this.shadowComponent&&t.shadowComponent.add(this.shadowComponent),Wy&&e.add(new Po(.5)),this.onAfterAddedToScene(),o&&YN(),Npe&&console.warn("Added shadow component",this.shadowComponent)}setShadowComponentOwner(e){if(e&&(e[Ma]===void 0||e[Ma]===this)&&(e[Ma]=this,e.children))for(const t of e.children)this.setShadowComponentOwner(t)}traverseOwnedShadowComponents(e,t,r){if(e&&e[Ma]===t){r(e);for(const s of e.children)this.traverseOwnedShadowComponents(s,t,r)}}removeShadowComponent(){this.shadowComponent&&this.shadowComponent.removeFromParent()}onAfterAddedToScene(){}setInteractable(e){this.shadowComponent&&(this.shadowComponent.interactable=e)}}class _A extends Va{awake(){super.awake()}}class q0{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 q0(this.input,this.event);return Object.assign(e,this),e}Use(){this.use()}StopPropagation(){this.event.stopImmediatePropagation()}}function uk(n,e){return ie.foreachComponent(n,t=>{if(!t.enabled)return;const r=t;if(e)switch(e){case"pointerdown":if(r.onPointerDown)return!0;break;case"pointerup":if(r.onPointerUp||r.onPointerClick)return!0;break;case"pointermove":if(r.onPointerEnter||r.onPointerExit||r.onPointerMove)return!0;break}else if(r.onPointerDown||r.onPointerUp||r.onPointerEnter||r.onPointerExit||r.onPointerClick)return!0},!1)===!0}var zpe=Object.defineProperty,jpe=Object.getOwnPropertyDescriptor,Gpe=(n,e,t,r)=>{for(var s=r>1?void 0:r?jpe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&zpe(e,t,s),s};class xA extends Be{awake(){Ta.createIfNoneExists(this.context)}onEnable(){var e;(e=Ta.get(this.context))==null||e.register(this)}onDisable(){var e;(e=Ta.get(this.context))==null||e.unregister(this)}}class No extends xA{constructor(){super(...arguments),d(this,"targets",null),d(this,"raycastHits",[]),d(this,"ignoreSkinnedMeshes",!1)}start(){this.targets=[this.gameObject]}performRaycast(e=null){if(!this.targets)return null;e??(e=new ml),e.targets=this.targets,e.results=this.raycastHits;const t=e.testObject;this.ignoreSkinnedMeshes&&(e.testObject=s=>s instanceof uo?"continue in children":t?t(s):!0);const r=this.context.physics.raycast(e);return e.testObject=t,r}}Gpe([w()],No.prototype,"ignoreSkinnedMeshes",2);class FS extends No{constructor(){super(),this.ignoreSkinnedMeshes=!0}}class wA extends xA{performRaycast(e){if(!wt.active||!(e!=null&&e.ray))return null;const t=e.ray.origin,r=.015;return this.context.physics.sphereOverlap(t,r)}}class US{static getObject(e){const t=e[Ma];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 r=this.tryFindCanvasGroup(e);if(r?.isCanvasGroup===!0&&(t&&(t.canvasGroup=r),r.blocksRaycasts===!1||r.interactable===!1))return!1;const s=Kp(e,o=>{if(o.isGraphic===!0)return o},!1);return t&&s?.isGraphic===!0&&(t.graphic=s),!(s?.raycastTarget===!1||s?.layer===2)}static tryFindCanvasGroup(e){if(!e)return null;const t=Kp(e,r=>{const s=r;if(s.blocksRaycasts!==void 0&&s.interactable!==void 0)return s},!1);return t!==void 0?t:this.tryFindCanvasGroup(e.parent)}}function dk(n){return n[Ma]||(n.parent?dk(n.parent):null)}function Vpe(n){return n.isUI===!0||typeof n[Ma]=="object"}function NS(n,e){if(!n)return;const t=n.material;if(t?.isMaterial===!0){const r=n.parent;r&&r.isText,t.side=e.doubleSided??!0?yi:nr,t.shadowSide=e.doubleSided?yi:nr,n.castShadow=e.castShadows?e.castShadows:!1,n.receiveShadow=e.receiveShadows?e.receiveShadows:!1}for(const r of n.children)NS(r,e)}function Xg(n,e,t){n[e]===void 0&&console.warn("Field",e,"is undefined on",n);const r=Proxy.revocable(n[e],{set(a,l,c,h){const u=a[l],p=Reflect.set(a,l,c,h);return t(c,u),p}}),s=r.revoke,o=n[e];return r.revoke=()=>{n[e]=o,s()},n[e]=r.proxy,r}const A8=Symbol("Scheduled action");function Qpe(n,e,t=Hi.OnBeforeRender){let r=n[A8];r||(r=n[A8]={});const s=e.name;r[t]||(r[t]={});const o=r[t];if(o[s])return;function*a(){e?.call(n),o[s]=null}const l=n.startCoroutine(a(),t);o[s]=l}const Ah=te("debugeventsystem");var pk=(n=>(n.BeforeHandleInput="BeforeHandleInput",n.AfterHandleInput="AfterHandleInput",n))(pk||{});const bh=class extends Be{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",n=>{var e;let t=null;if(Vpe(n)&&(t=(e=n[Ma])==null?void 0:e.gameObject),this._testObjectsCache.has(n)||t&&this._testObjectsCache.has(t))return this._testObjectsCache.get(n)===!1?"continue in children":!0;{let r=uk(n,this._currentPointerEventName);if(!r&&t&&(r=uk(t,this._currentPointerEventName)),r){this._testObjectsCache.set(n,!0);for(const s of n.children)this.shouldRaycastObject_AddToYesCache(s);return!0}return this._testObjectsCache.set(n,!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",[]),bh.systems.push(this)}static createIfNoneExists(n){this.didSearchEventSystem||(this.didSearchEventSystem=!0,bh.systems.length<=0&&bh.systems.push(...ie.findObjectsOfType(bh,n)));for(const t of bh.systems)if(t.context===n)return;const e=new ye;ie.addNewComponent(e,bh),n.scene.add(e)}static get systems(){const n=kt.Current;return this._eventSystemMap.has(n)||this._eventSystemMap.set(n,[]),this._eventSystemMap.get(n)}static get(n){const e=this._eventSystemMap.get(n);return e&&e.length>0?e[0]:null}static get instance(){return this.systems[0]}static ensureUpdateMeshUI(n,e,t=!1){Zu.update(n,e,t)}static markUIDirty(n){Zu.markDirty()}get hasActiveUI(){return this.currentActiveMeshUIComponents.length>0}get isHoveringObjects(){return this.hoveredByID.size>0}onDestroy(){bh.systems.splice(bh.systems.indexOf(this),1)}start(){if(this.raycaster.length<=0&&!ie.findObjectOfType(xA,this.context)){const n=ie.addNewComponent(this.context.scene,No);this.raycaster.push(n),(st()||Ah)&&console.warn("Added an ObjectRaycaster to the scene because no raycaster was found.")}}register(n){var e;n&&this.raycaster&&!this.raycaster.includes(n)&&((e=this.raycaster)==null||e.push(n))}unregister(n){var e,t;const r=(e=this.raycaster)==null?void 0:e.indexOf(n);r!==void 0&&r!==-1&&((t=this.raycaster)==null||t.splice(r,1))}onEnable(){this._handleInputFn??(this._handleInputFn=this.onPointerEvent.bind(this)),this.context.input.addEventListener(an.PointerDown,this._handleInputFn),this.context.input.addEventListener(an.PointerUp,this._handleInputFn),this.context.input.addEventListener(an.PointerMove,this._handleInputFn)}onDisable(){this.context.input.removeEventListener(an.PointerDown,this._handleInputFn),this.context.input.removeEventListener(an.PointerUp,this._handleInputFn),this.context.input.removeEventListener(an.PointerMove,this._handleInputFn)}onBeforeRender(){this.resetMeshUIStates()}onPointerEvent(n){if(n===void 0||n.propagationStopped)return;const e=new q0(this.context.input,n);this._currentPointerEventName=n.type,e.inputSource=this.context.input,e.isClick=n.isClick,e.isDoubleClick=n.isDoubleClick,e.isDown=n.type==an.PointerDown,e.isUp=n.type==an.PointerUp,e.isPressed=this.context.input.getPointerPressed(n.pointerId),Ah&&(e.isDown?console.log("DOWN",e.pointerId):e.isUp&&console.log("UP",e.pointerId),e.isClick&&console.log("CLICK",e.pointerId));const t=new ml;n.hasRay?t.ray=n.ray:t.screenPoint=this.context.input.getPointerPositionRC(n.pointerId);const r=this.performRaycast(t);if(r){for(const o of r)o.event=n,n.intersections.push(o);n.origin.onPointerHits&&n.origin.onPointerHits({sender:this,event:n,hits:r})}Ah&&e.isClick&&rn("EventSystem: "+e.pointerId+" - "+this.context.time.frame+" - Up:"+e.isUp+", Down:"+e.isDown);const s={sender:this,args:e,hasActiveUI:this.currentActiveMeshUIComponents.length>0};this.dispatchEvent(new CustomEvent("BeforeHandleInput",{detail:s})),this.handleIntersections(r,e),this.dispatchEvent(new CustomEvent("AfterHandleInput",{detail:s}))}shouldRaycastObject_AddToYesCache(n){this._testObjectsCache.set(n,!0);for(const e of n.children)this.shouldRaycastObject_AddToYesCache(e)}performRaycast(n){if(!this.raycaster)return null;this._testObjectsCache.clear(),this._sortedHits.length=0,n||(n=new ml),n.testObject=this.shouldRaycastObject;for(const e of this.raycaster){if(!e.activeAndEnabled)continue;this._currentlyActiveRaycaster=e;const t=e.performRaycast(n);this._currentlyActiveRaycaster=null,t&&t.length>0&&this._sortedHits.push(...t)}return this._sortedHits.sort((e,t)=>e.distance-t.distance),this._sortedHits}assignHitInformation(n,e){e?(n.intersection=e,n.point=e.point,n.normal=e.normal,n.face=e.face,n.distance=e.distance,n.instanceId=e.instanceId):(n.intersection=void 0,n.point=void 0,n.normal=void 0,n.face=void 0,n.distance=void 0,n.instanceId=void 0)}handleIntersections(n,e){var t;if(n!=null&&n.length){n=this.sortCandidates(n);for(const s of n){if(e.event.immediatePropagationStopped)return!1;if(this.assignHitInformation(e,s),this.handleEventOnObject(s.object,e))return!0}}this.assignHitInformation(e,n?.[0]),this.invokePointerCapture(e);const r=this.hoveredByID.get(e.pointerId);return r&&this.propagatePointerExit(r.obj,r.data,null),this.hoveredByID.delete(e.pointerId),e.isUp&&((t=this.pressedByID.get(e.pointerId))==null||t.handlers.forEach(s=>this.invokeOnPointerUp(e,s)),this.pressedByID.delete(e.pointerId)),!1}sortCandidates(n){this._sortingBuffer.length=0,this._noDepthTestingResults.length=0;for(let e=0;e<n.length;e++){const t=n[e],r=t.object;if(r.material&&r.material.depthTest===!1){this._noDepthTestingResults.push(t);continue}this._sortingBuffer.push(t)}for(const e of this._sortingBuffer)this._noDepthTestingResults.push(e);return this._noDepthTestingResults}handleEventOnObject(n,e){if(!this.testIsVisible(n))return e.isClick&&Ah&&console.log("not allowed",n),!1;if(e.pointerId===void 0)return Ah&&console.error("Event without pointer can't be handled",e),!1;e.object=n;const t=n.parent,r=e.isClick??!1;let s=null;if(t&&t.isUI){const c=(e.isPressed||e.isClick)??!1;if(t[Ma]){const h=t[Ma].gameObject;if(h){if(!US.isInteractable(h,this.out))return!1;s=this.out.canvasGroup??null,this.handleMeshUIIntersection(n,c),n=h}}}r&&Ah&&console.log(this.context.time.frame,n);const o=this.hoveredByID.get(e.pointerId),a=o?.obj;a!==n&&a&&this.propagatePointerExit(a,o.data,n);const l=this.hoveredByID.get(e.pointerId);if(l?(l.obj=n,l.data=e):this.hoveredByID.set(e.pointerId,{obj:n,data:e}),e.isDown){const c=this.pressedByID.get(e.pointerId);c?(c.obj=n,c.data=e):this.pressedByID.set(e.pointerId,{obj:n,data:e,handlers:new Set})}return(s===null||s.interactable)&&this.handleMainInteraction(n,e,a??null),!0}propagate(n,e){for(;n;)ie.foreachComponent(n,t=>{e(t)},!1),n=n.parent}handleMainInteraction(n,e,t){const r=this.pressedByID.get(e.pointerId),s=t!==n;let o=!0;switch(e.event.pointerType){case"mouse":case"touch":const a=this.context.input.getPointerPositionLastFrame(e.pointerId),l=this.context.input.getPointerPosition(e.pointerId);o=a&&!it.approximately(a,l);break}this.propagate(n,a=>{var l;const c=a;c.interactable!==!1&&(!c.activeAndEnabled||!c.enabled||(c.onPointerEnter&&s&&this.handlePointerEnter(c,e),e.isDown&&c.onPointerDown&&(c.onPointerDown(e),r?.handlers.add(c),this.handlePointerCapture(e,c)),c.onPointerMove&&(o&&c.onPointerMove(e),this.handlePointerCapture(e,c)),e.isUp&&(c.onPointerUp&&(this.invokeOnPointerUp(e,c),r?.handlers.delete(c)),c.onPointerExit&&((l=e.event)==null?void 0:l.pointerType)===q1.Touch&&(this.handlePointerExit(c,e),this.hoveredByID.delete(e.pointerId))),e.isClick&&c.onPointerClick&&c.onPointerClick(e)))}),e.isUp&&(r?.handlers.forEach(a=>{this.invokeOnPointerUp(e,a)}),this.pressedByID.delete(e.pointerId))}propagatePointerExit(n,e,t){this.propagate(n,r=>{if(!r.gameObject||r.destroyed)return;const s=r;if(s.onPointerExit){if(t&&this.isChild(t,r.gameObject))return;this.handlePointerExit(s,e)}})}invokeOnPointerUp(n,e){var t;(t=e.onPointerUp)==null||t.call(e,n),this.releasePointerCapture(n,e)}handlePointerEnter(n,e){n.onPointerEnter&&this.updatePointerState(n,e.pointerId,this.pointerEnterSymbol,!0)&&n.onPointerEnter(e),this.updatePointerState(n,e.pointerId,this.pointerExitSymbol,!1)}handlePointerExit(n,e){n.onPointerExit&&this.updatePointerState(n,e.pointerId,this.pointerExitSymbol,!0)&&n.onPointerExit(e),this.updatePointerState(n,e.pointerId,this.pointerEnterSymbol,!1)}updatePointerState(n,e,t,r){let s=n[t];if(r)return s&&s.includes(e)?!1:(s=s||[],s.push(e),n[t]=s,!0);{if(!s||!s.includes(e))return!1;const o=s.indexOf(e);return o!==-1&&s.splice(o,1),!0}}handlePointerCapture(n,e){if(n.z__pointer_ctured){n.z__pointer_ctured=!1;const t=n.pointerId;if(e.onPointerMove){const r=this._capturedPointer[t]||[];r.push(e),this._capturedPointer[t]=r}else st()&&!e.z__warned_no_pointermove&&(e.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 n.z__pointer_cture_rleased&&(n.z__pointer_cture_rleased=!1,this.releasePointerCapture(n,e))}releasePointerCapture(n,e){const t=n.pointerId;if(this._capturedPointer[t]){const r=this._capturedPointer[t].indexOf(e);r!==-1&&(this._capturedPointer[t].splice(r,1),Ah&&console.log("released pointer capture",t,e,this._capturedPointer))}}invokePointerCapture(n){var e;if(n.event.type===an.PointerMove){const t=n.pointerId,r=this._capturedPointer[t];if(r){Ah&&console.log("Captured",t,r);for(let s=0;s<r.length;s++){const o=r[s];if(o.destroyed){r.splice(s,1),s--;continue}(e=o.onPointerMove)==null||e.call(o,n)}}}}isChild(n,e){return!n||!e?!1:n===e?!0:n.parent?this.isChild(n.parent,e):!1}handleMeshUiObjectWithoutShadowDom(n,e){return!n||!n.isUI?!0:this.handleMeshUIIntersection(n,e)}handleMeshUIIntersection(n,e){const t=Zu.updateState(n,e);return t&&this.currentActiveMeshUIComponents.push(t),t!==null}resetMeshUIStates(){if(this.context.input.getPointerPressedCount()>0&&Zu.resetLastSelected(),!(!this.currentActiveMeshUIComponents||this.currentActiveMeshUIComponents.length<=0)){for(let n=0;n<this.currentActiveMeshUIComponents.length;n++){const e=this.currentActiveMeshUIComponents[n];Zu.resetState(e)}this.currentActiveMeshUIComponents.length=0}}testIsVisible(n){return n?ie.isActiveSelf(n)?this.testIsVisible(n.parent):!1:!0}};let Ta=bh;d(Ta,"_eventSystemMap",new Map),d(Ta,"didSearchEventSystem",!1);class Zu{static markDirty(){this.needsUpdate=!0}static update(e,t,r=!1){if(r){e.update();return}const s=t.time.frameCount;for(const o of this.lastUpdateFrame)if(o.context===t){if(s===o.frame)return;o.frame=s;let a=this.needsUpdate||s<1;o.nextUpdate===t.time.frameCount&&(a=!0),a&&(Ah&&console.log("Update threemeshui"),this.needsUpdate=!1,e.update());return}this.lastUpdateFrame=[{context:t,frame:s,nextUpdate:s}],e.update()}static updateState(e,t){let r=null;if(e&&(r=this.findBlockInParent(e),r&&r!==this.lastSelected)){if(r.interactable===!1)return null;this.needsUpdate=!0}return r}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 Hpe=Object.defineProperty,Wpe=Object.getOwnPropertyDescriptor,ln=(n,e,t,r)=>{for(var s=r>1?void 0:r?Wpe(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&Hpe(e,t,s),s};const mk=te("debugorbit"),zS=te("freecam"),jS=te("debugcamerafit"),GS=te("smoothcam"),Xpe={LEFT:"",UP:"",RIGHT:"",BOTTOM:""};let fk;class SA extends CustomEvent{constructor(e,t){super("target-reached",{detail:{controls:e,type:t}})}}class bi extends Be{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 C),d(this,"_lookTargetEndPosition",new C),d(this,"_lookTargetLerp01",0),d(this,"_lookTargetLerpDuration",0),d(this,"_cameraLerpActive",!1),d(this,"_cameraStartPosition",new C),d(this,"_cameraEndPosition",new C),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",e=>{if(this.clickBackgroundToFitScene>0&&e.isClick&&e.button===0){if(e.hasRay||e.intersections.push(...this.context.physics.raycast()),e.intersections.length<=0){const t=this.context.time.time-this._lastTimeClickOnBackground;this._lastTimeClickOnBackground=this.context.time.time,this.clickBackgroundToFitScene<=1||t<this.clickBackgroundToFitScene*.15?(this._clickOnBackgroundCount+=1,this._clickOnBackgroundCount>=this.clickBackgroundToFitScene-1&&this.fitCamera(this.context.scene.children,{immediate:!1})):this._clickOnBackgroundCount=0}mk&&console.log(this.clickBackgroundToFitScene,e.intersections.length,this._clickOnBackgroundCount)}}),d(this,"onControlsChangeStarted",()=>{this._syncedTransform&&this._syncedTransform.requestOwnership()}),d(this,"_shouldDisable",!1),d(this,"__onPreRender",()=>{const e=this.context.pre_render_callbacks.indexOf(this.__onPreRender);e>=0&&this.context.pre_render_callbacks.splice(e,1),this.autoFit&&(this.autoFit=!1,this.fitCamera(this.scene.children,{centerCamera:"y",immediate:!0}))}),d(this,"_haveAttachedKeyboardEvents",!1)}get isCameraController(){return!0}get controls(){return this._controls}get controllerObject(){return this._cameraObject}onStartInteraction(e){var t;(t=this.controls)==null||t.addEventListener("start",e)}get targetLerpSpeed(){return 5}set targetLerpSpeed(e){this.targetLerpDuration=1/e}awake(){this._didSetTarget=0,this._startedListeningToKeyEvents=!1}start(){this._eventSystem=Ta.get(this.context)??void 0,this._eventSystem&&(this._afterHandleInputFn=this.afterHandleInput.bind(this),this._eventSystem.addEventListener(pk.AfterHandleInput,this._afterHandleInputFn))}onDestroy(){var e,t;(e=this._controls)==null||e.dispose(),(t=this._eventSystem)==null||t.removeEventListener(pk.AfterHandleInput,this._afterHandleInputFn)}onEnable(){this._didSetTarget=0,this._enableTime=this.context.time.time;const e=ie.getComponent(this.gameObject,Li);this._camera=e;let t=e?.cam;if(!t&&this.gameObject instanceof Lt&&(t=this.gameObject),t&&vR(t,this,!0),!this._controls&&t instanceof Lt){this._cameraObject=t;const r=this.targetElement??this.context.renderer.domElement,s=t?.quaternion.clone();this._controls=new p8(t,r),t?.quaternion.copy(s),fk===void 0&&(fk={...this._controls.keys})}this._controls&&(zS&&(this.enablePan=!0,this.enableZoom=!0,this.middleClickToFocus=!0,aa()&&(this.doubleClickToFocus=!0)),this._controls.addEventListener("start",this.onControlsChangeStarted),t?.type==="PerspectiveCamera"?zS||(this._controls.minDistance=this.minZoom,this._controls.maxDistance=this.maxZoom):zS||(this._controls.minZoom=this.minZoom,this._controls.maxZoom=this.maxZoom),this._startedListeningToKeyEvents||(this._startedListeningToKeyEvents=!0,this._controls.listenToKeyEvents(window.document.body))),this._syncedTransform=ie.getComponent(this.gameObject,Ku)??void 0,this.context.input.addEventListener("pointerup",this._onPointerDown),this.context.pre_render_callbacks.push(this.__onPreRender)}onDisable(){var e;(e=this._camera)!=null&&e.cam&&vR(this._camera.cam,this,!1),this._controls&&(this._controls.enabled=!1,this._controls.autoRotate=!1,this._controls.removeEventListener("start",this.onControlsChangeStarted)),this.context.input.removeEventListener("pointerup",this._onPointerDown)}afterHandleInput(e){e.detail.args.pointerId===0&&(e.detail.args.isDown?this._controls&&this._eventSystem&&(this._shouldDisable=this._eventSystem.hasActiveUI):(!e.detail.args.isPressed||e.detail.args.isUp)&&(this._shouldDisable=!1))}onBeforeRender(){var e,t;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)&&(e=this.context.input.getPointerPositionDelta(0))!=null&&e.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 s=ie.getComponent(this.gameObject,Li);if(s&&!this.setLookTargetFromConstraint()){this.debugLog&&console.log("NO TARGET");const o=Bt(s.cam),a=Math.max(.01,o.length()),l=new C(0,0,-a).applyMatrix4(s.cam.matrixWorld);this.setLookTargetPosition(l,!0)}if(!this.setLookTargetFromConstraint()){const o=new ml;o.screenPoint=new Z(0,0),o.lineThreshold=.1;const a=this.context.physics.raycast(o);a.length>0&&this.setLookTargetPosition(a[0].point,!0),jS&&console.log("OrbitControls hits",...a)}}let r=this.middleClickToFocus&&this.context.input.getPointerClicked(1);if(r||(r=this.doubleClickToFocus&&this.context.input.getPointerDoubleClicked(0)&&this.context.time.time-this._enableTime>.3),r&&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 SA(this,"camera"));else{const s=it.easeInOutCubic(this._cameraLerp01);this._cameraObject.position.lerpVectors(this._cameraStartPosition,this._cameraEndPosition,s)}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 SA(this,"lookat"));else{const s=it.easeInOutCubic(this._lookTargetLerp01);this._controls.target.lerpVectors(this._lookTargetStartPosition,this._lookTargetEndPosition,s)}}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?fk:Xpe,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 GS=="number"||GS===!0){this._controls.enableDamping=!0;const s=typeof GS=="number"?GS:.99;this._controls.dampingFactor=Math.max(.001,1-Math.min(1,s))}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||(!zS&&(t=this.lookAtConstraint)!=null&&t.locked&&this.setLookTargetFromConstraint(0,this.lookAtConstraint01),this._controls.update(),mk&&At.DrawWireSphere(this._controls.target,.1,65280))}}setCameraAndLookTarget(e){if(!e||!(e instanceof ye))return;const t=Bt(e),r=SR(e);this.setTargetFromRaycast(new co(t,r)),this.setCameraTargetPosition(t)}setCameraTargetPosition(e,t=!1){var r,s;e&&(e instanceof ye&&(e=Bt(e)),this._cameraEndPosition||(this._cameraEndPosition=new C),this._cameraEndPosition.copy(e),t===!0?(this._cameraLerpActive=!1,(r=this.controllerObject)==null||r.position.copy(this._cameraEndPosition)):this._cameraObject&&(this._cameraLerpActive=!0,this._cameraLerp01=0,this._cameraStartPosition.copy((s=this._cameraObject)==null?void 0:s.position),typeof t=="number"?this._cameraLerpDuration=t:this._cameraLerpDuration=this.targetLerpDuration))}get cameraLerpActive(){return this._cameraLerpActive}stopCameraLerp(){this._cameraLerpActive=!1}setLookTargetPosition(e=null,t=!1){this._controls&&e&&(e instanceof ye&&(e=Bt(e)),this._lookTargetEndPosition.copy(e),mk&&(console.warn("OrbitControls: setLookTargetPosition",e,t),At.DrawWireSphere(this._lookTargetEndPosition,.2,16711680,2)),t===!0?this._controls.target.copy(this._lookTargetEndPosition):(this._lookTargetLerpActive=!0,this._lookTargetLerp01=0,this._lookTargetStartPosition.copy(this._controls.target),typeof t=="number"?this._lookTargetLerpDuration=t:this._lookTargetLerpDuration=this.targetLerpDuration))}get lookTargetLerpActive(){return this._lookTargetLerpActive}stopLookTargetLerp(){this._lookTargetLerpActive=!1}setLookTargetFromConstraint(e=0,t=1){var r;if(!this._controls)return!1;const s=(r=this.lookAtConstraint)==null?void 0:r.sources;if(s&&s.length>0){const o=s[e];if(o)return o.getWorldPosition(this._lookTargetEndPosition),this.lerpLookTarget(this._lookTargetEndPosition,t),!0}return!1}lerpTarget(e,t){return this.lerpLookTarget(e,t)}lerpLookTarget(e,t){this._controls&&(t>=1?this._controls.target.copy(e):this._controls.target.lerp(e,t))}setTargetFromRaycast(e){if(!this.controls)return;const t=e?this.context.physics.raycastFromRay(e):this.context.physics.raycast();for(const r of t)if(r.distance>0&&ie.isActiveInHierarchy(r.object)){const s=dk(r.object);if(s){const o=s.canvas;if(o!=null&&o.screenspace)break}this.setLookTargetPosition(r.point);break}}fitCamera(e,t={fitOffset:void 0,immediate:!1}){if(this.context.isInXR)return;const{immediate:r=!1,centerCamera:s}=t;let{fitOffset:o}=t;o==null&&(o=1.1);const a=this._cameraObject,l=this._controls;if(e!=null&&e.length||(e=this.context.scene.children),e.length<=0){console.warn("No objects to fit camera to...");return}if(!a||!l){console.warn("No camera or controls found to fit camera to objects...");return}const c=new C,h=new C,u=Ul(e,void 0);a.updateMatrixWorld(),a.updateProjectionMatrix(),u.getCenter(h);const p=new C;if(u.getSize(p),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,[...e]);return}if(c.length()<=1e-10){jS&&console.warn("Camera fit size is zero",u,[...e]);return}const m=a.fov,f=2*Math.atan(Math.tan(m*Math.PI/360/2)*a.aspect)/Math.PI*360,g=c.y/(2*Math.atan(Math.PI*m/360)),v=c.x/(2*Math.atan(Math.PI*f/360)),y=o*Math.max(g,v)+c.z/2;jS&&console.log("Fit camera to objects",g,v,"distance",y),l.maxDistance=y*10,l.minDistance=y*.01;const A=.05,_=h.clone();_.y-=c.y*A,this.setLookTargetPosition(_,r),this.autoTarget=!1;const b=ie.findObjectOfType(Yu),x=b?b.radius:0,E=Math.max(p.x,p.y,p.z,x);a.near=y/100,a.far=E+y*10,a.updateMatrixWorld(),a.updateProjectionMatrix();const I=Bt(a),T=h.clone();if(T.sub(I),s==="y"&&(T.y=0),T.normalize(),T.multiplyScalar(y),s==="y"&&(T.y+=-A*4*c.y),a.parent){const R=a.parent.worldToLocal(h.clone().sub(T));this.setCameraTargetPosition(R,r)}else console.error(`Can not fit camera ${a.name} because it has no parent`);if(jS){const R=new wI(u);this.context.scene.add(R),MR(R,Wv(a)),setTimeout(()=>{this.context.scene.remove(R)},1e4),this._haveAttachedKeyboardEvents||(this._haveAttachedKeyboardEvents=!0,document.body.addEventListener("keydown",D=>{D.code==="KeyF"&&this.fitCamera(e,{fitOffset:o,immediate:r})}))}l.update()}}ln([w()],bi.prototype,"autoTarget",2),ln([w()],bi.prototype,"autoFit",2),ln([w()],bi.prototype,"enableRotate",2),ln([w()],bi.prototype,"autoRotate",2),ln([w()],bi.prototype,"autoRotateSpeed",2),ln([w()],bi.prototype,"minAzimuthAngle",2),ln([w()],bi.prototype,"maxAzimuthAngle",2),ln([w()],bi.prototype,"minPolarAngle",2),ln([w()],bi.prototype,"maxPolarAngle",2),ln([w()],bi.prototype,"enableKeys",2),ln([w()],bi.prototype,"enableDamping",2),ln([w()],bi.prototype,"dampingFactor",2),ln([w()],bi.prototype,"enableZoom",2),ln([w()],bi.prototype,"minZoom",2),ln([w()],bi.prototype,"maxZoom",2),ln([w()],bi.prototype,"zoomSpeed",2),ln([w()],bi.prototype,"enablePan",2),ln([w(nm)],bi.prototype,"lookAtConstraint",2),ln([w()],bi.prototype,"lookAtConstraint01",2),ln([w()],bi.prototype,"allowInterrupt",2),ln([w()],bi.prototype,"middleClickToFocus",2),ln([w()],bi.prototype,"doubleClickToFocus",2),ln([w()],bi.prototype,"clickBackgroundToFitScene",2),ln([w()],bi.prototype,"targetLerpDuration",2);var qpe=Object.defineProperty,Ype=Object.getOwnPropertyDescriptor,$s=(n,e,t,r)=>{for(var s=r>1?void 0:r?Ype(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&qpe(e,t,s),s},$u=(n=>(n[n.Skybox=1]="Skybox",n[n.SolidColor=2]="SolidColor",n[n.Uninitialized=4]="Uninitialized",n))($u||{});const _h=te("debugcam"),b8=te("debugscreenpointtoray");var VS;const CA=(VS=class extends Be{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 ve)}get isCamera(){return!0}get aspect(){return this._cam instanceof Lt?this._cam.aspect:this.context.domWidth/this.context.domHeight}set aspect(n){this._cam instanceof Lt&&this._cam.aspect!==n&&(this._cam.aspect=n,this._cam.updateProjectionMatrix())}get fieldOfView(){return this._cam instanceof Lt?this._cam.fov:this._fov}set fieldOfView(n){const e=this.fieldOfView!=n;if(this._fov=n,e&&this._cam&&this._cam instanceof Lt){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(n){const e=this._nearClipPlane!=n;this._nearClipPlane=n,this._cam&&e&&(this._cam.near=n,this._cam.updateProjectionMatrix())}get farClipPlane(){return this._farClipPlane}set farClipPlane(n){const e=this._farClipPlane!=n;this._farClipPlane=n,this._cam&&e&&(this._cam.far=n,this._cam.updateProjectionMatrix())}get clearFlags(){return this._clearFlags}set clearFlags(n){n!==this._clearFlags&&(this._clearFlags=n,this.applyClearFlagsIfIsActiveCamera())}set cullingMask(n){this._cullingMask=n,this._cam&&(this._cam.layers.mask=n)}get cullingMask(){return this._cam?this._cam.layers.mask:this._cullingMask}set cullingLayer(n){this.cullingMask=(1<<n|0)>>>0}set backgroundBlurriness(n){n!==this._backgroundBlurriness&&(n===void 0?this._backgroundBlurriness=void 0:this._backgroundBlurriness=Math.min(Math.max(n,0),1),this.applyClearFlagsIfIsActiveCamera())}get backgroundBlurriness(){return this._backgroundBlurriness}set backgroundIntensity(n){n!==this._backgroundIntensity&&(n===void 0?this._backgroundIntensity=void 0:this._backgroundIntensity=Math.min(Math.max(n,0),10),this.applyClearFlagsIfIsActiveCamera())}get backgroundIntensity(){return this._backgroundIntensity}set backgroundRotation(n){n!==this._backgroundRotation&&(n===void 0?this._backgroundRotation=void 0:this._backgroundRotation=n,this.applyClearFlagsIfIsActiveCamera())}get backgroundRotation(){return this._backgroundRotation}set environmentIntensity(n){this._environmentIntensity=n}get environmentIntensity(){return this._environmentIntensity}get backgroundColor(){return this._backgroundColor??null}set backgroundColor(n){if(n){if(this._backgroundColor)this._backgroundColor.copy(n);else{if(!n.clone)return;this._backgroundColor=n.clone()}n.alpha===void 0&&(this._backgroundColor.alpha=1),this.applyClearFlagsIfIsActiveCamera()}}set targetTexture(n){this._targetTexture=n}get targetTexture(){return this._targetTexture}get cam(){return this.activeAndEnabled&&this.buildCamera(),this._cam}screenPointToRay(n,e,t){const r=this.cam,s=CA._origin;s.set(n,e,-1),this.context.input.convertScreenspaceToRaycastSpace(s),b8&&console.log("screenPointToRay",n.toFixed(2),e.toFixed(2),"now:",s.x.toFixed(2),s.y.toFixed(2),"isInXR:"+this.context.isInXR),s.z=-1,s.unproject(r);const o=CA._direction.set(s.x,s.y,s.z),a=Bt(r);return o.sub(a),o.normalize(),t?(t.set(a,o),t):new co(a.clone(),o.clone())}getFrustum(){return this._frustum||(this._frustum=new Yd,this.updateFrustum()),this._frustum}updateFrustum(){this._frustum||(this._frustum=new Yd),this._frustum.setFromProjectionMatrix(this.getProjectionScreenMatrix(this._projScreenMatrix,!0),this.context.renderer.coordinateSystem)}getProjectionScreenMatrix(n,e){return e&&this._projScreenMatrix.multiplyMatrices(this.cam.projectionMatrix,this.cam.matrixWorldInverse),n===this._projScreenMatrix?n:n.copy(this._projScreenMatrix)}awake(){b8&&window.addEventListener("pointerdown",n=>{const e=n.clientX,t=n.clientY;console.log("touch",e.toFixed(2),t.toFixed(2));const r=this.screenPointToRay(e,t),s="#"+Math.floor(Math.random()*16777215).toString(16);At.DrawRay(r.origin,r.direction,s,10)})}onEnable(){_h&&console.log(`Camera enabled: "${this.name}". ClearFlags=${$u[this._clearFlags]}`,this),this.buildCamera(),(this.tag=="MainCamera"||!this.context.mainCameraComponent)&&(this.context.setCurrentCamera(this),Kpe(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 n=this.context.renderer;if(n){const e=this.context.mainCameraComponent;this.applyClearFlags(),this._targetTexture.render(this.context.scene,this._cam,n),e?.applyClearFlags()}}}buildCamera(){if(this._cam)return;const n=this.gameObject.isCamera;let e=null;if(n?(e=this.gameObject,e?.layers.enableAll(),e instanceof Lt&&(this._fov=e.fov)):e=this.gameObject.children[0],e&&e.isCamera)e instanceof Lt&&(this._fov&&(e.fov=this._fov),e.near=this._nearClipPlane,e.far=this._farClipPlane,e.updateProjectionMatrix());else if(!this.orthographic)e=new Lt(this.fieldOfView,window.innerWidth/window.innerHeight,this._nearClipPlane,this._farClipPlane),this.fieldOfView&&(e.fov=this.fieldOfView),this.gameObject.add(e);else{const t=this.orthographicSize*100;e=new Bl(window.innerWidth/-t,window.innerWidth/t,window.innerHeight/t,window.innerHeight/-t,this._nearClipPlane,this._farClipPlane),this.gameObject.add(e)}this._cam=e,this._cam.layers.mask=this._cullingMask,this.tag=="MainCamera"&&this.context.setCurrentCamera(this)}applyClearFlagsIfIsActiveCamera(n){this.context.mainCameraComponent===this&&this.applyClearFlags(n)}applyClearFlags(n){if(!this._cam){_h&&console.log("Camera does not exist (apply clear flags)");return}if(this.fieldOfView=this._fov,_h){const e=`Camera "${this.name}" clear flags: ${$u[this._clearFlags]}`;console.debug(e)}switch(this._clearFlags){case 1:if(CA.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||n?.applySkybox===!0)&&this.applySceneSkybox(),this._backgroundBlurriness!==void 0?this.context.scene.backgroundBlurriness=this._backgroundBlurriness:_h&&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:_h&&console.warn(`Camera "${this.name}" has no background intensity`);break;case 2:if(this._backgroundColor){let e=this._backgroundColor.alpha;CA.backgroundShouldBeTransparent(this.context)&&(e=this.ARBackgroundAlpha??0),this.context.scene.background=null,this.context.renderer.setClearColor(this._backgroundColor,e)}else _h&&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 Jpe(this)),this._skybox.apply()}static backgroundShouldBeTransparent(n){var e,t,r,s;const o=(e=n.renderer.xr)==null?void 0:e.getSession();if(!o)return!1;if(typeof o._transparent=="boolean")return o._transparent;const a=o.environmentBlendMode;_h&&rn("Environment blend mode: "+a+" on "+navigator.userAgent);let l=a==="additive"||a==="alpha-blend";return n.isInAR&&a==="opaque"&&((t=navigator.userAgent)!=null&&t.includes("OculusBrowser")||(r=navigator.userAgent)!=null&&r.includes("Mozilla")&&(s=navigator.userAgent)!=null&&s.includes("Mobile WebXRViewer/v2"))&&(l=!0),o._transparent=l,l}},d(VS,"_origin",new C),d(VS,"_direction",new C),VS);let Li=CA;$s([w()],Li.prototype,"aspect",1),$s([w()],Li.prototype,"fieldOfView",1),$s([w()],Li.prototype,"nearClipPlane",1),$s([w()],Li.prototype,"farClipPlane",1),$s([w()],Li.prototype,"clearFlags",1),$s([w()],Li.prototype,"orthographic",2),$s([w()],Li.prototype,"orthographicSize",2),$s([w()],Li.prototype,"ARBackgroundAlpha",2),$s([w()],Li.prototype,"cullingMask",1),$s([w()],Li.prototype,"backgroundBlurriness",1),$s([w()],Li.prototype,"backgroundIntensity",1),$s([w(ii)],Li.prototype,"backgroundRotation",1),$s([w()],Li.prototype,"environmentIntensity",1),$s([w(Si)],Li.prototype,"backgroundColor",1),$s([w(Hg)],Li.prototype,"targetTexture",1);class Jpe{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&&(_h&&console.log(`Camera "${this._camera.name}" set skybox`,this._camera,this._skybox),this._skybox.mapping=so,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)),(_h||st())&&Di(`Camera "${this._camera.name}" has no skybox texture`))}}function Kpe(n){te("freecam")&&n.context.mainCameraComponent===n&&ie.getOrAddComponent(n.gameObject,bi)}class ed extends Be{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 pU),this._listener}onEnable(){Qu.registerWaitForInteraction(this.onInteraction),this.addListenerIfItExists()}onDisable(){Qu.unregisterWaitForInteraction(this.onInteraction),this.removeListenerIfItExists()}addListenerIfItExists(){const e=this._listener;if(!e||e!=null&&e.parent)return;const t=this.context.mainCameraComponent||ie.getComponentInParent(this.gameObject,Li);t!=null&&t.cam?t.cam.add(e):this.gameObject.add(e),e.filter?(e.gain.connect(e.filter),e.filter.connect(e.context.destination)):e.gain.connect(e.context.destination)}removeListenerIfItExists(){const e=this._listener;e&&(e.removeFromParent(),e.filter&&e.filter.disconnect(),e.gain&&e.gain.disconnect())}}class Zpe extends Sn{constructor(e,t=1,r=16,s=2){const o=new yt,a=r+s*2,l=new Float32Array((a*3+3)*3);o.setAttribute("position",new nt(l,3));const c=new Gi({color:65280}),h=new Gi({color:16776960});super(o,[h,c]),this.audio=e,this.range=t,this.divisionsInnerAngle=r,this.divisionsOuterAngle=s,this.type="PositionalAudioHelper",this.update()}update(){const e=this.audio,t=this.range,r=this.divisionsInnerAngle,s=this.divisionsOuterAngle,o=ui.degToRad(e.panner.coneInnerAngle),a=ui.degToRad(e.panner.coneOuterAngle),l=o/2,c=a/2;let h=0,u=0,p,m;const f=this.geometry,g=f.attributes.position;f.clearGroups();function v(y,A,_,b){const x=(A-y)/_;for(g.setXYZ(h,0,0,0),u++,p=y;p<A;p+=x)m=h+u,g.setXYZ(m,Math.sin(p)*t,0,Math.cos(p)*t),g.setXYZ(m+1,Math.sin(Math.min(p+x,A))*t,0,Math.cos(Math.min(p+x,A))*t),g.setXYZ(m+2,0,0,0),u+=3;f.addGroup(h,u,b),h+=u,u=0}v(-c,-l,s,0),v(-l,l,r,1),v(l,c,s,0),g.needsUpdate=!0,o===a&&(this.material[0].visible=!1)}dispose(){this.geometry.dispose(),this.material[0].dispose(),this.material[1].dispose()}}var $pe=Object.defineProperty,eme=Object.getOwnPropertyDescriptor,$l=(n,e,t,r)=>{for(var s=r>1?void 0:r?eme(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&$pe(e,t,s),s};const Ms=te("debugaudio"),td=class extends Be{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||aa())&&(this.wasPlaying=this.isPlaying,this.isPlaying&&this.pause());break;case"visible":Ms&&console.log("visible",this.enabled,this.playOnAwake,!this.isPlaying,td.userInteractionRegistered,this.wasPlaying),this.enabled&&this.playOnAwake&&!this.isPlaying&&td.userInteractionRegistered&&this.wasPlaying&&this.play();break}}),d(this,"onApplicationMuteChanged",()=>{var n,e;this.context.application.muted?(n=this.sound)==null||n.setVolume(0):(e=this.sound)==null||e.setVolume(this.volume)}),d(this,"createAudio",n=>{Ms&&console.log("AudioBuffer finished loading",n);const e=this.Sound;if(!e){Ms&&console.warn("Failed getting sound?",this.name);return}e.isPlaying&&e.stop(),n&&e.setBuffer(n),e.loop=this._loop,this.context.application.muted?e.setVolume(0):e.setVolume(this.volume),e.autoplay=this.shouldPlay&&td.userInteractionRegistered,this.applySpatialDistanceSettings(),e.isPlaying&&e.stop(),td.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 Qu.userInteractionRegistered}static registerWaitForAllowAudio(n){Qu.registerWaitForAllowAudio(n)}get loop(){return this.sound&&(this._loop=this.sound.getLoop()),this._loop}set loop(n){this._loop=n,this.sound&&this.sound.setLoop(n)}get spatialBlend(){return this._spatialBlend}set spatialBlend(n){n!==this._spatialBlend&&(this._spatialBlend=n,this._needUpdateSpatialDistanceSettings=!0)}get minDistance(){return this._minDistance}set minDistance(n){this._minDistance!==n&&(this._minDistance=n,this._needUpdateSpatialDistanceSettings=!0)}get maxDistance(){return this._maxDistance}set maxDistance(n){this._maxDistance!==n&&(this._maxDistance=n,this._needUpdateSpatialDistanceSettings=!0)}get volume(){return this._volume}set volume(n){this._volume=n,this.sound&&!this.context.application.muted&&(Ms&&console.log(this.name,"audio set volume",n),this.sound.setVolume(n))}get Sound(){var n;if(!this.sound&&td.userInteractionRegistered){let e=ie.getComponent(this.context.mainCamera,ed)??ie.findObjectOfType(ed,this.context);!e&&this.context.mainCamera&&(e=ie.addNewComponent(this.context.mainCamera,ed)),e!=null&&e.listener?(this.sound=new fU(e.listener),(n=this.gameObject)==null||n.add(this.sound)):Ms&&console.warn("No audio listener found in scene - can not play audio")}return this.sound}get ShouldPlay(){return this.shouldPlay}get audioContext(){var n;return(n=this.sound)==null?void 0:n.context}awake(){Ms&&console.log(this),this.audioLoader=new Nx,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),td.userInteractionRegistered?this.playOnAwake&&this.context.application.isVisible&&this.play():td.registerWaitForAllowAudio(()=>{this.enabled&&!this.destroyed&&this.shouldPlay&&this.onNewClip(this.clip)}),globalThis.addEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.addEventListener(cS.MuteChanged,this.onApplicationMuteChanged)}onDisable(){globalThis.removeEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.removeEventListener(cS.MuteChanged,this.onApplicationMuteChanged),this.pause()}applySpatialDistanceSettings(){const n=this.sound;if(!n)return;this._needUpdateSpatialDistanceSettings=!1;const e=it.lerp(10*this._maxDistance/Math.max(1e-4,this.spatialBlend),this._minDistance,this.spatialBlend);switch(Ms&&console.log(this.name,this._minDistance,this._maxDistance,this.spatialBlend,"Ref distance="+e),n.setRefDistance(e),n.setMaxDistance(Math.max(.01,this._maxDistance)),this.rollOffMode){case 0:n.setDistanceModel("exponential");break;case 1:n.setDistanceModel("linear");break;case 2:console.warn("Custom rolloff for AudioSource is not supported: "+this.name);break}this.spatialBlend>0?Ms&&!this.helper&&(this.helper=new Zpe(n,n.getRefDistance()),n.add(this.helper)):this.helper&&this.helper.parent&&this.helper.removeFromParent()}async onNewClip(n){if(n&&(this.clip=n),typeof n=="string")if(Ms&&console.log(n),n.endsWith(".mp3")||n.endsWith(".wav")){if(this.audioLoader||(this.audioLoader=new Nx),this.shouldPlay=!0,this._lastClipStartedLoading===n){Ms&&console.log("Is currently loading:",this._lastClipStartedLoading,this);return}this._lastClipStartedLoading=n,Ms&&console.log("load audio",n);const e=await this.audioLoader.loadAsync(n).catch(console.error);this._lastClipStartedLoading=null,e&&this.createAudio(e)}else console.warn("Unsupported audio clip type",n);else this.shouldPlay=!0,this.createAudio()}play(n=void 0){var e,t,r;!n&&this.clip&&(n=this.clip),n!==void 0&&typeof n!="string"&&!(n instanceof MediaStream)&&(st()&&console.warn("Called play on AudioSource with unknown argument type:",n+`
|
|
5733
5733
|
Using the assigned clip instead:`,this.clip),n=this.clip);let s=!this.sound||n&&n!==this.clip;if(typeof n=="string"&&!this.audioLoader&&(s=!0),(n instanceof MediaStream||typeof n=="string")&&(this.clip=n),s){this.shouldPlay=!0,this.onNewClip(n);return}if(this.shouldPlay=!0,this._hasEnded=!1,Ms&&console.log("play",(e=this.sound)==null?void 0:e.getVolume(),this.sound),this.sound&&!this.sound.isPlaying){const o=this.context.application.muted;o&&this.sound.setVolume(0),(t=this.gameObject)==null||t.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 n,e;Ms&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.isPlaying&&this.sound.source&&(this._lastContextTime=(n=this.sound)==null?void 0:n.context.currentTime,this.sound.pause()),(e=this._audioElement)==null||e.remove()}stop(){var n,e;Ms&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.source&&(this._lastContextTime=(n=this.sound)==null?void 0:n.context.currentTime,Ms&&console.log(this._lastContextTime),this.sound.stop()),(e=this._audioElement)==null||e.remove()}get isPlaying(){var n;return((n=this.sound)==null?void 0:n.isPlaying)??!1}set isPlaying(n){}get time(){var n,e;return(n=this.sound)!=null&&n.source?((e=this.sound.source)==null?void 0:e.context.currentTime)-this._lastContextTime+this.sound.offset:0}set time(n){if(this.sound){if(n===this.sound.offset)return;const e=this.isPlaying;this.stop(),this.sound.offset=n,e&&this.play()}}update(){this.helper&&(this.isPlaying&&this.helper.update(),this.helper.visible=this.isPlaying),this._needUpdateSpatialDistanceSettings&&this.applySpatialDistanceSettings(),this.sound&&!this.sound.isPlaying&&this.shouldPlay&&!this._hasEnded&&(this._hasEnded=!0,Ms&&console.log("Audio clip ended",this.clip),this.dispatchEvent(new CustomEvent("ended",{detail:this})))}};let Mn=td;$l([w(URL)],Mn.prototype,"clip",2),$l([w()],Mn.prototype,"playOnAwake",2),$l([w()],Mn.prototype,"preload",2),$l([w()],Mn.prototype,"loop",1),$l([w()],Mn.prototype,"spatialBlend",1),$l([w()],Mn.prototype,"minDistance",1),$l([w()],Mn.prototype,"maxDistance",1),$l([w()],Mn.prototype,"volume",1),$l([w()],Mn.prototype,"rollOffMode",2),$l([w()],Mn.prototype,"playInBackground",2);var tme=Object.defineProperty,ime=Object.getOwnPropertyDescriptor,QS=(n,e,t,r)=>{for(var s=r>1?void 0:r?ime(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&tme(e,t,s),s};const nme=te("debugsignals");class EA{constructor(){d(this,"guid")}}QS([w()],EA.prototype,"guid",2);class qg{constructor(){d(this,"signal"),d(this,"reaction")}}QS([w(EA)],qg.prototype,"signal",2),QS([w(Un)],qg.prototype,"reaction",2);var gk;const xh=(gk=class extends Be{constructor(){super(...arguments),d(this,"events")}static invoke(n){if(xh.receivers[n]){const e=xh.receivers[n];if(!e)return;for(const t of e)t.invoke(n)}}awake(){nme&&console.log("SignalReceiver awake",this)}onEnable(){if(this.events)for(const n of this.events)xh.receivers[n.signal.guid]||(xh.receivers[n.signal.guid]=[]),xh.receivers[n.signal.guid].push(this)}onDisable(){if(this.events){for(const n of this.events)if(xh.receivers[n.signal.guid]){const e=xh.receivers[n.signal.guid].indexOf(this);e>=0&&xh.receivers[n.signal.guid].splice(e,1)}}}invoke(n){if(!this.events||!Array.isArray(this.events))return;const e=typeof n=="object"?n.guid:n;for(const t of this.events)if(t.signal.guid===e)try{if(t.reaction){if(!t.reaction.invoke){console.warn("Missing invoke - possibly a serialization error",t,this);continue}}else{console.warn("Missing reaction for signal",t,this);continue}t.reaction.invoke()}catch(r){console.error(r)}}},d(gk,"receivers",{}),gk);let Yg=xh;QS([w(qg)],Yg.prototype,"events",2);var zo=(n=>(n.Activation="ActivationTrack",n.Animation="AnimationTrack",n.Audio="AudioTrack",n.Control="ControlTrack",n.Marker="MarkerTrack",n.Signal="SignalTrack",n))(zo||{}),ec=(n=>(n[n.None=0]="None",n[n.Hold=1]="Hold",n[n.Loop=2]="Loop",n[n.PingPong=3]="PingPong",n[n.Continue=4]="Continue",n))(ec||{}),vk=(n=>(n.Signal="SignalEmitter",n))(vk||{});const tc=te("debugtimeline");class MA{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 r=this.track.clips.length-1;r>=0;r--)yield this.track.clips[r];else for(const r of this.track.clips)yield r}getClipTime(e,t){return t.clipIn+(e-t.start)*t.timeScale}getClipTimeNormalized(e,t){return(e-t.start)/t.duration}evaluateWeight(e,t,r,s=!0){if(t<0||t>=r.length)return 0;const o=r[t];if(s||e>=o.start&&e<=o.end){let a=1;const l=!1;if(o.easeInDuration>0){const c=Math.min((e-o.start)/o.easeInDuration,1);a*=c}if(o.easeOutDuration>0&&!l){const c=Math.min((o.end-e)/o.easeOutDuration,1);a*=c}return a}return 0}}class rme{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 r=e.getRoot(),s=r.name+".position",o=r.name+".quaternion";tc&&console.log(t.name,t.tracks,s);for(const a of t.tracks)if(!(a.times.length<=0)){if(a.name.endsWith(s))this.rootStartPosition=new C().fromArray(a.values,0),this.rootEndPosition=new C().fromArray(a.values,a.values.length-3),this.rootPositionOffset=this.rootEndPosition.clone().sub(this.rootStartPosition),tc&&console.log(this.rootPositionOffset);else if(a.name.endsWith(o)&&(this.rootStartQuaternion=new Ce().fromArray(a.values,0),this.rootEndQuaternion=new Ce().fromArray(a.values,a.values.length-4),this.rootQuaternionOffset=this.rootEndQuaternion.clone().multiply(this.rootStartQuaternion),tc)){const l=new ii().setFromQuaternion(this.rootQuaternionOffset);console.log("ROT",l)}}}get hasOffsets(){return this.rootPositionOffset!==void 0||this.rootQuaternionOffset!==void 0}}class HS extends MA{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 C),d(this,"_totalOffsetRotation",new Ce),d(this,"_totalOffsetPosition2",new C),d(this,"_totalOffsetRotation2",new Ce),d(this,"_summedPos",new C),d(this,"_tempPos",new C),d(this,"_summedRot",new Ce),d(this,"_tempRot",new Ce),d(this,"_clipRotQuat",new Ce)}onDisable(){var e;(e=this.mixer)==null||e.stopAllAction()}onDestroy(){this.director.context.animations.unregisterAnimationMixer(this.mixer)}onStateChanged(){this._animator&&x8(this._animator.gameObject,this,this.director.isPlaying)}createHooks(e,t){var r,s;if(((r=t.tracks)==null?void 0:r.length)<=0){console.warn("No tracks in AnimationClip",t);return}const o=t.tracks[0].name.split("."),a=o[o.length-2],l=a+".position",c=a+".quaternion";let h=!1,u=!1;for(const p of t.tracks)p.name.endsWith(l)?(h=!0,this.createPositionInterpolant(t,e,p)):p.name.endsWith(c)&&(u=!0,this.createRotationInterpolant(t,e,p));if(!h||!u){const p=(s=this.mixer)==null?void 0:s.getRoot(),m=t.tracks[0],f=m.name.lastIndexOf("."),g=m.name.substring(0,f),v=g.substring(g.lastIndexOf(".")+1),y=p.getObjectByName(v);if(y)if(h){if(!u){const A=t.tracks[0].name.substring(0,f)+".quaternion";tc&&console.warn("Create quaternion track",v,y);const _=y.quaternion,b=new sa(A,[0,t.duration],[_.x,_.y,_.z,_.w,_.x,_.y,_.z,_.w]);t.tracks.push(b),this.createRotationInterpolant(t,e,b)}}else{const A=g+".position";tc&&console.warn("Create position track",v,y);const _=y.position,b=new kl(A,[0,t.duration],[_.x,_.y,_.z,_.x,_.y,_.z]);t.tracks.push(b),this.createPositionInterpolant(t,e,b)}}}bind(){if(!this._didBind){this._didBind=!0,tc&&console.log(this.models),this.mixer?this.target=this.mixer.getRoot():console.warn("No mixer was assigned to animation track");for(const e of this.actions){const t=new rme(e);this._actionOffsets.push(t)}this.target&&(this._animator=ie.getComponent(this.target,Wr)??null,this._animator&&x8(this._animator.gameObject,this,!0));for(const e of this.models){const t=e.asset,r=t.position,s=t.rotation;r&&r.x!==void 0&&(r.isVector3||(t.position=new C(r.x,r.y,r.z)),s.isQuaternion||(t.rotation=new Ce(s.x,s.y,s.z,s.w)))}this.ensureTrackOffsets()}}ensureTrackOffsets(){if(this.trackOffset){const e=this.trackOffset.position;e&&(e.isVector3||(this.trackOffset.position=new C(e.x,e.y,e.z)));const t=this.trackOffset.rotation;t&&(t.isQuaternion||(this.trackOffset.rotation=new Ce(t.x,t.y,t.z,t.w)))}}evaluate(e){var t,r,s,o,a,l,c;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 h=0,u=0,p=!1,m=!1,f=0;for(let g=0;g<this.clips.length;g++){const v=this.models[g],y=this.actions[g],A=v.asset;y.weight=0;const _=e>=v.start&&e<=v.end,b=v.preExtrapolationMode,x=v.postExtrapolationMode,E=g<this.clips.length-1?this.models[g+1]:null;let I=_,T=!1;if(!I&&!p&&v.end<e&&x!==ec.None?(!E||E.start>e)&&(I=!0,p=!0):g==0&&!I&&!m&&v.start>e&&b!==ec.None&&(!E||E.start<e)&&(I=!0,T=!0,m=!0),I){let R=1;R*=this.evaluateWeight(e,g,this.models,I),R*=this.director.weight;let D=_;if(T)switch(b){case ec.Hold:break;case ec.Loop:e+=v.start,D=!0;break;default:e+=v.start,D=!0;break}let M=this.getClipTime(e,v),P=0;const z=A.duration;if(T&&b===ec.Hold&&(M=0),D){if(A.loop)for(P+=Math.floor(M/(z+1e-6));M>z;)M-=z}else if(!_&&p)switch(x){case ec.Hold:M=this.getClipTime(v.end,v);break;case ec.Loop:M%=z;break;case ec.PingPong:const L=Math.floor(M/z)%2!==0;M%=z,L&&(M=z-M);break}v.reversed===!0?y.time=y.getClip().duration-M:y.time=M,y.timeScale=0;const V=Math.max(0,R);if(y.weight=V,f+=V,y.clampWhenFinished=!1,y.isRunning()||y.play(),this._useclipOffsets){const L=h==0?this._totalOffsetPosition:this._totalOffsetPosition2,H=h==0?this._totalOffsetRotation:this._totalOffsetRotation2;h<1&&(u=1-R),h+=1;const O=this._summedPos.set(0,0,0),F=this._tempPos.set(0,0,0),G=this._summedRot.identity(),J=this._tempRot.identity(),K=A.rotation;K&&(this._clipRotQuat.identity(),this._clipRotQuat.slerp(K,R));const oe=this._actionOffsets[g];if(oe.hasOffsets)for(let we=0;we<P;we++)oe.rootPositionOffset?F.copy(oe.rootPositionOffset):F.set(0,0,0),F.applyQuaternion(G),this._clipRotQuat&&F.applyQuaternion(this._clipRotQuat),oe.rootQuaternionOffset&&(J.copy(oe.rootQuaternionOffset),G.multiply(J)),O.add(F);this._clipRotQuat&&H.multiply(this._clipRotQuat),H.multiply(G),A.position&&O.add(A.position),L.add(O)}}}if(this._useclipOffsets&&(this._totalOffsetPosition.lerp(this._totalOffsetPosition2,u),this._totalOffsetRotation.slerp(this._totalOffsetRotation2,u)),this.__mixerError===void 0&&(tc||st())&&(r=(t=this._animator)==null?void 0:t.runtimeAnimatorController)!=null&&r.mixer&&this.mixer!==((o=(s=this._animator)==null?void 0:s.runtimeAnimatorController)==null?void 0:o.mixer)&&(this.__mixerError=!0,console.error("AnimationTrack mixer is not shared with the animator controller - this might result in the timeline to not animate properly. Please report a bug to the Needle Engine team!",this)),(a=this._animator)!=null&&a.runtimeAnimatorController){const g=Math.max(0,1-f);(c=(l=this._animator)==null?void 0:l.runtimeAnimatorController)==null||c.update(g)}else this.mixer.update(e)}createRotationInterpolant(e,t,r){var s;const o=r.createInterpolant.bind(r),a=new Ce;this.ensureTrackOffsets();const l=(s=this.trackOffset)==null?void 0:s.rotation;r.createInterpolant=()=>{const c=o(),h=c.evaluate.bind(c);return c.evaluate=u=>{var p;const m=h(u);if(a.set(m[0],m[1],m[2],m[3]),a.premultiply(this._totalOffsetRotation),l&&a.premultiply(l),this.director.animationCallbackReceivers)for(const f of this.director.animationCallbackReceivers)(p=f?.onTimelineRotation)==null||p.call(f,this.director,this.target,u,a);return m[0]=a.x,m[1]=a.y,m[2]=a.z,m[3]=a.w,m},c}}createPositionInterpolant(e,t,r){var s,o;const a=r.createInterpolant.bind(r),l=new C;this.ensureTrackOffsets();const c=(s=this.trackOffset)==null?void 0:s.rotation,h=(o=this.trackOffset)==null?void 0:o.position;let u;r.createInterpolant=()=>{const p=a(),m=p.evaluate.bind(p);return p.evaluate=f=>{var g,v,y;const A=m(f);if(l.set(A[0],A[1],A[2]),t.removeStartOffset&&(u===void 0?(u=null,u=(v=(g=this._actionOffsets.find(_=>_.clip===e))==null?void 0:g.rootStartPosition)==null?void 0:v.clone()):u!=null&&u.isVector3&&l.sub(u)),l.applyQuaternion(this._totalOffsetRotation),l.add(this._totalOffsetPosition),c&&l.applyQuaternion(c),h&&(l.x-=h.x,l.y+=h.y,l.z+=h.z),this.director.animationCallbackReceivers)for(const _ of this.director.animationCallbackReceivers)(y=_?.onTimelinePosition)==null||y.call(_,this.director,this.target,f,l);return A[0]=l.x,A[1]=l.y,A[2]=l.z,A},p}}}const sme=te("mutetimeline"),TA=class extends MA{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(n){const e=this.director.sourceId;return cu(e,n)}onAllowAudioChanged(n){for(let e=0;e<this.models.length;e++){const t=this.models[e];this.audio[e].setVolume(n?t.asset.volume:0)}}addModel(n){const e=new gI(this.listener);this.audio.push(e);const t=n;t._didTriggerPlay=!1,this.models.push(t)}onDisable(){for(const n of this.audio)n.isPlaying&&n.stop();for(const n of this.models)n._didTriggerPlay=!1}onDestroy(){for(const n of this.audio)n.source&&n?.disconnect();this.audio.length=0}onMuteChanged(){if(this.muted)for(let n=0;n<this.audio.length;n++){const e=this.audio[n];e!=null&&e.isPlaying&&e.stop()}}stop(){for(let n=0;n<this.audio.length;n++){const e=this.audio[n];e!=null&&e.isPlaying&&e.stop()}for(const n of this.models)n._didTriggerPlay=!1}onPauseChanged(){for(let n=0;n<this.audio.length;n++){const e=this.audio[n];e!=null&&e.isPlaying&&e.stop()}this._playableDirectorResumed=this.director.isPlaying}evaluate(n){if(sme||this.track.muted||this.director.speed<0)return;const e=this.director.context.application.muted,t=this._playableDirectorResumed;this._playableDirectorResumed=!1;const r=e?.1:0;for(let s=0;s<this.models.length;s++){const o=this.models[s],a=this.audio[s],l=o.asset;if((!a||!a.buffer)&&this.isInTimeRange(o,n-1,n+1)&&this.handleAudioLoading(o,a),Mn.userInteractionRegistered!==!1&&!(a===null||!a.buffer))if(a.playbackRate=this.director.context.time.timeScale*this.director.speed,a.loop=l.loop,n>=o.start&&n<=o.end&&n<this.director.duration){if(!a.isPlaying||!this.director.isPlaying)(t||!o._didTriggerPlay&&this.lastTime<n)&&(o.duration*o.timeScale>.3?a.offset=o.clipIn+(n-o.start)*o.timeScale:a.offset=0,tc&&console.log("Timeline Audio ("+this.track.name+") play with offset "+a.offset+" - "+o.asset.clip),a.play(r),o._didTriggerPlay=!0);else{const h=o.clipIn+(n-o.start)*o.timeScale,u=a.context.currentTime-a._startedAt+a.offset;Math.abs(h-u)>.3&&(a.offset=h,a.stop(),a.play(r))}let c=l.volume;if(this.track.volume!==void 0&&(c*=this.track.volume),e&&(c=0),o.easeInDuration>0){const h=Math.min((n-o.start)/o.easeInDuration,1);c*=h}if(o.easeOutDuration>0){const h=Math.min((o.end-n)/o.easeOutDuration,1);c*=h}a.setVolume(c*this.director.weight)}else o._didTriggerPlay=!1,this.director.isPlaying&&a.isPlaying&&a.stop()}this.lastTime=n}loadAudio(n,e=0,t=0){let r=null;const s=n-t,o=n+e;for(const a of this.models)if(this.isInTimeRange(a,s,o)){const l=this.audio[this.models.indexOf(a)],c=this.handleAudioLoading(a,l);c!==null&&(r===null&&(r=[]),r.push(c))}return r!==null?Promise.all(r):null}isInTimeRange(n,e,t){return e<=n.start&&t>=n.end||e>=n.start&&e<=n.end||t>=n.start&&t<=n.end}static dispose(){TA._audioBuffers.clear()}handleAudioLoading(n,e){this._audioLoader||(this._audioLoader=new Nx);const t=this.getAudioFilePath(n.asset.clip);if(TA._audioBuffers.get(t)){const s=TA._audioBuffers.get(t);return s.then(o=>{o&&e.setBuffer(o)}),s}tc&&console.warn("LOAD audio track",t,this.director.sourceId);const r=new Promise((s,o)=>{this._audioLoader.load(t,a=>{e.setBuffer(a),s(a)},void 0,a=>{console.error("Error loading audio",a),s(null)})});return TA._audioBuffers.set(t,r),r}};let IA=TA;d(IA,"_audioBuffers",new Map);class RA extends MA{constructor(){super(...arguments),d(this,"models",[]),d(this,"didTrigger",[]),d(this,"receivers",[])}evaluate(e){var t;if(this.track.muted)return;const r=this.director.context.time.deltaTime*1.5;for(let s=0;s<this.models.length;s++){const o=this.models[s],a=this.didTrigger[s],l=o.time-e;let c=!1;if(o.retroActive)c=l<=1e-6;else{const h=Math.abs(l);(h===0||h>=1e-5&&h<r)&&(c=!0)}if(c){if(!a)if(tc&&console.log("Trigger signal",e,o.time,o),this.didTrigger[s]=!0,((t=this.receivers)==null?void 0:t.length)<=0)Yg.invoke(o.asset);else for(const h of this.receivers)h&&h.invoke(o.asset)}else o.emitOnce||(this.didTrigger[s]=!1)}}}class WS extends MA{constructor(){super(...arguments),d(this,"models",[]),d(this,"timelines",[]),d(this,"_previousActiveModel",null)}resolveSourceObjects(e){for(let t=this.models.length-1;t>=0;t--){const r=this.models[t].asset;if(!r.sourceObject||typeof r.sourceObject!="object"){console.log("no source object, removing model",t,r),this.models.splice(t,1);continue}else{const s=ie.getComponent(r.sourceObject,id);this.timelines.push(s),s&&r.updateDirector&&(s.playOnAwake=!1)}}}evaluate(e){var t;this._previousActiveModel=null;for(let r=0;r<this.models.length;r++){const s=this.models[r],o=s.asset;if(e>=s.start&&e<=s.end){this._previousActiveModel=s;const a=this.getClipTime(e,s);if(o.controlActivation){const l=o.sourceObject;l.visible=!0}if(o.updateDirector){const l=this.timelines[r];l&&(l.isPlaying&&l.pause(),l.time=a,l.evaluate())}}else{const a=(t=this._previousActiveModel)==null?void 0:t.asset;if(o.controlActivation){const l=o.sourceObject;a?.sourceObject!==l&&(l.visible=!1)}}}}}var ome=Object.defineProperty,ame=Object.getOwnPropertyDescriptor,_8=(n,e,t,r)=>{for(var s=r>1?void 0:r?ame(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&ome(e,t,s),s};const Jg=te("debugtimeline");var yk;const Ak=(yk=class extends Be{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(n,e){this.createTrackFunctions[n]=e}get isPlaying(){return this._isPlaying}get isPaused(){return this._isPaused}get time(){return this._time}set time(n){typeof n=="number"&&!Number.isNaN(n)?this._time=n:(Jg||js())&&console.error("INVALID TIMELINE.TIME VALUE",n,this.name)}get duration(){return this._duration}set duration(n){this._duration=n}get weight(){return this._weight}set weight(n){this._weight=n}get speed(){return this._speed}set speed(n){this._speed=n}awake(){var n,e,t;Jg&&console.log(this,(n=this.playableAsset)==null?void 0:n.tracks),this.rebuildGraph(),this.isValid()||console.warn("PlayableDirector is not valid",this.playableAsset,(e=this.playableAsset)==null?void 0:e.tracks,Array.isArray((t=this.playableAsset)==null?void 0:t.tracks),this)}onEnable(){var n,e,t;for(const r of this._audioTracks)(n=r.onEnable)==null||n.call(r);for(const r of this._customTracks)(e=r.onEnable)==null||e.call(r);for(const r of this._animationTracks)(t=r.onEnable)==null||t.call(r);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 n,e,t;this.stop();for(const r of this._audioTracks)(n=r.onDisable)==null||n.call(r);for(const r of this._customTracks)(e=r.onDisable)==null||e.call(r);for(const r of this._animationTracks)(t=r.onDisable)==null||t.call(r);this._visibilityChangeEvt&&window.removeEventListener("visibilitychange",this._visibilityChangeEvt)}onDestroy(){var n;for(const e of this._allTracks)for(const t of e)(n=t.onDestroy)==null||n.call(t)}rebuildGraph(){this.isValid()&&(this.resolveBindings(),this.updateTimelineDuration(),this.setupAndCreateTrackHandlers())}async play(){if(!this.isValid())return;const n=this._isPaused==!0;if(this._isPaused=!1,!this._isPlaying){if(this._isPlaying=!0,n&&this.invokePauseChangedMethodsOnTracks(),this.waitForAudio){const e=[];for(const t of this._audioTracks){const r=t.loadAudio(this._time,1,0);r&&e.push(r)}if(e.length>0&&(await Promise.all(e),!this._isPlaying))return;for(;this._audioTracks.length>0&&this._isPlaying&&!Mn.userInteractionRegistered&&this.waitForAudio;)await Ll(200)}this.invokeStateChangedMethodsOnTracks(),this._internalUpdateRoutine=this.startCoroutine(this.internalUpdate(),Hi.LateUpdate)}}pause(){this.isValid()&&(this._isPlaying=!1,!this._isPaused&&(this._isPaused=!0,this.internalEvaluate(),this.invokePauseChangedMethodsOnTracks(),this.invokeStateChangedMethodsOnTracks()))}stop(){this._isStopping=!0;for(const t of this._audioTracks)t.stop();const n=this._isPaused==!0,e=this._isPlaying;this._isPlaying&&(this._time=0,this._isPlaying=!1,this._isPaused=!1,this.internalEvaluate(),n&&this.invokePauseChangedMethodsOnTracks()),this._isPlaying=!1,this._isPaused=!1,n&&!e&&this.invokePauseChangedMethodsOnTracks(),e&&this.invokeStateChangedMethodsOnTracks(),this._internalUpdateRoutine&&this.stopCoroutine(this._internalUpdateRoutine),this._internalUpdateRoutine=null,this._isStopping=!1}evaluate(){this.internalEvaluate(!0)}isValid(){return this.playableAsset&&this.playableAsset.tracks&&Array.isArray(this.playableAsset.tracks)}*forEachTrack(){for(const n of this._allTracks)for(const e of n)yield e}get audioTracks(){return this._audioTracks}resolveGuids(n){this._guidsMap=n}invokePauseChangedMethodsOnTracks(){var n;for(const e of this.forEachTrack())(n=e.onPauseChanged)==null||n.call(e)}invokeStateChangedMethodsOnTracks(){var n;for(const e of this.forEachTrack())(n=e.onStateChanged)==null||n.call(e,this._isPlaying)}*internalUpdate(){for(;this._isPlaying&&this.activeAndEnabled;)!this._isPaused&&this._isPlaying&&(this._time+=this.context.time.deltaTime*this.speed,this.internalEvaluate()),yield}internalEvaluate(n=!1){if(!this.isValid())return;let e=this._time;switch(this.extrapolationMode){case 0:this._speed>0?e=Math.min(e,this._duration):this._speed<0&&(e=Math.max(e,0)),this._time=e;break;case 1:e%=this._duration,this._time=e;break;case 2:if(e>this._duration){this.stop();return}break}const t=this._time;for(const r of this.playableAsset.tracks)if(!r.muted)switch(r.type){case zo.Activation:if(!n&&!this._isPlaying)continue;for(let s=0;s<r.outputs.length;s++){const o=r.outputs[s];if(typeof o=="object"){let a=!1;if(r.clips)for(const c of r.clips)c.start<=t&&t<=c.end&&(a=!0);const l=o;l.visible!==void 0&&l.visible!==a&&(l.visible=a,Jg&&console.warn(this.name,"set ActivationTrack-"+s,l.name,a,t))}}break}if(!this._isStopping)for(const r of this._animationTracks)r.evaluate(t);for(const r of this._audioTracks)r.evaluate(t);for(const r of this._signalTracks)r.evaluate(t);for(const r of this._controlTracks)r.evaluate(t);for(const r of this._customTracks)r.evaluate(t)}resolveBindings(){if(this._clonedPlayableAsset||(this._clonedPlayableAsset=!0,this.playableAsset=Nv(this.playableAsset)),!this.playableAsset||!this.playableAsset.tracks)return;const n=this.findRoot(this.gameObject);for(const e of this.playableAsset.tracks){for(let t=e.outputs.length-1;t>=0;t--){let r=e.outputs[t];if(typeof r=="string"){this._guidsMap&&this._guidsMap[r]&&(r=this._guidsMap[r]);const s=ie.findByGuid(r,n);s===null||typeof s!="object"?(e.outputs.splice(t,1),console.warn("Failed to resolve binding",r,e.name,e.type)):(Jg&&console.log("Resolved binding",r,"to",s),e.outputs[t]=s)}else if(r===null){if(e.outputs.splice(t,1),Ak.createTrackFunctions[e.type])continue;e.type!==zo.Audio&&e.type!==zo.Control&&e.type!==zo.Marker&&e.type!==zo.Signal&&console.warn("Missing binding",r,e.name,e.type,this.name,this.playableAsset.name)}}if(e.type===zo.Control&&e.clips)for(let t=0;t<e.clips.length;t++){const r=e.clips[t];let s=r.asset.sourceObject;if(typeof s=="string"){this._guidsMap&&this._guidsMap[s]&&(s=this._guidsMap[s]);const o=ie.findByGuid(s,n);o===null||typeof o!="object"?console.warn("Failed to resolve sourceObject binding",s,e.name,r):(Jg&&console.log("Resolved binding",s,"to",o),r.asset.sourceObject=o)}}}}findRoot(n){return n.parent?this.findRoot(n.parent):n}updateTimelineDuration(){if(this._duration=0,!(!this.playableAsset||!this.playableAsset.tracks)){for(const n of this.playableAsset.tracks)if(n.muted!==!0){if(n.clips)for(const e of n.clips)e.end>this._duration&&(this._duration=e.end);if(n.markers)for(const e of n.markers)e.time>this._duration&&(this._duration=e.time+.001)}}}setupAndCreateTrackHandlers(){var n,e,t;if(this._animationTracks.length=0,this._audioTracks.length=0,this._signalTracks.length=0,!this.playableAsset)return;let r=ie.findObjectOfType(ed,this.context);for(const s of this.playableAsset.tracks){const o=s.type,a=Ak.createTrackFunctions[o];if(a!=null){const l=a(this,s);if(typeof l.evaluate=="function"){l.director=this,l.track=s,this._customTracks.push(l);continue}}if(s.type===zo.Animation){if(!s.clips||s.clips.length<=0){Jg&&console.warn("Animation track has no clips",s);continue}for(let l=s.outputs.length-1;l>=0;l--){let c=s.outputs[l];if(c instanceof ye){const u=ie.getOrAddComponent(c,Wr);u&&(c=u)}const h=(n=c?.gameObject)==null?void 0:n.animations;if(h){const u=new HS;u.trackOffset=s.trackOffset,u.director=this,u.track=s;for(let p=0;p<s.clips.length;p++){const m=s.clips[p],f=m.asset;if(!f){console.error(`Timeline ${this.name}: clip #${p} on track "${s.name}" has no animation data`);continue}const g=f.clip;let v=g;if((typeof v=="string"||typeof v=="number")&&(v=h.find(A=>A.name===g)),!v){console.warn("Could not find animationClip for model",m,s.name,this.name,(e=this.playableAsset)==null?void 0:e.name);continue}c instanceof Wr&&c.runtimeAnimatorController&&(c.__internalDidAwakeAndStart||c.initializeRuntimeAnimatorController(),c.runtimeAnimatorController.mixer||c.runtimeAnimatorController.bind(c),u.mixer=c.runtimeAnimatorController.mixer),u.mixer||(u.mixer=new zx(c.gameObject),this.context.animations.registerAnimationMixer(u.mixer)),u.clips.push(v),u.mixer.uncacheAction(v),u.createHooks(m.asset,v);const y=u.mixer.clipAction(v);u.actions.push(y),u.models.push(m)}this._animationTracks.push(u)}}}else if(s.type===zo.Audio){if(!s.clips||s.clips.length<=0)continue;const l=new IA;l.director=this,l.track=s,l.audioSource=s.outputs.find(c=>c instanceof Mn),this._audioTracks.push(l),r||(r=(t=this.context.mainCameraComponent)==null?void 0:t.gameObject.addNewComponent(ed)),l.listener=r.listener;for(let c=0;c<s.clips.length;c++){const h=s.clips[c];l.addModel(h)}}else if(s.type===zo.Marker){const l=new RA;if(l.director=this,l.track=s,s.markers)for(const c of s.markers)switch(c.type){case vk.Signal:l.models.push(c),l.didTrigger.push(!1);break}if(l!==null&&l.models.length>0){const c=ie.getComponent(this.gameObject,Yg);c&&(l.receivers.push(c),this._signalTracks.push(l))}}else if(s.type===zo.Signal){const l=new RA;if(l.director=this,l.track=s,s.markers)for(const c of s.markers)l.models.push(c),l.didTrigger.push(!1);for(const c of s.outputs)l.receivers.push(c);this._signalTracks.push(l)}else if(s.type===zo.Control){const l=new WS;if(l.director=this,l.track=s,s.clips)for(const c of s.clips)l.models.push(c);l.resolveSourceObjects(this.context),this._controlTracks.push(l)}}}setAudioTracksAllowPlaying(n){for(const e of this._audioTracks)e.onAllowAudioChanged(n)}registerAnimationCallback(n){this.animationCallbackReceivers.push(n)}unregisterAnimationCallback(n){const e=this.animationCallbackReceivers.indexOf(n);e!==-1&&this.animationCallbackReceivers.splice(e,1)}},d(yk,"createTrackFunctions",{}),yk);let id=Ak;_8([w()],id.prototype,"playOnAwake",2),_8([w()],id.prototype,"extrapolationMode",2);const XS=Symbol("objectIsAnimatedData");function x8(n,e,t){if(!n)return;if(n[XS]===void 0){if(!t)return;n[XS]=new Set}const r=n[XS];t?r.add(e):r.has(e)&&r.delete(e)}function lme(n){if(!n)return!1;const e=n[XS];return e!==void 0&&e.size>0}di.registerCallback(Ci.ContextCreated,n=>{const e=n.context.domElement.getAttribute("autoplay");if(e!==void 0&&(e===""||e==="true"||e==="1")&&n.files)for(const t of n.files)ie.foreachComponent(t.file.scene,r=>{if(r.enabled!==!1){if(r instanceof Es&&r.playAutomatically||r instanceof Wr||r instanceof id&&r.playOnAwake===!0)return!0;if(r instanceof Es)return r.playAutomatically=!0,!0;if(r instanceof id)return r.playOnAwake=!0,!0}},!0)!==!0&&Bg.assignAnimationsFromFile(t.file,{createAnimationComponent:(r,s)=>gl(r,Es)})});class cme{constructor(){d(this,"_context")}get context(){return this._context??kt.Current}get isStateMachineBehaviour(){return!0}}class PA{constructor(e,t,r,s){d(this,"name"),d(this,"nameHash"),d(this,"normalizedTime"),d(this,"length"),d(this,"speed"),d(this,"action"),d(this,"hasTransitions");var o;this.name=e.name,this.nameHash=e.hash,this.normalizedTime=t,this.length=r,this.speed=s,this.action=e.motion.action||null,this.hasTransitions=((o=e.transitions)==null?void 0:o.length)>0||!1}}function w8(n,e){return{name:"Empty",isLooping:!1,guid:e?.generateUUID()??ui.generateUUID(),index:-1,clip:new zs(n,0,[])}}var nd=(n=>(n[n.If=1]="If",n[n.IfNot=2]="IfNot",n[n.Greater=3]="Greater",n[n.Less=4]="Less",n[n.Equals=6]="Equals",n[n.NotEqual=7]="NotEqual",n))(nd||{}),bk=(n=>(n[n.Float=1]="Float",n[n.Int=3]="Int",n[n.Bool=4]="Bool",n[n.Trigger=9]="Trigger",n))(bk||{});const Er=te("debuganimatorcontroller"),qS=te("debugrootmotion");class ea{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,Er&&console.log(this)}static createFromClips(e,t={looping:!1,autoTransition:!0,transitionDuration:0}){const r=[];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 p=o;(t.autoTransition===void 0||t.autoTransition===!0)&&(p=(o+1)%e.length),l.push({exitTime:1-u,offset:0,duration:h,hasExitTime:!0,destinationState:p,conditions:[]})}const c={name:a.name,hash:o,motion:{name:a.name,clip:a,isLooping:t?.looping??!1},transitions:l,behaviours:[]};r.push(c)}const s={name:"AnimatorController",guid:new Dr(Date.now()).generateUUID(),parameters:[],layers:[{name:"Base Layer",stateMachine:{defaultState:0,states:r}}]};return new ea(s)}play(e,t=-1,r=Number.NEGATIVE_INFINITY,s=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){Er&&console.log("transition to ",a),this.transitionTo(a,s,r);return}console.warn("Could not find "+e+" to play")}reset(){this.setStartTransition()}setBool(e,t){var r,s;const o=typeof e=="string"?"name":"hash";return(s=(r=this.model)==null?void 0:r.parameters)==null?void 0:s.filter(a=>a[o]===e).forEach(a=>a.value=t)}getBool(e){var t,r,s;const o=typeof e=="string"?"name":"hash";return((s=(r=(t=this.model)==null?void 0:t.parameters)==null?void 0:r.find(a=>a[o]===e))==null?void 0:s.value)??!1}setFloat(e,t){var r,s;const o=typeof e=="string"?"name":"hash",a=(s=(r=this.model)==null?void 0:r.parameters)==null?void 0:s.filter(l=>l[o]===e);return a.forEach(l=>l.value=t),a?.length>0}getFloat(e){var t,r,s;const o=typeof e=="string"?"name":"hash";return((s=(r=(t=this.model)==null?void 0:t.parameters)==null?void 0:r.find(a=>a[o]===e))==null?void 0:s.value)??0}setInteger(e,t){var r,s;const o=typeof e=="string"?"name":"hash";return(s=(r=this.model)==null?void 0:r.parameters)==null?void 0:s.filter(a=>a[o]===e).forEach(a=>a.value=t)}getInteger(e){var t,r,s;const o=typeof e=="string"?"name":"hash";return((s=(r=(t=this.model)==null?void 0:t.parameters)==null?void 0:r.find(a=>a[o]===e))==null?void 0:s.value)??0}setTrigger(e){var t,r;Er&&console.log("SET TRIGGER",e);const s=typeof e=="string"?"name":"hash";return(r=(t=this.model)==null?void 0:t.parameters)==null?void 0:r.filter(o=>o[s]===e).forEach(o=>o.value=!0)}resetTrigger(e){var t,r;const s=typeof e=="string"?"name":"hash";return(r=(t=this.model)==null?void 0:t.parameters)==null?void 0:r.filter(o=>o[s]===e).forEach(o=>o.value=!1)}getTrigger(e){var t,r,s;const o=typeof e=="string"?"name":"hash";return((s=(r=(t=this.model)==null?void 0:t.parameters)==null?void 0:r.find(a=>a[o]===e))==null?void 0:s.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 r of t.stateMachine.states)if(r.name===e||r.hash==e)return r}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,r=t<=0?0:Math.abs(e.time/t);return new PA(this._activeState,r,t,this._speed)}get currentAction(){return this._activeState&&this._activeState.motion.action||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,r;e?this.animator!==e&&(this._mixer&&(this._mixer.stopAllAction(),(t=this.context)==null||t.animations.unregisterAnimationMixer(this._mixer)),this.animator=e,this._mixer=new zx(this.animator.gameObject),(r=this.context)==null||r.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;Er&&console.warn("AnimatorController clone()",this.model);const e=Nv(this.model,(t,r,s)=>s==null?!0:!(s.type==="Object3D"||s.isObject3D===!0||oz(s)||s.tracks!==void 0||s instanceof ea));return console.assert(e!==this.model),new ea(e)}update(e){var t,r;if(!this.animator)return;this.evaluateTransitions(),this.updateActiveStates(e);const s=this.animator.context.time.deltaTime;this.animator.applyRootMotion&&((t=this.rootMotionHandler)==null||t.onBeforeUpdate(e)),this._mixer.update(s),this.animator.applyRootMotion&&((r=this.rootMotionHandler)==null||r.onAfterUpdate(e))}get activeState(){return this._activeState}updateActiveStates(e){for(let t=0;t<this._activeStates.length;t++){const r=this._activeStates[t],s=r.motion;if(!s.action)this._activeStates.splice(t,1),t--;else{const o=s.action;o.weight=e,o.getEffectiveWeight()<=0&&!o.isRunning()&&(Er&&console.debug("REMOVE",r.name,o.getEffectiveWeight(),o.isRunning(),o.isScheduled()),this._activeStates.splice(t,1),t--)}}}setStartTransition(){var e;this.model.layers.length>1&&(Er||st())&&console.warn("Multiple layers are not supported yet "+((e=this.animator)==null?void 0:e.name));for(const t of this.model.layers){const r=t.stateMachine;r.defaultState===void 0&&(Er&&console.warn("AnimatorController default state is undefined, will assign state 0 as default",t),r.defaultState=0);const s=r.states[r.defaultState];this.transitionTo(s,0,this.normalizedStartOffset);break}}evaluateTransitions(){var e;let t=!1;if(!this._activeState){if(this.setStartTransition(),!this._activeState)return;t=!0}const r=this._activeState,s=r.motion.action;for(const a of r.transitions){if(!a.hasExitTime&&a.conditions.length<=0)continue;let l=!0;for(const c of a.conditions)if(!this.evaluateCondition(c)){l=!1;break}if(l)if(s){const c=r.motion.clip.duration,h=c<=0?1:Math.abs(s.time/c);let u=a.exitTime;s.timeScale<0&&(u=1-u);let p=!1;if(a.hasExitTime?s.timeScale>0?p=h>=a.exitTime:s.timeScale<0&&(p=1-h>=a.exitTime):p=!0,p){for(const m of a.conditions){const f=this.model.parameters.find(g=>g.name===m.parameter);f?.type===bk.Trigger&&f.value&&(f.value=!1)}if(s.clampWhenFinished=!0,Er){const m=this.getState(a.destinationState,0);console.log(`Transition to ${a.destinationState} / ${m?.name}`,a,`
|
|
5734
5734
|
Timescale: `+s.timeScale,`
|
|
5735
5735
|
Normalized time: `+h.toFixed(3),`
|
|
@@ -6212,7 +6212,7 @@ Texture:`,r),this.setLightmapDebugMaterial()):f0&&console.log("Use debuglightmap
|
|
|
6212
6212
|
}
|
|
6213
6213
|
`};class pD extends Rt{constructor(e){super({type:"LineMaterial",uniforms:gf.clone(Lr.line.uniforms),vertexShader:Lr.line.vertexShader,fragmentShader:Lr.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 bQ=new C,_Q=new C,es=new Ye,ts=new Ye,gc=new Ye,mD=new C,fD=new ve,is=new Vx,xQ=new C,MC=new xi,TC=new wn,vc=new Ye;let yc,bm;function wQ(n,e,t){return vc.set(0,0,-e,1).applyMatrix4(n.projectionMatrix),vc.multiplyScalar(1/vc.w),vc.x=bm/t.width,vc.y=bm/t.height,vc.applyMatrix4(n.projectionMatrixInverse),vc.multiplyScalar(1/vc.w),Math.abs(Math.max(vc.x,vc.y))}function t0e(n,e){const t=n.matrixWorld,r=n.geometry,s=r.attributes.instanceStart,o=r.attributes.instanceEnd,a=Math.min(r.instanceCount,s.count);for(let l=0,c=a;l<c;l++){is.start.fromBufferAttribute(s,l),is.end.fromBufferAttribute(o,l),is.applyMatrix4(t);const h=new C,u=new C;yc.distanceSqToSegment(is.start,is.end,u,h),u.distanceTo(h)<bm*.5&&e.push({point:u,pointOnLine:h,distance:yc.origin.distanceTo(u),object:n,face:null,faceIndex:l,uv:null,uv1:null})}}function i0e(n,e,t){const r=e.projectionMatrix,s=n.material.resolution,o=n.matrixWorld,a=n.geometry,l=a.attributes.instanceStart,c=a.attributes.instanceEnd,h=Math.min(a.instanceCount,l.count),u=-e.near;yc.at(1,gc),gc.w=1,gc.applyMatrix4(e.matrixWorldInverse),gc.applyMatrix4(r),gc.multiplyScalar(1/gc.w),gc.x*=s.x/2,gc.y*=s.y/2,gc.z=0,mD.copy(gc),fD.multiplyMatrices(e.matrixWorldInverse,o);for(let p=0,m=h;p<m;p++){if(es.fromBufferAttribute(l,p),ts.fromBufferAttribute(c,p),es.w=1,ts.w=1,es.applyMatrix4(fD),ts.applyMatrix4(fD),es.z>u&&ts.z>u)continue;if(es.z>u){const A=es.z-ts.z,_=(es.z-u)/A;es.lerp(ts,_)}else if(ts.z>u){const A=ts.z-es.z,_=(ts.z-u)/A;ts.lerp(es,_)}es.applyMatrix4(r),ts.applyMatrix4(r),es.multiplyScalar(1/es.w),ts.multiplyScalar(1/ts.w),es.x*=s.x/2,es.y*=s.y/2,ts.x*=s.x/2,ts.y*=s.y/2,is.start.copy(es),is.start.z=0,is.end.copy(ts),is.end.z=0;const f=is.closestPointToPointParameter(mD,!0);is.at(f,xQ);const g=ui.lerp(es.z,ts.z,f),v=g>=-1&&g<=1,y=mD.distanceTo(xQ)<bm*.5;if(v&&y){is.start.fromBufferAttribute(l,p),is.end.fromBufferAttribute(c,p),is.start.applyMatrix4(o),is.end.applyMatrix4(o);const A=new C,_=new C;yc.distanceSqToSegment(is.start,is.end,_,A),t.push({point:_,pointOnLine:A,distance:yc.origin.distanceTo(_),object:n,face:null,faceIndex:p,uv:null,uv1:null})}}}class n0e extends me{constructor(e=new AQ,t=new pD({color:Math.random()*16777215})){super(e,t),this.isLineSegments2=!0,this.type="LineSegments2"}computeLineDistances(){const e=this.geometry,t=e.attributes.instanceStart,r=e.attributes.instanceEnd,s=new Float32Array(2*t.count);for(let a=0,l=0,c=t.count;a<c;a++,l+=2)bQ.fromBufferAttribute(t,a),_Q.fromBufferAttribute(r,a),s[l]=l===0?0:s[l-1],s[l+1]=s[l]+bQ.distanceTo(_Q);const o=new jx(s,2,1);return e.setAttribute("instanceDistanceStart",new Io(o,1,0)),e.setAttribute("instanceDistanceEnd",new Io(o,1,1)),this}raycast(e,t){const r=this.material.worldUnits,s=e.camera;s===null&&!r&&console.error('LineSegments2: "Raycaster.camera" needs to be set in order to raycast against LineSegments2 while worldUnits is set to false.');const o=e.params.Line2!==void 0&&e.params.Line2.threshold||0;yc=e.ray;const a=this.matrixWorld,l=this.geometry,c=this.material;bm=c.linewidth+o,l.boundingSphere===null&&l.computeBoundingSphere(),TC.copy(l.boundingSphere).applyMatrix4(a);let h;if(r)h=bm*.5;else{const p=Math.max(s.near,TC.distanceToPoint(yc.origin));h=wQ(s,p,c.resolution)}if(TC.radius+=h,yc.intersectsSphere(TC)===!1)return;l.boundingBox===null&&l.computeBoundingBox(),MC.copy(l.boundingBox).applyMatrix4(a);let u;if(r)u=bm*.5;else{const p=Math.max(s.near,MC.distanceToPoint(yc.origin));u=wQ(s,p,c.resolution)}MC.expandByScalar(u),yc.intersectsBox(MC)!==!1&&(r?t0e(this,t):i0e(this,s,t))}}class SQ extends AQ{constructor(){super(),this.isLineGeometry=!0,this.type="LineGeometry"}setPositions(e){const t=e.length-3,r=new Float32Array(2*t);for(let s=0;s<t;s+=3)r[2*s]=e[s],r[2*s+1]=e[s+1],r[2*s+2]=e[s+2],r[2*s+3]=e[s+3],r[2*s+4]=e[s+4],r[2*s+5]=e[s+5];return super.setPositions(r),this}setColors(e){const t=e.length-3,r=new Float32Array(2*t);for(let s=0;s<t;s+=3)r[2*s]=e[s],r[2*s+1]=e[s+1],r[2*s+2]=e[s+2],r[2*s+3]=e[s+3],r[2*s+4]=e[s+4],r[2*s+5]=e[s+5];return super.setColors(r),this}fromLine(e){const t=e.geometry;return this.setPositions(t.attributes.position.array),this}}class r0e extends n0e{constructor(e=new SQ,t=new pD({color:Math.random()*16777215})){super(e,t),this.isLine2=!0,this.type="Line2"}}class IC extends Be{}var s0e=Object.defineProperty,o0e=Object.getOwnPropertyDescriptor,_m=(n,e,t,r)=>{for(var s=r>1?void 0:r?o0e(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&s0e(e,t,s),s};const CQ=te("debugwebxr");class Da extends Be{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",e=>e.type==="SkinnedMesh"?"continue in children":!0)}onUpdateXR(e){const t=e.xr.rig;if(!(t!=null&&t.gameObject)||e.xr.isPassThrough)return;const r=e.xr.leftController,s=e.xr.rightController;r&&this.onHandleMovement(r,t.gameObject),s&&(this.onHandleRotation(s,t.gameObject),this.useTeleport&&this.onHandleTeleport(s,t.gameObject))}onLeaveXR(e){for(const t of this._lines)t.removeFromParent();for(const t of this._hitDiscs)t?.removeFromParent()}onBeforeRender(){var e;(e=this.context.xr)!=null&&e.running&&(this.showRays&&this.renderRays(this.context.xr),this.showHits&&this.renderHits(this.context.xr))}onHandleMovement(e,t){const r=e.getStick("xr-standard-thumbstick"),s=new C(r.x,0,r.y);s.multiplyScalar(this.context.time.deltaTimeUnscaled*this.movementSpeed);const o=Vi(t);s.multiplyScalar(o.x),s.applyQuaternion(e.xr.poseOrientation),s.y=0,s.applyQuaternion(t.worldQuaternion),t.position.add(s),t.updateMatrixWorld()}onHandleRotation(e,t){const r=e.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 s=r>0?1:-1;t.rotateY(s*it.toRadians(this.rotationStep))}}onHandleTeleport(e,t){var r;const s=e.getStick("xr-standard-thumbstick");if(this._didTeleport)s.y<.2&&(this._didTeleport=!1);else if(s.y>.8){this._didTeleport=!0;const o=this.context.physics.raycastFromRay(e.ray)[0];let a=o?.point;if(!a){this._plane||(this._plane=new ms(new C(0,1,0),0));const l=t.worldPosition;this._plane.setFromNormalAndCoplanarPoint(new C(0,1,0),l);const c=e.ray;a=l.clone(),this._plane.intersectLine(new Vx(c.origin,pi(c.direction).multiplyScalar(1e4).add(c.origin)),a),a.distanceTo(l)>t.scale.x*10&&(a=null)}if(a){if(this.useTeleportTarget&&!ie.getComponentInParent(o.object,IC))return;CQ&&At.DrawSphere(a,.025,16711680,5);const l=a.clone();this.useTeleportFade?(r=e.xr.fadeTransition())==null||r.then(()=>{t.worldPosition=l}):t.worldPosition=l}}}renderRays(e){for(let t=0;t<this._lines.length;t++){const r=this._lines[t];r&&(r.visible=!1)}for(let t=0;t<e.controllers.length;t++){const r=e.controllers[t];let s=this._lines[t];if(!r.connected||!r.isTracking||!r.ray||r.targetRayMode==="transient-pointer"||!r.hasSelectEvent){s&&(s.visible=!1);continue}s||(s=this.createRayLineObject(),s.scale.z=.5,this._lines[t]=s),r.updateRayWorldPosition(),r.updateRayWorldQuaternion();const o=r.rayWorldPosition,a=r.rayWorldQuaternion;s.position.copy(o),s.quaternion.copy(a);const l=e.rigScale,c=this._hitDistances[t]??l;s.scale.set(l,l,c),s.visible=!0,s.layers.disableAll(),s.layers.enable(2),s.parent!==this.context.scene&&this.context.scene.add(s)}}renderHits(e){for(const t of this._hitDiscs){if(!t)continue;const r=t.controller;if(!r||!r.connected||!r.isTracking){t.visible=!1;continue}}for(let t=0;t<e.controllers.length;t++){const r=e.controllers[t];if(!r.connected||!r.isTracking||!r.ray||!r.hasSelectEvent)continue;const s=this.context.time.smoothedFps>=59?1:10;if((this.context.time.frame+r.index)%s!==0){const l=this._hitDiscs[t];l&&l.hit&&(l.visible=!0,this.hitPointerSetPosition(r,l,l.hit.distance));continue}const o=this.context.physics.raycastFromRay(r.ray,{testObject:this.hitPointRaycastFilter})[0];this._hitDistances[t]=o?.distance;let a=this._hitDiscs[t];if(a&&(a.controller=r,a.hit=o),o){const l=e.rigScale??1;CQ&&(At.DrawWireSphere(o.point,.025*l,16711680),At.DrawLabel(pi(0,.2,0).add(o.point),o.object.name,.02,0)),a||(a=this.createHitPointObject(),this._hitDiscs[t]=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(r,a,o.distance);const h=o.normal.applyQuaternion(Mi(o.object));a.quaternion.setFromUnitVectors(a0e,h)}else this.hitPointerSetPosition(r,a,o.distance);a.parent!==this.context.scene&&this.context.scene.add(a)}else this._hitDiscs[t]&&(this._hitDiscs[t].visible=!1)}}hitPointerSetPosition(e,t,r){t.position.copy(e.rayWorldPosition),t.position.add(pi(0,0,r-.01).applyQuaternion(e.rayWorldQuaternion))}createHitPointObject(){var e=new ye;const t=new me(new ja(.3,6,6),new $t({color:15658734,opacity:.7,transparent:!0,depthTest:!1,side:yi}));return t.layers.disableAll(),t.layers.enable(2),e.add(t),e}createRayLineObject(){const e=new r0e;e.layers.disableAll(),e.layers.enable(2);const t=new SQ;e.geometry=t;const r=new Float32Array(9);r.set([0,0,.02,0,0,.4,0,0,1]),t.setPositions(r);const s=new Float32Array(9);s.set([1,1,1,.1,.1,.1,0,0,0]),t.setColors(s);const o=new pD({color:16777215,vertexColors:!0,worldUnits:!0,linewidth:.004,transparent:!0,blending:Ld,dashed:!1,alphaToCoverage:!0});return e.material=o,e}}_m([w()],Da.prototype,"movementSpeed",2),_m([w()],Da.prototype,"rotationStep",2),_m([w()],Da.prototype,"useTeleport",2),_m([w()],Da.prototype,"useTeleportTarget",2),_m([w()],Da.prototype,"useTeleportFade",2),_m([w()],Da.prototype,"showRays",2),_m([w()],Da.prototype,"showHits",2);const a0e=new C(0,1,0);var l0e=Object.defineProperty,c0e=Object.getOwnPropertyDescriptor,xo=(n,e,t,r)=>{for(var s=r>1?void 0:r?c0e(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&l0e(e,t,s),s};const cb=te("debugwebxr"),h0e=te("debugusdz");class Ir extends Be{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",e=>{cb&&console.log("WebXR.onAvatarSpawned",e),ie.getComponentInChildren(e,od)??(i=ie.addComponent(e,od))}),d(this,"_buttonFactory"),d(this,"_buttons",[])}awake(){wt.getXRSync(this.context)}onEnable(){var e,t;window.location.protocol!=="https:"&&Di('<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&&(ie.findObjectOfType(Rn)||(cb&&console.log("WebXR: Adding USDZExporter"),this._usdzExporter=ie.addComponent(this.gameObject,Rn),this._usdzExporter.objectToExport=this.context.scene,this._usdzExporter.autoExportAnimations=!0,this._usdzExporter.autoExportAudioSources=!0)),this.handleCreatingHTML(),this.handleOfferSession(),this.defaultAvatar||(cb&&console.warn("WebXR: No default avatar set, using static default avatar"),this.defaultAvatar=new ti("https://cdn.needle.tools/static/avatars/DefaultAvatar.glb")),this.defaultAvatar&&(this._playerSync=this.gameObject.getOrAddComponent(Kg),this._playerSync.autoSync=!1),this._playerSync&&(this._playerSync.asset=this.defaultAvatar,(e=this._playerSync.onPlayerSpawned)==null||e.removeEventListener(this.onAvatarSpawned),(t=this._playerSync.onPlayerSpawned)==null||t.addEventListener(this.onAvatarSpawned))}onDisable(){var e;(e=this._usdzExporter)==null||e.destroy(),this.removeButtons()}async handleOfferSession(){return this.createVRButton&&await wt.isVRSupported()&&this.createVRButton?wt.offerSession("immersive-vr","default",this.context):this.createARButton&&await wt.isARSupported()&&this.createARButton?wt.offerSession("immersive-ar","default",this.context):!1}get session(){return wt.active??null}get sessionMode(){return wt.activeMode??null}async enterVR(e){return wt.start("immersive-vr",e,this.context)}async enterAR(e){return wt.start("immersive-ar",e,this.context)}exitXR(){wt.stop()}onBeforeXR(e,t){e=="immersive-ar"&&this.useDepthSensing&&(t.optionalFeatures=t.optionalFeatures||[],t.optionalFeatures.push("depth-sensing"))}async onEnterXR(e){cb&&console.log("WebXR onEnterXR"),this._previousXRState=eo.Global.Mask;const t=e.xr.isVR;if(eo.Global.Set(t?rc.VR:rc.AR),this.usePlacementReticle&&e.xr.isAR){let s=ie.findObjectOfType(io);if(s)cb&&console.log("WebXR: WebARSessionRoot already exists, not creating a new one");else{const o=new ye;for(const a of this.context.scene.children)o.add(a);this.context.scene.add(o),s=ie.addComponent(o,io),this._createdComponentsInSession.push(s),s.arScale=this.arSceneScale,s.arTouchTransform=this.usePlacementAdjustment,s.useXRAnchor=this.useXRAnchor}}this.useDefaultControls&&this.setDefaultMovementEnabled(!0),(this.showControllerModels||this.showHandModels)&&this.setDefaultControllerRenderingEnabled(!0);let r=ie.findObjectOfType(wA);r||(r=this.gameObject.addNewComponent(wA)),this.createLocalAvatar(e.xr)}onLeaveXR(e){var t;eo.Global.Set(this._previousXRState),(t=this._playerSync)==null||t.destroyInstance();for(const r of this._createdComponentsInSession)r.destroy();this._createdComponentsInSession.length=0,this.handleOfferSession()}setDefaultMovementEnabled(e){let t=this.gameObject.getComponent(Da);return!t&&e&&(t=this.gameObject.addComponent(Da),this._createdComponentsInSession.push(t)),t&&(t.enabled=e),t}setDefaultControllerRenderingEnabled(e){let t=this.gameObject.getComponent(fc);return!t&&e&&(t=this.gameObject.addComponent(fc),this._createdComponentsInSession.push(t),t.createControllerModel=this.showControllerModels,t.createHandModel==this.showHandModels),t&&(t.enabled=e),t}async createLocalAvatar(e){this._playerSync&&e.running&&(this._playerSync.asset=this.defaultAvatar,await this._playerSync.getInstance())}getButtonsContainer(){return this.getButtonsFactory()}getButtonsFactory(){return this._buttonFactory||(this._buttonFactory=Am.getOrCreate()),this._buttonFactory}handleCreatingHTML(){if(this.createARButton||this.createVRButton||this.useQuicklookExport){if((vp()&&Lf()||h0e)&&this.useQuicklookExport){const e=ie.findObjectOfType(Rn);if(!e||e&&e.allowCreateQuicklookButton){const t=this.getButtonsFactory().createQuicklookButton();this.addButton(t,50)}}if(this.createARButton){const e=this.getButtonsFactory().createARButton();this.addButton(e,50)}if(this.createVRButton){const e=this.getButtonsFactory().createVRButton();this.addButton(e,50)}}if(this.createSendToQuestButton&&!ew()&&wt.isVRSupported().then(e=>{if(!e){const t=this.getButtonsFactory().createSendToQuestButton();this.addButton(t,50)}}),this.createQRCode&&!aa()){const e=PS(pc);e&&e.createQRCodeButton===!1?st()&&console.warn("WebXR: QRCode button is disabled in the Needle Menu component"):wt.isXRSupported().then(t=>{if(fp()||!t){const r=yh.getOrCreate().createQRCode();this.addButton(r,50)}})}}addButton(e,t){this._buttons.push(e),e.setAttribute("priority",t.toString()),this.context.menu.appendChild(e)}removeButtons(){for(const e of this._buttons)e.remove();this._buttons.length=0}}xo([w()],Ir.prototype,"createVRButton",2),xo([w()],Ir.prototype,"createARButton",2),xo([w()],Ir.prototype,"createSendToQuestButton",2),xo([w()],Ir.prototype,"createQRCode",2),xo([w()],Ir.prototype,"useDefaultControls",2),xo([w()],Ir.prototype,"showControllerModels",2),xo([w()],Ir.prototype,"showHandModels",2),xo([w()],Ir.prototype,"usePlacementReticle",2),xo([w()],Ir.prototype,"usePlacementAdjustment",2),xo([w()],Ir.prototype,"arSceneScale",2),xo([w()],Ir.prototype,"useXRAnchor",2),xo([w()],Ir.prototype,"useQuicklookExport",2),xo([w()],Ir.prototype,"useDepthSensing",2),xo([w(ti)],Ir.prototype,"defaultAvatar",2);class RC{get extensionName(){return"Physics"}onExportObject(e,t,r){const s=ie.getComponents(e,Oi).filter(c=>c.enabled),o=ie.getComponents(e,Vo).filter(c=>c.enabled&&!c.isTrigger);let a=s.length>0?s[0]:null;const l=o.length>0?o[0]:null;l&&!a&&(a=new Oi,a.isKinematic=!0),a&&t.addEventListener("serialize",(c,h)=>{var u,p,m;if(a){if(c.appendLine(),c.beginBlock('def RealityKitComponent "RigidBody"',"{",!0),a.useGravity||c.appendLine("bool gravityEnabled = 0"),c.appendLine('uniform token info:id = "RealityKit.RigidBody"'),a.isKinematic&&c.appendLine('token motionType = "Kinematic"'),c.beginBlock('def RealityKitStruct "massFrame"',"{",!0),c.appendLine(`float m_mass = ${a.mass}`),c.beginBlock('def RealityKitStruct "m_pose"',"{",!0),c.appendLine(`float3 position = (${a.centerOfMass.x}, ${a.centerOfMass.y}, ${a.centerOfMass.z})`),c.closeBlock("}"),c.closeBlock("}"),o.length>0){const f=o[0];c.beginBlock('def RealityKitStruct "material"',"{",!0);const g=f.sharedMaterial;g&&g.dynamicFriction!==void 0&&c.appendLine(`double dynamicFriction = ${(u=f.sharedMaterial)==null?void 0:u.dynamicFriction}`),g&&g.bounciness!==void 0&&c.appendLine(`double restitution = ${(p=f.sharedMaterial)==null?void 0:p.bounciness}`),g&&g.staticFriction!==void 0&&c.appendLine(`double staticFriction = ${(m=f.sharedMaterial)==null?void 0:m.staticFriction}`),c.closeBlock("}")}c.closeBlock("}")}}),l&&(t.addEventListener("serialize",(c,h)=>{var u;c.beginBlock('def RealityKitComponent "Collider"',"{",!0),c.appendLine("uint group = 1"),c.appendLine('uniform token info:id = "RealityKit.Collider"'),c.appendLine("uint mask = 4294967295");const p=l.isTrigger?"Trigger":"Default";if(c.appendLine(`token type = "${p}"`),c.beginBlock('def RealityKitStruct "Shape"',"{",!0),l instanceof i0){const m=l;c.appendLine('token shapeType = "Sphere"'),c.appendLine(`float radius = ${m.radius}`)}else if(l instanceof n0){const m=l;c.appendLine('token shapeType = "Box"'),c.appendLine(`float3 extent = (${m.size.x}, ${m.size.y}, ${m.size.z})`)}else if(l instanceof Ch){const m=l;c.appendLine('token shapeType = "Capsule"'),c.appendLine(`float radius = ${m.radius}`),c.appendLine(`float height = ${m.height}`)}else if(l instanceof cm&&(u=l.sharedMesh)!=null&&u.geometry){const m=l.sharedMesh.geometry;m.boundingBox||m.computeBoundingBox();const f=l.sharedMesh.geometry.boundingBox;f&&(c.appendLine('token shapeType = "Box"'),c.appendLine(`float3 extent = (${f.max.x-f.min.x}, ${f.max.y-f.min.y}, ${f.max.z-f.min.z})`),console.log("[USDZ] Only Box, Sphere, and Capsule colliders are supported in visionOS/iOS. MeshCollider will be exported as Box",l))}else console.warn("[USDZ] Only Box, Sphere, and Capsule colliders are supported in visionOS/iOS. Ignoring collider:",l);c.beginBlock('def RealityKitStruct "pose"',"{",!0),c.closeBlock("}"),c.closeBlock("}"),c.closeBlock("}")}),o.length>1&&console.log("WARNING: Multiple colliders detected. visionOS / iOS can only support objects with a single collider, only exporting the first collider: ",l))}}var u0e=Object.defineProperty,d0e=Object.getOwnPropertyDescriptor,Dh=(n,e,t,r)=>{for(var s=r>1?void 0:r?d0e(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&u0e(e,t,s),s};const xm=te("debugtext");var ur=(n=>(n[n.UpperLeft=0]="UpperLeft",n[n.UpperCenter=1]="UpperCenter",n[n.UpperRight=2]="UpperRight",n[n.MiddleLeft=3]="MiddleLeft",n[n.MiddleCenter=4]="MiddleCenter",n[n.MiddleRight=5]="MiddleRight",n[n.LowerLeft=6]="LowerLeft",n[n.LowerCenter=7]="LowerCenter",n[n.LowerRight=8]="LowerRight",n))(ur||{}),EQ=(n=>(n[n.Normal=0]="Normal",n[n.Bold=1]="Bold",n[n.Italic=2]="Italic",n[n.BoldAndItalic=3]="BoldAndItalic",n))(EQ||{});class Rs extends um{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 xe(1,0,1)),d(this,"_text",""),d(this,"_fontSize",12),d(this,"_textMeshUi",null),d(this,"_didHandleTextRenderOnTop",!1)}setAlphaFactor(e){var t;super.setAlphaFactor(e),(t=this.uiObject)==null||t.set({fontOpacity:this.color.alpha*this.alphaFactor}),this.markDirty()}get text(){return this._text}set text(e){e!==this._text&&(this._text=e,this.feedText(this.text,this.supportRichText),this.markDirty())}set_text(e){this.text=e}get fontSize(){return this._fontSize}set fontSize(e){var t;this._fontSize=e,(t=this.uiObject)==null||t.set({fontSize:e})}onColorChanged(){var e;this.sRGBTextColor.copy(this.color),this.sRGBTextColor.convertLinearToSRGB(),(e=this.uiObject)==null||e.set({color:this.sRGBTextColor,fontOpacity:this.color.alpha})}onParentRectTransformChanged(){super.onParentRectTransformChanged(),this.uiObject&&this.updateOverflow()}onBeforeCanvasRender(e){this.updateOverflow()}updateOverflow(){var e;const t=(e=this.uiObject)==null?void 0:e._overflow;t&&(t._needsUpdate=!0,this.markDirty())}onCreate(e){xm&&console.log(this),this.horizontalOverflow==1&&(e.whiteSpace="pre"),this.verticalOverflow==0&&(this.context.renderer.localClippingEnabled=!0,e.overflow="hidden"),this.horizontalOverflow==1&&this.verticalOverflow==0,e.lineHeight=this.lineSpacing,delete e.backgroundOpacity,delete e.backgroundColor,xm&&(e.backgroundColor=16750848,e.backgroundOpacity=.5);const t=this.rectTransform;e={...e,...this.getTextOpts()},this.getAlignment(e),xm&&(e.backgroundColor=Math.random()*16777215,e.backgroundOpacity=.1),this.uiObject=t.createNewText(e),this.feedText(this.text,this.supportRichText)}onAfterAddedToScene(){super.onAfterAddedToScene(),this.handleTextRenderOnTop()}getTextOpts(){const e=this.fontSize,t={color:this.color,fontOpacity:this.color.alpha,fontSize:e,fontKerning:"normal"};return this.setFont(t,this.fontStyle),t}onEnable(){var e;super.onEnable(),this._didHandleTextRenderOnTop=!1,this.uiObject&&this.uiObject.addAfterUpdate(()=>{this.setShadowComponentOwner(this.uiObject),this.markDirty()}),setTimeout(()=>this.markDirty(),10),(e=this.canvas)==null||e.registerEventReceiver(this)}onDisable(){var e;super.onDisable(),(e=this.canvas)==null||e.unregisterEventReceiver(this)}getAlignment(e){switch(e.flexDirection="column",this.alignment){case 0:case 3:case 6:e.textAlign="left";break;case 1:case 4:case 7:e.textAlign="center";break;case 2:case 5:case 8:e.textAlign="right";break}switch(this.alignment){default:case 0:case 1:case 2:e.alignItems="start";break;case 3:case 4:case 5:e.alignItems="center";break;case 6:case 7:case 8:e.alignItems="end";break}return e}feedText(e,t){var r,s,o;if(xm&&console.log("feedText",this.uiObject,e,t),!!this.uiObject)if(this._textMeshUi||(this._textMeshUi=[]),this.uiObject.children.length=0,!t||e.length===0)this.uiObject.textContent=e;else{let a=this.getNextTag(e);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 mw({textContent:e.substring(0,a.startIndex),color:"inherit"});this.uiObject.add(c)}}else{this.uiObject.textContent="",this.setOptions({textContent:e});return}const l=[];for(;a;){const c=this.getNextTag(e,a.endIndex),h={fontFamily:(r=this.uiObject)==null?void 0:r.get("fontFamily"),color:"inherit",textContent:""};if(c){h.textContent=this.getText(e,a,c),this.handleTag(a,h,l);const u=new mw(h);(s=this.uiObject)==null||s.add(u)}else{h.textContent=e.substring(a.endIndex),this.handleTag(a,h,l);const u=new mw(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 e=[],t=this.canvas,r={renderOnTop:t.renderOnTop,depthWrite:t.depthWrite,doubleSided:t.doubleSided};for(;;){let s=!1;if(this._textMeshUi)for(let o=0;o<this._textMeshUi.length;o++){if(e[o]===!0)continue;s=!0;const a=this._textMeshUi[o];a.textContent&&(NS(a,r),e[o]=!0)}if(!s)break;yield}}handleTag(e,t,r){if(!e.isEndTag){if(e.type.includes("color")){const s=new gD(e,{color:t.color});if(r.push(s),e.type.length>6){const o=parseInt("0x"+e.type.substring(7));t.color=o}else t.color=new xe(1,1,1)}else if(e.type=="b"){this.setFont(t,1);const s=new gD(e,{fontWeight:700});r.push(s)}else if(e.type=="i"){this.setFont(t,2);const s=new gD(e,{fontStyle:"italic"});r.push(s)}}}getText(e,t,r){return e.substring(t.endIndex,r.startIndex)}getNextTag(e,t=0){const r=e.indexOf("<",t),s=e.indexOf(">",r);if(r>=0&&s>=0){const o=e.substring(r+1,s);return{type:o,startIndex:r,endIndex:s+1,isEndTag:o.startsWith("/")}}return null}setFont(e,t){if(!this.font)return;const r=this.font,s=this.getFamilyNameWithCorrectSuffix(r,t);xm&&console.log("Selected font family:"+s);let o=mR.getFontFamily(s);switch(o||(o=mR.addFontFamily(s)),e.fontFamily=o,t){default:case 0:e.fontWeight=400,e.fontStyle="normal";break;case 1:e.fontWeight=700,e.fontStyle="normal";break;case 2:e.fontWeight=400,e.fontStyle="italic";break;case 3:e.fontStyle="italic",e.fontWeight=400}let a=o.getVariant(e.fontWeight,e.fontStyle);if(!a){let l=s;l!=null&&l.endsWith("-msdf.json")||(l+="-msdf.json");let c=s;c!=null&&c.endsWith(".png")||(c+=".png"),a=o.addVariant(e.fontWeight,e.fontStyle,l,c),a?.addEventListener("ready",()=>{this.markDirty()})}}getFamilyNameWithCorrectSuffix(e,t){var r;const s=e.lastIndexOf("-");if(s<0)return e;const o=(r=e.substring(s+1))==null?void 0:r.toLowerCase();if(p0e.includes(o))return xm&&console.warn("Unsupported font style: "+o),e;const a=e.lastIndexOf("/");let l=e;a>=0&&(l=l.substring(a+1));const c=l[0]===l[0].toUpperCase(),h=e.substring(0,s);switch(xm&&console.log("Select font: ",e,EQ[t],l,c,h),t){case 0:return c?h+"-Regular":h+"-regular";case 1:return c?h+"-Bold":h+"-bold";case 2:return c?h+"-Italic":h+"-italic";case 3:return c?h+"-BoldItalic":h+"-bolditalic";default:return e}}}Dh([w()],Rs.prototype,"alignment",2),Dh([w()],Rs.prototype,"verticalOverflow",2),Dh([w()],Rs.prototype,"horizontalOverflow",2),Dh([w()],Rs.prototype,"lineSpacing",2),Dh([w()],Rs.prototype,"supportRichText",2),Dh([w(URL)],Rs.prototype,"font",2),Dh([w()],Rs.prototype,"fontStyle",2),Dh([w()],Rs.prototype,"text",1),Dh([w()],Rs.prototype,"fontSize",1);class gD{constructor(e,t){d(this,"tag"),d(this,"previousValues"),this.tag=e,this.previousValues=t}}const p0e=["medium","mediumitalic","black","blackitalic","thin","thinitalic","extrabold","light","lightitalic","semibold"];class Ad{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 r;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=[]),(r=this.font)==null||r.push("sans-serif"));const s=this.font.map(o=>`"${o}"`).join(", ");t.appendLine(`string[] font = [ ${s} ]`),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/${CP(this.material)}>`),t.closeBlock()}}d(Ad,"global_id",0);class PC{static singleLine(e,t,r){const s=new Ad("text_"+Ad.getId());return s.content=e,t&&(s.pointSize=t),r&&(s.depth=r),s}static multiLine(e,t,r,s,o,a){const l=new Ad("text_"+Ad.getId());return l.content=e,l.width=t,l.height=r,l.horizontalAlignment=s,l.verticalAlignment=o,a!==void 0&&(l.wrapMode=a),l}}const m0e=new ve().makeRotationY(Math.PI),f0e=new ve().makeScale(-1,1,-1);class hb{get extensionName(){return"text"}exportText(e,t,r){const s=ie.getComponent(e,Rs);if(!s)return;const o=ie.getComponent(e,Ts);let a=100,l=100;o&&(a=o.width,l=o.height),t.matrix=m0e.clone(),o&&t.matrix.premultiply(f0e);const c=s.color.clone();t.material=new vs({color:c,emissive:c}),t.addEventListener("serialize",(h,u)=>{let p=s.text;p=p.replace(/\r/g,""),p=p.replace(/\n/g,"\\n");const m=PC.multiLine(p,a,l,"center","bottom","flowing");this.setTextAlignment(m,s.alignment),this.setOverflow(m,s),t.material&&(m.material=t.material),m.pointSize=this.convertToTextSize(s.fontSize),m.depth=.001,m.writeTo(void 0,h)})}convertToTextSize(e){return 1/.0502*144*e}setOverflow(e,t){t.horizontalOverflow?e.wrapMode="singleLine":e.wrapMode="flowing"}setTextAlignment(e,t){switch(t){case ur.LowerLeft:case ur.MiddleLeft:case ur.UpperLeft:e.horizontalAlignment="left";break;case ur.LowerCenter:case ur.MiddleCenter:case ur.UpperCenter:e.horizontalAlignment="center";break;case ur.LowerRight:case ur.MiddleRight:case ur.UpperRight:e.horizontalAlignment="right";break}switch(t){case ur.LowerLeft:case ur.LowerCenter:case ur.LowerRight:e.verticalAlignment="bottom";break;case ur.MiddleLeft:case ur.MiddleCenter:case ur.MiddleRight:e.verticalAlignment="middle";break;case ur.UpperLeft:case ur.UpperCenter:case ur.UpperRight:e.verticalAlignment="top";break}}}class BC{get extensionName(){return"tmui"}onExportObject(e,t,r){const s=ie.getComponent(e,Jr);if(s&&s.enabled&&s.renderMode===H8.WorldSpace){const o=new hb,a=ie.getComponent(e,Ts),l=ie.getComponent(e,hd),c=new Array;if(a){if(!ie.isActiveSelf(e)){const p=ie.isActiveSelf(e);ie.setActive(e,!0),a.onEnable(),a.updateTransform(),c.push(()=>{a.onDisable(),ie.setActive(e,p)})}e.traverse(p=>{if(!ie.isActiveInHierarchy(p)){const m=ie.isActiveSelf(p);ie.setActive(p,!0);const f=ie.getComponent(p,Va);f&&(f.onEnable(),c.push(()=>{f.onDisable()}));const g=ie.getComponent(p,Ts);g&&(g.onEnable(),g.updateTransform(),g.onApplyTransform(),c.push(()=>{g.onDisable()}));const v=ie.getComponent(p,Rs);v&&(v.onEnable(),c.push(()=>{v.onDisable()})),c.push(()=>{ie.setActive(p,m)})}}),a.width,a.height;const h=Ws.createEmpty(),u=a.shadowComponent;if(t.add(h),u){const p=u.matrix;h.matrix.copy(p);const m=new Map,f=new Map;m.set(u,h),f.set(u,l?l.alpha:1),u.traverse(g=>{if(g===u)return;const v=Ws.createEmpty();v.matrix.copy(g.matrix);const y=g.parent,A=!!y&&typeof y.textContent=="string"&&y.textContent.length>0;let _=f.get(y)||1;const b=ie.getComponent(g,hd);if(b&&(_*=b.alpha),g instanceof me&&A){const E=g[Ma];E?o.exportText(E.gameObject,v,r):console.error("Error when exporting UI: shadow component owner not found. This is likely a bug.",g)}if(g instanceof me&&!A){const E=g.geometry.clone();E.scale(1,1,-1),this.flipWindingOrder(E),v.geometry=E;const I=new xe,T=g.material.opacity;I.copy(g.material.color),v.material=new $t({color:I,opacity:T*_,map:g.material.map,transparent:!0})}m.set(g,v),f.set(g,_);const x=m.get(y);if(!x){console.error("Error when exporting UI: shadow component parent not found!",g,g.parent);return}x.add(v)})}}for(const h of c)h()}}flipWindingOrder(e){const t=e.index.array;for(let r=0,s=t.length/3;r<s;r++){const o=t[r*3];t[r*3]=t[r*3+2],t[r*3+2]=o}e.index.needsUpdate=!0}}const ub=te("debugusdz");function g0e(n,e){var t;const r=[],s=ie.getComponentsInChildren(n,Wr),o=ie.getComponentsInChildren(n,Es),a=new Array,l=new Array;if(e.injectImplicitBehaviours)for(const c of s){if(!c||!c.runtimeAnimatorController||!c.enabled)continue;const h=c.runtimeAnimatorController.activeState;if(!h||!h.motion||!h.motion.clip||((t=h.motion.clip.tracks)==null?void 0:t.length)<1||a.includes(c))continue;const u=new fm;u.animator=c,u.stateName=h.name,u.trigger="start",u.name="PlayAnimationOnClick_implicitAtStart_"+u.stateName;const p=new ye;ie.addComponent(p,u),l.push(p),a.push(c),n.add(p)}else for(const c of s){if(!c||!c.runtimeAnimatorController||!c.enabled)continue;ub&&console.log(c);const h=[];for(const u of c.runtimeAnimatorController.enumerateActions()){ub&&console.log(u);const p=u.getClip();h.includes(p)||h.push(p)}r.push({root:c.gameObject,clips:h})}if(e.injectImplicitBehaviours)for(const c of o){if(!c||!c.clip||!c.enabled||!c.playAutomatically||a.includes(c))continue;const h=new fm;h.animation=c,h.stateName=c.clip.name,h.trigger="start",h.name="PlayAnimationOnClick_implicitAtStart_"+h.stateName;const u=new ye;ie.addComponent(u,h),l.push(u),a.push(c),n.add(u)}else for(const c of o){ub&&console.log(c);const h=[];for(const u of c.animations)h.includes(u)||h.push(u);r.push({root:c.gameObject,clips:h})}ub&&r?.length>0&&console.log("USDZ Animation Clips without behaviours",r);for(const c of r)for(const h of c.clips)e.registerAnimation(c.root,h);return l}function v0e(n,e){const t=ie.getComponentsInChildren(n,Mn),r=ie.getComponentsInChildren(n,ud),s=new Array,o=new Array;ub&&console.log({audioSources:t,playAudioOnClicks:r});for(const a of r){if(!a.target)continue;const l=t.indexOf(a.target);l>-1&&t.splice(l,1)}for(const a of t){if(!a||!a.clip||a.volume<=0||s.includes(a))continue;const l=new ud;l.target=a,l.name="PlayAudioOnClick_implicitAtStart_",l.trigger="start";const c=new ye;ie.addComponent(c,l),console.log("implicit PlayAudioOnStart",c,l),o.push(c),s.push(a),n.add(c)}return o}function y0e(n){return new Ar("DisableAtStart",br.sceneStartTrigger(),gi.fadeAction(n,0,!1))}function MQ(n){const e=n.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 r=document.createElement("button");r.id="open-in-ar",r.innerText="Open in QuickLook",t.appendChild(r);const s=document.createElement("a");s.id="needle-usdz-link",s.style.display="none",s.rel="ar",s.href="",t.appendChild(s);const o=document.createElement("img");return o.id="button",s.appendChild(o),n.domElement.shadowRoot.appendChild(t),s}var A0e=Object.defineProperty,b0e=Object.getOwnPropertyDescriptor,Ps=(n,e,t,r)=>{for(var s=r>1?void 0:r?b0e(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&A0e(e,t,s),s};const Oa=te("debugusdz");class bd{constructor(){d(this,"callToAction"),d(this,"checkoutTitle"),d(this,"checkoutSubtitle"),d(this,"callToActionURL")}}Ps([w()],bd.prototype,"callToAction",2),Ps([w()],bd.prototype,"checkoutTitle",2),Ps([w()],bd.prototype,"checkoutSubtitle",2),Ps([w()],bd.prototype,"callToActionURL",2);var kC;const vD=(kC=class extends Be{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",n=>{n.preventDefault(),this.exportAndOpen()}),d(this,"_currentExportTasks",new Map),d(this,"_previousTimeScale",1),d(this,"lastCallback"),d(this,"_rootSessionRootWasAppliedTo",null),d(this,"_rootPositionBeforeExport",new C),d(this,"_rootRotationBeforeExport",new Ce),d(this,"_rootScaleBeforeExport",new C)}start(){var n,e,t;Oa&&(console.log("USDZExporter",this),console.log("Debug USDZ Mode. Press 'T' to export"),window.addEventListener("keydown",r=>{switch(r.key){case"t":this.exportAsync();break}}),aa()&&setTimeout(()=>{this.exportAsync()},2e3)),this.objectToExport||(this.objectToExport=this.gameObject),!((e=(n=this.objectToExport)==null?void 0:n.children)!=null&&e.length)&&!((t=this.objectToExport)!=null&&t.isMesh)&&(this.objectToExport=this.context.scene),this.interactive&&(this.extensions.push(new tC),this.extensions.push(new Pd),this.extensions.push(new RC),this.extensions.push(new hb),this.extensions.push(new BC))}onEnable(){var n;const e=vp(),t=Lf();(Oa||e&&t)&&(this.allowCreateQuicklookButton&&(this.button=this.createQuicklookButton()),this.lastCallback=this.quicklookCallback.bind(this),this.link=MQ(this.context),this.link.addEventListener("message",this.lastCallback)),Oa&&rn("USDZ Exporter enabled: "+this.name),(n=document.getElementById("open-in-ar"))==null||n.addEventListener("click",this.onClickedOpenInARElement)}onDisable(){var n,e,t;(n=this.button)==null||n.remove(),(e=this.link)==null||e.removeEventListener("message",this.lastCallback),Oa&&rn("USDZ Exporter disabled: "+this.name),(t=document.getElementById("open-in-ar"))==null||t.removeEventListener("click",this.onClickedOpenInARElement)}async exportAsync(){return this.exportAndOpen()}async exportAndOpen(){var n;let e=this.exportFileName??((n=this.objectToExport)==null?void 0:n.name)??this.name;if(e+="-"+Kj(),uu()||(e!==""&&(e+="-"),e+="MadeWithNeedle"),this.link||(this.link=MQ(this.context)),this.customUsdzFile)return Oa&&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?(Oa&&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(n){if(!n)return console.warn("No object to export"),null;const e=this._currentExportTasks.get(n);if(e)return e;const t=this.internalExport(n);return t instanceof Promise?(this._currentExportTasks.set(n,t),t.then(r=>(this._currentExportTasks.delete(n),r)).catch(r=>(this._currentExportTasks.delete(n),console.error("Error during USDZ export \u2013 please report a bug!",r),null))):t}async internalExport(n){ni.start("export-usdz",{onProgress:y=>{this.dispatchEvent(new CustomEvent("export-progress",{detail:{progress:y}}))}}),ni.report("export-usdz",{message:"Starting export",totalSteps:40,currentStep:0}),ni.report("export-usdz",{message:"Load progressive textures",autoStep:5}),ni.start("export-usdz-textures","export-usdz");const e=ie.getComponentsInChildren(n,ka);for(const y of e)y&&y.enabled&&y.start&&y.start();const t=ie.getComponentsInChildren(n,Tn),r=new Array;let s=0;for(const y of t){for(const A of y.sharedMeshes)if(A){const _=fi.assignMeshLOD(A,0);_ instanceof Promise&&r.push(new Promise((b,x)=>{_.then(()=>{s++,ni.report("export-usdz-textures",{message:"Loaded progressive mesh",currentStep:s,totalSteps:r.length}),b()}).catch(E=>x(E))}))}for(const A of y.sharedMaterials)if(A){const _=fi.assignTextureLOD(A,0);_ instanceof Promise&&r.push(new Promise((b,x)=>{_.then(()=>{s++,ni.report("export-usdz-textures",{message:"Loaded progressive texture",currentStep:s,totalSteps:r.length}),b()}).catch(E=>x(E))}))}}Oa&&rn("Progressive Loading: "+r.length),await Promise.all(r),Oa&&rn("Progressive Loading: done"),ni.end("export-usdz-textures");const o=eo.Global.Mask;eo.Global.Set(rc.AR);const a=new i5,l=new BA(this.quickLookCompatible),c=[l,...this.extensions],h={self:this,exporter:a,extensions:c,object:n};ni.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,ni.report("export-usdz","auto export animations and audio sources");const u=new Array;this.autoExportAnimations&&u.push(...g0e(n,l)),this.extensions.find(y=>y.extensionName==="Audio")&&this.autoExportAudioSources&&u.push(...v0e(n)),a.debug=Oa,a.keepObject=y=>{const A=ie.getComponent(y,Tn);return!(A&&!A.enabled)};const p=new Array;this.objectToExport&&this.quickLookCompatible&&this.interactive&&this.objectToExport.traverse(y=>{y.visible||p.push(y)});const m=this.extensions.find(y=>y.extensionName==="Behaviour");this.interactive&&m&&p.length>0&&m.addBehavior(y0e(p));let f=!0;this.quickLookCompatible&&!this.interactive&&(f=!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"),ni.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:f}),v=new Blob([g],{type:"model/vnd.usdz+zip"});this.revertWebARSessionRoot(),this.context.time.timeScale=this._previousTimeScale,ni.report("export-usdz","Invoking after-export"),this.dispatchEvent(new CustomEvent("after-export",{detail:h}));for(const y of u)ie.destroy(y);return eo.Global.Set(o),ni.end("export-usdz"),v}openInQuickLook(n,e){const t=n instanceof Blob?URL.createObjectURL(n):n,r=this.buildQuicklookOverlay();Oa&&console.log("QuickLook Overlay",r);const s=r.callToAction?encodeURIComponent(r.callToAction):"",o=r.checkoutTitle?encodeURIComponent(r.checkoutTitle):"",a=r.checkoutSubtitle?encodeURIComponent(r.checkoutSubtitle):"";this.link.href=t+`#callToAction=${s}&checkoutTitle=${o}&checkoutSubtitle=${a}&callToActionURL=${r.callToActionURL}`,this.lastCallback||(this.lastCallback=this.quicklookCallback.bind(this),this.link.addEventListener("message",this.lastCallback)),this.link.download=e+".usdz",this.link.click()}download(n,e){vD.save(n,e)}static save(n,e){const t=document.createElement("a");t.style.display="none",document.body.appendChild(t),typeof n=="string"?t.href=n:t.href=URL.createObjectURL(n),t.download=e,t.click(),t.remove()}quicklookCallback(n){if(n?.data=="_apple_ar_quicklook_button_tapped"){Oa&&Di("Quicklook closed via call to action button");var e=new CustomEvent("quicklook-button-tapped",{detail:this});if(this.dispatchEvent(e),!e.defaultPrevented){const t=new URLSearchParams(this.link.href);if(t){const r=t.get("callToActionURL");Oa&&rn("Quicklook url: "+r),r&&(uu()?globalThis.open(r,"_blank"):console.warn("Quicklook closed: custom redirects require a Needle Engine Pro license: https://needle.tools/pricing",r))}}}}buildQuicklookOverlay(){var n,e,t,r,s,o;const a={};return this.customBranding&&Object.assign(a,this.customBranding),uu()||(console.log("Custom Quicklook banner text requires pro license: https://needle.tools/pricing"),a.callToAction="Close",a.checkoutTitle="\u{1F335} Made with Needle",a.checkoutSubtitle="_"),(((n=a.callToAction)==null?void 0:n.length)||((e=a.checkoutTitle)==null?void 0:e.length)||((t=a.checkoutSubtitle)==null?void 0:t.length))&&((r=a.callToAction)!=null&&r.length||(a.callToAction="\0"),(s=a.checkoutTitle)!=null&&s.length||(a.checkoutTitle="\0"),(o=a.checkoutSubtitle)!=null&&o.length||(a.checkoutSubtitle="\0")),this.dispatchEvent(new CustomEvent("quicklook-overlay",{detail:a})),a}getARScaleAndTarget(){if(!this.objectToExport)return{scale:1,_invertForward:!1,target:this.gameObject,sessionRoot:null};let n=ie.getComponentInParent(this.objectToExport,io);n||(n=ie.getComponentInChildren(this.objectToExport,io));let e=1,t=!1;const r=this.objectToExport;if(n)e=n.arScale,t=n.invertForward;else{const s=ie.findObjectOfType(Ir);s&&(e=s.arSceneScale)}return{scale:1/e,_invertForward:t,target:r,sessionRoot:n?.gameObject??null}}applyWebARSessionRoot(){if(!this.objectToExport)return;const{scale:n,_invertForward:e,target:t,sessionRoot:r}=this.getARScaleAndTarget(),s=r?.matrixWorld.clone().invert();this._rootSessionRootWasAppliedTo=t,this._rootPositionBeforeExport.copy(t.position),this._rootRotationBeforeExport.copy(t.quaternion),this._rootScaleBeforeExport.copy(t.scale),t.scale.multiplyScalar(n),e&&t.quaternion.multiply(vD.invertForwardQuaternion),t.updateMatrix(),t.updateMatrixWorld(!0),r&&s&&t.matrix.premultiply(s)}revertWebARSessionRoot(){if(!this.objectToExport||!this._rootSessionRootWasAppliedTo)return;const n=this._rootSessionRootWasAppliedTo;n.position.copy(this._rootPositionBeforeExport),n.quaternion.copy(this._rootRotationBeforeExport),n.scale.copy(this._rootScaleBeforeExport),n.updateMatrix(),n.updateMatrixWorld(!0),this._rootSessionRootWasAppliedTo=null}createQuicklookButton(){const n=Am.getOrCreate().createQuicklookButton();return n.parentNode||this.context.menu.appendChild(n),n}},d(kC,"invertForwardMatrix",new ve().makeRotationY(Math.PI)),d(kC,"invertForwardQuaternion",new Ce().setFromEuler(new ii(0,Math.PI,0))),kC);let Rn=vD;Ps([w(ye)],Rn.prototype,"objectToExport",2),Ps([w()],Rn.prototype,"autoExportAnimations",2),Ps([w()],Rn.prototype,"autoExportAudioSources",2),Ps([w()],Rn.prototype,"exportFileName",2),Ps([w(URL)],Rn.prototype,"customUsdzFile",2),Ps([w(bd)],Rn.prototype,"customBranding",2),Ps([w()],Rn.prototype,"anchoringType",2),Ps([w()],Rn.prototype,"maxTextureSize",2),Ps([w()],Rn.prototype,"planeAnchoringAlignment",2),Ps([w()],Rn.prototype,"interactive",2),Ps([w()],Rn.prototype,"allowCreateQuicklookButton",2),Ps([w()],Rn.prototype,"quickLookCompatible",2);class db extends Be{constructor(){super(...arguments),d(this,"isUsed",!0),d(this,"usedBy",null)}}class yD extends Be{}const TQ=te("debugdeletable");class DC extends ac{}class AD extends Be{constructor(){super(...arguments),d(this,"deleteBoxes",[])}awake(){this.deleteBoxes=ie.findObjectsOfType(DC,this.context)}update(){for(const e of this.deleteBoxes){const t=this.gameObject;if(e.isInBox(t)===!0){const r=ie.getComponentInParent(this.gameObject,db);r?TQ&&console.warn("Can not delete object with usage marker",this.guid,r):(TQ&&console.log("DESTROY",this.gameObject),hA(this.gameObject,this.context.connection))}}}}var _0e=Object.defineProperty,x0e=Object.getOwnPropertyDescriptor,wm=(n,e,t,r)=>{for(var s=r>1?void 0:r?x0e(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&_0e(e,t,s),s};const w0e=te("debugpost");class xl extends Xr{constructor(){super(...arguments),d(this,"mode"),d(this,"focusDistance",new qe(1)),d(this,"focalLength",new qe(.2)),d(this,"aperture",new qe(20)),d(this,"gaussianMaxRadius",new qe),d(this,"resolutionScale",new qe(1*1/window.devicePixelRatio)),d(this,"bokehScale",new qe)}get typeName(){return"DepthOfField"}init(){this.focalLength.valueProcessor=t=>{const r=t/300,s=2;return it.lerp(s,.01,r)};const e=20;this.aperture.valueProcessor=t=>{const r=1-t/32;return it.lerp(1,e,r)}}onCreateEffect(){if(this.mode===0){w0e&&console.warn("DepthOfField: Mode is set to Off");return}const e=new $5(this.context.mainCamera,{worldFocusRange:.2,focalLength:1,bokehScale:20,resolutionScale:this.resolutionScale.value});return this.focusDistance.onValueChanged=t=>{e.cocMaterial.worldFocusDistance=t},this.focalLength.onValueChanged=t=>e.cocMaterial.worldFocusRange=t,this.aperture.onValueChanged=t=>e.bokehScale=t,this.resolutionScale&&(this.resolutionScale.onValueChanged=t=>e.resolution.scale=t),[e]}unapply(){}}wm([w()],xl.prototype,"mode",2),wm([w(qe)],xl.prototype,"focusDistance",2),wm([w(qe)],xl.prototype,"focalLength",2),wm([w(qe)],xl.prototype,"aperture",2),wm([w(qe)],xl.prototype,"gaussianMaxRadius",2),wm([w(qe)],xl.prototype,"resolutionScale",2),wm([w(qe)],xl.prototype,"bokehScale",2),Ra("DepthOfField",xl);var S0e=Object.defineProperty,C0e=Object.getOwnPropertyDescriptor,E0e=(n,e,t,r)=>{for(var s=r>1?void 0:r?C0e(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&S0e(e,t,s),s};class OC extends Be{constructor(){super(...arguments),d(this,"visibleOn")}onEnable(){this.apply()}apply(){this.test()||ie.setActive(this.gameObject,!1)}test(){return this.visibleOn<0?!0:aa()?(this.visibleOn&2)!==0:(this.visibleOn&1)!==0}}E0e([w()],OC.prototype,"visibleOn",2);class bD{get extensionName(){return"DocumentExtension"}onAfterBuildDocument(e){}}var M0e=Object.defineProperty,T0e=Object.getOwnPropertyDescriptor,Sm=(n,e,t,r)=>{for(var s=r>1?void 0:r?T0e(e,t):e,o=n.length-1,a;o>=0;o--)(a=n[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&M0e(e,t,s),s};const Ac=te("debugdrag");var IQ=(n=>(n[n.XZPlane=0]="XZPlane",n[n.Attached=1]="Attached",n[n.HitNormal=2]="HitNormal",n[n.DynamicViewAngle=3]="DynamicViewAngle",n[n.SnapToSurfaces=4]="SnapToSurfaces",n[n.None=5]="None",n))(IQ||{}),LC;const bc=(LC=class extends Be{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 C),d(this,"_marker",null),d(this,"_isDragging",!1),d(this,"_didDrag",!1)}static get HasAnySelected(){return this._active>0}setTargetObject(n){this.targetObject=n;for(const e of this._dragHandlers.values())e.setTargetObject(n)}awake(){this._potentialDragStartEvt=null,this._dragHandlers=new Map,this._totalMovement=new C,this._marker=null,this._isDragging=!1,this._didDrag=!1,this._dragHelper=null,this._draggingRigidbodies=[]}start(){this.orbit=ie.findObjectOfType(bi,this.context),this.gameObject.getComponentInParent(No)||this.gameObject.addComponent(No)}allowEdit(n=null){return this.context.connection.allowEditing}onPointerEnter(n){if(!this.allowEdit(this.gameObject)||n.mode!=="screen"||(n.event.mode==="tracked-pointer"||n.event.mode==="transient-pointer"?this.xrDragMode:this.dragMode)===5)return;const e=ie.getComponentInParent(n.object,bc);!e||e!==this||(bc.lastHovered=n.object,this.context.domElement.style.cursor="pointer")}onPointerExit(n){this.allowEdit(this.gameObject)&&n.mode==="screen"&&bc.lastHovered===n.object&&(this.context.domElement.style.cursor="auto")}onPointerDown(n){if(!(!this.allowEdit(this.gameObject)||n.used||(n.mode==="tracked-pointer"||n.mode==="transient-pointer"?this.xrDragMode:this.dragMode)===5)&&(bc.lastHovered=n.object,n.button===0)){this._dragHandlers.size===0&&(this._didDrag=!1,this._totalMovement.set(0,0,0),this._potentialDragStartEvt=n),bc._active+=1;const e=new R0e(this,this.targetObject||this.gameObject);if(this._dragHandlers.set(n.event.space,e),this.orbit&&(this.orbit.enabled=!1),e.onDragStart(n),this._dragHandlers.size===2){const t=this._dragHandlers.values(),r=t.next().value,s=t.next().value,o=new I0e(this,this.targetObject||this.gameObject,r,s);this._dragHandlers.set(this.gameObject,o),o.onDragStart(n)}n.use()}}onPointerMove(n){(this._isDragging||this._potentialDragStartEvt!==null)&&n.use()}onPointerUp(n){if(Ac&&At.DrawLabel(n.point??this.gameObject.worldPosition,"POINTERUP:"+n.pointerId+", "+n.button,.03,3),!this.allowEdit(this.gameObject)||n.button!==0)return;this._potentialDragStartEvt=null;const e=this._dragHandlers.get(n.event.space),t=this._dragHandlers.get(this.gameObject);t&&(t.handlerA===e||t.handlerB===e)&&(this._dragHandlers.delete(this.gameObject),t.onDragEnd(n)),e&&(bc._active>0&&(bc._active-=1),e.onDragEnd&&e.onDragEnd(n),this._dragHandlers.delete(n.event.space),this._dragHandlers.size===0&&this.onLastDragEnd(n),n.use()),bc._active===0&&this.orbit&&(this.orbit.enabled=!0)}update(){for(const n of this._dragHandlers.values())n.collectMovementInfo&&n.collectMovementInfo(),n.getTotalMovement&&this._totalMovement.add(n.getTotalMovement());if(this._potentialDragStartEvt){if(!this._didDrag)if(this._totalMovement.length()>3e-4)this._didDrag=!0;else return;const n=this._potentialDragStartEvt;this._potentialDragStartEvt=null,this.onFirstDragStart(n)}for(const n of this._dragHandlers.values())n.onDragUpdate&&n.onDragUpdate(this._dragHandlers.size);this._dragHelper&&this._dragHelper.hasSelected&&this.onAnyDragUpdate()}onFirstDragStart(n){if(!this._dragHelper)if(this.context.mainCamera)this._dragHelper=new PQ(this.context.mainCamera);else return;if(!n||!n.object)return;const e=ie.getComponentInParent(n.object,bc);if(!e||e!==this&&e._isDragging)return;const t=this.targetObject||this.gameObject;if(!t)return;this._isDragging=!0,this._dragHelper.setSelected(t,this.context),this.orbit&&(this.orbit.enabled=!1);const r=ie.getComponentInChildren(t,Ku);Ac&&console.log("DRAG START",r,t),r&&(r.fastMode=!0,r?.requestOwnership()),this._marker=ie.addComponent(t,db),this._draggingRigidbodies.length=0;const s=ie.getComponentsInChildren(t,Oi);s&&this._draggingRigidbodies.push(...s)}onAnyDragUpdate(){if(!this._dragHelper)return;this._dragHelper.showGizmo=this.showGizmo,this._dragHelper.onUpdate(this.context);for(const e of this._draggingRigidbodies)e.wakeUp(),e.resetVelocities(),e.resetForcesAndTorques();const n=this.targetObject||this.gameObject;Qa.markDirty(n)}onLastDragEnd(n){if(!this||!this._isDragging||(this._isDragging=!1,!this._dragHelper))return;for(const t of this._draggingRigidbodies)t.setVelocity(t.smoothedVelocity);this._draggingRigidbodies.length=0;const e=this._dragHelper.selected;if(Ac&&console.log("DRAG END",e,e?.visible),this._dragHelper.setSelected(null,this.context),this.orbit&&(this.orbit.enabled=!0),n!=null&&n.object){const t=ie.getComponentInChildren(n.object,Ku);t&&(t.fastMode=!1)}this._marker&&this._marker.destroy()}},d(LC,"_active",0),d(LC,"lastHovered"),LC);let La=bc;Sm([w()],La.prototype,"dragMode",2),Sm([w()],La.prototype,"snapGridResolution",2),Sm([w()],La.prototype,"keepRotation",2),Sm([w()],La.prototype,"xrDragMode",2),Sm([w()],La.prototype,"xrKeepRotation",2),Sm([w()],La.prototype,"xrDistanceDragFactor",2),Sm([w()],La.prototype,"showGizmo",2);class I0e{constructor(e,t,r,s){d(this,"handlerA"),d(this,"handlerB"),d(this,"context"),d(this,"settings"),d(this,"gameObject"),d(this,"_handlerAAttachmentPoint",new C),d(this,"_handlerBAttachmentPoint",new C),d(this,"_followObject"),d(this,"_manipulatorObject"),d(this,"_deviceMode"),d(this,"_followObjectStartWorldQuaternion",new Ce),d(this,"_manipulatorPosOffset",new C),d(this,"_manipulatorRotOffset",new Ce),d(this,"_manipulatorScaleOffset",new C),d(this,"_tempVec1",new C),d(this,"_tempVec2",new C),d(this,"_tempVec3",new C),d(this,"tempLookMatrix",new ve),d(this,"_initialScale",new C),d(this,"_initialDistance",0);var o,a;this.context=e.context,this.settings=e,this.gameObject=t,this.handlerA=r,this.handlerB=s,this._followObject=new ye,this._manipulatorObject=new ye,this.context.scene.add(this._manipulatorObject);const l=(a=(o=wt.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),l&&(l.worldToLocal(this._tempVec1),l.worldToLocal(this._tempVec2)),this._initialDistance=this._tempVec1.distanceTo(this._tempVec2),this._initialDistance<.02?(Ac&&console.log("Finding alternative drag attachment points since initial distance is too low: "+this._initialDistance.toFixed(2)),this.handlerA.followObject.parent.getWorldPosition(this._tempVec1),this.handlerB.followObject.parent.getWorldPosition(this._tempVec2),this._handlerAAttachmentPoint.copy(this._tempVec1),this._handlerBAttachmentPoint.copy(this._tempVec2),this.gameObject.worldToLocal(this._handlerAAttachmentPoint),this.gameObject.worldToLocal(this._handlerBAttachmentPoint),this._initialDistance=this._tempVec1.distanceTo(this._tempVec2),this._initialDistance<.001&&(console.warn("Not supported right now \u2013 controller drag points for multitouch are too close!"),this._initialDistance=1)):(this._handlerAAttachmentPoint.copy(this.handlerA.hitPointInLocalSpace),this._handlerBAttachmentPoint.copy(this.handlerB.hitPointInLocalSpace)),this._tempVec3.lerpVectors(this._tempVec1,this._tempVec2,.5),this._initialScale.copy(t.scale),Ac){this._followObject.add(new Po(2)),this._manipulatorObject.add(new Po(5));const c=h=>`${h.x.toFixed(2)}, ${h.y.toFixed(2)}, ${h.z.toFixed(2)}`;At.DrawLine(this._tempVec1,this._tempVec2,65535,0,!1),At.DrawLabel(this._tempVec3,"A:B "+this._initialDistance.toFixed(2)+`
|
|
6214
6214
|
`+c(this._tempVec1)+`
|
|
6215
|
-
`+c(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),Ac&&(At.DrawLabel(this._tempVec3.clone().add(new C(0,.2,0)),"A:B "+t.toFixed(2),.03),At.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 r=this.gameObject,s=this._followObject;s.updateMatrix(),s.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,p=this.settings.snapGridResolution;u.x=Math.round(u.x/p)*p,u.y=Math.round(u.y/p)*p,u.z=Math.round(u.z/p)*p,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=r.worldPosition;l.lerp(s.worldPosition,a),r.worldPosition=l;const c=r.worldQuaternion;c.slerp(s.worldQuaternion,a),r.worldQuaternion=c;const h=r.worldScale;h.lerp(s.worldScale,a),r.worldScale=h}setTargetObject(e){this.gameObject=e}}class R0e{constructor(e,t){d(this,"context"),d(this,"gameObject"),d(this,"settings"),d(this,"_lastRig"),d(this,"_followObject"),d(this,"_totalMovement",new C),d(this,"_totalMovementAlongRayDirection",0),d(this,"_grabStartDistance",0),d(this,"_deviceMode"),d(this,"_followObjectStartPosition",new C),d(this,"_followObjectStartQuaternion",new Ce),d(this,"_followObjectStartWorldQuaternion",new Ce),d(this,"_lastDragPosRigSpace"),d(this,"_tempVec",new C),d(this,"_tempMat",new ve),d(this,"_hitPointInLocalSpace",new C),d(this,"_hitNormalInLocalSpace",new C),d(this,"_bottomCenter",new C),d(this,"_backCenter",new C),d(this,"_backBottomCenter",new C),d(this,"_bounds",new xi),d(this,"_dragPlane",new ms(new C(0,1,0))),d(this,"_draggedOverObject",null),d(this,"_draggedOverObjectLastSetUp",null),d(this,"_draggedOverObjectLastNormal",new C),d(this,"_draggedOverObjectDuration",0),this.settings=e,this.context=e.context,this.gameObject=t,this._followObject=new ye}getTotalMovement(){return this._totalMovement}get followObject(){return this._followObject}get hitPointInLocalSpace(){return this._hitPointInLocalSpace}setTargetObject(e){this.gameObject=e}recenter(){var e,t;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 r=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),r.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 s=this._hitPointInLocalSpace.clone();this.gameObject.localToWorld(s),this._grabStartDistance=s.distanceTo(r.worldPosition);const o=(t=(e=wt.active)==null?void 0:e.rig)==null?void 0:t.gameObject,a=o?.worldScale.x||1;this._grabStartDistance/=a,this._totalMovementAlongRayDirection=0,this._lastDragPosRigSpace=void 0,Ac&&(At.DrawLine(s,r.worldPosition,65280,.5,!1),At.DrawLabel(r.worldPosition.add(new C(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 f=e.event.space,g=f.worldPosition;this.gameObject.worldToLocal(g),this._hitPointInLocalSpace.copy(g);const v=f.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 t=this._followObject.parent.worldForward,r=this._deviceMode==="tracked-pointer"||this._deviceMode==="transient-pointer"?this.settings.xrDragMode:this.settings.dragMode,s=this._hitPointInLocalSpace.clone();switch(this.gameObject.localToWorld(s),r){case 0:const f=new C(0,1,0);this.gameObject.parent&&f.transformDirection(this.gameObject.parent.matrixWorld.clone().invert()),this._dragPlane.setFromNormalAndCoplanarPoint(f,s);break;case 2:const g=this._hitNormalInLocalSpace.clone();g.transformDirection(this.gameObject.matrixWorld),this._dragPlane.setFromNormalAndCoplanarPoint(g,s);break;case 1:this._dragPlane.setFromNormalAndCoplanarPoint(t,s);break;case 3:const v=new C(0,1,0),y=t,A=v.angleTo(y),_=.5;A>Math.PI/2+_||A<Math.PI/2-_?this._dragPlane.setFromNormalAndCoplanarPoint(new C(0,1,0),s):this._dragPlane.setFromNormalAndCoplanarPoint(t,s);break}const o=this.gameObject.parent,a=this.gameObject.position.clone(),l=this.gameObject.quaternion.clone(),c=this.gameObject.scale.clone(),h=this.gameObject.matrixWorld.clone();o&&o.remove(this.gameObject),this.gameObject.position.set(0,0,0),this.gameObject.quaternion.set(0,0,0,1),this.gameObject.scale.set(1,1,1);const u=Ul([this.gameObject]);u.expandByPoint(this.gameObject.worldPosition);const p=new C;u.getCenter(p);const m=new C;u.getSize(m),this._bottomCenter.copy(p.clone().add(new C(0,-m.y/2,0))),this._backCenter.copy(p.clone().add(new C(0,0,m.z/2))),this._backBottomCenter.copy(p.clone().add(new C(0,-m.y/2,m.z/2))),this._bounds.copy(u),o&&o.add(this.gameObject),this.gameObject.position.copy(a),this.gameObject.quaternion.copy(l),this.gameObject.scale.copy(c),this.gameObject.matrixWorld.copy(h),this._draggedOverObject=null,this._draggedOverObjectLastSetUp=null,this._draggedOverObjectLastNormal.set(0,1,0),this._draggedOverObjectDuration=0}collectMovementInfo(){var e,t;if(!this._followObject.parent)return;const r=this._followObject.parent;this._followObject.updateMatrix();const s=r.worldPosition,o=(t=(e=wt.active)==null?void 0:e.rig)==null?void 0:t.gameObject;o&&o.worldToLocal(s),(this._lastDragPosRigSpace===void 0||o!=this._lastRig)&&(this._lastDragPosRigSpace=s.clone(),this._lastRig=o),this._tempVec.copy(s).sub(this._lastDragPosRigSpace);const a=r.worldForward;if(o&&(this._tempMat.copy(o.matrixWorld).invert(),a.transformDirection(this._tempMat)),this._totalMovementAlongRayDirection+=a.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(s),Ac){let l=s;o&&(l=l.clone(),l.transformDirection(o.matrixWorld)),At.DrawRay(l,a,255)}}onDragUpdate(e){if(e>1)return;const t=this.gameObject,r=this._followObject.parent;this._followObject.updateMatrix();const s=r.worldPosition,o=r.worldForward,a=this._deviceMode==="tracked-pointer"||this._deviceMode==="transient-pointer",l=a?this.settings.xrKeepRotation:this.settings.keepRotation,c=a?this.settings.xrDragMode:this.settings.dragMode;if(c===5)return;const h=10;l&&(this._followObject.worldQuaternion=this._followObjectStartWorldQuaternion),this._followObject.updateMatrix(),this._followObject.updateMatrixWorld(!0);let u=1,p=2;if(a&&this._grabStartDistance>.5){const y=1+this._totalMovementAlongRayDirection*(2*this.settings.xrDistanceDragFactor);u=Math.max(0,y),u=u*u*u}else this._grabStartDistance<=.5&&(p=3);this._followObject.position.copy(this._followObjectStartPosition),l||this._followObject.quaternion.copy(this._followObjectStartQuaternion),this._followObject.position.multiplyScalar(u),this._followObject.updateMatrix();const m=new co(s,o);if(c==4){const y=new ml;y.testObject=_=>_!==this.followObject&&_!==r&&_!==t;const A=this.context.physics.raycastFromRay(m,y);if(A.length>0){const _=A[0];if(this._draggedOverObject===_.object?this._draggedOverObjectDuration+=this.context.time.deltaTime:(this._draggedOverObject=_.object,this._draggedOverObjectDuration=0),_.face){const b=this._draggedOverObjectDuration>=.15,x=.001,E=this._totalMovement.length()>=x;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 I=pi(),T=pi();this._bounds.getCenter(I),this._bounds.getSize(T),I.sub(T.multiplyScalar(.5).multiply(_.face.normal)),this._hitPointInLocalSpace.copy(I),this._hitNormalInLocalSpace.copy(_.face.normal),this._bounds.getCenter(I),this._bounds.getSize(T),I.add(T.multiplyScalar(.5).multiply(_.face.normal));const R=pi(this._hitPointInLocalSpace).add(I);this._followObject.localToWorld(R);const D=_.point;this._dragPlane.setFromNormalAndCoplanarPoint(_.face.normal,D)}else if(!(b||E))return}}}if(c!==1&&m.intersectPlane(this._dragPlane,this._tempVec)){this._followObject.worldPosition=this._tempVec,this._followObject.updateMatrix(),this._followObject.updateMatrixWorld(!0);const y=this._hitPointInLocalSpace.clone();this._followObject.localToWorld(y),Ac&&At.DrawLine(y,this._tempVec,65535,0,!1),this._followObject.worldPosition=this._tempVec.multiplyScalar(2).sub(y),this._followObject.updateMatrix(),this._followObject.updateMatrix()}if(this.settings.snapGridResolution>0){const y=this._followObject.worldPosition,A=this.settings.snapGridResolution;y.x=Math.round(y.x/A)*A,y.y=Math.round(y.y/A)*A,y.z=Math.round(y.z/A)*A,this._followObject.worldPosition=y,this._followObject.updateMatrix()}l&&(this._followObject.worldQuaternion=this._followObjectStartWorldQuaternion,this._followObject.updateMatrix());const f=it.clamp01(this.context.time.deltaTime*h*p),g=t.worldPosition;g.lerp(this._followObject.worldPosition,f),t.worldPosition=g;const v=t.worldQuaternion;if(v.slerp(this._followObject.worldQuaternion,f),t.worldQuaternion=v,Ac){const y=this._hitPointInLocalSpace.clone();t.localToWorld(y),At.DrawSphere(y,.02,16711680);const A=this._hitNormalInLocalSpace.clone();A.applyQuaternion(v),At.DrawRay(y,A,16711680),At.DrawLabel(g.add(new C(0,.25,0)),`Distance: ${this._totalMovement.length().toFixed(2)}
|
|
6215
|
+
`+c(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),Ac&&(At.DrawLabel(this._tempVec3.clone().add(new C(0,.2,0)),"A:B "+t.toFixed(2),.03),At.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 r=this.gameObject,s=this._followObject;s.updateMatrix(),s.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,p=this.settings.snapGridResolution;u.x=Math.round(u.x/p)*p,u.y=Math.round(u.y/p)*p,u.z=Math.round(u.z/p)*p,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=r.worldPosition;l.lerp(s.worldPosition,a),r.worldPosition=l;const c=r.worldQuaternion;c.slerp(s.worldQuaternion,a),r.worldQuaternion=c;const h=r.worldScale;h.lerp(s.worldScale,a),r.worldScale=h}setTargetObject(e){this.gameObject=e}}class R0e{constructor(e,t){d(this,"context"),d(this,"gameObject"),d(this,"settings"),d(this,"_lastRig"),d(this,"_followObject"),d(this,"_totalMovement",new C),d(this,"_totalMovementAlongRayDirection",0),d(this,"_grabStartDistance",0),d(this,"_deviceMode"),d(this,"_followObjectStartPosition",new C),d(this,"_followObjectStartQuaternion",new Ce),d(this,"_followObjectStartWorldQuaternion",new Ce),d(this,"_lastDragPosRigSpace"),d(this,"_tempVec",new C),d(this,"_tempMat",new ve),d(this,"_hitPointInLocalSpace",new C),d(this,"_hitNormalInLocalSpace",new C),d(this,"_bottomCenter",new C),d(this,"_backCenter",new C),d(this,"_backBottomCenter",new C),d(this,"_bounds",new xi),d(this,"_dragPlane",new ms(new C(0,1,0))),d(this,"_draggedOverObject",null),d(this,"_draggedOverObjectLastSetUp",null),d(this,"_draggedOverObjectLastNormal",new C),d(this,"_draggedOverObjectDuration",0),this.settings=e,this.context=e.context,this.gameObject=t,this._followObject=new ye}getTotalMovement(){return this._totalMovement}get followObject(){return this._followObject}get hitPointInLocalSpace(){return this._hitPointInLocalSpace}setTargetObject(e){this.gameObject=e}recenter(){var e,t;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 r=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),r.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 s=this._hitPointInLocalSpace.clone();this.gameObject.localToWorld(s),this._grabStartDistance=s.distanceTo(r.worldPosition);const o=(t=(e=wt.active)==null?void 0:e.rig)==null?void 0:t.gameObject,a=o?.worldScale.x||1;this._grabStartDistance/=a,this._totalMovementAlongRayDirection=0,this._lastDragPosRigSpace=void 0,Ac&&(At.DrawLine(s,r.worldPosition,65280,.5,!1),At.DrawLabel(r.worldPosition.add(new C(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 f=e.event.space,g=f.worldPosition;this.gameObject.worldToLocal(g),this._hitPointInLocalSpace.copy(g);const v=f.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 t=this._followObject.parent.worldForward,r=this._deviceMode==="tracked-pointer"||this._deviceMode==="transient-pointer"?this.settings.xrDragMode:this.settings.dragMode,s=this._hitPointInLocalSpace.clone();switch(this.gameObject.localToWorld(s),r){case 0:const f=new C(0,1,0);this.gameObject.parent&&f.transformDirection(this.gameObject.parent.matrixWorld.clone().invert()),this._dragPlane.setFromNormalAndCoplanarPoint(f,s);break;case 2:const g=this._hitNormalInLocalSpace.clone();g.transformDirection(this.gameObject.matrixWorld),this._dragPlane.setFromNormalAndCoplanarPoint(g,s);break;case 1:this._dragPlane.setFromNormalAndCoplanarPoint(t,s);break;case 4:case 3:const v=new C(0,1,0),y=t,A=v.angleTo(y),_=.5;A>Math.PI/2+_||A<Math.PI/2-_?this._dragPlane.setFromNormalAndCoplanarPoint(new C(0,1,0),s):this._dragPlane.setFromNormalAndCoplanarPoint(t,s);break}const o=this.gameObject.parent,a=this.gameObject.position.clone(),l=this.gameObject.quaternion.clone(),c=this.gameObject.scale.clone(),h=this.gameObject.matrixWorld.clone();o&&o.remove(this.gameObject),this.gameObject.position.set(0,0,0),this.gameObject.quaternion.set(0,0,0,1),this.gameObject.scale.set(1,1,1);const u=Ul([this.gameObject]);u.expandByPoint(this.gameObject.worldPosition);const p=new C;u.getCenter(p);const m=new C;u.getSize(m),this._bottomCenter.copy(p.clone().add(new C(0,-m.y/2,0))),this._backCenter.copy(p.clone().add(new C(0,0,m.z/2))),this._backBottomCenter.copy(p.clone().add(new C(0,-m.y/2,m.z/2))),this._bounds.copy(u),o&&o.add(this.gameObject),this.gameObject.position.copy(a),this.gameObject.quaternion.copy(l),this.gameObject.scale.copy(c),this.gameObject.matrixWorld.copy(h),this._draggedOverObject=null,this._draggedOverObjectLastSetUp=null,this._draggedOverObjectLastNormal.set(0,1,0),this._draggedOverObjectDuration=0}collectMovementInfo(){var e,t;if(!this._followObject.parent)return;const r=this._followObject.parent;this._followObject.updateMatrix();const s=r.worldPosition,o=(t=(e=wt.active)==null?void 0:e.rig)==null?void 0:t.gameObject;o&&o.worldToLocal(s),(this._lastDragPosRigSpace===void 0||o!=this._lastRig)&&(this._lastDragPosRigSpace=s.clone(),this._lastRig=o),this._tempVec.copy(s).sub(this._lastDragPosRigSpace);const a=r.worldForward;if(o&&(this._tempMat.copy(o.matrixWorld).invert(),a.transformDirection(this._tempMat)),this._totalMovementAlongRayDirection+=a.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(s),Ac){let l=s;o&&(l=l.clone(),l.transformDirection(o.matrixWorld)),At.DrawRay(l,a,255)}}onDragUpdate(e){if(e>1)return;const t=this.gameObject,r=this._followObject.parent;this._followObject.updateMatrix();const s=r.worldPosition,o=r.worldForward,a=this._deviceMode==="tracked-pointer"||this._deviceMode==="transient-pointer",l=a?this.settings.xrKeepRotation:this.settings.keepRotation,c=a?this.settings.xrDragMode:this.settings.dragMode;if(c===5)return;const h=10;l&&(this._followObject.worldQuaternion=this._followObjectStartWorldQuaternion),this._followObject.updateMatrix(),this._followObject.updateMatrixWorld(!0);let u=1,p=2;if(a&&this._grabStartDistance>.5){const y=1+this._totalMovementAlongRayDirection*(2*this.settings.xrDistanceDragFactor);u=Math.max(0,y),u=u*u*u}else this._grabStartDistance<=.5&&(p=3);this._followObject.position.copy(this._followObjectStartPosition),l||this._followObject.quaternion.copy(this._followObjectStartQuaternion),this._followObject.position.multiplyScalar(u),this._followObject.updateMatrix();const m=new co(s,o);if(c==4){const y=new ml;y.testObject=_=>_!==this.followObject&&_!==r&&_!==t;const A=this.context.physics.raycastFromRay(m,y);if(A.length>0){const _=A[0];if(this._draggedOverObject===_.object?this._draggedOverObjectDuration+=this.context.time.deltaTime:(this._draggedOverObject=_.object,this._draggedOverObjectDuration=0),_.face){const b=this._draggedOverObjectDuration>=.15,x=.001,E=this._totalMovement.length()>=x;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 I=pi(),T=pi();this._bounds.getCenter(I),this._bounds.getSize(T),I.sub(T.multiplyScalar(.5).multiply(_.face.normal)),this._hitPointInLocalSpace.copy(I),this._hitNormalInLocalSpace.copy(_.face.normal),this._bounds.getCenter(I),this._bounds.getSize(T),I.add(T.multiplyScalar(.5).multiply(_.face.normal));const R=pi(this._hitPointInLocalSpace).add(I);this._followObject.localToWorld(R);const D=_.point;this._dragPlane.setFromNormalAndCoplanarPoint(_.face.normal,D)}else if(!(b||E))return}}}if(c!==1&&m.intersectPlane(this._dragPlane,this._tempVec)){this._followObject.worldPosition=this._tempVec,this._followObject.updateMatrix(),this._followObject.updateMatrixWorld(!0);const y=this._hitPointInLocalSpace.clone();this._followObject.localToWorld(y),Ac&&At.DrawLine(y,this._tempVec,65535,0,!1),this._followObject.worldPosition=this._tempVec.multiplyScalar(2).sub(y),this._followObject.updateMatrix(),this._followObject.updateMatrix()}if(this.settings.snapGridResolution>0){const y=this._followObject.worldPosition,A=this.settings.snapGridResolution;y.x=Math.round(y.x/A)*A,y.y=Math.round(y.y/A)*A,y.z=Math.round(y.z/A)*A,this._followObject.worldPosition=y,this._followObject.updateMatrix()}l&&(this._followObject.worldQuaternion=this._followObjectStartWorldQuaternion,this._followObject.updateMatrix());const f=it.clamp01(this.context.time.deltaTime*h*p),g=t.worldPosition;g.lerp(this._followObject.worldPosition,f),t.worldPosition=g;const v=t.worldQuaternion;if(v.slerp(this._followObject.worldQuaternion,f),t.worldQuaternion=v,Ac){const y=this._hitPointInLocalSpace.clone();t.localToWorld(y),At.DrawSphere(y,.02,16711680);const A=this._hitNormalInLocalSpace.clone();A.applyQuaternion(v),At.DrawRay(y,A,16711680),At.DrawLabel(g.add(new C(0,.25,0)),`Distance: ${this._totalMovement.length().toFixed(2)}
|
|
6216
6216
|
|
|
6217
6217
|
Along Ray: ${this._totalMovementAlongRayDirection.toFixed(2)}
|
|
6218
6218
|
|