@needle-tools/engine 4.1.0 → 4.1.1

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.
@@ -130,7 +130,7 @@ Open this page to get the console: `+t.toString())}const s=Y.isMobileDevice()||Y
130
130
  #__vconsole .vc-mask {
131
131
  overflow: hidden;
132
132
  }
133
- `,Xi?.prepend(n),s===!0&&jm()<=0&&rb(),console.log("\u{1F335} Debug console has loaded")}},t.onerror=()=>{console.warn("\u{1F335} Debug console failed to load."+(window.crossOriginIsolated?"This page is using cross-origin isolation, so external scripts can't be loaded.":"")),sc=!1,ai=null},t.src="https://unpkg.com/vconsole@latest/dist/vconsole.min.js",document.body.appendChild(t)}function gP(){if(!globalThis.VConsole)return;const s=new VConsole.VConsolePlugin("needle-console","\u{1F335} Inspect glTF"),t=()=>document.querySelector("#__vc_plug_"+s._id+" iframe");return s.on("renderTab",function(i){const n=globalThis["needle:codegen_files"];if(!n||n.length===0)return;let o=globalThis["needle:codegen_files"][0];const r=o.indexOf("?");r>-1&&(o=o.substring(0,r));const l=location.protocol+"//"+location.host+location.pathname+"/"+o,c=encodeURIComponent(l);s.fullUrl="https://viewer.needle.tools?inspect&file="+c;var h='<iframe src="" style="width: 100%; height: 99%; border: none;"></iframe>';i(h)}),s.on("show",function(){const i=t();i&&i.src!==s.fullUrl&&(i.src=s.fullUrl)}),s.on("hide",function(){const i=t();i&&(i.src="")}),s.on("addTopBar",function(i){var n=new Array;n.push({name:"Open in new window \u2197",onClick:function(o){window.open(s.fullUrl,"_blank"),ai?.hide()}}),n.push({name:"Reload",onClick:function(o){const r=t();r&&(r.src=s.fullUrl)}}),n.push({name:"Fullscreen",onClick:function(o){const r=t();r.requestFullscreen?r.requestFullscreen():r.webkitRequestFullscreen instanceof Function&&r.webkitRequestFullscreen()}}),i(n)}),s}function fP(){return document.querySelector("#__vconsole .vc-switch")||null}function yP(){return document.querySelector("#__vconsole")||null}const hb=O("debugdefines");uo('if(!globalThis[""4.1.0""]) globalThis[""4.1.0""] = "0.0.0";'),uo('if(!globalThis[""undefined""]) globalThis[""undefined""] = "unknown";'),uo('if(!globalThis[""Thu Feb 13 2025 12:58:05 GMT+0100 (Central European Standard Time)""]) globalThis[""Thu Feb 13 2025 12:58:05 GMT+0100 (Central European Standard Time)""] = "unknown";'),uo('if(!globalThis[""npk_74222a9fbd1b42572cdd3bf7f639eeb17a07d07f40a6185fac5f722e8fd34df9""]) globalThis[""npk_74222a9fbd1b42572cdd3bf7f639eeb17a07d07f40a6185fac5f722e8fd34df9""] = "unknown";'),uo('globalThis["__NEEDLE_ENGINE_VERSION__"] = "4.1.0";'),uo('globalThis["__NEEDLE_ENGINE_GENERATOR__"] = "undefined";'),uo('globalThis["__NEEDLE_PROJECT_BUILD_TIME__"] = "Thu Feb 13 2025 12:58:05 GMT+0100 (Central European Standard Time)";'),uo('globalThis["__NEEDLE_PUBLIC_KEY__"] = "npk_74222a9fbd1b42572cdd3bf7f639eeb17a07d07f40a6185fac5f722e8fd34df9";');const vs="4.1.0",Cd="undefined",ig="Thu Feb 13 2025 12:58:05 GMT+0100 (Central European Standard Time)";hb&&console.log(`Engine version: ${vs} (generator: ${Cd})
133
+ `,Xi?.prepend(n),s===!0&&jm()<=0&&rb(),console.log("\u{1F335} Debug console has loaded")}},t.onerror=()=>{console.warn("\u{1F335} Debug console failed to load."+(window.crossOriginIsolated?"This page is using cross-origin isolation, so external scripts can't be loaded.":"")),sc=!1,ai=null},t.src="https://unpkg.com/vconsole@latest/dist/vconsole.min.js",document.body.appendChild(t)}function gP(){if(!globalThis.VConsole)return;const s=new VConsole.VConsolePlugin("needle-console","\u{1F335} Inspect glTF"),t=()=>document.querySelector("#__vc_plug_"+s._id+" iframe");return s.on("renderTab",function(i){const n=globalThis["needle:codegen_files"];if(!n||n.length===0)return;let o=globalThis["needle:codegen_files"][0];const r=o.indexOf("?");r>-1&&(o=o.substring(0,r));const l=location.protocol+"//"+location.host+location.pathname+"/"+o,c=encodeURIComponent(l);s.fullUrl="https://viewer.needle.tools?inspect&file="+c;var h='<iframe src="" style="width: 100%; height: 99%; border: none;"></iframe>';i(h)}),s.on("show",function(){const i=t();i&&i.src!==s.fullUrl&&(i.src=s.fullUrl)}),s.on("hide",function(){const i=t();i&&(i.src="")}),s.on("addTopBar",function(i){var n=new Array;n.push({name:"Open in new window \u2197",onClick:function(o){window.open(s.fullUrl,"_blank"),ai?.hide()}}),n.push({name:"Reload",onClick:function(o){const r=t();r&&(r.src=s.fullUrl)}}),n.push({name:"Fullscreen",onClick:function(o){const r=t();r.requestFullscreen?r.requestFullscreen():r.webkitRequestFullscreen instanceof Function&&r.webkitRequestFullscreen()}}),i(n)}),s}function fP(){return document.querySelector("#__vconsole .vc-switch")||null}function yP(){return document.querySelector("#__vconsole")||null}const hb=O("debugdefines");uo('if(!globalThis[""4.1.1""]) globalThis[""4.1.1""] = "0.0.0";'),uo('if(!globalThis[""undefined""]) globalThis[""undefined""] = "unknown";'),uo('if(!globalThis[""Fri Feb 14 2025 12:52:58 GMT+0100 (Central European Standard Time)""]) globalThis[""Fri Feb 14 2025 12:52:58 GMT+0100 (Central European Standard Time)""] = "unknown";'),uo('if(!globalThis[""npk_74222a9fbd1b42572cdd3bf7f639eeb17a07d07f40a6185fac5f722e8fd34df9""]) globalThis[""npk_74222a9fbd1b42572cdd3bf7f639eeb17a07d07f40a6185fac5f722e8fd34df9""] = "unknown";'),uo('globalThis["__NEEDLE_ENGINE_VERSION__"] = "4.1.1";'),uo('globalThis["__NEEDLE_ENGINE_GENERATOR__"] = "undefined";'),uo('globalThis["__NEEDLE_PROJECT_BUILD_TIME__"] = "Fri Feb 14 2025 12:52:58 GMT+0100 (Central European Standard Time)";'),uo('globalThis["__NEEDLE_PUBLIC_KEY__"] = "npk_74222a9fbd1b42572cdd3bf7f639eeb17a07d07f40a6185fac5f722e8fd34df9";');const vs="4.1.1",Cd="undefined",ig="Fri Feb 14 2025 12:52:58 GMT+0100 (Central European Standard Time)";hb&&console.log(`Engine version: ${vs} (generator: ${Cd})
134
134
  Project built at ${ig}`);const oc="npk_74222a9fbd1b42572cdd3bf7f639eeb17a07d07f40a6185fac5f722e8fd34df9",xn="needle_isActiveInHierarchy",br="builtin_components",rc="needle_editor_guid";function uo(s){try{(0,eval)(s)}catch(t){hb&&console.error(t)}}const vP='<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>',bP=btoa(vP),_P="data:image/svg+xml;base64,"+bP,wP=_P,xP=`<?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(xP);const SP='<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>',CP=btoa(SP),OP="data:image/svg+xml;charset=utf-8;base64,"+CP,PP=OP,kP=O("debugpatch");function Od(s,t,i,n){const o=kP===t;if(!i&&!n)return;const r=t+"___needle";RP(s,t,i,n);const l=Object.getOwnPropertyDescriptor(s,t),c=s[t];o&&console.log("Patch",s.constructor.name,t,l,c),l?(o&&console.log("Apply patch with existing descriptor",s.constructor.name,t,l),typeof l.value=="function"&&(s[t]=ub(l.value,s,t))):(o&&console.log("Create patch with new property",s.constructor.name,t,l),Object.defineProperty(s,t,{set:function(h){if(typeof h=="function")this[r]=ub(h,s,t);else{const d=this[r];pb(s,t,this,d,h),this[r]=h,mb(s,t,this,d,h)}},get:function(){const h=this[r];return typeof h=="function"&&h[r]?h[r]:h}}))}function MP(s,t,i){const n=ng(s,t);if(n)for(let o=n.length-1;o>=0;o--){const r=n[o];r.prefix===i&&(r.prefix=null),r.postfix===i&&(r.postfix=null),!r.prefix&&!r.postfix&&n.splice(o,1)}}const db=Symbol("Needle:Patches:WrappedFunction");function ub(s,t,i){if(s[db])return s;const n=function(...o){pb(t,i,this,...o);const r=s.apply(this,o);return mb(t,i,this,r,...o),r};return n[db]=!0,n}const Pd="Needle:Patches";function sg(){return globalThis[Pd]||(globalThis[Pd]=new WeakMap),globalThis[Pd]}function ng(s,t){const i=sg().get(s);return i?i.get(t):null}function RP(s,t,i,n){let o=sg().get(s);o||(o=new Map,sg().set(s,o));let r=o.get(t);r||(r=[],o.set(t,r)),r.push({prefix:i,postfix:n})}function pb(s,t,i,...n){var o;if(!i)return;const r=ng(s,t);if(r)for(const l of r)(o=l.prefix)==null||o.call(i,...n)}function mb(s,t,i,n,...o){var r;if(!i)return;const l=ng(s,t);if(l)for(const c of l)(r=c.postfix)==null||r.call(i,n,...o)}const Pa=[];function kd(s){Pa.indexOf(s)===-1&&Pa.push(s)}function TP(s){const t=Pa.indexOf(s);t!==-1&&Pa.splice(t,1)}const ka=[];function og(s){ka.indexOf(s)===-1&&ka.push(s)}function EP(s){const t=ka.indexOf(s);t!==-1&&ka.splice(t,1)}function gb(s){globalThis.dispatchEvent(new CustomEvent("needle-xrsession-start",{detail:s}));for(let t=0;t<Pa.length;t++)Pa[t](s)}function fb(s){globalThis.dispatchEvent(new CustomEvent("needle-xrsession-end",{detail:s}));for(let t=0;t<ka.length;t++)ka[t](s)}const ct=O("debuginput");var Md=(s=>(s.Mouse="mouse",s.Touch="touch",s.Controller="controller",s.Hand="hand",s))(Md||{}),De=(s=>(s.PointerDown="pointerdown",s.PointerUp="pointerup",s.PointerMove="pointermove",s.KeyDown="keydown",s.KeyUp="keyup",s.KeyPressed="keypress",s))(De||{});class Sn extends PointerEvent{constructor(t,i,n){super(t,n),a(this,"clientZ"),a(this,"deviceIndex"),a(this,"origin"),a(this,"source"),a(this,"mode"),a(this,"_ray"),a(this,"space"),a(this,"isClick",!1),a(this,"isDoubleClick",!1),a(this,"_used",!1),a(this,"_pointerid"),a(this,"_pointerType"),a(this,"_type"),a(this,"metadata",{}),a(this,"intersections",new Array),a(this,"_immediatePropagationStopped",!1),a(this,"_propagationStopped",!1),this.clientZ=n.clientZ,this._pointerid=n.pointerId,this._pointerType=n.pointerType,this._type=t,this.deviceIndex=n.deviceIndex,this.origin=n.origin,this.source=i,this.mode=n.mode,this._ray=n.ray,this.space=n.device}get isSpatial(){return this.mode!="screen"}get ray(){return this._ray||(this._ray=new hr(this.space.worldPosition.clone(),this.space.worldForward.clone())),this._ray}set ray(t){this._ray=t}get hasRay(){return this._ray!==void 0}get used(){return this._used}use(){this._used=!0}get pointerId(){return this._pointerid}get pointerType(){return this._pointerType}get type(){return this._type}get immediatePropagationStopped(){return this._immediatePropagationStopped}get propagationStopped(){return this._immediatePropagationStopped||this._propagationStopped}stopImmediatePropagation(){var t;this._immediatePropagationStopped=!0,super.stopImmediatePropagation(),(t=this.source)==null||t.stopImmediatePropagation()}stopPropagation(){var t;this._propagationStopped=!0,super.stopPropagation(),(t=this.source)==null||t.stopPropagation(),ct&&console.warn("Stop propagation...",this.pointerId,this.pointerType)}}class ac extends KeyboardEvent{constructor(t,i,n){super(t,n),a(this,"source"),this.source=i}stopImmediatePropagation(){var t;super.stopImmediatePropagation(),(t=this.source)==null||t.stopImmediatePropagation()}}class AP{constructor(t){a(this,"key"),a(this,"keyType"),a(this,"source"),this.key=t.key,this.keyType=t.type,this.source=t}}var Ci=(s=>(s[s.Early=-100]="Early",s[s.Default=0]="Default",s[s.Late=100]="Late",s))(Ci||{});class yb{constructor(t){a(this,"_eventListeners",{}),a(this,"_doubleClickTimeThreshold",.2),a(this,"_longPressTimeThreshold",1),a(this,"_specialCursorTrigger",0),a(this,"context"),a(this,"_pointerDown",[!1]),a(this,"_pointerUp",[!1]),a(this,"_pointerClick",[!1]),a(this,"_pointerDoubleClick",[!1]),a(this,"_pointerPressed",[!1]),a(this,"_pointerPositions",[new oe]),a(this,"_pointerPositionsLastFrame",[new oe]),a(this,"_pointerPositionsDelta",[new oe]),a(this,"_pointerPositionsRC",[new oe]),a(this,"_pointerPositionDown",[new x]),a(this,"_pointerDownTime",[]),a(this,"_pointerUpTime",[]),a(this,"_pointerUpTimestamp",[]),a(this,"_pointerIds",[]),a(this,"_pointerTypes",[""]),a(this,"_mouseWheelChanged",[!1]),a(this,"_mouseWheelDeltaY",[0]),a(this,"_pointerEvent",[]),a(this,"_pointerEventsPressed",[]),a(this,"_pointerSpace",[]),a(this,"_pressedStack",new Map),a(this,"_htmlEventSource"),a(this,"onLostFocus",()=>{for(const i in this.keysPressed)this.keysPressed[i].pressed=!1}),a(this,"onEndOfFrame",()=>{for(let i=0;i<this._pointerUp.length;i++)this._pointerUp[i]=!1;for(let i=0;i<this._pointerDown.length;i++)this._pointerDown[i]=!1;for(let i=0;i<this._pointerClick.length;i++)this._pointerClick[i]=!1;for(let i=0;i<this._pointerDoubleClick.length;i++)this._pointerDoubleClick[i]=!1;for(const i of this._pointerPositionsDelta)i.set(0,0);for(let i=0;i<this._mouseWheelChanged.length;i++)this._mouseWheelChanged[i]=!1;for(let i=0;i<this._mouseWheelDeltaY.length;i++)this._mouseWheelDeltaY[i]=0}),a(this,"onContextMenu",i=>{this.canReceiveInput(i)!==!1&&i instanceof PointerEvent&&i.pointerType}),a(this,"keysPressed",{}),a(this,"onKeyDown",i=>{if(ct&&console.log(`key down ${i.code}, ${this.context.application.hasFocus}`,i),!this.context.application.hasFocus)return;const n=this.keysPressed[i.code];if(n&&n.pressed)return;this.keysPressed[i.code]={pressed:!0,frame:this.context.time.frameCount+1,startFrame:this.context.time.frameCount+1,key:i.key,code:i.code};const o=new ac("keydown",i,i);this.onDispatchEvent(o)}),a(this,"onKeyPressed",i=>{if(!this.context.application.hasFocus)return;const n=this.keysPressed[i.code];if(!n)return;n.pressed=!0,n.frame=this.context.time.frameCount+1;const o=new ac("keypress",i,i);this.onDispatchEvent(o)}),a(this,"onKeyUp",i=>{if(!this.context.application.hasFocus)return;const n=this.keysPressed[i.code];if(!n)return;n.pressed=!1,n.frame=this.context.time.frameCount+1;const o=new ac("keyup",i,i);this.onDispatchEvent(o)}),a(this,"onWheelWindow",i=>{document.pointerLockElement&&this.onMouseWheel(i)}),a(this,"onMouseWheel",i=>{if(this.canReceiveInput(i)===!1)return;this._mouseWheelDeltaY.length<=0&&this._mouseWheelDeltaY.push(0),this._mouseWheelChanged.length<=0&&this._mouseWheelChanged.push(!1),this._mouseWheelChanged[0]=!0;const n=this._mouseWheelDeltaY[0];this._mouseWheelDeltaY[0]=n+i.deltaY}),a(this,"onPointerDown",i=>{if(this.context.isInAR||this.canReceiveInput(i)===!1)return;i.target instanceof HTMLElement&&i.target.setPointerCapture(i.pointerId);const n=this.getPointerId(i);ct&&Le(`pointer down #${n}, identifier:${i.pointerId}`);const o=this.getAndUpdateSpatialObjectForScreenPosition(n,i.clientX,i.clientY),r=new Sn("pointerdown",i,{origin:this,mode:"screen",deviceIndex:0,pointerId:n,button:i.button,clientX:i.clientX,clientY:i.clientY,pointerType:i.pointerType,buttonName:this.getButtonName(i),device:o,pressure:i.pressure});this.onDown(r)}),a(this,"onPointerMove",i=>{if(this.context.isInAR)return;let n=i.button;i.pointerType==="mouse"&&(n=this.getFirstPressedButtonForPointer(0)??0);const o=this.getPointerId(i,n);n===-1&&(n=o);const r=this.getAndUpdateSpatialObjectForScreenPosition(o,i.clientX,i.clientY),l=new Sn("pointermove",i,{origin:this,mode:"screen",deviceIndex:0,pointerId:o,button:n,clientX:i.clientX,clientY:i.clientY,pointerType:i.pointerType,buttonName:this.getButtonName(i),device:r,pressure:i.pressure});this.onMove(l)}),a(this,"onPointerCancel",i=>{this.context.isInAR||(ct&&console.log("Pointer cancel",i),this.onPointerUp(i))}),a(this,"onPointerUp",i=>{if(this.context.isInAR)return;i.target instanceof HTMLElement&&i.target.releasePointerCapture(i.pointerId);const n=this.getPointerId(i),o=new Sn("pointerup",i,{origin:this,mode:"screen",deviceIndex:0,pointerId:n,button:i.button,clientX:i.clientX,clientY:i.clientY,pointerType:i.pointerType,buttonName:this.getButtonName(i),device:this.getAndUpdateSpatialObjectForScreenPosition(n,i.clientX,i.clientY),pressure:i.pressure});this.onUp(o),this._pointerIds[n]=-1,ct&&console.log("ID="+n,"PointerId="+i.pointerId,"ALL:",[...this._pointerIds])}),a(this,"onTouchStart",i=>{if(this.context.isInAR)for(let n=0;n<i.changedTouches.length;n++){const o=i.changedTouches[n],r=this.getPointerIndex(o.identifier),l=this.getAndUpdateSpatialObjectForScreenPosition(r,o.clientX,o.clientY),c=new Sn("pointerdown",i,{origin:this,mode:"screen",deviceIndex:0,pointerId:r,button:0,clientX:o.clientX,clientY:o.clientY,pointerType:"touch",buttonName:"unknown",device:l,pressure:o.force});this.onDown(c)}}),a(this,"onTouchMove",i=>{if(this.context.isInAR)for(let n=0;n<i.changedTouches.length;n++){const o=i.changedTouches[n],r=this.getPointerIndex(o.identifier),l=this.getAndUpdateSpatialObjectForScreenPosition(r,o.clientX,o.clientY),c=new Sn("pointermove",i,{origin:this,mode:"screen",deviceIndex:0,pointerId:r,button:0,clientX:o.clientX,clientY:o.clientY,pointerType:"touch",buttonName:"unknown",device:l,pressure:o.force});this.onMove(c)}}),a(this,"onTouchEnd",i=>{if(this.context.isInAR)for(let n=0;n<i.changedTouches.length;n++){const o=i.changedTouches[n],r=this.getPointerIndex(o.identifier),l=new Sn("pointerup",i,{origin:this,mode:"screen",deviceIndex:0,pointerId:r,button:0,clientX:o.clientX,clientY:o.clientY,pointerType:"touch",buttonName:"unknown",device:this.getAndUpdateSpatialObjectForScreenPosition(r,o.clientX,o.clientY),pressure:o.force});this.onUp(l),this._pointerIds[r]=-1}}),a(this,"tempNearPlaneVector",new x),a(this,"tempFarPlaneVector",new x),a(this,"tempLookMatrix",new ne),this.context=t,this.context.post_render_callbacks.push(this.onEndOfFrame)}addEventListener(t,i,n){if(this._eventListeners[t]||(this._eventListeners[t]=[]),!i||typeof i!="function"){console.error("Invalid call to addEventListener: callback is required and must be a function!");return}n?n={...n}:n={};let o=0;n?.queue!=null&&(o=n.queue);const r=this._eventListeners[t],l=r.find(c=>c.priority===o);l?l.listeners.push({callback:i,options:n}):(r.push({priority:o,listeners:[{callback:i,options:n}]}),r.sort((c,h)=>c.priority-h.priority))}removeEventListener(t,i,n){if(!this._eventListeners[t]||!i)return;const o=this._eventListeners[t];if(n?.queue!=null){const r=o.find(c=>c.priority===n.queue);if(!r)return;const l=r.listeners.findIndex(c=>c.callback===i);l>=0&&r.listeners.splice(l,1)}else for(const r of o){const l=r.listeners.findIndex(c=>c.callback===i);l>=0&&r.listeners.splice(l,1)}}dispatchEvent(t){var i,n,o,r;let l=!1;if(t instanceof ac){const c=this._eventListeners[t.type];if(c)for(const h of c)for(let d=0;d<h.listeners.length;d++){const u=h.listeners[d];if((n=(i=u.options)==null?void 0:i.signal)!=null&&n.aborted){h.listeners.splice(d,1),d--;continue}u.options.once&&(h.listeners.splice(d,1),d--),u.callback(t)}}if(t instanceof Sn){const c=this._eventListeners[t.type];if(c)for(const h of c){if(l)break;for(let d=0;d<h.listeners.length;d++){const u=h.listeners[d];if((r=(o=u.options)==null?void 0:o.signal)!=null&&r.aborted){h.listeners.splice(d,1),d--;continue}if(t.immediatePropagationStopped){l=!0,ct&&console.log("immediatePropagationStopped",t.type);break}else t.propagationStopped&&(l=!0,ct&&console.log("propagationStopped",t.type));u.options.once&&(h.listeners.splice(d,1),d--),u.callback(t)}}}}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)}get click(){return this._pointerClick[0]}get doubleClick(){return this._pointerDoubleClick[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")}getIsPointerIdInUse(t){for(const i of this._pointerEventsPressed)if(i.pointerId===t&&i.used)return!0;return!1}getPointerPressedCount(){let t=0;for(let i=0;i<this._pointerPressed.length;i++)this._pointerPressed[i]&&t++;return t}getPointerPosition(t){return t>=this._pointerPositions.length?null:this._pointerPositions[t]}getPointerPositionLastFrame(t){return t>=this._pointerPositionsLastFrame.length?null:this._pointerPositionsLastFrame[t]}getPointerPositionDelta(t){return t>=this._pointerPositionsDelta.length?null:this._pointerPositionsDelta[t]}getPointerPositionRC(t){return t>=this._pointerPositionsRC.length?null:this._pointerPositionsRC[t]}getPointerDown(t){return t>=this._pointerDown.length?!1:this._pointerDown[t]}getPointerUp(t){return t>=this._pointerUp.length?!1:this._pointerUp[t]}getPointerPressed(t){return t>=this._pointerPressed.length?!1:this._pointerPressed[t]}getPointerClicked(t){return t>=this._pointerClick.length?!1:this._pointerClick[t]}getPointerDoubleClicked(t){return t>=this._pointerDoubleClick.length?!1:this._pointerDoubleClick[t]}getPointerDownTime(t){return t>=this._pointerDownTime.length?-1:this._pointerDownTime[t]}getPointerUpTime(t){return t>=this._pointerUpTime.length?-1:this._pointerUpTime[t]}getPointerLongPress(t){return t>=this._pointerDownTime.length?!1:this.getPointerPressed(t)&&this.context.time.time-this._pointerDownTime[t]>this._longPressTimeThreshold}getIsMouse(t){return t<0||t>=this._pointerTypes.length?!1:this._pointerTypes[t]==="mouse"}getIsTouch(t){return t<0||t>=this._pointerTypes.length?!1:this._pointerTypes[t]==="touch"}getTouchesPressedCount(){let t=0;for(let i=0;i<this._pointerPressed.length;i++)this._pointerPressed[i]&&this.getIsTouch(i)&&t++;return t}getMouseWheelChanged(t=0){return t>=this._mouseWheelChanged.length?!1:this._mouseWheelChanged[t]}getMouseWheelDeltaY(t=0){return t>=this._mouseWheelDeltaY.length?0:this._mouseWheelDeltaY[t]}getPointerEvent(t){if(!(t>=this._pointerEvent.length))return this._pointerEvent[t]??void 0}*foreachPointerId(t){for(let i=0;i<this._pointerTypes.length;i++)if(this._pointerIsActive(i)){if(t!==void 0){const n=this._pointerTypes[i];if(Array.isArray(t)){let o=!1;for(const r of t)if(n===r){o=!0;break}if(!o)continue}else if(t!==n)continue}yield i}}*foreachTouchId(){for(let t=0;t<this._pointerTypes.length;t++)this._pointerTypes[t]==="touch"&&this._pointerIsActive[t]&&(yield t)}_pointerIsActive(t){return t<0?!1:this._pointerPressed[t]||this._pointerDown[t]||this._pointerUp[t]}onDownButton(t,i){let n=this._pressedStack.get(t);n||(n=[],this._pressedStack.set(t,n)),n.push(i)}onReleaseButton(t,i){const n=this._pressedStack.get(t);if(!n)return;const o=n.indexOf(i);o>=0&&n.splice(o,1)}getFirstPressedButtonForPointer(t){const i=this._pressedStack.get(t);if(i)return i[0]}getLatestPressedButtonForPointer(t){const i=this._pressedStack.get(t);if(i)return i[i.length-1]}getKeyDown(){for(const t in this.keysPressed){const i=this.keysPressed[t];if(i.startFrame===this.context.time.frameCount)return i.key}return null}getKeyPressed(){for(const t in this.keysPressed){const i=this.keysPressed[t];if(i.pressed)return i.key}return null}isKeyDown(t){var i;if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const n=this.getCodeForCommonKeyName(t);if(n!==null){for(const o of n)if(this.isKeyDown(o))return!0;return!1}return((i=this.keysPressed[t])==null?void 0:i.startFrame)===this.context.time.frameCount&&this.keysPressed[t].pressed}isKeyUp(t){var i;if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const n=this.getCodeForCommonKeyName(t);if(n!==null){for(const o of n)if(this.isKeyUp(o))return!0;return!1}return((i=this.keysPressed[t])==null?void 0:i.frame)===this.context.time.frameCount&&!this.keysPressed[t].pressed}isKeyPressed(t){var i;if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const n=this.getCodeForCommonKeyName(t);if(n!==null){for(const o of n)if(this.isKeyPressed(o))return!0;return!1}return(i=this.keysPressed[t])==null?void 0:i.pressed}getCodeForCommonKeyName(t){if(t.length===1){if(t>="0"&&t<="9")return["Digit"+t];if(t>="a"&&t<="z")return["Key"+t.toUpperCase()];if(t==" ")return["Space"]}switch(t){case"shift":case"Shift":return["ShiftLeft","ShiftRight"];case"control":case"Control":return["ControlLeft","ControlRight"];case"alt":case"Alt":return["AltLeft","AltRight"]}return null}createInputEvent(t){switch(t.type){case"pointerdown":ct&&Le("Create Pointer down"),this.onDownButton(t.deviceIndex,t.button),this.onDown(t);break;case"pointermove":ct&&Le("Create Pointer move"),this.onMove(t);break;case"pointerup":ct&&Le("Create Pointer up"),this.onUp(t),this.onReleaseButton(t.deviceIndex,t.button);break}}convertScreenspaceToRaycastSpace(t){return t.x=(t.x-this.context.domX)/this.context.domWidth*2-1,t.y=-((t.y-this.context.domY)/this.context.domHeight)*2+1,t}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 t,i;window.removeEventListener("contextmenu",this.onContextMenu),(t=this._htmlEventSource)==null||t.removeEventListener("pointerdown",this.onPointerDown),window.removeEventListener("pointermove",this.onPointerMove),window.removeEventListener("pointerup",this.onPointerUp),window.removeEventListener("pointercancel",this.onPointerCancel),(i=this._htmlEventSource)==null||i.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 t=this.context.post_render_callbacks.indexOf(this.onEndOfFrame);t>=0&&this.context.post_render_callbacks.splice(t,1),this.unbindEvents()}canReceiveInput(t){var i;return t.target===((i=this.context.renderer)==null?void 0:i.domElement)||t.target===this.context.domElement||this.context.isInAR||this.context.isInAR&&t.target===document.body&&Y.isMozillaXR()?!0:(ct&&console.warn("CanReceiveInput:False for",t.target),!1)}getPointerId(t,i){return t.pointerType==="mouse"?0+(i??t.button):this.getPointerIndex(t.pointerId)}getButtonName(t){const i=t.button;if(t.pointerType==="mouse")switch(i){case 0:return"left";case 1:return"middle";case 2:return"right"}return"unknown"}getAndUpdateSpatialObjectForScreenPosition(t,i,n){let o=this._pointerSpace[t];o||(o=new j,this._pointerSpace[t]=o),this._pointerSpace[t]=o;const r=this.context.mainCamera;if(r){const l=this.tempNearPlaneVector.set(i,n,-1);this.convertScreenspaceToRaycastSpace(l);const c=this.tempFarPlaneVector.set(l.x,l.y,1);l.unproject(r),c.unproject(r);const h=r.worldUp||$(0,1,0).applyQuaternion(Se(r));this.tempLookMatrix.lookAt(c,l,h),o.position.set(l.x,l.y,l.z),o.quaternion.setFromRotationMatrix(this.tempLookMatrix)}return o}isInRect(t){if(this.context.isInXR)return!0;const i=this.context.domElement.getBoundingClientRect(),n=t.clientX,o=t.clientY,r=n>=i.x&&n<=i.right&&o>=i.y&&o<=i.bottom;return ct&&!r&&console.log("Not in rect",i,n,o),r}onDown(t){const i=t.pointerId;if(this.getPointerPressed(i)&&console.warn(`Received pointerDown for pointerId that is already pressed: ${i}`,ct?t:""),ct&&console.log(t.pointerType,"DOWN",i),!!this.isInRect(t)){for(this.setPointerState(i,this._pointerPressed,!0),this.setPointerState(i,this._pointerDown,!0),this.setPointerStateT(i,this._pointerEvent,t.source);i>=this._pointerTypes.length;)this._pointerTypes.push(t.pointerType);for(this._pointerTypes[i]=t.pointerType;i>=this._pointerPositionDown.length;)this._pointerPositionDown.push(new x);for(this._pointerPositionDown[i].set(t.clientX,t.clientY,t.clientZ??0);i>=this._pointerPositions.length;)this._pointerPositions.push(new oe);this._pointerPositions[i].set(t.clientX,t.clientY),i>=this._pointerDownTime.length&&this._pointerDownTime.push(0),this._pointerDownTime[i]=this.context.time.realtimeSinceStartup,this.updatePointerPosition(t),this._pointerEventsPressed.push(t),this.onDispatchEvent(t)}}onMove(t){const i=t.pointerId,n=this.getPointerPressed(i);n===!1&&!this.isInRect(t)||t.pointerType==="touch"&&!n||(this.updatePointerPosition(t),this.setPointerStateT(i,this._pointerEvent,t.source),this.onDispatchEvent(t))}onUp(t){const i=t.pointerId;if(!this.getPointerPressed(i)){ct&&console.log(t.pointerType,"UP",i,"was not down");return}ct&&console.log(t.pointerType,"UP",i),this.setPointerState(i,this._pointerPressed,!1),this.setPointerStateT(i,this._pointerEvent,t.source),this.setPointerState(i,this._pointerUp,!0),this.updatePointerPosition(t);for(let c=this._pointerEventsPressed.length-1;c>=0;c--)if(this._pointerEventsPressed[c].pointerId===i){this._pointerEventsPressed.splice(c,1);break}if(!this._pointerPositionDown[i]){ct&&_e("Received pointer up event without matching down event for button: "+i),console.warn("Received pointer up event without matching down event for button: "+i);return}const n=this._pointerUpTime[i],o=this._pointerDownTime[i],r=this.context.time.realtimeSinceStartup,l=r-o;if(i>=this._pointerUpTime.length&&this._pointerUpTime.push(-99),this._pointerUpTime[i]=r,l<1){let c=t.clientX-this._pointerPositionDown[i].x,h=t.clientY-this._pointerPositionDown[i].y,d=0;if(t.isSpatial&&t.clientZ!=null&&(d=t.clientZ-this._pointerPositionDown[i].z,c*=200,h*=200,d*=200),Math.abs(c)<5&&Math.abs(h)<5&&Math.abs(d)<5){this.setPointerState(i,this._pointerClick,!0),t.isClick=!0;const u=r-n;ct&&console.log("CLICK",i,c,h,d,u),u<this._doubleClickTimeThreshold&&u>0&&(this.setPointerState(i,this._pointerDoubleClick,!0),t.isDoubleClick=!0)}}this.onDispatchEvent(t)}updatePointerPosition(t){const i=t.pointerId;for(;i>=this._pointerPositions.length;)this._pointerPositions.push(new oe);for(;i>=this._pointerPositionsLastFrame.length;)this._pointerPositionsLastFrame.push(new oe);for(;i>=this._pointerPositionsDelta.length;)this._pointerPositionsDelta.push(new oe);const n=this._pointerPositionsLastFrame[i];n.copy(this._pointerPositions[i]);const o=this._pointerPositionsDelta[i];let r=t.clientX-n.x,l=t.clientY-n.y;if(t.source instanceof MouseEvent||t.source instanceof TouchEvent){const u=t.source;r===0&&u.movementX!==0&&(r=u.movementX||0),l===0&&u.movementY!==0&&(l=u.movementY||0)}o.x+=r,o.y+=l,this._pointerPositions[i].x=t.clientX,this._pointerPositions[i].y=t.clientY;const c=t.clientX,h=t.clientY;for(;i>=this._pointerPositionsRC.length;)this._pointerPositionsRC.push(new oe);const d=this._pointerPositionsRC[i];d.set(c,h),this.convertScreenspaceToRaycastSpace(d)}getPointerIndex(t){let i=-1;for(let n=0;n<this._pointerIds.length;n++){if(this._pointerIds[n]===t)return n;i===-1&&this._pointerIds[n]===-1&&(i=n)}return i!==-1?(this._pointerIds[i]=t,i):(ct&&console.log("PUSH pointerId:",t),this._pointerIds.push(t),this._pointerIds.length-1)}setPointerState(t,i,n){i[t]=n}setPointerStateT(t,i,n){return i[t]=n,n}onDispatchEvent(t){const i=te.Current;try{te.Current=this.context,this.dispatchEvent(t)}finally{te.Current=i}}}const Ma=new ne().makeRotationY(Math.PI),Qi=new V().setFromAxisAngle(new x(0,1,0),Math.PI),IP=O("debugwebxr");class jP{constructor(){if(a(this,"priority",-1e5),a(this,"gameObject"),this.gameObject=new j,this.gameObject.name="Implicit XR Rig",IP){const t=wg(16733661);t.position.y+=.5,this.gameObject.add(t)}}isXRRig(){return!0}get isActive(){return this.gameObject.visible}}const zs=O("debugwebxr"),Rd=O("debugcustomgesture"),LP="https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles",DP="generic-trigger",BP=new V().setFromEuler(new Ft(vn.degToRad(0),vn.degToRad(-90),vn.degToRad(-90))),FP=new x(.04,-.04,0);class rg{constructor(t,i,n){a(this,"xr"),a(this,"inputSource"),a(this,"index",0),a(this,"emitEvents",!0),a(this,"_connected",!0),a(this,"_isTracking",!1),a(this,"__gamepad"),a(this,"__hand"),a(this,"__side"),a(this,"_hitTestSource"),a(this,"_hasSelectEvent",!1),a(this,"_isMxInk",!1),a(this,"_isMxInkFallback",!1),a(this,"_isMetaQuestTouchController",!1),a(this,"_handJointPoses",new Map),a(this,"_gripMatrix",new ne),a(this,"_gripPosition",new x),a(this,"_gripQuaternion",new V),a(this,"_linearVelocity",new x),a(this,"_rayPositionRaw",new x),a(this,"_rayRotationRaw",new V),a(this,"_rayMatrix",new ne),a(this,"_rayPosition",new x),a(this,"_rayQuaternion",new V),a(this,"_gripWorldPosition",new x),a(this,"_gripWorldQuaternion",new V),a(this,"_rayWorldPosition",new x),a(this,"_rayWorldQuaternion",new V),a(this,"_pinchPosition",new x),a(this,"_ray"),a(this,"_hand_wristDotUp"),a(this,"_object"),a(this,"_gripSpaceObject"),a(this,"_raySpaceObject"),a(this,"model",null),a(this,"_debugAxesHelper",new bi(.15)),a(this,"_debugGripAxesHelper",new bi(.07)),a(this,"_debugRayAxesHelper",new bi(.07)),a(this,"_hitTestSourcePromise",null),a(this,"onPointerHits",o=>{}),a(this,"_needleGamepadButtons",{}),a(this,"_buttonMap",new Map),a(this,"_motioncontroller"),a(this,"_layout"),a(this,"getMotionController"),a(this,"emitPointerDownEvent",!0),a(this,"emitPointerUpEvent",!0),a(this,"emitPointerMoveEvent",!0),a(this,"pointerMoveDistanceThreshold",.03),a(this,"pointerMoveAngleThreshold",.05),a(this,"_selectButtonIndex"),a(this,"_squeezeButtonIndex"),a(this,"onSelectStart",o=>{var r,l,c,h;if(!this.emitPointerDownEvent||this.inputSource!==o.inputSource)return;this.onUpdateFrame(o.frame),this._hasSelectEvent=!0;const d=(r=this._layout)==null?void 0:r.selectComponentId,u=(h=(c=(l=this._layout)==null?void 0:l.components[d])==null?void 0:c.gamepadIndices)==null?void 0:h.button;u!==void 0&&(this._selectButtonIndex=u),!Rd&&(zs&&q.DrawDirection(this.rayWorldPosition,$(0,.01,1).applyQuaternion(this.rayWorldQuaternion),16711680,10),this.emitPointerEvent(De.PointerDown,this._selectButtonIndex||0,"xr-standard-trigger",!0,o))}),a(this,"onSelectEnd",o=>{this.emitPointerUpEvent&&(Rd||this.inputSource===o.inputSource&&this.emitPointerEvent(De.PointerUp,this._selectButtonIndex||0,"xr-standard-trigger",!0,o))}),a(this,"onSequeezeStart",o=>{var r,l,c;this.emitPointerDownEvent&&this.inputSource===o.inputSource&&(this._squeezeButtonIndex=(c=(l=(r=this._layout)==null?void 0:r.components["xr-standard-squeeze"])==null?void 0:l.gamepadIndices)==null?void 0:c.button,this._squeezeButtonIndex!==void 0&&(zs&&q.DrawDirection(this.rayWorldPosition,$(0,.01,1).applyQuaternion(this.rayWorldQuaternion),255,10),this.emitPointerEvent(De.PointerDown,this._squeezeButtonIndex||0,"xr-standard-squeeze",!0,o)))}),a(this,"onSequeezeEnd",o=>{this.emitPointerUpEvent&&this.inputSource===o.inputSource&&this._squeezeButtonIndex!==void 0&&this.emitPointerEvent(De.PointerUp,this._squeezeButtonIndex||0,"xr-standard-squeeze",!0,o)}),a(this,"states",{}),a(this,"_didMoveLastFrame",!1),a(this,"_lastPointerMovePosition",new x),a(this,"_lastPointerMoveQuaternion",new V),a(this,"pointerInit"),this.xr=t,this.inputSource=i,this.index=n,this._object=new j,this._object.name=`NeedleXRController_${n}`,zs&&(this._object.add(this._debugAxesHelper),this._gripSpaceObject=new j,this._raySpaceObject=new j,this._gripSpaceObject.name=`NeedleXRController_${n}_gripSpace`,this._raySpaceObject.name=`NeedleXRController_${n}_raySpace`,this._gripSpaceObject.add(this._debugGripAxesHelper),this._raySpaceObject.add(this._debugRayAxesHelper),this.xr.context.scene.add(this._gripSpaceObject),this.xr.context.scene.add(this._raySpaceObject)),this.xr.context.scene.add(this._object),this._ray=new hr,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()}get context(){return this.xr.context}get connected(){return this._connected}get isTracking(){return this._isTracking}get gamepad(){return this.__gamepad??(this.__gamepad=this.inputSource.gamepad)}get isHand(){return this.hand!=null}get hand(){return this.__hand??(this.__hand=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.__side??(this.__side=this.inputSource.handedness)}get isRight(){return this.side==="right"}get isLeft(){return this.side==="left"}get isStylus(){return this._isMxInk}getHitTestSource(){return this._hitTestSource||this._requestHitTestSource(),this._hitTestSource}get hasHitTestSource(){return this._hitTestSource}cancelHitTestSource(){this._hitTestSource&&(this._hitTestSource.cancel(),this._hitTestSource=void 0)}get hasSelectEvent(){return this._hasSelectEvent}getHitTest(){return this.xr.getHitTest(this)}getHandJointPose(t,i){var n;if(i=i||this.xr.frame,!this.hand||!(i!=null&&i.getJointPose)||!this.xr.referenceSpace)return null;let o=(n=this._handJointPoses)==null?void 0:n.get(t);return o||(o=i.getJointPose(t,this.xr.referenceSpace),o&&this._handJointPoses.set(t,o),o)}get gripPosition(){return $(this._gripPosition)}get gripQuaternion(){return fs(this._gripQuaternion)}get gripMatrix(){return this._gripMatrix}get gripLinearVelocity(){return $(this._linearVelocity).applyQuaternion(Qi)}get rayPosition(){return $(this._rayPosition)}get rayQuaternion(){return fs(this._rayQuaternion)}get gripWorldPosition(){return $(this._gripWorldPosition)}get gripWorldQuaternion(){return fs(this._gripWorldQuaternion)}get rayWorldPosition(){return $(this._rayWorldPosition)}updateRayWorldPosition(){var t;const i=(t=this.xr.context.mainCamera)==null?void 0:t.parent;this._rayWorldPosition.copy(this._rayPositionRaw),i&&this._rayWorldPosition.applyMatrix4(i.matrixWorld)}get rayWorldQuaternion(){return fs(this._rayWorldQuaternion)}get pinchPosition(){return $(this._pinchPosition)}updateRayWorldQuaternion(){var t;const i=(t=this.xr.context.mainCamera)==null?void 0:t.parent,n=i?Se(i):void 0;this._rayWorldQuaternion.copy(this._rayRotationRaw).multiply(Qi),n&&this._rayWorldQuaternion.premultiply(n)}get ray(){return this._ray.origin.copy(this.rayWorldPosition),this._ray.direction.copy($(0,0,1).applyQuaternion(this.rayWorldQuaternion)),this._ray}get handWristDotUp(){var t;if(this._hand_wristDotUp!==void 0)return this._hand_wristDotUp;const i=(t=this.handObject)==null?void 0:t.joints.wrist;if(i){const n=$(0,1,0).applyQuaternion(i.quaternion),o=$(0,1,0).dot(n);return this._hand_wristDotUp=o}}get isHandUpsideDown(){return this.handWristDotUp!==void 0?this.handWristDotUp<-.7:!1}get isTeleportGesture(){var t;return this.isHandUpsideDown&&((t=this.getGesture("pinch"))==null?void 0:t.isDown)}get object(){return this._object}async getModelUrl(){var t;return(t=this.getMotionController)==null?void 0:t.then(i=>i?.assetUrl||null)}_requestHitTestSource(){var t;return this._hitTestSourcePromise?this._hitTestSourcePromise:this.xr.mode==="immersive-ar"&&this.inputSource.targetRayMode==="tracked-pointer"&&this.xr.session.requestHitTestSourceForTransientInput?this._hitTestSourcePromise=((t=this.xr.session.requestHitTestSourceForTransientInput({profile:this.inputSource.profiles[0],offsetRay:new XRRay}))==null?void 0:t.then(i=>(this._hitTestSourcePromise=null,this.connected?this._hitTestSource=i:(i.cancel(),null))))??null:null}onUpdate(t){performance.mark("NeedleXRController onUpdate start"),this.onUpdateFrame(t),this.updateInputEvents(),this.onUpdateMove(),performance.mark("NeedleXRController onUpdate end"),performance.measure("NeedleXRController onUpdate","NeedleXRController onUpdate start","NeedleXRController onUpdate end")}onRenderDebug(){var t;q.DrawSphere(this.rayWorldPosition,.003),q.DrawDirection(this.rayWorldPosition,$(0,0,10).applyQuaternion(this.rayWorldQuaternion));const i=(this.inputSource.gripSpace?this.gripWorldPosition:this.object.worldPosition).sub(this.object.worldForward.multiplyScalar(.1)),n=this.inputSource.profiles.join(`
135
135
  `);let o=`Controller[${this.index}] (${this.inputSource.targetRayMode}, ${this.side})
136
136
  C:${this.connected?"x":"-"} T:${this.isTracking?"x":"-"} Hand:${this.inputSource.hand?"x":"-"} Pen: ${this._isMxInk?"x":"-"}`;if(this.inputSource.hand&&(o+=`
@@ -151,12 +151,12 @@ See https://engine.needle.tools/docs/scripting.html#special-lifecycle-hooks for
151
151
  `+Oi);const c=await import("./vendor.light.min.js").then(p=>p.j),h=((n=c.default)==null?void 0:n.WebsocketBuilder)??c.WebsocketBuilder,d=((o=c.default)==null?void 0:o.ExponentialBackoff)??c.ExponentialBackoff,u=new h(Oi).withMaxRetries(10).withBackoff(new d(2e3,4)).onOpen(()=>{this._connectingToWebsocketPromise=null,this._ws=u,this.connected=!0,F()||li?console.log(`\u229E Connected to networking backend
152
152
  `+Oi):console.debug("\u229E Connected to networking backend",Oi),l(!0),this.onSendQueued(bs.OnConnection)}).onClose(p=>{this._connectingToWebsocketPromise=null,this.connected=!1,this._isInRoom=!1,l(!1);let g="Websocket connection closed...";Oi!=null&&Oi.includes("/socket")||(g+=' Do you perhaps mean to connect to "/socket"?'),console.error(g)}).onError(p=>{console.error("\u22A0 Websocket connection failed..."),l(!1)}).onRetry(()=>{console.log("\u2192 Retry connecting to networking websocket")}).build();u.addEventListener(c.WebsocketEvent.message,(p,g)=>{this.onMessage(p,g)})})}onMessage(t,i){const n=i.data;try{if(typeof n!="string"){n.size&&this.handleIncomingBinaryMessage(n);return}const o=JSON.parse(n);if(Array.isArray(o))for(const r of o)this.handleIncomingStringMessage(r);else this.handleIncomingStringMessage(o);return}catch(o){li&&n==="pong"?console.log("<<",n):F()&&console.error("Failed to parse message",o)}}async handleIncomingBinaryMessage(t){dg&&console.log("<< bin",this.context.time.frame);const i=await t.arrayBuffer();var n=new Uint8Array(i);const o=new KC(n),r=o.getBufferIdentifier(),l=this._listenersBinary[r],c=Cb(o),h=Ob(c);if(h&&typeof h=="string"&&(this._state[h]=c),!l)return;const d=c??o;for(const u of l)u(d)}handleIncomingStringMessage(t){var i,n;if(li&&console.log("<<",t.key??t),t.key)switch(t.key){case"connection-start-info":if(t.data){const c=t.data;c&&(console.assert(c.id!==void 0&&c.id!==null&&c.id.length>0,"server did not send connection id",c.id),console.debug("Your id is: "+c.id,this.context.alias??""),this._connectionId=c.id)}else console.warn("Expected connection id in "+t.key);break;case"joined-room":if(li&&console.log(t),t){this._isInRoom=!0;const c=t;this._currentRoomName=c.room,this._currentRoomViewId=c.viewId,this._currentRoomAllowEditing=c.allowEditing??!0,this._currentInRoom.length=0,this._currentInRoom.push(...c.inRoom),(dg||F())&&console.debug("Joined Needle Engine Room: "+c.room);const h=new URL(window.location.href);h.searchParams.has("room")&&h.searchParams.delete("room"),h.searchParams.set("view",this._currentRoomViewId),console.debug(`Room view id: ${this._currentRoomViewId}
153
153
  ${h.href}`)}this.onSendQueued(bs.OnRoomJoin);break;case"left-room":t.room===this.currentRoomName&&(this._isInRoom=!1,this._currentRoomName=null,this._currentInRoom.length=0);break;case"user-joined-room":if(t.data){const c=t.data;this._currentInRoom.push(c.userId),li&&console.log(c.userId+" joined","now in room:",this._currentInRoom)}break;case"user-left-room":if(t.data){const c=t.data,h=this._currentInRoom.indexOf(c.userId);h>=0&&(li&&console.log(c.userId+" left","now in room:",this._currentInRoom),this._currentInRoom.splice(h,1)),c.userId===this.connectionId&&console.log("you left the room")}break;case"all-room-state-deleted":li&&console.log("RECEIVED all-room-state-deleted"),this._state={};break;case"ping":case"pong":const l=(i=t.data)==null?void 0:i.time;l&&(this._currentDelay=this.context.time.time-l),li&&console.log("Current latency: "+this._currentDelay.toFixed(4)+" sec","Clients in room: "+((n=this._currentInRoom)==null?void 0:n.length));break}const o=t.data;o&&(this._state[o.guid]=o);let r=this._listeners[t.key];if(r){r=[...r];for(const l of r)try{l(t.data)}catch(c){console.error('Error invoking callback for "'+t.key+'"',c)}}}toMessage(t,i){return{key:t,data:i}}sendWithWebsocket(t,i,n=bs.OnRoomJoin){if(!this._ws){const r=this._waitingForSocket[n]||[];r.push(()=>this.sendWithWebsocket(t,i,n)),this._waitingForSocket[n]=r;return}const o=JSON.stringify(this.toMessage(t,i));li&&console.log(">>",t),this._ws.send(o)}onSendQueued(t){const i=this._waitingForSocket[t];if(i){for(const n of i)n();i.length=0}}}const cc=O("debugwebxr");class pg{constructor(t,i){a(this,"controllerStates",[]),a(this,"userId"),a(this,"context"),a(this,"userStateEvtName"),a(this,"onReceivedControllerState",n=>{cc&&console.log(`XRSync: Received change for ${this.userId}: ${n.type} ${n.handedness}; tracked=${n.isTracking}`);let o=!1;for(let r=0;r<this.controllerStates.length;r++)if(this.controllerStates[r].index===n.index){this.controllerStates[r]=n,o=!0;break}o||this.controllerStates.push(n)}),this.userId=t,this.context=i,this.userStateEvtName="xr-sync-user-state-"+t,this.context.connection.beginListen(this.userStateEvtName,this.onReceivedControllerState)}dispose(){this.context.connection.stopListen(this.userStateEvtName,this.onReceivedControllerState)}update(t){if(this.context.connection.isConnected!=!1){for(let i=this.controllerStates.length-1;i>=0;i--){const n=this.controllerStates[i];let o=!1;for(let r=0;r<t.controllers.length;r++)t.controllers[r].index===n.index&&(o=!0);o||(cc&&console.log(`XRSync: ${n.type} ${n.handedness} removed`,n.index),this.controllerStates.splice(i,1),this.sendControllerRemoved(n))}for(const i of t.controllers)this.updateControllerStates(i)}}onExitXR(t){for(const i of this.controllerStates)this.sendControllerRemoved(i);this.controllerStates.length=0}sendControllerRemoved(t){t.isTracking=!1,t.guid="",this.context.connection.send(this.userStateEvtName,t),this.context.connection.sendDeleteRemoteState(t.guid)}updateControllerStates(t){const i=this.controllerStates.find(n=>n.index===t.index);if(i){let n=!1;n||(n=i.isTracking!=t.isTracking),n&&(i.isTracking=t.isTracking,this.context.connection.send(this.userStateEvtName,i))}else{const n={guid:this.userId+"-"+t.index,isTracking:t.isTracking,handedness:t.side,index:t.index,type:t.hand?"hand":"controller"};this.controllerStates.push(n),this.context.connection.send(this.userStateEvtName,n),cc&&console.log(`XRSync: ${n.type} ${n.handedness} added`,n.index)}}}class Ib{constructor(t){a(this,"context"),a(this,"onJoinedRoom",()=>{if(this.context.connection.connectionId){this._states.has(this.context.connection.connectionId)||(cc&&console.log("XRSync: Local user joined room",this.context.connection.connectionId),this._states.set(this.context.connection.connectionId,new pg(this.context.connection.connectionId,this.context)));for(const i of this.context.connection.usersInRoom())this._states.has(i)||this._states.set(i,new pg(i,this.context))}}),a(this,"onLeftRoom",()=>{if(this.context.connection.connectionId&&!this._states.has(this.context.connection.connectionId)){const i=this._states.get(this.context.connection.connectionId);i?.dispose(),this._states.delete(this.context.connection.connectionId)}}),a(this,"onOtherUserJoinedRoom",i=>{const n=i.userId;this._states.has(n)||(cc&&console.log("XRSync: Remote user joined room",n),this._states.set(n,new pg(n,this.context)))}),a(this,"onOtherUserLeftRoom",i=>{const n=i.userId;if(!this._states.has(n)){const o=this._states.get(n);o?.dispose(),this._states.delete(n)}}),a(this,"_states",new Map),this.context=t,this.context.connection.beginListen(ie.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(ie.LeftRoom,this.onLeftRoom),this.context.connection.beginListen(ie.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.beginListen(ie.UserLeftRoom,this.onOtherUserLeftRoom)}hasState(t){return t?this._states.has(t):!1}isTracking(t,i){if(!t)return;const n=this._states.get(t);if(!n)return;const o=n.controllerStates.find(r=>r.handedness===i);return o?.isTracking||!1}getDeviceType(t,i){if(!t)return;const n=this._states.get(t);if(!n)return;const o=n.controllerStates.find(r=>r.handedness===i);return o?.type||"unknown"}destroy(){this.context.connection.stopListen(ie.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(ie.LeftRoom,this.onLeftRoom),this.context.connection.stopListen(ie.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.stopListen(ie.UserLeftRoom,this.onOtherUserLeftRoom)}onUpdate(t){if(this.context.connection.isConnected&&this.context.connection.connectionId){const i=this._states.get(this.context.connection.connectionId);i?.update(t)}}onExitXR(t){if(this.context.connection.isConnected&&this.context.connection.connectionId){const i=this._states.get(this.context.connection.connectionId);i?.onExitXR(t)}}}class jb{constructor(){a(this,"_fadeToColorQuad"),a(this,"_fadeToColorMaterial"),a(this,"_requestedFadeValue",0),a(this,"_transitionPromise",null),a(this,"_transitionResolve",null),this._fadeToColorMaterial=new Me({color:0,transparent:!0,depthTest:!1,fog:!1,side:_i}),this._fadeToColorQuad=new Q(new Ds(10,10),this._fadeToColorMaterial)}dispose(){this._fadeToColorQuad.geometry.dispose(),this._fadeToColorMaterial.dispose()}update(t,i){const n=this._fadeToColorQuad,o=this._fadeToColorMaterial;n.parent!==t&&o.opacity>0?t.add(n):o.opacity===0&&n.removeFromParent(),n.layers.set(2),n.material=this._fadeToColorMaterial,n.position.z=-1,n.renderOrder=1/0;const r=this._requestedFadeValue;o.opacity=W.lerp(o.opacity,r,i/.03),Math.abs(o.opacity-r)<=.01&&this._transitionResolve&&(this._transitionResolve(),this._transitionResolve=null,this._transitionPromise=null,this._requestedFadeValue=0)}remove(){this._fadeToColorQuad.removeFromParent()}fadeTransition(){if(this._transitionPromise)return this._transitionPromise;this._requestedFadeValue=1;const t=new Promise(i=>{this._transitionResolve=i});return this._transitionPromise=t,t}}var _r=(s=>(s[s.Quad=0]="Quad",s[s.Cube=1]="Cube",s[s.Sphere=2]="Sphere",s[s.RoundedCube=10]="RoundedCube",s))(_r||{}),Ed,mg;class mo{static createText(t,i){let n=null;const o=i?.font||GP(i?.familyFamily||null);o instanceof RC?n=ya(this,Ed,mg).call(this,t,o,i):n==null&&(n=new oo);const r=i?.color||16777215,l=new Q(n,i?.material??new ri({color:r}));return this.applyDefaultObjectOptions(l,i),o instanceof Promise?o.then(c=>{l.geometry=ya(this,Ed,mg).call(this,t,c,i),i!=null&&i.onGeometry&&i.onGeometry(l)}):i!=null&&i.onGeometry&&i.onGeometry(l),l}static createOccluder(t){const i=new Me({colorWrite:!1,depthWrite:!0,side:_i});return this.createPrimitive(t,{material:i})}static createPrimitive(t,i){let n;const o=i?.color||16777215;switch(t){case"Quad":case 0:{const r=new Ds(1,1,1,1),l=i?.material??new ri({color:o});i!=null&&i.texture&&"map"in l&&(l.map=i.texture),n=new Q(r,l),n.name="Quad"}break;case"Cube":case 1:{const r=new Wl(1,1,1),l=i?.material??new ri({color:o});i!=null&&i.texture&&"map"in l&&(l.map=i.texture),n=new Q(r,l),n.name="Cube"}break;case 10:case"RoundedCube":{const r=qP(1,1,1,.1,2),l=i?.material??new ri({color:o});i!=null&&i.texture&&"map"in l&&(l.map=i.texture),n=new Q(r,l),n.name="RoundedCube"}break;case"Sphere":case 2:{const r=new rd(.5,16,16),l=i?.material??new ri({color:o});i!=null&&i.texture&&"map"in l&&(l.map=i.texture),n=new Q(r,l),n.name="Sphere"}break;case"ShaderBall":n=new ro,n.name="ShaderBall",XP(n,i);break}return this.applyDefaultObjectOptions(n,i),n}static createSprite(t){const i=new hS({color:16777215});t!=null&&t.texture&&"map"in i&&(i.map=t.texture);const n=new dS(i);return this.applyDefaultObjectOptions(n,t),n}static applyDefaultObjectOptions(t,i){t.receiveShadow=!0,t.castShadow=!0,i!=null&&i.name&&(t.name=i.name),i!=null&&i.position&&(Array.isArray(i.position)?t.position.set(i.position[0],i.position[1],i.position[2]):t.position.set(i.position.x,i.position.y,i.position.z)),i!=null&&i.rotation&&(Array.isArray(i.rotation)?t.rotation.set(i.rotation[0],i.rotation[1],i.rotation[2]):t.rotation.set(i.rotation.x,i.rotation.y,i.rotation.z)),i!=null&&i.scale&&(typeof i.scale=="number"?t.scale.set(i.scale,i.scale,i.scale):t.scale.set(i.scale.x,i.scale.y,i.scale.z)),i?.receiveShadow!=null&&(t.receiveShadow=i.receiveShadow),i?.castShadow!=null&&(t.castShadow=i.castShadow),i!=null&&i.parent&&i.parent.add(t)}}Ed=new WeakSet,mg=function(s,t,i){const n=i?.depth||.1;return new TC(s,{font:t,size:1,depth:n,height:n,bevelEnabled:i?.bevel||!1,bevelThickness:.01,bevelOffset:.01,bevelSize:.01})},Hi(mo,Ed);function qP(s,t,i,n,o){const r=new uS,l=1e-5,c=n-l;r.absarc(l,l,l,-Math.PI/2,-Math.PI,!0),r.absarc(l,t-c*2,l,Math.PI,Math.PI/2,!0),r.absarc(s-c*2,t-c*2,l,Math.PI/2,0,!0),r.absarc(s-c*2,l,l,0,-Math.PI/2,!0);const h=new pS(r,{bevelEnabled:!0,bevelSegments:o*2,steps:1,bevelSize:c,bevelThickness:n,curveSegments:o});return h.scale(1,1,1-n),h.center(),h.computeVertexNormals(),h}const Ad=new Map;function GP(s){let t="";switch(s){default:case"OpenSans":t="https://cdn.needle.tools/static/fonts/facetype/Open Sans_Regular_ascii.json";break;case"Helvetiker":t="https://raw.githubusercontent.com/mrdoob/three.js/master/examples/fonts/helvetiker_regular.typeface.json";break}if(Ad.has(t)){const o=Ad.get(t);if(o)return o}const i=new EC,n=new Promise((o,r)=>{i.load(t,l=>{Ad.set(t,l),o(l)},void 0,r)});return Ad.set(t,n),n}let gg=!1,fg=null;function XP(s,t){if(fg===null){const i="https://cdn.needle.tools/static/models/shaderball.glb",n=new mr,o=_m(null);n.setDRACOLoader(o.dracoLoader),n.setKTX2Loader(o.ktx2Loader),gg=!0,fg=n.loadAsync(i).then(r=>{const l=r.scene;return l.position.y-=.5,l}).catch(r=>(console.warn("Failed to load shaderball mesh: "+r.message),Db())).finally(()=>{gg=!1})}if(gg){const i=Db();i.name="ShaderBall-Placeholder";const n=i.children[0];n?.type==="Mesh"&&Lb(n,t),s.add(i)}fg.then(i=>{s.children.forEach(r=>{r.name==="ShaderBall-Placeholder"&&s.remove(r)});const n=i.clone(),o=n.children[0];o?.type==="Mesh"&&Lb(o,t),s.add(n)})}function Lb(s,t){var i;if(t?.color||t?.material||t?.texture){const n=t?.material??((i=s.material)==null?void 0:i.clone())??new ri;t.color&&"color"in n&&n.color instanceof ae&&n.color.set(t.color),t!=null&&t.texture&&"map"in n&&(n.map=t.texture),s.material=n}}function Db(){return new ro().add(mo.createPrimitive("Sphere",{material:new Me({transparent:!0,opacity:.1})}))}const Bb=class{constructor(s,t,i){a(this,"_session"),a(this,"_mode"),a(this,"_init"),a(this,"_renderer"),a(this,"_camera"),a(this,"_scene"),a(this,"onEnd",()=>{var n;(n=this._session)==null||n.removeEventListener("end",this.onEnd),this._renderer.setAnimationLoop(null),this._renderer.dispose(),this._scene.clear()}),a(this,"_lastTime",0),a(this,"onFrame",(n,o)=>{const r=n-this._lastTime;this.update(n,r),this._camera.parent!==this._scene&&this._scene.add(this._camera),this._renderer.render(this._scene,this._camera)}),a(this,"_objects",[]),this._mode=s,this._init=t,this._session=i,this._session.addEventListener("end",this.onEnd),this._renderer=new cr({alpha:!0}),this._renderer.setAnimationLoop(this.onFrame),this._renderer.xr.setSession(i),this._renderer.xr.enabled=!0,this._camera=new be,this._scene=new $i,this._scene.fog=new Gy(4473924,10,250),this._scene.add(this._camera),this.setupScene()}static get active(){return this._active}static async start(s,t){if(this._active)return console.error("Cannot start a new XR session while one is already active"),null;if(this._requestInFlight)return console.error("Cannot start a new XR session while a request is already in flight"),null;if("xr"in navigator&&navigator.xr){if(!t)return console.error("XRSessionInit must be provided"),null;this._requestInFlight=!0;const i=await navigator.xr.requestSession(s,t);return i.addEventListener("end",()=>{this._active=null}),this._requestInFlight?(this._requestInFlight=!1,this._active=new Bb(s,t,i),this._active):(i.end(),null)}return null}static async handoff(){return this._active?this._active.handoff():null}static async stop(){this._requestInFlight=!1,this._active&&(await this._active.end(),await gs(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 s={session:this._session,mode:this._mode,init:this._init};return await this.onBeforeHandoff(),this.onEnd(),this._session=null,s}async onBeforeHandoff(){await gs(1e3),this._scene.clear()}setupScene(){this._scene.background=new ae(0),this._scene.add(new lm(5,10,1118481,1118481));const s=new cm(16777215,1);s.position.set(0,20,0),s.castShadow=!1,this._scene.add(s);const t=new cm(16777215,1);t.position.set(0,-1,0),t.castShadow=!1,this._scene.add(t);const i=new Xy(16777215,1,100,1);i.position.set(0,2,0),i.castShadow=!1,i.distance=200,this._scene.add(i);const n=50;for(let o=0;o<100;o++){const r=new ri({color:2236962,metalness:1,roughness:.8});this.isAR&&(r.emissive=new ae(Math.random(),Math.random(),Math.random()),r.emissiveIntensity=Math.random());const l=W.random(0,1)>.5?_r.Sphere:_r.Cube,c=mo.createPrimitive(l,{material:r});c.position.x=W.random(-n,n),c.position.y=W.random(-2,n),c.position.z=W.random(-n,n),c.rotation.x=W.random(0,Math.PI*2),c.rotation.y=W.random(0,Math.PI*2),c.rotation.z=W.random(0,Math.PI*2),c.scale.multiplyScalar(.5+Math.random()*10);const h=c.position.distanceTo(this._camera.position)-c.scale.x;h<1&&c.position.multiplyScalar(1+1/h),this._objects.push(c),this._scene.add(c)}}update(s,t){const i=s*4e-4;for(let n=0;n<this._objects.length;n++){const o=this._objects[n];o.position.y+=Math.sin(i+n*.5)*.005,o.rotateY(.002)}}};let Ea=Bb;a(Ea,"_active",null),a(Ea,"_requestInFlight",!1);var hc;(s=>{const t=[];function i(){if(!(t!=null&&t.length))return!1;for(const r of t)r.exportAndOpen();return!0}s.exportAndOpen=i;function n(r){t.push(r)}s.registerExporter=n;function o(r){if(!t)return;const l=t.indexOf(r);l>=0&&t.splice(l,1)}s.unregisterExporter=o})(hc||(hc={}));const Fb="NeedleXRSession onStart",zb="NeedleXRSession onEnd",gt=O("debugwebxr"),Ub=O("stats");let yg=0;function QP(s){let t=null;const i=s;return i.getAROverlayContainer?t=i.getAROverlayContainer():t=s,t}YP();async function YP(){var s;if(O("debugasap")){let t=globalThis["needle:XRSession"];if(t instanceof Promise){delete globalThis["needle:XRSession"],ge.addContextCreatedCallback(async i=>{if(!t)return;vr(!0);const n=await t;if(n){const o=Z.getDefaultSessionInit("immersive-vr");Z.setSession("immersive-vr",n,o,i.context)}else console.error("NeedleXRSession: ASAP session was rejected");t=void 0});return}}if("xr"in navigator){if(/WebXRViewer\//i.test(navigator.userAgent)){console.warn("WebXRViewer does not support addEventListener");return}(s=navigator.xr)==null||s.addEventListener("sessiongranted",async()=>{vr(!0),console.log("Received Session Granted..."),await gs(100);const t=sessionStorage.getItem("needle_xr_session_mode"),i=sessionStorage.getItem("needle_xr_session_init")??null,n=i?JSON.parse(i):null;let o=null;if(Nb()&&(await Ea.start(t||"immersive-vr",n||Z.getDefaultSessionInit("immersive-vr")),await JP(),o=await Ea.handoff()),o)Z.setSession(o.mode,o.session,o.init,te.Current);else if(t&&i){console.log("Session Granted: Restore last session");const r=JSON.parse(i);Z.start(t,r).catch(l=>console.warn(l))}else Z.start("immersive-vr").catch(r=>console.warn("Session Granted failed:",r))},{once:!0})}}function KP(s,t){sessionStorage.setItem("needle_xr_session_mode",s),sessionStorage.setItem("needle_xr_session_init",JSON.stringify(t))}function ZP(){sessionStorage.removeItem("needle_xr_session_mode"),sessionStorage.removeItem("needle_xr_session_init")}const vg=new Set;ge.registerCallback(fe.ContextCreationStart,async s=>{vg.add(s.context)}),ge.registerCallback(fe.ContextCreated,async s=>{vg.delete(s.context)});function Nb(){return vg.size>0}function JP(){return new Promise(s=>{const t=Date.now(),i=setInterval(()=>{(!Nb()||Date.now()-t>6e4)&&(clearInterval(i),s())},100)})}Y.isDesktop()&&F()&&window.addEventListener("keydown",s=>{(s.key==="x"||s.key==="Escape")&&Z.active&&Z.stop()});const go=class{constructor(s,t,i,n){a(this,"context"),a(this,"session"),a(this,"mode"),a(this,"controllers",[]),a(this,"_rigScale",1),a(this,"_lastRigScaleUpdate",-1),a(this,"_rigs",[]),a(this,"_viewerHitTestSource",null),a(this,"_defaultRig"),a(this,"_xr_scripts"),a(this,"_xr_update_scripts",[]),a(this,"_inactive_scripts",[]),a(this,"_controllerAdded"),a(this,"_controllerRemoved"),a(this,"_originalCameraWorldPosition"),a(this,"_originalCameraWorldRotation"),a(this,"_originalCameraWorldScale"),a(this,"_originalCameraParent"),a(this,"_mainCamera",null),a(this,"onRendererSessionSet",()=>{var l;this.running&&(this.context.renderer.xr.enabled=!0,this.context.renderer.xr.updateCamera(this.context.mainCamera),(l=this.context.mainCameraComponent)==null||l.applyClearFlags())}),a(this,"onInputSourceAdded",l=>{if(l.targetRayMode==="screen")return;let c=0;for(let d=0;d<this.session.inputSources.length;d++)if(this.session.inputSources[d]===l){c=d;break}if(this.controllers.find(d=>d.inputSource===l)){console.debug("Controller already exists for input source",c);return}else if(this._newControllers.find(d=>d.inputSource===l)){console.debug("Controller already registered for input source",c);return}const h=new rg(this,l,c);this._newControllers.push(h)}),a(this,"_ended",!1),a(this,"_newControllers",[]),a(this,"onEnd",l=>{var c,h,d;if(this._ended)return;this._ended=!0,console.debug("XR Session ended"),ZP(),this.onAfterRender(),this.revertCustomForward(),this._didStart=!1,this._previousCameraParent=null,po(this.onBefore,Ce.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 y,f;(y=this.context.mainCameraComponent)==null||y.applyClearFlags(),(f=this.context.mainCameraComponent)==null||f.applyClippingPlane()}),fb({session:this});for(const y of go._xrEndListeners)y({xr:this});const g=[...this.controllers];for(let y=0;y<g.length;y++)this.disconnectInputSource(g[y].inputSource);this._newControllers.length=0,this.controllers.length=0;for(const y of this._xr_scripts)(c=y?.onLeaveXR)==null||c.call(y,{xr:this});(h=this.sync)==null||h.onExitXR(this),this.context.mainCamera&&((d=this._originalCameraParent)==null||d.add(this.context.mainCamera),this._originalCameraWorldPosition&&lt(this.context.mainCamera,this._originalCameraWorldPosition),this._originalCameraWorldRotation&&qi(this.context.mainCamera,this._originalCameraWorldRotation),this._originalCameraWorldScale&&Oa(this.context.mainCamera,this._originalCameraWorldScale)),this.context.requestSizeUpdate(),this._defaultRig.gameObject.removeFromParent(),vr(!1),performance.mark(zb),performance.measure("NeedleXRSession",Fb,zb)}),a(this,"_didStart",!1),a(this,"onBefore",l=>{var c,h,d,u,p,g,y,f;const v=l.xrFrame;if(!v)return;performance.mark("NeedleXRSession onBefore start"),this.context.xr=this,this.context.mainCameraComponent&&this.context.mainCameraComponent!==this._mainCamera&&(this._mainCamera=this.context.mainCameraComponent),((c=this.rig)==null?void 0:c.isActive)==!1&&(gt&&console.warn("Latest rig is not active - trying to activate a different rig",this.rig),this.updateActiveXRRig()),this.rig&&(h=this._mainCamera)!=null&&h.gameObject&&((u=(d=this._mainCamera)==null?void 0:d.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 b={xr:this};if(this._didStart){if(this.context.new_scripts_xr.length>0){const w=[...this.context.new_scripts_xr];for(let _=0;_<w.length;_++){const C=this.context.new_scripts_xr[_];if(!C||C.destroyed||((g=C.supportsXR)==null?void 0:g.call(C,this.mode))==!1){this.context.new_scripts_xr.splice(_,1);continue}if(!C.activeAndEnabled){this.context.new_scripts_xr.splice(_,1),this.markInactive(C);continue}if(this.addScript(C)){this.invokeCallback_EnterXR(C);for(const R of this.controllers)this.invokeCallback_ControllerAdded(C,R)}}}}else{if(this._didStart=!0,this.mode==="immersive-vr"){const _=Si(this.context.scene.children);if(_){const C=_.getSize($());if(C.length()>0){const R=this._defaultRig.gameObject;R.position.set(_.min.x+C.x*.5,_.min.y,_.max.z+C.z*.5+1.5);const M=_.getCenter($());M.y=R.position.y,R.lookAt(M)}}}gb({session:this});for(const _ of go._xrStartListeners)_(b);const w=[...this._xr_scripts];gt&&console.log("NeedleXRSession start, handle scripts:",w);for(const _ of w){if(_.destroyed){this._script_to_remove.push(_);continue}if(!_.activeAndEnabled){this.markInactive(_);continue}this.invokeCallback_EnterXR(_);for(const C of this.controllers)this.invokeCallback_ControllerAdded(_,C)}}this.syncCameraCullingMask();for(const w of this.controllers)w.onUpdate(v);if(this._newControllers.length>0){const w=[...this._newControllers];this._newControllers.length=0;for(const _ of w){if(!_.connected){console.warn("New controller is not connected",_);continue}this.controllers.push(_);for(const C of this._xr_scripts){if(C.destroyed){this._script_to_remove.push(C);continue}C.activeAndEnabled!==!1&&this.invokeCallback_ControllerAdded(C,_)}}this.controllers.sort((_,C)=>_.index-C.index)}gt&&this.context.time.frame%30===0&&this.controllers.length<=0&&this.session.inputSources.length>0&&(vr(!0),console.error("XRControllers are not added but inputSources are present")),performance.mark("NeedleXRSession update scripts start");for(const w of this._xr_update_scripts){if(w.destroyed===!0){this._script_to_remove.push(w);continue}if(w.activeAndEnabled===!1){this.markInactive(w);continue}w.onUpdateXR&&w.onUpdateXR(b)}if(performance.mark("NeedleXRSession update scripts end"),performance.measure("NeedleXRSession update scripts","NeedleXRSession update scripts start","NeedleXRSession update scripts end"),this.handleInactiveScripts(),this._script_to_remove.length>0){const w=[...new Set(this._script_to_remove)];this._script_to_remove.length=0;for(const _ of w)!_.destroyed&&this.running&&((y=_.onLeaveXR)==null||y.call(_,b)),this.removeScript(_)}(f=this.sync)==null||f.onUpdate(this),this.onRenderDebug(),performance.mark("NeedleXRSession onBefore end"),performance.measure("NE XR frame","NeedleXRSession onBefore start","NeedleXRSession onBefore end")}),a(this,"onBeforeRender",()=>{this.context.mainCamera&&this.updateFade(this.context.mainCamera)}),a(this,"onAfterRender",()=>{if(this.onUpdateFade_PostRender(),Y.isDesktop()||!this._renderOnceOnDevice){const l=this.context.renderer;if(l.xr.isPresenting&&this.context.mainCamera){this._renderOnceOnDevice=!0;const c=l.xr.enabled,h=l.getRenderTarget(),d=this.context.scene.background;l.xr.enabled=!1,l.setRenderTarget(null),this.isPassThrough&&(this.context.scene.background=null),this.context.composer?this.context.composer.render(this.context.time.deltaTime):l.render(this.context.scene,this.context.mainCamera),l.xr.enabled=c,l.setRenderTarget(h),this.context.scene.background=d}}}),a(this,"_script_to_remove",[]),a(this,"_camera"),a(this,"_cameraRenderParent",new j().rotateY(Math.PI)),a(this,"_previousCameraParent"),a(this,"_customforward",!0),a(this,"originalCameraNearPlane"),a(this,"_viewerPose"),a(this,"_transformOrientation",new V),a(this,"_transformPosition",new x),a(this,"_transition");var o,r;performance.mark(Fb),KP(s,n.init),this.session=t,this.mode=s,this.context=i,(gt||O("console"))&&vr(!0),this._xr_scripts=[...n.scripts],this._xr_update_scripts=this._xr_scripts.filter(l=>typeof l.onUpdateXR=="function"),this._controllerAdded=n.controller_added,this._controllerRemoved=n.controller_removed,Cn(this.onBefore,Ce.LateUpdate),this.context.pre_render_callbacks.push(this.onBeforeRender),this.context.post_render_callbacks.push(this.onAfterRender),((o=n.init.optionalFeatures)!=null&&o.includes("hit-test")||(r=n.init.requiredFeatures)!=null&&r.includes("hit-test"))&&t.requestReferenceSpace("viewer").then(l=>{var c,h;return(h=(c=t.requestHitTestSource)==null?void 0:c.call(t,{space:l}))==null?void 0:h.then(d=>this._viewerHitTestSource=d).catch(d=>console.error(d))}).catch(l=>console.error(l)),this.context.mainCamera&&(this._originalCameraWorldPosition=ee(this.context.mainCamera,new x),this._originalCameraWorldRotation=Se(this.context.mainCamera,new V),this._originalCameraWorldScale=Ke(this.context.mainCamera,new x),this._originalCameraParent=this.context.mainCamera.parent),this._defaultRig=new jP,this.context.scene.add(this._defaultRig.gameObject),this.addRig(this._defaultRig);for(let l=0;l<t.inputSources.length;l++){const c=t.inputSources[l];if(!c.handedness){console.warn("Input source in xr session has no handedness - ignoring",l);continue}this.onInputSourceAdded(c)}this.session.addEventListener("end",this.onEnd),this.session.addEventListener("inputsourceschange",l=>{for(const c of l.removed)this.disconnectInputSource(c);for(const c of l.added)this.onInputSourceAdded(c)}),this.context.xr=this,this.context.renderer.xr.setSession(this.session).then(this.onRendererSessionSet),"controllerAutoUpdate"in this.context.renderer.xr?(console.debug("Disabling three.js controllerAutoUpdate"),this.context.renderer.xr.controllerAutoUpdate=!1):gt&&console.warn("controllerAutoUpdate is not available in three.js - cannot disable it")}static getXRSync(s){return this._sync||(this._sync=new Ib(s)),this._sync}static get currentSessionRequest(){return this._currentSessionRequestMode}static get active(){return this._activeSession}static get activeMode(){var s;return((s=this._activeSession)==null?void 0:s.mode)??null}static get xrSystem(){return"xr"in navigator?navigator.xr:void 0}static isXRSupported(){return Promise.all([this.isVRSupported(),this.isARSupported()]).then(s=>s.some(t=>t)).catch(()=>!1)}static isVRSupported(){return this.isSessionSupported("immersive-vr")}static isARSupported(){return this.isSessionSupported("immersive-ar")}static isSessionSupported(s){var t;return((t=this.xrSystem)==null?void 0:t.isSessionSupported(s).catch(i=>(gt&&console.error(i),!1)))??Promise.resolve(!1)}static onSessionRequestStart(s){this._sessionRequestStartListeners.push(s)}static offSessionRequestStart(s){const t=this._sessionRequestStartListeners.indexOf(s);t>=0&&this._sessionRequestStartListeners.splice(t,1)}static onSessionRequestEnd(s){this._sessionRequestEndListeners.push(s)}static offSessionRequestEnd(s){const t=this._sessionRequestEndListeners.indexOf(s);t>=0&&this._sessionRequestEndListeners.splice(t,1)}static onXRSessionStart(s){this._xrStartListeners.push(s)}static offXRSessionStart(s){const t=this._xrStartListeners.indexOf(s);t>=0&&this._xrStartListeners.splice(t,1)}static onXRSessionEnd(s){this._xrEndListeners.push(s)}static offXRSessionEnd(s){const t=this._xrEndListeners.indexOf(s);t>=0&&this._xrEndListeners.splice(t,1)}static onControllerAdded(s){this._controllerAddedListeners.push(s)}static offControllerAdded(s){const t=this._controllerAddedListeners.indexOf(s);t>=0&&this._controllerAddedListeners.splice(t,1)}static onControllerRemoved(s){this._controllerRemovedListeners.push(s)}static offControllerRemoved(s){const t=this._controllerRemovedListeners.indexOf(s);t>=0&&this._controllerRemovedListeners.splice(t,1)}static offerSession(s,t,i){return"xr"in navigator&&navigator.xr&&"offerSession"in navigator.xr?(typeof navigator.xr.offerSession=="function"&&(console.log("WebXR offerSession is available - requesting mode: "+s),t=="default"&&(t=this.getDefaultSessionInit(s)),navigator.xr.offerSession(s,{...t}).then(n=>go.setSession(s,n,t,i)).catch(n=>{console.log("XRSession offer rejected (perhaps because another call to offerSession was made or a call to requestSession was made)")})),!0):!1}static getDefaultSessionInit(s){switch(s){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",s),{}}}static async start(s,t,i){var n,o,r,l;if(Y.isiOS()){if(s==="ar")if(await this.isARSupported())s="immersive-ar";else return hc.exportAndOpen(),null}else s=="ar"&&(s="immersive-ar");if(F()&&O("debugxrpreroom"))return console.warn("Debug: Starting temporary XR session"),await Ea.start(s,t||go.getDefaultSessionInit(s)),null;if(this._currentSessionRequest)return console.warn("A XRSession is already being requested"),(gt||F())&&_e("A XRSession is already being requested"),this._currentSessionRequest.then(()=>this._activeSession);if(this._activeSession)return console.error("A XRSession is already running"),this._activeSession;if(i||(i=te.Current),i||(i=ge.All[0]),!i)throw new Error("No Needle Engine Context found");switch(performance.mark("NeedleXRSession start"),t||(t={}),s){case"immersive-ar":{if(await((n=this.xrSystem)==null?void 0:n.isSessionSupported("immersive-ar"))!==!0)return console.error(s+" is not supported by this browser."),null;const u=this.getDefaultSessionInit(s),p=QP(i.domElement);p&&!Y.isQuest()&&(u.domOverlay={root:p},u.optionalFeatures.push("dom-overlay")),t={...u,...t}}break;case"immersive-vr":{if(await((o=this.xrSystem)==null?void 0:o.isSessionSupported("immersive-vr"))!==!0)return console.error(s+" is not supported by this browser."),null;t={...this.getDefaultSessionInit(s),...t}}break;default:console.warn("No default session init for mode",s);break}t.optionalFeatures??(t.optionalFeatures=[]),t.requiredFeatures??(t.requiredFeatures=[]),await Ea.stop();const c=s=="immersive-ar"?i.scripts_immersive_ar:i.scripts_immersive_vr;gt?console.log(`%cRequesting ${s} session`,"font-weight:bold;",t,c):console.log(`%cRequesting ${s} session`,"font-weight:bold;");for(const u of c)u.onBeforeXR&&u.onBeforeXR(s,t);for(const u of this._sessionRequestStartListeners)u({mode:s,init:t});gt&&Le("Requesting "+s+" session ("+Date.now()+")"),this._currentSessionRequest=(r=navigator.xr)==null?void 0:r.requestSession(s,t),this._currentSessionRequestMode=s;const h=await((l=this._currentSessionRequest)==null?void 0:l.catch(u=>{console.error(u,"Code: "+u.code),u.code===9&&_e("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:"&&_e("XR requires a secure connection (HTTPS)")}));this._currentSessionRequest=void 0,this._currentSessionRequestMode=null;for(const u of this._sessionRequestEndListeners)u({mode:s,init:t,newSession:h||null});if(!h)return console.warn("XR Session request was rejected"),null;const d=this.setSession(s,h,t,i);return performance.mark("NeedleXRSession end"),performance.measure("NeedleXRSession Startup","NeedleXRSession start","NeedleXRSession end"),d}static setSession(s,t,i,n){if(this._activeSession)return console.error("A XRSession is already running"),this._activeSession;const o=s=="immersive-ar"?n.scripts_immersive_ar:n.scripts_immersive_vr;return this._activeSession=new go(s,t,n,{scripts:o,controller_added:this._controllerAddedListeners,controller_removed:this._controllerRemovedListeners,init:i}),t.addEventListener("end",this.onEnd),gt?console.log(`%cStarted ${s} session`,"font-weight:bold;",o):console.log(`%cStarted ${s} session`,"font-weight:bold;"),this._activeSession}static stop(){var s;(s=this._activeSession)==null||s.end()}get sync(){return go._sync}get running(){return!this._ended&&this.session!=null}get interactionMode(){return this.session.interactionMode}get visibilityState(){return this.session.visibilityState}get isVisibleBlurred(){return this.session.visibilityState==="visible-blurred"}get isSystemKeyboardSupported(){return this.session.isSystemKeyboardSupported}get environmentBlendMode(){return this.session.environmentBlendMode}get frame(){return this.context.xrFrame}get leftController(){return this.controllers.find(s=>s.side==="left")}get rightController(){return this.controllers.find(s=>s.side==="right")}getController(s){return typeof s=="number"?this.controllers[s]||null:this.controllers.find(t=>t.side===s)||null}get isPassThrough(){return!!(this.environmentBlendMode!=="opaque"&&this.interactionMode==="world-space"||this.mode==="immersive-ar"&&this.environmentBlendMode!=="opaque"&&this.controllers.some(s=>s.inputSource.targetRayMode==="tracked-pointer")||F()&&Y.isDesktop()&&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 s=this.frame.getImageTrackingResults();for(const t of s)if(t.trackingState==="tracked")return!0}catch{return!1}return!1}get rig(){const s=this._rigs[0]??null;return s!=null&&s.gameObject&&Pr(s.gameObject)||s?.isActive===!1?(this.updateActiveXRRig(),this._rigs[0]??null):s}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(s){this._rigs.indexOf(s)>=0||(s.priority===void 0&&(s.priority=0),this._rigs.push(s),this.updateActiveXRRig())}removeRig(s){const t=this._rigs.indexOf(s);t!==-1&&(this._rigs.splice(t,1),this.updateActiveXRRig())}setRigActive(s){const t=this._rigs.indexOf(s),i=this._rigs[0];this._rigs.splice(t,1),this._rigs.unshift(s),s.priority=i?.priority??0,this.updateActiveXRRig()}getUserOffsetInRig(){var s;const t=(s=this.context.mainCamera)==null?void 0:s.position;if(!t||!this.rig)return $(0,0,0);const i=$(t);return i.x*=-1,i.z*=-1,i.applyQuaternion(fs(this.rig.gameObject.quaternion)),i}updateActiveXRRig(){const s=this._rigs[0]??null;this._defaultRig.gameObject.parent!==this.context.scene&&this.context.scene.add(this._defaultRig.gameObject),this._defaultRig.gameObject.visible=!0,this._rigs.includes(this._defaultRig)||this._rigs.push(this._defaultRig);let t=this._rigs[0];t&&t.priority===void 0&&(t.priority=0);for(let i=1;i<this._rigs.length;i++){const n=this._rigs[i];if(n.isActive){if(Pr(n.gameObject)){this._rigs.splice(i,1),i--;continue}(!t||t.isActive===!1||n.priority!==void 0&&n.priority>t.priority)&&(t=n)}}if(s!==t){const i=this._rigs.indexOf(t);i>=0&&this._rigs.splice(i,1),this._rigs.unshift(t)}gt&&(s===t?console.log("Updated Active XR Rig:",t,"prev:",s):console.log("Updated Active XRRig:",t," (the same as before)"))}getHitTest(s){if(s)return this.getControllerHitTest(s);if(!this._viewerHitTestSource)return null;const t=this._viewerHitTestSource,i=this.frame.getHitTestResults(t);if(i.length>0){const n=i[0];return this.convertHitTestResult(n)}return null}getControllerHitTest(s){const t=s.getHitTestSource();if(!t)return null;const i=this.frame.getHitTestResultsForTransientInput(t);for(const n of i)if(n.inputSource===s.inputSource)for(const o of n.results)return this.convertHitTestResult(o);return null}convertHitTestResult(s){const t=this.context.renderer.xr.getReferenceSpace(),i=t&&s.getPose(t);if(i){const n=$(i.transform.position),o=fs(i.transform.orientation),r=this.context.mainCamera;if(r?.parent!==this._cameraRenderParent&&n.applyMatrix4(Ma),r!=null&&r.parent){n.applyMatrix4(r.parent.matrixWorld),o.multiply(Qi);const l=Se(r.parent);l.premultiply(Qi),o.premultiply(l)}return{hit:s,position:n,quaternion:o}}return null}convertSpace(s){const t=$(s.position);t.applyMatrix4(Ma);const i=fs(s.orientation);return i.premultiply(Qi),{position:t,quaternion:i}}disconnectInputSource(s){const t=(i,n,o)=>{if(i.inputSource===s){gt&&console.log("Disconnecting controller",i.index),this.controllers.splice(o,1),this.invokeControllerEvent(i,this._controllerRemoved,"removed");const r={xr:this,controller:i,change:"removed"};for(const l of this._xr_scripts)l.onXRControllerRemoved&&l.onXRControllerRemoved(r);i.onDisconnected()}};for(let i=this.controllers.length-1;i>=0;i--){const n=this.controllers[i];t(n,this.controllers,i)}for(let i=this._newControllers.length-1;i>=0;i--){const n=this._newControllers[i];t(n,this._newControllers,i)}}end(){this._ended||this.session.end().catch(s=>console.warn(s))}onRenderDebug(){if(gt)for(const s of this.controllers)s.onRenderDebug();if((gt||Ub)&&this.rig&&(yg++,yg>=20)){const s=this.rig.gameObject.worldPosition,t=this.rig.gameObject.worldForward;s.add(t.multiplyScalar(1.5));const i=this.rig.gameObject.worldUp;s.add(i.multiplyScalar(2.5));let n="";if(n+=`${this.context.time.smoothedFps.toFixed(0)} FPS`,n+=`, calls: ${this.context.renderer.info.render.calls}, tris: ${this.context.renderer.info.render.triangles.toLocaleString()}`,gt||Ub)for(const o of this.controllers)n+=`
154
- ${o.hand?"hand":"ctrl"} ${o.inputSource.handedness}[${o.index}] con:${o.connected} tr:${o.isTracking} hts:${o.hasHitTestSource?"yes":"no"}`;yg=0,q.DrawLabel(s,n,void 0,1/60*20)}}addScript(s){return this._xr_scripts.includes(s)?!1:(gt&&console.log("Register new XRScript",s),this._xr_scripts.push(s),typeof s.onUpdateXR=="function"&&this._xr_update_scripts.push(s),!0)}markInactive(s){if(!(this._inactive_scripts.indexOf(s)>=0)){this.removeScript(s,!1),this._inactive_scripts.push(s);for(const t of this.controllers)this.invokeCallback_ControllerRemoved(s,t);this.invokeCallback_LeaveXR(s)}}handleInactiveScripts(){if(this._inactive_scripts.length>0)for(let s=this._inactive_scripts.length-1;s>=0;s--){const t=this._inactive_scripts[s];if(t.activeAndEnabled){this._inactive_scripts.splice(s,1),this.addScript(t),this.invokeCallback_EnterXR(t);for(const i of this.controllers)this.invokeCallback_ControllerAdded(t,i)}}}removeScript(s,t=!0){gt&&console.log("Remove XRScript",s);const i=this._xr_scripts.indexOf(s);i>=0&&this._xr_scripts.splice(i,1);const n=this._xr_update_scripts.indexOf(s);if(n>=0&&this._xr_update_scripts.splice(n,1),t){const o=this._inactive_scripts.indexOf(s);o>=0&&this._inactive_scripts.splice(o,1)}}invokeCallback_EnterXR(s){s.onEnterXR&&s.onEnterXR({xr:this})}invokeCallback_ControllerAdded(s,t){s.onXRControllerAdded&&s.onXRControllerAdded({xr:this,controller:t,change:"added"})}invokeCallback_ControllerRemoved(s,t){s.onXRControllerRemoved&&s.onXRControllerRemoved({xr:this,controller:t,change:"removed"})}invokeCallback_LeaveXR(s){s.onLeaveXR&&!s.destroyed&&s.onLeaveXR({xr:this})}syncCameraCullingMask(){var s;const t=this.context.xrCamera,i=(s=this.context.mainCameraComponent)==null?void 0:s.cullingMask;if(t&&i!==void 0){for(const n of t.cameras)n.layers.mask=i;t.layers.mask=i}else if(t){for(const n of t.cameras)n.layers.enableAll();t.layers.enableAll()}}invokeControllerEvent(s,t,i){for(let n=t.length-1;n>=0;n--){const o=t[n];if(o)try{o({xr:this,controller:s,change:i})}catch(r){console.error(r)}}}applyCustomForward(){var s;if(this.context.mainCamera&&this._customforward){this._camera=this.context.mainCamera,this._camera.parent!==this._cameraRenderParent&&(this._previousCameraParent=this._camera.parent,(s=this._previousCameraParent)==null||s.add(this._cameraRenderParent)),this._cameraRenderParent.name="XR Camera Render Parent",this._cameraRenderParent.add(this._camera);let t=.02;if(this.rig){const i=Ke(this.rig.gameObject);t*=i.x}this._camera instanceof be&&this._camera.near>t&&(this.originalCameraNearPlane=this._camera.near,this._camera.near=t)}}revertCustomForward(){this._camera&&this._previousCameraParent&&this._previousCameraParent.add(this._camera),this._previousCameraParent=null,this._camera instanceof be&&this.originalCameraNearPlane!=null&&(this._camera.near=this.originalCameraNearPlane)}internalUpdateState(){const s=this.context.renderer.xr.getReferenceSpace();if(!s){this._viewerPose=void 0;return}if(this._viewerPose=this.frame.getViewerPose(s),this._viewerPose){const t=this._viewerPose.transform;this._transformPosition.set(t.position.x,t.position.y,t.position.z),this._transformOrientation.set(t.orientation.x,t.orientation.y,t.orientation.z,t.orientation.w)}}get transition(){return this._transition||(this._transition=new jb),this._transition}fadeTransition(){return this._transition||(this._transition=new jb),this._transition.fadeTransition()}updateFade(s){this._transition&&s instanceof be&&this._transition.update(s,this.context.time.deltaTime)}onUpdateFade_PostRender(){var s;(s=this._transition)==null||s.remove()}};let Z=go;a(Z,"_sync",null),a(Z,"_currentSessionRequestMode",null),a(Z,"_currentSessionRequest"),a(Z,"_activeSession"),a(Z,"_sessionRequestStartListeners",[]),a(Z,"_sessionRequestEndListeners",[]),a(Z,"_xrStartListeners",[]),a(Z,"_xrEndListeners",[]),a(Z,"_controllerAddedListeners",[]),a(Z,"_controllerRemovedListeners",[]),a(Z,"onEnd",()=>{gt&&console.log("XR Session ended"),go._activeSession=null});const bg=O("debugwebxr");class Wb{static tryFindAvatarObjects(t,i,n){if(n.head&&n.leftHand&&n.rightHand)return;const o=t.name.toLocaleLowerCase();!n.head&&o.includes("head")&&(bg&&console.log("FOUND AVATAR HEAD",t.name),n.head=new le("",i,t)),o.includes("hand")&&(!n.leftHand&&o.includes("left")&&(bg&&console.log("FOUND AVATAR LEFT HAND",t.name),n.leftHand=new le("",i,t)),!n.rightHand&&o.includes("right")&&(bg&&console.log("FOUND AVATAR RIGHT HAND",t.name),n.rightHand=new le("",i,t)));for(let r=0;r<t.children.length;r++){if(n.head&&n.leftHand&&n.rightHand)return;const l=t.children[r];this.tryFindAvatarObjects(l,i,n)}}}const zt=new x,Vb=new x,Hb=new V,ek=O("debuggizmos"),_s=8947848,_g=32,ws=class{constructor(){}static isGizmo(s){return s[xg]!==void 0}static DrawLabel(s,t,i=.05,n=0,o,r,l){var c;if(!ws.enabled)return null;o||(o=_s);const h=((c=Z.active)==null?void 0:c.rigScale)??1,d=Ee.getTextLabel(n,t,i*h,o,r);return l instanceof j&&l.add(d),d.position.x=s.x,d.position.y=s.y,d.position.z=s.z,d}static DrawRay(s,t,i=_s,n=0,o=!0){if(!ws.enabled)return;const r=Ee.getLine(n),l=r.geometry.getAttribute("position");l.setXYZ(0,s.x,s.y,s.z),zt.set(t.x,t.y,t.z).multiplyScalar(999999999),l.setXYZ(1,s.x+zt.x,s.y+zt.y,s.z+zt.z),l.needsUpdate=!0,r.material.color.set(i),r.material.depthTest=o,r.material.depthWrite=!1}static DrawDirection(s,t,i=_s,n=0,o=!0,r=1){if(!ws.enabled)return;const l=Ee.getLine(n),c=l.geometry.getAttribute("position");c.setXYZ(0,s.x,s.y,s.z),t.w!==void 0?(zt.set(0,0,-r),Hb.set(t.x,t.y,t.z,t.w),zt.applyQuaternion(Hb)):(zt.set(t.x,t.y,t.z),zt.multiplyScalar(r)),c.setXYZ(1,s.x+zt.x,s.y+zt.y,s.z+zt.z),c.needsUpdate=!0,l.material.color.set(i),l.material.depthTest=o,l.material.depthWrite=!1}static DrawLine(s,t,i=_s,n=0,o=!0){if(!ws.enabled)return;const r=Ee.getLine(n),l=r.geometry.getAttribute("position");l.setXYZ(0,s.x,s.y,s.z),l.setXYZ(1,t.x,t.y,t.z),l.needsUpdate=!0,r.material.color.set(i),r.material.depthTest=o,r.material.depthWrite=!1,r.material.fog=!1}static DrawCircle(s,t,i,n=_s,o=0,r=!0){if(!ws.enabled)return;const l=Ee.getCircle(o);l.position.set(s.x,s.y,s.z),l.scale.set(i,i,i),l.quaternion.setFromUnitVectors(this._up,zt.set(t.x,t.y,t.z).normalize()),l.material.color.set(n),l.material.depthTest=r,l.material.depthWrite=!1,l.material.fog=!1}static DrawWireSphere(s,t,i=_s,n=0,o=!0){if(!ws.enabled)return;const r=Ee.getSphere(t,n,!0);fr(r,s.x,s.y,s.z),r.material.color.set(i),r.material.depthTest=o,r.material.depthWrite=!1,r.material.fog=!1}static DrawSphere(s,t,i=_s,n=0,o=!0){if(!ws.enabled)return;const r=Ee.getSphere(t,n,!1);fr(r,s.x,s.y,s.z),r.material.color.set(i),r.material.depthTest=o,r.material.depthWrite=!1}static DrawWireBox(s,t,i=_s,n=0,o=!0){if(!ws.enabled)return;const r=Ee.getBox(n);r.position.set(s.x,s.y,s.z),r.scale.set(t.x,t.y,t.z),r.material.color.set(i),r.material.depthTest=o,r.material.wireframe=!0,r.material.depthWrite=!1,r.material.fog=!1}static DrawWireBox3(s,t=_s,i=0,n=!0){if(!ws.enabled)return;const o=Ee.getBox(i);o.position.copy(s.getCenter(zt)),o.scale.copy(s.getSize(zt)),o.material.color.set(t),o.material.depthTest=n,o.material.wireframe=!0,o.material.depthWrite=!1,o.material.fog=!1}static DrawArrow(s,t,i=_s,n=0,o=!0,r=!1){if(!ws.enabled)return;const l=Ee.getArrowHead(n);l.position.set(t.x,t.y,t.z),l.quaternion.setFromUnitVectors(this._up.set(0,1,0),zt.set(t.x,t.y,t.z).sub(Vb.set(s.x,s.y,s.z)).normalize());const c=zt.set(t.x,t.y,t.z).sub(Vb.set(s.x,s.y,s.z)).length()*.1;l.scale.set(c,c,c),l.material.color.set(i),l.material.depthTest=o,l.material.wireframe=r,this.DrawLine(s,t,i,n,o)}static DrawWireMesh(s){const t=Ee.getMesh(s.duration??0);"mesh"in s?(t.geometry=s.mesh.geometry,t.matrix.copy(s.mesh.matrixWorld)):(t.geometry=s.geometry,t.matrix.copy(s.matrix)),t.matrixAutoUpdate=!1,t.matrixWorldAutoUpdate=!1,t.material.color.set(s.color??_s),t.material.depthTest=s.depthTest??!0,t.material.wireframe=!0}static setVisible(s){for(const t of Ee.timedObjectsBuffer)t.visible=s}};let q=ws;a(q,"enabled",!0),a(q,"_up",new x(0,1,0));const tk=new Wl(1,1,1);function wg(s=null){const t=new ae(s??14540253),i=new gS(tk);return new Qy(i,new Yy({color:t}))}const xg=Symbol("GizmoCache");class Ee{static ensureFont(){let t=Re.FontLibrary.getFontFamily(this.familyName);if(!t){t=Re.FontLibrary.addFontFamily(this.familyName);const i=t.addVariant("normal","normal","https://uploads.needle.tools/include/font-msdf.json","https://uploads.needle.tools/include/font.png");i?.addEventListener("ready",()=>{Re.update()})}}static getTextLabel(t,i,n,o,r){this.ensureFont();let l=this.textLabelCache.pop(),c=1;r&&typeof r=="string"&&r?.length>=8&&r.startsWith("#")?(c=parseInt(r.substring(7),16)/255,r=r.substring(0,7),ek&&console.log(r,c)):typeof r=="object"&&r.a!==void 0&&(c=r.a);const h={boxSizing:"border-box",fontFamily:this.familyName,width:"auto",fontSize:n,color:o,lineHeight:1,backgroundColor:r??void 0,backgroundOpacity:c,textContent:i,borderRadius:.5*n,padding:.8*n,whiteSpace:"pre",offset:.05*n};if(l)l.set(h);else{l=new vv(h);const d=this,u=l;u.setText=function(p){this.set({textContent:p}),d.tmuiNeedsUpdate=!0}}return this.tmuiNeedsUpdate=!0,this.registerTimedObject(te.Current,l,t,this.textLabelCache),l}static getBox(t){let i=this.boxesCache.pop();if(!i){const n=new Wl(1,1,1);i=new Q(n)}return this.registerTimedObject(te.Current,i,t,this.boxesCache),i}static getLine(t){let i=this.linesCache.pop();if(!i){i=new Vl;let n=i.geometry.getAttribute("position");n||(n=new mt(new Float32Array(2*3),3),i.geometry.setAttribute("position",n))}return i.frustumCulled=!1,this.registerTimedObject(te.Current,i,t,this.linesCache),i}static getCircle(t){let i=this.circlesCache.pop();if(!i){i=new Vl;let n=i.geometry.getAttribute("position");if(!n){n=new mt(new Float32Array(_g*3),3),i.geometry.setAttribute("position",n);const o=$(0,1,0),r=$(0,0,1),l=$(r);l.cross(o).normalize();const c=$(l),h=Math.PI*2/(_g-1);for(let d=0;d<_g+1;d++){const u=h*d;o.copy(c).multiplyScalar(Math.cos(u)*1),l.copy(r).multiplyScalar(Math.sin(u)*1);const p=o.add(l);n.setXYZ(d,p.x,p.y,p.z)}}}return i.frustumCulled=!1,this.registerTimedObject(te.Current,i,t,this.circlesCache),i}static getSphere(t,i,n){let o=this.spheresCache.pop();return o||(o=new Q(new rd(1,8,8))),o.scale.set(t,t,t),o.material.wireframe=n,this.registerTimedObject(te.Current,o,i,this.spheresCache),o}static getArrowHead(t){let i=this.arrowHeadsCache.pop();return i||(i=new Q(new mS(0,.5,1,8))),this.registerTimedObject(te.Current,i,t,this.arrowHeadsCache),i}static getMesh(t){let i=this.mesh.pop();return i||(i=new Q,i.material=new Me),this.registerTimedObject(te.Current,i,t,this.mesh),i}static registerTimedObject(t,i,n,o){if(!t){console.error("No Needle Engine context available. Did you call a Gizmos function in global scope?");return}const r=this.contextBeforeRenderCallbacks.get(t),l=this.contextPostRenderCallbacks.get(t);if(r){if(t.pre_render_callbacks[t.pre_render_callbacks.length-1]!==r){const c=t.pre_render_callbacks.indexOf(r);c>=0&&t.pre_render_callbacks.splice(c,1),t.pre_render_callbacks.push(r)}}else{const c=()=>{this.onBeforeRender(t,this.timedObjectsBuffer)};this.contextBeforeRenderCallbacks.set(t,c),t.pre_render_callbacks.push(c)}if(l){if(t.post_render_callbacks[t.post_render_callbacks.length-1]!==l){const c=t.post_render_callbacks.indexOf(l);c>=0&&t.post_render_callbacks.splice(c,1),t.post_render_callbacks.push(l)}}else{const c=()=>{this.onPostRender(t,this.timedObjectsBuffer,this.timesBuffer)};this.contextPostRenderCallbacks.set(t,c),t.post_render_callbacks.push(c)}i.traverse(c=>{c.layers.disableAll(),c.layers.enable(2)}),i.renderOrder=999999,i[xg]=o,i.castShadow=!1,i.receiveShadow=!1,i.isGizmo=!0,this.timedObjectsBuffer.push(i),this.timesBuffer.push(te.Current.time.realtimeSinceStartup+n),t.scene.add(i)}static onBeforeRender(t,i){this.tmuiNeedsUpdate&&(this.tmuiNeedsUpdate=!1,Re.update());for(let n=0;n<i.length;n++){const o=i[n];if(t.mainCamera&&o instanceof Re.MeshUIBaseElement){if(Pr(o))continue;const r=t.isInVR,l=!1,c=!r;Kl(o,t.mainCamera,l,c)}}}static onPostRender(t,i,n){const o=t.time.realtimeSinceStartup;for(let r=i.length-1;r>=0;r--){const l=i[r];o>=n[r]-1e-6&&(i.splice(r,1),n.splice(r,1),l.removeFromParent(),Pr(l)!=!0&&l[xg].push(l))}}}a(Ee,"familyName","needle-gizmos"),a(Ee,"linesCache",[]),a(Ee,"circlesCache",[]),a(Ee,"spheresCache",[]),a(Ee,"boxesCache",[]),a(Ee,"arrowHeadsCache",[]),a(Ee,"mesh",[]),a(Ee,"textLabelCache",[]),a(Ee,"timedObjectsBuffer",new Array),a(Ee,"timesBuffer",new Array),a(Ee,"contextPostRenderCallbacks",new Map),a(Ee,"contextBeforeRenderCallbacks",new Map),a(Ee,"tmuiNeedsUpdate",!1);const Pi=O("debugphysics"),$b=new no;class Ns{constructor(){a(this,"ray"),a(this,"cam"),a(this,"screenPoint"),a(this,"raycaster"),a(this,"results"),a(this,"targets"),a(this,"recursive",!0),a(this,"minDistance"),a(this,"maxDistance"),a(this,"lineThreshold"),a(this,"layerMask"),a(this,"ignore"),a(this,"testObject"),a(this,"useAcceleratedRaycast")}screenPointFromOffset(t,i){this.screenPoint===void 0&&(this.screenPoint=new oe),this.screenPoint.x=t/window.innerWidth*2-1,this.screenPoint.y=-(i/window.innerHeight)*2+1}setLayer(t){$b.set(t),this.layerMask=$b}setMask(t){this.layerMask||(this.layerMask=new no);const i=this.layerMask;i?i.mask=t:this.layerMask=t}}a(Ns,"AllLayers",4294967295);class Sg{constructor(t,i,n){a(this,"distance"),a(this,"point"),a(this,"object"),this.object=t,this.distance=i,this.point=n}}const Cg=class{constructor(s){a(this,"context"),a(this,"engine"),a(this,"raycaster",new ld),a(this,"defaultRaycastOptions",new Ns),a(this,"targetBuffer",new Array(1)),a(this,"defaultThresholds",{Mesh:{},Line:{threshold:-1},LOD:{},Points:{threshold:0},Sprite:{}}),a(this,"sphereResults",new Array),a(this,"sphereMask",new no),a(this,"sphere",new ad),a(this,"tempBoundingBox",new vi),this.context=s}static get raycasting(){return this._raycasting>0}raycastPhysicsFast(s,t=void 0,i=1/0,n=!0){var o;return((o=this.context.physics.engine)==null?void 0:o.raycast(s,t,{maxDistance:i,solid:n}))??null}raycastPhysicsFastAndGetNormal(s,t=void 0,i=1/0,n=!0){var o;return((o=this.context.physics.engine)==null?void 0:o.raycastAndGetNormal(s,t,{maxDistance:i,solid:n}))??null}sphereOverlapPhysics(s,t){var i;return((i=this.context.physics.engine)==null?void 0:i.sphereOverlap(s,t))??null}sphereOverlap(s,t,i=!0,n=!1,o=null){if(this.sphereResults.length=0,!this.context.scene)return this.sphereResults;const r=this.sphereMask;r.enableAll(),r.disable(2);for(const l of this.context.scene.children)this.intersectSphere(l,s,t,r,this.sphereResults,i,n,o);return this.sphereResults.sort((l,c)=>l.distance-c.distance)}raycastFromRay(s,t=null){const i=t??this.defaultRaycastOptions;i.ray=s;const n=this.raycast(i);return i===this.defaultRaycastOptions&&(i.ray=void 0),n}raycast(s=null){Pi&&performance.mark("raycast.start"),s||(s=this.defaultRaycastOptions);const t=s.screenPoint??this.context.input.mousePositionRC,i=s.raycaster??this.raycaster;if(i.near=s.minDistance??0,i.far=s.maxDistance??1/0,i.params=this.defaultThresholds,s.lineThreshold===void 0&&(s.lineThreshold=-1),i.params.Line={threshold:s.lineThreshold},s.ray)i.ray.copy(s.ray);else{const l=s.cam??this.context.mainCamera;if(!l)return Pi&&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 fS&&c.cameras.length>0?i.setFromCamera(t,c.cameras[0]):i.setFromCamera(t,l)}let n=s.targets;n||(n=this.targetBuffer,n.length=1,n[0]=this.context.scene);let o=s.results;this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),o||(this.defaultRaycastOptions.results||(this.defaultRaycastOptions.results=new Array),o=this.defaultRaycastOptions.results),s.layerMask!==void 0?s.layerMask instanceof no?i.layers.mask=s.layerMask.mask:i.layers.mask=s.layerMask:(i.layers.enableAll(),i.layers.disable(2)),Pi&&console.time("raycast"),o.length=0,Cg._raycasting++,this.intersect(this.raycaster,n,o,s),o.sort((l,c)=>l.distance-c.distance);const r=s.ignore;return r!==void 0&&r.length>0&&(o=o.filter(l=>!r.includes(l.object))),Cg._raycasting--,Pi&&(console.timeEnd("raycast"),console.warn("#"+this.context.time.frame+", hits:",o!=null&&o.length?[...o]:"nothing"),performance.mark("raycast.end"),performance.measure("raycast","raycast.start","raycast.end")),o}intersect(s,t,i,n){var o,r,l;for(const c of t){if(!c||c.visible===!1||q.isGizmo(c)||n.lineThreshold!==void 0&&n.lineThreshold<0&&c instanceof Vl)continue;let h=!0;const d=c,u=d.geometry;if(n.testObject){const p=(o=n.testObject)==null?void 0:o.call(n,c);if(p===!1)continue;p==="continue in children"&&(h=!1)}if(h&&(u&&qb(u)||(h=!1)),h){const p=av(c);p&&(d.geometry=p);const g=i.length;let y=!0;if(n.precise===!1&&(y=!1),y||(y=((l=(r=u.getAttribute("position"))==null?void 0:r.array)==null?void 0:l.length)<64),d instanceof xa&&(y=!1),!y&&sk(d,s,i)||(n.useAcceleratedRaycast!==!1?Ld.runMeshBVHRaycast(s,d,i,this.context):s.intersectObject(d,!1,i)),Pi&&i.length!=g){const f=i[i.length-1],v=p?8969557:7798784;q.DrawWireSphere(f.point,.1,v,1,!1),q.DrawWireMesh({mesh:c,depthTest:!1,duration:.2,color:v})}d.geometry=u}n.recursive!==!1&&this.intersect(s,c.children,i,n)}return i}intersectSphere(s,t,i,n,o,r,l,c){let h=s&&s.isMesh&&s.layers.test(n)&&!q.isGizmo(s);h&&(h=s.visible),h&&(h=!(s instanceof Vl)),h&&(h=!(s instanceof xa));const d=s,u=d.geometry;if(h&&c){const p=c(s);if(p===!1)return;p==="continue in children"&&(h=!1)}if(u&&qb(u)||(h=!1),h){if(l){const p=this.sphere;p.center.copy(t),p.radius=i;const g=o.length;if(Ld.runMeshBVHRaycast(this.sphere,d,o,this.context),g!=o.length&&!r)return}else if(u.boundingBox||u.computeBoundingBox(),u.boundingBox){d.matrixWorldNeedsUpdate&&d.updateWorldMatrix(!1,!1);const p=this.tempBoundingBox.copy(u.boundingBox).applyMatrix4(d.matrixWorld),g=this.sphere;if(g.center.copy(t),g.radius=i,g.intersectsBox(p)){const y=ee(s),f=y.distanceTo(g.center),v=new Sg(s,f,y);if(o.push(v),!r)return}}}if(s.children)for(const p of s.children){const g=o.length;if(this.intersectSphere(p,t,i,n,o,r,l,c),g!=o.length&&!r)return}}};let Id=Cg;a(Id,"_raycasting",0);function qb(s){return!(s.index&&s.index.array.length<3)}const wr=new ad,jd=new dr,ik=new qy;function sk(s,t,i){const n=s._computeIntersections;if(!n)return!1;let o=s["_computeIntersections:Needle"];return o||(o=s["_computeIntersections:Needle"]=function(r,l,c){const h=this,d=h.geometry.boundingSphere;if(d){if(h instanceof xa){jd.setFromNormalAndCoplanarPoint($(0,1,0),$(0,-h.position.y,0)),jd.applyMatrix4(h.matrixWorld,ik);const p=r.ray.intersectPlane(jd,$());if(p){wr.copy(d),wr.applyMatrix4(h.matrixWorld);const g=$(p).sub(r.ray.origin).length(),y=wr.radius*.5;g<y&&l.push({distance:g,point:p,object:h,normal:jd.normal.clone()})}return}wr.copy(d),wr.applyMatrix4(h.matrixWorld);const u=r.ray.intersectSphere(wr,$());if(u){const p=$(u).sub(r.ray.origin),g=p.length();if(g>wr.radius){const y=p.clone().normalize();l.push({distance:g,point:u,object:h,normal:y})}}}}),s._computeIntersections=o,t.intersectObject(s,!1,i),s._computeIntersections=n,!0}var Ld;(s=>{function t(w,_,C,R){var M,E,D;if(!_.geometry||!_.geometry.hasAttribute("position"))return!1;const L=_.geometry;if(_!=null&&_.isSkinnedMesh){const U=_,z=U.bvhNeedsUpdate;if(!U.staticGenerator)c(),r&&(U.staticGenerator=new r(_),U.staticGenerator.applyWorldTransforms=!1,U.staticGeometry=U.staticGenerator.generate(),L.boundsTree=l?.call(U.staticGeometry),U.staticGeometryLastUpdate=performance.now()+Math.random()*200,U.autoUpdateMeshBVH===void 0&&(U.autoUpdateMeshBVH=!1));else if(L.boundsTree&&(U.autoUpdateMeshBVH===!0||z===!0)){const H=performance.now(),T=H-U.staticGeometryLastUpdate;(z||T>100)&&(U.bvhNeedsUpdate=!1,U.staticGeometryLastUpdate=H,(M=U.staticGenerator)==null||M.generate(U.staticGeometry),L.boundsTree.refit())}}else if(!L.boundsTree){d||b();let U=!0;if((R.xr||L[y]===!1||(E=L.getAttribute("position"))!=null&&E.isInterleavedBufferAttribute||L.index&&(D=L.index)!=null&&D.isInterleavedBufferAttribute)&&(U=!1),U&&p){if(L[g]===void 0){let z=null;if(v.length>0){const H=v.shift();H&&!H.running&&(z=H)}if(!z&&f.length<3&&(z=new p,f.push(z)),z!=null&&!z.running){const H=_.name;Pi&&console.log("<<<< worker start",H,z),L[g]="queued",performance.mark("bvh.create.start");const T=L.clone();try{z.generate(T).then(I=>{L[g]="done",L.boundsTree=I}).catch(I=>{L[g]="failed - "+I?.message,L[y]=!1,Pi&&console.error("Failed to generate mesh bvh on worker",I)}).finally(()=>{Pi&&console.log(">>>>> worker done",H,{hasBoundsTre:L.boundsTree!=null}),v.push(z),T.dispose(),performance.mark("bvh.create.end"),performance.measure("bvh.create (worker)","bvh.create.start","bvh.create.end")})}catch(I){console.error("Failed to generate mesh bvh on worker",I)}}else Pi&&console.warn("No worker available")}}else(!u||!U)&&(c(),o&&(performance.mark("bvh.create.start"),L.boundsTree=new o(L),performance.mark("bvh.create.end"),performance.measure("bvh.create","bvh.create.start","bvh.create.end")))}if(w instanceof ld){const U=w,z=_.raycast;L.boundsTree?(c(),n&&(_.acceleratedRaycast||(_.acceleratedRaycast=n.bind(_),Pi&&console.debug(`Physics: bind acceleratedRaycast fn to "${_.name}"`)),_.raycast=_.acceleratedRaycast)):Pi&&console.warn("No bounds tree found for mesh",_.name,{workerTask:L[g],hasAcceleratedRaycast:n!=null});const H=U.firstHitOnly;return U.firstHitOnly=!1,U.intersectObject(_,!1,C),U.firstHitOnly=H,_.raycast=z,!0}else if(w instanceof ad){const U=L.boundsTree;if(U){const z=w;if(h.copy(_.matrixWorld).invert(),z.applyMatrix4(h),U.intersectsSphere(z)){const H=ee(_),T=H.distanceTo(z.center),I=new Sg(_,T,H);C.push(I)}}return!0}return!1}s.runMeshBVHRaycast=t;let i=!1,n=null,o=null,r=null,l=null;function c(){i||(i=!0,import("./vendor.light.min.js").then(w=>w.k).then(w=>{n=w.acceleratedRaycast,o=w.MeshBVH,r=w.StaticGeometryGenerator,l=w.computeBoundsTree}).catch(w=>{(Pi||F())&&console.error("Failed to load BVH library...",w.message)}))}const h=new ne;let d=!1,u=!1,p=null;const g=Symbol("Needle:MeshBVH-Worker"),y=Symbol("Needle:MeshBVH-CanUseWorker"),f=[],v=[];function b(){d=!0,u=!0,Promise.resolve().then(()=>Gj).then(w=>{p=w.GenerateMeshBVHWorker}).catch(w=>{(Pi||F())&&console.warn("Failed to setup mesh bvh worker")}).finally(()=>{u=!1})}})(Ld||(Ld={}));const Gb=Symbol("gltf-loader-internal-usage-tracker"),nk=O("debugusers"),Dd=class{constructor(s){a(this,"parser"),a(this,"_getDependency"),a(this,"_loadingId"),a(this,"_loadedObjects",new Set),this.parser=s,this._getDependency=this.parser.getDependency,this._loadingId=Date.now().toString()}get name(){return"NEEDLE_internal_usage_tracker"}static isLoading(s){return Dd._loadingProcesses>0}beforeRoot(){Dd._loadingProcesses++;const s=this,t=this._getDependency;return this.parser.getDependency=function(i,n){const o=t.call(this,i,n);return o.then(r=>(r&&(s._loadedObjects.add(r),r[Gb]=s._loadingId),r)),o},null}afterRoot(s){Dd._loadingProcesses--,this.parser.getDependency=this._getDependency;for(const t of this._loadedObjects)delete t[Gb],t instanceof j&&(t.parent||t instanceof Q&&setTimeout(()=>{nk&&console.warn("> GLTF LOADER: Mesh not used in scene!",t),t.material=null,t.geometry=null},1e3));return null}};let Og=Dd;a(Og,"_loadingProcesses",0);class Xb{constructor(){window.addEventListener("unhandledrejection",t=>{var i;if(t.defaultPrevented)return;const n=(i=t?.reason)==null?void 0:i.path;if(n){const o=n[0];o&&o.tagName==="IMG"&&(console.warn(`Could not load image:
155
- `+o.src),t.preventDefault())}})}}const Bd=O("trackresources");function Qb(){return Bd==="dispose"}let xr=!0;Bd===0&&(xr=!1);function ok(s){xr=s}function Yb(){return xr}const Kb=Symbol("disposable");function Pg(s,t){s&&(s[Kb]=t,Sr&&console.warn("Set disposable",t,s))}const Zb=Symbol("disposed");function rk(s){return s[Zb]===!0}function Te(s){var t;if(s){if(s[Kb]===!1){Sr&&console.warn("Object is marked as not disposable",s);return}if(s[Zb]=!0,s instanceof $i)Te(s.environment),Te(s.background),Te(s.customDepthMaterial),Te(s.customDistanceMaterial);else if(s instanceof bn)Te(s.geometry),Te(s.material),Te(s.skeleton),Te(s.bindMatrix),Te(s.bindMatrixInverse),Te(s.customDepthMaterial),Te(s.customDistanceMaterial),s.geometry=null,s.material=null,s.visible=!1;else if(s instanceof Q)Te(s.geometry),Te(s.material),Te(s.customDepthMaterial),Te(s.customDistanceMaterial),s.geometry=null,s.material=null,s.visible=!1;else if(s instanceof oo){Aa(s);for(const i of Object.keys(s.attributes)){const n=s.attributes[i];Te(n)}}else if(s instanceof mt||s instanceof Ky)Sr&&console.warn("BufferAttribute dispose not supported",s.count);else if(s instanceof Array)for(const i of s)i instanceof Oe&&Te(i);else if(s instanceof Oe){Aa(s);for(const n of Object.keys(s)){const o=s[n];o instanceof Ne&&(Te(o),s[n]=null)}const i=s.uniforms;if(i)for(const n of Object.keys(i)){const o=i[n];o instanceof Ne?(Te(o),i[n]=null):o instanceof so&&(Te(o.value),o.value=null)}}else s instanceof Ne?(Aa(s),Aa(s.source),((t=s.source)==null?void 0:t.data)instanceof ImageBitmap&&Aa(s.source.data)):s instanceof yS?(Aa(s.boneTexture),s.boneTexture=null):s instanceof vS||!(s instanceof j)&&Sr&&console.warn("Unknown object type",s)}}function Aa(s){s&&((Sr||Qb()||Bd)&&console.warn("\u{1F9E8} FREE",s),s instanceof ImageBitmap?s.close():s instanceof bS?s.data=null:s.dispose())}function Jb(s){(s instanceof Q||s instanceof bn)&&(s.material=null,s.geometry=null)}const ak=new Set;function kg(s,t,i=null,n){if(n||(n=ak,n.clear()),!s)return n;const o=s[dc];if(o)for(const r of o)n.has(r)||i?.call(null,r)!==!1&&(n.add(r),t&&kg(r,!0,i,n));return n}function lk(s){return s[uc]}const Sr=O("debugresourceusers")||O("debugmemory"),dc=Symbol("needle-resource-users"),uc=Symbol("needle-resource-users-count");function Xt(s,t){Od(s,t,function(i,n){xr&&!Id.raycasting&&(Fd(dc,this,i,!1),Fd(dc,this,n,!0))})}xr&&(Xt(Q.prototype,"material"),Xt(Q.prototype,"geometry"),Xt(Oe.prototype,"map"),Xt(Oe.prototype,"bumpMap"),Xt(Oe.prototype,"alphaMap"),Xt(Oe.prototype,"normalMap"),Xt(Oe.prototype,"displacementMap"),Xt(Oe.prototype,"roughnessMap"),Xt(Oe.prototype,"metalnessMap"),Xt(Oe.prototype,"emissiveMap"),Xt(Oe.prototype,"specularMap"),Xt(Oe.prototype,"envMap"),Xt(Oe.prototype,"lightMap"),Xt(Oe.prototype,"aoMap"),Xt(Oe.prototype,"gradientMap"));function ck(s){if(xr===!1)return;const t=s[dc];if(t)for(const i of t)Fd(dc,i,s,!1)}xr&&Od(Oe.prototype,"dispose",function(){ck(this)});let Mg=0;function Fd(s,t,i,n){if(Mg>0)return;if(Array.isArray(i)){for(const r of i)Fd(s,t,r,n);return}if(!i)return;let o=i[s];if(o||(o=new Set),n){if(t&&!o.has(t)){o.add(t);let r=i[uc]||0;r+=1,i[uc]=r,Sr&&console.warn(`\u{1F7E2} Added user of "${i.type}"`,t,i,r,"users:",o)}}else if(t&&o.has(t)){o.delete(t);let r=i[uc]||0;r>0&&(r-=1,i[uc]=r),Sr&&console.warn(`\u{1F534} Removed user of "${i.type}"`,t,i,r,"users:",o),r<=0&&(Og.isLoading(i)||(Bd&&console.warn(`\u{1F534} Removed all user of "${i.type}"`,i),Qb()&&Te(i)))}i[s]=o}try{Od(cr.prototype,"render",function(){Mg++},function(){Mg--})}catch(s){console.warn("Could not wrap WebGLRenderer.render",s)}const e_=O("debugcomponentevents");class pc{static addComponentLifecylceEventListener(t,i){this.eventListeners.has(t)&&this.eventListeners.set(t,[]);let n=this.eventListeners.get(t);n||(n=[]),n.push(i),this.eventListeners.set(t,n),e_&&console.log("Added event listener for "+t,this.eventListeners)}static removeComponentLifecylceEventListener(t,i){const n=this.eventListeners.get(t);if(!n)return;const o=n.indexOf(i);o<0||n.splice(o,1)}static dispatchComponentLifecycleEvent(t,i){const n=this.eventListeners.get(t);if(e_&&console.log("Dispatching event "+t,n),!!n)for(const o of n)o(i)}}a(pc,"eventListeners",new Map);const mc=Symbol("NEEDLE_NEED_UPDATE_INSTANCE"),t_=Symbol("isUsingInstancing"),i_=Symbol("instancingRenderer"),gc=Symbol("instancingAutoUpdateBounds");class cs{static isUsingInstancing(t){return t[t_]===!0}static getRenderer(t){return t[i_]||null}setAutoUpdateBounds(t,i){const n=cs.getRenderer(t);n&&(n[gc]=i)}static markDirty(t,i=!0){if(t&&(this.isUsingInstancing(t)&&(t[mc]=!0,t.matrixWorldNeedsUpdate=!0),i))for(const n of t.children)cs.markDirty(n,!0)}}function Ia(s,t){try{t?s(t):s()}catch(i){return console.error(i),!1}return!0}const Rg=O("debugnewscripts"),hk=O("debughierarchy"),Be=[];function dk(){return Be.length>0}function zd(s){if(!(s.new_scripts.length<=0)){if(Rg&&console.log("Register new components",s.new_scripts.length,[...s.new_scripts],s.alias?"element: "+s.alias:s.hash,s),s.new_scripts_pre_setup_callbacks.length>0){for(const t of s.new_scripts_pre_setup_callbacks)t&&t();s.new_scripts_pre_setup_callbacks.length=0}Be.length=0,s.new_scripts.length>0&&Be.push(...s.new_scripts),s.new_scripts.length=0;for(let t=0;t<Be.length;t++)try{const i=Be[t];if(i.isComponent!==!0){(F()||Rg)&&console.error(`Registered script is not a Needle Engine component.
154
+ ${o.hand?"hand":"ctrl"} ${o.inputSource.handedness}[${o.index}] con:${o.connected} tr:${o.isTracking} hts:${o.hasHitTestSource?"yes":"no"}`;yg=0,q.DrawLabel(s,n,void 0,1/60*20)}}addScript(s){return this._xr_scripts.includes(s)?!1:(gt&&console.log("Register new XRScript",s),this._xr_scripts.push(s),typeof s.onUpdateXR=="function"&&this._xr_update_scripts.push(s),!0)}markInactive(s){if(!(this._inactive_scripts.indexOf(s)>=0)){this.removeScript(s,!1),this._inactive_scripts.push(s);for(const t of this.controllers)this.invokeCallback_ControllerRemoved(s,t);this.invokeCallback_LeaveXR(s)}}handleInactiveScripts(){if(this._inactive_scripts.length>0)for(let s=this._inactive_scripts.length-1;s>=0;s--){const t=this._inactive_scripts[s];if(t.activeAndEnabled){this._inactive_scripts.splice(s,1),this.addScript(t),this.invokeCallback_EnterXR(t);for(const i of this.controllers)this.invokeCallback_ControllerAdded(t,i)}}}removeScript(s,t=!0){gt&&console.log("Remove XRScript",s);const i=this._xr_scripts.indexOf(s);i>=0&&this._xr_scripts.splice(i,1);const n=this._xr_update_scripts.indexOf(s);if(n>=0&&this._xr_update_scripts.splice(n,1),t){const o=this._inactive_scripts.indexOf(s);o>=0&&this._inactive_scripts.splice(o,1)}}invokeCallback_EnterXR(s){s.onEnterXR&&s.onEnterXR({xr:this})}invokeCallback_ControllerAdded(s,t){s.onXRControllerAdded&&s.onXRControllerAdded({xr:this,controller:t,change:"added"})}invokeCallback_ControllerRemoved(s,t){s.onXRControllerRemoved&&s.onXRControllerRemoved({xr:this,controller:t,change:"removed"})}invokeCallback_LeaveXR(s){s.onLeaveXR&&!s.destroyed&&s.onLeaveXR({xr:this})}syncCameraCullingMask(){var s;const t=this.context.xrCamera,i=(s=this.context.mainCameraComponent)==null?void 0:s.cullingMask;if(t&&i!==void 0){for(const n of t.cameras)n.layers.mask=i;t.layers.mask=i}else if(t){for(const n of t.cameras)n.layers.enableAll();t.layers.enableAll()}}invokeControllerEvent(s,t,i){for(let n=t.length-1;n>=0;n--){const o=t[n];if(o)try{o({xr:this,controller:s,change:i})}catch(r){console.error(r)}}}applyCustomForward(){var s;if(this.context.mainCamera&&this._customforward){this._camera=this.context.mainCamera,this._camera.parent!==this._cameraRenderParent&&(this._previousCameraParent=this._camera.parent,(s=this._previousCameraParent)==null||s.add(this._cameraRenderParent)),this._cameraRenderParent.name="XR Camera Render Parent",this._cameraRenderParent.add(this._camera);let t=.02;if(this.rig){const i=Ke(this.rig.gameObject);t*=i.x}this._camera instanceof be&&this._camera.near>t&&(this.originalCameraNearPlane=this._camera.near,this._camera.near=t)}}revertCustomForward(){this._camera&&this._previousCameraParent&&this._previousCameraParent.add(this._camera),this._previousCameraParent=null,this._camera instanceof be&&this.originalCameraNearPlane!=null&&(this._camera.near=this.originalCameraNearPlane)}internalUpdateState(){const s=this.context.renderer.xr.getReferenceSpace();if(!s){this._viewerPose=void 0;return}if(this._viewerPose=this.frame.getViewerPose(s),this._viewerPose){const t=this._viewerPose.transform;this._transformPosition.set(t.position.x,t.position.y,t.position.z),this._transformOrientation.set(t.orientation.x,t.orientation.y,t.orientation.z,t.orientation.w)}}get transition(){return this._transition||(this._transition=new jb),this._transition}fadeTransition(){return this._transition||(this._transition=new jb),this._transition.fadeTransition()}updateFade(s){this._transition&&s instanceof be&&this._transition.update(s,this.context.time.deltaTime)}onUpdateFade_PostRender(){var s;(s=this._transition)==null||s.remove()}};let Z=go;a(Z,"_sync",null),a(Z,"_currentSessionRequestMode",null),a(Z,"_currentSessionRequest"),a(Z,"_activeSession"),a(Z,"_sessionRequestStartListeners",[]),a(Z,"_sessionRequestEndListeners",[]),a(Z,"_xrStartListeners",[]),a(Z,"_xrEndListeners",[]),a(Z,"_controllerAddedListeners",[]),a(Z,"_controllerRemovedListeners",[]),a(Z,"onEnd",()=>{gt&&console.log("XR Session ended"),go._activeSession=null});const bg=O("debugwebxr");class Wb{static tryFindAvatarObjects(t,i,n){if(n.head&&n.leftHand&&n.rightHand)return;const o=t.name.toLocaleLowerCase();!n.head&&o.includes("head")&&(bg&&console.log("FOUND AVATAR HEAD",t.name),n.head=new le("",i,t)),o.includes("hand")&&(!n.leftHand&&o.includes("left")&&(bg&&console.log("FOUND AVATAR LEFT HAND",t.name),n.leftHand=new le("",i,t)),!n.rightHand&&o.includes("right")&&(bg&&console.log("FOUND AVATAR RIGHT HAND",t.name),n.rightHand=new le("",i,t)));for(let r=0;r<t.children.length;r++){if(n.head&&n.leftHand&&n.rightHand)return;const l=t.children[r];this.tryFindAvatarObjects(l,i,n)}}}const zt=new x,Vb=new x,Hb=new V,e2=O("debuggizmos"),_s=8947848,_g=32,ws=class{constructor(){}static isGizmo(s){return s[xg]!==void 0}static DrawLabel(s,t,i=.05,n=0,o,r,l){var c;if(!ws.enabled)return null;o||(o=_s);const h=((c=Z.active)==null?void 0:c.rigScale)??1,d=Ee.getTextLabel(n,t,i*h,o,r);return l instanceof j&&l.add(d),d.position.x=s.x,d.position.y=s.y,d.position.z=s.z,d}static DrawRay(s,t,i=_s,n=0,o=!0){if(!ws.enabled)return;const r=Ee.getLine(n),l=r.geometry.getAttribute("position");l.setXYZ(0,s.x,s.y,s.z),zt.set(t.x,t.y,t.z).multiplyScalar(999999999),l.setXYZ(1,s.x+zt.x,s.y+zt.y,s.z+zt.z),l.needsUpdate=!0,r.material.color.set(i),r.material.depthTest=o,r.material.depthWrite=!1}static DrawDirection(s,t,i=_s,n=0,o=!0,r=1){if(!ws.enabled)return;const l=Ee.getLine(n),c=l.geometry.getAttribute("position");c.setXYZ(0,s.x,s.y,s.z),t.w!==void 0?(zt.set(0,0,-r),Hb.set(t.x,t.y,t.z,t.w),zt.applyQuaternion(Hb)):(zt.set(t.x,t.y,t.z),zt.multiplyScalar(r)),c.setXYZ(1,s.x+zt.x,s.y+zt.y,s.z+zt.z),c.needsUpdate=!0,l.material.color.set(i),l.material.depthTest=o,l.material.depthWrite=!1}static DrawLine(s,t,i=_s,n=0,o=!0){if(!ws.enabled)return;const r=Ee.getLine(n),l=r.geometry.getAttribute("position");l.setXYZ(0,s.x,s.y,s.z),l.setXYZ(1,t.x,t.y,t.z),l.needsUpdate=!0,r.material.color.set(i),r.material.depthTest=o,r.material.depthWrite=!1,r.material.fog=!1}static DrawCircle(s,t,i,n=_s,o=0,r=!0){if(!ws.enabled)return;const l=Ee.getCircle(o);l.position.set(s.x,s.y,s.z),l.scale.set(i,i,i),l.quaternion.setFromUnitVectors(this._up,zt.set(t.x,t.y,t.z).normalize()),l.material.color.set(n),l.material.depthTest=r,l.material.depthWrite=!1,l.material.fog=!1}static DrawWireSphere(s,t,i=_s,n=0,o=!0){if(!ws.enabled)return;const r=Ee.getSphere(t,n,!0);fr(r,s.x,s.y,s.z),r.material.color.set(i),r.material.depthTest=o,r.material.depthWrite=!1,r.material.fog=!1}static DrawSphere(s,t,i=_s,n=0,o=!0){if(!ws.enabled)return;const r=Ee.getSphere(t,n,!1);fr(r,s.x,s.y,s.z),r.material.color.set(i),r.material.depthTest=o,r.material.depthWrite=!1}static DrawWireBox(s,t,i=_s,n=0,o=!0){if(!ws.enabled)return;const r=Ee.getBox(n);r.position.set(s.x,s.y,s.z),r.scale.set(t.x,t.y,t.z),r.material.color.set(i),r.material.depthTest=o,r.material.wireframe=!0,r.material.depthWrite=!1,r.material.fog=!1}static DrawWireBox3(s,t=_s,i=0,n=!0){if(!ws.enabled)return;const o=Ee.getBox(i);o.position.copy(s.getCenter(zt)),o.scale.copy(s.getSize(zt)),o.material.color.set(t),o.material.depthTest=n,o.material.wireframe=!0,o.material.depthWrite=!1,o.material.fog=!1}static DrawArrow(s,t,i=_s,n=0,o=!0,r=!1){if(!ws.enabled)return;const l=Ee.getArrowHead(n);l.position.set(t.x,t.y,t.z),l.quaternion.setFromUnitVectors(this._up.set(0,1,0),zt.set(t.x,t.y,t.z).sub(Vb.set(s.x,s.y,s.z)).normalize());const c=zt.set(t.x,t.y,t.z).sub(Vb.set(s.x,s.y,s.z)).length()*.1;l.scale.set(c,c,c),l.material.color.set(i),l.material.depthTest=o,l.material.wireframe=r,this.DrawLine(s,t,i,n,o)}static DrawWireMesh(s){const t=Ee.getMesh(s.duration??0);"mesh"in s?(t.geometry=s.mesh.geometry,t.matrix.copy(s.mesh.matrixWorld)):(t.geometry=s.geometry,t.matrix.copy(s.matrix)),t.matrixAutoUpdate=!1,t.matrixWorldAutoUpdate=!1,t.material.color.set(s.color??_s),t.material.depthTest=s.depthTest??!0,t.material.wireframe=!0}static setVisible(s){for(const t of Ee.timedObjectsBuffer)t.visible=s}};let q=ws;a(q,"enabled",!0),a(q,"_up",new x(0,1,0));const t2=new Wl(1,1,1);function wg(s=null){const t=new ae(s??14540253),i=new gS(t2);return new Qy(i,new Yy({color:t}))}const xg=Symbol("GizmoCache");class Ee{static ensureFont(){let t=Re.FontLibrary.getFontFamily(this.familyName);if(!t){t=Re.FontLibrary.addFontFamily(this.familyName);const i=t.addVariant("normal","normal","https://uploads.needle.tools/include/font-msdf.json","https://uploads.needle.tools/include/font.png");i?.addEventListener("ready",()=>{Re.update()})}}static getTextLabel(t,i,n,o,r){this.ensureFont();let l=this.textLabelCache.pop(),c=1;r&&typeof r=="string"&&r?.length>=8&&r.startsWith("#")?(c=parseInt(r.substring(7),16)/255,r=r.substring(0,7),e2&&console.log(r,c)):typeof r=="object"&&r.a!==void 0&&(c=r.a);const h={boxSizing:"border-box",fontFamily:this.familyName,width:"auto",fontSize:n,color:o,lineHeight:1,backgroundColor:r??void 0,backgroundOpacity:c,textContent:i,borderRadius:.5*n,padding:.8*n,whiteSpace:"pre",offset:.05*n};if(l)l.set(h);else{l=new vv(h);const d=this,u=l;u.setText=function(p){this.set({textContent:p}),d.tmuiNeedsUpdate=!0}}return this.tmuiNeedsUpdate=!0,this.registerTimedObject(te.Current,l,t,this.textLabelCache),l}static getBox(t){let i=this.boxesCache.pop();if(!i){const n=new Wl(1,1,1);i=new Q(n)}return this.registerTimedObject(te.Current,i,t,this.boxesCache),i}static getLine(t){let i=this.linesCache.pop();if(!i){i=new Vl;let n=i.geometry.getAttribute("position");n||(n=new mt(new Float32Array(2*3),3),i.geometry.setAttribute("position",n))}return i.frustumCulled=!1,this.registerTimedObject(te.Current,i,t,this.linesCache),i}static getCircle(t){let i=this.circlesCache.pop();if(!i){i=new Vl;let n=i.geometry.getAttribute("position");if(!n){n=new mt(new Float32Array(_g*3),3),i.geometry.setAttribute("position",n);const o=$(0,1,0),r=$(0,0,1),l=$(r);l.cross(o).normalize();const c=$(l),h=Math.PI*2/(_g-1);for(let d=0;d<_g+1;d++){const u=h*d;o.copy(c).multiplyScalar(Math.cos(u)*1),l.copy(r).multiplyScalar(Math.sin(u)*1);const p=o.add(l);n.setXYZ(d,p.x,p.y,p.z)}}}return i.frustumCulled=!1,this.registerTimedObject(te.Current,i,t,this.circlesCache),i}static getSphere(t,i,n){let o=this.spheresCache.pop();return o||(o=new Q(new rd(1,8,8))),o.scale.set(t,t,t),o.material.wireframe=n,this.registerTimedObject(te.Current,o,i,this.spheresCache),o}static getArrowHead(t){let i=this.arrowHeadsCache.pop();return i||(i=new Q(new mS(0,.5,1,8))),this.registerTimedObject(te.Current,i,t,this.arrowHeadsCache),i}static getMesh(t){let i=this.mesh.pop();return i||(i=new Q,i.material=new Me),this.registerTimedObject(te.Current,i,t,this.mesh),i}static registerTimedObject(t,i,n,o){if(!t){console.error("No Needle Engine context available. Did you call a Gizmos function in global scope?");return}const r=this.contextBeforeRenderCallbacks.get(t),l=this.contextPostRenderCallbacks.get(t);if(r){if(t.pre_render_callbacks[t.pre_render_callbacks.length-1]!==r){const c=t.pre_render_callbacks.indexOf(r);c>=0&&t.pre_render_callbacks.splice(c,1),t.pre_render_callbacks.push(r)}}else{const c=()=>{this.onBeforeRender(t,this.timedObjectsBuffer)};this.contextBeforeRenderCallbacks.set(t,c),t.pre_render_callbacks.push(c)}if(l){if(t.post_render_callbacks[t.post_render_callbacks.length-1]!==l){const c=t.post_render_callbacks.indexOf(l);c>=0&&t.post_render_callbacks.splice(c,1),t.post_render_callbacks.push(l)}}else{const c=()=>{this.onPostRender(t,this.timedObjectsBuffer,this.timesBuffer)};this.contextPostRenderCallbacks.set(t,c),t.post_render_callbacks.push(c)}i.traverse(c=>{c.layers.disableAll(),c.layers.enable(2)}),i.renderOrder=999999,i[xg]=o,i.castShadow=!1,i.receiveShadow=!1,i.isGizmo=!0,this.timedObjectsBuffer.push(i),this.timesBuffer.push(te.Current.time.realtimeSinceStartup+n),t.scene.add(i)}static onBeforeRender(t,i){this.tmuiNeedsUpdate&&(this.tmuiNeedsUpdate=!1,Re.update());for(let n=0;n<i.length;n++){const o=i[n];if(t.mainCamera&&o instanceof Re.MeshUIBaseElement){if(Pr(o))continue;const r=t.isInVR,l=!1,c=!r;Kl(o,t.mainCamera,l,c)}}}static onPostRender(t,i,n){const o=t.time.realtimeSinceStartup;for(let r=i.length-1;r>=0;r--){const l=i[r];o>=n[r]-1e-6&&(i.splice(r,1),n.splice(r,1),l.removeFromParent(),Pr(l)!=!0&&l[xg].push(l))}}}a(Ee,"familyName","needle-gizmos"),a(Ee,"linesCache",[]),a(Ee,"circlesCache",[]),a(Ee,"spheresCache",[]),a(Ee,"boxesCache",[]),a(Ee,"arrowHeadsCache",[]),a(Ee,"mesh",[]),a(Ee,"textLabelCache",[]),a(Ee,"timedObjectsBuffer",new Array),a(Ee,"timesBuffer",new Array),a(Ee,"contextPostRenderCallbacks",new Map),a(Ee,"contextBeforeRenderCallbacks",new Map),a(Ee,"tmuiNeedsUpdate",!1);const Pi=O("debugphysics"),$b=new no;class Ns{constructor(){a(this,"ray"),a(this,"cam"),a(this,"screenPoint"),a(this,"raycaster"),a(this,"results"),a(this,"targets"),a(this,"recursive",!0),a(this,"minDistance"),a(this,"maxDistance"),a(this,"lineThreshold"),a(this,"layerMask"),a(this,"ignore"),a(this,"testObject"),a(this,"useAcceleratedRaycast")}screenPointFromOffset(t,i){this.screenPoint===void 0&&(this.screenPoint=new oe),this.screenPoint.x=t/window.innerWidth*2-1,this.screenPoint.y=-(i/window.innerHeight)*2+1}setLayer(t){$b.set(t),this.layerMask=$b}setMask(t){this.layerMask||(this.layerMask=new no);const i=this.layerMask;i?i.mask=t:this.layerMask=t}}a(Ns,"AllLayers",4294967295);class Sg{constructor(t,i,n){a(this,"distance"),a(this,"point"),a(this,"object"),this.object=t,this.distance=i,this.point=n}}const Cg=class{constructor(s){a(this,"context"),a(this,"engine"),a(this,"raycaster",new ld),a(this,"defaultRaycastOptions",new Ns),a(this,"targetBuffer",new Array(1)),a(this,"defaultThresholds",{Mesh:{},Line:{threshold:-1},LOD:{},Points:{threshold:0},Sprite:{}}),a(this,"sphereResults",new Array),a(this,"sphereMask",new no),a(this,"sphere",new ad),a(this,"tempBoundingBox",new vi),this.context=s}static get raycasting(){return this._raycasting>0}raycastPhysicsFast(s,t=void 0,i=1/0,n=!0){var o;return((o=this.context.physics.engine)==null?void 0:o.raycast(s,t,{maxDistance:i,solid:n}))??null}raycastPhysicsFastAndGetNormal(s,t=void 0,i=1/0,n=!0){var o;return((o=this.context.physics.engine)==null?void 0:o.raycastAndGetNormal(s,t,{maxDistance:i,solid:n}))??null}sphereOverlapPhysics(s,t){var i;return((i=this.context.physics.engine)==null?void 0:i.sphereOverlap(s,t))??null}sphereOverlap(s,t,i=!0,n=!1,o=null){if(this.sphereResults.length=0,!this.context.scene)return this.sphereResults;const r=this.sphereMask;r.enableAll(),r.disable(2);for(const l of this.context.scene.children)this.intersectSphere(l,s,t,r,this.sphereResults,i,n,o);return this.sphereResults.sort((l,c)=>l.distance-c.distance)}raycastFromRay(s,t=null){const i=t??this.defaultRaycastOptions;i.ray=s;const n=this.raycast(i);return i===this.defaultRaycastOptions&&(i.ray=void 0),n}raycast(s=null){Pi&&performance.mark("raycast.start"),s||(s=this.defaultRaycastOptions);const t=s.screenPoint??this.context.input.mousePositionRC,i=s.raycaster??this.raycaster;if(i.near=s.minDistance??0,i.far=s.maxDistance??1/0,i.params=this.defaultThresholds,s.lineThreshold===void 0&&(s.lineThreshold=-1),i.params.Line={threshold:s.lineThreshold},s.ray)i.ray.copy(s.ray);else{const l=s.cam??this.context.mainCamera;if(!l)return Pi&&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 fS&&c.cameras.length>0?i.setFromCamera(t,c.cameras[0]):i.setFromCamera(t,l)}let n=s.targets;n||(n=this.targetBuffer,n.length=1,n[0]=this.context.scene);let o=s.results;this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),o||(this.defaultRaycastOptions.results||(this.defaultRaycastOptions.results=new Array),o=this.defaultRaycastOptions.results),s.layerMask!==void 0?s.layerMask instanceof no?i.layers.mask=s.layerMask.mask:i.layers.mask=s.layerMask:(i.layers.enableAll(),i.layers.disable(2)),Pi&&console.time("raycast"),o.length=0,Cg._raycasting++,this.intersect(this.raycaster,n,o,s),o.sort((l,c)=>l.distance-c.distance);const r=s.ignore;return r!==void 0&&r.length>0&&(o=o.filter(l=>!r.includes(l.object))),Cg._raycasting--,Pi&&(console.timeEnd("raycast"),console.warn("#"+this.context.time.frame+", hits:",o!=null&&o.length?[...o]:"nothing"),performance.mark("raycast.end"),performance.measure("raycast","raycast.start","raycast.end")),o}intersect(s,t,i,n){var o,r,l;for(const c of t){if(!c||c.visible===!1||q.isGizmo(c)||n.lineThreshold!==void 0&&n.lineThreshold<0&&c instanceof Vl)continue;let h=!0;const d=c,u=d.geometry;if(n.testObject){const p=(o=n.testObject)==null?void 0:o.call(n,c);if(p===!1)continue;p==="continue in children"&&(h=!1)}if(h&&(u&&qb(u)||(h=!1)),h){const p=av(c);p&&(d.geometry=p);const g=i.length;let y=!0;if(n.precise===!1&&(y=!1),y||(y=((l=(r=u.getAttribute("position"))==null?void 0:r.array)==null?void 0:l.length)<64),d instanceof xa&&(y=!1),!y&&s2(d,s,i)||(n.useAcceleratedRaycast!==!1?Ld.runMeshBVHRaycast(s,d,i,this.context):s.intersectObject(d,!1,i)),Pi&&i.length!=g){const f=i[i.length-1],v=p?8969557:7798784;q.DrawWireSphere(f.point,.1,v,1,!1),q.DrawWireMesh({mesh:c,depthTest:!1,duration:.2,color:v})}d.geometry=u}n.recursive!==!1&&this.intersect(s,c.children,i,n)}return i}intersectSphere(s,t,i,n,o,r,l,c){let h=s&&s.isMesh&&s.layers.test(n)&&!q.isGizmo(s);h&&(h=s.visible),h&&(h=!(s instanceof Vl)),h&&(h=!(s instanceof xa));const d=s,u=d.geometry;if(h&&c){const p=c(s);if(p===!1)return;p==="continue in children"&&(h=!1)}if(u&&qb(u)||(h=!1),h){if(l){const p=this.sphere;p.center.copy(t),p.radius=i;const g=o.length;if(Ld.runMeshBVHRaycast(this.sphere,d,o,this.context),g!=o.length&&!r)return}else if(u.boundingBox||u.computeBoundingBox(),u.boundingBox){d.matrixWorldNeedsUpdate&&d.updateWorldMatrix(!1,!1);const p=this.tempBoundingBox.copy(u.boundingBox).applyMatrix4(d.matrixWorld),g=this.sphere;if(g.center.copy(t),g.radius=i,g.intersectsBox(p)){const y=ee(s),f=y.distanceTo(g.center),v=new Sg(s,f,y);if(o.push(v),!r)return}}}if(s.children)for(const p of s.children){const g=o.length;if(this.intersectSphere(p,t,i,n,o,r,l,c),g!=o.length&&!r)return}}};let Id=Cg;a(Id,"_raycasting",0);function qb(s){return!(s.index&&s.index.array.length<3)}const wr=new ad,jd=new dr,i2=new qy;function s2(s,t,i){const n=s._computeIntersections;if(!n)return!1;let o=s["_computeIntersections:Needle"];return o||(o=s["_computeIntersections:Needle"]=function(r,l,c){const h=this,d=h.geometry.boundingSphere;if(d){if(h instanceof xa){jd.setFromNormalAndCoplanarPoint($(0,1,0),$(0,-h.position.y,0)),jd.applyMatrix4(h.matrixWorld,i2);const p=r.ray.intersectPlane(jd,$());if(p){wr.copy(d),wr.applyMatrix4(h.matrixWorld);const g=$(p).sub(r.ray.origin).length(),y=wr.radius*.5;g<y&&l.push({distance:g,point:p,object:h,normal:jd.normal.clone()})}return}wr.copy(d),wr.applyMatrix4(h.matrixWorld);const u=r.ray.intersectSphere(wr,$());if(u){const p=$(u).sub(r.ray.origin),g=p.length();if(g>wr.radius){const y=p.clone().normalize();l.push({distance:g,point:u,object:h,normal:y})}}}}),s._computeIntersections=o,t.intersectObject(s,!1,i),s._computeIntersections=n,!0}var Ld;(s=>{function t(w,_,C,R){var M,E,D;if(!_.geometry||!_.geometry.hasAttribute("position"))return!1;const L=_.geometry;if(_!=null&&_.isSkinnedMesh){const U=_,z=U.bvhNeedsUpdate;if(!U.staticGenerator)c(),r&&(U.staticGenerator=new r(_),U.staticGenerator.applyWorldTransforms=!1,U.staticGeometry=U.staticGenerator.generate(),L.boundsTree=l?.call(U.staticGeometry),U.staticGeometryLastUpdate=performance.now()+Math.random()*200,U.autoUpdateMeshBVH===void 0&&(U.autoUpdateMeshBVH=!1));else if(L.boundsTree&&(U.autoUpdateMeshBVH===!0||z===!0)){const H=performance.now(),T=H-U.staticGeometryLastUpdate;(z||T>100)&&(U.bvhNeedsUpdate=!1,U.staticGeometryLastUpdate=H,(M=U.staticGenerator)==null||M.generate(U.staticGeometry),L.boundsTree.refit())}}else if(!L.boundsTree){d||b();let U=!0;if((R.xr||L[y]===!1||(E=L.getAttribute("position"))!=null&&E.isInterleavedBufferAttribute||L.index&&(D=L.index)!=null&&D.isInterleavedBufferAttribute)&&(U=!1),U&&p){if(L[g]===void 0){let z=null;if(v.length>0){const H=v.shift();H&&!H.running&&(z=H)}if(!z&&f.length<3&&(z=new p,f.push(z)),z!=null&&!z.running){const H=_.name;Pi&&console.log("<<<< worker start",H,z),L[g]="queued",performance.mark("bvh.create.start");const T=L.clone();try{z.generate(T).then(I=>{L[g]="done",L.boundsTree=I}).catch(I=>{L[g]="failed - "+I?.message,L[y]=!1,Pi&&console.error("Failed to generate mesh bvh on worker",I)}).finally(()=>{Pi&&console.log(">>>>> worker done",H,{hasBoundsTre:L.boundsTree!=null}),v.push(z),T.dispose(),performance.mark("bvh.create.end"),performance.measure("bvh.create (worker)","bvh.create.start","bvh.create.end")})}catch(I){console.error("Failed to generate mesh bvh on worker",I)}}else Pi&&console.warn("No worker available")}}else(!u||!U)&&(c(),o&&(performance.mark("bvh.create.start"),L.boundsTree=new o(L),performance.mark("bvh.create.end"),performance.measure("bvh.create","bvh.create.start","bvh.create.end")))}if(w instanceof ld){const U=w,z=_.raycast;L.boundsTree?(c(),n&&(_.acceleratedRaycast||(_.acceleratedRaycast=n.bind(_),Pi&&console.debug(`Physics: bind acceleratedRaycast fn to "${_.name}"`)),_.raycast=_.acceleratedRaycast)):Pi&&console.warn("No bounds tree found for mesh",_.name,{workerTask:L[g],hasAcceleratedRaycast:n!=null});const H=U.firstHitOnly;return U.firstHitOnly=!1,U.intersectObject(_,!1,C),U.firstHitOnly=H,_.raycast=z,!0}else if(w instanceof ad){const U=L.boundsTree;if(U){const z=w;if(h.copy(_.matrixWorld).invert(),z.applyMatrix4(h),U.intersectsSphere(z)){const H=ee(_),T=H.distanceTo(z.center),I=new Sg(_,T,H);C.push(I)}}return!0}return!1}s.runMeshBVHRaycast=t;let i=!1,n=null,o=null,r=null,l=null;function c(){i||(i=!0,import("./vendor.light.min.js").then(w=>w.k).then(w=>{n=w.acceleratedRaycast,o=w.MeshBVH,r=w.StaticGeometryGenerator,l=w.computeBoundsTree}).catch(w=>{(Pi||F())&&console.error("Failed to load BVH library...",w.message)}))}const h=new ne;let d=!1,u=!1,p=null;const g=Symbol("Needle:MeshBVH-Worker"),y=Symbol("Needle:MeshBVH-CanUseWorker"),f=[],v=[];function b(){d=!0,u=!0,Promise.resolve().then(()=>Gj).then(w=>{p=w.GenerateMeshBVHWorker}).catch(w=>{(Pi||F())&&console.warn("Failed to setup mesh bvh worker")}).finally(()=>{u=!1})}})(Ld||(Ld={}));const Gb=Symbol("gltf-loader-internal-usage-tracker"),n2=O("debugusers"),Dd=class{constructor(s){a(this,"parser"),a(this,"_getDependency"),a(this,"_loadingId"),a(this,"_loadedObjects",new Set),this.parser=s,this._getDependency=this.parser.getDependency,this._loadingId=Date.now().toString()}get name(){return"NEEDLE_internal_usage_tracker"}static isLoading(s){return Dd._loadingProcesses>0}beforeRoot(){Dd._loadingProcesses++;const s=this,t=this._getDependency;return this.parser.getDependency=function(i,n){const o=t.call(this,i,n);return o.then(r=>(r&&(s._loadedObjects.add(r),r[Gb]=s._loadingId),r)),o},null}afterRoot(s){Dd._loadingProcesses--,this.parser.getDependency=this._getDependency;for(const t of this._loadedObjects)delete t[Gb],t instanceof j&&(t.parent||t instanceof Q&&setTimeout(()=>{n2&&console.warn("> GLTF LOADER: Mesh not used in scene!",t),t.material=null,t.geometry=null},1e3));return null}};let Og=Dd;a(Og,"_loadingProcesses",0);class Xb{constructor(){window.addEventListener("unhandledrejection",t=>{var i;if(t.defaultPrevented)return;const n=(i=t?.reason)==null?void 0:i.path;if(n){const o=n[0];o&&o.tagName==="IMG"&&(console.warn(`Could not load image:
155
+ `+o.src),t.preventDefault())}})}}const Bd=O("trackresources");function Qb(){return Bd==="dispose"}let xr=!0;Bd===0&&(xr=!1);function o2(s){xr=s}function Yb(){return xr}const Kb=Symbol("disposable");function Pg(s,t){s&&(s[Kb]=t,Sr&&console.warn("Set disposable",t,s))}const Zb=Symbol("disposed");function r2(s){return s[Zb]===!0}function Te(s){var t;if(s){if(s[Kb]===!1){Sr&&console.warn("Object is marked as not disposable",s);return}if(s[Zb]=!0,s instanceof $i)Te(s.environment),Te(s.background),Te(s.customDepthMaterial),Te(s.customDistanceMaterial);else if(s instanceof bn)Te(s.geometry),Te(s.material),Te(s.skeleton),Te(s.bindMatrix),Te(s.bindMatrixInverse),Te(s.customDepthMaterial),Te(s.customDistanceMaterial),s.geometry=null,s.material=null,s.visible=!1;else if(s instanceof Q)Te(s.geometry),Te(s.material),Te(s.customDepthMaterial),Te(s.customDistanceMaterial),s.geometry=null,s.material=null,s.visible=!1;else if(s instanceof oo){Aa(s);for(const i of Object.keys(s.attributes)){const n=s.attributes[i];Te(n)}}else if(s instanceof mt||s instanceof Ky)Sr&&console.warn("BufferAttribute dispose not supported",s.count);else if(s instanceof Array)for(const i of s)i instanceof Oe&&Te(i);else if(s instanceof Oe){Aa(s);for(const n of Object.keys(s)){const o=s[n];o instanceof Ne&&(Te(o),s[n]=null)}const i=s.uniforms;if(i)for(const n of Object.keys(i)){const o=i[n];o instanceof Ne?(Te(o),i[n]=null):o instanceof so&&(Te(o.value),o.value=null)}}else s instanceof Ne?(Aa(s),Aa(s.source),((t=s.source)==null?void 0:t.data)instanceof ImageBitmap&&Aa(s.source.data)):s instanceof yS?(Aa(s.boneTexture),s.boneTexture=null):s instanceof vS||!(s instanceof j)&&Sr&&console.warn("Unknown object type",s)}}function Aa(s){s&&((Sr||Qb()||Bd)&&console.warn("\u{1F9E8} FREE",s),s instanceof ImageBitmap?s.close():s instanceof bS?s.data=null:s.dispose())}function Jb(s){(s instanceof Q||s instanceof bn)&&(s.material=null,s.geometry=null)}const a2=new Set;function kg(s,t,i=null,n){if(n||(n=a2,n.clear()),!s)return n;const o=s[dc];if(o)for(const r of o)n.has(r)||i?.call(null,r)!==!1&&(n.add(r),t&&kg(r,!0,i,n));return n}function l2(s){return s[uc]}const Sr=O("debugresourceusers")||O("debugmemory"),dc=Symbol("needle-resource-users"),uc=Symbol("needle-resource-users-count");function Xt(s,t){Od(s,t,function(i,n){xr&&!Id.raycasting&&(Fd(dc,this,i,!1),Fd(dc,this,n,!0))})}xr&&(Xt(Q.prototype,"material"),Xt(Q.prototype,"geometry"),Xt(Oe.prototype,"map"),Xt(Oe.prototype,"bumpMap"),Xt(Oe.prototype,"alphaMap"),Xt(Oe.prototype,"normalMap"),Xt(Oe.prototype,"displacementMap"),Xt(Oe.prototype,"roughnessMap"),Xt(Oe.prototype,"metalnessMap"),Xt(Oe.prototype,"emissiveMap"),Xt(Oe.prototype,"specularMap"),Xt(Oe.prototype,"envMap"),Xt(Oe.prototype,"lightMap"),Xt(Oe.prototype,"aoMap"),Xt(Oe.prototype,"gradientMap"));function c2(s){if(xr===!1)return;const t=s[dc];if(t)for(const i of t)Fd(dc,i,s,!1)}xr&&Od(Oe.prototype,"dispose",function(){c2(this)});let Mg=0;function Fd(s,t,i,n){if(Mg>0)return;if(Array.isArray(i)){for(const r of i)Fd(s,t,r,n);return}if(!i)return;let o=i[s];if(o||(o=new Set),n){if(t&&!o.has(t)){o.add(t);let r=i[uc]||0;r+=1,i[uc]=r,Sr&&console.warn(`\u{1F7E2} Added user of "${i.type}"`,t,i,r,"users:",o)}}else if(t&&o.has(t)){o.delete(t);let r=i[uc]||0;r>0&&(r-=1,i[uc]=r),Sr&&console.warn(`\u{1F534} Removed user of "${i.type}"`,t,i,r,"users:",o),r<=0&&(Og.isLoading(i)||(Bd&&console.warn(`\u{1F534} Removed all user of "${i.type}"`,i),Qb()&&Te(i)))}i[s]=o}try{Od(cr.prototype,"render",function(){Mg++},function(){Mg--})}catch(s){console.warn("Could not wrap WebGLRenderer.render",s)}const e_=O("debugcomponentevents");class pc{static addComponentLifecylceEventListener(t,i){this.eventListeners.has(t)&&this.eventListeners.set(t,[]);let n=this.eventListeners.get(t);n||(n=[]),n.push(i),this.eventListeners.set(t,n),e_&&console.log("Added event listener for "+t,this.eventListeners)}static removeComponentLifecylceEventListener(t,i){const n=this.eventListeners.get(t);if(!n)return;const o=n.indexOf(i);o<0||n.splice(o,1)}static dispatchComponentLifecycleEvent(t,i){const n=this.eventListeners.get(t);if(e_&&console.log("Dispatching event "+t,n),!!n)for(const o of n)o(i)}}a(pc,"eventListeners",new Map);const mc=Symbol("NEEDLE_NEED_UPDATE_INSTANCE"),t_=Symbol("isUsingInstancing"),i_=Symbol("instancingRenderer"),gc=Symbol("instancingAutoUpdateBounds");class cs{static isUsingInstancing(t){return t[t_]===!0}static getRenderer(t){return t[i_]||null}setAutoUpdateBounds(t,i){const n=cs.getRenderer(t);n&&(n[gc]=i)}static markDirty(t,i=!0){if(t&&(this.isUsingInstancing(t)&&(t[mc]=!0,t.matrixWorldNeedsUpdate=!0),i))for(const n of t.children)cs.markDirty(n,!0)}}function Ia(s,t){try{t?s(t):s()}catch(i){return console.error(i),!1}return!0}const Rg=O("debugnewscripts"),h2=O("debughierarchy"),Be=[];function d2(){return Be.length>0}function zd(s){if(!(s.new_scripts.length<=0)){if(Rg&&console.log("Register new components",s.new_scripts.length,[...s.new_scripts],s.alias?"element: "+s.alias:s.hash,s),s.new_scripts_pre_setup_callbacks.length>0){for(const t of s.new_scripts_pre_setup_callbacks)t&&t();s.new_scripts_pre_setup_callbacks.length=0}Be.length=0,s.new_scripts.length>0&&Be.push(...s.new_scripts),s.new_scripts.length=0;for(let t=0;t<Be.length;t++)try{const i=Be[t];if(i.isComponent!==!0){(F()||Rg)&&console.error(`Registered script is not a Needle Engine component.
156
156
  The script will be ignored. Please make sure your component extends "Behaviour" imported from "@needle-tools/engine"
157
157
  `,i),Be.splice(t,1),t--;continue}if(i.destroyed)continue;if(!i.gameObject){console.warn(`Component can not be initialized: no GameObject assigned.
158
- Did you add and remove a component in the same frame?`),Be.splice(t,1),t--;continue}i.context=s,fc(i.gameObject),Tg(i,s)}catch(i){console.error(i),On(Be[t],s),Be.splice(t,1),t--}for(let t=0;t<Be.length;t++)try{const i=Be[t];if(i.destroyed){On(Be[t],s),Be.splice(t,1),t--;continue}if(i.registering)try{i.registering()}catch(n){console.error(n)}i.__internalAwake!==void 0&&(i.gameObject||console.error("Calling awake for a component without a GameObject",i,i.gameObject),fc(i.gameObject),i.activeAndEnabled&&Ia(i.__internalAwake.bind(i)))}catch(i){console.error(i),On(Be[t],s),Be.splice(t,1),t--}for(let t=0;t<Be.length;t++)try{const i=Be[t];if(i.destroyed||i.enabled===!1||(fc(i.gameObject),i.activeAndEnabled===!1))continue;i.__internalEnable!==void 0&&(i.enabled=!0,Ia(i.__internalEnable.bind(i)))}catch(i){console.error(i),On(Be[t],s),Be.splice(t,1),t--}for(let t=0;t<Be.length;t++)try{const i=Be[t];if(i.destroyed||!i.gameObject)continue;s.new_script_start.push(i)}catch(i){console.error(i),On(Be[t],s),Be.splice(t,1),t--}Be.length=0;for(const t of s.new_scripts_post_setup_callbacks)t&&t();s.new_scripts_post_setup_callbacks.length=0}}function uk(s){s&&(s.__internalDisable(!0),On(s,s.context))}function s_(s,t){for(let i=0;i<s.new_script_start.length;i++)try{const n=s.new_script_start[i];if(t!==void 0&&n.gameObject!==t||n.destroyed||n.activeAndEnabled===!1)continue;Ia(n.__internalAwake.bind(n)),n.enabled&&(Ia(n.__internalEnable.bind(n)),Ia(n.__internalStart.bind(n)),s.new_script_start.splice(i,1),i--)}catch(n){console.error(n),On(s.new_script_start[i],s),s.new_script_start.splice(i,1),i--}}function Tg(s,t){t.scripts.indexOf(s)===-1&&(t.scripts.push(s),s.earlyUpdate&&t.scripts_earlyUpdate.push(s),s.update&&t.scripts_update.push(s),s.lateUpdate&&t.scripts_lateUpdate.push(s),s.onBeforeRender&&t.scripts_onBeforeRender.push(s),s.onAfterRender&&t.scripts_onAfterRender.push(s),s.onPausedChanged&&t.scripts_pausedChanged.push(s),Eg(s,null)&&t.new_scripts_xr.push(s),Eg(s,"immersive-vr")&&t.scripts_immersive_vr.push(s),Eg(s,"immersive-ar")&&t.scripts_immersive_ar.push(s))}function On(s,t){Yi(s,t.new_scripts),Yi(s,t.new_script_start),Yi(s,t.scripts),Yi(s,t.scripts_earlyUpdate),Yi(s,t.scripts_update),Yi(s,t.scripts_lateUpdate),Yi(s,t.scripts_onBeforeRender),Yi(s,t.scripts_onAfterRender),Yi(s,t.scripts_pausedChanged),Yi(s,t.new_scripts_xr),Yi(s,t.scripts_immersive_vr),Yi(s,t.scripts_immersive_ar),t.stopAllCoroutinesFrom(s)}function Yi(s,t){const i=t.indexOf(s);i>=0&&t.splice(i,1)}function Eg(s,t){var i;if(s){const n=s;if(n.onBeforeXR||n.onEnterXR||n.onUpdateXR||n.onLeaveXR||n.onXRControllerAdded||n.onXRControllerRemoved)return!(t!=null&&((i=n.supportsXR)==null?void 0:i.call(n,t))===!1)}return!1}function Ud(s){if(s||(s=ge.Current.scene),!s){console.trace("Invalid call - no current context.");return}const t=Ba(s);n_(s,t,!0)||(Rg||F()?console.error(`Error updating hierarchy
159
- Do you have circular references in your project? <a target="_blank" href="https://docs.needle.tools/circular-reference"> Click here for more information.`,s):console.error('Failed to update active state in hierarchy of "'+s.name+'"',s),console.warn(" \u2191 this error might be caused by circular references. Please make sure you don't have files with circular references (e.g. one GLB 1 is loading GLB 2 which is then loading GLB 1 again)."))}function n_(s,t,i,n=0){if(n>1e3)return console.warn("Hierarchy is too deep (> 1000 level) - will abort updating active state"),!1;const o=Ba(s);if(t&&(t=o,t&&s.parent)){const c=s.parent;t=c[xn],t===void 0&&(c instanceof $i||(t=!0))}const r=s[xn]!==t;s[xn]=t,r&&(hk&&console.warn("ACTIVE CHANGE",s.name,o,s.visible,t,"changed?"+r,s),i&&pk(s,c=>{t?c.enabled&&(Ia(c.__internalAwake.bind(c)),c.enabled&&(c.__didEnable=!0,c.onEnable())):c.__didAwake&&c.enabled&&(c.__didEnable=!1,c.onDisable())}));let l=!0;if(s.children){const c=n+1;for(const h of s.children)n_(h,t,i,c)===!1&&(l=!1)}return l}function fc(s){let t=!0,i=s,n=!1;for(;i&&i;){if(i.type==="Scene"&&(n=!0),!Ba(i)){t=!1;break}i=i.parent}if(!s){console.error("GO is null");return}s[xn]=t&&n}function pk(s,t){var i;if((i=s.userData)!=null&&i.components)for(const n of s.userData.components)t(n)}const Nd=new Map,o_=Symbol("prewarmFlag"),Ag=Symbol("waitingForPrewarm"),Ig=O("debugprewarm");function mk(s,t){!s||s[o_]===!0||s[Ag]===!0||(Nd.has(t)||Nd.set(t,[]),s[Ag]=!0,Nd.get(t).push(s),Ig&&console.debug("register prewarm",s.name))}let jg=null,Lg=null;function gk(s){if(!s)return;const t=Nd.get(s);if(!(t!=null&&t.length))return;const i=s.mainCamera;if(i){Ig&&console.log("prewarm",t.length,"objects",[...t]);const n=s.renderer;if(n.compile){const o=s.scene;n.compile(o,i),jg??(jg=new _S(64)),Lg??(Lg=new wS(.001,9999999,jg)),Lg.update(n,o);for(const r of t)r[o_]=!0,r[Ag]=!1;t.length=0,Ig&&console.log("prewarm done")}}}ge.registerCallback(fe.ContextCreated,s=>{const t=s.context;d_(t),l_(t)});const Wd=O("debugcomponents"),r_="eff8ba80-635d-11ec-90d6-0242ac120003";class Bt{constructor(t){a(this,"_originalSeed"),a(this,"_seed"),typeof t=="string"&&(t=Bt.hash(t)),this._originalSeed=t,this._seed=t}get seed(){return this._seed}set seed(t){this._seed=t}reset(){this._seed=this._originalSeed}generateUUID(t){if(typeof t=="string")return mv(t,r_);const i=this._seed;return this._seed-=1,mv(i.toString(),r_)}initialize(t){typeof t=="string"?this._seed=Bt.hash(t):this._seed=t}static createFromString(t){return new Bt(this.hash(t))}static hash(t){let i=0;for(let n=0;n<t.length;n++)i=t.charCodeAt(n)+((i<<5)-i);return i}}var a_=(s=>(s.NewInstanceCreated="new-instance-created",s.InstanceDestroyed="instance-destroyed",s))(a_||{});class fk{constructor(t){a(this,"guid"),a(this,"dontSave"),this.guid=t}}function yc(s,t,i=!0,n){if(!s)return;const o=s;if(Mi(s,i),!t){console.warn("Can not send destroy: No networking connection provided",s.guid);return}if(!t.isConnected){F()&&console.debug("Can not send destroy: not connected",s.guid);return}let r=s.guid;if(!r&&o.uuid&&(r=o.uuid),!r){console.warn("Can not send destroy: failed to find guid",s);return}Dg(r,t,n)}function Dg(s,t,i){const n=new fk(s);i?.saveInRoom===!1&&(n.dontSave=!0),t.send("instance-destroyed",n,bs.Queued)}function l_(s){s.connection.beginListen("instance-destroyed",t=>{Wd&&console.log("[Remote] Destroyed",s.scene,t);const i=Gg(t.guid,s.scene);i&&Mi(i)})}class yk{constructor(t,i,n){a(this,"filename"),a(this,"hash"),a(this,"size"),this.filename=t,this.hash=i,this.size=n}}class c_{constructor(t,i){a(this,"guid"),a(this,"originalGuid"),a(this,"seed"),a(this,"visible"),a(this,"hostData"),a(this,"dontSave"),a(this,"parent"),a(this,"position"),a(this,"rotation"),a(this,"scale"),a(this,"preventCreation"),a(this,"deleteStateOnDisconnect"),this.originalGuid=t,this.guid=i}}function Bg(s,t,i,n){var o,r;const l=s;if(!l.guid)return console.warn("Can not instantiate: No guid",l),null;if(t.context||(t.context=te.Current),!t.context)return console.error("Missing network instantiate options / reference to network connection in sync instantiate"),null;const c=t?{...t}:null,{instance:h,seed:d}=vk(l,t);if(h){const u=h;if(u.guid){Wd&&console.log("[Local] new instance","gameobject:",h?.guid);const p=new c_(l.guid,u.guid);p.seed=d,t.deleteOnDisconnect===!0&&(p.deleteStateOnDisconnect=!0),c&&(c.position&&(p.position={x:c.position.x,y:c.position.y,z:c.position.z}),c.rotation&&(p.rotation={x:c.rotation.x,y:c.rotation.y,z:c.rotation.z,w:c.rotation.w}),c.scale&&(p.scale={x:c.scale.x,y:c.scale.y,z:c.scale.z})),p.position||(p.position={x:u.position.x,y:u.position.y,z:u.position.z}),p.rotation||(p.rotation={x:u.quaternion.x,y:u.quaternion.y,z:u.quaternion.z,w:u.quaternion.w}),p.scale||(p.scale={x:u.scale.x,y:u.scale.y,z:u.scale.z}),p.visible=l.visible,c!=null&&c.parent&&(typeof c.parent=="string"?p.parent=c.parent:p.parent=c.parent.guid),p.hostData=i,n===!1&&(p.dontSave=!0),!((o=t?.context)!=null&&o.connection)&&F()&&console.debug("Object will be instantiated but it will not be synced: not connected",l.guid),t.context.connection.isInRoom&&ja.push(new WeakRef(u)),(r=t?.context)==null||r.connection.send("new-instance-created",p)}else console.warn("Missing guid, can not send new instance event",u)}return h}function h_(){return Math.random()*9999999}const ja=new Array;function d_(s){s.connection.beginListen("new-instance-created",async t=>{const i=await bk(t.originalGuid,s.scene);if(t.preventCreation===!0)return;if(!i){console.warn("could not find object that was instantiated: "+t.guid);return}const n=new js;t.position&&(n.position=new x(t.position.x,t.position.y,t.position.z)),t.rotation&&(n.rotation=new V(t.rotation.x,t.rotation.y,t.rotation.z,t.rotation.w)),t.scale&&(n.scale=new x(t.scale.x,t.scale.y,t.scale.z)),n.parent=t.parent,t.seed&&(n.idProvider=new Bt(t.seed)),n.visible=t.visible,n.context=s,Wd&&s.alias&&console.log("[Remote] instantiate in: "+s.alias);const o=za(i,n);ja.push(new WeakRef(o)),o&&(t.parent==="scene"&&s.scene.add(o),Wd&&console.log("[Remote] new instance","gameobject:",o?.guid,i))}),s.connection.beginListen("left-room",()=>{ja.length>0&&console.debug(`Left networking room, cleaning up ${ja.length} instantiated objects`);for(const t of ja){const i=t.deref();i&&i.destroy()}ja.length=0})}function vk(s,t){const i=h_(),n=t??new js;n.idProvider=new Bt(i);const o=za(s,n);return{seed:i,instance:o}}const u_={};function p_(s,t){u_[s]=t}async function bk(s,t){const i=u_[s];if(i!=null){const n=await i(s);if(n)return n}return m_(s,t)}function m_(s,t){if(t===null||!s)return null;if(t.guid===s)return t;if(t.children)for(const i of t.children){const n=m_(s,i);if(n)return n}return null}const vc=O("gizmos"),ft=O("debugextension"),Fg=O("debugtypes");class _k{constructor(){a(this,"_types",new Map),Fg&&console.warn("TypeStore: Created",this)}add(t,i){Fg&&console.warn("ADD TYPE",t);const n=this._types.get(t);n?Fg&&n!==i&&console.warn("Type name exists multiple times in your project and may lead to runtime errors:",t):this._types.set(t,i)}get(t){return this._types.get(t)||null}getKey(t){for(const[i,n]of this._types)if(n===t)return i;return null}}const wk=Symbol("BuiltInType"),S=new _k,xk=function(s){S.get(s.name)||S.add(s.name,s)},zg=O("debugresolvedependencies"),Sk=["/extensions/","extensions/"],Ck=[{prefix:"/nodes/",dependencyName:"node"},{prefix:"/meshes/",dependencyName:"mesh"},{prefix:"/materials/",dependencyName:"material"},{prefix:"/textures/",dependencyName:"texture"},{prefix:"/animations/",dependencyName:"animation"},{prefix:"nodes/",dependencyName:"node"},{prefix:"meshes/",dependencyName:"mesh"},{prefix:"materials/",dependencyName:"material"},{prefix:"textures/",dependencyName:"texture"},{prefix:"animations/",dependencyName:"animation"}];async function Ug(s,t){zg&&console.log(s,t);const i=[];Ng(Ck,s,t,i);const n=await Promise.all(i);return typeof t=="string"&&n.length===1?n[0]:n}function g_(s,t){return!s||!t?!1:s["needle:identifier"]!=null&&t["needle:identifier"]!=null?s["needle:identifier"]===t["needle:identifier"]:!1}function Ok(s,t){s["needle:identifier"]=t}function Ng(s,t,i,n){if(typeof i=="object"&&i!==void 0&&i!==null)for(const o of Object.keys(i)){const r=i[o];if(typeof r=="string"){const l=f_(t,r);if(l!=null)typeof l.then=="function"?n.push(l.then(c=>i[o]=c)):i[o]=l;else{const c=y_(s,t,r);if(c){n.push(c.then(h=>(i[o]=h,h)));continue}}}else if(Array.isArray(r))for(let l=0;l<r.length;l++){const c=r[l],h=f_(t,c);if(h!==null){typeof h.then=="function"?n.push(h.then(d=>r[l]=d)):r[l]=h;continue}for(const d of s){const u=v_(d.prefix,c);if(u>=0){zg&&console.log(d,u,d.dependencyName),n.push(t.getDependency(d.dependencyName,u).then(p=>r[l]=p));break}}typeof c=="object"&&Ng(s,t,c,n)}else typeof r=="object"&&Ng(s,t,r,n)}else if(typeof i=="string"){const o=y_(s,t,i);o&&n.push(o)}}function f_(s,t){if(s&&s.plugins&&typeof t=="string"){for(const i of Sk)if(t.startsWith(i)){let n=t.substring(i.length);const o=n.indexOf("/");o>=0&&(n=n.substring(0,o));const r=s.plugins[n];if(ft&&console.log(n,r),typeof r?.resolve=="function"){const l=t.substring(i.length+n.length+1);return r.resolve(s,l)}break}}return null}function y_(s,t,i){for(const n of s){const o=v_(n.prefix,i);if(o>=0)return zg&&console.warn("GET DEPENDENCY",n,o,n.dependencyName),t.getDependency(n.dependencyName,o)}return null}function v_(s,t){if(typeof t=="string"&&t.startsWith(s)){const i=t.substring(s.length),n=Number.parseInt(i);if(n>=0)return n}return-1}const Wg="NEEDLE_persistent_assets";function Pk(s){return s?.___persistentAsset===!0}class kk{constructor(t){a(this,"parser"),this.parser=t}get name(){return Wg}async afterRoot(t){var i,n;if(!((n=(i=this.parser)==null?void 0:i.json)!=null&&n.extensions))return;const o=this.parser.json.extensions[Wg];if(!o)return;ft&&console.log(o);const r=new Array;for(const l of o?.assets){const c=Ug(this.parser,l);c&&r.push(c)}await Promise.all(r)}resolve(t,i){const n=Number.parseInt(i);if(n>=0){ft&&console.log(i);const o=t.json.extensions[Wg];if(o){const r=o?.assets[n];if(r&&typeof r=="object"){r.___persistentAsset=!0;const l=r.__type;l&&S.get(l)}return r}}return null}}const Ws=O("debugserializer");class Mk{constructor(){a(this,"typeMap",new Map)}register(t,i){if(this.typeMap.has(t)){const n=this.typeMap.get(t);if(n===i)return;Ws&&console.warn("Type: "+t+" is already registered",i,n)}Ws&&console.log("Register type serializer",i.name,i,t),this.typeMap.set(t,i)}getSerializer(t){if(t)return this.typeMap.get(t)}getSerializerForConstructor(t,i=0){if(i>20)return;if(!t||!t.constructor){Ws&&console.log("invalid type");return}const n=t.name,o=this.getSerializer(t);if(o!==void 0)return Ws&&console.log("FOUND SERIALIZER",o?.name,t.name,t.constructor.name,"for type: "+n,o,t,this.typeMap),o;const r=Object.getPrototypeOf(t);if(r&&r!==t){const l=this.getSerializerForConstructor(r,++i);if(l){const c=r.constructor||r.prototype;Ws&&console.log("FOUND SERIALIZER(in constructor) "+c.constructor.name,c.name,c,l),this.register(c,l)}return l}Ws&&console.warn("No serializer found for "+n,t,t.name,t.constructor.name)}}const Vd=new Mk;class Ki{constructor(t,i){if(a(this,"name"),this.name=i,Array.isArray(t))for(const n of t)Vd.register(n,this);else Vd.register(t,this)}}class Rk{constructor(){a(this,"isDevMode",Gt()),a(this,"cache",{})}registerDefinedKeys(t,i){if(this.isDevMode&&this.cache[t]===void 0){this.cache[t]=Object.keys(i);const n=i;n.$serializedTypes&&Object.keys(n.$serializedTypes)&&this.cache[t].push(...Object.keys(n.$serializedTypes)),Ws&&console.log("registerDefinedKeys for "+t,this.cache[t],i)}}getDefinedKey(t,i){return this.cache[t]===void 0?!1:this.cache[t].includes(i)}}class Vg{constructor(t){a(this,"root"),a(this,"gltf"),a(this,"gltfId"),a(this,"object"),a(this,"target"),a(this,"nodeId"),a(this,"nodeToObject"),a(this,"objectToNode"),a(this,"context"),a(this,"path"),a(this,"type"),a(this,"serializable"),a(this,"implementationInformation"),this.root=t}}function b_(s,t){const i=s.$serializedTypes;if(i===void 0)return null;const n={};for(const r in i){const l=s[r];if(l!=null&&typeof l=="object"){const c=Vd.getSerializerForConstructor(l);if(c){n[r]=c.onSerialize(l,t);continue}}n[r]=l}function o(r){const l=S._types;for(const[c,h]of l)if(h===s.constructor)return c;return r.__name||r.constructor.name}return n.name=o(s),typeof s.guid=="string"&&(n.guid=s.guid),n}const Hd=[];function __(s,t){if(!s)return t;typeof s.$serializedTypes=="object"&&(t||(t={}),Object.assign(t,s.$serializedTypes));const i=Object.getPrototypeOf(s);return __(i,t)}function $d(s,t,i){if(!s)return!1;if(i.target=s,s.onBeforeDeserialize!==void 0){const o=s.onBeforeDeserialize(t,i);if(typeof o=="boolean")return o}const n=__(s);if(t){if(typeof t.guid=="string"&&(s.guid=t.guid),n)for(const o in n){let r=function(h){const d=h.type;return d?Hg(c,d,i,void 0,s[o]):Hg(c,h,i,void 0,s[o])};const l=n[o],c=t[o];if(Ws&&console.log(o,c,s,l),!(s[o]!==void 0&&c===void 0)&&(i.type=void 0,i.path=o,i.serializable=l,!(s.onBeforeDeserializeMember!==void 0&&s.onBeforeDeserializeMember(o,c,i)===!0))){if(l===null)s[o]=c;else{if(Array.isArray(l))for(let h=0;h<l.length;h++){const d=l[h],u=r(d);if(u!==void 0||h===l.length-1){s[o]=u;break}}else s[o]=r(l);Hd.length=0}s.onAfterDeserializeMember!==void 0&&s.onAfterDeserializeMember(o,c,i)}}Ak(s,t)}return Ek(s,t,i.implementationInformation),s.onAfterDeserialize!==void 0&&s.onAfterDeserialize(t,i),!0}const Tk=O("noerrors");function Ek(s,t,i){var n,o;if(Tk||!t||!Gt()||!s||s.constructor&&s.constructor[wk]===!0)return;const r=(n=s.constructor)==null?void 0:n.name,l=Object.getOwnPropertyNames(t);for(const c of l){if(c==="sourceId")continue;const h=s[c];if(h==null)continue;const d=t[c];if(i?.getDefinedKey(r,c)===!1){const u=c.charAt(0).toUpperCase()+c.slice(1);i.getDefinedKey(r,u)&&(Bs(xi.Warn,'<strong>Please rename</strong> "'+u+'" to "'+c+'" in '+r),console.warn('Please use lowercase for field: "'+u+'" in '+r,d,s));continue}if(d!=null){if(typeof d=="object"&&(h===void 0||!h.isObject3D)){if(typeof d.node=="number"||typeof d.guid=="string"){if(d.could_not_resolve)continue;if(!(h!==void 0&&Object.keys(h).length>1)){Bs(xi.Warn,`<strong>Missing serialization for object reference!</strong>
158
+ Did you add and remove a component in the same frame?`),Be.splice(t,1),t--;continue}i.context=s,fc(i.gameObject),Tg(i,s)}catch(i){console.error(i),On(Be[t],s),Be.splice(t,1),t--}for(let t=0;t<Be.length;t++)try{const i=Be[t];if(i.destroyed){On(Be[t],s),Be.splice(t,1),t--;continue}if(i.registering)try{i.registering()}catch(n){console.error(n)}i.__internalAwake!==void 0&&(i.gameObject||console.error("Calling awake for a component without a GameObject",i,i.gameObject),fc(i.gameObject),i.activeAndEnabled&&Ia(i.__internalAwake.bind(i)))}catch(i){console.error(i),On(Be[t],s),Be.splice(t,1),t--}for(let t=0;t<Be.length;t++)try{const i=Be[t];if(i.destroyed||i.enabled===!1||(fc(i.gameObject),i.activeAndEnabled===!1))continue;i.__internalEnable!==void 0&&(i.enabled=!0,Ia(i.__internalEnable.bind(i)))}catch(i){console.error(i),On(Be[t],s),Be.splice(t,1),t--}for(let t=0;t<Be.length;t++)try{const i=Be[t];if(i.destroyed||!i.gameObject)continue;s.new_script_start.push(i)}catch(i){console.error(i),On(Be[t],s),Be.splice(t,1),t--}Be.length=0;for(const t of s.new_scripts_post_setup_callbacks)t&&t();s.new_scripts_post_setup_callbacks.length=0}}function u2(s){s&&(s.__internalDisable(!0),On(s,s.context))}function s_(s,t){for(let i=0;i<s.new_script_start.length;i++)try{const n=s.new_script_start[i];if(t!==void 0&&n.gameObject!==t||n.destroyed||n.activeAndEnabled===!1)continue;Ia(n.__internalAwake.bind(n)),n.enabled&&(Ia(n.__internalEnable.bind(n)),Ia(n.__internalStart.bind(n)),s.new_script_start.splice(i,1),i--)}catch(n){console.error(n),On(s.new_script_start[i],s),s.new_script_start.splice(i,1),i--}}function Tg(s,t){t.scripts.indexOf(s)===-1&&(t.scripts.push(s),s.earlyUpdate&&t.scripts_earlyUpdate.push(s),s.update&&t.scripts_update.push(s),s.lateUpdate&&t.scripts_lateUpdate.push(s),s.onBeforeRender&&t.scripts_onBeforeRender.push(s),s.onAfterRender&&t.scripts_onAfterRender.push(s),s.onPausedChanged&&t.scripts_pausedChanged.push(s),Eg(s,null)&&t.new_scripts_xr.push(s),Eg(s,"immersive-vr")&&t.scripts_immersive_vr.push(s),Eg(s,"immersive-ar")&&t.scripts_immersive_ar.push(s))}function On(s,t){Yi(s,t.new_scripts),Yi(s,t.new_script_start),Yi(s,t.scripts),Yi(s,t.scripts_earlyUpdate),Yi(s,t.scripts_update),Yi(s,t.scripts_lateUpdate),Yi(s,t.scripts_onBeforeRender),Yi(s,t.scripts_onAfterRender),Yi(s,t.scripts_pausedChanged),Yi(s,t.new_scripts_xr),Yi(s,t.scripts_immersive_vr),Yi(s,t.scripts_immersive_ar),t.stopAllCoroutinesFrom(s)}function Yi(s,t){const i=t.indexOf(s);i>=0&&t.splice(i,1)}function Eg(s,t){var i;if(s){const n=s;if(n.onBeforeXR||n.onEnterXR||n.onUpdateXR||n.onLeaveXR||n.onXRControllerAdded||n.onXRControllerRemoved)return!(t!=null&&((i=n.supportsXR)==null?void 0:i.call(n,t))===!1)}return!1}function Ud(s){if(s||(s=ge.Current.scene),!s){console.trace("Invalid call - no current context.");return}const t=Ba(s);n_(s,t,!0)||(Rg||F()?console.error(`Error updating hierarchy
159
+ Do you have circular references in your project? <a target="_blank" href="https://docs.needle.tools/circular-reference"> Click here for more information.`,s):console.error('Failed to update active state in hierarchy of "'+s.name+'"',s),console.warn(" \u2191 this error might be caused by circular references. Please make sure you don't have files with circular references (e.g. one GLB 1 is loading GLB 2 which is then loading GLB 1 again)."))}function n_(s,t,i,n=0){if(n>1e3)return console.warn("Hierarchy is too deep (> 1000 level) - will abort updating active state"),!1;const o=Ba(s);if(t&&(t=o,t&&s.parent)){const c=s.parent;t=c[xn],t===void 0&&(c instanceof $i||(t=!0))}const r=s[xn]!==t;s[xn]=t,r&&(h2&&console.warn("ACTIVE CHANGE",s.name,o,s.visible,t,"changed?"+r,s),i&&p2(s,c=>{t?c.enabled&&(Ia(c.__internalAwake.bind(c)),c.enabled&&(c.__didEnable=!0,c.onEnable())):c.__didAwake&&c.enabled&&(c.__didEnable=!1,c.onDisable())}));let l=!0;if(s.children){const c=n+1;for(const h of s.children)n_(h,t,i,c)===!1&&(l=!1)}return l}function fc(s){let t=!0,i=s,n=!1;for(;i&&i;){if(i.type==="Scene"&&(n=!0),!Ba(i)){t=!1;break}i=i.parent}if(!s){console.error("GO is null");return}s[xn]=t&&n}function p2(s,t){var i;if((i=s.userData)!=null&&i.components)for(const n of s.userData.components)t(n)}const Nd=new Map,o_=Symbol("prewarmFlag"),Ag=Symbol("waitingForPrewarm"),Ig=O("debugprewarm");function m2(s,t){!s||s[o_]===!0||s[Ag]===!0||(Nd.has(t)||Nd.set(t,[]),s[Ag]=!0,Nd.get(t).push(s),Ig&&console.debug("register prewarm",s.name))}let jg=null,Lg=null;function g2(s){if(!s)return;const t=Nd.get(s);if(!(t!=null&&t.length))return;const i=s.mainCamera;if(i){Ig&&console.log("prewarm",t.length,"objects",[...t]);const n=s.renderer;if(n.compile){const o=s.scene;n.compile(o,i),jg??(jg=new _S(64)),Lg??(Lg=new wS(.001,9999999,jg)),Lg.update(n,o);for(const r of t)r[o_]=!0,r[Ag]=!1;t.length=0,Ig&&console.log("prewarm done")}}}ge.registerCallback(fe.ContextCreated,s=>{const t=s.context;d_(t),l_(t)});const Wd=O("debugcomponents"),r_="eff8ba80-635d-11ec-90d6-0242ac120003";class Bt{constructor(t){a(this,"_originalSeed"),a(this,"_seed"),typeof t=="string"&&(t=Bt.hash(t)),this._originalSeed=t,this._seed=t}get seed(){return this._seed}set seed(t){this._seed=t}reset(){this._seed=this._originalSeed}generateUUID(t){if(typeof t=="string")return mv(t,r_);const i=this._seed;return this._seed-=1,mv(i.toString(),r_)}initialize(t){typeof t=="string"?this._seed=Bt.hash(t):this._seed=t}static createFromString(t){return new Bt(this.hash(t))}static hash(t){let i=0;for(let n=0;n<t.length;n++)i=t.charCodeAt(n)+((i<<5)-i);return i}}var a_=(s=>(s.NewInstanceCreated="new-instance-created",s.InstanceDestroyed="instance-destroyed",s))(a_||{});class f2{constructor(t){a(this,"guid"),a(this,"dontSave"),this.guid=t}}function yc(s,t,i=!0,n){if(!s)return;const o=s;if(Mi(s,i),!t){console.warn("Can not send destroy: No networking connection provided",s.guid);return}if(!t.isConnected){F()&&console.debug("Can not send destroy: not connected",s.guid);return}let r=s.guid;if(!r&&o.uuid&&(r=o.uuid),!r){console.warn("Can not send destroy: failed to find guid",s);return}Dg(r,t,n)}function Dg(s,t,i){const n=new f2(s);i?.saveInRoom===!1&&(n.dontSave=!0),t.send("instance-destroyed",n,bs.Queued)}function l_(s){s.connection.beginListen("instance-destroyed",t=>{Wd&&console.log("[Remote] Destroyed",s.scene,t);const i=Gg(t.guid,s.scene);i&&Mi(i)})}class y2{constructor(t,i,n){a(this,"filename"),a(this,"hash"),a(this,"size"),this.filename=t,this.hash=i,this.size=n}}class c_{constructor(t,i){a(this,"guid"),a(this,"originalGuid"),a(this,"seed"),a(this,"visible"),a(this,"hostData"),a(this,"dontSave"),a(this,"parent"),a(this,"position"),a(this,"rotation"),a(this,"scale"),a(this,"preventCreation"),a(this,"deleteStateOnDisconnect"),this.originalGuid=t,this.guid=i}}function Bg(s,t,i,n){var o,r;const l=s;if(!l.guid)return console.warn("Can not instantiate: No guid",l),null;if(t.context||(t.context=te.Current),!t.context)return console.error("Missing network instantiate options / reference to network connection in sync instantiate"),null;const c=t?{...t}:null,{instance:h,seed:d}=v2(l,t);if(h){const u=h;if(u.guid){Wd&&console.log("[Local] new instance","gameobject:",h?.guid);const p=new c_(l.guid,u.guid);p.seed=d,t.deleteOnDisconnect===!0&&(p.deleteStateOnDisconnect=!0),c&&(c.position&&(p.position={x:c.position.x,y:c.position.y,z:c.position.z}),c.rotation&&(p.rotation={x:c.rotation.x,y:c.rotation.y,z:c.rotation.z,w:c.rotation.w}),c.scale&&(p.scale={x:c.scale.x,y:c.scale.y,z:c.scale.z})),p.position||(p.position={x:u.position.x,y:u.position.y,z:u.position.z}),p.rotation||(p.rotation={x:u.quaternion.x,y:u.quaternion.y,z:u.quaternion.z,w:u.quaternion.w}),p.scale||(p.scale={x:u.scale.x,y:u.scale.y,z:u.scale.z}),p.visible=l.visible,c!=null&&c.parent&&(typeof c.parent=="string"?p.parent=c.parent:p.parent=c.parent.guid),p.hostData=i,n===!1&&(p.dontSave=!0),!((o=t?.context)!=null&&o.connection)&&F()&&console.debug("Object will be instantiated but it will not be synced: not connected",l.guid),t.context.connection.isInRoom&&ja.push(new WeakRef(u)),(r=t?.context)==null||r.connection.send("new-instance-created",p)}else console.warn("Missing guid, can not send new instance event",u)}return h}function h_(){return Math.random()*9999999}const ja=new Array;function d_(s){s.connection.beginListen("new-instance-created",async t=>{const i=await b2(t.originalGuid,s.scene);if(t.preventCreation===!0)return;if(!i){console.warn("could not find object that was instantiated: "+t.guid);return}const n=new js;t.position&&(n.position=new x(t.position.x,t.position.y,t.position.z)),t.rotation&&(n.rotation=new V(t.rotation.x,t.rotation.y,t.rotation.z,t.rotation.w)),t.scale&&(n.scale=new x(t.scale.x,t.scale.y,t.scale.z)),n.parent=t.parent,t.seed&&(n.idProvider=new Bt(t.seed)),n.visible=t.visible,n.context=s,Wd&&s.alias&&console.log("[Remote] instantiate in: "+s.alias);const o=za(i,n);ja.push(new WeakRef(o)),o&&(t.parent==="scene"&&s.scene.add(o),Wd&&console.log("[Remote] new instance","gameobject:",o?.guid,i))}),s.connection.beginListen("left-room",()=>{ja.length>0&&console.debug(`Left networking room, cleaning up ${ja.length} instantiated objects`);for(const t of ja){const i=t.deref();i&&i.destroy()}ja.length=0})}function v2(s,t){const i=h_(),n=t??new js;n.idProvider=new Bt(i);const o=za(s,n);return{seed:i,instance:o}}const u_={};function p_(s,t){u_[s]=t}async function b2(s,t){const i=u_[s];if(i!=null){const n=await i(s);if(n)return n}return m_(s,t)}function m_(s,t){if(t===null||!s)return null;if(t.guid===s)return t;if(t.children)for(const i of t.children){const n=m_(s,i);if(n)return n}return null}const vc=O("gizmos"),ft=O("debugextension"),Fg=O("debugtypes");class _2{constructor(){a(this,"_types",new Map),Fg&&console.warn("TypeStore: Created",this)}add(t,i){Fg&&console.warn("ADD TYPE",t);const n=this._types.get(t);n?Fg&&n!==i&&console.warn("Type name exists multiple times in your project and may lead to runtime errors:",t):this._types.set(t,i)}get(t){return this._types.get(t)||null}getKey(t){for(const[i,n]of this._types)if(n===t)return i;return null}}const w2=Symbol("BuiltInType"),S=new _2,x2=function(s){S.get(s.name)||S.add(s.name,s)},zg=O("debugresolvedependencies"),S2=["/extensions/","extensions/"],C2=[{prefix:"/nodes/",dependencyName:"node"},{prefix:"/meshes/",dependencyName:"mesh"},{prefix:"/materials/",dependencyName:"material"},{prefix:"/textures/",dependencyName:"texture"},{prefix:"/animations/",dependencyName:"animation"},{prefix:"nodes/",dependencyName:"node"},{prefix:"meshes/",dependencyName:"mesh"},{prefix:"materials/",dependencyName:"material"},{prefix:"textures/",dependencyName:"texture"},{prefix:"animations/",dependencyName:"animation"}];async function Ug(s,t){zg&&console.log(s,t);const i=[];Ng(C2,s,t,i);const n=await Promise.all(i);return typeof t=="string"&&n.length===1?n[0]:n}function g_(s,t){return!s||!t?!1:s["needle:identifier"]!=null&&t["needle:identifier"]!=null?s["needle:identifier"]===t["needle:identifier"]:!1}function O2(s,t){s["needle:identifier"]=t}function Ng(s,t,i,n){if(typeof i=="object"&&i!==void 0&&i!==null)for(const o of Object.keys(i)){const r=i[o];if(typeof r=="string"){const l=f_(t,r);if(l!=null)typeof l.then=="function"?n.push(l.then(c=>i[o]=c)):i[o]=l;else{const c=y_(s,t,r);if(c){n.push(c.then(h=>(i[o]=h,h)));continue}}}else if(Array.isArray(r))for(let l=0;l<r.length;l++){const c=r[l],h=f_(t,c);if(h!==null){typeof h.then=="function"?n.push(h.then(d=>r[l]=d)):r[l]=h;continue}for(const d of s){const u=v_(d.prefix,c);if(u>=0){zg&&console.log(d,u,d.dependencyName),n.push(t.getDependency(d.dependencyName,u).then(p=>r[l]=p));break}}typeof c=="object"&&Ng(s,t,c,n)}else typeof r=="object"&&Ng(s,t,r,n)}else if(typeof i=="string"){const o=y_(s,t,i);o&&n.push(o)}}function f_(s,t){if(s&&s.plugins&&typeof t=="string"){for(const i of S2)if(t.startsWith(i)){let n=t.substring(i.length);const o=n.indexOf("/");o>=0&&(n=n.substring(0,o));const r=s.plugins[n];if(ft&&console.log(n,r),typeof r?.resolve=="function"){const l=t.substring(i.length+n.length+1);return r.resolve(s,l)}break}}return null}function y_(s,t,i){for(const n of s){const o=v_(n.prefix,i);if(o>=0)return zg&&console.warn("GET DEPENDENCY",n,o,n.dependencyName),t.getDependency(n.dependencyName,o)}return null}function v_(s,t){if(typeof t=="string"&&t.startsWith(s)){const i=t.substring(s.length),n=Number.parseInt(i);if(n>=0)return n}return-1}const Wg="NEEDLE_persistent_assets";function P2(s){return s?.___persistentAsset===!0}class k2{constructor(t){a(this,"parser"),this.parser=t}get name(){return Wg}async afterRoot(t){var i,n;if(!((n=(i=this.parser)==null?void 0:i.json)!=null&&n.extensions))return;const o=this.parser.json.extensions[Wg];if(!o)return;ft&&console.log(o);const r=new Array;for(const l of o?.assets){const c=Ug(this.parser,l);c&&r.push(c)}await Promise.all(r)}resolve(t,i){const n=Number.parseInt(i);if(n>=0){ft&&console.log(i);const o=t.json.extensions[Wg];if(o){const r=o?.assets[n];if(r&&typeof r=="object"){r.___persistentAsset=!0;const l=r.__type;l&&S.get(l)}return r}}return null}}const Ws=O("debugserializer");class M2{constructor(){a(this,"typeMap",new Map)}register(t,i){if(this.typeMap.has(t)){const n=this.typeMap.get(t);if(n===i)return;Ws&&console.warn("Type: "+t+" is already registered",i,n)}Ws&&console.log("Register type serializer",i.name,i,t),this.typeMap.set(t,i)}getSerializer(t){if(t)return this.typeMap.get(t)}getSerializerForConstructor(t,i=0){if(i>20)return;if(!t||!t.constructor){Ws&&console.log("invalid type");return}const n=t.name,o=this.getSerializer(t);if(o!==void 0)return Ws&&console.log("FOUND SERIALIZER",o?.name,t.name,t.constructor.name,"for type: "+n,o,t,this.typeMap),o;const r=Object.getPrototypeOf(t);if(r&&r!==t){const l=this.getSerializerForConstructor(r,++i);if(l){const c=r.constructor||r.prototype;Ws&&console.log("FOUND SERIALIZER(in constructor) "+c.constructor.name,c.name,c,l),this.register(c,l)}return l}Ws&&console.warn("No serializer found for "+n,t,t.name,t.constructor.name)}}const Vd=new M2;class Ki{constructor(t,i){if(a(this,"name"),this.name=i,Array.isArray(t))for(const n of t)Vd.register(n,this);else Vd.register(t,this)}}class R2{constructor(){a(this,"isDevMode",Gt()),a(this,"cache",{})}registerDefinedKeys(t,i){if(this.isDevMode&&this.cache[t]===void 0){this.cache[t]=Object.keys(i);const n=i;n.$serializedTypes&&Object.keys(n.$serializedTypes)&&this.cache[t].push(...Object.keys(n.$serializedTypes)),Ws&&console.log("registerDefinedKeys for "+t,this.cache[t],i)}}getDefinedKey(t,i){return this.cache[t]===void 0?!1:this.cache[t].includes(i)}}class Vg{constructor(t){a(this,"root"),a(this,"gltf"),a(this,"gltfId"),a(this,"object"),a(this,"target"),a(this,"nodeId"),a(this,"nodeToObject"),a(this,"objectToNode"),a(this,"context"),a(this,"path"),a(this,"type"),a(this,"serializable"),a(this,"implementationInformation"),this.root=t}}function b_(s,t){const i=s.$serializedTypes;if(i===void 0)return null;const n={};for(const r in i){const l=s[r];if(l!=null&&typeof l=="object"){const c=Vd.getSerializerForConstructor(l);if(c){n[r]=c.onSerialize(l,t);continue}}n[r]=l}function o(r){const l=S._types;for(const[c,h]of l)if(h===s.constructor)return c;return r.__name||r.constructor.name}return n.name=o(s),typeof s.guid=="string"&&(n.guid=s.guid),n}const Hd=[];function __(s,t){if(!s)return t;typeof s.$serializedTypes=="object"&&(t||(t={}),Object.assign(t,s.$serializedTypes));const i=Object.getPrototypeOf(s);return __(i,t)}function $d(s,t,i){if(!s)return!1;if(i.target=s,s.onBeforeDeserialize!==void 0){const o=s.onBeforeDeserialize(t,i);if(typeof o=="boolean")return o}const n=__(s);if(t){if(typeof t.guid=="string"&&(s.guid=t.guid),n)for(const o in n){let r=function(h){const d=h.type;return d?Hg(c,d,i,void 0,s[o]):Hg(c,h,i,void 0,s[o])};const l=n[o],c=t[o];if(Ws&&console.log(o,c,s,l),!(s[o]!==void 0&&c===void 0)&&(i.type=void 0,i.path=o,i.serializable=l,!(s.onBeforeDeserializeMember!==void 0&&s.onBeforeDeserializeMember(o,c,i)===!0))){if(l===null)s[o]=c;else{if(Array.isArray(l))for(let h=0;h<l.length;h++){const d=l[h],u=r(d);if(u!==void 0||h===l.length-1){s[o]=u;break}}else s[o]=r(l);Hd.length=0}s.onAfterDeserializeMember!==void 0&&s.onAfterDeserializeMember(o,c,i)}}A2(s,t)}return E2(s,t,i.implementationInformation),s.onAfterDeserialize!==void 0&&s.onAfterDeserialize(t,i),!0}const T2=O("noerrors");function E2(s,t,i){var n,o;if(T2||!t||!Gt()||!s||s.constructor&&s.constructor[w2]===!0)return;const r=(n=s.constructor)==null?void 0:n.name,l=Object.getOwnPropertyNames(t);for(const c of l){if(c==="sourceId")continue;const h=s[c];if(h==null)continue;const d=t[c];if(i?.getDefinedKey(r,c)===!1){const u=c.charAt(0).toUpperCase()+c.slice(1);i.getDefinedKey(r,u)&&(Bs(xi.Warn,'<strong>Please rename</strong> "'+u+'" to "'+c+'" in '+r),console.warn('Please use lowercase for field: "'+u+'" in '+r,d,s));continue}if(d!=null){if(typeof d=="object"&&(h===void 0||!h.isObject3D)){if(typeof d.node=="number"||typeof d.guid=="string"){if(d.could_not_resolve)continue;if(!(h!==void 0&&Object.keys(h).length>1)){Bs(xi.Warn,`<strong>Missing serialization for object reference!</strong>
160
160
 
161
161
  Please change to:
162
162
  @serializable(Object3D)
@@ -171,12 +171,12 @@ Please change to:
171
171
  ${c}? : AssetReference;
172
172
 
173
173
  in script ${r}.ts
174
- <a href="https://docs.needle.tools/serializable" target="_blank">documentation</a>`),console.warn(r,c,s[c],s);continue}}}}function Ak(s,t){for(const i of Object.keys(t)){const n=t[i];if(typeof n=="object"&&n!==null&&n!==void 0){const o=s[i];if(!o){Ws&&console.log(i,"is undefined on",s);continue}for(const r of Object.keys(n))if(o[r]===void 0&&w_(n[r])&&!w_(o)){const l=Ik(o,r);if(l&&(l?.writable===void 0||l?.writable===!1)&&l.set===void 0){Ws&&console.warn('Property is not writable "'+r+'"',o,l,n[r],o[r]);continue}o[r]=n[r]}}}}function Ik(s,t){for(;s;){const i=Object.getOwnPropertyDescriptor(s,t);if(i)return i;s=Object.getPrototypeOf(s)}}function w_(s){switch(typeof s){case"number":case"string":case"boolean":return!0}return!1}function Hg(s,t,i,n,o){let r=typeof t=="function"&&t.prototype===void 0,l=t;if(r)try{if(l=t?.call(t,o),r=!1,l==null)return}catch(u){console.error("Error in callback",u,s)}if(i.type=l,!r&&o instanceof l)return o;if(n||(n={serializer:Vd.getSerializerForConstructor(l)}),o&&typeof o=="object"&&Pk(o)){if(o.__concreteInstance)return o.__concreteInstance;const u=o;if(!u.$serializedTypes&&l.prototype.$serializedTypes&&(u.$serializedTypes=l.prototype.$serializedTypes),u.$serializedTypes&&$d(u,s,i),o&&l!==void 0)try{let p=null;n.serializer&&(p=n.serializer.onDeserialize(s,i)),p||(p=new l,ft&&console.log("Create concrete instance for persistent asset",o,"instance:",p),La(p,o)),o.__concreteInstance=p,o=p}catch(p){console.error("Error creating instance or creating values on instance",p,o,l)}return o}if(Array.isArray(s)){const u=[];for(let p=0;p<s.length;p++){const g=s[p],y=Hg(g,t,i,n,g);u.push(y)}return u}const c=n?.serializer;if(c)return c.onDeserialize(s,i);let h;if(s&&(s.isMaterial||s.isTexture||s.isObject3D||s instanceof ur))h=s;else{if(s===void 0)return;if(s===null&&(l===Oe||l===Ne||l===Q||l===ur))return null;try{h=new l(...jk(s))}catch(u){console.error("Error creating "+i.path,i.target,u);return}}const d=h;return d.$serializedTypes&&$d(d,s,i),h}function jk(s){if(Hd.length=0,typeof s=="object"&&s!==null&&s!==void 0)for(const t of Object.keys(s))Hd.push(s[t]);return Hd}const $g=Symbol("assigned component properties");function La(s,t,i){var n;if(t==null||s==null)return;s[$g]=!0;const o=((n=s.constructor)==null?void 0:n.name)??"unknown";i?.registerDefinedKeys(o,s);for(const r of Object.keys(t)){const l=Lk(s,r);typeof l?.value!="function"&&(!l||l.writable===!0||l?.set!==void 0)&&(s[r]=t[r])}delete s[$g]}function Lk(s,t){let i;do i=Object.getOwnPropertyDescriptor(s,t);while(!i&&(s=Object.getPrototypeOf(s)));return i}const x_=Symbol("customVisibilityFlag");function Pn(s,t){s.layers[x_]=t}const S_=Symbol("DidPatchLayers");function Dk(){const s=no.prototype;if(s[S_])return;s[S_]=!0;const t=s.test;s.test=function(i){return this[x_]===!1?!1:t.call(this,i)}}Dk(),Object.defineProperty(be.prototype,"fov",{get:function(){return this._fov},set:function(s){const t=s!==this._fov;this._fov=s,t&&this.view!==void 0&&this.updateProjectionMatrix()},configurable:!0}),Object.defineProperty(be.prototype,"near",{get:function(){return this._near},set:function(s){const t=s!==this._near;this._near=s,t&&this.view!==void 0&&this.updateProjectionMatrix()},configurable:!0}),Object.defineProperty(be.prototype,"far",{get:function(){return this._far},set:function(s){const t=s!==this._far;this._far=s,t&&this.view!==void 0&&this.updateProjectionMatrix()},configurable:!0});const C_=new Map;function O_(s,t){if(!s)return;if(!t){console.warn("No prototype found",s,s.prototype,s.constructor);return}const i=C_.get(t);i&&i.apply(s)}function P_(s){const t=Bk(s.prototype);C_.set(s,t)}function Bk(s){return new Fk(s)}class Fk{constructor(t){a(this,"$symbol"),a(this,"extensions"),a(this,"descriptors"),this.$symbol=Symbol("prototype-extension"),this.extensions=Object.keys(t),this.descriptors=new Array;for(let i=0;i<this.extensions.length;i++){const n=this.extensions[i],o=Object.getOwnPropertyDescriptor(t,n);o&&this.descriptors.push(o)}}apply(t){if(!t[this.$symbol]){t[this.$symbol]=!0;for(let i=0;i<this.extensions.length;i++){const n=this.extensions[i],o=this.descriptors[i];o&&Object.defineProperty(t,n,o)}}}}const zk=O("debuggetcomponent"),k_=()=>zk||globalThis.NEEDLE_DEBUG_GETCOMPONENT===!0;function Uk(s){return s==null||s.isObject3D?s:s.object&&s.object.isObject3D?s.object:s}function qg(s,t){if(!s||!s.userData.components)return t;const i=s.userData.components.indexOf(t);return i<0||(pc.dispatchComponentLifecycleEvent("removing-component",t),t.gameObject=null,s.userData.components.splice(i,1)),t}function bc(s,t,i){return Or(s,t)||ki(s,t,i)}const M_=new Bt("addComponentIdProvider");function Cr(s,t,i=!0){s.userData||(s.userData={}),s.userData.components||(s.userData.components=[]),s.userData.components.push(t),t.gameObject=s,(t.guid===void 0||t.guid==="invalid")&&(t.guid=M_.generateUUID()),Xd(s),fu(t,t.context);try{i&&t.__internalAwake&&(fc(s),t.activeAndEnabled&&t.__internalAwake()),pc.dispatchComponentLifecycleEvent("component-added",t)}catch(n){console.error(n)}return t}function ki(s,t,i,n){if(typeof t=="function"){const o=new t;i&&o.__internalNewInstanceCreated(i);let r=!0;return n?.callAwake!=null&&(r=n.callAwake),Cr(s,o,r)}if(t.destroyed)return console.warn("Can not move/add a destroyed component",t),t;if(t.gameObject===s)return t;if(t.gameObject&&t.gameObject.userData.components){const o=t.gameObject.userData.components.indexOf(t);t.gameObject.userData.components.splice(o,1)}if(!s.userData.components)s.userData.components=[];else if(s.userData.components.includes(t))return t;return s.userData.components.push(t),t.gameObject=s,(t.guid===void 0||t.guid==="invalid")&&(t.guid=M_.generateUUID()),i&&t._internalInit(i),fu(t,t.context),t}function R_(s){if(s.gameObject&&s.gameObject.userData.components){const t=s.gameObject.userData.components.indexOf(s);s.gameObject.userData.components.splice(t,1)}s.__internalDisable&&s.__internalDisable(),On(s,s.context??te.Current),s.destroy(),s.gameObject=null}let T_=!1;function E_(s,t,i){var n;if(s==null)return null;if(!s.isObject3D)return console.error("Object is not object3D"),null;if(!((n=s?.userData)!=null&&n.components)||(typeof t=="string"&&(T_||(T_=!0,console.warn(`Accessing components by name is not supported.
174
+ <a href="https://docs.needle.tools/serializable" target="_blank">documentation</a>`),console.warn(r,c,s[c],s);continue}}}}function A2(s,t){for(const i of Object.keys(t)){const n=t[i];if(typeof n=="object"&&n!==null&&n!==void 0){const o=s[i];if(!o){Ws&&console.log(i,"is undefined on",s);continue}for(const r of Object.keys(n))if(o[r]===void 0&&w_(n[r])&&!w_(o)){const l=I2(o,r);if(l&&(l?.writable===void 0||l?.writable===!1)&&l.set===void 0){Ws&&console.warn('Property is not writable "'+r+'"',o,l,n[r],o[r]);continue}o[r]=n[r]}}}}function I2(s,t){for(;s;){const i=Object.getOwnPropertyDescriptor(s,t);if(i)return i;s=Object.getPrototypeOf(s)}}function w_(s){switch(typeof s){case"number":case"string":case"boolean":return!0}return!1}function Hg(s,t,i,n,o){let r=typeof t=="function"&&t.prototype===void 0,l=t;if(r)try{if(l=t?.call(t,o),r=!1,l==null)return}catch(u){console.error("Error in callback",u,s)}if(i.type=l,!r&&o instanceof l)return o;if(n||(n={serializer:Vd.getSerializerForConstructor(l)}),o&&typeof o=="object"&&P2(o)){if(o.__concreteInstance)return o.__concreteInstance;const u=o;if(!u.$serializedTypes&&l.prototype.$serializedTypes&&(u.$serializedTypes=l.prototype.$serializedTypes),u.$serializedTypes&&$d(u,s,i),o&&l!==void 0)try{let p=null;n.serializer&&(p=n.serializer.onDeserialize(s,i)),p||(p=new l,ft&&console.log("Create concrete instance for persistent asset",o,"instance:",p),La(p,o)),o.__concreteInstance=p,o=p}catch(p){console.error("Error creating instance or creating values on instance",p,o,l)}return o}if(Array.isArray(s)){const u=[];for(let p=0;p<s.length;p++){const g=s[p],y=Hg(g,t,i,n,g);u.push(y)}return u}const c=n?.serializer;if(c)return c.onDeserialize(s,i);let h;if(s&&(s.isMaterial||s.isTexture||s.isObject3D||s instanceof ur))h=s;else{if(s===void 0)return;if(s===null&&(l===Oe||l===Ne||l===Q||l===ur))return null;try{h=new l(...j2(s))}catch(u){console.error("Error creating "+i.path,i.target,u);return}}const d=h;return d.$serializedTypes&&$d(d,s,i),h}function j2(s){if(Hd.length=0,typeof s=="object"&&s!==null&&s!==void 0)for(const t of Object.keys(s))Hd.push(s[t]);return Hd}const $g=Symbol("assigned component properties");function La(s,t,i){var n;if(t==null||s==null)return;s[$g]=!0;const o=((n=s.constructor)==null?void 0:n.name)??"unknown";i?.registerDefinedKeys(o,s);for(const r of Object.keys(t)){const l=L2(s,r);typeof l?.value!="function"&&(!l||l.writable===!0||l?.set!==void 0)&&(s[r]=t[r])}delete s[$g]}function L2(s,t){let i;do i=Object.getOwnPropertyDescriptor(s,t);while(!i&&(s=Object.getPrototypeOf(s)));return i}const x_=Symbol("customVisibilityFlag");function Pn(s,t){s.layers[x_]=t}const S_=Symbol("DidPatchLayers");function D2(){const s=no.prototype;if(s[S_])return;s[S_]=!0;const t=s.test;s.test=function(i){return this[x_]===!1?!1:t.call(this,i)}}D2(),Object.defineProperty(be.prototype,"fov",{get:function(){return this._fov},set:function(s){const t=s!==this._fov;this._fov=s,t&&this.view!==void 0&&this.updateProjectionMatrix()},configurable:!0}),Object.defineProperty(be.prototype,"near",{get:function(){return this._near},set:function(s){const t=s!==this._near;this._near=s,t&&this.view!==void 0&&this.updateProjectionMatrix()},configurable:!0}),Object.defineProperty(be.prototype,"far",{get:function(){return this._far},set:function(s){const t=s!==this._far;this._far=s,t&&this.view!==void 0&&this.updateProjectionMatrix()},configurable:!0});const C_=new Map;function O_(s,t){if(!s)return;if(!t){console.warn("No prototype found",s,s.prototype,s.constructor);return}const i=C_.get(t);i&&i.apply(s)}function P_(s){const t=B2(s.prototype);C_.set(s,t)}function B2(s){return new F2(s)}class F2{constructor(t){a(this,"$symbol"),a(this,"extensions"),a(this,"descriptors"),this.$symbol=Symbol("prototype-extension"),this.extensions=Object.keys(t),this.descriptors=new Array;for(let i=0;i<this.extensions.length;i++){const n=this.extensions[i],o=Object.getOwnPropertyDescriptor(t,n);o&&this.descriptors.push(o)}}apply(t){if(!t[this.$symbol]){t[this.$symbol]=!0;for(let i=0;i<this.extensions.length;i++){const n=this.extensions[i],o=this.descriptors[i];o&&Object.defineProperty(t,n,o)}}}}const z2=O("debuggetcomponent"),k_=()=>z2||globalThis.NEEDLE_DEBUG_GETCOMPONENT===!0;function U2(s){return s==null||s.isObject3D?s:s.object&&s.object.isObject3D?s.object:s}function qg(s,t){if(!s||!s.userData.components)return t;const i=s.userData.components.indexOf(t);return i<0||(pc.dispatchComponentLifecycleEvent("removing-component",t),t.gameObject=null,s.userData.components.splice(i,1)),t}function bc(s,t,i){return Or(s,t)||ki(s,t,i)}const M_=new Bt("addComponentIdProvider");function Cr(s,t,i=!0){s.userData||(s.userData={}),s.userData.components||(s.userData.components=[]),s.userData.components.push(t),t.gameObject=s,(t.guid===void 0||t.guid==="invalid")&&(t.guid=M_.generateUUID()),Xd(s),fu(t,t.context);try{i&&t.__internalAwake&&(fc(s),t.activeAndEnabled&&t.__internalAwake()),pc.dispatchComponentLifecycleEvent("component-added",t)}catch(n){console.error(n)}return t}function ki(s,t,i,n){if(typeof t=="function"){const o=new t;i&&o.__internalNewInstanceCreated(i);let r=!0;return n?.callAwake!=null&&(r=n.callAwake),Cr(s,o,r)}if(t.destroyed)return console.warn("Can not move/add a destroyed component",t),t;if(t.gameObject===s)return t;if(t.gameObject&&t.gameObject.userData.components){const o=t.gameObject.userData.components.indexOf(t);t.gameObject.userData.components.splice(o,1)}if(!s.userData.components)s.userData.components=[];else if(s.userData.components.includes(t))return t;return s.userData.components.push(t),t.gameObject=s,(t.guid===void 0||t.guid==="invalid")&&(t.guid=M_.generateUUID()),i&&t._internalInit(i),fu(t,t.context),t}function R_(s){if(s.gameObject&&s.gameObject.userData.components){const t=s.gameObject.userData.components.indexOf(s);s.gameObject.userData.components.splice(t,1)}s.__internalDisable&&s.__internalDisable(),On(s,s.context??te.Current),s.destroy(),s.gameObject=null}let T_=!1;function E_(s,t,i){var n;if(s==null)return null;if(!s.isObject3D)return console.error("Object is not object3D"),null;if(!((n=s?.userData)!=null&&n.components)||(typeof t=="string"&&(T_||(T_=!0,console.warn(`Accessing components by name is not supported.
175
175
  Please use the component type instead. This may keep working in local development but it will fail when bundling your application.
176
176
 
177
177
  You can import other modules your main module to get access to types
178
178
  or if you use npmdefs you can make types available globally using globalThis:
179
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis`,t))),k_()&&console.log("[onGetComponent] FIND",t),t==null))return null;for(let o=0;o<s.userData.components.length;o++){const r=s.userData.components[o];let l=Object.getPrototypeOf(r);for(;l;){if(l===t.prototype)if(k_()&&console.log("[onGetComponent] MATCH BY PROTOYPE",l),i)i.push(r);else return r;l=Object.getPrototypeOf(l)}}return i||null}function Or(s,t){const i=E_(s,t);return i?Array.isArray(i)?i[0]:i:null}function _c(s,t,i,n=!0){return i||(i=[]),n&&(i.length=0),E_(s,t,i),i}function wc(s,t,i){var n;const o=Or(s,t);if(i===!1&&o?.enabled===!1)return null;if(o)return o;for(let r=0;r<((n=s?.children)==null?void 0:n.length);r++){const l=wc(s.children[r],t);if(l)return l}return null}function Da(s,t,i,n=!0){var o;i||(i=[]),n&&(i.length=0),_c(s,t,i,!1);for(let r=0;r<((o=s?.children)==null?void 0:o.length);r++)Da(s.children[r],t,i,!1);return i}function xc(s,t){if(!s)return null;if(Array.isArray(s)){for(let n=0;n<s.length;n++){const o=Uk(s[n]),r=xc(o,t);if(r)return r}return null}return Or(s,t)||(s.parent?xc(s.parent,t):null)}function qd(s,t,i,n=!0){return i||(i=[]),n&&(i.length=0),s?(_c(s,t,i,!1),s.parent?qd(s.parent,t,i,!1):i):i}function Gd(s,t=void 0,i=!0){if(!s)return null;if(!t&&(t=te.Current,!t))return console.error("Can not search object without any needle context or scene!!!"),null;let n=t;if(n.isScene||(n=t?.scene),!n)return null;for(const o in n.children){const r=n.children[o];if(i===!1&&r[xn]===!1)continue;const l=wc(r,s);if(l)return l}return null}function A_(s,t,i=void 0){if(!s)return t??[];if(t||(t=[]),t.length=0,!i&&(i=te.Current,!i))return console.error("Can not search object without any needle context or scene!!!"),t;"scene"in i&&(i=i.scene);const n=i;if(!n)return t;for(const o in n.children){const r=n.children[o];Da(r,s,t,!1)}return t}function Xd(s){s&&s.isObject3D===!0&&O_(s,j)}j.prototype.SetActive=function(s){this.visible=s},j.prototype.setActive=function(s){this.visible=s},j.prototype.destroy=function(){Mi(this)},j.prototype.addComponent=function(s,t){return ki(this,s,t)},j.prototype.addNewComponent=function(s,t){return ki(this,s,t)},j.prototype.removeComponent=function(s){return qg(this,s)},j.prototype.getOrAddComponent=function(s,t){return bc(this,s,t)},j.prototype.getComponent=function(s){return Or(this,s)},j.prototype.getComponents=function(s,t){return _c(this,s,t)},j.prototype.getComponentInChildren=function(s){return wc(this,s)},j.prototype.getComponentsInChildren=function(s,t){return Da(this,s,t)},j.prototype.getComponentInParent=function(s){return xc(this,s)},j.prototype.getComponentsInParent=function(s,t){return qd(this,s,t)},Object.getOwnPropertyDescriptor(j.prototype,"activeSelf")||Object.defineProperty(j.prototype,"activeSelf",{get:function(){return Ba(this)},set:function(s){Sc(this,s)}}),Object.getOwnPropertyDescriptor(j.prototype,"worldPosition")||Object.defineProperty(j.prototype,"worldPosition",{get:function(){return this instanceof lv?ee(this.object):ee(this)},set:function(s){lt(this,s)}}),Object.getOwnPropertyDescriptor(j.prototype,"worldQuaternion")||Object.defineProperty(j.prototype,"worldQuaternion",{get:function(){return this instanceof lv?Se(this.object):Se(this)},set:function(s){qi(this,s)}}),Object.getOwnPropertyDescriptor(j.prototype,"worldRotation")||Object.defineProperty(j.prototype,"worldRotation",{get:function(){return Zl(this)},set:function(s){Qm(this,s)}}),Object.getOwnPropertyDescriptor(j.prototype,"worldScale")||Object.defineProperty(j.prototype,"worldScale",{get:function(){return Ke(this)},set:function(s){Oa(this,s)}}),Object.getOwnPropertyDescriptor(j.prototype,"worldForward")||Object.defineProperty(j.prototype,"worldForward",{get:function(){return $().set(0,0,1).applyQuaternion(Se(this))}}),Object.getOwnPropertyDescriptor(j.prototype,"worldRight")||Object.defineProperty(j.prototype,"worldRight",{get:function(){return $().set(1,0,0).applyQuaternion(Se(this))}}),Object.getOwnPropertyDescriptor(j.prototype,"worldUp")||Object.defineProperty(j.prototype,"worldUp",{get:function(){return $().set(0,1,0).applyQuaternion(Se(this))}}),P_(j);class we extends ae{constructor(t,i,n,o){var r=(...l)=>{super(...l),a(this,"alpha",1)};i!=null&&n!=null?(r(t,i,n),this.alpha=o):(r(t),this.alpha=1)}get isRGBAColor(){return!0}set a(t){this.alpha=t}get a(){return this.alpha}clone(){const t=super.clone();return t.alpha=this.alpha,t}copy(t){return this.r=t.r,this.g=t.g,this.b=t.b,"alpha"in t&&typeof t.alpha=="number"?this.alpha=t.alpha:typeof t.a=="number"&&(this.alpha=t.a),this}lerp(t,i){const n=t;return n.alpha!=null&&(this.alpha=W.lerp(this.alpha,n.alpha,i)),super.lerp(t,i)}lerpColors(t,i,n){const o=t,r=i;return o.alpha!=null&&r.alpha!=null&&(this.alpha=W.lerp(o.alpha,r.alpha,n)),super.lerpColors(t,i,n)}multiply(t){const i=t;return i.alpha!=null&&(this.alpha=this.alpha*i.alpha),super.multiply(t)}fromArray(t,i=0){return this.alpha=t[i+3],super.fromArray(t,i)}}const Qd=O("debuggetcomponent"),Yd=O("debuginstantiate");class js{constructor(){a(this,"idProvider"),a(this,"parent"),a(this,"keepWorldPosition"),a(this,"position"),a(this,"rotation"),a(this,"scale"),a(this,"visible"),a(this,"context"),a(this,"components")}clone(){var t,i,n;const o=new js;return o.idProvider=this.idProvider,o.parent=this.parent,o.keepWorldPosition=this.keepWorldPosition,o.position=(t=this.position)==null?void 0:t.clone(),o.rotation=(i=this.rotation)==null?void 0:i.clone(),o.scale=(n=this.scale)==null?void 0:n.clone(),o.visible=this.visible,o.context=this.context,o.components=this.components,o}cloneAssign(t){var i,n,o;this.idProvider=t.idProvider,this.parent=t.parent,this.keepWorldPosition=t.keepWorldPosition,this.position=(i=t.position)==null?void 0:i.clone(),this.rotation=(n=t.rotation)==null?void 0:n.clone(),this.scale=(o=t.scale)==null?void 0:o.clone(),this.visible=t.visible,this.context=t.context,this.components=t.components}}function Ba(s){return s.visible}function Sc(s,t){return typeof t=="number"&&(t=t>.5),s.visible=t,s.visible}function I_(s){return s[xn]||Kd(s)}function j_(s,t){s[t_]=t}function Kd(s){return cs.isUsingInstancing(s)}function Gg(s,t){return Sa(s,t,!0,!0)}const L_=Symbol("isDestroyed");function Pr(s){return s[L_]}function D_(s,t){s[L_]=t}const Xg=Symbol("isDontDestroy");function Fa(s,t=!0){s[Xg]=t}const Zd=[],Jd=[];function Mi(s,t=!0,i=!1){Zd.length=0,Jd.length=0,Qg(s,t,!0);for(const n of Zd)n.gameObject=null,n.context=null;for(const n of Jd)D_(n,!0),i&&Te(n),Jb(n);Jd.length=0,Zd.length=0}function Qg(s,t=!0,i=!0){var n;if(s==null)return;const o=s;if(o.isComponent){if(o[Xg])return;Zd.push(o);const c=o.gameObject;o.__internalDisable(),o.__internalDestroy(),o.gameObject=c;return}if(s[Xg])return;const r=s;Qd&&console.log(r),Jd.push(r);const l=(n=r.userData)==null?void 0:n.components;if(l!=null&&Array.isArray(l)){let c=l.length;for(let h=0;h<l.length;h++){const d=l[h];Qg(d,t,!1),l.length<c&&(c=l.length,h--)}}if(t&&r.children)for(const c of r.children)Qg(c,t,!1);i&&r.removeFromParent()}function kr(s,t,i=!0){return B_(s,t,i)}function*eu(s,t,i=!1,n=999,o=0){if(s!=null&&s.userData.components&&!(o>n)){for(const r of s.userData.components)t&&r?.isComponent===!0&&r instanceof t?yield r:yield r;if(i===!0)for(const r of s.children)yield*eu(r,t,!0,n,o+1)}}function B_(s,t,i,n=0){var o;if(s){if(s.isObject3D,n>1e3){console.warn("Failed to iterate components: too many levels");return}if((o=s.userData)!=null&&o.components)for(let r=0;r<s.userData.components.length;r++){const l=s.userData.components[r];if(l?.isComponent===!0){const c=t(l);if(c!==void 0)return c}}if(i&&s.children){const r=n+1;for(let l=0;l<s.children.length;l++){const c=s.children[l];if(!c)continue;const h=B_(c,t,i,r);if(h!==void 0)return h}}}}function za(s,t){if("isAssetReference"in s)return s.instantiate(t??void 0);let i=null;t!=null&&(t.x!==void 0?(i=new js,i.position=t):i=t);let n=te.Current;i!=null&&i.context&&(n=i.context),Qd&&n.alias&&console.log("context",n.alias),i&&!i.idProvider&&(i.idProvider=new Bt(Date.now()));const o=[],r={},l={},c=F_(n,s,i,o,r,l);c&&(Wk(r),Nk(l,r)),Qd&&(xd(s,!0),xd(c,!0));const h={};if(i?.components!==!1){for(const d in o){const u=o[d],p=u.guid;i&&i.idProvider&&(u.guid=i.idProvider.generateUUID(),h[p]=u.guid,Qd&&console.log(u.name,u.guid)),fu(u,n),u.__internalNewInstanceCreated&&u.__internalNewInstanceCreated()}for(const d in o){const u=o[d];u.resolveGuids&&u.resolveGuids(h),u.enabled!==!1&&(u.enabled=!0)}zd(n)}return c}function F_(s,t,i,n,o,r){var l;if(!t)return null;const c=t.userData;t.userData={};const h=t.children;t.children=[];const d=t.clone(!1);if(Xd(d),t.userData=c,t.children=h,o[t.uuid]={original:t,clone:d},Yd&&console.log("ADD",t,d),t.type==="SkinnedMesh"&&(r[t.uuid]={original:t,clone:d}),i?.visible!==void 0&&(d.visible=i.visible),i!=null&&i.idProvider){d.uuid=i.idProvider.generateUUID();const p=d;p&&(p.guid=d.uuid)}t.animations&&t.animations.length>0&&(d.animations=[...t.animations]);const u=t.parent;if(u&&u.add(d),i!=null&&i.position?lt(d,i.position):d.position.copy(t.position),i!=null&&i.rotation?qi(d,i.rotation):d.quaternion.copy(t.quaternion),i!=null&&i.scale?d.scale.copy(i.scale):d.scale.copy(t.scale),i!=null&&i.parent&&i.parent!=="scene"){let p=null;if(typeof i.parent=="string"?p=Sa(i.parent,s.scene,!0):p=i.parent,p){const g=i.keepWorldPosition===!0?p.attach:p.add;g?g.call(p,d):console.error("Invalid parent object",p,"received when instantiating:",t)}else console.warn("could not find parent:",i.parent)}for(const[p,g]of Object.entries(t.userData))p!=="components"&&(d.userData[p]=g);if((l=t.userData)!=null&&l.components){const p=t.userData.components,g=[];d.userData.components=g;for(let y=0;y<p.length;y++){const f=p[y],v=new f.constructor;La(v,f),f[rc]!==void 0&&(v[rc]=f[rc]),g.push(v),v.gameObject=d,n.push(v),o[f.guid]={original:f,clone:v},pc.dispatchComponentLifecycleEvent("component-added",v)}}i&&(i.position=void 0,i.rotation=void 0,i.scale=void 0,i.parent=void 0);for(const p in t.children){const g=t.children[p],y=F_(s,g,i,n,o,r);y&&d.add(y)}return d}function Nk(s,t){for(const i in s){const n=s[i],o=n.original,r=o.skeleton,l=n.clone;if(!r){console.warn("Skinned mesh has no skeleton?",n);continue}const c=r.bones,h=l.skeleton.clone();l.skeleton=h,l.bindMatrix.clone().copy(o.bindMatrix),l.bindMatrixInverse.copy(o.bindMatrixInverse);const d=[];h.bones=d;for(let u=0;u<c.length;u++){const p=c[u],g=t[p.uuid].clone;d.push(g)}}for(const i in s){const n=s[i].clone;n.skeleton.update(),n.bind(n.skeleton,n.bindMatrix),n.updateMatrixWorld(!0)}}function Wk(s){var t;for(const i in s){const n=s[i].clone;if(n!=null&&n.isObject3D&&(t=n?.userData)!=null&&t.components)for(let o=0;o<n.userData.components.length;o++){const r=n.userData.components[o],l=Object.entries(r);for(const[c,h]of l)if(Array.isArray(h)){const d=[];r[c]=d;for(let u=0;u<h.length;u++){const p=h[u];if(typeof p!="object"){d.push(p);continue}const g=z_(r,c,p,s);g!==void 0?d.push(g):d.push(p)}}else if(typeof h=="object"){const d=z_(r,c,h,s);d!==void 0&&(r[c]=d)}}}}function z_(s,t,i,n){var o,r;if(i!=null)if(i.isComponent===!0){const l=i.gameObject;if(l){const c=l.uuid,h=(o=n[c])==null?void 0:o.clone;if(!h){Yd&&console.log("reference did not change",t,s,i);return}const d=l.userData.components.indexOf(i);if(d>=0&&h.isObject3D)return Yd&&console.log(t,c),h.userData.components[d];console.warn("could not find component",t,i)}}else if(i.isObject3D===!0){if(t==="gameObject")return;const l=i;if(l){const c=l.uuid,h=(r=n[c])==null?void 0:r.clone;if(h)return Yd&&console.log(t,"old",i,"new",h),h}}else{if(i.isVector4||i.isVector3||i.isVector2||i.isQuaternion||i.isEuler||i.isColor===!0)return i.clone();if(i.isEventList===!0)return i.__internalOnInstantiate(n)}}var Mr;(s=>{s.baseUrl="https://networking.needle.tools";function t(h){return gv(new Uint8Array(h))}s.hashMD5=t;function i(h){const d=gv(new Uint8Array(h),{encoding:"binary",asBytes:!0});return btoa(String.fromCharCode(...d))}s.hashMD5_Base64=i;function n(h){const d=new Uint8Array(h);return crypto.subtle.digest("SHA-256",d).then(u=>btoa(String.fromCharCode(...new Uint8Array(u))))}s.hashSha256=n;function o(h){const d=h.filesize/1024/1024;return Ss()?d<50:d<5}s.canUpload=o;async function r(h,d){var u;const p=s.baseUrl;if(p){if(!h.name)return console.error("Upload: file name is missing"),null}else return console.error("Blob storage base url is not set"),null;let g=null;h instanceof File?g=await h.arrayBuffer():g=h.data;const y=g.byteLength,f=y/1024/1024;if(f>50)return d?.silent!==!0&&_e(`File (${f.toFixed(1)}MB) is too large for uploading (see console for details)`),console.warn(`Your file is too large for uploading (${f.toFixed(1)}MB). Max allowed size is 50MB`),null;if(!Ss()&&f>5)return d?.silent!==!0&&_e('File is too large for uploading. Please get a <a href="https://needle.tools/pricing" target="_blank">commercial license</a> to upload files larger than 5MB'),console.warn(`Your file is too large for uploading (${f.toFixed(1)}MB). Max size is 5MB for non-commercial users. Please get a commercial license at https://needle.tools/pricing for larger files (up to 50MB)`),null;if(y<1)return console.warn(`Your file is too small for uploading (${f.toFixed(1)}MB). Min size is 1 byte`),null;const v=i(g),b={filename:h.name,"Content-Md5":v,"Content-Type":h.type||"application/octet-stream",FileSize:y.toString(),"Content-Disposition":`attachment; filename="${h.name}"`,"x-amz-server-side-encryption":"AES256"},w=await fetch(p+"/api/needle/blob",{method:"POST",headers:b,signal:d?.abort}).then(_=>_.json()).catch(_=>(console.error(_),null));if(w==null)return console.warn("Upload failed..."),null;if("error"in w)return console.error(w.error),null;if("upload"in w&&w.upload){let _=function(M){var E;return(E=d?.onProgress)==null||E.call(null,{progress01:0,state:"inprogress"}),fetch(M,{method:"PUT",headers:b,body:g,signal:d?.abort}).then(D=>{var L;return(L=d?.onProgress)==null||L.call(null,{progress01:1,state:"finished"}),D}).catch(D=>D)};console.debug("Uploading file",w.upload);let C=!1,R=null;for(let M=0;M<3;M++)try{if(C)break;if((u=d?.abort)!=null&&u.aborted)return console.debug("Aborted upload"),null;const E=await _(w.upload);E instanceof Error?(R=E,await gs(1e3*M)):E.ok&&(console.debug("File uploaded successfully"),C=!0)}catch(E){console.error(E)}if(!C)return console.error(R?.message||"Failed to upload file"),null}if("download"in w){const _=p+w.download;return console.debug("File found in blob storage",_),{key:w.key,success:!0,download_url:_}}return null}s.upload=r;function l(h){return`${s.baseUrl}/api/needle/blob/${h}`}s.getBlobUrlForKey=l;async function c(h,d){var u;const p=await fetch(h),g=(u=p.body)==null?void 0:u.getReader(),y=p.headers.get("Content-Length"),f=y?parseInt(y):0;if(!g)return null;let v=0;const b=[];for(;;){const{done:C,value:R}=await g.read();if(R&&(b.push(R),v+=R.length,d?.call(null,new ProgressEvent("progress",{loaded:v,total:f}))),C)break}const w=new Uint8Array(v);let _=0;for(const C of b)w.set(C,_),_+=C.length;return w}s.download=c})(Mr||(Mr={}));const fo=O("debugaddressables");class U_{constructor(t){a(this,"_context"),a(this,"_assetReferences",{}),a(this,"preUpdate",()=>{}),this._context=t,this._context.pre_update_callbacks.push(this.preUpdate)}dispose(){const t=this._context.pre_update_callbacks.indexOf(this.preUpdate);t>=0&&this._context.pre_update_callbacks.splice(t,1);for(const i in this._assetReferences){const n=this._assetReferences[i];n?.unload()}this._assetReferences={}}findAssetReference(t){return this._assetReferences[t]||null}registerAssetReference(t){return t.url&&(this._assetReferences[t.url]?console.warn("Asset reference already registered",t):this._assetReferences[t.url]=t),t}unregisterAssetReference(t){t.url&&delete this._assetReferences[t.url]}}const Yg=Symbol("assetReference"),Ua=class{constructor(s,t,i=null){a(this,"_loading"),a(this,"_asset"),a(this,"_glbRoot"),a(this,"_url"),a(this,"_progressListeners",[]),a(this,"_hash"),a(this,"_hashedUri"),a(this,"_isLoadingRawBinary",!1),a(this,"_rawBinary"),this._url=s,this._hash=t,s.includes("?v=")?this._hashedUri=s:this._hashedUri=t?s+"?v="+t:s,i!==null&&(this.asset=i),p_(this._url,this.onResolvePrefab.bind(this))}static getOrCreateFromUrl(s,t){if(!t&&(t=te.Current,!t))throw new Error('Context is required when sourceId is a string. When you call this method from a component you can call it with "getOrCreate(this, url)" where "this" is the component.');const i=t.addressables,n=i.findAssetReference(s);if(n)return n;const o=new Ua(s,t.hash);return i.registerAssetReference(o),o}static getOrCreate(s,t,i){if(typeof s=="string"){if(!i&&(i=te.Current,!i))throw new Error('Context is required when sourceId is a string. When you call this method from a component you can call it with "getOrCreate(this, url)" where "this" is the component.')}else i=s.context,s=s.sourceId;const n=co(s,t);fo&&console.log("GetOrCreate Addressable from",s,t,"FinalPath=",n);const o=i.addressables,r=o.findAssetReference(n);if(r)return r;const l=new Ua(n,i.hash);return o.registerAssetReference(l),l}get isAssetReference(){return!0}get asset(){return this._glbRoot??this._asset}set asset(s){this._asset=s}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(s){return s===this.url&&(this.mustLoad&&await this.loadAssetAsync(),this.asset)?this.asset:null}get mustLoad(){return!this.asset||this.asset.__destroyed===!0||Pr(this.asset)===!0}isLoaded(){return this._rawBinary||this.asset!==void 0}unload(){this.asset&&(fo&&console.log("Unload",this.asset),"scene"in this.asset&&this.asset.scene&&Mi(this.asset.scene,!0,!0),Mi(this.asset,!0,!0)),this.asset=null,this._rawBinary=void 0,this._glbRoot=null,this._loading=void 0,te.Current&&te.Current.addressables.unregisterAssetReference(this)}async preload(){if(!this.mustLoad||this._isLoadingRawBinary)return null;if(this._rawBinary!==void 0)return this._rawBinary;this._isLoadingRawBinary=!0,fo&&console.log("Preload",this._hashedUri);const s=await Mr.download(this._hashedUri,t=>{this.raiseProgressEvent(t)});return this._rawBinary=s?.buffer??null,this._isLoadingRawBinary=!1,this._rawBinary}async loadAssetAsync(s){if(fo&&console.log("loadAssetAsync",this.url),!this.mustLoad)return this.asset;if(s&&this._progressListeners.push(s),this._loading!==void 0)return this._loading.then(n=>this.asset);const t=te.Current;if(this._rawBinary){if(!(this._rawBinary instanceof ArrayBuffer))return console.error("Invalid raw binary data",this._rawBinary),null;this._loading=ms().parseSync(t,this._rawBinary,this.url,null),this.raiseProgressEvent(new ProgressEvent("progress",{loaded:this._rawBinary.byteLength,total:this._rawBinary.byteLength}))}else fo&&console.log("Load async",this.url),this._loading=ms().loadSync(t,this._hashedUri,this.url,null,n=>{this.raiseProgressEvent(n)});const i=await this._loading;return this._progressListeners.length=0,this._glbRoot=this.tryGetActualGameObjectRoot(i),this._loading=void 0,i?(i[Yg]=this,this._glbRoot&&(this._glbRoot[Yg]=this),this.asset&&(this.asset[Yg]=this),zd(t),i.scene!==void 0&&(this.asset=i),this.asset):null}async instantiate(s){return this.onInstantiate(s,!1)}async instantiateSynced(s,t=!0){return this.onInstantiate(s,!0,t)}beginListenDownload(s){this._progressListeners.indexOf(s)<0&&this._progressListeners.push(s)}endListenDownload(s){const t=this._progressListeners.indexOf(s);t>=0&&this._progressListeners.splice(t,1)}raiseProgressEvent(s){for(const t of this._progressListeners)t(this,s)}async onInstantiate(s,t=!1,i){const n=te.Current,o=new js;if(s instanceof j?o.parent=s:s&&(Object.assign(o,s),o.cloneAssign(s)),o.parent||(o.parent=n.scene),this.mustLoad&&await this.loadAssetAsync(),fo&&console.log("Instantiate",this.url,"parent:",s),this.asset){fo&&console.log("Add to scene",this.asset);let r=Ua.currentlyInstantiating.get(this.url);if(r!==void 0&&r>=1e4)return console.error("Recursive or too many instantiations of "+this.url+" in the same frame ("+r+")"),null;try{if(r===void 0&&(r=0),r+=1,Ua.currentlyInstantiating.set(this.url,r),t){o.context=n;const l=this.asset;l.guid=this.url;const c=Bg(l,o,void 0,i);if(c)return c}else{const l=za(this.asset,o);if(l)return l}}finally{n.post_render_callbacks.push(()=>{r===void 0||r<0?r=0:r-=1,Ua.currentlyInstantiating.set(this.url,r)})}}else fo&&console.warn("Failed to load asset",this.url);return null}tryGetActualGameObjectRoot(s){if(s&&s.scene){const t=s.scene;return t.isGroup&&t.children.length===1&&t.children[0].name+"glb"===t.name?t.children[0]:t}return null}};let le=Ua;a(le,"currentlyInstantiating",new Map);class Vk extends Ki{constructor(){super([le],"AssetReferenceSerializer")}onSerialize(t,i){if(t&&t.uri!==void 0&&typeof t.uri=="string")return t.uri}onDeserialize(t,i){if(typeof t=="string")return i.context?i.gltfId?le.getOrCreate(i.gltfId,t,i.context):(console.error("Missing source id"),null):(console.error("Missing context"),null);if(t instanceof j){if(!i.context)return console.error("Missing context"),null;if(!i.gltfId)return console.error("Missing source id"),null;const n=t,o=i.context,r=n.guid??n.uuid,l=o.addressables.findAssetReference(r);if(l)return l;const c=new le(r,void 0,n);return o.addressables.registerAssetReference(c),c}return null}}new Vk;const Hk=Promise.resolve(null),tu=class{constructor(s){a(this,"url"),a(this,"_bitmap"),a(this,"_bitmapObject"),a(this,"loader",null),this.url=s}static getOrCreate(s){let t=tu.imageReferences.get(s);return t||(t=new tu(s),tu.imageReferences.set(s,t)),t}dispose(){this._bitmapObject&&this._bitmapObject.close(),this._bitmap=void 0}createHTMLImage(){const s=new Image;return s.src=this.url,s}createTexture(){return this.url?(this.loader||(this.loader=new va),this.loader.setCrossOrigin("anonymous"),this.loader.loadAsync(this.url)):Hk}getBitmap(){return this._bitmap?this._bitmap:(this._bitmap=new Promise((s,t)=>{const i=document.createElement("img");i.addEventListener("load",()=>{this._bitmap=createImageBitmap(i).then(n=>(this._bitmapObject=n,s(n),n))}),i.addEventListener("error",n=>{console.error("Failed to load image:"+this.url,n),s(null)}),i.src=this.url}),this._bitmap)}};let iu=tu;a(iu,"imageReferences",new Map);class N_ extends Ki{constructor(){super([iu],"ImageReferenceSerializer")}onSerialize(t,i){return null}onDeserialize(t,i){if(typeof t=="string"){const n=co(i.gltfId,t);return iu.getOrCreate(n)}}}new N_;const su=class{constructor(s){a(this,"url"),a(this,"res"),this.url=s}static getOrCreate(s){let t=su.cache.get(s);return t||(t=new su(s),su.cache.set(s,t)),t}async loadRaw(){return this.res||(this.res=fetch(this.url)),this.res.then(s=>s.blob())}async loadText(){return this.res||(this.res=fetch(this.url)),this.res.then(s=>s.text())}};let nu=su;a(nu,"cache",new Map);class W_ extends Ki{constructor(){super([nu],"FileReferenceSerializer")}onSerialize(t,i){return null}onDeserialize(t,i){if(typeof t=="string"){const n=co(i.gltfId,t);return nu.getOrCreate(n)}}}new W_;class $k{constructor(t){a(this,"context"),a(this,"mixers",[]),this.context=t}onDestroy(){this.mixers.forEach(t=>t.stopAllAction()),this.mixers.length=0}registerAnimationMixer(t){if(!t){console.warn("AnimationsRegistry.registerAnimationMixer called with null or undefined mixer");return}this.mixers.includes(t)||this.mixers.push(t)}unregisterAnimationMixer(t){if(!t){console.warn("AnimationsRegistry.unregisterAnimationMixer called with null or undefined mixer");return}const i=this.mixers.indexOf(t);i!==-1&&this.mixers.splice(i,1)}}class Na{static tryGetActionsFromMixer(t){return t._actions||null}static tryGetAnimationClipsFromObjectHierarchy(t,i){if(i||(i=new Array),t)t.animations&&i.push(...t.animations);else return i;if(t.children)for(const n of t.children)this.tryGetAnimationClipsFromObjectHierarchy(n,i);return i}static assignAnimationsFromFile(t,i){if(!t||!t.animations){console.debug("No animations found in file");return}for(let o=0;o<t.animations.length;o++){const r=t.animations[o];if(!r.tracks||r.tracks.length<=0){console.warn("Animation has no tracks");continue}for(const l in r.tracks){const c=r.tracks[l],h=ba.parseTrackName(c.name);let d=ba.findNode(t.scene,h.nodeName);if(!d){const p=c.__objectName??c.name.substring(0,c.name.indexOf("."));if(d=t.scene.getObjectByProperty("uuid",p),!d)continue}let u=n(d);if(!u){if(!(i!=null&&i.createAnimationComponent)){console.warn("No AnimationComponent found in parent hierarchy of object and no 'createAnimationComponent' callback was provided in options.");continue}u=i.createAnimationComponent(t.scene,r)}u.addClip&&u.addClip(r)}}function n(o){var r;if(!o)return null;const l=(r=o.userData)==null?void 0:r.components;if(l&&l.length>0){for(let c=0;c<l.length;c++)if(l[c].isAnimationComponent===!0)return o}return n(o.parent)}}}var ou=(s=>(s.Visible="application-visible",s.Hidden="application-hidden",s.MuteChanged="application-mutechanged",s))(ou||{});let ru=!1;const Wa=[];function Rr(){if(ru)return;F()&&console.debug("User interaction registered: audio can now be played"),ru=!0;const s=[...Wa];Wa.length=0,s.forEach(t=>t())}document.addEventListener("mousedown",Rr),document.addEventListener("pointerup",Rr),document.addEventListener("click",Rr),document.addEventListener("dragstart",Rr),document.addEventListener("touchend",Rr),document.addEventListener("keydown",Rr),Z.onXRSessionStart(()=>{Rr()});const V_=class extends EventTarget{constructor(s){super(),a(this,"_mute",!1),a(this,"context"),a(this,"_isVisible",!0),this.context=s,window.addEventListener("visibilitychange",this.onVisiblityChanged.bind(this),!1)}static get userInteractionRegistered(){return ru}static registerWaitForInteraction(s){if(s!==null){if(ru){s();return}Wa.indexOf(s)===-1&&Wa.push(s)}}static unregisterWaitForInteraction(s){const t=Wa.indexOf(s);t!==-1&&Wa.splice(t,1)}get muted(){return this._mute}set muted(s){s!==this._mute&&(this._mute=s,this.dispatchEvent(new Event("application-mutechanged")))}get hasFocus(){return document.hasFocus()}get isVisible(){return this._isVisible}onVisiblityChanged(s){switch(s.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 kn=V_;a(kn,"registerWaitForAllowAudio",V_.registerWaitForInteraction);function*H_(s,t=null){const i=t?t.time:te.Current.time,n=i.time;for(;i.time-n<s;)yield}function*qk(s){for(let t=0;t<s;t++)yield}function*$_(s){let t=!0;for(s.then(()=>t=!1),s.catch(()=>t=!1);t;)yield}const q_="NEEDLE_lightmaps",Cc=O("debuglightmapsextension")||O("debuglightmaps");var yo=(s=>(s[s.Lightmap=0]="Lightmap",s[s.Skybox=1]="Skybox",s[s.Reflection=2]="Reflection",s))(yo||{});class Gk{constructor(t,i,n){a(this,"parser"),a(this,"registry"),a(this,"source"),this.parser=t,this.registry=i,this.source=n}get name(){return q_}afterRoot(t){const i=this.parser.json.extensions;if(i){const n=i[q_];if(n){const o=n.textures;return o!=null&&o.length?(Cc&&console.log(n),new Promise(async(r,l)=>{const c=[];for(const d of o)if(d.pointer){Cc&&console.log(d);let u=null;if(d.pointer.startsWith("/textures/"))Cc&&console.log("Load texture from gltf",d.pointer),u=Ug(this.parser,d.pointer).then(p=>this.resolveTexture(d,p));else if(typeof d.pointer=="string"){Cc&&console.log("Load texture from path",d.pointer);const p=co(this.source,d.pointer);let g;p.endsWith(".exr")?g=new md(this.parser.options.manager):p.endsWith(".hdr")?g=new wm(this.parser.options.manager):g=new va(this.parser.options.manager),u=g.loadAsync(p,void 0).then(y=>this.resolveTexture(d,y))}else d.pointer;u&&c.push(u)}const h=await yd(c);h!=null&&h.anyFailed&&F()&&console.error("Failed to load lightmap extension",h),r()})):null}}return null}resolveTexture(t,i){const n=i;Cc&&console.log("Lightmap loaded:",n),n!=null&&n.isTexture&&(this.registry?(n.colorSpace=pr,this.registry.registerTexture(this.source,t.type,n,t.index)):console.log(yo[t.type],t.pointer,n))}}const G_=!!O("debuglightmaps");class Xk{constructor(t){a(this,"_context"),a(this,"_lightmaps",new Map),this._context=t}clear(){this._lightmaps.clear()}registerTexture(t,i,n,o){G_&&console.log("Registering ",yo[i]+' "'+t+'"',n),this._lightmaps.has(t)||this._lightmaps.set(t,new Map);const r=this._lightmaps.get(t),l=r?.get(i)??[];l.length<o&&(l.length=o+1),l[o]=n,r?.set(i,l)}tryGetLightmap(t,i=0){return this.tryGet(t,yo.Lightmap,i)}tryGetSkybox(t){return this.tryGet(t,yo.Skybox,0)}tryGetReflection(t){return this.tryGet(t,yo.Reflection,0)}tryGet(t,i,n){if(!t)return G_&&console.warn("Missing source id"),null;const o=this._lightmaps.get(t);if(!o)return null;const r=o.get(i);return r===void 0||!(r!=null&&r.length)||r.length<=n?null:r[n]}}qt.lights_fragment_maps=qt.lights_fragment_maps.replace("vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );",`
179
+ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis`,t))),k_()&&console.log("[onGetComponent] FIND",t),t==null))return null;for(let o=0;o<s.userData.components.length;o++){const r=s.userData.components[o];let l=Object.getPrototypeOf(r);for(;l;){if(l===t.prototype)if(k_()&&console.log("[onGetComponent] MATCH BY PROTOYPE",l),i)i.push(r);else return r;l=Object.getPrototypeOf(l)}}return i||null}function Or(s,t){const i=E_(s,t);return i?Array.isArray(i)?i[0]:i:null}function _c(s,t,i,n=!0){return i||(i=[]),n&&(i.length=0),E_(s,t,i),i}function wc(s,t,i){var n;const o=Or(s,t);if(i===!1&&o?.enabled===!1)return null;if(o)return o;for(let r=0;r<((n=s?.children)==null?void 0:n.length);r++){const l=wc(s.children[r],t);if(l)return l}return null}function Da(s,t,i,n=!0){var o;i||(i=[]),n&&(i.length=0),_c(s,t,i,!1);for(let r=0;r<((o=s?.children)==null?void 0:o.length);r++)Da(s.children[r],t,i,!1);return i}function xc(s,t){if(!s)return null;if(Array.isArray(s)){for(let n=0;n<s.length;n++){const o=U2(s[n]),r=xc(o,t);if(r)return r}return null}return Or(s,t)||(s.parent?xc(s.parent,t):null)}function qd(s,t,i,n=!0){return i||(i=[]),n&&(i.length=0),s?(_c(s,t,i,!1),s.parent?qd(s.parent,t,i,!1):i):i}function Gd(s,t=void 0,i=!0){if(!s)return null;if(!t&&(t=te.Current,!t))return console.error("Can not search object without any needle context or scene!!!"),null;let n=t;if(n.isScene||(n=t?.scene),!n)return null;for(const o in n.children){const r=n.children[o];if(i===!1&&r[xn]===!1)continue;const l=wc(r,s);if(l)return l}return null}function A_(s,t,i=void 0){if(!s)return t??[];if(t||(t=[]),t.length=0,!i&&(i=te.Current,!i))return console.error("Can not search object without any needle context or scene!!!"),t;"scene"in i&&(i=i.scene);const n=i;if(!n)return t;for(const o in n.children){const r=n.children[o];Da(r,s,t,!1)}return t}function Xd(s){s&&s.isObject3D===!0&&O_(s,j)}j.prototype.SetActive=function(s){this.visible=s},j.prototype.setActive=function(s){this.visible=s},j.prototype.destroy=function(){Mi(this)},j.prototype.addComponent=function(s,t){return ki(this,s,t)},j.prototype.addNewComponent=function(s,t){return ki(this,s,t)},j.prototype.removeComponent=function(s){return qg(this,s)},j.prototype.getOrAddComponent=function(s,t){return bc(this,s,t)},j.prototype.getComponent=function(s){return Or(this,s)},j.prototype.getComponents=function(s,t){return _c(this,s,t)},j.prototype.getComponentInChildren=function(s){return wc(this,s)},j.prototype.getComponentsInChildren=function(s,t){return Da(this,s,t)},j.prototype.getComponentInParent=function(s){return xc(this,s)},j.prototype.getComponentsInParent=function(s,t){return qd(this,s,t)},Object.getOwnPropertyDescriptor(j.prototype,"activeSelf")||Object.defineProperty(j.prototype,"activeSelf",{get:function(){return Ba(this)},set:function(s){Sc(this,s)}}),Object.getOwnPropertyDescriptor(j.prototype,"worldPosition")||Object.defineProperty(j.prototype,"worldPosition",{get:function(){return this instanceof lv?ee(this.object):ee(this)},set:function(s){lt(this,s)}}),Object.getOwnPropertyDescriptor(j.prototype,"worldQuaternion")||Object.defineProperty(j.prototype,"worldQuaternion",{get:function(){return this instanceof lv?Se(this.object):Se(this)},set:function(s){qi(this,s)}}),Object.getOwnPropertyDescriptor(j.prototype,"worldRotation")||Object.defineProperty(j.prototype,"worldRotation",{get:function(){return Zl(this)},set:function(s){Qm(this,s)}}),Object.getOwnPropertyDescriptor(j.prototype,"worldScale")||Object.defineProperty(j.prototype,"worldScale",{get:function(){return Ke(this)},set:function(s){Oa(this,s)}}),Object.getOwnPropertyDescriptor(j.prototype,"worldForward")||Object.defineProperty(j.prototype,"worldForward",{get:function(){return $().set(0,0,1).applyQuaternion(Se(this))}}),Object.getOwnPropertyDescriptor(j.prototype,"worldRight")||Object.defineProperty(j.prototype,"worldRight",{get:function(){return $().set(1,0,0).applyQuaternion(Se(this))}}),Object.getOwnPropertyDescriptor(j.prototype,"worldUp")||Object.defineProperty(j.prototype,"worldUp",{get:function(){return $().set(0,1,0).applyQuaternion(Se(this))}}),P_(j);class we extends ae{constructor(t,i,n,o){var r=(...l)=>{super(...l),a(this,"alpha",1)};i!=null&&n!=null?(r(t,i,n),this.alpha=o):(r(t),this.alpha=1)}get isRGBAColor(){return!0}set a(t){this.alpha=t}get a(){return this.alpha}clone(){const t=super.clone();return t.alpha=this.alpha,t}copy(t){return this.r=t.r,this.g=t.g,this.b=t.b,"alpha"in t&&typeof t.alpha=="number"?this.alpha=t.alpha:typeof t.a=="number"&&(this.alpha=t.a),this}lerp(t,i){const n=t;return n.alpha!=null&&(this.alpha=W.lerp(this.alpha,n.alpha,i)),super.lerp(t,i)}lerpColors(t,i,n){const o=t,r=i;return o.alpha!=null&&r.alpha!=null&&(this.alpha=W.lerp(o.alpha,r.alpha,n)),super.lerpColors(t,i,n)}multiply(t){const i=t;return i.alpha!=null&&(this.alpha=this.alpha*i.alpha),super.multiply(t)}fromArray(t,i=0){return this.alpha=t[i+3],super.fromArray(t,i)}}const Qd=O("debuggetcomponent"),Yd=O("debuginstantiate");class js{constructor(){a(this,"idProvider"),a(this,"parent"),a(this,"keepWorldPosition"),a(this,"position"),a(this,"rotation"),a(this,"scale"),a(this,"visible"),a(this,"context"),a(this,"components")}clone(){var t,i,n;const o=new js;return o.idProvider=this.idProvider,o.parent=this.parent,o.keepWorldPosition=this.keepWorldPosition,o.position=(t=this.position)==null?void 0:t.clone(),o.rotation=(i=this.rotation)==null?void 0:i.clone(),o.scale=(n=this.scale)==null?void 0:n.clone(),o.visible=this.visible,o.context=this.context,o.components=this.components,o}cloneAssign(t){var i,n,o;this.idProvider=t.idProvider,this.parent=t.parent,this.keepWorldPosition=t.keepWorldPosition,this.position=(i=t.position)==null?void 0:i.clone(),this.rotation=(n=t.rotation)==null?void 0:n.clone(),this.scale=(o=t.scale)==null?void 0:o.clone(),this.visible=t.visible,this.context=t.context,this.components=t.components}}function Ba(s){return s.visible}function Sc(s,t){return typeof t=="number"&&(t=t>.5),s.visible=t,s.visible}function I_(s){return s[xn]||Kd(s)}function j_(s,t){s[t_]=t}function Kd(s){return cs.isUsingInstancing(s)}function Gg(s,t){return Sa(s,t,!0,!0)}const L_=Symbol("isDestroyed");function Pr(s){return s[L_]}function D_(s,t){s[L_]=t}const Xg=Symbol("isDontDestroy");function Fa(s,t=!0){s[Xg]=t}const Zd=[],Jd=[];function Mi(s,t=!0,i=!1){Zd.length=0,Jd.length=0,Qg(s,t,!0);for(const n of Zd)n.gameObject=null,n.context=null;for(const n of Jd)D_(n,!0),i&&Te(n),Jb(n);Jd.length=0,Zd.length=0}function Qg(s,t=!0,i=!0){var n;if(s==null)return;const o=s;if(o.isComponent){if(o[Xg])return;Zd.push(o);const c=o.gameObject;o.__internalDisable(),o.__internalDestroy(),o.gameObject=c;return}if(s[Xg])return;const r=s;Qd&&console.log(r),Jd.push(r);const l=(n=r.userData)==null?void 0:n.components;if(l!=null&&Array.isArray(l)){let c=l.length;for(let h=0;h<l.length;h++){const d=l[h];Qg(d,t,!1),l.length<c&&(c=l.length,h--)}}if(t&&r.children)for(const c of r.children)Qg(c,t,!1);i&&r.removeFromParent()}function kr(s,t,i=!0){return B_(s,t,i)}function*eu(s,t,i=!1,n=999,o=0){if(s!=null&&s.userData.components&&!(o>n)){for(const r of s.userData.components)t&&r?.isComponent===!0&&r instanceof t?yield r:yield r;if(i===!0)for(const r of s.children)yield*eu(r,t,!0,n,o+1)}}function B_(s,t,i,n=0){var o;if(s){if(s.isObject3D,n>1e3){console.warn("Failed to iterate components: too many levels");return}if((o=s.userData)!=null&&o.components)for(let r=0;r<s.userData.components.length;r++){const l=s.userData.components[r];if(l?.isComponent===!0){const c=t(l);if(c!==void 0)return c}}if(i&&s.children){const r=n+1;for(let l=0;l<s.children.length;l++){const c=s.children[l];if(!c)continue;const h=B_(c,t,i,r);if(h!==void 0)return h}}}}function za(s,t){if("isAssetReference"in s)return s.instantiate(t??void 0);let i=null;t!=null&&(t.x!==void 0?(i=new js,i.position=t):i=t);let n=te.Current;i!=null&&i.context&&(n=i.context),Qd&&n.alias&&console.log("context",n.alias),i&&!i.idProvider&&(i.idProvider=new Bt(Date.now()));const o=[],r={},l={},c=F_(n,s,i,o,r,l);c&&(W2(r),N2(l,r)),Qd&&(xd(s,!0),xd(c,!0));const h={};if(i?.components!==!1){for(const d in o){const u=o[d],p=u.guid;i&&i.idProvider&&(u.guid=i.idProvider.generateUUID(),h[p]=u.guid,Qd&&console.log(u.name,u.guid)),fu(u,n),u.__internalNewInstanceCreated&&u.__internalNewInstanceCreated()}for(const d in o){const u=o[d];u.resolveGuids&&u.resolveGuids(h),u.enabled!==!1&&(u.enabled=!0)}zd(n)}return c}function F_(s,t,i,n,o,r){var l;if(!t)return null;const c=t.userData;t.userData={};const h=t.children;t.children=[];const d=t.clone(!1);if(Xd(d),t.userData=c,t.children=h,o[t.uuid]={original:t,clone:d},Yd&&console.log("ADD",t,d),t.type==="SkinnedMesh"&&(r[t.uuid]={original:t,clone:d}),i?.visible!==void 0&&(d.visible=i.visible),i!=null&&i.idProvider){d.uuid=i.idProvider.generateUUID();const p=d;p&&(p.guid=d.uuid)}t.animations&&t.animations.length>0&&(d.animations=[...t.animations]);const u=t.parent;if(u&&u.add(d),i!=null&&i.position?lt(d,i.position):d.position.copy(t.position),i!=null&&i.rotation?qi(d,i.rotation):d.quaternion.copy(t.quaternion),i!=null&&i.scale?d.scale.copy(i.scale):d.scale.copy(t.scale),i!=null&&i.parent&&i.parent!=="scene"){let p=null;if(typeof i.parent=="string"?p=Sa(i.parent,s.scene,!0):p=i.parent,p){const g=i.keepWorldPosition===!0?p.attach:p.add;g?g.call(p,d):console.error("Invalid parent object",p,"received when instantiating:",t)}else console.warn("could not find parent:",i.parent)}for(const[p,g]of Object.entries(t.userData))p!=="components"&&(d.userData[p]=g);if((l=t.userData)!=null&&l.components){const p=t.userData.components,g=[];d.userData.components=g;for(let y=0;y<p.length;y++){const f=p[y],v=new f.constructor;La(v,f),f[rc]!==void 0&&(v[rc]=f[rc]),g.push(v),v.gameObject=d,n.push(v),o[f.guid]={original:f,clone:v},pc.dispatchComponentLifecycleEvent("component-added",v)}}i&&(i.position=void 0,i.rotation=void 0,i.scale=void 0,i.parent=void 0);for(const p in t.children){const g=t.children[p],y=F_(s,g,i,n,o,r);y&&d.add(y)}return d}function N2(s,t){for(const i in s){const n=s[i],o=n.original,r=o.skeleton,l=n.clone;if(!r){console.warn("Skinned mesh has no skeleton?",n);continue}const c=r.bones,h=l.skeleton.clone();l.skeleton=h,l.bindMatrix.clone().copy(o.bindMatrix),l.bindMatrixInverse.copy(o.bindMatrixInverse);const d=[];h.bones=d;for(let u=0;u<c.length;u++){const p=c[u],g=t[p.uuid].clone;d.push(g)}}for(const i in s){const n=s[i].clone;n.skeleton.update(),n.bind(n.skeleton,n.bindMatrix),n.updateMatrixWorld(!0)}}function W2(s){var t;for(const i in s){const n=s[i].clone;if(n!=null&&n.isObject3D&&(t=n?.userData)!=null&&t.components)for(let o=0;o<n.userData.components.length;o++){const r=n.userData.components[o],l=Object.entries(r);for(const[c,h]of l)if(Array.isArray(h)){const d=[];r[c]=d;for(let u=0;u<h.length;u++){const p=h[u];if(typeof p!="object"){d.push(p);continue}const g=z_(r,c,p,s);g!==void 0?d.push(g):d.push(p)}}else if(typeof h=="object"){const d=z_(r,c,h,s);d!==void 0&&(r[c]=d)}}}}function z_(s,t,i,n){var o,r;if(i!=null)if(i.isComponent===!0){const l=i.gameObject;if(l){const c=l.uuid,h=(o=n[c])==null?void 0:o.clone;if(!h){Yd&&console.log("reference did not change",t,s,i);return}const d=l.userData.components.indexOf(i);if(d>=0&&h.isObject3D)return Yd&&console.log(t,c),h.userData.components[d];console.warn("could not find component",t,i)}}else if(i.isObject3D===!0){if(t==="gameObject")return;const l=i;if(l){const c=l.uuid,h=(r=n[c])==null?void 0:r.clone;if(h)return Yd&&console.log(t,"old",i,"new",h),h}}else{if(i.isVector4||i.isVector3||i.isVector2||i.isQuaternion||i.isEuler||i.isColor===!0)return i.clone();if(i.isEventList===!0)return i.__internalOnInstantiate(n)}}var Mr;(s=>{s.baseUrl="https://networking.needle.tools";function t(h){return gv(new Uint8Array(h))}s.hashMD5=t;function i(h){const d=gv(new Uint8Array(h),{encoding:"binary",asBytes:!0});return btoa(String.fromCharCode(...d))}s.hashMD5_Base64=i;function n(h){const d=new Uint8Array(h);return crypto.subtle.digest("SHA-256",d).then(u=>btoa(String.fromCharCode(...new Uint8Array(u))))}s.hashSha256=n;function o(h){const d=h.filesize/1024/1024;return Ss()?d<50:d<5}s.canUpload=o;async function r(h,d){var u;const p=s.baseUrl;if(p){if(!h.name)return console.error("Upload: file name is missing"),null}else return console.error("Blob storage base url is not set"),null;let g=null;h instanceof File?g=await h.arrayBuffer():g=h.data;const y=g.byteLength,f=y/1024/1024;if(f>50)return d?.silent!==!0&&_e(`File (${f.toFixed(1)}MB) is too large for uploading (see console for details)`),console.warn(`Your file is too large for uploading (${f.toFixed(1)}MB). Max allowed size is 50MB`),null;if(!Ss()&&f>5)return d?.silent!==!0&&_e('File is too large for uploading. Please get a <a href="https://needle.tools/pricing" target="_blank">commercial license</a> to upload files larger than 5MB'),console.warn(`Your file is too large for uploading (${f.toFixed(1)}MB). Max size is 5MB for non-commercial users. Please get a commercial license at https://needle.tools/pricing for larger files (up to 50MB)`),null;if(y<1)return console.warn(`Your file is too small for uploading (${f.toFixed(1)}MB). Min size is 1 byte`),null;const v=i(g),b={filename:h.name,"Content-Md5":v,"Content-Type":h.type||"application/octet-stream",FileSize:y.toString(),"Content-Disposition":`attachment; filename="${h.name}"`,"x-amz-server-side-encryption":"AES256"},w=await fetch(p+"/api/needle/blob",{method:"POST",headers:b,signal:d?.abort}).then(_=>_.json()).catch(_=>(console.error(_),null));if(w==null)return console.warn("Upload failed..."),null;if("error"in w)return console.error(w.error),null;if("upload"in w&&w.upload){let _=function(M){var E;return(E=d?.onProgress)==null||E.call(null,{progress01:0,state:"inprogress"}),fetch(M,{method:"PUT",headers:b,body:g,signal:d?.abort}).then(D=>{var L;return(L=d?.onProgress)==null||L.call(null,{progress01:1,state:"finished"}),D}).catch(D=>D)};console.debug("Uploading file",w.upload);let C=!1,R=null;for(let M=0;M<3;M++)try{if(C)break;if((u=d?.abort)!=null&&u.aborted)return console.debug("Aborted upload"),null;const E=await _(w.upload);E instanceof Error?(R=E,await gs(1e3*M)):E.ok&&(console.debug("File uploaded successfully"),C=!0)}catch(E){console.error(E)}if(!C)return console.error(R?.message||"Failed to upload file"),null}if("download"in w){const _=p+w.download;return console.debug("File found in blob storage",_),{key:w.key,success:!0,download_url:_}}return null}s.upload=r;function l(h){return`${s.baseUrl}/api/needle/blob/${h}`}s.getBlobUrlForKey=l;async function c(h,d){var u;const p=await fetch(h),g=(u=p.body)==null?void 0:u.getReader(),y=p.headers.get("Content-Length"),f=y?parseInt(y):0;if(!g)return null;let v=0;const b=[];for(;;){const{done:C,value:R}=await g.read();if(R&&(b.push(R),v+=R.length,d?.call(null,new ProgressEvent("progress",{loaded:v,total:f}))),C)break}const w=new Uint8Array(v);let _=0;for(const C of b)w.set(C,_),_+=C.length;return w}s.download=c})(Mr||(Mr={}));const fo=O("debugaddressables");class U_{constructor(t){a(this,"_context"),a(this,"_assetReferences",{}),a(this,"preUpdate",()=>{}),this._context=t,this._context.pre_update_callbacks.push(this.preUpdate)}dispose(){const t=this._context.pre_update_callbacks.indexOf(this.preUpdate);t>=0&&this._context.pre_update_callbacks.splice(t,1);for(const i in this._assetReferences){const n=this._assetReferences[i];n?.unload()}this._assetReferences={}}findAssetReference(t){return this._assetReferences[t]||null}registerAssetReference(t){return t.url&&(this._assetReferences[t.url]?console.warn("Asset reference already registered",t):this._assetReferences[t.url]=t),t}unregisterAssetReference(t){t.url&&delete this._assetReferences[t.url]}}const Yg=Symbol("assetReference"),Ua=class{constructor(s,t,i=null){a(this,"_loading"),a(this,"_asset"),a(this,"_glbRoot"),a(this,"_url"),a(this,"_progressListeners",[]),a(this,"_hash"),a(this,"_hashedUri"),a(this,"_isLoadingRawBinary",!1),a(this,"_rawBinary"),this._url=s,this._hash=t,s.includes("?v=")?this._hashedUri=s:this._hashedUri=t?s+"?v="+t:s,i!==null&&(this.asset=i),p_(this._url,this.onResolvePrefab.bind(this))}static getOrCreateFromUrl(s,t){if(!t&&(t=te.Current,!t))throw new Error('Context is required when sourceId is a string. When you call this method from a component you can call it with "getOrCreate(this, url)" where "this" is the component.');const i=t.addressables,n=i.findAssetReference(s);if(n)return n;const o=new Ua(s,t.hash);return i.registerAssetReference(o),o}static getOrCreate(s,t,i){if(typeof s=="string"){if(!i&&(i=te.Current,!i))throw new Error('Context is required when sourceId is a string. When you call this method from a component you can call it with "getOrCreate(this, url)" where "this" is the component.')}else i=s.context,s=s.sourceId;const n=co(s,t);fo&&console.log("GetOrCreate Addressable from",s,t,"FinalPath=",n);const o=i.addressables,r=o.findAssetReference(n);if(r)return r;const l=new Ua(n,i.hash);return o.registerAssetReference(l),l}get isAssetReference(){return!0}get asset(){return this._glbRoot??this._asset}set asset(s){this._asset=s}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(s){return s===this.url&&(this.mustLoad&&await this.loadAssetAsync(),this.asset)?this.asset:null}get mustLoad(){return!this.asset||this.asset.__destroyed===!0||Pr(this.asset)===!0}isLoaded(){return this._rawBinary||this.asset!==void 0}unload(){this.asset&&(fo&&console.log("Unload",this.asset),"scene"in this.asset&&this.asset.scene&&Mi(this.asset.scene,!0,!0),Mi(this.asset,!0,!0)),this.asset=null,this._rawBinary=void 0,this._glbRoot=null,this._loading=void 0,te.Current&&te.Current.addressables.unregisterAssetReference(this)}async preload(){if(!this.mustLoad||this._isLoadingRawBinary)return null;if(this._rawBinary!==void 0)return this._rawBinary;this._isLoadingRawBinary=!0,fo&&console.log("Preload",this._hashedUri);const s=await Mr.download(this._hashedUri,t=>{this.raiseProgressEvent(t)});return this._rawBinary=s?.buffer??null,this._isLoadingRawBinary=!1,this._rawBinary}async loadAssetAsync(s){if(fo&&console.log("loadAssetAsync",this.url),!this.mustLoad)return this.asset;if(s&&this._progressListeners.push(s),this._loading!==void 0)return this._loading.then(n=>this.asset);const t=te.Current;if(this._rawBinary){if(!(this._rawBinary instanceof ArrayBuffer))return console.error("Invalid raw binary data",this._rawBinary),null;this._loading=ms().parseSync(t,this._rawBinary,this.url,null),this.raiseProgressEvent(new ProgressEvent("progress",{loaded:this._rawBinary.byteLength,total:this._rawBinary.byteLength}))}else fo&&console.log("Load async",this.url),this._loading=ms().loadSync(t,this._hashedUri,this.url,null,n=>{this.raiseProgressEvent(n)});const i=await this._loading;return this._progressListeners.length=0,this._glbRoot=this.tryGetActualGameObjectRoot(i),this._loading=void 0,i?(i[Yg]=this,this._glbRoot&&(this._glbRoot[Yg]=this),this.asset&&(this.asset[Yg]=this),zd(t),i.scene!==void 0&&(this.asset=i),this.asset):null}async instantiate(s){return this.onInstantiate(s,!1)}async instantiateSynced(s,t=!0){return this.onInstantiate(s,!0,t)}beginListenDownload(s){this._progressListeners.indexOf(s)<0&&this._progressListeners.push(s)}endListenDownload(s){const t=this._progressListeners.indexOf(s);t>=0&&this._progressListeners.splice(t,1)}raiseProgressEvent(s){for(const t of this._progressListeners)t(this,s)}async onInstantiate(s,t=!1,i){const n=te.Current,o=new js;if(s instanceof j?o.parent=s:s&&(Object.assign(o,s),o.cloneAssign(s)),o.parent||(o.parent=n.scene),this.mustLoad&&await this.loadAssetAsync(),fo&&console.log("Instantiate",this.url,"parent:",s),this.asset){fo&&console.log("Add to scene",this.asset);let r=Ua.currentlyInstantiating.get(this.url);if(r!==void 0&&r>=1e4)return console.error("Recursive or too many instantiations of "+this.url+" in the same frame ("+r+")"),null;try{if(r===void 0&&(r=0),r+=1,Ua.currentlyInstantiating.set(this.url,r),t){o.context=n;const l=this.asset;l.guid=this.url;const c=Bg(l,o,void 0,i);if(c)return c}else{const l=za(this.asset,o);if(l)return l}}finally{n.post_render_callbacks.push(()=>{r===void 0||r<0?r=0:r-=1,Ua.currentlyInstantiating.set(this.url,r)})}}else fo&&console.warn("Failed to load asset",this.url);return null}tryGetActualGameObjectRoot(s){if(s&&s.scene){const t=s.scene;return t.isGroup&&t.children.length===1&&t.children[0].name+"glb"===t.name?t.children[0]:t}return null}};let le=Ua;a(le,"currentlyInstantiating",new Map);class V2 extends Ki{constructor(){super([le],"AssetReferenceSerializer")}onSerialize(t,i){if(t&&t.uri!==void 0&&typeof t.uri=="string")return t.uri}onDeserialize(t,i){if(typeof t=="string")return i.context?i.gltfId?le.getOrCreate(i.gltfId,t,i.context):(console.error("Missing source id"),null):(console.error("Missing context"),null);if(t instanceof j){if(!i.context)return console.error("Missing context"),null;if(!i.gltfId)return console.error("Missing source id"),null;const n=t,o=i.context,r=n.guid??n.uuid,l=o.addressables.findAssetReference(r);if(l)return l;const c=new le(r,void 0,n);return o.addressables.registerAssetReference(c),c}return null}}new V2;const H2=Promise.resolve(null),tu=class{constructor(s){a(this,"url"),a(this,"_bitmap"),a(this,"_bitmapObject"),a(this,"loader",null),this.url=s}static getOrCreate(s){let t=tu.imageReferences.get(s);return t||(t=new tu(s),tu.imageReferences.set(s,t)),t}dispose(){this._bitmapObject&&this._bitmapObject.close(),this._bitmap=void 0}createHTMLImage(){const s=new Image;return s.src=this.url,s}createTexture(){return this.url?(this.loader||(this.loader=new va),this.loader.setCrossOrigin("anonymous"),this.loader.loadAsync(this.url)):H2}getBitmap(){return this._bitmap?this._bitmap:(this._bitmap=new Promise((s,t)=>{const i=document.createElement("img");i.addEventListener("load",()=>{this._bitmap=createImageBitmap(i).then(n=>(this._bitmapObject=n,s(n),n))}),i.addEventListener("error",n=>{console.error("Failed to load image:"+this.url,n),s(null)}),i.src=this.url}),this._bitmap)}};let iu=tu;a(iu,"imageReferences",new Map);class N_ extends Ki{constructor(){super([iu],"ImageReferenceSerializer")}onSerialize(t,i){return null}onDeserialize(t,i){if(typeof t=="string"){const n=co(i.gltfId,t);return iu.getOrCreate(n)}}}new N_;const su=class{constructor(s){a(this,"url"),a(this,"res"),this.url=s}static getOrCreate(s){let t=su.cache.get(s);return t||(t=new su(s),su.cache.set(s,t)),t}async loadRaw(){return this.res||(this.res=fetch(this.url)),this.res.then(s=>s.blob())}async loadText(){return this.res||(this.res=fetch(this.url)),this.res.then(s=>s.text())}};let nu=su;a(nu,"cache",new Map);class W_ extends Ki{constructor(){super([nu],"FileReferenceSerializer")}onSerialize(t,i){return null}onDeserialize(t,i){if(typeof t=="string"){const n=co(i.gltfId,t);return nu.getOrCreate(n)}}}new W_;class $2{constructor(t){a(this,"context"),a(this,"mixers",[]),this.context=t}onDestroy(){this.mixers.forEach(t=>t.stopAllAction()),this.mixers.length=0}registerAnimationMixer(t){if(!t){console.warn("AnimationsRegistry.registerAnimationMixer called with null or undefined mixer");return}this.mixers.includes(t)||this.mixers.push(t)}unregisterAnimationMixer(t){if(!t){console.warn("AnimationsRegistry.unregisterAnimationMixer called with null or undefined mixer");return}const i=this.mixers.indexOf(t);i!==-1&&this.mixers.splice(i,1)}}class Na{static tryGetActionsFromMixer(t){return t._actions||null}static tryGetAnimationClipsFromObjectHierarchy(t,i){if(i||(i=new Array),t)t.animations&&i.push(...t.animations);else return i;if(t.children)for(const n of t.children)this.tryGetAnimationClipsFromObjectHierarchy(n,i);return i}static assignAnimationsFromFile(t,i){if(!t||!t.animations){console.debug("No animations found in file");return}for(let o=0;o<t.animations.length;o++){const r=t.animations[o];if(!r.tracks||r.tracks.length<=0){console.warn("Animation has no tracks");continue}for(const l in r.tracks){const c=r.tracks[l],h=ba.parseTrackName(c.name);let d=ba.findNode(t.scene,h.nodeName);if(!d){const p=c.__objectName??c.name.substring(0,c.name.indexOf("."));if(d=t.scene.getObjectByProperty("uuid",p),!d)continue}let u=n(d);if(!u){if(!(i!=null&&i.createAnimationComponent)){console.warn("No AnimationComponent found in parent hierarchy of object and no 'createAnimationComponent' callback was provided in options.");continue}u=i.createAnimationComponent(t.scene,r)}u.addClip&&u.addClip(r)}}function n(o){var r;if(!o)return null;const l=(r=o.userData)==null?void 0:r.components;if(l&&l.length>0){for(let c=0;c<l.length;c++)if(l[c].isAnimationComponent===!0)return o}return n(o.parent)}}}var ou=(s=>(s.Visible="application-visible",s.Hidden="application-hidden",s.MuteChanged="application-mutechanged",s))(ou||{});let ru=!1;const Wa=[];function Rr(){if(ru)return;F()&&console.debug("User interaction registered: audio can now be played"),ru=!0;const s=[...Wa];Wa.length=0,s.forEach(t=>t())}document.addEventListener("mousedown",Rr),document.addEventListener("pointerup",Rr),document.addEventListener("click",Rr),document.addEventListener("dragstart",Rr),document.addEventListener("touchend",Rr),document.addEventListener("keydown",Rr),Z.onXRSessionStart(()=>{Rr()});const V_=class extends EventTarget{constructor(s){super(),a(this,"_mute",!1),a(this,"context"),a(this,"_isVisible",!0),this.context=s,window.addEventListener("visibilitychange",this.onVisiblityChanged.bind(this),!1)}static get userInteractionRegistered(){return ru}static registerWaitForInteraction(s){if(s!==null){if(ru){s();return}Wa.indexOf(s)===-1&&Wa.push(s)}}static unregisterWaitForInteraction(s){const t=Wa.indexOf(s);t!==-1&&Wa.splice(t,1)}get muted(){return this._mute}set muted(s){s!==this._mute&&(this._mute=s,this.dispatchEvent(new Event("application-mutechanged")))}get hasFocus(){return document.hasFocus()}get isVisible(){return this._isVisible}onVisiblityChanged(s){switch(s.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 kn=V_;a(kn,"registerWaitForAllowAudio",V_.registerWaitForInteraction);function*H_(s,t=null){const i=t?t.time:te.Current.time,n=i.time;for(;i.time-n<s;)yield}function*q2(s){for(let t=0;t<s;t++)yield}function*$_(s){let t=!0;for(s.then(()=>t=!1),s.catch(()=>t=!1);t;)yield}const q_="NEEDLE_lightmaps",Cc=O("debuglightmapsextension")||O("debuglightmaps");var yo=(s=>(s[s.Lightmap=0]="Lightmap",s[s.Skybox=1]="Skybox",s[s.Reflection=2]="Reflection",s))(yo||{});class G2{constructor(t,i,n){a(this,"parser"),a(this,"registry"),a(this,"source"),this.parser=t,this.registry=i,this.source=n}get name(){return q_}afterRoot(t){const i=this.parser.json.extensions;if(i){const n=i[q_];if(n){const o=n.textures;return o!=null&&o.length?(Cc&&console.log(n),new Promise(async(r,l)=>{const c=[];for(const d of o)if(d.pointer){Cc&&console.log(d);let u=null;if(d.pointer.startsWith("/textures/"))Cc&&console.log("Load texture from gltf",d.pointer),u=Ug(this.parser,d.pointer).then(p=>this.resolveTexture(d,p));else if(typeof d.pointer=="string"){Cc&&console.log("Load texture from path",d.pointer);const p=co(this.source,d.pointer);let g;p.endsWith(".exr")?g=new md(this.parser.options.manager):p.endsWith(".hdr")?g=new wm(this.parser.options.manager):g=new va(this.parser.options.manager),u=g.loadAsync(p,void 0).then(y=>this.resolveTexture(d,y))}else d.pointer;u&&c.push(u)}const h=await yd(c);h!=null&&h.anyFailed&&F()&&console.error("Failed to load lightmap extension",h),r()})):null}}return null}resolveTexture(t,i){const n=i;Cc&&console.log("Lightmap loaded:",n),n!=null&&n.isTexture&&(this.registry?(n.colorSpace=pr,this.registry.registerTexture(this.source,t.type,n,t.index)):console.log(yo[t.type],t.pointer,n))}}const G_=!!O("debuglightmaps");class X2{constructor(t){a(this,"_context"),a(this,"_lightmaps",new Map),this._context=t}clear(){this._lightmaps.clear()}registerTexture(t,i,n,o){G_&&console.log("Registering ",yo[i]+' "'+t+'"',n),this._lightmaps.has(t)||this._lightmaps.set(t,new Map);const r=this._lightmaps.get(t),l=r?.get(i)??[];l.length<o&&(l.length=o+1),l[o]=n,r?.set(i,l)}tryGetLightmap(t,i=0){return this.tryGet(t,yo.Lightmap,i)}tryGetSkybox(t){return this.tryGet(t,yo.Skybox,0)}tryGetReflection(t){return this.tryGet(t,yo.Reflection,0)}tryGet(t,i,n){if(!t)return G_&&console.warn("Missing source id"),null;const o=this._lightmaps.get(t);if(!o)return null;const r=o.get(i);return r===void 0||!(r!=null&&r.length)||r.length<=n?null:r[n]}}qt.lights_fragment_maps=qt.lights_fragment_maps.replace("vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );",`
180
180
  vec2 lUv = vLightMapUv.xy * lightmapScaleOffset.xy + vec2(lightmapScaleOffset.z, (1. - (lightmapScaleOffset.y + lightmapScaleOffset.w)));
181
181
  vec4 lightMapTexel = texture2D( lightMap, lUv);
182
182
  // The range of RGBM lightmaps goes from 0 to 34.49 (5^2.2) in linear space, and from 0 to 5 in gamma space.
@@ -199,13 +199,13 @@ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects
199
199
  irradiance += 0.;
200
200
  #else
201
201
  irradiance += getLightProbeIrradiance( lightProbe, geometry.normal );
202
- #endif`),xS.lightmap.lightmapScaleOffset={value:new me(1,1,0,0)};const Kg=O("debugprogressive"),au=new vi,lu=new ad;class Qk{constructor(t){a(this,"context"),a(this,"_lodsManager"),this.context=t}get manager(){return this._lodsManager}get targetTriangleDensity(){var t;return((t=this._lodsManager)==null?void 0:t.targetTriangleDensity)??-1}set targetTriangleDensity(t){this._lodsManager&&(this._lodsManager.targetTriangleDensity=t)}setRenderer(t){var i;(i=this._lodsManager)==null||i.disable(),wa.removePlugin(this),wa.addPlugin(this),wa.debugDrawLine=q.DrawLine,this._lodsManager=wa.get(t),this._lodsManager.enable()}disable(){var t;(t=this._lodsManager)==null||t.disable(),wa.removePlugin(this)}onAfterUpdatedLOD(t,i,n,o,r){Kg&&this.onRenderDebug(n,o,r)}onRenderDebug(t,i,n){var o,r,l;if(!i.geometry||!et.hasLODLevelAvailable(i.geometry)&&!et.hasLODLevelAvailable(i.material))return;const c=wa.getObjectLODState(i);if(!c)return;let h=n.mesh_lod;const d=n.mesh_lod!=c.lastLodLevel_Mesh||n.texture_lod!=c.lastLodLevel_Texture;if(Kg&&i.geometry.boundingSphere){const u=i.geometry.boundingSphere;lu.copy(u),lu.applyMatrix4(i.matrixWorld);const p=lu.center,g=lu.radius,y=["#76c43e","#bcc43e","#c4ac3e","#c4673e","#ff3e3e"];if(d)q.DrawWireSphere(p,g,y[h],.1);else{const f=((o=i.geometry.index)==null?void 0:o.count)??0,v=(r=et.getMeshLODInformation(i.geometry))==null?void 0:r.lods;h=v?Math.min(v?.length-1,h):0;let b="";if(v&&c.lastScreenCoverage>0)for(let C=0;C<v.length;C++){const R=v[C].density,M=C==v.length-1;b+=R.toFixed(0)+">"+(R/c.lastScreenCoverage).toFixed(0)+(M?"":",")}const w=v?(l=v[h])==null?void 0:l.density:-1;let _="LOD "+n.mesh_lod+`
202
+ #endif`),xS.lightmap.lightmapScaleOffset={value:new me(1,1,0,0)};const Kg=O("debugprogressive"),au=new vi,lu=new ad;class Q2{constructor(t){a(this,"context"),a(this,"_lodsManager"),this.context=t}get manager(){return this._lodsManager}get targetTriangleDensity(){var t;return((t=this._lodsManager)==null?void 0:t.targetTriangleDensity)??-1}set targetTriangleDensity(t){this._lodsManager&&(this._lodsManager.targetTriangleDensity=t)}setRenderer(t){var i;(i=this._lodsManager)==null||i.disable(),wa.removePlugin(this),wa.addPlugin(this),wa.debugDrawLine=q.DrawLine,this._lodsManager=wa.get(t),this._lodsManager.enable()}disable(){var t;(t=this._lodsManager)==null||t.disable(),wa.removePlugin(this)}onAfterUpdatedLOD(t,i,n,o,r){Kg&&this.onRenderDebug(n,o,r)}onRenderDebug(t,i,n){var o,r,l;if(!i.geometry||!et.hasLODLevelAvailable(i.geometry)&&!et.hasLODLevelAvailable(i.material))return;const c=wa.getObjectLODState(i);if(!c)return;let h=n.mesh_lod;const d=n.mesh_lod!=c.lastLodLevel_Mesh||n.texture_lod!=c.lastLodLevel_Texture;if(Kg&&i.geometry.boundingSphere){const u=i.geometry.boundingSphere;lu.copy(u),lu.applyMatrix4(i.matrixWorld);const p=lu.center,g=lu.radius,y=["#76c43e","#bcc43e","#c4ac3e","#c4673e","#ff3e3e"];if(d)q.DrawWireSphere(p,g,y[h],.1);else{const f=((o=i.geometry.index)==null?void 0:o.count)??0,v=(r=et.getMeshLODInformation(i.geometry))==null?void 0:r.lods;h=v?Math.min(v?.length-1,h):0;let b="";if(v&&c.lastScreenCoverage>0)for(let C=0;C<v.length;C++){const R=v[C].density,M=C==v.length-1;b+=R.toFixed(0)+">"+(R/c.lastScreenCoverage).toFixed(0)+(M?"":",")}const w=v?(l=v[h])==null?void 0:l.density:-1;let _="LOD "+n.mesh_lod+`
203
203
  TEX `+n.texture_lod;if(Kg=="density"&&(_+=`
204
204
  `+f+` tris
205
205
  `+(w/c.lastScreenCoverage).toFixed(0)+` dens
206
206
  `+(c.lastScreenCoverage*100).toFixed(1)+`% cov
207
207
  `+(c.lastCentrality*100).toFixed(1)+`% centr
208
- `+(au.min.x.toFixed(2)+"-"+au.max.x.toFixed(2)+"x"+au.min.y.toFixed(2)+"-"+au.max.y.toFixed(2))+" scr"),c.lastScreenCoverage>.1){const C=t,R=C.worldForward,M=C.worldPosition,E=$(R).multiplyScalar(g*.7).add(p),D=E.distanceTo(M),L=y[Math.min(y.length-1,Math.max(0,h))]+"88",U=this.context.domHeight>0?screen.height/this.context.domHeight:1,z=t.isPerspectiveCamera?Math.tan(t.fov*Math.PI/180/2):1;q.DrawLabel(E,_,D*.012*U*z,void 0,16777215,L)}}}}}const Yk=O("debugplayerview");var vo=(s=>(s.Browser="browser",s.Headset="headset",s.Handheld="handheld",s))(vo||{});class X_{constructor(t,i){a(this,"userId"),a(this,"context"),a(this,"viewDevice","browser"),a(this,"removed",!1),a(this,"_object"),this.userId=t,this.context=i}get currentObject(){return this._object}set currentObject(t){this._object=t}get isConnected(){return this.context.connection.userIsInRoom(this.userId)}}class Q_{constructor(t){a(this,"context"),a(this,"playerViews",new Map),this.context=t}setPlayerView(t,i,n){let o=this.playerViews.get(t);o||(o=new X_(t,this.context),this.playerViews.set(t,o)),o.viewDevice=n,o.currentObject=i,o.removed=!1}getPlayerView(t){if(!!t){if(!this.context.connection.userIsInRoom(t)){this.playerViews.delete(t);return}return this.playerViews.get(t)}}removePlayerView(t,i){const n=this.playerViews.get(t);n?.viewDevice===i&&(Yk&&console.log("REMOVE",t),n.removed=!0,this.playerViews.delete(t))}}new Zy;const Oc=new Uint8Array(4);Oc[0]=255,Oc[1]=255,Oc[2]=255,Oc[3]=255;const Kk=new hm(Oc,1,1,cd);function Zg(s,t=1){const i="alpha"in s,n=t*t,o=new Uint8Array(4*n),r=Math.floor(s.r*255),l=Math.floor(s.g*255),c=Math.floor(s.b*255);for(let d=0;d<n;d++){const u=d*4;o[u+0]=r,o[u+1]=l,o[u+2]=c,i?o[u+3]=Math.floor(s.alpha*255):o[u+3]=255}const h=new hm(o,t,t);return h.needsUpdate=!0,h}function Zk(s,t,i,n=1,o=3){const r=n*o,l=[s,t,i],c=l.length,h=new Uint8Array(4*c*r),d=new ae;for(let p=0;p<o;p++){const g=Math.floor(p/o*c),y=W.clamp(g+1,0,c-1),f=l[g],v=l[y],b=p/o*c%1;d.lerpColors(f,v,b);const w=Math.floor(d.r*255),_=Math.floor(d.g*255),C=Math.floor(d.b*255);for(let R=0;R<n;R++){const M=(p*n+R)*4;h[M+0]=w,h[M+1]=_,h[M+2]=C,h[M+3]=255}}const u=new hm(h,n,o);return u.needsUpdate=!0,u}function cu(s,t){const i=s.elements;t||(t=[]),t.length=0;for(let n=0;n<16;n+=4){const o=i[n],r=i[n+1],l=i[n+2],c=i[n+3],h=new me(o,r,l,c);t.push(h)}return t}const Jg=[],Y_=[];function Jk(s,t){if(Jg.length===0)for(let i=0;i<27;i++)Jg.push(0);t||(t=Jg);for(let i=0;i<27;i++)Y_[i]=t[i];t=Y_,s.unity_SHAr={value:new me(t[9],t[3],t[6],t[0])},s.unity_SHBr={value:new me(t[12],t[15],t[18],t[21])},s.unity_SHAg={value:new me(t[10],t[4],t[7],t[1])},s.unity_SHBg={value:new me(t[13],t[16],t[19],t[22])},s.unity_SHAb={value:new me(t[11],t[5],t[8],t[2])},s.unity_SHBb={value:new me(t[14],t[17],t[20],t[23])},s.unity_SHC={value:new me(t[24],t[25],t[26],1)}}class e2{constructor(t,i,n){a(this,"vertexShader"),a(this,"fragmentShader"),a(this,"technique"),this.vertexShader=t,this.fragmentShader=i,this.technique=n}}async function t2(s,t){if(!s)return console.error("Can not find technique: no shader data"),null;const i=s.programs[t],n=i.vertexShader,o=i.fragmentShader;if(n!==void 0&&o!==void 0){const r=s.shaders[n],l=s.shaders[o];if(r.uri&&l.uri||r.code&&l.code){if(!r.code&&r.uri&&await K_(r),!l.code&&l.uri&&await K_(l),!r.code||!l.code)return null;const c=s.techniques[t];return new e2(r.code,l.code,c)}}return console.error("Shader technique not found",t),null}async function K_(s){const t=s.uri;if(t)if(t.endsWith(".glsl")){const i=await new Zy().loadAsync(t);s.code=i.toString()}else s.code=i2(s.uri)}function i2(s){return decodeURIComponent(Array.prototype.map.call(atob(s),function(t){return"%"+("00"+t.charCodeAt(0).toString(16)).slice(-2)}).join(""))}const xs=O("debugenvlight");var Va=(s=>(s[s.Skybox=0]="Skybox",s[s.Trilight=1]="Trilight",s[s.Flat=3]="Flat",s[s.Custom=4]="Custom",s))(Va||{}),hu=(s=>(s[s.Skybox=0]="Skybox",s[s.Custom=1]="Custom",s))(hu||{});class Z_{constructor(t){a(this,"context"),a(this,"_currentLightSettingsId"),a(this,"_sceneLightSettings"),a(this,"_timevec4",new me),a(this,"__currentReflectionId",null),a(this,"_lighting",{}),this.context=t,this.context.pre_update_callbacks.push(this.preUpdate.bind(this))}preUpdate(){const t=this.context.time;this._timevec4.x=t.time,this._timevec4.y=Math.sin(t.time),this._timevec4.z=Math.cos(t.time),this._timevec4.w=t.deltaTime}get timeVec4(){return this._timevec4}get environmentIntensity(){if(!this._sceneLightSettings||!this._currentLightSettingsId)return 1;const t=this._sceneLightSettings.get(this._currentLightSettingsId);return t?t.ambientIntensity:1}get sceneLightSettings(){var t;return(t=this._sceneLightSettings)==null?void 0:t.values()}enable(t){var i;t instanceof le&&(t=t.url);const n=(i=this._sceneLightSettings)==null?void 0:i.get(t);return n?(xs&&console.log("Enable scene light settings",t,n),t!==this._currentLightSettingsId&&this._currentLightSettingsId&&this.disable(this._currentLightSettingsId),this._currentLightSettingsId=t,n.enabled=!0,!0):(xs&&console.warn("No light settings found for",t),!1)}disable(t){var i;if(t instanceof le&&(t=t.url),t==null)return!1;const n=(i=this._sceneLightSettings)==null?void 0:i.get(t);return n?(xs&&console.log("Disable scene light settings",t,n),n.enabled=!1,!0):!1}disableCurrent(){if(this._currentLightSettingsId){const t=this._currentLightSettingsId;return this.disable(this._currentLightSettingsId),t}return null}internalRegisterSceneLightSettings(t){const i=t.sourceId;if(!i){console.error("Missing source id for scene light settings, can not register:",t);return}xs&&console.log("Register "+t?.sourceId+" lighting",t),this._sceneLightSettings||(this._sceneLightSettings=new Map),this._sceneLightSettings.set(i,t)}internalUnregisterSceneLightSettings(t){const i=t.sourceId;if(!i){console.error("Missing source id for scene light settings, can not unregister:",t);return}xs&&console.log("Unregister "+t?.sourceId+" lighting",t),this._sceneLightSettings&&this._sceneLightSettings.delete(i)}internalRegisterReflection(t,i){xs&&console.log("Register reflection",t,i);const n=new J_(this.context,i,1);this._lighting[t]=n}internalGetReflection(t){return this._lighting[t]}internalEnableReflection(t){var i;this.__currentReflectionId=t;const n=(i=this._sceneLightSettings)==null?void 0:i.get(t);switch(xs&&console.log("Enable reflection",t,n?Va[n.ambientMode]:"Unknown ambient mode",n),n?.ambientMode){case 0:case 4:const o=this.internalGetReflection(t);if(o&&o.Source){xs&&console.log("Setting environment reflection",o);const r=this.context.scene,l=o.Source;l.mapping=_n,r.environment=l;return}else xs&&console.warn("Could not find reflection for source",t);break}if(n?.environmentReflectionSource===1)switch(n?.ambientMode){case 1:if(n.ambientTrilight){const o=n.ambientTrilight,r=Zk(o[0],o[1],o[2],64,64);r.colorSpace=ps,r.mapping=_n,this.context.scene.environment=r}else console.error("Missing ambient trilight",n.sourceId);return;case 3:if(n.ambientLight){const o=Zg(n.ambientLight,64);o.colorSpace=ps,o.mapping=_n,this.context.scene.environment=o}else console.error("Missing ambientlight",n.sourceId);return;default:return}}internalDisableReflection(t){if(t&&t!==this.__currentReflectionId){xs&&console.log("Not disabling reflection for",t,"because it is not the current light settings id",this.__currentReflectionId);return}xs&&console.log("Disable reflection",t);const i=this.context.scene;i.environment=null}}class J_{constructor(t,i,n=1){a(this,"_source"),this._source=i,i.mapping=_n}get Source(){return this._source}}const ew=O("timescale");let ef=1;typeof ew=="number"&&(ef=ew);class tw{constructor(){a(this,"_time",0),a(this,"_deltaTime",0),a(this,"_deltaTimeUnscaled",0),a(this,"timeScale",1),a(this,"_frame",0),a(this,"clock",new SS),a(this,"_smoothedFps",0),a(this,"_smoothedDeltaTime",0),a(this,"_fpsSamples",[]),a(this,"_fpsSampleIndex",0),typeof ef=="number"&&(this.timeScale=ef)}get time(){return this._time}set time(t){this._time=t}get deltaTime(){return this._deltaTime}set deltaTime(t){this._deltaTime=t}get deltaTimeUnscaled(){return this._deltaTimeUnscaled}get frame(){return this._frame}set frame(t){this._frame=t}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 t=0;for(let i=0;i<this._fpsSamples.length;i++)t+=this._fpsSamples[i];this._smoothedDeltaTime=t/this._fpsSamples.length,this._smoothedFps=1/this._smoothedDeltaTime}}let iw=!1;function sw(s){iw||(iw=!0,s2(),n2())}sw();function s2(){const s=`
208
+ `+(au.min.x.toFixed(2)+"-"+au.max.x.toFixed(2)+"x"+au.min.y.toFixed(2)+"-"+au.max.y.toFixed(2))+" scr"),c.lastScreenCoverage>.1){const C=t,R=C.worldForward,M=C.worldPosition,E=$(R).multiplyScalar(g*.7).add(p),D=E.distanceTo(M),L=y[Math.min(y.length-1,Math.max(0,h))]+"88",U=this.context.domHeight>0?screen.height/this.context.domHeight:1,z=t.isPerspectiveCamera?Math.tan(t.fov*Math.PI/180/2):1;q.DrawLabel(E,_,D*.012*U*z,void 0,16777215,L)}}}}}const Y2=O("debugplayerview");var vo=(s=>(s.Browser="browser",s.Headset="headset",s.Handheld="handheld",s))(vo||{});class X_{constructor(t,i){a(this,"userId"),a(this,"context"),a(this,"viewDevice","browser"),a(this,"removed",!1),a(this,"_object"),this.userId=t,this.context=i}get currentObject(){return this._object}set currentObject(t){this._object=t}get isConnected(){return this.context.connection.userIsInRoom(this.userId)}}class Q_{constructor(t){a(this,"context"),a(this,"playerViews",new Map),this.context=t}setPlayerView(t,i,n){let o=this.playerViews.get(t);o||(o=new X_(t,this.context),this.playerViews.set(t,o)),o.viewDevice=n,o.currentObject=i,o.removed=!1}getPlayerView(t){if(!!t){if(!this.context.connection.userIsInRoom(t)){this.playerViews.delete(t);return}return this.playerViews.get(t)}}removePlayerView(t,i){const n=this.playerViews.get(t);n?.viewDevice===i&&(Y2&&console.log("REMOVE",t),n.removed=!0,this.playerViews.delete(t))}}new Zy;const Oc=new Uint8Array(4);Oc[0]=255,Oc[1]=255,Oc[2]=255,Oc[3]=255;const K2=new hm(Oc,1,1,cd);function Zg(s,t=1){const i="alpha"in s,n=t*t,o=new Uint8Array(4*n),r=Math.floor(s.r*255),l=Math.floor(s.g*255),c=Math.floor(s.b*255);for(let d=0;d<n;d++){const u=d*4;o[u+0]=r,o[u+1]=l,o[u+2]=c,i?o[u+3]=Math.floor(s.alpha*255):o[u+3]=255}const h=new hm(o,t,t);return h.needsUpdate=!0,h}function Z2(s,t,i,n=1,o=3){const r=n*o,l=[s,t,i],c=l.length,h=new Uint8Array(4*c*r),d=new ae;for(let p=0;p<o;p++){const g=Math.floor(p/o*c),y=W.clamp(g+1,0,c-1),f=l[g],v=l[y],b=p/o*c%1;d.lerpColors(f,v,b);const w=Math.floor(d.r*255),_=Math.floor(d.g*255),C=Math.floor(d.b*255);for(let R=0;R<n;R++){const M=(p*n+R)*4;h[M+0]=w,h[M+1]=_,h[M+2]=C,h[M+3]=255}}const u=new hm(h,n,o);return u.needsUpdate=!0,u}function cu(s,t){const i=s.elements;t||(t=[]),t.length=0;for(let n=0;n<16;n+=4){const o=i[n],r=i[n+1],l=i[n+2],c=i[n+3],h=new me(o,r,l,c);t.push(h)}return t}const Jg=[],Y_=[];function J2(s,t){if(Jg.length===0)for(let i=0;i<27;i++)Jg.push(0);t||(t=Jg);for(let i=0;i<27;i++)Y_[i]=t[i];t=Y_,s.unity_SHAr={value:new me(t[9],t[3],t[6],t[0])},s.unity_SHBr={value:new me(t[12],t[15],t[18],t[21])},s.unity_SHAg={value:new me(t[10],t[4],t[7],t[1])},s.unity_SHBg={value:new me(t[13],t[16],t[19],t[22])},s.unity_SHAb={value:new me(t[11],t[5],t[8],t[2])},s.unity_SHBb={value:new me(t[14],t[17],t[20],t[23])},s.unity_SHC={value:new me(t[24],t[25],t[26],1)}}class ek{constructor(t,i,n){a(this,"vertexShader"),a(this,"fragmentShader"),a(this,"technique"),this.vertexShader=t,this.fragmentShader=i,this.technique=n}}async function tk(s,t){if(!s)return console.error("Can not find technique: no shader data"),null;const i=s.programs[t],n=i.vertexShader,o=i.fragmentShader;if(n!==void 0&&o!==void 0){const r=s.shaders[n],l=s.shaders[o];if(r.uri&&l.uri||r.code&&l.code){if(!r.code&&r.uri&&await K_(r),!l.code&&l.uri&&await K_(l),!r.code||!l.code)return null;const c=s.techniques[t];return new ek(r.code,l.code,c)}}return console.error("Shader technique not found",t),null}async function K_(s){const t=s.uri;if(t)if(t.endsWith(".glsl")){const i=await new Zy().loadAsync(t);s.code=i.toString()}else s.code=ik(s.uri)}function ik(s){return decodeURIComponent(Array.prototype.map.call(atob(s),function(t){return"%"+("00"+t.charCodeAt(0).toString(16)).slice(-2)}).join(""))}const xs=O("debugenvlight");var Va=(s=>(s[s.Skybox=0]="Skybox",s[s.Trilight=1]="Trilight",s[s.Flat=3]="Flat",s[s.Custom=4]="Custom",s))(Va||{}),hu=(s=>(s[s.Skybox=0]="Skybox",s[s.Custom=1]="Custom",s))(hu||{});class Z_{constructor(t){a(this,"context"),a(this,"_currentLightSettingsId"),a(this,"_sceneLightSettings"),a(this,"_timevec4",new me),a(this,"__currentReflectionId",null),a(this,"_lighting",{}),this.context=t,this.context.pre_update_callbacks.push(this.preUpdate.bind(this))}preUpdate(){const t=this.context.time;this._timevec4.x=t.time,this._timevec4.y=Math.sin(t.time),this._timevec4.z=Math.cos(t.time),this._timevec4.w=t.deltaTime}get timeVec4(){return this._timevec4}get environmentIntensity(){if(!this._sceneLightSettings||!this._currentLightSettingsId)return 1;const t=this._sceneLightSettings.get(this._currentLightSettingsId);return t?t.ambientIntensity:1}get sceneLightSettings(){var t;return(t=this._sceneLightSettings)==null?void 0:t.values()}enable(t){var i;t instanceof le&&(t=t.url);const n=(i=this._sceneLightSettings)==null?void 0:i.get(t);return n?(xs&&console.log("Enable scene light settings",t,n),t!==this._currentLightSettingsId&&this._currentLightSettingsId&&this.disable(this._currentLightSettingsId),this._currentLightSettingsId=t,n.enabled=!0,!0):(xs&&console.warn("No light settings found for",t),!1)}disable(t){var i;if(t instanceof le&&(t=t.url),t==null)return!1;const n=(i=this._sceneLightSettings)==null?void 0:i.get(t);return n?(xs&&console.log("Disable scene light settings",t,n),n.enabled=!1,!0):!1}disableCurrent(){if(this._currentLightSettingsId){const t=this._currentLightSettingsId;return this.disable(this._currentLightSettingsId),t}return null}internalRegisterSceneLightSettings(t){const i=t.sourceId;if(!i){console.error("Missing source id for scene light settings, can not register:",t);return}xs&&console.log("Register "+t?.sourceId+" lighting",t),this._sceneLightSettings||(this._sceneLightSettings=new Map),this._sceneLightSettings.set(i,t)}internalUnregisterSceneLightSettings(t){const i=t.sourceId;if(!i){console.error("Missing source id for scene light settings, can not unregister:",t);return}xs&&console.log("Unregister "+t?.sourceId+" lighting",t),this._sceneLightSettings&&this._sceneLightSettings.delete(i)}internalRegisterReflection(t,i){xs&&console.log("Register reflection",t,i);const n=new J_(this.context,i,1);this._lighting[t]=n}internalGetReflection(t){return this._lighting[t]}internalEnableReflection(t){var i;this.__currentReflectionId=t;const n=(i=this._sceneLightSettings)==null?void 0:i.get(t);switch(xs&&console.log("Enable reflection",t,n?Va[n.ambientMode]:"Unknown ambient mode",n),n?.ambientMode){case 0:case 4:const o=this.internalGetReflection(t);if(o&&o.Source){xs&&console.log("Setting environment reflection",o);const r=this.context.scene,l=o.Source;l.mapping=_n,r.environment=l;return}else xs&&console.warn("Could not find reflection for source",t);break}if(n?.environmentReflectionSource===1)switch(n?.ambientMode){case 1:if(n.ambientTrilight){const o=n.ambientTrilight,r=Z2(o[0],o[1],o[2],64,64);r.colorSpace=ps,r.mapping=_n,this.context.scene.environment=r}else console.error("Missing ambient trilight",n.sourceId);return;case 3:if(n.ambientLight){const o=Zg(n.ambientLight,64);o.colorSpace=ps,o.mapping=_n,this.context.scene.environment=o}else console.error("Missing ambientlight",n.sourceId);return;default:return}}internalDisableReflection(t){if(t&&t!==this.__currentReflectionId){xs&&console.log("Not disabling reflection for",t,"because it is not the current light settings id",this.__currentReflectionId);return}xs&&console.log("Disable reflection",t);const i=this.context.scene;i.environment=null}}class J_{constructor(t,i,n=1){a(this,"_source"),this._source=i,i.mapping=_n}get Source(){return this._source}}const ew=O("timescale");let ef=1;typeof ew=="number"&&(ef=ew);class tw{constructor(){a(this,"_time",0),a(this,"_deltaTime",0),a(this,"_deltaTimeUnscaled",0),a(this,"timeScale",1),a(this,"_frame",0),a(this,"clock",new SS),a(this,"_smoothedFps",0),a(this,"_smoothedDeltaTime",0),a(this,"_fpsSamples",[]),a(this,"_fpsSampleIndex",0),typeof ef=="number"&&(this.timeScale=ef)}get time(){return this._time}set time(t){this._time=t}get deltaTime(){return this._deltaTime}set deltaTime(t){this._deltaTime=t}get deltaTimeUnscaled(){return this._deltaTimeUnscaled}get frame(){return this._frame}set frame(t){this._frame=t}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 t=0;for(let i=0;i<this._fpsSamples.length;i++)t+=this._fpsSamples[i];this._smoothedDeltaTime=t/this._fpsSamples.length,this._smoothedFps=1/this._smoothedDeltaTime}}let iw=!1;function sw(s){iw||(iw=!0,sk(),nk())}sw();function sk(){const s=`
209
209
  float startCompression = 0.8;
210
210
  float desaturation = 0.5;
211
211
  // Patched tonemapping function
@@ -226,7 +226,7 @@ vec3 NeutralToneMapping( vec3 color ) {
226
226
  return mix(color, vec3(1, 1, 1), g);
227
227
  }
228
228
  `,t="vec3 NeutralToneMapping( vec3 color ) {",i=`return mix( color, vec3( newPeak ), g );
229
- }`,n=qt.tonemapping_pars_fragment.indexOf(t),o=qt.tonemapping_pars_fragment.indexOf(i,n);if(n>=0&&o>=0){const r=qt.tonemapping_pars_fragment.substring(n,o+i.length);qt.tonemapping_pars_fragment=qt.tonemapping_pars_fragment.replace(r,s)}else F()&&console.error("Couldn't find NeutralToneMapping in ShaderChunk.tonemapping_pars_fragment")}function n2(){const s=`
229
+ }`,n=qt.tonemapping_pars_fragment.indexOf(t),o=qt.tonemapping_pars_fragment.indexOf(i,n);if(n>=0&&o>=0){const r=qt.tonemapping_pars_fragment.substring(n,o+i.length);qt.tonemapping_pars_fragment=qt.tonemapping_pars_fragment.replace(r,s)}else F()&&console.error("Couldn't find NeutralToneMapping in ShaderChunk.tonemapping_pars_fragment")}function nk(){const s=`
230
230
  // 0: Default, 1: Golden, 2: Punchy
231
231
  #define AGX_LOOK 0
232
232
 
@@ -376,7 +376,7 @@ vec3 AgXToneMapping( vec3 color ) {
376
376
  <div class="wrapper">
377
377
  <img class="logo" src=${PP} />
378
378
  </div>
379
- `,this._root.appendChild(t.content.cloneNode(!0)),this.wrapper=this._root.querySelector(".wrapper"),this._root.appendChild(this.wrapper),this.addEventListener("click",()=>{globalThis.open("https://needle.tools","_blank")}),this.wrapper.setAttribute("title","Made with Needle Engine")}static get elementName(){return pu}static create(){return document.createElement(pu)}setLogoVisible(t){this.logoElement.style.display=t?"block":"none"}}customElements.get(pu)||customElements.define(pu,rw);const of=O("debugspatialmenu");class o2{constructor(t,i){a(this,"_context"),a(this,"needleMenu"),a(this,"htmlButtonsMap",new Map),a(this,"enabled",!0),a(this,"userRequestedMenu",!1),a(this,"uiisDirty",!1),a(this,"_showNeedleLogo"),a(this,"_wasInXR",!1),a(this,"preRender",()=>{var r;if(!this.enabled){(r=this.menu)==null||r.removeFromParent();return}of&&Y.isDesktop()&&this.updateMenu();const l=this._context.xr;if(!(l!=null&&l.running)){this._wasInXR&&(this._wasInXR=!1,this.onExitXR());return}this._wasInXR||(this._wasInXR=!0,this.onEnterXR()),this.updateMenu()}),a(this,"_menuTarget",new j),a(this,"positionFilter",new Fm(90,.5)),a(this,"familyName","Needle Spatial Menu"),a(this,"menu"),a(this,"_poweredByNeedleElement");var n;this._context=t,this._context.pre_render_callbacks.push(this.preRender),this.needleMenu=i;const o=(n=this.needleMenu.shadowRoot)==null?void 0:n.querySelector(".options");o?new MutationObserver(r=>{if(this.enabled&&!(this._context.isInXR==!1&&!of))for(const l of r)l.type==="childList"&&(l.addedNodes.forEach(c=>{this.createButtonFromHTMLNode(c)}),l.removedNodes.forEach(c=>{const h=c,d=this.htmlButtonsMap.get(h);d&&(this.htmlButtonsMap.delete(h),d.remove(),Re.update())}))}).observe(o,{childList:!0}):console.error("Could not find options container in needle menu")}setEnabled(t){var i;this.enabled=t,t||(i=this.menu)==null||i.removeFromParent()}setDisplay(t){return this.enabled?(this.userRequestedMenu=t,!0):!1}onDestroy(){const t=this._context.pre_render_callbacks.indexOf(this.preRender);t>-1&&this._context.pre_render_callbacks.splice(t,1)}markDirty(){this.uiisDirty=!0}showNeedleLogo(t){this._showNeedleLogo=t}onEnterXR(){var t;const i=(t=this.needleMenu.shadowRoot)==null?void 0:t.querySelector(".options");i&&i.childNodes.forEach(n=>{this.createButtonFromHTMLNode(n)})}onExitXR(){var t;(t=this.menu)==null||t.removeFromParent()}createButtonFromHTMLNode(t){const i=this.getMenu(),n=this.htmlButtonsMap.get(t);if(n){n.add();return}if(t instanceof HTMLButtonElement){const o=this.createButton(i,t);this.htmlButtonsMap.set(t,o),o.add()}else t instanceof HTMLSlotElement&&t.assignedNodes().forEach(o=>{this.createButtonFromHTMLNode(o)})}updateMenu(){var t,i;performance.mark("NeedleSpatialMenu updateMenu start");const n=this.getMenu();this.handleNeedleWatermark(),this._context.scene.add(n);const o=this._context.mainCamera,r=this._context.xr,l=r?.rigScale||1;if(o){const c=o.worldPosition,h=o.worldForward.multiplyScalar(-1),d=h.y>.6,u=h.y>.4,p=(n.visible?u:d)||this.userRequestedMenu,g=!n.visible&&p;n.visible=p||Y.isDesktop()&&of,h.multiplyScalar(3*l),c.add(h),g&&(n.position.copy(this._menuTarget.position),n.position.y+=.25,this._menuTarget.position.copy(n.position),this.positionFilter.reset(n.position),n.quaternion.copy(this._menuTarget.quaternion),this.markDirty());const y=this._menuTarget.position.distanceTo(c);(g||y>1.5*l)&&(this.ensureRenderOnTop(this.menu),this._menuTarget.position.copy(c),this._context.scene.add(this._menuTarget),Kl(this._menuTarget,this._context.mainCamera,!0,!0),this._menuTarget.removeFromParent()),this.positionFilter.filter(this._menuTarget.position,n.position,this._context.time.time);const f=5;(t=this.menu)==null||t.quaternion.slerp(this._menuTarget.quaternion,this._context.time.deltaTime*f),(i=this.menu)==null||i.scale.setScalar(l)}this.uiisDirty&&(performance.mark("SpatialMenu.update.uiisDirty.start"),this.uiisDirty=!1,Re.update(),performance.mark("SpatialMenu.update.uiisDirty.end"),performance.measure("SpatialMenu.update.uiisDirty","SpatialMenu.update.uiisDirty.start","SpatialMenu.update.uiisDirty.end")),performance.mark("NeedleSpatialMenu updateMenu end"),performance.measure("SpatialMenu.update","NeedleSpatialMenu updateMenu start","NeedleSpatialMenu updateMenu end")}ensureRenderOnTop(t,i=0){t instanceof Q&&(t.material.depthTest=!1,t.material.depthWrite=!1),t.renderOrder=1e3+i*2;for(const n of t.children)this.ensureRenderOnTop(n,i+1)}get isVisible(){var t;return(t=this.menu)==null?void 0:t.visible}getMenu(){if(this.menu)return this.menu;this.ensureFont(),this.menu=new Re.Block({boxSizing:"border-box",fontFamily:this.familyName,height:"auto",fontSize:.1,color:0,lineHeight:1,backgroundColor:16777215,backgroundOpacity:.55,borderRadius:1,whiteSpace:"pre-wrap",flexDirection:"row",alignItems:"center",padding:new me(0,.05,0,.05),borderColor:0,borderOpacity:.05,borderWidth:.005});const t=S.get("ObjectRaycaster");return t&&Cr(this.menu,new t),this.menu}handleNeedleWatermark(){var t;if(!this._poweredByNeedleElement){this._poweredByNeedleElement=new Re.Block({width:"auto",height:"auto",fontSize:.05,whiteSpace:"pre-wrap",flexDirection:"row",flexWrap:"wrap",justifyContent:"center",margin:.02,borderRadius:.02,padding:.02,backgroundColor:16777215,backgroundOpacity:1}),this._poweredByNeedleElement["needle:use_eventsystem"]=!0;const i=new aw(this._context,()=>globalThis.open("https://needle.tools","_self"));Cr(this._poweredByNeedleElement,i);const n=new Re.Text({textContent:"Powered by",width:"auto",height:"auto"}),o=new Re.Text({textContent:"needle",width:"auto",height:"auto",fontSize:.07,margin:new me(0,0,0,.02)});this._poweredByNeedleElement.add(n),this._poweredByNeedleElement.add(o),(t=this.menu)==null||t.add(this._poweredByNeedleElement),this.markDirty(),new va().load("./include/needle/poweredbyneedle.webp",r=>{var l;i.allowModifyUI=!1,n.removeFromParent(),o.removeFromParent();const c=r.image.width/r.image.height;(l=this._poweredByNeedleElement)==null||l.set({backgroundImage:r,backgroundOpacity:1,width:.1*c,height:.1}),this.markDirty()})}if(this.menu){const i=this.menu.children.indexOf(this._poweredByNeedleElement);if(!this._showNeedleLogo&&bo())i>=0&&(this._poweredByNeedleElement.removeFromParent(),this.markDirty());else{this._poweredByNeedleElement.visible=!0,this.menu.add(this._poweredByNeedleElement);const n=this.menu.children.indexOf(this._poweredByNeedleElement);i!==n&&this.markDirty()}}}ensureFont(){let t=Re.FontLibrary.getFontFamily(this.familyName);if(!t){t=Re.FontLibrary.addFontFamily(this.familyName);const i=t.addVariant("normal","normal","./include/needle/arial-msdf.json","./include/needle/arial.png");i?.addEventListener("ready",()=>{this.markDirty()})}}createButton(t,i){const n=new Re.Block({width:"auto",height:"auto",whiteSpace:"pre-wrap",flexDirection:"row",flexWrap:"wrap",justifyContent:"center",backgroundColor:16777215,backgroundOpacity:0,padding:.02,margin:.01,borderRadius:.02,cursor:"pointer",fontSize:.05}),o=new Re.Text({textContent:"",width:"auto",justifyContent:"center",alignItems:"center",backgroundOpacity:0,backgroundColor:16777215,fontFamily:this.familyName,color:0,borderRadius:.02,padding:.01});n.add(o),n["needle:use_eventsystem"]=!0;const r=new aw(this._context,()=>i.click());return Cr(n,r),new r2(this,t,i,n,o)}}class r2{constructor(t,i,n,o,r){a(this,"menu"),a(this,"root"),a(this,"htmlbutton"),a(this,"spatialContainer"),a(this,"spatialText"),a(this,"spatialIcon"),a(this,"_lastText",""),a(this,"_lastTexture"),this.menu=t,this.root=i,this.htmlbutton=n,this.spatialContainer=o,this.spatialText=r,new MutationObserver(l=>{for(const c of l)c.type==="attributes"?c.attributeName==="style"&&this.updateVisible():c.type==="childList"&&this.updateText()}).observe(n,{attributes:!0,childList:!0}),this.updateText()}add(){this.spatialContainer.parent!=this.root&&(this.root.add(this.spatialContainer),this.menu.markDirty(),this.updateVisible(),this.updateText())}remove(){this.spatialContainer.parent&&(this.spatialContainer.removeFromParent(),this.menu.markDirty())}updateVisible(){const t=this.spatialContainer.visible;this.spatialContainer.visible=this.htmlbutton.style.display!=="none",t!==this.spatialContainer.visible&&this.menu.markDirty()}updateText(){let t="",i="";this.htmlbutton.childNodes.forEach(n=>{n.nodeType===Node.TEXT_NODE?t+=n.textContent:n instanceof HTMLElement&&nw(n)&&n.textContent&&(i=n.textContent)}),this._lastText!==t&&(this._lastText=t,this.spatialText.name=t,this.spatialText.set({textContent:t}),this.menu.markDirty()),t.length<=0?this.spatialText.parent&&(this.spatialText.removeFromParent(),this.menu.markDirty()):this.spatialText.parent||(this.spatialContainer.add(this.spatialText),this.menu.markDirty()),i&&this.createIcon(i)}async createIcon(t){var i;if(!this.spatialIcon){const o=await tf(t);if(o&&!this.spatialIcon){const r=new Re.Block({width:.08,height:.08,backgroundColor:16777215,backgroundImage:o,backgroundOpacity:1,margin:new me(0,.005,0,0)});this.spatialIcon=r,this.spatialContainer.add(r),this.menu.markDirty()}}if(t!=this._lastTexture){this._lastTexture=t;const o=await tf(t);o&&((i=this.spatialIcon)==null||i.set({backgroundImage:o}),this.menu.markDirty())}const n=this.spatialContainer.children.indexOf(this.spatialIcon);n>0&&(this.spatialContainer.children.splice(n,1),this.spatialContainer.children.unshift(this.spatialIcon),this.menu.markDirty())}}class aw{constructor(t,i){a(this,"isComponent",!0),a(this,"enabled",!0),a(this,"gameObject"),a(this,"allowModifyUI",!0),a(this,"context"),a(this,"onclick"),this.context=t,this.onclick=i}get activeAndEnabled(){return!0}__internalAwake(){}__internalEnable(){}__internalDisable(){}__internalStart(){}onEnable(){}onDisable(){}get element(){return this.gameObject}onPointerEnter(){this.context.input.setCursorPointer(),this.allowModifyUI&&(this.element.set({backgroundOpacity:1}),Re.update())}onPointerExit(){this.context.input.setCursorNormal(),this.allowModifyUI&&(this.element.set({backgroundOpacity:0}),Re.update())}onPointerDown(t){t.use()}onPointerUp(t){t.use()}onPointerClick(t){t.use(),this.onclick()}}const Tr="needle-menu",Pc=O("debugmenu"),lw=O("debugnoncommercial");let a2=class{constructor(s){a(this,"_context"),a(this,"_menu"),a(this,"_spatialMenu"),a(this,"onPostMessage",t=>{if(t.origin===globalThis.location.origin&&typeof t.data=="object"){const i=t.data,n=i.type;if(n==="needle:menu"){const o=i.button;if(o){if(!o.label)return console.error("NeedleMenu: buttoninfo.label is required");if(!o.onclick)return console.error("NeedleMenu: buttoninfo.onclick is required");const r=document.createElement("button");if(r.textContent=o.label,o.icon){const l=Ot(o.icon);r.prepend(l)}o.priority&&r.setAttribute("priority",o.priority.toString()),r.onclick=()=>{if(o.onclick){const l=o.onclick.startsWith("http")||o.onclick.startsWith("www."),c=o.target||"_blank";l?globalThis.open(o.onclick,c):console.error("NeedleMenu: onclick is not a valid link",o.onclick)}},this._menu.appendChild(r)}else Pc&&console.error("NeedleMenu: unknown postMessage event",i)}else Pc&&console.warn("NeedleMenu: unknown postMessage type",n,i)}}),a(this,"onStartXR",t=>{t.session.isScreenBasedAR&&(this._menu.previousParent=this._menu.parentNode,this._context.arOverlayElement.appendChild(this._menu),t.session.session.addEventListener("end",this.onExitXR),this._menu.closeFoldout())}),a(this,"onExitXR",()=>{this._menu.previousParent&&(this._menu.previousParent.appendChild(this._menu),delete this._menu.previousParent)}),a(this,"_muteButton"),a(this,"_fullscreenButton"),this._menu=hw.getOrCreate(s.domElement,s),this._context=s,this._spatialMenu=new o2(s,this._menu),window.addEventListener("message",this.onPostMessage),kd(this.onStartXR)}onDestroy(){window.removeEventListener("message",this.onPostMessage),this._menu.remove(),this._spatialMenu.onDestroy()}setPosition(s){this._menu.setPosition(s)}setVisible(s){this._menu.setVisible(s)}showNeedleLogo(s){var t;this._menu.showNeedleLogo(s),(t=this._spatialMenu)==null||t.showNeedleLogo(s)}showSpatialMenu(s){this._spatialMenu.setEnabled(s)}setSpatialMenuVisible(s){this._spatialMenu.setDisplay(s)}get spatialMenuIsVisible(){return this._spatialMenu.isVisible}showQRCodeButton(s){if(s==="desktop-only"&&(s=!Y.isMobileDevice()),s){const t=Mn.getOrCreate().createQRCode();return t.style.display="",this._menu.appendChild(t),t}else{const t=Mn.getOrCreate().qrButton;return t&&(t.style.display="none"),t??null}}showAudioPlaybackOption(s){var t;if(!s){(t=this._muteButton)==null||t.remove();return}this._muteButton=Mn.getOrCreate().createMuteButton(this._context),this._muteButton.setAttribute("priority","100"),this._menu.appendChild(this._muteButton)}showFullscreenOption(s){var t;if(!s){(t=this._fullscreenButton)==null||t.remove();return}this._fullscreenButton=Mn.getOrCreate().createFullscreenButton(this._context),this._fullscreenButton&&(this._fullscreenButton.setAttribute("priority","150"),this._menu.appendChild(this._fullscreenButton))}appendChild(s){return this._menu.appendChild(s)}};var mu,gu,rf;const cw=class extends HTMLElement{constructor(){var s,t,i,n,o,r;super(),Hi(this,gu),a(this,"_domElement",null),a(this,"_context",null),a(this,"_sizeChangeInterval"),Hi(this,mu,f=>{if(!f.defaultPrevented&&f.target==this._domElement&&f instanceof PointerEvent&&f.button===0&&this.root.classList.contains("open")){const v=this.foldout.getBoundingClientRect(),b=f;b.clientX>v.left&&b.clientX<v.right&&b.clientY>v.top&&b.clientY<v.bottom||this.root.classList.toggle("open",!1)}}),a(this,"_userRequestedLogoVisible"),a(this,"_userRequestedMenuVisible"),a(this,"root"),a(this,"wrapper"),a(this,"options"),a(this,"logoContainer"),a(this,"compactMenuButton"),a(this,"foldout"),a(this,"_isHandlingChange",!1),a(this,"_didSort",new Map),a(this,"_lastAvailableWidthChange",0),a(this,"_timeoutHandle",0),a(this,"handleSizeChange",(f,v)=>{if(!this._domElement)return;const b=this._domElement.clientWidth;if(b<100){clearTimeout(this._timeoutHandle),this.root.classList.add("compact"),this.foldout.classList.add("floating-panel-style");return}const w=20*2,_=b-w;if(!v&&Math.abs(_-this._lastAvailableWidthChange)<1)return;this._lastAvailableWidthChange=_,clearTimeout(this._timeoutHandle),this._timeoutHandle=setTimeout(()=>{const M=R();M<0?(this.root.classList.add("compact"),this.foldout.classList.add("floating-panel-style")):M>0&&(this.root.classList.remove("compact"),this.foldout.classList.remove("floating-panel-style"),R()<0&&(this.root.classList.add("compact"),this.foldout.classList.add("floating-panel-style")))},5);const C=()=>this.options.clientWidth+this.logoContainer.clientWidth,R=()=>_-C()});const l=document.createElement("template");l.innerHTML=`<style>
379
+ `,this._root.appendChild(t.content.cloneNode(!0)),this.wrapper=this._root.querySelector(".wrapper"),this._root.appendChild(this.wrapper),this.addEventListener("click",()=>{globalThis.open("https://needle.tools","_blank")}),this.wrapper.setAttribute("title","Made with Needle Engine")}static get elementName(){return pu}static create(){return document.createElement(pu)}setLogoVisible(t){this.logoElement.style.display=t?"block":"none"}}customElements.get(pu)||customElements.define(pu,rw);const of=O("debugspatialmenu");class ok{constructor(t,i){a(this,"_context"),a(this,"needleMenu"),a(this,"htmlButtonsMap",new Map),a(this,"enabled",!0),a(this,"userRequestedMenu",!1),a(this,"uiisDirty",!1),a(this,"_showNeedleLogo"),a(this,"_wasInXR",!1),a(this,"preRender",()=>{var r;if(!this.enabled){(r=this.menu)==null||r.removeFromParent();return}of&&Y.isDesktop()&&this.updateMenu();const l=this._context.xr;if(!(l!=null&&l.running)){this._wasInXR&&(this._wasInXR=!1,this.onExitXR());return}this._wasInXR||(this._wasInXR=!0,this.onEnterXR()),this.updateMenu()}),a(this,"_menuTarget",new j),a(this,"positionFilter",new Fm(90,.5)),a(this,"familyName","Needle Spatial Menu"),a(this,"menu"),a(this,"_poweredByNeedleElement");var n;this._context=t,this._context.pre_render_callbacks.push(this.preRender),this.needleMenu=i;const o=(n=this.needleMenu.shadowRoot)==null?void 0:n.querySelector(".options");o?new MutationObserver(r=>{if(this.enabled&&!(this._context.isInXR==!1&&!of))for(const l of r)l.type==="childList"&&(l.addedNodes.forEach(c=>{this.createButtonFromHTMLNode(c)}),l.removedNodes.forEach(c=>{const h=c,d=this.htmlButtonsMap.get(h);d&&(this.htmlButtonsMap.delete(h),d.remove(),Re.update())}))}).observe(o,{childList:!0}):console.error("Could not find options container in needle menu")}setEnabled(t){var i;this.enabled=t,t||(i=this.menu)==null||i.removeFromParent()}setDisplay(t){return this.enabled?(this.userRequestedMenu=t,!0):!1}onDestroy(){const t=this._context.pre_render_callbacks.indexOf(this.preRender);t>-1&&this._context.pre_render_callbacks.splice(t,1)}markDirty(){this.uiisDirty=!0}showNeedleLogo(t){this._showNeedleLogo=t}onEnterXR(){var t;const i=(t=this.needleMenu.shadowRoot)==null?void 0:t.querySelector(".options");i&&i.childNodes.forEach(n=>{this.createButtonFromHTMLNode(n)})}onExitXR(){var t;(t=this.menu)==null||t.removeFromParent()}createButtonFromHTMLNode(t){const i=this.getMenu(),n=this.htmlButtonsMap.get(t);if(n){n.add();return}if(t instanceof HTMLButtonElement){const o=this.createButton(i,t);this.htmlButtonsMap.set(t,o),o.add()}else t instanceof HTMLSlotElement&&t.assignedNodes().forEach(o=>{this.createButtonFromHTMLNode(o)})}updateMenu(){var t,i;performance.mark("NeedleSpatialMenu updateMenu start");const n=this.getMenu();this.handleNeedleWatermark(),this._context.scene.add(n);const o=this._context.mainCamera,r=this._context.xr,l=r?.rigScale||1;if(o){const c=o.worldPosition,h=o.worldForward.multiplyScalar(-1),d=h.y>.6,u=h.y>.4,p=(n.visible?u:d)||this.userRequestedMenu,g=!n.visible&&p;n.visible=p||Y.isDesktop()&&of,h.multiplyScalar(3*l),c.add(h),g&&(n.position.copy(this._menuTarget.position),n.position.y+=.25,this._menuTarget.position.copy(n.position),this.positionFilter.reset(n.position),n.quaternion.copy(this._menuTarget.quaternion),this.markDirty());const y=this._menuTarget.position.distanceTo(c);(g||y>1.5*l)&&(this.ensureRenderOnTop(this.menu),this._menuTarget.position.copy(c),this._context.scene.add(this._menuTarget),Kl(this._menuTarget,this._context.mainCamera,!0,!0),this._menuTarget.removeFromParent()),this.positionFilter.filter(this._menuTarget.position,n.position,this._context.time.time);const f=5;(t=this.menu)==null||t.quaternion.slerp(this._menuTarget.quaternion,this._context.time.deltaTime*f),(i=this.menu)==null||i.scale.setScalar(l)}this.uiisDirty&&(performance.mark("SpatialMenu.update.uiisDirty.start"),this.uiisDirty=!1,Re.update(),performance.mark("SpatialMenu.update.uiisDirty.end"),performance.measure("SpatialMenu.update.uiisDirty","SpatialMenu.update.uiisDirty.start","SpatialMenu.update.uiisDirty.end")),performance.mark("NeedleSpatialMenu updateMenu end"),performance.measure("SpatialMenu.update","NeedleSpatialMenu updateMenu start","NeedleSpatialMenu updateMenu end")}ensureRenderOnTop(t,i=0){t instanceof Q&&(t.material.depthTest=!1,t.material.depthWrite=!1),t.renderOrder=1e3+i*2;for(const n of t.children)this.ensureRenderOnTop(n,i+1)}get isVisible(){var t;return(t=this.menu)==null?void 0:t.visible}getMenu(){if(this.menu)return this.menu;this.ensureFont(),this.menu=new Re.Block({boxSizing:"border-box",fontFamily:this.familyName,height:"auto",fontSize:.1,color:0,lineHeight:1,backgroundColor:16777215,backgroundOpacity:.55,borderRadius:1,whiteSpace:"pre-wrap",flexDirection:"row",alignItems:"center",padding:new me(0,.05,0,.05),borderColor:0,borderOpacity:.05,borderWidth:.005});const t=S.get("ObjectRaycaster");return t&&Cr(this.menu,new t),this.menu}handleNeedleWatermark(){var t;if(!this._poweredByNeedleElement){this._poweredByNeedleElement=new Re.Block({width:"auto",height:"auto",fontSize:.05,whiteSpace:"pre-wrap",flexDirection:"row",flexWrap:"wrap",justifyContent:"center",margin:.02,borderRadius:.02,padding:.02,backgroundColor:16777215,backgroundOpacity:1}),this._poweredByNeedleElement["needle:use_eventsystem"]=!0;const i=new aw(this._context,()=>globalThis.open("https://needle.tools","_self"));Cr(this._poweredByNeedleElement,i);const n=new Re.Text({textContent:"Powered by",width:"auto",height:"auto"}),o=new Re.Text({textContent:"needle",width:"auto",height:"auto",fontSize:.07,margin:new me(0,0,0,.02)});this._poweredByNeedleElement.add(n),this._poweredByNeedleElement.add(o),(t=this.menu)==null||t.add(this._poweredByNeedleElement),this.markDirty(),new va().load("./include/needle/poweredbyneedle.webp",r=>{var l;i.allowModifyUI=!1,n.removeFromParent(),o.removeFromParent();const c=r.image.width/r.image.height;(l=this._poweredByNeedleElement)==null||l.set({backgroundImage:r,backgroundOpacity:1,width:.1*c,height:.1}),this.markDirty()})}if(this.menu){const i=this.menu.children.indexOf(this._poweredByNeedleElement);if(!this._showNeedleLogo&&bo())i>=0&&(this._poweredByNeedleElement.removeFromParent(),this.markDirty());else{this._poweredByNeedleElement.visible=!0,this.menu.add(this._poweredByNeedleElement);const n=this.menu.children.indexOf(this._poweredByNeedleElement);i!==n&&this.markDirty()}}}ensureFont(){let t=Re.FontLibrary.getFontFamily(this.familyName);if(!t){t=Re.FontLibrary.addFontFamily(this.familyName);const i=t.addVariant("normal","normal","./include/needle/arial-msdf.json","./include/needle/arial.png");i?.addEventListener("ready",()=>{this.markDirty()})}}createButton(t,i){const n=new Re.Block({width:"auto",height:"auto",whiteSpace:"pre-wrap",flexDirection:"row",flexWrap:"wrap",justifyContent:"center",backgroundColor:16777215,backgroundOpacity:0,padding:.02,margin:.01,borderRadius:.02,cursor:"pointer",fontSize:.05}),o=new Re.Text({textContent:"",width:"auto",justifyContent:"center",alignItems:"center",backgroundOpacity:0,backgroundColor:16777215,fontFamily:this.familyName,color:0,borderRadius:.02,padding:.01});n.add(o),n["needle:use_eventsystem"]=!0;const r=new aw(this._context,()=>i.click());return Cr(n,r),new rk(this,t,i,n,o)}}class rk{constructor(t,i,n,o,r){a(this,"menu"),a(this,"root"),a(this,"htmlbutton"),a(this,"spatialContainer"),a(this,"spatialText"),a(this,"spatialIcon"),a(this,"_lastText",""),a(this,"_lastTexture"),this.menu=t,this.root=i,this.htmlbutton=n,this.spatialContainer=o,this.spatialText=r,new MutationObserver(l=>{for(const c of l)c.type==="attributes"?c.attributeName==="style"&&this.updateVisible():c.type==="childList"&&this.updateText()}).observe(n,{attributes:!0,childList:!0}),this.updateText()}add(){this.spatialContainer.parent!=this.root&&(this.root.add(this.spatialContainer),this.menu.markDirty(),this.updateVisible(),this.updateText())}remove(){this.spatialContainer.parent&&(this.spatialContainer.removeFromParent(),this.menu.markDirty())}updateVisible(){const t=this.spatialContainer.visible;this.spatialContainer.visible=this.htmlbutton.style.display!=="none",t!==this.spatialContainer.visible&&this.menu.markDirty()}updateText(){let t="",i="";this.htmlbutton.childNodes.forEach(n=>{n.nodeType===Node.TEXT_NODE?t+=n.textContent:n instanceof HTMLElement&&nw(n)&&n.textContent&&(i=n.textContent)}),this._lastText!==t&&(this._lastText=t,this.spatialText.name=t,this.spatialText.set({textContent:t}),this.menu.markDirty()),t.length<=0?this.spatialText.parent&&(this.spatialText.removeFromParent(),this.menu.markDirty()):this.spatialText.parent||(this.spatialContainer.add(this.spatialText),this.menu.markDirty()),i&&this.createIcon(i)}async createIcon(t){var i;if(!this.spatialIcon){const o=await tf(t);if(o&&!this.spatialIcon){const r=new Re.Block({width:.08,height:.08,backgroundColor:16777215,backgroundImage:o,backgroundOpacity:1,margin:new me(0,.005,0,0)});this.spatialIcon=r,this.spatialContainer.add(r),this.menu.markDirty()}}if(t!=this._lastTexture){this._lastTexture=t;const o=await tf(t);o&&((i=this.spatialIcon)==null||i.set({backgroundImage:o}),this.menu.markDirty())}const n=this.spatialContainer.children.indexOf(this.spatialIcon);n>0&&(this.spatialContainer.children.splice(n,1),this.spatialContainer.children.unshift(this.spatialIcon),this.menu.markDirty())}}class aw{constructor(t,i){a(this,"isComponent",!0),a(this,"enabled",!0),a(this,"gameObject"),a(this,"allowModifyUI",!0),a(this,"context"),a(this,"onclick"),this.context=t,this.onclick=i}get activeAndEnabled(){return!0}__internalAwake(){}__internalEnable(){}__internalDisable(){}__internalStart(){}onEnable(){}onDisable(){}get element(){return this.gameObject}onPointerEnter(){this.context.input.setCursorPointer(),this.allowModifyUI&&(this.element.set({backgroundOpacity:1}),Re.update())}onPointerExit(){this.context.input.setCursorNormal(),this.allowModifyUI&&(this.element.set({backgroundOpacity:0}),Re.update())}onPointerDown(t){t.use()}onPointerUp(t){t.use()}onPointerClick(t){t.use(),this.onclick()}}const Tr="needle-menu",Pc=O("debugmenu"),lw=O("debugnoncommercial");let ak=class{constructor(s){a(this,"_context"),a(this,"_menu"),a(this,"_spatialMenu"),a(this,"onPostMessage",t=>{if(t.origin===globalThis.location.origin&&typeof t.data=="object"){const i=t.data,n=i.type;if(n==="needle:menu"){const o=i.button;if(o){if(!o.label)return console.error("NeedleMenu: buttoninfo.label is required");if(!o.onclick)return console.error("NeedleMenu: buttoninfo.onclick is required");const r=document.createElement("button");if(r.textContent=o.label,o.icon){const l=Ot(o.icon);r.prepend(l)}o.priority&&r.setAttribute("priority",o.priority.toString()),r.onclick=()=>{if(o.onclick){const l=o.onclick.startsWith("http")||o.onclick.startsWith("www."),c=o.target||"_blank";l?globalThis.open(o.onclick,c):console.error("NeedleMenu: onclick is not a valid link",o.onclick)}},this._menu.appendChild(r)}else Pc&&console.error("NeedleMenu: unknown postMessage event",i)}else Pc&&console.warn("NeedleMenu: unknown postMessage type",n,i)}}),a(this,"onStartXR",t=>{t.session.isScreenBasedAR&&(this._menu.previousParent=this._menu.parentNode,this._context.arOverlayElement.appendChild(this._menu),t.session.session.addEventListener("end",this.onExitXR),this._menu.closeFoldout())}),a(this,"onExitXR",()=>{this._menu.previousParent&&(this._menu.previousParent.appendChild(this._menu),delete this._menu.previousParent)}),a(this,"_muteButton"),a(this,"_fullscreenButton"),this._menu=hw.getOrCreate(s.domElement,s),this._context=s,this._spatialMenu=new ok(s,this._menu),window.addEventListener("message",this.onPostMessage),kd(this.onStartXR)}onDestroy(){window.removeEventListener("message",this.onPostMessage),this._menu.remove(),this._spatialMenu.onDestroy()}setPosition(s){this._menu.setPosition(s)}setVisible(s){this._menu.setVisible(s)}showNeedleLogo(s){var t;this._menu.showNeedleLogo(s),(t=this._spatialMenu)==null||t.showNeedleLogo(s)}showSpatialMenu(s){this._spatialMenu.setEnabled(s)}setSpatialMenuVisible(s){this._spatialMenu.setDisplay(s)}get spatialMenuIsVisible(){return this._spatialMenu.isVisible}showQRCodeButton(s){if(s==="desktop-only"&&(s=!Y.isMobileDevice()),s){const t=Mn.getOrCreate().createQRCode();return t.style.display="",this._menu.appendChild(t),t}else{const t=Mn.getOrCreate().qrButton;return t&&(t.style.display="none"),t??null}}showAudioPlaybackOption(s){var t;if(!s){(t=this._muteButton)==null||t.remove();return}this._muteButton=Mn.getOrCreate().createMuteButton(this._context),this._muteButton.setAttribute("priority","100"),this._menu.appendChild(this._muteButton)}showFullscreenOption(s){var t;if(!s){(t=this._fullscreenButton)==null||t.remove();return}this._fullscreenButton=Mn.getOrCreate().createFullscreenButton(this._context),this._fullscreenButton&&(this._fullscreenButton.setAttribute("priority","150"),this._menu.appendChild(this._fullscreenButton))}appendChild(s){return this._menu.appendChild(s)}};var mu,gu,rf;const cw=class extends HTMLElement{constructor(){var s,t,i,n,o,r;super(),Hi(this,gu),a(this,"_domElement",null),a(this,"_context",null),a(this,"_sizeChangeInterval"),Hi(this,mu,f=>{if(!f.defaultPrevented&&f.target==this._domElement&&f instanceof PointerEvent&&f.button===0&&this.root.classList.contains("open")){const v=this.foldout.getBoundingClientRect(),b=f;b.clientX>v.left&&b.clientX<v.right&&b.clientY>v.top&&b.clientY<v.bottom||this.root.classList.toggle("open",!1)}}),a(this,"_userRequestedLogoVisible"),a(this,"_userRequestedMenuVisible"),a(this,"root"),a(this,"wrapper"),a(this,"options"),a(this,"logoContainer"),a(this,"compactMenuButton"),a(this,"foldout"),a(this,"_isHandlingChange",!1),a(this,"_didSort",new Map),a(this,"_lastAvailableWidthChange",0),a(this,"_timeoutHandle",0),a(this,"handleSizeChange",(f,v)=>{if(!this._domElement)return;const b=this._domElement.clientWidth;if(b<100){clearTimeout(this._timeoutHandle),this.root.classList.add("compact"),this.foldout.classList.add("floating-panel-style");return}const w=20*2,_=b-w;if(!v&&Math.abs(_-this._lastAvailableWidthChange)<1)return;this._lastAvailableWidthChange=_,clearTimeout(this._timeoutHandle),this._timeoutHandle=setTimeout(()=>{const M=R();M<0?(this.root.classList.add("compact"),this.foldout.classList.add("floating-panel-style")):M>0&&(this.root.classList.remove("compact"),this.foldout.classList.remove("floating-panel-style"),R()<0&&(this.root.classList.add("compact"),this.foldout.classList.add("floating-panel-style")))},5);const C=()=>this.options.clientWidth+this.logoContainer.clientWidth,R=()=>_-C()});const l=document.createElement("template");l.innerHTML=`<style>
380
380
 
381
381
  #root {
382
382
  position: absolute;
@@ -749,20 +749,20 @@ vec3 AgXToneMapping( vec3 color ) {
749
749
  <div class="expanded-click-area"></div>
750
750
  </button>
751
751
  </div>
752
- `;const c=this.attachShadow({mode:"open"});ow(),uu(nf,{loadedCallback:()=>{this.handleSizeChange()}}),uu(nf,{element:c});const h=l.content.cloneNode(!0);c?.appendChild(h),this.root=c.querySelector("#root"),this.wrapper=(s=this.root)==null?void 0:s.querySelector(".wrapper"),this.options=(t=this.root)==null?void 0:t.querySelector(".options"),this.logoContainer=(i=this.root)==null?void 0:i.querySelector(".logo"),this.compactMenuButton=(n=this.root)==null?void 0:n.querySelector(".compact-menu-button"),this.compactMenuButton.append(Ot("more_vert")),this.foldout=(o=this.root)==null?void 0:o.querySelector(".foldout"),(r=this.root)==null||r.appendChild(this.wrapper),this.wrapper.classList.add("wrapper");const d=rw.create();d.style.minHeight="1rem",this.logoContainer.append(d),this.logoContainer.addEventListener("click",()=>{globalThis.open("https://needle.tools","_blank")});try{window.requestAnimationFrame(()=>m2(f=>{if(f==!0&&Ss()&&!lw){let v=this._userRequestedLogoVisible;v===void 0&&(v=!1),ya(this,gu,rf).call(this,v)}}))}catch(f){console.error("[Needle Menu] License check failed.",f)}this.compactMenuButton.addEventListener("click",f=>{f.preventDefault(),this.root.classList.toggle("open")});let u=this._context;setTimeout(()=>u=this._context);let p=0;const g=(f,v)=>{var b,w,_;Pc&&console.log("Set menu visible",v),u!=null&&u.isInAR&&u.arOverlayElement?f!=u.arOverlayElement&&u.arOverlayElement.appendChild(this):this.parentNode!=((b=this._domElement)==null?void 0:b.shadowRoot)&&((_=(w=this._domElement)==null?void 0:w.shadowRoot)==null||_.appendChild(this)),this.style.display=v?"flex":"none",this.style.visibility="visible",this.style.opacity="1"};let y=!1;new MutationObserver(f=>{var v;if(!y)try{y=!0,this.onChangeDetected(f);const b=this==null?void 0:this.parentNode;if((this.style.display!="flex"||this.style.visibility!="visible"||this.style.opacity!="1"||b!=((v=this._domElement)==null?void 0:v.shadowRoot))&&!Ss()){const w=p++;Gt()&&this._userRequestedMenuVisible===!1?(w===0&&g(b,this._userRequestedMenuVisible),w===1&&console.warn("Needle Menu Warning: You need a PRO license to hide the Needle Engine menu \u2192 The menu will be visible in your deployed website if you don't have a PRO license. See https://needle.tools/pricing for details.")):w===0?g(b,!0):setTimeout(()=>g(b,!0),5)}}finally{y=!1}}).observe(this.root,{childList:!0,subtree:!0,attributes:!0}),Pc&&this.___insertDebugOptions()}static create(){return document.createElement(Tr,{is:Tr})}static getOrCreate(s,t){let i=s.querySelector(Tr);return!i&&s.shadowRoot&&(i=s.shadowRoot.querySelector(Tr)),i||(i=window.document.body.querySelector(Tr)),i||(i=cw.create(),s.shadowRoot?s.shadowRoot.appendChild(i):s.appendChild(i)),i._domElement=s,i._context=t,i}connectedCallback(){window.addEventListener("resize",this.handleSizeChange),this.handleMenuVisible(),this._sizeChangeInterval=setInterval(()=>this.handleSizeChange(void 0,!0),5e3),setTimeout(()=>{var s,t;(s=this._domElement)==null||s.addEventListener("resize",this.handleSizeChange),(t=this._domElement)==null||t.addEventListener("click",pe(this,mu))},1)}disconnectedCallback(){var s,t;window.removeEventListener("resize",this.handleSizeChange),clearInterval(this._sizeChangeInterval),(s=this._domElement)==null||s.removeEventListener("resize",this.handleSizeChange),(t=this._context)==null||t.domElement.removeEventListener("click",pe(this,mu))}showNeedleLogo(s){this._userRequestedLogoVisible=s,!(!s&&(!Ss()||lw)&&(console.warn("Needle Menu: You need a PRO license to hide the Needle Engine logo."),!Gt()))&&ya(this,gu,rf).call(this,s)}setPosition(s){if(s!=="top"&&s!=="bottom")return console.error("NeedleMenu.setPosition: invalid position",s);this.root.classList.remove("top","bottom"),this.root.classList.add(s)}setVisible(s){this._userRequestedMenuVisible=s,this.style.display=s?"flex":"none"}closeFoldout(){this.root.classList.remove("open")}append(...s){for(const t of s)if(typeof t=="string"){const i=document.createTextNode(t);this.options.appendChild(i)}else this.options.appendChild(t)}appendChild(s){var t;if(!(s instanceof Node)){const i=document.createElement("button");if(i.textContent=s.label,i.onclick=s.onClick,i.setAttribute("priority",((t=s.priority)==null?void 0:t.toString())??"0"),s.title&&(i.title=s.title),s.icon){const n=Ot(s.icon);s.iconSide==="right"?i.appendChild(n):i.prepend(n)}s.class&&i.classList.add(s.class),s=i}return this.options.appendChild(s)}prepend(...s){for(const t of s)if(typeof t=="string"){const i=document.createTextNode(t);this.options.prepend(i)}else this.options.prepend(t)}onChangeDetected(s){if(!this._isHandlingChange){this._isHandlingChange=!0;try{this.handleMenuVisible();for(const t of s)t.target==this.options&&this.onOptionsChildrenChanged(t)}finally{this._isHandlingChange=!1}}}onOptionsChildrenChanged(s){if(this.root.classList.toggle("has-options",this.hasAnyVisibleOptions),this.root.classList.toggle("has-no-options",!this.hasAnyVisibleOptions),this.handleSizeChange(void 0,!0),s.type==="childList"&&s.addedNodes.length>0){const t=Array.from(this.options.children);t.sort((n,o)=>{const r=parseInt(n.getAttribute("priority")||"0"),l=parseInt(o.getAttribute("priority")||"0");return r-l});let i=!1;for(let n=0;n<t.length;n++){const o=this.options.children[n],r=t[n];if(o!==r){i=!0;break}}if(i)for(const n of t)this.options.appendChild(n)}}handleMenuVisible(){Pc&&console.log("Update VisibleState: Any Content?",this.hasAnyContent),this.hasAnyContent?this.root.style.display="":this.root.style.display="none",this.root.classList.toggle("has-options",this.hasAnyVisibleOptions),this.root.classList.toggle("has-no-options",!this.hasAnyVisibleOptions)}get hasAnyContent(){return!!(this.logoContainer.style.display!="none"||this.hasAnyVisibleOptions)}get hasAnyVisibleOptions(){for(let s=0;s<this.options.children.length;s++){const t=this.options.children[s];if(t.tagName==="SLOT"){const i=t.assignedNodes();for(const n of i)if(n instanceof HTMLElement&&n.style.display!="none")return!0}else if(t.style.display!="none")return!0}return!1}___insertDebugOptions(){window.addEventListener("keydown",i=>{i.key==="p"&&this.setPosition(this.root.classList.contains("top")?"bottom":"top")});const s=document.createElement("button");s.textContent="Hide Buttons",s.onclick=()=>{const i=new Array(this.options.children.length);for(let n=0;n<this.options.children.length;n++)i[n]=this.options.children[n];for(const n of i)this.options.removeChild(n);setTimeout(()=>{for(const n of i)this.options.appendChild(n)},1e3)},this.appendChild(s);const t=document.createElement("button");t.textContent="Toggle Logo",t.addEventListener("click",()=>{this.logoContainer.style.display=this.logoContainer.style.display==="none"?"":"none"}),this.appendChild(t)}};let hw=cw;mu=new WeakMap,gu=new WeakSet,rf=function(s){this.logoContainer.style.display="",this.logoContainer.style.opacity="1",this.logoContainer.style.visibility="visible",s?(this.root.classList.remove("logo-hidden"),this.root.classList.add("logo-visible")):(this.root.classList.remove("logo-visible"),this.root.classList.add("logo-hidden"))},customElements.get(Tr)||customElements.define(Tr,hw);const st=O("debugcontext"),l2=O("stats"),c2=O("debugactive"),h2=O("debugframerate"),d2=O("debugcoroutine"),u2={};class p2{constructor(){a(this,"name"),a(this,"alias"),a(this,"hash"),a(this,"runInBackground"),a(this,"domElement"),a(this,"renderer"),a(this,"camera"),a(this,"scene")}}var Ce=(s=>(s[s.Start=-1]="Start",s[s.EarlyUpdate=0]="EarlyUpdate",s[s.Update=1]="Update",s[s.LateUpdate=2]="LateUpdate",s[s.OnBeforeRender=3]="OnBeforeRender",s[s.OnAfterRender=4]="OnAfterRender",s[s.PrePhysicsStep=9]="PrePhysicsStep",s[s.PostPhysicsStep=10]="PostPhysicsStep",s[s.Undefined=-1]="Undefined",s))(Ce||{});function fu(s,t){if(!s)return;if(!s.isComponent){(F()||st)&&console.error(`Registered script is not a Needle Engine component.
752
+ `;const c=this.attachShadow({mode:"open"});ow(),uu(nf,{loadedCallback:()=>{this.handleSizeChange()}}),uu(nf,{element:c});const h=l.content.cloneNode(!0);c?.appendChild(h),this.root=c.querySelector("#root"),this.wrapper=(s=this.root)==null?void 0:s.querySelector(".wrapper"),this.options=(t=this.root)==null?void 0:t.querySelector(".options"),this.logoContainer=(i=this.root)==null?void 0:i.querySelector(".logo"),this.compactMenuButton=(n=this.root)==null?void 0:n.querySelector(".compact-menu-button"),this.compactMenuButton.append(Ot("more_vert")),this.foldout=(o=this.root)==null?void 0:o.querySelector(".foldout"),(r=this.root)==null||r.appendChild(this.wrapper),this.wrapper.classList.add("wrapper");const d=rw.create();d.style.minHeight="1rem",this.logoContainer.append(d),this.logoContainer.addEventListener("click",()=>{globalThis.open("https://needle.tools","_blank")});try{window.requestAnimationFrame(()=>mk(f=>{if(f==!0&&Ss()&&!lw){let v=this._userRequestedLogoVisible;v===void 0&&(v=!1),ya(this,gu,rf).call(this,v)}}))}catch(f){console.error("[Needle Menu] License check failed.",f)}this.compactMenuButton.addEventListener("click",f=>{f.preventDefault(),this.root.classList.toggle("open")});let u=this._context;setTimeout(()=>u=this._context);let p=0;const g=(f,v)=>{var b,w,_;Pc&&console.log("Set menu visible",v),u!=null&&u.isInAR&&u.arOverlayElement?f!=u.arOverlayElement&&u.arOverlayElement.appendChild(this):this.parentNode!=((b=this._domElement)==null?void 0:b.shadowRoot)&&((_=(w=this._domElement)==null?void 0:w.shadowRoot)==null||_.appendChild(this)),this.style.display=v?"flex":"none",this.style.visibility="visible",this.style.opacity="1"};let y=!1;new MutationObserver(f=>{var v;if(!y)try{y=!0,this.onChangeDetected(f);const b=this==null?void 0:this.parentNode;if((this.style.display!="flex"||this.style.visibility!="visible"||this.style.opacity!="1"||b!=((v=this._domElement)==null?void 0:v.shadowRoot))&&!Ss()){const w=p++;Gt()&&this._userRequestedMenuVisible===!1?(w===0&&g(b,this._userRequestedMenuVisible),w===1&&console.warn("Needle Menu Warning: You need a PRO license to hide the Needle Engine menu \u2192 The menu will be visible in your deployed website if you don't have a PRO license. See https://needle.tools/pricing for details.")):w===0?g(b,!0):setTimeout(()=>g(b,!0),5)}}finally{y=!1}}).observe(this.root,{childList:!0,subtree:!0,attributes:!0}),Pc&&this.___insertDebugOptions()}static create(){return document.createElement(Tr,{is:Tr})}static getOrCreate(s,t){let i=s.querySelector(Tr);return!i&&s.shadowRoot&&(i=s.shadowRoot.querySelector(Tr)),i||(i=window.document.body.querySelector(Tr)),i||(i=cw.create(),s.shadowRoot?s.shadowRoot.appendChild(i):s.appendChild(i)),i._domElement=s,i._context=t,i}connectedCallback(){window.addEventListener("resize",this.handleSizeChange),this.handleMenuVisible(),this._sizeChangeInterval=setInterval(()=>this.handleSizeChange(void 0,!0),5e3),setTimeout(()=>{var s,t;(s=this._domElement)==null||s.addEventListener("resize",this.handleSizeChange),(t=this._domElement)==null||t.addEventListener("click",pe(this,mu))},1)}disconnectedCallback(){var s,t;window.removeEventListener("resize",this.handleSizeChange),clearInterval(this._sizeChangeInterval),(s=this._domElement)==null||s.removeEventListener("resize",this.handleSizeChange),(t=this._context)==null||t.domElement.removeEventListener("click",pe(this,mu))}showNeedleLogo(s){this._userRequestedLogoVisible=s,!(!s&&(!Ss()||lw)&&(console.warn("Needle Menu: You need a PRO license to hide the Needle Engine logo."),!Gt()))&&ya(this,gu,rf).call(this,s)}setPosition(s){if(s!=="top"&&s!=="bottom")return console.error("NeedleMenu.setPosition: invalid position",s);this.root.classList.remove("top","bottom"),this.root.classList.add(s)}setVisible(s){this._userRequestedMenuVisible=s,this.style.display=s?"flex":"none"}closeFoldout(){this.root.classList.remove("open")}append(...s){for(const t of s)if(typeof t=="string"){const i=document.createTextNode(t);this.options.appendChild(i)}else this.options.appendChild(t)}appendChild(s){var t;if(!(s instanceof Node)){const i=document.createElement("button");if(i.textContent=s.label,i.onclick=s.onClick,i.setAttribute("priority",((t=s.priority)==null?void 0:t.toString())??"0"),s.title&&(i.title=s.title),s.icon){const n=Ot(s.icon);s.iconSide==="right"?i.appendChild(n):i.prepend(n)}s.class&&i.classList.add(s.class),s=i}return this.options.appendChild(s)}prepend(...s){for(const t of s)if(typeof t=="string"){const i=document.createTextNode(t);this.options.prepend(i)}else this.options.prepend(t)}onChangeDetected(s){if(!this._isHandlingChange){this._isHandlingChange=!0;try{this.handleMenuVisible();for(const t of s)t.target==this.options&&this.onOptionsChildrenChanged(t)}finally{this._isHandlingChange=!1}}}onOptionsChildrenChanged(s){if(this.root.classList.toggle("has-options",this.hasAnyVisibleOptions),this.root.classList.toggle("has-no-options",!this.hasAnyVisibleOptions),this.handleSizeChange(void 0,!0),s.type==="childList"&&s.addedNodes.length>0){const t=Array.from(this.options.children);t.sort((n,o)=>{const r=parseInt(n.getAttribute("priority")||"0"),l=parseInt(o.getAttribute("priority")||"0");return r-l});let i=!1;for(let n=0;n<t.length;n++){const o=this.options.children[n],r=t[n];if(o!==r){i=!0;break}}if(i)for(const n of t)this.options.appendChild(n)}}handleMenuVisible(){Pc&&console.log("Update VisibleState: Any Content?",this.hasAnyContent),this.hasAnyContent?this.root.style.display="":this.root.style.display="none",this.root.classList.toggle("has-options",this.hasAnyVisibleOptions),this.root.classList.toggle("has-no-options",!this.hasAnyVisibleOptions)}get hasAnyContent(){return!!(this.logoContainer.style.display!="none"||this.hasAnyVisibleOptions)}get hasAnyVisibleOptions(){for(let s=0;s<this.options.children.length;s++){const t=this.options.children[s];if(t.tagName==="SLOT"){const i=t.assignedNodes();for(const n of i)if(n instanceof HTMLElement&&n.style.display!="none")return!0}else if(t.style.display!="none")return!0}return!1}___insertDebugOptions(){window.addEventListener("keydown",i=>{i.key==="p"&&this.setPosition(this.root.classList.contains("top")?"bottom":"top")});const s=document.createElement("button");s.textContent="Hide Buttons",s.onclick=()=>{const i=new Array(this.options.children.length);for(let n=0;n<this.options.children.length;n++)i[n]=this.options.children[n];for(const n of i)this.options.removeChild(n);setTimeout(()=>{for(const n of i)this.options.appendChild(n)},1e3)},this.appendChild(s);const t=document.createElement("button");t.textContent="Toggle Logo",t.addEventListener("click",()=>{this.logoContainer.style.display=this.logoContainer.style.display==="none"?"":"none"}),this.appendChild(t)}};let hw=cw;mu=new WeakMap,gu=new WeakSet,rf=function(s){this.logoContainer.style.display="",this.logoContainer.style.opacity="1",this.logoContainer.style.visibility="visible",s?(this.root.classList.remove("logo-hidden"),this.root.classList.add("logo-visible")):(this.root.classList.remove("logo-visible"),this.root.classList.add("logo-hidden"))},customElements.get(Tr)||customElements.define(Tr,hw);const st=O("debugcontext"),lk=O("stats"),ck=O("debugactive"),hk=O("debugframerate"),dk=O("debugcoroutine"),uk={};class pk{constructor(){a(this,"name"),a(this,"alias"),a(this,"hash"),a(this,"runInBackground"),a(this,"domElement"),a(this,"renderer"),a(this,"camera"),a(this,"scene")}}var Ce=(s=>(s[s.Start=-1]="Start",s[s.EarlyUpdate=0]="EarlyUpdate",s[s.Update=1]="Update",s[s.LateUpdate=2]="LateUpdate",s[s.OnBeforeRender=3]="OnBeforeRender",s[s.OnAfterRender=4]="OnAfterRender",s[s.PrePhysicsStep=9]="PrePhysicsStep",s[s.PostPhysicsStep=10]="PostPhysicsStep",s[s.Undefined=-1]="Undefined",s))(Ce||{});function fu(s,t){if(!s)return;if(!s.isComponent){(F()||st)&&console.error(`Registered script is not a Needle Engine component.
753
753
  The script will be ignored. Please make sure your component extends "Behaviour" imported from "@needle-tools/engine"
754
- `,s);return}t||(t=te.Current,st&&console.warn("> Registering component without context"));const i=t?.new_scripts;i.includes(s)||i.push(s)}const Ae=class{constructor(s){a(this,"name"),a(this,"alias"),a(this,"isManagedExternally",!1),a(this,"isPaused",!1),a(this,"runInBackground",!1),a(this,"targetFrameRate"),a(this,"physicsSteps",1),a(this,"hash"),a(this,"domElement"),a(this,"_resolutionScaleFactor",1),a(this,"_boundingClientRectFrame",-1),a(this,"_boundingClientRect",null),a(this,"_domX"),a(this,"_domY"),a(this,"xr",null),a(this,"_xrFrame",null),a(this,"_currentFrameEvent",-1),a(this,"scene"),a(this,"renderer"),a(this,"composer",null),a(this,"scripts",[]),a(this,"scripts_pausedChanged",[]),a(this,"scripts_earlyUpdate",[]),a(this,"scripts_update",[]),a(this,"scripts_lateUpdate",[]),a(this,"scripts_onBeforeRender",[]),a(this,"scripts_onAfterRender",[]),a(this,"scripts_WithCorroutines",[]),a(this,"scripts_immersive_vr",[]),a(this,"scripts_immersive_ar",[]),a(this,"coroutines",{}),a(this,"post_setup_callbacks",[]),a(this,"pre_update_callbacks",[]),a(this,"pre_render_callbacks",[]),a(this,"post_render_callbacks",[]),a(this,"pre_update_oneshot_callbacks",[]),a(this,"new_scripts",[]),a(this,"new_script_start",[]),a(this,"new_scripts_pre_setup_callbacks",[]),a(this,"new_scripts_post_setup_callbacks",[]),a(this,"new_scripts_xr",[]),a(this,"mainCameraComponent"),a(this,"_mainCamera",null),a(this,"_fallbackCamera",null),a(this,"application"),a(this,"animations"),a(this,"time"),a(this,"input"),a(this,"physics"),a(this,"connection"),a(this,"assets"),a(this,"mainLight",null),a(this,"sceneLighting"),a(this,"addressables"),a(this,"lightmaps"),a(this,"players"),a(this,"lodsManager"),a(this,"menu"),a(this,"_sizeChanged",!1),a(this,"_isCreated",!1),a(this,"_isCreating",!1),a(this,"_isVisible",!1),a(this,"_stats",l2?new AC:null),a(this,"_intersectionObserver",null),a(this,"_disposeCallbacks",[]),a(this,"maxRenderResolution"),a(this,"_originalCreationArgs"),a(this,"onUnhandledRejection",n=>{this.onError(n.reason)}),a(this,"_cameraStack",[]),a(this,"_onBeforeRenderListeners",new Map),a(this,"_onAfterRenderListeners",new Map),a(this,"_requireDepthTexture",!1),a(this,"_requireColorTexture",!1),a(this,"_renderTarget"),a(this,"_isRendering",!1),a(this,"_createId",0),a(this,"_renderlooperrors",0),a(this,"_lastTimestamp",0),a(this,"_accumulatedTime",0),a(this,"_dispatchReadyAfterFrame",!1),a(this,"_wasPaused",!1),this.name=s?.name||"",this.alias=s?.alias,this.domElement=s?.domElement||document.body,this.hash=s?.hash,s!=null&&s.renderer&&(this.renderer=s.renderer,this.isManagedExternally=!0),s?.runInBackground!==void 0&&(this.runInBackground=s.runInBackground),s!=null&&s.scene?this.scene=s.scene:this.scene=new $i,s!=null&&s.camera&&(this._mainCamera=s.camera),this.application=new kn(this),this.time=new tw,this.input=new yb(this),this.physics=new Id(this),this.connection=new Ab(this),this.assets=new Xb,this.sceneLighting=new Z_(this),this.addressables=new U_(this),this.lightmaps=new Xk(this),this.players=new Q_(this),this.menu=new a2(this),this.lodsManager=new Qk(this),this.animations=new $k(this);const t=()=>this._sizeChanged=!0;window.addEventListener("resize",t),this._disposeCallbacks.push(()=>window.removeEventListener("resize",t));const i=new ResizeObserver(n=>this._sizeChanged=!0);i.observe(this.domElement),this._disposeCallbacks.push(()=>i.disconnect()),this._intersectionObserver=new IntersectionObserver(n=>{this._isVisible=n[0].isIntersecting}),this._disposeCallbacks.push(()=>{var n;return(n=this._intersectionObserver)==null?void 0:n.disconnect()}),ge.register(this)}static get DefaultTargetFrameRate(){return Ae._defaultTargetFramerate.value}static set DefaultTargetFrameRate(s){Ae._defaultTargetFramerate.value=s}static get DefaultWebGLRendererParameters(){return Ae._defaultWebglRendererParameters}get version(){return vs}static get Current(){return ge.Current}static set Current(s){ge.Current=s}appendHTMLElement(s){return this.domElement.shadowRoot?this.domElement.shadowRoot.appendChild(s):this.domElement.appendChild(s)}get resolutionScaleFactor(){return this._resolutionScaleFactor}set resolutionScaleFactor(s){if(s!==this._resolutionScaleFactor&&typeof s=="number"){if(s<=0){console.error("Invalid resolution scale factor",s);return}this._resolutionScaleFactor=s,this.updateSize()}}calculateBoundingClientRect(){if(this.xr){this._domX=0,this._domY=0;return}this._boundingClientRectFrame!==this.time.frame&&(this._boundingClientRectFrame=this.time.frame,this._boundingClientRect=this.domElement.getBoundingClientRect(),this._domX=this._boundingClientRect.x,this._domY=this._boundingClientRect.y)}get domWidth(){return this.isInAR?window.innerWidth:this.domElement.clientWidth}get domHeight(){return this.isInAR?window.innerHeight:this.domElement.clientHeight}get domX(){return this.calculateBoundingClientRect(),this._domX}get domY(){return this.calculateBoundingClientRect(),this._domY}get isInXR(){var s,t;return((t=(s=this.renderer)==null?void 0:s.xr)==null?void 0:t.isPresenting)||!1}get xrSessionMode(){var s;return(s=this.xr)==null?void 0:s.mode}get isInVR(){return this.xrSessionMode==="immersive-vr"}get isInAR(){return this.xrSessionMode==="immersive-ar"}get isInPassThrough(){return this.xr?this.xr.isPassThrough:!1}get xrSession(){var s,t;return(t=(s=this.renderer)==null?void 0:s.xr)==null?void 0:t.getSession()}get xrFrame(){return this._xrFrame}get xrCamera(){var s,t;return this.renderer.xr.isPresenting?(t=(s=this.renderer)==null?void 0:s.xr)==null?void 0:t.getCamera():void 0}get arOverlayElement(){const s=this.domElement;return typeof s.getAROverlayContainer=="function"?s.getAROverlayContainer():this.domElement}get currentFrameEvent(){return this._currentFrameEvent}get mainCamera(){if(this._mainCamera)return this._mainCamera;if(this.mainCameraComponent){const s=this.mainCameraComponent;return s.threeCamera||s.buildCamera(),s.threeCamera}return this._fallbackCamera||(this._fallbackCamera=new be(75,this.domWidth/this.domHeight,.1,1e3)),this._fallbackCamera}set mainCamera(s){this._mainCamera=s}get rendererData(){return this.sceneLighting}get isCreated(){return this._isCreated}createNewRenderer(s){var t,i,n;if((t=this.renderer)==null||t.dispose(),s={...Ae.DefaultWebGLRendererParameters,...s},!s.canvas){const o=(n=(i=this.domElement)==null?void 0:i.shadowRoot)==null?void 0:n.querySelector("canvas");o&&(s.canvas=o,st&&console.log("Using canvas from shadow root",o))}st&&console.log("Using Renderer Parameters:",s,this.domElement),this.renderer=new cr(s),this.renderer.debug.checkShaderErrors=F()||O("checkshadererrors")===!0,this.renderer.toneMappingExposure=1,this.renderer.toneMapping=_a,this.renderer.setClearColor(new ae("lightgrey"),0),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=CS,this.renderer.setSize(this.domWidth,this.domHeight),this.renderer.outputColorSpace=ps,this.renderer.nodes={library:new OS,modelViewMatrix:null,modelNormalViewMatrix:null},this.lodsManager.setRenderer(this.renderer),this.input.bindEvents()}internalOnUpdateVisible(){var s,t;(s=this._intersectionObserver)==null||s.disconnect(),(t=this._intersectionObserver)==null||t.observe(this.domElement)}requestSizeUpdate(){this._sizeChanged=!0}updateSize(s=!1){var t,i,n;if(s||!this.isManagedExternally&&((t=this.renderer.xr)==null?void 0:t.isPresenting)===!1){this._sizeChanged=!1;const o=this.resolutionScaleFactor;let r=this.domWidth*o,l=this.domHeight*o;this.maxRenderResolution&&(this.maxRenderResolution.x=Math.max(1,this.maxRenderResolution.x),r=Math.min(this.maxRenderResolution.x,r),this.maxRenderResolution.y=Math.max(1,this.maxRenderResolution.y),l=Math.min(this.maxRenderResolution.y,l));const c=this.mainCamera;this.updateAspect(c),this.renderer.setSize(r,l,!0),this.renderer.setPixelRatio(window.devicePixelRatio),this.renderer.domElement.style.width="100%",this.renderer.domElement.style.height="100%",this.composer&&((i=this.composer.setSize)==null||i.call(this.composer,r,l),"setPixelRatio"in this.composer&&typeof this.composer.setPixelRatio=="function"&&((n=this.composer.setPixelRatio)==null||n.call(this.composer,window.devicePixelRatio)))}}updateAspect(s,t,i){if(!s)return;t===void 0&&(t=this.domWidth),i===void 0&&(i=this.domHeight);const n=t/i;if(s.isPerspectiveCamera){const o=s,r=o.aspect;o.aspect=n,r!==o.aspect&&s.updateProjectionMatrix()}else if(s.isOrthographicCamera){const o=s,r=o.top-o.bottom,l=r*n/2,c=r/2;(o.left!=-l||o.top!=c)&&(o.left=-l,o.right=l,o.top=c,o.bottom=-c,s.updateProjectionMatrix())}}recreate(){this.clear(),this.create(this._originalCreationArgs)}async onCreate(s){return this.create(s)}async create(s){try{this._isCreating=!0,s!==this._originalCreationArgs&&(this._originalCreationArgs=Gl(s)),window.addEventListener("unhandledrejection",this.onUnhandledRejection);const t=await this.internalOnCreate(s);return this._isCreated=t,t}finally{window.removeEventListener("unhandledrejection",this.onUnhandledRejection),this._isCreating=!1}}onError(s){this.domElement.dispatchEvent(new CustomEvent("error",{detail:s}))}clear(){var s,t,i,n;ge.dispatchCallback(fe.ContextClearing,this),Us(this,fe.ContextClearing),Mi(this.scene,!0,!0),this.scene=new $i,(s=this.addressables)==null||s.dispose(),(t=this.lightmaps)==null||t.clear(),(n=(i=this.physics)==null?void 0:i.engine)==null||n.clearCaches(),this.lodsManager.disable(),this.isManagedExternally||this.renderer&&(this.renderer.renderLists.dispose(),this.renderer.state.reset(),this.renderer.resetState()),ge.dispatchCallback(fe.ContextCleared,this)}dispose(){this.internalOnDestroy()}onDestroy(){this.internalOnDestroy()}internalOnDestroy(){var s,t;Ae.Current=this,ge.dispatchCallback(fe.ContextDestroying,this),Us(this,fe.ContextDestroying),this.clear(),(s=this.renderer)==null||s.setAnimationLoop(null),this.renderer&&(this.renderer.setClearAlpha(0),this.renderer.clear(),this.isManagedExternally||(st&&console.log("Disposing renderer"),this.renderer.dispose())),this.scene=null,this.renderer=null,this.input.dispose(),this.menu.onDestroy(),this.animations.onDestroy();for(const i of this._disposeCallbacks)try{i()}catch(n){console.error("Error in on dispose callback:",n,i)}(t=this.domElement)!=null&&t.parentElement&&this.domElement.parentElement.removeChild(this.domElement),this._isCreated=!1,ge.dispatchCallback(fe.ContextDestroyed,this),Us(this,fe.ContextDestroyed),ge.unregister(this),Ae.Current===this&&(Ae.Current=null)}registerCoroutineUpdate(s,t,i){return typeof t?.next!="function"?(console.error("Registered invalid coroutine function from "+s.name+`
754
+ `,s);return}t||(t=te.Current,st&&console.warn("> Registering component without context"));const i=t?.new_scripts;i.includes(s)||i.push(s)}const Ae=class{constructor(s){a(this,"name"),a(this,"alias"),a(this,"isManagedExternally",!1),a(this,"isPaused",!1),a(this,"runInBackground",!1),a(this,"targetFrameRate"),a(this,"physicsSteps",1),a(this,"hash"),a(this,"domElement"),a(this,"_resolutionScaleFactor",1),a(this,"_boundingClientRectFrame",-1),a(this,"_boundingClientRect",null),a(this,"_domX"),a(this,"_domY"),a(this,"xr",null),a(this,"_xrFrame",null),a(this,"_currentFrameEvent",-1),a(this,"scene"),a(this,"renderer"),a(this,"composer",null),a(this,"scripts",[]),a(this,"scripts_pausedChanged",[]),a(this,"scripts_earlyUpdate",[]),a(this,"scripts_update",[]),a(this,"scripts_lateUpdate",[]),a(this,"scripts_onBeforeRender",[]),a(this,"scripts_onAfterRender",[]),a(this,"scripts_WithCorroutines",[]),a(this,"scripts_immersive_vr",[]),a(this,"scripts_immersive_ar",[]),a(this,"coroutines",{}),a(this,"post_setup_callbacks",[]),a(this,"pre_update_callbacks",[]),a(this,"pre_render_callbacks",[]),a(this,"post_render_callbacks",[]),a(this,"pre_update_oneshot_callbacks",[]),a(this,"new_scripts",[]),a(this,"new_script_start",[]),a(this,"new_scripts_pre_setup_callbacks",[]),a(this,"new_scripts_post_setup_callbacks",[]),a(this,"new_scripts_xr",[]),a(this,"mainCameraComponent"),a(this,"_mainCamera",null),a(this,"_fallbackCamera",null),a(this,"application"),a(this,"animations"),a(this,"time"),a(this,"input"),a(this,"physics"),a(this,"connection"),a(this,"assets"),a(this,"mainLight",null),a(this,"sceneLighting"),a(this,"addressables"),a(this,"lightmaps"),a(this,"players"),a(this,"lodsManager"),a(this,"menu"),a(this,"_sizeChanged",!1),a(this,"_isCreated",!1),a(this,"_isCreating",!1),a(this,"_isVisible",!1),a(this,"_stats",lk?new AC:null),a(this,"_intersectionObserver",null),a(this,"_disposeCallbacks",[]),a(this,"maxRenderResolution"),a(this,"_originalCreationArgs"),a(this,"onUnhandledRejection",n=>{this.onError(n.reason)}),a(this,"_cameraStack",[]),a(this,"_onBeforeRenderListeners",new Map),a(this,"_onAfterRenderListeners",new Map),a(this,"_requireDepthTexture",!1),a(this,"_requireColorTexture",!1),a(this,"_renderTarget"),a(this,"_isRendering",!1),a(this,"_createId",0),a(this,"_renderlooperrors",0),a(this,"_lastTimestamp",0),a(this,"_accumulatedTime",0),a(this,"_dispatchReadyAfterFrame",!1),a(this,"_wasPaused",!1),this.name=s?.name||"",this.alias=s?.alias,this.domElement=s?.domElement||document.body,this.hash=s?.hash,s!=null&&s.renderer&&(this.renderer=s.renderer,this.isManagedExternally=!0),s?.runInBackground!==void 0&&(this.runInBackground=s.runInBackground),s!=null&&s.scene?this.scene=s.scene:this.scene=new $i,s!=null&&s.camera&&(this._mainCamera=s.camera),this.application=new kn(this),this.time=new tw,this.input=new yb(this),this.physics=new Id(this),this.connection=new Ab(this),this.assets=new Xb,this.sceneLighting=new Z_(this),this.addressables=new U_(this),this.lightmaps=new X2(this),this.players=new Q_(this),this.menu=new ak(this),this.lodsManager=new Q2(this),this.animations=new $2(this);const t=()=>this._sizeChanged=!0;window.addEventListener("resize",t),this._disposeCallbacks.push(()=>window.removeEventListener("resize",t));const i=new ResizeObserver(n=>this._sizeChanged=!0);i.observe(this.domElement),this._disposeCallbacks.push(()=>i.disconnect()),this._intersectionObserver=new IntersectionObserver(n=>{this._isVisible=n[0].isIntersecting}),this._disposeCallbacks.push(()=>{var n;return(n=this._intersectionObserver)==null?void 0:n.disconnect()}),ge.register(this)}static get DefaultTargetFrameRate(){return Ae._defaultTargetFramerate.value}static set DefaultTargetFrameRate(s){Ae._defaultTargetFramerate.value=s}static get DefaultWebGLRendererParameters(){return Ae._defaultWebglRendererParameters}get version(){return vs}static get Current(){return ge.Current}static set Current(s){ge.Current=s}appendHTMLElement(s){return this.domElement.shadowRoot?this.domElement.shadowRoot.appendChild(s):this.domElement.appendChild(s)}get resolutionScaleFactor(){return this._resolutionScaleFactor}set resolutionScaleFactor(s){if(s!==this._resolutionScaleFactor&&typeof s=="number"){if(s<=0){console.error("Invalid resolution scale factor",s);return}this._resolutionScaleFactor=s,this.updateSize()}}calculateBoundingClientRect(){if(this.xr){this._domX=0,this._domY=0;return}this._boundingClientRectFrame!==this.time.frame&&(this._boundingClientRectFrame=this.time.frame,this._boundingClientRect=this.domElement.getBoundingClientRect(),this._domX=this._boundingClientRect.x,this._domY=this._boundingClientRect.y)}get domWidth(){return this.isInAR?window.innerWidth:this.domElement.clientWidth}get domHeight(){return this.isInAR?window.innerHeight:this.domElement.clientHeight}get domX(){return this.calculateBoundingClientRect(),this._domX}get domY(){return this.calculateBoundingClientRect(),this._domY}get isInXR(){var s,t;return((t=(s=this.renderer)==null?void 0:s.xr)==null?void 0:t.isPresenting)||!1}get xrSessionMode(){var s;return(s=this.xr)==null?void 0:s.mode}get isInVR(){return this.xrSessionMode==="immersive-vr"}get isInAR(){return this.xrSessionMode==="immersive-ar"}get isInPassThrough(){return this.xr?this.xr.isPassThrough:!1}get xrSession(){var s,t;return(t=(s=this.renderer)==null?void 0:s.xr)==null?void 0:t.getSession()}get xrFrame(){return this._xrFrame}get xrCamera(){var s,t;return this.renderer.xr.isPresenting?(t=(s=this.renderer)==null?void 0:s.xr)==null?void 0:t.getCamera():void 0}get arOverlayElement(){const s=this.domElement;return typeof s.getAROverlayContainer=="function"?s.getAROverlayContainer():this.domElement}get currentFrameEvent(){return this._currentFrameEvent}get mainCamera(){if(this._mainCamera)return this._mainCamera;if(this.mainCameraComponent){const s=this.mainCameraComponent;return s.threeCamera||s.buildCamera(),s.threeCamera}return this._fallbackCamera||(this._fallbackCamera=new be(75,this.domWidth/this.domHeight,.1,1e3)),this._fallbackCamera}set mainCamera(s){this._mainCamera=s}get rendererData(){return this.sceneLighting}get isCreated(){return this._isCreated}createNewRenderer(s){var t,i,n;if((t=this.renderer)==null||t.dispose(),s={...Ae.DefaultWebGLRendererParameters,...s},!s.canvas){const o=(n=(i=this.domElement)==null?void 0:i.shadowRoot)==null?void 0:n.querySelector("canvas");o&&(s.canvas=o,st&&console.log("Using canvas from shadow root",o))}st&&console.log("Using Renderer Parameters:",s,this.domElement),this.renderer=new cr(s),this.renderer.debug.checkShaderErrors=F()||O("checkshadererrors")===!0,this.renderer.toneMappingExposure=1,this.renderer.toneMapping=_a,this.renderer.setClearColor(new ae("lightgrey"),0),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=CS,this.renderer.setSize(this.domWidth,this.domHeight),this.renderer.outputColorSpace=ps,this.renderer.nodes={library:new OS,modelViewMatrix:null,modelNormalViewMatrix:null},this.lodsManager.setRenderer(this.renderer),this.input.bindEvents()}internalOnUpdateVisible(){var s,t;(s=this._intersectionObserver)==null||s.disconnect(),(t=this._intersectionObserver)==null||t.observe(this.domElement)}requestSizeUpdate(){this._sizeChanged=!0}updateSize(s=!1){var t,i,n;if(s||!this.isManagedExternally&&((t=this.renderer.xr)==null?void 0:t.isPresenting)===!1){this._sizeChanged=!1;const o=this.resolutionScaleFactor;let r=this.domWidth*o,l=this.domHeight*o;this.maxRenderResolution&&(this.maxRenderResolution.x=Math.max(1,this.maxRenderResolution.x),r=Math.min(this.maxRenderResolution.x,r),this.maxRenderResolution.y=Math.max(1,this.maxRenderResolution.y),l=Math.min(this.maxRenderResolution.y,l));const c=this.mainCamera;this.updateAspect(c),this.renderer.setSize(r,l,!0),this.renderer.setPixelRatio(window.devicePixelRatio),this.renderer.domElement.style.width="100%",this.renderer.domElement.style.height="100%",this.composer&&((i=this.composer.setSize)==null||i.call(this.composer,r,l),"setPixelRatio"in this.composer&&typeof this.composer.setPixelRatio=="function"&&((n=this.composer.setPixelRatio)==null||n.call(this.composer,window.devicePixelRatio)))}}updateAspect(s,t,i){if(!s)return;t===void 0&&(t=this.domWidth),i===void 0&&(i=this.domHeight);const n=t/i;if(s.isPerspectiveCamera){const o=s,r=o.aspect;o.aspect=n,r!==o.aspect&&s.updateProjectionMatrix()}else if(s.isOrthographicCamera){const o=s,r=o.top-o.bottom,l=r*n/2,c=r/2;(o.left!=-l||o.top!=c)&&(o.left=-l,o.right=l,o.top=c,o.bottom=-c,s.updateProjectionMatrix())}}recreate(){this.clear(),this.create(this._originalCreationArgs)}async onCreate(s){return this.create(s)}async create(s){try{this._isCreating=!0,s!==this._originalCreationArgs&&(this._originalCreationArgs=Gl(s)),window.addEventListener("unhandledrejection",this.onUnhandledRejection);const t=await this.internalOnCreate(s);return this._isCreated=t,t}finally{window.removeEventListener("unhandledrejection",this.onUnhandledRejection),this._isCreating=!1}}onError(s){this.domElement.dispatchEvent(new CustomEvent("error",{detail:s}))}clear(){var s,t,i,n;ge.dispatchCallback(fe.ContextClearing,this),Us(this,fe.ContextClearing),Mi(this.scene,!0,!0),this.scene=new $i,(s=this.addressables)==null||s.dispose(),(t=this.lightmaps)==null||t.clear(),(n=(i=this.physics)==null?void 0:i.engine)==null||n.clearCaches(),this.lodsManager.disable(),this.isManagedExternally||this.renderer&&(this.renderer.renderLists.dispose(),this.renderer.state.reset(),this.renderer.resetState()),ge.dispatchCallback(fe.ContextCleared,this)}dispose(){this.internalOnDestroy()}onDestroy(){this.internalOnDestroy()}internalOnDestroy(){var s,t;Ae.Current=this,ge.dispatchCallback(fe.ContextDestroying,this),Us(this,fe.ContextDestroying),this.clear(),(s=this.renderer)==null||s.setAnimationLoop(null),this.renderer&&(this.renderer.setClearAlpha(0),this.renderer.clear(),this.isManagedExternally||(st&&console.log("Disposing renderer"),this.renderer.dispose())),this.scene=null,this.renderer=null,this.input.dispose(),this.menu.onDestroy(),this.animations.onDestroy();for(const i of this._disposeCallbacks)try{i()}catch(n){console.error("Error in on dispose callback:",n,i)}(t=this.domElement)!=null&&t.parentElement&&this.domElement.parentElement.removeChild(this.domElement),this._isCreated=!1,ge.dispatchCallback(fe.ContextDestroyed,this),Us(this,fe.ContextDestroyed),ge.unregister(this),Ae.Current===this&&(Ae.Current=null)}registerCoroutineUpdate(s,t,i){return typeof t?.next!="function"?(console.error("Registered invalid coroutine function from "+s.name+`
755
755
  Coroutine functions must be generators: "*myCoroutine() {...}"
756
756
  Start a coroutine from a component by calling "this.startCoroutine(myCoroutine())"`),t):(this.coroutines[i]||(this.coroutines[i]=[]),this.coroutines[i].push({comp:s,main:t}),t)}unregisterCoroutineUpdate(s,t){if(!this.coroutines[t])return;const i=this.coroutines[t].findIndex(n=>n.main===s);i>=0&&this.coroutines[t].splice(i,1)}stopAllCoroutinesFrom(s){for(const t in this.coroutines){const i=this.coroutines[t];for(let n=i.length-1;n>=0;n--)i[n].comp===s&&i.splice(n,1)}}setCurrentCamera(s){var t;if(!s)return;if(s.threeCamera||s.buildCamera(),!s.threeCamera){console.warn("Camera component is missing camera",s);return}const i=this._cameraStack.indexOf(s);i>=0&&this._cameraStack.splice(i,1),this._cameraStack.push(s),this.mainCameraComponent=s;const n=s.threeCamera;n.isPerspectiveCamera&&this.updateAspect(n),(t=this.mainCameraComponent)==null||t.applyClearFlagsIfIsActiveCamera()}removeCamera(s){if(!s)return;const t=this._cameraStack.indexOf(s);if(t>=0&&this._cameraStack.splice(t,1),this.mainCameraComponent===s&&(this.mainCameraComponent=void 0,this._cameraStack.length>0)){const i=this._cameraStack[this._cameraStack.length-1];this.setCurrentCamera(i)}}addBeforeRenderListener(s,t){this._onBeforeRenderListeners.has(s.uuid)||(this._onBeforeRenderListeners.set(s.uuid,[]),s.onBeforeRender=this._createRenderCallbackWrapper(s,this._onBeforeRenderListeners)),this._onBeforeRenderListeners.get(s.uuid).push(t)}removeBeforeRenderListener(s,t){if(this._onBeforeRenderListeners.has(s.uuid)){const i=this._onBeforeRenderListeners.get(s.uuid),n=i.indexOf(t);n>=0&&i.splice(n,1)}}addAfterRenderListener(s,t){var i;this._onAfterRenderListeners.has(s.uuid)||(this._onAfterRenderListeners.set(s.uuid,[]),s.onAfterRender=this._createRenderCallbackWrapper(s,this._onAfterRenderListeners)),(i=this._onAfterRenderListeners.get(s.uuid))==null||i.push(t)}removeAfterRenderListener(s,t){if(this._onAfterRenderListeners.has(s.uuid)){const i=this._onAfterRenderListeners.get(s.uuid),n=i.indexOf(t);n>=0&&i.splice(n,1)}}_createRenderCallbackWrapper(s,t){return(i,n,o,r,l,c)=>{const h=t.get(s.uuid);if(h)for(let d=0;d<h.length;d++){const u=h[d];u(i,n,o,r,l,c)}}}get isRendering(){return this._isRendering}setRequireDepth(s){this._requireDepthTexture=s}setRequireColor(s){this._requireColorTexture=s}get depthTexture(){var s;return((s=this._renderTarget)==null?void 0:s.depthTexture)||null}get opaqueColorTexture(){var s;return((s=this._renderTarget)==null?void 0:s.texture)||null}get isVisibleToUser(){if(this.isInXR)return!0;if(!this._isVisible)return!1;const s=getComputedStyle(this.domElement);return s.visibility!=="hidden"&&s.display!=="none"&&s.opacity!=="0"}async internalOnCreate(s){var t,i,n,o,r,l,c,h;const d=++this._createId;st&&console.log("Creating context",this.name,s);const u=globalThis["needle:dependencies:ready"];u instanceof Promise&&(st&&console.log("Waiting for dependencies to be ready"),await u.catch(f=>{if(st||F()){if(ic("Needle Engine dependencies failed to load. Please check the console for more details"),f instanceof ReferenceError){let v="YourComponentName";const b=f.message.indexOf("'");if(b>0){const w=f.message.indexOf("'",b+1);if(w>0){const _=f.message.substring(b+1,w);_.length>3&&(v=_)}}console.error(`Needle Engine dependencies failed to load:
757
757
 
758
758
  # Make sure you don't have circular imports in your scripts!
759
759
  \u2192 Possible solution: Replace @serializable(${v}) in your script with @serializable(Behaviour)
760
760
 
761
- ---`,f);return}console.error("Needle Engine dependencies failed to load",f)}}).then(()=>{st&&console.log("Needle Engine dependencies are ready")})),this.clear(),this.isManagedExternally===!1&&(this.createNewRenderer(),(t=this.renderer)==null||t.setAnimationLoop(null)),await gs(1),Ae.Current=this,await ge.dispatchCallback(fe.ContextCreationStart,this);let p=!0,g;try{Ae.Current=this,s?g=await this.internalLoadInitialContent(d,s):g=[]}catch(f){console.error(f),p=!1}if(!p)return this.onError("Failed to load initial content"),!1;if(d!==this._createId||(i=s?.abortSignal)!=null&&i.aborted)return!1;if(this.internalOnUpdateVisible(),!this.renderer)return st&&console.warn("Context has no renderer (perhaps it was disconnected?",this.domElement.isConnected),!1;!this.isManagedExternally&&!this.domElement.shadowRoot&&this.domElement.prepend(this.renderer.domElement),Ae.Current=this,Ae.Current=this;for(let f=0;f<this.new_scripts.length;f++){const v=this.new_scripts[f];if(v.gameObject!==void 0&&v.gameObject!==null){v.gameObject.userData===void 0&&(v.gameObject.userData={}),v.gameObject.userData.components===void 0&&(v.gameObject.userData.components=[]);const b=v.gameObject.userData.components;b.includes(v)||b.push(v)}}if(this.post_setup_callbacks)for(let f=0;f<this.post_setup_callbacks.length;f++)Ae.Current=this,await this.post_setup_callbacks[f](this);if(!this._mainCamera){Ae.Current=this;let f=null;kr(this.scene,v=>{const b=v;if(b!=null&&b.isCamera){if(fc(b.gameObject),!b.activeAndEnabled)return;if(b.tag==="MainCamera")return f=b,!0;f=b}}),f?this.setCurrentCamera(f):!ge.dispatchCallback(fe.MissingCamera,this,{files:g})&&!this.mainCamera&&!this.isManagedExternally&&console.warn("Missing camera in main scene",this)}this.input.bindEvents(),Ae.Current=this,zd(this),this.physics.engine&&((n=this.physics.engine)==null||n.step(0),(o=this.physics.engine)==null||o.postStep()),!this.isManagedExternally&&this.composer&&this.mainCamera,this._sizeChanged=!0,this._stats&&(this._stats.showPanel(0),this._stats.dom.style.position="absolute",(r=this.domElement.shadowRoot)==null||r.appendChild(this._stats.dom)),st&&xd(this.scene,!0),this.targetFrameRate===void 0?(st&&console.warn("No target framerate set, using default",Ae.DefaultTargetFrameRate),this.targetFrameRate=Ae._defaultTargetFramerate):st&&console.log("Target framerate set to",this.targetFrameRate),this._dispatchReadyAfterFrame=!0;const y=ge.dispatchCallback(fe.ContextCreated,this,{files:g});return y&&("internalSetLoadingMessage"in this.domElement&&typeof this.domElement.internalSetLoadingMessage=="function"&&((l=this.domElement)==null||l.internalSetLoadingMessage("finish loading")),await y),(c=s?.abortSignal)!=null&&c.aborted?!1:(Us(this,fe.ContextCreated),st&&console.log("Context Created...",this.renderer,this.renderer.domElement),this._isCreating=!1,!this.isManagedExternally&&!((h=s?.abortSignal)!=null&&h.aborted)&&this.restartRenderLoop(),!0)}async internalLoadInitialContent(s,t){var i,n,o,r;const l=new Array;if(t.files.length===0)return l;const c=[...t.files],h={name:"",progress:null,index:0,count:c.length},d=ms(),u=0;for(let p=0;p<c.length;p++){if((i=t.abortSignal)!=null&&i.aborted){st&&console.log("Aborting loading because of abort signal");break}if(s!==this._createId){st&&console.log("Aborting loading because create id changed",s,this._createId);break}const g=c[p];(n=t?.onLoadingStart)==null||n.call(this,p,g),st&&console.log("Context Load "+g);const y=await d.loadSync(this,g,g,u,f=>{var v,b;(v=t.abortSignal)!=null&&v.aborted||(h.name=g,h.progress=f,h.index=p,h.count=c.length,(b=t.onLoadingProgress)==null||b.call(this,h))});(o=t?.onLoadingFinished)==null||o.call(this,p,g,y??null),y?l.push({src:g,file:y}):console.warn("Could not load file: "+g)}if(s!==this._createId||(r=t.abortSignal)!=null&&r.aborted){st&&console.log("Aborting loading because create id changed or abort signal was set",s,this._createId);for(const p of l)if(p&&p.file)for(const g of p.file.scenes)Mi(g,!0,!0)}else{let p=!1;for(const g of l)g&&g.file&&(g.file.scene?(p=!0,this.scene.add(g.file.scene)):console.warn("No scene found in loaded file"));if(!p){for(const g of l)if(g&&g.file&&"parser"in g.file){let y=0;if(!Array.isArray(g.file.parser.json.materials))continue;for(let f=0;f<g.file.parser.json.materials.length;f++){const v=await g.file.parser.getDependency("material",f),b=new j;b.position.x=f*1.1,b.position.y=y,this.scene.add(b),mo.createPrimitive("ShaderBall",{parent:b,material:v})}y+=1}}}return l}restartRenderLoop(){return this.renderer?this._isCreating?(console.warn("Can not start render loop while creating context"),!1):(this.renderer.setAnimationLoop((s,t)=>{this.isManagedExternally||this.update(s,t)}),!0):(console.error("Can not start render loop without renderer"),!1)}update(s,t){if(t===void 0&&(t=null),F()||st||dk())try{performance.mark("update.start"),this.internalStep(s,t),this._renderlooperrors=0,performance.mark("update.end"),performance.measure("NE Frame","update.start","update.end")}catch(i){this._renderlooperrors+=1,(F()||st)&&(i instanceof Error||i instanceof TypeError)&&Le("Caught unhandled exception during render-loop - see console for details.",xi.Error),console.error("Frame #"+this.time.frame+`
762
- `,i),this._renderlooperrors>=3&&(console.warn("Stopping render loop due to error"),this.renderer.setAnimationLoop(null)),this.domElement.dispatchEvent(new CustomEvent("error",{detail:i}))}else this.internalStep(s,t)}updatePhysics(s){this.internalUpdatePhysics(s)}internalStep(s,t){this.internalOnBeforeRender(s,t)!==!1&&(this.internalOnRender(),this.internalOnAfterRender())}internalOnBeforeRender(s,t){var i;this.renderer.info.autoReset=!0;const n=t!==null&&this._xrFrame===null;if(this._xrFrame=t,n&&this.domElement.dispatchEvent(new CustomEvent("xr-session-started",{detail:{context:this,session:this.xrSession,frame:t}})),this._currentFrameEvent=-1,this.isManagedExternally===!1&&this.isInXR===!1&&this.targetFrameRate!==void 0){this._lastTimestamp===0&&(this._lastTimestamp=s),this._accumulatedTime+=(s-this._lastTimestamp)/1e3,this._lastTimestamp=s;let o=this.targetFrameRate;if(typeof o=="object"&&(o=o.value),this._accumulatedTime<1/(o+1))return!1;this._accumulatedTime=0}if((i=this._stats)==null||i.begin(),Ae.Current=this,this.onHandlePaused())return!1;for(Ae.Current=this,this.time.update(),h2&&console.log("FPS",this.time.smoothedFps.toFixed(0)),zd(this),Ud(this.scene),s_(this),Us(this,-1);this._cameraStack.length>0&&(!this.mainCameraComponent||this.mainCameraComponent.destroyed);){this._cameraStack.splice(this._cameraStack.length-1,1);const o=this._cameraStack[this._cameraStack.length-1];this.setCurrentCamera(o)}if(this.pre_update_oneshot_callbacks){for(const o in this.pre_update_oneshot_callbacks)this.pre_update_oneshot_callbacks[o]();this.pre_update_oneshot_callbacks.length=0}if(this.pre_update_callbacks)for(const o in this.pre_update_callbacks)this.pre_update_callbacks[o]();this._currentFrameEvent=0;for(let o=0;o<this.scripts_earlyUpdate.length;o++){const r=this.scripts_earlyUpdate[o];r.activeAndEnabled&&r.earlyUpdate!==void 0&&(Ae.Current=this,r.earlyUpdate())}if(this.executeCoroutines(0),Us(this,0),this.onHandlePaused())return!1;this._currentFrameEvent=1;for(let o=0;o<this.scripts_update.length;o++){const r=this.scripts_update[o];r.activeAndEnabled&&r.update!==void 0&&(Ae.Current=this,r.update())}if(this.executeCoroutines(1),Us(this,1),this.onHandlePaused())return!1;this._currentFrameEvent=2;for(let o=0;o<this.scripts_lateUpdate.length;o++){const r=this.scripts_lateUpdate[o];r.activeAndEnabled&&r.lateUpdate!==void 0&&(Ae.Current=this,r.lateUpdate())}if(this.executeCoroutines(2),Us(this,2),this.onHandlePaused()||(this.physicsSteps===void 0&&(this.physicsSteps=1),this.physics.engine&&this.physicsSteps>0&&this.internalUpdatePhysics(this.physicsSteps),this.onHandlePaused()))return!1;if(this.isVisibleToUser||this.runInBackground){this._currentFrameEvent=3;for(let o=0;o<this.scripts_onBeforeRender.length;o++){const r=this.scripts_onBeforeRender[o];r.activeAndEnabled&&r.onBeforeRender!==void 0&&(Ae.Current=this,r.onBeforeRender(t))}if(this.executeCoroutines(3),Us(this,3),this._sizeChanged&&this.updateSize(),this.pre_render_callbacks)for(const o in this.pre_render_callbacks)this.pre_render_callbacks[o](t)}return!0}internalUpdatePhysics(s){if(!this.physics.engine)return!1;const t=s,i=this.time.deltaTime/t;for(let n=0;n<t;n++)this._currentFrameEvent=9,this.executeCoroutines(9),this.physics.engine.step(i),this._currentFrameEvent=10,this.executeCoroutines(10);return this.physics.engine.postStep(),!0}internalOnRender(){this.isManagedExternally||(gk(this),this._currentFrameEvent=-1,IC.update(),this.renderNow(),this._currentFrameEvent=4)}internalOnAfterRender(){if(this.isVisibleToUser||this.runInBackground){for(let s=0;s<this.scripts_onAfterRender.length;s++){const t=this.scripts_onAfterRender[s];t.activeAndEnabled&&t.onAfterRender!==void 0&&(Ae.Current=this,t.onAfterRender())}if(this.executeCoroutines(4),Us(this,4),this.post_render_callbacks)for(const s in this.post_render_callbacks)this.post_render_callbacks[s]()}this._currentFrameEvent=-1,this.connection.sendBufferedMessagesNow(),this._stats&&(this._stats.end(),this.time.frameCount%150===0&&console.log(this.renderer.info.render.calls+" DrawCalls",`
761
+ ---`,f);return}console.error("Needle Engine dependencies failed to load",f)}}).then(()=>{st&&console.log("Needle Engine dependencies are ready")})),this.clear(),this.isManagedExternally===!1&&(this.createNewRenderer(),(t=this.renderer)==null||t.setAnimationLoop(null)),await gs(1),Ae.Current=this,await ge.dispatchCallback(fe.ContextCreationStart,this);let p=!0,g;try{Ae.Current=this,s?g=await this.internalLoadInitialContent(d,s):g=[]}catch(f){console.error(f),p=!1}if(!p)return this.onError("Failed to load initial content"),!1;if(d!==this._createId||(i=s?.abortSignal)!=null&&i.aborted)return!1;if(this.internalOnUpdateVisible(),!this.renderer)return st&&console.warn("Context has no renderer (perhaps it was disconnected?",this.domElement.isConnected),!1;!this.isManagedExternally&&!this.domElement.shadowRoot&&this.domElement.prepend(this.renderer.domElement),Ae.Current=this,Ae.Current=this;for(let f=0;f<this.new_scripts.length;f++){const v=this.new_scripts[f];if(v.gameObject!==void 0&&v.gameObject!==null){v.gameObject.userData===void 0&&(v.gameObject.userData={}),v.gameObject.userData.components===void 0&&(v.gameObject.userData.components=[]);const b=v.gameObject.userData.components;b.includes(v)||b.push(v)}}if(this.post_setup_callbacks)for(let f=0;f<this.post_setup_callbacks.length;f++)Ae.Current=this,await this.post_setup_callbacks[f](this);if(!this._mainCamera){Ae.Current=this;let f=null;kr(this.scene,v=>{const b=v;if(b!=null&&b.isCamera){if(fc(b.gameObject),!b.activeAndEnabled)return;if(b.tag==="MainCamera")return f=b,!0;f=b}}),f?this.setCurrentCamera(f):!ge.dispatchCallback(fe.MissingCamera,this,{files:g})&&!this.mainCamera&&!this.isManagedExternally&&console.warn("Missing camera in main scene",this)}this.input.bindEvents(),Ae.Current=this,zd(this),this.physics.engine&&((n=this.physics.engine)==null||n.step(0),(o=this.physics.engine)==null||o.postStep()),!this.isManagedExternally&&this.composer&&this.mainCamera,this._sizeChanged=!0,this._stats&&(this._stats.showPanel(0),this._stats.dom.style.position="absolute",(r=this.domElement.shadowRoot)==null||r.appendChild(this._stats.dom)),st&&xd(this.scene,!0),this.targetFrameRate===void 0?(st&&console.warn("No target framerate set, using default",Ae.DefaultTargetFrameRate),this.targetFrameRate=Ae._defaultTargetFramerate):st&&console.log("Target framerate set to",this.targetFrameRate),this._dispatchReadyAfterFrame=!0;const y=ge.dispatchCallback(fe.ContextCreated,this,{files:g});return y&&("internalSetLoadingMessage"in this.domElement&&typeof this.domElement.internalSetLoadingMessage=="function"&&((l=this.domElement)==null||l.internalSetLoadingMessage("finish loading")),await y),(c=s?.abortSignal)!=null&&c.aborted?!1:(Us(this,fe.ContextCreated),st&&console.log("Context Created...",this.renderer,this.renderer.domElement),this._isCreating=!1,!this.isManagedExternally&&!((h=s?.abortSignal)!=null&&h.aborted)&&this.restartRenderLoop(),!0)}async internalLoadInitialContent(s,t){var i,n,o,r;const l=new Array;if(t.files.length===0)return l;const c=[...t.files],h={name:"",progress:null,index:0,count:c.length},d=ms(),u=0;for(let p=0;p<c.length;p++){if((i=t.abortSignal)!=null&&i.aborted){st&&console.log("Aborting loading because of abort signal");break}if(s!==this._createId){st&&console.log("Aborting loading because create id changed",s,this._createId);break}const g=c[p];(n=t?.onLoadingStart)==null||n.call(this,p,g),st&&console.log("Context Load "+g);const y=await d.loadSync(this,g,g,u,f=>{var v,b;(v=t.abortSignal)!=null&&v.aborted||(h.name=g,h.progress=f,h.index=p,h.count=c.length,(b=t.onLoadingProgress)==null||b.call(this,h))});(o=t?.onLoadingFinished)==null||o.call(this,p,g,y??null),y?l.push({src:g,file:y}):console.warn("Could not load file: "+g)}if(s!==this._createId||(r=t.abortSignal)!=null&&r.aborted){st&&console.log("Aborting loading because create id changed or abort signal was set",s,this._createId);for(const p of l)if(p&&p.file)for(const g of p.file.scenes)Mi(g,!0,!0)}else{let p=!1;for(const g of l)g&&g.file&&(g.file.scene?(p=!0,this.scene.add(g.file.scene)):console.warn("No scene found in loaded file"));if(!p){for(const g of l)if(g&&g.file&&"parser"in g.file){let y=0;if(!Array.isArray(g.file.parser.json.materials))continue;for(let f=0;f<g.file.parser.json.materials.length;f++){const v=await g.file.parser.getDependency("material",f),b=new j;b.position.x=f*1.1,b.position.y=y,this.scene.add(b),mo.createPrimitive("ShaderBall",{parent:b,material:v})}y+=1}}}return l}restartRenderLoop(){return this.renderer?this._isCreating?(console.warn("Can not start render loop while creating context"),!1):(this.renderer.setAnimationLoop((s,t)=>{this.isManagedExternally||this.update(s,t)}),!0):(console.error("Can not start render loop without renderer"),!1)}update(s,t){if(t===void 0&&(t=null),F()||st||d2())try{performance.mark("update.start"),this.internalStep(s,t),this._renderlooperrors=0,performance.mark("update.end"),performance.measure("NE Frame","update.start","update.end")}catch(i){this._renderlooperrors+=1,(F()||st)&&(i instanceof Error||i instanceof TypeError)&&Le("Caught unhandled exception during render-loop - see console for details.",xi.Error),console.error("Frame #"+this.time.frame+`
762
+ `,i),this._renderlooperrors>=3&&(console.warn("Stopping render loop due to error"),this.renderer.setAnimationLoop(null)),this.domElement.dispatchEvent(new CustomEvent("error",{detail:i}))}else this.internalStep(s,t)}updatePhysics(s){this.internalUpdatePhysics(s)}internalStep(s,t){this.internalOnBeforeRender(s,t)!==!1&&(this.internalOnRender(),this.internalOnAfterRender())}internalOnBeforeRender(s,t){var i;this.renderer.info.autoReset=!0;const n=t!==null&&this._xrFrame===null;if(this._xrFrame=t,n&&this.domElement.dispatchEvent(new CustomEvent("xr-session-started",{detail:{context:this,session:this.xrSession,frame:t}})),this._currentFrameEvent=-1,this.isManagedExternally===!1&&this.isInXR===!1&&this.targetFrameRate!==void 0){this._lastTimestamp===0&&(this._lastTimestamp=s),this._accumulatedTime+=(s-this._lastTimestamp)/1e3,this._lastTimestamp=s;let o=this.targetFrameRate;if(typeof o=="object"&&(o=o.value),this._accumulatedTime<1/(o+1))return!1;this._accumulatedTime=0}if((i=this._stats)==null||i.begin(),Ae.Current=this,this.onHandlePaused())return!1;for(Ae.Current=this,this.time.update(),hk&&console.log("FPS",this.time.smoothedFps.toFixed(0)),zd(this),Ud(this.scene),s_(this),Us(this,-1);this._cameraStack.length>0&&(!this.mainCameraComponent||this.mainCameraComponent.destroyed);){this._cameraStack.splice(this._cameraStack.length-1,1);const o=this._cameraStack[this._cameraStack.length-1];this.setCurrentCamera(o)}if(this.pre_update_oneshot_callbacks){for(const o in this.pre_update_oneshot_callbacks)this.pre_update_oneshot_callbacks[o]();this.pre_update_oneshot_callbacks.length=0}if(this.pre_update_callbacks)for(const o in this.pre_update_callbacks)this.pre_update_callbacks[o]();this._currentFrameEvent=0;for(let o=0;o<this.scripts_earlyUpdate.length;o++){const r=this.scripts_earlyUpdate[o];r.activeAndEnabled&&r.earlyUpdate!==void 0&&(Ae.Current=this,r.earlyUpdate())}if(this.executeCoroutines(0),Us(this,0),this.onHandlePaused())return!1;this._currentFrameEvent=1;for(let o=0;o<this.scripts_update.length;o++){const r=this.scripts_update[o];r.activeAndEnabled&&r.update!==void 0&&(Ae.Current=this,r.update())}if(this.executeCoroutines(1),Us(this,1),this.onHandlePaused())return!1;this._currentFrameEvent=2;for(let o=0;o<this.scripts_lateUpdate.length;o++){const r=this.scripts_lateUpdate[o];r.activeAndEnabled&&r.lateUpdate!==void 0&&(Ae.Current=this,r.lateUpdate())}if(this.executeCoroutines(2),Us(this,2),this.onHandlePaused()||(this.physicsSteps===void 0&&(this.physicsSteps=1),this.physics.engine&&this.physicsSteps>0&&this.internalUpdatePhysics(this.physicsSteps),this.onHandlePaused()))return!1;if(this.isVisibleToUser||this.runInBackground){this._currentFrameEvent=3;for(let o=0;o<this.scripts_onBeforeRender.length;o++){const r=this.scripts_onBeforeRender[o];r.activeAndEnabled&&r.onBeforeRender!==void 0&&(Ae.Current=this,r.onBeforeRender(t))}if(this.executeCoroutines(3),Us(this,3),this._sizeChanged&&this.updateSize(),this.pre_render_callbacks)for(const o in this.pre_render_callbacks)this.pre_render_callbacks[o](t)}return!0}internalUpdatePhysics(s){if(!this.physics.engine)return!1;const t=s,i=this.time.deltaTime/t;for(let n=0;n<t;n++)this._currentFrameEvent=9,this.executeCoroutines(9),this.physics.engine.step(i),this._currentFrameEvent=10,this.executeCoroutines(10);return this.physics.engine.postStep(),!0}internalOnRender(){this.isManagedExternally||(g2(this),this._currentFrameEvent=-1,IC.update(),this.renderNow(),this._currentFrameEvent=4)}internalOnAfterRender(){if(this.isVisibleToUser||this.runInBackground){for(let s=0;s<this.scripts_onAfterRender.length;s++){const t=this.scripts_onAfterRender[s];t.activeAndEnabled&&t.onAfterRender!==void 0&&(Ae.Current=this,t.onAfterRender())}if(this.executeCoroutines(4),Us(this,4),this.post_render_callbacks)for(const s in this.post_render_callbacks)this.post_render_callbacks[s]()}this._currentFrameEvent=-1,this.connection.sendBufferedMessagesNow(),this._stats&&(this._stats.end(),this.time.frameCount%150===0&&console.log(this.renderer.info.render.calls+" DrawCalls",`
763
763
  Render:`,{...this.renderer.info.render},`
764
764
  Memory:`,{...this.renderer.info.memory},`
765
- Target Framerate: `+this.targetFrameRate)),this._dispatchReadyAfterFrame&&(this._dispatchReadyAfterFrame=!1,this.domElement.dispatchEvent(new CustomEvent("ready")),ge.dispatchCallback(fe.ContextFirstFrameRendered,this))}renderNow(s){var t;return!s&&(s=this.mainCamera,!s)?!1:(this.handleRendererContextLost(),this._isRendering=!0,this.renderRequiredTextures(),this.renderer.toneMapping!==_a&&sw(),this.composer&&!this.isInXR?(s&&((t=this.composer.passes[0])==null?void 0:t.mainCamera)!=s&&this.composer.setMainCamera(s),this.composer.render(this.time.deltaTime)):s&&(this.isInXR&&Y.isMacOS()&&this.renderer.clearDepth(),this.renderer.render(this.scene,s)),this._isRendering=!1,!0)}handleRendererContextLost(){this.renderer.getContext().isContextLost()&&(console.warn("Attempting to recover WebGL context..."),this.renderer.forceContextRestore())}onHandlePaused(){const s=this.evaluatePaused();if(this._wasPaused!==s){c2&&console.log("Paused?",s,"context:"+this.alias);for(let t=0;t<this.scripts_pausedChanged.length;t++){const i=this.scripts_pausedChanged[t];i.activeAndEnabled&&i.onPausedChanged!==void 0&&(Ae.Current=this,i.onPausedChanged(s,this._wasPaused))}}return this._wasPaused=s,s}evaluatePaused(){return this.isInXR?!1:this.isPaused?!0:this.runInBackground?!1:!this.isVisibleToUser}renderRequiredTextures(){if(!this.mainCamera||!this._requireDepthTexture&&!this._requireColorTexture)return;if(!this._renderTarget){if(this._renderTarget=new ao(this.domWidth,this.domHeight),this._requireDepthTexture){const i=new PS(this.domWidth,this.domHeight);this._renderTarget.depthTexture=i}this._requireColorTexture&&(this._renderTarget.texture=new Ne,this._renderTarget.texture.generateMipmaps=!1,this._renderTarget.texture.minFilter=hd,this._renderTarget.texture.magFilter=hd,this._renderTarget.texture.format=cd)}const s=this._renderTarget;s.texture&&(s.texture.colorSpace=this.renderer.outputColorSpace);const t=this.renderer.getRenderTarget();this.renderer.setRenderTarget(s),this.renderer.render(this.scene,this.mainCamera),this.renderer.setRenderTarget(t)}executeCoroutines(s){var t;if(this.coroutines[s]){const n=this.coroutines[s];for(let o=0;o<n.length;o++)try{const r=n[o];if(!r.comp||r.comp.destroyed||!r.main||r.comp.enabled===!1){d2&&console.log("Removing coroutine",r.comp,r.comp.enabled),n.splice(o,1),--o;continue}const l=r.chained;if(l&&l.length>0){const d=l[l.length-1].next();if(d.done&&l.pop(),i(d)&&(r.chained||(r.chained=[]),r.chained.push(d.value)),!d.done)continue}const c=r.main.next();if(c.done===!0){n.splice(o,1),--o;continue}const h=c.value;if(i(h)){if(h.next().done)continue;r.chained||(r.chained=[]),r.chained.push(h)}else if(h instanceof Promise){const d=h;r.chained||(r.chained=[]);const u=$_(d);(t=r.chained)==null||t.push(u);continue}}catch(r){console.error(r)}}function i(n){return!!(n&&n.next&&n.return)}}};let te=Ae;a(te,"_defaultTargetFramerate",{value:90,toString(){return this.value}}),a(te,"_defaultWebglRendererParameters",{antialias:!0,alpha:!1,powerPreference:Y.isiOS()||Y.isMacOS()?"default":"high-performance",stencil:!0});const Zi=O("debuglicense"),dw=[];let Er="basic";Zi&&console.log("License Type: "+Er);function bo(){switch(Er){case"pro":case"enterprise":return!0}return!1}function af(){switch(Er){case"indie":return!0}return!1}function Ss(){return bo()||af()}function m2(s){if(bo()||af())return s(!0);dw.push(s)}function g2(s){for(const t of dw)try{t(s)}catch{}}ge.registerCallback(fe.ContextRegistered,s=>{v2(s.context),_2(),y2(s.context)});let Ar,lf=!1,yu="";async function f2(){if(Ar)return Ar;if(Er==="basic")try{const s="https://engine.needle.tools/licensing/check?location="+encodeURIComponent(window.location.href)+"&version="+vs+"&generator="+encodeURIComponent(Cd),t=await fetch(s,{method:"GET"}).catch(i=>{Zi&&console.error("License check failed",i)});t?.status===200?(lf=!1,Zi&&console.log("License check succeeded"),Er="pro",g2(!0)):t?.status===403?(lf=!0,yu=await t.text()):Zi&&console.log("License check failed with status "+t?.status)}catch(s){Zi&&console.error("License check failed",s)}else Zi&&console.log('Runtime license check is skipped because license is already applied as "'+Er+'"')}Ar=f2();async function y2(s){function t(){const o=document.createElement("div");o.className="needle-forbidden",o.style.cssText=`
765
+ Target Framerate: `+this.targetFrameRate)),this._dispatchReadyAfterFrame&&(this._dispatchReadyAfterFrame=!1,this.domElement.dispatchEvent(new CustomEvent("ready")),ge.dispatchCallback(fe.ContextFirstFrameRendered,this))}renderNow(s){var t;return!s&&(s=this.mainCamera,!s)?!1:(this.handleRendererContextLost(),this._isRendering=!0,this.renderRequiredTextures(),this.renderer.toneMapping!==_a&&sw(),this.composer&&!this.isInXR?(s&&((t=this.composer.passes[0])==null?void 0:t.mainCamera)!=s&&this.composer.setMainCamera(s),this.composer.render(this.time.deltaTime)):s&&(this.isInXR&&Y.isMacOS()&&this.renderer.clearDepth(),this.renderer.render(this.scene,s)),this._isRendering=!1,!0)}handleRendererContextLost(){this.renderer.getContext().isContextLost()&&(console.warn("Attempting to recover WebGL context..."),this.renderer.forceContextRestore())}onHandlePaused(){const s=this.evaluatePaused();if(this._wasPaused!==s){ck&&console.log("Paused?",s,"context:"+this.alias);for(let t=0;t<this.scripts_pausedChanged.length;t++){const i=this.scripts_pausedChanged[t];i.activeAndEnabled&&i.onPausedChanged!==void 0&&(Ae.Current=this,i.onPausedChanged(s,this._wasPaused))}}return this._wasPaused=s,s}evaluatePaused(){return this.isInXR?!1:this.isPaused?!0:this.runInBackground?!1:!this.isVisibleToUser}renderRequiredTextures(){if(!this.mainCamera||!this._requireDepthTexture&&!this._requireColorTexture)return;if(!this._renderTarget){if(this._renderTarget=new ao(this.domWidth,this.domHeight),this._requireDepthTexture){const i=new PS(this.domWidth,this.domHeight);this._renderTarget.depthTexture=i}this._requireColorTexture&&(this._renderTarget.texture=new Ne,this._renderTarget.texture.generateMipmaps=!1,this._renderTarget.texture.minFilter=hd,this._renderTarget.texture.magFilter=hd,this._renderTarget.texture.format=cd)}const s=this._renderTarget;s.texture&&(s.texture.colorSpace=this.renderer.outputColorSpace);const t=this.renderer.getRenderTarget();this.renderer.setRenderTarget(s),this.renderer.render(this.scene,this.mainCamera),this.renderer.setRenderTarget(t)}executeCoroutines(s){var t;if(this.coroutines[s]){const n=this.coroutines[s];for(let o=0;o<n.length;o++)try{const r=n[o];if(!r.comp||r.comp.destroyed||!r.main||r.comp.enabled===!1){dk&&console.log("Removing coroutine",r.comp,r.comp.enabled),n.splice(o,1),--o;continue}const l=r.chained;if(l&&l.length>0){const d=l[l.length-1].next();if(d.done&&l.pop(),i(d)&&(r.chained||(r.chained=[]),r.chained.push(d.value)),!d.done)continue}const c=r.main.next();if(c.done===!0){n.splice(o,1),--o;continue}const h=c.value;if(i(h)){if(h.next().done)continue;r.chained||(r.chained=[]),r.chained.push(h)}else if(h instanceof Promise){const d=h;r.chained||(r.chained=[]);const u=$_(d);(t=r.chained)==null||t.push(u);continue}}catch(r){console.error(r)}}function i(n){return!!(n&&n.next&&n.return)}}};let te=Ae;a(te,"_defaultTargetFramerate",{value:90,toString(){return this.value}}),a(te,"_defaultWebglRendererParameters",{antialias:!0,alpha:!1,powerPreference:Y.isiOS()||Y.isMacOS()?"default":"high-performance",stencil:!0});const Zi=O("debuglicense"),dw=[];let Er="basic";Zi&&console.log("License Type: "+Er);function bo(){switch(Er){case"pro":case"enterprise":return!0}return!1}function af(){switch(Er){case"indie":return!0}return!1}function Ss(){return bo()||af()}function mk(s){if(bo()||af())return s(!0);dw.push(s)}function gk(s){for(const t of dw)try{t(s)}catch{}}ge.registerCallback(fe.ContextRegistered,s=>{vk(s.context),_k(),yk(s.context)});let Ar,lf=!1,yu="";async function fk(){if(Ar)return Ar;if(Er==="basic")try{const s="https://engine.needle.tools/licensing/check?location="+encodeURIComponent(window.location.href)+"&version="+vs+"&generator="+encodeURIComponent(Cd),t=await fetch(s,{method:"GET"}).catch(i=>{Zi&&console.error("License check failed",i)});t?.status===200?(lf=!1,Zi&&console.log("License check succeeded"),Er="pro",gk(!0)):t?.status===403?(lf=!0,yu=await t.text()):Zi&&console.log("License check failed with status "+t?.status)}catch(s){Zi&&console.error("License check failed",s)}else Zi&&console.log('Runtime license check is skipped because license is already applied as "'+Er+'"')}Ar=fk();async function yk(s){function t(){const o=document.createElement("div");o.className="needle-forbidden",o.style.cssText=`
766
766
  position: fixed;
767
767
  top: 0;
768
768
  left: 0;
@@ -790,7 +790,7 @@ Target Framerate: `+this.targetFrameRate)),this._dispatchReadyAfterFrame&&(this.
790
790
  align-items: center;
791
791
  background-color: rgba(0,0,0,.3);
792
792
  text-shadow: 0 0 2px black;
793
- `;const c=l.style.cssText,h=yu?.length>1?yu:"This web application has been paused.<br/>You might be in violation of the Needle Engine terms of use.<br/>Please contact the Needle support if you think this is a mistake.";return l.innerHTML=h,setInterval(()=>{l.innerHTML!==h&&(l.innerHTML=h),l.parentNode!==o&&o.appendChild(l),o.style.cssText!==r&&(o.style.cssText=r),l.style.cssText!==c&&(l.style.cssText=c)},500),o}let i=t();const n=i.style.cssText;setInterval(()=>{var o;lf===!0&&(i.style.cssText!==n&&(i=t()),s.domElement.shadowRoot?i.parentNode!==s.domElement.shadowRoot&&((o=s.domElement.shadowRoot)==null||o.appendChild(i)):i.parentNode!=document.body&&document.body.appendChild(i))},500)}async function v2(s){try{if(Ss()!==!0)return cf(s)}catch(t){return Zi&&console.log("License check failed",t),cf(s)}Zi&&cf(s)}async function cf(s){s.domElement.addEventListener("ready",()=>!0),await Ar?.catch(()=>{}),!Ss()&&b2()}let uw=0;async function b2(s){var t;const i=Date.now();if(i-uw<2e3)return;uw=i;const n=`
793
+ `;const c=l.style.cssText,h=yu?.length>1?yu:"This web application has been paused.<br/>You might be in violation of the Needle Engine terms of use.<br/>Please contact the Needle support if you think this is a mistake.";return l.innerHTML=h,setInterval(()=>{l.innerHTML!==h&&(l.innerHTML=h),l.parentNode!==o&&o.appendChild(l),o.style.cssText!==r&&(o.style.cssText=r),l.style.cssText!==c&&(l.style.cssText=c)},500),o}let i=t();const n=i.style.cssText;setInterval(()=>{var o;lf===!0&&(i.style.cssText!==n&&(i=t()),s.domElement.shadowRoot?i.parentNode!==s.domElement.shadowRoot&&((o=s.domElement.shadowRoot)==null||o.appendChild(i)):i.parentNode!=document.body&&document.body.appendChild(i))},500)}async function vk(s){try{if(Ss()!==!0)return cf(s)}catch(t){return Zi&&console.log("License check failed",t),cf(s)}Zi&&cf(s)}async function cf(s){s.domElement.addEventListener("ready",()=>!0),await Ar?.catch(()=>{}),!Ss()&&bk()}let uw=0;async function bk(s){var t;const i=Date.now();if(i-uw<2e3)return;uw=i;const n=`
794
794
  position: relative;
795
795
  display: block;
796
796
  font-size: 18px;
@@ -806,7 +806,7 @@ Target Framerate: `+this.targetFrameRate)),this._dispatchReadyAfterFrame&&(this.
806
806
  padding-left: 25px;
807
807
  border-radius: .5em;
808
808
  border: 2px solid rgba(160,160,160,.3);
809
- `,o=`Needle Engine \u2014 No license active, commercial use is not allowed. Visit https://needle.tools/pricing for more information and licensing options! v${vs}`;(t=te.Current)!=null&&t.xr?console.log(o):console.log("%c "+o,n)}async function _2(){var s;if(!window.crossOriginIsolated)try{const t="https://needle-engine-analytics-v2-r26roub2hq-lz.a.run.app";if(t){Zi&&console.log("Analytics backend url",t);const i=window.location.href.split("?")[0];let n="api/v2/new/request";t.endsWith("/")||(n="/"+n);const o=Er,r=`${t}${n}`;Zi&&console.log("Sending non-commercial usage message to analytics backend",r);const l={license:o,url:i,hostname:window.location.hostname,pathname:window.location.pathname,version:vs,generator:Cd,build_time:ig,public_key:oc},c=(s=navigator.sendBeacon)==null?void 0:s.call(navigator,r,JSON.stringify(l));Zi&&console.log("Send beacon result",c)}}catch(t){Zi&&console.log("Failed to send non-commercial usage message to analytics backend",t)}}const Ir=O("debugloading"),kc=O("debugloadingrendering"),pw=O("debuglicense");class w2{constructor(){a(this,"className"),a(this,"additionalClasses")}}let Mc=0,mw;function hf(s){Ir&&console.log(s.progress.loaded.toFixed(0)+"/"+s.progress.total.toFixed(0),s);const t=s.count,i=s.progress.total;i===0||i===void 0?(mw!==s.name&&(Mc=0),mw=s.name,Mc+=(1-Mc)*.001,Ir&&_e("Loading "+s.name+" did not report total size")):Mc=s.progress.loaded/i;const n=s.index/t+Mc/t;return W.clamp01(n)}const df=class{constructor(s,t){a(this,"loadingProgress",0),a(this,"_element"),a(this,"_progress",0),a(this,"_allowCustomLoadingElement",!0),a(this,"_loadingElement"),a(this,"_loadingTextContainer",null),a(this,"_loadingBar",null),a(this,"_messageContainer",null),a(this,"_loadingElementOptions"),a(this,"_progressLoop"),this._element=s,this._loadingElementOptions=t}async onLoadingBegin(s){const t=this._element.shadowRoot||this._element;if(Ir&&console.warn("Begin Loading"),!this._loadingElement){for(let i=0;i<t.children.length;i++){const n=t.children[i];if(n.classList.contains(df.LoadingContainerClassName)){if(!this._allowCustomLoadingElement){Ir&&console.warn("Remove custom loading container"),t.removeChild(n);continue}this._loadingElement=this.createLoadingElement(n)}}this._loadingElement||(this._loadingElement=this.createLoadingElement())}this._progress=0,this.loadingProgress=0,this._loadingElement.style.display="flex",t.appendChild(this._loadingElement),this.smoothProgressLoop(),this.setMessage(s??"")}onLoadingUpdate(s,t){var i;if(!((i=this._loadingElement)!=null&&i.parentNode))return;let n=0;typeof s=="number"?n=s:("index"in s&&(n=hf(s)),!t&&"name"in s&&this.setMessage("loading "+s.name)),this.loadingProgress=n,t&&this.setMessage(t),this.updateDisplay()}onLoadingFinished(){Ir&&console.warn("Finished Loading"),kc||(this.loadingProgress=1,this.onDoneLoading())}setMessage(s){this._messageContainer&&(this._messageContainer.innerText=s)}smoothProgressLoop(){if(this._progressLoop)return;let s=1/12;kc&&(s=1/500,typeof kc=="number"&&(s*=kc)),this._progressLoop=setInterval(()=>{this.loadingProgress>=.95&&!kc&&(s=.9),this._progress=W.lerp(this._progress,this.loadingProgress,s*this.loadingProgress),this.updateDisplay()},s)}onDoneLoading(){this._loadingElement&&(Ir&&console.log("Hiding loading element"),this._loadingElement.style.display="none",this._loadingElement.remove()),this._progressLoop&&clearInterval(this._progressLoop),this._progressLoop=null}updateDisplay(){const s=this._progress,t=(s*100).toFixed(0)+"%";this._loadingBar&&(this._loadingBar.style.width=s*100+"%"),this._loadingTextContainer&&(this._loadingTextContainer.textContent=t)}createLoadingElement(s){var t,i;Ir&&!s&&console.log("Creating loading element"),this._loadingElement=s||document.createElement("div");let n=this._element.getAttribute("loading-style");(!n||n==="auto")&&(window.matchMedia("(prefers-color-scheme: dark)").matches?n="dark":n="light");const o=bo();if(!s&&(this._loadingElement.style.position="absolute",this._loadingElement.style.width="100%",this._loadingElement.style.height="100%",this._loadingElement.style.left="0",this._loadingElement.style.top="0",n==="light"?this._loadingElement.style.backgroundColor="#ddd":this._loadingElement.style.backgroundColor="#222",this._loadingElement.style.display="flex",this._loadingElement.style.alignItems="center",this._loadingElement.style.justifyContent="center",this._loadingElement.style.zIndex=Number.MAX_SAFE_INTEGER.toString(),this._loadingElement.style.flexDirection="column",this._loadingElement.style.pointerEvents="none",this._loadingElement.style.color="white",this._loadingElement.style.fontFamily='system-ui, Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol"',this._loadingElement.style.fontSize="1rem",n==="light"?this._loadingElement.style.color="rgba(0,0,0,.6)":this._loadingElement.style.color="rgba(255,255,255,.3)",o&&this._element)){const f=this._element.getAttribute("loading-background-color");f&&(this._loadingElement.style.backgroundColor=f);const v=this._element.getAttribute("loading-text-color");v&&(this._loadingElement.style.color=v)}const r=((t=this._loadingElementOptions)==null?void 0:t.className)??df.LoadingContainerClassName;if(this._loadingElement.classList.add(r),(i=this._loadingElementOptions)!=null&&i.additionalClasses)for(const f of this._loadingElementOptions.additionalClasses)this._loadingElement.classList.add(f);const l=document.createElement("div");this._loadingElement.appendChild(l);const c=document.createElement("img"),h=120;if(c.style.width=`${h}px`,c.style.height=`${h}px`,c.style.paddingTop="20px",c.style.paddingBottom="10px",c.style.margin="0px",c.style.userSelect="none",c.style.objectFit="contain",c.style.transition="transform 1.5s ease-out, opacity .3s ease-in-out",c.style.transform="translateY(30px)",c.style.opacity="0.05",setTimeout(()=>{c.style.opacity="1",c.style.transform="translateY(0px)"},1),c.src=wP,o&&this._element){const f=this._element.getAttribute("loading-logo-src");f&&(c.src=f)}l.appendChild(c);const d=document.createElement("div");d.style.cssText=`
809
+ `,o=`Needle Engine \u2014 No license active, commercial use is not allowed. Visit https://needle.tools/pricing for more information and licensing options! v${vs}`;(t=te.Current)!=null&&t.xr?console.log(o):console.log("%c "+o,n)}async function _k(){var s;if(!window.crossOriginIsolated)try{const t="https://needle-engine-analytics-v2-r26roub2hq-lz.a.run.app";if(t){Zi&&console.log("Analytics backend url",t);const i=window.location.href.split("?")[0];let n="api/v2/new/request";t.endsWith("/")||(n="/"+n);const o=Er,r=`${t}${n}`;Zi&&console.log("Sending non-commercial usage message to analytics backend",r);const l={license:o,url:i,hostname:window.location.hostname,pathname:window.location.pathname,version:vs,generator:Cd,build_time:ig,public_key:oc},c=(s=navigator.sendBeacon)==null?void 0:s.call(navigator,r,JSON.stringify(l));Zi&&console.log("Send beacon result",c)}}catch(t){Zi&&console.log("Failed to send non-commercial usage message to analytics backend",t)}}const Ir=O("debugloading"),kc=O("debugloadingrendering"),pw=O("debuglicense");class wk{constructor(){a(this,"className"),a(this,"additionalClasses")}}let Mc=0,mw;function hf(s){Ir&&console.log(s.progress.loaded.toFixed(0)+"/"+s.progress.total.toFixed(0),s);const t=s.count,i=s.progress.total;i===0||i===void 0?(mw!==s.name&&(Mc=0),mw=s.name,Mc+=(1-Mc)*.001,Ir&&_e("Loading "+s.name+" did not report total size")):Mc=s.progress.loaded/i;const n=s.index/t+Mc/t;return W.clamp01(n)}const df=class{constructor(s,t){a(this,"loadingProgress",0),a(this,"_element"),a(this,"_progress",0),a(this,"_allowCustomLoadingElement",!0),a(this,"_loadingElement"),a(this,"_loadingTextContainer",null),a(this,"_loadingBar",null),a(this,"_messageContainer",null),a(this,"_loadingElementOptions"),a(this,"_progressLoop"),this._element=s,this._loadingElementOptions=t}async onLoadingBegin(s){const t=this._element.shadowRoot||this._element;if(Ir&&console.warn("Begin Loading"),!this._loadingElement){for(let i=0;i<t.children.length;i++){const n=t.children[i];if(n.classList.contains(df.LoadingContainerClassName)){if(!this._allowCustomLoadingElement){Ir&&console.warn("Remove custom loading container"),t.removeChild(n);continue}this._loadingElement=this.createLoadingElement(n)}}this._loadingElement||(this._loadingElement=this.createLoadingElement())}this._progress=0,this.loadingProgress=0,this._loadingElement.style.display="flex",t.appendChild(this._loadingElement),this.smoothProgressLoop(),this.setMessage(s??"")}onLoadingUpdate(s,t){var i;if(!((i=this._loadingElement)!=null&&i.parentNode))return;let n=0;typeof s=="number"?n=s:("index"in s&&(n=hf(s)),!t&&"name"in s&&this.setMessage("loading "+s.name)),this.loadingProgress=n,t&&this.setMessage(t),this.updateDisplay()}onLoadingFinished(){Ir&&console.warn("Finished Loading"),kc||(this.loadingProgress=1,this.onDoneLoading())}setMessage(s){this._messageContainer&&(this._messageContainer.innerText=s)}smoothProgressLoop(){if(this._progressLoop)return;let s=1/12;kc&&(s=1/500,typeof kc=="number"&&(s*=kc)),this._progressLoop=setInterval(()=>{this.loadingProgress>=.95&&!kc&&(s=.9),this._progress=W.lerp(this._progress,this.loadingProgress,s*this.loadingProgress),this.updateDisplay()},s)}onDoneLoading(){this._loadingElement&&(Ir&&console.log("Hiding loading element"),this._loadingElement.style.display="none",this._loadingElement.remove()),this._progressLoop&&clearInterval(this._progressLoop),this._progressLoop=null}updateDisplay(){const s=this._progress,t=(s*100).toFixed(0)+"%";this._loadingBar&&(this._loadingBar.style.width=s*100+"%"),this._loadingTextContainer&&(this._loadingTextContainer.textContent=t)}createLoadingElement(s){var t,i;Ir&&!s&&console.log("Creating loading element"),this._loadingElement=s||document.createElement("div");let n=this._element.getAttribute("loading-style");(!n||n==="auto")&&(window.matchMedia("(prefers-color-scheme: dark)").matches?n="dark":n="light");const o=bo();if(!s&&(this._loadingElement.style.position="absolute",this._loadingElement.style.width="100%",this._loadingElement.style.height="100%",this._loadingElement.style.left="0",this._loadingElement.style.top="0",n==="light"?this._loadingElement.style.backgroundColor="#ddd":this._loadingElement.style.backgroundColor="#222",this._loadingElement.style.display="flex",this._loadingElement.style.alignItems="center",this._loadingElement.style.justifyContent="center",this._loadingElement.style.zIndex=Number.MAX_SAFE_INTEGER.toString(),this._loadingElement.style.flexDirection="column",this._loadingElement.style.pointerEvents="none",this._loadingElement.style.color="white",this._loadingElement.style.fontFamily='system-ui, Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol"',this._loadingElement.style.fontSize="1rem",n==="light"?this._loadingElement.style.color="rgba(0,0,0,.6)":this._loadingElement.style.color="rgba(255,255,255,.3)",o&&this._element)){const f=this._element.getAttribute("loading-background-color");f&&(this._loadingElement.style.backgroundColor=f);const v=this._element.getAttribute("loading-text-color");v&&(this._loadingElement.style.color=v)}const r=((t=this._loadingElementOptions)==null?void 0:t.className)??df.LoadingContainerClassName;if(this._loadingElement.classList.add(r),(i=this._loadingElementOptions)!=null&&i.additionalClasses)for(const f of this._loadingElementOptions.additionalClasses)this._loadingElement.classList.add(f);const l=document.createElement("div");this._loadingElement.appendChild(l);const c=document.createElement("img"),h=120;if(c.style.width=`${h}px`,c.style.height=`${h}px`,c.style.paddingTop="20px",c.style.paddingBottom="10px",c.style.margin="0px",c.style.userSelect="none",c.style.objectFit="contain",c.style.transition="transform 1.5s ease-out, opacity .3s ease-in-out",c.style.transform="translateY(30px)",c.style.opacity="0.05",setTimeout(()=>{c.style.opacity="1",c.style.transform="translateY(0px)"},1),c.src=wP,o&&this._element){const f=this._element.getAttribute("loading-logo-src");f&&(c.src=f)}l.appendChild(c);const d=document.createElement("div");d.style.cssText=`
810
810
  display: flex;
811
811
  flex-direction: column;
812
812
  align-items: center;
@@ -815,7 +815,7 @@ Target Framerate: `+this.targetFrameRate)),this._dispatchReadyAfterFrame&&(this.
815
815
  opacity: 0;
816
816
  transition: opacity 1s ease-in-out 4s;
817
817
  `,setTimeout(()=>{d.style.opacity="1"},1),this._loadingElement.appendChild(d);const u=document.createElement("div"),p=100;u.style.display="flex",u.style.width=p+"%",u.style.height="3px",u.style.position="absolute",u.style.left="0",u.style.bottom="0px",u.style.opacity="0",u.style.transition="opacity 1s ease-in-out 2s",setTimeout(()=>{u.style.opacity="1"},1),n==="light"?u.style.backgroundColor="rgba(0,0,0,.2)":u.style.backgroundColor="rgba(255,255,255,.2)",this._loadingElement.appendChild(u),this._loadingBar=document.createElement("div"),u.appendChild(this._loadingBar);const g=function(f){return W.lerp(0,p,f)+"%"};if(this._loadingBar.style.background=`linear-gradient(90deg, #204f49 ${g(0)}, #0BA398 ${g(.3)}, #66A22F ${g(.6)}, #D7DB0A ${g(1)})`,this._loadingBar.style.backgroundAttachment="fixed",this._loadingBar.style.width="0%",this._loadingBar.style.height="100%",o&&this._element){const f=this._element.getAttribute("primary-color"),v=this._element.getAttribute("secondary-color");f&&v?this._loadingBar.style.background=`linear-gradient(90deg, ${f} ${g(0)}, ${v} ${g(1)})`:f?this._loadingBar.style.background=f:v&&(this._loadingBar.style.background=v)}this._loadingTextContainer=document.createElement("div"),this._loadingTextContainer.style.display="flex",this._loadingTextContainer.style.justifyContent="center",this._loadingTextContainer.style.marginTop=".2rem",d.appendChild(this._loadingTextContainer);const y=document.createElement("div");if(this._messageContainer=y,y.style.display="flex",y.style.fontSize=".8rem",y.style.paddingTop=".1rem",y.style.justifyContent="center",d.appendChild(y),o&&this._element){const f=this._element.getAttribute("loading-text-color");f&&(y.style.color=f)}return this.handleRuntimeLicense(this._loadingElement),this._loadingElement}async handleRuntimeLicense(s){let t=Ss();if(t)return;pw&&console.log("Loading UI has commercial license?",t);const i=document.createElement("div");i.style.paddingTop=".6em",i.style.fontSize=".8em",i.style.textTransform="uppercase",i.innerText=`NEEDLE ENGINE NON COMMERCIAL VERSION
818
- CLICK HERE TO GET A LICENSE`,i.style.cursor="pointer",i.style.userSelect="none",i.style.textAlign="center",i.style.pointerEvents="all",i.addEventListener("click",()=>window.open("https://needle.tools/pricing","_self")),i.style.opacity="0",s.appendChild(i),!F()&&Ar&&(pw&&console.log("Waiting for runtime license check"),await Ar,t=Ss()),!t&&(i.style.transition="opacity .5s ease-in-out",i.style.opacity="1")}};let uf=df;a(uf,"LoadingContainerClassName","loading");const Rc=O("debugoverlay"),gw="ar",x2="quit-ar";class S2{constructor(){a(this,"arContainer",null),a(this,"currentSession",null),a(this,"_createdAROnlyElements",[]),a(this,"_reparentedObjects",[]),a(this,"contentElement",null),a(this,"originalDomOverlayParent",null),a(this,"requestEndAR",()=>{this.onRequestedEndAR()})}get ARContainer(){return this.arContainer}onBegin(t,i,n){var o;if(this.currentSession=n,this.arContainer=i,Y.isMozillaXR()){const r=t.domElement.children;for(let l=0;l<r?.length;l++){const c=r[l];if(!c||c===this.arContainer)return;this._reparentedObjects.push({el:c,previousParent:c.parentElement}),(o=this.arContainer)==null||o.appendChild(c)}i?(this.originalDomOverlayParent=i.parentNode,this.originalDomOverlayParent&&(console.log("Reparent DOM Overlay to body",i,i.style.display),i.style.display="",i.style.visibility="",document.body.appendChild(i))):console.warn("WebXRViewer: No DOM Overlay found")}this.ensureQuitARButton(this.arContainer)}onEnd(t){var i;for(const n of this._createdAROnlyElements)n.remove&&n.remove();for(const n of this._reparentedObjects){const o=n.el;(i=n.previousParent)==null||i.appendChild(o)}this._reparentedObjects.length=0,Y.isMozillaXR()&&setTimeout(()=>{var n;const o=t.renderer.domElement;o&&((n=t.domElement.shadowRoot)==null||n.prepend(o));const r=document.querySelectorAll("*");for(var l=0;l<r.length;l++){const c=r[l];c&&c._displayChanged!==void 0&&c._displayWas!==void 0&&(c.style.display=c._displayWas)}},10)}createOverlayContainer(t){if(this.contentElement)return this.contentElement;Rc&&console.log("Setup overlay container");const i=t.shadowRoot.querySelector(".content");this.contentElement=i;const n=t.shadowRoot.querySelector(".overlay-content");return n&&i.appendChild(n),Rc&&!Y.isMobileDevice()&&this.ensureQuitARButton(i),i}onRequestedEndAR(){this.currentSession&&(this.currentSession.end(),this.currentSession=null)}ensureQuitARButton(t){const i=document.createElement("slot");i.setAttribute("name","quit-ar"),this.appendElement(i,t),this._createdAROnlyElements.push(i),i.style.pointerEvents="auto";const n=document.querySelector(`.${x2}`);if(n){n.addEventListener("click",this.requestEndAR),Rc&&n.addEventListener("click",()=>console.log("Clicked quit-ar button"));return}i.addEventListener("click",this.requestEndAR),Rc&&i.addEventListener("click",()=>console.log("Clicked fallback close button"));const o=document.createElement("div");o.style.cssText=`
818
+ CLICK HERE TO GET A LICENSE`,i.style.cursor="pointer",i.style.userSelect="none",i.style.textAlign="center",i.style.pointerEvents="all",i.addEventListener("click",()=>window.open("https://needle.tools/pricing","_self")),i.style.opacity="0",s.appendChild(i),!F()&&Ar&&(pw&&console.log("Waiting for runtime license check"),await Ar,t=Ss()),!t&&(i.style.transition="opacity .5s ease-in-out",i.style.opacity="1")}};let uf=df;a(uf,"LoadingContainerClassName","loading");const Rc=O("debugoverlay"),gw="ar",xk="quit-ar";class Sk{constructor(){a(this,"arContainer",null),a(this,"currentSession",null),a(this,"_createdAROnlyElements",[]),a(this,"_reparentedObjects",[]),a(this,"contentElement",null),a(this,"originalDomOverlayParent",null),a(this,"requestEndAR",()=>{this.onRequestedEndAR()})}get ARContainer(){return this.arContainer}onBegin(t,i,n){var o;if(this.currentSession=n,this.arContainer=i,Y.isMozillaXR()){const r=t.domElement.children;for(let l=0;l<r?.length;l++){const c=r[l];if(!c||c===this.arContainer)return;this._reparentedObjects.push({el:c,previousParent:c.parentElement}),(o=this.arContainer)==null||o.appendChild(c)}i?(this.originalDomOverlayParent=i.parentNode,this.originalDomOverlayParent&&(console.log("Reparent DOM Overlay to body",i,i.style.display),i.style.display="",i.style.visibility="",document.body.appendChild(i))):console.warn("WebXRViewer: No DOM Overlay found")}this.ensureQuitARButton(this.arContainer)}onEnd(t){var i;for(const n of this._createdAROnlyElements)n.remove&&n.remove();for(const n of this._reparentedObjects){const o=n.el;(i=n.previousParent)==null||i.appendChild(o)}this._reparentedObjects.length=0,Y.isMozillaXR()&&setTimeout(()=>{var n;const o=t.renderer.domElement;o&&((n=t.domElement.shadowRoot)==null||n.prepend(o));const r=document.querySelectorAll("*");for(var l=0;l<r.length;l++){const c=r[l];c&&c._displayChanged!==void 0&&c._displayWas!==void 0&&(c.style.display=c._displayWas)}},10)}createOverlayContainer(t){if(this.contentElement)return this.contentElement;Rc&&console.log("Setup overlay container");const i=t.shadowRoot.querySelector(".content");this.contentElement=i;const n=t.shadowRoot.querySelector(".overlay-content");return n&&i.appendChild(n),Rc&&!Y.isMobileDevice()&&this.ensureQuitARButton(i),i}onRequestedEndAR(){this.currentSession&&(this.currentSession.end(),this.currentSession=null)}ensureQuitARButton(t){const i=document.createElement("slot");i.setAttribute("name","quit-ar"),this.appendElement(i,t),this._createdAROnlyElements.push(i),i.style.pointerEvents="auto";const n=document.querySelector(`.${xk}`);if(n){n.addEventListener("click",this.requestEndAR),Rc&&n.addEventListener("click",()=>console.log("Clicked quit-ar button"));return}i.addEventListener("click",this.requestEndAR),Rc&&i.addEventListener("click",()=>console.log("Clicked fallback close button"));const o=document.createElement("div");o.style.cssText=`
819
819
  position: fixed;
820
820
  top: 0;
821
821
  right: 0;
@@ -833,17 +833,17 @@ CLICK HERE TO GET A LICENSE`,i.style.cursor="pointer",i.style.userSelect="none",
833
833
  align-items: center;
834
834
  `,o.appendChild(r);var l=document.createElementNS("http://www.w3.org/2000/svg","path");l.setAttribute("d","M 12,12 L 28,28 M 28,12 12,28"),l.setAttribute("stroke","#000000"),l.setAttribute("stroke-width","2px"),l.style.cssText=`
835
835
  /**filter: drop-shadow(0 0px 1.2px rgba(0,0,0,.7));**/
836
- `,r.appendChild(l),Rc&&console.log("Created fallback close button",r,t)}appendElement(t,i){return i.shadowRoot?i.shadowRoot.appendChild(t):i.appendChild(t)}}const pf=O("debugdecoders");let mf=null;function vu(){if(!mf){const s=_m(null);mf={dracoLoader:s.dracoLoader,ktx2Loader:s.ktx2Loader,meshoptDecoder:s.meshoptDecoder}}return mf}function fw(s){if(s!==void 0&&typeof s=="string"){kC(s);const t=vu();pf&&console.log("Setting draco decoder path to",s),t.dracoLoader.setDecoderPath(s)}}function yw(s){if(s!==void 0&&typeof s=="string"){const t=vu();pf&&console.log("Setting draco decoder type to",s),t.dracoLoader.setDecoderConfig({type:s})}}function vw(s){if(s!==void 0&&typeof s=="string"){MC(s);const t=vu();pf&&console.log("Setting ktx2 transcoder path to",s),t.ktx2Loader.setTranscoderPath(s)}}function bu(s,t){const i=vu();return t.renderer?i.ktx2Loader.detectSupport(t.renderer):console.warn("No renderer provided to detect ktx2 support - loading KTX2 textures will probably fail"),OC(s),s.dracoLoader||s.setDRACOLoader(i.dracoLoader),s.ktx2Loader||s.setKTX2Loader(i.ktx2Loader),s.meshoptDecoder||s.setMeshoptDecoder(i.meshoptDecoder),PC(s,{progressive:!0}),s}const Ha=function(s){return m(s)},m=function(s){if(s===void 0&&(s=null),!Array.isArray(s))s=bw(s);else for(let t=0;t<s.length;t++){const i=s[t];s[t]=bw(i)}return function(t,i){typeof i!="string"&&(i=i.name),Object.getOwnPropertyDescriptor(t,"$serializedTypes")||(t.$serializedTypes={});const n=t.$serializedTypes=t.$serializedTypes||{};n[i]=s}};function bw(s){var t,i;switch((i=(t=s?.prototype)==null?void 0:t.constructor)==null?void 0:i.name){case"Number":case"String":case"Boolean":return null}return s}class P extends j{constructor(){super(...arguments),a(this,"guid")}static isDestroyed(t){return Pr(t)}static setActive(t,i,n=!0){t&&(Sc(t,i),Ud(t),i&&n&&s_(te.Current,t))}static isActiveSelf(t){return Ba(t)}static isActiveInHierarchy(t){return I_(t)}static markAsInstancedRendered(t,i){j_(t,i)}static isUsingInstancing(t){return Kd(t)}static foreachComponent(t,i,n=!0){return kr(t,i,n)}static instantiateSynced(t,i){return t?Bg(t,i):null}static instantiate(t,i=null){return"isAssetReference"in t,za(t,i)}static destroySynced(t,i,n=!0){if(!t)return;const o=t;i=i??te.Current,yc(o,i.connection,n)}static destroy(t,i=!0){return Mi(t,i)}static add(t,i,n){if(!(!t||!i)){if(t===i){console.warn("Can not add object to self",t);return}n||(n=te.Current),i.add(t),Sc(t,!0),Ud(t),n?P.foreachComponent(t,o=>{Tg(o,n),!o.__internalDidAwakeAndStart&&n.new_script_start.includes(o)===!1&&n.new_script_start.push(o)},!0):console.warn("Missing context")}}static remove(t){var i;t&&((i=t.parent)==null||i.remove(t),Sc(t,!1),Ud(t),P.foreachComponent(t,n=>{uk(n)},!0))}static invokeOnChildren(t,i,...n){this.invoke(t,i,!0,n)}static invoke(t,i,n=!1,...o){t&&this.foreachComponent(t,r=>{const l=r[i];l&&typeof l=="function"&&l?.call(r,...o)},n)}static addNewComponent(t,i,n,o=!0){return ki(t,i,n,{callAwake:o})}static addComponent(t,i,n,o){return ki(t,i,n,o)}static moveComponent(t,i){return ki(t,i)}static removeComponent(t){return qg(t.gameObject,t),t}static getOrAddComponent(t,i){return bc(t,i)}static getComponent(t,i){return t===null?null:Or(t,i)}static getComponents(t,i,n=null){return t===null?n??[]:_c(t,i,n)}static findByGuid(t,i){return Gg(t,i)}static findObjectOfType(t,i,n=!0){return Gd(t,i??te.Current,n)}static findObjectsOfType(t,i){const n=[];return A_(t,n,i),n}static getComponentInChildren(t,i){return wc(t,i)}static getComponentsInChildren(t,i,n=null){return Da(t,i,n??void 0)}static getComponentInParent(t,i){return xc(t,i)}static getComponentsInParent(t,i,n=null){return qd(t,i,n)}static getAllComponents(t){var i;const n=(i=t.userData)==null?void 0:i.components;return n?[...n]:[]}static*iterateComponents(t){var i;const n=(i=t?.userData)==null?void 0:i.components;if(n&&Array.isArray(n))for(let o=0;o<n.length;o++)yield n[o]}}const _u=class{constructor(s){a(this,"__context"),a(this,"__name"),a(this,"gameObject"),a(this,"guid","invalid"),a(this,"sourceId"),a(this,"__didAwake",!1),a(this,"__didStart",!1),a(this,"__didEnable",!1),a(this,"__isEnabled"),a(this,"__destroyed",!1),a(this,"_eventListeners",new Map),this.__didAwake=!1,this.__didStart=!1,this.__didEnable=!1,this.__isEnabled=void 0,this.__destroyed=!1,this._internalInit(s)}get isComponent(){return!0}get context(){return this.__context??te.Current}set context(s){this.__context=s}get scene(){return this.context.scene}get layer(){var s,t;return(t=(s=this.gameObject)==null?void 0:s.userData)==null?void 0:t.layer}get name(){var s,t;return(s=this.gameObject)!=null&&s.name?this.gameObject.name:(t=this.gameObject)==null?void 0:t.userData.name}set name(s){this.gameObject?(this.gameObject.userData||(this.gameObject.userData={}),this.gameObject.userData.name=s,this.__name=s):this.__name=s}get tag(){var s;return(s=this.gameObject)==null?void 0:s.userData.tag}set tag(s){this.gameObject&&(this.gameObject.userData||(this.gameObject.userData={}),this.gameObject.userData.tag=s)}get static(){var s;return(s=this.gameObject)==null?void 0:s.userData.static}set static(s){this.gameObject&&(this.gameObject.userData||(this.gameObject.userData={}),this.gameObject.userData.static=s)}get activeAndEnabled(){return!(this.destroyed||this.__isEnabled===!1||!this.__isActiveInHierarchy)}get __isActive(){return this.gameObject.visible}get __isActiveInHierarchy(){if(!this.gameObject)return!1;const s=this.gameObject[xn];return s===void 0?!0:s}set __isActiveInHierarchy(s){this.gameObject&&(this.gameObject[xn]=s)}awake(){}onEnable(){}onDisable(){}onDestroy(){this.__destroyed=!0}startCoroutine(s,t=Ce.Update){return this.context.registerCoroutineUpdate(this,s,t)}stopCoroutine(s,t=Ce.Update){this.context.unregisterCoroutineUpdate(s,t)}get destroyed(){return this.__destroyed}destroy(){this.__destroyed||this.__internalDestroy()}get __internalDidAwakeAndStart(){return this.__didAwake&&this.__didStart}__internalNewInstanceCreated(s){return this.__didAwake=!1,this.__didStart=!1,this.__didEnable=!1,this.__isEnabled=void 0,this.__destroyed=!1,this._internalInit(s),this}_internalInit(s){if(typeof s=="object")for(const t of Object.keys(s)){const i=s[t];typeof i!="function"&&(this[t]=i)}}__internalAwake(){this.__didAwake||(this.__didAwake=!0,this.awake())}__internalStart(){this.__didStart||(this.__didStart=!0,this.start&&this.start())}__internalEnable(s){return this.__destroyed?(F()&&console.warn("[Needle Engine Dev] Trying to enable destroyed component"),!1):this.__didAwake?this.__didEnable?(s!==!0&&(this.__isEnabled=!0),!1):(this.__didEnable=!0,this.__isEnabled=!0,this.onEnable(),!0):!1}__internalDisable(s){if(this.__didAwake){if(!this.__didEnable){s!==!0&&(this.__isEnabled=!1);return}this.__didEnable=!1,this.__isEnabled=!1,this.onDisable()}}__internalDestroy(){var s;this.__destroyed||(this.__destroyed=!0,this.__didAwake&&((s=this.onDestroy)==null||s.call(this),this.dispatchEvent(new CustomEvent("destroyed",{detail:this}))),R_(this))}get enabled(){return typeof this.__isEnabled=="boolean"?this.__isEnabled:!0}set enabled(s){if(this.__destroyed){F()&&console.warn(`[Needle Engine Dev] Trying to ${s?"enable":"disable"} destroyed component`);return}if(typeof s=="number"&&(s>=.5?s=!0:s=!1),!this.__didAwake){this.__isEnabled=s;return}s?this.__internalEnable():this.__internalDisable()}get worldPosition(){return ee(this.gameObject)}set worldPosition(s){lt(this.gameObject,s)}setWorldPosition(s,t,i){fr(this.gameObject,s,t,i)}get worldQuaternion(){return Se(this.gameObject)}set worldQuaternion(s){qi(this.gameObject,s)}setWorldQuaternion(s,t,i,n){$m(this.gameObject,s,t,i,n)}get worldEuler(){return Gm(this.gameObject)}set worldEuler(s){Xm(this.gameObject,s)}get worldRotation(){return this.gameObject.worldRotation}set worldRotation(s){this.setWorldRotation(s.x,s.y,s.z,!0)}setWorldRotation(s,t,i,n=!0){Jl(this.gameObject,s,t,i,n)}get forward(){return _u._forward.set(0,0,-1).applyQuaternion(this.worldQuaternion)}get right(){return _u._right.set(1,0,0).applyQuaternion(this.worldQuaternion)}get up(){return _u._up.set(0,1,0).applyQuaternion(this.worldQuaternion)}addEventListener(s,t){this._eventListeners[s]=this._eventListeners[s]||[],this._eventListeners[s].push(t)}removeEventListener(s,t){if(!this._eventListeners[s])return;const i=this._eventListeners[s].indexOf(t);i>=0&&this._eventListeners[s].splice(i,1)}dispatchEvent(s){if(!s||!this._eventListeners[s.type])return!1;const t=this._eventListeners[s.type];for(let i=0;i<t.length;i++)t[i](s);return!1}};let A=_u;a(A,"_forward",new x),a(A,"_right",new x),a(A,"_up",new x);const C2=Object.freeze(Object.defineProperty({__proto__:null,Behaviour:A,Component:A,GameObject:P},Symbol.toStringTag,{value:"Module"}));var O2=Object.defineProperty,P2=Object.getOwnPropertyDescriptor,_w=(s,t,i,n)=>{for(var o=n>1?void 0:n?P2(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&O2(t,i,o),o};class Tc extends A{constructor(){super(...arguments),a(this,"from"),a(this,"to"),a(this,"width",0),a(this,"centered",!0),a(this,"_centerPos")}awake(){this._centerPos=new x}update(){if(!this.from||!this.to)return;const t=ee(this.from).clone(),i=ee(this.to).clone(),n=t.distanceTo(i);this._centerPos.copy(t),this._centerPos.add(i),this._centerPos.multiplyScalar(.5),lt(this.gameObject,this.centered?this._centerPos:t),this.gameObject.lookAt(ee(this.to).clone()),this.gameObject.scale.set(this.width,this.width,n)}}_w([m(P)],Tc.prototype,"from",2),_w([m(P)],Tc.prototype,"to",2);var k2=Object.defineProperty,M2=Object.getOwnPropertyDescriptor,jr=(s,t,i,n)=>{for(var o=n>1?void 0:n?M2(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&k2(t,i,o),o};const _o=O("debuganimation");let ww=class{constructor(){a(this,"x"),a(this,"y")}};class Ut extends A{constructor(){super(...arguments),a(this,"playAutomatically",!0),a(this,"randomStartTime",!0),a(this,"minMaxSpeed"),a(this,"minMaxOffsetNormalized"),a(this,"loop",!0),a(this,"clampWhenFinished",!1),a(this,"_tempAnimationClipBeforeGameObjectExisted",null),a(this,"_tempAnimationsArray"),a(this,"mixer"),a(this,"_actions"),a(this,"_handles")}get isAnimationComponent(){return!0}addClip(t){this.animations||(this.animations=[]),this.animations.push(t)}get time(){if(this.actions){for(const t of this.actions)if(t.isRunning())return t.time}return 0}set time(t){if(this.actions)for(const i of this.actions)i.time=t}get clip(){var t;return(t=this.animations)!=null&&t.length?this.animations[0]:null}set clip(t){if(!this.__didAwake){_o&&console.warn("Assign clip during serialization",t),this._tempAnimationClipBeforeGameObjectExisted=t;return}t&&(this.gameObject.animations||(this.gameObject.animations=[]),!this.animations.includes(t)&&(this.animations.length>0?this.animations.splice(0,0,t):this.animations.push(t)))}set clips(t){this.animations=t}set animations(t){t==null||!Array.isArray(t)||(this.gameObject?this.gameObject.animations=t:this._tempAnimationsArray=t)}get animations(){return this.gameObject.animations||this._tempAnimationsArray||[]}get actions(){return this._actions}set actions(t){this._actions=t}awake(){this.mixer=void 0,_o&&console.log("Animation Awake",this.name,this),this._tempAnimationsArray&&(this.animations=this._tempAnimationsArray,this._tempAnimationsArray=void 0),this._tempAnimationClipBeforeGameObjectExisted&&(this.clip=this._tempAnimationClipBeforeGameObjectExisted,this._tempAnimationClipBeforeGameObjectExisted=null),this.actions=[],this._handles=[]}onEnable(){var t;if(this.playAutomatically&&((t=this.animations)==null?void 0:t.length)>0){const i=Math.floor(Math.random()*this.animations.length),n=this.animations[i];this.play(i,{exclusive:!0,fadeDuration:0,startTime:this.randomStartTime?Math.random()*n.duration:0,loop:this.loop,clampWhenFinished:this.clampWhenFinished})}}update(){this.mixer&&(this.mixer.update(this.context.time.deltaTime),this._handles.forEach(t=>t.update()))}onDisable(){this.mixer&&this.mixer.stopAllAction()}onDestroy(){this.context.animations.unregisterAnimationMixer(this.mixer)}getAction(t){var i;return((i=this.actions)==null?void 0:i.find(n=>n.getClip().name===t))||null}get isPlaying(){if(this.actions){for(let t=0;t<this.actions.length;t++)if(this.actions[t].isRunning())return!0}return!1}stopAll(t){if(this.actions)for(const i of this.actions)t!=null&&t.fadeDuration?i.fadeOut(t.fadeDuration):i.stop()}stop(t,i){if(t===void 0){this.stopAll();return}else if(typeof t=="number"){if(t>=this.animations.length){_o&&console.log("No animation at index",t);return}t=this.animations[t]}else typeof t=="string"&&(t=this.animations.find(o=>o.name===t));if(!t){console.error("Could not find clip",t);return}const n=this.actions.find(o=>o.getClip()===t);if(!n){console.error("Could not find action",t);return}i!=null&&i.fadeDuration?n.fadeOut(i.fadeDuration):n.stop()}pause(t,i=!1){if(t===void 0){for(const o of this.actions)o.paused=!i;return}else if(typeof t=="number"){if(t>=this.animations.length){_o&&console.log("No animation at index",t);return}t=this.animations[t]}else typeof t=="string"&&(t=this.animations.find(o=>o.name===t));if(!t){console.error("Could not find clip",t);return}const n=this.actions.find(o=>o.getClip()===t);if(!n){console.error("Could not find action",t);return}n.paused=!i}resume(){for(const t of this.actions)t.paused=!1}play(t=0,i){if(_o&&console.log("PLAY",t),this.ensureMixer(),!this.mixer){_o&&console.warn("Missing mixer",this);return}t===void 0&&(t=0);let n=t;if(typeof t=="number"){if(t>=this.animations.length){_o&&console.log("No animation at index",t);return}n=this.animations[t]}else typeof t=="string"&&(n=this.animations.find(r=>r.name===t));if(!n){console.error("Could not find clip",t);return}i||(i={});for(const r of this.actions)if(r.getClip()===n)return this.internalOnPlay(r,i);if(!n.tracks){console.warn("Clip is no AnimationClip",n);return}const o=this.mixer.clipAction(n);return this.actions.push(o),this.internalOnPlay(o,i)}internalOnPlay(t,i){var n=this.actions.find(r=>r===t);if(n===t&&n.isRunning()&&n.time<n.getClip().duration){const r=this.tryFindHandle(t);if(n.paused&&(n.paused=!1),r)return r.waitForFinish()}if(i.loop===void 0&&(i.loop=this.loop),i.clampWhenFinished===void 0&&(i.clampWhenFinished=this.clampWhenFinished),i.minMaxOffsetNormalized===void 0&&this.randomStartTime&&(i.minMaxOffsetNormalized=this.minMaxOffsetNormalized),i.minMaxSpeed===void 0&&(i.minMaxSpeed=this.minMaxSpeed),i?.exclusive??!0)for(const r of this.actions)r!=n&&(i.fadeDuration?r.fadeOut(i.fadeDuration):r.stop());if(i!=null&&i.fadeDuration&&t.fadeIn(i.fadeDuration),t.enabled=!0,i?.startTime!=null)t.time=i.startTime;else if(i!=null&&i.minMaxOffsetNormalized&&i.minMaxOffsetNormalized.x!=0&&i.minMaxOffsetNormalized.y!=0){const r=t.getClip();t.time=W.lerp(i.minMaxOffsetNormalized.x,i.minMaxOffsetNormalized.y,Math.random())*r.duration}else t.time>=t.getClip().duration&&(t.time=0);i!=null&&i.minMaxSpeed?t.timeScale=W.lerp(i.minMaxSpeed.x,i.minMaxSpeed.y,Math.random()):t.timeScale=i?.speed??1,i?.loop!=null?t.loop=i.loop?kS:dm:t.loop=dm,i!=null&&i.clampWhenFinished&&(t.clampWhenFinished=!0),t.paused=!1,t.play(),_o&&console.log("PLAY",t.getClip().name,t);const o=new R2(t,this.mixer,i,r=>{this._handles.splice(this._handles.indexOf(o),1)});return this._handles.push(o),o.waitForFinish()}tryFindHandle(t){for(const i of this._handles)if(i.action===t)return i}ensureMixer(){if(!this.mixer){const t="animationMixer";this.gameObject[t]&&(this.mixer=this.gameObject[t]),(!this.mixer||!this.mixer.clipAction)&&(this.mixer=new um(this.gameObject),this.gameObject[t]=this.mixer)}this.context.animations.registerAnimationMixer(this.mixer)}}jr([m()],Ut.prototype,"playAutomatically",2),jr([m()],Ut.prototype,"randomStartTime",2),jr([m(ww)],Ut.prototype,"minMaxSpeed",2),jr([m(ww)],Ut.prototype,"minMaxOffsetNormalized",2),jr([m()],Ut.prototype,"loop",2),jr([m()],Ut.prototype,"clampWhenFinished",2),jr([m(ur)],Ut.prototype,"clips",1);class R2{constructor(t,i,n,o){a(this,"mixer"),a(this,"action"),a(this,"promise",null),a(this,"_options"),a(this,"_resolveCallback",null),a(this,"_resolvedOrRejectedCallback"),a(this,"onFinished",r=>{r.action===this.action&&this.onResolve()}),this.action=t,this.mixer=i,this._resolvedOrRejectedCallback=o,this._options=n}waitForFinish(){return this.promise?this.promise:(this.promise=new Promise(t=>{this._resolveCallback=t}),this.mixer.addEventListener("finished",this.onFinished),this.promise)}update(){this._options&&this._options.endTime!==void 0&&this.action.time>this._options.endTime&&(this._options.loop===!0?this.action.time=this._options.startTime??0:(this.action.time=this._options.endTime,this.action.timeScale=0,this.onResolve()))}onResolve(){var t,i;this.dispose(),(t=this._resolvedOrRejectedCallback)==null||t.call(this,this),(i=this._resolveCallback)==null||i.call(this,this.action)}dispose(){this.mixer.removeEventListener("finished",this.onFinished)}}var T2=Object.defineProperty,E2=Object.getOwnPropertyDescriptor,wo=(s,t,i,n)=>{for(var o=n>1?void 0:n?E2(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&T2(t,i,o),o};class Qt{constructor(t=0,i=0){a(this,"time",0),a(this,"value",0),a(this,"inTangent",1/0),a(this,"inWeight"),a(this,"outTangent",1/0),a(this,"outWeight"),a(this,"weightedMode"),this.time=t,this.value=i}}wo([m()],Qt.prototype,"time",2),wo([m()],Qt.prototype,"value",2),wo([m()],Qt.prototype,"inTangent",2),wo([m()],Qt.prototype,"inWeight",2),wo([m()],Qt.prototype,"outTangent",2),wo([m()],Qt.prototype,"outWeight",2),wo([m()],Qt.prototype,"weightedMode",2);const Ec=class{constructor(){a(this,"keys",[])}static linearFromTo(s,t,i){const n=new Ec,o=new Qt;o.time=0,o.value=s;const r=new Qt;return r.time=i,r.value=t,n.keys.push(o,r),n}static constant(s){const t=new Ec,i=new Qt;return i.time=0,i.value=s,t.keys.push(i),t}clone(){var s;const t=new Ec;return t.keys=((s=this.keys)==null?void 0:s.map(i=>{const n=new Qt;return n.time=i.time,n.value=i.value,n.inTangent=i.inTangent,n.inWeight=i.inWeight,n.outTangent=i.outTangent,n.outWeight=i.outWeight,n.weightedMode=i.weightedMode,n}))||[],t}get duration(){return!this.keys||this.keys.length==0?0:this.keys[this.keys.length-1].time}evaluate(s){if(!this.keys||this.keys.length==0)return 0;if(this.keys.length===1)return this.keys[0].value;if(this.keys[0].time>=s)return this.keys[0].value;for(let t=0;t<this.keys.length;t++){const i=this.keys[t];if(i.time<=s)if(t+1<this.keys.length){const n=this.keys[t+1];if(n.time<s)continue;return!isFinite(i.outTangent)||!isFinite(n.inTangent)?i.value:Ec.interpolateValue(s,i,n)}else return i.value}return this.keys[this.keys.length-1].value}static interpolateValue(s,t,i){const n=t.time,o=t.value,r=t.outTangent,l=i.time,c=i.value,h=i.inTangent,d=l-n,u=d*d,p=u*d,g=((r+h)*d-2*(c-o))/p,y=(3*(c-o)-(h+2*r)*d)/u,f=r,v=o,b=s-n,w=b*b,_=w*b;return g*_+y*w+f*b+v}};let Lr=Ec;wo([m(Qt)],Lr.prototype,"keys",2);const wu=Symbol("objectIsAnimatedData");function xw(s,t,i){if(!s)return;if(s[wu]===void 0){if(!i)return;s[wu]=new Set}const n=s[wu];i?n.add(t):n.has(t)&&n.delete(t)}function A2(s){if(!s)return!1;const t=s[wu];return t!==void 0&&t.size>0}class I2{constructor(){a(this,"_context")}get context(){return this._context??te.Current}get isStateMachineBehaviour(){return!0}}class Ac{constructor(t,i,n,o){a(this,"name"),a(this,"nameHash"),a(this,"normalizedTime"),a(this,"length"),a(this,"speed"),a(this,"action"),a(this,"hasTransitions");var r;this.name=t.name,this.nameHash=t.hash,this.normalizedTime=i,this.length=n,this.speed=o,this.action=t.motion.action||null,this.hasTransitions=((r=t.transitions)==null?void 0:r.length)>0||!1}}function Sw(s,t){return{name:"Empty",isLooping:!1,guid:t?.generateUUID()??vn.generateUUID(),index:-1,clip:new ur(s,0,[])}}var xo=(s=>(s[s.If=1]="If",s[s.IfNot=2]="IfNot",s[s.Greater=3]="Greater",s[s.Less=4]="Less",s[s.Equals=6]="Equals",s[s.NotEqual=7]="NotEqual",s))(xo||{}),gf=(s=>(s[s.Float=1]="Float",s[s.Int=3]="Int",s[s.Bool=4]="Bool",s[s.Trigger=9]="Trigger",s))(gf||{});const ht=O("debuganimatorcontroller"),xu=O("debugrootmotion");class Vi{constructor(t){a(this,"_speed",1),a(this,"normalizedStartOffset",0),a(this,"animator"),a(this,"model"),a(this,"_mixer"),a(this,"_activeState"),a(this,"_activeStates",[]),a(this,"_heldActions",[]),a(this,"rootMotionHandler"),this.model=t,ht&&console.log(this)}static createFromClips(t,i={looping:!1,autoTransition:!0,transitionDuration:0}){const n=[];for(let r=0;r<t.length;r++){const l=t[r],c=[];if(i.autoTransition!==!1){const d=i.transitionDuration??0,u=d/l.duration;let p=r;(i.autoTransition===void 0||i.autoTransition===!0)&&(p=(r+1)%t.length),c.push({exitTime:1-u,offset:0,duration:d,hasExitTime:!0,destinationState:p,conditions:[]})}const h={name:l.name,hash:r,motion:{name:l.name,clip:l,isLooping:i?.looping??!1},transitions:c,behaviours:[]};n.push(h)}const o={name:"AnimatorController",guid:new Bt(Date.now()).generateUUID(),parameters:[],layers:[{name:"Base Layer",stateMachine:{defaultState:0,states:n}}]};return new Vi(o)}play(t,i=-1,n=Number.NEGATIVE_INFINITY,o=0){if(i<0)i=0;else if(i>=this.model.layers.length){console.warn("invalid layer");return}const r=this.model.layers[i].stateMachine;for(const l of r.states)if(l.name===t||l.hash===t){ht&&console.log("transition to ",l),this.transitionTo(l,o,n);return}console.warn("Could not find "+t+" to play")}reset(){this.setStartTransition()}setBool(t,i){var n,o;const r=typeof t=="string"?"name":"hash";return(o=(n=this.model)==null?void 0:n.parameters)==null?void 0:o.filter(l=>l[r]===t).forEach(l=>l.value=i)}getBool(t){var i,n,o;const r=typeof t=="string"?"name":"hash";return((o=(n=(i=this.model)==null?void 0:i.parameters)==null?void 0:n.find(l=>l[r]===t))==null?void 0:o.value)??!1}setFloat(t,i){var n,o;const r=typeof t=="string"?"name":"hash",l=(o=(n=this.model)==null?void 0:n.parameters)==null?void 0:o.filter(c=>c[r]===t);return l.forEach(c=>c.value=i),l?.length>0}getFloat(t){var i,n,o;const r=typeof t=="string"?"name":"hash";return((o=(n=(i=this.model)==null?void 0:i.parameters)==null?void 0:n.find(l=>l[r]===t))==null?void 0:o.value)??0}setInteger(t,i){var n,o;const r=typeof t=="string"?"name":"hash";return(o=(n=this.model)==null?void 0:n.parameters)==null?void 0:o.filter(l=>l[r]===t).forEach(l=>l.value=i)}getInteger(t){var i,n,o;const r=typeof t=="string"?"name":"hash";return((o=(n=(i=this.model)==null?void 0:i.parameters)==null?void 0:n.find(l=>l[r]===t))==null?void 0:o.value)??0}setTrigger(t){var i,n;ht&&console.log("SET TRIGGER",t);const o=typeof t=="string"?"name":"hash";return(n=(i=this.model)==null?void 0:i.parameters)==null?void 0:n.filter(r=>r[o]===t).forEach(r=>r.value=!0)}resetTrigger(t){var i,n;const o=typeof t=="string"?"name":"hash";return(n=(i=this.model)==null?void 0:i.parameters)==null?void 0:n.filter(r=>r[o]===t).forEach(r=>r.value=!1)}getTrigger(t){var i,n,o;const r=typeof t=="string"?"name":"hash";return((o=(n=(i=this.model)==null?void 0:i.parameters)==null?void 0:n.find(l=>l[r]===t))==null?void 0:o.value)??!1}isInTransition(){return this._activeStates.length>1}setSpeed(t){this._speed=t}FindState(t){return this.findState(t)}findState(t){if(!t)return null;if(Array.isArray(this.model.layers)){for(const i of this.model.layers)for(const n of i.stateMachine.states)if(n.name===t||n.hash==t)return n}return null}getCurrentStateInfo(){if(!this._activeState)return null;const t=this._activeState.motion.action;if(!t)return null;const i=this._activeState.motion.clip.duration,n=i<=0?0:Math.abs(t.time/i);return new Ac(this._activeState,n,i,this._speed)}get currentAction(){return this._activeState&&this._activeState.motion.action||null}get context(){var t;return(t=this.animator)==null?void 0:t.context}get mixer(){return this._mixer}dispose(){var t;if(this._mixer.stopAllAction(),this.animator){this._mixer.uncacheRoot(this.animator.gameObject);for(const i of this._activeStates)i.motion.clip&&this.mixer.uncacheAction(i.motion.clip,this.animator.gameObject)}(t=this.context)==null||t.animations.unregisterAnimationMixer(this._mixer)}bind(t){var i,n;t?this.animator!==t&&(this._mixer&&(this._mixer.stopAllAction(),(i=this.context)==null||i.animations.unregisterAnimationMixer(this._mixer)),this.animator=t,this._mixer=new um(this.animator.gameObject),(n=this.context)==null||n.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;ht&&console.warn("AnimatorController clone()",this.model);const t=Gl(this.model,(i,n,o)=>o==null?!0:!(o.type==="Object3D"||o.isObject3D===!0||Zv(o)||o.tracks!==void 0||o instanceof Vi));return console.assert(t!==this.model),new Vi(t)}update(t){var i,n;if(!this.animator)return;this.evaluateTransitions(),this.updateActiveStates(t);const o=this.animator.context.time.deltaTime;this.animator.applyRootMotion&&((i=this.rootMotionHandler)==null||i.onBeforeUpdate(t)),this._mixer.update(o),this.animator.applyRootMotion&&((n=this.rootMotionHandler)==null||n.onAfterUpdate(t))}get activeState(){return this._activeState}updateActiveStates(t){for(let i=0;i<this._activeStates.length;i++){const n=this._activeStates[i],o=n.motion;if(!o.action)this._activeStates.splice(i,1),i--;else{const r=o.action;r.weight=t,r.getEffectiveWeight()<=0&&!r.isRunning()&&(ht&&console.debug("REMOVE",n.name,r.getEffectiveWeight(),r.isRunning(),r.isScheduled()),this._activeStates.splice(i,1),i--)}}}setStartTransition(){var t;this.model.layers.length>1&&(ht||F())&&console.warn("Multiple layers are not supported yet "+((t=this.animator)==null?void 0:t.name));for(const i of this.model.layers){const n=i.stateMachine;n.defaultState===void 0&&(ht&&console.warn("AnimatorController default state is undefined, will assign state 0 as default",i),n.defaultState=0);const o=n.states[n.defaultState];this.transitionTo(o,0,this.normalizedStartOffset);break}}evaluateTransitions(){var t;let i=!1;if(!this._activeState){if(this.setStartTransition(),!this._activeState)return;i=!0}const n=this._activeState,o=n.motion.action;for(const l of n.transitions){if(!l.hasExitTime&&l.conditions.length<=0)continue;let c=!0;for(const h of l.conditions)if(!this.evaluateCondition(h)){c=!1;break}if(c)if(o){const h=n.motion.clip.duration,d=h<=0?1:Math.abs(o.time/h);let u=l.exitTime;o.timeScale<0&&(u=1-u);let p=!1;if(l.hasExitTime?o.timeScale>0?p=d>=l.exitTime:o.timeScale<0&&(p=1-d>=l.exitTime):p=!0,p){for(const g of l.conditions){const y=this.model.parameters.find(f=>f.name===g.parameter);y?.type===gf.Trigger&&y.value&&(y.value=!1)}if(o.clampWhenFinished=!0,ht){const g=this.getState(l.destinationState,0);console.log(`Transition to ${l.destinationState} / ${g?.name}`,l,`
836
+ `,r.appendChild(l),Rc&&console.log("Created fallback close button",r,t)}appendElement(t,i){return i.shadowRoot?i.shadowRoot.appendChild(t):i.appendChild(t)}}const pf=O("debugdecoders");let mf=null;function vu(){if(!mf){const s=_m(null);mf={dracoLoader:s.dracoLoader,ktx2Loader:s.ktx2Loader,meshoptDecoder:s.meshoptDecoder}}return mf}function fw(s){if(s!==void 0&&typeof s=="string"){kC(s);const t=vu();pf&&console.log("Setting draco decoder path to",s),t.dracoLoader.setDecoderPath(s)}}function yw(s){if(s!==void 0&&typeof s=="string"){const t=vu();pf&&console.log("Setting draco decoder type to",s),t.dracoLoader.setDecoderConfig({type:s})}}function vw(s){if(s!==void 0&&typeof s=="string"){MC(s);const t=vu();pf&&console.log("Setting ktx2 transcoder path to",s),t.ktx2Loader.setTranscoderPath(s)}}function bu(s,t){const i=vu();return t.renderer?i.ktx2Loader.detectSupport(t.renderer):console.warn("No renderer provided to detect ktx2 support - loading KTX2 textures will probably fail"),OC(s),s.dracoLoader||s.setDRACOLoader(i.dracoLoader),s.ktx2Loader||s.setKTX2Loader(i.ktx2Loader),s.meshoptDecoder||s.setMeshoptDecoder(i.meshoptDecoder),PC(s,{progressive:!0}),s}const Ha=function(s){return m(s)},m=function(s){if(s===void 0&&(s=null),!Array.isArray(s))s=bw(s);else for(let t=0;t<s.length;t++){const i=s[t];s[t]=bw(i)}return function(t,i){typeof i!="string"&&(i=i.name),Object.getOwnPropertyDescriptor(t,"$serializedTypes")||(t.$serializedTypes={});const n=t.$serializedTypes=t.$serializedTypes||{};n[i]=s}};function bw(s){var t,i;switch((i=(t=s?.prototype)==null?void 0:t.constructor)==null?void 0:i.name){case"Number":case"String":case"Boolean":return null}return s}class P extends j{constructor(){super(...arguments),a(this,"guid")}static isDestroyed(t){return Pr(t)}static setActive(t,i,n=!0){t&&(Sc(t,i),Ud(t),i&&n&&s_(te.Current,t))}static isActiveSelf(t){return Ba(t)}static isActiveInHierarchy(t){return I_(t)}static markAsInstancedRendered(t,i){j_(t,i)}static isUsingInstancing(t){return Kd(t)}static foreachComponent(t,i,n=!0){return kr(t,i,n)}static instantiateSynced(t,i){return t?Bg(t,i):null}static instantiate(t,i=null){return"isAssetReference"in t,za(t,i)}static destroySynced(t,i,n=!0){if(!t)return;const o=t;i=i??te.Current,yc(o,i.connection,n)}static destroy(t,i=!0){return Mi(t,i)}static add(t,i,n){if(!(!t||!i)){if(t===i){console.warn("Can not add object to self",t);return}n||(n=te.Current),i.add(t),Sc(t,!0),Ud(t),n?P.foreachComponent(t,o=>{Tg(o,n),!o.__internalDidAwakeAndStart&&n.new_script_start.includes(o)===!1&&n.new_script_start.push(o)},!0):console.warn("Missing context")}}static remove(t){var i;t&&((i=t.parent)==null||i.remove(t),Sc(t,!1),Ud(t),P.foreachComponent(t,n=>{u2(n)},!0))}static invokeOnChildren(t,i,...n){this.invoke(t,i,!0,n)}static invoke(t,i,n=!1,...o){t&&this.foreachComponent(t,r=>{const l=r[i];l&&typeof l=="function"&&l?.call(r,...o)},n)}static addNewComponent(t,i,n,o=!0){return ki(t,i,n,{callAwake:o})}static addComponent(t,i,n,o){return ki(t,i,n,o)}static moveComponent(t,i){return ki(t,i)}static removeComponent(t){return qg(t.gameObject,t),t}static getOrAddComponent(t,i){return bc(t,i)}static getComponent(t,i){return t===null?null:Or(t,i)}static getComponents(t,i,n=null){return t===null?n??[]:_c(t,i,n)}static findByGuid(t,i){return Gg(t,i)}static findObjectOfType(t,i,n=!0){return Gd(t,i??te.Current,n)}static findObjectsOfType(t,i){const n=[];return A_(t,n,i),n}static getComponentInChildren(t,i){return wc(t,i)}static getComponentsInChildren(t,i,n=null){return Da(t,i,n??void 0)}static getComponentInParent(t,i){return xc(t,i)}static getComponentsInParent(t,i,n=null){return qd(t,i,n)}static getAllComponents(t){var i;const n=(i=t.userData)==null?void 0:i.components;return n?[...n]:[]}static*iterateComponents(t){var i;const n=(i=t?.userData)==null?void 0:i.components;if(n&&Array.isArray(n))for(let o=0;o<n.length;o++)yield n[o]}}const _u=class{constructor(s){a(this,"__context"),a(this,"__name"),a(this,"gameObject"),a(this,"guid","invalid"),a(this,"sourceId"),a(this,"__didAwake",!1),a(this,"__didStart",!1),a(this,"__didEnable",!1),a(this,"__isEnabled"),a(this,"__destroyed",!1),a(this,"_eventListeners",new Map),this.__didAwake=!1,this.__didStart=!1,this.__didEnable=!1,this.__isEnabled=void 0,this.__destroyed=!1,this._internalInit(s)}get isComponent(){return!0}get context(){return this.__context??te.Current}set context(s){this.__context=s}get scene(){return this.context.scene}get layer(){var s,t;return(t=(s=this.gameObject)==null?void 0:s.userData)==null?void 0:t.layer}get name(){var s,t;return(s=this.gameObject)!=null&&s.name?this.gameObject.name:(t=this.gameObject)==null?void 0:t.userData.name}set name(s){this.gameObject?(this.gameObject.userData||(this.gameObject.userData={}),this.gameObject.userData.name=s,this.__name=s):this.__name=s}get tag(){var s;return(s=this.gameObject)==null?void 0:s.userData.tag}set tag(s){this.gameObject&&(this.gameObject.userData||(this.gameObject.userData={}),this.gameObject.userData.tag=s)}get static(){var s;return(s=this.gameObject)==null?void 0:s.userData.static}set static(s){this.gameObject&&(this.gameObject.userData||(this.gameObject.userData={}),this.gameObject.userData.static=s)}get activeAndEnabled(){return!(this.destroyed||this.__isEnabled===!1||!this.__isActiveInHierarchy)}get __isActive(){return this.gameObject.visible}get __isActiveInHierarchy(){if(!this.gameObject)return!1;const s=this.gameObject[xn];return s===void 0?!0:s}set __isActiveInHierarchy(s){this.gameObject&&(this.gameObject[xn]=s)}awake(){}onEnable(){}onDisable(){}onDestroy(){this.__destroyed=!0}startCoroutine(s,t=Ce.Update){return this.context.registerCoroutineUpdate(this,s,t)}stopCoroutine(s,t=Ce.Update){this.context.unregisterCoroutineUpdate(s,t)}get destroyed(){return this.__destroyed}destroy(){this.__destroyed||this.__internalDestroy()}get __internalDidAwakeAndStart(){return this.__didAwake&&this.__didStart}__internalNewInstanceCreated(s){return this.__didAwake=!1,this.__didStart=!1,this.__didEnable=!1,this.__isEnabled=void 0,this.__destroyed=!1,this._internalInit(s),this}_internalInit(s){if(typeof s=="object")for(const t of Object.keys(s)){const i=s[t];typeof i!="function"&&(this[t]=i)}}__internalAwake(){this.__didAwake||(this.__didAwake=!0,this.awake())}__internalStart(){this.__didStart||(this.__didStart=!0,this.start&&this.start())}__internalEnable(s){return this.__destroyed?(F()&&console.warn("[Needle Engine Dev] Trying to enable destroyed component"),!1):this.__didAwake?this.__didEnable?(s!==!0&&(this.__isEnabled=!0),!1):(this.__didEnable=!0,this.__isEnabled=!0,this.onEnable(),!0):!1}__internalDisable(s){if(this.__didAwake){if(!this.__didEnable){s!==!0&&(this.__isEnabled=!1);return}this.__didEnable=!1,this.__isEnabled=!1,this.onDisable()}}__internalDestroy(){var s;this.__destroyed||(this.__destroyed=!0,this.__didAwake&&((s=this.onDestroy)==null||s.call(this),this.dispatchEvent(new CustomEvent("destroyed",{detail:this}))),R_(this))}get enabled(){return typeof this.__isEnabled=="boolean"?this.__isEnabled:!0}set enabled(s){if(this.__destroyed){F()&&console.warn(`[Needle Engine Dev] Trying to ${s?"enable":"disable"} destroyed component`);return}if(typeof s=="number"&&(s>=.5?s=!0:s=!1),!this.__didAwake){this.__isEnabled=s;return}s?this.__internalEnable():this.__internalDisable()}get worldPosition(){return ee(this.gameObject)}set worldPosition(s){lt(this.gameObject,s)}setWorldPosition(s,t,i){fr(this.gameObject,s,t,i)}get worldQuaternion(){return Se(this.gameObject)}set worldQuaternion(s){qi(this.gameObject,s)}setWorldQuaternion(s,t,i,n){$m(this.gameObject,s,t,i,n)}get worldEuler(){return Gm(this.gameObject)}set worldEuler(s){Xm(this.gameObject,s)}get worldRotation(){return this.gameObject.worldRotation}set worldRotation(s){this.setWorldRotation(s.x,s.y,s.z,!0)}setWorldRotation(s,t,i,n=!0){Jl(this.gameObject,s,t,i,n)}get forward(){return _u._forward.set(0,0,-1).applyQuaternion(this.worldQuaternion)}get right(){return _u._right.set(1,0,0).applyQuaternion(this.worldQuaternion)}get up(){return _u._up.set(0,1,0).applyQuaternion(this.worldQuaternion)}addEventListener(s,t){this._eventListeners[s]=this._eventListeners[s]||[],this._eventListeners[s].push(t)}removeEventListener(s,t){if(!this._eventListeners[s])return;const i=this._eventListeners[s].indexOf(t);i>=0&&this._eventListeners[s].splice(i,1)}dispatchEvent(s){if(!s||!this._eventListeners[s.type])return!1;const t=this._eventListeners[s.type];for(let i=0;i<t.length;i++)t[i](s);return!1}};let A=_u;a(A,"_forward",new x),a(A,"_right",new x),a(A,"_up",new x);const Ck=Object.freeze(Object.defineProperty({__proto__:null,Behaviour:A,Component:A,GameObject:P},Symbol.toStringTag,{value:"Module"}));var Ok=Object.defineProperty,Pk=Object.getOwnPropertyDescriptor,_w=(s,t,i,n)=>{for(var o=n>1?void 0:n?Pk(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&Ok(t,i,o),o};class Tc extends A{constructor(){super(...arguments),a(this,"from"),a(this,"to"),a(this,"width",0),a(this,"centered",!0),a(this,"_centerPos")}awake(){this._centerPos=new x}update(){if(!this.from||!this.to)return;const t=ee(this.from).clone(),i=ee(this.to).clone(),n=t.distanceTo(i);this._centerPos.copy(t),this._centerPos.add(i),this._centerPos.multiplyScalar(.5),lt(this.gameObject,this.centered?this._centerPos:t),this.gameObject.lookAt(ee(this.to).clone()),this.gameObject.scale.set(this.width,this.width,n)}}_w([m(P)],Tc.prototype,"from",2),_w([m(P)],Tc.prototype,"to",2);var kk=Object.defineProperty,Mk=Object.getOwnPropertyDescriptor,jr=(s,t,i,n)=>{for(var o=n>1?void 0:n?Mk(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&kk(t,i,o),o};const _o=O("debuganimation");let ww=class{constructor(){a(this,"x"),a(this,"y")}};class Ut extends A{constructor(){super(...arguments),a(this,"playAutomatically",!0),a(this,"randomStartTime",!0),a(this,"minMaxSpeed"),a(this,"minMaxOffsetNormalized"),a(this,"loop",!0),a(this,"clampWhenFinished",!1),a(this,"_tempAnimationClipBeforeGameObjectExisted",null),a(this,"_tempAnimationsArray"),a(this,"mixer"),a(this,"_actions"),a(this,"_handles")}get isAnimationComponent(){return!0}addClip(t){this.animations||(this.animations=[]),this.animations.push(t)}get time(){if(this.actions){for(const t of this.actions)if(t.isRunning())return t.time}return 0}set time(t){if(this.actions)for(const i of this.actions)i.time=t}get clip(){var t;return(t=this.animations)!=null&&t.length?this.animations[0]:null}set clip(t){if(!this.__didAwake){_o&&console.warn("Assign clip during serialization",t),this._tempAnimationClipBeforeGameObjectExisted=t;return}t&&(this.gameObject.animations||(this.gameObject.animations=[]),!this.animations.includes(t)&&(this.animations.length>0?this.animations.splice(0,0,t):this.animations.push(t)))}set clips(t){this.animations=t}set animations(t){t==null||!Array.isArray(t)||(this.gameObject?this.gameObject.animations=t:this._tempAnimationsArray=t)}get animations(){return this.gameObject.animations||this._tempAnimationsArray||[]}get actions(){return this._actions}set actions(t){this._actions=t}awake(){this.mixer=void 0,_o&&console.log("Animation Awake",this.name,this),this._tempAnimationsArray&&(this.animations=this._tempAnimationsArray,this._tempAnimationsArray=void 0),this._tempAnimationClipBeforeGameObjectExisted&&(this.clip=this._tempAnimationClipBeforeGameObjectExisted,this._tempAnimationClipBeforeGameObjectExisted=null),this.actions=[],this._handles=[]}onEnable(){var t;if(this.playAutomatically&&((t=this.animations)==null?void 0:t.length)>0){const i=Math.floor(Math.random()*this.animations.length),n=this.animations[i];this.play(i,{exclusive:!0,fadeDuration:0,startTime:this.randomStartTime?Math.random()*n.duration:0,loop:this.loop,clampWhenFinished:this.clampWhenFinished})}}update(){this.mixer&&(this.mixer.update(this.context.time.deltaTime),this._handles.forEach(t=>t.update()))}onDisable(){this.mixer&&this.mixer.stopAllAction()}onDestroy(){this.context.animations.unregisterAnimationMixer(this.mixer)}getAction(t){var i;return((i=this.actions)==null?void 0:i.find(n=>n.getClip().name===t))||null}get isPlaying(){if(this.actions){for(let t=0;t<this.actions.length;t++)if(this.actions[t].isRunning())return!0}return!1}stopAll(t){if(this.actions)for(const i of this.actions)t!=null&&t.fadeDuration?i.fadeOut(t.fadeDuration):i.stop()}stop(t,i){if(t===void 0){this.stopAll();return}else if(typeof t=="number"){if(t>=this.animations.length){_o&&console.log("No animation at index",t);return}t=this.animations[t]}else typeof t=="string"&&(t=this.animations.find(o=>o.name===t));if(!t){console.error("Could not find clip",t);return}const n=this.actions.find(o=>o.getClip()===t);if(!n){console.error("Could not find action",t);return}i!=null&&i.fadeDuration?n.fadeOut(i.fadeDuration):n.stop()}pause(t,i=!1){if(t===void 0){for(const o of this.actions)o.paused=!i;return}else if(typeof t=="number"){if(t>=this.animations.length){_o&&console.log("No animation at index",t);return}t=this.animations[t]}else typeof t=="string"&&(t=this.animations.find(o=>o.name===t));if(!t){console.error("Could not find clip",t);return}const n=this.actions.find(o=>o.getClip()===t);if(!n){console.error("Could not find action",t);return}n.paused=!i}resume(){for(const t of this.actions)t.paused=!1}play(t=0,i){if(_o&&console.log("PLAY",t),this.ensureMixer(),!this.mixer){_o&&console.warn("Missing mixer",this);return}t===void 0&&(t=0);let n=t;if(typeof t=="number"){if(t>=this.animations.length){_o&&console.log("No animation at index",t);return}n=this.animations[t]}else typeof t=="string"&&(n=this.animations.find(r=>r.name===t));if(!n){console.error("Could not find clip",t);return}i||(i={});for(const r of this.actions)if(r.getClip()===n)return this.internalOnPlay(r,i);if(!n.tracks){console.warn("Clip is no AnimationClip",n);return}const o=this.mixer.clipAction(n);return this.actions.push(o),this.internalOnPlay(o,i)}internalOnPlay(t,i){var n=this.actions.find(r=>r===t);if(n===t&&n.isRunning()&&n.time<n.getClip().duration){const r=this.tryFindHandle(t);if(n.paused&&(n.paused=!1),r)return r.waitForFinish()}if(i.loop===void 0&&(i.loop=this.loop),i.clampWhenFinished===void 0&&(i.clampWhenFinished=this.clampWhenFinished),i.minMaxOffsetNormalized===void 0&&this.randomStartTime&&(i.minMaxOffsetNormalized=this.minMaxOffsetNormalized),i.minMaxSpeed===void 0&&(i.minMaxSpeed=this.minMaxSpeed),i?.exclusive??!0)for(const r of this.actions)r!=n&&(i.fadeDuration?r.fadeOut(i.fadeDuration):r.stop());if(i!=null&&i.fadeDuration&&t.fadeIn(i.fadeDuration),t.enabled=!0,i?.startTime!=null)t.time=i.startTime;else if(i!=null&&i.minMaxOffsetNormalized&&i.minMaxOffsetNormalized.x!=0&&i.minMaxOffsetNormalized.y!=0){const r=t.getClip();t.time=W.lerp(i.minMaxOffsetNormalized.x,i.minMaxOffsetNormalized.y,Math.random())*r.duration}else t.time>=t.getClip().duration&&(t.time=0);i!=null&&i.minMaxSpeed?t.timeScale=W.lerp(i.minMaxSpeed.x,i.minMaxSpeed.y,Math.random()):t.timeScale=i?.speed??1,i?.loop!=null?t.loop=i.loop?kS:dm:t.loop=dm,i!=null&&i.clampWhenFinished&&(t.clampWhenFinished=!0),t.paused=!1,t.play(),_o&&console.log("PLAY",t.getClip().name,t);const o=new Rk(t,this.mixer,i,r=>{this._handles.splice(this._handles.indexOf(o),1)});return this._handles.push(o),o.waitForFinish()}tryFindHandle(t){for(const i of this._handles)if(i.action===t)return i}ensureMixer(){if(!this.mixer){const t="animationMixer";this.gameObject[t]&&(this.mixer=this.gameObject[t]),(!this.mixer||!this.mixer.clipAction)&&(this.mixer=new um(this.gameObject),this.gameObject[t]=this.mixer)}this.context.animations.registerAnimationMixer(this.mixer)}}jr([m()],Ut.prototype,"playAutomatically",2),jr([m()],Ut.prototype,"randomStartTime",2),jr([m(ww)],Ut.prototype,"minMaxSpeed",2),jr([m(ww)],Ut.prototype,"minMaxOffsetNormalized",2),jr([m()],Ut.prototype,"loop",2),jr([m()],Ut.prototype,"clampWhenFinished",2),jr([m(ur)],Ut.prototype,"clips",1);class Rk{constructor(t,i,n,o){a(this,"mixer"),a(this,"action"),a(this,"promise",null),a(this,"_options"),a(this,"_resolveCallback",null),a(this,"_resolvedOrRejectedCallback"),a(this,"onFinished",r=>{r.action===this.action&&this.onResolve()}),this.action=t,this.mixer=i,this._resolvedOrRejectedCallback=o,this._options=n}waitForFinish(){return this.promise?this.promise:(this.promise=new Promise(t=>{this._resolveCallback=t}),this.mixer.addEventListener("finished",this.onFinished),this.promise)}update(){this._options&&this._options.endTime!==void 0&&this.action.time>this._options.endTime&&(this._options.loop===!0?this.action.time=this._options.startTime??0:(this.action.time=this._options.endTime,this.action.timeScale=0,this.onResolve()))}onResolve(){var t,i;this.dispose(),(t=this._resolvedOrRejectedCallback)==null||t.call(this,this),(i=this._resolveCallback)==null||i.call(this,this.action)}dispose(){this.mixer.removeEventListener("finished",this.onFinished)}}var Tk=Object.defineProperty,Ek=Object.getOwnPropertyDescriptor,wo=(s,t,i,n)=>{for(var o=n>1?void 0:n?Ek(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&Tk(t,i,o),o};class Qt{constructor(t=0,i=0){a(this,"time",0),a(this,"value",0),a(this,"inTangent",1/0),a(this,"inWeight"),a(this,"outTangent",1/0),a(this,"outWeight"),a(this,"weightedMode"),this.time=t,this.value=i}}wo([m()],Qt.prototype,"time",2),wo([m()],Qt.prototype,"value",2),wo([m()],Qt.prototype,"inTangent",2),wo([m()],Qt.prototype,"inWeight",2),wo([m()],Qt.prototype,"outTangent",2),wo([m()],Qt.prototype,"outWeight",2),wo([m()],Qt.prototype,"weightedMode",2);const Ec=class{constructor(){a(this,"keys",[])}static linearFromTo(s,t,i){const n=new Ec,o=new Qt;o.time=0,o.value=s;const r=new Qt;return r.time=i,r.value=t,n.keys.push(o,r),n}static constant(s){const t=new Ec,i=new Qt;return i.time=0,i.value=s,t.keys.push(i),t}clone(){var s;const t=new Ec;return t.keys=((s=this.keys)==null?void 0:s.map(i=>{const n=new Qt;return n.time=i.time,n.value=i.value,n.inTangent=i.inTangent,n.inWeight=i.inWeight,n.outTangent=i.outTangent,n.outWeight=i.outWeight,n.weightedMode=i.weightedMode,n}))||[],t}get duration(){return!this.keys||this.keys.length==0?0:this.keys[this.keys.length-1].time}evaluate(s){if(!this.keys||this.keys.length==0)return 0;if(this.keys.length===1)return this.keys[0].value;if(this.keys[0].time>=s)return this.keys[0].value;for(let t=0;t<this.keys.length;t++){const i=this.keys[t];if(i.time<=s)if(t+1<this.keys.length){const n=this.keys[t+1];if(n.time<s)continue;return!isFinite(i.outTangent)||!isFinite(n.inTangent)?i.value:Ec.interpolateValue(s,i,n)}else return i.value}return this.keys[this.keys.length-1].value}static interpolateValue(s,t,i){const n=t.time,o=t.value,r=t.outTangent,l=i.time,c=i.value,h=i.inTangent,d=l-n,u=d*d,p=u*d,g=((r+h)*d-2*(c-o))/p,y=(3*(c-o)-(h+2*r)*d)/u,f=r,v=o,b=s-n,w=b*b,_=w*b;return g*_+y*w+f*b+v}};let Lr=Ec;wo([m(Qt)],Lr.prototype,"keys",2);const wu=Symbol("objectIsAnimatedData");function xw(s,t,i){if(!s)return;if(s[wu]===void 0){if(!i)return;s[wu]=new Set}const n=s[wu];i?n.add(t):n.has(t)&&n.delete(t)}function Ak(s){if(!s)return!1;const t=s[wu];return t!==void 0&&t.size>0}class Ik{constructor(){a(this,"_context")}get context(){return this._context??te.Current}get isStateMachineBehaviour(){return!0}}class Ac{constructor(t,i,n,o){a(this,"name"),a(this,"nameHash"),a(this,"normalizedTime"),a(this,"length"),a(this,"speed"),a(this,"action"),a(this,"hasTransitions");var r;this.name=t.name,this.nameHash=t.hash,this.normalizedTime=i,this.length=n,this.speed=o,this.action=t.motion.action||null,this.hasTransitions=((r=t.transitions)==null?void 0:r.length)>0||!1}}function Sw(s,t){return{name:"Empty",isLooping:!1,guid:t?.generateUUID()??vn.generateUUID(),index:-1,clip:new ur(s,0,[])}}var xo=(s=>(s[s.If=1]="If",s[s.IfNot=2]="IfNot",s[s.Greater=3]="Greater",s[s.Less=4]="Less",s[s.Equals=6]="Equals",s[s.NotEqual=7]="NotEqual",s))(xo||{}),gf=(s=>(s[s.Float=1]="Float",s[s.Int=3]="Int",s[s.Bool=4]="Bool",s[s.Trigger=9]="Trigger",s))(gf||{});const ht=O("debuganimatorcontroller"),xu=O("debugrootmotion");class Vi{constructor(t){a(this,"_speed",1),a(this,"normalizedStartOffset",0),a(this,"animator"),a(this,"model"),a(this,"_mixer"),a(this,"_activeState"),a(this,"_activeStates",[]),a(this,"_heldActions",[]),a(this,"rootMotionHandler"),this.model=t,ht&&console.log(this)}static createFromClips(t,i={looping:!1,autoTransition:!0,transitionDuration:0}){const n=[];for(let r=0;r<t.length;r++){const l=t[r],c=[];if(i.autoTransition!==!1){const d=i.transitionDuration??0,u=d/l.duration;let p=r;(i.autoTransition===void 0||i.autoTransition===!0)&&(p=(r+1)%t.length),c.push({exitTime:1-u,offset:0,duration:d,hasExitTime:!0,destinationState:p,conditions:[]})}const h={name:l.name,hash:r,motion:{name:l.name,clip:l,isLooping:i?.looping??!1},transitions:c,behaviours:[]};n.push(h)}const o={name:"AnimatorController",guid:new Bt(Date.now()).generateUUID(),parameters:[],layers:[{name:"Base Layer",stateMachine:{defaultState:0,states:n}}]};return new Vi(o)}play(t,i=-1,n=Number.NEGATIVE_INFINITY,o=0){if(i<0)i=0;else if(i>=this.model.layers.length){console.warn("invalid layer");return}const r=this.model.layers[i].stateMachine;for(const l of r.states)if(l.name===t||l.hash===t){ht&&console.log("transition to ",l),this.transitionTo(l,o,n);return}console.warn("Could not find "+t+" to play")}reset(){this.setStartTransition()}setBool(t,i){var n,o;const r=typeof t=="string"?"name":"hash";return(o=(n=this.model)==null?void 0:n.parameters)==null?void 0:o.filter(l=>l[r]===t).forEach(l=>l.value=i)}getBool(t){var i,n,o;const r=typeof t=="string"?"name":"hash";return((o=(n=(i=this.model)==null?void 0:i.parameters)==null?void 0:n.find(l=>l[r]===t))==null?void 0:o.value)??!1}setFloat(t,i){var n,o;const r=typeof t=="string"?"name":"hash",l=(o=(n=this.model)==null?void 0:n.parameters)==null?void 0:o.filter(c=>c[r]===t);return l.forEach(c=>c.value=i),l?.length>0}getFloat(t){var i,n,o;const r=typeof t=="string"?"name":"hash";return((o=(n=(i=this.model)==null?void 0:i.parameters)==null?void 0:n.find(l=>l[r]===t))==null?void 0:o.value)??0}setInteger(t,i){var n,o;const r=typeof t=="string"?"name":"hash";return(o=(n=this.model)==null?void 0:n.parameters)==null?void 0:o.filter(l=>l[r]===t).forEach(l=>l.value=i)}getInteger(t){var i,n,o;const r=typeof t=="string"?"name":"hash";return((o=(n=(i=this.model)==null?void 0:i.parameters)==null?void 0:n.find(l=>l[r]===t))==null?void 0:o.value)??0}setTrigger(t){var i,n;ht&&console.log("SET TRIGGER",t);const o=typeof t=="string"?"name":"hash";return(n=(i=this.model)==null?void 0:i.parameters)==null?void 0:n.filter(r=>r[o]===t).forEach(r=>r.value=!0)}resetTrigger(t){var i,n;const o=typeof t=="string"?"name":"hash";return(n=(i=this.model)==null?void 0:i.parameters)==null?void 0:n.filter(r=>r[o]===t).forEach(r=>r.value=!1)}getTrigger(t){var i,n,o;const r=typeof t=="string"?"name":"hash";return((o=(n=(i=this.model)==null?void 0:i.parameters)==null?void 0:n.find(l=>l[r]===t))==null?void 0:o.value)??!1}isInTransition(){return this._activeStates.length>1}setSpeed(t){this._speed=t}FindState(t){return this.findState(t)}findState(t){if(!t)return null;if(Array.isArray(this.model.layers)){for(const i of this.model.layers)for(const n of i.stateMachine.states)if(n.name===t||n.hash==t)return n}return null}getCurrentStateInfo(){if(!this._activeState)return null;const t=this._activeState.motion.action;if(!t)return null;const i=this._activeState.motion.clip.duration,n=i<=0?0:Math.abs(t.time/i);return new Ac(this._activeState,n,i,this._speed)}get currentAction(){return this._activeState&&this._activeState.motion.action||null}get context(){var t;return(t=this.animator)==null?void 0:t.context}get mixer(){return this._mixer}dispose(){var t;if(this._mixer.stopAllAction(),this.animator){this._mixer.uncacheRoot(this.animator.gameObject);for(const i of this._activeStates)i.motion.clip&&this.mixer.uncacheAction(i.motion.clip,this.animator.gameObject)}(t=this.context)==null||t.animations.unregisterAnimationMixer(this._mixer)}bind(t){var i,n;t?this.animator!==t&&(this._mixer&&(this._mixer.stopAllAction(),(i=this.context)==null||i.animations.unregisterAnimationMixer(this._mixer)),this.animator=t,this._mixer=new um(this.animator.gameObject),(n=this.context)==null||n.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;ht&&console.warn("AnimatorController clone()",this.model);const t=Gl(this.model,(i,n,o)=>o==null?!0:!(o.type==="Object3D"||o.isObject3D===!0||Zv(o)||o.tracks!==void 0||o instanceof Vi));return console.assert(t!==this.model),new Vi(t)}update(t){var i,n;if(!this.animator)return;this.evaluateTransitions(),this.updateActiveStates(t);const o=this.animator.context.time.deltaTime;this.animator.applyRootMotion&&((i=this.rootMotionHandler)==null||i.onBeforeUpdate(t)),this._mixer.update(o),this.animator.applyRootMotion&&((n=this.rootMotionHandler)==null||n.onAfterUpdate(t))}get activeState(){return this._activeState}updateActiveStates(t){for(let i=0;i<this._activeStates.length;i++){const n=this._activeStates[i],o=n.motion;if(!o.action)this._activeStates.splice(i,1),i--;else{const r=o.action;r.weight=t,r.getEffectiveWeight()<=0&&!r.isRunning()&&(ht&&console.debug("REMOVE",n.name,r.getEffectiveWeight(),r.isRunning(),r.isScheduled()),this._activeStates.splice(i,1),i--)}}}setStartTransition(){var t;this.model.layers.length>1&&(ht||F())&&console.warn("Multiple layers are not supported yet "+((t=this.animator)==null?void 0:t.name));for(const i of this.model.layers){const n=i.stateMachine;n.defaultState===void 0&&(ht&&console.warn("AnimatorController default state is undefined, will assign state 0 as default",i),n.defaultState=0);const o=n.states[n.defaultState];this.transitionTo(o,0,this.normalizedStartOffset);break}}evaluateTransitions(){var t;let i=!1;if(!this._activeState){if(this.setStartTransition(),!this._activeState)return;i=!0}const n=this._activeState,o=n.motion.action;for(const l of n.transitions){if(!l.hasExitTime&&l.conditions.length<=0)continue;let c=!0;for(const h of l.conditions)if(!this.evaluateCondition(h)){c=!1;break}if(c)if(o){const h=n.motion.clip.duration,d=h<=0?1:Math.abs(o.time/h);let u=l.exitTime;o.timeScale<0&&(u=1-u);let p=!1;if(l.hasExitTime?o.timeScale>0?p=d>=l.exitTime:o.timeScale<0&&(p=1-d>=l.exitTime):p=!0,p){for(const g of l.conditions){const y=this.model.parameters.find(f=>f.name===g.parameter);y?.type===gf.Trigger&&y.value&&(y.value=!1)}if(o.clampWhenFinished=!0,ht){const g=this.getState(l.destinationState,0);console.log(`Transition to ${l.destinationState} / ${g?.name}`,l,`
837
837
  Timescale: `+o.timeScale,`
838
838
  Normalized time: `+d.toFixed(3),`
839
- Exit Time: `+u,l.hasExitTime)}this.transitionTo(l.destinationState,l.duration,l.offset);return}}else{this.transitionTo(l.destinationState,l.duration,l.offset);return}}o&&this.setTimescale(o,n);let r=!1;if(n.motion.isLooping&&o&&(o.time>=o.getClip().duration?(r=!0,o.reset(),o.time=0,o.play()):o.time<=0&&o.timeScale<0&&(r=!0,o.reset(),o.time=o.getClip().duration,o.play())),!r&&n&&!i&&o&&this.animator&&n.behaviours){const l=o?.getClip().duration,c=o.time/l,h=new Ac(this._activeState,c,l,this._speed);for(const d of n.behaviours)d.instance&&((t=d.instance.onStateUpdate)==null||t.call(d.instance,this.animator,h,0))}}setTimescale(t,i){let n=i.speed??1;i.speedParameter&&(n*=this.getFloat(i.speedParameter)),n!==void 0&&(t.timeScale=n*this._speed)}getState(t,i){return typeof t=="number"&&(t==-1&&(t=this.model.layers[i].stateMachine.defaultState,t===void 0&&(ht&&console.warn("AnimatorController default state is undefined: ",this.model,"Layer: "+i),t=0)),t=this.model.layers[i].stateMachine.states[t]),t}releaseHeldActions(t){for(const i of this._heldActions)i.fadeOut(t);this._heldActions.length=0}transitionTo(t,i,n){var o,r,l,c,h,d,u,p;if(!this.animator)return;const g=0;if(t=this.getState(t,g),!(t!=null&&t.motion)||!t.motion.clip||!(t.motion.clip instanceof ur))return;const y=this._activeState===t;if(y){const _=t.motion;if(!_.action_loopback&&_.clip){const C=this.rootMotionHandler?this.animator.gameObject.matrix.clone():null;this._mixer.uncacheAction(_.clip,this.animator.gameObject),C&&C.decompose(this.animator.gameObject.position,this.animator.gameObject.quaternion,this.animator.gameObject.scale),_.action_loopback=this.createAction(_.clip)}}if((o=this._activeState)!=null&&o.behaviours&&this._activeState.motion.action){const _=(r=this._activeState)==null?void 0:r.motion.clip.duration,C=this._activeState.motion.action.time/_,R=new Ac(this._activeState,C,_,this._speed);for(const M of this._activeState.behaviours)(c=(l=M.instance)==null?void 0:l.onStateExit)==null||c.call(M.instance,this.animator,R,g)}const f=(h=this._activeState)==null?void 0:h.motion.action;y&&(t.motion.action=t.motion.action_loopback,t.motion.action_loopback=f);const v=this._activeState;this._activeState=t;const b=(d=t.motion)==null?void 0:d.action,w=t.motion.clip;if(w?.duration<=0&&w.tracks.length<=0?f&&this._heldActions.push(f):f&&(f.fadeOut(i),this.releaseHeldActions(i)),b){if(n=Math.max(0,Math.min(1,n)),t.cycleOffsetParameter){let C=this.getFloat(t.cycleOffsetParameter);typeof C=="number"?(C<0&&(C+=1),n+=C,n%=1):ht&&console.warn("AnimatorController cycle offset parameter is not a number",t.cycleOffsetParameter)}else typeof t.cycleOffset=="number"&&(n+=t.cycleOffset,n%=1);b.isRunning()&&b.stop(),b.reset(),b.enabled=!0,this.setTimescale(b,t);const _=t.motion.clip.duration;if(b.time=y?0:n*_,b.timeScale<0&&(b.time=_-b.time),b.clampWhenFinished=!0,b.setLoop(dm,0),i>0?b.fadeIn(i):b.weight=1,b.play(),this.rootMotionHandler&&this.rootMotionHandler.onStart(b),this._activeStates.includes(t)||this._activeStates.push(t),this._activeState.behaviours){const C=new Ac(t,n,_,this._speed);for(const R of this._activeState.behaviours)(p=(u=R.instance)==null?void 0:u.onStateEnter)==null||p.call(R.instance,this.animator,C,g)}}else ht&&(t.__warned_no_motion||(t.__warned_no_motion=!0,console.warn("No action",t.motion,this)));ht&&console.log("TRANSITION FROM "+v?.name+" TO "+t.name,i,f,b,b?.getEffectiveTimeScale(),b?.getEffectiveWeight(),b?.isRunning(),b?.isScheduled(),b?.paused)}createAction(t){var i,n;if(this._mixer.existingAction(t)&&this._mixer.uncacheAction(t,(i=this.animator)==null?void 0:i.gameObject),(n=this.animator)!=null&&n.applyRootMotion){this.rootMotionHandler||(this.rootMotionHandler=new j2(this));const o=this.animator.gameObject;return this.rootMotionHandler.createClip(this._mixer,o,t)}else return this._mixer.clipAction(t)}evaluateCondition(t){const i=this.model.parameters.find(n=>n.name===t.parameter);if(!i)return!1;switch(t.mode){case xo.If:return i.value===!0;case xo.IfNot:return i.value===!1;case xo.Greater:return i.value>t.threshold;case xo.Less:return i.value<t.threshold;case xo.Equals:return i.value===t.threshold;case xo.NotEqual:return i.value!==t.threshold}return!1}createActions(t){var i,n,o,r;ht&&console.log("AnimatorController createActions",this.model);for(const l of this.model.layers){const c=l.stateMachine;for(let h=0;h<c.states.length;h++){const d=c.states[h];d.transitions||(d.transitions=[]);for(const u of d.transitions)u.conditions||(u.conditions=[]);if(d.motion||(ht&&console.warn("No motion",d),d.motion=Sw(d.name)),this.animator&&d.motion.clips){const u=(i=d.motion.clips)==null?void 0:i.find(p=>{var g,y;return p.node.name===((y=(g=this.animator)==null?void 0:g.gameObject)==null?void 0:y.name)});u?d.motion.clip=u.clip:(ht||F())&&console.warn('Could not find clip for animator "'+((o=(n=this.animator)==null?void 0:n.gameObject)==null?void 0:o.name)+'"',d.motion.clips.map(p=>p.node.name))}if(!d.motion.clip){ht&&console.warn("No clip assigned to state",d);const u=new ur(void 0,void 0,[]);d.motion.clip=u}if((r=d.motion)!=null&&r.clip){const u=d.motion.clip;if(u instanceof ur){const p=this.createAction(u);d.motion.action=p}else(ht||F())&&console.warn("No valid animationclip assigned",d)}if(d.behaviours&&Array.isArray(d.behaviours))for(const u of d.behaviours){if(!(u!=null&&u.typeName))continue;const p=S.get(u.typeName);if(p){const g=new p;g.isStateMachineBehaviour&&(g._context=this.context??void 0,La(g,u.properties),u.instance=g),ht&&console.log("Created animator controller behaviour",d.name,u.typeName,u.properties,g)}else(ht||F())&&console.warn("Could not find AnimatorBehaviour type: "+u.typeName)}}}}*enumerateActions(){if(this.model.layers)for(const t of this.model.layers){const i=t.stateMachine;for(let n=0;n<i.states.length;n++){const o=i.states[n];o!=null&&o.motion&&(o.motion.action&&(yield o.motion.action),o.motion.action_loopback&&(yield o.motion.action_loopback))}}}}class Cw{constructor(t,i){a(this,"track"),a(this,"createdInterpolant"),a(this,"originalEvaluate"),a(this,"customEvaluate"),this.track=t;const n=t,o=n.createInterpolant.bind(t);n.createInterpolant=()=>(n.createInterpolant=o,this.createdInterpolant=o(),this.originalEvaluate=this.createdInterpolant.evaluate.bind(this.createdInterpolant),this.customEvaluate=r=>{if(!this.originalEvaluate)return;const l=this.originalEvaluate(r);return i(r,l)},this.createdInterpolant.evaluate=this.customEvaluate,this.createdInterpolant)}dispose(){this.createdInterpolant&&this.originalEvaluate&&(this.createdInterpolant.evaluate=this.originalEvaluate),this.track=void 0,this.createdInterpolant=null,this.originalEvaluate=void 0,this.customEvaluate=void 0}}const yt=class{constructor(s,t,i,n,o){if(a(this,"_action"),a(this,"root"),a(this,"clip"),a(this,"positionWrapper",null),a(this,"rotationWrapper",null),a(this,"context"),a(this,"positionChange",new x),a(this,"rotationChange",new V),a(this,"_prevTime",0),this.context=s,this.root=t,this.clip=i,yt.firstKeyframeRotation[this.cacheId]||(yt.firstKeyframeRotation[this.cacheId]=new V),o){const r=o.values;yt.firstKeyframeRotation[this.cacheId].set(r[0],r[1],r[2],r[3])}yt.spaceRotation[this.cacheId]||(yt.spaceRotation[this.cacheId]=new V),yt.effectiveSpaceRotation[this.cacheId]||(yt.effectiveSpaceRotation[this.cacheId]=new V),yt.clipOffsetRotation[this.cacheId]=new V,o&&yt.clipOffsetRotation[this.cacheId].set(o.values[0],o.values[1],o.values[2],o.values[3]).invert(),this.handlePosition(i,n),this.handleRotation(i,o)}set action(s){this._action=s}get action(){return this._action}get cacheId(){return this.root.uuid}onStart(s){if(s.getClip()!==this.clip)return;yt.lastObjRotation[this.cacheId]||(yt.lastObjRotation[this.cacheId]=this.root.quaternion.clone());const t=yt.lastObjRotation[this.cacheId];if(yt.spaceRotation[this.cacheId].copy(t),xu){const i=new Ft().setFromQuaternion(t);console.log("START",this.clip.name,W.toDegrees(i.y),this.root.position.z)}}getClipRotationOffset(){return yt.clipOffsetRotation[this.cacheId]}handlePosition(s,t){if(t){const i=this.root;xu&&i.add(new bi),yt.lastObjPosition[this.cacheId]||(yt.lastObjPosition[this.cacheId]=this.root.position.clone());const n=new x,o=new x;this.positionWrapper=new Cw(t,(r,l)=>{const c=this.action.getEffectiveWeight();return xu&&i.position.length()>8&&i.position.set(0,i.position.y,0),r>this._prevTime&&(n.set(l[0],l[1],l[2]),n.sub(o),n.multiplyScalar(c),n.applyQuaternion(this.getClipRotationOffset()),n.applyQuaternion(i.quaternion),this.positionChange.copy(n)),o.fromArray(l),this._prevTime=r,l[0]=0,l[1]=0,l[2]=0,l})}}handleRotation(s,t){if(t){if(xu){const r=t.values,l=new Ft().setFromQuaternion(new V(r[0],r[1],r[2],r[3]));console.log(s.name,t.name,"FIRST ROTATION IN TRACK",W.toDegrees(l.y));const c=t.values.length-4,h=new V().set(r[c],r[c+1],r[c+2],r[c+3]),d=new Ft().setFromQuaternion(h);console.log(s.name,t.name,"LAST ROTATION IN TRACK",W.toDegrees(d.y))}let i=0;const n=new V,o=new V;this.rotationWrapper=new Cw(t,(r,l)=>(r>i&&(o.set(l[0],l[1],l[2],l[3]),n.invert(),o.multiply(n),this.rotationChange.copy(o)),n.fromArray(l),i=r,l[0]=0,l[1]=0,l[2]=0,l[3]=1,l))}}onBeforeUpdate(s){this.positionChange.set(0,0,0),this.rotationChange.set(0,0,0,1)}onAfterUpdate(s){return!this.action||(s*=this.action.getEffectiveWeight(),s<=0)?!1:(this.positionChange.multiplyScalar(s),this.rotationChange.slerp(yt.identityQuaternion,1-s),!0)}};let So=yt;a(So,"lastObjPosition",{}),a(So,"lastObjRotation",{}),a(So,"firstKeyframeRotation",{}),a(So,"spaceRotation",{}),a(So,"effectiveSpaceRotation",{}),a(So,"clipOffsetRotation",{}),a(So,"identityQuaternion",new V);class j2{constructor(t){a(this,"controller"),a(this,"handler",[]),a(this,"root"),a(this,"basePosition",new x),a(this,"baseQuaternion",new V),a(this,"baseRotation",new Ft),a(this,"summedPosition",new x),a(this,"summedRotation",new V),this.controller=t}createClip(t,i,n){this.root=i,i&&"name"in i&&i.name;const o=this.findRootTrack(n,".position"),r=this.findRootTrack(n,".quaternion"),l=new So(this.controller.context,i,n,o,r);this.handler.push(l);const c=t.clipAction(n);return l.action=c,c}onStart(t){for(const i of this.handler)i.onStart(t)}onBeforeUpdate(t){this.basePosition.copy(this.root.position),this.baseQuaternion.copy(this.root.quaternion);for(const i of this.handler)i.onBeforeUpdate(t)}onAfterUpdate(t){if(!(t<=0)){this.root.position.copy(this.basePosition),this.root.quaternion.copy(this.baseQuaternion),this.summedPosition.set(0,0,0),this.summedRotation.set(0,0,0,1);for(const i of this.handler)i.onAfterUpdate(t)&&(this.summedPosition.add(i.positionChange),this.summedRotation.multiply(i.rotationChange));this.root.position.add(this.summedPosition),this.root.quaternion.multiply(this.summedRotation)}}findRootTrack(t,i){const n=t.tracks;if(!n)return null;for(const o of n)if(o.name.endsWith(i))return o;return null}}class L2 extends Ki{onSerialize(t,i){}onDeserialize(t,i){if(i.type===Vi&&t?.__type==="AnimatorController")return new Vi(t)}}new L2(Vi);var D2=Object.defineProperty,B2=Object.getOwnPropertyDescriptor,Su=(s,t,i,n)=>{for(var o=n>1?void 0:n?B2(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&D2(t,i,o),o};const Ji=O("debuganimator");class Pt extends A{constructor(){super(...arguments),a(this,"applyRootMotion",!1),a(this,"hasRootMotion",!1),a(this,"keepAnimatorControllerStateOnDisable",!1),a(this,"_parametersAreDirty",!1),a(this,"_isDirty",!1),a(this,"_speed",1),a(this,"_normalizedStartOffset",0),a(this,"_animatorController",null),a(this,"_initializeWithRuntimeAnimatorController")}get isAnimationComponent(){return!0}set runtimeAnimatorController(t){var i;this._animatorController&&this._animatorController.model===t||(t?t instanceof Vi?(t.animator&&t.animator!==this&&(console.warn("AnimatorController can not be bound to multiple animators",(i=t.model)==null?void 0:i.name),t.model||console.error("AnimatorController has no model"),t=new Vi(t.model)),this._animatorController=t,this._animatorController.bind(this)):(Ji&&console.log("Assign animator controller",t,this),this._animatorController=new Vi(t),this.__didAwake&&this._animatorController.bind(this)):this._animatorController=null)}get runtimeAnimatorController(){return this._animatorController}getCurrentStateInfo(){var t;return(t=this.runtimeAnimatorController)==null?void 0:t.getCurrentStateInfo()}get currentAction(){var t;return((t=this.runtimeAnimatorController)==null?void 0:t.currentAction)||null}get parametersAreDirty(){return this._parametersAreDirty}get isDirty(){return this._isDirty}Play(t,i=-1,n=Number.NEGATIVE_INFINITY,o=0){this.play(t,i,n,o)}play(t,i=-1,n=Number.NEGATIVE_INFINITY,o=0){var r;(r=this.runtimeAnimatorController)==null||r.play(t,i,n,o),this._isDirty=!0}Reset(){this.reset()}reset(){var t;(t=this._animatorController)==null||t.reset(),this._isDirty=!0}SetBool(t,i){this.setBool(t,i)}setBool(t,i){var n,o;Ji&&console.log("setBool",t,i),((n=this.runtimeAnimatorController)==null?void 0:n.getBool(t))!==i&&(this._parametersAreDirty=!0),(o=this.runtimeAnimatorController)==null||o.setBool(t,i)}GetBool(t){return this.getBool(t)}getBool(t){var i;const n=((i=this.runtimeAnimatorController)==null?void 0:i.getBool(t))??!1;return Ji&&console.log("getBool",t,n),n}toggleBool(t){this.setBool(t,!this.getBool(t))}SetFloat(t,i){this.setFloat(t,i)}setFloat(t,i){var n,o;((n=this.runtimeAnimatorController)==null?void 0:n.getFloat(t))!==i&&(this._parametersAreDirty=!0),Ji&&console.log("setFloat",t,i),(o=this.runtimeAnimatorController)==null||o.setFloat(t,i)}GetFloat(t){return this.getFloat(t)}getFloat(t){var i;const n=((i=this.runtimeAnimatorController)==null?void 0:i.getFloat(t))??-1;return Ji&&console.log("getFloat",t,n),n}SetInteger(t,i){this.setInteger(t,i)}setInteger(t,i){var n,o;((n=this.runtimeAnimatorController)==null?void 0:n.getInteger(t))!==i&&(this._parametersAreDirty=!0),Ji&&console.log("setInteger",t,i),(o=this.runtimeAnimatorController)==null||o.setInteger(t,i)}GetInteger(t){return this.getInteger(t)}getInteger(t){var i;const n=((i=this.runtimeAnimatorController)==null?void 0:i.getInteger(t))??-1;return Ji&&console.log("getInteger",t,n),n}SetTrigger(t){this.setTrigger(t)}setTrigger(t){var i;this._parametersAreDirty=!0,Ji&&console.log("setTrigger",t),(i=this.runtimeAnimatorController)==null||i.setTrigger(t)}ResetTrigger(t){this.resetTrigger(t)}resetTrigger(t){var i;this._parametersAreDirty=!0,Ji&&console.log("resetTrigger",t),(i=this.runtimeAnimatorController)==null||i.resetTrigger(t)}GetTrigger(t){this.getTrigger(t)}getTrigger(t){var i;const n=(i=this.runtimeAnimatorController)==null?void 0:i.getTrigger(t);return Ji&&console.log("getTrigger",t,n),n}IsInTransition(){return this.isInTransition()}isInTransition(){var t;return((t=this.runtimeAnimatorController)==null?void 0:t.isInTransition())??!1}SetSpeed(t){return this.setSpeed(t)}setSpeed(t){var i;t!==this._speed&&(Ji&&console.log("setSpeed",t),this._speed=t,((i=this._animatorController)==null?void 0:i.animator)==this&&this._animatorController.setSpeed(t))}set minMaxSpeed(t){var i;this._speed=W.lerp(t.x,t.y,Math.random()),((i=this._animatorController)==null?void 0:i.animator)==this&&this._animatorController.setSpeed(this._speed)}set minMaxOffsetNormalized(t){var i;this._normalizedStartOffset=W.lerp(t.x,t.y,Math.random()),((i=this.runtimeAnimatorController)==null?void 0:i.animator)==this&&(this.runtimeAnimatorController.normalizedStartOffset=this._normalizedStartOffset)}awake(){Ji&&console.log("ANIMATOR",this.name,this),this.gameObject&&this.initializeRuntimeAnimatorController()}initializeRuntimeAnimatorController(t=!1){const i=t||this.runtimeAnimatorController!==this._initializeWithRuntimeAnimatorController;if(this.runtimeAnimatorController&&i){const n=this.runtimeAnimatorController.clone();this._initializeWithRuntimeAnimatorController=n,n?(console.assert(this.runtimeAnimatorController!==n),this.runtimeAnimatorController=n,console.assert(this.runtimeAnimatorController===n),this.runtimeAnimatorController.bind(this),this.runtimeAnimatorController.setSpeed(this._speed),this.runtimeAnimatorController.normalizedStartOffset=this._normalizedStartOffset):console.warn("Could not clone animator controller",this.runtimeAnimatorController)}}onDisable(){var t;this.keepAnimatorControllerStateOnDisable||(t=this._animatorController)==null||t.reset()}onBeforeRender(){this._isDirty=!1,this._parametersAreDirty=!1,!A2(this.gameObject)&&this._animatorController&&this._animatorController.update(1)}}Su([m()],Pt.prototype,"applyRootMotion",2),Su([m()],Pt.prototype,"hasRootMotion",2),Su([m()],Pt.prototype,"keepAnimatorControllerStateOnDisable",2),Su([m()],Pt.prototype,"runtimeAnimatorController",1);const Ow=Symbol("previous-visibility"),Ic=class extends ao{render(s,t,i){if("addPass"in i)this._unsupported_effectcomposer_warning||(console.warn("RenderTexture.render() does not yet support EffectComposer"),this._unsupported_effectcomposer_warning=!0);else if(i instanceof cr){this.onBeforeRender();const n=i.getRenderTarget(),o=i.xr.enabled;i.xr.enabled=!1,i.setRenderTarget(this),i.clear(!0,!0,!0),i.render(s,t),i.setRenderTarget(n),i.xr.enabled=o,this.onAfterRender()}}onBeforeRender(){Ic._userSet.clear();const s=kg(this.texture,!0,null,Ic._userSet);for(const t of s)t instanceof Q&&(t[Ow]=t.visible,t.visible=!1)}onAfterRender(){for(const s of Ic._userSet)s instanceof Q&&(s.visible=s[Ow]);Ic._userSet.clear()}};let $a=Ic;a($a,"_userSet",new Set);var F2=Object.defineProperty,z2=Object.getOwnPropertyDescriptor,jc=(s,t,i,n)=>{for(var o=n>1?void 0:n?z2(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&F2(t,i,o),o};const Cu=O("debuggroundprojection");class Vs extends A{constructor(){super(...arguments),a(this,"applyOnAwake",!1),a(this,"autoFit",!0),a(this,"_radius",50),a(this,"_height",3),a(this,"_arblending",0),a(this,"_lastBackground"),a(this,"_lastRadius"),a(this,"_lastHeight"),a(this,"_projection"),a(this,"_watcher"),a(this,"_needsTextureUpdate",!1),a(this,"_blurrynessShader",null),a(this,"_lastBlurriness",-1)}set radius(t){this._radius=t,this._projection&&this.updateProjection()}get radius(){return this._radius}set height(t){this._height=t,this._projection&&this.updateProjection()}get height(){return this._height}set arBlending(t){this._arblending=t,this._needsTextureUpdate=!0}get arBlending(){return this._arblending}awake(){this.applyOnAwake&&this.updateAndCreate()}onEnable(){this.context.time.frameCount>0&&this.applyOnAwake&&this.updateAndCreate(),this._watcher||(this._watcher=new Jn(this.context.scene,"background"),this._watcher.subscribeWrite(t=>{Cu&&console.log("Background changed",this.context.scene.background),this._needsTextureUpdate=!0}))}onDisable(){var t,i;(t=this._watcher)==null||t.revoke(),(i=this._projection)==null||i.removeFromParent()}onEnterXR(){this.activeAndEnabled&&(this._needsTextureUpdate=!0,this.updateProjection())}async onLeaveXR(){this.activeAndEnabled&&(await Xl(1),this.updateProjection())}onBeforeRender(){this._projection&&this.scene.backgroundRotation&&this._projection.rotation.copy(this.scene.backgroundRotation),this.context.scene.backgroundBlurriness!==void 0&&this._lastBlurriness!=this.context.scene.backgroundBlurriness&&this.context.scene.backgroundBlurriness>.001?this.updateProjection():this._needsTextureUpdate&&this.context.scene.background instanceof Ne&&this.updateBlurriness(this.context.scene.background,this.context.scene.backgroundBlurriness)}updateAndCreate(){var t;this.updateProjection(),(t=this._watcher)==null||t.apply()}updateProjection(){var t,i,n,o,r,l;if(!this.context.scene.background){(t=this._projection)==null||t.removeFromParent();return}const c=this.context.scene.background;if(!(c instanceof Ne)){(i=this._projection)==null||i.removeFromParent();return}if(((n=this.context.xr)!=null&&n.isPassThrough||(o=this.context.xr)!=null&&o.isAR)&&this.arBlending===0){(r=this._projection)==null||r.removeFromParent();return}if(!this.gameObject||this.destroyed)return;let h=!0;const d=0,u=c!==this._lastBackground||this._height!==this._lastHeight||this._radius!==this._lastRadius;if(!this._projection||u){Cu&&console.log("Create/Update Ground Projection",c.name),(l=this._projection)==null||l.removeFromParent();try{this._projection=new xa(c,this._height,this._radius,64)}catch(p){console.error("Error creating three GroundProjection",p);return}this._projection.position.y=this._height-d,this._projection.name="GroundProjection",Ym(this._projection,!1)}else h=!1;if(this._projection.parent||this.gameObject.add(this._projection),this.autoFit&&h){this._projection.updateWorldMatrix(!0,!0);const p=Si(this.context.scene.children,[this._projection]),g=p.min.y;if(g<1/0){const y=$();y.x=p.min.x+(p.max.x-p.min.x)*.5;const f=Ke(this.gameObject).x;y.y=g+this._height*f-d,y.z=p.min.z+(p.max.z-p.min.z)*.5,lt(this._projection,y)}Cu&&q.DrawWireBox3(p,65280,5)}this.context.scene.backgroundBlurriness>.001&&this._needsTextureUpdate&&this.updateBlurriness(c,this.context.scene.backgroundBlurriness),this._lastBackground=c,this._lastHeight=this._height,this._lastRadius=this._radius,this._needsTextureUpdate=!1}updateBlurriness(t,i){var n;if(this._projection){if(!t)return}else return;this._needsTextureUpdate=!1,Cu&&console.log("Update Blurriness",i),this._blurrynessShader??(this._blurrynessShader=new us({name:"GroundProjectionBlurriness",uniforms:{map:{value:t},blurriness:{value:i},blending:{value:0},alphaFactor:{value:1}},vertexShader:U2,fragmentShader:N2})),this._blurrynessShader.depthWrite=!1,this._blurrynessShader.uniforms.map.value=t,this._blurrynessShader.uniforms.blurriness.value=1,this._lastBlurriness=i,t.needsUpdate=!0;const o=this._projection.material.transparent;this._projection.material.transparent=(((n=this.context.xr)==null?void 0:n.isAR)===!0&&this.arBlending>1e-6)??!1,this._projection.material.transparent?this._blurrynessShader.uniforms.blending.value=this.arBlending:this._blurrynessShader.uniforms.blending.value=0,this.context.isInPassThrough?this._blurrynessShader.uniforms.alphaFactor.value=.95:this._blurrynessShader.uniforms.alphaFactor.value=1,o!==this._projection.material.transparent&&(this._projection.material.needsUpdate=!0),this._projection.material.map=Gi.copyTexture(t,this._blurrynessShader),this._projection.material.depthTest=!0,this._projection.material.depthWrite=!1}}jc([m()],Vs.prototype,"applyOnAwake",2),jc([m()],Vs.prototype,"autoFit",2),jc([m()],Vs.prototype,"radius",1),jc([m()],Vs.prototype,"height",1),jc([m()],Vs.prototype,"arBlending",1);const U2=`
839
+ Exit Time: `+u,l.hasExitTime)}this.transitionTo(l.destinationState,l.duration,l.offset);return}}else{this.transitionTo(l.destinationState,l.duration,l.offset);return}}o&&this.setTimescale(o,n);let r=!1;if(n.motion.isLooping&&o&&(o.time>=o.getClip().duration?(r=!0,o.reset(),o.time=0,o.play()):o.time<=0&&o.timeScale<0&&(r=!0,o.reset(),o.time=o.getClip().duration,o.play())),!r&&n&&!i&&o&&this.animator&&n.behaviours){const l=o?.getClip().duration,c=o.time/l,h=new Ac(this._activeState,c,l,this._speed);for(const d of n.behaviours)d.instance&&((t=d.instance.onStateUpdate)==null||t.call(d.instance,this.animator,h,0))}}setTimescale(t,i){let n=i.speed??1;i.speedParameter&&(n*=this.getFloat(i.speedParameter)),n!==void 0&&(t.timeScale=n*this._speed)}getState(t,i){return typeof t=="number"&&(t==-1&&(t=this.model.layers[i].stateMachine.defaultState,t===void 0&&(ht&&console.warn("AnimatorController default state is undefined: ",this.model,"Layer: "+i),t=0)),t=this.model.layers[i].stateMachine.states[t]),t}releaseHeldActions(t){for(const i of this._heldActions)i.fadeOut(t);this._heldActions.length=0}transitionTo(t,i,n){var o,r,l,c,h,d,u,p;if(!this.animator)return;const g=0;if(t=this.getState(t,g),!(t!=null&&t.motion)||!t.motion.clip||!(t.motion.clip instanceof ur))return;const y=this._activeState===t;if(y){const _=t.motion;if(!_.action_loopback&&_.clip){const C=this.rootMotionHandler?this.animator.gameObject.matrix.clone():null;this._mixer.uncacheAction(_.clip,this.animator.gameObject),C&&C.decompose(this.animator.gameObject.position,this.animator.gameObject.quaternion,this.animator.gameObject.scale),_.action_loopback=this.createAction(_.clip)}}if((o=this._activeState)!=null&&o.behaviours&&this._activeState.motion.action){const _=(r=this._activeState)==null?void 0:r.motion.clip.duration,C=this._activeState.motion.action.time/_,R=new Ac(this._activeState,C,_,this._speed);for(const M of this._activeState.behaviours)(c=(l=M.instance)==null?void 0:l.onStateExit)==null||c.call(M.instance,this.animator,R,g)}const f=(h=this._activeState)==null?void 0:h.motion.action;y&&(t.motion.action=t.motion.action_loopback,t.motion.action_loopback=f);const v=this._activeState;this._activeState=t;const b=(d=t.motion)==null?void 0:d.action,w=t.motion.clip;if(w?.duration<=0&&w.tracks.length<=0?f&&this._heldActions.push(f):f&&(f.fadeOut(i),this.releaseHeldActions(i)),b){if(n=Math.max(0,Math.min(1,n)),t.cycleOffsetParameter){let C=this.getFloat(t.cycleOffsetParameter);typeof C=="number"?(C<0&&(C+=1),n+=C,n%=1):ht&&console.warn("AnimatorController cycle offset parameter is not a number",t.cycleOffsetParameter)}else typeof t.cycleOffset=="number"&&(n+=t.cycleOffset,n%=1);b.isRunning()&&b.stop(),b.reset(),b.enabled=!0,this.setTimescale(b,t);const _=t.motion.clip.duration;if(b.time=y?0:n*_,b.timeScale<0&&(b.time=_-b.time),b.clampWhenFinished=!0,b.setLoop(dm,0),i>0?b.fadeIn(i):b.weight=1,b.play(),this.rootMotionHandler&&this.rootMotionHandler.onStart(b),this._activeStates.includes(t)||this._activeStates.push(t),this._activeState.behaviours){const C=new Ac(t,n,_,this._speed);for(const R of this._activeState.behaviours)(p=(u=R.instance)==null?void 0:u.onStateEnter)==null||p.call(R.instance,this.animator,C,g)}}else ht&&(t.__warned_no_motion||(t.__warned_no_motion=!0,console.warn("No action",t.motion,this)));ht&&console.log("TRANSITION FROM "+v?.name+" TO "+t.name,i,f,b,b?.getEffectiveTimeScale(),b?.getEffectiveWeight(),b?.isRunning(),b?.isScheduled(),b?.paused)}createAction(t){var i,n;if(this._mixer.existingAction(t)&&this._mixer.uncacheAction(t,(i=this.animator)==null?void 0:i.gameObject),(n=this.animator)!=null&&n.applyRootMotion){this.rootMotionHandler||(this.rootMotionHandler=new jk(this));const o=this.animator.gameObject;return this.rootMotionHandler.createClip(this._mixer,o,t)}else return this._mixer.clipAction(t)}evaluateCondition(t){const i=this.model.parameters.find(n=>n.name===t.parameter);if(!i)return!1;switch(t.mode){case xo.If:return i.value===!0;case xo.IfNot:return i.value===!1;case xo.Greater:return i.value>t.threshold;case xo.Less:return i.value<t.threshold;case xo.Equals:return i.value===t.threshold;case xo.NotEqual:return i.value!==t.threshold}return!1}createActions(t){var i,n,o,r;ht&&console.log("AnimatorController createActions",this.model);for(const l of this.model.layers){const c=l.stateMachine;for(let h=0;h<c.states.length;h++){const d=c.states[h];d.transitions||(d.transitions=[]);for(const u of d.transitions)u.conditions||(u.conditions=[]);if(d.motion||(ht&&console.warn("No motion",d),d.motion=Sw(d.name)),this.animator&&d.motion.clips){const u=(i=d.motion.clips)==null?void 0:i.find(p=>{var g,y;return p.node.name===((y=(g=this.animator)==null?void 0:g.gameObject)==null?void 0:y.name)});u?d.motion.clip=u.clip:(ht||F())&&console.warn('Could not find clip for animator "'+((o=(n=this.animator)==null?void 0:n.gameObject)==null?void 0:o.name)+'"',d.motion.clips.map(p=>p.node.name))}if(!d.motion.clip){ht&&console.warn("No clip assigned to state",d);const u=new ur(void 0,void 0,[]);d.motion.clip=u}if((r=d.motion)!=null&&r.clip){const u=d.motion.clip;if(u instanceof ur){const p=this.createAction(u);d.motion.action=p}else(ht||F())&&console.warn("No valid animationclip assigned",d)}if(d.behaviours&&Array.isArray(d.behaviours))for(const u of d.behaviours){if(!(u!=null&&u.typeName))continue;const p=S.get(u.typeName);if(p){const g=new p;g.isStateMachineBehaviour&&(g._context=this.context??void 0,La(g,u.properties),u.instance=g),ht&&console.log("Created animator controller behaviour",d.name,u.typeName,u.properties,g)}else(ht||F())&&console.warn("Could not find AnimatorBehaviour type: "+u.typeName)}}}}*enumerateActions(){if(this.model.layers)for(const t of this.model.layers){const i=t.stateMachine;for(let n=0;n<i.states.length;n++){const o=i.states[n];o!=null&&o.motion&&(o.motion.action&&(yield o.motion.action),o.motion.action_loopback&&(yield o.motion.action_loopback))}}}}class Cw{constructor(t,i){a(this,"track"),a(this,"createdInterpolant"),a(this,"originalEvaluate"),a(this,"customEvaluate"),this.track=t;const n=t,o=n.createInterpolant.bind(t);n.createInterpolant=()=>(n.createInterpolant=o,this.createdInterpolant=o(),this.originalEvaluate=this.createdInterpolant.evaluate.bind(this.createdInterpolant),this.customEvaluate=r=>{if(!this.originalEvaluate)return;const l=this.originalEvaluate(r);return i(r,l)},this.createdInterpolant.evaluate=this.customEvaluate,this.createdInterpolant)}dispose(){this.createdInterpolant&&this.originalEvaluate&&(this.createdInterpolant.evaluate=this.originalEvaluate),this.track=void 0,this.createdInterpolant=null,this.originalEvaluate=void 0,this.customEvaluate=void 0}}const yt=class{constructor(s,t,i,n,o){if(a(this,"_action"),a(this,"root"),a(this,"clip"),a(this,"positionWrapper",null),a(this,"rotationWrapper",null),a(this,"context"),a(this,"positionChange",new x),a(this,"rotationChange",new V),a(this,"_prevTime",0),this.context=s,this.root=t,this.clip=i,yt.firstKeyframeRotation[this.cacheId]||(yt.firstKeyframeRotation[this.cacheId]=new V),o){const r=o.values;yt.firstKeyframeRotation[this.cacheId].set(r[0],r[1],r[2],r[3])}yt.spaceRotation[this.cacheId]||(yt.spaceRotation[this.cacheId]=new V),yt.effectiveSpaceRotation[this.cacheId]||(yt.effectiveSpaceRotation[this.cacheId]=new V),yt.clipOffsetRotation[this.cacheId]=new V,o&&yt.clipOffsetRotation[this.cacheId].set(o.values[0],o.values[1],o.values[2],o.values[3]).invert(),this.handlePosition(i,n),this.handleRotation(i,o)}set action(s){this._action=s}get action(){return this._action}get cacheId(){return this.root.uuid}onStart(s){if(s.getClip()!==this.clip)return;yt.lastObjRotation[this.cacheId]||(yt.lastObjRotation[this.cacheId]=this.root.quaternion.clone());const t=yt.lastObjRotation[this.cacheId];if(yt.spaceRotation[this.cacheId].copy(t),xu){const i=new Ft().setFromQuaternion(t);console.log("START",this.clip.name,W.toDegrees(i.y),this.root.position.z)}}getClipRotationOffset(){return yt.clipOffsetRotation[this.cacheId]}handlePosition(s,t){if(t){const i=this.root;xu&&i.add(new bi),yt.lastObjPosition[this.cacheId]||(yt.lastObjPosition[this.cacheId]=this.root.position.clone());const n=new x,o=new x;this.positionWrapper=new Cw(t,(r,l)=>{const c=this.action.getEffectiveWeight();return xu&&i.position.length()>8&&i.position.set(0,i.position.y,0),r>this._prevTime&&(n.set(l[0],l[1],l[2]),n.sub(o),n.multiplyScalar(c),n.applyQuaternion(this.getClipRotationOffset()),n.applyQuaternion(i.quaternion),this.positionChange.copy(n)),o.fromArray(l),this._prevTime=r,l[0]=0,l[1]=0,l[2]=0,l})}}handleRotation(s,t){if(t){if(xu){const r=t.values,l=new Ft().setFromQuaternion(new V(r[0],r[1],r[2],r[3]));console.log(s.name,t.name,"FIRST ROTATION IN TRACK",W.toDegrees(l.y));const c=t.values.length-4,h=new V().set(r[c],r[c+1],r[c+2],r[c+3]),d=new Ft().setFromQuaternion(h);console.log(s.name,t.name,"LAST ROTATION IN TRACK",W.toDegrees(d.y))}let i=0;const n=new V,o=new V;this.rotationWrapper=new Cw(t,(r,l)=>(r>i&&(o.set(l[0],l[1],l[2],l[3]),n.invert(),o.multiply(n),this.rotationChange.copy(o)),n.fromArray(l),i=r,l[0]=0,l[1]=0,l[2]=0,l[3]=1,l))}}onBeforeUpdate(s){this.positionChange.set(0,0,0),this.rotationChange.set(0,0,0,1)}onAfterUpdate(s){return!this.action||(s*=this.action.getEffectiveWeight(),s<=0)?!1:(this.positionChange.multiplyScalar(s),this.rotationChange.slerp(yt.identityQuaternion,1-s),!0)}};let So=yt;a(So,"lastObjPosition",{}),a(So,"lastObjRotation",{}),a(So,"firstKeyframeRotation",{}),a(So,"spaceRotation",{}),a(So,"effectiveSpaceRotation",{}),a(So,"clipOffsetRotation",{}),a(So,"identityQuaternion",new V);class jk{constructor(t){a(this,"controller"),a(this,"handler",[]),a(this,"root"),a(this,"basePosition",new x),a(this,"baseQuaternion",new V),a(this,"baseRotation",new Ft),a(this,"summedPosition",new x),a(this,"summedRotation",new V),this.controller=t}createClip(t,i,n){this.root=i,i&&"name"in i&&i.name;const o=this.findRootTrack(n,".position"),r=this.findRootTrack(n,".quaternion"),l=new So(this.controller.context,i,n,o,r);this.handler.push(l);const c=t.clipAction(n);return l.action=c,c}onStart(t){for(const i of this.handler)i.onStart(t)}onBeforeUpdate(t){this.basePosition.copy(this.root.position),this.baseQuaternion.copy(this.root.quaternion);for(const i of this.handler)i.onBeforeUpdate(t)}onAfterUpdate(t){if(!(t<=0)){this.root.position.copy(this.basePosition),this.root.quaternion.copy(this.baseQuaternion),this.summedPosition.set(0,0,0),this.summedRotation.set(0,0,0,1);for(const i of this.handler)i.onAfterUpdate(t)&&(this.summedPosition.add(i.positionChange),this.summedRotation.multiply(i.rotationChange));this.root.position.add(this.summedPosition),this.root.quaternion.multiply(this.summedRotation)}}findRootTrack(t,i){const n=t.tracks;if(!n)return null;for(const o of n)if(o.name.endsWith(i))return o;return null}}class Lk extends Ki{onSerialize(t,i){}onDeserialize(t,i){if(i.type===Vi&&t?.__type==="AnimatorController")return new Vi(t)}}new Lk(Vi);var Dk=Object.defineProperty,Bk=Object.getOwnPropertyDescriptor,Su=(s,t,i,n)=>{for(var o=n>1?void 0:n?Bk(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&Dk(t,i,o),o};const Ji=O("debuganimator");class Pt extends A{constructor(){super(...arguments),a(this,"applyRootMotion",!1),a(this,"hasRootMotion",!1),a(this,"keepAnimatorControllerStateOnDisable",!1),a(this,"_parametersAreDirty",!1),a(this,"_isDirty",!1),a(this,"_speed",1),a(this,"_normalizedStartOffset",0),a(this,"_animatorController",null),a(this,"_initializeWithRuntimeAnimatorController")}get isAnimationComponent(){return!0}set runtimeAnimatorController(t){var i;this._animatorController&&this._animatorController.model===t||(t?t instanceof Vi?(t.animator&&t.animator!==this&&(console.warn("AnimatorController can not be bound to multiple animators",(i=t.model)==null?void 0:i.name),t.model||console.error("AnimatorController has no model"),t=new Vi(t.model)),this._animatorController=t,this._animatorController.bind(this)):(Ji&&console.log("Assign animator controller",t,this),this._animatorController=new Vi(t),this.__didAwake&&this._animatorController.bind(this)):this._animatorController=null)}get runtimeAnimatorController(){return this._animatorController}getCurrentStateInfo(){var t;return(t=this.runtimeAnimatorController)==null?void 0:t.getCurrentStateInfo()}get currentAction(){var t;return((t=this.runtimeAnimatorController)==null?void 0:t.currentAction)||null}get parametersAreDirty(){return this._parametersAreDirty}get isDirty(){return this._isDirty}Play(t,i=-1,n=Number.NEGATIVE_INFINITY,o=0){this.play(t,i,n,o)}play(t,i=-1,n=Number.NEGATIVE_INFINITY,o=0){var r;(r=this.runtimeAnimatorController)==null||r.play(t,i,n,o),this._isDirty=!0}Reset(){this.reset()}reset(){var t;(t=this._animatorController)==null||t.reset(),this._isDirty=!0}SetBool(t,i){this.setBool(t,i)}setBool(t,i){var n,o;Ji&&console.log("setBool",t,i),((n=this.runtimeAnimatorController)==null?void 0:n.getBool(t))!==i&&(this._parametersAreDirty=!0),(o=this.runtimeAnimatorController)==null||o.setBool(t,i)}GetBool(t){return this.getBool(t)}getBool(t){var i;const n=((i=this.runtimeAnimatorController)==null?void 0:i.getBool(t))??!1;return Ji&&console.log("getBool",t,n),n}toggleBool(t){this.setBool(t,!this.getBool(t))}SetFloat(t,i){this.setFloat(t,i)}setFloat(t,i){var n,o;((n=this.runtimeAnimatorController)==null?void 0:n.getFloat(t))!==i&&(this._parametersAreDirty=!0),Ji&&console.log("setFloat",t,i),(o=this.runtimeAnimatorController)==null||o.setFloat(t,i)}GetFloat(t){return this.getFloat(t)}getFloat(t){var i;const n=((i=this.runtimeAnimatorController)==null?void 0:i.getFloat(t))??-1;return Ji&&console.log("getFloat",t,n),n}SetInteger(t,i){this.setInteger(t,i)}setInteger(t,i){var n,o;((n=this.runtimeAnimatorController)==null?void 0:n.getInteger(t))!==i&&(this._parametersAreDirty=!0),Ji&&console.log("setInteger",t,i),(o=this.runtimeAnimatorController)==null||o.setInteger(t,i)}GetInteger(t){return this.getInteger(t)}getInteger(t){var i;const n=((i=this.runtimeAnimatorController)==null?void 0:i.getInteger(t))??-1;return Ji&&console.log("getInteger",t,n),n}SetTrigger(t){this.setTrigger(t)}setTrigger(t){var i;this._parametersAreDirty=!0,Ji&&console.log("setTrigger",t),(i=this.runtimeAnimatorController)==null||i.setTrigger(t)}ResetTrigger(t){this.resetTrigger(t)}resetTrigger(t){var i;this._parametersAreDirty=!0,Ji&&console.log("resetTrigger",t),(i=this.runtimeAnimatorController)==null||i.resetTrigger(t)}GetTrigger(t){this.getTrigger(t)}getTrigger(t){var i;const n=(i=this.runtimeAnimatorController)==null?void 0:i.getTrigger(t);return Ji&&console.log("getTrigger",t,n),n}IsInTransition(){return this.isInTransition()}isInTransition(){var t;return((t=this.runtimeAnimatorController)==null?void 0:t.isInTransition())??!1}SetSpeed(t){return this.setSpeed(t)}setSpeed(t){var i;t!==this._speed&&(Ji&&console.log("setSpeed",t),this._speed=t,((i=this._animatorController)==null?void 0:i.animator)==this&&this._animatorController.setSpeed(t))}set minMaxSpeed(t){var i;this._speed=W.lerp(t.x,t.y,Math.random()),((i=this._animatorController)==null?void 0:i.animator)==this&&this._animatorController.setSpeed(this._speed)}set minMaxOffsetNormalized(t){var i;this._normalizedStartOffset=W.lerp(t.x,t.y,Math.random()),((i=this.runtimeAnimatorController)==null?void 0:i.animator)==this&&(this.runtimeAnimatorController.normalizedStartOffset=this._normalizedStartOffset)}awake(){Ji&&console.log("ANIMATOR",this.name,this),this.gameObject&&this.initializeRuntimeAnimatorController()}initializeRuntimeAnimatorController(t=!1){const i=t||this.runtimeAnimatorController!==this._initializeWithRuntimeAnimatorController;if(this.runtimeAnimatorController&&i){const n=this.runtimeAnimatorController.clone();this._initializeWithRuntimeAnimatorController=n,n?(console.assert(this.runtimeAnimatorController!==n),this.runtimeAnimatorController=n,console.assert(this.runtimeAnimatorController===n),this.runtimeAnimatorController.bind(this),this.runtimeAnimatorController.setSpeed(this._speed),this.runtimeAnimatorController.normalizedStartOffset=this._normalizedStartOffset):console.warn("Could not clone animator controller",this.runtimeAnimatorController)}}onDisable(){var t;this.keepAnimatorControllerStateOnDisable||(t=this._animatorController)==null||t.reset()}onBeforeRender(){this._isDirty=!1,this._parametersAreDirty=!1,!Ak(this.gameObject)&&this._animatorController&&this._animatorController.update(1)}}Su([m()],Pt.prototype,"applyRootMotion",2),Su([m()],Pt.prototype,"hasRootMotion",2),Su([m()],Pt.prototype,"keepAnimatorControllerStateOnDisable",2),Su([m()],Pt.prototype,"runtimeAnimatorController",1);const Ow=Symbol("previous-visibility"),Ic=class extends ao{render(s,t,i){if("addPass"in i)this._unsupported_effectcomposer_warning||(console.warn("RenderTexture.render() does not yet support EffectComposer"),this._unsupported_effectcomposer_warning=!0);else if(i instanceof cr){this.onBeforeRender();const n=i.getRenderTarget(),o=i.xr.enabled;i.xr.enabled=!1,i.setRenderTarget(this),i.clear(!0,!0,!0),i.render(s,t),i.setRenderTarget(n),i.xr.enabled=o,this.onAfterRender()}}onBeforeRender(){Ic._userSet.clear();const s=kg(this.texture,!0,null,Ic._userSet);for(const t of s)t instanceof Q&&(t[Ow]=t.visible,t.visible=!1)}onAfterRender(){for(const s of Ic._userSet)s instanceof Q&&(s.visible=s[Ow]);Ic._userSet.clear()}};let $a=Ic;a($a,"_userSet",new Set);var Fk=Object.defineProperty,zk=Object.getOwnPropertyDescriptor,jc=(s,t,i,n)=>{for(var o=n>1?void 0:n?zk(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&Fk(t,i,o),o};const Cu=O("debuggroundprojection");class Vs extends A{constructor(){super(...arguments),a(this,"applyOnAwake",!1),a(this,"autoFit",!0),a(this,"_radius",50),a(this,"_height",3),a(this,"_arblending",0),a(this,"_lastBackground"),a(this,"_lastRadius"),a(this,"_lastHeight"),a(this,"_projection"),a(this,"_watcher"),a(this,"_needsTextureUpdate",!1),a(this,"_blurrynessShader",null),a(this,"_lastBlurriness",-1)}set radius(t){this._radius=t,this._projection&&this.updateProjection()}get radius(){return this._radius}set height(t){this._height=t,this._projection&&this.updateProjection()}get height(){return this._height}set arBlending(t){this._arblending=t,this._needsTextureUpdate=!0}get arBlending(){return this._arblending}awake(){this.applyOnAwake&&this.updateAndCreate()}onEnable(){this.context.time.frameCount>0&&this.applyOnAwake&&this.updateAndCreate(),this._watcher||(this._watcher=new Jn(this.context.scene,"background"),this._watcher.subscribeWrite(t=>{Cu&&console.log("Background changed",this.context.scene.background),this._needsTextureUpdate=!0}))}onDisable(){var t,i;(t=this._watcher)==null||t.revoke(),(i=this._projection)==null||i.removeFromParent()}onEnterXR(){this.activeAndEnabled&&(this._needsTextureUpdate=!0,this.updateProjection())}async onLeaveXR(){this.activeAndEnabled&&(await Xl(1),this.updateProjection())}onBeforeRender(){this._projection&&this.scene.backgroundRotation&&this._projection.rotation.copy(this.scene.backgroundRotation),this.context.scene.backgroundBlurriness!==void 0&&this._lastBlurriness!=this.context.scene.backgroundBlurriness&&this.context.scene.backgroundBlurriness>.001?this.updateProjection():this._needsTextureUpdate&&this.context.scene.background instanceof Ne&&this.updateBlurriness(this.context.scene.background,this.context.scene.backgroundBlurriness)}updateAndCreate(){var t;this.updateProjection(),(t=this._watcher)==null||t.apply()}updateProjection(){var t,i,n,o,r,l;if(!this.context.scene.background){(t=this._projection)==null||t.removeFromParent();return}const c=this.context.scene.background;if(!(c instanceof Ne)){(i=this._projection)==null||i.removeFromParent();return}if(((n=this.context.xr)!=null&&n.isPassThrough||(o=this.context.xr)!=null&&o.isAR)&&this.arBlending===0){(r=this._projection)==null||r.removeFromParent();return}if(!this.gameObject||this.destroyed)return;let h=!0;const d=0,u=c!==this._lastBackground||this._height!==this._lastHeight||this._radius!==this._lastRadius;if(!this._projection||u){Cu&&console.log("Create/Update Ground Projection",c.name),(l=this._projection)==null||l.removeFromParent();try{this._projection=new xa(c,this._height,this._radius,64)}catch(p){console.error("Error creating three GroundProjection",p);return}this._projection.position.y=this._height-d,this._projection.name="GroundProjection",Ym(this._projection,!1)}else h=!1;if(this._projection.parent||this.gameObject.add(this._projection),this.autoFit&&h){this._projection.updateWorldMatrix(!0,!0);const p=Si(this.context.scene.children,[this._projection]),g=p.min.y;if(g<1/0){const y=$();y.x=p.min.x+(p.max.x-p.min.x)*.5;const f=Ke(this.gameObject).x;y.y=g+this._height*f-d,y.z=p.min.z+(p.max.z-p.min.z)*.5,lt(this._projection,y)}Cu&&q.DrawWireBox3(p,65280,5)}this.context.scene.backgroundBlurriness>.001&&this._needsTextureUpdate&&this.updateBlurriness(c,this.context.scene.backgroundBlurriness),this._lastBackground=c,this._lastHeight=this._height,this._lastRadius=this._radius,this._needsTextureUpdate=!1}updateBlurriness(t,i){var n;if(this._projection){if(!t)return}else return;this._needsTextureUpdate=!1,Cu&&console.log("Update Blurriness",i),this._blurrynessShader??(this._blurrynessShader=new us({name:"GroundProjectionBlurriness",uniforms:{map:{value:t},blurriness:{value:i},blending:{value:0},alphaFactor:{value:1}},vertexShader:Uk,fragmentShader:Nk})),this._blurrynessShader.depthWrite=!1,this._blurrynessShader.uniforms.map.value=t,this._blurrynessShader.uniforms.blurriness.value=1,this._lastBlurriness=i,t.needsUpdate=!0;const o=this._projection.material.transparent;this._projection.material.transparent=(((n=this.context.xr)==null?void 0:n.isAR)===!0&&this.arBlending>1e-6)??!1,this._projection.material.transparent?this._blurrynessShader.uniforms.blending.value=this.arBlending:this._blurrynessShader.uniforms.blending.value=0,this.context.isInPassThrough?this._blurrynessShader.uniforms.alphaFactor.value=.95:this._blurrynessShader.uniforms.alphaFactor.value=1,o!==this._projection.material.transparent&&(this._projection.material.needsUpdate=!0),this._projection.material.map=Gi.copyTexture(t,this._blurrynessShader),this._projection.material.depthTest=!0,this._projection.material.depthWrite=!1}}jc([m()],Vs.prototype,"applyOnAwake",2),jc([m()],Vs.prototype,"autoFit",2),jc([m()],Vs.prototype,"radius",1),jc([m()],Vs.prototype,"height",1),jc([m()],Vs.prototype,"arBlending",1);const Uk=`
840
840
  varying vec2 vUv;
841
841
 
842
842
  void main() {
843
843
  vUv = uv;
844
844
  gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
845
845
  }
846
- `,N2=`
846
+ `,Nk=`
847
847
  uniform sampler2D map;
848
848
  uniform float blurriness;
849
849
  uniform float alphaFactor;
@@ -905,7 +905,7 @@ Exit Time: `+u,l.hasExitTime)}this.transitionTo(l.destinationState,l.duration,l.
905
905
  // Uncomment to visualize blur amount
906
906
  // gl_FragColor = vec4(blurAmount, 0.0, 0.0, 1.0);
907
907
  }
908
- `;var W2=Object.defineProperty,V2=Object.getOwnPropertyDescriptor,ff=(s,t,i,n)=>{for(var o=n>1?void 0:n?V2(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&W2(t,i,o),o};class Dr extends A{constructor(){super(...arguments),a(this,"constraintActive",!0),a(this,"locked",!1),a(this,"sources",[])}}ff([m()],Dr.prototype,"constraintActive",2),ff([m()],Dr.prototype,"locked",2),ff([m(j)],Dr.prototype,"sources",2);function H2(s,t){return Cn(s,fe.ContextCreated,t),()=>po(s,fe.ContextCreated)}function $2(s,t){return Cn(s,fe.ContextClearing,t),()=>po(s,fe.ContextClearing)}function q2(s,t){return Cn(s,fe.ContextDestroying,t),()=>po(s,fe.ContextDestroying)}function Pw(s,t){return Cn(s,Ce.Start,t),()=>po(s,Ce.Start)}function kw(s,t){return Cn(s,Ce.Update,t),()=>po(s,Ce.Update)}function G2(s,t){return Cn(s,Ce.OnBeforeRender,t),()=>po(s,Ce.OnBeforeRender)}function X2(s,t){return Cn(s,Ce.OnAfterRender,t),()=>po(s,Ce.OnAfterRender)}let Br=class{constructor(){a(this,"bb",null),a(this,"bb_pos",0)}__init(s,t){return this.bb_pos=s,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(s,t,i,n){return s.prep(4,12),s.writeFloat32(n),s.writeFloat32(i),s.writeFloat32(t),s.offset()}};class Mw{constructor(){a(this,"bb",null),a(this,"bb_pos",0)}__init(t,i){return this.bb_pos=t,this.bb=i,this}position(t){return(t||new Br).__init(this.bb_pos,this.bb)}rotation(t){return(t||new Br).__init(this.bb_pos+12,this.bb)}scale(t){return(t||new Br).__init(this.bb_pos+24,this.bb)}static sizeOf(){return 36}static createTransform(t,i,n,o,r,l,c,h,d,u){return t.prep(4,36),t.prep(4,12),t.writeFloat32(u),t.writeFloat32(d),t.writeFloat32(h),t.prep(4,12),t.writeFloat32(c),t.writeFloat32(l),t.writeFloat32(r),t.prep(4,12),t.writeFloat32(o),t.writeFloat32(n),t.writeFloat32(i),t.offset()}}class eo{constructor(){a(this,"bb",null),a(this,"bb_pos",0)}__init(t,i){return this.bb_pos=t,this.bb=i,this}static getRootAsSyncedTransformModel(t,i){return(i||new eo).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsSyncedTransformModel(t,i){return t.setPosition(t.position()+fv),(i||new eo).__init(t.readInt32(t.position())+t.position(),t)}guid(t){const i=this.bb.__offset(this.bb_pos,4);return i?this.bb.__string(this.bb_pos+i,t):null}fast(){const t=this.bb.__offset(this.bb_pos,6);return t?!!this.bb.readInt8(this.bb_pos+t):!1}transform(t){const i=this.bb.__offset(this.bb_pos,8);return i?(t||new Mw).__init(this.bb_pos+i,this.bb):null}dontSave(){const t=this.bb.__offset(this.bb_pos,10);return t?!!this.bb.readInt8(this.bb_pos+t):!1}static startSyncedTransformModel(t){t.startObject(4)}static addGuid(t,i){t.addFieldOffset(0,i,0)}static addFast(t,i){t.addFieldInt8(1,+i,0)}static addTransform(t,i){t.addFieldStruct(2,i,0)}static addDontSave(t,i){t.addFieldInt8(3,+i,0)}static endSyncedTransformModel(t){return t.endObject()}static finishSyncedTransformModelBuffer(t,i){t.finish(i)}static finishSizePrefixedSyncedTransformModelBuffer(t,i){t.finish(i,void 0,!0)}}var B;(s=>{(t=>{t.MAYBEMODULE=null;const i=[];function n(){return t.MODULE?Promise.resolve(t.MODULE):new Promise(r=>{i.push(r)})}t.ready=n;async function o(){if(t.MODULE)return t.MODULE;const r=await import("./rapier.light.min.js");return t.MODULE=r,t.MAYBEMODULE=r,i.forEach(l=>l(r)),i.length=0,r}t.load=o})(s.RAPIER_PHYSICS||(s.RAPIER_PHYSICS={})),(t=>{t.MAYBEMODULE=null;const i=[];function n(){return t.MODULE?Promise.resolve(t.MODULE):new Promise(r=>{i.push(r)})}t.ready=n;async function o(){if(t.MODULE)return t.MODULE;const r=await import("./postprocessing.light.min.js").then(l=>l.i);return t.MODULE=r,t.MAYBEMODULE=r,i.forEach(l=>l(r)),i.length=0,r}t.load=o})(s.POSTPROCESSING||(s.POSTPROCESSING={})),(t=>{t.MAYBEMODULE=null;const i=[];function n(){return t.MODULE?Promise.resolve(t.MODULE):new Promise(r=>{i.push(r)})}t.ready=n;async function o(){if(t.MODULE)return t.MODULE;const r=await import("./postprocessing.light.min.js").then(l=>l.N);return t.MODULE=r,t.MAYBEMODULE=r,i.forEach(l=>l(r)),i.length=0,r}t.load=o})(s.POSTPROCESSING_AO||(s.POSTPROCESSING_AO={}))})(B||(B={}));var vt=(s=>(s[s.Average=0]="Average",s[s.Multiply=1]="Multiply",s[s.Minimum=2]="Minimum",s[s.Maximum=3]="Maximum",s))(vt||{}),Ou=(s=>(s[s.Discrete=0]="Discrete",s[s.Continuous=1]="Continuous",s))(Ou||{}),tt=(s=>(s[s.None=0]="None",s[s.FreezePositionX=2]="FreezePositionX",s[s.FreezePositionY=4]="FreezePositionY",s[s.FreezePositionZ=8]="FreezePositionZ",s[s.FreezePosition=14]="FreezePosition",s[s.FreezeRotationX=16]="FreezeRotationX",s[s.FreezeRotationY=32]="FreezeRotationY",s[s.FreezeRotationZ=64]="FreezeRotationZ",s[s.FreezeRotation=112]="FreezeRotation",s[s.FreezeAll=126]="FreezeAll",s))(tt||{}),qa=(s=>(s[s.None=0]="None",s[s.X=2]="X",s[s.Y=4]="Y",s[s.Z=8]="Z",s[s.All=-1]="All",s))(qa||{});const kt=function(s,t){return function(i,n,o){Q2(i,n,o,s,t)}};function Q2(s,t,i,n,o){if(!o&&!n&&!s.onValidate)return;if(i!==void 0){console.error("Invalid usage of validate decorator. Only fields can be validated.",s,t,i),Le("Invalid usage of validate decorator. Only fields can be validated. Property: "+t,xi.Error);return}let r="";if(typeof t=="string"?r=t:r=t.name,s.__internalAwake){const l=Symbol(r),c=s.__internalAwake;s.__internalAwake=function(){var h;if(!this.onValidate){F()&&console.warn('Usage of @validate decorate detected but there is no onValidate method in your class: "'+((h=s.constructor)==null?void 0:h.name)+'"');return}if(this[l]===void 0){this[l]=this[r];const d=this[r];if(d instanceof oe||d instanceof x||d instanceof me||d instanceof V){const u=this[r];fd(u,()=>{this.onValidate(r)})}Object.defineProperty(this,r,{set:function(u){var p;if(this[$g]===!0)this[l]=u;else{n?.call(this,u);const g=this[l];this[l]=u,(p=this.onValidate)==null||p.call(this,r,g)}},get:function(){return o?.call(this),this[l]}})}c.call(this)}}}const Y2=function(s){return function(t,i,n){let o="";typeof i=="string"?o=i:o=i.name;const r=s.prototype,l=Object.getOwnPropertyDescriptor(r,o);if(!(l!=null&&l.value)){console.warn("Can not apply prefix: type does not have method named",i,s);return}const c=l.value,h=t[o];Object.defineProperty(r,o,{value:function(...d){const u=h?.call(this,...d);if(u instanceof Promise){u.then(p=>{if(p!==!1)return c.call(this,...d)});return}if(u!==!1)return c.call(this,...d)}})}};var K2=Object.defineProperty,Z2=Object.getOwnPropertyDescriptor,Ri=(s,t,i,n)=>{for(var o=n>1?void 0:n?Z2(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&K2(t,i,o),o};class J2{constructor(t,i){a(this,"positionChanged",!1),a(this,"rotationChanged",!1),a(this,"position"),a(this,"quaternion"),a(this,"_positionKeys",["x","y","z"]),a(this,"_quaternionKeys",["_x","_y","_z","_w"]),a(this,"mute",!1),a(this,"context"),a(this,"obj"),a(this,"_positionWatch"),a(this,"_rotationWatch"),this.context=i,this.obj=t}get isDirty(){return this.positionChanged||this.rotationChanged}reset(t=!1){if(this.positionChanged=!1,this.rotationChanged=!1,this.mute=!1,t){if(this.position)for(const i of this._positionKeys)delete this.position[i];if(this.quaternion)for(const i of this._quaternionKeys)delete this.quaternion[i]}}syncValues(){for(const t of this._positionKeys)this.position[t]=this.obj.position[t];for(const t of this._quaternionKeys)this.quaternion[t]=this.obj.quaternion[t]}applyValues(){if(this.positionChanged&&this.position)for(const t of this._positionKeys){const i=this.position[t];i!==void 0&&(this.obj.position[t]=i)}if(this.rotationChanged&&this.quaternion)for(const t of this._quaternionKeys){const i=this.quaternion[t];i!==void 0&&(this.obj.quaternion[t]=i)}}start(t,i){this.reset(),t&&(this._positionWatch||(this._positionWatch=new Jn(this.obj.position,["x","y","z"])),this._positionWatch.apply(),this.position={},this._positionWatch.subscribeWrite((r,l)=>{var c;if((c=this.context.physics.engine)!=null&&c.isUpdating||this.mute)return;const h=this.position[l];Math.abs(h-r)<1e-5||(this.position[l]=r,this.positionChanged=!0)})),i&&(this._rotationWatch||(this._rotationWatch=new Jn(this.obj.quaternion,["_x","_y","_z","_w"])),this._rotationWatch.apply(),this.quaternion={},this._rotationWatch.subscribeWrite((r,l)=>{var c;if((c=this.context.physics.engine)!=null&&c.isUpdating||this.mute)return;const h=this.quaternion[l];Math.abs(h-r)<1e-5||(this.quaternion[l]=r,this.rotationChanged=!0)}));const n=this.obj.matrixWorld.multiplyMatrices.bind(this.obj.matrixWorld),o=new ne;this.obj.matrixWorld.multiplyMatrices=(r,l)=>{var c;return(c=this.context.physics.engine)!=null&&c.isUpdating||this.mute||o.equals(r)||(this.positionChanged=!0,this.rotationChanged=!0,o.copy(r)),n(r,l)}}stop(){var t,i;(t=this._positionWatch)==null||t.revoke(),(i=this._rotationWatch)==null||i.revoke()}}var yf;const vf=(yf=class extends A{constructor(){super(...arguments),a(this,"autoMass",!0),a(this,"_mass",0),a(this,"useGravity",!0),a(this,"centerOfMass",new x(0,0,0)),a(this,"constraints",tt.None),a(this,"isKinematic",!1),a(this,"drag",0),a(this,"angularDrag",1),a(this,"detectCollisions",!0),a(this,"sleepThreshold",.01),a(this,"collisionDetectionMode",Ou.Discrete),a(this,"_gravityScale",1),a(this,"dominanceGroup",0),a(this,"_propertiesChanged",!1),a(this,"_currentVelocity",new x),a(this,"_smoothedVelocity",new x),a(this,"_smoothedVelocityGetter",new x),a(this,"_lastPosition",new x),a(this,"_watch")}get isRigidbody(){return!0}set mass(s){s!==this._mass&&(this._mass=s,this._propertiesChanged=!0,this.__didAwake&&(this.autoMass=!1))}get mass(){var s,t;return this.autoMass?((t=(s=this.context.physics.engine)==null?void 0:s.getBody(this))==null?void 0:t.mass())??-1:this._mass}get lockPositionX(){return(this.constraints&tt.FreezePositionX)!==0}get lockPositionY(){return(this.constraints&tt.FreezePositionY)!==0}get lockPositionZ(){return(this.constraints&tt.FreezePositionZ)!==0}get lockRotationX(){return(this.constraints&tt.FreezeRotationX)!==0}get lockRotationY(){return(this.constraints&tt.FreezeRotationY)!==0}get lockRotationZ(){return(this.constraints&tt.FreezeRotationZ)!==0}set lockPositionX(s){s?this.constraints|=tt.FreezePositionX:this.constraints&=~tt.FreezePositionX}set lockPositionY(s){s?this.constraints|=tt.FreezePositionY:this.constraints&=~tt.FreezePositionY}set lockPositionZ(s){s?this.constraints|=tt.FreezePositionZ:this.constraints&=~tt.FreezePositionZ}set lockRotationX(s){s?this.constraints|=tt.FreezeRotationX:this.constraints&=~tt.FreezeRotationX}set lockRotationY(s){s?this.constraints|=tt.FreezeRotationY:this.constraints&=~tt.FreezeRotationY}set lockRotationZ(s){s?this.constraints|=tt.FreezeRotationZ:this.constraints&=~tt.FreezeRotationZ}set gravityScale(s){this._gravityScale=s}get gravityScale(){return this._gravityScale}awake(){this._watch=void 0,this._propertiesChanged=!1}onEnable(){this._watch||(this._watch=new J2(this.gameObject,this.context)),this._watch.start(!0,!0),this.startCoroutine(this.beforePhysics(),Ce.LateUpdate),F()&&(globalThis.false?B.RAPIER_PHYSICS.ready().then(async()=>{var s;await Xl(3),(s=this.context.physics.engine)!=null&&s.getBody(this)||console.warn(`Rigidbody could not be created. Ensure "${this.name}" has a Collider component.`)}):console.warn("Rigidbody could not be created: Rapier physics are explicitly disabled."))}onDisable(){var s,t;(s=this._watch)==null||s.stop(),(t=this.context.physics.engine)==null||t.removeBody(this)}onDestroy(){var s;(s=this.context.physics.engine)==null||s.removeBody(this)}onValidate(){this._propertiesChanged=!0}*beforePhysics(){for(var s,t,i,n;;)this._propertiesChanged&&(this._propertiesChanged=!1,(s=this.context.physics.engine)==null||s.updateProperties(this)),(t=this._watch)!=null&&t.isDirty?(this._watch.mute=!0,this._watch.applyValues(),(i=this.context.physics.engine)==null||i.updateBody(this,this._watch.positionChanged,this._watch.rotationChanged),this._watch.reset()):(n=this._watch)==null||n.syncValues(),this.captureVelocity(),yield}teleport(s,t=!0){var i;(i=this._watch)==null||i.reset(!0),t?this.gameObject.position.set(s.x,s.y,s.z):this.setWorldPosition(s.x,s.y,s.z),this.resetForcesAndTorques(),this.resetVelocities()}resetForces(s=!0){var t;(t=this.context.physics.engine)==null||t.resetForces(this,s)}resetTorques(s=!0){var t;(t=this.context.physics.engine)==null||t.resetTorques(this,s)}resetVelocities(){this.setVelocity(0,0,0),this.setAngularVelocity(0,0,0)}resetForcesAndTorques(){this.resetForces(),this.resetTorques()}wakeUp(){var s;(s=this.context.physics.engine)==null||s.wakeup(this)}get isSleeping(){var s;return(s=this.context.physics.engine)==null?void 0:s.isSleeping(this)}updateProperties(){var s;return this._propertiesChanged=!1,(s=this.context.physics.engine)==null?void 0:s.updateProperties(this)}applyForce(s,t,i=!0){var n;this._propertiesChanged&&this.updateProperties(),(n=this.context.physics.engine)==null||n.addForce(this,s,i)}applyImpulse(s,t=!0){var i;this._propertiesChanged&&this.updateProperties(),(i=this.context.physics.engine)==null||i.applyImpulse(this,s,t)}setForce(s,t,i,n=!0){var o,r,l;(o=this.context.physics.engine)==null||o.resetForces(this,n),typeof s=="number"?(t??(t=0),i??(i=0),(r=this.context.physics.engine)==null||r.addForce(this,{x:s,y:t,z:i},n)):(l=this.context.physics.engine)==null||l.addForce(this,s,n)}getVelocity(){var s;const t=(s=this.context.physics.engine)==null?void 0:s.getLinearVelocity(this);return t?(this._currentVelocity.x=t.x,this._currentVelocity.y=t.y,this._currentVelocity.z=t.z,this._currentVelocity):this._currentVelocity.set(0,0,0)}setVelocity(s,t,i,n=!0){var o,r;if(s instanceof x){const l=s;(o=this.context.physics.engine)==null||o.setLinearVelocity(this,l,n);return}t===void 0||i===void 0||(r=this.context.physics.engine)==null||r.setLinearVelocity(this,{x:s,y:t,z:i},n)}getAngularVelocity(){var s;const t=(s=this.context.physics.engine)==null?void 0:s.getAngularVelocity(this);return t?(this._currentVelocity.x=t.x,this._currentVelocity.y=t.y,this._currentVelocity.z=t.z,this._currentVelocity):this._currentVelocity.set(0,0,0)}setAngularVelocity(s,t,i,n=!0){var o,r;if(typeof s=="object"){const l=s;(o=this.context.physics.engine)==null||o.setAngularVelocity(this,l,n);return}if(t===void 0||i===void 0||typeof t=="boolean"){console.warn("setAngularVelocity expects either a Vec3 or 3 numbers");return}(r=this.context.physics.engine)==null||r.setAngularVelocity(this,{x:s,y:t,z:i},n)}setTorque(s,t,i){typeof s=="number"?this.setAngularVelocity(s,t,i):this.setAngularVelocity(s)}get smoothedVelocity(){return this._smoothedVelocityGetter.copy(this._smoothedVelocity),this._smoothedVelocityGetter.multiplyScalar(1/this.context.time.deltaTime)}setBodyFromGameObject(s=null){}captureVelocity(){const s=ee(this.gameObject);this.gameObject.matrixWorld.decompose(vf.tempPosition,eM,tM);const t=s.sub(this._lastPosition);this._lastPosition.copy(vf.tempPosition),this._smoothedVelocity.lerp(t,this.context.time.deltaTime/.1)}},a(yf,"tempPosition",new x),yf);let ye=vf;Ri([kt()],ye.prototype,"autoMass",2),Ri([m()],ye.prototype,"mass",1),Ri([kt(),m()],ye.prototype,"useGravity",2),Ri([m(x)],ye.prototype,"centerOfMass",2),Ri([kt(),m()],ye.prototype,"constraints",2),Ri([kt(),m()],ye.prototype,"isKinematic",2),Ri([kt(),m()],ye.prototype,"drag",2),Ri([kt(),m()],ye.prototype,"angularDrag",2),Ri([kt(),m()],ye.prototype,"detectCollisions",2),Ri([kt(),m()],ye.prototype,"sleepThreshold",2),Ri([kt(),m()],ye.prototype,"collisionDetectionMode",2),Ri([kt()],ye.prototype,"_gravityScale",2),Ri([kt()],ye.prototype,"dominanceGroup",2),new x;const eM=new V,tM=new x,Co=O("debugsync"),Lc="STRS";cg(Lc,eo.getRootAsSyncedTransformModel);const Hs=new Sm;function Rw(s,t,i=!0){Hs.clear();const n=Hs.createString(s);eo.startSyncedTransformModel(Hs),eo.addGuid(Hs,n),eo.addFast(Hs,i);const o=t.worldPosition,r=t.worldEuler,l=t.gameObject.scale;eo.addTransform(Hs,Mw.createTransform(Hs,o.x,o.y,o.z,r.x,r.y,r.z,l.x,l.y,l.z));const c=eo.endSyncedTransformModel(Hs);return Hs.finish(c,Lc),Hs.asUint8Array()}let bf=0,Dc=0;kw(s=>{var t;const i=(t=s.connection.currentServerUrl)!=null&&t.includes("glitch")?10:40;Dc=Math.floor(bf/i),bf=0,Co&&Dc>0&&console.log("Sync Transform Fast Interval",Dc)});class $s extends A{constructor(){super(...arguments),a(this,"overridePhysics",!0),a(this,"interpolatePosition",!0),a(this,"interpolateRotation",!0),a(this,"fastMode",!1),a(this,"syncDestroy",!1),a(this,"_model",null),a(this,"_needsUpdate",!0),a(this,"rb",null),a(this,"_wasKinematic",!1),a(this,"_receivedDataBefore",!1),a(this,"_targetPosition"),a(this,"_targetRotation"),a(this,"_receivedFastUpdate",!1),a(this,"_shouldRequestOwnership",!1),a(this,"joinedRoomCallback",null),a(this,"receivedDataCallback",null),a(this,"tempEuler",new Ft),a(this,"receivedUpdate",!1),a(this,"lastWorldPos"),a(this,"lastWorldRotation")}requestOwnership(){Co&&console.log("Request ownership"),this._model?this._model.requestOwnership():(this._shouldRequestOwnership=!0,this._needsUpdate=!0)}hasOwnership(){var t;return((t=this._model)==null?void 0:t.hasOwnership)??void 0}isOwned(){var t;return(t=this._model)==null?void 0:t.isOwned}awake(){Co&&console.log("new instance",this.guid,this),this._receivedDataBefore=!1,this._targetPosition=new x,this._targetRotation=new V,this.lastWorldPos=new x,this.lastWorldRotation=new V,this.rb=P.getComponentInChildren(this.gameObject,ye),this.rb&&(this._wasKinematic=this.rb.isKinematic),this.receivedUpdate=!0,this._model=new ug(this.context.connection,this.guid),this.context.connection.isConnected&&this.tryGetLastState(),this.joinedRoomCallback=this.tryGetLastState.bind(this),this.context.connection.beginListen(ie.JoinedRoom,this.joinedRoomCallback),this.receivedDataCallback=this.onReceivedData.bind(this),this.context.connection.beginListenBinary(Lc,this.receivedDataCallback)}onDestroy(){this.syncDestroy&&Dg(this.guid,this.context.connection),this._model=null,this.context.connection.stopListen(ie.JoinedRoom,this.joinedRoomCallback),this.context.connection.stopListenBinary(Lc,this.receivedDataCallback)}tryGetLastState(){const t=this.context.connection.tryGetState(this.guid);t&&this.onReceivedData(t)}onReceivedData(t){var i;if(!this.destroyed&&typeof t.guid=="function"&&t.guid()===this.guid){Co&&console.log("new data",this.context.connection.connectionId,this.context.time.frameCount,this.guid,t),this.receivedUpdate=!0,this._receivedFastUpdate=t.fast();const n=t.transform();if(n){cs.markDirty(this.gameObject,!0);const o=n.position();o&&(this.interpolatePosition&&((i=this._targetPosition)==null||i.set(o.x(),o.y(),o.z())),(!this.interpolatePosition||!this._receivedDataBefore)&&this.setWorldPosition(o.x(),o.y(),o.z()));const r=n.rotation();r&&(this.tempEuler.set(r.x(),r.y(),r.z()),this.interpolateRotation&&this._targetRotation.setFromEuler(this.tempEuler),(!this.interpolateRotation||!this._receivedDataBefore)&&Xm(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){Co&&console.log("no model or room",this.name,this.guid,this.context.connection.isInRoom);return}this._shouldRequestOwnership&&(this._shouldRequestOwnership=!1,this._model.requestOwnership());const t=this.worldPosition,i=this.worldQuaternion;if(this._model.isOwned&&!this.receivedUpdate){const r=t.distanceTo(this.lastWorldPos),l=i.angleTo(this.lastWorldRotation),c=this._model.hasOwnership||this.fastMode?1e-4:.001;(r>c||l>c)&&(this._model.hasOwnership?this._needsUpdate=!0:(Co&&console.log(this.guid,"reset because not owned but",this.gameObject.name,this.lastWorldPos),this.worldPosition=this.lastWorldPos,t.copy(this.lastWorldPos),this.worldQuaternion=this.lastWorldRotation,i.copy(this.lastWorldRotation),cs.markDirty(this.gameObject,!0),this._needsUpdate=!1))}if(this._model&&!this._model.hasOwnership&&this._model.isOwned&&this._receivedDataBefore){const r=this._receivedFastUpdate||this.fastMode?.5:.3;let l=!1;if(this.interpolatePosition&&this._targetPosition){const c=this.worldPosition;c.lerp(this._targetPosition,r),this.worldPosition=c,l=!0}if(this.interpolateRotation&&this._targetRotation){const c=this.worldQuaternion;c.slerp(this._targetRotation,r),this.worldQuaternion=c,l=!0}l&&cs.markDirty(this.gameObject,!0)}if(this.receivedUpdate=!1,this.lastWorldPos.copy(t),this.lastWorldRotation.copy(i),!this._model||!this._model||this._model.hasOwnership===void 0||!this._model.hasOwnership)return;this.rb&&this.overridePhysics&&this._wasKinematic!==void 0&&(Co&&console.log("reset kinematic",this.rb.name,this._wasKinematic),this.rb.isKinematic=this._wasKinematic);const n=10,o=this.rb||this.fastMode;if(this._needsUpdate&&(this.context.time.frameCount%n===0||o)){if(bf++,o&&Dc>0&&this.context.time.frameCount%Dc!==0)return;Co&&console.log("send update",this.context.connection.connectionId,this.guid,this.gameObject.name,this.gameObject.guid),this._needsUpdate=!1;const r=Rw(this.guid,this,!!o);this.context.connection.sendBinary(r)}}}const iM=O("debugshadowcomponents");bv.prototype.interactable={get(){return this.interactive},set(s){this.interactable=s}};const es=Symbol("shadowDomOwner");class ls extends A{constructor(){super(...arguments),a(this,"_shadowComponent",null),a(this,"_controlsChildLayout",!0),a(this,"_root"),a(this,"_parentComponent")}isRoot(){var t;return((t=this.Root)==null?void 0:t.gameObject)===this.gameObject}get canvas(){const t=this.Root;return t!=null&&t.isCanvas?t:null}get Canvas(){return this.canvas}markDirty(){ts.markUIDirty(this.context)}get shadowComponent(){return this._shadowComponent}set shadowComponent(t){this._shadowComponent=t}get controlsChildLayout(){return this._controlsChildLayout}set controlsChildLayout(t){this._controlsChildLayout=t,this.shadowComponent&&(this.shadowComponent.autoLayout=t)}get Root(){return this._root===void 0&&(this._root=P.getComponentInParent(this.gameObject,Bc)),this._root}__internalNewInstanceCreated(t){return super.__internalNewInstanceCreated(t),this.shadowComponent=null,this._root=void 0,this._parentComponent=void 0,this}onEnable(){super.onEnable()}addShadowComponent(t,i){var n;if(!t)return;this.removeShadowComponent();const o=this.isRoot()?this.gameObject:this.gameObject.parent;if(this._parentComponent=P.getComponentInParent(o,ls),!this._parentComponent){console.warn(`Component "${this.name}" doesn't have a UI parent anywhere. Do you have an UI element outside a Canvas? UI components must be a child of a Canvas component`,this);return}t.name=this.name+" ("+(this.constructor.name??"UI")+")",t.autoLayout=this._parentComponent.controlsChildLayout,t[es]=this,this.setShadowComponentOwner(t);let r=!1;if(((n=this.Root)==null?void 0:n.gameObject)===this.gameObject)this.gameObject.add(t);else{const l=this._parentComponent.shadowComponent;l&&(l?.add(t),r=!0)}this.shadowComponent=t,i&&i.shadowComponent&&this.shadowComponent&&i.shadowComponent.add(this.shadowComponent),vc&&t.add(new bi(.5)),this.onAfterAddedToScene(),r&&aO(),iM&&console.warn("Added shadow component",this.shadowComponent)}setShadowComponentOwner(t){if(t&&(t[es]===void 0||t[es]===this)&&(t[es]=this,t.children))for(const i of t.children)this.setShadowComponentOwner(i)}traverseOwnedShadowComponents(t,i,n){if(t&&t[es]===i){n(t);for(const o of t.children)this.traverseOwnedShadowComponents(o,i,n)}}removeShadowComponent(){this.shadowComponent&&this.shadowComponent.removeFromParent()}onAfterAddedToScene(){}setInteractable(t){this.shadowComponent&&(this.shadowComponent.interactable=t)}}class Bc extends ls{awake(){super.awake()}}class Fl{constructor(t,i){a(this,"event"),a(this,"button"),a(this,"buttonName"),a(this,"_used",!1),a(this,"_propagationStopped",!1),a(this,"z__pointer_ctured",!1),a(this,"z__pointer_cture_rleased",!1),a(this,"inputSource"),a(this,"object"),a(this,"point"),a(this,"normal"),a(this,"face"),a(this,"distance"),a(this,"instanceId"),a(this,"intersection"),a(this,"isDown"),a(this,"isUp"),a(this,"isPressed"),a(this,"isClick"),a(this,"isDoubleClick"),a(this,"input"),this.event=i,this.input=t,this.button=i.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())}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 t=new Fl(this.input,this.event);return Object.assign(t,this),t}Use(){this.use()}StopPropagation(){this.event.stopImmediatePropagation()}}function Pu(s,t){return P.foreachComponent(s,i=>{if(!i.enabled)return;const n=i;if(t)switch(t){case"pointerdown":if(n.onPointerDown)return!0;break;case"pointerup":if(n.onPointerUp||n.onPointerClick)return!0;break;case"pointermove":if(n.onPointerEnter||n.onPointerExit||n.onPointerMove)return!0;break}else if(n.onPointerDown||n.onPointerUp||n.onPointerEnter||n.onPointerExit||n.onPointerClick)return!0},!1)===!0}const Rn=new Array;class qs{constructor(t,i,n,o){a(this,"enabled",!0),a(this,"target"),a(this,"methodName"),a(this,"arguments"),this.target=t,this.methodName=i||null,this.arguments=n,o!=null&&(this.enabled=o)}get canClone(){return this.target instanceof Object}invoke(...t){if(this.enabled!==!1){if(typeof this.target=="function")this.arguments?(Rn.length=0,t!==void 0&&t.length>0&&Rn.push(...t),Rn.push(...this.arguments),this.target(...this.arguments),Rn.length=0):this.target(...t);else if(this.methodName!=null){const i=this.target[this.methodName];typeof i=="function"?this.arguments?(Rn.length=0,t!==void 0&&t.length>0&&Rn.push(...t),Rn.push(...this.arguments),i.call(this.target,...Rn),Rn.length=0):i.call(this.target,...t):this.arguments?this.target[this.methodName]=this.arguments[0]||t[0]:this.target[this.methodName]=t[0]}}}}const sM=s=>/^[A-Z]*$/.test(s);class ku extends Event{constructor(){super(...arguments),a(this,"args")}}class ke{constructor(t){if(a(this,"isEventList",!0),a(this,"target"),a(this,"key"),a(this,"_isInvoking",!1),a(this,"methods",[]),a(this,"_methodsCopy",[]),this.methods=[],Array.isArray(t))for(const i of t)i instanceof qs?this.methods.push(i):typeof i=="function"&&this.methods.push(new qs(i));else typeof t=="function"&&this.methods.push(new qs(t))}__internalOnInstantiate(t){var i;const n=new Array;for(let o=0;o<this.methods.length;o++){const r=this.methods[o];if(!(r.target instanceof Function)){const l=r.target;let c=l?.uuid;if(l&&(c=l.guid),c){const h=t[c];if(h){const d=(i=r.arguments)==null?void 0:i.map(u=>u instanceof Object&&u.uuid?t[u.uuid]:u!=null&&u.isComponent?t[u.guid]:u);n.push(new qs(h.clone,r.methodName,d,r.enabled))}else F()&&console.warn("Could not find target for event listener")}}}return new ke(n)}setEventTarget(t,i){if(this.key=t,this.target=i,this.key!==void 0){let n="",o=!1;for(const r of this.key)o&&sM(r)&&(n+="-"),o=!0,n+=r.toLowerCase();this.key=n}}get listenerCount(){var t;return((t=this.methods)==null?void 0:t.length)??0}get isInvoking(){return this._isInvoking}static from(...t){return new ke(t)}invoke(...t){var i;if(this._isInvoking)return console.warn("Circular event invocation detected. Please check your event listeners for circular references.",this),!1;if(((i=this.methods)==null?void 0:i.length)<=0)return!1;this._isInvoking=!0;try{this._methodsCopy.length=0,this._methodsCopy.push(...this.methods);for(const n of this._methodsCopy)n.invoke(...t);if(typeof this.target=="object"&&typeof this.key=="string"){const n=this.target.dispatchEvent;if(typeof n=="function"){const o=new ku(this.key);o.args=t,n.call(this.target,o)}}}finally{this._isInvoking=!1,this._methodsCopy.length=0}return!0}addEventListener(t){return this.methods.push(new qs(t)),t}removeEventListener(t){if(t)for(let i=this.methods.length-1;i>=0;i--)this.methods[i].target===t&&(this.methods[i].enabled=!1,this.methods.splice(i,1))}removeAllEventListeners(){this.methods.length=0}}class nM extends Ki{constructor(){super([ae,we],"ColorSerializer")}onDeserialize(t){if(t!=null)return t.a!==void 0?new we(t.r,t.g,t.b,t.a):t.alpha!==void 0?new we(t.r,t.g,t.b,t.alpha):new ae(t.r,t.g,t.b)}onSerialize(t){if(t!=null)return t.a!==void 0?{r:t.r,g:t.g,b:t.b,a:t.a}:{r:t.r,g:t.g,b:t.b}}}const oM=new nM;class rM extends Ki{constructor(){super([Ft],"EulerSerializer")}onDeserialize(t,i){if(t!=null){if(t.order)return new Ft(t.x,t.y,t.z,t.order);if(t.x!=null)return new Ft(t.x,t.y,t.z)}}onSerialize(t,i){return{x:t.x,y:t.y,z:t.z,order:t.order}}}const aM=new rM;class lM extends Ki{constructor(){super(j,"ObjectSerializer")}onSerialize(t,i){if(i.objectToNode!==void 0&&t.uuid){const n=i.objectToNode[t.uuid];return ft&&console.log(n,t.name,t.uuid),{node:n}}}onDeserialize(t,i){var n,o,r;if(typeof t=="string"){if(t.endsWith(".glb")||t.endsWith(".gltf")){if(i.serializable instanceof Array&&i.serializable.includes(le))return;F()&&_e("Detected wrong usage of @serializable with Object3D or GameObject. Instead you should use AssetReference here! Please see the console for details.");const l=(o=(n=i.target)==null?void 0:n.constructor)==null?void 0:o.name;console.warn(`Wrong usage of @serializable detected in your script "${l}"
908
+ `;var Wk=Object.defineProperty,Vk=Object.getOwnPropertyDescriptor,ff=(s,t,i,n)=>{for(var o=n>1?void 0:n?Vk(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&Wk(t,i,o),o};class Dr extends A{constructor(){super(...arguments),a(this,"constraintActive",!0),a(this,"locked",!1),a(this,"sources",[])}}ff([m()],Dr.prototype,"constraintActive",2),ff([m()],Dr.prototype,"locked",2),ff([m(j)],Dr.prototype,"sources",2);function Hk(s,t){return Cn(s,fe.ContextCreated,t),()=>po(s,fe.ContextCreated)}function $k(s,t){return Cn(s,fe.ContextClearing,t),()=>po(s,fe.ContextClearing)}function qk(s,t){return Cn(s,fe.ContextDestroying,t),()=>po(s,fe.ContextDestroying)}function Pw(s,t){return Cn(s,Ce.Start,t),()=>po(s,Ce.Start)}function kw(s,t){return Cn(s,Ce.Update,t),()=>po(s,Ce.Update)}function Gk(s,t){return Cn(s,Ce.OnBeforeRender,t),()=>po(s,Ce.OnBeforeRender)}function Xk(s,t){return Cn(s,Ce.OnAfterRender,t),()=>po(s,Ce.OnAfterRender)}let Br=class{constructor(){a(this,"bb",null),a(this,"bb_pos",0)}__init(s,t){return this.bb_pos=s,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(s,t,i,n){return s.prep(4,12),s.writeFloat32(n),s.writeFloat32(i),s.writeFloat32(t),s.offset()}};class Mw{constructor(){a(this,"bb",null),a(this,"bb_pos",0)}__init(t,i){return this.bb_pos=t,this.bb=i,this}position(t){return(t||new Br).__init(this.bb_pos,this.bb)}rotation(t){return(t||new Br).__init(this.bb_pos+12,this.bb)}scale(t){return(t||new Br).__init(this.bb_pos+24,this.bb)}static sizeOf(){return 36}static createTransform(t,i,n,o,r,l,c,h,d,u){return t.prep(4,36),t.prep(4,12),t.writeFloat32(u),t.writeFloat32(d),t.writeFloat32(h),t.prep(4,12),t.writeFloat32(c),t.writeFloat32(l),t.writeFloat32(r),t.prep(4,12),t.writeFloat32(o),t.writeFloat32(n),t.writeFloat32(i),t.offset()}}class eo{constructor(){a(this,"bb",null),a(this,"bb_pos",0)}__init(t,i){return this.bb_pos=t,this.bb=i,this}static getRootAsSyncedTransformModel(t,i){return(i||new eo).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsSyncedTransformModel(t,i){return t.setPosition(t.position()+fv),(i||new eo).__init(t.readInt32(t.position())+t.position(),t)}guid(t){const i=this.bb.__offset(this.bb_pos,4);return i?this.bb.__string(this.bb_pos+i,t):null}fast(){const t=this.bb.__offset(this.bb_pos,6);return t?!!this.bb.readInt8(this.bb_pos+t):!1}transform(t){const i=this.bb.__offset(this.bb_pos,8);return i?(t||new Mw).__init(this.bb_pos+i,this.bb):null}dontSave(){const t=this.bb.__offset(this.bb_pos,10);return t?!!this.bb.readInt8(this.bb_pos+t):!1}static startSyncedTransformModel(t){t.startObject(4)}static addGuid(t,i){t.addFieldOffset(0,i,0)}static addFast(t,i){t.addFieldInt8(1,+i,0)}static addTransform(t,i){t.addFieldStruct(2,i,0)}static addDontSave(t,i){t.addFieldInt8(3,+i,0)}static endSyncedTransformModel(t){return t.endObject()}static finishSyncedTransformModelBuffer(t,i){t.finish(i)}static finishSizePrefixedSyncedTransformModelBuffer(t,i){t.finish(i,void 0,!0)}}var B;(s=>{(t=>{t.MAYBEMODULE=null;const i=[];function n(){return t.MODULE?Promise.resolve(t.MODULE):new Promise(r=>{i.push(r)})}t.ready=n;async function o(){if(t.MODULE)return t.MODULE;const r=await import("./rapier.light.min.js");return t.MODULE=r,t.MAYBEMODULE=r,i.forEach(l=>l(r)),i.length=0,r}t.load=o})(s.RAPIER_PHYSICS||(s.RAPIER_PHYSICS={})),(t=>{t.MAYBEMODULE=null;const i=[];function n(){return t.MODULE?Promise.resolve(t.MODULE):new Promise(r=>{i.push(r)})}t.ready=n;async function o(){if(t.MODULE)return t.MODULE;const r=await import("./postprocessing.light.min.js").then(l=>l.i);return t.MODULE=r,t.MAYBEMODULE=r,i.forEach(l=>l(r)),i.length=0,r}t.load=o})(s.POSTPROCESSING||(s.POSTPROCESSING={})),(t=>{t.MAYBEMODULE=null;const i=[];function n(){return t.MODULE?Promise.resolve(t.MODULE):new Promise(r=>{i.push(r)})}t.ready=n;async function o(){if(t.MODULE)return t.MODULE;const r=await import("./postprocessing.light.min.js").then(l=>l.N);return t.MODULE=r,t.MAYBEMODULE=r,i.forEach(l=>l(r)),i.length=0,r}t.load=o})(s.POSTPROCESSING_AO||(s.POSTPROCESSING_AO={}))})(B||(B={}));var vt=(s=>(s[s.Average=0]="Average",s[s.Multiply=1]="Multiply",s[s.Minimum=2]="Minimum",s[s.Maximum=3]="Maximum",s))(vt||{}),Ou=(s=>(s[s.Discrete=0]="Discrete",s[s.Continuous=1]="Continuous",s))(Ou||{}),tt=(s=>(s[s.None=0]="None",s[s.FreezePositionX=2]="FreezePositionX",s[s.FreezePositionY=4]="FreezePositionY",s[s.FreezePositionZ=8]="FreezePositionZ",s[s.FreezePosition=14]="FreezePosition",s[s.FreezeRotationX=16]="FreezeRotationX",s[s.FreezeRotationY=32]="FreezeRotationY",s[s.FreezeRotationZ=64]="FreezeRotationZ",s[s.FreezeRotation=112]="FreezeRotation",s[s.FreezeAll=126]="FreezeAll",s))(tt||{}),qa=(s=>(s[s.None=0]="None",s[s.X=2]="X",s[s.Y=4]="Y",s[s.Z=8]="Z",s[s.All=-1]="All",s))(qa||{});const kt=function(s,t){return function(i,n,o){Qk(i,n,o,s,t)}};function Qk(s,t,i,n,o){if(!o&&!n&&!s.onValidate)return;if(i!==void 0){console.error("Invalid usage of validate decorator. Only fields can be validated.",s,t,i),Le("Invalid usage of validate decorator. Only fields can be validated. Property: "+t,xi.Error);return}let r="";if(typeof t=="string"?r=t:r=t.name,s.__internalAwake){const l=Symbol(r),c=s.__internalAwake;s.__internalAwake=function(){var h;if(!this.onValidate){F()&&console.warn('Usage of @validate decorate detected but there is no onValidate method in your class: "'+((h=s.constructor)==null?void 0:h.name)+'"');return}if(this[l]===void 0){this[l]=this[r];const d=this[r];if(d instanceof oe||d instanceof x||d instanceof me||d instanceof V){const u=this[r];fd(u,()=>{this.onValidate(r)})}Object.defineProperty(this,r,{set:function(u){var p;if(this[$g]===!0)this[l]=u;else{n?.call(this,u);const g=this[l];this[l]=u,(p=this.onValidate)==null||p.call(this,r,g)}},get:function(){return o?.call(this),this[l]}})}c.call(this)}}}const Yk=function(s){return function(t,i,n){let o="";typeof i=="string"?o=i:o=i.name;const r=s.prototype,l=Object.getOwnPropertyDescriptor(r,o);if(!(l!=null&&l.value)){console.warn("Can not apply prefix: type does not have method named",i,s);return}const c=l.value,h=t[o];Object.defineProperty(r,o,{value:function(...d){const u=h?.call(this,...d);if(u instanceof Promise){u.then(p=>{if(p!==!1)return c.call(this,...d)});return}if(u!==!1)return c.call(this,...d)}})}};var Kk=Object.defineProperty,Zk=Object.getOwnPropertyDescriptor,Ri=(s,t,i,n)=>{for(var o=n>1?void 0:n?Zk(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&Kk(t,i,o),o};class Jk{constructor(t,i){a(this,"positionChanged",!1),a(this,"rotationChanged",!1),a(this,"position"),a(this,"quaternion"),a(this,"_positionKeys",["x","y","z"]),a(this,"_quaternionKeys",["_x","_y","_z","_w"]),a(this,"mute",!1),a(this,"context"),a(this,"obj"),a(this,"_positionWatch"),a(this,"_rotationWatch"),this.context=i,this.obj=t}get isDirty(){return this.positionChanged||this.rotationChanged}reset(t=!1){if(this.positionChanged=!1,this.rotationChanged=!1,this.mute=!1,t){if(this.position)for(const i of this._positionKeys)delete this.position[i];if(this.quaternion)for(const i of this._quaternionKeys)delete this.quaternion[i]}}syncValues(){for(const t of this._positionKeys)this.position[t]=this.obj.position[t];for(const t of this._quaternionKeys)this.quaternion[t]=this.obj.quaternion[t]}applyValues(){if(this.positionChanged&&this.position)for(const t of this._positionKeys){const i=this.position[t];i!==void 0&&(this.obj.position[t]=i)}if(this.rotationChanged&&this.quaternion)for(const t of this._quaternionKeys){const i=this.quaternion[t];i!==void 0&&(this.obj.quaternion[t]=i)}}start(t,i){this.reset(),t&&(this._positionWatch||(this._positionWatch=new Jn(this.obj.position,["x","y","z"])),this._positionWatch.apply(),this.position={},this._positionWatch.subscribeWrite((r,l)=>{var c;if((c=this.context.physics.engine)!=null&&c.isUpdating||this.mute)return;const h=this.position[l];Math.abs(h-r)<1e-5||(this.position[l]=r,this.positionChanged=!0)})),i&&(this._rotationWatch||(this._rotationWatch=new Jn(this.obj.quaternion,["_x","_y","_z","_w"])),this._rotationWatch.apply(),this.quaternion={},this._rotationWatch.subscribeWrite((r,l)=>{var c;if((c=this.context.physics.engine)!=null&&c.isUpdating||this.mute)return;const h=this.quaternion[l];Math.abs(h-r)<1e-5||(this.quaternion[l]=r,this.rotationChanged=!0)}));const n=this.obj.matrixWorld.multiplyMatrices.bind(this.obj.matrixWorld),o=new ne;this.obj.matrixWorld.multiplyMatrices=(r,l)=>{var c;return(c=this.context.physics.engine)!=null&&c.isUpdating||this.mute||o.equals(r)||(this.positionChanged=!0,this.rotationChanged=!0,o.copy(r)),n(r,l)}}stop(){var t,i;(t=this._positionWatch)==null||t.revoke(),(i=this._rotationWatch)==null||i.revoke()}}var yf;const vf=(yf=class extends A{constructor(){super(...arguments),a(this,"autoMass",!0),a(this,"_mass",0),a(this,"useGravity",!0),a(this,"centerOfMass",new x(0,0,0)),a(this,"constraints",tt.None),a(this,"isKinematic",!1),a(this,"drag",0),a(this,"angularDrag",1),a(this,"detectCollisions",!0),a(this,"sleepThreshold",.01),a(this,"collisionDetectionMode",Ou.Discrete),a(this,"_gravityScale",1),a(this,"dominanceGroup",0),a(this,"_propertiesChanged",!1),a(this,"_currentVelocity",new x),a(this,"_smoothedVelocity",new x),a(this,"_smoothedVelocityGetter",new x),a(this,"_lastPosition",new x),a(this,"_watch")}get isRigidbody(){return!0}set mass(s){s!==this._mass&&(this._mass=s,this._propertiesChanged=!0,this.__didAwake&&(this.autoMass=!1))}get mass(){var s,t;return this.autoMass?((t=(s=this.context.physics.engine)==null?void 0:s.getBody(this))==null?void 0:t.mass())??-1:this._mass}get lockPositionX(){return(this.constraints&tt.FreezePositionX)!==0}get lockPositionY(){return(this.constraints&tt.FreezePositionY)!==0}get lockPositionZ(){return(this.constraints&tt.FreezePositionZ)!==0}get lockRotationX(){return(this.constraints&tt.FreezeRotationX)!==0}get lockRotationY(){return(this.constraints&tt.FreezeRotationY)!==0}get lockRotationZ(){return(this.constraints&tt.FreezeRotationZ)!==0}set lockPositionX(s){s?this.constraints|=tt.FreezePositionX:this.constraints&=~tt.FreezePositionX}set lockPositionY(s){s?this.constraints|=tt.FreezePositionY:this.constraints&=~tt.FreezePositionY}set lockPositionZ(s){s?this.constraints|=tt.FreezePositionZ:this.constraints&=~tt.FreezePositionZ}set lockRotationX(s){s?this.constraints|=tt.FreezeRotationX:this.constraints&=~tt.FreezeRotationX}set lockRotationY(s){s?this.constraints|=tt.FreezeRotationY:this.constraints&=~tt.FreezeRotationY}set lockRotationZ(s){s?this.constraints|=tt.FreezeRotationZ:this.constraints&=~tt.FreezeRotationZ}set gravityScale(s){this._gravityScale=s}get gravityScale(){return this._gravityScale}awake(){this._watch=void 0,this._propertiesChanged=!1}onEnable(){this._watch||(this._watch=new Jk(this.gameObject,this.context)),this._watch.start(!0,!0),this.startCoroutine(this.beforePhysics(),Ce.LateUpdate),F()&&(globalThis.false?B.RAPIER_PHYSICS.ready().then(async()=>{var s;await Xl(3),(s=this.context.physics.engine)!=null&&s.getBody(this)||console.warn(`Rigidbody could not be created. Ensure "${this.name}" has a Collider component.`)}):console.warn("Rigidbody could not be created: Rapier physics are explicitly disabled."))}onDisable(){var s,t;(s=this._watch)==null||s.stop(),(t=this.context.physics.engine)==null||t.removeBody(this)}onDestroy(){var s;(s=this.context.physics.engine)==null||s.removeBody(this)}onValidate(){this._propertiesChanged=!0}*beforePhysics(){for(var s,t,i,n;;)this._propertiesChanged&&(this._propertiesChanged=!1,(s=this.context.physics.engine)==null||s.updateProperties(this)),(t=this._watch)!=null&&t.isDirty?(this._watch.mute=!0,this._watch.applyValues(),(i=this.context.physics.engine)==null||i.updateBody(this,this._watch.positionChanged,this._watch.rotationChanged),this._watch.reset()):(n=this._watch)==null||n.syncValues(),this.captureVelocity(),yield}teleport(s,t=!0){var i;(i=this._watch)==null||i.reset(!0),t?this.gameObject.position.set(s.x,s.y,s.z):this.setWorldPosition(s.x,s.y,s.z),this.resetForcesAndTorques(),this.resetVelocities()}resetForces(s=!0){var t;(t=this.context.physics.engine)==null||t.resetForces(this,s)}resetTorques(s=!0){var t;(t=this.context.physics.engine)==null||t.resetTorques(this,s)}resetVelocities(){this.setVelocity(0,0,0),this.setAngularVelocity(0,0,0)}resetForcesAndTorques(){this.resetForces(),this.resetTorques()}wakeUp(){var s;(s=this.context.physics.engine)==null||s.wakeup(this)}get isSleeping(){var s;return(s=this.context.physics.engine)==null?void 0:s.isSleeping(this)}updateProperties(){var s;return this._propertiesChanged=!1,(s=this.context.physics.engine)==null?void 0:s.updateProperties(this)}applyForce(s,t,i=!0){var n;this._propertiesChanged&&this.updateProperties(),(n=this.context.physics.engine)==null||n.addForce(this,s,i)}applyImpulse(s,t=!0){var i;this._propertiesChanged&&this.updateProperties(),(i=this.context.physics.engine)==null||i.applyImpulse(this,s,t)}setForce(s,t,i,n=!0){var o,r,l;(o=this.context.physics.engine)==null||o.resetForces(this,n),typeof s=="number"?(t??(t=0),i??(i=0),(r=this.context.physics.engine)==null||r.addForce(this,{x:s,y:t,z:i},n)):(l=this.context.physics.engine)==null||l.addForce(this,s,n)}getVelocity(){var s;const t=(s=this.context.physics.engine)==null?void 0:s.getLinearVelocity(this);return t?(this._currentVelocity.x=t.x,this._currentVelocity.y=t.y,this._currentVelocity.z=t.z,this._currentVelocity):this._currentVelocity.set(0,0,0)}setVelocity(s,t,i,n=!0){var o,r;if(s instanceof x){const l=s;(o=this.context.physics.engine)==null||o.setLinearVelocity(this,l,n);return}t===void 0||i===void 0||(r=this.context.physics.engine)==null||r.setLinearVelocity(this,{x:s,y:t,z:i},n)}getAngularVelocity(){var s;const t=(s=this.context.physics.engine)==null?void 0:s.getAngularVelocity(this);return t?(this._currentVelocity.x=t.x,this._currentVelocity.y=t.y,this._currentVelocity.z=t.z,this._currentVelocity):this._currentVelocity.set(0,0,0)}setAngularVelocity(s,t,i,n=!0){var o,r;if(typeof s=="object"){const l=s;(o=this.context.physics.engine)==null||o.setAngularVelocity(this,l,n);return}if(t===void 0||i===void 0||typeof t=="boolean"){console.warn("setAngularVelocity expects either a Vec3 or 3 numbers");return}(r=this.context.physics.engine)==null||r.setAngularVelocity(this,{x:s,y:t,z:i},n)}setTorque(s,t,i){typeof s=="number"?this.setAngularVelocity(s,t,i):this.setAngularVelocity(s)}get smoothedVelocity(){return this._smoothedVelocityGetter.copy(this._smoothedVelocity),this._smoothedVelocityGetter.multiplyScalar(1/this.context.time.deltaTime)}setBodyFromGameObject(s=null){}captureVelocity(){const s=ee(this.gameObject);this.gameObject.matrixWorld.decompose(vf.tempPosition,eM,tM);const t=s.sub(this._lastPosition);this._lastPosition.copy(vf.tempPosition),this._smoothedVelocity.lerp(t,this.context.time.deltaTime/.1)}},a(yf,"tempPosition",new x),yf);let ye=vf;Ri([kt()],ye.prototype,"autoMass",2),Ri([m()],ye.prototype,"mass",1),Ri([kt(),m()],ye.prototype,"useGravity",2),Ri([m(x)],ye.prototype,"centerOfMass",2),Ri([kt(),m()],ye.prototype,"constraints",2),Ri([kt(),m()],ye.prototype,"isKinematic",2),Ri([kt(),m()],ye.prototype,"drag",2),Ri([kt(),m()],ye.prototype,"angularDrag",2),Ri([kt(),m()],ye.prototype,"detectCollisions",2),Ri([kt(),m()],ye.prototype,"sleepThreshold",2),Ri([kt(),m()],ye.prototype,"collisionDetectionMode",2),Ri([kt()],ye.prototype,"_gravityScale",2),Ri([kt()],ye.prototype,"dominanceGroup",2),new x;const eM=new V,tM=new x,Co=O("debugsync"),Lc="STRS";cg(Lc,eo.getRootAsSyncedTransformModel);const Hs=new Sm;function Rw(s,t,i=!0){Hs.clear();const n=Hs.createString(s);eo.startSyncedTransformModel(Hs),eo.addGuid(Hs,n),eo.addFast(Hs,i);const o=t.worldPosition,r=t.worldEuler,l=t.gameObject.scale;eo.addTransform(Hs,Mw.createTransform(Hs,o.x,o.y,o.z,r.x,r.y,r.z,l.x,l.y,l.z));const c=eo.endSyncedTransformModel(Hs);return Hs.finish(c,Lc),Hs.asUint8Array()}let bf=0,Dc=0;kw(s=>{var t;const i=(t=s.connection.currentServerUrl)!=null&&t.includes("glitch")?10:40;Dc=Math.floor(bf/i),bf=0,Co&&Dc>0&&console.log("Sync Transform Fast Interval",Dc)});class $s extends A{constructor(){super(...arguments),a(this,"overridePhysics",!0),a(this,"interpolatePosition",!0),a(this,"interpolateRotation",!0),a(this,"fastMode",!1),a(this,"syncDestroy",!1),a(this,"_model",null),a(this,"_needsUpdate",!0),a(this,"rb",null),a(this,"_wasKinematic",!1),a(this,"_receivedDataBefore",!1),a(this,"_targetPosition"),a(this,"_targetRotation"),a(this,"_receivedFastUpdate",!1),a(this,"_shouldRequestOwnership",!1),a(this,"joinedRoomCallback",null),a(this,"receivedDataCallback",null),a(this,"tempEuler",new Ft),a(this,"receivedUpdate",!1),a(this,"lastWorldPos"),a(this,"lastWorldRotation")}requestOwnership(){Co&&console.log("Request ownership"),this._model?this._model.requestOwnership():(this._shouldRequestOwnership=!0,this._needsUpdate=!0)}hasOwnership(){var t;return((t=this._model)==null?void 0:t.hasOwnership)??void 0}isOwned(){var t;return(t=this._model)==null?void 0:t.isOwned}awake(){Co&&console.log("new instance",this.guid,this),this._receivedDataBefore=!1,this._targetPosition=new x,this._targetRotation=new V,this.lastWorldPos=new x,this.lastWorldRotation=new V,this.rb=P.getComponentInChildren(this.gameObject,ye),this.rb&&(this._wasKinematic=this.rb.isKinematic),this.receivedUpdate=!0,this._model=new ug(this.context.connection,this.guid),this.context.connection.isConnected&&this.tryGetLastState(),this.joinedRoomCallback=this.tryGetLastState.bind(this),this.context.connection.beginListen(ie.JoinedRoom,this.joinedRoomCallback),this.receivedDataCallback=this.onReceivedData.bind(this),this.context.connection.beginListenBinary(Lc,this.receivedDataCallback)}onDestroy(){this.syncDestroy&&Dg(this.guid,this.context.connection),this._model=null,this.context.connection.stopListen(ie.JoinedRoom,this.joinedRoomCallback),this.context.connection.stopListenBinary(Lc,this.receivedDataCallback)}tryGetLastState(){const t=this.context.connection.tryGetState(this.guid);t&&this.onReceivedData(t)}onReceivedData(t){var i;if(!this.destroyed&&typeof t.guid=="function"&&t.guid()===this.guid){Co&&console.log("new data",this.context.connection.connectionId,this.context.time.frameCount,this.guid,t),this.receivedUpdate=!0,this._receivedFastUpdate=t.fast();const n=t.transform();if(n){cs.markDirty(this.gameObject,!0);const o=n.position();o&&(this.interpolatePosition&&((i=this._targetPosition)==null||i.set(o.x(),o.y(),o.z())),(!this.interpolatePosition||!this._receivedDataBefore)&&this.setWorldPosition(o.x(),o.y(),o.z()));const r=n.rotation();r&&(this.tempEuler.set(r.x(),r.y(),r.z()),this.interpolateRotation&&this._targetRotation.setFromEuler(this.tempEuler),(!this.interpolateRotation||!this._receivedDataBefore)&&Xm(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){Co&&console.log("no model or room",this.name,this.guid,this.context.connection.isInRoom);return}this._shouldRequestOwnership&&(this._shouldRequestOwnership=!1,this._model.requestOwnership());const t=this.worldPosition,i=this.worldQuaternion;if(this._model.isOwned&&!this.receivedUpdate){const r=t.distanceTo(this.lastWorldPos),l=i.angleTo(this.lastWorldRotation),c=this._model.hasOwnership||this.fastMode?1e-4:.001;(r>c||l>c)&&(this._model.hasOwnership?this._needsUpdate=!0:(Co&&console.log(this.guid,"reset because not owned but",this.gameObject.name,this.lastWorldPos),this.worldPosition=this.lastWorldPos,t.copy(this.lastWorldPos),this.worldQuaternion=this.lastWorldRotation,i.copy(this.lastWorldRotation),cs.markDirty(this.gameObject,!0),this._needsUpdate=!1))}if(this._model&&!this._model.hasOwnership&&this._model.isOwned&&this._receivedDataBefore){const r=this._receivedFastUpdate||this.fastMode?.5:.3;let l=!1;if(this.interpolatePosition&&this._targetPosition){const c=this.worldPosition;c.lerp(this._targetPosition,r),this.worldPosition=c,l=!0}if(this.interpolateRotation&&this._targetRotation){const c=this.worldQuaternion;c.slerp(this._targetRotation,r),this.worldQuaternion=c,l=!0}l&&cs.markDirty(this.gameObject,!0)}if(this.receivedUpdate=!1,this.lastWorldPos.copy(t),this.lastWorldRotation.copy(i),!this._model||!this._model||this._model.hasOwnership===void 0||!this._model.hasOwnership)return;this.rb&&this.overridePhysics&&this._wasKinematic!==void 0&&(Co&&console.log("reset kinematic",this.rb.name,this._wasKinematic),this.rb.isKinematic=this._wasKinematic);const n=10,o=this.rb||this.fastMode;if(this._needsUpdate&&(this.context.time.frameCount%n===0||o)){if(bf++,o&&Dc>0&&this.context.time.frameCount%Dc!==0)return;Co&&console.log("send update",this.context.connection.connectionId,this.guid,this.gameObject.name,this.gameObject.guid),this._needsUpdate=!1;const r=Rw(this.guid,this,!!o);this.context.connection.sendBinary(r)}}}const iM=O("debugshadowcomponents");bv.prototype.interactable={get(){return this.interactive},set(s){this.interactable=s}};const es=Symbol("shadowDomOwner");class ls extends A{constructor(){super(...arguments),a(this,"_shadowComponent",null),a(this,"_controlsChildLayout",!0),a(this,"_root"),a(this,"_parentComponent")}isRoot(){var t;return((t=this.Root)==null?void 0:t.gameObject)===this.gameObject}get canvas(){const t=this.Root;return t!=null&&t.isCanvas?t:null}get Canvas(){return this.canvas}markDirty(){ts.markUIDirty(this.context)}get shadowComponent(){return this._shadowComponent}set shadowComponent(t){this._shadowComponent=t}get controlsChildLayout(){return this._controlsChildLayout}set controlsChildLayout(t){this._controlsChildLayout=t,this.shadowComponent&&(this.shadowComponent.autoLayout=t)}get Root(){return this._root===void 0&&(this._root=P.getComponentInParent(this.gameObject,Bc)),this._root}__internalNewInstanceCreated(t){return super.__internalNewInstanceCreated(t),this.shadowComponent=null,this._root=void 0,this._parentComponent=void 0,this}onEnable(){super.onEnable()}addShadowComponent(t,i){var n;if(!t)return;this.removeShadowComponent();const o=this.isRoot()?this.gameObject:this.gameObject.parent;if(this._parentComponent=P.getComponentInParent(o,ls),!this._parentComponent){console.warn(`Component "${this.name}" doesn't have a UI parent anywhere. Do you have an UI element outside a Canvas? UI components must be a child of a Canvas component`,this);return}t.name=this.name+" ("+(this.constructor.name??"UI")+")",t.autoLayout=this._parentComponent.controlsChildLayout,t[es]=this,this.setShadowComponentOwner(t);let r=!1;if(((n=this.Root)==null?void 0:n.gameObject)===this.gameObject)this.gameObject.add(t);else{const l=this._parentComponent.shadowComponent;l&&(l?.add(t),r=!0)}this.shadowComponent=t,i&&i.shadowComponent&&this.shadowComponent&&i.shadowComponent.add(this.shadowComponent),vc&&t.add(new bi(.5)),this.onAfterAddedToScene(),r&&aO(),iM&&console.warn("Added shadow component",this.shadowComponent)}setShadowComponentOwner(t){if(t&&(t[es]===void 0||t[es]===this)&&(t[es]=this,t.children))for(const i of t.children)this.setShadowComponentOwner(i)}traverseOwnedShadowComponents(t,i,n){if(t&&t[es]===i){n(t);for(const o of t.children)this.traverseOwnedShadowComponents(o,i,n)}}removeShadowComponent(){this.shadowComponent&&this.shadowComponent.removeFromParent()}onAfterAddedToScene(){}setInteractable(t){this.shadowComponent&&(this.shadowComponent.interactable=t)}}class Bc extends ls{awake(){super.awake()}}class Fl{constructor(t,i){a(this,"event"),a(this,"button"),a(this,"buttonName"),a(this,"_used",!1),a(this,"_propagationStopped",!1),a(this,"z__pointer_ctured",!1),a(this,"z__pointer_cture_rleased",!1),a(this,"inputSource"),a(this,"object"),a(this,"point"),a(this,"normal"),a(this,"face"),a(this,"distance"),a(this,"instanceId"),a(this,"intersection"),a(this,"isDown"),a(this,"isUp"),a(this,"isPressed"),a(this,"isClick"),a(this,"isDoubleClick"),a(this,"input"),this.event=i,this.input=t,this.button=i.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())}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 t=new Fl(this.input,this.event);return Object.assign(t,this),t}Use(){this.use()}StopPropagation(){this.event.stopImmediatePropagation()}}function Pu(s,t){return P.foreachComponent(s,i=>{if(!i.enabled)return;const n=i;if(t)switch(t){case"pointerdown":if(n.onPointerDown)return!0;break;case"pointerup":if(n.onPointerUp||n.onPointerClick)return!0;break;case"pointermove":if(n.onPointerEnter||n.onPointerExit||n.onPointerMove)return!0;break}else if(n.onPointerDown||n.onPointerUp||n.onPointerEnter||n.onPointerExit||n.onPointerClick)return!0},!1)===!0}const Rn=new Array;class qs{constructor(t,i,n,o){a(this,"enabled",!0),a(this,"target"),a(this,"methodName"),a(this,"arguments"),this.target=t,this.methodName=i||null,this.arguments=n,o!=null&&(this.enabled=o)}get canClone(){return this.target instanceof Object}invoke(...t){if(this.enabled!==!1){if(typeof this.target=="function")this.arguments?(Rn.length=0,t!==void 0&&t.length>0&&Rn.push(...t),Rn.push(...this.arguments),this.target(...this.arguments),Rn.length=0):this.target(...t);else if(this.methodName!=null){const i=this.target[this.methodName];typeof i=="function"?this.arguments?(Rn.length=0,t!==void 0&&t.length>0&&Rn.push(...t),Rn.push(...this.arguments),i.call(this.target,...Rn),Rn.length=0):i.call(this.target,...t):this.arguments?this.target[this.methodName]=this.arguments[0]||t[0]:this.target[this.methodName]=t[0]}}}}const sM=s=>/^[A-Z]*$/.test(s);class ku extends Event{constructor(){super(...arguments),a(this,"args")}}class ke{constructor(t){if(a(this,"isEventList",!0),a(this,"target"),a(this,"key"),a(this,"_isInvoking",!1),a(this,"methods",[]),a(this,"_methodsCopy",[]),this.methods=[],Array.isArray(t))for(const i of t)i instanceof qs?this.methods.push(i):typeof i=="function"&&this.methods.push(new qs(i));else typeof t=="function"&&this.methods.push(new qs(t))}__internalOnInstantiate(t){var i;const n=new Array;for(let o=0;o<this.methods.length;o++){const r=this.methods[o];if(!(r.target instanceof Function)){const l=r.target;let c=l?.uuid;if(l&&(c=l.guid),c){const h=t[c];if(h){const d=(i=r.arguments)==null?void 0:i.map(u=>u instanceof Object&&u.uuid?t[u.uuid]:u!=null&&u.isComponent?t[u.guid]:u);n.push(new qs(h.clone,r.methodName,d,r.enabled))}else F()&&console.warn("Could not find target for event listener")}}}return new ke(n)}setEventTarget(t,i){if(this.key=t,this.target=i,this.key!==void 0){let n="",o=!1;for(const r of this.key)o&&sM(r)&&(n+="-"),o=!0,n+=r.toLowerCase();this.key=n}}get listenerCount(){var t;return((t=this.methods)==null?void 0:t.length)??0}get isInvoking(){return this._isInvoking}static from(...t){return new ke(t)}invoke(...t){var i;if(this._isInvoking)return console.warn("Circular event invocation detected. Please check your event listeners for circular references.",this),!1;if(((i=this.methods)==null?void 0:i.length)<=0)return!1;this._isInvoking=!0;try{this._methodsCopy.length=0,this._methodsCopy.push(...this.methods);for(const n of this._methodsCopy)n.invoke(...t);if(typeof this.target=="object"&&typeof this.key=="string"){const n=this.target.dispatchEvent;if(typeof n=="function"){const o=new ku(this.key);o.args=t,n.call(this.target,o)}}}finally{this._isInvoking=!1,this._methodsCopy.length=0}return!0}addEventListener(t){return this.methods.push(new qs(t)),t}removeEventListener(t){if(t)for(let i=this.methods.length-1;i>=0;i--)this.methods[i].target===t&&(this.methods[i].enabled=!1,this.methods.splice(i,1))}removeAllEventListeners(){this.methods.length=0}}class nM extends Ki{constructor(){super([ae,we],"ColorSerializer")}onDeserialize(t){if(t!=null)return t.a!==void 0?new we(t.r,t.g,t.b,t.a):t.alpha!==void 0?new we(t.r,t.g,t.b,t.alpha):new ae(t.r,t.g,t.b)}onSerialize(t){if(t!=null)return t.a!==void 0?{r:t.r,g:t.g,b:t.b,a:t.a}:{r:t.r,g:t.g,b:t.b}}}const oM=new nM;class rM extends Ki{constructor(){super([Ft],"EulerSerializer")}onDeserialize(t,i){if(t!=null){if(t.order)return new Ft(t.x,t.y,t.z,t.order);if(t.x!=null)return new Ft(t.x,t.y,t.z)}}onSerialize(t,i){return{x:t.x,y:t.y,z:t.z,order:t.order}}}const aM=new rM;class lM extends Ki{constructor(){super(j,"ObjectSerializer")}onSerialize(t,i){if(i.objectToNode!==void 0&&t.uuid){const n=i.objectToNode[t.uuid];return ft&&console.log(n,t.name,t.uuid),{node:n}}}onDeserialize(t,i){var n,o,r;if(typeof t=="string"){if(t.endsWith(".glb")||t.endsWith(".gltf")){if(i.serializable instanceof Array&&i.serializable.includes(le))return;F()&&_e("Detected wrong usage of @serializable with Object3D or GameObject. Instead you should use AssetReference here! Please see the console for details.");const l=(o=(n=i.target)==null?void 0:n.constructor)==null?void 0:o.name;console.warn(`Wrong usage of @serializable detected in your script "${l}"
909
909
 
910
910
  It looks like you used @serializable(Object3D) or @serializable(GameObject) for a prefab or scene reference which is exported to a separate glTF file.
911
911
 
@@ -935,8 +935,8 @@ Incoming:`,this._incomingCalls),r}else it&&console.error("Failed to make call",s
935
935
 
936
936
  Device: ${this._deviceMode}
937
937
 
938
- `,.03);const R=this._bottomCenter.clone(),M=this._backCenter.clone(),E=this._backBottomCenter.clone();i.localToWorld(R),i.localToWorld(M),i.localToWorld(E),q.DrawSphere(R,.01,65280,0,!1),q.DrawSphere(M,.01,255,0,!1),q.DrawSphere(E,.01,16711935,0,!1),q.DrawLine(R,E,65535,0,!1),q.DrawLine(E,M,65535,0,!1)}}onDragEnd(t){console.assert(this._followObject.parent===t.event.space,"Drag end: _followObject is not parented to the space object"),this._followObject.removeFromParent(),this._followObject.destroy(),this._lastDragPosRigSpace=void 0}setPlaneViewAligned(t,i){if(!this._followObject.parent)return!1;const n=this._followObject.parent.worldForward,o=$(0,1,0),r=n,l=o.angleTo(r),c=.5;return i&&(l>Math.PI/2+c||l<Math.PI/2-c)?this._dragPlane.setFromNormalAndCoplanarPoint(o,t):this._dragPlane.setFromNormalAndCoplanarPoint(n,t),!0}}const Kw=class{constructor(s){a(this,"showGizmo",!0),a(this,"useViewAngle",!0),a(this,"_selected",null),a(this,"_context",null),a(this,"_camera"),a(this,"_cameraPlane",new dr),a(this,"_hasGroundPlane",!1),a(this,"_groundPlane",new dr),a(this,"_groundOffset",new x),a(this,"_groundOffsetFactor",0),a(this,"_groundDistance",0),a(this,"_groundPlanePoint",new x),a(this,"_raycaster",new ld),a(this,"_cameraPlaneOffset",new x),a(this,"_intersection",new x),a(this,"_worldPosition",new x),a(this,"_inverseMatrix",new ne),a(this,"_rbs",[]),a(this,"_groundLine"),a(this,"_groundMarker"),a(this,"_groundOffsetVector",new x(0,1,0)),a(this,"_requireUpdateGroundPlane",!0),a(this,"_didDragOnGroundPlaneLastFrame",!1),this._camera=s;const t=new Vl(Kw.geometry),i=t.material;i.color=new ae(.4,.4,.4),t.layers.set(2),t.name="line",t.scale.y=1,this._groundLine=t;const n=new rd(.5,22,22),o=new Me({color:i.color}),r=new Q(n,o);r.visible=!1,r.layers.set(2),this._groundMarker=r}get hasSelected(){return this._selected!==null&&this._selected!==void 0}get selected(){return this._selected}setSelected(s,t){if(this._selected&&t)for(const i of this._rbs)i.wakeUp(),i.setVelocity(0,0,0);if(this._selected&&Xs.Remove(t,this._selected),this._selected=s,this._context=t,this._rbs.length=0,s?(t.scene.add(this._groundLine),t.scene.add(this._groundMarker)):(this._groundLine.removeFromParent(),this._groundMarker.removeFromParent()),this._selected){if(!t){console.error("DragHelper: no context");return}Xs.Add(t,this._selected,null),this._groundOffsetFactor=0,this._hasGroundPlane=!0,this._groundOffset.set(0,0,0),this._requireUpdateGroundPlane=!0,this.onUpdateScreenSpacePlane()}}onUpdate(s){this._selected}onUpdateWorldPosition(s,t,i){if(this._selected){if(i){const n=ee(this._selected);n.y=s.y,s=n}if(lt(this._selected,s),lt(this._groundLine,s),this._hasGroundPlane?this._groundLine.scale.y=this._groundDistance:this._groundLine.scale.y=1e3,this._groundLine.visible=this.showGizmo,this._groundMarker.visible=t!==null&&this.showGizmo,t){const n=ee(this._camera).distanceTo(t)*.01;this._groundMarker.scale.set(n,n,n),lt(this._groundMarker,t)}}}onUpdateScreenSpacePlane(){if(!this._selected||!this._context)return;const s=this._context.input.getPointerPositionRC(0);s&&(this._raycaster.setFromCamera(s,this._camera),this._cameraPlane.setFromNormalAndCoplanarPoint(this._camera.getWorldDirection(this._cameraPlane.normal),this._worldPosition.setFromMatrixPosition(this._selected.matrixWorld)),this._raycaster.ray.intersectPlane(this._cameraPlane,this._intersection)&&this._selected.parent&&(this._inverseMatrix.copy(this._selected.parent.matrixWorld).invert(),this._cameraPlaneOffset.copy(this._intersection).sub(this._worldPosition.setFromMatrixPosition(this._selected.matrixWorld))))}onUpdateGroundPlane(){if(!this._selected||!this._context)return;const s=ee(this._selected),t=new hr($(0,.1,0).add(s),$(0,-1,0)),i=new Ns;i.testObject=o=>o!==this._selected;const n=this._context.physics.raycastFromRay(t,i);for(let o=0;o<n.length;o++){const r=n[o];if(!r.face||this.contains(this._selected,r.object))continue;const l=$(0,1,0);this._groundPlane.setFromNormalAndCoplanarPoint(l,r.point);break}this._hasGroundPlane=!0,this._groundPlane.setFromNormalAndCoplanarPoint(t.direction.multiplyScalar(-1),t.origin),this._raycaster.ray.intersectPlane(this._groundPlane,this._intersection),this._groundDistance=this._intersection.distanceTo(s),this._groundOffset.copy(this._intersection).sub(s)}contains(s,t){if(s===t)return!0;if(s.children){for(const i of s.children)if(this.contains(i,t))return!0}return!1}};let hR=Kw;a(hR,"geometry",new oo().setFromPoints([new x(0,0,0),new x(0,-1,0)]));var Zw=(s=>(s.File_Spawned="file-spawned",s))(Zw||{});class dR{constructor(t,i,n,o,r,l,c,h,d){a(this,"guid"),a(this,"file_name"),a(this,"file_hash"),a(this,"file_size"),a(this,"position"),a(this,"scale"),a(this,"seed"),a(this,"sender"),a(this,"downloadUrl"),a(this,"parentGuid"),a(this,"boundsSize"),this.seed=i,this.guid=n,this.file_name=o,this.file_hash=r,this.file_size=l,this.position=c,this.scale=h,this.sender=t,this.downloadUrl=d}}var Ao;(s=>{const t=new Map;function i(o){var r;t.has(o.guid)&&n(o.guid);const l=new j;t.set(o.guid,l);const c=new j;c.position.y=-.5,l.add(c);const h=new Q(new Wl(1,1,1,1,1,1),new Me({color:14540253,wireframe:!0,transparent:!0,opacity:.3}));h.position.y=.5,c.add(h);const d=new j;c.add(d);const u=new Q(new Wl(1,1,1,1,1,1),new Me({color:12307660,transparent:!0,opacity:.4}));u.position.y=.5,d.scale.y=.01,d.add(u);const p=new Q(new Ds(1,1,1,1),new Me({color:34,transparent:!0,opacity:.05,depthTest:!1}));return p.rotateX(-Math.PI/2),p.position.y=.51,u.add(p),o.parent.add(l),l.rotateY(Math.PI/2),o.position&&((r=l.position)==null||r.copy(o.position)),o.size&&(l.worldScale=new x().copy(o.size)),l.position.y=l.scale.y/2,{object:l,onProgress:g=>{d instanceof j&&d.scale.set(1,g,1)}}}s.addPreview=i;function n(o){const r=t.get(o);r&&(t.delete(o),r.removeFromParent())}s.removePreview=n})(Ao||(Ao={}));var uR=Object.defineProperty,pR=Object.getOwnPropertyDescriptor,tl=(s,t,i,n)=>{for(var o=n>1?void 0:n?pR(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&uR(t,i,o),o};const Ps=O("debugdroplistener");class Wu extends CustomEvent{constructor(t){super("object-added",{detail:t})}}const mR="blob";class Dn extends A{constructor(){super(...arguments),a(this,"useNetworking",!0),a(this,"dropArea"),a(this,"fitIntoVolume",!1),a(this,"fitVolumeSize",new x(1,1,1)),a(this,"placeAtHitPosition",!0),a(this,"onDropped",new ke),a(this,"onNetworkEvent",t=>{var i;if(!this.useNetworking){Ps&&console.debug("[DropListener] Ignoring networked event because networking is disabled",t);return}if((i=t.guid)!=null&&i.startsWith(this.guid)){const n=t.url;if(console.debug("[DropListener] Received networked event",t),n)if(Array.isArray(n))for(const o of n)this.addFromUrl(o,{screenposition:new oe,point:t.point,size:t.size},!0);else this.addFromUrl(n,{screenposition:new oe,point:t.point,size:t.size},!0)}}),a(this,"handlePaste",t=>{this.context.connection.allowEditing===!1||t.defaultPrevented||navigator.clipboard.readText().then(i=>{if(i&&(i.startsWith("http")||i.startsWith("https")||i.startsWith("blob"))){const n={screenposition:new oe(this.context.input.mousePosition.x,this.context.input.mousePosition.y)};this.testIfIsInDropArea(n)&&this.addFromUrl(i,n,!1)}}).catch(console.warn)}),a(this,"onDrag",t=>{this.context.connection.allowEditing!==!1&&t.preventDefault()}),a(this,"onDrop",async t=>{if(this.context.connection.allowEditing===!1||(Ps&&console.log(t),!(t!=null&&t.dataTransfer))||t["droplistener:handled"])return;t.preventDefault();const i={screenposition:new oe(t.offsetX,t.offsetY)};if(this.dropArea&&this.testIfIsInDropArea(i)===!1)return;t["droplistener:handled"]=!0;const n=t.dataTransfer.items;if(!n)return;const o=[];for(const r in n){const l=n[r];if(l.kind==="file"){const c=l.getAsFile();if(!c)continue;o.push(c)}else l.kind==="string"&&l.type=="text/plain"&&l.getAsString(c=>{this.addFromUrl(c,i,!1)})}o.length>0&&await this.addDroppedFiles(o,i)}),a(this,"_abort",null),a(this,"_addedObjects",new Array),a(this,"_addedModels",new Array)}onEnable(){this.context.renderer.domElement.addEventListener("dragover",this.onDrag),this.context.renderer.domElement.addEventListener("drop",this.onDrop),window.addEventListener("paste",this.handlePaste),this.context.connection.beginListen("droplistener",this.onNetworkEvent)}onDisable(){this.context.renderer.domElement.removeEventListener("dragover",this.onDrag),this.context.renderer.domElement.removeEventListener("drop",this.onDrop),window.removeEventListener("paste",this.handlePaste),this.context.connection.stopListen("droplistener",this.onNetworkEvent)}loadFromURL(t,i){this.addFromUrl(t,{screenposition:new oe,point:i?.point,size:i?.size},!0)}forgetObjects(){this.removePreviouslyAddedObjects(!1)}async addFromUrl(t,i,n){Ps&&console.log("dropped url",t);try{if(t.startsWith("https://github.com/")){const l=t.split("/"),c=l[3],h=l[4],d=l[6],u=l.slice(7).join("/");t=`https://raw.githubusercontent.com/${c}/${h}/${d}/${u}`}else t.startsWith("https://polyhaven.com/a")&&(t=gR(t));if(!t)return null;const o=t.toLowerCase();if(o.endsWith(".hdr")||o.endsWith(".hdri")||o.endsWith(".exr")||o.endsWith(".png")||o.endsWith(".jpg")||o.endsWith(".jpeg"))return null;this.removePreviouslyAddedObjects();const r=await Vu.loadFileFromURL(new URL(t),{guid:this.guid,context:this.context,parent:this.gameObject,point:i.point,size:i.size});if(r&&this._addedObjects.length<=0)return i.url=t,this.addObject(r,i,n)}catch{console.warn("String is not a valid URL",t)}return null}async addDroppedFiles(t,i){var n,o;if(Ps&&console.log("Add files",t),!!Array.isArray(t)&&t.length){this.deleteDropEvent(),this.removePreviouslyAddedObjects(),ql(mR,null),(n=this._abort)==null||n.abort("New files dropped"),this._abort=new AbortController;for(const r of t){if(!r)continue;console.debug("Load file "+r.name);const l=await Vu.loadFile(r,this.context,{guid:this.guid});if(l){this.dispatchEvent(new CustomEvent("file-dropped",{detail:r})),i.file=r;const c=this.addObject(l,i,!1);c&&this.context.connection.isConnected&&this.useNetworking&&(console.debug("Uploading dropped file to blob storage"),Mr.upload(r,{abort:(o=this._abort)==null?void 0:o.signal}).then(h=>{h!=null&&h.download_url&&this._addedObjects.includes(c)&&this.sendDropEvent(h.download_url,c,l.contentMD5)}).catch(console.warn));break}}}}removePreviouslyAddedObjects(t=!0){if(t)for(const i of this._addedObjects)i.parent===this.gameObject&&Mi(i,!0,!0);this._addedObjects.length=0,this._addedModels.length=0}addObject(t,i,n){var o,r;const{model:l,contentMD5:c}=t;if(Ps&&console.log(`Dropped ${this.gameObject.name}`,l),!(l!=null&&l.scene))return console.warn("No object specified to add to scene",l),null;this.removePreviouslyAddedObjects();const h=l.scene;this.gameObject.attach(h),h.position.set(0,0,0),h.quaternion.identity(),this._addedObjects.push(h),this._addedModels.push(l);const d=new vi().setFromCenterAndSize(new x(0,this.fitVolumeSize.y*.5,0).add(this.gameObject.worldPosition),this.fitVolumeSize);if(Ps&&q.DrawWireBox3(d,255,5),this.fitIntoVolume&&tb(h,d,{position:!this.placeAtHitPosition}),this.placeAtHitPosition&&i&&i.screenposition){h.visible=!1;const p=this.context.physics.raycast({screenPoint:this.context.input.convertScreenspaceToRaycastSpace(i.screenposition.clone())});if(h.visible=!0,p&&p.length>0)for(const g of p){const y=g.point.clone();Ps&&console.log("Place object at hit",g),ib(h,y);break}}Na.assignAnimationsFromFile(l,{createAnimationComponent:p=>ki(p,Ut)});const u=new Wu({sender:this,gltf:l,model:l,object:h,contentMD5:c,dropped:i.file||(i.url?new URL(i.url):void 0)});return this.dispatchEvent(u),(o=this.onDropped)==null||o.invoke(u.detail),!n&&(r=i.url)!=null&&r.startsWith("http")&&this.context.connection.isConnected&&h&&this.sendDropEvent(i.url,h,c),h}async sendDropEvent(t,i,n){if(!this.useNetworking){Ps&&console.debug("[DropListener] Ignoring networked event because networking is disabled",t);return}if(this.context.connection.isConnected){console.debug('Sending drop event "'+i.name+'"',t);const o=Si([i]),r={name:i.name,guid:this.guid,url:t,point:i.worldPosition.clone(),size:o.getSize(new x),contentMD5:n};this.context.connection.send("droplistener",r)}}deleteDropEvent(){this.context.connection.sendDeleteRemoteState(this.guid)}testIfIsInDropArea(t){if(this.dropArea){const i=this.context.input.convertScreenspaceToRaycastSpace(t.screenposition.clone());if(!this.context.physics.raycast({targets:[this.dropArea],screenPoint:i,recursive:!0,testObject:n=>!this._addedObjects.includes(n)}).length)return F()&&console.log(`Dropped outside of drop area for DropListener "${this.name}".`),!1}return!0}}tl([m()],Dn.prototype,"useNetworking",2),tl([m(j)],Dn.prototype,"dropArea",2),tl([m()],Dn.prototype,"fitIntoVolume",2),tl([m(x)],Dn.prototype,"fitVolumeSize",2),tl([m()],Dn.prototype,"placeAtHitPosition",2),tl([m(ke)],Dn.prototype,"onDropped",2);function gR(s){if(!s.startsWith("https://polyhaven.com/"))return s;const t="https://dl.polyhaven.org/file/ph-assets/Models/gltf/4k/",i=new URL(s).pathname.split("/").pop(),n=`${t}${i}/${i}_4k.gltf`;return console.log("Resolved polyhaven asset url",s,"\u2192",n),n}var Vu;(s=>{async function t(n,o,r){const l=n.name.toLowerCase();return l.endsWith(".gltf")||l.endsWith(".glb")||l.endsWith(".fbx")||l.endsWith(".obj")||l.endsWith(".usdz")||l.endsWith(".vrm")||n.type==="model/gltf+json"||n.type==="model/gltf-binary"?new Promise((c,h)=>{const d=new FileReader;d.readAsArrayBuffer(n),d.onloadend=async u=>{const p=d.result,g=r.guid,y=new Bt(g),f=await ms().parseSync(o,p,n.name,y);if(f){const v=Mr.hashMD5(p);c({model:f,contentMD5:v})}}}):(console.warn("Unsupported file type: "+l,n.type),null)}s.loadFile=t;async function i(n,o){return new Promise(async(r,l)=>{const c=new Bt(o.guid),h=n.toString();Ps&&q.DrawWireSphere(o.point,.1,16711680,3);const d=Ao.addPreview({guid:o.guid,parent:o.parent,position:o?.point,size:o?.size}),u=await ms().loadSync(o.context,h,h,c,p=>{d.onProgress(p.loaded/p.total)}).catch(console.warn);if(u){const p=await fetch(h).then(y=>y.arrayBuffer()),g=Mr.hashMD5(p);Ps?setTimeout(()=>Ao.removePreview(o.guid),3e3):Ao.removePreview(o.guid),r({model:u,contentMD5:g})}else Ps?setTimeout(()=>Ao.removePreview(o.guid),3e3):Ao.removePreview(o.guid),console.warn("Unsupported file type: "+n.toString())})}s.loadFileFromURL=i})(Vu||(Vu={}));var fR=Object.defineProperty,yR=Object.getOwnPropertyDescriptor,Hu=(s,t,i,n)=>{for(var o=n>1?void 0:n?yR(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&fR(t,i,o),o};const Jw=class extends A{constructor(){super(...arguments),a(this,"parent",null),a(this,"object",null),a(this,"limitCount",10),a(this,"limitInterval",60),a(this,"_currentCount",0),a(this,"_startPosition",null),a(this,"_startQuaternion",null),a(this,"_forwardPointerEvents",new Map)}start(){var s,t;if(this._currentCount=0,this._startPosition=null,this._startQuaternion=null,this.object||(this.object=this.gameObject),this.object){if(this.object===this.gameObject){const n=new Bt(this.guid);this.object=P.instantiate(this.object,{idProvider:n,keepWorldPosition:!1});const o=P.getComponent(this.object,Jw);o?.destroy();let r=this.object.getComponentInChildren(di);r||(r=this.object.addComponent(di,{dragMode:zf.SnapToSurfaces}),r.guid=n.generateUUID());let l=P.getComponent(r.gameObject,$s);l||(l=r.gameObject.addComponent($s),l.guid=n.generateUUID())}this.object.visible=!1;const i=this.gameObject.getComponent(di);i&&(i.enabled=!1),this._startPosition=((s=this.object.position)==null?void 0:s.clone())??new x(0,0,0),this._startQuaternion=((t=this.object.quaternion)==null?void 0:t.clone())??new V(0,0,0,1)}this.gameObject.getComponentInParent(Ti)||this.gameObject.addComponent(Ti),this.cloneLimitIntervalFn()}onPointerEnter(s){s.used||this.object&&this.context.connection.allowEditing&&s.button===0&&this.context.input.setCursorPointer()}onPointerExit(s){s.used||this.object&&this.context.connection.allowEditing&&s.button===0&&this.context.input.setCursorNormal()}onPointerDown(s){if(s.used||!this.object||!this.context.connection.allowEditing||s.button!==0)return;const t=this.handleDuplication();if(t){const i=P.getComponent(t,di);i?(i.onPointerDown(s),this._forwardPointerEvents.set(s.event.space,i)):console.warn("Duplicated object does not have DragControls",t)}else console.warn("Could not duplicate object. Has the target object been destroyed?",this)}onPointerUp(s){if(s.used)return;const t=this._forwardPointerEvents.get(s.event.space);t&&(t.onPointerUp(s),this._forwardPointerEvents.delete(s.event.space))}cloneLimitIntervalFn(){this.destroyed||(this._currentCount>0&&(this._currentCount-=1),setTimeout(()=>{this.cloneLimitIntervalFn()},this.limitInterval/this.limitCount*1e3))}handleDuplication(){var s;if(!this.object||this._currentCount>=this.limitCount||this.object===this.gameObject)return null;if(P.isDestroyed(this.object))return this.object=null,null;this.object.visible=!0,this._startPosition&&this.object.position.copy(this._startPosition),this._startQuaternion&&this.object.quaternion.copy(this._startQuaternion);const t=new js;this.parent||(this.parent=this.gameObject.parent),this.parent&&(t.parent=this.parent.guid??((s=this.parent.userData)==null?void 0:s.guid),t.keepWorldPosition=!0),t.position=this.worldPosition,t.rotation=this.worldQuaternion,t.context=this.context,this._currentCount+=1;const i=P.instantiateSynced(this.object,t);return console.assert(i!==this.object,"Duplicated object is original"),this.object.visible=!1,this._startPosition&&this.object.position.clone().copy(this._startPosition),this._startQuaternion&&this.object.quaternion.clone().copy(this._startQuaternion),i}};let Nr=Jw;Hu([m(j)],Nr.prototype,"parent",2),Hu([m(j)],Nr.prototype,"object",2),Hu([m()],Nr.prototype,"limitCount",2),Hu([m()],Nr.prototype,"limitInterval",2);var il=(s=>(s[s.PointerEnter=0]="PointerEnter",s[s.PointerExit=1]="PointerExit",s[s.PointerDown=2]="PointerDown",s[s.PointerUp=3]="PointerUp",s[s.PointerClick=4]="PointerClick",s[s.Drag=5]="Drag",s[s.Drop=6]="Drop",s[s.Scroll=7]="Scroll",s[s.UpdateSelected=8]="UpdateSelected",s[s.Select=9]="Select",s[s.Deselect=10]="Deselect",s[s.Move=11]="Move",s[s.InitializePotentialDrag=12]="InitializePotentialDrag",s[s.BeginDrag=13]="BeginDrag",s[s.EndDrag=14]="EndDrag",s[s.Submit=15]="Submit",s[s.Cancel=16]="Cancel",s))(il||{}),vR=Object.defineProperty,bR=Object.getOwnPropertyDescriptor,Uf=(s,t,i,n)=>{for(var o=n>1?void 0:n?bR(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&vR(t,i,o),o};class Nf{constructor(){a(this,"eventID"),a(this,"callback",new ke)}}Uf([m()],Nf.prototype,"eventID",2),Uf([m(ke)],Nf.prototype,"callback",2);class $u extends A{constructor(){super(...arguments),a(this,"triggers",[])}invoke(t){var i;if(this.triggers)for(const n of this.triggers)n.eventID===t&&((i=n.callback)==null||i.invoke())}onPointerClick(t){this.invoke(il.PointerClick)}onPointerEnter(t){this.invoke(il.PointerEnter)}onPointerExit(t){this.invoke(il.PointerExit)}onPointerDown(t){this.invoke(il.PointerDown)}onPointerUp(t){this.invoke(il.PointerUp)}}Uf([m(Nf)],$u.prototype,"triggers",2);class ex{constructor(t){a(this,"writer"),this.writer=t}writeNode(t){}}class _R extends ex{beforeWriteNode(t,i){q.isGizmo(t)&&(i.keep=!1)}}class tx extends ex{beforeWriteTexture(t,i){t.isRenderTargetTexture&&(i.newTexture=Zg(new we(1,1,1,0)))}}function Wf(s){const t=Bu.DontExport;return!(s.hideFlags&t)}const Vf=O("debugexr");class wR{constructor(t){a(this,"parser"),this.parser=t,Vf&&console.log(t)}get name(){return"EXT_texture_exr"}loadTexture(t){const i=this.name,n=this.parser,o=n.json.textures[t];if(Vf&&console.log("EXT_texture_exr.loadTexture",t,o),!o.extensions||!o.extensions[i])return null;const r=o.extensions[i],l=new md(n.options.manager);return Vf&&console.log("EXT_texture_exr.loadTexture",r),n.loadTextureImage(t,r.source,l)}}typeof window<"u"&&window.addEventListener("unhandledrejection",s=>{});const Bn=ft,qu="$___Export_Components",xR="NEEDLE_components";var ix;class SR{constructor(){a(this,ix)}}ix=br;class CR{constructor(t,i,n){a(this,"node"),a(this,"nodeIndex"),a(this,"nodeDef"),this.node=t,this.nodeIndex=i,this.nodeDef=n}}class sx{constructor(){a(this,"parser"),a(this,"nodeToObjectMap",{}),a(this,"gltf",null),a(this,"exportContext"),a(this,"objectToNodeMap",{}),a(this,"context"),a(this,"writer")}get name(){return xR}registerExport(t){t.register(i=>{if("serializeUserData"in i){const n=i.serializeUserData.bind(i);this.writer=i,i.serializeUserData=(o,r)=>{try{this.serializeUserData(o,r)&&(i.extensionsUsed[this.name]=!0),n(o,r)}finally{this.afterSerializeUserData(o,r)}}}return this})}beforeParse(){this.exportContext={},this.objectToNodeMap={}}serializeUserData(t,i){var n;const o=(n=t.userData)==null?void 0:n.components;return!o||o.length<=0?!1:(delete t.userData.components,t[qu]=o,!0)}afterSerializeUserData(t,i){if(t.type==="Scene"&&Bn&&console.log("DONE",JSON.stringify(i)),t[qu]===void 0)return;const n=t[qu];delete t[qu],n!==null&&(t.userData.components=n)}writeNode(t,i){const n=this.writer.json.nodes.length;Bn&&console.log(t.name,n,t.uuid);const o=new CR(t,n,i);this.exportContext[n]=o,this.objectToNodeMap[t.uuid]=n}afterParse(t){var i;Bn&&console.log("AFTER",t);for(const n in this.exportContext){const o=this.exportContext[n],r=o.node,l=o.nodeDef,c=o.nodeIndex,h=(i=r.userData)==null?void 0:i.components;if(!h||h.length<=0)continue;const d=new SR;l.extensions=l.extensions||{},l.extensions[this.name]=d,this.context.object=r,this.context.nodeId=c,this.context.objectToNode=this.objectToNodeMap;const u=[];for(const p of h){this.context.target=p;const g=ms().writeBuiltinComponentData(p,this.context);g!==null&&u.push(g)}u.length>0&&(d[br]=u,Bn&&console.log("DID WRITE",r,"nodeIndex",c,u))}}beforeRoot(){return Bn&&console.log("BEGIN LOAD"),this.nodeToObjectMap={},null}async afterRoot(t){this.gltf=t;const i=t.parser,n=i?.extensions;if(!n)return;const o=n[this.name];Bn&&console.log("After root",t,this.parser,n);const r=[];if(o===!0){const l=i.json.nodes;if(l){for(let c=0;c<l.length;c++){const h=await i.getDependency("node",c);this.nodeToObjectMap[c]=h}for(let c=0;c<l.length;c++){const h=l[c],d=c,u=h.extensions;if(!u)continue;const p=u[this.name];if(!p)continue;Bn&&console.log("NODE",h);const g=this.nodeToObjectMap[d];if(!g){console.error("Could not find object for node index: "+d,h,i);continue}Xd(g),r.push(this.createComponents(g,p))}}}await Promise.all(r);for(const l of i.associations.keys()){const c=i.associations.get(l);if(c?.materials!=null){const h="/materials/"+c.materials;Ok(l,h)}}}async createComponents(t,i){if(!i)return;const n=i[br];if(n){const o=new Array;Bn&&console.log(t.name,n);for(const r in n){const l=n[r];Bn&&console.log("Serialized data",JSON.parse(JSON.stringify(l))),l&&this.parser&&o.push(Ug(this.parser,l).catch(c=>console.error(`Error while resolving references (see console for details)
939
- `,c,t,l))),t.userData=t.userData||{},t.userData[br]=t.userData[br]||[],t.userData[br].push(l)}await Promise.all(o).catch(r=>{console.error("Error while loading components",r)})}}}const nx="NEEDLE_gameobject_data";class OR{constructor(t){a(this,"parser"),this.parser=t}get name(){return nx}afterRoot(t){var i;const n=[];for(let o=0;o<((i=this.parser.json.nodes)==null?void 0:i.length);o++){const r=this.parser.json.nodes[o];if(r&&r.extensions){const l=r.extensions[nx];if(l){const c=this.findAndApplyExtensionData(o,l);n.push(c)}}}return Promise.all(n).then(()=>null)}async findAndApplyExtensionData(t,i){const n=await this.parser.getDependency("node",t);n&&this.applyExtensionData(n,i)}applyExtensionData(t,i){i.layers===void 0&&(i.layers=0),t.userData.layer=i.layers,t.layers.disableAll(),t.layers.set(i.layers),t.userData.tag=i.tag??"none",t.hideFlags=0,t.userData.static=i.static??!1,t.visible=i.activeSelf??!0,t.guid=i.guid}}const ox="NEEDLE_lighting_settings",sl=O("debugenvlight");class PR{constructor(t,i,n){a(this,"parser"),a(this,"sourceId"),a(this,"context"),this.parser=t,this.sourceId=i,this.context=n}get name(){return ox}afterRoot(t){const i=this.parser.json.extensions;if(i){const n=i[ox];if(n){sl&&console.log('Loaded "'+this.name+'", src: "'+this.sourceId+'"',n);let o;if(t.scene.children.length===1){const r=t.scene.children[0];o=P.addComponent(r,Gu,{},{callAwake:!1})}else{const r=new j;r.name="LightSettings "+this.sourceId,t.scene.add(r),o=P.addComponent(r,Gu,{},{callAwake:!1})}o.sourceId=this.sourceId,o.ambientIntensity=n.ambientIntensity,o.ambientLight=new ae().fromArray(n.ambientLight),Array.isArray(n.ambientTrilight)&&(o.ambientTrilight=n.ambientTrilight.map(r=>new ae().fromArray(r))),o.ambientMode=n.ambientMode,o.environmentReflectionSource=n.environmentReflectionSource}}return null}}ge.registerCallback(fe.ContextCreated,s=>{const t=s.context,i=P.findObjectOfType(Gu,t);i!=null&&i.sourceId&&(i.enabled=!0)});class Gu extends A{constructor(){super(...arguments),a(this,"ambientMode",Va.Skybox),a(this,"ambientLight"),a(this,"ambientTrilight"),a(this,"ambientIntensity",1),a(this,"environmentReflectionSource",hu.Skybox),a(this,"_hasReflection",!1),a(this,"_ambientLightObj"),a(this,"_hemisphereLightObj")}awake(){var t;if(this.sourceId){const n=this.environmentReflectionSource===hu.Skybox?yo.Skybox:yo.Reflection,o=this.context.lightmaps.tryGet(this.sourceId,n,0);this._hasReflection=o!=null,o&&this.context.sceneLighting.internalRegisterReflection(this.sourceId,o)}this.enabled=!1,this.context.sceneLighting.internalRegisterSceneLightSettings(this),sl&&window.addEventListener("keydown",n=>{if(!this.destroyed)switch(n.key){case"l":this.enabled=!this.enabled;break}});const i=(t=this.gameObject.userData)==null?void 0:t.components;if(i){const n=i.indexOf(this);i.splice(n,1),i.push(this)}}onDestroy(){this.context.sceneLighting.internalUnregisterSceneLightSettings(this)}calculateIntensityFactor(t){const i=Math.max(t.r,t.g,t.b);return 2.2*W.lerp(0,1.33,i)}onEnable(){if(sl&&console.warn("\u{1F4A1}\u{1F7E1} >>> Enable lighting",this.sourceId,this.enabled,this),this.ambientMode==Va.Flat){if(this.ambientLight&&!this._ambientLightObj){const t=this.calculateIntensityFactor(this.ambientLight);this._ambientLightObj=new jS(this.ambientLight,this.ambientIntensity*t),sl&&console.log("Created ambient light",this.sourceId,this._ambientLightObj,this.ambientIntensity,t)}this._ambientLightObj&&this.gameObject.add(this._ambientLightObj)}else if(this.ambientMode===Va.Trilight){if(this.ambientTrilight){const t=this.ambientTrilight[0],i=this.ambientTrilight[this.ambientTrilight.length-1],n=this.calculateIntensityFactor(i);this._hemisphereLightObj=new LS(i,t,this.ambientIntensity*n),this.gameObject.add(this._hemisphereLightObj),sl&&console.log("Created hemisphere ambient light",this.sourceId,this._hemisphereLightObj,this.ambientIntensity,n)}}else this._ambientLightObj&&this._ambientLightObj.removeFromParent(),this._hemisphereLightObj&&this._hemisphereLightObj.removeFromParent();this.sourceId&&this.context.sceneLighting.internalEnableReflection(this.sourceId)}onDisable(){sl&&console.warn("\u{1F4A1}\u26AB <<< Disable lighting:",this.sourceId,this),this._ambientLightObj&&this._ambientLightObj.removeFromParent(),this._hemisphereLightObj&&this._hemisphereLightObj.removeFromParent(),this.sourceId&&this.context.sceneLighting.internalDisableReflection(this.sourceId)}}const Hf=O("debugstencil");function kR(s,t){return(s&1<<t.layer)!=0}const MR=Symbol("stencils"),nl=class{constructor(s,t){a(this,"parser"),a(this,"source"),this.parser=s,this.source=t}get name(){return"NEEDLE_render_objects"}static applyStencil(s){if(!s)return;const t=s.sourceId;if(Hf&&console.log(t,nl.stencils),!t)return;const i=nl.stencils[t];if(i)for(let n=i.length-1;n>=0;n--){const o=i[n];if(kR(o.layer,s)){Hf&&console.log(o),setTimeout(()=>{Gt()&&Kd(s.gameObject)&&(_e("Stencil not supported on instanced objects"),console.warn("Stencil not supported on instanced objects",s))},500);for(let r=0;r<s.sharedMaterials.length;r++){let l=s.sharedMaterials[r];l&&(l=l.clone(),l[MR]=!0,l.stencilWrite=!0,l.stencilWriteMask=255,l.stencilFuncMask=255,l.stencilRef=o.value,l.stencilFunc=o.compareFunc,l.stencilZPass=o.passOp,l.stencilFail=o.failOp,l.stencilZFail=o.zFailOp,s.sharedMaterials[r]=l)}s.gameObject.renderOrder=o.event*1e3+o.index*50;break}}}afterRoot(s){const t=this.parser.json.extensions;if(t){const i=t[TR];if(i){Hf&&console.log(i);const n=i.stencil;if(n&&Array.isArray(n))for(const o of n){const r={...o};r.compareFunc=RR(r.compareFunc),r.passOp=qf(r.passOp),r.failOp=qf(r.failOp),r.zFailOp=qf(r.zFailOp),nl.stencils[this.source]||(nl.stencils[this.source]=[]),nl.stencils[this.source].push(r)}}}return null}};let $f=nl;a($f,"stencils",{});function qf(s){switch(s){case 0:return VS;case 1:return WS;case 2:return NS;case 3:return US;case 4:return zS;case 6:return FS;case 7:return BS;case 5:return DS}return 0}function RR(s){switch(s){case 1:return ev;case 2:return YS;case 3:return QS;case 4:return XS;case 5:return GS;case 6:return qS;case 7:return $S;case 8:return HS}return ev}const TR="NEEDLE_render_objects";var rx=(s=>(s[s.INT=5124]="INT",s[s.FLOAT=5126]="FLOAT",s[s.FLOAT_VEC2=35664]="FLOAT_VEC2",s[s.FLOAT_VEC3=35665]="FLOAT_VEC3",s[s.FLOAT_VEC4=35666]="FLOAT_VEC4",s[s.INT_VEC2=35667]="INT_VEC2",s[s.INT_VEC3=35668]="INT_VEC3",s[s.INT_VEC4=35669]="INT_VEC4",s[s.BOOL=35670]="BOOL",s[s.BOOL_VEC2=35671]="BOOL_VEC2",s[s.BOOL_VEC3=35672]="BOOL_VEC3",s[s.BOOL_VEC4=35673]="BOOL_VEC4",s[s.FLOAT_MAT2=35674]="FLOAT_MAT2",s[s.FLOAT_MAT3=35675]="FLOAT_MAT3",s[s.FLOAT_MAT4=35676]="FLOAT_MAT4",s[s.SAMPLER_2D=35678]="SAMPLER_2D",s[s.SAMPLER_3D=35680]="SAMPLER_3D",s[s.SAMPLER_CUBE=35681]="SAMPLER_CUBE",s[s.UNKNOWN=0]="UNKNOWN",s))(rx||{});const en=O("debugcustomshader"),ol="NEEDLE_techniques_webgl";class ER{constructor(){a(this,"objectToWorldMatrix",new ne),a(this,"worldToObjectMatrix",new ne),a(this,"objectToWorld",new Array),a(this,"worldToObject",new Array)}updateFrom(t){this.objectToWorldMatrix.copy(t.matrixWorld),cu(this.objectToWorldMatrix,this.objectToWorld),this.worldToObjectMatrix.copy(t.matrixWorld).invert(),cu(this.worldToObjectMatrix,this.worldToObject)}}const Ve=class extends tv{constructor(s,...t){super(...t),a(this,"identifier"),a(this,"onBeforeRenderSceneCallback",this.onBeforeRenderScene.bind(this)),a(this,"_sphericalHarmonicsName","unity_SpecCube0"),a(this,"_objToWorldName","hlslcc_mtx4x4unity_ObjectToWorld"),a(this,"_worldToObjectName","hlslcc_mtx4x4unity_WorldToObject"),a(this,"_viewProjectionName","hlslcc_mtx4x4unity_MatrixVP"),a(this,"_viewMatrixName","hlslcc_mtx4x4unity_MatrixV"),a(this,"_rendererData",new ER),this.identifier=s,en&&console.log(this),this.type="NEEDLE_CUSTOM_SHADER",this.uniforms[this._objToWorldName]||(this.uniforms[this._objToWorldName]={value:[]}),this.uniforms[this._worldToObjectName]||(this.uniforms[this._worldToObjectName]={value:[]}),this.uniforms[this._viewProjectionName]||(this.uniforms[this._viewProjectionName]={value:[]}),this.uniforms[this._sphericalHarmonicsName],(this.depthTextureUniform||this.opaqueTextureUniform)&&te.Current.pre_render_callbacks.push(this.onBeforeRenderSceneCallback)}clone(){const s=super.clone();return ax(s),s}dispose(){super.dispose();const s=te.Current.pre_render_callbacks.indexOf(this.onBeforeRenderSceneCallback);s>=0&&te.Current.pre_render_callbacks.splice(s,1)}get depthTextureUniform(){if(this.uniforms)return this.uniforms._CameraDepthTexture}get opaqueTextureUniform(){if(this.uniforms)return this.uniforms._CameraOpaqueTexture}onBeforeRenderScene(){this.opaqueTextureUniform&&te.Current.setRequireColor(!0),this.depthTextureUniform&&te.Current.setRequireDepth(!0)}onBeforeRender(s,t,i,n,o,r){n.attributes.tangent||n.computeTangents(),this.onUpdateUniforms(i,o)}onUpdateUniforms(s,t){const i=te.Current;if(s&&(Ve.viewProjection&&this.uniforms[this._viewProjectionName]&&(Ve.viewProjection.copy(s.projectionMatrix).multiply(s.matrixWorldInverse),cu(Ve.viewProjection,Ve._viewProjectionValues)),Ve.viewMatrix&&this.uniforms[this._viewMatrixName]&&(Ve.viewMatrix.copy(s.matrixWorldInverse),cu(Ve.viewMatrix,Ve._viewMatrixValues)),this.uniforms[Ve._worldSpaceCameraPosName]&&Ve._worldSpaceCameraPos.setFromMatrixPosition(s.matrixWorld)),this.uniforms._TimeParameters&&(this.uniforms._TimeParameters.value=i.sceneLighting.timeVec4),this.uniforms._Time){const l=this.uniforms._Time.value;l.x=i.sceneLighting.timeVec4.x/20,l.y=i.sceneLighting.timeVec4.x,l.z=i.sceneLighting.timeVec4.x*2,l.w=i.sceneLighting.timeVec4.x*3}if(this.uniforms._SinTime){const l=this.uniforms._SinTime.value;l.x=Math.sin(i.sceneLighting.timeVec4.x/8),l.y=Math.sin(i.sceneLighting.timeVec4.x/4),l.z=Math.sin(i.sceneLighting.timeVec4.x/2),l.w=Math.sin(i.sceneLighting.timeVec4.x)}if(this.uniforms._CosTime){const l=this.uniforms._CosTime.value;l.x=Math.cos(i.sceneLighting.timeVec4.x/8),l.y=Math.cos(i.sceneLighting.timeVec4.x/4),l.z=Math.cos(i.sceneLighting.timeVec4.x/2),l.w=Math.cos(i.sceneLighting.timeVec4.x)}if(this.uniforms.unity_DeltaTime){const l=this.uniforms.unity_DeltaTime.value;l.x=i.time.deltaTime,l.y=1/i.time.deltaTime,l.z=i.time.smoothedDeltaTime,l.w=1/i.time.smoothedDeltaTime}const n=i.mainLight;if(n){const l=ee(n.gameObject,Ve._mainLightPosition);this.uniforms._MainLightPosition={value:l.normalize()},Ve._mainLightColor.set(n.color.r,n.color.g,n.color.b,0),this.uniforms._MainLightColor={value:Ve._mainLightColor};const c=n.intensity;Ve._lightData.z=c,this.uniforms.unity_LightData={value:Ve._lightData}}if(s&&(Ve.viewProjection&&this.uniforms[this._viewProjectionName]&&(this.uniforms[this._viewProjectionName].value=Ve._viewProjectionValues),Ve.viewMatrix&&this.uniforms[this._viewMatrixName]&&(this.uniforms[this._viewMatrixName].value=Ve._viewMatrixValues),this.uniforms[Ve._worldSpaceCameraPosName]&&(this.uniforms[Ve._worldSpaceCameraPosName]={value:Ve._worldSpaceCameraPos}),i.mainCameraComponent)){if(this.uniforms._ProjectionParams){const l=this.uniforms._ProjectionParams.value;l.x=1,l.y=i.mainCameraComponent.nearClipPlane,l.z=i.mainCameraComponent.farClipPlane,l.w=1/l.z,this.uniforms._ProjectionParams.value=l}if(this.uniforms._ZBufferParams){const l=this.uniforms._ZBufferParams.value,c=i.mainCameraComponent;l.x=1-c.farClipPlane/c.nearClipPlane,l.y=c.farClipPlane/c.nearClipPlane,l.z=l.x/c.farClipPlane,l.w=l.y/c.farClipPlane,this.uniforms._ZBufferParams.value=l}if(this.uniforms._ScreenParams){const l=this.uniforms._ScreenParams.value;l.x=i.domWidth,l.y=i.domHeight,l.z=1+1/l.x,l.w=1+1/l.y,this.uniforms._ScreenParams.value=l}if(this.uniforms._ScaledScreenParams){const l=this.uniforms._ScaledScreenParams.value;l.x=i.domWidth,l.y=i.domHeight,l.z=1+1/l.x,l.w=1+1/l.y,this.uniforms._ScaledScreenParams.value=l}}const o=this.depthTextureUniform;o&&(o.value=i.depthTexture);const r=this.opaqueTextureUniform;if(r&&(r.value=i.opaqueColorTexture),t){const l=this._rendererData;l.updateFrom(t),this.uniforms[this._worldToObjectName].value=l.worldToObject,this.uniforms[this._objToWorldName].value=l.objectToWorld}this.uniformsNeedUpdate=!0}};let ks=Ve;a(ks,"viewProjection",new ne),a(ks,"_viewProjectionValues",[]),a(ks,"viewMatrix",new ne),a(ks,"_viewMatrixValues",[]),a(ks,"_worldSpaceCameraPosName","_WorldSpaceCameraPos"),a(ks,"_worldSpaceCameraPos",new x),a(ks,"_mainLightColor",new me),a(ks,"_mainLightPosition",new x),a(ks,"_lightData",new me);class AR{constructor(t,i){a(this,"parser"),a(this,"identifier"),this.parser=t,this.identifier=i}get name(){return ol}loadMaterial(t){const i=this.parser.json.materials[t];if(!i)return en&&console.log(t,this.parser.json.materials),null;if(!i.extensions||!i.extensions[ol])return en&&console.log(`Material ${t} does not use NEEDLE_techniques_webgl`),null;en&&console.log(`Material ${t} uses NEEDLE_techniques_webgl`,i);const n=i.extensions[ol].technique;if(n<0)return console.debug(`Material ${t} does not have a valid technique index`),null;const o=this.parser.json.extensions[ol];if(!o)return en?console.error("Missing shader data",this.parser.json.extensions):console.debug("Missing custom shader data in parser.json.extensions"),null;en&&console.log(o);const r=o.techniques[n];return r?new Promise(async(l,c)=>{var h,d,u;const p=await t2(o,r.program),g=p?.fragmentShader,y=p?.vertexShader;if(!g||!y)return c();en&&console.log("loadMaterial",i,p);const f={},v=r.uniforms;(y.includes("_Time")||g.includes("_Time"))&&(f._Time={value:new me(0,0,0,0)}),(y.includes("_SinTime")||g.includes("_SinTime"))&&(f._SinTime={value:new me(0,0,0,0)}),(y.includes("_CosTime")||g.includes("_CosTime"))&&(f._CosTime={value:new me(0,0,0,0)}),(y.includes("unity_DeltaTime")||g.includes("unity_DeltaTime"))&&(f.unity_DeltaTime={value:new me(0,0,0,0)});for(const _ in v){const C=_;switch(C){case"_TimeParameters":const R=new me;f[C]={value:R};break;case"hlslcc_mtx4x4unity_MatrixV":case"hlslcc_mtx4x4unity_MatrixVP":f[C]={value:[]};break;case"_MainLightPosition":case"_MainLightColor":case"_WorldSpaceCameraPos":f[C]={value:[0,0,0,1]};break;case"unity_OrthoParams":break;case"unity_SpecCube0":f[C]={value:null};break;default:case"_ScreenParams":case"_ZBufferParams":case"_ProjectionParams":f[C]={value:[0,0,0,0]};break;case"_CameraOpaqueTexture":case"_CameraDepthTexture":f[C]={value:null};break}}let b=!1;if(i.extensions&&i.extensions[ol]){const _=i.extensions[ol];if(_.technique===n){en&&console.log(i.name,"Material Properties",_);for(const C in _.values){const R=_.values[C];if(typeof R=="string"){if(R.startsWith("/textures/")){const M=R.substring(10),E=Number.parseInt(M);if(E>=0){const D=await this.parser.getDependency("texture",E);D instanceof Ne&&(D.colorSpace=pr,D.needsUpdate=!0),f[C]={value:D};continue}}switch(C){case"alphaMode":R==="BLEND"&&(b=!0);continue}}if(Array.isArray(R)&&R.length===4){f[C]={value:new me(R[0],R[1],R[2],R[3])};continue}f[C]={value:R}}}}const w=new ks(this.identifier,{name:i.name??"",uniforms:f,vertexShader:y,fragmentShader:g,lights:!1});switch(w.glslVersion=KS,w.vertexShader=w.vertexShader.replace("#version 300 es",""),w.fragmentShader=w.fragmentShader.replace("#version 300 es",""),(h=f._Cull)==null?void 0:h.value){case 0:w.side=_i;break;case 1:w.side=fm;break;case 2:w.side=lo;break;default:w.side=lo;break}switch((d=f._ZTest)==null?void 0:d.value){case 3:w.depthTest=!0,w.depthFunc=nC;break;case 6:w.depthTest=!0,w.depthFunc=sC;break;case 2:w.depthTest=!0,w.depthFunc=iC;break;case 4:w.depthTest=!0,w.depthFunc=tC;break;case 5:w.depthTest=!0,w.depthFunc=eC;break;case 7:w.depthTest=!0,w.depthFunc=JS;break;case 8:w.depthTest=!1,w.depthFunc=ZS;break}w.transparent=b,b&&(w.depthWrite=!1),Jk(f),w.onUpdateUniforms();for(const _ in v){const C=_,R=v[_].type;if(((u=f[C])==null?void 0:u.value)===void 0)switch(R){case rx.SAMPLER_2D:f[C]={value:Kk},console.warn("Missing/unassigned texture, fallback to white: "+C);break;default:C==="unity_OrthoParams"||console.warn("TODO: EXPECTED UNIFORM / fallback NOT SET: "+C,v[_]);break}}en&&console.log(w.uuid,f),ax(w),l(w)}):null}}function ax(s){if(s.uniforms){en&&console.log("Uniforms:",s.uniforms);for(const i in s.uniforms)switch(t(i,i),i){case"_Color":t("color",i);break}}function t(i,n){Object.getOwnPropertyDescriptor(s,i)||Object.defineProperty(s,i,{get:()=>s.uniforms[n].value,set:o=>{s.uniforms[n].value=o,s.needsUpdate=!0}})}}const IR=O("debugextensions");let Xu;const jR=import("./three-examples.light.min.js").then(s=>s.r).then(async s=>(Xu=s.GLTFAnimationPointerExtension,Xu)).catch(s=>{console.warn("Failed to import GLTFLoaderAnimationPointer. Please use @needle-tools/three for full KHR_animation support",s)}),Wr=new Array;function LR(s){Wr.includes(s)||Wr.push(s)}function DR(s){const t=Wr.indexOf(s);t>=0&&Wr.splice(t,1)}function Qu(s){const t=new sx;return s.register(i=>(t.parser=i,t)),t}class BR{resolvePath(t){return t.includes("/extensions/builtin_components/")?t.replace("/extensions/builtin_components/","/userData/components/"):t.includes("extensions/builtin_components/")?t.replace("extensions/builtin_components/","/userData/components/"):t}}async function Yu(s,t,i){const n=i.indexOf("?");n>=0&&(i=i.substring(0,n)),s.register(o=>new OR(o)),s.register(o=>new kk(o)),s.register(o=>new Gk(o,t.lightmaps,i)),s.register(o=>new PR(o,i,t)),s.register(o=>new AR(o,i)),s.register(o=>new $f(o,i)),s.register(o=>new et(o,i)),s.register(o=>new wR(o)),Yb()&&s.register(o=>new Og(o)),await jR.catch(o=>{}),s.register(o=>{if(Xu){const r=new Xu(o);return r.setAnimationPointerResolver.bind(r)(new BR),r}else return(IR||F())&&console.error("Missing KHR_animation_pointer extension..."),{name:"KHR_animation_pointer_NOT_AVAILABLE"}});for(const o of Wr)o.onImport&&o.onImport(s,i,t)}function Gf(s,t){for(const i of Wr)i.onExport&&i.onExport(s,t)}function Xf(s,t,i){for(const n of Wr)n.onLoaded&&n.onLoaded(s,t,i)}class lx{constructor(t){this.writer=t,this.name="EXT_mesh_gpu_instancing"}writeNode(t,i){if(t.constructor.name!=="InstancedMesh")return;const n=this.writer,o=n.extensionsUsed,r={};i.extensions=i.extensions||{},i.extensions[this.name]=r;let l=new ne;const c=new Array,h=new Array,d=new Array;for(let y=0;y<t.count;y++){t.getMatrixAt(y,l);let f=new x,v=new V,b=new x;l.decompose(f,v,b),c.push(f.x,f.y,f.z),h.push(v.x,v.y,v.z,v.w),d.push(b.x,b.y,b.z)}const u=new Float32Array(c),p=new Float32Array(h),g=new Float32Array(d);r.attributes={TRANSLATION:n.processAccessor(new mt(u,3)),ROTATION:n.processAccessor(new mt(p,4)),SCALE:n.processAccessor(new mt(g,3))},o[this.name]=!0}}var FR=Object.defineProperty,zR=Object.getOwnPropertyDescriptor,cx=(s,t,i,n)=>{for(var o=n>1?void 0:n?zR(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&FR(t,i,o),o};const Ku=O("debugreflectionprobe"),hx=O("noreflectionprobe"),UR=Symbol("reflectionProbeKey"),NR=Symbol("original material");var Zu;const Fn=(Zu=class extends A{constructor(){var s;super(),a(this,"_texture"),a(this,"center"),a(this,"size"),a(this,"_boxHelper"),Fn._probes.has(this.context)||Fn._probes.set(this.context,[]),(s=Fn._probes.get(this.context))==null||s.push(this)}static get(s,t,i,n){if(!s||s.isObject3D!==!0||hx)return null;const o=Fn._probes.get(t);if(o){for(const r of o)if(r.__didAwake||r.__internalAwake(),r.enabled&&n&&r.gameObject===n)return r}return Ku&&console.debug("Did not find reflection probe",s.name,i,s),null}set texture(s){if(s&&!(s instanceof Ne)){console.error("ReflectionProbe.texture must be a Texture",s);return}this._texture=s,s&&(s.mapping=_n,s.colorSpace=ps,s.needsUpdate=!0)}get texture(){return this._texture}isInBox(s){var t;return(t=this._boxHelper)==null?void 0:t.isInBox(s)}awake(){this._boxHelper=this.gameObject.addComponent(is),this._boxHelper.updateBox(!0),Ku&&this._boxHelper.showHelper(5592320,!0),this.texture&&(this.texture.mapping=_n,this.texture.colorSpace=ps,this.texture.needsUpdate=!0)}onDestroy(){const s=Fn._probes.get(this.context);if(s){const t=s.indexOf(this);t>=0&&s.splice(t,1)}}onSet(s){var t;if(hx||!this.enabled||((t=s.sharedMaterials)==null?void 0:t.length)<=0||!this.texture)return;let i=Fn._rendererMaterialsCache.get(s);i||(i=[],Fn._rendererMaterialsCache.set(s,i));for(let n=0;n<s.sharedMaterials.length;n++){const o=s.sharedMaterials[n];if(!o||o.envMap===void 0||o instanceof Me)continue;let r=i[n];const l=o===r?.copy,c=!r||r.material.uuid!==o.uuid||r.copy.version!==o.version;if(!l&&c){if(Ku){let u="";r?r.material!==o?u="reference changed; cached instance?: "+l:r.copy.version!==o.version&&(u="version changed"):u="not cached",console.warn("Cloning material",o.name,o.version,"Reason:",u,`
938
+ `,.03);const R=this._bottomCenter.clone(),M=this._backCenter.clone(),E=this._backBottomCenter.clone();i.localToWorld(R),i.localToWorld(M),i.localToWorld(E),q.DrawSphere(R,.01,65280,0,!1),q.DrawSphere(M,.01,255,0,!1),q.DrawSphere(E,.01,16711935,0,!1),q.DrawLine(R,E,65535,0,!1),q.DrawLine(E,M,65535,0,!1)}}onDragEnd(t){console.assert(this._followObject.parent===t.event.space,"Drag end: _followObject is not parented to the space object"),this._followObject.removeFromParent(),this._followObject.destroy(),this._lastDragPosRigSpace=void 0}setPlaneViewAligned(t,i){if(!this._followObject.parent)return!1;const n=this._followObject.parent.worldForward,o=$(0,1,0),r=n,l=o.angleTo(r),c=.5;return i&&(l>Math.PI/2+c||l<Math.PI/2-c)?this._dragPlane.setFromNormalAndCoplanarPoint(o,t):this._dragPlane.setFromNormalAndCoplanarPoint(n,t),!0}}const Kw=class{constructor(s){a(this,"showGizmo",!0),a(this,"useViewAngle",!0),a(this,"_selected",null),a(this,"_context",null),a(this,"_camera"),a(this,"_cameraPlane",new dr),a(this,"_hasGroundPlane",!1),a(this,"_groundPlane",new dr),a(this,"_groundOffset",new x),a(this,"_groundOffsetFactor",0),a(this,"_groundDistance",0),a(this,"_groundPlanePoint",new x),a(this,"_raycaster",new ld),a(this,"_cameraPlaneOffset",new x),a(this,"_intersection",new x),a(this,"_worldPosition",new x),a(this,"_inverseMatrix",new ne),a(this,"_rbs",[]),a(this,"_groundLine"),a(this,"_groundMarker"),a(this,"_groundOffsetVector",new x(0,1,0)),a(this,"_requireUpdateGroundPlane",!0),a(this,"_didDragOnGroundPlaneLastFrame",!1),this._camera=s;const t=new Vl(Kw.geometry),i=t.material;i.color=new ae(.4,.4,.4),t.layers.set(2),t.name="line",t.scale.y=1,this._groundLine=t;const n=new rd(.5,22,22),o=new Me({color:i.color}),r=new Q(n,o);r.visible=!1,r.layers.set(2),this._groundMarker=r}get hasSelected(){return this._selected!==null&&this._selected!==void 0}get selected(){return this._selected}setSelected(s,t){if(this._selected&&t)for(const i of this._rbs)i.wakeUp(),i.setVelocity(0,0,0);if(this._selected&&Xs.Remove(t,this._selected),this._selected=s,this._context=t,this._rbs.length=0,s?(t.scene.add(this._groundLine),t.scene.add(this._groundMarker)):(this._groundLine.removeFromParent(),this._groundMarker.removeFromParent()),this._selected){if(!t){console.error("DragHelper: no context");return}Xs.Add(t,this._selected,null),this._groundOffsetFactor=0,this._hasGroundPlane=!0,this._groundOffset.set(0,0,0),this._requireUpdateGroundPlane=!0,this.onUpdateScreenSpacePlane()}}onUpdate(s){this._selected}onUpdateWorldPosition(s,t,i){if(this._selected){if(i){const n=ee(this._selected);n.y=s.y,s=n}if(lt(this._selected,s),lt(this._groundLine,s),this._hasGroundPlane?this._groundLine.scale.y=this._groundDistance:this._groundLine.scale.y=1e3,this._groundLine.visible=this.showGizmo,this._groundMarker.visible=t!==null&&this.showGizmo,t){const n=ee(this._camera).distanceTo(t)*.01;this._groundMarker.scale.set(n,n,n),lt(this._groundMarker,t)}}}onUpdateScreenSpacePlane(){if(!this._selected||!this._context)return;const s=this._context.input.getPointerPositionRC(0);s&&(this._raycaster.setFromCamera(s,this._camera),this._cameraPlane.setFromNormalAndCoplanarPoint(this._camera.getWorldDirection(this._cameraPlane.normal),this._worldPosition.setFromMatrixPosition(this._selected.matrixWorld)),this._raycaster.ray.intersectPlane(this._cameraPlane,this._intersection)&&this._selected.parent&&(this._inverseMatrix.copy(this._selected.parent.matrixWorld).invert(),this._cameraPlaneOffset.copy(this._intersection).sub(this._worldPosition.setFromMatrixPosition(this._selected.matrixWorld))))}onUpdateGroundPlane(){if(!this._selected||!this._context)return;const s=ee(this._selected),t=new hr($(0,.1,0).add(s),$(0,-1,0)),i=new Ns;i.testObject=o=>o!==this._selected;const n=this._context.physics.raycastFromRay(t,i);for(let o=0;o<n.length;o++){const r=n[o];if(!r.face||this.contains(this._selected,r.object))continue;const l=$(0,1,0);this._groundPlane.setFromNormalAndCoplanarPoint(l,r.point);break}this._hasGroundPlane=!0,this._groundPlane.setFromNormalAndCoplanarPoint(t.direction.multiplyScalar(-1),t.origin),this._raycaster.ray.intersectPlane(this._groundPlane,this._intersection),this._groundDistance=this._intersection.distanceTo(s),this._groundOffset.copy(this._intersection).sub(s)}contains(s,t){if(s===t)return!0;if(s.children){for(const i of s.children)if(this.contains(i,t))return!0}return!1}};let hR=Kw;a(hR,"geometry",new oo().setFromPoints([new x(0,0,0),new x(0,-1,0)]));var Zw=(s=>(s.File_Spawned="file-spawned",s))(Zw||{});class dR{constructor(t,i,n,o,r,l,c,h,d){a(this,"guid"),a(this,"file_name"),a(this,"file_hash"),a(this,"file_size"),a(this,"position"),a(this,"scale"),a(this,"seed"),a(this,"sender"),a(this,"downloadUrl"),a(this,"parentGuid"),a(this,"boundsSize"),this.seed=i,this.guid=n,this.file_name=o,this.file_hash=r,this.file_size=l,this.position=c,this.scale=h,this.sender=t,this.downloadUrl=d}}var Ao;(s=>{const t=new Map;function i(o){var r;t.has(o.guid)&&n(o.guid);const l=new j;t.set(o.guid,l);const c=new j;c.position.y=-.5,l.add(c);const h=new Q(new Wl(1,1,1,1,1,1),new Me({color:14540253,wireframe:!0,transparent:!0,opacity:.3}));h.position.y=.5,c.add(h);const d=new j;c.add(d);const u=new Q(new Wl(1,1,1,1,1,1),new Me({color:12307660,transparent:!0,opacity:.4}));u.position.y=.5,d.scale.y=.01,d.add(u);const p=new Q(new Ds(1,1,1,1),new Me({color:34,transparent:!0,opacity:.05,depthTest:!1}));return p.rotateX(-Math.PI/2),p.position.y=.51,u.add(p),o.parent.add(l),l.rotateY(Math.PI/2),o.position&&((r=l.position)==null||r.copy(o.position)),o.size&&(l.worldScale=new x().copy(o.size)),l.position.y=l.scale.y/2,{object:l,onProgress:g=>{d instanceof j&&d.scale.set(1,g,1)}}}s.addPreview=i;function n(o){const r=t.get(o);r&&(t.delete(o),r.removeFromParent())}s.removePreview=n})(Ao||(Ao={}));var uR=Object.defineProperty,pR=Object.getOwnPropertyDescriptor,tl=(s,t,i,n)=>{for(var o=n>1?void 0:n?pR(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&uR(t,i,o),o};const Ps=O("debugdroplistener");class Wu extends CustomEvent{constructor(t){super("object-added",{detail:t})}}const mR="blob";class Dn extends A{constructor(){super(...arguments),a(this,"useNetworking",!0),a(this,"dropArea"),a(this,"fitIntoVolume",!1),a(this,"fitVolumeSize",new x(1,1,1)),a(this,"placeAtHitPosition",!0),a(this,"onDropped",new ke),a(this,"onNetworkEvent",t=>{var i;if(!this.useNetworking){Ps&&console.debug("[DropListener] Ignoring networked event because networking is disabled",t);return}if((i=t.guid)!=null&&i.startsWith(this.guid)){const n=t.url;if(console.debug("[DropListener] Received networked event",t),n)if(Array.isArray(n))for(const o of n)this.addFromUrl(o,{screenposition:new oe,point:t.point,size:t.size},!0);else this.addFromUrl(n,{screenposition:new oe,point:t.point,size:t.size},!0)}}),a(this,"handlePaste",t=>{this.context.connection.allowEditing===!1||t.defaultPrevented||navigator.clipboard.readText().then(i=>{if(i&&(i.startsWith("http")||i.startsWith("https")||i.startsWith("blob"))){const n={screenposition:new oe(this.context.input.mousePosition.x,this.context.input.mousePosition.y)};this.testIfIsInDropArea(n)&&this.addFromUrl(i,n,!1)}}).catch(console.warn)}),a(this,"onDrag",t=>{this.context.connection.allowEditing!==!1&&t.preventDefault()}),a(this,"onDrop",async t=>{if(this.context.connection.allowEditing===!1||(Ps&&console.log(t),!(t!=null&&t.dataTransfer))||t["droplistener:handled"])return;t.preventDefault();const i={screenposition:new oe(t.offsetX,t.offsetY)};if(this.dropArea&&this.testIfIsInDropArea(i)===!1)return;t["droplistener:handled"]=!0;const n=t.dataTransfer.items;if(!n)return;const o=[];for(const r in n){const l=n[r];if(l.kind==="file"){const c=l.getAsFile();if(!c)continue;o.push(c)}else l.kind==="string"&&l.type=="text/plain"&&l.getAsString(c=>{this.addFromUrl(c,i,!1)})}o.length>0&&await this.addDroppedFiles(o,i)}),a(this,"_abort",null),a(this,"_addedObjects",new Array),a(this,"_addedModels",new Array)}onEnable(){this.context.renderer.domElement.addEventListener("dragover",this.onDrag),this.context.renderer.domElement.addEventListener("drop",this.onDrop),window.addEventListener("paste",this.handlePaste),this.context.connection.beginListen("droplistener",this.onNetworkEvent)}onDisable(){this.context.renderer.domElement.removeEventListener("dragover",this.onDrag),this.context.renderer.domElement.removeEventListener("drop",this.onDrop),window.removeEventListener("paste",this.handlePaste),this.context.connection.stopListen("droplistener",this.onNetworkEvent)}loadFromURL(t,i){this.addFromUrl(t,{screenposition:new oe,point:i?.point,size:i?.size},!0)}forgetObjects(){this.removePreviouslyAddedObjects(!1)}async addFromUrl(t,i,n){Ps&&console.log("dropped url",t);try{if(t.startsWith("https://github.com/")){const l=t.split("/"),c=l[3],h=l[4],d=l[6],u=l.slice(7).join("/");t=`https://raw.githubusercontent.com/${c}/${h}/${d}/${u}`}else t.startsWith("https://polyhaven.com/a")&&(t=gR(t));if(!t)return null;const o=t.toLowerCase();if(o.endsWith(".hdr")||o.endsWith(".hdri")||o.endsWith(".exr")||o.endsWith(".png")||o.endsWith(".jpg")||o.endsWith(".jpeg"))return null;this.removePreviouslyAddedObjects();const r=await Vu.loadFileFromURL(new URL(t),{guid:this.guid,context:this.context,parent:this.gameObject,point:i.point,size:i.size});if(r&&this._addedObjects.length<=0)return i.url=t,this.addObject(r,i,n)}catch{console.warn("String is not a valid URL",t)}return null}async addDroppedFiles(t,i){var n,o;if(Ps&&console.log("Add files",t),!!Array.isArray(t)&&t.length){this.deleteDropEvent(),this.removePreviouslyAddedObjects(),ql(mR,null),(n=this._abort)==null||n.abort("New files dropped"),this._abort=new AbortController;for(const r of t){if(!r)continue;console.debug("Load file "+r.name);const l=await Vu.loadFile(r,this.context,{guid:this.guid});if(l){this.dispatchEvent(new CustomEvent("file-dropped",{detail:r})),i.file=r;const c=this.addObject(l,i,!1);c&&this.context.connection.isConnected&&this.useNetworking&&(console.debug("Uploading dropped file to blob storage"),Mr.upload(r,{abort:(o=this._abort)==null?void 0:o.signal}).then(h=>{h!=null&&h.download_url&&this._addedObjects.includes(c)&&this.sendDropEvent(h.download_url,c,l.contentMD5)}).catch(console.warn));break}}}}removePreviouslyAddedObjects(t=!0){if(t)for(const i of this._addedObjects)i.parent===this.gameObject&&Mi(i,!0,!0);this._addedObjects.length=0,this._addedModels.length=0}addObject(t,i,n){var o,r;const{model:l,contentMD5:c}=t;if(Ps&&console.log(`Dropped ${this.gameObject.name}`,l),!(l!=null&&l.scene))return console.warn("No object specified to add to scene",l),null;this.removePreviouslyAddedObjects();const h=l.scene;this.gameObject.attach(h),h.position.set(0,0,0),h.quaternion.identity(),this._addedObjects.push(h),this._addedModels.push(l);const d=new vi().setFromCenterAndSize(new x(0,this.fitVolumeSize.y*.5,0).add(this.gameObject.worldPosition),this.fitVolumeSize);if(Ps&&q.DrawWireBox3(d,255,5),this.fitIntoVolume&&tb(h,d,{position:!this.placeAtHitPosition}),this.placeAtHitPosition&&i&&i.screenposition){h.visible=!1;const p=this.context.physics.raycast({screenPoint:this.context.input.convertScreenspaceToRaycastSpace(i.screenposition.clone())});if(h.visible=!0,p&&p.length>0)for(const g of p){const y=g.point.clone();Ps&&console.log("Place object at hit",g),ib(h,y);break}}Na.assignAnimationsFromFile(l,{createAnimationComponent:p=>ki(p,Ut)});const u=new Wu({sender:this,gltf:l,model:l,object:h,contentMD5:c,dropped:i.file||(i.url?new URL(i.url):void 0)});return this.dispatchEvent(u),(o=this.onDropped)==null||o.invoke(u.detail),!n&&(r=i.url)!=null&&r.startsWith("http")&&this.context.connection.isConnected&&h&&this.sendDropEvent(i.url,h,c),h}async sendDropEvent(t,i,n){if(!this.useNetworking){Ps&&console.debug("[DropListener] Ignoring networked event because networking is disabled",t);return}if(this.context.connection.isConnected){console.debug('Sending drop event "'+i.name+'"',t);const o=Si([i]),r={name:i.name,guid:this.guid,url:t,point:i.worldPosition.clone(),size:o.getSize(new x),contentMD5:n};this.context.connection.send("droplistener",r)}}deleteDropEvent(){this.context.connection.sendDeleteRemoteState(this.guid)}testIfIsInDropArea(t){if(this.dropArea){const i=this.context.input.convertScreenspaceToRaycastSpace(t.screenposition.clone());if(!this.context.physics.raycast({targets:[this.dropArea],screenPoint:i,recursive:!0,testObject:n=>!this._addedObjects.includes(n)}).length)return F()&&console.log(`Dropped outside of drop area for DropListener "${this.name}".`),!1}return!0}}tl([m()],Dn.prototype,"useNetworking",2),tl([m(j)],Dn.prototype,"dropArea",2),tl([m()],Dn.prototype,"fitIntoVolume",2),tl([m(x)],Dn.prototype,"fitVolumeSize",2),tl([m()],Dn.prototype,"placeAtHitPosition",2),tl([m(ke)],Dn.prototype,"onDropped",2);function gR(s){if(!s.startsWith("https://polyhaven.com/"))return s;const t="https://dl.polyhaven.org/file/ph-assets/Models/gltf/4k/",i=new URL(s).pathname.split("/").pop(),n=`${t}${i}/${i}_4k.gltf`;return console.log("Resolved polyhaven asset url",s,"\u2192",n),n}var Vu;(s=>{async function t(n,o,r){const l=n.name.toLowerCase();return l.endsWith(".gltf")||l.endsWith(".glb")||l.endsWith(".fbx")||l.endsWith(".obj")||l.endsWith(".usdz")||l.endsWith(".vrm")||n.type==="model/gltf+json"||n.type==="model/gltf-binary"?new Promise((c,h)=>{const d=new FileReader;d.readAsArrayBuffer(n),d.onloadend=async u=>{const p=d.result,g=r.guid,y=new Bt(g),f=await ms().parseSync(o,p,n.name,y);if(f){const v=Mr.hashMD5(p);c({model:f,contentMD5:v})}}}):(console.warn("Unsupported file type: "+l,n.type),null)}s.loadFile=t;async function i(n,o){return new Promise(async(r,l)=>{const c=new Bt(o.guid),h=n.toString();Ps&&q.DrawWireSphere(o.point,.1,16711680,3);const d=Ao.addPreview({guid:o.guid,parent:o.parent,position:o?.point,size:o?.size}),u=await ms().loadSync(o.context,h,h,c,p=>{d.onProgress(p.loaded/p.total)}).catch(console.warn);if(u){const p=await fetch(h).then(y=>y.arrayBuffer()),g=Mr.hashMD5(p);Ps?setTimeout(()=>Ao.removePreview(o.guid),3e3):Ao.removePreview(o.guid),r({model:u,contentMD5:g})}else Ps?setTimeout(()=>Ao.removePreview(o.guid),3e3):Ao.removePreview(o.guid),console.warn("Unsupported file type: "+n.toString())})}s.loadFileFromURL=i})(Vu||(Vu={}));var fR=Object.defineProperty,yR=Object.getOwnPropertyDescriptor,Hu=(s,t,i,n)=>{for(var o=n>1?void 0:n?yR(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&fR(t,i,o),o};const Jw=class extends A{constructor(){super(...arguments),a(this,"parent",null),a(this,"object",null),a(this,"limitCount",10),a(this,"limitInterval",60),a(this,"_currentCount",0),a(this,"_startPosition",null),a(this,"_startQuaternion",null),a(this,"_forwardPointerEvents",new Map)}start(){var s,t;if(this._currentCount=0,this._startPosition=null,this._startQuaternion=null,this.object||(this.object=this.gameObject),this.object){if(this.object===this.gameObject){const n=new Bt(this.guid);this.object=P.instantiate(this.object,{idProvider:n,keepWorldPosition:!1});const o=P.getComponent(this.object,Jw);o?.destroy();let r=this.object.getComponentInChildren(di);r||(r=this.object.addComponent(di,{dragMode:zf.SnapToSurfaces}),r.guid=n.generateUUID());let l=P.getComponent(r.gameObject,$s);l||(l=r.gameObject.addComponent($s),l.guid=n.generateUUID())}this.object.visible=!1;const i=this.gameObject.getComponent(di);i&&(i.enabled=!1),this._startPosition=((s=this.object.position)==null?void 0:s.clone())??new x(0,0,0),this._startQuaternion=((t=this.object.quaternion)==null?void 0:t.clone())??new V(0,0,0,1)}this.gameObject.getComponentInParent(Ti)||this.gameObject.addComponent(Ti),this.cloneLimitIntervalFn()}onPointerEnter(s){s.used||this.object&&this.context.connection.allowEditing&&s.button===0&&this.context.input.setCursorPointer()}onPointerExit(s){s.used||this.object&&this.context.connection.allowEditing&&s.button===0&&this.context.input.setCursorNormal()}onPointerDown(s){if(s.used||!this.object||!this.context.connection.allowEditing||s.button!==0)return;const t=this.handleDuplication();if(t){const i=P.getComponent(t,di);i?(i.onPointerDown(s),this._forwardPointerEvents.set(s.event.space,i)):console.warn("Duplicated object does not have DragControls",t)}else console.warn("Could not duplicate object. Has the target object been destroyed?",this)}onPointerUp(s){if(s.used)return;const t=this._forwardPointerEvents.get(s.event.space);t&&(t.onPointerUp(s),this._forwardPointerEvents.delete(s.event.space))}cloneLimitIntervalFn(){this.destroyed||(this._currentCount>0&&(this._currentCount-=1),setTimeout(()=>{this.cloneLimitIntervalFn()},this.limitInterval/this.limitCount*1e3))}handleDuplication(){var s;if(!this.object||this._currentCount>=this.limitCount||this.object===this.gameObject)return null;if(P.isDestroyed(this.object))return this.object=null,null;this.object.visible=!0,this._startPosition&&this.object.position.copy(this._startPosition),this._startQuaternion&&this.object.quaternion.copy(this._startQuaternion);const t=new js;this.parent||(this.parent=this.gameObject.parent),this.parent&&(t.parent=this.parent.guid??((s=this.parent.userData)==null?void 0:s.guid),t.keepWorldPosition=!0),t.position=this.worldPosition,t.rotation=this.worldQuaternion,t.context=this.context,this._currentCount+=1;const i=P.instantiateSynced(this.object,t);return console.assert(i!==this.object,"Duplicated object is original"),this.object.visible=!1,this._startPosition&&this.object.position.clone().copy(this._startPosition),this._startQuaternion&&this.object.quaternion.clone().copy(this._startQuaternion),i}};let Nr=Jw;Hu([m(j)],Nr.prototype,"parent",2),Hu([m(j)],Nr.prototype,"object",2),Hu([m()],Nr.prototype,"limitCount",2),Hu([m()],Nr.prototype,"limitInterval",2);var il=(s=>(s[s.PointerEnter=0]="PointerEnter",s[s.PointerExit=1]="PointerExit",s[s.PointerDown=2]="PointerDown",s[s.PointerUp=3]="PointerUp",s[s.PointerClick=4]="PointerClick",s[s.Drag=5]="Drag",s[s.Drop=6]="Drop",s[s.Scroll=7]="Scroll",s[s.UpdateSelected=8]="UpdateSelected",s[s.Select=9]="Select",s[s.Deselect=10]="Deselect",s[s.Move=11]="Move",s[s.InitializePotentialDrag=12]="InitializePotentialDrag",s[s.BeginDrag=13]="BeginDrag",s[s.EndDrag=14]="EndDrag",s[s.Submit=15]="Submit",s[s.Cancel=16]="Cancel",s))(il||{}),vR=Object.defineProperty,bR=Object.getOwnPropertyDescriptor,Uf=(s,t,i,n)=>{for(var o=n>1?void 0:n?bR(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&vR(t,i,o),o};class Nf{constructor(){a(this,"eventID"),a(this,"callback",new ke)}}Uf([m()],Nf.prototype,"eventID",2),Uf([m(ke)],Nf.prototype,"callback",2);class $u extends A{constructor(){super(...arguments),a(this,"triggers",[])}invoke(t){var i;if(this.triggers)for(const n of this.triggers)n.eventID===t&&((i=n.callback)==null||i.invoke())}onPointerClick(t){this.invoke(il.PointerClick)}onPointerEnter(t){this.invoke(il.PointerEnter)}onPointerExit(t){this.invoke(il.PointerExit)}onPointerDown(t){this.invoke(il.PointerDown)}onPointerUp(t){this.invoke(il.PointerUp)}}Uf([m(Nf)],$u.prototype,"triggers",2);class ex{constructor(t){a(this,"writer"),this.writer=t}writeNode(t){}}class _R extends ex{beforeWriteNode(t,i){q.isGizmo(t)&&(i.keep=!1)}}class tx extends ex{beforeWriteTexture(t,i){t.isRenderTargetTexture&&(i.newTexture=Zg(new we(1,1,1,0)))}}function Wf(s){const t=Bu.DontExport;return!(s.hideFlags&t)}const Vf=O("debugexr");class wR{constructor(t){a(this,"parser"),this.parser=t,Vf&&console.log(t)}get name(){return"EXT_texture_exr"}loadTexture(t){const i=this.name,n=this.parser,o=n.json.textures[t];if(Vf&&console.log("EXT_texture_exr.loadTexture",t,o),!o.extensions||!o.extensions[i])return null;const r=o.extensions[i],l=new md(n.options.manager);return Vf&&console.log("EXT_texture_exr.loadTexture",r),n.loadTextureImage(t,r.source,l)}}typeof window<"u"&&window.addEventListener("unhandledrejection",s=>{});const Bn=ft,qu="$___Export_Components",xR="NEEDLE_components";var ix;class SR{constructor(){a(this,ix)}}ix=br;class CR{constructor(t,i,n){a(this,"node"),a(this,"nodeIndex"),a(this,"nodeDef"),this.node=t,this.nodeIndex=i,this.nodeDef=n}}class sx{constructor(){a(this,"parser"),a(this,"nodeToObjectMap",{}),a(this,"gltf",null),a(this,"exportContext"),a(this,"objectToNodeMap",{}),a(this,"context"),a(this,"writer")}get name(){return xR}registerExport(t){t.register(i=>{if("serializeUserData"in i){const n=i.serializeUserData.bind(i);this.writer=i,i.serializeUserData=(o,r)=>{try{this.serializeUserData(o,r)&&(i.extensionsUsed[this.name]=!0),n(o,r)}finally{this.afterSerializeUserData(o,r)}}}return this})}beforeParse(){this.exportContext={},this.objectToNodeMap={}}serializeUserData(t,i){var n;const o=(n=t.userData)==null?void 0:n.components;return!o||o.length<=0?!1:(delete t.userData.components,t[qu]=o,!0)}afterSerializeUserData(t,i){if(t.type==="Scene"&&Bn&&console.log("DONE",JSON.stringify(i)),t[qu]===void 0)return;const n=t[qu];delete t[qu],n!==null&&(t.userData.components=n)}writeNode(t,i){const n=this.writer.json.nodes.length;Bn&&console.log(t.name,n,t.uuid);const o=new CR(t,n,i);this.exportContext[n]=o,this.objectToNodeMap[t.uuid]=n}afterParse(t){var i;Bn&&console.log("AFTER",t);for(const n in this.exportContext){const o=this.exportContext[n],r=o.node,l=o.nodeDef,c=o.nodeIndex,h=(i=r.userData)==null?void 0:i.components;if(!h||h.length<=0)continue;const d=new SR;l.extensions=l.extensions||{},l.extensions[this.name]=d,this.context.object=r,this.context.nodeId=c,this.context.objectToNode=this.objectToNodeMap;const u=[];for(const p of h){this.context.target=p;const g=ms().writeBuiltinComponentData(p,this.context);g!==null&&u.push(g)}u.length>0&&(d[br]=u,Bn&&console.log("DID WRITE",r,"nodeIndex",c,u))}}beforeRoot(){return Bn&&console.log("BEGIN LOAD"),this.nodeToObjectMap={},null}async afterRoot(t){this.gltf=t;const i=t.parser,n=i?.extensions;if(!n)return;const o=n[this.name];Bn&&console.log("After root",t,this.parser,n);const r=[];if(o===!0){const l=i.json.nodes;if(l){for(let c=0;c<l.length;c++){const h=await i.getDependency("node",c);this.nodeToObjectMap[c]=h}for(let c=0;c<l.length;c++){const h=l[c],d=c,u=h.extensions;if(!u)continue;const p=u[this.name];if(!p)continue;Bn&&console.log("NODE",h);const g=this.nodeToObjectMap[d];if(!g){console.error("Could not find object for node index: "+d,h,i);continue}Xd(g),r.push(this.createComponents(g,p))}}}await Promise.all(r);for(const l of i.associations.keys()){const c=i.associations.get(l);if(c?.materials!=null){const h="/materials/"+c.materials;O2(l,h)}}}async createComponents(t,i){if(!i)return;const n=i[br];if(n){const o=new Array;Bn&&console.log(t.name,n);for(const r in n){const l=n[r];Bn&&console.log("Serialized data",JSON.parse(JSON.stringify(l))),l&&this.parser&&o.push(Ug(this.parser,l).catch(c=>console.error(`Error while resolving references (see console for details)
939
+ `,c,t,l))),t.userData=t.userData||{},t.userData[br]=t.userData[br]||[],t.userData[br].push(l)}await Promise.all(o).catch(r=>{console.error("Error while loading components",r)})}}}const nx="NEEDLE_gameobject_data";class OR{constructor(t){a(this,"parser"),this.parser=t}get name(){return nx}afterRoot(t){var i;const n=[];for(let o=0;o<((i=this.parser.json.nodes)==null?void 0:i.length);o++){const r=this.parser.json.nodes[o];if(r&&r.extensions){const l=r.extensions[nx];if(l){const c=this.findAndApplyExtensionData(o,l);n.push(c)}}}return Promise.all(n).then(()=>null)}async findAndApplyExtensionData(t,i){const n=await this.parser.getDependency("node",t);n&&this.applyExtensionData(n,i)}applyExtensionData(t,i){i.layers===void 0&&(i.layers=0),t.userData.layer=i.layers,t.layers.disableAll(),t.layers.set(i.layers),t.userData.tag=i.tag??"none",t.hideFlags=0,t.userData.static=i.static??!1,t.visible=i.activeSelf??!0,t.guid=i.guid}}const ox="NEEDLE_lighting_settings",sl=O("debugenvlight");class PR{constructor(t,i,n){a(this,"parser"),a(this,"sourceId"),a(this,"context"),this.parser=t,this.sourceId=i,this.context=n}get name(){return ox}afterRoot(t){const i=this.parser.json.extensions;if(i){const n=i[ox];if(n){sl&&console.log('Loaded "'+this.name+'", src: "'+this.sourceId+'"',n);let o;if(t.scene.children.length===1){const r=t.scene.children[0];o=P.addComponent(r,Gu,{},{callAwake:!1})}else{const r=new j;r.name="LightSettings "+this.sourceId,t.scene.add(r),o=P.addComponent(r,Gu,{},{callAwake:!1})}o.sourceId=this.sourceId,o.ambientIntensity=n.ambientIntensity,o.ambientLight=new ae().fromArray(n.ambientLight),Array.isArray(n.ambientTrilight)&&(o.ambientTrilight=n.ambientTrilight.map(r=>new ae().fromArray(r))),o.ambientMode=n.ambientMode,o.environmentReflectionSource=n.environmentReflectionSource}}return null}}ge.registerCallback(fe.ContextCreated,s=>{const t=s.context,i=P.findObjectOfType(Gu,t);i!=null&&i.sourceId&&(i.enabled=!0)});class Gu extends A{constructor(){super(...arguments),a(this,"ambientMode",Va.Skybox),a(this,"ambientLight"),a(this,"ambientTrilight"),a(this,"ambientIntensity",1),a(this,"environmentReflectionSource",hu.Skybox),a(this,"_hasReflection",!1),a(this,"_ambientLightObj"),a(this,"_hemisphereLightObj")}awake(){var t;if(this.sourceId){const n=this.environmentReflectionSource===hu.Skybox?yo.Skybox:yo.Reflection,o=this.context.lightmaps.tryGet(this.sourceId,n,0);this._hasReflection=o!=null,o&&this.context.sceneLighting.internalRegisterReflection(this.sourceId,o)}this.enabled=!1,this.context.sceneLighting.internalRegisterSceneLightSettings(this),sl&&window.addEventListener("keydown",n=>{if(!this.destroyed)switch(n.key){case"l":this.enabled=!this.enabled;break}});const i=(t=this.gameObject.userData)==null?void 0:t.components;if(i){const n=i.indexOf(this);i.splice(n,1),i.push(this)}}onDestroy(){this.context.sceneLighting.internalUnregisterSceneLightSettings(this)}calculateIntensityFactor(t){const i=Math.max(t.r,t.g,t.b);return 2.2*W.lerp(0,1.33,i)}onEnable(){if(sl&&console.warn("\u{1F4A1}\u{1F7E1} >>> Enable lighting",this.sourceId,this.enabled,this),this.ambientMode==Va.Flat){if(this.ambientLight&&!this._ambientLightObj){const t=this.calculateIntensityFactor(this.ambientLight);this._ambientLightObj=new jS(this.ambientLight,this.ambientIntensity*t),sl&&console.log("Created ambient light",this.sourceId,this._ambientLightObj,this.ambientIntensity,t)}this._ambientLightObj&&this.gameObject.add(this._ambientLightObj)}else if(this.ambientMode===Va.Trilight){if(this.ambientTrilight){const t=this.ambientTrilight[0],i=this.ambientTrilight[this.ambientTrilight.length-1],n=this.calculateIntensityFactor(i);this._hemisphereLightObj=new LS(i,t,this.ambientIntensity*n),this.gameObject.add(this._hemisphereLightObj),sl&&console.log("Created hemisphere ambient light",this.sourceId,this._hemisphereLightObj,this.ambientIntensity,n)}}else this._ambientLightObj&&this._ambientLightObj.removeFromParent(),this._hemisphereLightObj&&this._hemisphereLightObj.removeFromParent();this.sourceId&&this.context.sceneLighting.internalEnableReflection(this.sourceId)}onDisable(){sl&&console.warn("\u{1F4A1}\u26AB <<< Disable lighting:",this.sourceId,this),this._ambientLightObj&&this._ambientLightObj.removeFromParent(),this._hemisphereLightObj&&this._hemisphereLightObj.removeFromParent(),this.sourceId&&this.context.sceneLighting.internalDisableReflection(this.sourceId)}}const Hf=O("debugstencil");function kR(s,t){return(s&1<<t.layer)!=0}const MR=Symbol("stencils"),nl=class{constructor(s,t){a(this,"parser"),a(this,"source"),this.parser=s,this.source=t}get name(){return"NEEDLE_render_objects"}static applyStencil(s){if(!s)return;const t=s.sourceId;if(Hf&&console.log(t,nl.stencils),!t)return;const i=nl.stencils[t];if(i)for(let n=i.length-1;n>=0;n--){const o=i[n];if(kR(o.layer,s)){Hf&&console.log(o),setTimeout(()=>{Gt()&&Kd(s.gameObject)&&(_e("Stencil not supported on instanced objects"),console.warn("Stencil not supported on instanced objects",s))},500);for(let r=0;r<s.sharedMaterials.length;r++){let l=s.sharedMaterials[r];l&&(l=l.clone(),l[MR]=!0,l.stencilWrite=!0,l.stencilWriteMask=255,l.stencilFuncMask=255,l.stencilRef=o.value,l.stencilFunc=o.compareFunc,l.stencilZPass=o.passOp,l.stencilFail=o.failOp,l.stencilZFail=o.zFailOp,s.sharedMaterials[r]=l)}s.gameObject.renderOrder=o.event*1e3+o.index*50;break}}}afterRoot(s){const t=this.parser.json.extensions;if(t){const i=t[TR];if(i){Hf&&console.log(i);const n=i.stencil;if(n&&Array.isArray(n))for(const o of n){const r={...o};r.compareFunc=RR(r.compareFunc),r.passOp=qf(r.passOp),r.failOp=qf(r.failOp),r.zFailOp=qf(r.zFailOp),nl.stencils[this.source]||(nl.stencils[this.source]=[]),nl.stencils[this.source].push(r)}}}return null}};let $f=nl;a($f,"stencils",{});function qf(s){switch(s){case 0:return VS;case 1:return WS;case 2:return NS;case 3:return US;case 4:return zS;case 6:return FS;case 7:return BS;case 5:return DS}return 0}function RR(s){switch(s){case 1:return ev;case 2:return YS;case 3:return QS;case 4:return XS;case 5:return GS;case 6:return qS;case 7:return $S;case 8:return HS}return ev}const TR="NEEDLE_render_objects";var rx=(s=>(s[s.INT=5124]="INT",s[s.FLOAT=5126]="FLOAT",s[s.FLOAT_VEC2=35664]="FLOAT_VEC2",s[s.FLOAT_VEC3=35665]="FLOAT_VEC3",s[s.FLOAT_VEC4=35666]="FLOAT_VEC4",s[s.INT_VEC2=35667]="INT_VEC2",s[s.INT_VEC3=35668]="INT_VEC3",s[s.INT_VEC4=35669]="INT_VEC4",s[s.BOOL=35670]="BOOL",s[s.BOOL_VEC2=35671]="BOOL_VEC2",s[s.BOOL_VEC3=35672]="BOOL_VEC3",s[s.BOOL_VEC4=35673]="BOOL_VEC4",s[s.FLOAT_MAT2=35674]="FLOAT_MAT2",s[s.FLOAT_MAT3=35675]="FLOAT_MAT3",s[s.FLOAT_MAT4=35676]="FLOAT_MAT4",s[s.SAMPLER_2D=35678]="SAMPLER_2D",s[s.SAMPLER_3D=35680]="SAMPLER_3D",s[s.SAMPLER_CUBE=35681]="SAMPLER_CUBE",s[s.UNKNOWN=0]="UNKNOWN",s))(rx||{});const en=O("debugcustomshader"),ol="NEEDLE_techniques_webgl";class ER{constructor(){a(this,"objectToWorldMatrix",new ne),a(this,"worldToObjectMatrix",new ne),a(this,"objectToWorld",new Array),a(this,"worldToObject",new Array)}updateFrom(t){this.objectToWorldMatrix.copy(t.matrixWorld),cu(this.objectToWorldMatrix,this.objectToWorld),this.worldToObjectMatrix.copy(t.matrixWorld).invert(),cu(this.worldToObjectMatrix,this.worldToObject)}}const Ve=class extends tv{constructor(s,...t){super(...t),a(this,"identifier"),a(this,"onBeforeRenderSceneCallback",this.onBeforeRenderScene.bind(this)),a(this,"_sphericalHarmonicsName","unity_SpecCube0"),a(this,"_objToWorldName","hlslcc_mtx4x4unity_ObjectToWorld"),a(this,"_worldToObjectName","hlslcc_mtx4x4unity_WorldToObject"),a(this,"_viewProjectionName","hlslcc_mtx4x4unity_MatrixVP"),a(this,"_viewMatrixName","hlslcc_mtx4x4unity_MatrixV"),a(this,"_rendererData",new ER),this.identifier=s,en&&console.log(this),this.type="NEEDLE_CUSTOM_SHADER",this.uniforms[this._objToWorldName]||(this.uniforms[this._objToWorldName]={value:[]}),this.uniforms[this._worldToObjectName]||(this.uniforms[this._worldToObjectName]={value:[]}),this.uniforms[this._viewProjectionName]||(this.uniforms[this._viewProjectionName]={value:[]}),this.uniforms[this._sphericalHarmonicsName],(this.depthTextureUniform||this.opaqueTextureUniform)&&te.Current.pre_render_callbacks.push(this.onBeforeRenderSceneCallback)}clone(){const s=super.clone();return ax(s),s}dispose(){super.dispose();const s=te.Current.pre_render_callbacks.indexOf(this.onBeforeRenderSceneCallback);s>=0&&te.Current.pre_render_callbacks.splice(s,1)}get depthTextureUniform(){if(this.uniforms)return this.uniforms._CameraDepthTexture}get opaqueTextureUniform(){if(this.uniforms)return this.uniforms._CameraOpaqueTexture}onBeforeRenderScene(){this.opaqueTextureUniform&&te.Current.setRequireColor(!0),this.depthTextureUniform&&te.Current.setRequireDepth(!0)}onBeforeRender(s,t,i,n,o,r){n.attributes.tangent||n.computeTangents(),this.onUpdateUniforms(i,o)}onUpdateUniforms(s,t){const i=te.Current;if(s&&(Ve.viewProjection&&this.uniforms[this._viewProjectionName]&&(Ve.viewProjection.copy(s.projectionMatrix).multiply(s.matrixWorldInverse),cu(Ve.viewProjection,Ve._viewProjectionValues)),Ve.viewMatrix&&this.uniforms[this._viewMatrixName]&&(Ve.viewMatrix.copy(s.matrixWorldInverse),cu(Ve.viewMatrix,Ve._viewMatrixValues)),this.uniforms[Ve._worldSpaceCameraPosName]&&Ve._worldSpaceCameraPos.setFromMatrixPosition(s.matrixWorld)),this.uniforms._TimeParameters&&(this.uniforms._TimeParameters.value=i.sceneLighting.timeVec4),this.uniforms._Time){const l=this.uniforms._Time.value;l.x=i.sceneLighting.timeVec4.x/20,l.y=i.sceneLighting.timeVec4.x,l.z=i.sceneLighting.timeVec4.x*2,l.w=i.sceneLighting.timeVec4.x*3}if(this.uniforms._SinTime){const l=this.uniforms._SinTime.value;l.x=Math.sin(i.sceneLighting.timeVec4.x/8),l.y=Math.sin(i.sceneLighting.timeVec4.x/4),l.z=Math.sin(i.sceneLighting.timeVec4.x/2),l.w=Math.sin(i.sceneLighting.timeVec4.x)}if(this.uniforms._CosTime){const l=this.uniforms._CosTime.value;l.x=Math.cos(i.sceneLighting.timeVec4.x/8),l.y=Math.cos(i.sceneLighting.timeVec4.x/4),l.z=Math.cos(i.sceneLighting.timeVec4.x/2),l.w=Math.cos(i.sceneLighting.timeVec4.x)}if(this.uniforms.unity_DeltaTime){const l=this.uniforms.unity_DeltaTime.value;l.x=i.time.deltaTime,l.y=1/i.time.deltaTime,l.z=i.time.smoothedDeltaTime,l.w=1/i.time.smoothedDeltaTime}const n=i.mainLight;if(n){const l=ee(n.gameObject,Ve._mainLightPosition);this.uniforms._MainLightPosition={value:l.normalize()},Ve._mainLightColor.set(n.color.r,n.color.g,n.color.b,0),this.uniforms._MainLightColor={value:Ve._mainLightColor};const c=n.intensity;Ve._lightData.z=c,this.uniforms.unity_LightData={value:Ve._lightData}}if(s&&(Ve.viewProjection&&this.uniforms[this._viewProjectionName]&&(this.uniforms[this._viewProjectionName].value=Ve._viewProjectionValues),Ve.viewMatrix&&this.uniforms[this._viewMatrixName]&&(this.uniforms[this._viewMatrixName].value=Ve._viewMatrixValues),this.uniforms[Ve._worldSpaceCameraPosName]&&(this.uniforms[Ve._worldSpaceCameraPosName]={value:Ve._worldSpaceCameraPos}),i.mainCameraComponent)){if(this.uniforms._ProjectionParams){const l=this.uniforms._ProjectionParams.value;l.x=1,l.y=i.mainCameraComponent.nearClipPlane,l.z=i.mainCameraComponent.farClipPlane,l.w=1/l.z,this.uniforms._ProjectionParams.value=l}if(this.uniforms._ZBufferParams){const l=this.uniforms._ZBufferParams.value,c=i.mainCameraComponent;l.x=1-c.farClipPlane/c.nearClipPlane,l.y=c.farClipPlane/c.nearClipPlane,l.z=l.x/c.farClipPlane,l.w=l.y/c.farClipPlane,this.uniforms._ZBufferParams.value=l}if(this.uniforms._ScreenParams){const l=this.uniforms._ScreenParams.value;l.x=i.domWidth,l.y=i.domHeight,l.z=1+1/l.x,l.w=1+1/l.y,this.uniforms._ScreenParams.value=l}if(this.uniforms._ScaledScreenParams){const l=this.uniforms._ScaledScreenParams.value;l.x=i.domWidth,l.y=i.domHeight,l.z=1+1/l.x,l.w=1+1/l.y,this.uniforms._ScaledScreenParams.value=l}}const o=this.depthTextureUniform;o&&(o.value=i.depthTexture);const r=this.opaqueTextureUniform;if(r&&(r.value=i.opaqueColorTexture),t){const l=this._rendererData;l.updateFrom(t),this.uniforms[this._worldToObjectName].value=l.worldToObject,this.uniforms[this._objToWorldName].value=l.objectToWorld}this.uniformsNeedUpdate=!0}};let ks=Ve;a(ks,"viewProjection",new ne),a(ks,"_viewProjectionValues",[]),a(ks,"viewMatrix",new ne),a(ks,"_viewMatrixValues",[]),a(ks,"_worldSpaceCameraPosName","_WorldSpaceCameraPos"),a(ks,"_worldSpaceCameraPos",new x),a(ks,"_mainLightColor",new me),a(ks,"_mainLightPosition",new x),a(ks,"_lightData",new me);class AR{constructor(t,i){a(this,"parser"),a(this,"identifier"),this.parser=t,this.identifier=i}get name(){return ol}loadMaterial(t){const i=this.parser.json.materials[t];if(!i)return en&&console.log(t,this.parser.json.materials),null;if(!i.extensions||!i.extensions[ol])return en&&console.log(`Material ${t} does not use NEEDLE_techniques_webgl`),null;en&&console.log(`Material ${t} uses NEEDLE_techniques_webgl`,i);const n=i.extensions[ol].technique;if(n<0)return console.debug(`Material ${t} does not have a valid technique index`),null;const o=this.parser.json.extensions[ol];if(!o)return en?console.error("Missing shader data",this.parser.json.extensions):console.debug("Missing custom shader data in parser.json.extensions"),null;en&&console.log(o);const r=o.techniques[n];return r?new Promise(async(l,c)=>{var h,d,u;const p=await tk(o,r.program),g=p?.fragmentShader,y=p?.vertexShader;if(!g||!y)return c();en&&console.log("loadMaterial",i,p);const f={},v=r.uniforms;(y.includes("_Time")||g.includes("_Time"))&&(f._Time={value:new me(0,0,0,0)}),(y.includes("_SinTime")||g.includes("_SinTime"))&&(f._SinTime={value:new me(0,0,0,0)}),(y.includes("_CosTime")||g.includes("_CosTime"))&&(f._CosTime={value:new me(0,0,0,0)}),(y.includes("unity_DeltaTime")||g.includes("unity_DeltaTime"))&&(f.unity_DeltaTime={value:new me(0,0,0,0)});for(const _ in v){const C=_;switch(C){case"_TimeParameters":const R=new me;f[C]={value:R};break;case"hlslcc_mtx4x4unity_MatrixV":case"hlslcc_mtx4x4unity_MatrixVP":f[C]={value:[]};break;case"_MainLightPosition":case"_MainLightColor":case"_WorldSpaceCameraPos":f[C]={value:[0,0,0,1]};break;case"unity_OrthoParams":break;case"unity_SpecCube0":f[C]={value:null};break;default:case"_ScreenParams":case"_ZBufferParams":case"_ProjectionParams":f[C]={value:[0,0,0,0]};break;case"_CameraOpaqueTexture":case"_CameraDepthTexture":f[C]={value:null};break}}let b=!1;if(i.extensions&&i.extensions[ol]){const _=i.extensions[ol];if(_.technique===n){en&&console.log(i.name,"Material Properties",_);for(const C in _.values){const R=_.values[C];if(typeof R=="string"){if(R.startsWith("/textures/")){const M=R.substring(10),E=Number.parseInt(M);if(E>=0){const D=await this.parser.getDependency("texture",E);D instanceof Ne&&(D.colorSpace=pr,D.needsUpdate=!0),f[C]={value:D};continue}}switch(C){case"alphaMode":R==="BLEND"&&(b=!0);continue}}if(Array.isArray(R)&&R.length===4){f[C]={value:new me(R[0],R[1],R[2],R[3])};continue}f[C]={value:R}}}}const w=new ks(this.identifier,{name:i.name??"",uniforms:f,vertexShader:y,fragmentShader:g,lights:!1});switch(w.glslVersion=KS,w.vertexShader=w.vertexShader.replace("#version 300 es",""),w.fragmentShader=w.fragmentShader.replace("#version 300 es",""),(h=f._Cull)==null?void 0:h.value){case 0:w.side=_i;break;case 1:w.side=fm;break;case 2:w.side=lo;break;default:w.side=lo;break}switch((d=f._ZTest)==null?void 0:d.value){case 3:w.depthTest=!0,w.depthFunc=nC;break;case 6:w.depthTest=!0,w.depthFunc=sC;break;case 2:w.depthTest=!0,w.depthFunc=iC;break;case 4:w.depthTest=!0,w.depthFunc=tC;break;case 5:w.depthTest=!0,w.depthFunc=eC;break;case 7:w.depthTest=!0,w.depthFunc=JS;break;case 8:w.depthTest=!1,w.depthFunc=ZS;break}w.transparent=b,b&&(w.depthWrite=!1),J2(f),w.onUpdateUniforms();for(const _ in v){const C=_,R=v[_].type;if(((u=f[C])==null?void 0:u.value)===void 0)switch(R){case rx.SAMPLER_2D:f[C]={value:K2},console.warn("Missing/unassigned texture, fallback to white: "+C);break;default:C==="unity_OrthoParams"||console.warn("TODO: EXPECTED UNIFORM / fallback NOT SET: "+C,v[_]);break}}en&&console.log(w.uuid,f),ax(w),l(w)}):null}}function ax(s){if(s.uniforms){en&&console.log("Uniforms:",s.uniforms);for(const i in s.uniforms)switch(t(i,i),i){case"_Color":t("color",i);break}}function t(i,n){Object.getOwnPropertyDescriptor(s,i)||Object.defineProperty(s,i,{get:()=>s.uniforms[n].value,set:o=>{s.uniforms[n].value=o,s.needsUpdate=!0}})}}const IR=O("debugextensions");let Xu;const jR=import("./three-examples.light.min.js").then(s=>s.r).then(async s=>(Xu=s.GLTFAnimationPointerExtension,Xu)).catch(s=>{console.warn("Failed to import GLTFLoaderAnimationPointer. Please use @needle-tools/three for full KHR_animation support",s)}),Wr=new Array;function LR(s){Wr.includes(s)||Wr.push(s)}function DR(s){const t=Wr.indexOf(s);t>=0&&Wr.splice(t,1)}function Qu(s){const t=new sx;return s.register(i=>(t.parser=i,t)),t}class BR{resolvePath(t){return t.includes("/extensions/builtin_components/")?t.replace("/extensions/builtin_components/","/userData/components/"):t.includes("extensions/builtin_components/")?t.replace("extensions/builtin_components/","/userData/components/"):t}}async function Yu(s,t,i){const n=i.indexOf("?");n>=0&&(i=i.substring(0,n)),s.register(o=>new OR(o)),s.register(o=>new k2(o)),s.register(o=>new G2(o,t.lightmaps,i)),s.register(o=>new PR(o,i,t)),s.register(o=>new AR(o,i)),s.register(o=>new $f(o,i)),s.register(o=>new et(o,i)),s.register(o=>new wR(o)),Yb()&&s.register(o=>new Og(o)),await jR.catch(o=>{}),s.register(o=>{if(Xu){const r=new Xu(o);return r.setAnimationPointerResolver.bind(r)(new BR),r}else return(IR||F())&&console.error("Missing KHR_animation_pointer extension..."),{name:"KHR_animation_pointer_NOT_AVAILABLE"}});for(const o of Wr)o.onImport&&o.onImport(s,i,t)}function Gf(s,t){for(const i of Wr)i.onExport&&i.onExport(s,t)}function Xf(s,t,i){for(const n of Wr)n.onLoaded&&n.onLoaded(s,t,i)}class lx{constructor(t){this.writer=t,this.name="EXT_mesh_gpu_instancing"}writeNode(t,i){if(t.constructor.name!=="InstancedMesh")return;const n=this.writer,o=n.extensionsUsed,r={};i.extensions=i.extensions||{},i.extensions[this.name]=r;let l=new ne;const c=new Array,h=new Array,d=new Array;for(let y=0;y<t.count;y++){t.getMatrixAt(y,l);let f=new x,v=new V,b=new x;l.decompose(f,v,b),c.push(f.x,f.y,f.z),h.push(v.x,v.y,v.z,v.w),d.push(b.x,b.y,b.z)}const u=new Float32Array(c),p=new Float32Array(h),g=new Float32Array(d);r.attributes={TRANSLATION:n.processAccessor(new mt(u,3)),ROTATION:n.processAccessor(new mt(p,4)),SCALE:n.processAccessor(new mt(g,3))},o[this.name]=!0}}var FR=Object.defineProperty,zR=Object.getOwnPropertyDescriptor,cx=(s,t,i,n)=>{for(var o=n>1?void 0:n?zR(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&FR(t,i,o),o};const Ku=O("debugreflectionprobe"),hx=O("noreflectionprobe"),UR=Symbol("reflectionProbeKey"),NR=Symbol("original material");var Zu;const Fn=(Zu=class extends A{constructor(){var s;super(),a(this,"_texture"),a(this,"center"),a(this,"size"),a(this,"_boxHelper"),Fn._probes.has(this.context)||Fn._probes.set(this.context,[]),(s=Fn._probes.get(this.context))==null||s.push(this)}static get(s,t,i,n){if(!s||s.isObject3D!==!0||hx)return null;const o=Fn._probes.get(t);if(o){for(const r of o)if(r.__didAwake||r.__internalAwake(),r.enabled&&n&&r.gameObject===n)return r}return Ku&&console.debug("Did not find reflection probe",s.name,i,s),null}set texture(s){if(s&&!(s instanceof Ne)){console.error("ReflectionProbe.texture must be a Texture",s);return}this._texture=s,s&&(s.mapping=_n,s.colorSpace=ps,s.needsUpdate=!0)}get texture(){return this._texture}isInBox(s){var t;return(t=this._boxHelper)==null?void 0:t.isInBox(s)}awake(){this._boxHelper=this.gameObject.addComponent(is),this._boxHelper.updateBox(!0),Ku&&this._boxHelper.showHelper(5592320,!0),this.texture&&(this.texture.mapping=_n,this.texture.colorSpace=ps,this.texture.needsUpdate=!0)}onDestroy(){const s=Fn._probes.get(this.context);if(s){const t=s.indexOf(this);t>=0&&s.splice(t,1)}}onSet(s){var t;if(hx||!this.enabled||((t=s.sharedMaterials)==null?void 0:t.length)<=0||!this.texture)return;let i=Fn._rendererMaterialsCache.get(s);i||(i=[],Fn._rendererMaterialsCache.set(s,i));for(let n=0;n<s.sharedMaterials.length;n++){const o=s.sharedMaterials[n];if(!o||o.envMap===void 0||o instanceof Me)continue;let r=i[n];const l=o===r?.copy,c=!r||r.material.uuid!==o.uuid||r.copy.version!==o.version;if(!l&&c){if(Ku){let u="";r?r.material!==o?u="reference changed; cached instance?: "+l:r.copy.version!==o.version&&(u="version changed"):u="not cached",console.warn("Cloning material",o.name,o.version,"Reason:",u,`
940
940
  `,o.uuid,`
941
941
  `,r?.copy.uuid,`
942
942
  `,s.name)}const d=o.clone();d.version=o.version,r?(r.copy=d,r.material=o):(r={material:o,copy:d},i.push(r)),d[UR]=this,d[NR]=o,Ku&&console.log("Set reflection",s.name,s.guid)}r&&r.copy&&(r.copy.onBeforeCompile=o.onBeforeCompile);const h=r?.copy;h.envMap=this.texture,s.sharedMaterials[n]=h}}onUnset(s){const t=Fn._rendererMaterialsCache.get(s);if(t)for(let i=0;i<t.length;i++){const n=t[i];s.sharedMaterials[i]=n.material}}},a(Zu,"_probes",new Map),a(Zu,"_rendererMaterialsCache",new Map),Zu);let rl=Fn;cx([m(x)],rl.prototype,"center",2),cx([m(x)],rl.prototype,"size",2);const ui=O("debuginstancing"),Qf=class{constructor(){a(this,"objs",[])}setup(s,t,i,n,o,r=0){s.applySettings(t);const l=this.tryCreateOrAddInstance(t,i,o);if(l){n===null&&(n=[]),n.push(l),et.assignTextureLOD(l.renderer.material,0);for(let c=0;c<s.sharedMeshes.length;c++){const h=s.sharedMeshes[c],d=h.geometry;et.assignMeshLOD(h,0).then(u=>{u&&s.activeAndEnabled&&d!=u&&l.setGeometry(u)})}}else if(r<=0&&t.type!=="Mesh"){const c=r+1;for(const h of t.children)n=this.setup(s,h,i,n,o,c)}return r===0&&o.useMatrixWorldAutoUpdate&&n&&n.length>=0&&this.autoUpdateInstanceMatrix(t),n}tryCreateOrAddInstance(s,t,i){if(s.type==="Mesh"){const n=i.foundMeshes;if(i.foundMeshes+=1,!i.rend.enableInstancing)return null;if(i.rend.enableInstancing!==!0){if(n>=i.rend.enableInstancing.length)return ui&&console.error("Something is wrong with instance setup",s,i.rend.enableInstancing,n),null;if(!i.rend.enableInstancing[n])return null}const o=s,r=o.material;for(const d of this.objs)if(!!d.canAdd(o.geometry,r))return d.addInstance(o);let l=Qf.getStartInstanceCount(s);(!l||l<0)&&(l=4);let c=s.name;c!=null&&c.length||(c=Rv());const h=new dx(c,o.geometry,r,l,t);return this.objs.push(h),h.addInstance(o)}return null}autoUpdateInstanceMatrix(s){const t=s.matrixWorld.multiplyMatrices.bind(s.matrixWorld),i=s.matrixWorld.clone(),n=(o,r)=>{const l=t(o,r);return(s[mc]||i.equals(l)===!1)&&(i.copy(l),s[mc]=!0),l};s.matrixWorld.multiplyMatrices=n}};let Vr=Qf;a(Vr,"instance",new Qf),a(Vr,"getStartInstanceCount",s=>4);const Ju=class{constructor(s,t){a(this,"object"),a(this,"renderer"),a(this,"__instanceIndex",-1),a(this,"__reservedVertexRange",0),a(this,"__reservedIndexRange",0),a(this,"__geometryIndex",-1),a(this,"meshInformation"),this.__instanceIndex=-1,this.object=s,this.renderer=t,s[i_]=t,this.meshInformation=Hr(s.geometry),Ju.all.push(this)}get name(){return this.object.name}get isActive(){return this.__instanceIndex>=0}get vertexCount(){return this.object.geometry.attributes.position.count}get maxVertexCount(){return Math.max(this.meshInformation.vertexCount,this.vertexCount)}get reservedVertexCount(){return this.__reservedVertexRange}get indexCount(){return this.object.geometry.index?this.object.geometry.index.count:0}get maxIndexCount(){return Math.max(this.meshInformation.indexCount,this.indexCount)}get reservedIndexCount(){return this.__reservedIndexRange}updateMeshInformation(){const s=Hr(this.object.geometry),t=this.meshInformation.vertexCount,i=this.meshInformation.indexCount;return Object.assign(this.meshInformation,s),t!==this.meshInformation.vertexCount||i!==this.meshInformation.indexCount}updateInstanceMatrix(s=!1,t=!0){this.__instanceIndex<0||(t&&this.object.updateWorldMatrix(!0,s),this.renderer.updateInstance(this.object.matrixWorld,this.__instanceIndex))}setMatrix(s){this.__instanceIndex<0||this.renderer.updateInstance(s,this.__instanceIndex)}setGeometry(s){if(this.__geometryIndex<0)return!1;const t=this;if(this.vertexCount>this.__reservedVertexRange)return i(`Instancing: Can not update geometry (${this.name}), reserved vertex range is too small: ${this.__reservedVertexRange.toLocaleString()} < ${this.vertexCount.toLocaleString()} vertices for ${this.name}`);if(this.indexCount>this.__reservedIndexRange)return i(`Instancing: Can not update geometry (${this.name}), reserved index range is too small: ${this.__reservedIndexRange.toLocaleString()} < ${this.indexCount.toLocaleString()} indices for ${this.name}`);return this.renderer.updateGeometry(s,this.__geometryIndex);function i(n){return t.updateMeshInformation()&&(t.renderer.remove(t,!0),t.renderer.add(t))?!0:((F()||ui)&&console.error(n),!1)}}add(){this.__instanceIndex>=0||(this.renderer.add(this),P.markAsInstancedRendered(this.object,!0))}remove(s){if(!(this.__instanceIndex<0)&&(this.renderer.remove(this,s),P.markAsInstancedRendered(this.object,!1),s)){const t=Ju.all.indexOf(this);t>=0&&Ju.all.splice(t,1)}}};let Zc=Ju;a(Zc,"all",[]);class dx{constructor(t,i,n,o,r){a(this,"allowResize",!0),a(this,"name",""),a(this,"geometry"),a(this,"material"),a(this,"_context"),a(this,"_batchedMesh"),a(this,"_handles",[]),a(this,"_geometryIds",new Map),a(this,"_maxInstanceCount"),a(this,"_currentInstanceCount",0),a(this,"_currentVertexCount",0),a(this,"_currentIndexCount",0),a(this,"_maxVertexCount"),a(this,"_maxIndexCount"),a(this,"_needUpdateBounds",!1),a(this,"_debugMaterial",null),a(this,"onBeforeRender",()=>{this._batchedMesh.layers.enableAll(),this._needUpdateBounds&&this._batchedMesh[gc]===!0&&(ui&&console.log("Update instancing bounds",this.name,this._batchedMesh.matrixWorldNeedsUpdate),this.updateBounds())}),a(this,"onAfterRender",()=>{this._batchedMesh.layers.disableAll()}),a(this,"_availableBuckets",new Array),a(this,"_usedBuckets",new Array),this.name=t,this.geometry=i,this.material=n,this._context=r,this._maxInstanceCount=Math.max(2,o),ui&&(this._debugMaterial=ux());const l=this.tryEstimateVertexCountSize(this._maxInstanceCount,[i],o);this._maxVertexCount=l.vertexCount,this._maxIndexCount=l.indexCount,this._batchedMesh=new iv(this._maxInstanceCount,this._maxVertexCount,this._maxIndexCount,this._debugMaterial??this.material),this._batchedMesh[gc]=!0,this._batchedMesh.visible=!0,this._context.scene.add(this._batchedMesh),n instanceof tv&&(n.defines.USE_INSTANCING=!0,n.needsUpdate=!0),r.pre_render_callbacks.push(this.onBeforeRender),r.post_render_callbacks.push(this.onAfterRender),ui&&console.log(`Instanced renderer created with ${this._maxInstanceCount} instances, ${this._maxVertexCount} max vertices and ${this._maxIndexCount} max indices for "${t}"`)}get batchedMesh(){return this._batchedMesh}get visible(){return this._batchedMesh.visible}set visible(t){this._batchedMesh.visible=t}get castShadow(){return this._batchedMesh.castShadow}set castShadow(t){this._batchedMesh.castShadow=t}set receiveShadow(t){this._batchedMesh.receiveShadow=t}get count(){return this._currentInstanceCount}updateBounds(t=!0,i=!0){this._needUpdateBounds=!1,t&&this._batchedMesh.computeBoundingBox(),i&&this._batchedMesh.computeBoundingSphere()}canAdd(t,i){return this._maxVertexCount>1e7||i!==this.material||!this.validateGeometry(t)?!1:!!(!this.mustGrow(t)||this.allowResize)}dispose(){ui&&console.warn("Dispose instanced renderer",this.name),this._context.scene.remove(this._batchedMesh),this._batchedMesh.dispose(),this._batchedMesh=null,this._handles=[]}addInstance(t){const i=new Zc(t,this);t.castShadow===!0&&this._batchedMesh.castShadow===!1&&(this._batchedMesh.castShadow=!0),t.receiveShadow===!0&&this._batchedMesh.receiveShadow===!1&&(this._batchedMesh.receiveShadow=!0);try{this.add(i)}catch(n){if(console.error(`Failed adding mesh to instancing (object name: "${t.name}", instances: ${this._currentInstanceCount.toLocaleString()}/${this._maxInstanceCount.toLocaleString()}, vertices: ${this._currentVertexCount.toLocaleString()}/${this._maxVertexCount.toLocaleString()}, indices: ${this._currentIndexCount.toLocaleString()}/${this._maxIndexCount.toLocaleString()})
@@ -1198,7 +1198,7 @@ dateFormat X
1198
1198
  axisFormat %s
1199
1199
  `;const g=Array.from(r),y=new Set;for(const w of g)if(w.affectedObjects&&typeof w.affectedObjects!="string"){if(Array.isArray(w.affectedObjects))for(const _ of w.affectedObjects)y.add(_);else y.add(w.affectedObjects);l&&(p+=`section ${w.animationName} (${w.id})
1200
1200
  `,p+=`${w.id} : ${w.start}, ${w.duration}s
1201
- `)}l&&console.log(p);const f=new Set;for(const w of y){w.getPath||console.error("USDZExporter: Animation target object has no getPath method. This is likely a bug",w);let _=w.getPath();_.startsWith("<")&&(_=_.substring(1)),_.endsWith(">")&&(_=_.substring(0,_.length-1)),f.add({path:_,obj:w})}const v=Array.from(f).sort((w,_)=>w.path.length-_.path.length),b=new Array;for(let w=0;w<v.length;w++)for(let _=w+1;_<v.length;_++)if(v[_].path.startsWith(v[w].path)){const C=v[_],R=v[w];b.push({child:C.obj.displayName+" ("+C.path+")",parent:R.obj.displayName+" ("+R.path+")"})}b.length&&console.warn("USDZExporter: There are overlapping PlayAnimation actions. This can lead to undefined runtime behaviour when playing multiple animations. Please restructure the hierarchy so that animations don't overlap.",{overlappingTargets:b,playAnimationActions:r})}for(const p of new Set([...i,...n]))if(Array.isArray(p))for(const g of p)o.add(g.uuid);else o.add(p.uuid);cp&&console.log("All Behavior trigger sources and action targets",i,n,o),this.targetUuids=new Set(o)}onAfterHierarchy(t,i){var n;if((n=this.behaviours)!=null&&n.length){i.beginBlock('def Scope "Behaviors"');for(const o of this.behaviours)o.writeTo(this,t.document,i);i.closeBlock()}}async onAfterSerialize(t){cp&&console.log("onAfterSerialize behaviours",this.behaviourComponentsCopy);for(const i of this.behaviourComponentsCopy)typeof i.afterSerialize=="function"&&(i.afterSerialize.constructor.name==="AsyncFunction"?await i.afterSerialize(this,t):i.afterSerialize(this,t));for(const{clipUrl:i,filesKey:n}of this.audioClipsCopy){if(t.files[n])return;const o=await(await(await fetch(i)).blob()).arrayBuffer(),r=new Uint8Array(o);t.files[n]=r}this.behaviourComponentsCopy.length=0,this.audioClipsCopy.length=0}}var pT=Object.defineProperty,mT=Object.getOwnPropertyDescriptor,$e=(s,t,i,n)=>{for(var o=n>1?void 0:n?mT(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&pT(t,i,o),o};const zx=O("debugusdzbehaviours");function oh(s){s&&(s.getComponentInParent(Fc)||(F()&&console.debug('Raycaster on "'+s.name+'" was automatically added, because no raycaster was found in the parent hierarchy.'),s.addComponent(Ti)))}class $r extends A{constructor(){super(...arguments),a(this,"object"),a(this,"target"),a(this,"duration",1),a(this,"relativeMotion",!1),a(this,"coroutine",null),a(this,"targetPos",new x),a(this,"targetRot",new V),a(this,"targetScale",new x)}start(){oh(this.gameObject)}onPointerClick(t){t.use(),this.coroutine&&this.stopCoroutine(this.coroutine),this.relativeMotion?this.coroutine=this.startCoroutine(this.moveRelative()):this.coroutine=this.startCoroutine(this.moveToTarget())}*moveToTarget(){if(!this.target||!this.object)return;const t=ee(this.object).clone(),i=ee(this.target).clone(),n=Se(this.object).clone(),o=Se(this.target).clone(),r=Ke(this.object).clone(),l=Ke(this.target).clone(),c=t.distanceTo(i),h=n.angleTo(o),d=r.distanceTo(l);if(c<.01&&h<.01&&d<.01){lt(this.object,i),qi(this.object,o),Oa(this.object,l),this.coroutine=null;return}let u=0,p=0;for(;u<1;)u+=this.context.time.deltaTime/this.duration,u>1&&(u=1),p=u<.5?4*u*u*u:1-Math.pow(-2*u+2,3)/2,this.targetPos.lerpVectors(t,i,p),this.targetRot.slerpQuaternions(n,o,p),this.targetScale.lerpVectors(r,l,p),lt(this.object,this.targetPos),qi(this.object,this.targetRot),Oa(this.object,this.targetScale),yield;this.coroutine=null}*moveRelative(){if(!this.target||!this.object)return;const t=this.object.position.clone(),i=this.object.quaternion.clone(),n=this.object.scale.clone(),o=this.target.position.clone(),r=this.target.quaternion.clone(),l=this.target.scale.clone();o.applyQuaternion(this.object.quaternion),this.targetPos.copy(this.object.position).add(o),this.targetRot.copy(this.object.quaternion).multiply(r),this.targetScale.copy(this.object.scale).multiply(l);let c=0,h=0;for(;c<1;)c+=this.context.time.deltaTime/this.duration,c>1&&(c=1),h=c<.5?4*c*c*c:1-Math.pow(-2*c+2,3)/2,this.object.position.lerpVectors(t,this.targetPos,h),this.object.quaternion.slerpQuaternions(i,this.targetRot,h),this.object.scale.lerpVectors(n,this.targetScale,h),yield;this.coroutine=null}beforeCreateDocument(t){var i;if(this.target&&this.object&&this.gameObject){const n=new bt("Move to "+((i=this.target)==null?void 0:i.name),_t.tapTrigger(this.gameObject),ue.transformAction(this.object,this.target,this.duration,this.relativeMotion?"relative":"absolute"));t.addBehavior(n)}}}$e([m(j)],$r.prototype,"object",2),$e([m(j)],$r.prototype,"target",2),$e([m()],$r.prototype,"duration",2),$e([m()],$r.prototype,"relativeMotion",2);var dp;const sn=(dp=class extends A{constructor(){super(...arguments),a(this,"materialToSwitch"),a(this,"variantMaterial"),a(this,"fadeDuration",0),a(this,"_objectsWithThisMaterial",null),a(this,"selfModel"),a(this,"targetModels")}start(){var s;this._objectsWithThisMaterial=this.objectsWithThisMaterial,oh(this.gameObject),F()&&this._objectsWithThisMaterial.length<=0&&console.warn('ChangeMaterialOnClick: No objects found with material "'+((s=this.materialToSwitch)==null?void 0:s.name)+'"')}onPointerEnter(s){this.context.input.setCursorPointer()}onPointerExit(s){this.context.input.setCursorNormal()}onPointerClick(s){if(s.use(),!!this.variantMaterial)for(let t=0;t<this.objectsWithThisMaterial.length;t++){const i=this.objectsWithThisMaterial[t];i.material=this.variantMaterial}}get objectsWithThisMaterial(){return this._objectsWithThisMaterial!=null?this._objectsWithThisMaterial:(this._objectsWithThisMaterial=[],this.variantMaterial&&this.materialToSwitch&&this.context.scene.traverse(s=>{if(s instanceof Q)if(Array.isArray(s.material)){for(const t of s.material)if(t===this.materialToSwitch){this.objectsWithThisMaterial.push(s);break}}else s.material===this.materialToSwitch?this.objectsWithThisMaterial.push(s):g_(s.material,this.materialToSwitch)&&this.objectsWithThisMaterial.push(s)}),this._objectsWithThisMaterial)}async beforeCreateDocument(s,t){this.targetModels=[],sn._materialTriggersPerId={},sn.variantSwitchIndex=0,this.materialToSwitch&&await et.assignTextureLOD(this.materialToSwitch,0),this.variantMaterial&&await et.assignTextureLOD(this.variantMaterial,0)}createBehaviours(s,t,i){this.objectsWithThisMaterial.find(n=>n.uuid===t.uuid)&&this.targetModels.push(t),this.gameObject.uuid===t.uuid&&(this.selfModel=t,this.materialToSwitch&&(sn._materialTriggersPerId[this.materialToSwitch.uuid]||(sn._materialTriggersPerId[this.materialToSwitch.uuid]=[]),sn._materialTriggersPerId[this.materialToSwitch.uuid].push(this)))}afterCreateDocument(s,t){if(!this.materialToSwitch)return;const i=sn._materialTriggersPerId[this.materialToSwitch.uuid];if(i){const n={};for(const o of i){const r=o.createVariants();r&&r.length>0&&(n[o.selfModel.uuid]=r)}for(const o of i){const r=[];for(const l in n)l!==o.selfModel.uuid&&r.push(...n[l]);o.createAndAttachBehaviors(s,n[o.selfModel.uuid],r)}}delete sn._materialTriggersPerId[this.materialToSwitch.uuid]}createAndAttachBehaviors(s,t,i){const n=[],o=[],r=Math.max(0,this.fadeDuration);o.push(ue.fadeAction([...this.targetModels,...i],r,!1)),n.push(ue.fadeAction(t,r,!1)),o.push(ue.fadeAction(t,r,!0)),s.addBehavior(new bt("Select_"+this.selfModel.name,_t.tapTrigger(this.selfModel),ue.parallel(...o))),s.addBehavior(new bt("StartHidden_"+this.selfModel.name,_t.sceneStartTrigger(),ue.parallel(...n)))}static getMaterialName(s){return Ms(s.name||"Material")+"_"+s.id}createVariants(){if(!this.variantMaterial)return null;const s=[];for(const t of this.targetModels){const i=t.clone();i.name+="_Variant_"+sn.variantSwitchIndex+++"_"+sn.getMaterialName(this.variantMaterial),i.displayName=i.displayName+": Variant with material "+this.variantMaterial.name,i.material=this.variantMaterial,i.geometry=t.geometry,i.transform=t.transform,(!t.parent||!t.parent.isEmpty())&&Zt.createEmptyParent(t),t.parent&&t.parent.add(i),s.push(i)}return s}},a(dp,"_materialTriggersPerId",{}),a(dp,"variantSwitchIndex",0),dp);let ml=sn;$e([m(Oe)],ml.prototype,"materialToSwitch",2),$e([m(Oe)],ml.prototype,"variantMaterial",2),$e([m()],ml.prototype,"fadeDuration",2);var gl;const qe=(gl=class extends A{constructor(){super(...arguments),a(this,"target"),a(this,"toggleOnClick",!1),a(this,"targetState",!0),a(this,"hideSelf",!0),a(this,"selfModel"),a(this,"selfModelClone"),a(this,"targetModel"),a(this,"toggleModel"),a(this,"stateBeforeCreatingDocument",!1),a(this,"targetStateBeforeCreatingDocument",!1)}start(){oh(this.gameObject)}onPointerClick(s){s.use(),!this.toggleOnClick&&this.hideSelf&&(this.gameObject.visible=!1),this.target&&(this.target.visible=this.toggleOnClick?!this.target.visible:this.targetState)}createBehaviours(s,t,i){t.uuid===this.gameObject.uuid&&(this.selfModel=t,this.selfModelClone=t.clone())}beforeCreateDocument(){this.target&&(this.gameObject[qe.wasVisible]===void 0&&(this.gameObject[qe.wasVisible]=this.gameObject.activeSelf),this.target[qe.wasVisible]===void 0&&(this.target[qe.wasVisible]=this.target.activeSelf),this.stateBeforeCreatingDocument=this.gameObject[qe.wasVisible],this.targetStateBeforeCreatingDocument=this.target[qe.wasVisible],this.gameObject.visible=!0,this.target.visible=!0)}afterCreateDocument(s,t){if(!this.target)return;this.targetModel=t.document.findById(this.target.uuid);const i=this.selfModel;if(this.selfModel&&this.targetModel){let n=this.selfModel,o=this.targetState;if(this.toggleOnClick)if(o=!this.targetStateBeforeCreatingDocument,!this.selfModelClone.geometry)(!this.selfModel.parent||this.selfModel.parent.isEmpty())&&Jf.createEmptyParent(this.selfModel),this.toggleModel=this.selfModel.deepClone(),this.toggleModel.name+="_toggle",this.selfModel.parent.add(this.toggleModel);else{if(!this.gameObject[qe.toggleClone]){const c=this.selfModelClone.clone();c.setMatrix(new ne),c.name+="_toggle"+qe.clonedToggleIndex++,i.add(c),this.gameObject[qe.toggleClone]=c,console.warn("USDZExport: Toggle "+this.gameObject.name+" doesn't have geometry. It will be deep cloned and nested behaviours will likely not work.")}const l=this.gameObject[qe.toggleClone];if(!this.gameObject[qe.reverseToggleClone]){const c=this.selfModelClone.clone();c.setMatrix(new ne),c.name+="_toggleReverse"+qe.clonedToggleIndex++,i.add(c),this.gameObject[qe.reverseToggleClone]=c}this.toggleModel=this.gameObject[qe.reverseToggleClone],(!this.toggleModel.geometry||!l.geometry)&&console.error("triggers without childs and without geometry won't work!",this,i.geometry),n=l,i.geometry=null,i.material=null}if(this.toggleModel){if(this.toggleOnClick){const l=[];l.push(ue.fadeAction(n,0,!1)),l.push(ue.fadeAction(this.toggleModel,0,!0)),l.push(ue.fadeAction(this.targetModel,0,o)),s.addBehavior(new bt("Toggle_"+n.name+"_toggleTo"+(o?"On":"Off"),_t.tapTrigger(n),ue.parallel(...l)));const c=[];c.push(ue.fadeAction(this.toggleModel,0,!1)),c.push(ue.fadeAction(n,0,!0)),c.push(ue.fadeAction(this.targetModel,0,!o)),s.addBehavior(new bt("Toggle_"+n.name+"_toggleTo"+(o?"Off":"On"),_t.tapTrigger(this.toggleModel),ue.parallel(...c)))}}else{const l=[];this.hideSelf&&l.push(ue.fadeAction(n,0,!1)),l.push(ue.fadeAction(this.targetModel,0,o)),s.addBehavior(new bt("Toggle_"+n.name+"_toggleTo"+(o?"On":"Off"),_t.tapTrigger(n),ue.parallel(...l)))}const r=new Array;this.targetStateBeforeCreatingDocument||r.push(this.targetModel),this.stateBeforeCreatingDocument||r.push(i),this.toggleModel&&r.push(this.toggleModel),s.addBehavior(new bt("HideOnStart_"+this.gameObject.name,_t.sceneStartTrigger(),ue.fadeAction(r,0,!1)))}}afterSerialize(s,t){this.gameObject[qe.wasVisible]!==void 0&&(this.gameObject.visible=this.gameObject[qe.wasVisible],delete this.gameObject[qe.wasVisible]),this.target&&this.target[qe.wasVisible]!==void 0&&(this.target.visible=this.target[qe.wasVisible],delete this.target[qe.wasVisible]),delete this.gameObject[qe.toggleClone],delete this.gameObject[qe.reverseToggleClone]}},a(gl,"clonedToggleIndex",0),a(gl,"wasVisible",Symbol("usdz_SetActiveOnClick_wasVisible")),a(gl,"toggleClone",Symbol("clone for toggling")),a(gl,"reverseToggleClone",Symbol("clone for reverse toggling")),gl);let qr=qe;$e([m(j)],qr.prototype,"target",2),$e([m()],qr.prototype,"toggleOnClick",2),$e([m()],qr.prototype,"targetState",2),$e([m()],qr.prototype,"hideSelf",2);class u0 extends A{constructor(){super(...arguments),a(this,"wasVisible",!1)}start(){P.setActive(this.gameObject,!1)}createBehaviours(t,i,n){i.uuid===this.gameObject.uuid&&(this.wasVisible||t.addBehavior(new bt("HideOnStart_"+this.gameObject.name,_t.sceneStartTrigger(),ue.fadeAction(i,0,!1))))}beforeCreateDocument(){this.wasVisible=P.isActiveSelf(this.gameObject)}}class fl extends A{constructor(){super(...arguments),a(this,"target"),a(this,"duration",.5),a(this,"motionType","bounce")}beforeCreateDocument(){}createBehaviours(t,i,n){if(this.target&&i.uuid===this.gameObject.uuid){const o=new bt("emphasize "+this.name,_t.tapTrigger(this.gameObject),ue.emphasize(this.target,this.duration,this.motionType,void 0,"basic"));t.addBehavior(o)}}afterCreateDocument(t,i){}}$e([m()],fl.prototype,"target",2),$e([m()],fl.prototype,"duration",2),$e([m()],fl.prototype,"motionType",2);class jo extends A{constructor(){super(...arguments),a(this,"target"),a(this,"clip",""),a(this,"toggleOnClick",!1),a(this,"trigger","tap")}start(){oh(this.gameObject)}ensureAudioSource(){if(!this.target){const t=this.gameObject.addComponent(We);t&&(this.target=t,t.spatialBlend=1,t.volume=1,t.loop=!1,t.preload=!0)}}onPointerClick(t){var i;t.use(),!(!((i=this.target)!=null&&i.clip)&&!this.clip)&&(this.ensureAudioSource(),this.target&&(this.target.isPlaying&&this.toggleOnClick?this.target.stop():(!this.toggleOnClick&&this.target.isPlaying&&this.target.stop(),this.clip?this.target.play(this.clip):this.target.play())))}createBehaviours(t,i,n){if(!(!this.target&&!this.clip)&&i.uuid===this.gameObject.uuid){const o=this.clip?this.clip:this.target?this.target.clip:void 0;if(!o||typeof o!="string")return;const r=this.target?this.target.gameObject:this.gameObject;lr.getName(o);const l=this.target?this.target.volume:1,c=this.target&&this.target.spatialBlend==0?"nonSpatial":"spatial";let h=!1;this.gameObject.traverse(g=>{g instanceof Q&&g.visible&&(h=!0)}),h=!0;const d=t.addAudioClip(o);let u=ue.playAudioAction(r,d,"play",l,c);this.target&&this.target.loop&&(u=ue.sequence(u).makeLooping());const p=this.name?"_"+this.name:"";if(h&&this.trigger==="tap"){this.toggleOnClick&&(u.multiplePerformOperation="stop");const g=new bt("playAudio"+p,_t.tapTrigger(i),u);t.addBehavior(g)}if(this.target&&this.target.playOnAwake&&this.target.enabled)if(h&&this.trigger==="tap")console.warn("USDZExport: Audio sources that are played on tap can't also auto-play at scene start due to a QuickLook bug.");else{const g=new bt("playAudioOnStart"+p,_t.sceneStartTrigger(),u);t.addBehavior(g)}}}}$e([m(We)],jo.prototype,"target",2),$e([m(URL)],jo.prototype,"clip",2),$e([m()],jo.prototype,"toggleOnClick",2);var up;const nn=(up=class extends A{constructor(){super(...arguments),a(this,"animator"),a(this,"stateName"),a(this,"trigger","tap"),a(this,"animation"),a(this,"selfModel"),a(this,"stateAnimationModel"),a(this,"animationSequence",new Array),a(this,"animationLoopAfterSequence",new Array),a(this,"randomOffsetNormalized",0)}get target(){var s,t;return((s=this.animator)==null?void 0:s.gameObject)||((t=this.animation)==null?void 0:t.gameObject)}start(){oh(this.gameObject)}onPointerClick(s){var t;s.use(),this.target&&this.stateName&&((t=this.animator)==null||t.play(this.stateName,0,0,.1))}createBehaviours(s,t,i){t.uuid===this.gameObject.uuid&&(this.selfModel=t)}afterSerialize(){if(nn.rootsWithExclusivePlayback.size>1){const s='Multiple root objects targeted by more than one animation. To work around QuickLook bug FB13410767, animations will be set as "exclusive" and activating them will stop other animations being marked as exclusive.';F()&&_e(s),console.warn(s,...nn.rootsWithExclusivePlayback)}nn.animationActions=[],nn.rootsWithExclusivePlayback=new Set}afterCreateDocument(s,t){if(this.animationSequence===void 0&&this.animationLoopAfterSequence===void 0||!this.stateAnimationModel||!this.target)return;const i=t.document,n=t.extensions.find(l=>l instanceof nh);if(!n)return;const o=n.getClipCount(this.target)>1;o&&(F()&&console.warn("Setting exclusive playback for "+this.target.name+"@"+this.stateName+" because it has "+n.getClipCount(this.target)+" animations. This works around QuickLook bug FB13410767."),nn.rootsWithExclusivePlayback.add(this.target));const r=this.name?this.name:"";i.traverse(l=>{var c,h;if(l.uuid===((c=this.target)==null?void 0:c.uuid)){const d=nn.getActionForSequences(i,l,this.animationSequence,this.animationLoopAfterSequence,this.randomOffsetNormalized),u=new bt(this.trigger+"_"+r+"_toPlayAnimation_"+this.stateName+"_on_"+((h=this.target)==null?void 0:h.name),this.trigger=="tap"?_t.tapTrigger(this.selfModel):_t.sceneStartTrigger(),d);o&&u.makeExclusive(!0),s.addBehavior(u)}})}static getActionForSequences(s,t,i,n,o){const r=(c,h)=>{let d=nn.animationActions.find(u=>u.affectedObjects==c&&u.start==h.start&&u.duration==h.duration&&u.animationSpeed==h.speed);return d||(d=ue.startAnimationAction(c,h),nn.animationActions.push(d)),d},l=ue.sequence();if(i&&i.length>0)for(const c of i)l.addAction(r(t,c));if(n&&n.length>0){const c=l.actions.length==0?l:ue.sequence();for(const h of n)c.addAction(r(t,h));c.makeLooping(),l!==c&&l.addAction(c)}return o&&o>0&&l.actions.unshift(ue.waitAction(o)),l}static getAndRegisterAnimationSequences(s,t,i){var n,o,r,l,c,h,d,u;if(!t)return;const p=t.getComponent(Pt),g=t.getComponent(Ut);if(!p&&!g)return;if(p&&!i)throw new Error("PlayAnimationOnClick: No stateName specified for animator "+p.name+" on "+t.name);let y=[],f=[];if(g){const M=s.registerAnimation(t,g.clip);M&&(g.loop?f.push(M):y.push(M));let E=0;if(g.minMaxOffsetNormalized){const D=g.minMaxOffsetNormalized.x,L=g.minMaxOffsetNormalized.y;E=(((n=g.clip)==null?void 0:n.duration)||1)*(D+Math.random()*(L-D))}return{animationSequence:y,animationLoopAfterSequence:f,randomTimeOffset:E}}const v=p?.runtimeAnimatorController;let b=v?.findState(i),w=[],_=[];if(v&&b){const M=new Array;M.push(b);let E=!1;for(;M.length<100;){if(!b||b===null||!b.transitions||b.transitions.length===0){(o=b.motion)!=null&&o.isLooping&&(E=!0);break}const D=b.transitions.find(U=>U.conditions.length===0),L=D?v.getState(D.destinationState,0):null;if(L&&M.includes(L)){b=L,E=!0;break}else if(D){if(b=L,!b)break;M.push(b)}else{E=((r=b.motion)==null?void 0:r.isLooping)??!1;break}}if(E&&b){const D=M.indexOf(b);w=M.slice(0,D),_=M.slice(D),zx&&console.log("found loop from "+i,"states until loop",w,"states looping",_)}else w=M,_=[],zx&&console.log("found no loop from "+i,"states",w);if(!_.length){const D=w[w.length-1],L=(l=D.motion)==null?void 0:l.clip;if(L){let U;if(s.holdClipMap.has(L))U=s.holdClipMap.get(L);else{const z=D.name+"_hold";U=L.clone(),U.duration=1,U.name=z;const H=L.duration;U.tracks=L.tracks.map(T=>{const I=T.clone();I.times=new Float32Array([0,H]);const G=T.values.length,J=T.getValueSize(),se=T.values.slice(G-J,G);return I.values=new Float32Array(2*J),I.values.set(se,0),I.values.set(se,J),I}),U.name=z,s.holdClipMap.set(L,U)}if(U){const z={name:U.name,motion:{clip:U,isLooping:!1,name:U.name},speed:1,transitions:[],behaviours:[],hash:D.hash+1};_.push(z)}}}}if(w.length===1&&(!((c=w[0].motion)!=null&&c.clip)||((d=(h=w[0].motion)==null?void 0:h.clip.tracks)==null?void 0:d.length)===0)){y=new Array;const M=s.registerAnimation(t,null);M&&y.push(M);return}if(w=w.filter(M=>{var E,D,L;return((E=M.motion)==null?void 0:E.clip)&&((L=(D=M.motion)==null?void 0:D.clip.tracks)==null?void 0:L.length)>0}),_=_.filter(M=>{var E,D,L;return((E=M.motion)==null?void 0:E.clip)&&((L=(D=M.motion)==null?void 0:D.clip.tracks)==null?void 0:L.length)>0}),w.length===0&&_.length===0){console.warn("No clips found for state "+i+" on "+p?.name+", can't export animation data");return}const C=(M,E)=>{if(!t)return;const D=s.registerAnimation(t,M.motion.clip??null);D?(D.speed=M.speed,E.push(D)):console.warn("Couldn't register animation for state "+M.name+" on "+p?.name)};if(w.length>0){y=new Array;for(const M of w)C(M,y)}if(_.length>0){f=new Array;for(const M of _)C(M,f)}let R=0;if(p&&v&&p.minMaxOffsetNormalized){const M=p.minMaxOffsetNormalized.x,E=p.minMaxOffsetNormalized.y,D=w.length?w[0]:_.length?_[0]:null;R=(((u=D?.motion.clip)==null?void 0:u.duration)||1)*(M+Math.random()*(E-M))}return{animationSequence:y,animationLoopAfterSequence:f,randomTimeOffset:R}}createAnimation(s,t,i){if(!this.target||!this.animator&&!this.animation)return;const n=nn.getAndRegisterAnimationSequences(s,this.target,this.stateName);n&&(this.animationSequence=n.animationSequence,this.animationLoopAfterSequence=n.animationLoopAfterSequence,this.randomOffsetNormalized=n.randomTimeOffset,this.stateAnimationModel=t)}},a(up,"animationActions",[]),a(up,"rootsWithExclusivePlayback",new Set),up);let Gr=nn;$e([m(Pt)],Gr.prototype,"animator",2),$e([m()],Gr.prototype,"stateName",2);class yl extends A{constructor(){super(...arguments),a(this,"target")}getType(){}getDuration(){}}$e([m(j)],yl.prototype,"target",2);class rh extends A{constructor(){super(...arguments),a(this,"target")}}$e([m(yl)],rh.prototype,"target",2);class ah extends yl{constructor(){super(...arguments),a(this,"type",1),a(this,"duration",1)}getType(){switch(this.type){case 1:return"hide";case 0:return"show"}}getDuration(){return this.duration}}$e([m()],ah.prototype,"type",2),$e([m()],ah.prototype,"duration",2);class p0 extends rh{}class pp{get extensionName(){return"Physics"}onExportObject(t,i,n){const o=P.getComponents(t,ye).filter(h=>h.enabled),r=P.getComponents(t,hi).filter(h=>h.enabled&&!h.isTrigger);let l=o.length>0?o[0]:null;const c=r.length>0?r[0]:null;c&&!l&&(l=new ye,l.isKinematic=!0),l&&i.addEventListener("serialize",(h,d)=>{var u,p,g;if(l){if(h.appendLine(),h.beginBlock('def RealityKitComponent "RigidBody"',"{",!0),l.useGravity||h.appendLine("bool gravityEnabled = 0"),h.appendLine('uniform token info:id = "RealityKit.RigidBody"'),l.isKinematic&&h.appendLine('token motionType = "Kinematic"'),h.beginBlock('def RealityKitStruct "massFrame"',"{",!0),h.appendLine(`float m_mass = ${l.mass}`),h.beginBlock('def RealityKitStruct "m_pose"',"{",!0),h.appendLine(`float3 position = (${l.centerOfMass.x}, ${l.centerOfMass.y}, ${l.centerOfMass.z})`),h.closeBlock("}"),h.closeBlock("}"),r.length>0){const y=r[0];h.beginBlock('def RealityKitStruct "material"',"{",!0);const f=y.sharedMaterial;f&&f.dynamicFriction!==void 0&&h.appendLine(`double dynamicFriction = ${(u=y.sharedMaterial)==null?void 0:u.dynamicFriction}`),f&&f.bounciness!==void 0&&h.appendLine(`double restitution = ${(p=y.sharedMaterial)==null?void 0:p.bounciness}`),f&&f.staticFriction!==void 0&&h.appendLine(`double staticFriction = ${(g=y.sharedMaterial)==null?void 0:g.staticFriction}`),h.closeBlock("}")}h.closeBlock("}")}}),c&&(i.addEventListener("serialize",(h,d)=>{var u;h.beginBlock('def RealityKitComponent "Collider"',"{",!0),h.appendLine("uint group = 1"),h.appendLine('uniform token info:id = "RealityKit.Collider"'),h.appendLine("uint mask = 4294967295");const p=c.isTrigger?"Trigger":"Default";if(h.appendLine(`token type = "${p}"`),h.beginBlock('def RealityKitStruct "Shape"',"{",!0),c instanceof Za){const g=c;h.appendLine('token shapeType = "Sphere"'),h.appendLine(`float radius = ${g.radius}`)}else if(c instanceof Ja){const g=c;h.appendLine('token shapeType = "Box"'),h.appendLine(`float3 extent = (${g.size.x}, ${g.size.y}, ${g.size.z})`)}else if(c instanceof In){const g=c;h.appendLine('token shapeType = "Capsule"'),h.appendLine(`float radius = ${g.radius}`),h.appendLine(`float height = ${g.height}`)}else if(c instanceof Eo&&(u=c.sharedMesh)!=null&&u.geometry){const g=c.sharedMesh.geometry;g.boundingBox||g.computeBoundingBox();const y=c.sharedMesh.geometry.boundingBox;y&&(h.appendLine('token shapeType = "Box"'),h.appendLine(`float3 extent = (${y.max.x-y.min.x}, ${y.max.y-y.min.y}, ${y.max.z-y.min.z})`),console.log("[USDZ] Only Box, Sphere, and Capsule colliders are supported in visionOS/iOS. MeshCollider will be exported as Box",c))}else console.warn("[USDZ] Only Box, Sphere, and Capsule colliders are supported in visionOS/iOS. Ignoring collider:",c);h.beginBlock('def RealityKitStruct "pose"',"{",!0),h.closeBlock("}"),h.closeBlock("}"),h.closeBlock("}")}),r.length>1&&console.log("WARNING: Multiple colliders detected. visionOS / iOS can only support objects with a single collider, only exporting the first collider: ",c))}}class m0{get extensionName(){return"DocumentExtension"}onAfterBuildDocument(t){}}var gT=Object.defineProperty,fT=Object.getOwnPropertyDescriptor,lh=(s,t,i,n)=>{for(var o=n>1?void 0:n?fT(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&gT(t,i,o),o};const g0=O("debugui"),f0=O("debuguilayout");class y0{constructor(){a(this,"width"),a(this,"height")}}class v0{constructor(){a(this,"x"),a(this,"y"),a(this,"width"),a(this,"height")}}const Rs=new x,ch=new ne,mp=new V,Ux=class extends ls{constructor(){super(...arguments),a(this,"_anchoredPosition"),a(this,"sizeDelta",new oe(100,100)),a(this,"pivot",new oe(.5,.5)),a(this,"anchorMin",new oe(0,0)),a(this,"anchorMax",new oe(1,1)),a(this,"minWidth"),a(this,"minHeight"),a(this,"lastMatrix"),a(this,"rectBlock"),a(this,"_transformNeedsUpdate",!1),a(this,"_initialPosition"),a(this,"_parentRectTransform"),a(this,"_lastUpdateFrame",-1),a(this,"_lastAnchoring"),a(this,"_createdBlocks",[]),a(this,"_createdTextBlocks",[])}get parent(){return this._parentRectTransform}get translation(){return this.gameObject.position}get rotation(){return this.gameObject.quaternion}get scale(){return this.gameObject.scale}get anchoredPosition(){return this._anchoredPosition||(this._anchoredPosition=new oe),this._anchoredPosition}set anchoredPosition(s){this._anchoredPosition=s}get width(){let s=this.sizeDelta.x;if(this.anchorMin.x!==this.anchorMax.x&&this._parentRectTransform){const t=this._parentRectTransform.width,i=this.anchorMax.x-this.anchorMin.x;s=t*i,s+=this.sizeDelta.x}return this.minWidth!==void 0&&s<this.minWidth?this.minWidth:s}get height(){let s=this.sizeDelta.y;if(this.anchorMin.y!==this.anchorMax.y&&this._parentRectTransform){const t=this._parentRectTransform.height,i=this.anchorMax.y-this.anchorMin.y;s=t*i,s+=this.sizeDelta.y}return this.minHeight!==void 0&&s<this.minHeight?this.minHeight:s}awake(){super.awake(),this._anchoredPosition||(this._anchoredPosition=new oe),this.lastMatrix=new ne,this.rectBlock=new j,this.rectBlock.name=this.name,this._initialPosition=this.gameObject.position.clone(),this._initialPosition.z=0,Xa(this,"_anchoredPosition",()=>{this.markDirty()}),Xa(this,"sizeDelta",()=>{this.markDirty()}),Xa(this,"pivot",()=>{this.markDirty()}),Xa(this,"anchorMin",()=>{this.markDirty()}),Xa(this,"anchorMax",()=>{this.markDirty()})}onEnable(){var s;super.onEnable(),this.rectBlock||(this.rectBlock=new j),this.lastMatrix||(this.lastMatrix=new ne),this._lastAnchoring||(this._lastAnchoring=new oe),this._initialPosition||(this._initialPosition=new x),this._anchoredPosition||(this._anchoredPosition=new oe),this.addShadowComponent(this.rectBlock),this._transformNeedsUpdate=!0,(s=this.canvas)==null||s.registerTransform(this)}onDisable(){var s;super.onDisable(),this.removeShadowComponent(),(s=this.canvas)==null||s.unregisterTransform(this)}onParentRectTransformChanged(s){this._transformNeedsUpdate||this.onApplyTransform(f0?`${s.name} changed`:void 0)}get isDirty(){return this._transformNeedsUpdate||(this._transformNeedsUpdate=!this.lastMatrix.equals(this.gameObject.matrix)),this._transformNeedsUpdate}markDirty(){this._transformNeedsUpdate||(f0&&console.warn("RectTransform markDirty()",this.name),this._transformNeedsUpdate=!0,this._lastUpdateFrame=-1)}updateTransform(){(this._transformNeedsUpdate||!this.lastMatrix.equals(this.gameObject.matrix))&&this.canUpdate()&&this.onApplyTransform(this._transformNeedsUpdate?"Marked dirty":"Matrix changed")}canUpdate(){return this._transformNeedsUpdate&&this.activeAndEnabled&&this._lastUpdateFrame!==this.context.time.frame}onApplyTransform(s){var t;if(this.context.time.frameCount===this._lastUpdateFrame)return;this._lastUpdateFrame=this.context.time.frameCount;const i=this.shadowComponent;if(!i)return;this.gameObject.parent?this._parentRectTransform=P.getComponentInParent(this.gameObject.parent,Ux):this._parentRectTransform=void 0,this._transformNeedsUpdate=!1,f0&&console.warn("RectTransform \u2192 ApplyTransform",this.name+" because "+s),this.isRoot()?this.Root.screenspace||(i.rotation.y=Math.PI):(i.matrix.identity(),i.matrixAutoUpdate=!1,Rs.set(0,0,0),this.applyPivot(Rs),i.matrix.setPosition(Rs.x,Rs.y,0),(this.gameObject.quaternion.x||this.gameObject.quaternion.y||this.gameObject.quaternion.z)&&(mp.copy(this.gameObject.quaternion),mp.x*=-1,mp.z*=-1,ch.makeRotationFromQuaternion(mp),i.matrix.premultiply(ch)),Rs.set(0,0,0),this.applyAnchoring(Rs),(t=this.canvas)!=null&&t.screenspace?Rs.z+=.1:Rs.z+=.01,ch.identity(),ch.setPosition(Rs.x,Rs.y,Rs.z),i.matrix.premultiply(ch),i.matrix.scale(this.gameObject.scale)),this.lastMatrix.copy(this.gameObject.matrix);const n=!0;for(const o of eu(this.gameObject,ls,n,1)){if(o===this||!o.activeAndEnabled)continue;const r=o;r.onParentRectTransformChanged&&r.onParentRectTransformChanged(this)}}applyAnchoring(s){this._lastAnchoring||(this._lastAnchoring=new oe);const t=this._lastAnchoring.sub(this._anchoredPosition);this.gameObject.position.x+=t.x,this.gameObject.position.y+=t.y,this._lastAnchoring.copy(this._anchoredPosition),s.x+=this._initialPosition.x-this.gameObject.position.x,s.y+=this._initialPosition.y-this.gameObject.position.y,s.z+=this._initialPosition.z-this.gameObject.position.z;const i=this._parentRectTransform;if(i){let n=0;const o=1-this.anchorMax.y-this.anchorMin.y;n-=i.height*.5*o,s.y+=n;let r=0;const l=1-this.anchorMax.x-this.anchorMin.x;r-=i.width*.5*l,s.x+=r}}applyPivot(s){if(this.pivot&&!this.isRoot()){const t=this.pivot.x-.5;s.x-=t*this.sizeDelta.x*this.gameObject.scale.x;const i=this.pivot.y-.5;s.y-=i*this.sizeDelta.y*this.gameObject.scale.y}}getBasicOptions(){const s={width:this.sizeDelta.x,height:this.sizeDelta.y,offset:0,backgroundOpacity:0,borderWidth:0,borderRadius:0,borderOpacity:0,letterSpacing:-.03};return this.ensureValidSize(s),s}ensureValidSize(s,t=1e-4){return s.width<=0&&(s.width=t),s.height<=0&&(s.height=1e-4),s}createNewBlock(s){s={...this.getBasicOptions(),...s},g0&&console.log(this.name,s);const t=new bv(s);return this._createdBlocks.push(t),t}createNewText(s){g0&&console.log(s),s={...this.getBasicOptions(),...s},g0&&console.log(this.name,s);const t=new vv(s);return this._createdTextBlocks.push(t),t}};let Wt=Ux;lh([m(oe)],Wt.prototype,"anchoredPosition",1),lh([m(oe)],Wt.prototype,"sizeDelta",2),lh([m(oe)],Wt.prototype,"pivot",2),lh([m(oe)],Wt.prototype,"anchorMin",2),lh([m(oe)],Wt.prototype,"anchorMax",2);var yT=Object.defineProperty,vT=Object.getOwnPropertyDescriptor,Nx=(s,t,i,n)=>{for(var o=n>1?void 0:n?vT(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&yT(t,i,o),o};class vl extends A{constructor(){super(...arguments),a(this,"effectColor"),a(this,"effectDistance")}}Nx([m(we)],vl.prototype,"effectColor",2),Nx([m(oe)],vl.prototype,"effectDistance",2);var bT=Object.defineProperty,_T=Object.getOwnPropertyDescriptor,Wx=(s,t,i,n)=>{for(var o=n>1?void 0:n?_T(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&bT(t,i,o),o};const gp={backgroundColor:new ae(1,1,1),backgroundOpacity:1,borderColor:new ae(1,1,1),borderOpacity:1};var b0;const hh=(b0=class extends ls{constructor(){super(...arguments),a(this,"_alphaFactor",1),a(this,"sRGBColor",new ae(1,0,1)),a(this,"raycastTarget",!0),a(this,"uiObject",null),a(this,"_color",null),a(this,"_rect",null),a(this,"_stateManager",null),a(this,"_currentlyCreatingPanel",!1)}get isGraphic(){return!0}get color(){return this._color||(this._color=new we(1,1,1,1)),this._color}set color(s){(!this._color||this._color.r!==s.r||this._color.g!==s.g||this._color.b!==s.b||this._color.alpha!==s.alpha)&&(this._color||(this._color=new we(1,1,1,1)),this._color.copy(s),this.onColorChanged())}setAlphaFactor(s){this._alphaFactor=s,this.onColorChanged()}get alphaFactor(){return this._alphaFactor}onColorChanged(){this.uiObject&&(this.sRGBColor.copy(this._color),this.sRGBColor.convertLinearToSRGB(),gp.backgroundColor=this.sRGBColor,gp.backgroundOpacity=this._color.alpha*this._alphaFactor,this.applyEffects(gp,this._alphaFactor),this.uiObject.set(gp),this.markDirty())}get m_Color(){return this._color}get rectTransform(){if(this._rect||(this._rect=P.getComponent(this.gameObject,Wt)),!this._rect)throw new Error("Not Supported: Make sure to add a RectTransform component before adding a UI Graphic component.");return this._rect}onParentRectTransformChanged(){var s;(s=this.uiObject)==null||s.set({width:this.rectTransform.width,height:this.rectTransform.height}),this.markDirty()}__internalNewInstanceCreated(s){return super.__internalNewInstanceCreated(s),this._rect=null,this.uiObject=null,this._color&&(this._color=this._color.clone()),this}setState(s){this.makePanel(),this.uiObject&&(this.uiObject.setState(s),this==null||this.markDirty())}setupState(s){this.makePanel(),this.uiObject&&(this._stateManager||(this._stateManager=new lO(this.uiObject)),this.uiObject.setupState(s.state,s.attributes))}setOptions(s){this.makePanel(),this.uiObject&&this.uiObject.set(s)}awake(){super.awake(),this.makePanel(),Xa(this,"_color",()=>yM(this,this.onColorChanged))}onEnable(){var s;super.onEnable(),this.uiObject&&((s=this.rectTransform.shadowComponent)==null||s.add(this.uiObject),this.addShadowComponent(this.uiObject,this.rectTransform))}onDisable(){super.onDisable(),this.uiObject&&this.removeShadowComponent()}makePanel(){if(this.uiObject||this._currentlyCreatingPanel)return;this._currentlyCreatingPanel=!0;const s=.015,t={backgroundColor:this.color,backgroundOpacity:this.color.alpha,offset:s};this.onBeforeCreate(t),this.applyEffects(t),this.onCreate(t),this.controlsChildLayout=!1,this._currentlyCreatingPanel=!1,this.onAfterCreated(),this.onColorChanged()}onBeforeCreate(s){}onCreate(s){this.uiObject=this.rectTransform.createNewBlock(s),this.uiObject.name=this.name}onAfterCreated(){}applyEffects(s,t=1){var i;const n=(i=this.gameObject)==null?void 0:i.getComponent(vl);n&&(n.effectDistance&&(s.borderWidth=Math.max(Math.abs(n.effectDistance.x),Math.abs(n.effectDistance.y))),n.effectColor&&(s.borderColor=n.effectColor,s.borderOpacity=n.effectColor.alpha*t))}async setTexture(s){if(this.setOptions({backgroundOpacity:0}),s){if(hh.textureCache.has(s))s=hh.textureCache.get(s);else if(!s.isRenderTargetTexture){const t=s.clone();t.colorSpace=pr,hh.textureCache.set(s,t),s=t}this.setOptions({backgroundImage:s,borderRadius:0,backgroundOpacity:this.color.alpha,backgroundSize:"stretch"}),et.assignTextureLOD(s,0).then(t=>{t instanceof Ne&&(s&&hh.textureCache.set(s,t),this.setOptions({backgroundImage:t}),this.markDirty())})}else this.setOptions({backgroundImage:void 0,borderRadius:0,backgroundOpacity:this.color.alpha});this.markDirty()}onAfterAddedToScene(){super.onAfterAddedToScene(),this.shadowComponent&&(this.shadowComponent.offset=this.shadowComponent.position.z)}},a(b0,"textureCache",new Map),b0);let Xr=hh;Wx([m(we)],Xr.prototype,"color",1),Wx([m()],Xr.prototype,"raycastTarget",2);class dh extends Xr{constructor(){super(...arguments),a(this,"_flippedObject",!1)}onAfterCreated(){this.uiObject&&!this._flippedObject&&(this._flippedObject=!0,this.uiObject.scale.y*=-1)}}var wT=Object.defineProperty,xT=Object.getOwnPropertyDescriptor,Nn=(s,t,i,n)=>{for(var o=n>1?void 0:n?xT(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&wT(t,i,o),o};const Qr=O("debugtext");var dt=(s=>(s[s.UpperLeft=0]="UpperLeft",s[s.UpperCenter=1]="UpperCenter",s[s.UpperRight=2]="UpperRight",s[s.MiddleLeft=3]="MiddleLeft",s[s.MiddleCenter=4]="MiddleCenter",s[s.MiddleRight=5]="MiddleRight",s[s.LowerLeft=6]="LowerLeft",s[s.LowerCenter=7]="LowerCenter",s[s.LowerRight=8]="LowerRight",s))(dt||{}),Vx=(s=>(s[s.Normal=0]="Normal",s[s.Bold=1]="Bold",s[s.Italic=2]="Italic",s[s.BoldAndItalic=3]="BoldAndItalic",s))(Vx||{});class Vt extends Xr{constructor(){super(...arguments),a(this,"alignment",0),a(this,"verticalOverflow",0),a(this,"horizontalOverflow",0),a(this,"lineSpacing",1),a(this,"supportRichText",!1),a(this,"font"),a(this,"fontStyle",0),a(this,"sRGBTextColor",new ae(1,0,1)),a(this,"_text",""),a(this,"_fontSize",12),a(this,"_textMeshUi",null),a(this,"_didHandleTextRenderOnTop",!1)}setAlphaFactor(t){var i;super.setAlphaFactor(t),(i=this.uiObject)==null||i.set({fontOpacity:this.color.alpha*this.alphaFactor}),this.markDirty()}get text(){return this._text}set text(t){t!==this._text&&(this._text=t,this.feedText(this.text,this.supportRichText),this.markDirty())}set_text(t){this.text=t}get fontSize(){return this._fontSize}set fontSize(t){var i;this._fontSize=t,(i=this.uiObject)==null||i.set({fontSize:t})}onColorChanged(){var t;this.sRGBTextColor.copy(this.color),this.sRGBTextColor.convertLinearToSRGB(),(t=this.uiObject)==null||t.set({color:this.sRGBTextColor,fontOpacity:this.color.alpha})}onParentRectTransformChanged(){super.onParentRectTransformChanged(),this.uiObject&&this.updateOverflow()}onBeforeCanvasRender(t){this.updateOverflow()}updateOverflow(){var t;const i=(t=this.uiObject)==null?void 0:t._overflow;i&&(i._needsUpdate=!0)}onCreate(t){Qr&&console.log(this),this.horizontalOverflow==1&&(t.whiteSpace="pre"),this.verticalOverflow==0&&(this.context.renderer.localClippingEnabled=!0,t.overflow="hidden"),this.horizontalOverflow==1&&this.verticalOverflow==0,t.lineHeight=this.lineSpacing,delete t.backgroundOpacity,delete t.backgroundColor,Qr&&(t.backgroundColor=16750848,t.backgroundOpacity=.5);const i=this.rectTransform;t={...t,...this.getTextOpts()},this.getAlignment(t),Qr&&(t.backgroundColor=Math.random()*16777215,t.backgroundOpacity=.1),this.uiObject=i.createNewText(t),this.feedText(this.text,this.supportRichText)}onAfterAddedToScene(){super.onAfterAddedToScene(),this.handleTextRenderOnTop()}getTextOpts(){const t=this.fontSize,i={color:this.color,fontOpacity:this.color.alpha,fontSize:t,fontKerning:"normal"};return this.setFont(i,this.fontStyle),i}onEnable(){var t;super.onEnable(),this._didHandleTextRenderOnTop=!1,this.uiObject&&this.uiObject.addAfterUpdate(()=>{this.setShadowComponentOwner(this.uiObject),this.markDirty()}),setTimeout(()=>this.markDirty(),10),(t=this.canvas)==null||t.registerEventReceiver(this)}onDisable(){var t;super.onDisable(),(t=this.canvas)==null||t.unregisterEventReceiver(this)}getAlignment(t){switch(t.flexDirection="column",this.alignment){case 0:case 3:case 6:t.textAlign="left";break;case 1:case 4:case 7:t.textAlign="center";break;case 2:case 5:case 8:t.textAlign="right";break}switch(this.alignment){default:case 0:case 1:case 2:t.alignItems="start";break;case 3:case 4:case 5:t.alignItems="center";break;case 6:case 7:case 8:t.alignItems="end";break}return t}feedText(t,i){var n,o,r;if(Qr&&console.log("feedText",this.uiObject,t,i),!!this.uiObject)if(this._textMeshUi||(this._textMeshUi=[]),this.uiObject.children.length=0,!i||t.length===0)this.uiObject.textContent=t;else{let l=this.getNextTag(t);if(l){if(l.startIndex>0){for(let d=this.uiObject.children.length-1;d>=0;d--){const u=this.uiObject.children[d];u.isUI&&(this.uiObject.remove(u),u.clear())}const h=new Om({textContent:t.substring(0,l.startIndex),color:"inherit"});this.uiObject.add(h)}}else{this.uiObject.textContent="",this.setOptions({textContent:t});return}const c=[];for(;l;){const h=this.getNextTag(t,l.endIndex),d={fontFamily:(n=this.uiObject)==null?void 0:n.get("fontFamily"),color:"inherit",textContent:""};if(h){d.textContent=this.getText(t,l,h),this.handleTag(l,d,c);const u=new Om(d);(o=this.uiObject)==null||o.add(u)}else{d.textContent=t.substring(l.endIndex),this.handleTag(l,d,c);const u=new Om(d);(r=this.uiObject)==null||r.add(u)}l=h}}}handleTextRenderOnTop(){this._didHandleTextRenderOnTop||(this._didHandleTextRenderOnTop=!0,this.startCoroutine(this.renderOnTopCoroutine()))}*renderOnTopCoroutine(){if(!this.canvas)return;const t=[],i=this.canvas,n={renderOnTop:i.renderOnTop,depthWrite:i.depthWrite,doubleSided:i.doubleSided};for(;;){let o=!1;if(this._textMeshUi)for(let r=0;r<this._textMeshUi.length;r++){if(t[r]===!0)continue;o=!0;const l=this._textMeshUi[r];l.textContent&&(Au(l,n),t[r]=!0)}if(!o)break;yield}}handleTag(t,i,n){if(!t.isEndTag){if(t.type.includes("color")){const o=new _0(t,{color:i.color});if(n.push(o),t.type.length>6){const r=parseInt("0x"+t.type.substring(7));i.color=r}else i.color=new ae(1,1,1)}else if(t.type=="b"){this.setFont(i,1);const o=new _0(t,{fontWeight:700});n.push(o)}else if(t.type=="i"){this.setFont(i,2);const o=new _0(t,{fontStyle:"italic"});n.push(o)}}}getText(t,i,n){return t.substring(i.endIndex,n.startIndex)}getNextTag(t,i=0){const n=t.indexOf("<",i),o=t.indexOf(">",n);if(n>=0&&o>=0){const r=t.substring(n+1,o);return{type:r,startIndex:n,endIndex:o+1,isEndTag:r.startsWith("/")}}return null}setFont(t,i){if(!this.font)return;const n=this.font,o=this.getFamilyNameWithCorrectSuffix(n,i);Qr&&console.log("Selected font family:"+o);let r=_v.getFontFamily(o);switch(r||(r=_v.addFontFamily(o)),t.fontFamily=r,i){default:case 0:t.fontWeight=400,t.fontStyle="normal";break;case 1:t.fontWeight=700,t.fontStyle="normal";break;case 2:t.fontWeight=400,t.fontStyle="italic";break;case 3:t.fontStyle="italic",t.fontWeight=400}let l=r.getVariant(t.fontWeight,t.fontStyle);if(!l){let c=o;c!=null&&c.endsWith("-msdf.json")||(c+="-msdf.json");let h=o;h!=null&&h.endsWith(".png")||(h+=".png"),l=r.addVariant(t.fontWeight,t.fontStyle,c,h),l?.addEventListener("ready",()=>{this.markDirty()})}}getFamilyNameWithCorrectSuffix(t,i){var n;const o=t.lastIndexOf("-");if(o<0)return t;const r=(n=t.substring(o+1))==null?void 0:n.toLowerCase();if(ST.includes(r))return Qr&&console.warn("Unsupported font style: "+r),t;const l=t.lastIndexOf("/");let c=t;l>=0&&(c=c.substring(l+1));const h=c[0]===c[0].toUpperCase(),d=t.substring(0,o);switch(Qr&&console.log("Select font: ",t,Vx[i],c,h,d),i){case 0:return h?d+"-Regular":d+"-regular";case 1:return h?d+"-Bold":d+"-bold";case 2:return h?d+"-Italic":d+"-italic";case 3:return h?d+"-BoldItalic":d+"-bolditalic";default:return t}}}Nn([m()],Vt.prototype,"alignment",2),Nn([m()],Vt.prototype,"verticalOverflow",2),Nn([m()],Vt.prototype,"horizontalOverflow",2),Nn([m()],Vt.prototype,"lineSpacing",2),Nn([m()],Vt.prototype,"supportRichText",2),Nn([m(URL)],Vt.prototype,"font",2),Nn([m()],Vt.prototype,"fontStyle",2),Nn([m()],Vt.prototype,"text",1),Nn([m()],Vt.prototype,"fontSize",1);class _0{constructor(t,i){a(this,"tag"),a(this,"previousValues"),this.tag=t,this.previousValues=i}}const ST=["medium","mediumitalic","black","blackitalic","thin","thinitalic","extrabold","light","lightitalic","semibold"];class Lo{constructor(t){a(this,"id"),a(this,"content",""),a(this,"font",[]),a(this,"pointSize",144),a(this,"width"),a(this,"height"),a(this,"depth"),a(this,"wrapMode"),a(this,"horizontalAlignment"),a(this,"verticalAlignment"),a(this,"material"),this.id=t}static getId(){return this.global_id++}setDepth(t){return this.depth=t,this}setPointSize(t){return this.pointSize=t,this}setHorizontalAlignment(t){return this.horizontalAlignment=t,this}setVerticalAlignment(t){return this.verticalAlignment=t,this}writeTo(t,i){var n;i.beginBlock(`def Preliminary_Text "${this.id}"`,"(",!1),i.appendLine('prepend apiSchemas = ["MaterialBindingAPI"]'),i.closeBlock(")"),i.beginBlock(),this.content&&i.appendLine(`string content = "${this.content}"`),(!this.font||this.font.length<=0)&&(this.font||(this.font=[]),(n=this.font)==null||n.push("sans-serif"));const o=this.font.map(r=>`"${r}"`).join(", ");i.appendLine(`string[] font = [ ${o} ]`),i.appendLine(`double pointSize = ${this.pointSize}`),typeof this.width=="number"&&i.appendLine(`double width = ${this.width}`),typeof this.height=="number"&&i.appendLine(`double height = ${this.height}`),typeof this.depth=="number"&&i.appendLine(`double depth = ${this.depth}`),this.wrapMode&&i.appendLine(`token wrapMode = "${this.wrapMode}"`),this.horizontalAlignment&&i.appendLine(`token horizontalAlignment = "${this.horizontalAlignment}"`),this.verticalAlignment&&i.appendLine(`token verticalAlignment = "${this.verticalAlignment}"`),this.material!==void 0&&i.appendLine(`rel material:binding = </StageRoot/Materials/${s0(this.material)}>`),i.closeBlock()}}a(Lo,"global_id",0);class fp{static singleLine(t,i,n){const o=new Lo("text_"+Lo.getId());return o.content=t,i&&(o.pointSize=i),n&&(o.depth=n),o}static multiLine(t,i,n,o,r,l){const c=new Lo("text_"+Lo.getId());return c.content=t,c.width=i,c.height=n,c.horizontalAlignment=o,c.verticalAlignment=r,l!==void 0&&(c.wrapMode=l),c}}const CT=new ne().makeRotationY(Math.PI),OT=new ne().makeScale(-1,1,-1);class uh{get extensionName(){return"text"}exportText(t,i,n){const o=P.getComponent(t,Vt);if(!o)return;const r=P.getComponent(t,Wt);let l=100,c=100;r&&(l=r.width,c=r.height);const h=CT.clone();r&&h.premultiply(OT),i.setMatrix(h);const d=o.color.clone();i.material=new ri({color:d,emissive:d}),i.addEventListener("serialize",(u,p)=>{let g=o.text;g=g.replace(/\r/g,""),g=g.replace(/\n/g,"\\n");const y=fp.multiLine(g,l,c,"center","bottom","flowing");this.setTextAlignment(y,o.alignment),this.setOverflow(y,o),i.material&&(y.material=i.material),y.pointSize=this.convertToTextSize(o.fontSize),y.depth=.001,y.writeTo(void 0,u)})}convertToTextSize(t){return 1/.0502*144*t}setOverflow(t,i){i.horizontalOverflow?t.wrapMode="singleLine":t.wrapMode="flowing"}setTextAlignment(t,i){switch(i){case dt.LowerLeft:case dt.MiddleLeft:case dt.UpperLeft:t.horizontalAlignment="left";break;case dt.LowerCenter:case dt.MiddleCenter:case dt.UpperCenter:t.horizontalAlignment="center";break;case dt.LowerRight:case dt.MiddleRight:case dt.UpperRight:t.horizontalAlignment="right";break}switch(i){case dt.LowerLeft:case dt.LowerCenter:case dt.LowerRight:t.verticalAlignment="bottom";break;case dt.MiddleLeft:case dt.MiddleCenter:case dt.MiddleRight:t.verticalAlignment="middle";break;case dt.UpperLeft:case dt.UpperCenter:case dt.UpperRight:t.verticalAlignment="top";break}}}var PT=Object.defineProperty,kT=Object.getOwnPropertyDescriptor,nt=(s,t,i,n)=>{for(var o=n>1?void 0:n?kT(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&PT(t,i,o),o};const Hx=O("debuguilayout");class Do{constructor(){a(this,"left",0),a(this,"right",0),a(this,"top",0),a(this,"bottom",0)}get vertical(){return this.top+this.bottom}get horizontal(){return this.left+this.right}}nt([m()],Do.prototype,"left",2),nt([m()],Do.prototype,"right",2),nt([m()],Do.prototype,"top",2),nt([m()],Do.prototype,"bottom",2);class Ii extends A{constructor(){super(...arguments),a(this,"_rectTransform",null),a(this,"_needsUpdate",!1),a(this,"childAlignment",0),a(this,"reverseArrangement",!1),a(this,"spacing",0),a(this,"padding"),a(this,"minWidth",0),a(this,"minHeight",0),a(this,"flexibleHeight",0),a(this,"flexibleWidth",0),a(this,"preferredHeight",0),a(this,"preferredWidth",0)}get rectTransform(){return this._rectTransform}onParentRectTransformChanged(t){this._needsUpdate=!0}get isDirty(){return this._needsUpdate}get isLayoutGroup(){return!0}updateLayout(){this._rectTransform&&(Hx&&console.warn("Layout Update",this.context.time.frame,this.name),this._needsUpdate=!1,this.onCalculateLayout(this._rectTransform))}start(){this._needsUpdate=!0}onEnable(){Hx&&console.log(this.name,this),this._rectTransform=this.gameObject.getComponent(Wt);const t=this.gameObject.getComponentInParent(Rt);t&&t.registerLayoutGroup(this),this._needsUpdate=!0}onDisable(){const t=this.gameObject.getComponentInParent(Rt);t&&t.unregisterLayoutGroup(this)}set m_Spacing(t){t!==this.spacing&&(this._needsUpdate=!0,this.spacing=t)}get m_Spacing(){return this.spacing}}nt([m()],Ii.prototype,"childAlignment",2),nt([m()],Ii.prototype,"reverseArrangement",2),nt([m()],Ii.prototype,"spacing",2),nt([m(Do)],Ii.prototype,"padding",2),nt([m()],Ii.prototype,"minWidth",2),nt([m()],Ii.prototype,"minHeight",2),nt([m()],Ii.prototype,"flexibleHeight",2),nt([m()],Ii.prototype,"flexibleWidth",2),nt([m()],Ii.prototype,"preferredHeight",2),nt([m()],Ii.prototype,"preferredWidth",2);class Bo extends Ii{constructor(){super(...arguments),a(this,"childControlHeight",!0),a(this,"childControlWidth",!0),a(this,"childForceExpandHeight",!1),a(this,"childForceExpandWidth",!1),a(this,"childScaleHeight",!1),a(this,"childScaleWidth",!1)}onCalculateLayout(t){var i;const n=this.primaryAxis,o=t.width;let r=o;const l=t.height;let c=l;r-=this.padding.horizontal,c-=this.padding.vertical,n==="x"?this.padding.horizontal:this.padding.vertical;const h=n==="x",d=h?"y":"x",u=h?this.childControlWidth:this.childControlHeight,p=h?this.childControlHeight:this.childControlWidth,g=h?this.childForceExpandWidth:this.childForceExpandHeight,y=h?this.childForceExpandHeight:this.childForceExpandWidth,f=h?c:r,v=h?o:l,b=.5*(h?this.childAlignment%3:Math.floor(this.childAlignment/3));let w=0;h?w+=this.padding.left:w+=this.padding.top;let _=0,C=0;for(let L=0;L<this.gameObject.children.length;L++){const U=this.gameObject.children[L],z=P.getComponent(U,Wt);z!=null&&z.activeAndEnabled&&(C+=1,h?_+=z.width:_+=z.height)}let R=0;const M=this.spacing*(C-1);if(g||u){let L=0;h?L=r-=M:L=c-=M,C>0&&(R=L/C)}let E=0;E+=this.padding.left,E-=this.padding.right,b!==0&&(w=v-_,w*=b,w-=M*b,h?(w-=this.padding.right*b,w+=this.padding.left*(1-b),w<this.padding.left&&(w=this.padding.left)):(w-=this.padding.bottom*b,w+=this.padding.top*(1-b),w<this.padding.top&&(w=this.padding.top)));let D=1;for(let L=0;L<this.gameObject.children.length;L++){const U=this.gameObject.children[L],z=P.getComponent(U,Wt);if(z!=null&&z.activeAndEnabled){(i=z.pivot)==null||i.set(.5,.5),z.anchorMin.set(0,1),z.anchorMax.set(0,1);const H=o*.5+E*.5;z.anchoredPosition.x!==H&&(z.anchoredPosition.x=H);const T=l*-.5;z.anchoredPosition.y!==T&&(z.anchoredPosition.y=T),y&&p&&z.sizeDelta[d]!==f&&(z.sizeDelta[d]=f),g&&u&&z.sizeDelta[n]!==R&&(z.sizeDelta[n]=R);const I=h?z.width:z.height,G=I*.5;if(w+=G,g){const se=R*D-R*.5;se>w&&(w=se-R*.5+I+this.padding.left,w-=G)}let J=w;n==="y"&&(J=-J),z.anchoredPosition[n]!==J&&(z.anchoredPosition[n]=J),w+=G,w+=this.spacing,D+=1}}}}nt([m()],Bo.prototype,"childControlHeight",2),nt([m()],Bo.prototype,"childControlWidth",2),nt([m()],Bo.prototype,"childForceExpandHeight",2),nt([m()],Bo.prototype,"childForceExpandWidth",2),nt([m()],Bo.prototype,"childScaleHeight",2),nt([m()],Bo.prototype,"childScaleWidth",2);class w0 extends Bo{get primaryAxis(){return"y"}}class x0 extends Bo{get primaryAxis(){return"x"}}class S0 extends Ii{onCalculateLayout(){}}var MT=Object.defineProperty,RT=Object.getOwnPropertyDescriptor,on=(s,t,i,n)=>{for(var o=n>1?void 0:n?RT(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&MT(t,i,o),o},$x=(s=>(s[s.ScreenSpaceOverlay=0]="ScreenSpaceOverlay",s[s.ScreenSpaceCamera=1]="ScreenSpaceCamera",s[s.WorldSpace=2]="WorldSpace",s[s.Undefined=-1]="Undefined",s))($x||{});const C0=O("debuguilayout"),qx=class extends Bc{constructor(){super(...arguments),a(this,"_renderOnTop"),a(this,"_depthWrite",!1),a(this,"_doubleSided",!0),a(this,"_castShadows",!1),a(this,"_receiveShadows",!1),a(this,"_renderMode",-1),a(this,"_rootCanvas"),a(this,"_scaleFactor",1),a(this,"worldCamera"),a(this,"planeDistance",-1),a(this,"_boundRenderSettingsChanged",this.onRenderSettingsChanged.bind(this)),a(this,"previousParent",null),a(this,"_lastMatrixWorld",null),a(this,"_rectTransforms",[]),a(this,"_layoutGroups",new Map),a(this,"_receivers",[]),a(this,"onBeforeRenderRoutine",()=>{var s,t,i,n;if(this.previousParent=this.gameObject.parent,((s=this.context.xr)!=null&&s.isVR||(t=this.context.xr)!=null&&t.isPassThrough)&&this.screenspace){this.gameObject.visible=!1,this.gameObject.removeFromParent();return}this.renderOnTop||this.screenspace?this.gameObject.removeFromParent():(this.onUpdateRenderMode(),this.handleLayoutUpdates(),(i=this.shadowComponent)==null||i.updateMatrixWorld(!0),(n=this.shadowComponent)==null||n.updateWorldMatrix(!0,!0),this.invokeBeforeRenderEvents(),ts.ensureUpdateMeshUI(wv,this.context))}),a(this,"onAfterRenderRoutine",()=>{var s,t,i,n,o;if(((s=this.context.xr)!=null&&s.isVR||(t=this.context.xr)!=null&&t.isPassThrough)&&this.screenspace){(i=this.previousParent)==null||i.add(this.gameObject);return}if((this.screenspace||this.renderOnTop)&&this.previousParent&&this.context.mainCamera){if(this.screenspace){const c=this.context.mainCamera;c?.add(this.gameObject)}else this.previousParent.add(this.gameObject);const r=this.context.renderer.autoClear,l=this.context.renderer.autoClearColor;this.context.renderer.autoClear=!1,this.context.renderer.autoClearColor=!1,this.context.renderer.clearDepth(),this.onUpdateRenderMode(!0),this.handleLayoutUpdates(),(n=this.shadowComponent)==null||n.updateMatrixWorld(!0),this.invokeBeforeRenderEvents(),ts.ensureUpdateMeshUI(wv,this.context,!0),this.context.renderer.render(this.gameObject,this.context.mainCamera),this.context.renderer.autoClear=r,this.context.renderer.autoClearColor=l,this.previousParent.add(this.gameObject)}(o=this._lastMatrixWorld)==null||o.copy(this.gameObject.matrixWorld)}),a(this,"_updateRenderSettingsRoutine"),a(this,"_activeRenderMode",-1),a(this,"_lastWidth",-1),a(this,"_lastHeight",-1)}get isCanvas(){return!0}get screenspace(){return this.renderMode!==2}set renderOnTop(s){s!==this._renderOnTop&&(this._renderOnTop=s,this.onRenderSettingsChanged())}get renderOnTop(){return this._renderOnTop!==void 0?this._renderOnTop:!!(this.screenspace&&this._renderMode===0)}set depthWrite(s){this._depthWrite!==s&&(this._depthWrite=s,this.onRenderSettingsChanged())}get depthWrite(){return this._depthWrite}set doubleSided(s){this._doubleSided!==s&&(this._doubleSided=s,this.onRenderSettingsChanged())}get doubleSided(){return this._doubleSided}set castShadows(s){this._castShadows!==s&&(this._castShadows=s,this.onRenderSettingsChanged())}get castShadows(){return this._castShadows}set receiveShadows(s){this._receiveShadows!==s&&(this._receiveShadows=s,this.onRenderSettingsChanged())}get receiveShadows(){return this._receiveShadows}get renderMode(){return this._renderMode}set renderMode(s){this._renderMode!==s&&(this._renderMode=s,this.onRenderSettingsChanged())}set rootCanvas(s){this._rootCanvas instanceof qx||(this._rootCanvas=s)}get rootCanvas(){return this._rootCanvas}get scaleFactor(){return this._scaleFactor}set scaleFactor(s){this._scaleFactor=s}awake(){var s;this.shadowComponent=this.gameObject,this.previousParent=this.gameObject.parent,C0&&console.log("Canvas.Awake()",((s=this.previousParent)==null?void 0:s.name)+"/"+this.gameObject.name),super.awake()}start(){this.onUpdateRenderMode()}onEnable(){super.onEnable(),this._updateRenderSettingsRoutine=void 0,this._lastMatrixWorld=new ne,this.onUpdateRenderMode(),document.addEventListener("resize",this._boundRenderSettingsChanged),this.context.pre_render_callbacks.push(this.onBeforeRenderRoutine),this.context.post_render_callbacks.push(this.onAfterRenderRoutine)}onDisable(){super.onDisable(),document.removeEventListener("resize",this._boundRenderSettingsChanged);const s=this.context.pre_render_callbacks.indexOf(this.onBeforeRenderRoutine);s!==-1&&this.context.pre_render_callbacks.splice(s,1);const t=this.context.post_render_callbacks.indexOf(this.onAfterRenderRoutine);t!==-1&&this.context.post_render_callbacks.splice(t,1)}registerTransform(s){this._rectTransforms.push(s)}unregisterTransform(s){const t=this._rectTransforms.indexOf(s);t!==-1&&this._rectTransforms.splice(t,1)}registerLayoutGroup(s){const t=s.gameObject;this._layoutGroups.set(t,s)}unregisterLayoutGroup(s){const t=s.gameObject;this._layoutGroups.delete(t)}registerEventReceiver(s){this._receivers.push(s)}unregisterEventReceiver(s){const t=this._receivers.indexOf(s);t!==-1&&this._receivers.splice(t,1)}async onEnterXR(s){this.screenspace?(s.xr.isVR||s.xr.isPassThrough)&&(this.gameObject.visible=!1):(this.gameObject.visible=!1,await Xl(1).then(()=>{this.gameObject.visible=!0}))}onLeaveXR(s){this.screenspace&&(s.xr.isVR||s.xr.isPassThrough)&&(this.gameObject.visible=!0)}invokeBeforeRenderEvents(){var s;for(const t of this._receivers)(s=t.onBeforeCanvasRender)==null||s.call(t,this)}handleLayoutUpdates(){this._lastMatrixWorld===null&&(this._lastMatrixWorld=new ne);const s=!this._lastMatrixWorld.equals(this.gameObject.matrixWorld);C0&&s&&console.log("Canvas Layout changed",this.context.time.frameCount,this.name);const t=!1;for(const i of this._rectTransforms){s&&i.markDirty();let n=this._layoutGroups.get(i.gameObject);i.isDirty&&!n&&(n=i.gameObject.getComponentInParent(Ii)),(i.isDirty||n!=null&&n.isDirty)&&(C0&&!t&&console.log("CANVAS UPDATE ### "+i.name+" ##################################### "+this.context.time.frame),n?.updateLayout(),i.updateTransform())}}applyRenderSettings(){this.onRenderSettingsChanged()}onRenderSettingsChanged(){this._updateRenderSettingsRoutine||(this._updateRenderSettingsRoutine=this.startCoroutine(this._updateRenderSettingsDelayed(),Ce.OnBeforeRender))}*_updateRenderSettingsDelayed(){if(yield,this._updateRenderSettingsRoutine=void 0,this.shadowComponent){this.onUpdateRenderMode(),Au(this.shadowComponent,this);for(const s of P.getComponentsInChildren(this.gameObject,ls))Au(s.shadowComponent,this)}}onUpdateRenderMode(s=!1){if(!s&&this._renderMode===this._activeRenderMode&&this._lastWidth===this.context.domWidth&&this._lastHeight===this.context.domHeight)return;this._activeRenderMode=this._renderMode;let t=this.context.mainCameraComponent,i=10;switch(t&&t.nearClipPlane>0&&t.farClipPlane>0&&(i=W.lerp(t.nearClipPlane,t.farClipPlane,.01)),this._renderMode===1&&(this.worldCamera&&(t=this.worldCamera),this.planeDistance>0&&(i=this.planeDistance)),this._renderMode){case 0:case 1:if(this._lastWidth=this.context.domWidth,this._lastHeight=this.context.domHeight,!t)return;const n=i+.01;this.gameObject.position.x=0,this.gameObject.position.y=0,this.gameObject.position.z=-n,this.gameObject.quaternion.identity();const o=this.gameObject.getComponent(Wt);let r=!1;o.sizeDelta.x!==this.context.domWidth&&(r=!0),o.sizeDelta.y!==this.context.domHeight&&(r=!0);const l=t.fieldOfView*Math.PI/180,c=2*Math.tan(l/2)*Math.abs(n);this.gameObject.scale.x=c/this.context.domHeight,this.gameObject.scale.y=c/this.context.domHeight,this.gameObject.scale.z=.01,r&&(o.sizeDelta.x=this.context.domWidth,o.sizeDelta.y=this.context.domHeight,o?.markDirty());break;case 2:this._lastWidth=-1,this._lastHeight=-1;break}}};let Rt=qx;on([m()],Rt.prototype,"renderOnTop",1),on([m()],Rt.prototype,"depthWrite",1),on([m()],Rt.prototype,"doubleSided",1),on([m()],Rt.prototype,"castShadows",1),on([m()],Rt.prototype,"receiveShadows",1),on([m()],Rt.prototype,"renderMode",1),on([m(Rt)],Rt.prototype,"rootCanvas",1),on([m()],Rt.prototype,"scaleFactor",1),on([m(Pe)],Rt.prototype,"worldCamera",2),on([m()],Rt.prototype,"planeDistance",2);var TT=Object.defineProperty,ET=Object.getOwnPropertyDescriptor,O0=(s,t,i,n)=>{for(var o=n>1?void 0:n?ET(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&TT(t,i,o),o};class Fo extends A{constructor(){super(...arguments),a(this,"_alpha",1),a(this,"interactable",!0),a(this,"blocksRaycasts",!0),a(this,"_isDirty",!1),a(this,"_buffer",[])}get alpha(){return this._alpha}set alpha(t){t!==this._alpha&&(this._alpha=t,this.markDirty())}get isCanvasGroup(){return!0}markDirty(){this._isDirty||(this._isDirty=!0,this.startCoroutine(this.applyChangesDelayed(),Ce.OnBeforeRender))}*applyChangesDelayed(){this._isDirty=!1,this.applyChangesNow()}applyChangesNow(){this._buffer.length=0;for(const t of P.getComponentsInChildren(this.gameObject,ls,this._buffer)){const i=t;i.setAlphaFactor&&i.setAlphaFactor(this._alpha)}}}O0([m()],Fo.prototype,"alpha",1),O0([m()],Fo.prototype,"interactable",2),O0([m()],Fo.prototype,"blocksRaycasts",2);class yp{get extensionName(){return"tmui"}onExportObject(t,i,n){const o=P.getComponent(t,Rt);if(o&&o.enabled&&o.renderMode===$x.WorldSpace){const r=new uh,l=P.getComponent(t,Wt),c=P.getComponent(t,Fo),h=new Array;if(l){if(!P.isActiveSelf(t)){const p=P.isActiveSelf(t);P.setActive(t,!0),l.onEnable(),l.updateTransform(),h.push(()=>{l.onDisable(),P.setActive(t,p)})}t.traverse(p=>{if(!P.isActiveInHierarchy(p)){const g=P.isActiveSelf(p);P.setActive(p,!0);const y=P.getComponent(p,ls);y&&(y.onEnable(),h.push(()=>{y.onDisable()}));const f=P.getComponent(p,Wt);f&&(f.onEnable(),f.updateTransform(),f.onApplyTransform(),h.push(()=>{f.onDisable()}));const v=P.getComponent(p,Vt);v&&(v.onEnable(),h.push(()=>{v.onDisable()})),h.push(()=>{P.setActive(p,g)})}}),l.width,l.height;const d=Zt.createEmpty(),u=l.shadowComponent;if(i.add(d),u){const p=u.matrix;d.setMatrix(p);const g=new Map,y=new Map;g.set(u,d),y.set(u,c?c.alpha:1),u.traverse(f=>{if(f===u)return;const v=Zt.createEmpty();v.setMatrix(f.matrix);const b=f.parent,w=!!b&&typeof b.textContent=="string"&&b.textContent.length>0;let _=y.get(b)||1;const C=P.getComponent(f,Fo);if(C&&(_*=C.alpha),f instanceof Q&&w){const M=f[es];M?r.exportText(M.gameObject,v,n):console.error("Error when exporting UI: shadow component owner not found. This is likely a bug.",f)}if(f instanceof Q&&!w){const M=f.geometry.clone();M.scale(1,1,-1),this.flipWindingOrder(M),v.geometry=M;const E=new ae,D=f.material.opacity;E.copy(f.material.color),v.material=new Me({color:E,opacity:D*_,map:f.material.map,transparent:!0})}g.set(f,v),y.set(f,_);const R=g.get(b);if(!R){console.error("Error when exporting UI: shadow component parent not found!",f,f.parent);return}R.add(v)})}}for(const d of h)d()}}flipWindingOrder(t){const i=t.index.array;for(let n=0,o=i.length/3;n<o;n++){const r=i[n*3];i[n*3]=i[n*3+2],i[n*3+2]=r}t.index.needsUpdate=!0}}const Gx=class{constructor(){a(this,"_quicklookButton"),a(this,"_arButton"),a(this,"_vrButton"),a(this,"_sendToQuestButton")}static create(){return new Gx}static getOrCreate(){return this._instance||(this._instance=this.create()),this._instance}get isSecureConnection(){return window.location.protocol==="https:"}get quicklookButton(){return this._quicklookButton}get arButton(){return this._arButton}get vrButton(){return this._vrButton}get sendToQuestButton(){return this._sendToQuestButton}get qrButton(){return Mn.getOrCreate().createQRCode()}createQuicklookButton(){if(this._quicklookButton)return this._quicklookButton;const s=document.createElement("button");this._quicklookButton=s,s.dataset.needle="quicklook-button";const t=Y.supportsQuickLookAR();s.innerText="View in AR",s.prepend(Ot("view_in_ar"));let i=!1,n=null;return s.addEventListener("click",()=>{n=Gd(Ge),n||(i=!0,n=new Ge),i&&(n.objectToExport=te.Current.scene),n?(s.classList.add("this-mode-is-requested"),n.exportAndOpen().then(()=>{s.classList.remove("this-mode-is-requested")}).catch(o=>{s.classList.remove("this-mode-is-requested"),console.error(o)})):console.warn("No USDZExporter component found in the scene")}),this.hideElementDuringXRSession(s),s}createARButton(s){var t;if(this._arButton)return this._arButton;const i="immersive-ar",n=document.createElement("button");return this._arButton=n,n.classList.add("webxr-button"),n.dataset.needle="webxr-ar-button",n.innerText="Enter AR",n.prepend(Ot("view_in_ar")),n.title="Click to start an AR session",n.addEventListener("click",()=>Z.start(i,s)),this.updateSessionSupported(n,i),this.listenToXRSessionState(n,i),this.hideElementDuringXRSession(n),this.isSecureConnection||(n.disabled=!0,n.title="WebXR requires a secure connection (HTTPS)"),Y.isMozillaXR()||(t=navigator.xr)==null||t.addEventListener("devicechange",()=>this.updateSessionSupported(n,i)),n}createVRButton(s){var t;if(this._vrButton)return this._vrButton;const i="immersive-vr",n=document.createElement("button");return this._vrButton=n,n.classList.add("webxr-button"),n.dataset.needle="webxr-vr-button",n.innerText="Enter VR",n.prepend(Ot("panorama_photosphere")),n.title="Click to start a VR session",n.addEventListener("click",()=>Z.start(i,s)),this.updateSessionSupported(n,i),this.listenToXRSessionState(n,i),this.hideElementDuringXRSession(n),this.isSecureConnection||(n.disabled=!0,n.title="WebXR requires a secure connection (HTTPS)"),Y.isMozillaXR()||(t=navigator.xr)==null||t.addEventListener("devicechange",()=>this.updateSessionSupported(n,i)),n}createSendToQuestButton(){var s;if(this._sendToQuestButton)return this._sendToQuestButton;const t="https://oculus.com/open_url/?url=",i=document.createElement("button");return this._sendToQuestButton=i,i.dataset.needle="webxr-sendtoquest-button",i.innerText="Open on Quest",i.prepend(Ot("share_windows")),i.title="Click to send this page to the Oculus Browser on your Quest",i.addEventListener("click",()=>{const n=encodeURIComponent(window.location.href),o=t+n;window.open(o)==null&&Le("This page doesn't allow popups. Please paste "+o+" into your browser.")}),this.listenToXRSessionState(i),this.hideElementDuringXRSession(i),Y.isMozillaXR()||(s=navigator.xr)==null||s.addEventListener("devicechange",()=>{var n;(n=navigator.xr)!=null&&n.isSessionSupported("immersive-vr")?i.style.display="none":i.style.display=""}),i}createQRCode(){return Mn.getOrCreate().createQRCode()}updateSessionSupported(s,t){if(!("xr"in navigator)){s.style.display="none";return}Z.isSessionSupported(t).then(i=>{s.style.display=i?"":"none",F()&&!i&&console.log('[WebXR] "'+t+'" is not supported on this device \u2013 make sure your server runs using HTTPS and you have a device connected that supports '+t)})}hideElementDuringXRSession(s){kd(t=>{s["previous-display"]=s.style.display,s.style.display="none"}),og(t=>{s["previous-display"]!=null&&(s.style.display=s["previous-display"])})}listenToXRSessionState(s,t){t&&(Z.onSessionRequestStart(i=>{i.mode===t?s.classList.add("this-mode-is-requested"):(s["was-disabled"]=s.disabled,s.disabled=!0,s.classList.add("other-mode-is-requested"))}),Z.onSessionRequestEnd(i=>{s.classList.remove("this-mode-is-requested"),s.classList.remove("other-mode-is-requested"),s.disabled=s["was-disabled"]}))}};let Yr=Gx;a(Yr,"_instance");var AT=Object.defineProperty,IT=Object.getOwnPropertyDescriptor,wt=(s,t,i,n)=>{for(var o=n>1?void 0:n?IT(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&AT(t,i,o),o};const vp=O("debugspriterenderer"),jT=O("wireframe"),P0=class{static getOrCreateGeometry(s){if(s.__cached_geometry)return s.__cached_geometry;if(s.guid&&P0.cache[s.guid])return vp&&console.log("Take cached geometry for sprite",s.guid),P0.cache[s.guid];const t=new oo;s.__cached_geometry=t;const i=new Float32Array(s.triangles.length*3),n=new Float32Array(s.triangles.length*2);for(let o=0;o<s.triangles.length;o+=1){const r=s.triangles[o];i[o*3]=-s.vertices[r].x,i[o*3+1]=s.vertices[r].y,i[o*3+2]=0;const l=s.uv[r];n[o*2]=l.x,n[o*2+1]=1-l.y}return t.setAttribute("position",new mt(i,3)),t.setAttribute("uv",new mt(n,2)),s.guid&&(this.cache[s.guid]=t),vp&&console.log("Built sprite geometry",s,t),t}};let ph=P0;a(ph,"cache",{});class LT{constructor(){a(this,"x"),a(this,"y")}}function Xx(s){s&&(s.colorSpace!=ps&&(s.colorSpace=ps,s.needsUpdate=!0),s.minFilter==hd&&s.magFilter==hd&&(s.anisotropy=1,s.needsUpdate=!0))}let rn=class{constructor(s){a(this,"guid"),a(this,"texture"),a(this,"triangles"),a(this,"uv"),a(this,"vertices"),a(this,"__cached_geometry"),a(this,"_mesh"),a(this,"_material"),s&&(this.texture=s,this.triangles=[0,1,2,0,2,3],this.uv=[{x:0,y:0},{x:1,y:0},{x:1,y:1},{x:0,y:1}],this.vertices=[{x:-.5,y:-.5},{x:.5,y:-.5},{x:.5,y:.5},{x:-.5,y:.5}])}get mesh(){return this._mesh||(this._mesh=new Q(ph.getOrCreateGeometry(this),this.material)),this._mesh}get material(){return this._material||(this.texture&&Xx(this.texture),this._material=new Me({map:this.texture,color:16777215,side:_i,transparent:!0})),this._material}getGeometry(){return ph.getOrCreateGeometry(this)}};wt([m()],rn.prototype,"guid",2),wt([m(Ne)],rn.prototype,"texture",2),wt([Ha()],rn.prototype,"triangles",2),wt([Ha()],rn.prototype,"uv",2),wt([Ha()],rn.prototype,"vertices",2);const k0=Symbol("spriteOwner");class zo{constructor(){a(this,"sprites")}}wt([m(rn)],zo.prototype,"sprites",2);const Qx=class{constructor(){a(this,"spriteSheet"),a(this,"index",0)}static create(){const s=new Qx;return s.spriteSheet=new zo,s}set sprite(s){s&&(this.spriteSheet?((this.index===null||this.index===void 0)&&(this.index=0),this.spriteSheet.sprites[this.index]=s):(this.spriteSheet=new zo,this.spriteSheet.sprites=[s],this.index=0))}get sprite(){if(this.spriteSheet)return this.spriteSheet.sprites[this.index]}update(s){if(!this.spriteSheet)return;const t=this.index;if(t<0||t>=this.spriteSheet.sprites.length)return;const i=this.spriteSheet.sprites[t],n=i?.texture;if(n&&(Xx(n),!i.__hasLoadedProgressive)){i.__hasLoadedProgressive=!0;const o=n;et.assignTextureLOD(n,0).then(r=>{r instanceof Ne&&(i.texture=r,s?.map===o&&(s.map=r,s.needsUpdate=!0))})}}};let Wn=Qx;wt([m(zo)],Wn.prototype,"spriteSheet",2),wt([m()],Wn.prototype,"index",2);class pi extends A{constructor(){super(...arguments),a(this,"drawMode",0),a(this,"size",{x:1,y:1}),a(this,"color"),a(this,"sharedMaterial"),a(this,"transparent",!0),a(this,"cutoutThreshold",0),a(this,"castShadows",!1),a(this,"renderOrder",0),a(this,"toneMapped",!0),a(this,"_spriteSheet"),a(this,"_currentSprite")}set texture(t){var i;if(!this._spriteSheet)return;const n=(i=this._spriteSheet.spriteSheet)==null?void 0:i.sprites[this.spriteIndex];n&&(n.texture=t,this.updateSprite())}addSprite(t,i=!1){var n,o;if(this._spriteSheet||(this._spriteSheet=Wn.create()),!this._spriteSheet.spriteSheet)return-1;(n=this._spriteSheet.spriteSheet)==null||n.sprites.push(t);const r=((o=this._spriteSheet.spriteSheet)==null?void 0:o.sprites.length)-1;return i&&(this.spriteIndex=r),r}get sprite(){return this._spriteSheet}set sprite(t){if(t!==this._spriteSheet)if(typeof t=="number"){const i=Math.floor(t);this.spriteIndex=i;return}else t instanceof rn?(this._spriteSheet||(this._spriteSheet=Wn.create()),this._spriteSheet.sprite!=t&&(this._spriteSheet.sprite=t,this.updateSprite())):t!=this._spriteSheet&&(this._spriteSheet=t,this.updateSprite())}set spriteIndex(t){this._spriteSheet&&t!==this.spriteIndex&&(this._spriteSheet.index=t,this.updateSprite())}get spriteIndex(){var t;return((t=this._spriteSheet)==null?void 0:t.index)??0}get spriteFrames(){var t,i;return((i=(t=this._spriteSheet)==null?void 0:t.spriteSheet)==null?void 0:i.sprites.length)??0}awake(){this._currentSprite=void 0,this._spriteSheet||(this._spriteSheet=new Wn,this._spriteSheet.spriteSheet=new zo),vp&&console.log("Awake",this.name,this,this.sprite)}start(){this._currentSprite?this.gameObject&&this.gameObject.add(this._currentSprite):this.updateSprite()}updateSprite(t=!1){var i;if(!this.__didAwake&&!t)return!1;const n=this._spriteSheet;if(!((i=n?.spriteSheet)!=null&&i.sprites))return console.warn("SpriteRenderer has no data or spritesheet assigned..."),!1;const o=n.spriteSheet.sprites[this.spriteIndex];if(!o)return vp&&console.warn("Sprite not found",this.spriteIndex,n.spriteSheet.sprites),!1;if(this._currentSprite)this._currentSprite.geometry=ph.getOrCreateGeometry(o),this._currentSprite.material.map=o.texture;else{const r=new Me({color:16777215,side:_i});if(jT&&(r.wireframe=!0),this.color&&(r.color||(r.color=new ae),r.color.copy(this.color),r.opacity=this.color.alpha),r.transparent=!0,r.toneMapped=this.toneMapped,o.texture&&!r.wireframe){let l=o.texture;l[k0]!==void 0&&l[k0]!==this&&this.spriteFrames>1&&(l=o.texture=l.clone()),l[k0]=this,r.map=l}this.sharedMaterial=r,this._currentSprite=new Q(ph.getOrCreateGeometry(o),r),this._currentSprite.renderOrder=Math.round(this.renderOrder),et.assignTextureLOD(r,0)}return this._currentSprite.parent!==this.gameObject&&(this.drawMode===2&&this._currentSprite.scale.set(this.size.x,this.size.y,1),this.gameObject&&this.gameObject.add(this._currentSprite)),this._currentSprite&&this._currentSprite.layers.set(this.layer),this.sharedMaterial&&(this.sharedMaterial.alphaTest=this.cutoutThreshold,this.sharedMaterial.transparent=this.transparent),this._currentSprite.castShadow=this.castShadows,n?.update(this.sharedMaterial),!0}}wt([m()],pi.prototype,"drawMode",2),wt([m(LT)],pi.prototype,"size",2),wt([m(we)],pi.prototype,"color",2),wt([m(Oe)],pi.prototype,"sharedMaterial",2),wt([m()],pi.prototype,"transparent",2),wt([m()],pi.prototype,"cutoutThreshold",2),wt([m()],pi.prototype,"castShadows",2),wt([m()],pi.prototype,"renderOrder",2),wt([m()],pi.prototype,"toneMapped",2),wt([m(Wn)],pi.prototype,"sprite",1);const Yx=O("debugwebxr"),DT=new ne().makeRotationY(Math.PI);class Vn extends A{constructor(){super(...arguments),a(this,"_arScale",1),a(this,"invertForward",!1),a(this,"customReticle"),a(this,"arTouchTransform",!0),a(this,"autoPlace",!1),a(this,"autoCenter",!1),a(this,"useXRAnchor",!1),a(this,"_isPlacing",!0),a(this,"_startOffset",new ne),a(this,"_createdPlacementObject",null),a(this,"_reparentedComponents",[]),a(this,"_placementScene",new $i),a(this,"_reticle",[]),a(this,"_hits",[]),a(this,"_placementStartTime",-1),a(this,"_rigPlacementMatrix"),a(this,"_anchor",null),a(this,"userInput"),a(this,"onPlaceScene",t=>{var i;if(this._isPlacing==!1||t!=null&&t.used)return;let n=this._reticle[0];if(!n){console.warn("No reticle to place...");return}if(!n.visible&&!this.autoPlace){console.warn("Reticle is not visible (can not place)");return}if((i=Z.active)!=null&&i.isTrackingImages){console.warn("Scene Placement is disabled while images are being tracked");return}let o=this._hits[0];if(t&&t.origin instanceof rg){const r=this._reticle[t.origin.index];r&&(n=r,o=this._hits[t.origin.index])}if(t&&(t.stopImmediatePropagation(),t.stopPropagation(),t.use()),this._isPlacing=!1,this.context.input.removeEventListener("pointerup",this.onPlaceScene),this.onRevertSceneChanges(),n.position.copy(n.lastPos),n.quaternion.copy(n.lastQuat),this.onApplyPose(n),this.useXRAnchor&&this.onCreateAnchor(Z.active,o),this.context.xr)for(const r of this.context.xr.controllers)r.cancelHitTestSource()}),a(this,"upVec",new x(0,1,0)),a(this,"lookPoint",new x),a(this,"worldUpVec",new x(0,1,0))}static onPlaced(t){const i="placed";return this._eventListeners[i]||(this._eventListeners[i]=[]),this._eventListeners[i].push(t),()=>{const n=this._eventListeners[i].indexOf(t);n>=0&&this._eventListeners[i].splice(n,1)}}get arScale(){return this._arScale}set arScale(t){t!==this._arScale&&(this._arScale=t,this.onScaleChanged())}onEnable(){var t;(t=this.customReticle)==null||t.preload()}supportsXR(t){return t==="immersive-ar"}onEnterXR(t){Yx&&console.log("ENTER WEBXR: SessionRoot start..."),this._anchor=null,this.gameObject.updateMatrixWorld(),this._startOffset.copy(this.gameObject.matrixWorld);const i=new j;this._createdPlacementObject=i,i.name="AR Session Root",this._placementScene.name="AR Placement Scene",this._placementScene.children.length=0;for(let n=this.context.scene.children.length-1;n>=0;n--){const o=this.context.scene.children[n];this._placementScene.add(o)}if(this.context.scene.add(i),this.autoCenter){const n=Si(this._placementScene.children),o=n.getCenter(new x),r=n.getSize(new x),l=new ne;l.makeTranslation(o.x,o.y-r.y*.5,o.z),this._startOffset.multiply(l)}this._reparentedComponents.length=0,this._reparentedComponents.push({comp:this,originalObject:this.gameObject}),P.addComponent(i,this);for(const n of this._reticle)Mi(n);this._reticle.length=0,this._isPlacing=!0,this.context.input.addEventListener("pointerup",this.onPlaceScene,{queue:Ci.Early})}onLeaveXR(){this.context.input.removeEventListener("pointerup",this.onPlaceScene,{queue:Ci.Early}),this.onRevertSceneChanges(),this._anchor=null,this._rigPlacementMatrix=void 0}onUpdateXR(t){var i,n,o,r;if(t.xr.isTrackingImages){for(const l of this._reticle)l.visible=!1;return}if(this._isPlacing){const l=(i=t.xr.rig)==null?void 0:i.gameObject;l&&l.parent!==this.context.scene&&this.context.scene.add(l);let c=!1;if(t.xr.isPassThrough&&t.xr.controllers.length>0&&!this.autoPlace)for(const h of t.xr.controllers){const d=h.getHitTest();d&&(c=!0,this.updateReticleAndHits(t.xr,h.index,d,t.xr.rigScale))}if(!c){const h=t.xr.getHitTest();h&&this.updateReticleAndHits(t.xr,0,h,t.xr.rigScale)}}else{if(this._anchor&&t.xr.referenceSpace){const l=t.xr.frame.getPose(this._anchor.anchorSpace,t.xr.referenceSpace);if(l&&this.context.time.frame%20===0){const c=t.xr.convertSpace(l.transform),h=this._reticle[0];h&&(h.position.copy(c.position),h.quaternion.copy(c.quaternion),this.onApplyPose(h))}}if(this.arTouchTransform?(this.userInput||(this.userInput=new bp(this.context)),(n=this.userInput)==null||n.enable()):(o=this.userInput)==null||o.disable(),this.arTouchTransform&&(r=this.userInput)!=null&&r.hasChanged){if(t.xr.rig){const l=t.xr.rig.gameObject;this.userInput.applyMatrixTo(l.matrix,!0),l.matrix.decompose(l.position,l.quaternion,l.scale),this.userInput.factor=l.scale.x}this.userInput.reset()}}}updateReticleAndHits(t,i,n,o){this._hits[i]=n.hit;let r=this._reticle[i];if(!r){if(this.customReticle)if(this.customReticle.asset)r=za(this.customReticle.asset);else{this.customReticle.loadAssetAsync();return}else r=new Q(new rC(.07,.09,32).rotateX(-Math.PI/2),new Me({side:_i,depthTest:!1,depthWrite:!1,transparent:!0,opacity:1,color:15658734})),r.name="AR Placement Reticle";if(Yx){const l=new bi(1);l.position.y+=.01,r.add(l)}this._reticle[i]=r,r.matrixAutoUpdate=!1,r.visible=!1}if(r.lastPos=r.lastPos||n.position.clone(),r.lastQuat=r.lastQuat||n.quaternion.clone(),r.position.copy(r.lastPos.lerp(n.position,this.context.time.deltaTime/.1)),r.lastPos.copy(r.position),r.quaternion.copy(r.lastQuat.slerp(n.quaternion,this.context.time.deltaTime/.05)),r.lastQuat.copy(r.quaternion),r.scale.set(o,o,o),this.customReticle&&this.applyViewBasedTransform(r),r.updateMatrix(),r.visible=!0,r.parent!==this.context.scene&&this.context.scene.add(r),this._placementStartTime<0&&(this._placementStartTime=this.context.time.realtimeSinceStartup),this.autoPlace)if(this.upVec.set(0,1,0).applyQuaternion(r.quaternion),this.upVec.dot($(0,1,0))>.9){let l=r["autoplace:timer"]||0;l>=1?(r.visible=!1,this.onPlaceScene(null)):(l+=this.context.time.deltaTime,r["autoplace:timer"]=l)}else r["autoplace:timer"]=0}onScaleChanged(){}onRevertSceneChanges(){var t;for(const i of this._reticle)i&&(i.visible=!1,i?.removeFromParent());this._reticle.length=0;for(let i=this._placementScene.children.length-1;i>=0;i--){const n=this._placementScene.children[i];this.context.scene.add(n)}(t=this._createdPlacementObject)==null||t.removeFromParent();for(const i of this._reparentedComponents)P.addComponent(i.originalObject,i.comp)}async onCreateAnchor(t,i){if(i.createAnchor===void 0){console.warn("Hit does not support creating an anchor",i),F()&&_e("Hit does not support creating an anchor");return}else{const n=await i.createAnchor(t.viewerPose.transform);t.running&&n&&(this._anchor=n)}}applyViewBasedTransform(t){const i=this.context.mainCamera,n=t,o=i.worldPosition,r=n.worldPosition;this.upVec.set(0,1,0).applyQuaternion(t.quaternion);const l=i.worldPosition;l&&t.position.clone().sub(l).angleTo(this.upVec)<Math.PI/2&&this.upVec.negate();const c=this.upVec.angleTo(this.worldUpVec)*180/Math.PI,h=30;c>h&&c<180-h||c<-h&&c>-180+h?(this.lookPoint.copy(t.position).add(this.upVec),this.lookPoint.y=t.position.y,t.lookAt(this.lookPoint)):(o.y=r.y,t.lookAt(o))}onApplyPose(t){var i,n,o,r;const l=(n=(i=Z.active)==null?void 0:i.rig)==null?void 0:n.gameObject;if(!l){console.warn("No rig object to place");return}(o=Z.active)!=null&&o.rigScale;const c=l.parent||this.context.scene;this._rigPlacementMatrix?(r=this._rigPlacementMatrix)==null||r.decompose(l.position,l.quaternion,l.scale):this._rigPlacementMatrix=l.matrix.clone(),this.applyViewBasedTransform(t),t.updateMatrix(),this.context.scene.add(t),t.attach(l),t.removeFromParent(),l.scale.set(this.arScale,this.arScale,this.arScale),l.position.multiplyScalar(this.arScale),l.updateMatrix(),this.invertForward&&l.matrix.premultiply(DT),l.matrix.premultiply(this._startOffset),l.matrix.decompose(l.position,l.quaternion,l.scale),c.add(l)}}a(Vn,"_eventListeners",{});const M0=class{constructor(s){a(this,"oneFingerDrag",!0),a(this,"twoFingerRotate",!0),a(this,"twoFingerScale",!0),a(this,"factor",1),a(this,"context"),a(this,"offset"),a(this,"plane"),a(this,"_scale",1),a(this,"_hasChanged",!1),a(this,"_enabled",!1),a(this,"currentlyUsedPointerIds",new Set),a(this,"currentlyUnusedPointerIds",new Set),a(this,"onPointerDownEarly",t=>{this.isActive&&t.stopPropagation()}),a(this,"onPointerDownLate",t=>{t.used?this.currentlyUsedPointerIds.add(t.pointerId):this.currentlyUsedPointerIds.size<=0&&this.currentlyUnusedPointerIds.add(t.pointerId)}),a(this,"onPointerUpEarly",t=>{this.currentlyUsedPointerIds.delete(t.pointerId),this.currentlyUnusedPointerIds.delete(t.pointerId)}),a(this,"prev",new Map),a(this,"_didMultitouch",!1),a(this,"touchStart",t=>{if(!t.defaultPrevented)for(let i=0;i<t.changedTouches.length;i++){const n=t.changedTouches[i],o=Y.isAndroidDevice()&&n.clientY<window.innerHeight*.1;this.prev.has(n.identifier)||this.prev.set(n.identifier,{ignore:o,x:0,z:0,screenx:0,screeny:0});const r=this.prev.get(n.identifier);if(r){const l=this.getPositionOnPlane(n.clientX,n.clientY);r.x=l.x,r.z=l.z,r.screenx=n.clientX,r.screeny=n.clientY}}}),a(this,"touchEnd",t=>{t.touches.length<=0&&(this._didMultitouch=!1);for(let i=0;i<t.changedTouches.length;i++){const n=t.changedTouches[i];this.prev.delete(n.identifier)}}),a(this,"touchMove",t=>{if(!t.defaultPrevented&&this.isActive){if(t.touches.length===1){if(this._didMultitouch)return;const i=t.touches[0],n=this.prev.get(i.identifier);if(!n||n.ignore)return;const o=this.getPositionOnPlane(i.clientX,i.clientY),r=o.x-n.x,l=o.z-n.z;if(r===0&&l===0)return;this.oneFingerDrag&&this.addMovement(r,l),n.x=o.x,n.z=o.z,n.screenx=i.clientX,n.screeny=i.clientY;return}else if(t.touches.length===2){this._didMultitouch=!0;const i=t.touches[0],n=t.touches[1],o=this.prev.get(i.identifier),r=this.prev.get(n.identifier);if(!o||!r)return;if(this.twoFingerRotate){const l=Math.atan2(i.clientY-n.clientY,i.clientX-n.clientX),c=Math.atan2(o.screeny-r.screeny,o.screenx-r.screenx),h=l-c;Math.abs(h)>.001&&this.addRotation(h)}if(this.twoFingerScale){const l=i.clientX-n.clientX,c=i.clientY-n.clientY,h=Math.sqrt(l*l+c*c),d=o.screenx-r.screenx,u=o.screeny-r.screeny,p=Math.sqrt(d*d+u*u),g=h-p;Math.abs(g)>2&&this.addScale(g)}o.screenx=i.clientX,o.screeny=i.clientY,r.screenx=n.clientX,r.screeny=n.clientY}}}),a(this,"_raycaster",new ld),a(this,"_intersection",new x),a(this,"_screenPos",new x),a(this,"_tempMatrix",new ne),this.context=s,this.offset=new ne,this.plane=new dr,this.plane.setFromNormalAndCoplanarPoint(M0.up,M0.zero)}reset(){this._scale=1,this.offset.identity()}get hasChanged(){return this._hasChanged}applyMatrixTo(s,t){this._hasChanged=!1,t?(this.offset.invert(),s.premultiply(this.offset)):s.multiply(this.offset)}get isActive(){return this.currentlyUsedPointerIds.size<=0&&this.currentlyUnusedPointerIds.size>0}enable(){this._enabled||(this._enabled=!0,this.context.input.addEventListener("pointerdown",this.onPointerDownEarly,{queue:Ci.Early}),this.context.input.addEventListener("pointerdown",this.onPointerDownLate,{queue:Ci.Late}),this.context.input.addEventListener("pointerup",this.onPointerUpEarly,{queue:Ci.Early}),window.addEventListener("touchstart",this.touchStart,{passive:!1}),window.addEventListener("touchmove",this.touchMove,{passive:!1}),window.addEventListener("touchend",this.touchEnd,{passive:!1}))}disable(){this._enabled&&(this._enabled=!1,this.context.input.removeEventListener("pointerdown",this.onPointerDownEarly,{queue:Ci.Early}),this.context.input.removeEventListener("pointerdown",this.onPointerDownLate,{queue:Ci.Late}),this.context.input.removeEventListener("pointerup",this.onPointerUpEarly,{queue:Ci.Early}),window.removeEventListener("touchstart",this.touchStart),window.removeEventListener("touchmove",this.touchMove),window.removeEventListener("touchend",this.touchEnd))}getPositionOnPlane(s,t){const i=this.context.mainCamera;return this._screenPos.x=s/window.innerWidth*2-1,this._screenPos.y=-(t/window.innerHeight)*2+1,this._screenPos.z=1,this._screenPos.unproject(i),this._raycaster.set(i.position,this._screenPos.sub(i.position)),this._raycaster.ray.intersectPlane(this.plane,this._intersection),this._intersection}addMovement(s,t){s/=this._scale,t/=this._scale,s*=this.factor,t*=this.factor,this.offset.elements[12]+=s,this.offset.elements[14]+=t,(s!==0||t!==0)&&(this._hasChanged=!0)}addScale(s){s/=window.innerWidth,s*=-1,this._scale*=1+s,this._tempMatrix.makeScale(1-s,1-s,1-s),this.offset.premultiply(this._tempMatrix),s!==0&&(this._hasChanged=!0)}addRotation(s){s*=-1,this._tempMatrix.makeRotationY(s),this.offset.premultiply(this._tempMatrix),s!==0&&(this._hasChanged=!0)}};let bp=M0;a(bp,"up",new x(0,1,0)),a(bp,"zero",new x(0,0,0)),a(bp,"one",new x(1,1,1));const Uo=O("debugautosync"),R0=Symbol("syncerId");class BT{constructor(){a(this,"_syncers",{})}getOrCreateSyncer(t){if(!t.guid)return null;if(this._syncers[t.guid])return this._syncers[t.guid];const i=new FT(t);return i[R0]=t.guid,this._syncers[i[R0]]=i,i}removeSyncer(t){delete this._syncers[t[R0]]}}const T0=new BT;class FT{constructor(t){a(this,"comp"),a(this,"hasChanges",!1),a(this,"changedProperties",{}),a(this,"_isReceiving",!1),a(this,"_isInit",!1),a(this,"onHandleSending",()=>{if(!this.hasChanges)return;this.hasChanges=!1;const i=this.comp.context.connection;if(!i||!i.isConnected||!i.isInRoom){for(const n in this.changedProperties)delete this.changedProperties[n];return}for(const n in this.changedProperties){const o=this.changedProperties[n];Uo&&console.log("SEND",this.comp.guid,this.networkingKey),i.send(this.networkingKey,{guid:this.comp.guid,property:n,data:o},bs.Queued),delete this.changedProperties[n]}}),a(this,"onHandleReceiving",i=>{if(Uo&&console.log("SYNCFIELD RECEIVE",this.comp.name,this.comp.guid,i),!!this._isInit&&this.comp&&i.guid===this.comp.guid)try{this._isReceiving=!0,this.comp[i.property]=i.data}catch(n){console.error(n)}finally{this._isReceiving=!1}}),this.comp=t}get networkingKey(){return this.comp.guid}init(t){if(this._isInit)return;this._isInit=!0,this.comp=t,this.comp.context.post_render_callbacks.push(this.onHandleSending),this.comp.context.connection.beginListen(this.networkingKey,this.onHandleReceiving);const i=this.comp.context.connection.tryGetState(this.comp.guid);i&&this.onHandleReceiving(i)}destroy(){this._isInit&&(this.comp.context.post_render_callbacks.splice(this.comp.context.post_render_callbacks.indexOf(this.onHandleSending),1),this.comp.context.connection.stopListen(this.networkingKey,this.onHandleReceiving),this.comp=null,this._isInit=!1)}notifyChanged(t,i){this._isReceiving||(Uo&&console.log("Property changed: "+t,i),this.hasChanges=!0,this.changedProperties[t]=i)}}function zT(s,t){let i=t!==s;return!i&&s&&t&&(Array.isArray(s)&&Array.isArray(t)||typeof s=="object"&&typeof t=="object")&&(i=!0),i}const mh=Symbol("AutoSyncHandler");function UT(s){if(s[mh])return s[mh];const t=T0.getOrCreateSyncer(s);return t?.init(s),s[mh]=t,t}function NT(s){const t=s[mh];t&&(T0.removeSyncer(t),t.destroy(),delete s[mh])}const E0=function(s=null){return function(t,i){var n;let o="";typeof i=="string"?o=i:o=i.name;let r=null,l;typeof s=="string"?l=t[s]:typeof s=="function"&&(l=s),l==null&&(F()||Uo)&&s!=null&&console.warn('syncField: no callback function found for property "'+o+'"','"'+s+'"');const c=t,h=c.__internalAwake;if(typeof h!="function"){(Uo||F())&&console.error('@syncField can currently only used on Needle Engine Components, custom object of type "'+((n=t?.constructor)==null?void 0:n.name)+'" is not supported',t);return}Uo&&console.log(o);const d=Symbol(o);c.__internalAwake=function(){if(this[d]!==void 0)return;this[d]=this[o],r=T0.getOrCreateSyncer(this);const p=Object.getOwnPropertyDescriptor(this,o);if(p?.set===void 0){let g=!1;Object.defineProperty(this,o,{set:function(y){var f;const v=this[d];if(this[d]=y,g){(F()||Uo)&&console.warn("Recursive call detected",o);return}g=!0;try{const b=zT(y,v);Uo&&console.log("SyncField assignment",o,"changed?",b,y,l),b&&l?.call(this,y,v)!==!1&&((f=UT(this))==null||f.notifyChanged(o,y))}finally{g=!1}},get:function(){return this[d]},configurable:!0,enumerable:!0})}r?.init(this),h.call(this)};const u=c.__internalDestroy;c.__internalDestroy=function(){NT(this),u.call(this)}}};var WT=Object.defineProperty,VT=Object.getOwnPropertyDescriptor,_p=(s,t,i,n)=>{for(var o=n>1?void 0:n?VT(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&WT(t,i,o),o};const ti=O("debugplayersync"),Kx=class extends A{constructor(){super(...arguments),a(this,"autoSync",!0),a(this,"asset"),a(this,"onPlayerSpawned"),a(this,"_localInstance"),a(this,"onJoinedRoom",()=>{ti&&console.log("PlayerSync.joinedRoom. autoSync is set to "+this.autoSync),this.autoSync&&this.getInstance()}),a(this,"destroyInstance",()=>{var s;(s=this._localInstance)==null||s.then(t=>{ti&&console.log("PlayerSync.destroyInstance",t),yc(t,this.context.connection,!0,{saveInRoom:!1})}),this._localInstance=void 0})}static async setupFrom(s,t){const i=le.getOrCreateFromUrl(s);if(!i.asset){const r=await i.loadAssetAsync();r&&P.getOrAddComponent(r,ji)}const n=new Kx;n._internalInit(t),n.asset=i;const o=new j;return o.guid=s,P.addComponent(o,n),n}awake(){this.watchTabVisible(),this.onPlayerSpawned||(this.onPlayerSpawned=new ke)}onEnable(){this.context.connection.beginListen(ie.RoomStateSent,this.onJoinedRoom),this.context.connection.beginListen(ie.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(ie.LeftRoom,this.destroyInstance),this.context.connection.isInRoom&&this.onJoinedRoom()}onDisable(){this.context.connection.stopListen(ie.RoomStateSent,this.onJoinedRoom),this.context.connection.stopListen(ie.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(ie.LeftRoom,this.destroyInstance)}async getInstance(){var s,t,i,n,o,r;if(this._localInstance)return this._localInstance;if(ti&&console.log("PlayerSync.createInstance",(s=this.asset)==null?void 0:s.url),!((t=this.asset)!=null&&t.asset)&&!((i=this.asset)!=null&&i.url))return console.error('PlayerSync: can not create an instance because "asset" is not set and or has no URL!'),null;this.gameObject.guid||console.warn("PlayerSync: gameObject has no guid! This might cause issues with syncing the player state."),this._localInstance=(n=this.asset)==null?void 0:n.instantiateSynced({parent:this.gameObject,deleteOnDisconnect:!0},!0);const l=await this._localInstance;if(l){const c=P.getComponentsInChildren(l,ji);if(ti&&console.log(`PlayerSync.createInstance: found ${c?.length} PlayerState components. Owner: ${this.context.connection.connectionId}`),c!=null&&c.length){for(const h of c)h.owner=this.context.connection.connectionId;(o=this.onPlayerSpawned)==null||o.invoke(l)}else this._localInstance=void 0,console.error("<strong>Failed finding PlayerState on "+((r=this.asset)==null?void 0:r.url)+"</strong>: please make sure the asset has a PlayerState component!"),P.destroySynced(l)}else this._localInstance=void 0,console.warn("PlayerSync: failed instantiating asset!");return this._localInstance}watchTabVisible(){window.addEventListener("visibilitychange",s=>{if(document.visibilityState==="visible")for(let t=ji.all.length-1;t>=0;t--){const i=ji.all[t];(!i.owner||!this.context.connection.userIsInRoom(i.owner))&&i.doDestroy()}})}};let bl=Kx;_p([m()],bl.prototype,"autoSync",2),_p([m(le)],bl.prototype,"asset",2),_p([m(ke)],bl.prototype,"onPlayerSpawned",2);var Zx=(s=>(s.OwnerChanged="ownerChanged",s))(Zx||{}),gh;const Tt=(gh=class extends A{constructor(){super(...arguments),a(this,"onOwnerChangeEvent",new ke),a(this,"onFirstOwnerChangeEvent",new ke),a(this,"hasOwner",!1),a(this,"owner"),a(this,"dontDestroy",!1),a(this,"onUserLeftRoom",s=>{if(s.userId===this.owner){ti&&console.log("PLAYERSYNC LEFT",this.owner),this.doDestroy();return}})}static get all(){return Tt._all}static get local(){return Tt._local}static getFor(s){if(s instanceof j)return P.getComponentInParent(s,Tt);if(s instanceof A)return P.getComponentInParent(s.gameObject,Tt)}static isLocalPlayer(s){const t=Tt.getFor(s);return t?.isLocalPlayer??!1}static addEventListener(s,t){return this._callbacks[s]||(this._callbacks[s]=[]),this._callbacks[s].push(t),t}static removeEventListener(s,t){if(!this._callbacks[s])return;const i=this._callbacks[s].indexOf(t);i>=0&&this._callbacks[s].splice(i,1)}static dispatchEvent(s,t){if(this._callbacks[s])for(const i of this._callbacks[s])i(t)}get isLocalPlayer(){return this.owner===this.context.connection.connectionId}onOwnerChange(s,t){var i,n;ti&&console.log(`PlayerSync.onOwnerChange: ${t} \u2192 ${s} (me: ${this.context.connection.connectionId})`);const o=Tt._local.indexOf(this);o>=0&&Tt._local.splice(o,1);const r={playerState:this,oldValue:t,newValue:s};if(this.hasOwner||(this.hasOwner=!0,(i=this.onFirstOwnerChangeEvent)==null||i.invoke(r)),(n=this.onOwnerChangeEvent)==null||n.invoke(r),this.owner===this.context.connection.connectionId){Tt._local.push(this);const c=new CustomEvent("local-owner-changed",{detail:r});this.dispatchEvent(c)}const l=new CustomEvent("owner-changed",{detail:r});this.dispatchEvent(l),Tt.dispatchEvent("ownerChanged",l)}awake(){Tt.all.push(this),ti&&console.log("Registered new PlayerState",this.guid,Tt.all.length-1,Tt.all),this.context.connection.beginListen(ie.UserLeftRoom,this.onUserLeftRoom)}async start(){ti&&console.log("PLAYERSTATE.START, owner: "+this.owner,this.context.connection.usersInRoom([])),this.owner?(this.context.connection.isInRoom||await gs(300),this.context.connection.userIsInRoom(this.owner)==!1&&(ti&&console.log(`PlayerSync.start \u2192 doDestroy "${this.name}" because user "${this.owner}" is not in room anymore...`,"Currently in room:",...this.context.connection.usersInRoom()),this.doDestroy())):this.owner||(ti&&console.warn("PlayerState.start \u2192 owner is undefined!",this.name),setTimeout(()=>{!this.destroyed&&!this.owner?this.dontDestroy?ti&&console.warn("PlayerState.start \u2192 owner is still undefined but dontDestroy is set to true",this.name):(ti&&console.warn(`PlayerState.start \u2192 owner is still undefined: destroying "${this.name}" instance now`),this.doDestroy()):ti&&console.log("PlayerState.start \u2192 owner is assigned",this.owner)},2e3))}doDestroy(){ti&&console.log("PlayerSync.doDestroy \u2192 syncDestroy",this.name),yc(this.gameObject,this.context.connection,!0,{saveInRoom:!1})}onDestroy(){if(ti&&console.warn("PlayerState.onDestroy",this.owner),this.context.connection.stopListen(ie.UserLeftRoom,this.onUserLeftRoom),Tt.all.splice(Tt.all.indexOf(this),1),this.isLocalPlayer){const s=Tt._local.indexOf(this);s>=0&&Tt._local.splice(s,1)}}},a(gh,"_all",[]),a(gh,"_local",[]),a(gh,"_callbacks",{}),gh);let ji=Tt;_p([E0(ji.prototype.onOwnerChange)],ji.prototype,"owner",2);var HT=Object.defineProperty,$T=Object.getOwnPropertyDescriptor,_l=(s,t,i,n)=>{for(var o=n>1?void 0:n?$T(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&HT(t,i,o),o};class an extends A{constructor(){super(...arguments),a(this,"position","bottom"),a(this,"showNeedleLogo",!0),a(this,"showSpatialMenu"),a(this,"createFullscreenButton"),a(this,"createMuteButton"),a(this,"createQRCodeButton")}onEnable(){this.applyOptions()}applyOptions(){this.context.menu.setPosition(this.position),this.context.menu.showNeedleLogo(this.showNeedleLogo),this.createFullscreenButton===!0&&this.context.menu.showFullscreenOption(!0),this.createMuteButton===!0&&this.context.menu.showAudioPlaybackOption(!0),this.showSpatialMenu===!0&&this.context.menu.showSpatialMenu(this.showSpatialMenu),this.createQRCodeButton===!0&&(Y.isMobileDevice()||this.context.menu.showQRCodeButton(!0))}}_l([m()],an.prototype,"position",2),_l([m()],an.prototype,"showNeedleLogo",2),_l([m()],an.prototype,"showSpatialMenu",2),_l([m()],an.prototype,"createFullscreenButton",2),_l([m()],an.prototype,"createMuteButton",2),_l([m()],an.prototype,"createQRCodeButton",2);var qT=Object.defineProperty,GT=Object.getOwnPropertyDescriptor,A0=(s,t,i,n)=>{for(var o=n>1?void 0:n?GT(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&qT(t,i,o),o};const fh=O("debugwebxr"),Jx=new V().setFromAxisAngle(new x(0,1,0),Math.PI);class No extends A{constructor(){super(...arguments),a(this,"head"),a(this,"leftHand"),a(this,"rightHand"),a(this,"_leftHandMeshes"),a(this,"_rightHandMeshes"),a(this,"_syncTransforms")}async onEnterXR(t){if(!this.activeAndEnabled)return;fh&&console.warn("AVATAR ENTER XR",this.guid,this.sourceId,this,this.activeAndEnabled),this._syncTransforms&&(this._syncTransforms.length=0),await this.prepareAvatar();const i=ji.getFor(this);if(i!=null&&i.owner){const n=this.gameObject.addComponent(Mt);n.avatar=this.gameObject,n.connectionId=i.owner}else this.context.connection.isConnected?console.error("No player state found for avatar",this):i&&!this.context.connection.isConnected&&(i.dontDestroy=!0)}onLeaveXR(t){const i=this.gameObject.getComponent(Mt);i&&i.destroy()}onUpdateXR(t){var i,n;if(!this.activeAndEnabled)return;const o=ji.isLocalPlayer(this);if(!o)return;const r=t.xr;if(r.rig&&r.rig.gameObject!==this.gameObject.parent&&(this.gameObject.position.set(0,0,0),this.gameObject.rotation.set(0,0,0),this.gameObject.scale.set(1,1,1),r.rig.gameObject.add(this.gameObject)),this._syncTransforms&&o)for(const u of this._syncTransforms)u.fastMode=!0,u.isOwned()||u.requestOwnership();if(this.head&&this.context.mainCamera){const u=this.head.asset;if(u.position.copy(this.context.mainCamera.position),u.position.x*=-1,u.position.z*=-1,u.quaternion.copy(this.context.mainCamera.quaternion),u.quaternion.x*=-1,this.context.time.frameCount%10===0&&this.head.asset){const p=P.getComponentsInChildren(this.head.asset,Ei);for(const g of p)g.enabled=!1,g.gameObject.visible=!1}}const l=t.xr.leftController,c=(i=this.leftHand)==null?void 0:i.asset;l&&c?(c.position.copy(l.gripPosition),c.quaternion.copy(l.gripQuaternion),c.quaternion.multiply(Jx),c.visible=l.isTracking,this.updateHandVisibility(l,c,this._leftHandMeshes)):c&&c.visible&&(c.visible=!1);const h=t.xr.rightController,d=(n=this.rightHand)==null?void 0:n.asset;h&&d?(d.position.copy(h.gripPosition),d.quaternion.copy(h.gripQuaternion),d.quaternion.multiply(Jx),d.visible=h.isTracking,this.updateHandVisibility(h,d,this._rightHandMeshes)):d&&d.visible&&(d.visible=!1)}onBeforeRender(){this.context.xr&&this.context.time.frame%10===0&&this.updateRemoteAvatarVisibility()}updateHandVisibility(t,i,n){if(n){const o=t.model&&t.model.visible&&t.model!==i;n.forEach(r=>{Pn(r,!o)})}}updateRemoteAvatarVisibility(){var t,i,n;if(this.context.connection.isConnected){const o=ji.getFor(this);if(o&&o.isLocalPlayer==!1){const r=Z.getXRSync(this.context);if(r&&r.hasState(o.owner)){this.tryFindAvatarObjectsIfMissing();const l=(t=this.leftHand)==null?void 0:t.asset;l&&(l.visible=r?.isTracking(o.owner,"left")??!1);const c=(i=this.rightHand)==null?void 0:i.asset;c&&(c.visible=r?.isTracking(o.owner,"right")??!1)}if((n=this.head)!=null&&n.asset){const l=P.getComponentsInChildren(this.head.asset,Ei);for(const c of l)c.enabled=!1,c.gameObject.visible=!0}}}}tryFindAvatarObjectsIfMissing(){if(!this.head||!this.leftHand||!this.rightHand){const t={head:this.head,leftHand:this.leftHand,rightHand:this.rightHand};Wb.tryFindAvatarObjects(this.gameObject,this.sourceId||"",t),t.head&&(this.head=t.head),t.leftHand&&(this.leftHand=t.leftHand),t.rightHand&&(this.rightHand=t.rightHand)}}async prepareAvatar(){var t,i;if(this.tryFindAvatarObjectsIfMissing(),this.head)this.head instanceof j&&(this.head=new le("",this.sourceId,this.head));else{const n=new j;n.name="Head";const o=mo.createPrimitive(_r.Cube);n.add(o),this.gameObject.add(n),this.head=new le("",this.sourceId,n),fh&&console.log("Create head",n)}if(this.rightHand)this.rightHand instanceof j&&(this.rightHand=new le("",this.sourceId,this.rightHand));else{const n=new j;n.name="Right Hand",this.gameObject.add(n),this.rightHand=new le("",this.sourceId,n),fh&&console.log("Create right hand",n)}if(this.leftHand)this.leftHand instanceof j&&(this.leftHand=new le("",this.sourceId,this.leftHand));else{const n=new j;n.name="Left Hand",this.gameObject.add(n),this.leftHand=new le("",this.sourceId,n),fh&&console.log("Create left hand",n)}await this.loadAvatarObjects(this.head,this.leftHand,this.rightHand),this._leftHandMeshes=[],(t=this.leftHand.asset)==null||t.traverse(n=>{n!=null&&n.isMesh&&this._leftHandMeshes.push(n)}),this._rightHandMeshes=[],(i=this.rightHand.asset)==null||i.traverse(n=>{n!=null&&n.isMesh&&this._rightHandMeshes.push(n)}),ji.isLocalPlayer(this.gameObject)&&(this._syncTransforms=P.getComponentsInChildren(this.gameObject,$s))}async loadAvatarObjects(t,i,n){const o=t.loadAssetAsync(),r=i.loadAssetAsync(),l=n.loadAssetAsync(),c=new Array;o&&c.push(o),r&&c.push(r),l&&c.push(l);const h=await yd(c);fh&&console.log("Avatar loaded results:",h)}}A0([m(le)],No.prototype,"head",2),A0([m(le)],No.prototype,"leftHand",2),A0([m(le)],No.prototype,"rightHand",2);var XT=Object.defineProperty,QT=Object.getOwnPropertyDescriptor,wp=(s,t,i,n)=>{for(var o=n>1?void 0:n?QT(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&XT(t,i,o),o};const Hn=O("debugwebxr"),Wo=new Array;class ln extends A{constructor(){super(...arguments),a(this,"createControllerModel",!0),a(this,"createHandModel",!0),a(this,"customLeftHand"),a(this,"customRightHand"),a(this,"_models",new Array)}supportsXR(t){return t==="immersive-vr"||t==="immersive-ar"}async onXRControllerAdded(t){var i;if(!(t.xr.isVR||t.xr.isPassThrough))return;const{controller:n}=t;if(Hn&&console.warn("Add Controller Model for",n.side,n.index),this.createControllerModel||this.createHandModel){if(n.hand){if(this.createHandModel){const o=await this.loadHandModel(this,n);if(!o||!n.connected||!n.isHand){o!=null&&o.handObject&&Fa(o.handObject,!1),(i=o?.handObject)==null||i.destroy();return}this._models.push({controller:n,model:o.handObject,handmesh:o.handmesh}),this._models.sort((r,l)=>r.controller.index-l.controller.index),this.scene.add(o.handObject),n.model=o.handObject}}else if(this.createControllerModel){const o=await n.getModelUrl();if(o){const r=await this.loadModel(n,o);if(!r||!n.connected||n.isHand)return;this._models.push({controller:n,model:r}),this._models.sort((l,c)=>l.controller.index-c.controller.index),this.scene.add(r),r.traverse(l=>{l.layers.set(2),l.matrixAutoUpdate=!1,l.updateMatrix()}),n.model=r}else n.targetRayMode!=="transient-pointer"&&console.warn("XRControllerModel: no model found for "+n.side)}}}onXRControllerRemoved(t){console.debug("XR Controller Removed",t.controller.side,t.controller.index);const i=this._models.findIndex(o=>o.controller===t.controller),n=this._models[i];n&&(this._models.splice(i,1),n.model&&(Fa(n.model,!1),n.model.destroy(),n.model=void 0))}onLeaveXR(t){for(const i of this._models)i&&(i.model&&(Fa(i.model,!1),i.model.destroy(),i.model=void 0),i.controller.model===i.model&&(i.controller.model=null));this._models.length=0}onBeforeRender(){if(Z.active&&(Hn&&(Wo[0]=Date.now()),this.updateRendering(Z.active),Hn)){const t=Date.now()-Wo[0];Wo.push(t),Wo.length>=30&&(Wo[0]=0,Wo.reduce((i,n)=>i+n,0)/Wo.length,Wo.length=0)}}updateRendering(t){var i,n,o,r,l;for(let c=0;c<this._models.length;c++){const h=this._models[c];if(!h)continue;const d=h.controller;if(!d.connected){Hn&&console.warn("XRControllerModel.onUpdateXR: controller is not connected anymore",d.side,d.hand);continue}if(h.model&&!h.handmesh)h.model.matrixAutoUpdate=!1,h.model.matrix.copy(d.gripMatrix),h.model.visible=d.isTracking,(i=t.rig)==null||i.gameObject.add(h.model);else if(d.inputSource.hand&&h.handmesh){const u=t.referenceSpace,p=this.context.renderer.xr.getHand(d.index);if(u&&t.frame.getJointPose){for(const g of d.inputSource.hand.values()){const y=p.joints[g.jointName];if(y){const f=d.getHandJointPose(g);if(f){const v=f.transform.position,b=f.transform.orientation;y.position.copy(v),y.quaternion.copy(b),y.matrixAutoUpdate=!1}y.visible=f!=null}}h.model&&(h.model.visible=d.isTracking,h.model.visible&&h.model.parent!==((n=t.rig)==null?void 0:n.gameObject)&&((o=t.rig)==null||o.gameObject.add(h.model))),(r=h.model)!=null&&r.visible&&((l=h.handmesh)==null||l.updateMesh(),h.model.matrixAutoUpdate=!1,h.model.matrix.identity(),h.model.applyMatrix4(Ma))}}}}async loadModel(t,i){var n;if(!t.connected)return console.warn("XRControllerModel.onXRControllerAdded: controller is not connected anymore",t.side),null;const o=await le.getOrCreate("",i).instantiate();return Fa(o),(n=Z.active)!=null&&n.isPassThrough&&o.traverseVisible(r=>{this.makeOccluder(r)}),o}async loadHandModel(t,i){const n=this.context,o=n.renderer.xr.getHand(i.index);o||(Hn?q.DrawLabel(i.rayWorldPosition,"No hand found for index "+i.index,.05,5):console.warn("No hand found for index "+i.index));const r=new mr;bu(r,n),await Yu(r,n,this.sourceId??"");const l=Qu(r);let c="";const h=i.side==="left"?this.customLeftHand:this.customRightHand;h?(c=h.url.split(".").slice(0,-1).join("."),r.setPath("")):(c=i.inputSource.handedness==="left"?"left":"right",r.setPath("https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles/generic-hand/"));const d=new j;Fa(d);const u=new zC(d,o,r.path,c,r,p=>{var g;const y=l.gltf;((g=y?.scene.children)==null?void 0:g.length)===0&&(y.scene.children[0]=p),ms().createBuiltinComponents(t.context,t.sourceId||c,l.gltf,null,l),p.traverse(f=>{var v;f.layers.set(2),(v=Z.active)!=null&&v.isPassThrough&&!h&&this.makeOccluder(f),f instanceof Q&&et.assignMeshLOD(f,0)}),i.connected||(Hn&&q.DrawLabel(i.rayWorldPosition,"Hand is loaded but not connected anymore",.05,5),p.removeFromParent())});if(Hn&&d.add(new bi(.5)),i.inputSource.hand){Hn&&console.log(i.inputSource.hand);for(const p of i.inputSource.hand.values())if(o.joints[p.jointName]===void 0){const g=new ro;g.matrixAutoUpdate=!1,g.visible=!0,o.joints[p.jointName]=g,o.add(g)}}else Hn&&q.DrawLabel(i.rayWorldPosition,"No inputSource.hand found for index "+i.index,.05,5);return{handObject:d,handmesh:u}}makeOccluder(t){if(t instanceof Q){let i=t.material;i instanceof Oe&&(i=t.material=i.clone(),i.depthWrite=!0,i.depthTest=!0,i.colorWrite=!1,t.receiveShadow=!1,t.renderOrder=-100)}}}a(ln,"factory",new FC),wp([m()],ln.prototype,"createControllerModel",2),wp([m()],ln.prototype,"createHandModel",2),wp([m(le)],ln.prototype,"customLeftHand",2),wp([m(le)],ln.prototype,"customRightHand",2);class xp extends A{}var YT=Object.defineProperty,KT=Object.getOwnPropertyDescriptor,Vo=(s,t,i,n)=>{for(var o=n>1?void 0:n?KT(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&YT(t,i,o),o};const I0=O("debugwebxr");class Li extends A{constructor(){super(...arguments),a(this,"movementSpeed",1.5),a(this,"rotationStep",30),a(this,"useTeleport",!0),a(this,"usePinchToTeleport",!0),a(this,"useTeleportTarget",!1),a(this,"useTeleportFade",!1),a(this,"showRays",!0),a(this,"showHits",!0),a(this,"isXRMovementHandler",!0),a(this,"xrSessionMode","immersive-vr"),a(this,"_didApplyRotation",!1),a(this,"_didTeleport",!1),a(this,"_teleportBuffer",new Array),a(this,"_plane",null),a(this,"_lines",[]),a(this,"_hitDiscs",[]),a(this,"_hitDistances",[]),a(this,"_lastHitDistances",[]),a(this,"hitPointRaycastFilter",t=>t.type==="SkinnedMesh"?"continue in children":!0)}onUpdateXR(t){const i=t.xr.rig;if(!(i!=null&&i.gameObject)||t.xr.isPassThrough)return;const n=t.xr.leftController,o=t.xr.rightController;n&&this.onHandleMovement(n,i.gameObject),o&&(this.onHandleRotation(o,i.gameObject),this.useTeleport&&this.onHandleTeleport(o,i.gameObject))}onLeaveXR(t){for(const i of this._lines)i.removeFromParent();for(const i of this._hitDiscs)i?.removeFromParent()}onBeforeRender(){var t;(t=this.context.xr)!=null&&t.running&&(this.showRays&&this.renderRays(this.context.xr),this.showHits&&this.renderHits(this.context.xr))}onHandleMovement(t,i){const n=t.getStick("xr-standard-thumbstick");if(n.x!=0||n.y!=0){const o=$(n.x,0,n.y);o.multiplyScalar(this.context.time.deltaTimeUnscaled*this.movementSpeed);const r=Ke(i);o.multiplyScalar(r.x),o.applyQuaternion(t.xr.poseOrientation),o.y=0,o.applyQuaternion(i.worldQuaternion),i.position.add(o),i.updateWorldMatrix(!1,!1);for(const l of i.children)l.updateWorldMatrix(!1,!1)}}onHandleRotation(t,i){if(t._isMxInk)return;const n=t.getStick("xr-standard-thumbstick").x;if(this._didApplyRotation)Math.abs(n)<.3&&(this._didApplyRotation=!1);else if(Math.abs(n)>.5){this._didApplyRotation=!0;const o=n>0?1:-1,r=ee(this.context.mainCamera).clone();i.rotateY(o*W.toRadians(this.rotationStep));const l=ee(this.context.mainCamera).clone().sub(r);l.y=0,i.position.sub(l)}}onHandleTeleport(t,i){var n,o,r,l,c;let h=0;if(t.hand&&this.usePinchToTeleport&&t.isTeleportGesture){const d=t.getPointerId("primary");if(d!=null&&this.context.input.getIsPointerIdInUse(d))return;const u=t.getGesture("pinch");u&&(h=u.value)}else h=(n=t.getStick("xr-standard-thumbstick"))==null?void 0:n.y;if(this._didTeleport)h>=0&&h<.4?this._didTeleport=!1:h<0&&h>-.4&&(this._didTeleport=!1);else if(h>.8){this._didTeleport=!0;const d=this.context.physics.raycastFromRay(t.ray)[0];if(d&&d.object instanceof xa){const p=(o=d.normal)==null?void 0:o.dot($(0,1,0));if(p!==void 0&&p<.4)return}let u=d?.point;if(!u&&!this.useTeleportTarget){this._plane||(this._plane=new dr(new x(0,1,0),0));const p=i.worldPosition;this._plane.setFromNormalAndCoplanarPoint(new x(0,1,0),p);const g=t.ray;u=p.clone(),this._plane.intersectLine(new aC(g.origin,$(g.direction).multiplyScalar(1e4).add(g.origin)),u),u.distanceTo(p)>i.scale.x*10&&(u=null)}if(u){if(this.useTeleportTarget&&!P.getComponentInParent(d.object,xp))return;const p=u.clone();if(I0&&q.DrawSphere(u,.025,16711680,5),(r=this.context.mainCamera)==null?void 0:r.position){const g=(l=this.context.xr)==null?void 0:l.getUserOffsetInRig();g&&(g.y=0,p.sub(g),I0&&q.DrawWireSphere(g.add(p),.025,65280,5))}this._teleportBuffer.push(i.matrix.clone()),this._teleportBuffer.length>10&&this._teleportBuffer.shift(),this.useTeleportFade?(c=t.xr.fadeTransition())==null||c.then(()=>{i.worldPosition=p}):i.worldPosition=p}}else if(h<-.8&&(this._didTeleport=!0,this._teleportBuffer.length>0)){const d=this._teleportBuffer.pop();d&&d.decompose(i.position,i.quaternion,i.scale)}}renderRays(t){var i;for(let n=0;n<this._lines.length;n++){const o=this._lines[n];o&&(o.visible=!1)}for(let n=0;n<t.controllers.length;n++){const o=t.controllers[n];let r=this._lines[n];if(!o.connected||!o.isTracking||!o.ray||o.targetRayMode==="transient-pointer"||!o.hasSelectEvent){r&&(r.visible=!1);continue}r||(r=this.createRayLineObject(),r.scale.z=.5,this._lines[n]=r),o.updateRayWorldPosition(),o.updateRayWorldQuaternion();const l=o.rayWorldPosition,c=o.rayWorldQuaternion;r.position.copy(l),r.quaternion.copy(c);const h=t.rigScale,d=this.usePinchToTeleport&&o.isTeleportGesture,u=this._lastHitDistances[n],p=this._hitDistances[n]!=null,g=u??h;r.scale.set(h,h,g),r.visible=!0,r.layers.disableAll(),r.layers.enable(2);let y=r.material.opacity;d?y=1:this.showHits&&g<t.rigScale*.5?y=0:(i=o.getButton("primary"))!=null&&i.pressed?y=.5:y=p?.2:.1,r.material.opacity=W.lerp(r.material.opacity,y,this.context.time.deltaTimeUnscaled/.1),r.parent!==this.context.scene&&this.context.scene.add(r)}}renderHits(t){var i;for(const n of this._hitDiscs){if(!n)continue;const o=n.controller;if(!o||!o.connected||!o.isTracking){n.visible=!1;continue}}for(let n=0;n<t.controllers.length;n++){const o=t.controllers[n];if(!o.connected||!o.isTracking||!o.ray||!o.hasSelectEvent)continue;let r=this._hitDiscs[n],l=!0;const c=o.getPointerId("primary");c!=null&&this.context.input.getIsPointerIdInUse(c)&&(r&&(r.visible=!1),this._hitDistances[n]=null,this._lastHitDistances[n]=0,l=!1);const h=this.context.time.smoothedFps>=59?1:10;if((this.context.time.frame+o.index)%h!==0&&(l=!1),!l){const p=this._hitDiscs[n];p&&p.visible&&p.hit&&this.updateHitPointerPosition(o,p,p.hit.distance);continue}const d=this.context.physics.raycastFromRay(o.ray,{testObject:this.hitPointRaycastFilter,precise:!1});let u=d.find(p=>this.usePinchToTeleport&&o.isTeleportGesture?!0:this.isObjectWithInteractiveComponent(p.object));if(u||(u=d[0]),r&&(r.controller=o,r.hit=u),this._hitDistances[n]=u?.distance||null,u){this._lastHitDistances[n]=u.distance;const p=t.rigScale??1;I0&&(q.DrawWireSphere(u.point,.025*p,16711680),q.DrawLabel($(0,.2,0).add(u.point),u.object.name,.02,0)),r||(r=this.createHitPointObject(),this._hitDiscs[n]=r),r.hit=u,r.visible=u.distance>p*.05;let g=.01*(p+u.distance);const y=(i=o.getButton("primary"))==null?void 0:i.pressed;y&&(g*=1.1),r.scale.set(g,g,g),r.layers.set(2);let f=r.material.opacity;if(y?f=1:f=u.distance<.15*p?.2:.6,r.material.opacity=W.lerp(r.material.opacity,f,this.context.time.deltaTimeUnscaled/.1),r.visible){if(u.normal){this.updateHitPointerPosition(o,r,u.distance);const v=u.normal.applyQuaternion(Se(u.object));r.quaternion.setFromUnitVectors(ZT,v)}else this.updateHitPointerPosition(o,r,u.distance);r.parent!==this.context.scene&&this.context.scene.add(r)}}else this._hitDiscs[n]&&(this._hitDiscs[n].visible=!1)}}isObjectWithInteractiveComponent(t,i=0){return Pu(t)||t.isUI===!0?!0:t.isScene?!1:t.parent?this.isObjectWithInteractiveComponent(t.parent,i+1):!1}updateHitPointerPosition(t,i,n){const o=$(t.rayWorldPosition);o.add($(0,0,n-.01).applyQuaternion(t.rayWorldQuaternion)),i.position.lerp(o,this.context.time.deltaTimeUnscaled/.05)}createHitPointObject(){const t=new Q(new rd(.3,6,6),new Me({color:15658734,opacity:.7,transparent:!0,depthTest:!1,depthWrite:!1,side:_i}));return t.layers.disableAll(),t.layers.enable(2),t}createRayLineObject(){const t=new UC;t.layers.disableAll(),t.layers.enable(2);const i=new NC;t.geometry=i;const n=new Float32Array(9);n.set([0,0,.02,0,0,.4,0,0,1]),i.setPositions(n);const o=new Float32Array(9);o.set([1,1,1,.1,.1,.1,0,0,0]),i.setColors(o);const r=new WC({color:16777215,vertexColors:!0,worldUnits:!0,linewidth:.004,transparent:!0,depthWrite:!1,blending:nv,dashed:!1});return t.material=r,t}}Vo([m()],Li.prototype,"movementSpeed",2),Vo([m()],Li.prototype,"rotationStep",2),Vo([m()],Li.prototype,"useTeleport",2),Vo([m()],Li.prototype,"usePinchToTeleport",2),Vo([m()],Li.prototype,"useTeleportTarget",2),Vo([m()],Li.prototype,"useTeleportFade",2),Vo([m()],Li.prototype,"showRays",2),Vo([m()],Li.prototype,"showHits",2);const ZT=new x(0,1,0);var JT=Object.defineProperty,eE=Object.getOwnPropertyDescriptor,xt=(s,t,i,n)=>{for(var o=n>1?void 0:n?eE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&JT(t,i,o),o};const yh=O("debugwebxr"),tE=O("debugusdz");var j0;const wl=(j0=class extends A{constructor(){super(...arguments),a(this,"createVRButton",!0),a(this,"createARButton",!0),a(this,"createSendToQuestButton",!0),a(this,"createQRCode",!0),a(this,"useDefaultControls",!0),a(this,"showControllerModels",!0),a(this,"showHandModels",!0),a(this,"usePlacementReticle",!0),a(this,"customARPlacementReticle"),a(this,"usePlacementAdjustment",!0),a(this,"arScale",1),a(this,"useXRAnchor",!1),a(this,"autoPlace",!0),a(this,"autoCenter",!1),a(this,"useQuicklookExport",!1),a(this,"useDepthSensing",!1),a(this,"useSpatialGrab",!0),a(this,"defaultAvatar"),a(this,"_playerSync"),a(this,"_createdComponentsInSession",[]),a(this,"_usdzExporter"),a(this,"_exitXRMenuButton"),a(this,"_previousXRState",0),a(this,"_spatialGrabRaycaster"),a(this,"onAvatarSpawned",s=>{yh&&console.log("WebXR.onAvatarSpawned",s),P.getComponentInChildren(s,No)??(e=P.addComponent(s,No))}),a(this,"_buttonFactory"),a(this,"_buttons",[])}awake(){Z.getXRSync(this.context)}onEnable(){var s,t;window.location.protocol!=="https:"&&_e('<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&&(P.findObjectOfType(Ge)||(yh&&console.log("WebXR: Adding USDZExporter"),this._usdzExporter=P.addComponent(this.gameObject,Ge),this._usdzExporter.objectToExport=this.context.scene,this._usdzExporter.autoExportAnimations=!0,this._usdzExporter.autoExportAudioSources=!0)),this.handleCreatingHTML(),this.handleOfferSession(),this.defaultAvatar===!0&&(yh&&console.warn("WebXR: No default avatar set, using static default avatar"),this.defaultAvatar=new le("https://cdn.needle.tools/static/avatars/DefaultAvatar.glb")),this.defaultAvatar&&(this._playerSync=this.gameObject.getOrAddComponent(bl),this._playerSync.autoSync=!1),this._playerSync&&typeof this.defaultAvatar!="boolean"&&(this._playerSync.asset=this.defaultAvatar,(s=this._playerSync.onPlayerSpawned)==null||s.removeEventListener(this.onAvatarSpawned),(t=this._playerSync.onPlayerSpawned)==null||t.addEventListener(this.onAvatarSpawned))}onDisable(){var s;(s=this._usdzExporter)==null||s.destroy(),this.removeButtons()}async handleOfferSession(){return this.createVRButton&&await Z.isVRSupported()&&this.createVRButton?Z.offerSession("immersive-vr","default",this.context):this.createARButton&&await Z.isARSupported()&&this.createARButton?Z.offerSession("immersive-ar","default",this.context):!1}get session(){return Z.active??null}get sessionMode(){return Z.activeMode??null}async enterVR(s){return Z.start("immersive-vr",s,this.context)}async enterAR(s){return Z.start("immersive-ar",s,this.context)}exitXR(){Z.stop()}get isActiveWebXR(){return!wl.activeWebXRComponent||wl.activeWebXRComponent===this}onBeforeXR(s,t){var i;if(!this.isActiveWebXR){console.warn(`WebXR: another WebXR component is already active (${(i=wl.activeWebXRComponent)==null?void 0:i.name}). This is ignored: ${this.name}`);return}wl.activeWebXRComponent=this,s=="immersive-ar"&&this.useDepthSensing&&(t.optionalFeatures=t.optionalFeatures||[],t.optionalFeatures.push("depth-sensing"))}async onEnterXR(s){if(!this.isActiveWebXR)return;yh&&console.log("WebXR onEnterXR"),this._previousXRState=Kt.Global.Mask;const t=s.xr.isVR;if(Kt.Global.Set(t?Ks.VR:Ks.AR),s.xr.isAR){let i=P.findObjectOfType(Vn);if(!i)if(this.usePlacementReticle){const n=new j;for(const o of this.context.scene.children)n.add(o);this.context.scene.add(n),i=P.addComponent(n,Vn),this._createdComponentsInSession.push(i)}else(yh||F())&&console.warn("WebXR: No WebARSessionRoot found in scene and usePlacementReticle is disabled in WebXR component.");i&&(i.customReticle=this.customARPlacementReticle,i.arScale=this.arScale,i.arTouchTransform=this.usePlacementAdjustment,i.autoPlace=this.autoPlace,i.autoCenter=this.autoCenter,i.useXRAnchor=this.useXRAnchor)}this.useDefaultControls&&this.setDefaultMovementEnabled(!0),(this.showControllerModels||this.showHandModels)&&this.setDefaultControllerRenderingEnabled(!0),this.useSpatialGrab&&(this._spatialGrabRaycaster=P.findObjectOfType(Ga)??void 0,this._spatialGrabRaycaster||(this._spatialGrabRaycaster=this.gameObject.addComponent(Ga))),this.createLocalAvatar(s.xr),s.xr.isScreenBasedAR||(this._exitXRMenuButton=this.context.menu.appendChild({label:"Quit XR",onClick:()=>this.exitXR(),icon:"exit_to_app",priority:2e4}))}onUpdateXR(s){this.isActiveWebXR&&this._spatialGrabRaycaster&&(this._spatialGrabRaycaster.enabled=this.useSpatialGrab)}onLeaveXR(s){var t,i;if((t=this._exitXRMenuButton)==null||t.remove(),!!this.isActiveWebXR){Kt.Global.Set(this._previousXRState),(i=this._playerSync)==null||i.destroyInstance();for(const n of this._createdComponentsInSession)n.destroy();this._createdComponentsInSession.length=0,this.handleOfferSession(),Xl(1).then(()=>wl.activeWebXRComponent=null)}}setDefaultMovementEnabled(s){let t=this.gameObject.getComponent(Li);return!t&&s&&(t=this.gameObject.addComponent(Li),this._createdComponentsInSession.push(t)),t&&(t.enabled=s),t}setDefaultControllerRenderingEnabled(s){let t=this.gameObject.getComponent(ln);return!t&&s&&(t=this.gameObject.addComponent(ln),this._createdComponentsInSession.push(t),t.createControllerModel=this.showControllerModels,t.createHandModel==this.showHandModels),t&&(t.enabled=s),t}async createLocalAvatar(s){this._playerSync&&s.running&&typeof this.defaultAvatar!="boolean"&&(this._playerSync.asset=this.defaultAvatar,await this._playerSync.getInstance())}getButtonsContainer(){return this.getButtonsFactory()}getButtonsFactory(){return this._buttonFactory||(this._buttonFactory=Yr.getOrCreate()),this._buttonFactory}handleCreatingHTML(){if(this.createARButton||this.createVRButton||this.useQuicklookExport){if((Y.isiOS()&&Y.isSafari()||tE)&&this.useQuicklookExport){const s=P.findObjectOfType(Ge);if(!s||s&&s.allowCreateQuicklookButton){const t=this.getButtonsFactory().createQuicklookButton();this.addButton(t,50)}}if(this.createARButton){const s=this.getButtonsFactory().createARButton();this.addButton(s,50)}if(this.createVRButton){const s=this.getButtonsFactory().createVRButton();this.addButton(s,50)}}if(this.createSendToQuestButton&&!Y.isQuest()&&Z.isVRSupported().then(s=>{if(!s){const t=this.getButtonsFactory().createSendToQuestButton();this.addButton(t,50)}}),this.createQRCode){const s=Gd(an);if(s&&s.createQRCodeButton===!1)F()&&console.warn("WebXR: QRCode button is disabled in the Needle Menu component");else if(!Y.isMobileDevice()){const t=Mn.getOrCreate().createQRCode();this.addButton(t,50)}}}addButton(s,t){this._buttons.push(s),s.setAttribute("priority",t.toString()),this.context.menu.appendChild(s)}removeButtons(){for(const s of this._buttons)s.remove();this._buttons.length=0}},a(j0,"activeWebXRComponent",null),j0);let Je=wl;xt([m()],Je.prototype,"createVRButton",2),xt([m()],Je.prototype,"createARButton",2),xt([m()],Je.prototype,"createSendToQuestButton",2),xt([m()],Je.prototype,"createQRCode",2),xt([m()],Je.prototype,"useDefaultControls",2),xt([m()],Je.prototype,"showControllerModels",2),xt([m()],Je.prototype,"showHandModels",2),xt([m()],Je.prototype,"usePlacementReticle",2),xt([m(le)],Je.prototype,"customARPlacementReticle",2),xt([m()],Je.prototype,"usePlacementAdjustment",2),xt([m()],Je.prototype,"arScale",2),xt([m()],Je.prototype,"useXRAnchor",2),xt([m()],Je.prototype,"autoPlace",2),xt([m()],Je.prototype,"autoCenter",2),xt([m()],Je.prototype,"useQuicklookExport",2),xt([m()],Je.prototype,"useDepthSensing",2),xt([m()],Je.prototype,"useSpatialGrab",2),xt([m(le)],Je.prototype,"defaultAvatar",2);const vh=O("debugusdz");function iE(s,t){var i;const n=[],o=P.getComponentsInChildren(s,Pt),r=P.getComponentsInChildren(s,Ut),l=new Array,c=new Array;if(t.injectImplicitBehaviours)for(const h of o){if(!h||!h.runtimeAnimatorController||!h.enabled)continue;const d=h.runtimeAnimatorController.activeState;if(!d||!d.motion||!d.motion.clip||((i=d.motion.clip.tracks)==null?void 0:i.length)<1||l.includes(h))continue;const u=new Gr;u.animator=h,u.stateName=d.name,u.trigger="start",u.name="PlayAnimationOnClick_implicitAtStart_"+u.stateName;const p=new j;P.addComponent(p,u),c.push(p),l.push(h),s.add(p)}else for(const h of o){if(!h||!h.runtimeAnimatorController||!h.enabled)continue;vh&&console.log(h);const d=[];for(const u of h.runtimeAnimatorController.enumerateActions()){vh&&console.log(u);const p=u.getClip();d.includes(p)||d.push(p)}n.push({root:h.gameObject,clips:d})}if(t.injectImplicitBehaviours)for(const h of r){if(!h||!h.clip||!h.enabled||!h.playAutomatically||l.includes(h))continue;const d=new Gr;d.animation=h,d.stateName=h.clip.name,d.trigger="start",d.name="PlayAnimationOnClick_implicitAtStart_"+d.stateName;const u=new j;P.addComponent(u,d),c.push(u),l.push(h),s.add(u)}else for(const h of r){vh&&console.log(h);const d=[];for(const u of h.animations)d.includes(u)||d.push(u);n.push({root:h.gameObject,clips:d})}vh&&n?.length>0&&console.log("USDZ Animation Clips without behaviours",n);for(const h of n)for(const d of h.clips)t.registerAnimation(h.root,d);return c}function sE(s,t){const i=P.getComponentsInChildren(s,We),n=P.getComponentsInChildren(s,jo),o=new Array,r=new Array;vh&&console.log({audioSources:i,playAudioOnClicks:n});for(const l of n){if(!l.target)continue;const c=i.indexOf(l.target);c>-1&&i.splice(c,1)}for(const l of i){if(!l||!l.clip||l.volume<=0||o.includes(l))continue;const c=new jo;c.target=l,c.name="PlayAudioOnClick_implicitAtStart_",c.trigger="start";const h=new j;P.addComponent(h,c),console.log("implicit PlayAudioOnStart",h,c),r.push(h),o.push(l),s.add(h)}return r}function nE(s){return new bt("DisableAtStart",_t.sceneStartTrigger(),ue.fadeAction(s,0,!1))}function e1(s,t){const i=s.domElement.shadowRoot.querySelector("link[rel='ar']");if(i)return i;const n=document.createElement("div");n.classList.add("menu"),n.classList.add("quicklook-menu"),n.style.display="none",n.style.visibility="hidden";const o=document.createElement("button");o.id="open-in-ar",t?(o.innerText="View in AR",o.title="View this scene in AR. The scene will be exported to USDZ and opened with Apple's QuickLook."):(o.innerText="View in AR",o.title="Download this scene for AR. Open the downloaded USDZ file to view it in AR using Apple's QuickLook."),n.appendChild(o);const r=document.createElement("a");r.id="needle-usdz-link",r.style.display="none",r.rel="ar",r.href="",r.target="_blank",n.appendChild(r);const l=document.createElement("img");return l.id="button",r.appendChild(l),s.domElement.shadowRoot.appendChild(n),r}var oE=Object.defineProperty,rE=Object.getOwnPropertyDescriptor,Et=(s,t,i,n)=>{for(var o=n>1?void 0:n?rE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&oE(t,i,o),o};const Di=O("debugusdz"),aE=O("debugusdzpruning");class Ho{constructor(){a(this,"callToAction"),a(this,"checkoutTitle"),a(this,"checkoutSubtitle"),a(this,"callToActionURL")}}Et([m()],Ho.prototype,"callToAction",2),Et([m()],Ho.prototype,"checkoutTitle",2),Et([m()],Ho.prototype,"checkoutSubtitle",2),Et([m()],Ho.prototype,"callToActionURL",2);var Sp;const L0=(Sp=class extends A{constructor(){super(...arguments),a(this,"objectToExport"),a(this,"autoExportAnimations",!0),a(this,"autoExportAudioSources",!0),a(this,"exportFileName"),a(this,"customUsdzFile"),a(this,"customBranding"),a(this,"anchoringType","plane"),a(this,"maxTextureSize",2048),a(this,"planeAnchoringAlignment","horizontal"),a(this,"interactive",!0),a(this,"physics",!0),a(this,"allowCreateQuicklookButton",!0),a(this,"quickLookCompatible",!0),a(this,"extensions",[]),a(this,"link"),a(this,"button"),a(this,"onClickedOpenInARElement",s=>{s.preventDefault(),this.exportAndOpen()}),a(this,"_currentExportTasks",new Map),a(this,"_previousTimeScale",1),a(this,"lastCallback"),a(this,"_rootSessionRootWasAppliedTo",null),a(this,"_rootPositionBeforeExport",new x),a(this,"_rootRotationBeforeExport",new V),a(this,"_rootScaleBeforeExport",new x)}start(){var s,t,i;Di&&(console.log("USDZExporter",this),console.log("Debug USDZ Mode. Press 'T' to export"),window.addEventListener("keydown",n=>{switch(n.key){case"t":this.exportAndOpen();break}})),this.objectToExport||(this.objectToExport=this.gameObject),!((t=(s=this.objectToExport)==null?void 0:s.children)!=null&&t.length)&&!((i=this.objectToExport)!=null&&i.isMesh)&&(this.objectToExport=this.context.scene)}onEnable(){var s;const t=Y.supportsQuickLookAR(),i=Y.isiOS()||Y.isiPad();!this.button&&(Di||t||i)&&(this.allowCreateQuicklookButton&&(this.button=this.createQuicklookButton()),this.lastCallback=this.quicklookCallback.bind(this),this.link=e1(this.context,t),this.link.addEventListener("message",this.lastCallback)),Di&&Le("USDZ Exporter enabled: "+this.name),(s=document.getElementById("open-in-ar"))==null||s.addEventListener("click",this.onClickedOpenInARElement),hc.registerExporter(this)}onDisable(){var s,t,i;(s=this.button)==null||s.remove(),(t=this.link)==null||t.removeEventListener("message",this.lastCallback),Di&&Le("USDZ Exporter disabled: "+this.name),(i=document.getElementById("open-in-ar"))==null||i.removeEventListener("click",this.onClickedOpenInARElement),hc.unregisterExporter(this)}async exportAsync(){return this.exportAndOpen()}async exportAndOpen(){var s;let t=this.exportFileName??((s=this.objectToExport)==null?void 0:s.name)??this.name;if(t+="-"+fx(),bo()||(t!==""&&(t+="-"),t+="MadeWithNeedle"),this.link||(this.link=e1(this.context,Y.supportsQuickLookAR())),this.customUsdzFile)return Di&&console.log("Exporting custom usdz",this.customUsdzFile),this.openInQuickLook(this.customUsdzFile,t),null;if(!this.objectToExport)return console.warn("No object to export",this),null;const i=await this.export(this.objectToExport);return i?(Di&&console.log("USDZ generation done. Downloading as "+t),this.openInQuickLook(i,t),i):(console.error("USDZ generation failed. Please report a bug",this),null)}async export(s){if(!s)return console.warn("No object to export"),null;const t=this._currentExportTasks.get(s);if(t)return t;const i=this.internalExport(s);return i instanceof Promise?(this._currentExportTasks.set(s,i),i.then(n=>(this._currentExportTasks.delete(s),n)).catch(n=>(this._currentExportTasks.delete(s),console.error("Error during USDZ export \u2013 please report a bug!",n),null))):i}async internalExport(s){ce.start("export-usdz",{onProgress:C=>{this.dispatchEvent(new CustomEvent("export-progress",{detail:{progress:C}}))}}),ce.report("export-usdz",{message:"Starting export",totalSteps:40,currentStep:0}),ce.report("export-usdz",{message:"Load progressive textures",autoStep:5}),ce.start("export-usdz-textures","export-usdz");const t=P.getComponentsInChildren(s,pi);for(const C of t)C&&C.enabled&&C.updateSprite(!0);const i=P.getComponentsInChildren(s,Ze),n=new Array;let o=0;for(const C of i){for(const R of C.sharedMeshes)if(R){const M=et.assignMeshLOD(R,0);M instanceof Promise&&n.push(new Promise((E,D)=>{M.then(()=>{o++,ce.report("export-usdz-textures",{message:"Loaded progressive mesh",currentStep:o,totalSteps:n.length}),E()}).catch(L=>D(L))}))}for(const R of C.sharedMaterials)if(R){const M=et.assignTextureLOD(R,0);M instanceof Promise&&n.push(new Promise((E,D)=>{M.then(()=>{o++,ce.report("export-usdz-textures",{message:"Loaded progressive texture",currentStep:o,totalSteps:n.length}),E()}).catch(L=>D(L))}))}}Di&&Le("Progressive Loading: "+n.length),await Promise.all(n),Di&&Le("Progressive Loading: done"),ce.end("export-usdz-textures");const r=Kt.Global.Mask;Kt.Global.Set(Ks.AR);const l=new wx,c=new nh(this.quickLookCompatible);let h;const d=[];this.interactive&&(d.push(new hp),d.push(new lr),globalThis.false&&P.getComponentsInChildren(s,ye).length>0&&(this.physics?(h=new pp,d.push(h)):F()&&console.warn("USDZExporter: Physics export is disabled, but there are active Rigidbody components in the scene. They will not be exported.")),d.push(new uh),d.push(new yp));const u=[c,...d,...this.extensions],p={self:this,exporter:l,extensions:u,object:s};ce.report("export-usdz","Invoking before-export"),this.dispatchEvent(new CustomEvent("before-export",{detail:p})),this.applyWebARSessionRoot(),this._previousTimeScale=this.context.time.timeScale,this.context.time.timeScale=0,ce.report("export-usdz","auto export animations and audio sources");const g=new Array;this.autoExportAnimations&&g.push(...iE(s,c)),this.extensions.find(C=>C.extensionName==="Audio")&&this.autoExportAudioSources&&g.push(...sE(s)),l.debug=Di,l.pruneUnusedNodes=!aE;const y=Vr.instance.objs.map(C=>C.batchedMesh);l.keepObject=C=>{let R=!0;const M=P.getComponent(C,Ze);return M&&!M.enabled&&(R=!1),R&&y.includes(C)&&(R=!1),R&&P.getComponentInParent(C,Os)&&(R=!1),R&&P.getComponentInParent(C,Vs)&&(R=!1),Di&&!R&&console.log("USDZExporter: Discarding object",C),R},l.beforeWritingDocument=()=>{if(F()&&c&&h){const C=c.animatedRoots;for(const R of C){const M=P.getComponentsInChildren(R,ye).filter(D=>D.enabled),E=P.getComponents(R,hi).filter(D=>D.enabled&&!D.isTrigger);(M.length>0||E.length>0)&&console.error("An animated object has physics components in its child hierarchy. This can lead to undefined behaviour due to a bug in Apple's QuickLook (FB15925487). Remove the physics components from child objects or verify that you get the expected results.",R)}}};const f=new Array;this.objectToExport&&this.quickLookCompatible&&this.interactive&&this.objectToExport.traverse(C=>{C.visible||f.push(C)});const v=this.extensions.find(C=>C.extensionName==="Behaviour");this.interactive&&v&&f.length>0&&v.addBehavior(nE(f));let b=!0;this.quickLookCompatible&&!this.interactive&&(b=!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"),ce.report("export-usdz","Invoking exporter.parse");const w=await l.parse(this.objectToExport,{ar:{anchoring:{type:this.anchoringType},planeAnchoring:{alignment:this.planeAnchoringAlignment}},extensions:u,quickLookCompatible:this.quickLookCompatible,maxTextureSize:this.maxTextureSize,exportInvisible:b}),_=new Blob([w],{type:"model/vnd.usdz+zip"});this.revertWebARSessionRoot(),this.context.time.timeScale=this._previousTimeScale,ce.report("export-usdz","Invoking after-export"),this.dispatchEvent(new CustomEvent("after-export",{detail:p}));for(const C of g)P.destroy(C);return Kt.Global.Set(r),ce.end("export-usdz"),_}openInQuickLook(s,t){const i=s instanceof Blob?URL.createObjectURL(s):s,n=this.buildQuicklookOverlay();Di&&console.log("QuickLook Overlay",n);const o=n.callToAction?encodeURIComponent(n.callToAction):"",r=n.checkoutTitle?encodeURIComponent(n.checkoutTitle):"",l=n.checkoutSubtitle?encodeURIComponent(n.checkoutSubtitle):"";this.link.href=i+`#callToAction=${o}&checkoutTitle=${r}&checkoutSubtitle=${l}&callToActionURL=${n.callToActionURL}`,this.lastCallback||(this.lastCallback=this.quicklookCallback.bind(this),this.link.addEventListener("message",this.lastCallback)),this.link.download=t+".usdz",this.link.click()}download(s,t){L0.save(s,t)}static save(s,t){const i=document.createElement("a");i.style.display="none",document.body.appendChild(i),typeof s=="string"?i.href=s:i.href=URL.createObjectURL(s),i.download=t,i.click(),i.remove()}quicklookCallback(s){if(s?.data=="_apple_ar_quicklook_button_tapped"){Di&&_e("Quicklook closed via call to action button");var t=new CustomEvent("quicklook-button-tapped",{detail:this});if(this.dispatchEvent(t),!t.defaultPrevented){const i=new URLSearchParams(this.link.href);if(i){const n=i.get("callToActionURL");Di&&Le("Quicklook url: "+n),n&&(bo()?globalThis.open(n,"_blank"):console.warn("Quicklook closed: custom redirects require a Needle Engine Pro license: https://needle.tools/pricing",n))}}}}buildQuicklookOverlay(){var s,t,i,n,o,r;const l={};return this.customBranding&&Object.assign(l,this.customBranding),bo()||(console.log("Custom Quicklook banner text requires pro license: https://needle.tools/pricing"),l.callToAction="Close",l.checkoutTitle="\u{1F335} Made with Needle",l.checkoutSubtitle="_"),(((s=l.callToAction)==null?void 0:s.length)||((t=l.checkoutTitle)==null?void 0:t.length)||((i=l.checkoutSubtitle)==null?void 0:i.length))&&((n=l.callToAction)!=null&&n.length||(l.callToAction="\0"),(o=l.checkoutTitle)!=null&&o.length||(l.checkoutTitle="\0"),(r=l.checkoutSubtitle)!=null&&r.length||(l.checkoutSubtitle="\0")),this.dispatchEvent(new CustomEvent("quicklook-overlay",{detail:l})),l}getARScaleAndTarget(){if(!this.objectToExport)return{scale:1,_invertForward:!1,target:this.gameObject,sessionRoot:null};const s=P.findObjectOfType(Je);let t=P.getComponentInParent(this.objectToExport,Vn);t||(t=P.getComponentInChildren(this.objectToExport,Vn));let i=1,n=!1;const o=this.objectToExport;return s?i=s.arScale:t&&(i=t.arScale,n=t.invertForward),{scale:1/i,_invertForward:n,target:o,sessionRoot:t?.gameObject??null}}applyWebARSessionRoot(){if(!this.objectToExport)return;const{scale:s,_invertForward:t,target:i,sessionRoot:n}=this.getARScaleAndTarget(),o=n?.matrixWorld.clone().invert();this._rootSessionRootWasAppliedTo=i,this._rootPositionBeforeExport.copy(i.position),this._rootRotationBeforeExport.copy(i.quaternion),this._rootScaleBeforeExport.copy(i.scale),i.scale.multiplyScalar(s),t&&i.quaternion.multiply(L0.invertForwardQuaternion),i.updateMatrix(),i.updateMatrixWorld(!0),n&&o&&i.matrix.premultiply(o)}revertWebARSessionRoot(){if(!this.objectToExport||!this._rootSessionRootWasAppliedTo)return;const s=this._rootSessionRootWasAppliedTo;s.position.copy(this._rootPositionBeforeExport),s.quaternion.copy(this._rootRotationBeforeExport),s.scale.copy(this._rootScaleBeforeExport),s.updateMatrix(),s.updateMatrixWorld(!0),this._rootSessionRootWasAppliedTo=null}createQuicklookButton(){const s=Yr.getOrCreate().createQuicklookButton();return s.parentNode||this.context.menu.appendChild(s),s}},a(Sp,"invertForwardMatrix",new ne().makeRotationY(Math.PI)),a(Sp,"invertForwardQuaternion",new V().setFromEuler(new Ft(0,Math.PI,0))),Sp);let Ge=L0;Et([m(j)],Ge.prototype,"objectToExport",2),Et([m()],Ge.prototype,"autoExportAnimations",2),Et([m()],Ge.prototype,"autoExportAudioSources",2),Et([m()],Ge.prototype,"exportFileName",2),Et([m(URL)],Ge.prototype,"customUsdzFile",2),Et([m(Ho)],Ge.prototype,"customBranding",2),Et([m()],Ge.prototype,"anchoringType",2),Et([m()],Ge.prototype,"maxTextureSize",2),Et([m()],Ge.prototype,"planeAnchoringAlignment",2),Et([m()],Ge.prototype,"interactive",2),Et([m()],Ge.prototype,"physics",2),Et([m()],Ge.prototype,"allowCreateQuicklookButton",2),Et([m()],Ge.prototype,"quickLookCompatible",2);var lE=Object.defineProperty,cE=Object.getOwnPropertyDescriptor,D0=(s,t,i,n)=>{for(var o=n>1?void 0:n?cE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&lE(t,i,o),o};class xl extends A{constructor(){super(...arguments),a(this,"_fog")}get fog(){return this._fog||(this._fog=new Gy(0,0,50)),this._fog}get mode(){return 1}set near(t){this.fog.near=t}get near(){return this.fog.near}set far(t){this.fog.far=t}get far(){return this.fog.far}set color(t){this.fog.color.copy(t)}get color(){return this.fog.color}onEnable(){this.scene.fog=this.fog}onDisable(){this.scene.fog===this._fog&&(this.scene.fog=null)}}D0([m()],xl.prototype,"near",1),D0([m()],xl.prototype,"far",1),D0([m(ae)],xl.prototype,"color",1);var hE=Object.defineProperty,dE=Object.getOwnPropertyDescriptor,B0=(s,t,i,n)=>{for(var o=n>1?void 0:n?dE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&hE(t,i,o),o};class Kr extends A{constructor(){super(...arguments),a(this,"objectBounds",!1),a(this,"color"),a(this,"isGizmo",!0),a(this,"_gizmoObject",null),a(this,"_boxHelper",null)}onEnable(){this.isGizmo&&!vc||(this._gizmoObject||(this.objectBounds?this._gizmoObject=new lC(this.gameObject,this.color??16776960):(this.objectBounds=!1,this._gizmoObject=wg(this.color??16776960))),this.objectBounds?(this.scene.add(this._gizmoObject),this._boxHelper=this._gizmoObject,this.startCoroutine(this.syncObjectBounds(),Ce.OnBeforeRender)):this.gameObject.add(this._gizmoObject))}onDisable(){this._gizmoObject&&this.gameObject.remove(this._gizmoObject)}*syncObjectBounds(){for(var t;this._boxHelper;)(t=this._boxHelper)==null||t.update(),yield}}B0([m()],Kr.prototype,"objectBounds",2),B0([m(ae)],Kr.prototype,"color",2),B0([m()],Kr.prototype,"isGizmo",2);var uE=Object.defineProperty,pE=Object.getOwnPropertyDescriptor,F0=(s,t,i,n)=>{for(var o=n>1?void 0:n?pE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&uE(t,i,o),o};class Sl extends A{constructor(){super(...arguments),a(this,"isGizmo",!1),a(this,"color0"),a(this,"color1"),a(this,"gridHelper"),a(this,"size"),a(this,"divisions"),a(this,"offset")}onEnable(){if(this.isGizmo&&!vc)return;const t=this.size,i=this.divisions;this.gridHelper||(this.gridHelper=new lm(t,i,this.color0??new ae(.4,.4,.4),this.color1??new ae(.6,.6,.6)),this.offset!==void 0&&(this.gridHelper.position.y+=this.offset)),this.gridHelper&&this.gameObject.add(this.gridHelper)}onDisable(){this.gridHelper&&(this.gameObject.remove(this.gridHelper),this.gridHelper=null)}}F0([m()],Sl.prototype,"isGizmo",2),F0([m(ae)],Sl.prototype,"color0",2),F0([m(ae)],Sl.prototype,"color1",2);var mE=Object.defineProperty,gE=Object.getOwnPropertyDescriptor,z0=(s,t,i,n)=>{for(var o=n>1?void 0:n?gE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&mE(t,i,o),o};class U0 extends A{constructor(){super(...arguments),a(this,"connectedBody"),a(this,"_rigidBody",null)}get rigidBody(){return this._rigidBody}onEnable(){this._rigidBody||(this._rigidBody=this.gameObject.getComponent(ye)),this.rigidBody&&this.connectedBody&&this.startCoroutine(this.create())}*create(){yield,this.rigidBody&&this.connectedBody&&this.activeAndEnabled&&this.createJoint(this.rigidBody,this.connectedBody)}}z0([m(ye)],U0.prototype,"connectedBody",2);class N0 extends U0{createJoint(t,i){var n;(n=this.context.physics.engine)==null||n.addFixedJoint(t,i)}}class bh extends U0{constructor(){super(...arguments),a(this,"anchor"),a(this,"axis")}createJoint(t,i){var n;this.axis&&this.anchor&&((n=this.context.physics.engine)==null||n.addHingeJoint(t,i,this.anchor,this.axis))}}z0([m(x)],bh.prototype,"anchor",2),z0([m(x)],bh.prototype,"axis",2);var fE=Object.defineProperty,yE=Object.getOwnPropertyDescriptor,cn=(s,t,i,n)=>{for(var o=n>1?void 0:n?yE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&fE(t,i,o),o};function W0(s){return s*Math.PI/180}const t1=300,$o=O("debuglights");class mi extends A{constructor(){super(...arguments),a(this,"type",0),a(this,"range",1),a(this,"spotAngle",1),a(this,"innerSpotAngle",1),a(this,"_color",new ae(16777215)),a(this,"_shadowNearPlane",.1),a(this,"_shadowBias",0),a(this,"_shadowNormalBias",0),a(this,"_overrideShadowBiasSettings",!1),a(this,"_shadows",1),a(this,"lightmapBakeType",4),a(this,"_intensity",-1),a(this,"_shadowDistance"),a(this,"shadowWidth"),a(this,"shadowHeight"),a(this,"_shadowResolution"),a(this,"light"),a(this,"_webXRStartedListener"),a(this,"_webXREndedListener"),a(this,"_webARRoot")}set color(t){this._color=t,this.light!==void 0&&(this.light.color=t)}get color(){return this.light?this.light.color:this._color}set shadowNearPlane(t){var i,n;if(t!==this._shadowNearPlane&&(this._shadowNearPlane=t,((n=(i=this.light)==null?void 0:i.shadow)==null?void 0:n.camera)!==void 0)){const o=this.light.shadow.camera;o.near=t}}get shadowNearPlane(){return this._shadowNearPlane}set shadowBias(t){var i,n;t!==this._shadowBias&&(this._shadowBias=t,((n=(i=this.light)==null?void 0:i.shadow)==null?void 0:n.bias)!==void 0&&(this.light.shadow.bias=t,this.light.shadow.needsUpdate=!0))}get shadowBias(){return this._shadowBias}set shadowNormalBias(t){var i,n;t!==this._shadowNormalBias&&(this._shadowNormalBias=t,((n=(i=this.light)==null?void 0:i.shadow)==null?void 0:n.normalBias)!==void 0&&(this.light.shadow.normalBias=t,this.light.shadow.needsUpdate=!0))}get shadowNormalBias(){return this._shadowNormalBias}set shadows(t){this._shadows=t,this.light&&(this.light.castShadow=t!==0,this.updateShadowSoftHard())}get shadows(){return this._shadows}set intensity(t){var i;if(this._intensity=t,this.light){let n=1;if(this.context.isInXR&&this._webARRoot){const o=(i=this._webARRoot)==null?void 0:i.arScale;typeof o=="number"&&o>0&&(n/=o)}this.light.intensity=t*n}$o&&console.log("Set light intensity to "+this._intensity,t,this)}get intensity(){return this._intensity}get shadowDistance(){const t=this.light;return t!=null&&t.shadow?t.shadow.camera.far:-1}set shadowDistance(t){this._shadowDistance=t;const i=this.light;if(i!=null&&i.shadow){const n=i.shadow.camera;n.far=t,n.updateProjectionMatrix()}}get shadowResolution(){const t=this.light;return t!=null&&t.shadow?t.shadow.mapSize.x:-1}set shadowResolution(t){if(t===this._shadowResolution)return;this._shadowResolution=t;const i=this.light;i!=null&&i.shadow&&(i.shadow.mapSize.set(t,t),i.shadow.needsUpdate=!0)}get isBaked(){return this.lightmapBakeType===2}get selfIsLight(){if(this.gameObject.isLight===!0)return!0;switch(this.gameObject.type){case"SpotLight":case"PointLight":case"DirectionalLight":return!0}return!1}getWorldPosition(t){return this.light?this.type===1?this.light.getWorldPosition(t).multiplyScalar(1):this.light.getWorldPosition(t):t}awake(){this.color=new ae(this.color??16777215),$o&&console.log(this.name,this)}onEnable(){$o&&console.log("ENABLE LIGHT",this.name),this.createLight(),!this.isBaked&&(this.light&&(this.light.visible=!0,this.light.intensity=this._intensity,$o&&console.log("Set light intensity to "+this.light.intensity,this.name),this.selfIsLight||this.light.parent!==this.gameObject&&this.gameObject.add(this.light)),this.type===1&&this.startCoroutine(this.updateMainLightRoutine(),Ce.LateUpdate))}onDisable(){$o&&console.log("DISABLE LIGHT",this.name),this.light&&(this.selfIsLight?this.light.intensity=0:this.light.visible=!1)}onEnterXR(t){this._webARRoot=P.getComponentInParent(this.gameObject,Vn)??void 0}onLeaveXR(t){}createLight(){const t=this.selfIsLight;if(t&&!this.light)switch(this.light=this.gameObject,this.light.name=this.name,this._intensity=this.light.intensity,this.type){case 1:this.setDirectionalLight(this.light);break}else if(!this.light)switch(this.type){case 1:const i=new cm(this.color,this.intensity*Math.PI);if(i.position.set(0,0,-t1*.5).applyQuaternion(this.gameObject.quaternion),this.gameObject.add(i.target),fr(i.target,0,0,0),this.light=i,this.gameObject.position.set(0,0,0),this.gameObject.rotation.set(0,0,0),$o){const l=new hC(this.light,.2,this.color);this.context.scene.add(l)}break;case 0:const n=new cC(this.color,this.intensity*Math.PI,this.range,W0(this.spotAngle/2),1-W0(this.innerSpotAngle/2)/W0(this.spotAngle/2),2);n.position.set(0,0,0),n.rotation.set(0,0,0),this.light=n;const o=n.target;n.add(o),o.position.set(0,0,this.range),o.rotation.set(0,0,0);break;case 2:const r=new Xy(this.color,this.intensity*Math.PI,this.range);this.light=r;break}if(this.light){if(this._intensity>=0?this.light.intensity=this._intensity:this._intensity=this.light.intensity,this.shadows!==0?this.light.castShadow=!0:this.light.castShadow=!1,this.light.shadow){this._shadowResolution!==void 0&&this._shadowResolution>4?(this.light.shadow.mapSize.width=this._shadowResolution,this.light.shadow.mapSize.height=this._shadowResolution):(this.light.shadow.mapSize.width=2048,this.light.shadow.mapSize.height=2048),$o&&console.log("Override shadow bias?",this._overrideShadowBiasSettings,this.shadowBias,this.shadowNormalBias),this.light.shadow.bias=this.shadowBias,this.light.shadow.normalBias=this.shadowNormalBias,this.updateShadowSoftHard();const i=this.light.shadow.camera;if(i.near=this.shadowNearPlane,this._shadowDistance!==void 0&&typeof this._shadowDistance=="number"?i.far=this._shadowDistance:i.far=t1*Math.abs(this.gameObject.scale.z),this.gameObject.scale.set(1,1,1),this.shadowWidth!==void 0)i.left=-this.shadowWidth/2,i.right=this.shadowWidth/2;else{const n=this.gameObject.scale.x;i.left*=n,i.right*=n}if(this.shadowHeight!==void 0)i.top=this.shadowHeight/2,i.bottom=-this.shadowHeight/2;else{const n=this.gameObject.scale.y;i.top*=n,i.bottom*=n}this.light.shadow.needsUpdate=!0,$o&&this.context.scene.add(new dC(i))}this.isBaked?this.light.removeFromParent():t||this.gameObject.add(this.light)}}*updateMainLightRoutine(){for(;;){this.type===1&&((!this.context.mainLight||this.intensity>this.context.mainLight.intensity)&&(this.context.mainLight=this),yield);break}}updateShadowSoftHard(){this.light&&this.light.shadow&&(this.shadows===2||(this.light.shadow.radius=1,this.light.shadow.blurSamples=1))}setDirectionalLight(t){t.add(t.target),t.target.position.set(0,0,-1)}}a(mi,"allowChangingRendererShadowMapType",!0),cn([m()],mi.prototype,"type",2),cn([m(ae)],mi.prototype,"color",1),cn([m()],mi.prototype,"shadowNearPlane",1),cn([m()],mi.prototype,"shadowBias",1),cn([m()],mi.prototype,"shadowNormalBias",1),cn([m()],mi.prototype,"shadows",1),cn([m()],mi.prototype,"lightmapBakeType",2),cn([m()],mi.prototype,"intensity",1),cn([m()],mi.prototype,"shadowDistance",1),cn([m()],mi.prototype,"shadowResolution",1),new x(0,0,0);var vE=Object.defineProperty,bE=Object.getOwnPropertyDescriptor,_h=(s,t,i,n)=>{for(var o=n>1?void 0:n?bE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&vE(t,i,o),o};const V0=O("debuglods"),_E=O("nolods");class Zr{constructor(){a(this,"screenRelativeTransitionHeight"),a(this,"distance"),a(this,"renderers")}}_h([m()],Zr.prototype,"screenRelativeTransitionHeight",2),_h([m()],Zr.prototype,"distance",2),_h([m(Ze)],Zr.prototype,"renderers",2);class wE{constructor(t){a(this,"model"),this.model=t}get renderers(){return this.model.renderers}}class wh extends A{constructor(){super(...arguments),a(this,"fadeMode",0),a(this,"localReferencePoint"),a(this,"lodCount",0),a(this,"size",0),a(this,"animateCrossFading",!1),a(this,"lodModels"),a(this,"_lods",[]),a(this,"_settings",[]),a(this,"_lodsHandler"),a(this,"_distanceFactor",1)}start(){if(V0&&console.log("LODGROUP",this.name,this.lodModels,this),!_E&&!this._lodsHandler&&this.gameObject&&this.lodModels&&Array.isArray(this.lodModels)){const t=[];for(const n of this.lodModels){const o=new wE(n);this._lods.push(o);for(const r of o.renderers)t.includes(r)||t.push(r)}this._lodsHandler=new Array;for(let n=0;n<t.length;n++){const o=new uC;this._lodsHandler.push(o),this.gameObject.add(o)}const i=new j;i.name="Cull "+this.name;for(let n=0;n<t.length;n++){const o=t[n],r=this._lodsHandler[n],l=o.gameObject;V0&&console.log(n,l.name);for(const c of this._lods){const h=c.model.distance;let d=null;if(c.renderers.includes(o)?d=l:d=i,d.type==="Group"){console.warn(`LODGroup ${this.name}: Group or MultiMaterial object's are not supported as LOD object: ${d.name}`);continue}V0&&console.log("LEVEL",d.name,h),r.autoUpdate=!1,this.onAddLodLevel(r,d,c.model.distance)}}}}onAfterRender(){if(!this.gameObject||!this._lodsHandler)return;const t=this.context.mainCamera;if(t)for(const i of this._lodsHandler){i.update(t);const n=i.getCurrentLevel(),o=i.levels[n];i.layers.mask=o.object.layers.mask}}onAddLodLevel(t,i,n){if(i===this.gameObject){console.warn("LODGroup component must be on parent object and not mesh directly at the moment",i.name,i);return}t.addLevel(i,n*this._distanceFactor,.01);const o={lod:t,levelIndex:t.levels.length-1,distance:n};this._settings.push(o)}distanceFactor(t){if(t!==this._distanceFactor){this._distanceFactor=t;for(const i of this._settings){const n=i.lod.levels[i.levelIndex];n.distance=i.distance*t}}}}_h([m(x)],wh.prototype,"localReferencePoint",2),_h([m(Zr)],wh.prototype,"lodModels",2);var xE=Object.defineProperty,SE=Object.getOwnPropertyDescriptor,CE=(s,t,i,n)=>{for(var o=n>1?void 0:n?SE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&xE(t,i,o),o};const Cp=O("debugnestedgltf");class Op extends A{constructor(){super(...arguments),a(this,"filePath"),a(this,"loadAssetInParent",!0),a(this,"_isLoadingOrDoneLoading",!1)}listenToProgress(t){var i;(i=this.filePath)==null||i.beginListenDownload(t)}preload(){var t;(t=this.filePath)==null||t.preload()}async start(){var t,i,n,o,r;if(this._isLoadingOrDoneLoading)return;Cp&&console.log(this,this.guid);const l=this.gameObject.parent;if(l){this._isLoadingOrDoneLoading=!0;const c=new js;c.idProvider=new Bt(this.hash(this.guid)),c.parent=this.loadAssetInParent!==!1?l:this.gameObject,this.gameObject.updateMatrix();const h=this.gameObject.matrix;Cp&&console.log("Load nested:",((t=this.filePath)==null?void 0:t.url)??this.filePath,this.gameObject.position);const d=await((n=(i=this.filePath)==null?void 0:i.instantiate)==null?void 0:n.call(this.filePath,c));Cp&&console.log("Nested loaded:",((o=this.filePath)==null?void 0:o.url)??this.filePath,d),d&&this.loadAssetInParent!==!1&&(d.matrixAutoUpdate=!1,d.matrix.identity(),d.applyMatrix4(h),d.matrixAutoUpdate=!0,d.layers.disableAll(),d.layers.set(this.layer),this.dispatchEvent(new CustomEvent("loaded",{detail:{instance:d,assetReference:this.filePath}}))),Cp&&console.log("Nested loading done:",((r=this.filePath)==null?void 0:r.url)??this.filePath,d)}}onDestroy(){var t;(t=this.filePath)==null||t.unload()}hash(t){let i=0;for(let n=0;n<t.length;n++)i=t.charCodeAt(n)+((i<<5)-i);return i}}CE([m(le)],Op.prototype,"filePath",2);var OE=Object.defineProperty,PE=Object.getOwnPropertyDescriptor,H0=(s,t,i,n)=>{for(var o=n>1?void 0:n?PE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&OE(t,i,o),o};const kE=O("debugnet"),$0=class extends A{constructor(){super(...arguments),a(this,"url",null),a(this,"urlParameterName",null),a(this,"localhost",null)}awake(){kE&&console.log(this),this.context.connection.registerProvider(this)}getWebsocketUrl(){let s=this.url?$0.GetUrl(this.url,this.localhost):null;if(this.urlParameterName){const i=O(this.urlParameterName);i&&typeof i=="string"&&(s=i)}if(!s)return null;const t=new RegExp("(((https?)|(?<socket_prefix>wss?))://)?(www.)?(?<url>.+)","gm").exec(s);return t!=null&&t.groups?t?.groups.socket_prefix?s:"wss://"+t?.groups.url:null}static GetUrl(s,t){let i=s;const n=$0.IsLocalNetwork()&&t;if(n&&(i=t),s!=null&&s.startsWith("/")){const o=n?i:window.location.origin;o!=null&&o.endsWith("/")&&s.startsWith("/")&&(s=s.substring(1)),i=o+s}return i}static IsLocalNetwork(s=window.location.hostname){return Gt(s)}};let Cl=$0;H0([m()],Cl.prototype,"url",2),H0([m()],Cl.prototype,"urlParameterName",2),H0([m()],Cl.prototype,"localhost",2);var ME=Object.defineProperty,RE=Object.getOwnPropertyDescriptor,Pp=(s,t,i,n)=>{for(var o=n>1?void 0:n?RE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&ME(t,i,o),o};class Jr extends A{constructor(){super(...arguments),a(this,"referenceSpace"),a(this,"from"),a(this,"affectPosition",!1),a(this,"affectRotation",!1),a(this,"alignLookDirection",!1),a(this,"levelLookDirection",!1),a(this,"levelPosition",!1),a(this,"positionOffset",new x(0,0,0)),a(this,"rotationOffset",new x(0,0,0)),a(this,"offset",new x(0,0,0))}update(){if(!this.from)return;var t=ee(this.from),i=Se(this.from);this.offset.copy(this.positionOffset);const n=this.offset.length();if(this.referenceSpace&&this.offset.transformDirection(this.referenceSpace.matrixWorld).multiplyScalar(n),t.add(this.offset),this.levelPosition&&this.referenceSpace){const c=new dr(this.gameObject.up,0),h=ee(this.referenceSpace);c.setFromNormalAndCoplanarPoint(this.gameObject.up,h);const d=new x(0,0,0);c.projectPoint(t,d),t.copy(d)}this.affectPosition&&lt(this.gameObject,t);const o=new Ft(this.rotationOffset.x,this.rotationOffset.y,this.rotationOffset.z),r=new V().setFromEuler(o);this.affectRotation&&qi(this.gameObject,i.multiply(r));const l=new x;this.from.getWorldDirection(l).multiplyScalar(50),this.levelLookDirection&&(l.y=0),this.alignLookDirection&&this.gameObject.lookAt(l)}}Pp([m(P)],Jr.prototype,"referenceSpace",2),Pp([m(P)],Jr.prototype,"from",2),Pp([m(x)],Jr.prototype,"positionOffset",2),Pp([m(x)],Jr.prototype,"rotationOffset",2);var TE=Object.defineProperty,EE=Object.getOwnPropertyDescriptor,k=(s,t,i,n)=>{for(var o=n>1?void 0:n?EE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&TE(t,i,o),o};const kp=O("debugparticles");var $n=(s=>(s[s.Billboard=0]="Billboard",s[s.Stretch=1]="Stretch",s[s.HorizontalBillboard=2]="HorizontalBillboard",s[s.VerticalBillboard=3]="VerticalBillboard",s[s.Mesh=4]="Mesh",s))($n||{});class qo{constructor(){a(this,"alphaKeys",[]),a(this,"colorKeys",[])}get duration(){return 1}evaluate(t,i){let n,o=0,r=null,l=0;for(let c=0;c<this.alphaKeys.length;c++){const h=this.alphaKeys[c];(h.time<t||!n)&&(n=h,o=c)}for(let c=0;c<this.colorKeys.length;c++){const h=this.colorKeys[c];(h.time<t||!r)&&(r=h,l=c)}if(r)if(l+1<this.colorKeys.length){const c=this.colorKeys[l+1],h=W.remap(t,r.time,c.time,0,1);i.r=W.lerp(r.color.r,c.color.r,h),i.g=W.lerp(r.color.g,c.color.g,h),i.b=W.lerp(r.color.b,c.color.b,h)}else i.r=r.color.r,i.g=r.color.g,i.b=r.color.b;if(n)if(o+1<this.alphaKeys.length){const c=this.alphaKeys[o+1],h=W.remap(t,n.time,c.time,0,1);i.alpha=W.lerp(n.alpha,c.alpha,h)}else i.alpha=n.alpha;return i}}k([m()],qo.prototype,"alphaKeys",2),k([m()],qo.prototype,"colorKeys",2);var xh=(s=>(s[s.Local=0]="Local",s[s.World=1]="World",s[s.Custom=2]="Custom",s))(xh||{}),Mp=(s=>(s[s.Sphere=0]="Sphere",s[s.SphereShell=1]="SphereShell",s[s.Hemisphere=2]="Hemisphere",s[s.HemisphereShell=3]="HemisphereShell",s[s.Cone=4]="Cone",s[s.Box=5]="Box",s[s.Mesh=6]="Mesh",s[s.ConeShell=7]="ConeShell",s[s.ConeVolume=8]="ConeVolume",s[s.ConeVolumeShell=9]="ConeVolumeShell",s[s.Circle=10]="Circle",s[s.CircleEdge=11]="CircleEdge",s[s.SingleSidedEdge=12]="SingleSidedEdge",s[s.MeshRenderer=13]="MeshRenderer",s[s.SkinnedMeshRenderer=14]="SkinnedMeshRenderer",s[s.BoxShell=15]="BoxShell",s[s.BoxEdge=16]="BoxEdge",s[s.Donut=17]="Donut",s[s.Rectangle=18]="Rectangle",s[s.Sprite=19]="Sprite",s[s.SpriteRenderer=20]="SpriteRenderer",s))(Mp||{});const Sh=class{constructor(){a(this,"mode","Constant"),a(this,"constant"),a(this,"constantMin"),a(this,"constantMax"),a(this,"curve"),a(this,"curveMin"),a(this,"curveMax"),a(this,"curveMultiplier")}static constant(s){const t=new Sh;return t.setConstant(s),t}static betweenTwoConstants(s,t){const i=new Sh;return i.setMinMaxConstant(s,t),i}static curve(s,t=1){const i=new Sh;return i.setCurve(s,t),i}setConstant(s){this.mode=0,this.constant=s}setMinMaxConstant(s,t){this.mode=3,this.constantMin=s,this.constantMax=t}setCurve(s,t=1){this.mode=1,this.curve=s,this.curveMultiplier=t}clone(){var s,t,i;const n=new Sh;return n.mode=this.mode,n.constant=this.constant,n.constantMin=this.constantMin,n.constantMax=this.constantMax,n.curve=(s=this.curve)==null?void 0:s.clone(),n.curveMin=(t=this.curveMin)==null?void 0:t.clone(),n.curveMax=(i=this.curveMax)==null?void 0:i.clone(),n.curveMultiplier=this.curveMultiplier,n}evaluate(s,t){const i=t===void 0?Math.random():t;switch(this.mode){case 0:case"Constant":return this.constant;case 1:case"Curve":return s=W.clamp01(s),this.curve.evaluate(s)*this.curveMultiplier;case 2:case"TwoCurves":const n=s*this.curveMin.duration,o=s*this.curveMax.duration;return W.lerp(this.curveMin.evaluate(n),this.curveMax.evaluate(o),i%1)*this.curveMultiplier;case 3:case"TwoConstants":return W.lerp(this.constantMin,this.constantMax,i%1);default:this.curveMax.evaluate(s)*this.curveMultiplier;break}return 0}getMax(){switch(this.mode){case 0:case"Constant":return this.constant;case 1:case"Curve":return this.getMaxFromCurve(this.curve)*this.curveMultiplier;case 2:case"TwoCurves":return Math.max(this.getMaxFromCurve(this.curveMin),this.getMaxFromCurve(this.curveMax))*this.curveMultiplier;case 3:case"TwoConstants":return Math.max(this.constantMin,this.constantMax);default:return 0}}getMaxFromCurve(s){if(!s)return 0;let t=Number.MIN_VALUE;for(let i=0;i<s.keys.length;i++){const n=s.keys[i];n.value>t&&(t=n.value)}return t}};let X=Sh;k([m()],X.prototype,"mode",2),k([m()],X.prototype,"constant",2),k([m()],X.prototype,"constantMin",2),k([m()],X.prototype,"constantMax",2),k([m(Lr)],X.prototype,"curve",2),k([m(Lr)],X.prototype,"curveMin",2),k([m(Lr)],X.prototype,"curveMax",2),k([m()],X.prototype,"curveMultiplier",2);var Rp;const At=(Rp=class{constructor(){a(this,"mode",0),a(this,"color"),a(this,"colorMin"),a(this,"colorMax"),a(this,"gradient"),a(this,"gradientMin"),a(this,"gradientMax")}static constant(s){const t=new At;return t.constant(s),t}static betweenTwoColors(s,t){const i=new At;return i.betweenTwoColors(s,t),i}constant(s){return this.mode=0,this.color=s,this}betweenTwoColors(s,t){return this.mode=2,this.colorMin=s,this.colorMax=t,this}evaluate(s,t){const i=t===void 0?Math.random():t;switch(this.mode){case 0:case"Color":return this.color;case 1:case"Gradient":return this.gradient.evaluate(s,At._temp),At._temp;case 2:case"TwoColors":return At._temp.lerpColors(this.colorMin,this.colorMax,i);case 3:case"TwoGradients":return this.gradientMin.evaluate(s,At._temp),this.gradientMax.evaluate(s,At._temp2),At._temp.lerp(At._temp2,i);case 4:case"RandomColor":const n=Math.random();return this.gradientMin.evaluate(s,At._temp),this.gradientMax.evaluate(s,At._temp2),At._temp.lerp(At._temp2,n)}return At._temp.set(16777215),At._temp.alpha=1,At._temp}},a(Rp,"_temp",new we(0,0,0,1)),a(Rp,"_temp2",new we(0,0,0,1)),Rp);let ii=At;k([m()],ii.prototype,"mode",2),k([m(we)],ii.prototype,"color",2),k([m(we)],ii.prototype,"colorMin",2),k([m(we)],ii.prototype,"colorMax",2),k([m(qo)],ii.prototype,"gradient",2),k([m(qo)],ii.prototype,"gradientMin",2),k([m(qo)],ii.prototype,"gradientMax",2);var q0=(s=>(s[s.Hierarchy=0]="Hierarchy",s[s.Local=1]="Local",s[s.Shape=2]="Shape",s))(q0||{});class It{constructor(){a(this,"cullingMode"),a(this,"duration"),a(this,"emitterVelocityMode"),a(this,"flipRotation"),a(this,"gravityModifier"),a(this,"gravityModifierMultiplier"),a(this,"loop"),a(this,"maxParticles"),a(this,"playOnAwake"),a(this,"prewarm"),a(this,"ringBufferLoopRange"),a(this,"ringBufferMode"),a(this,"scalingMode"),a(this,"simulationSpace"),a(this,"simulationSpeed"),a(this,"startColor"),a(this,"startDelay"),a(this,"startDelayMultiplier"),a(this,"startLifetime"),a(this,"startLifetimeMultiplier"),a(this,"startRotation"),a(this,"startRotationMultiplier"),a(this,"startRotation3D"),a(this,"startRotationX"),a(this,"startRotationXMultiplier"),a(this,"startRotationY"),a(this,"startRotationYMultiplier"),a(this,"startRotationZ"),a(this,"startRotationZMultiplier"),a(this,"startSize"),a(this,"startSize3D"),a(this,"startSizeMultiplier"),a(this,"startSizeX"),a(this,"startSizeXMultiplier"),a(this,"startSizeY"),a(this,"startSizeYMultiplier"),a(this,"startSizeZ"),a(this,"startSizeZMultiplier"),a(this,"startSpeed"),a(this,"startSpeedMultiplier"),a(this,"stopAction"),a(this,"useUnscaledTime")}}k([m(X)],It.prototype,"gravityModifier",2),k([m(ii)],It.prototype,"startColor",2),k([m(X)],It.prototype,"startDelay",2),k([m(X)],It.prototype,"startLifetime",2),k([m(X)],It.prototype,"startRotation",2),k([m(X)],It.prototype,"startRotationX",2),k([m(X)],It.prototype,"startRotationY",2),k([m(X)],It.prototype,"startRotationZ",2),k([m(X)],It.prototype,"startSize",2),k([m(X)],It.prototype,"startSizeX",2),k([m(X)],It.prototype,"startSizeY",2),k([m(X)],It.prototype,"startSizeZ",2),k([m(X)],It.prototype,"startSpeed",2);class Ch{constructor(){a(this,"cycleCount"),a(this,"maxCount"),a(this,"minCount"),a(this,"probability"),a(this,"repeatInterval"),a(this,"time"),a(this,"count"),a(this,"_performed",0)}reset(){this._performed=0}run(t){if(t<=this.time)return 0;let i=0;if(this.cycleCount===0||this._performed<this.cycleCount){const n=this.time+this.repeatInterval*this._performed;if(t>=n&&(this._performed+=1,Math.random()<this.probability))switch(this.count.mode){case 0:i=this.count.constant;break;case 3:i=W.lerp(this.count.constantMin,this.count.constantMax,Math.random());break;case 1:i=this.count.curve.evaluate(Math.random());break;case 2:const o=Math.random();i=W.lerp(this.count.curveMin.evaluate(o),this.count.curveMax.evaluate(o),Math.random());break}}return i}}class hn{constructor(){a(this,"enabled"),a(this,"bursts"),a(this,"rateOverTime"),a(this,"rateOverTimeMultiplier"),a(this,"rateOverDistance"),a(this,"rateOverDistanceMultiplier"),a(this,"system")}get burstCount(){var t;return((t=this.bursts)==null?void 0:t.length)??0}reset(){var t;(t=this.bursts)==null||t.forEach(i=>i.reset())}getBurst(){let t=0;if(this.burstCount>0)for(let i=0;i<this.burstCount;i++){const n=this.bursts[i];this.system.main.loop&&n.time>=this.system.time&&n.reset(),t+=Math.round(n.run(this.system.time))}return t}}k([m()],hn.prototype,"enabled",2),k([m()],hn.prototype,"bursts",2),k([m(X)],hn.prototype,"rateOverTime",2),k([m()],hn.prototype,"rateOverTimeMultiplier",2),k([m(X)],hn.prototype,"rateOverDistance",2),k([m()],hn.prototype,"rateOverDistanceMultiplier",2);class Oh{constructor(){a(this,"enabled"),a(this,"color")}}k([m(ii)],Oh.prototype,"color",2);class Go{constructor(){a(this,"enabled"),a(this,"separateAxes"),a(this,"size"),a(this,"sizeMultiplier"),a(this,"x"),a(this,"xMultiplier"),a(this,"y"),a(this,"yMultiplier"),a(this,"z"),a(this,"zMultiplier"),a(this,"_time",0),a(this,"_temp",new x)}evaluate(t,i,n){if(i||(i=this._temp),!this.enabled)return i.x=i.y=i.z=1,i;if(this.separateAxes)i.x=this.x.evaluate(t,n)*this.xMultiplier,i.y=this.y.evaluate(t,n)*this.yMultiplier,i.z=this.z.evaluate(t,n)*this.zMultiplier;else{const o=this.size.evaluate(t,n)*this.sizeMultiplier;i.x=o}return i}}k([m(X)],Go.prototype,"size",2),k([m(X)],Go.prototype,"x",2),k([m(X)],Go.prototype,"y",2),k([m(X)],Go.prototype,"z",2);var Tp;const Ph=(Tp=class{constructor(){a(this,"shapeType",5),a(this,"enabled",!0),a(this,"alignToDirection",!1),a(this,"angle",0),a(this,"arc",360),a(this,"arcSpread"),a(this,"arcSpeedMultiplier"),a(this,"arcMode"),a(this,"boxThickness"),a(this,"position"),a(this,"rotation"),a(this,"_rotation",new Ft),a(this,"scale"),a(this,"radius"),a(this,"radiusThickness"),a(this,"sphericalDirectionAmount"),a(this,"randomDirectionAmount"),a(this,"randomPositionAmount"),a(this,"meshShapeType"),a(this,"meshRenderer"),a(this,"_meshObj"),a(this,"_meshGeometry"),a(this,"system"),a(this,"_space"),a(this,"_worldSpaceMatrix",new ne),a(this,"_worldSpaceMatrixInverse",new ne),a(this,"_vector",new x(0,0,0)),a(this,"_temp",new x(0,0,0)),a(this,"_triangle",new pC),a(this,"_dir",new x),a(this,"_loopTime",0),a(this,"_loopDirection",1),kp&&console.log(this)}get type(){return Mp[this.shapeType]}initialize(s){this.onInitialize(s),s.position.x=this._vector.x,s.position.y=this._vector.y,s.position.z=this._vector.z}toJSON(){return this}clone(){return new Ph}setMesh(s){this.meshRenderer=s,s?(this._meshObj=s.sharedMeshes[Math.floor(Math.random()*s.sharedMeshes.length)],this._meshGeometry=this._meshObj.geometry):(this._meshObj=void 0,this._meshGeometry=void 0)}update(s,t){}onUpdate(s,t,i,n){this.system=s,this._space=i,i===1&&(this._worldSpaceMatrix.copy(n.matrixWorld),this._worldSpaceMatrix.elements[0]=1,this._worldSpaceMatrix.elements[5]=1,this._worldSpaceMatrix.elements[10]=1,this._worldSpaceMatrixInverse.copy(this._worldSpaceMatrix).invert())}applyRotation(s){const t=this.rotation.x!==0||this.rotation.y!==0||this.rotation.z!==0;return t&&(this._rotation.x=W.toRadians(this.rotation.x),this._rotation.y=W.toRadians(this.rotation.y),this._rotation.z=W.toRadians(this.rotation.z),this._rotation.order="ZYX",s.applyEuler(this._rotation)),t}onInitialize(s){this._vector.set(0,0,0),s.mesh=void 0,s.mesh_geometry=void 0;const t=this._temp.copy(this.position),i=this._space===1;i&&t.applyQuaternion(this.system.worldQuaternion);let n=this.radius;if(i&&(n*=this.system.worldScale.x),this.enabled){switch(this.shapeType){case 5:kp&&q.DrawWireBox(this.position,this.scale,14540253,1),this._vector.x=Math.random()*this.scale.x-this.scale.x/2,this._vector.y=Math.random()*this.scale.y-this.scale.y/2,this._vector.z=Math.random()*this.scale.z-this.scale.z/2,this._vector.add(t);break;case 4:this.randomConePoint(this.position,this.angle,n,this.radiusThickness,this.arc,this.arcMode,this._vector);break;case 0:this.randomSpherePoint(this.position,n,this.radiusThickness,this.arc,this._vector);break;case 10:this.randomCirclePoint(this.position,n,this.radiusThickness,this.arc,this._vector);break;case 13:const o=this.meshRenderer;o?.destroyed==!1&&this.setMesh(o);const r=s.mesh=this._meshObj,l=s.mesh_geometry=this._meshGeometry;if(r&&l)switch(this.meshShapeType){case 0:{const c=l.getAttribute("position"),h=Math.floor(Math.random()*c.count);this._vector.fromBufferAttribute(c,h),this._vector.applyMatrix4(r.matrixWorld),s.mesh_normal=h}break;case 1:break;case 2:{const c=l.index;if(c){let h=Math.random(),d=Math.random();h+d>1&&(h=1-h,d=1-d);const u=Math.floor(Math.random()*(c.count/3));let p=u*3,g=u*3+1,y=u*3+2;p=c.getX(p),g=c.getX(g),y=c.getX(y);const f=l.getAttribute("position");this._triangle.a.fromBufferAttribute(f,p),this._triangle.b.fromBufferAttribute(f,g),this._triangle.c.fromBufferAttribute(f,y),this._vector.set(0,0,0).addScaledVector(this._triangle.a,h).addScaledVector(this._triangle.b,d).addScaledVector(this._triangle.c,1-(h+d)),this._vector.applyMatrix4(r.matrixWorld),s.mesh_normal=u}}break}break;default:this._vector.set(0,0,0),F()&&!globalThis.__particlesystem_shapetype_unsupported&&(console.warn("ParticleSystem ShapeType is not supported:",Mp[this.shapeType]),globalThis.__particlesystem_shapetype_unsupported=!0);break}this.randomizePosition(this._vector,this.randomPositionAmount)}this.applyRotation(this._vector),i&&(this._vector.applyQuaternion(this.system.worldQuaternion),this._vector.add(this.system.worldPos)),kp&&q.DrawSphere(this._vector,.03,16711680,.5,!0)}getDirection(s,t){var i;if(!this.enabled)return this._dir.set(0,0,1),this._dir;switch(this.shapeType){case 5:this._dir.set(0,0,1);break;case 4:this._dir.set(0,0,1);break;case 10:case 0:const n=t.x,o=t.y,r=t.z;this._dir.set(n,o,r),(i=this.system)!=null&&i.worldspace?this._dir.sub(this.system.worldPos):this._dir.sub(this.position);break;case 13:const l=s.mesh,c=s.mesh_geometry;if(l&&c)switch(this.meshShapeType){case 0:{const h=c.getAttribute("normal"),d=s.mesh_normal;this._dir.fromBufferAttribute(h,d)}break;case 1:break;case 2:{const h=c.index;if(h){const d=s.mesh_normal,u=h.getX(d*3),p=h.getX(d*3+1),g=h.getX(d*3+2),y=c.getAttribute("position"),f=$(),v=$(),b=$();f.fromBufferAttribute(y,u),v.fromBufferAttribute(y,p),b.fromBufferAttribute(y,g),f.sub(v),b.sub(v),f.cross(b),this._dir.copy(f).multiplyScalar(-1);const w=Se(l);this._dir.applyQuaternion(w)}}break}break;default:this._dir.set(0,0,1);break}return this._space===1&&this._dir.applyQuaternion(this.system.worldQuaternion),this.applyRotation(this._dir),this._dir.normalize(),this.spherizeDirection(this._dir,this.sphericalDirectionAmount),this.randomizeDirection(this._dir,this.randomDirectionAmount),kp&&(q.DrawSphere(t,.01,8925952,.5,!0),q.DrawDirection(t,this._dir,8925952,.5,!0)),this._dir}randomizePosition(s,t){if(t<=0)return;const i=Ph._tempVec;i.set(Math.random()*2-1,Math.random()*2-1,Math.random()*2-1),i.x*=t*this.scale.x,i.y*=t*this.scale.y,i.z*=t*this.scale.z,s.add(i)}randomizeDirection(s,t){if(t===0)return;const i=Ph._randomQuat,n=Ph._tempVec;n.set(Math.random()-.5,Math.random()-.5,Math.random()-.5).normalize(),i.setFromAxisAngle(n,t*Math.random()*Math.PI),s.applyQuaternion(i)}spherizeDirection(s,t){if(t===0)return;const i=Math.random()*Math.PI*2,n=Math.acos(1-Math.random()*2),o=Math.sin(n)*Math.cos(i),r=Math.sin(n)*Math.sin(i),l=Math.cos(n),c=new x(o,r,l);s.lerp(c,t)}randomSpherePoint(s,t,i,n,o){const r=Math.random(),l=Math.random(),c=2*Math.PI*r*(n/360),h=Math.acos(2*l-1),d=W.lerp(1,1-Math.pow(1-Math.random(),Math.PI),i)*t,u=s.x+this.scale.x*(-d*Math.sin(h)*Math.cos(c)),p=s.y+this.scale.y*(d*Math.sin(h)*Math.sin(c)),g=s.z+this.scale.z*(d*Math.cos(h));o.x=u,o.y=p,o.z=g}randomCirclePoint(s,t,i,n,o){const r=Math.random(),l=2*Math.PI*r*(n/360),c=W.lerp(1,1-Math.pow(1-Math.random(),Math.PI),i)*t,h=s.x+this.scale.x*c*Math.cos(l),d=s.y+this.scale.y*c*Math.sin(l),u=s.z;o.x=h,o.y=d,o.z=u}randomConePoint(s,t,i,n,o,r,l){let c=0,h=0;switch(r){case 0:c=Math.random(),h=Math.random();break;case 2:this._loopTime>1&&(this._loopDirection=-1),this._loopTime<0&&(this._loopDirection=1);case 1:c=.5,h=Math.random(),this._loopTime+=this.system.deltaTime*this._loopDirection;break}let d=2*Math.PI*c*(o/360);switch(r){case 2:case 1:d+=Math.PI+.5,d+=this._loopTime*Math.PI*2,d%=W.toRadians(o);break}const u=Math.acos(2*h-1),p=W.lerp(1,1-Math.pow(1-Math.random(),Math.PI),n)*i,g=s.x+-p*Math.sin(u)*Math.cos(d),y=s.y+p*Math.sin(u)*Math.sin(d),f=s.z;l.x=g*this.scale.x,l.y=y*this.scale.y,l.z=f*this.scale.z}},a(Tp,"_randomQuat",new V),a(Tp,"_tempVec",new x),Tp);let Xe=Ph;k([m()],Xe.prototype,"shapeType",2),k([m()],Xe.prototype,"enabled",2),k([m()],Xe.prototype,"alignToDirection",2),k([m()],Xe.prototype,"angle",2),k([m()],Xe.prototype,"arc",2),k([m()],Xe.prototype,"arcSpread",2),k([m()],Xe.prototype,"arcSpeedMultiplier",2),k([m()],Xe.prototype,"arcMode",2),k([m(x)],Xe.prototype,"boxThickness",2),k([m(x)],Xe.prototype,"position",2),k([m(x)],Xe.prototype,"rotation",2),k([m(x)],Xe.prototype,"scale",2),k([m()],Xe.prototype,"radius",2),k([m()],Xe.prototype,"radiusThickness",2),k([m()],Xe.prototype,"sphericalDirectionAmount",2),k([m()],Xe.prototype,"randomDirectionAmount",2),k([m()],Xe.prototype,"randomPositionAmount",2),k([m()],Xe.prototype,"meshShapeType",2),k([m(th)],Xe.prototype,"meshRenderer",2);class xe{constructor(){a(this,"damping"),a(this,"enabled"),a(this,"frequency"),a(this,"octaveCount"),a(this,"octaveMultiplier"),a(this,"octaveScale"),a(this,"positionAmount"),a(this,"quality"),a(this,"remap"),a(this,"remapEnabled"),a(this,"remapMultiplier"),a(this,"remapX"),a(this,"remapXMultiplier"),a(this,"remapY"),a(this,"remapYMultiplier"),a(this,"remapZ"),a(this,"remapZMultiplier"),a(this,"scrollSpeedMultiplier"),a(this,"separateAxes"),a(this,"strengthMultiplier"),a(this,"strengthX"),a(this,"strengthXMultiplier"),a(this,"strengthY"),a(this,"strengthYMultiplier"),a(this,"strengthZ"),a(this,"strengthZMultiplier"),a(this,"_noise"),a(this,"_time",0),a(this,"_temp",new x)}update(t){this._time+=t.time.deltaTime*this.scrollSpeedMultiplier}apply(t,i,n,o,r,l){if(!this.enabled)return;this._noise||(this._noise=ZC(()=>0));const c=this._temp.set(i.x,i.y,i.z).multiplyScalar(this.frequency),h=this._noise(c.x,c.y,c.z,this._time),d=this._noise(c.x,c.y,c.z,this._time+1e3*this.frequency),u=this._noise(c.x,c.y,c.z,this._time+2e3*this.frequency);this._temp.set(h,d,u).normalize();const p=r/l;let g=this.positionAmount.evaluate(p);this.separateAxes?(this._temp.x*=g*this.strengthXMultiplier,this._temp.y*=g*this.strengthYMultiplier,this._temp.z*=g*this.strengthZMultiplier):(this.strengthX&&(g*=this.strengthX.evaluate(p)*1.5),this._temp.multiplyScalar(g)),n.x+=this._temp.x,n.y+=this._temp.y,n.z+=this._temp.z}}k([m()],xe.prototype,"damping",2),k([m()],xe.prototype,"enabled",2),k([m()],xe.prototype,"frequency",2),k([m()],xe.prototype,"octaveCount",2),k([m()],xe.prototype,"octaveMultiplier",2),k([m()],xe.prototype,"octaveScale",2),k([m(X)],xe.prototype,"positionAmount",2),k([m()],xe.prototype,"quality",2),k([m(X)],xe.prototype,"remap",2),k([m()],xe.prototype,"remapEnabled",2),k([m()],xe.prototype,"remapMultiplier",2),k([m(X)],xe.prototype,"remapX",2),k([m()],xe.prototype,"remapXMultiplier",2),k([m(X)],xe.prototype,"remapY",2),k([m()],xe.prototype,"remapYMultiplier",2),k([m(X)],xe.prototype,"remapZ",2),k([m()],xe.prototype,"remapZMultiplier",2),k([m()],xe.prototype,"scrollSpeedMultiplier",2),k([m()],xe.prototype,"separateAxes",2),k([m()],xe.prototype,"strengthMultiplier",2),k([m(X)],xe.prototype,"strengthX",2),k([m()],xe.prototype,"strengthXMultiplier",2),k([m(X)],xe.prototype,"strengthY",2),k([m()],xe.prototype,"strengthYMultiplier",2),k([m(X)],xe.prototype,"strengthZ",2),k([m()],xe.prototype,"strengthZMultiplier",2);class ze{constructor(){a(this,"enabled"),a(this,"attachRibbonToTransform",!1),a(this,"colorOverLifetime"),a(this,"colorOverTrail"),a(this,"dieWithParticles",!0),a(this,"inheritParticleColor",!0),a(this,"lifetime"),a(this,"lifetimeMultiplier"),a(this,"minVertexDistance",.2),a(this,"mode",0),a(this,"ratio",1),a(this,"ribbonCount",1),a(this,"shadowBias",0),a(this,"sizeAffectsLifetime",!1),a(this,"sizeAffectsWidth",!1),a(this,"splitSubEmitterRibbons",!1),a(this,"textureMode",0),a(this,"widthOverTrail"),a(this,"widthOverTrailMultiplier"),a(this,"worldSpace",!1)}getWidth(t,i,n,o){const r=this.widthOverTrail.evaluate(n,o);return t*=r,t}getColor(t,i,n){const o=this.colorOverTrail.evaluate(n),r=this.colorOverLifetime.evaluate(i);t.x*=o.r*r.r,t.y*=o.g*r.g,t.z*=o.b*r.b,"alpha"in o&&"alpha"in r&&(t.w*=o.alpha*r.alpha)}}k([m()],ze.prototype,"enabled",2),k([m()],ze.prototype,"attachRibbonToTransform",2),k([m(ii)],ze.prototype,"colorOverLifetime",2),k([m(ii)],ze.prototype,"colorOverTrail",2),k([m()],ze.prototype,"dieWithParticles",2),k([m()],ze.prototype,"inheritParticleColor",2),k([m(X)],ze.prototype,"lifetime",2),k([m()],ze.prototype,"lifetimeMultiplier",2),k([m()],ze.prototype,"minVertexDistance",2),k([m()],ze.prototype,"mode",2),k([m()],ze.prototype,"ratio",2),k([m()],ze.prototype,"ribbonCount",2),k([m()],ze.prototype,"shadowBias",2),k([m()],ze.prototype,"sizeAffectsLifetime",2),k([m()],ze.prototype,"sizeAffectsWidth",2),k([m()],ze.prototype,"splitSubEmitterRibbons",2),k([m()],ze.prototype,"textureMode",2),k([m(X)],ze.prototype,"widthOverTrail",2),k([m()],ze.prototype,"widthOverTrailMultiplier",2),k([m()],ze.prototype,"worldSpace",2);class Qe{constructor(){a(this,"enabled"),a(this,"space",0),a(this,"orbitalX"),a(this,"orbitalY"),a(this,"orbitalZ"),a(this,"orbitalXMultiplier"),a(this,"orbitalYMultiplier"),a(this,"orbitalZMultiplier"),a(this,"orbitalOffsetX"),a(this,"orbitalOffsetY"),a(this,"orbitalOffsetZ"),a(this,"speedModifier"),a(this,"speedModifierMultiplier"),a(this,"x"),a(this,"xMultiplier"),a(this,"y"),a(this,"yMultiplier"),a(this,"z"),a(this,"zMultiplier"),a(this,"_system"),a(this,"_temp",new x),a(this,"_temp2",new x),a(this,"_temp3",new x),a(this,"_hasOrbital",!1),a(this,"_index",0),a(this,"_orbitalMatrix",new ne)}update(t){this._system=t}init(t){this._index==0&&(t.debug=!0),this._index+=1,t.orbitx=this.orbitalX.evaluate(Math.random()),t.orbity=this.orbitalY.evaluate(Math.random()),t.orbitz=this.orbitalZ.evaluate(Math.random()),this._hasOrbital=t.orbitx!=0||t.orbity!=0||t.orbitz!=0}apply(t,i,n,o,r,l,c){var h;if(!this.enabled)return;const d=l/c,u=this.speedModifier.evaluate(d)*this.speedModifierMultiplier,p=this.x.evaluate(d),g=this.y.evaluate(d),y=this.z.evaluate(d);if(this._temp.set(-p,g,y),this._system&&this._system.main.simulationSpace===1&&this._temp.applyQuaternion(this._system.worldQuaternion),this._hasOrbital&&((h=this._system)==null?void 0:h.worldPos)){const f=this._temp2.set(n.x,n.y,n.z),v=this.orbitalXMultiplier,b=this.orbitalYMultiplier,w=this.orbitalZMultiplier,_=u*Math.PI*2*10,C=Math.cos(_*v),R=Math.sin(_*v),M=Math.cos(_*b),E=Math.sin(_*b),D=Math.cos(_*w),L=Math.sin(_*w),U=f.x*(M*D)+f.y*(M*L)+f.z*-E,z=f.x*(R*E*D-C*L)+f.y*(R*E*L+C*D)+f.z*(R*M),H=f.x*(C*E*D+R*L)+f.y*(C*E*L-R*D)+f.z*(C*M),T=this._temp3.set(f.x-U,f.y-z,f.z-H);T.normalize(),T.multiplyScalar(.2/r*Math.max(this.orbitalXMultiplier,this.orbitalYMultiplier,this.orbitalZMultiplier)),o.x+=T.x,o.y+=T.y,o.z+=T.z}o.x+=this._temp.x,o.y+=this._temp.y,o.z+=this._temp.z,o.x*=u,o.y*=u,o.z*=u}}k([m()],Qe.prototype,"enabled",2),k([m()],Qe.prototype,"space",2),k([m(X)],Qe.prototype,"orbitalX",2),k([m(X)],Qe.prototype,"orbitalY",2),k([m(X)],Qe.prototype,"orbitalZ",2),k([m()],Qe.prototype,"orbitalXMultiplier",2),k([m()],Qe.prototype,"orbitalYMultiplier",2),k([m()],Qe.prototype,"orbitalZMultiplier",2),k([m()],Qe.prototype,"orbitalOffsetX",2),k([m()],Qe.prototype,"orbitalOffsetY",2),k([m()],Qe.prototype,"orbitalOffsetZ",2),k([m(X)],Qe.prototype,"speedModifier",2),k([m()],Qe.prototype,"speedModifierMultiplier",2),k([m(X)],Qe.prototype,"x",2),k([m()],Qe.prototype,"xMultiplier",2),k([m(X)],Qe.prototype,"y",2),k([m()],Qe.prototype,"yMultiplier",2),k([m(X)],Qe.prototype,"z",2),k([m()],Qe.prototype,"zMultiplier",2);class jt{constructor(){a(this,"animation"),a(this,"enabled"),a(this,"cycleCount"),a(this,"frameOverTime"),a(this,"frameOverTimeMultiplier"),a(this,"numTilesX"),a(this,"numTilesY"),a(this,"startFrame"),a(this,"startFrameMultiplier"),a(this,"rowMode"),a(this,"rowIndex"),a(this,"spriteCount"),a(this,"timeMode")}sampleOnceAtStart(){if(this.timeMode===0)switch(this.frameOverTime.mode){case 0:case 3:case 2:case 1:return!0}return!1}getStartIndex(){return this.sampleOnceAtStart()?Math.random()*(this.numTilesX*this.numTilesY):0}evaluate(t){if(!this.sampleOnceAtStart())return this.getIndex(t)}getIndex(t){const i=this.numTilesX*this.numTilesY;t=t*this.cycleCount;let n=this.frameOverTime.evaluate(t%1);return n*=this.frameOverTimeMultiplier,n*=i,n=n%i,n=Math.floor(n),n}}k([m()],jt.prototype,"animation",2),k([m()],jt.prototype,"enabled",2),k([m()],jt.prototype,"cycleCount",2),k([m(X)],jt.prototype,"frameOverTime",2),k([m()],jt.prototype,"frameOverTimeMultiplier",2),k([m()],jt.prototype,"numTilesX",2),k([m()],jt.prototype,"numTilesY",2),k([m(X)],jt.prototype,"startFrame",2),k([m()],jt.prototype,"startFrameMultiplier",2),k([m()],jt.prototype,"rowMode",2),k([m()],jt.prototype,"rowIndex",2),k([m()],jt.prototype,"spriteCount",2),k([m()],jt.prototype,"timeMode",2);class ns{constructor(){a(this,"enabled"),a(this,"separateAxes"),a(this,"x"),a(this,"xMultiplier"),a(this,"y"),a(this,"yMultiplier"),a(this,"z"),a(this,"zMultiplier")}evaluate(t,i){return this.enabled?this.separateAxes?0:this.z.evaluate(t,i)*-1:0}}k([m()],ns.prototype,"enabled",2),k([m()],ns.prototype,"separateAxes",2),k([m(X)],ns.prototype,"x",2),k([m()],ns.prototype,"xMultiplier",2),k([m(X)],ns.prototype,"y",2),k([m()],ns.prototype,"yMultiplier",2),k([m(X)],ns.prototype,"z",2),k([m()],ns.prototype,"zMultiplier",2);class Bi{constructor(){a(this,"enabled"),a(this,"range"),a(this,"separateAxes"),a(this,"x"),a(this,"xMultiplier"),a(this,"y"),a(this,"yMultiplier"),a(this,"z"),a(this,"zMultiplier")}evaluate(t,i){if(!this.enabled)return 0;if(!this.separateAxes){const n=W.lerp(this.range.x,this.range.y,i);return this.z.evaluate(n)*-1}return 0}}k([m()],Bi.prototype,"enabled",2),k([m()],Bi.prototype,"range",2),k([m()],Bi.prototype,"separateAxes",2),k([m(X)],Bi.prototype,"x",2),k([m()],Bi.prototype,"xMultiplier",2),k([m(X)],Bi.prototype,"y",2),k([m()],Bi.prototype,"yMultiplier",2),k([m(X)],Bi.prototype,"z",2),k([m()],Bi.prototype,"zMultiplier",2);class ot{constructor(){a(this,"enabled"),a(this,"dampen"),a(this,"drag"),a(this,"dragMultiplier"),a(this,"limit"),a(this,"limitMultiplier"),a(this,"separateAxes"),a(this,"limitX"),a(this,"limitXMultiplier"),a(this,"limitY"),a(this,"limitYMultiplier"),a(this,"limitZ"),a(this,"limitZMultiplier"),a(this,"multiplyDragByParticleSize",!1),a(this,"multiplyDragByParticleVelocity",!1),a(this,"space"),a(this,"_temp",new x),a(this,"_temp2",new x)}apply(t,i,n,o,r,l,c){if(this.enabled){const h=this.limit.evaluate(r)*this.limitMultiplier;if(i.length()>h){this._temp.copy(i).normalize().multiplyScalar(h);const d=this.dampen*.5;i.x=W.lerp(i.x,this._temp.x,d),i.y=W.lerp(i.y,this._temp.y,d),i.z=W.lerp(i.z,this._temp.z,d),n.x=W.lerp(n.x,this._temp.x,d),n.y=W.lerp(n.y,this._temp.y,d),n.z=W.lerp(n.z,this._temp.z,d)}}}}k([m()],ot.prototype,"enabled",2),k([m()],ot.prototype,"dampen",2),k([m(X)],ot.prototype,"drag",2),k([m()],ot.prototype,"dragMultiplier",2),k([m(X)],ot.prototype,"limit",2),k([m()],ot.prototype,"limitMultiplier",2),k([m()],ot.prototype,"separateAxes",2),k([m(X)],ot.prototype,"limitX",2),k([m()],ot.prototype,"limitXMultiplier",2),k([m(X)],ot.prototype,"limitY",2),k([m()],ot.prototype,"limitYMultiplier",2),k([m(X)],ot.prototype,"limitZ",2),k([m()],ot.prototype,"limitZMultiplier",2),k([m()],ot.prototype,"multiplyDragByParticleSize",2),k([m()],ot.prototype,"multiplyDragByParticleVelocity",2),k([m()],ot.prototype,"space",2);const i1=class{constructor(){a(this,"enabled"),a(this,"curve"),a(this,"curveMultiplier"),a(this,"mode"),a(this,"system"),a(this,"_temp",new x),a(this,"_firstUpdate",!0),a(this,"_frames",0)}clone(){var s;const t=new i1;return t.enabled=this.enabled,t.curve=(s=this.curve)==null?void 0:s.clone(),t.curveMultiplier=this.curveMultiplier,t.mode=this.mode,t}get _lastWorldPosition(){return this.system._iv_lastWorldPosition||(this.system._iv_lastWorldPosition=new x),this.system._iv_lastWorldPosition}get _velocity(){return this.system._iv_velocity||(this.system._iv_velocity=new x),this.system._iv_velocity}awake(s){this.system=s,this.reset()}reset(){this._firstUpdate=!0}update(s){this.enabled&&this.system.worldspace!==!1&&(this._firstUpdate?(this._firstUpdate=!1,this._velocity.set(0,0,0),this._lastWorldPosition.copy(this.system.worldPos)):this._lastWorldPosition&&(this._velocity.copy(this.system.worldPos).sub(this._lastWorldPosition).multiplyScalar(1/this.system.deltaTime),this._lastWorldPosition.copy(this.system.worldPos)))}applyInitial(s){if(this.enabled&&this.system.worldspace!==!1&&this.mode===0){const t=this.curve.evaluate(Math.random(),Math.random());this._temp.copy(this._velocity).multiplyScalar(t),s.x+=this._temp.x,s.y+=this._temp.y,s.z+=this._temp.z}}applyCurrent(s,t,i){if(this.enabled&&this.system&&this.system.worldspace!==!1&&this.mode===1){const n=this.curve.evaluate(t,i);this._temp.copy(this._velocity).multiplyScalar(n),s.x+=this._temp.x,s.y+=this._temp.y,s.z+=this._temp.z}}};let Xo=i1;k([m()],Xo.prototype,"enabled",2),k([m(X)],Xo.prototype,"curve",2),k([m()],Xo.prototype,"curveMultiplier",2),k([m()],Xo.prototype,"mode",2);class si{constructor(){a(this,"enabled"),a(this,"range"),a(this,"separateAxes"),a(this,"size"),a(this,"sizeMultiplier"),a(this,"x"),a(this,"xMultiplier"),a(this,"y"),a(this,"yMultiplier"),a(this,"z"),a(this,"zMultiplier")}evaluate(t,i,n,o){const r=t.length(),l=W.remap(r,this.range.x,this.range.y,0,1),c=this.size.evaluate(l,n);return o.x*=c,o.y*=c,o.z*=c,o}}k([m()],si.prototype,"enabled",2),k([m(oe)],si.prototype,"range",2),k([m()],si.prototype,"separateAxes",2),k([m(X)],si.prototype,"size",2),k([m()],si.prototype,"sizeMultiplier",2),k([m(X)],si.prototype,"x",2),k([m()],si.prototype,"xMultiplier",2),k([m(X)],si.prototype,"y",2),k([m()],si.prototype,"yMultiplier",2),k([m(X)],si.prototype,"z",2),k([m()],si.prototype,"zMultiplier",2);class ea{constructor(){a(this,"enabled"),a(this,"range"),a(this,"color")}evaluate(t,i,n){const o=t.length(),r=W.remap(o,this.range.x,this.range.y,0,1),l=this.color.evaluate(r,i);n.x*=l.r,n.y*=l.g,n.z*=l.b,"alpha"in l&&(n.w*=l.alpha)}}k([m()],ea.prototype,"enabled",2),k([m(oe)],ea.prototype,"range",2),k([m(ii)],ea.prototype,"color",2),new x(1,1,1),new x(0,0,1);class Ep{constructor(t,i,n,o){a(this,"type","NeedleParticleSubEmitter"),a(this,"emitterType"),a(this,"emitterProbability"),a(this,"q_",new V),a(this,"v_",new x),a(this,"v2_",new x),a(this,"_emitterMatrix",new Cm),a(this,"_circularBuffer"),this.system=t,this.particleSystem=i,this.subSystem=n,this.subParticleSystem=o,this.subParticleSystem&&this.subParticleSystem&&(this.subParticleSystem.onlyUsedByOther=!0);const r=1e3;this._circularBuffer=new wi(()=>new Cm,r)}clone(){throw new Error("Method not implemented.")}initialize(t){t.emissionState={burstIndex:0,burstWaveIndex:0,time:0,waitEmiting:0},this._emitterMatrix.copy(this.subSystem.matrixWorld).invert().premultiply(this.system.matrixWorld),this._emitterMatrix.setPosition(0,0,0),this.emitterType===G0.Birth&&this.run(t)}update(t,i){this.run(t)}frameUpdate(t){}toJSON(){}reset(){}run(t){if(this.subSystem.currentParticles>=this.subSystem.main.maxParticles||!this.subParticleSystem||!t.emissionState||this.emitterProbability&&Math.random()>this.emitterProbability)return;const i=this.system.deltaTime;if(this.emitterType===G0.Death){let o=t.life;if(t[Ol]!==void 0&&(o=t[Ol]),!(t.age+i*1.2>=o))return;const r=this.subSystem.main.maxParticles-this.subSystem.currentParticles;t.emissionState.waitEmiting=r}const n=new Cm;n.set(1,0,0,t.position.x,0,1,0,t.position.y,0,0,1,t.position.z,0,0,0,1),this.particleSystem.worldSpace||n.multiplyMatrices(this._emitterMatrix,n),this.subParticleSystem.emit(i,t.emissionState,n)}}var AE=Object.defineProperty,IE=Object.getOwnPropertyDescriptor,Ye=(s,t,i,n)=>{for(var o=n>1?void 0:n?IE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&AE(t,i,o),o};const Qo=O("debugparticles"),jE=O("noprogressive"),LE=O("debugprogressive");var G0=(s=>(s[s.Birth=0]="Birth",s[s.Collision=1]="Collision",s[s.Death=2]="Death",s[s.Trigger=3]="Trigger",s[s.Manual=4]="Manual",s))(G0||{});class os extends A{constructor(){super(...arguments),a(this,"renderMode"),a(this,"particleMaterial"),a(this,"trailMaterial"),a(this,"particleMesh"),a(this,"maxParticleSize"),a(this,"minParticleSize"),a(this,"velocityScale"),a(this,"cameraVelocityScale"),a(this,"lengthScale")}start(){if(this.maxParticleSize!==.5&&this.minParticleSize!==0&&F()){const t=`ParticleSystem "${this.name}" has non-default min/max particle size. This may not render correctly. Please set min size to 0 and the max size to 0.5 and use the "StartSize" setting instead`;console.warn(t)}}get transparent(){var t;return((t=this.particleMaterial)==null?void 0:t.transparent)??!1}getMaterial(t=!1){let i=t===!0&&this.trailMaterial?this.trailMaterial:this.particleMaterial;if(i){if(i.type==="MeshStandardMaterial"){Qo&&console.debug("ParticleSystemRenderer.getMaterial: MeshStandardMaterial detected, converting to MeshBasicMaterial. See https://github.com/Alchemist0823/three.quarks/issues/101"),"map"in i&&i.map&&(i.map.colorSpace=pr,i.map.premultiplyAlpha=!1);const n=new Me({map:i.map});t?this.trailMaterial=n:this.particleMaterial=n}i.map&&(i.map.colorSpace=pr,i.map.premultiplyAlpha=!1),t&&i.side===lo&&(i=i.clone(),i.side=fm,t?this.trailMaterial=i:this.particleMaterial=i)}return i&&!jE&&i._didRequestTextureLOD===void 0&&(i._didRequestTextureLOD=0,LE&&console.log("Load material LOD",i.name),et.assignTextureLOD(i,0)),i}getMesh(t){let i=null;if(!i&&(this.particleMesh instanceof Q&&(i=this.particleMesh.geometry),i===null)){i=new Ds(1,1);const n=i.attributes.uv;for(let o=0;o<n.count;o++)n.setX(o,1-n.getX(o))}return new Q(i,this.getMaterial())}}Ye([m()],os.prototype,"renderMode",2),Ye([m(Oe)],os.prototype,"particleMaterial",2),Ye([m(Oe)],os.prototype,"trailMaterial",2),Ye([m()],os.prototype,"maxParticleSize",2),Ye([m()],os.prototype,"minParticleSize",2),Ye([m()],os.prototype,"velocityScale",2),Ye([m()],os.prototype,"cameraVelocityScale",2),Ye([m()],os.prototype,"lengthScale",2);class Ap{constructor(t,i=1){a(this,"_curve"),a(this,"_factor"),a(this,"type","function"),this._curve=t,this._factor=i}startGen(t){}genValue(t,i){return this._curve.evaluate(i,Math.random())*this._factor}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}}class X0{constructor(t){a(this,"type","value"),a(this,"system"),this.system=t}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}startGen(t){}}class DE extends X0{genValue(){return this.system.textureSheetAnimation.getStartIndex()}}class BE extends X0{constructor(){super(...arguments),a(this,"_lastPosition",new x),a(this,"_lastDistance",0)}update(){const t=ee(this.system.gameObject);this._lastDistance=this._lastPosition.distanceTo(t),this._lastPosition.copy(t)}genValue(){if(!this.system.isPlaying||!this.system.emission.enabled||this.system.currentParticles>=this.system.maxParticles)return 0;let t=this.system.emission.rateOverTime.evaluate(this.system.time/this.system.duration,Math.random());if(this.system.deltaTime>0){const o=this.system.emission.rateOverDistance.evaluate(this.system.time/this.system.duration,Math.random());let r=this._lastDistance/this.system.deltaTime*o;Number.isFinite(r)||(r=0),t+=r}const i=this.system.emission.getBurst();i>0&&(t+=i/this.system.deltaTime);const n=this.system.maxParticles-this.system.currentParticles;return W.clamp(t,0,n/this.system.deltaTime)}}class FE extends X0{genValue(){return this.system.isPlaying,0}}class Yo{constructor(t){a(this,"system"),a(this,"type"),this.type=Object.getPrototypeOf(this).constructor.name||"ParticleSystemBaseBehaviour",t&&(this.system=t)}get context(){return this.system.context}initialize(t){}update(t,i){}frameUpdate(t){}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}reset(){}}class zE extends Yo{constructor(){super(...arguments),a(this,"type","NeedleTextureSheet")}update(t,i){const n=this.system.textureSheetAnimation;if(n.enabled){const o=t.age/t.life,r=n.evaluate(o);r!==void 0&&(t.uvTile=r)}}}const s1=Symbol("particleRotation");class UE extends Yo{constructor(){super(...arguments),a(this,"type","NeedleRotation")}initialize(t){t[s1]=Math.random()}update(t,i){if(t.rotation===void 0)return;const n=t.age/t.life;if(typeof t.rotation=="number"&&(this.system.rotationOverLifetime.enabled?t.rotation+=this.system.rotationOverLifetime.evaluate(n,t[s1])*i:this.system.renderer.renderMode===$n.Billboard&&(t.rotation=Math.PI),this.system.rotationBySpeed.enabled)){const o=t.velocity.length();t.rotation+=this.system.rotationBySpeed.evaluate(n,o)*i}}}const n1=Symbol("sizeLerpFactor"),NE=new x;class WE extends Yo{constructor(){super(...arguments),a(this,"type","NeedleSize"),a(this,"_minSize",0),a(this,"_maxSize",1)}initialize(t){t[n1]=Math.random(),this._minSize=this.system.renderer.minParticleSize,this._maxSize=this.system.renderer.maxParticleSize}update(t,i){const n=t.age/t.life;let o=1;this.system.sizeOverLifetime.enabled&&(o*=this.system.sizeOverLifetime.evaluate(n,void 0,t[n1]).x);let r=1;this.system.renderer.renderMode!==$n.Mesh&&(r=this.system.worldScale.x/this.system.cameraScale);const l=$(t.startSize).multiplyScalar(o*r);if(t.size.set(l.x,l.y,l.z),this.system.localspace){const c=c1(this.system,NE);t.size.x*=c.x,t.size.y*=c.y,t.size.z*=c.z}}}const Ol=Symbol("particleLife"),Q0=Symbol("trailLifetime"),o1=Symbol("trailStartLength"),Y0=Symbol("trailWidthRandom");class VE extends Yo{constructor(){super(...arguments),a(this,"type","NeedleTrail")}initialize(t){t instanceof yv&&(t[Ol]=t.life,this.system.trails.enabled&&this.system.trails.dieWithParticles===!1&&(t[Q0]=this.system.trails.lifetime.evaluate(Math.random(),Math.random()),t.life+=t[Q0]),t[o1]=t.length,t[Y0]=Math.random())}update(t){var i;if((i=this.system.trails)!=null&&i.enabled&&t instanceof yv){const n=t,o=t.age/t[Ol],r=t.previous.values(),l=t.previous.length;for(let c=0;c<l;c++){const h=r.next().value,d=1-c/(l-1),u=t.size;if(u.x<=0&&!this.system.trails.sizeAffectsWidth){const p=20*this.system.trails.widthOverTrail.evaluate(.5,n[Y0]);u.x=p,u.y=p,u.z=p}h.size=this.system.trails.getWidth(u.x,o,d,n[Y0]),h.color.copy(t.color),this.system.trails.getColor(h.color,o,d)}if(t.age>t[Ol]){t.velocity.set(0,0,0);const c=(t.age-t[Ol])/t[Q0];n.length=W.lerp(t[o1],0,c)}}}}const Ip=Symbol("startVelocity"),r1=Symbol("gravityModifier"),K0=Symbol("gravitySpeed"),jp=Symbol("velocity lerp factor"),Z0=new x;class HE extends Yo{constructor(){super(...arguments),a(this,"type","NeedleVelocity"),a(this,"_gravityDirection",new x)}initialize(t){var i,n;const o=this.system.main.simulationSpeed;t.startSpeed=this.system.main.startSpeed.evaluate(Math.random(),Math.random());const r=this.system.shape.getDirection(t,t.position);t.velocity.x=r.x*t.startSpeed,t.velocity.y=r.y*t.startSpeed,t.velocity.z=r.z*t.startSpeed,(i=this.system.inheritVelocity)!=null&&i.enabled&&this.system.inheritVelocity.applyInitial(t.velocity),t[Ip]?t[Ip].copy(t.velocity):t[Ip]=t.velocity.clone();const l=this.system.main.gravityModifier.evaluate(Math.random(),Math.random());t[r1]=l*o,t[K0]=l*o*.5,t[jp]=Math.random(),(n=this.system.velocityOverLifetime)==null||n.init(t),this._gravityDirection.set(0,-1,0),this.system.main.simulationSpace===xh.Local&&this._gravityDirection.applyQuaternion(this.system.worldQuaternionInverted).normalize()}update(t,i){var n;const o=t[Ip],r=t[r1];if(r!==0){const g=r*t[K0];Z0.copy(this._gravityDirection).multiplyScalar(g),t[K0]+=i*.05,o.add(Z0)}t.velocity.copy(o);const l=t.age/t.life;(n=this.system.inheritVelocity)!=null&&n.enabled&&this.system.inheritVelocity.applyCurrent(t.velocity,l,t[jp]);const c=this.system.noise;c.enabled&&c.apply(0,t.position,t.velocity,i,t.age,t.life);const h=this.system.sizeBySpeed;h!=null&&h.enabled&&(t.size=h.evaluate(t.velocity,l,t[jp],t.size));const d=this.system.colorBySpeed;d!=null&&d.enabled&&d.evaluate(t.velocity,t[jp],t.color);const u=this.system.velocityOverLifetime;u.enabled&&u.apply(t,0,t.position,t.velocity,i,t.age,t.life);const p=this.system.limitVelocityOverLifetime;if(p.enabled&&p.apply(t.position,o,t.velocity,t.size,l,i,1),this.system.worldspace){const g=this.system.worldScale;t.velocity.x*=g.x,t.velocity.y*=g.y,t.velocity.z*=g.z}}}const a1=Symbol("colorLerpFactor"),l1=new we(1,1,1,1),ta=new we(1,1,1,1);class $E extends Yo{constructor(){super(...arguments),a(this,"type","NeedleColor")}initialize(t){}_init(t){const i=this.system.renderer.particleMaterial;ta.copy(this.system.main.startColor.evaluate(Math.random())),i!=null&&i.color&&(l1.copy(i.color),ta.multiply(l1)),ta.convertLinearToSRGB(),t.startColor.set(ta.r,ta.g,ta.b,ta.alpha),t.color.copy(t.startColor),t[a1]=Math.random()}update(t,i){if(t.age===0&&this._init(t),this.system.colorOverLifetime.enabled){const n=t.age/t.life,o=this.system.colorOverLifetime.color.evaluate(n,t[a1]);t.color.set(o.r,o.g,o.b,"alpha"in o?o.alpha:1).multiply(t.startColor)}else t.color.copy(t.startColor)}}class qE{constructor(t){a(this,"system"),a(this,"emission"),a(this,"autoDestroy"),a(this,"startLength"),a(this,"emissionBursts"),a(this,"onlyUsedByOther"),a(this,"behaviors",[]),a(this,"rendererEmitterSettings",{startLength:new sO(220),followLocalOrigin:!1}),a(this,"flatWhiteTexture"),a(this,"clonedTexture",{original:void 0,clone:void 0}),this.system=t,this.emission=new BE(this.system)}get anim(){return this.system.textureSheetAnimation}get prewarm(){return!1}get material(){return this.system.renderer.getMaterial(this.system.trails.enabled)}get layers(){return this.system.gameObject.layers}update(){this.emission.update()}get looping(){return this.system.main.loop}get duration(){return this.system.duration}get shape(){return this.system.shape}get startLife(){return new Ap(this.system.main.startLifetime)}get startSpeed(){return new Ap(this.system.main.startSpeed)}get startRotation(){return new Ap(this.system.main.startRotation)}get startSize(){return new Ap(this.system.main.startSize)}get startColor(){return new tO(new iO(1,1,1,1))}get emissionOverTime(){return this.emission}get emissionOverDistance(){return new FE(this.system)}get instancingGeometry(){return this.system.renderer.getMesh(this.system.renderer.renderMode).geometry}get renderMode(){if(this.system.trails.enabled===!0)return wn.Trail;switch(this.system.renderer.renderMode){case $n.Billboard:return wn.BillBoard;case $n.Stretch:return wn.StretchedBillBoard;case $n.HorizontalBillboard:return wn.HorizontalBillBoard;case $n.VerticalBillboard:return wn.VerticalBillBoard;case $n.Mesh:return wn.Mesh}return wn.BillBoard}get speedFactor(){var t;let i=this.system.main.simulationSpeed;return((t=this.system.renderer)==null?void 0:t.renderMode)===$n.Stretch&&(i*=this.system.renderer.velocityScale??1),i}get texture(){const t=this.material;if(t&&t.map){const i=t.map;if(this.clonedTexture.original!==i||!this.clonedTexture.clone){const n=i.clone();n.premultiplyAlpha=!1,n.colorSpace=pr,this.clonedTexture.original=i,this.clonedTexture.clone=n}return this.clonedTexture.clone}return this.flatWhiteTexture||(this.flatWhiteTexture=Zg(new we(1,1,1,1),1)),this.flatWhiteTexture}get startTileIndex(){return new DE(this.system)}get uTileCount(){var t;return this.anim.enabled?(t=this.anim)==null?void 0:t.numTilesX:void 0}get vTileCount(){var t;return this.anim.enabled?(t=this.anim)==null?void 0:t.numTilesY:void 0}get renderOrder(){return 1}get blending(){var t;return((t=this.system.renderer.particleMaterial)==null?void 0:t.blending)??mC}get transparent(){return this.system.renderer.transparent}get worldSpace(){return this.system.main.simulationSpace===xh.World}}class GE{constructor(){a(this,"burstParticleIndex",0),a(this,"burstParticleCount",0),a(this,"isBursting",!1),a(this,"travelDistance",0),a(this,"previousWorldPos"),a(this,"burstIndex",0),a(this,"burstWaveIndex",0),a(this,"time",0),a(this,"waitEmiting",0)}}const Lp=class extends A{constructor(){super(...arguments),a(this,"_state"),a(this,"colorOverLifetime"),a(this,"main"),a(this,"emission"),a(this,"sizeOverLifetime"),a(this,"shape"),a(this,"noise"),a(this,"trails"),a(this,"velocityOverLifetime"),a(this,"limitVelocityOverLifetime"),a(this,"inheritVelocity"),a(this,"colorBySpeed"),a(this,"textureSheetAnimation"),a(this,"rotationOverLifetime"),a(this,"rotationBySpeed"),a(this,"sizeBySpeed"),a(this,"_cameraScale",1),a(this,"__worldQuaternion",new V),a(this,"_worldQuaternionInverted",new V),a(this,"_worldScale",new x),a(this,"_worldPositionFrame",-1),a(this,"_worldPos",new x),a(this,"_renderer"),a(this,"_batchSystem"),a(this,"_particleSystem"),a(this,"_interface"),a(this,"_container"),a(this,"_time",0),a(this,"_isPlaying",!0),a(this,"_isUsedAsSubsystem",!1),a(this,"_didPreWarm",!1),a(this,"_bursts"),a(this,"_subEmitterSystems"),a(this,"_lastBatchesCount",-1)}play(s=!1){var t;s&&P.foreachComponent(this.gameObject,i=>{i instanceof Lp&&i!==this&&i.play(!1)},!0),this._isPlaying=!0,this._particleSystem&&(this._particleSystem.emissionState.time=0,this._particleSystem.emitEnded=!1),(t=this.emission)==null||t.reset()}pause(s=!0){s&&P.foreachComponent(this.gameObject,t=>{t instanceof Lp&&t!==this&&t.pause(!1)},!0),this._isPlaying=!1}stop(s=!0,t=!1){s&&P.foreachComponent(this.gameObject,i=>{i instanceof Lp&&i!==this&&i.stop(!1,t)},!0),this._isPlaying=!1,this._time=0,t&&this.reset()}reset(){var s;this._time=0,this._particleSystem&&(this._particleSystem.particleNum=0,this._particleSystem.emissionState.time=0,this._particleSystem.emitEnded=!1,(s=this.emission)==null||s.reset())}emit(s){if(this._particleSystem){this.onUpdate(),s=Math.min(s,this.maxParticles-this.currentParticles),this._state||(this._state=new GE),this._state.waitEmiting=s,this._state.time=0;const t=this._particleSystem.emitEnded;this._particleSystem.emitEnded=!1,this._particleSystem.emit(this.deltaTime,this._state,this._particleSystem.emitter.matrixWorld),this._particleSystem.emitEnded=t}}get playOnAwake(){return this.main.playOnAwake}set playOnAwake(s){this.main.playOnAwake=s}get renderer(){return this._renderer}get isPlaying(){return this._isPlaying}get currentParticles(){var s;return((s=this._particleSystem)==null?void 0:s.particleNum)??0}get maxParticles(){return this.main.maxParticles}get time(){return this._time}get duration(){return this.main.duration}get deltaTime(){return this.context.time.deltaTime*this.main.simulationSpeed}get scale(){return this.gameObject.scale.x}get cameraScale(){return this._cameraScale}get container(){return this._container}get worldspace(){return this.main.simulationSpace===xh.World}get localspace(){return this.main.simulationSpace===xh.Local}get worldQuaternion(){return this.__worldQuaternion}get worldQuaternionInverted(){return this._worldQuaternionInverted}get worldScale(){return this._worldScale}get worldPos(){return this._worldPositionFrame!==this.context.time.frame&&(this._worldPositionFrame=this.context.time.frame,ee(this.gameObject,this._worldPos)),this._worldPos}get matrixWorld(){return this._container.matrixWorld}get isSubsystem(){return this._isUsedAsSubsystem}addBehaviour(s){return this._particleSystem?(s instanceof Yo&&(s.system=this),(F()||Qo)&&console.debug("Add custom ParticleSystem Behaviour",s),this._particleSystem.addBehavior(s),!0):!1}removeBehaviour(s){if(!this._particleSystem)return!1;const t=this._particleSystem.behaviors,i=t.indexOf(s);return i!==-1&&((F()||Qo)&&console.debug("Remove custom ParticleSystem Behaviour",i,s),t.splice(i,1)),!0}removeAllBehaviours(){return this._particleSystem?(this._particleSystem.behaviors.length=0,!0):!1}get behaviours(){return this._particleSystem?this._particleSystem.behaviors:null}get particleSystem(){return this._particleSystem??null}set bursts(s){for(let t=0;t<s.length;t++){const i=s[t];if(!(i instanceof Ch)){const n=new Ch;La(n,i),s[t]=n}}this._bursts=s}set subEmitterSystems(s){for(let t=0;t<s.length;t++){const i=s[t];if(!(i instanceof kh)){const n=new kh;La(n,i),s[t]=n}}Qo&&s.length>0&&console.log("SubEmitters: ",s,this),this._subEmitterSystems=s}onAfterDeserialize(s){if(this._subEmitterSystems&&Array.isArray(this._subEmitterSystems))for(const t of this._subEmitterSystems)t._deserialize(this.context,this.gameObject)}awake(){if(this._worldPositionFrame=-1,this._renderer=this.gameObject.getComponent(os),!this.main)throw new Error("Not Supported: ParticleSystem needs a serialized MainModule. Creating new particle systems at runtime is currently not supported.");this._container=new j,this._container.matrixAutoUpdate=!1,this.context.scene.add(this._container),this._batchSystem=new JC,this._batchSystem.name=this.gameObject.name,this._container.add(this._batchSystem),this._interface=new qE(this),this._particleSystem=new eO(this._interface),this._particleSystem.addBehavior(new WE(this)),this._particleSystem.addBehavior(new $E(this)),this._particleSystem.addBehavior(new zE(this)),this._particleSystem.addBehavior(new UE(this)),this._particleSystem.addBehavior(new HE(this)),this._particleSystem.addBehavior(new VE(this)),this._batchSystem.addSystem(this._particleSystem);const s=this._particleSystem.emitter;this.context.scene.add(s),this.inheritVelocity.system&&this.inheritVelocity.system!==this&&(this.inheritVelocity=this.inheritVelocity.clone()),this.inheritVelocity.awake(this),Qo&&(console.log(this),this.gameObject.add(new bi(1)))}start(){this.addSubParticleSystems(),this.updateLayers(),this.renderer.particleMesh instanceof Q&&this._interface.renderMode==wn.Mesh&&et.assignMeshLOD(this.renderer.particleMesh,0).then(s=>{s&&this.particleSystem&&this._interface.renderMode==wn.Mesh&&(this.particleSystem.instancingGeometry=s)})}onDestroy(){var s,t,i,n;(s=this._container)==null||s.removeFromParent(),(t=this._batchSystem)==null||t.removeFromParent(),(i=this._particleSystem)==null||i.emitter.removeFromParent(),(n=this._particleSystem)==null||n.dispose()}onEnable(){this.main&&(this.inheritVelocity&&(this.inheritVelocity.system=this),this._batchSystem&&(this._batchSystem.visible=!0),this.playOnAwake&&this.play(),this._isPlaying=this.playOnAwake)}onDisable(){this._batchSystem&&(this._batchSystem.visible=!1)}onBeforeRender(){var s;this.main&&(this._didPreWarm===!1&&((s=this.main)==null?void 0:s.prewarm)===!0&&(this._didPreWarm=!0,this.preWarm()),this.onUpdate(),this.onSimulate(this.deltaTime))}preWarm(){var s;if(!((s=this.emission)!=null&&s.enabled)||this.emission.rateOverTime.getMax()<=0)return;const t=1/60,i=this.main.duration,n=this.main.startLifetime.getMax(),o=1e3,r=Math.min(Math.max(i,n)/Math.max(.01,this.main.simulationSpeed),o),l=Math.ceil(r/t),c=Date.now();Qo&&console.log(`Particles ${this.name} - Prewarm for ${l} frames (${r} sec). Duration: ${i}, Lifetime: ${n}`);for(let h=0;h<l&&!(this.currentParticles>=this.maxParticles);h++){const d=Date.now()-c;if(d>2e3){console.warn(`Particles ${this.name} - Prewarm took too long. Aborting: ${d}`);break}this.onUpdate(),this.onSimulate(t)}}onSimulate(s){if(this._batchSystem){let t=this.context.time.frameCount%60===0;this._lastBatchesCount!==this._batchSystem.batches.length&&(this._lastBatchesCount=this._batchSystem.batches.length,t=!0),t&&this.updateLayers(),this._batchSystem.update(s)}this._time+=s,this._time>this.duration&&(this._time=0)}updateLayers(){if(this._batchSystem)for(let s=0;s<this._batchSystem.batches.length;s++){const t=this._batchSystem.batches[s];t.layers.disableAll();const i=this.layer;t.layers.mask=1<<i}}onUpdate(){var s,t;if(this._bursts&&(this.emission.bursts=this._bursts,delete this._bursts),!this._isPlaying)return;const i=this.context.mainCamera;if(i){const r=Ke(i);this._cameraScale=r.x}const n=!this.worldspace,o=this.gameObject;if(Se(o,this.__worldQuaternion),this._worldQuaternionInverted.copy(this.__worldQuaternion).invert(),Ke(this.gameObject,this._worldScale),n&&this._container&&(s=this.gameObject)!=null&&s.parent){const r=c1(this,Z0);this._container.matrix.makeScale(r.x,r.y,r.z),this._container.matrix.makeRotationFromQuaternion(this.__worldQuaternion),this._container.matrix.setPosition(this.worldPos),this._container.matrix.scale(this.gameObject.scale)}this.emission.system=this,this._interface.update(),this.shape.onUpdate(this,this.context,this.main.simulationSpace,this.gameObject),this.noise.update(this.context),(t=this.inheritVelocity)==null||t.update(this.context),this.velocityOverLifetime.update(this)}addSubParticleSystems(){var s;if(this._subEmitterSystems&&this._particleSystem)for(const t of this._subEmitterSystems){t.particleSystem&&(t.particleSystem.__internalAwake?t.particleSystem.__internalAwake():F()&&console.warn("SubParticleSystem serialization issue(?)",t.particleSystem,t));const i=(s=t.particleSystem)==null?void 0:s._particleSystem;if(i){t.particleSystem._isUsedAsSubsystem=!0;const n=new Ep(this,this._particleSystem,t.particleSystem,i);n.emitterType=t.type,n.emitterProbability=t.emitProbability,this._particleSystem.addBehavior(n)}else Qo&&console.warn("Could not add SubParticleSystem",t,this)}}};let rt=Lp;Ye([m(Oh)],rt.prototype,"colorOverLifetime",2),Ye([m(It)],rt.prototype,"main",2),Ye([m(hn)],rt.prototype,"emission",2),Ye([m(Go)],rt.prototype,"sizeOverLifetime",2),Ye([m(Xe)],rt.prototype,"shape",2),Ye([m(xe)],rt.prototype,"noise",2),Ye([m(ze)],rt.prototype,"trails",2),Ye([m(Qe)],rt.prototype,"velocityOverLifetime",2),Ye([m(ot)],rt.prototype,"limitVelocityOverLifetime",2),Ye([m(Xo)],rt.prototype,"inheritVelocity",2),Ye([m(ea)],rt.prototype,"colorBySpeed",2),Ye([m(jt)],rt.prototype,"textureSheetAnimation",2),Ye([m(ns)],rt.prototype,"rotationOverLifetime",2),Ye([m(Bi)],rt.prototype,"rotationBySpeed",2),Ye([m(si)],rt.prototype,"sizeBySpeed",2);class kh{constructor(){a(this,"particleSystem"),a(this,"emitProbability",1),a(this,"properties"),a(this,"type")}_deserialize(t,i){const n=this.particleSystem;if(n instanceof rt)return;let o="";n&&typeof n.guid=="string"&&(o=n.guid,this.particleSystem=P.findByGuid(o,i)),Qo&&!(this.particleSystem instanceof rt)&&console.warn("Could not find particle system for sub emitter",o,i,this)}}function c1(s,t){if(t.set(1,1,1),s.gameObject.parent&&s.localspace)switch(s.main.scalingMode){case q0.Local:t=Ke(s.gameObject.parent,t),t.x=1/t.x,t.y=1/t.y,t.z=1/t.z;break;default:if(!s.unsupported_scaling_mode){s.unsupported_scaling_mode=!0;const i="ParticleSystem scale mode "+q0[s.main.scalingMode]+" is not supported";F()&&_e(i),console.warn(i,s.name,s)}t=Ke(s.gameObject,t);break}return t}class zl extends A{constructor(){super(...arguments),a(this,"_didAssignPlayerColor",!1),a(this,"tryAssignColor",()=>{const t=P.getComponentInParent(this.gameObject,ji);if(t&&t.owner)return this._didAssignPlayerColor=!0,this.assignUserColor(t.owner),!0;const i=P.getComponentInParent(this.gameObject,Mt);return i!=null&&i.connectionId?(this._didAssignPlayerColor=!0,this.assignUserColor(i.connectionId),!0):!1})}onEnable(){this.context.connection.beginListen(ie.JoinedRoom,this.tryAssignColor),this._didAssignPlayerColor||this.startCoroutine(this.waitForConnection())}onDisable(){this.context.connection.stopListen(ie.JoinedRoom,this.tryAssignColor)}*waitForConnection(){for(;!this.destroyed&&this.activeAndEnabled&&(yield H_(.2),!this.tryAssignColor()););}assignUserColor(t){const i=zl.hashCode(t),n=zl.colorFromHashCode(i);if(this.gameObject.type==="Mesh"){const o=this.gameObject;this.assignColor(n,t,o)}else if(this.gameObject.children)for(const o of this.gameObject.children){const r=o;r.material&&r.material.color&&this.assignColor(n,t,r)}}assignColor(t,i,n){let o=n.material;o&&(o._playerMaterial!==i&&(o=o.clone(),o._playerMaterial=i,n.material=o),o.color=t)}static hashCode(t){var i=0,n,o;if(t.length===0)return i;for(n=0;n<t.length;n++)o=t.charCodeAt(n),i=(i<<5)-i+o,i|=0;return i}static colorFromHashCode(t){const i=(t&16711680)>>16,n=(t&65280)>>8,o=t&255;return new ae(i/255,n/255,o/255)}}const XE=O("debugpost");let J0=null;function QE(s){J0=s}function h1(s){let t=s.gameObject;for(;t;){for(const i of eu(t))if(i.isPostProcessingManager===!0)return i;t=t.parent}return null}function YE(s){let t=h1(s);if(!t)if(J0){XE&&console.warn("Adding postprocessing manager to the scene.");const i=s.scene;t=ki(i,J0)}else F()&&console.warn("No post processing manager found");return t}var KE=Object.defineProperty,ZE=Object.getOwnPropertyDescriptor,d1=(s,t,i,n)=>{for(var o=n>1?void 0:n?ZE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&KE(t,i,o),o};const JE=O("debugpost");class N{constructor(t){a(this,"isVolumeParameter",!0),a(this,"_isInitialized",!1),a(this,"_active",!0),a(this,"_value"),a(this,"_valueRaw"),a(this,"_defaultValue"),a(this,"valueProcessor"),a(this,"onValueChanged"),t!==void 0&&this.initialize(t)}get isInitialized(){return this._isInitialized}initialize(t){t!==void 0&&(this._value=t,this._defaultValue=t,this._valueRaw=t,this._isInitialized=!0)}get overrideState(){return this._active}set overrideState(t){if(this._active===t)return;this._active=t;const i=t?this._valueRaw:this._defaultValue;this.processValue(i,!0)}get value(){return this._valueRaw}set value(t){this.isInitialized||this.initialize(t),this.processValue(t,!1)}set defaultValue(t){this._defaultValue=t}__init(){this.processValue(this._valueRaw,!0)}processValue(t,i){if(t==null||!i&&this.testIfValueChanged(t)===!1)return;const n=this._value;JE&&typeof n=="number"&&typeof t=="number"&&(n?.toFixed(4),t?.toFixed(4)),!this._active&&this._defaultValue!==void 0?(this._value=this._defaultValue,t=this._defaultValue,this._valueRaw=t):(this._valueRaw=t,this._active&&this.valueProcessor&&(t=this.valueProcessor(t)),this._value=t),this.onValueChanged&&this.onValueChanged(t,n,this)}testIfValueChanged(t){return this._valueRaw!==t}}d1([m()],N.prototype,"overrideState",1),d1([m()],N.prototype,"value",1);class eA extends Ki{constructor(){super([N])}onSerialize(t,i){}onDeserialize(t,i){const n=i.target,o=i.path;let r;if(n&&o&&(r=n[o]),(typeof r!="object"||typeof r=="object"&&r.isVolumeParameter!==!0)&&(r=new N),typeof t=="object"&&"value"in t){const l=t.value;r.initialize(l),r.overrideState=t.overrideState}else r.value=t;return r}}new eA;var tA=Object.defineProperty,iA=Object.getOwnPropertyDescriptor,sA=(s,t,i,n)=>{for(var o=n>1?void 0:n?iA(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&tA(t,i,o),o};const nA=O("debugpost");class at extends A{constructor(t=void 0){if(super(),a(this,"active",!0),a(this,"_manager",null),a(this,"_result"),a(this,"_postprocessingContext",null),t)for(const i of Object.keys(t)){const n=t[i],o=this[i];o instanceof N?o.initialize(n):o!==void 0&&(this[i]=n)}}get isPostProcessingEffect(){return!0}onEnable(){super.onEnable(),this.onEffectEnabled(),this.__internalDidAwakeAndStart&&(this.active=!0)}onDisable(){var t;super.onDisable(),(t=this._manager)==null||t.removeEffect(this),this.active=!1}onEffectEnabled(t){var i;t&&t.isPostProcessingManager===!0?this._manager=t:this._manager||(this._manager=YE(this)),(i=this._manager)==null||i.addEffect(this)}init(){}get postprocessingContext(){return this._postprocessingContext}apply(t){var i;return this._postprocessingContext=t,this._result||(this.initParameters(),this._result=(i=this.onCreateEffect)==null?void 0:i.call(this)),this._result&&this.initParameters(),this._result}unapply(){}dispose(){nA&&console.warn("DISPOSE",this),this._result&&(Array.isArray(this._result)?this._result.forEach(t=>t.dispose()):this._result.dispose()),this._result=void 0}initParameters(){const t=Object.keys(this);for(const i of t){const n=this[i];n instanceof N&&n.__init()}}onEditorModification(t){const i=t.propertyName;if(this[i]instanceof N){const n=t.value;return this[i].value=n,!0}}}sA([m()],at.prototype,"active",2);var oA=Object.defineProperty,rA=Object.getOwnPropertyDescriptor,aA=(s,t,i,n)=>{for(var o=n>1?void 0:n?rA(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&oA(t,i,o),o};const lA=O("debugpost"),ey={};function rs(s,t){ey[s]=t}function cA(s){return s.__type in ey?ey[s.__type]:(lA&&s.__type&&console.warn("Unknown postprocessing type",s.__type,s),at)}class Mh{constructor(){a(this,"components",[])}init(){var t;(t=this.components)==null||t.forEach(i=>i.init())}addEffect(t){this.components.push(t)}removeEffect(t){const i=this.components.indexOf(t);i>=0&&this.components.splice(i,1)}}aA([Ha([s=>cA(s),at])],Mh.prototype,"components",2);var hA=Object.defineProperty,dA=Object.getOwnPropertyDescriptor,uA=(s,t,i,n)=>{for(var o=n>1?void 0:n?dA(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&hA(t,i,o),o};class Rh extends at{constructor(){super(...arguments),a(this,"preset",new N(2))}get typeName(){return"Antialiasing"}onCreateEffect(){const t=new B.POSTPROCESSING.MODULE.SMAAEffect({preset:B.POSTPROCESSING.MODULE.SMAAPreset.HIGH,edgeDetectionMode:B.POSTPROCESSING.MODULE.EdgeDetectionMode.DEPTH});return this.preset.onValueChanged=i=>{t.applyPreset(i)},t}}uA([m(N)],Rh.prototype,"preset",2),rs("Antialiasing",Rh);var pA=Object.defineProperty,mA=Object.getOwnPropertyDescriptor,ty=(s,t,i,n)=>{for(var o=n>1?void 0:n?mA(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&pA(t,i,o),o},iy;const u1=(iy=class extends at{constructor(){super(...arguments),a(this,"threshold",new N(.9)),a(this,"intensity",new N(1)),a(this,"scatter",new N(.3)),a(this,"selectiveBloom")}get typeName(){return"Bloom"}init(){this.threshold.valueProcessor=s=>s,this.intensity.valueProcessor=s=>s,this.scatter.valueProcessor=s=>s}onCreateEffect(){let s;if(this.selectiveBloom==null&&(this.selectiveBloom=u1.useSelectiveBloom),this.selectiveBloom){const t=s=new B.POSTPROCESSING.MODULE.SelectiveBloomEffect(this.context.scene,this.context.mainCamera,{blendFunction:B.POSTPROCESSING.MODULE.BlendFunction.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,radius:.85,intensity:this.intensity.value});t.inverted=!0}else s=new B.POSTPROCESSING.MODULE.BloomEffect({blendFunction:B.POSTPROCESSING.MODULE.BlendFunction.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,radius:.85,intensity:this.intensity.value});return this.intensity.onValueChanged=t=>{s.intensity=t},this.threshold.onValueChanged=t=>{s.luminanceMaterial.threshold=Math.pow(t,2.2)},this.scatter.onValueChanged=t=>{s.luminancePass.enabled=!0,s.luminanceMaterial.smoothing=t,s.mipmapBlurPass&&(s.mipmapBlurPass.radius=vn.lerp(.1,.9,t))},s}},a(iy,"useSelectiveBloom",!1),iy);let ia=u1;ty([m(N)],ia.prototype,"threshold",2),ty([m(N)],ia.prototype,"intensity",2),ty([m(N)],ia.prototype,"scatter",2),rs("Bloom",ia);var gA=Object.defineProperty,fA=Object.getOwnPropertyDescriptor,yA=(s,t,i,n)=>{for(var o=n>1?void 0:n?fA(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&gA(t,i,o),o};class Th extends at{constructor(){super(...arguments),a(this,"intensity",new N(0))}get typeName(){return"ChromaticAberration"}onCreateEffect(){const t=new B.POSTPROCESSING.MODULE.ChromaticAberrationEffect;return t.offset=new oe(0,0),t.radialModulation=!0,t.modulationOffset=.15,this.intensity.valueProcessor=i=>i*.02,this.intensity.onValueChanged=i=>{t.offset.x=-i,t.offset.y=i},t}}yA([m(N)],Th.prototype,"intensity",2),rs("ChromaticAberration",Th);var vA=Object.defineProperty,bA=Object.getOwnPropertyDescriptor,p1=(s,t,i,n)=>{for(var o=n>1?void 0:n?bA(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&vA(t,i,o),o};const m1=O("debugpost");var Dp=(s=>(s[s.None=0]="None",s[s.Neutral=1]="Neutral",s[s.ACES=2]="ACES",s[s.AgX=3]="AgX",s[s.KhronosNeutral=4]="KhronosNeutral",s))(Dp||{});function sy(s){switch(s){case 0:return ud;case 1:return bm;case 2:return vm;case 3:return dd;case 4:return Hl;default:return Hl}}function _A(s){switch(s){case ud:return 0;case vm:return 2;case dd:return 3;case Hl:return 1;case bm:return 1;default:return 0}}function g1(s){switch(s){case ud:return B.POSTPROCESSING.MODULE.ToneMappingMode.LINEAR;case vm:return B.POSTPROCESSING.MODULE.ToneMappingMode.ACES_FILMIC;case dd:return B.POSTPROCESSING.MODULE.ToneMappingMode.AGX;case Hl:return B.POSTPROCESSING.MODULE.ToneMappingMode.NEUTRAL;case bm:return B.POSTPROCESSING.MODULE.ToneMappingMode.REINHARD;default:return B.POSTPROCESSING.MODULE.ToneMappingMode.LINEAR}}const f1=class extends at{constructor(){super(...arguments),a(this,"mode",new N(void 0)),a(this,"exposure",new N(1))}get typeName(){return"ToneMapping"}setMode(s){const t=Dp[s];return t===void 0?(console.error("Invalid ToneMapping mode",s),this):(this.mode.value=t,this)}get isToneMapping(){return!0}onEffectEnabled(){const s=h1(this);s&&super.onEffectEnabled(s)}onCreateEffect(){if(this.postprocessingContext)for(const i of this.postprocessingContext.components){if(i===this)break;if(i!=this&&i instanceof f1){console.warn("Multiple tonemapping effects found in the same postprocessing stack: Please check your scene setup.",{activeEffect:i,ignoredEffect:this});return}}if(this.mode.isInitialized==!1){const i=_A(this.context.renderer.toneMapping);this.mode.initialize(i)}const s=sy(this.mode.value),t=new B.POSTPROCESSING.MODULE.ToneMappingEffect({mode:g1(s)});return this.mode.onValueChanged=i=>{const n=sy(i);t.mode=g1(n),m1&&console.log("ToneMapping mode changed to",Dp[i],n,t.mode)},m1&&console.log("Use ToneMapping",Dp[this.mode.value],s,t.mode,"renderer.tonemapping: "+this.context.renderer.toneMapping),this.exposure.onValueChanged=i=>{this.context.renderer.toneMappingExposure=i},t}onBeforeRender(){this.mode.overrideState&&(this.context.renderer.toneMapping=sy(this.mode.value)),this.exposure.overrideState&&(this.context.renderer.toneMappingExposure=this.exposure.value)}};let Ko=f1;p1([m(N)],Ko.prototype,"mode",2),p1([m(N)],Ko.prototype,"exposure",2),rs("Tonemapping",Ko);var wA=Object.defineProperty,xA=Object.getOwnPropertyDescriptor,Bp=(s,t,i,n)=>{for(var o=n>1?void 0:n?xA(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&wA(t,i,o),o};class Zo extends at{constructor(){super(...arguments),a(this,"postExposure",new N(0)),a(this,"contrast",new N(0)),a(this,"hueShift",new N(0)),a(this,"saturation",new N(0))}get typeName(){return"ColorAdjustments"}init(){this.postExposure.valueProcessor=t=>(t=Math.pow(2,t),t),this.contrast.valueProcessor=t=>{let i=1;return t>0?i=200:t<0&&(i=100),t/i},this.contrast.defaultValue=0,this.hueShift.valueProcessor=t=>Math.PI*t/180,this.hueShift.defaultValue=0,this.saturation.valueProcessor=t=>t<0?t/100:t/(100*Math.PI),this.saturation.defaultValue=0}onCreateEffect(){var t,i;const n=[];this.context.renderer.toneMapping!==_a&&this.postExposure.overrideState&&(this.context.renderer.toneMapping=_a);let o=(t=this.postprocessingContext)==null?void 0:t.components.find(c=>c instanceof Ko);o||(o=new Ko,(i=this.postprocessingContext)==null||i.components.push(o)),this.postExposure.onValueChanged=c=>{this.postExposure.overrideState&&(o.exposure.value=c)};const r=new B.POSTPROCESSING.MODULE.BrightnessContrastEffect;this.contrast.onValueChanged=c=>r.contrast=c;const l=new B.POSTPROCESSING.MODULE.HueSaturationEffect;return n.push(r),n.push(l),this.hueShift.onValueChanged=c=>l.hue=c,this.saturation.onValueChanged=c=>l.saturation=c,n}}Bp([m(N)],Zo.prototype,"postExposure",2),Bp([m(N)],Zo.prototype,"contrast",2),Bp([m(N)],Zo.prototype,"hueShift",2),Bp([m(N)],Zo.prototype,"saturation",2),rs("ColorAdjustments",Zo);var SA=Object.defineProperty,CA=Object.getOwnPropertyDescriptor,sa=(s,t,i,n)=>{for(var o=n>1?void 0:n?CA(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&SA(t,i,o),o};const OA=O("debugpost");class Ts extends at{constructor(){super(...arguments),a(this,"mode"),a(this,"focusDistance",new N(1)),a(this,"focalLength",new N(.2)),a(this,"aperture",new N(20)),a(this,"gaussianMaxRadius",new N),a(this,"resolutionScale",new N(1*1/window.devicePixelRatio)),a(this,"bokehScale",new N)}get typeName(){return"DepthOfField"}init(){this.focalLength.valueProcessor=i=>{const n=i/300,o=2;return W.lerp(o,.01,n)};const t=20;this.aperture.valueProcessor=i=>{const n=1-i/32;return W.lerp(1,t,n)}}onCreateEffect(){if(this.mode===0){OA&&console.warn("DepthOfField: Mode is set to Off");return}const t=new B.POSTPROCESSING.MODULE.DepthOfFieldEffect(this.context.mainCamera,{worldFocusRange:.2,focalLength:1,bokehScale:20,resolutionScale:this.resolutionScale.value});return this.focusDistance.onValueChanged=i=>{t.cocMaterial.worldFocusDistance=i},this.focalLength.onValueChanged=i=>t.cocMaterial.worldFocusRange=i,this.aperture.onValueChanged=i=>t.bokehScale=i,this.resolutionScale&&(this.resolutionScale.onValueChanged=i=>t.resolution.scale=i),[t]}unapply(){}}sa([m()],Ts.prototype,"mode",2),sa([m(N)],Ts.prototype,"focusDistance",2),sa([m(N)],Ts.prototype,"focalLength",2),sa([m(N)],Ts.prototype,"aperture",2),sa([m(N)],Ts.prototype,"gaussianMaxRadius",2),sa([m(N)],Ts.prototype,"resolutionScale",2),sa([m(N)],Ts.prototype,"bokehScale",2),rs("DepthOfField",Ts);class Eh extends at{constructor(t){super(),a(this,"effect"),this.effect=t}get typeName(){return this.effect.constructor.name}onCreateEffect(){return this.effect}}var PA=Object.defineProperty,kA=Object.getOwnPropertyDescriptor,MA=(s,t,i,n)=>{for(var o=n>1?void 0:n?kA(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&PA(t,i,o),o};class Ah extends at{constructor(){super(...arguments),a(this,"granularity",new N(10))}get typeName(){return"PixelationEffect"}onCreateEffect(){const t=new B.POSTPROCESSING.MODULE.PixelationEffect;return this.granularity.onValueChanged=i=>{t.granularity=i},t}}MA([m(N)],Ah.prototype,"granularity",2),rs("PixelationEffect",Ah);var RA=Object.defineProperty,TA=Object.getOwnPropertyDescriptor,Ih=(s,t,i,n)=>{for(var o=n>1?void 0:n?TA(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&RA(t,i,o),o};class qn extends at{constructor(){super(...arguments),a(this,"intensity",new N(2)),a(this,"falloff",new N(1)),a(this,"samples",new N(9)),a(this,"color",new N(new ae(0,0,0))),a(this,"luminanceInfluence",new N(.7)),a(this,"_ssao")}get typeName(){return"ScreenSpaceAmbientOcclusion"}onBeforeRender(){if(this._ssao&&this.context.mainCamera instanceof be){const t=this.context.mainCamera.far-this.context.mainCamera.near;this._ssao.ssaoMaterial.worldDistanceFalloff=t*.01,this._ssao.ssaoMaterial.worldDistanceThreshold=this.context.mainCamera.far}}onCreateEffect(){const t=this.context.mainCamera,i=new B.POSTPROCESSING.MODULE.NormalPass(this.context.scene,t),n=new B.POSTPROCESSING.MODULE.DepthDownsamplingPass({normalBuffer:i.texture,resolutionScale:.5}),o=this._ssao=new B.POSTPROCESSING.MODULE.SSAOEffect(t,i.texture,{normalDepthBuffer:n.texture,worldDistanceThreshold:1,worldDistanceFalloff:1,worldProximityThreshold:.1,worldProximityFalloff:2,intensity:1,blendFunction:B.POSTPROCESSING.MODULE.BlendFunction.MULTIPLY,luminanceInfluence:.5});this.intensity.onValueChanged=l=>{o.intensity=l},this.falloff.onValueChanged=l=>{o.ssaoMaterial.radius=l*.1},this.samples.onValueChanged=l=>{o.ssaoMaterial.samples=l},this.color.onValueChanged=l=>{o.color||(o.color=new ae),o.color.copy(l)},this.luminanceInfluence.onValueChanged=l=>{o.luminanceInfluence=l};const r=new Array;return r.push(i),r.push(n),r.push(o),r}}Ih([m(N)],qn.prototype,"intensity",2),Ih([m(N)],qn.prototype,"falloff",2),Ih([m(N)],qn.prototype,"samples",2),Ih([m(N)],qn.prototype,"color",2),Ih([m(N)],qn.prototype,"luminanceInfluence",2),rs("ScreenSpaceAmbientOcclusion",qn);var EA=Object.defineProperty,AA=Object.getOwnPropertyDescriptor,na=(s,t,i,n)=>{for(var o=n>1?void 0:n?AA(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&EA(t,i,o),o},ny=(s=>(s[s.Performance=0]="Performance",s[s.Low=1]="Low",s[s.Medium=2]="Medium",s[s.High=3]="High",s[s.Ultra=4]="Ultra",s))(ny||{});class Es extends at{constructor(){super(...arguments),a(this,"gammaCorrection",!0),a(this,"aoRadius",new N(1)),a(this,"falloff",new N(1)),a(this,"intensity",new N(1)),a(this,"color",new N(new ae(0,0,0))),a(this,"screenspaceRadius",!1),a(this,"quality",2),a(this,"_ssao")}get typeName(){return"ScreenSpaceAmbientOcclusionN8"}onValidate(){this._ssao&&(this._ssao.setQualityMode(ny[this.quality]),this._ssao.configuration.gammaCorrection=this.gammaCorrection,this._ssao.configuration.screenSpaceRadius=this.screenspaceRadius)}onCreateEffect(){const t=this.context.mainCamera,i=this._ssao=new B.POSTPROCESSING_AO.MODULE.N8AOPostPass(this.context.scene,t,this.context.domWidth,this.context.domHeight),n=ny[this.quality];i.setQualityMode(n),i.configuration.gammaCorrection=this.gammaCorrection,i.configuration.screenSpaceRadius=this.screenspaceRadius,this.intensity.onValueChanged=r=>{i.configuration.intensity=r},this.falloff.onValueChanged=r=>{i.configuration.distanceFalloff=r},this.aoRadius.onValueChanged=r=>{i.configuration.aoRadius=r},this.color.onValueChanged=r=>{i.color||(i.color=new ae),i.configuration.color.copy(r)};const o=new Array;return o.push(i),o}}na([kt(),m()],Es.prototype,"gammaCorrection",2),na([m(N)],Es.prototype,"aoRadius",2),na([m(N)],Es.prototype,"falloff",2),na([m(N)],Es.prototype,"intensity",2),na([m(N)],Es.prototype,"color",2),na([kt(),m()],Es.prototype,"screenspaceRadius",2),na([kt(),m()],Es.prototype,"quality",2),rs("ScreenSpaceAmbientOcclusionN8",Es);var IA=Object.defineProperty,jA=Object.getOwnPropertyDescriptor,y1=(s,t,i,n)=>{for(var o=n>1?void 0:n?jA(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&IA(t,i,o),o};class jh extends at{constructor(){super(...arguments),a(this,"_effect"),a(this,"_amount",1),a(this,"_radius",1)}get typeName(){return"Sharpening"}onCreateEffect(){return this._effect??(this._effect=new(LA())),this.effect}get effect(){return this._effect}set amount(t){this._amount=t,this._effect&&(this._effect.uniforms.get("amount").value=t)}get amount(){return this._effect?this._effect.uniforms.get("amount").value:this._amount}set radius(t){this._radius=t,this._effect&&(this._effect.uniforms.get("radius").value=t)}get radius(){return this._effect?this._effect.uniforms.get("radius").value:this._radius}}y1([m()],jh.prototype,"amount",1),y1([m()],jh.prototype,"radius",1);function LA(){const s=`
1201
+ `)}l&&console.log(p);const f=new Set;for(const w of y){w.getPath||console.error("USDZExporter: Animation target object has no getPath method. This is likely a bug",w);let _=w.getPath();_.startsWith("<")&&(_=_.substring(1)),_.endsWith(">")&&(_=_.substring(0,_.length-1)),f.add({path:_,obj:w})}const v=Array.from(f).sort((w,_)=>w.path.length-_.path.length),b=new Array;for(let w=0;w<v.length;w++)for(let _=w+1;_<v.length;_++)if(v[_].path.startsWith(v[w].path)){const C=v[_],R=v[w];b.push({child:C.obj.displayName+" ("+C.path+")",parent:R.obj.displayName+" ("+R.path+")"})}b.length&&console.warn("USDZExporter: There are overlapping PlayAnimation actions. This can lead to undefined runtime behaviour when playing multiple animations. Please restructure the hierarchy so that animations don't overlap.",{overlappingTargets:b,playAnimationActions:r})}for(const p of new Set([...i,...n]))if(Array.isArray(p))for(const g of p)o.add(g.uuid);else o.add(p.uuid);cp&&console.log("All Behavior trigger sources and action targets",i,n,o),this.targetUuids=new Set(o)}onAfterHierarchy(t,i){var n;if((n=this.behaviours)!=null&&n.length){i.beginBlock('def Scope "Behaviors"');for(const o of this.behaviours)o.writeTo(this,t.document,i);i.closeBlock()}}async onAfterSerialize(t){cp&&console.log("onAfterSerialize behaviours",this.behaviourComponentsCopy);for(const i of this.behaviourComponentsCopy)typeof i.afterSerialize=="function"&&(i.afterSerialize.constructor.name==="AsyncFunction"?await i.afterSerialize(this,t):i.afterSerialize(this,t));for(const{clipUrl:i,filesKey:n}of this.audioClipsCopy){if(t.files[n])return;const o=await(await(await fetch(i)).blob()).arrayBuffer(),r=new Uint8Array(o);t.files[n]=r}this.behaviourComponentsCopy.length=0,this.audioClipsCopy.length=0}}var pT=Object.defineProperty,mT=Object.getOwnPropertyDescriptor,$e=(s,t,i,n)=>{for(var o=n>1?void 0:n?mT(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&pT(t,i,o),o};const zx=O("debugusdzbehaviours");function oh(s){s&&(s.getComponentInParent(Fc)||(F()&&console.debug('Raycaster on "'+s.name+'" was automatically added, because no raycaster was found in the parent hierarchy.'),s.addComponent(Ti)))}class $r extends A{constructor(){super(...arguments),a(this,"object"),a(this,"target"),a(this,"duration",1),a(this,"relativeMotion",!1),a(this,"coroutine",null),a(this,"targetPos",new x),a(this,"targetRot",new V),a(this,"targetScale",new x)}start(){oh(this.gameObject)}onPointerClick(t){t.use(),this.coroutine&&this.stopCoroutine(this.coroutine),this.relativeMotion?this.coroutine=this.startCoroutine(this.moveRelative()):this.coroutine=this.startCoroutine(this.moveToTarget())}*moveToTarget(){if(!this.target||!this.object)return;const t=ee(this.object).clone(),i=ee(this.target).clone(),n=Se(this.object).clone(),o=Se(this.target).clone(),r=Ke(this.object).clone(),l=Ke(this.target).clone(),c=t.distanceTo(i),h=n.angleTo(o),d=r.distanceTo(l);if(c<.01&&h<.01&&d<.01){lt(this.object,i),qi(this.object,o),Oa(this.object,l),this.coroutine=null;return}let u=0,p=0;for(;u<1;)u+=this.context.time.deltaTime/this.duration,u>1&&(u=1),p=u<.5?4*u*u*u:1-Math.pow(-2*u+2,3)/2,this.targetPos.lerpVectors(t,i,p),this.targetRot.slerpQuaternions(n,o,p),this.targetScale.lerpVectors(r,l,p),lt(this.object,this.targetPos),qi(this.object,this.targetRot),Oa(this.object,this.targetScale),yield;this.coroutine=null}*moveRelative(){if(!this.target||!this.object)return;const t=this.object.position.clone(),i=this.object.quaternion.clone(),n=this.object.scale.clone(),o=this.target.position.clone(),r=this.target.quaternion.clone(),l=this.target.scale.clone();o.applyQuaternion(this.object.quaternion),this.targetPos.copy(this.object.position).add(o),this.targetRot.copy(this.object.quaternion).multiply(r),this.targetScale.copy(this.object.scale).multiply(l);let c=0,h=0;for(;c<1;)c+=this.context.time.deltaTime/this.duration,c>1&&(c=1),h=c<.5?4*c*c*c:1-Math.pow(-2*c+2,3)/2,this.object.position.lerpVectors(t,this.targetPos,h),this.object.quaternion.slerpQuaternions(i,this.targetRot,h),this.object.scale.lerpVectors(n,this.targetScale,h),yield;this.coroutine=null}beforeCreateDocument(t){var i;if(this.target&&this.object&&this.gameObject){const n=new bt("Move to "+((i=this.target)==null?void 0:i.name),_t.tapTrigger(this.gameObject),ue.transformAction(this.object,this.target,this.duration,this.relativeMotion?"relative":"absolute"));t.addBehavior(n)}}}$e([m(j)],$r.prototype,"object",2),$e([m(j)],$r.prototype,"target",2),$e([m()],$r.prototype,"duration",2),$e([m()],$r.prototype,"relativeMotion",2);var dp;const sn=(dp=class extends A{constructor(){super(...arguments),a(this,"materialToSwitch"),a(this,"variantMaterial"),a(this,"fadeDuration",0),a(this,"_objectsWithThisMaterial",null),a(this,"selfModel"),a(this,"targetModels")}start(){var s;this._objectsWithThisMaterial=this.objectsWithThisMaterial,oh(this.gameObject),F()&&this._objectsWithThisMaterial.length<=0&&console.warn('ChangeMaterialOnClick: No objects found with material "'+((s=this.materialToSwitch)==null?void 0:s.name)+'"')}onPointerEnter(s){this.context.input.setCursorPointer()}onPointerExit(s){this.context.input.setCursorNormal()}onPointerClick(s){if(s.use(),!!this.variantMaterial)for(let t=0;t<this.objectsWithThisMaterial.length;t++){const i=this.objectsWithThisMaterial[t];i.material=this.variantMaterial}}get objectsWithThisMaterial(){return this._objectsWithThisMaterial!=null?this._objectsWithThisMaterial:(this._objectsWithThisMaterial=[],this.variantMaterial&&this.materialToSwitch&&this.context.scene.traverse(s=>{if(s instanceof Q)if(Array.isArray(s.material)){for(const t of s.material)if(t===this.materialToSwitch){this.objectsWithThisMaterial.push(s);break}}else s.material===this.materialToSwitch?this.objectsWithThisMaterial.push(s):g_(s.material,this.materialToSwitch)&&this.objectsWithThisMaterial.push(s)}),this._objectsWithThisMaterial)}async beforeCreateDocument(s,t){this.targetModels=[],sn._materialTriggersPerId={},sn.variantSwitchIndex=0,this.materialToSwitch&&await et.assignTextureLOD(this.materialToSwitch,0),this.variantMaterial&&await et.assignTextureLOD(this.variantMaterial,0)}createBehaviours(s,t,i){this.objectsWithThisMaterial.find(n=>n.uuid===t.uuid)&&this.targetModels.push(t),this.gameObject.uuid===t.uuid&&(this.selfModel=t,this.materialToSwitch&&(sn._materialTriggersPerId[this.materialToSwitch.uuid]||(sn._materialTriggersPerId[this.materialToSwitch.uuid]=[]),sn._materialTriggersPerId[this.materialToSwitch.uuid].push(this)))}afterCreateDocument(s,t){if(!this.materialToSwitch)return;const i=sn._materialTriggersPerId[this.materialToSwitch.uuid];if(i){const n={};for(const o of i){const r=o.createVariants();r&&r.length>0&&(n[o.selfModel.uuid]=r)}for(const o of i){const r=[];for(const l in n)l!==o.selfModel.uuid&&r.push(...n[l]);o.createAndAttachBehaviors(s,n[o.selfModel.uuid],r)}}delete sn._materialTriggersPerId[this.materialToSwitch.uuid]}createAndAttachBehaviors(s,t,i){const n=[],o=[],r=Math.max(0,this.fadeDuration);o.push(ue.fadeAction([...this.targetModels,...i],r,!1)),n.push(ue.fadeAction(t,r,!1)),o.push(ue.fadeAction(t,r,!0)),s.addBehavior(new bt("Select_"+this.selfModel.name,_t.tapTrigger(this.selfModel),ue.parallel(...o))),s.addBehavior(new bt("StartHidden_"+this.selfModel.name,_t.sceneStartTrigger(),ue.parallel(...n)))}static getMaterialName(s){return Ms(s.name||"Material")+"_"+s.id}createVariants(){if(!this.variantMaterial)return null;const s=[];for(const t of this.targetModels){const i=t.clone();i.name+="_Variant_"+sn.variantSwitchIndex+++"_"+sn.getMaterialName(this.variantMaterial),i.displayName=i.displayName+": Variant with material "+this.variantMaterial.name,i.material=this.variantMaterial,i.geometry=t.geometry,i.transform=t.transform,(!t.parent||!t.parent.isEmpty())&&Zt.createEmptyParent(t),t.parent&&t.parent.add(i),s.push(i)}return s}},a(dp,"_materialTriggersPerId",{}),a(dp,"variantSwitchIndex",0),dp);let ml=sn;$e([m(Oe)],ml.prototype,"materialToSwitch",2),$e([m(Oe)],ml.prototype,"variantMaterial",2),$e([m()],ml.prototype,"fadeDuration",2);var gl;const qe=(gl=class extends A{constructor(){super(...arguments),a(this,"target"),a(this,"toggleOnClick",!1),a(this,"targetState",!0),a(this,"hideSelf",!0),a(this,"selfModel"),a(this,"selfModelClone"),a(this,"targetModel"),a(this,"toggleModel"),a(this,"stateBeforeCreatingDocument",!1),a(this,"targetStateBeforeCreatingDocument",!1)}start(){oh(this.gameObject)}onPointerClick(s){s.use(),!this.toggleOnClick&&this.hideSelf&&(this.gameObject.visible=!1),this.target&&(this.target.visible=this.toggleOnClick?!this.target.visible:this.targetState)}createBehaviours(s,t,i){t.uuid===this.gameObject.uuid&&(this.selfModel=t,this.selfModelClone=t.clone())}beforeCreateDocument(){this.target&&(this.gameObject[qe.wasVisible]===void 0&&(this.gameObject[qe.wasVisible]=this.gameObject.activeSelf),this.target[qe.wasVisible]===void 0&&(this.target[qe.wasVisible]=this.target.activeSelf),this.stateBeforeCreatingDocument=this.gameObject[qe.wasVisible],this.targetStateBeforeCreatingDocument=this.target[qe.wasVisible],this.gameObject.visible=!0,this.target.visible=!0)}afterCreateDocument(s,t){if(!this.target)return;this.targetModel=t.document.findById(this.target.uuid);const i=this.selfModel;if(this.selfModel&&this.targetModel){let n=this.selfModel,o=this.targetState;if(this.toggleOnClick)if(o=!this.targetStateBeforeCreatingDocument,!this.selfModelClone.geometry)(!this.selfModel.parent||this.selfModel.parent.isEmpty())&&Jf.createEmptyParent(this.selfModel),this.toggleModel=this.selfModel.deepClone(),this.toggleModel.name+="_toggle",this.selfModel.parent.add(this.toggleModel);else{if(!this.gameObject[qe.toggleClone]){const c=this.selfModelClone.clone();c.setMatrix(new ne),c.name+="_toggle"+qe.clonedToggleIndex++,i.add(c),this.gameObject[qe.toggleClone]=c,console.warn("USDZExport: Toggle "+this.gameObject.name+" doesn't have geometry. It will be deep cloned and nested behaviours will likely not work.")}const l=this.gameObject[qe.toggleClone];if(!this.gameObject[qe.reverseToggleClone]){const c=this.selfModelClone.clone();c.setMatrix(new ne),c.name+="_toggleReverse"+qe.clonedToggleIndex++,i.add(c),this.gameObject[qe.reverseToggleClone]=c}this.toggleModel=this.gameObject[qe.reverseToggleClone],(!this.toggleModel.geometry||!l.geometry)&&console.error("triggers without childs and without geometry won't work!",this,i.geometry),n=l,i.geometry=null,i.material=null}if(this.toggleModel){if(this.toggleOnClick){const l=[];l.push(ue.fadeAction(n,0,!1)),l.push(ue.fadeAction(this.toggleModel,0,!0)),l.push(ue.fadeAction(this.targetModel,0,o)),s.addBehavior(new bt("Toggle_"+n.name+"_toggleTo"+(o?"On":"Off"),_t.tapTrigger(n),ue.parallel(...l)));const c=[];c.push(ue.fadeAction(this.toggleModel,0,!1)),c.push(ue.fadeAction(n,0,!0)),c.push(ue.fadeAction(this.targetModel,0,!o)),s.addBehavior(new bt("Toggle_"+n.name+"_toggleTo"+(o?"Off":"On"),_t.tapTrigger(this.toggleModel),ue.parallel(...c)))}}else{const l=[];this.hideSelf&&l.push(ue.fadeAction(n,0,!1)),l.push(ue.fadeAction(this.targetModel,0,o)),s.addBehavior(new bt("Toggle_"+n.name+"_toggleTo"+(o?"On":"Off"),_t.tapTrigger(n),ue.parallel(...l)))}const r=new Array;this.targetStateBeforeCreatingDocument||r.push(this.targetModel),this.stateBeforeCreatingDocument||r.push(i),this.toggleModel&&r.push(this.toggleModel),s.addBehavior(new bt("HideOnStart_"+this.gameObject.name,_t.sceneStartTrigger(),ue.fadeAction(r,0,!1)))}}afterSerialize(s,t){this.gameObject[qe.wasVisible]!==void 0&&(this.gameObject.visible=this.gameObject[qe.wasVisible],delete this.gameObject[qe.wasVisible]),this.target&&this.target[qe.wasVisible]!==void 0&&(this.target.visible=this.target[qe.wasVisible],delete this.target[qe.wasVisible]),delete this.gameObject[qe.toggleClone],delete this.gameObject[qe.reverseToggleClone]}},a(gl,"clonedToggleIndex",0),a(gl,"wasVisible",Symbol("usdz_SetActiveOnClick_wasVisible")),a(gl,"toggleClone",Symbol("clone for toggling")),a(gl,"reverseToggleClone",Symbol("clone for reverse toggling")),gl);let qr=qe;$e([m(j)],qr.prototype,"target",2),$e([m()],qr.prototype,"toggleOnClick",2),$e([m()],qr.prototype,"targetState",2),$e([m()],qr.prototype,"hideSelf",2);class u0 extends A{constructor(){super(...arguments),a(this,"wasVisible",!1)}start(){P.setActive(this.gameObject,!1)}createBehaviours(t,i,n){i.uuid===this.gameObject.uuid&&(this.wasVisible||t.addBehavior(new bt("HideOnStart_"+this.gameObject.name,_t.sceneStartTrigger(),ue.fadeAction(i,0,!1))))}beforeCreateDocument(){this.wasVisible=P.isActiveSelf(this.gameObject)}}class fl extends A{constructor(){super(...arguments),a(this,"target"),a(this,"duration",.5),a(this,"motionType","bounce")}beforeCreateDocument(){}createBehaviours(t,i,n){if(this.target&&i.uuid===this.gameObject.uuid){const o=new bt("emphasize "+this.name,_t.tapTrigger(this.gameObject),ue.emphasize(this.target,this.duration,this.motionType,void 0,"basic"));t.addBehavior(o)}}afterCreateDocument(t,i){}}$e([m()],fl.prototype,"target",2),$e([m()],fl.prototype,"duration",2),$e([m()],fl.prototype,"motionType",2);class jo extends A{constructor(){super(...arguments),a(this,"target"),a(this,"clip",""),a(this,"toggleOnClick",!1),a(this,"trigger","tap")}start(){oh(this.gameObject)}ensureAudioSource(){if(!this.target){const t=this.gameObject.addComponent(We);t&&(this.target=t,t.spatialBlend=1,t.volume=1,t.loop=!1,t.preload=!0)}}onPointerClick(t){var i;t.use(),!(!((i=this.target)!=null&&i.clip)&&!this.clip)&&(this.ensureAudioSource(),this.target&&(this.target.isPlaying&&this.toggleOnClick?this.target.stop():(!this.toggleOnClick&&this.target.isPlaying&&this.target.stop(),this.clip?this.target.play(this.clip):this.target.play())))}createBehaviours(t,i,n){if(!(!this.target&&!this.clip)&&i.uuid===this.gameObject.uuid){const o=this.clip?this.clip:this.target?this.target.clip:void 0;if(!o||typeof o!="string")return;const r=this.target?this.target.gameObject:this.gameObject;lr.getName(o);const l=this.target?this.target.volume:1,c=this.target&&this.target.spatialBlend==0?"nonSpatial":"spatial";let h=!1;this.gameObject.traverse(g=>{g instanceof Q&&g.visible&&(h=!0)}),h=!0;const d=t.addAudioClip(o);let u=ue.playAudioAction(r,d,"play",l,c);this.target&&this.target.loop&&(u=ue.sequence(u).makeLooping());const p=this.name?"_"+this.name:"";if(h&&this.trigger==="tap"){this.toggleOnClick&&(u.multiplePerformOperation="stop");const g=new bt("playAudio"+p,_t.tapTrigger(i),u);t.addBehavior(g)}if(this.target&&this.target.playOnAwake&&this.target.enabled)if(h&&this.trigger==="tap")console.warn("USDZExport: Audio sources that are played on tap can't also auto-play at scene start due to a QuickLook bug.");else{const g=new bt("playAudioOnStart"+p,_t.sceneStartTrigger(),u);t.addBehavior(g)}}}}$e([m(We)],jo.prototype,"target",2),$e([m(URL)],jo.prototype,"clip",2),$e([m()],jo.prototype,"toggleOnClick",2);var up;const nn=(up=class extends A{constructor(){super(...arguments),a(this,"animator"),a(this,"stateName"),a(this,"trigger","tap"),a(this,"animation"),a(this,"selfModel"),a(this,"stateAnimationModel"),a(this,"animationSequence",new Array),a(this,"animationLoopAfterSequence",new Array),a(this,"randomOffsetNormalized",0)}get target(){var s,t;return((s=this.animator)==null?void 0:s.gameObject)||((t=this.animation)==null?void 0:t.gameObject)}start(){oh(this.gameObject)}onPointerClick(s){var t;s.use(),this.target&&this.stateName&&((t=this.animator)==null||t.play(this.stateName,0,0,.1))}createBehaviours(s,t,i){t.uuid===this.gameObject.uuid&&(this.selfModel=t)}afterSerialize(){if(nn.rootsWithExclusivePlayback.size>1){const s='Multiple root objects targeted by more than one animation. To work around QuickLook bug FB13410767, animations will be set as "exclusive" and activating them will stop other animations being marked as exclusive.';F()&&_e(s),console.warn(s,...nn.rootsWithExclusivePlayback)}nn.animationActions=[],nn.rootsWithExclusivePlayback=new Set}afterCreateDocument(s,t){if(this.animationSequence===void 0&&this.animationLoopAfterSequence===void 0||!this.stateAnimationModel||!this.target)return;const i=t.document,n=t.extensions.find(l=>l instanceof nh);if(!n)return;const o=n.getClipCount(this.target)>1;o&&(F()&&console.warn("Setting exclusive playback for "+this.target.name+"@"+this.stateName+" because it has "+n.getClipCount(this.target)+" animations. This works around QuickLook bug FB13410767."),nn.rootsWithExclusivePlayback.add(this.target));const r=this.name?this.name:"";i.traverse(l=>{var c,h;if(l.uuid===((c=this.target)==null?void 0:c.uuid)){const d=nn.getActionForSequences(i,l,this.animationSequence,this.animationLoopAfterSequence,this.randomOffsetNormalized),u=new bt(this.trigger+"_"+r+"_toPlayAnimation_"+this.stateName+"_on_"+((h=this.target)==null?void 0:h.name),this.trigger=="tap"?_t.tapTrigger(this.selfModel):_t.sceneStartTrigger(),d);o&&u.makeExclusive(!0),s.addBehavior(u)}})}static getActionForSequences(s,t,i,n,o){const r=(c,h)=>{let d=nn.animationActions.find(u=>u.affectedObjects==c&&u.start==h.start&&u.duration==h.duration&&u.animationSpeed==h.speed);return d||(d=ue.startAnimationAction(c,h),nn.animationActions.push(d)),d},l=ue.sequence();if(i&&i.length>0)for(const c of i)l.addAction(r(t,c));if(n&&n.length>0){const c=l.actions.length==0?l:ue.sequence();for(const h of n)c.addAction(r(t,h));c.makeLooping(),l!==c&&l.addAction(c)}return o&&o>0&&l.actions.unshift(ue.waitAction(o)),l}static getAndRegisterAnimationSequences(s,t,i){var n,o,r,l,c,h,d,u;if(!t)return;const p=t.getComponent(Pt),g=t.getComponent(Ut);if(!p&&!g)return;if(p&&!i)throw new Error("PlayAnimationOnClick: No stateName specified for animator "+p.name+" on "+t.name);let y=[],f=[];if(g){const M=s.registerAnimation(t,g.clip);M&&(g.loop?f.push(M):y.push(M));let E=0;if(g.minMaxOffsetNormalized){const D=g.minMaxOffsetNormalized.x,L=g.minMaxOffsetNormalized.y;E=(((n=g.clip)==null?void 0:n.duration)||1)*(D+Math.random()*(L-D))}return{animationSequence:y,animationLoopAfterSequence:f,randomTimeOffset:E}}const v=p?.runtimeAnimatorController;let b=v?.findState(i),w=[],_=[];if(v&&b){const M=new Array;M.push(b);let E=!1;for(;M.length<100;){if(!b||b===null||!b.transitions||b.transitions.length===0){(o=b.motion)!=null&&o.isLooping&&(E=!0);break}const D=b.transitions.find(U=>U.conditions.length===0),L=D?v.getState(D.destinationState,0):null;if(L&&M.includes(L)){b=L,E=!0;break}else if(D){if(b=L,!b)break;M.push(b)}else{E=((r=b.motion)==null?void 0:r.isLooping)??!1;break}}if(E&&b){const D=M.indexOf(b);w=M.slice(0,D),_=M.slice(D),zx&&console.log("found loop from "+i,"states until loop",w,"states looping",_)}else w=M,_=[],zx&&console.log("found no loop from "+i,"states",w);if(!_.length){const D=w[w.length-1],L=(l=D.motion)==null?void 0:l.clip;if(L){let U;if(s.holdClipMap.has(L))U=s.holdClipMap.get(L);else{const z=D.name+"_hold";U=L.clone(),U.duration=1,U.name=z;const H=L.duration;U.tracks=L.tracks.map(T=>{const I=T.clone();I.times=new Float32Array([0,H]);const G=T.values.length,J=T.getValueSize(),se=T.values.slice(G-J,G);return I.values=new Float32Array(2*J),I.values.set(se,0),I.values.set(se,J),I}),U.name=z,s.holdClipMap.set(L,U)}if(U){const z={name:U.name,motion:{clip:U,isLooping:!1,name:U.name},speed:1,transitions:[],behaviours:[],hash:D.hash+1};_.push(z)}}}}if(w.length===1&&(!((c=w[0].motion)!=null&&c.clip)||((d=(h=w[0].motion)==null?void 0:h.clip.tracks)==null?void 0:d.length)===0)){y=new Array;const M=s.registerAnimation(t,null);M&&y.push(M);return}if(w=w.filter(M=>{var E,D,L;return((E=M.motion)==null?void 0:E.clip)&&((L=(D=M.motion)==null?void 0:D.clip.tracks)==null?void 0:L.length)>0}),_=_.filter(M=>{var E,D,L;return((E=M.motion)==null?void 0:E.clip)&&((L=(D=M.motion)==null?void 0:D.clip.tracks)==null?void 0:L.length)>0}),w.length===0&&_.length===0){console.warn("No clips found for state "+i+" on "+p?.name+", can't export animation data");return}const C=(M,E)=>{if(!t)return;const D=s.registerAnimation(t,M.motion.clip??null);D?(D.speed=M.speed,E.push(D)):console.warn("Couldn't register animation for state "+M.name+" on "+p?.name)};if(w.length>0){y=new Array;for(const M of w)C(M,y)}if(_.length>0){f=new Array;for(const M of _)C(M,f)}let R=0;if(p&&v&&p.minMaxOffsetNormalized){const M=p.minMaxOffsetNormalized.x,E=p.minMaxOffsetNormalized.y,D=w.length?w[0]:_.length?_[0]:null;R=(((u=D?.motion.clip)==null?void 0:u.duration)||1)*(M+Math.random()*(E-M))}return{animationSequence:y,animationLoopAfterSequence:f,randomTimeOffset:R}}createAnimation(s,t,i){if(!this.target||!this.animator&&!this.animation)return;const n=nn.getAndRegisterAnimationSequences(s,this.target,this.stateName);n&&(this.animationSequence=n.animationSequence,this.animationLoopAfterSequence=n.animationLoopAfterSequence,this.randomOffsetNormalized=n.randomTimeOffset,this.stateAnimationModel=t)}},a(up,"animationActions",[]),a(up,"rootsWithExclusivePlayback",new Set),up);let Gr=nn;$e([m(Pt)],Gr.prototype,"animator",2),$e([m()],Gr.prototype,"stateName",2);class yl extends A{constructor(){super(...arguments),a(this,"target")}getType(){}getDuration(){}}$e([m(j)],yl.prototype,"target",2);class rh extends A{constructor(){super(...arguments),a(this,"target")}}$e([m(yl)],rh.prototype,"target",2);class ah extends yl{constructor(){super(...arguments),a(this,"type",1),a(this,"duration",1)}getType(){switch(this.type){case 1:return"hide";case 0:return"show"}}getDuration(){return this.duration}}$e([m()],ah.prototype,"type",2),$e([m()],ah.prototype,"duration",2);class p0 extends rh{}class pp{get extensionName(){return"Physics"}onExportObject(t,i,n){const o=P.getComponents(t,ye).filter(h=>h.enabled),r=P.getComponents(t,hi).filter(h=>h.enabled&&!h.isTrigger);let l=o.length>0?o[0]:null;const c=r.length>0?r[0]:null;c&&!l&&(l=new ye,l.isKinematic=!0),l&&i.addEventListener("serialize",(h,d)=>{var u,p,g;if(l){if(h.appendLine(),h.beginBlock('def RealityKitComponent "RigidBody"',"{",!0),l.useGravity||h.appendLine("bool gravityEnabled = 0"),h.appendLine('uniform token info:id = "RealityKit.RigidBody"'),l.isKinematic&&h.appendLine('token motionType = "Kinematic"'),h.beginBlock('def RealityKitStruct "massFrame"',"{",!0),h.appendLine(`float m_mass = ${l.mass}`),h.beginBlock('def RealityKitStruct "m_pose"',"{",!0),h.appendLine(`float3 position = (${l.centerOfMass.x}, ${l.centerOfMass.y}, ${l.centerOfMass.z})`),h.closeBlock("}"),h.closeBlock("}"),r.length>0){const y=r[0];h.beginBlock('def RealityKitStruct "material"',"{",!0);const f=y.sharedMaterial;f&&f.dynamicFriction!==void 0&&h.appendLine(`double dynamicFriction = ${(u=y.sharedMaterial)==null?void 0:u.dynamicFriction}`),f&&f.bounciness!==void 0&&h.appendLine(`double restitution = ${(p=y.sharedMaterial)==null?void 0:p.bounciness}`),f&&f.staticFriction!==void 0&&h.appendLine(`double staticFriction = ${(g=y.sharedMaterial)==null?void 0:g.staticFriction}`),h.closeBlock("}")}h.closeBlock("}")}}),c&&(i.addEventListener("serialize",(h,d)=>{var u;h.beginBlock('def RealityKitComponent "Collider"',"{",!0),h.appendLine("uint group = 1"),h.appendLine('uniform token info:id = "RealityKit.Collider"'),h.appendLine("uint mask = 4294967295");const p=c.isTrigger?"Trigger":"Default";if(h.appendLine(`token type = "${p}"`),h.beginBlock('def RealityKitStruct "Shape"',"{",!0),c instanceof Za){const g=c;h.appendLine('token shapeType = "Sphere"'),h.appendLine(`float radius = ${g.radius}`)}else if(c instanceof Ja){const g=c;h.appendLine('token shapeType = "Box"'),h.appendLine(`float3 extent = (${g.size.x}, ${g.size.y}, ${g.size.z})`)}else if(c instanceof In){const g=c;h.appendLine('token shapeType = "Capsule"'),h.appendLine(`float radius = ${g.radius}`),h.appendLine(`float height = ${g.height}`)}else if(c instanceof Eo&&(u=c.sharedMesh)!=null&&u.geometry){const g=c.sharedMesh.geometry;g.boundingBox||g.computeBoundingBox();const y=c.sharedMesh.geometry.boundingBox;y&&(h.appendLine('token shapeType = "Box"'),h.appendLine(`float3 extent = (${y.max.x-y.min.x}, ${y.max.y-y.min.y}, ${y.max.z-y.min.z})`),console.log("[USDZ] Only Box, Sphere, and Capsule colliders are supported in visionOS/iOS. MeshCollider will be exported as Box",c))}else console.warn("[USDZ] Only Box, Sphere, and Capsule colliders are supported in visionOS/iOS. Ignoring collider:",c);h.beginBlock('def RealityKitStruct "pose"',"{",!0),h.closeBlock("}"),h.closeBlock("}"),h.closeBlock("}")}),r.length>1&&console.log("WARNING: Multiple colliders detected. visionOS / iOS can only support objects with a single collider, only exporting the first collider: ",c))}}class m0{get extensionName(){return"DocumentExtension"}onAfterBuildDocument(t){}}var gT=Object.defineProperty,fT=Object.getOwnPropertyDescriptor,lh=(s,t,i,n)=>{for(var o=n>1?void 0:n?fT(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&gT(t,i,o),o};const g0=O("debugui"),f0=O("debuguilayout");class y0{constructor(){a(this,"width"),a(this,"height")}}class v0{constructor(){a(this,"x"),a(this,"y"),a(this,"width"),a(this,"height")}}const Rs=new x,ch=new ne,mp=new V,Ux=class extends ls{constructor(){super(...arguments),a(this,"_anchoredPosition"),a(this,"sizeDelta",new oe(100,100)),a(this,"pivot",new oe(.5,.5)),a(this,"anchorMin",new oe(0,0)),a(this,"anchorMax",new oe(1,1)),a(this,"minWidth"),a(this,"minHeight"),a(this,"lastMatrix"),a(this,"rectBlock"),a(this,"_transformNeedsUpdate",!1),a(this,"_initialPosition"),a(this,"_parentRectTransform"),a(this,"_lastUpdateFrame",-1),a(this,"_lastAnchoring"),a(this,"_createdBlocks",[]),a(this,"_createdTextBlocks",[])}get parent(){return this._parentRectTransform}get translation(){return this.gameObject.position}get rotation(){return this.gameObject.quaternion}get scale(){return this.gameObject.scale}get anchoredPosition(){return this._anchoredPosition||(this._anchoredPosition=new oe),this._anchoredPosition}set anchoredPosition(s){this._anchoredPosition=s}get width(){let s=this.sizeDelta.x;if(this.anchorMin.x!==this.anchorMax.x&&this._parentRectTransform){const t=this._parentRectTransform.width,i=this.anchorMax.x-this.anchorMin.x;s=t*i,s+=this.sizeDelta.x}return this.minWidth!==void 0&&s<this.minWidth?this.minWidth:s}get height(){let s=this.sizeDelta.y;if(this.anchorMin.y!==this.anchorMax.y&&this._parentRectTransform){const t=this._parentRectTransform.height,i=this.anchorMax.y-this.anchorMin.y;s=t*i,s+=this.sizeDelta.y}return this.minHeight!==void 0&&s<this.minHeight?this.minHeight:s}awake(){super.awake(),this._anchoredPosition||(this._anchoredPosition=new oe),this.lastMatrix=new ne,this.rectBlock=new j,this.rectBlock.name=this.name,this._initialPosition=this.gameObject.position.clone(),this._initialPosition.z=0,Xa(this,"_anchoredPosition",()=>{this.markDirty()}),Xa(this,"sizeDelta",()=>{this.markDirty()}),Xa(this,"pivot",()=>{this.markDirty()}),Xa(this,"anchorMin",()=>{this.markDirty()}),Xa(this,"anchorMax",()=>{this.markDirty()})}onEnable(){var s;super.onEnable(),this.rectBlock||(this.rectBlock=new j),this.lastMatrix||(this.lastMatrix=new ne),this._lastAnchoring||(this._lastAnchoring=new oe),this._initialPosition||(this._initialPosition=new x),this._anchoredPosition||(this._anchoredPosition=new oe),this.addShadowComponent(this.rectBlock),this._transformNeedsUpdate=!0,(s=this.canvas)==null||s.registerTransform(this)}onDisable(){var s;super.onDisable(),this.removeShadowComponent(),(s=this.canvas)==null||s.unregisterTransform(this)}onParentRectTransformChanged(s){this._transformNeedsUpdate||this.onApplyTransform(f0?`${s.name} changed`:void 0)}get isDirty(){return this._transformNeedsUpdate||(this._transformNeedsUpdate=!this.lastMatrix.equals(this.gameObject.matrix)),this._transformNeedsUpdate}markDirty(){this._transformNeedsUpdate||(f0&&console.warn("RectTransform markDirty()",this.name),this._transformNeedsUpdate=!0,this._lastUpdateFrame=-1)}updateTransform(){(this._transformNeedsUpdate||!this.lastMatrix.equals(this.gameObject.matrix))&&this.canUpdate()&&this.onApplyTransform(this._transformNeedsUpdate?"Marked dirty":"Matrix changed")}canUpdate(){return this._transformNeedsUpdate&&this.activeAndEnabled&&this._lastUpdateFrame!==this.context.time.frame}onApplyTransform(s){var t;if(this.context.time.frameCount===this._lastUpdateFrame)return;this._lastUpdateFrame=this.context.time.frameCount;const i=this.shadowComponent;if(!i)return;this.gameObject.parent?this._parentRectTransform=P.getComponentInParent(this.gameObject.parent,Ux):this._parentRectTransform=void 0,this._transformNeedsUpdate=!1,f0&&console.warn("RectTransform \u2192 ApplyTransform",this.name+" because "+s),this.isRoot()?this.Root.screenspace||(i.rotation.y=Math.PI):(i.matrix.identity(),i.matrixAutoUpdate=!1,Rs.set(0,0,0),this.applyPivot(Rs),i.matrix.setPosition(Rs.x,Rs.y,0),(this.gameObject.quaternion.x||this.gameObject.quaternion.y||this.gameObject.quaternion.z)&&(mp.copy(this.gameObject.quaternion),mp.x*=-1,mp.z*=-1,ch.makeRotationFromQuaternion(mp),i.matrix.premultiply(ch)),Rs.set(0,0,0),this.applyAnchoring(Rs),(t=this.canvas)!=null&&t.screenspace?Rs.z+=.1:Rs.z+=.01,ch.identity(),ch.setPosition(Rs.x,Rs.y,Rs.z),i.matrix.premultiply(ch),i.matrix.scale(this.gameObject.scale)),this.lastMatrix.copy(this.gameObject.matrix);const n=!0;for(const o of eu(this.gameObject,ls,n,1)){if(o===this||!o.activeAndEnabled)continue;const r=o;r.onParentRectTransformChanged&&r.onParentRectTransformChanged(this)}}applyAnchoring(s){this._lastAnchoring||(this._lastAnchoring=new oe);const t=this._lastAnchoring.sub(this._anchoredPosition);this.gameObject.position.x+=t.x,this.gameObject.position.y+=t.y,this._lastAnchoring.copy(this._anchoredPosition),s.x+=this._initialPosition.x-this.gameObject.position.x,s.y+=this._initialPosition.y-this.gameObject.position.y,s.z+=this._initialPosition.z-this.gameObject.position.z;const i=this._parentRectTransform;if(i){let n=0;const o=1-this.anchorMax.y-this.anchorMin.y;n-=i.height*.5*o,s.y+=n;let r=0;const l=1-this.anchorMax.x-this.anchorMin.x;r-=i.width*.5*l,s.x+=r}}applyPivot(s){if(this.pivot&&!this.isRoot()){const t=this.pivot.x-.5;s.x-=t*this.sizeDelta.x*this.gameObject.scale.x;const i=this.pivot.y-.5;s.y-=i*this.sizeDelta.y*this.gameObject.scale.y}}getBasicOptions(){const s={width:this.sizeDelta.x,height:this.sizeDelta.y,offset:0,backgroundOpacity:0,borderWidth:0,borderRadius:0,borderOpacity:0,letterSpacing:-.03};return this.ensureValidSize(s),s}ensureValidSize(s,t=1e-4){return s.width<=0&&(s.width=t),s.height<=0&&(s.height=1e-4),s}createNewBlock(s){s={...this.getBasicOptions(),...s},g0&&console.log(this.name,s);const t=new bv(s);return this._createdBlocks.push(t),t}createNewText(s){g0&&console.log(s),s={...this.getBasicOptions(),...s},g0&&console.log(this.name,s);const t=new vv(s);return this._createdTextBlocks.push(t),t}};let Wt=Ux;lh([m(oe)],Wt.prototype,"anchoredPosition",1),lh([m(oe)],Wt.prototype,"sizeDelta",2),lh([m(oe)],Wt.prototype,"pivot",2),lh([m(oe)],Wt.prototype,"anchorMin",2),lh([m(oe)],Wt.prototype,"anchorMax",2);var yT=Object.defineProperty,vT=Object.getOwnPropertyDescriptor,Nx=(s,t,i,n)=>{for(var o=n>1?void 0:n?vT(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&yT(t,i,o),o};class vl extends A{constructor(){super(...arguments),a(this,"effectColor"),a(this,"effectDistance")}}Nx([m(we)],vl.prototype,"effectColor",2),Nx([m(oe)],vl.prototype,"effectDistance",2);var bT=Object.defineProperty,_T=Object.getOwnPropertyDescriptor,Wx=(s,t,i,n)=>{for(var o=n>1?void 0:n?_T(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&bT(t,i,o),o};const gp={backgroundColor:new ae(1,1,1),backgroundOpacity:1,borderColor:new ae(1,1,1),borderOpacity:1};var b0;const hh=(b0=class extends ls{constructor(){super(...arguments),a(this,"_alphaFactor",1),a(this,"sRGBColor",new ae(1,0,1)),a(this,"raycastTarget",!0),a(this,"uiObject",null),a(this,"_color",null),a(this,"_rect",null),a(this,"_stateManager",null),a(this,"_currentlyCreatingPanel",!1)}get isGraphic(){return!0}get color(){return this._color||(this._color=new we(1,1,1,1)),this._color}set color(s){(!this._color||this._color.r!==s.r||this._color.g!==s.g||this._color.b!==s.b||this._color.alpha!==s.alpha)&&(this._color||(this._color=new we(1,1,1,1)),this._color.copy(s),this.onColorChanged())}setAlphaFactor(s){this._alphaFactor=s,this.onColorChanged()}get alphaFactor(){return this._alphaFactor}onColorChanged(){this.uiObject&&(this.sRGBColor.copy(this._color),this.sRGBColor.convertLinearToSRGB(),gp.backgroundColor=this.sRGBColor,gp.backgroundOpacity=this._color.alpha*this._alphaFactor,this.applyEffects(gp,this._alphaFactor),this.uiObject.set(gp),this.markDirty())}get m_Color(){return this._color}get rectTransform(){if(this._rect||(this._rect=P.getComponent(this.gameObject,Wt)),!this._rect)throw new Error("Not Supported: Make sure to add a RectTransform component before adding a UI Graphic component.");return this._rect}onParentRectTransformChanged(){var s;(s=this.uiObject)==null||s.set({width:this.rectTransform.width,height:this.rectTransform.height}),this.markDirty()}__internalNewInstanceCreated(s){return super.__internalNewInstanceCreated(s),this._rect=null,this.uiObject=null,this._color&&(this._color=this._color.clone()),this}setState(s){this.makePanel(),this.uiObject&&(this.uiObject.setState(s),this==null||this.markDirty())}setupState(s){this.makePanel(),this.uiObject&&(this._stateManager||(this._stateManager=new lO(this.uiObject)),this.uiObject.setupState(s.state,s.attributes))}setOptions(s){this.makePanel(),this.uiObject&&this.uiObject.set(s)}awake(){super.awake(),this.makePanel(),Xa(this,"_color",()=>yM(this,this.onColorChanged))}onEnable(){var s;super.onEnable(),this.uiObject&&((s=this.rectTransform.shadowComponent)==null||s.add(this.uiObject),this.addShadowComponent(this.uiObject,this.rectTransform))}onDisable(){super.onDisable(),this.uiObject&&this.removeShadowComponent()}makePanel(){if(this.uiObject||this._currentlyCreatingPanel)return;this._currentlyCreatingPanel=!0;const s=.015,t={backgroundColor:this.color,backgroundOpacity:this.color.alpha,offset:s};this.onBeforeCreate(t),this.applyEffects(t),this.onCreate(t),this.controlsChildLayout=!1,this._currentlyCreatingPanel=!1,this.onAfterCreated(),this.onColorChanged()}onBeforeCreate(s){}onCreate(s){this.uiObject=this.rectTransform.createNewBlock(s),this.uiObject.name=this.name}onAfterCreated(){}applyEffects(s,t=1){var i;const n=(i=this.gameObject)==null?void 0:i.getComponent(vl);n&&(n.effectDistance&&(s.borderWidth=Math.max(Math.abs(n.effectDistance.x),Math.abs(n.effectDistance.y))),n.effectColor&&(s.borderColor=n.effectColor,s.borderOpacity=n.effectColor.alpha*t))}async setTexture(s){if(this.setOptions({backgroundOpacity:0}),s){if(hh.textureCache.has(s))s=hh.textureCache.get(s);else if(!s.isRenderTargetTexture){const t=s.clone();t.colorSpace=pr,hh.textureCache.set(s,t),s=t}this.setOptions({backgroundImage:s,borderRadius:0,backgroundOpacity:this.color.alpha,backgroundSize:"stretch"}),et.assignTextureLOD(s,0).then(t=>{t instanceof Ne&&(s&&hh.textureCache.set(s,t),this.setOptions({backgroundImage:t}),this.markDirty())})}else this.setOptions({backgroundImage:void 0,borderRadius:0,backgroundOpacity:this.color.alpha});this.markDirty()}onAfterAddedToScene(){super.onAfterAddedToScene(),this.shadowComponent&&(this.shadowComponent.offset=this.shadowComponent.position.z)}},a(b0,"textureCache",new Map),b0);let Xr=hh;Wx([m(we)],Xr.prototype,"color",1),Wx([m()],Xr.prototype,"raycastTarget",2);class dh extends Xr{constructor(){super(...arguments),a(this,"_flippedObject",!1)}onAfterCreated(){this.uiObject&&!this._flippedObject&&(this._flippedObject=!0,this.uiObject.scale.y*=-1)}}var wT=Object.defineProperty,xT=Object.getOwnPropertyDescriptor,Nn=(s,t,i,n)=>{for(var o=n>1?void 0:n?xT(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&wT(t,i,o),o};const Qr=O("debugtext");var dt=(s=>(s[s.UpperLeft=0]="UpperLeft",s[s.UpperCenter=1]="UpperCenter",s[s.UpperRight=2]="UpperRight",s[s.MiddleLeft=3]="MiddleLeft",s[s.MiddleCenter=4]="MiddleCenter",s[s.MiddleRight=5]="MiddleRight",s[s.LowerLeft=6]="LowerLeft",s[s.LowerCenter=7]="LowerCenter",s[s.LowerRight=8]="LowerRight",s))(dt||{}),Vx=(s=>(s[s.Normal=0]="Normal",s[s.Bold=1]="Bold",s[s.Italic=2]="Italic",s[s.BoldAndItalic=3]="BoldAndItalic",s))(Vx||{});class Vt extends Xr{constructor(){super(...arguments),a(this,"alignment",0),a(this,"verticalOverflow",0),a(this,"horizontalOverflow",0),a(this,"lineSpacing",1),a(this,"supportRichText",!1),a(this,"font"),a(this,"fontStyle",0),a(this,"sRGBTextColor",new ae(1,0,1)),a(this,"_text",""),a(this,"_fontSize",12),a(this,"_textMeshUi",null),a(this,"_didHandleTextRenderOnTop",!1)}setAlphaFactor(t){var i;super.setAlphaFactor(t),(i=this.uiObject)==null||i.set({fontOpacity:this.color.alpha*this.alphaFactor}),this.markDirty()}get text(){return this._text}set text(t){t!==this._text&&(this._text=t,this.feedText(this.text,this.supportRichText),this.markDirty())}set_text(t){this.text=t}get fontSize(){return this._fontSize}set fontSize(t){var i;this._fontSize=t,(i=this.uiObject)==null||i.set({fontSize:t})}onColorChanged(){var t;this.sRGBTextColor.copy(this.color),this.sRGBTextColor.convertLinearToSRGB(),(t=this.uiObject)==null||t.set({color:this.sRGBTextColor,fontOpacity:this.color.alpha})}onParentRectTransformChanged(){super.onParentRectTransformChanged(),this.uiObject&&this.updateOverflow()}onBeforeCanvasRender(t){this.updateOverflow()}updateOverflow(){var t;const i=(t=this.uiObject)==null?void 0:t._overflow;i&&(i._needsUpdate=!0)}onCreate(t){Qr&&console.log(this),this.horizontalOverflow==1&&(t.whiteSpace="pre"),this.verticalOverflow==0&&(this.context.renderer.localClippingEnabled=!0,t.overflow="hidden"),this.horizontalOverflow==1&&this.verticalOverflow==0,t.lineHeight=this.lineSpacing,delete t.backgroundOpacity,delete t.backgroundColor,Qr&&(t.backgroundColor=16750848,t.backgroundOpacity=.5);const i=this.rectTransform;t={...t,...this.getTextOpts()},this.getAlignment(t),Qr&&(t.backgroundColor=Math.random()*16777215,t.backgroundOpacity=.1),this.uiObject=i.createNewText(t),this.feedText(this.text,this.supportRichText)}onAfterAddedToScene(){super.onAfterAddedToScene(),this.handleTextRenderOnTop()}getTextOpts(){const t=this.fontSize,i={color:this.color,fontOpacity:this.color.alpha,fontSize:t,fontKerning:"normal"};return this.setFont(i,this.fontStyle),i}onEnable(){var t;super.onEnable(),this._didHandleTextRenderOnTop=!1,this.uiObject&&this.uiObject.addAfterUpdate(()=>{this.setShadowComponentOwner(this.uiObject),this.markDirty()}),setTimeout(()=>this.markDirty(),10),(t=this.canvas)==null||t.registerEventReceiver(this)}onDisable(){var t;super.onDisable(),(t=this.canvas)==null||t.unregisterEventReceiver(this)}getAlignment(t){switch(t.flexDirection="column",this.alignment){case 0:case 3:case 6:t.textAlign="left";break;case 1:case 4:case 7:t.textAlign="center";break;case 2:case 5:case 8:t.textAlign="right";break}switch(this.alignment){default:case 0:case 1:case 2:t.alignItems="start";break;case 3:case 4:case 5:t.alignItems="center";break;case 6:case 7:case 8:t.alignItems="end";break}return t}feedText(t,i){var n,o,r;if(Qr&&console.log("feedText",this.uiObject,t,i),!!this.uiObject)if(this._textMeshUi||(this._textMeshUi=[]),this.uiObject.children.length=0,!i||t.length===0)this.uiObject.textContent=t;else{let l=this.getNextTag(t);if(l){if(l.startIndex>0){for(let d=this.uiObject.children.length-1;d>=0;d--){const u=this.uiObject.children[d];u.isUI&&(this.uiObject.remove(u),u.clear())}const h=new Om({textContent:t.substring(0,l.startIndex),color:"inherit"});this.uiObject.add(h)}}else{this.uiObject.textContent="",this.setOptions({textContent:t});return}const c=[];for(;l;){const h=this.getNextTag(t,l.endIndex),d={fontFamily:(n=this.uiObject)==null?void 0:n.get("fontFamily"),color:"inherit",textContent:""};if(h){d.textContent=this.getText(t,l,h),this.handleTag(l,d,c);const u=new Om(d);(o=this.uiObject)==null||o.add(u)}else{d.textContent=t.substring(l.endIndex),this.handleTag(l,d,c);const u=new Om(d);(r=this.uiObject)==null||r.add(u)}l=h}}}handleTextRenderOnTop(){this._didHandleTextRenderOnTop||(this._didHandleTextRenderOnTop=!0,this.startCoroutine(this.renderOnTopCoroutine()))}*renderOnTopCoroutine(){if(!this.canvas)return;const t=[],i=this.canvas,n={renderOnTop:i.renderOnTop,depthWrite:i.depthWrite,doubleSided:i.doubleSided};for(;;){let o=!1;if(this._textMeshUi)for(let r=0;r<this._textMeshUi.length;r++){if(t[r]===!0)continue;o=!0;const l=this._textMeshUi[r];l.textContent&&(Au(l,n),t[r]=!0)}if(!o)break;yield}}handleTag(t,i,n){if(!t.isEndTag){if(t.type.includes("color")){const o=new _0(t,{color:i.color});if(n.push(o),t.type.length>6){const r=parseInt("0x"+t.type.substring(7));i.color=r}else i.color=new ae(1,1,1)}else if(t.type=="b"){this.setFont(i,1);const o=new _0(t,{fontWeight:700});n.push(o)}else if(t.type=="i"){this.setFont(i,2);const o=new _0(t,{fontStyle:"italic"});n.push(o)}}}getText(t,i,n){return t.substring(i.endIndex,n.startIndex)}getNextTag(t,i=0){const n=t.indexOf("<",i),o=t.indexOf(">",n);if(n>=0&&o>=0){const r=t.substring(n+1,o);return{type:r,startIndex:n,endIndex:o+1,isEndTag:r.startsWith("/")}}return null}setFont(t,i){if(!this.font)return;const n=this.font,o=this.getFamilyNameWithCorrectSuffix(n,i);Qr&&console.log("Selected font family:"+o);let r=_v.getFontFamily(o);switch(r||(r=_v.addFontFamily(o)),t.fontFamily=r,i){default:case 0:t.fontWeight=400,t.fontStyle="normal";break;case 1:t.fontWeight=700,t.fontStyle="normal";break;case 2:t.fontWeight=400,t.fontStyle="italic";break;case 3:t.fontStyle="italic",t.fontWeight=400}let l=r.getVariant(t.fontWeight,t.fontStyle);if(!l){let c=o;c!=null&&c.endsWith("-msdf.json")||(c+="-msdf.json");let h=o;h!=null&&h.endsWith(".png")||(h+=".png"),l=r.addVariant(t.fontWeight,t.fontStyle,c,h),l?.addEventListener("ready",()=>{this.markDirty()})}}getFamilyNameWithCorrectSuffix(t,i){var n;const o=t.lastIndexOf("-");if(o<0)return t;const r=(n=t.substring(o+1))==null?void 0:n.toLowerCase();if(ST.includes(r))return Qr&&console.warn("Unsupported font style: "+r),t;const l=t.lastIndexOf("/");let c=t;l>=0&&(c=c.substring(l+1));const h=c[0]===c[0].toUpperCase(),d=t.substring(0,o);switch(Qr&&console.log("Select font: ",t,Vx[i],c,h,d),i){case 0:return h?d+"-Regular":d+"-regular";case 1:return h?d+"-Bold":d+"-bold";case 2:return h?d+"-Italic":d+"-italic";case 3:return h?d+"-BoldItalic":d+"-bolditalic";default:return t}}}Nn([m()],Vt.prototype,"alignment",2),Nn([m()],Vt.prototype,"verticalOverflow",2),Nn([m()],Vt.prototype,"horizontalOverflow",2),Nn([m()],Vt.prototype,"lineSpacing",2),Nn([m()],Vt.prototype,"supportRichText",2),Nn([m(URL)],Vt.prototype,"font",2),Nn([m()],Vt.prototype,"fontStyle",2),Nn([m()],Vt.prototype,"text",1),Nn([m()],Vt.prototype,"fontSize",1);class _0{constructor(t,i){a(this,"tag"),a(this,"previousValues"),this.tag=t,this.previousValues=i}}const ST=["medium","mediumitalic","black","blackitalic","thin","thinitalic","extrabold","light","lightitalic","semibold"];class Lo{constructor(t){a(this,"id"),a(this,"content",""),a(this,"font",[]),a(this,"pointSize",144),a(this,"width"),a(this,"height"),a(this,"depth"),a(this,"wrapMode"),a(this,"horizontalAlignment"),a(this,"verticalAlignment"),a(this,"material"),this.id=t}static getId(){return this.global_id++}setDepth(t){return this.depth=t,this}setPointSize(t){return this.pointSize=t,this}setHorizontalAlignment(t){return this.horizontalAlignment=t,this}setVerticalAlignment(t){return this.verticalAlignment=t,this}writeTo(t,i){var n;i.beginBlock(`def Preliminary_Text "${this.id}"`,"(",!1),i.appendLine('prepend apiSchemas = ["MaterialBindingAPI"]'),i.closeBlock(")"),i.beginBlock(),this.content&&i.appendLine(`string content = "${this.content}"`),(!this.font||this.font.length<=0)&&(this.font||(this.font=[]),(n=this.font)==null||n.push("sans-serif"));const o=this.font.map(r=>`"${r}"`).join(", ");i.appendLine(`string[] font = [ ${o} ]`),i.appendLine(`double pointSize = ${this.pointSize}`),typeof this.width=="number"&&i.appendLine(`double width = ${this.width}`),typeof this.height=="number"&&i.appendLine(`double height = ${this.height}`),typeof this.depth=="number"&&i.appendLine(`double depth = ${this.depth}`),this.wrapMode&&i.appendLine(`token wrapMode = "${this.wrapMode}"`),this.horizontalAlignment&&i.appendLine(`token horizontalAlignment = "${this.horizontalAlignment}"`),this.verticalAlignment&&i.appendLine(`token verticalAlignment = "${this.verticalAlignment}"`),this.material!==void 0&&i.appendLine(`rel material:binding = </StageRoot/Materials/${s0(this.material)}>`),i.closeBlock()}}a(Lo,"global_id",0);class fp{static singleLine(t,i,n){const o=new Lo("text_"+Lo.getId());return o.content=t,i&&(o.pointSize=i),n&&(o.depth=n),o}static multiLine(t,i,n,o,r,l){const c=new Lo("text_"+Lo.getId());return c.content=t,c.width=i,c.height=n,c.horizontalAlignment=o,c.verticalAlignment=r,l!==void 0&&(c.wrapMode=l),c}}const CT=new ne().makeRotationY(Math.PI),OT=new ne().makeScale(-1,1,-1);class uh{get extensionName(){return"text"}exportText(t,i,n){const o=P.getComponent(t,Vt);if(!o)return;const r=P.getComponent(t,Wt);let l=100,c=100;r&&(l=r.width,c=r.height);const h=CT.clone();r&&h.premultiply(OT),i.setMatrix(h);const d=o.color.clone();i.material=new ri({color:d,emissive:d}),i.addEventListener("serialize",(u,p)=>{let g=o.text;g=g.replace(/\r/g,""),g=g.replace(/\n/g,"\\n");const y=fp.multiLine(g,l,c,"center","bottom","flowing");this.setTextAlignment(y,o.alignment),this.setOverflow(y,o),i.material&&(y.material=i.material),y.pointSize=this.convertToTextSize(o.fontSize),y.depth=.001,y.writeTo(void 0,u)})}convertToTextSize(t){return 1/.0502*144*t}setOverflow(t,i){i.horizontalOverflow?t.wrapMode="singleLine":t.wrapMode="flowing"}setTextAlignment(t,i){switch(i){case dt.LowerLeft:case dt.MiddleLeft:case dt.UpperLeft:t.horizontalAlignment="left";break;case dt.LowerCenter:case dt.MiddleCenter:case dt.UpperCenter:t.horizontalAlignment="center";break;case dt.LowerRight:case dt.MiddleRight:case dt.UpperRight:t.horizontalAlignment="right";break}switch(i){case dt.LowerLeft:case dt.LowerCenter:case dt.LowerRight:t.verticalAlignment="bottom";break;case dt.MiddleLeft:case dt.MiddleCenter:case dt.MiddleRight:t.verticalAlignment="middle";break;case dt.UpperLeft:case dt.UpperCenter:case dt.UpperRight:t.verticalAlignment="top";break}}}var PT=Object.defineProperty,kT=Object.getOwnPropertyDescriptor,nt=(s,t,i,n)=>{for(var o=n>1?void 0:n?kT(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&PT(t,i,o),o};const Hx=O("debuguilayout");class Do{constructor(){a(this,"left",0),a(this,"right",0),a(this,"top",0),a(this,"bottom",0)}get vertical(){return this.top+this.bottom}get horizontal(){return this.left+this.right}}nt([m()],Do.prototype,"left",2),nt([m()],Do.prototype,"right",2),nt([m()],Do.prototype,"top",2),nt([m()],Do.prototype,"bottom",2);class Ii extends A{constructor(){super(...arguments),a(this,"_rectTransform",null),a(this,"_needsUpdate",!1),a(this,"childAlignment",0),a(this,"reverseArrangement",!1),a(this,"spacing",0),a(this,"padding"),a(this,"minWidth",0),a(this,"minHeight",0),a(this,"flexibleHeight",0),a(this,"flexibleWidth",0),a(this,"preferredHeight",0),a(this,"preferredWidth",0)}get rectTransform(){return this._rectTransform}onParentRectTransformChanged(t){this._needsUpdate=!0}get isDirty(){return this._needsUpdate}get isLayoutGroup(){return!0}updateLayout(){this._rectTransform&&(Hx&&console.warn("Layout Update",this.context.time.frame,this.name),this._needsUpdate=!1,this.onCalculateLayout(this._rectTransform))}start(){this._needsUpdate=!0}onEnable(){Hx&&console.log(this.name,this),this._rectTransform=this.gameObject.getComponent(Wt);const t=this.gameObject.getComponentInParent(Rt);t&&t.registerLayoutGroup(this),this._needsUpdate=!0}onDisable(){const t=this.gameObject.getComponentInParent(Rt);t&&t.unregisterLayoutGroup(this)}set m_Spacing(t){t!==this.spacing&&(this._needsUpdate=!0,this.spacing=t)}get m_Spacing(){return this.spacing}}nt([m()],Ii.prototype,"childAlignment",2),nt([m()],Ii.prototype,"reverseArrangement",2),nt([m()],Ii.prototype,"spacing",2),nt([m(Do)],Ii.prototype,"padding",2),nt([m()],Ii.prototype,"minWidth",2),nt([m()],Ii.prototype,"minHeight",2),nt([m()],Ii.prototype,"flexibleHeight",2),nt([m()],Ii.prototype,"flexibleWidth",2),nt([m()],Ii.prototype,"preferredHeight",2),nt([m()],Ii.prototype,"preferredWidth",2);class Bo extends Ii{constructor(){super(...arguments),a(this,"childControlHeight",!0),a(this,"childControlWidth",!0),a(this,"childForceExpandHeight",!1),a(this,"childForceExpandWidth",!1),a(this,"childScaleHeight",!1),a(this,"childScaleWidth",!1)}onCalculateLayout(t){var i;const n=this.primaryAxis,o=t.width;let r=o;const l=t.height;let c=l;r-=this.padding.horizontal,c-=this.padding.vertical,n==="x"?this.padding.horizontal:this.padding.vertical;const h=n==="x",d=h?"y":"x",u=h?this.childControlWidth:this.childControlHeight,p=h?this.childControlHeight:this.childControlWidth,g=h?this.childForceExpandWidth:this.childForceExpandHeight,y=h?this.childForceExpandHeight:this.childForceExpandWidth,f=h?c:r,v=h?o:l,b=.5*(h?this.childAlignment%3:Math.floor(this.childAlignment/3));let w=0;h?w+=this.padding.left:w+=this.padding.top;let _=0,C=0;for(let L=0;L<this.gameObject.children.length;L++){const U=this.gameObject.children[L],z=P.getComponent(U,Wt);z!=null&&z.activeAndEnabled&&(C+=1,h?_+=z.width:_+=z.height)}let R=0;const M=this.spacing*(C-1);if(g||u){let L=0;h?L=r-=M:L=c-=M,C>0&&(R=L/C)}let E=0;E+=this.padding.left,E-=this.padding.right,b!==0&&(w=v-_,w*=b,w-=M*b,h?(w-=this.padding.right*b,w+=this.padding.left*(1-b),w<this.padding.left&&(w=this.padding.left)):(w-=this.padding.bottom*b,w+=this.padding.top*(1-b),w<this.padding.top&&(w=this.padding.top)));let D=1;for(let L=0;L<this.gameObject.children.length;L++){const U=this.gameObject.children[L],z=P.getComponent(U,Wt);if(z!=null&&z.activeAndEnabled){(i=z.pivot)==null||i.set(.5,.5),z.anchorMin.set(0,1),z.anchorMax.set(0,1);const H=o*.5+E*.5;z.anchoredPosition.x!==H&&(z.anchoredPosition.x=H);const T=l*-.5;z.anchoredPosition.y!==T&&(z.anchoredPosition.y=T),y&&p&&z.sizeDelta[d]!==f&&(z.sizeDelta[d]=f),g&&u&&z.sizeDelta[n]!==R&&(z.sizeDelta[n]=R);const I=h?z.width:z.height,G=I*.5;if(w+=G,g){const se=R*D-R*.5;se>w&&(w=se-R*.5+I+this.padding.left,w-=G)}let J=w;n==="y"&&(J=-J),z.anchoredPosition[n]!==J&&(z.anchoredPosition[n]=J),w+=G,w+=this.spacing,D+=1}}}}nt([m()],Bo.prototype,"childControlHeight",2),nt([m()],Bo.prototype,"childControlWidth",2),nt([m()],Bo.prototype,"childForceExpandHeight",2),nt([m()],Bo.prototype,"childForceExpandWidth",2),nt([m()],Bo.prototype,"childScaleHeight",2),nt([m()],Bo.prototype,"childScaleWidth",2);class w0 extends Bo{get primaryAxis(){return"y"}}class x0 extends Bo{get primaryAxis(){return"x"}}class S0 extends Ii{onCalculateLayout(){}}var MT=Object.defineProperty,RT=Object.getOwnPropertyDescriptor,on=(s,t,i,n)=>{for(var o=n>1?void 0:n?RT(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&MT(t,i,o),o},$x=(s=>(s[s.ScreenSpaceOverlay=0]="ScreenSpaceOverlay",s[s.ScreenSpaceCamera=1]="ScreenSpaceCamera",s[s.WorldSpace=2]="WorldSpace",s[s.Undefined=-1]="Undefined",s))($x||{});const C0=O("debuguilayout"),qx=class extends Bc{constructor(){super(...arguments),a(this,"_renderOnTop"),a(this,"_depthWrite",!1),a(this,"_doubleSided",!0),a(this,"_castShadows",!1),a(this,"_receiveShadows",!1),a(this,"_renderMode",-1),a(this,"_rootCanvas"),a(this,"_scaleFactor",1),a(this,"worldCamera"),a(this,"planeDistance",-1),a(this,"_boundRenderSettingsChanged",this.onRenderSettingsChanged.bind(this)),a(this,"previousParent",null),a(this,"_lastMatrixWorld",null),a(this,"_rectTransforms",[]),a(this,"_layoutGroups",new Map),a(this,"_receivers",[]),a(this,"onBeforeRenderRoutine",()=>{var s,t,i,n;if(this.previousParent=this.gameObject.parent,((s=this.context.xr)!=null&&s.isVR||(t=this.context.xr)!=null&&t.isPassThrough)&&this.screenspace){this.gameObject.visible=!1,this.gameObject.removeFromParent();return}this.renderOnTop||this.screenspace?this.gameObject.removeFromParent():(this.onUpdateRenderMode(),this.handleLayoutUpdates(),(i=this.shadowComponent)==null||i.updateMatrixWorld(!0),(n=this.shadowComponent)==null||n.updateWorldMatrix(!0,!0),this.invokeBeforeRenderEvents(),ts.ensureUpdateMeshUI(wv,this.context))}),a(this,"onAfterRenderRoutine",()=>{var s,t,i,n,o;if(((s=this.context.xr)!=null&&s.isVR||(t=this.context.xr)!=null&&t.isPassThrough)&&this.screenspace){(i=this.previousParent)==null||i.add(this.gameObject);return}if((this.screenspace||this.renderOnTop)&&this.previousParent&&this.context.mainCamera){if(this.screenspace){const c=this.context.mainCamera;c?.add(this.gameObject)}else this.previousParent.add(this.gameObject);const r=this.context.renderer.autoClear,l=this.context.renderer.autoClearColor;this.context.renderer.autoClear=!1,this.context.renderer.autoClearColor=!1,this.context.renderer.clearDepth(),this.onUpdateRenderMode(!0),this.handleLayoutUpdates(),(n=this.shadowComponent)==null||n.updateMatrixWorld(!0),this.invokeBeforeRenderEvents(),ts.ensureUpdateMeshUI(wv,this.context,!0),this.context.renderer.render(this.gameObject,this.context.mainCamera),this.context.renderer.autoClear=r,this.context.renderer.autoClearColor=l,this.previousParent.add(this.gameObject)}(o=this._lastMatrixWorld)==null||o.copy(this.gameObject.matrixWorld)}),a(this,"_updateRenderSettingsRoutine"),a(this,"_activeRenderMode",-1),a(this,"_lastWidth",-1),a(this,"_lastHeight",-1)}get isCanvas(){return!0}get screenspace(){return this.renderMode!==2}set renderOnTop(s){s!==this._renderOnTop&&(this._renderOnTop=s,this.onRenderSettingsChanged())}get renderOnTop(){return this._renderOnTop!==void 0?this._renderOnTop:!!(this.screenspace&&this._renderMode===0)}set depthWrite(s){this._depthWrite!==s&&(this._depthWrite=s,this.onRenderSettingsChanged())}get depthWrite(){return this._depthWrite}set doubleSided(s){this._doubleSided!==s&&(this._doubleSided=s,this.onRenderSettingsChanged())}get doubleSided(){return this._doubleSided}set castShadows(s){this._castShadows!==s&&(this._castShadows=s,this.onRenderSettingsChanged())}get castShadows(){return this._castShadows}set receiveShadows(s){this._receiveShadows!==s&&(this._receiveShadows=s,this.onRenderSettingsChanged())}get receiveShadows(){return this._receiveShadows}get renderMode(){return this._renderMode}set renderMode(s){this._renderMode!==s&&(this._renderMode=s,this.onRenderSettingsChanged())}set rootCanvas(s){this._rootCanvas instanceof qx||(this._rootCanvas=s)}get rootCanvas(){return this._rootCanvas}get scaleFactor(){return this._scaleFactor}set scaleFactor(s){this._scaleFactor=s}awake(){var s;this.shadowComponent=this.gameObject,this.previousParent=this.gameObject.parent,C0&&console.log("Canvas.Awake()",((s=this.previousParent)==null?void 0:s.name)+"/"+this.gameObject.name),super.awake()}start(){this.onUpdateRenderMode()}onEnable(){super.onEnable(),this._updateRenderSettingsRoutine=void 0,this._lastMatrixWorld=new ne,this.onUpdateRenderMode(),document.addEventListener("resize",this._boundRenderSettingsChanged),this.context.pre_render_callbacks.push(this.onBeforeRenderRoutine),this.context.post_render_callbacks.push(this.onAfterRenderRoutine)}onDisable(){super.onDisable(),document.removeEventListener("resize",this._boundRenderSettingsChanged);const s=this.context.pre_render_callbacks.indexOf(this.onBeforeRenderRoutine);s!==-1&&this.context.pre_render_callbacks.splice(s,1);const t=this.context.post_render_callbacks.indexOf(this.onAfterRenderRoutine);t!==-1&&this.context.post_render_callbacks.splice(t,1)}registerTransform(s){this._rectTransforms.push(s)}unregisterTransform(s){const t=this._rectTransforms.indexOf(s);t!==-1&&this._rectTransforms.splice(t,1)}registerLayoutGroup(s){const t=s.gameObject;this._layoutGroups.set(t,s)}unregisterLayoutGroup(s){const t=s.gameObject;this._layoutGroups.delete(t)}registerEventReceiver(s){this._receivers.push(s)}unregisterEventReceiver(s){const t=this._receivers.indexOf(s);t!==-1&&this._receivers.splice(t,1)}async onEnterXR(s){this.screenspace?(s.xr.isVR||s.xr.isPassThrough)&&(this.gameObject.visible=!1):(this.gameObject.visible=!1,await Xl(1).then(()=>{this.gameObject.visible=!0}))}onLeaveXR(s){this.screenspace&&(s.xr.isVR||s.xr.isPassThrough)&&(this.gameObject.visible=!0)}invokeBeforeRenderEvents(){var s;for(const t of this._receivers)(s=t.onBeforeCanvasRender)==null||s.call(t,this)}handleLayoutUpdates(){this._lastMatrixWorld===null&&(this._lastMatrixWorld=new ne);const s=!this._lastMatrixWorld.equals(this.gameObject.matrixWorld);C0&&s&&console.log("Canvas Layout changed",this.context.time.frameCount,this.name);const t=!1;for(const i of this._rectTransforms){s&&i.markDirty();let n=this._layoutGroups.get(i.gameObject);i.isDirty&&!n&&(n=i.gameObject.getComponentInParent(Ii)),(i.isDirty||n!=null&&n.isDirty)&&(C0&&!t&&console.log("CANVAS UPDATE ### "+i.name+" ##################################### "+this.context.time.frame),n?.updateLayout(),i.updateTransform())}}applyRenderSettings(){this.onRenderSettingsChanged()}onRenderSettingsChanged(){this._updateRenderSettingsRoutine||(this._updateRenderSettingsRoutine=this.startCoroutine(this._updateRenderSettingsDelayed(),Ce.OnBeforeRender))}*_updateRenderSettingsDelayed(){if(yield,this._updateRenderSettingsRoutine=void 0,this.shadowComponent){this.onUpdateRenderMode(),Au(this.shadowComponent,this);for(const s of P.getComponentsInChildren(this.gameObject,ls))Au(s.shadowComponent,this)}}onUpdateRenderMode(s=!1){if(!s&&this._renderMode===this._activeRenderMode&&this._lastWidth===this.context.domWidth&&this._lastHeight===this.context.domHeight)return;this._activeRenderMode=this._renderMode;let t=this.context.mainCameraComponent,i=10;switch(t&&t.nearClipPlane>0&&t.farClipPlane>0&&(i=W.lerp(t.nearClipPlane,t.farClipPlane,.01)),this._renderMode===1&&(this.worldCamera&&(t=this.worldCamera),this.planeDistance>0&&(i=this.planeDistance)),this._renderMode){case 0:case 1:if(this._lastWidth=this.context.domWidth,this._lastHeight=this.context.domHeight,!t)return;const n=i+.01;this.gameObject.position.x=0,this.gameObject.position.y=0,this.gameObject.position.z=-n,this.gameObject.quaternion.identity();const o=this.gameObject.getComponent(Wt);let r=!1;o.sizeDelta.x!==this.context.domWidth&&(r=!0),o.sizeDelta.y!==this.context.domHeight&&(r=!0);const l=t.fieldOfView*Math.PI/180,c=2*Math.tan(l/2)*Math.abs(n);this.gameObject.scale.x=c/this.context.domHeight,this.gameObject.scale.y=c/this.context.domHeight,this.gameObject.scale.z=.01,r&&(o.sizeDelta.x=this.context.domWidth,o.sizeDelta.y=this.context.domHeight,o?.markDirty());break;case 2:this._lastWidth=-1,this._lastHeight=-1;break}}};let Rt=qx;on([m()],Rt.prototype,"renderOnTop",1),on([m()],Rt.prototype,"depthWrite",1),on([m()],Rt.prototype,"doubleSided",1),on([m()],Rt.prototype,"castShadows",1),on([m()],Rt.prototype,"receiveShadows",1),on([m()],Rt.prototype,"renderMode",1),on([m(Rt)],Rt.prototype,"rootCanvas",1),on([m()],Rt.prototype,"scaleFactor",1),on([m(Pe)],Rt.prototype,"worldCamera",2),on([m()],Rt.prototype,"planeDistance",2);var TT=Object.defineProperty,ET=Object.getOwnPropertyDescriptor,O0=(s,t,i,n)=>{for(var o=n>1?void 0:n?ET(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&TT(t,i,o),o};class Fo extends A{constructor(){super(...arguments),a(this,"_alpha",1),a(this,"interactable",!0),a(this,"blocksRaycasts",!0),a(this,"_isDirty",!1),a(this,"_buffer",[])}get alpha(){return this._alpha}set alpha(t){t!==this._alpha&&(this._alpha=t,this.markDirty())}get isCanvasGroup(){return!0}markDirty(){this._isDirty||(this._isDirty=!0,this.startCoroutine(this.applyChangesDelayed(),Ce.OnBeforeRender))}*applyChangesDelayed(){this._isDirty=!1,this.applyChangesNow()}applyChangesNow(){this._buffer.length=0;for(const t of P.getComponentsInChildren(this.gameObject,ls,this._buffer)){const i=t;i.setAlphaFactor&&i.setAlphaFactor(this._alpha)}}}O0([m()],Fo.prototype,"alpha",1),O0([m()],Fo.prototype,"interactable",2),O0([m()],Fo.prototype,"blocksRaycasts",2);class yp{get extensionName(){return"tmui"}onExportObject(t,i,n){const o=P.getComponent(t,Rt);if(o&&o.enabled&&o.renderMode===$x.WorldSpace){const r=new uh,l=P.getComponent(t,Wt),c=P.getComponent(t,Fo),h=new Array;if(l){if(!P.isActiveSelf(t)){const p=P.isActiveSelf(t);P.setActive(t,!0),l.onEnable(),l.updateTransform(),h.push(()=>{l.onDisable(),P.setActive(t,p)})}t.traverse(p=>{if(!P.isActiveInHierarchy(p)){const g=P.isActiveSelf(p);P.setActive(p,!0);const y=P.getComponent(p,ls);y&&(y.onEnable(),h.push(()=>{y.onDisable()}));const f=P.getComponent(p,Wt);f&&(f.onEnable(),f.updateTransform(),f.onApplyTransform(),h.push(()=>{f.onDisable()}));const v=P.getComponent(p,Vt);v&&(v.onEnable(),h.push(()=>{v.onDisable()})),h.push(()=>{P.setActive(p,g)})}}),l.width,l.height;const d=Zt.createEmpty(),u=l.shadowComponent;if(i.add(d),u){const p=u.matrix;d.setMatrix(p);const g=new Map,y=new Map;g.set(u,d),y.set(u,c?c.alpha:1),u.traverse(f=>{if(f===u)return;const v=Zt.createEmpty();v.setMatrix(f.matrix);const b=f.parent,w=!!b&&typeof b.textContent=="string"&&b.textContent.length>0;let _=y.get(b)||1;const C=P.getComponent(f,Fo);if(C&&(_*=C.alpha),f instanceof Q&&w){const M=f[es];M?r.exportText(M.gameObject,v,n):console.error("Error when exporting UI: shadow component owner not found. This is likely a bug.",f)}if(f instanceof Q&&!w){const M=f.geometry.clone();M.scale(1,1,-1),this.flipWindingOrder(M),v.geometry=M;const E=new ae,D=f.material.opacity;E.copy(f.material.color),v.material=new Me({color:E,opacity:D*_,map:f.material.map,transparent:!0})}g.set(f,v),y.set(f,_);const R=g.get(b);if(!R){console.error("Error when exporting UI: shadow component parent not found!",f,f.parent);return}R.add(v)})}}for(const d of h)d()}}flipWindingOrder(t){const i=t.index.array;for(let n=0,o=i.length/3;n<o;n++){const r=i[n*3];i[n*3]=i[n*3+2],i[n*3+2]=r}t.index.needsUpdate=!0}}const Gx=class{constructor(){a(this,"_quicklookButton"),a(this,"_arButton"),a(this,"_vrButton"),a(this,"_sendToQuestButton")}static create(){return new Gx}static getOrCreate(){return this._instance||(this._instance=this.create()),this._instance}get isSecureConnection(){return window.location.protocol==="https:"}get quicklookButton(){return this._quicklookButton}get arButton(){return this._arButton}get vrButton(){return this._vrButton}get sendToQuestButton(){return this._sendToQuestButton}get qrButton(){return Mn.getOrCreate().createQRCode()}createQuicklookButton(){if(this._quicklookButton)return this._quicklookButton;const s=document.createElement("button");this._quicklookButton=s,s.dataset.needle="quicklook-button";const t=Y.supportsQuickLookAR();s.innerText="View in AR",s.prepend(Ot("view_in_ar"));let i=!1,n=null;return s.addEventListener("click",()=>{n=Gd(Ge),n||(i=!0,n=new Ge),i&&(n.objectToExport=te.Current.scene),n?(s.classList.add("this-mode-is-requested"),n.exportAndOpen().then(()=>{s.classList.remove("this-mode-is-requested")}).catch(o=>{s.classList.remove("this-mode-is-requested"),console.error(o)})):console.warn("No USDZExporter component found in the scene")}),this.hideElementDuringXRSession(s),s}createARButton(s){var t;if(this._arButton)return this._arButton;const i="immersive-ar",n=document.createElement("button");return this._arButton=n,n.classList.add("webxr-button"),n.dataset.needle="webxr-ar-button",n.innerText="Enter AR",n.prepend(Ot("view_in_ar")),n.title="Click to start an AR session",n.addEventListener("click",()=>Z.start(i,s)),this.updateSessionSupported(n,i),this.listenToXRSessionState(n,i),this.hideElementDuringXRSession(n),this.isSecureConnection||(n.disabled=!0,n.title="WebXR requires a secure connection (HTTPS)"),Y.isMozillaXR()||(t=navigator.xr)==null||t.addEventListener("devicechange",()=>this.updateSessionSupported(n,i)),n}createVRButton(s){var t;if(this._vrButton)return this._vrButton;const i="immersive-vr",n=document.createElement("button");return this._vrButton=n,n.classList.add("webxr-button"),n.dataset.needle="webxr-vr-button",n.innerText="Enter VR",n.prepend(Ot("panorama_photosphere")),n.title="Click to start a VR session",n.addEventListener("click",()=>Z.start(i,s)),this.updateSessionSupported(n,i),this.listenToXRSessionState(n,i),this.hideElementDuringXRSession(n),this.isSecureConnection||(n.disabled=!0,n.title="WebXR requires a secure connection (HTTPS)"),Y.isMozillaXR()||(t=navigator.xr)==null||t.addEventListener("devicechange",()=>this.updateSessionSupported(n,i)),n}createSendToQuestButton(){var s;if(this._sendToQuestButton)return this._sendToQuestButton;const t="https://oculus.com/open_url/?url=",i=document.createElement("button");return this._sendToQuestButton=i,i.dataset.needle="webxr-sendtoquest-button",i.innerText="Open on Quest",i.prepend(Ot("share_windows")),i.title="Click to send this page to the Oculus Browser on your Quest",i.addEventListener("click",()=>{const n=encodeURIComponent(window.location.href),o=t+n;window.open(o)==null&&Le("This page doesn't allow popups. Please paste "+o+" into your browser.")}),this.listenToXRSessionState(i),this.hideElementDuringXRSession(i),Y.isMozillaXR()||(s=navigator.xr)==null||s.addEventListener("devicechange",()=>{var n;(n=navigator.xr)!=null&&n.isSessionSupported("immersive-vr")?i.style.display="none":i.style.display=""}),i}createQRCode(){return Mn.getOrCreate().createQRCode()}updateSessionSupported(s,t){if(!("xr"in navigator)){s.style.display="none";return}Z.isSessionSupported(t).then(i=>{s.style.display=i?"":"none",F()&&!i&&console.log('[WebXR] "'+t+'" is not supported on this device \u2013 make sure your server runs using HTTPS and you have a device connected that supports '+t)})}hideElementDuringXRSession(s){kd(t=>{s["previous-display"]=s.style.display,s.style.display="none"}),og(t=>{s["previous-display"]!=null&&(s.style.display=s["previous-display"])})}listenToXRSessionState(s,t){t&&(Z.onSessionRequestStart(i=>{i.mode===t?s.classList.add("this-mode-is-requested"):(s["was-disabled"]=s.disabled,s.disabled=!0,s.classList.add("other-mode-is-requested"))}),Z.onSessionRequestEnd(i=>{s.classList.remove("this-mode-is-requested"),s.classList.remove("other-mode-is-requested"),s.disabled=s["was-disabled"]}))}};let Yr=Gx;a(Yr,"_instance");var AT=Object.defineProperty,IT=Object.getOwnPropertyDescriptor,wt=(s,t,i,n)=>{for(var o=n>1?void 0:n?IT(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&AT(t,i,o),o};const vp=O("debugspriterenderer"),jT=O("wireframe"),P0=class{static getOrCreateGeometry(s){if(s.__cached_geometry)return s.__cached_geometry;if(s.guid&&P0.cache[s.guid])return vp&&console.log("Take cached geometry for sprite",s.guid),P0.cache[s.guid];const t=new oo;s.__cached_geometry=t;const i=new Float32Array(s.triangles.length*3),n=new Float32Array(s.triangles.length*2);for(let o=0;o<s.triangles.length;o+=1){const r=s.triangles[o];i[o*3]=-s.vertices[r].x,i[o*3+1]=s.vertices[r].y,i[o*3+2]=0;const l=s.uv[r];n[o*2]=l.x,n[o*2+1]=1-l.y}return t.setAttribute("position",new mt(i,3)),t.setAttribute("uv",new mt(n,2)),s.guid&&(this.cache[s.guid]=t),vp&&console.log("Built sprite geometry",s,t),t}};let ph=P0;a(ph,"cache",{});class LT{constructor(){a(this,"x"),a(this,"y")}}function Xx(s){s&&(s.colorSpace!=ps&&(s.colorSpace=ps,s.needsUpdate=!0),s.minFilter==hd&&s.magFilter==hd&&(s.anisotropy=1,s.needsUpdate=!0))}let rn=class{constructor(s){a(this,"guid"),a(this,"texture"),a(this,"triangles"),a(this,"uv"),a(this,"vertices"),a(this,"__cached_geometry"),a(this,"_mesh"),a(this,"_material"),s&&(this.texture=s,this.triangles=[0,1,2,0,2,3],this.uv=[{x:0,y:0},{x:1,y:0},{x:1,y:1},{x:0,y:1}],this.vertices=[{x:-.5,y:-.5},{x:.5,y:-.5},{x:.5,y:.5},{x:-.5,y:.5}])}get mesh(){return this._mesh||(this._mesh=new Q(ph.getOrCreateGeometry(this),this.material)),this._mesh}get material(){return this._material||(this.texture&&Xx(this.texture),this._material=new Me({map:this.texture,color:16777215,side:_i,transparent:!0})),this._material}getGeometry(){return ph.getOrCreateGeometry(this)}};wt([m()],rn.prototype,"guid",2),wt([m(Ne)],rn.prototype,"texture",2),wt([Ha()],rn.prototype,"triangles",2),wt([Ha()],rn.prototype,"uv",2),wt([Ha()],rn.prototype,"vertices",2);const k0=Symbol("spriteOwner");class zo{constructor(){a(this,"sprites")}}wt([m(rn)],zo.prototype,"sprites",2);const Qx=class{constructor(){a(this,"spriteSheet"),a(this,"index",0)}static create(){const s=new Qx;return s.spriteSheet=new zo,s}set sprite(s){s&&(this.spriteSheet?((this.index===null||this.index===void 0)&&(this.index=0),this.spriteSheet.sprites[this.index]=s):(this.spriteSheet=new zo,this.spriteSheet.sprites=[s],this.index=0))}get sprite(){if(this.spriteSheet)return this.spriteSheet.sprites[this.index]}update(s){if(!this.spriteSheet)return;const t=this.index;if(t<0||t>=this.spriteSheet.sprites.length)return;const i=this.spriteSheet.sprites[t],n=i?.texture;if(n&&(Xx(n),!i.__hasLoadedProgressive)){i.__hasLoadedProgressive=!0;const o=n;et.assignTextureLOD(n,0).then(r=>{r instanceof Ne&&(i.texture=r,s?.map===o&&(s.map=r,s.needsUpdate=!0))})}}};let Wn=Qx;wt([m(zo)],Wn.prototype,"spriteSheet",2),wt([m()],Wn.prototype,"index",2);class pi extends A{constructor(){super(...arguments),a(this,"drawMode",0),a(this,"size",{x:1,y:1}),a(this,"color"),a(this,"sharedMaterial"),a(this,"transparent",!0),a(this,"cutoutThreshold",0),a(this,"castShadows",!1),a(this,"renderOrder",0),a(this,"toneMapped",!0),a(this,"_spriteSheet"),a(this,"_currentSprite")}set texture(t){var i;if(!this._spriteSheet)return;const n=(i=this._spriteSheet.spriteSheet)==null?void 0:i.sprites[this.spriteIndex];n&&(n.texture=t,this.updateSprite())}addSprite(t,i=!1){var n,o;if(this._spriteSheet||(this._spriteSheet=Wn.create()),!this._spriteSheet.spriteSheet)return-1;(n=this._spriteSheet.spriteSheet)==null||n.sprites.push(t);const r=((o=this._spriteSheet.spriteSheet)==null?void 0:o.sprites.length)-1;return i&&(this.spriteIndex=r),r}get sprite(){return this._spriteSheet}set sprite(t){if(t!==this._spriteSheet)if(typeof t=="number"){const i=Math.floor(t);this.spriteIndex=i;return}else t instanceof rn?(this._spriteSheet||(this._spriteSheet=Wn.create()),this._spriteSheet.sprite!=t&&(this._spriteSheet.sprite=t,this.updateSprite())):t!=this._spriteSheet&&(this._spriteSheet=t,this.updateSprite())}set spriteIndex(t){this._spriteSheet&&t!==this.spriteIndex&&(this._spriteSheet.index=t,this.updateSprite())}get spriteIndex(){var t;return((t=this._spriteSheet)==null?void 0:t.index)??0}get spriteFrames(){var t,i;return((i=(t=this._spriteSheet)==null?void 0:t.spriteSheet)==null?void 0:i.sprites.length)??0}awake(){this._currentSprite=void 0,this._spriteSheet||(this._spriteSheet=new Wn,this._spriteSheet.spriteSheet=new zo),vp&&console.log("Awake",this.name,this,this.sprite)}start(){this._currentSprite?this.gameObject&&this.gameObject.add(this._currentSprite):this.updateSprite()}updateSprite(t=!1){var i;if(!this.__didAwake&&!t)return!1;const n=this._spriteSheet;if(!((i=n?.spriteSheet)!=null&&i.sprites))return console.warn("SpriteRenderer has no data or spritesheet assigned..."),!1;const o=n.spriteSheet.sprites[this.spriteIndex];if(!o)return vp&&console.warn("Sprite not found",this.spriteIndex,n.spriteSheet.sprites),!1;if(this._currentSprite)this._currentSprite.geometry=ph.getOrCreateGeometry(o),this._currentSprite.material.map=o.texture;else{const r=new Me({color:16777215,side:_i});if(jT&&(r.wireframe=!0),this.color&&(r.color||(r.color=new ae),r.color.copy(this.color),r.opacity=this.color.alpha),r.transparent=!0,r.toneMapped=this.toneMapped,o.texture&&!r.wireframe){let l=o.texture;l[k0]!==void 0&&l[k0]!==this&&this.spriteFrames>1&&(l=o.texture=l.clone()),l[k0]=this,r.map=l}this.sharedMaterial=r,this._currentSprite=new Q(ph.getOrCreateGeometry(o),r),this._currentSprite.renderOrder=Math.round(this.renderOrder),et.assignTextureLOD(r,0)}return this._currentSprite.parent!==this.gameObject&&(this.drawMode===2&&this._currentSprite.scale.set(this.size.x,this.size.y,1),this.gameObject&&this.gameObject.add(this._currentSprite)),this._currentSprite&&this._currentSprite.layers.set(this.layer),this.sharedMaterial&&(this.sharedMaterial.alphaTest=this.cutoutThreshold,this.sharedMaterial.transparent=this.transparent),this._currentSprite.castShadow=this.castShadows,n?.update(this.sharedMaterial),!0}}wt([m()],pi.prototype,"drawMode",2),wt([m(LT)],pi.prototype,"size",2),wt([m(we)],pi.prototype,"color",2),wt([m(Oe)],pi.prototype,"sharedMaterial",2),wt([m()],pi.prototype,"transparent",2),wt([m()],pi.prototype,"cutoutThreshold",2),wt([m()],pi.prototype,"castShadows",2),wt([m()],pi.prototype,"renderOrder",2),wt([m()],pi.prototype,"toneMapped",2),wt([m(Wn)],pi.prototype,"sprite",1);const Yx=O("debugwebxr"),DT=new ne().makeRotationY(Math.PI);class Vn extends A{constructor(){super(...arguments),a(this,"_arScale",1),a(this,"invertForward",!1),a(this,"customReticle"),a(this,"arTouchTransform",!0),a(this,"autoPlace",!1),a(this,"autoCenter",!1),a(this,"useXRAnchor",!1),a(this,"_isPlacing",!0),a(this,"_startOffset",new ne),a(this,"_createdPlacementObject",null),a(this,"_reparentedComponents",[]),a(this,"_placementScene",new $i),a(this,"_reticle",[]),a(this,"_hits",[]),a(this,"_placementStartTime",-1),a(this,"_rigPlacementMatrix"),a(this,"_anchor",null),a(this,"userInput"),a(this,"onPlaceScene",t=>{var i;if(this._isPlacing==!1||t!=null&&t.used)return;let n=this._reticle[0];if(!n){console.warn("No reticle to place...");return}if(!n.visible&&!this.autoPlace){console.warn("Reticle is not visible (can not place)");return}if((i=Z.active)!=null&&i.isTrackingImages){console.warn("Scene Placement is disabled while images are being tracked");return}let o=this._hits[0];if(t&&t.origin instanceof rg){const r=this._reticle[t.origin.index];r&&(n=r,o=this._hits[t.origin.index])}if(t&&(t.stopImmediatePropagation(),t.stopPropagation(),t.use()),this._isPlacing=!1,this.context.input.removeEventListener("pointerup",this.onPlaceScene),this.onRevertSceneChanges(),n.position.copy(n.lastPos),n.quaternion.copy(n.lastQuat),this.onApplyPose(n),this.useXRAnchor&&this.onCreateAnchor(Z.active,o),this.context.xr)for(const r of this.context.xr.controllers)r.cancelHitTestSource()}),a(this,"upVec",new x(0,1,0)),a(this,"lookPoint",new x),a(this,"worldUpVec",new x(0,1,0))}static onPlaced(t){const i="placed";return this._eventListeners[i]||(this._eventListeners[i]=[]),this._eventListeners[i].push(t),()=>{const n=this._eventListeners[i].indexOf(t);n>=0&&this._eventListeners[i].splice(n,1)}}get arScale(){return this._arScale}set arScale(t){t!==this._arScale&&(this._arScale=t,this.onScaleChanged())}onEnable(){var t;(t=this.customReticle)==null||t.preload()}supportsXR(t){return t==="immersive-ar"}onEnterXR(t){Yx&&console.log("ENTER WEBXR: SessionRoot start..."),this._anchor=null,this.gameObject.updateMatrixWorld(),this._startOffset.copy(this.gameObject.matrixWorld);const i=new j;this._createdPlacementObject=i,i.name="AR Session Root",this._placementScene.name="AR Placement Scene",this._placementScene.children.length=0;for(let n=this.context.scene.children.length-1;n>=0;n--){const o=this.context.scene.children[n];this._placementScene.add(o)}if(this.context.scene.add(i),this.autoCenter){const n=Si(this._placementScene.children),o=n.getCenter(new x),r=n.getSize(new x),l=new ne;l.makeTranslation(o.x,o.y-r.y*.5,o.z),this._startOffset.multiply(l)}this._reparentedComponents.length=0,this._reparentedComponents.push({comp:this,originalObject:this.gameObject}),P.addComponent(i,this);for(const n of this._reticle)Mi(n);this._reticle.length=0,this._isPlacing=!0,this.context.input.addEventListener("pointerup",this.onPlaceScene,{queue:Ci.Early})}onLeaveXR(){this.context.input.removeEventListener("pointerup",this.onPlaceScene,{queue:Ci.Early}),this.onRevertSceneChanges(),this._anchor=null,this._rigPlacementMatrix=void 0}onUpdateXR(t){var i,n,o,r;if(t.xr.isTrackingImages){for(const l of this._reticle)l.visible=!1;return}if(this._isPlacing){const l=(i=t.xr.rig)==null?void 0:i.gameObject;l&&l.parent!==this.context.scene&&this.context.scene.add(l);let c=!1;if(t.xr.isPassThrough&&t.xr.controllers.length>0&&!this.autoPlace)for(const h of t.xr.controllers){const d=h.getHitTest();d&&(c=!0,this.updateReticleAndHits(t.xr,h.index,d,t.xr.rigScale))}if(!c){const h=t.xr.getHitTest();h&&this.updateReticleAndHits(t.xr,0,h,t.xr.rigScale)}}else{if(this._anchor&&t.xr.referenceSpace){const l=t.xr.frame.getPose(this._anchor.anchorSpace,t.xr.referenceSpace);if(l&&this.context.time.frame%20===0){const c=t.xr.convertSpace(l.transform),h=this._reticle[0];h&&(h.position.copy(c.position),h.quaternion.copy(c.quaternion),this.onApplyPose(h))}}if(this.arTouchTransform?(this.userInput||(this.userInput=new bp(this.context)),(n=this.userInput)==null||n.enable()):(o=this.userInput)==null||o.disable(),this.arTouchTransform&&(r=this.userInput)!=null&&r.hasChanged){if(t.xr.rig){const l=t.xr.rig.gameObject;this.userInput.applyMatrixTo(l.matrix,!0),l.matrix.decompose(l.position,l.quaternion,l.scale),this.userInput.factor=l.scale.x}this.userInput.reset()}}}updateReticleAndHits(t,i,n,o){this._hits[i]=n.hit;let r=this._reticle[i];if(!r){if(this.customReticle)if(this.customReticle.asset)r=za(this.customReticle.asset);else{this.customReticle.loadAssetAsync();return}else r=new Q(new rC(.07,.09,32).rotateX(-Math.PI/2),new Me({side:_i,depthTest:!1,depthWrite:!1,transparent:!0,opacity:1,color:15658734})),r.name="AR Placement Reticle";if(Yx){const l=new bi(1);l.position.y+=.01,r.add(l)}this._reticle[i]=r,r.matrixAutoUpdate=!1,r.visible=!1}if(r.lastPos=r.lastPos||n.position.clone(),r.lastQuat=r.lastQuat||n.quaternion.clone(),r.position.copy(r.lastPos.lerp(n.position,this.context.time.deltaTime/.1)),r.lastPos.copy(r.position),r.quaternion.copy(r.lastQuat.slerp(n.quaternion,this.context.time.deltaTime/.05)),r.lastQuat.copy(r.quaternion),r.scale.set(o,o,o),this.customReticle&&this.applyViewBasedTransform(r),r.updateMatrix(),r.visible=!0,r.parent!==this.context.scene&&this.context.scene.add(r),this._placementStartTime<0&&(this._placementStartTime=this.context.time.realtimeSinceStartup),this.autoPlace)if(this.upVec.set(0,1,0).applyQuaternion(r.quaternion),this.upVec.dot($(0,1,0))>.9){let l=r["autoplace:timer"]||0;l>=1?(r.visible=!1,this.onPlaceScene(null)):(l+=this.context.time.deltaTime,r["autoplace:timer"]=l)}else r["autoplace:timer"]=0}onScaleChanged(){}onRevertSceneChanges(){var t;for(const i of this._reticle)i&&(i.visible=!1,i?.removeFromParent());this._reticle.length=0;for(let i=this._placementScene.children.length-1;i>=0;i--){const n=this._placementScene.children[i];this.context.scene.add(n)}(t=this._createdPlacementObject)==null||t.removeFromParent();for(const i of this._reparentedComponents)P.addComponent(i.originalObject,i.comp)}async onCreateAnchor(t,i){if(i.createAnchor===void 0){console.warn("Hit does not support creating an anchor",i),F()&&_e("Hit does not support creating an anchor");return}else{const n=await i.createAnchor(t.viewerPose.transform);t.running&&n&&(this._anchor=n)}}applyViewBasedTransform(t){const i=this.context.mainCamera,n=t,o=i.worldPosition,r=n.worldPosition;this.upVec.set(0,1,0).applyQuaternion(t.quaternion);const l=i.worldPosition;l&&t.position.clone().sub(l).angleTo(this.upVec)<Math.PI/2&&this.upVec.negate();const c=this.upVec.angleTo(this.worldUpVec)*180/Math.PI,h=30;c>h&&c<180-h||c<-h&&c>-180+h?(this.lookPoint.copy(t.position).add(this.upVec),this.lookPoint.y=t.position.y,t.lookAt(this.lookPoint)):(o.y=r.y,t.lookAt(o))}onApplyPose(t){var i,n,o,r;const l=(n=(i=Z.active)==null?void 0:i.rig)==null?void 0:n.gameObject;if(!l){console.warn("No rig object to place");return}(o=Z.active)!=null&&o.rigScale;const c=l.parent||this.context.scene;this._rigPlacementMatrix?(r=this._rigPlacementMatrix)==null||r.decompose(l.position,l.quaternion,l.scale):this._rigPlacementMatrix=l.matrix.clone(),this.applyViewBasedTransform(t),t.updateMatrix(),this.context.scene.add(t),t.attach(l),t.removeFromParent(),l.scale.set(this.arScale,this.arScale,this.arScale),l.position.multiplyScalar(this.arScale),l.updateMatrix(),this.invertForward&&l.matrix.premultiply(DT),l.matrix.premultiply(this._startOffset),l.matrix.decompose(l.position,l.quaternion,l.scale),c.add(l)}}a(Vn,"_eventListeners",{});const M0=class{constructor(s){a(this,"oneFingerDrag",!0),a(this,"twoFingerRotate",!0),a(this,"twoFingerScale",!0),a(this,"factor",1),a(this,"context"),a(this,"offset"),a(this,"plane"),a(this,"_scale",1),a(this,"_hasChanged",!1),a(this,"_enabled",!1),a(this,"currentlyUsedPointerIds",new Set),a(this,"currentlyUnusedPointerIds",new Set),a(this,"onPointerDownEarly",t=>{this.isActive&&t.stopPropagation()}),a(this,"onPointerDownLate",t=>{t.used?this.currentlyUsedPointerIds.add(t.pointerId):this.currentlyUsedPointerIds.size<=0&&this.currentlyUnusedPointerIds.add(t.pointerId)}),a(this,"onPointerUpEarly",t=>{this.currentlyUsedPointerIds.delete(t.pointerId),this.currentlyUnusedPointerIds.delete(t.pointerId)}),a(this,"prev",new Map),a(this,"_didMultitouch",!1),a(this,"touchStart",t=>{if(!t.defaultPrevented)for(let i=0;i<t.changedTouches.length;i++){const n=t.changedTouches[i],o=Y.isAndroidDevice()&&n.clientY<window.innerHeight*.1;this.prev.has(n.identifier)||this.prev.set(n.identifier,{ignore:o,x:0,z:0,screenx:0,screeny:0});const r=this.prev.get(n.identifier);if(r){const l=this.getPositionOnPlane(n.clientX,n.clientY);r.x=l.x,r.z=l.z,r.screenx=n.clientX,r.screeny=n.clientY}}}),a(this,"touchEnd",t=>{t.touches.length<=0&&(this._didMultitouch=!1);for(let i=0;i<t.changedTouches.length;i++){const n=t.changedTouches[i];this.prev.delete(n.identifier)}}),a(this,"touchMove",t=>{if(!t.defaultPrevented&&this.isActive){if(t.touches.length===1){if(this._didMultitouch)return;const i=t.touches[0],n=this.prev.get(i.identifier);if(!n||n.ignore)return;const o=this.getPositionOnPlane(i.clientX,i.clientY),r=o.x-n.x,l=o.z-n.z;if(r===0&&l===0)return;this.oneFingerDrag&&this.addMovement(r,l),n.x=o.x,n.z=o.z,n.screenx=i.clientX,n.screeny=i.clientY;return}else if(t.touches.length===2){this._didMultitouch=!0;const i=t.touches[0],n=t.touches[1],o=this.prev.get(i.identifier),r=this.prev.get(n.identifier);if(!o||!r)return;if(this.twoFingerRotate){const l=Math.atan2(i.clientY-n.clientY,i.clientX-n.clientX),c=Math.atan2(o.screeny-r.screeny,o.screenx-r.screenx),h=l-c;Math.abs(h)>.001&&this.addRotation(h)}if(this.twoFingerScale){const l=i.clientX-n.clientX,c=i.clientY-n.clientY,h=Math.sqrt(l*l+c*c),d=o.screenx-r.screenx,u=o.screeny-r.screeny,p=Math.sqrt(d*d+u*u),g=h-p;Math.abs(g)>2&&this.addScale(g)}o.screenx=i.clientX,o.screeny=i.clientY,r.screenx=n.clientX,r.screeny=n.clientY}}}),a(this,"_raycaster",new ld),a(this,"_intersection",new x),a(this,"_screenPos",new x),a(this,"_tempMatrix",new ne),this.context=s,this.offset=new ne,this.plane=new dr,this.plane.setFromNormalAndCoplanarPoint(M0.up,M0.zero)}reset(){this._scale=1,this.offset.identity()}get hasChanged(){return this._hasChanged}applyMatrixTo(s,t){this._hasChanged=!1,t?(this.offset.invert(),s.premultiply(this.offset)):s.multiply(this.offset)}get isActive(){return this.currentlyUsedPointerIds.size<=0&&this.currentlyUnusedPointerIds.size>0}enable(){this._enabled||(this._enabled=!0,this.context.input.addEventListener("pointerdown",this.onPointerDownEarly,{queue:Ci.Early}),this.context.input.addEventListener("pointerdown",this.onPointerDownLate,{queue:Ci.Late}),this.context.input.addEventListener("pointerup",this.onPointerUpEarly,{queue:Ci.Early}),window.addEventListener("touchstart",this.touchStart,{passive:!1}),window.addEventListener("touchmove",this.touchMove,{passive:!1}),window.addEventListener("touchend",this.touchEnd,{passive:!1}))}disable(){this._enabled&&(this._enabled=!1,this.context.input.removeEventListener("pointerdown",this.onPointerDownEarly,{queue:Ci.Early}),this.context.input.removeEventListener("pointerdown",this.onPointerDownLate,{queue:Ci.Late}),this.context.input.removeEventListener("pointerup",this.onPointerUpEarly,{queue:Ci.Early}),window.removeEventListener("touchstart",this.touchStart),window.removeEventListener("touchmove",this.touchMove),window.removeEventListener("touchend",this.touchEnd))}getPositionOnPlane(s,t){const i=this.context.mainCamera;return this._screenPos.x=s/window.innerWidth*2-1,this._screenPos.y=-(t/window.innerHeight)*2+1,this._screenPos.z=1,this._screenPos.unproject(i),this._raycaster.set(i.position,this._screenPos.sub(i.position)),this._raycaster.ray.intersectPlane(this.plane,this._intersection),this._intersection}addMovement(s,t){s/=this._scale,t/=this._scale,s*=this.factor,t*=this.factor,this.offset.elements[12]+=s,this.offset.elements[14]+=t,(s!==0||t!==0)&&(this._hasChanged=!0)}addScale(s){s/=window.innerWidth,s*=-1,this._scale*=1+s,this._tempMatrix.makeScale(1-s,1-s,1-s),this.offset.premultiply(this._tempMatrix),s!==0&&(this._hasChanged=!0)}addRotation(s){s*=-1,this._tempMatrix.makeRotationY(s),this.offset.premultiply(this._tempMatrix),s!==0&&(this._hasChanged=!0)}};let bp=M0;a(bp,"up",new x(0,1,0)),a(bp,"zero",new x(0,0,0)),a(bp,"one",new x(1,1,1));const Uo=O("debugautosync"),R0=Symbol("syncerId");class BT{constructor(){a(this,"_syncers",{})}getOrCreateSyncer(t){if(!t.guid)return null;if(this._syncers[t.guid])return this._syncers[t.guid];const i=new FT(t);return i[R0]=t.guid,this._syncers[i[R0]]=i,i}removeSyncer(t){delete this._syncers[t[R0]]}}const T0=new BT;class FT{constructor(t){a(this,"comp"),a(this,"hasChanges",!1),a(this,"changedProperties",{}),a(this,"_isReceiving",!1),a(this,"_isInit",!1),a(this,"onHandleSending",()=>{if(!this.hasChanges)return;this.hasChanges=!1;const i=this.comp.context.connection;if(!i||!i.isConnected||!i.isInRoom){for(const n in this.changedProperties)delete this.changedProperties[n];return}for(const n in this.changedProperties){const o=this.changedProperties[n];Uo&&console.log("SEND",this.comp.guid,this.networkingKey),i.send(this.networkingKey,{guid:this.comp.guid,property:n,data:o},bs.Queued),delete this.changedProperties[n]}}),a(this,"onHandleReceiving",i=>{if(Uo&&console.log("SYNCFIELD RECEIVE",this.comp.name,this.comp.guid,i),!!this._isInit&&this.comp&&i.guid===this.comp.guid)try{this._isReceiving=!0,this.comp[i.property]=i.data}catch(n){console.error(n)}finally{this._isReceiving=!1}}),this.comp=t}get networkingKey(){return this.comp.guid}init(t){if(this._isInit)return;this._isInit=!0,this.comp=t,this.comp.context.post_render_callbacks.push(this.onHandleSending),this.comp.context.connection.beginListen(this.networkingKey,this.onHandleReceiving);const i=this.comp.context.connection.tryGetState(this.comp.guid);i&&this.onHandleReceiving(i)}destroy(){this._isInit&&(this.comp.context.post_render_callbacks.splice(this.comp.context.post_render_callbacks.indexOf(this.onHandleSending),1),this.comp.context.connection.stopListen(this.networkingKey,this.onHandleReceiving),this.comp=null,this._isInit=!1)}notifyChanged(t,i){this._isReceiving||(Uo&&console.log("Property changed: "+t,i),this.hasChanges=!0,this.changedProperties[t]=i)}}function zT(s,t){let i=t!==s;return!i&&s&&t&&(Array.isArray(s)&&Array.isArray(t)||typeof s=="object"&&typeof t=="object")&&(i=!0),i}const mh=Symbol("AutoSyncHandler");function UT(s){if(s[mh])return s[mh];const t=T0.getOrCreateSyncer(s);return t?.init(s),s[mh]=t,t}function NT(s){const t=s[mh];t&&(T0.removeSyncer(t),t.destroy(),delete s[mh])}const E0=function(s=null){return function(t,i){var n;let o="";typeof i=="string"?o=i:o=i.name;let r=null,l;typeof s=="string"?l=t[s]:typeof s=="function"&&(l=s),l==null&&(F()||Uo)&&s!=null&&console.warn('syncField: no callback function found for property "'+o+'"','"'+s+'"');const c=t,h=c.__internalAwake;if(typeof h!="function"){(Uo||F())&&console.error('@syncField can currently only used on Needle Engine Components, custom object of type "'+((n=t?.constructor)==null?void 0:n.name)+'" is not supported',t);return}Uo&&console.log(o);const d=Symbol(o);c.__internalAwake=function(){if(this[d]!==void 0)return;this[d]=this[o],r=T0.getOrCreateSyncer(this);const p=Object.getOwnPropertyDescriptor(this,o);if(p?.set===void 0){let g=!1;Object.defineProperty(this,o,{set:function(y){var f;const v=this[d];if(this[d]=y,g){(F()||Uo)&&console.warn("Recursive call detected",o);return}g=!0;try{const b=zT(y,v);Uo&&console.log("SyncField assignment",o,"changed?",b,y,l),b&&l?.call(this,y,v)!==!1&&((f=UT(this))==null||f.notifyChanged(o,y))}finally{g=!1}},get:function(){return this[d]},configurable:!0,enumerable:!0})}r?.init(this),h.call(this)};const u=c.__internalDestroy;c.__internalDestroy=function(){NT(this),u.call(this)}}};var WT=Object.defineProperty,VT=Object.getOwnPropertyDescriptor,_p=(s,t,i,n)=>{for(var o=n>1?void 0:n?VT(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&WT(t,i,o),o};const ti=O("debugplayersync"),Kx=class extends A{constructor(){super(...arguments),a(this,"autoSync",!0),a(this,"asset"),a(this,"onPlayerSpawned"),a(this,"_localInstance"),a(this,"onJoinedRoom",()=>{ti&&console.log("PlayerSync.joinedRoom. autoSync is set to "+this.autoSync),this.autoSync&&this.getInstance()}),a(this,"destroyInstance",()=>{var s;(s=this._localInstance)==null||s.then(t=>{ti&&console.log("PlayerSync.destroyInstance",t),yc(t,this.context.connection,!0,{saveInRoom:!1})}),this._localInstance=void 0})}static async setupFrom(s,t){const i=le.getOrCreateFromUrl(s);if(!i.asset){const r=await i.loadAssetAsync();r&&P.getOrAddComponent(r,ji)}const n=new Kx;n._internalInit(t),n.asset=i;const o=new j;return o.guid=s,P.addComponent(o,n),n}awake(){this.watchTabVisible(),this.onPlayerSpawned||(this.onPlayerSpawned=new ke)}onEnable(){this.context.connection.beginListen(ie.RoomStateSent,this.onJoinedRoom),this.context.connection.beginListen(ie.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(ie.LeftRoom,this.destroyInstance),this.context.connection.isInRoom&&this.onJoinedRoom()}onDisable(){this.context.connection.stopListen(ie.RoomStateSent,this.onJoinedRoom),this.context.connection.stopListen(ie.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(ie.LeftRoom,this.destroyInstance)}async getInstance(){var s,t,i,n,o,r;if(this._localInstance)return this._localInstance;if(ti&&console.log("PlayerSync.createInstance",(s=this.asset)==null?void 0:s.url),!((t=this.asset)!=null&&t.asset)&&!((i=this.asset)!=null&&i.url))return console.error('PlayerSync: can not create an instance because "asset" is not set and or has no URL!'),null;this.gameObject.guid||console.warn("PlayerSync: gameObject has no guid! This might cause issues with syncing the player state."),this._localInstance=(n=this.asset)==null?void 0:n.instantiateSynced({parent:this.gameObject,deleteOnDisconnect:!0},!0);const l=await this._localInstance;if(l){const c=P.getComponentsInChildren(l,ji);if(ti&&console.log(`PlayerSync.createInstance: found ${c?.length} PlayerState components. Owner: ${this.context.connection.connectionId}`),c!=null&&c.length){for(const h of c)h.owner=this.context.connection.connectionId;(o=this.onPlayerSpawned)==null||o.invoke(l)}else this._localInstance=void 0,console.error("<strong>Failed finding PlayerState on "+((r=this.asset)==null?void 0:r.url)+"</strong>: please make sure the asset has a PlayerState component!"),P.destroySynced(l)}else this._localInstance=void 0,console.warn("PlayerSync: failed instantiating asset!");return this._localInstance}watchTabVisible(){window.addEventListener("visibilitychange",s=>{if(document.visibilityState==="visible")for(let t=ji.all.length-1;t>=0;t--){const i=ji.all[t];(!i.owner||!this.context.connection.userIsInRoom(i.owner))&&i.doDestroy()}})}};let bl=Kx;_p([m()],bl.prototype,"autoSync",2),_p([m(le)],bl.prototype,"asset",2),_p([m(ke)],bl.prototype,"onPlayerSpawned",2);var Zx=(s=>(s.OwnerChanged="ownerChanged",s))(Zx||{}),gh;const Tt=(gh=class extends A{constructor(){super(...arguments),a(this,"onOwnerChangeEvent",new ke),a(this,"onFirstOwnerChangeEvent",new ke),a(this,"hasOwner",!1),a(this,"owner"),a(this,"dontDestroy",!1),a(this,"onUserLeftRoom",s=>{if(s.userId===this.owner){ti&&console.log("PLAYERSYNC LEFT",this.owner),this.doDestroy();return}})}static get all(){return Tt._all}static get local(){return Tt._local}static getFor(s){if(s instanceof j)return P.getComponentInParent(s,Tt);if(s instanceof A)return P.getComponentInParent(s.gameObject,Tt)}static isLocalPlayer(s){const t=Tt.getFor(s);return t?.isLocalPlayer??!1}static addEventListener(s,t){return this._callbacks[s]||(this._callbacks[s]=[]),this._callbacks[s].push(t),t}static removeEventListener(s,t){if(!this._callbacks[s])return;const i=this._callbacks[s].indexOf(t);i>=0&&this._callbacks[s].splice(i,1)}static dispatchEvent(s,t){if(this._callbacks[s])for(const i of this._callbacks[s])i(t)}get isLocalPlayer(){return this.owner===this.context.connection.connectionId}onOwnerChange(s,t){var i,n;ti&&console.log(`PlayerSync.onOwnerChange: ${t} \u2192 ${s} (me: ${this.context.connection.connectionId})`);const o=Tt._local.indexOf(this);o>=0&&Tt._local.splice(o,1);const r={playerState:this,oldValue:t,newValue:s};if(this.hasOwner||(this.hasOwner=!0,(i=this.onFirstOwnerChangeEvent)==null||i.invoke(r)),(n=this.onOwnerChangeEvent)==null||n.invoke(r),this.owner===this.context.connection.connectionId){Tt._local.push(this);const c=new CustomEvent("local-owner-changed",{detail:r});this.dispatchEvent(c)}const l=new CustomEvent("owner-changed",{detail:r});this.dispatchEvent(l),Tt.dispatchEvent("ownerChanged",l)}awake(){Tt.all.push(this),ti&&console.log("Registered new PlayerState",this.guid,Tt.all.length-1,Tt.all),this.context.connection.beginListen(ie.UserLeftRoom,this.onUserLeftRoom)}async start(){ti&&console.log("PLAYERSTATE.START, owner: "+this.owner,this.context.connection.usersInRoom([])),this.owner?(this.context.connection.isInRoom||await gs(300),this.context.connection.userIsInRoom(this.owner)==!1&&(ti&&console.log(`PlayerSync.start \u2192 doDestroy "${this.name}" because user "${this.owner}" is not in room anymore...`,"Currently in room:",...this.context.connection.usersInRoom()),this.doDestroy())):this.owner||(ti&&console.warn("PlayerState.start \u2192 owner is undefined!",this.name),setTimeout(()=>{!this.destroyed&&!this.owner?this.dontDestroy?ti&&console.warn("PlayerState.start \u2192 owner is still undefined but dontDestroy is set to true",this.name):(ti&&console.warn(`PlayerState.start \u2192 owner is still undefined: destroying "${this.name}" instance now`),this.doDestroy()):ti&&console.log("PlayerState.start \u2192 owner is assigned",this.owner)},2e3))}doDestroy(){ti&&console.log("PlayerSync.doDestroy \u2192 syncDestroy",this.name),yc(this.gameObject,this.context.connection,!0,{saveInRoom:!1})}onDestroy(){if(ti&&console.warn("PlayerState.onDestroy",this.owner),this.context.connection.stopListen(ie.UserLeftRoom,this.onUserLeftRoom),Tt.all.splice(Tt.all.indexOf(this),1),this.isLocalPlayer){const s=Tt._local.indexOf(this);s>=0&&Tt._local.splice(s,1)}}},a(gh,"_all",[]),a(gh,"_local",[]),a(gh,"_callbacks",{}),gh);let ji=Tt;_p([E0(ji.prototype.onOwnerChange)],ji.prototype,"owner",2);var HT=Object.defineProperty,$T=Object.getOwnPropertyDescriptor,_l=(s,t,i,n)=>{for(var o=n>1?void 0:n?$T(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&HT(t,i,o),o};class an extends A{constructor(){super(...arguments),a(this,"position","bottom"),a(this,"showNeedleLogo",!0),a(this,"showSpatialMenu"),a(this,"createFullscreenButton"),a(this,"createMuteButton"),a(this,"createQRCodeButton")}onEnable(){this.applyOptions()}applyOptions(){this.context.menu.setPosition(this.position),this.context.menu.showNeedleLogo(this.showNeedleLogo),this.createFullscreenButton===!0&&this.context.menu.showFullscreenOption(!0),this.createMuteButton===!0&&this.context.menu.showAudioPlaybackOption(!0),this.showSpatialMenu===!0&&this.context.menu.showSpatialMenu(this.showSpatialMenu),this.createQRCodeButton===!0&&(Y.isMobileDevice()||this.context.menu.showQRCodeButton(!0))}}_l([m()],an.prototype,"position",2),_l([m()],an.prototype,"showNeedleLogo",2),_l([m()],an.prototype,"showSpatialMenu",2),_l([m()],an.prototype,"createFullscreenButton",2),_l([m()],an.prototype,"createMuteButton",2),_l([m()],an.prototype,"createQRCodeButton",2);var qT=Object.defineProperty,GT=Object.getOwnPropertyDescriptor,A0=(s,t,i,n)=>{for(var o=n>1?void 0:n?GT(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&qT(t,i,o),o};const fh=O("debugwebxr"),Jx=new V().setFromAxisAngle(new x(0,1,0),Math.PI);class No extends A{constructor(){super(...arguments),a(this,"head"),a(this,"leftHand"),a(this,"rightHand"),a(this,"_leftHandMeshes"),a(this,"_rightHandMeshes"),a(this,"_syncTransforms")}async onEnterXR(t){if(!this.activeAndEnabled)return;fh&&console.warn("AVATAR ENTER XR",this.guid,this.sourceId,this,this.activeAndEnabled),this._syncTransforms&&(this._syncTransforms.length=0),await this.prepareAvatar();const i=ji.getFor(this);if(i!=null&&i.owner){const n=this.gameObject.addComponent(Mt);n.avatar=this.gameObject,n.connectionId=i.owner}else this.context.connection.isConnected?console.error("No player state found for avatar",this):i&&!this.context.connection.isConnected&&(i.dontDestroy=!0)}onLeaveXR(t){const i=this.gameObject.getComponent(Mt);i&&i.destroy()}onUpdateXR(t){var i,n;if(!this.activeAndEnabled)return;const o=ji.isLocalPlayer(this);if(!o)return;const r=t.xr;if(r.rig&&r.rig.gameObject!==this.gameObject.parent&&(this.gameObject.position.set(0,0,0),this.gameObject.rotation.set(0,0,0),this.gameObject.scale.set(1,1,1),r.rig.gameObject.add(this.gameObject)),this._syncTransforms&&o)for(const u of this._syncTransforms)u.fastMode=!0,u.isOwned()||u.requestOwnership();if(this.head&&this.context.mainCamera){const u=this.head.asset;if(u.position.copy(this.context.mainCamera.position),u.position.x*=-1,u.position.z*=-1,u.quaternion.copy(this.context.mainCamera.quaternion),u.quaternion.x*=-1,this.context.time.frameCount%10===0&&this.head.asset){const p=P.getComponentsInChildren(this.head.asset,Ei);for(const g of p)g.enabled=!1,g.gameObject.visible=!1}}const l=t.xr.leftController,c=(i=this.leftHand)==null?void 0:i.asset;l&&c?(c.position.copy(l.gripPosition),c.quaternion.copy(l.gripQuaternion),c.quaternion.multiply(Jx),c.visible=l.isTracking,this.updateHandVisibility(l,c,this._leftHandMeshes)):c&&c.visible&&(c.visible=!1);const h=t.xr.rightController,d=(n=this.rightHand)==null?void 0:n.asset;h&&d?(d.position.copy(h.gripPosition),d.quaternion.copy(h.gripQuaternion),d.quaternion.multiply(Jx),d.visible=h.isTracking,this.updateHandVisibility(h,d,this._rightHandMeshes)):d&&d.visible&&(d.visible=!1)}onBeforeRender(){this.context.xr&&this.context.time.frame%10===0&&this.updateRemoteAvatarVisibility()}updateHandVisibility(t,i,n){if(n){const o=t.model&&t.model.visible&&t.model!==i;n.forEach(r=>{Pn(r,!o)})}}updateRemoteAvatarVisibility(){var t,i,n;if(this.context.connection.isConnected){const o=ji.getFor(this);if(o&&o.isLocalPlayer==!1){const r=Z.getXRSync(this.context);if(r&&r.hasState(o.owner)){this.tryFindAvatarObjectsIfMissing();const l=(t=this.leftHand)==null?void 0:t.asset;l&&(l.visible=r?.isTracking(o.owner,"left")??!1);const c=(i=this.rightHand)==null?void 0:i.asset;c&&(c.visible=r?.isTracking(o.owner,"right")??!1)}if((n=this.head)!=null&&n.asset){const l=P.getComponentsInChildren(this.head.asset,Ei);for(const c of l)c.enabled=!1,c.gameObject.visible=!0}}}}tryFindAvatarObjectsIfMissing(){if(!this.head||!this.leftHand||!this.rightHand){const t={head:this.head,leftHand:this.leftHand,rightHand:this.rightHand};Wb.tryFindAvatarObjects(this.gameObject,this.sourceId||"",t),t.head&&(this.head=t.head),t.leftHand&&(this.leftHand=t.leftHand),t.rightHand&&(this.rightHand=t.rightHand)}}async prepareAvatar(){var t,i;if(this.tryFindAvatarObjectsIfMissing(),this.head)this.head instanceof j&&(this.head=new le("",this.sourceId,this.head));else{const n=new j;n.name="Head";const o=mo.createPrimitive(_r.Cube);n.add(o),this.gameObject.add(n),this.head=new le("",this.sourceId,n),fh&&console.log("Create head",n)}if(this.rightHand)this.rightHand instanceof j&&(this.rightHand=new le("",this.sourceId,this.rightHand));else{const n=new j;n.name="Right Hand",this.gameObject.add(n),this.rightHand=new le("",this.sourceId,n),fh&&console.log("Create right hand",n)}if(this.leftHand)this.leftHand instanceof j&&(this.leftHand=new le("",this.sourceId,this.leftHand));else{const n=new j;n.name="Left Hand",this.gameObject.add(n),this.leftHand=new le("",this.sourceId,n),fh&&console.log("Create left hand",n)}await this.loadAvatarObjects(this.head,this.leftHand,this.rightHand),this._leftHandMeshes=[],(t=this.leftHand.asset)==null||t.traverse(n=>{n!=null&&n.isMesh&&this._leftHandMeshes.push(n)}),this._rightHandMeshes=[],(i=this.rightHand.asset)==null||i.traverse(n=>{n!=null&&n.isMesh&&this._rightHandMeshes.push(n)}),ji.isLocalPlayer(this.gameObject)&&(this._syncTransforms=P.getComponentsInChildren(this.gameObject,$s))}async loadAvatarObjects(t,i,n){const o=t.loadAssetAsync(),r=i.loadAssetAsync(),l=n.loadAssetAsync(),c=new Array;o&&c.push(o),r&&c.push(r),l&&c.push(l);const h=await yd(c);fh&&console.log("Avatar loaded results:",h)}}A0([m(le)],No.prototype,"head",2),A0([m(le)],No.prototype,"leftHand",2),A0([m(le)],No.prototype,"rightHand",2);var XT=Object.defineProperty,QT=Object.getOwnPropertyDescriptor,wp=(s,t,i,n)=>{for(var o=n>1?void 0:n?QT(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&XT(t,i,o),o};const Hn=O("debugwebxr"),Wo=new Array;class ln extends A{constructor(){super(...arguments),a(this,"createControllerModel",!0),a(this,"createHandModel",!0),a(this,"customLeftHand"),a(this,"customRightHand"),a(this,"_models",new Array)}supportsXR(t){return t==="immersive-vr"||t==="immersive-ar"}async onXRControllerAdded(t){var i;if(!(t.xr.isVR||t.xr.isPassThrough))return;const{controller:n}=t;if(Hn&&console.warn("Add Controller Model for",n.side,n.index),this.createControllerModel||this.createHandModel){if(n.hand){if(this.createHandModel){const o=await this.loadHandModel(this,n);if(!o||!n.connected||!n.isHand){o!=null&&o.handObject&&Fa(o.handObject,!1),(i=o?.handObject)==null||i.destroy();return}this._models.push({controller:n,model:o.handObject,handmesh:o.handmesh}),this._models.sort((r,l)=>r.controller.index-l.controller.index),this.scene.add(o.handObject),n.model=o.handObject}}else if(this.createControllerModel){const o=await n.getModelUrl();if(o){const r=await this.loadModel(n,o);if(!r||!n.connected||n.isHand)return;this._models.push({controller:n,model:r}),this._models.sort((l,c)=>l.controller.index-c.controller.index),this.scene.add(r),r.traverse(l=>{l.layers.set(2),l.matrixAutoUpdate=!1,l.updateMatrix()}),n.model=r}else n.targetRayMode!=="transient-pointer"&&console.warn("XRControllerModel: no model found for "+n.side)}}}onXRControllerRemoved(t){console.debug("XR Controller Removed",t.controller.side,t.controller.index);const i=this._models.findIndex(o=>o.controller===t.controller),n=this._models[i];n&&(this._models.splice(i,1),n.model&&(Fa(n.model,!1),n.model.destroy(),n.model=void 0))}onLeaveXR(t){for(const i of this._models)i&&(i.model&&(Fa(i.model,!1),i.model.destroy(),i.model=void 0),i.controller.model===i.model&&(i.controller.model=null));this._models.length=0}onBeforeRender(){if(Z.active&&(Hn&&(Wo[0]=Date.now()),this.updateRendering(Z.active),Hn)){const t=Date.now()-Wo[0];Wo.push(t),Wo.length>=30&&(Wo[0]=0,Wo.reduce((i,n)=>i+n,0)/Wo.length,Wo.length=0)}}updateRendering(t){var i,n,o,r,l;for(let c=0;c<this._models.length;c++){const h=this._models[c];if(!h)continue;const d=h.controller;if(!d.connected){Hn&&console.warn("XRControllerModel.onUpdateXR: controller is not connected anymore",d.side,d.hand);continue}if(h.model&&!h.handmesh)h.model.matrixAutoUpdate=!1,h.model.matrix.copy(d.gripMatrix),h.model.visible=d.isTracking,(i=t.rig)==null||i.gameObject.add(h.model);else if(d.inputSource.hand&&h.handmesh){const u=t.referenceSpace,p=this.context.renderer.xr.getHand(d.index);if(u&&t.frame.getJointPose){for(const g of d.inputSource.hand.values()){const y=p.joints[g.jointName];if(y){const f=d.getHandJointPose(g);if(f){const v=f.transform.position,b=f.transform.orientation;y.position.copy(v),y.quaternion.copy(b),y.matrixAutoUpdate=!1}y.visible=f!=null}}h.model&&(h.model.visible=d.isTracking,h.model.visible&&h.model.parent!==((n=t.rig)==null?void 0:n.gameObject)&&((o=t.rig)==null||o.gameObject.add(h.model))),(r=h.model)!=null&&r.visible&&((l=h.handmesh)==null||l.updateMesh(),h.model.matrixAutoUpdate=!1,h.model.matrix.identity(),h.model.applyMatrix4(Ma))}}}}async loadModel(t,i){var n;if(!t.connected)return console.warn("XRControllerModel.onXRControllerAdded: controller is not connected anymore",t.side),null;const o=await le.getOrCreate("",i).instantiate();return Fa(o),(n=Z.active)!=null&&n.isPassThrough&&o.traverseVisible(r=>{this.makeOccluder(r)}),o}async loadHandModel(t,i){const n=this.context,o=n.renderer.xr.getHand(i.index);o||(Hn?q.DrawLabel(i.rayWorldPosition,"No hand found for index "+i.index,.05,5):console.warn("No hand found for index "+i.index));const r=new mr;bu(r,n),await Yu(r,n,this.sourceId??"");const l=Qu(r);let c="";const h=i.side==="left"?this.customLeftHand:this.customRightHand;h?(c=h.url.split(".").slice(0,-1).join("."),r.setPath("")):(c=i.inputSource.handedness==="left"?"left":"right",r.setPath("https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles/generic-hand/"));const d=new j;Fa(d);const u=new zC(d,o,r.path,c,r,p=>{var g;const y=l.gltf;((g=y?.scene.children)==null?void 0:g.length)===0&&(y.scene.children[0]=p),ms().createBuiltinComponents(t.context,t.sourceId||c,l.gltf,null,l),p.traverse(f=>{var v;f.layers.set(2),(v=Z.active)!=null&&v.isPassThrough&&!h&&this.makeOccluder(f),f instanceof Q&&et.assignMeshLOD(f,0)}),i.connected||(Hn&&q.DrawLabel(i.rayWorldPosition,"Hand is loaded but not connected anymore",.05,5),p.removeFromParent())});if(Hn&&d.add(new bi(.5)),i.inputSource.hand){Hn&&console.log(i.inputSource.hand);for(const p of i.inputSource.hand.values())if(o.joints[p.jointName]===void 0){const g=new ro;g.matrixAutoUpdate=!1,g.visible=!0,o.joints[p.jointName]=g,o.add(g)}}else Hn&&q.DrawLabel(i.rayWorldPosition,"No inputSource.hand found for index "+i.index,.05,5);return{handObject:d,handmesh:u}}makeOccluder(t){if(t instanceof Q){let i=t.material;i instanceof Oe&&(i=t.material=i.clone(),i.depthWrite=!0,i.depthTest=!0,i.colorWrite=!1,t.receiveShadow=!1,t.renderOrder=-100)}}}a(ln,"factory",new FC),wp([m()],ln.prototype,"createControllerModel",2),wp([m()],ln.prototype,"createHandModel",2),wp([m(le)],ln.prototype,"customLeftHand",2),wp([m(le)],ln.prototype,"customRightHand",2);class xp extends A{}var YT=Object.defineProperty,KT=Object.getOwnPropertyDescriptor,Vo=(s,t,i,n)=>{for(var o=n>1?void 0:n?KT(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&YT(t,i,o),o};const I0=O("debugwebxr");class Li extends A{constructor(){super(...arguments),a(this,"movementSpeed",1.5),a(this,"rotationStep",30),a(this,"useTeleport",!0),a(this,"usePinchToTeleport",!0),a(this,"useTeleportTarget",!1),a(this,"useTeleportFade",!1),a(this,"showRays",!0),a(this,"showHits",!0),a(this,"isXRMovementHandler",!0),a(this,"xrSessionMode","immersive-vr"),a(this,"_didApplyRotation",!1),a(this,"_didTeleport",!1),a(this,"_teleportBuffer",new Array),a(this,"_plane",null),a(this,"_lines",[]),a(this,"_hitDiscs",[]),a(this,"_hitDistances",[]),a(this,"_lastHitDistances",[]),a(this,"hitPointRaycastFilter",t=>t.type==="SkinnedMesh"?"continue in children":!0)}onUpdateXR(t){const i=t.xr.rig;if(!(i!=null&&i.gameObject)||t.xr.isPassThrough)return;const n=t.xr.leftController,o=t.xr.rightController;n&&this.onHandleMovement(n,i.gameObject),o&&(this.onHandleRotation(o,i.gameObject),this.useTeleport&&this.onHandleTeleport(o,i.gameObject))}onLeaveXR(t){for(const i of this._lines)i.removeFromParent();for(const i of this._hitDiscs)i?.removeFromParent()}onBeforeRender(){var t;(t=this.context.xr)!=null&&t.running&&(this.showRays&&this.renderRays(this.context.xr),this.showHits&&this.renderHits(this.context.xr))}onHandleMovement(t,i){const n=t.getStick("xr-standard-thumbstick");if(n.x!=0||n.y!=0){const o=$(n.x,0,n.y);o.multiplyScalar(this.context.time.deltaTimeUnscaled*this.movementSpeed);const r=Ke(i);o.multiplyScalar(r.x),o.applyQuaternion(t.xr.poseOrientation),o.y=0,o.applyQuaternion(i.worldQuaternion),i.position.add(o),i.updateWorldMatrix(!1,!1);for(const l of i.children)l.updateWorldMatrix(!1,!1)}}onHandleRotation(t,i){if(t._isMxInk)return;const n=t.getStick("xr-standard-thumbstick").x;if(this._didApplyRotation)Math.abs(n)<.3&&(this._didApplyRotation=!1);else if(Math.abs(n)>.5){this._didApplyRotation=!0;const o=n>0?1:-1,r=ee(this.context.mainCamera).clone();i.rotateY(o*W.toRadians(this.rotationStep));const l=ee(this.context.mainCamera).clone().sub(r);l.y=0,i.position.sub(l)}}onHandleTeleport(t,i){var n,o,r,l,c;let h=0;if(t.hand&&this.usePinchToTeleport&&t.isTeleportGesture){const d=t.getPointerId("primary");if(d!=null&&this.context.input.getIsPointerIdInUse(d))return;const u=t.getGesture("pinch");u&&(h=u.value)}else h=(n=t.getStick("xr-standard-thumbstick"))==null?void 0:n.y;if(this._didTeleport)h>=0&&h<.4?this._didTeleport=!1:h<0&&h>-.4&&(this._didTeleport=!1);else if(h>.8){this._didTeleport=!0;const d=this.context.physics.raycastFromRay(t.ray)[0];if(d&&d.object instanceof xa){const p=(o=d.normal)==null?void 0:o.dot($(0,1,0));if(p!==void 0&&p<.4)return}let u=d?.point;if(!u&&!this.useTeleportTarget){this._plane||(this._plane=new dr(new x(0,1,0),0));const p=i.worldPosition;this._plane.setFromNormalAndCoplanarPoint(new x(0,1,0),p);const g=t.ray;u=p.clone(),this._plane.intersectLine(new aC(g.origin,$(g.direction).multiplyScalar(1e4).add(g.origin)),u),u.distanceTo(p)>i.scale.x*10&&(u=null)}if(u){if(this.useTeleportTarget&&!P.getComponentInParent(d.object,xp))return;const p=u.clone();if(I0&&q.DrawSphere(u,.025,16711680,5),(r=this.context.mainCamera)==null?void 0:r.position){const g=(l=this.context.xr)==null?void 0:l.getUserOffsetInRig();g&&(g.y=0,p.sub(g),I0&&q.DrawWireSphere(g.add(p),.025,65280,5))}this._teleportBuffer.push(i.matrix.clone()),this._teleportBuffer.length>10&&this._teleportBuffer.shift(),this.useTeleportFade?(c=t.xr.fadeTransition())==null||c.then(()=>{i.worldPosition=p}):i.worldPosition=p}}else if(h<-.8&&(this._didTeleport=!0,this._teleportBuffer.length>0)){const d=this._teleportBuffer.pop();d&&d.decompose(i.position,i.quaternion,i.scale)}}renderRays(t){var i;for(let n=0;n<this._lines.length;n++){const o=this._lines[n];o&&(o.visible=!1)}for(let n=0;n<t.controllers.length;n++){const o=t.controllers[n];let r=this._lines[n];if(!o.connected||!o.isTracking||!o.ray||o.targetRayMode==="transient-pointer"||!o.hasSelectEvent){r&&(r.visible=!1);continue}r||(r=this.createRayLineObject(),r.scale.z=.5,this._lines[n]=r),o.updateRayWorldPosition(),o.updateRayWorldQuaternion();const l=o.rayWorldPosition,c=o.rayWorldQuaternion;r.position.copy(l),r.quaternion.copy(c);const h=t.rigScale,d=this.usePinchToTeleport&&o.isTeleportGesture,u=this._lastHitDistances[n],p=this._hitDistances[n]!=null,g=u??h;r.scale.set(h,h,g),r.visible=!0,r.layers.disableAll(),r.layers.enable(2);let y=r.material.opacity;d?y=1:this.showHits&&g<t.rigScale*.5?y=0:(i=o.getButton("primary"))!=null&&i.pressed?y=.5:y=p?.2:.1,r.material.opacity=W.lerp(r.material.opacity,y,this.context.time.deltaTimeUnscaled/.1),r.parent!==this.context.scene&&this.context.scene.add(r)}}renderHits(t){var i;for(const n of this._hitDiscs){if(!n)continue;const o=n.controller;if(!o||!o.connected||!o.isTracking){n.visible=!1;continue}}for(let n=0;n<t.controllers.length;n++){const o=t.controllers[n];if(!o.connected||!o.isTracking||!o.ray||!o.hasSelectEvent)continue;let r=this._hitDiscs[n],l=!0;const c=o.getPointerId("primary");c!=null&&this.context.input.getIsPointerIdInUse(c)&&(r&&(r.visible=!1),this._hitDistances[n]=null,this._lastHitDistances[n]=0,l=!1);const h=this.context.time.smoothedFps>=59?1:10;if((this.context.time.frame+o.index)%h!==0&&(l=!1),!l){const p=this._hitDiscs[n];p&&p.visible&&p.hit&&this.updateHitPointerPosition(o,p,p.hit.distance);continue}const d=this.context.physics.raycastFromRay(o.ray,{testObject:this.hitPointRaycastFilter,precise:!1});let u=d.find(p=>this.usePinchToTeleport&&o.isTeleportGesture?!0:this.isObjectWithInteractiveComponent(p.object));if(u||(u=d[0]),r&&(r.controller=o,r.hit=u),this._hitDistances[n]=u?.distance||null,u){this._lastHitDistances[n]=u.distance;const p=t.rigScale??1;I0&&(q.DrawWireSphere(u.point,.025*p,16711680),q.DrawLabel($(0,.2,0).add(u.point),u.object.name,.02,0)),r||(r=this.createHitPointObject(),this._hitDiscs[n]=r),r.hit=u,r.visible=u.distance>p*.05;let g=.01*(p+u.distance);const y=(i=o.getButton("primary"))==null?void 0:i.pressed;y&&(g*=1.1),r.scale.set(g,g,g),r.layers.set(2);let f=r.material.opacity;if(y?f=1:f=u.distance<.15*p?.2:.6,r.material.opacity=W.lerp(r.material.opacity,f,this.context.time.deltaTimeUnscaled/.1),r.visible){if(u.normal){this.updateHitPointerPosition(o,r,u.distance);const v=u.normal.applyQuaternion(Se(u.object));r.quaternion.setFromUnitVectors(ZT,v)}else this.updateHitPointerPosition(o,r,u.distance);r.parent!==this.context.scene&&this.context.scene.add(r)}}else this._hitDiscs[n]&&(this._hitDiscs[n].visible=!1)}}isObjectWithInteractiveComponent(t,i=0){return Pu(t)||t.isUI===!0?!0:t.isScene?!1:t.parent?this.isObjectWithInteractiveComponent(t.parent,i+1):!1}updateHitPointerPosition(t,i,n){const o=$(t.rayWorldPosition);o.add($(0,0,n-.01).applyQuaternion(t.rayWorldQuaternion)),i.position.lerp(o,this.context.time.deltaTimeUnscaled/.05)}createHitPointObject(){const t=new Q(new rd(.3,6,6),new Me({color:15658734,opacity:.7,transparent:!0,depthTest:!1,depthWrite:!1,side:_i}));return t.layers.disableAll(),t.layers.enable(2),t}createRayLineObject(){const t=new UC;t.layers.disableAll(),t.layers.enable(2);const i=new NC;t.geometry=i;const n=new Float32Array(9);n.set([0,0,.02,0,0,.4,0,0,1]),i.setPositions(n);const o=new Float32Array(9);o.set([1,1,1,.1,.1,.1,0,0,0]),i.setColors(o);const r=new WC({color:16777215,vertexColors:!0,worldUnits:!0,linewidth:.004,transparent:!0,depthWrite:!1,blending:nv,dashed:!1});return t.material=r,t}}Vo([m()],Li.prototype,"movementSpeed",2),Vo([m()],Li.prototype,"rotationStep",2),Vo([m()],Li.prototype,"useTeleport",2),Vo([m()],Li.prototype,"usePinchToTeleport",2),Vo([m()],Li.prototype,"useTeleportTarget",2),Vo([m()],Li.prototype,"useTeleportFade",2),Vo([m()],Li.prototype,"showRays",2),Vo([m()],Li.prototype,"showHits",2);const ZT=new x(0,1,0);var JT=Object.defineProperty,eE=Object.getOwnPropertyDescriptor,xt=(s,t,i,n)=>{for(var o=n>1?void 0:n?eE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&JT(t,i,o),o};const yh=O("debugwebxr"),tE=O("debugusdz");var j0;const wl=(j0=class extends A{constructor(){super(...arguments),a(this,"createVRButton",!0),a(this,"createARButton",!0),a(this,"createSendToQuestButton",!0),a(this,"createQRCode",!0),a(this,"useDefaultControls",!0),a(this,"showControllerModels",!0),a(this,"showHandModels",!0),a(this,"usePlacementReticle",!0),a(this,"customARPlacementReticle"),a(this,"usePlacementAdjustment",!0),a(this,"arScale",1),a(this,"useXRAnchor",!1),a(this,"autoPlace",!0),a(this,"autoCenter",!1),a(this,"useQuicklookExport",!1),a(this,"useDepthSensing",!1),a(this,"useSpatialGrab",!0),a(this,"defaultAvatar"),a(this,"_playerSync"),a(this,"_createdComponentsInSession",[]),a(this,"_usdzExporter"),a(this,"_exitXRMenuButton"),a(this,"_previousXRState",0),a(this,"_spatialGrabRaycaster"),a(this,"onAvatarSpawned",s=>{yh&&console.log("WebXR.onAvatarSpawned",s),P.getComponentInChildren(s,No)??(e=P.addComponent(s,No))}),a(this,"_buttonFactory"),a(this,"_buttons",[])}awake(){Z.getXRSync(this.context)}onEnable(){var s,t;window.location.protocol!=="https:"&&_e('<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&&(P.findObjectOfType(Ge)||(yh&&console.log("WebXR: Adding USDZExporter"),this._usdzExporter=P.addComponent(this.gameObject,Ge),this._usdzExporter.objectToExport=this.context.scene,this._usdzExporter.autoExportAnimations=!0,this._usdzExporter.autoExportAudioSources=!0)),this.handleCreatingHTML(),this.handleOfferSession(),this.defaultAvatar===!0&&(yh&&console.warn("WebXR: No default avatar set, using static default avatar"),this.defaultAvatar=new le("https://cdn.needle.tools/static/avatars/DefaultAvatar.glb")),this.defaultAvatar&&(this._playerSync=this.gameObject.getOrAddComponent(bl),this._playerSync.autoSync=!1),this._playerSync&&typeof this.defaultAvatar!="boolean"&&(this._playerSync.asset=this.defaultAvatar,(s=this._playerSync.onPlayerSpawned)==null||s.removeEventListener(this.onAvatarSpawned),(t=this._playerSync.onPlayerSpawned)==null||t.addEventListener(this.onAvatarSpawned))}onDisable(){var s;(s=this._usdzExporter)==null||s.destroy(),this.removeButtons()}async handleOfferSession(){return this.createVRButton&&await Z.isVRSupported()&&this.createVRButton?Z.offerSession("immersive-vr","default",this.context):this.createARButton&&await Z.isARSupported()&&this.createARButton?Z.offerSession("immersive-ar","default",this.context):!1}get session(){return Z.active??null}get sessionMode(){return Z.activeMode??null}async enterVR(s){return Z.start("immersive-vr",s,this.context)}async enterAR(s){return Z.start("immersive-ar",s,this.context)}exitXR(){Z.stop()}get isActiveWebXR(){return!wl.activeWebXRComponent||wl.activeWebXRComponent===this}onBeforeXR(s,t){var i;if(!this.isActiveWebXR){console.warn(`WebXR: another WebXR component is already active (${(i=wl.activeWebXRComponent)==null?void 0:i.name}). This is ignored: ${this.name}`);return}wl.activeWebXRComponent=this,s=="immersive-ar"&&this.useDepthSensing&&(t.optionalFeatures=t.optionalFeatures||[],t.optionalFeatures.push("depth-sensing"))}async onEnterXR(s){if(!this.isActiveWebXR)return;yh&&console.log("WebXR onEnterXR"),this._previousXRState=Kt.Global.Mask;const t=s.xr.isVR;if(Kt.Global.Set(t?Ks.VR:Ks.AR),s.xr.isAR){let i=P.findObjectOfType(Vn);if(!i)if(this.usePlacementReticle){const n=new j;for(const o of this.context.scene.children)n.add(o);this.context.scene.add(n),i=P.addComponent(n,Vn),this._createdComponentsInSession.push(i)}else(yh||F())&&console.warn("WebXR: No WebARSessionRoot found in scene and usePlacementReticle is disabled in WebXR component.");i&&(i.customReticle=this.customARPlacementReticle,i.arScale=this.arScale,i.arTouchTransform=this.usePlacementAdjustment,i.autoPlace=this.autoPlace,i.autoCenter=this.autoCenter,i.useXRAnchor=this.useXRAnchor)}this.useDefaultControls&&this.setDefaultMovementEnabled(!0),(this.showControllerModels||this.showHandModels)&&this.setDefaultControllerRenderingEnabled(!0),this.useSpatialGrab&&(this._spatialGrabRaycaster=P.findObjectOfType(Ga)??void 0,this._spatialGrabRaycaster||(this._spatialGrabRaycaster=this.gameObject.addComponent(Ga))),this.createLocalAvatar(s.xr),s.xr.isScreenBasedAR||(this._exitXRMenuButton=this.context.menu.appendChild({label:"Quit XR",onClick:()=>this.exitXR(),icon:"exit_to_app",priority:2e4}))}onUpdateXR(s){this.isActiveWebXR&&this._spatialGrabRaycaster&&(this._spatialGrabRaycaster.enabled=this.useSpatialGrab)}onLeaveXR(s){var t,i;if((t=this._exitXRMenuButton)==null||t.remove(),!!this.isActiveWebXR){Kt.Global.Set(this._previousXRState),(i=this._playerSync)==null||i.destroyInstance();for(const n of this._createdComponentsInSession)n.destroy();this._createdComponentsInSession.length=0,this.handleOfferSession(),Xl(1).then(()=>wl.activeWebXRComponent=null)}}setDefaultMovementEnabled(s){let t=this.gameObject.getComponent(Li);return!t&&s&&(t=this.gameObject.addComponent(Li),this._createdComponentsInSession.push(t)),t&&(t.enabled=s),t}setDefaultControllerRenderingEnabled(s){let t=this.gameObject.getComponent(ln);return!t&&s&&(t=this.gameObject.addComponent(ln),this._createdComponentsInSession.push(t),t.createControllerModel=this.showControllerModels,t.createHandModel==this.showHandModels),t&&(t.enabled=s),t}async createLocalAvatar(s){this._playerSync&&s.running&&typeof this.defaultAvatar!="boolean"&&(this._playerSync.asset=this.defaultAvatar,await this._playerSync.getInstance())}getButtonsContainer(){return this.getButtonsFactory()}getButtonsFactory(){return this._buttonFactory||(this._buttonFactory=Yr.getOrCreate()),this._buttonFactory}handleCreatingHTML(){if(this.createARButton||this.createVRButton||this.useQuicklookExport){if((Y.isiOS()&&Y.isSafari()||tE)&&this.useQuicklookExport){const s=P.findObjectOfType(Ge);if(!s||s&&s.allowCreateQuicklookButton){const t=this.getButtonsFactory().createQuicklookButton();this.addButton(t,50)}}if(this.createARButton){const s=this.getButtonsFactory().createARButton();this.addButton(s,50)}if(this.createVRButton){const s=this.getButtonsFactory().createVRButton();this.addButton(s,50)}}if(this.createSendToQuestButton&&!Y.isQuest()&&Z.isVRSupported().then(s=>{if(!s){const t=this.getButtonsFactory().createSendToQuestButton();this.addButton(t,50)}}),this.createQRCode){const s=Gd(an);if(s&&s.createQRCodeButton===!1)F()&&console.warn("WebXR: QRCode button is disabled in the Needle Menu component");else if(!Y.isMobileDevice()){const t=Mn.getOrCreate().createQRCode();this.addButton(t,50)}}}addButton(s,t){this._buttons.push(s),s.setAttribute("priority",t.toString()),this.context.menu.appendChild(s)}removeButtons(){for(const s of this._buttons)s.remove();this._buttons.length=0}},a(j0,"activeWebXRComponent",null),j0);let Je=wl;xt([m()],Je.prototype,"createVRButton",2),xt([m()],Je.prototype,"createARButton",2),xt([m()],Je.prototype,"createSendToQuestButton",2),xt([m()],Je.prototype,"createQRCode",2),xt([m()],Je.prototype,"useDefaultControls",2),xt([m()],Je.prototype,"showControllerModels",2),xt([m()],Je.prototype,"showHandModels",2),xt([m()],Je.prototype,"usePlacementReticle",2),xt([m(le)],Je.prototype,"customARPlacementReticle",2),xt([m()],Je.prototype,"usePlacementAdjustment",2),xt([m()],Je.prototype,"arScale",2),xt([m()],Je.prototype,"useXRAnchor",2),xt([m()],Je.prototype,"autoPlace",2),xt([m()],Je.prototype,"autoCenter",2),xt([m()],Je.prototype,"useQuicklookExport",2),xt([m()],Je.prototype,"useDepthSensing",2),xt([m()],Je.prototype,"useSpatialGrab",2),xt([m(le)],Je.prototype,"defaultAvatar",2);const vh=O("debugusdz");function iE(s,t){var i;const n=[],o=P.getComponentsInChildren(s,Pt),r=P.getComponentsInChildren(s,Ut),l=new Array,c=new Array;if(t.injectImplicitBehaviours)for(const h of o){if(!h||!h.runtimeAnimatorController||!h.enabled)continue;const d=h.runtimeAnimatorController.activeState;if(!d||!d.motion||!d.motion.clip||((i=d.motion.clip.tracks)==null?void 0:i.length)<1||l.includes(h))continue;const u=new Gr;u.animator=h,u.stateName=d.name,u.trigger="start",u.name="PlayAnimationOnClick_implicitAtStart_"+u.stateName;const p=new j;P.addComponent(p,u),c.push(p),l.push(h),s.add(p)}else for(const h of o){if(!h||!h.runtimeAnimatorController||!h.enabled)continue;vh&&console.log(h);const d=[];for(const u of h.runtimeAnimatorController.enumerateActions()){vh&&console.log(u);const p=u.getClip();d.includes(p)||d.push(p)}n.push({root:h.gameObject,clips:d})}if(t.injectImplicitBehaviours)for(const h of r){if(!h||!h.clip||!h.enabled||!h.playAutomatically||l.includes(h))continue;const d=new Gr;d.animation=h,d.stateName=h.clip.name,d.trigger="start",d.name="PlayAnimationOnClick_implicitAtStart_"+d.stateName;const u=new j;P.addComponent(u,d),c.push(u),l.push(h),s.add(u)}else for(const h of r){vh&&console.log(h);const d=[];for(const u of h.animations)d.includes(u)||d.push(u);n.push({root:h.gameObject,clips:d})}vh&&n?.length>0&&console.log("USDZ Animation Clips without behaviours",n);for(const h of n)for(const d of h.clips)t.registerAnimation(h.root,d);return c}function sE(s,t){const i=P.getComponentsInChildren(s,We),n=P.getComponentsInChildren(s,jo),o=new Array,r=new Array;vh&&console.log({audioSources:i,playAudioOnClicks:n});for(const l of n){if(!l.target)continue;const c=i.indexOf(l.target);c>-1&&i.splice(c,1)}for(const l of i){if(!l||!l.clip||l.volume<=0||o.includes(l))continue;const c=new jo;c.target=l,c.name="PlayAudioOnClick_implicitAtStart_",c.trigger="start";const h=new j;P.addComponent(h,c),console.log("implicit PlayAudioOnStart",h,c),r.push(h),o.push(l),s.add(h)}return r}function nE(s){return new bt("DisableAtStart",_t.sceneStartTrigger(),ue.fadeAction(s,0,!1))}function e1(s,t){const i=s.domElement.shadowRoot.querySelector("link[rel='ar']");if(i)return i;const n=document.createElement("div");n.classList.add("menu"),n.classList.add("quicklook-menu"),n.style.display="none",n.style.visibility="hidden";const o=document.createElement("button");o.id="open-in-ar",t?(o.innerText="View in AR",o.title="View this scene in AR. The scene will be exported to USDZ and opened with Apple's QuickLook."):(o.innerText="View in AR",o.title="Download this scene for AR. Open the downloaded USDZ file to view it in AR using Apple's QuickLook."),n.appendChild(o);const r=document.createElement("a");r.id="needle-usdz-link",r.style.display="none",r.rel="ar",r.href="",r.target="_blank",n.appendChild(r);const l=document.createElement("img");return l.id="button",r.appendChild(l),s.domElement.shadowRoot.appendChild(n),r}var oE=Object.defineProperty,rE=Object.getOwnPropertyDescriptor,Et=(s,t,i,n)=>{for(var o=n>1?void 0:n?rE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&oE(t,i,o),o};const Di=O("debugusdz"),aE=O("debugusdzpruning");class Ho{constructor(){a(this,"callToAction"),a(this,"checkoutTitle"),a(this,"checkoutSubtitle"),a(this,"callToActionURL")}}Et([m()],Ho.prototype,"callToAction",2),Et([m()],Ho.prototype,"checkoutTitle",2),Et([m()],Ho.prototype,"checkoutSubtitle",2),Et([m()],Ho.prototype,"callToActionURL",2);var Sp;const L0=(Sp=class extends A{constructor(){super(...arguments),a(this,"objectToExport"),a(this,"autoExportAnimations",!0),a(this,"autoExportAudioSources",!0),a(this,"exportFileName"),a(this,"customUsdzFile"),a(this,"customBranding"),a(this,"anchoringType","plane"),a(this,"maxTextureSize",2048),a(this,"planeAnchoringAlignment","horizontal"),a(this,"interactive",!0),a(this,"physics",!0),a(this,"allowCreateQuicklookButton",!0),a(this,"quickLookCompatible",!0),a(this,"extensions",[]),a(this,"link"),a(this,"button"),a(this,"onClickedOpenInARElement",s=>{s.preventDefault(),this.exportAndOpen()}),a(this,"_currentExportTasks",new Map),a(this,"_previousTimeScale",1),a(this,"lastCallback"),a(this,"_rootSessionRootWasAppliedTo",null),a(this,"_rootPositionBeforeExport",new x),a(this,"_rootRotationBeforeExport",new V),a(this,"_rootScaleBeforeExport",new x)}start(){var s,t,i;Di&&(console.log("USDZExporter",this),console.log("Debug USDZ Mode. Press 'T' to export"),window.addEventListener("keydown",n=>{switch(n.key){case"t":this.exportAndOpen();break}})),this.objectToExport||(this.objectToExport=this.gameObject),!((t=(s=this.objectToExport)==null?void 0:s.children)!=null&&t.length)&&!((i=this.objectToExport)!=null&&i.isMesh)&&(this.objectToExport=this.context.scene)}onEnable(){var s;const t=Y.supportsQuickLookAR(),i=Y.isiOS()||Y.isiPad();!this.button&&(Di||t||i)&&(this.allowCreateQuicklookButton&&(this.button=this.createQuicklookButton()),this.lastCallback=this.quicklookCallback.bind(this),this.link=e1(this.context,t),this.link.addEventListener("message",this.lastCallback)),Di&&Le("USDZ Exporter enabled: "+this.name),(s=document.getElementById("open-in-ar"))==null||s.addEventListener("click",this.onClickedOpenInARElement),hc.registerExporter(this)}onDisable(){var s,t,i;(s=this.button)==null||s.remove(),(t=this.link)==null||t.removeEventListener("message",this.lastCallback),Di&&Le("USDZ Exporter disabled: "+this.name),(i=document.getElementById("open-in-ar"))==null||i.removeEventListener("click",this.onClickedOpenInARElement),hc.unregisterExporter(this)}async exportAsync(){return this.exportAndOpen()}async exportAndOpen(){var s;let t=this.exportFileName??((s=this.objectToExport)==null?void 0:s.name)??this.name;if(t+="-"+fx(),bo()||(t!==""&&(t+="-"),t+="MadeWithNeedle"),this.link||(this.link=e1(this.context,Y.supportsQuickLookAR())),this.customUsdzFile)return Di&&console.log("Exporting custom usdz",this.customUsdzFile),this.openInQuickLook(this.customUsdzFile,t),null;if(!this.objectToExport)return console.warn("No object to export",this),null;const i=await this.export(this.objectToExport);return i?(Di&&console.log("USDZ generation done. Downloading as "+t),this.openInQuickLook(i,t),i):(console.error("USDZ generation failed. Please report a bug",this),null)}async export(s){if(!s)return console.warn("No object to export"),null;const t=this._currentExportTasks.get(s);if(t)return t;const i=this.internalExport(s);return i instanceof Promise?(this._currentExportTasks.set(s,i),i.then(n=>(this._currentExportTasks.delete(s),n)).catch(n=>(this._currentExportTasks.delete(s),console.error("Error during USDZ export \u2013 please report a bug!",n),null))):i}async internalExport(s){ce.start("export-usdz",{onProgress:C=>{this.dispatchEvent(new CustomEvent("export-progress",{detail:{progress:C}}))}}),ce.report("export-usdz",{message:"Starting export",totalSteps:40,currentStep:0}),ce.report("export-usdz",{message:"Load progressive textures",autoStep:5}),ce.start("export-usdz-textures","export-usdz");const t=P.getComponentsInChildren(s,pi);for(const C of t)C&&C.enabled&&C.updateSprite(!0);const i=P.getComponentsInChildren(s,Ze),n=new Array;let o=0;for(const C of i){for(const R of C.sharedMeshes)if(R){const M=et.assignMeshLOD(R,0);M instanceof Promise&&n.push(new Promise((E,D)=>{M.then(()=>{o++,ce.report("export-usdz-textures",{message:"Loaded progressive mesh",currentStep:o,totalSteps:n.length}),E()}).catch(L=>D(L))}))}for(const R of C.sharedMaterials)if(R){const M=et.assignTextureLOD(R,0);M instanceof Promise&&n.push(new Promise((E,D)=>{M.then(()=>{o++,ce.report("export-usdz-textures",{message:"Loaded progressive texture",currentStep:o,totalSteps:n.length}),E()}).catch(L=>D(L))}))}}Di&&Le("Progressive Loading: "+n.length),await Promise.all(n),Di&&Le("Progressive Loading: done"),ce.end("export-usdz-textures");const r=Kt.Global.Mask;Kt.Global.Set(Ks.AR);const l=new wx,c=new nh(this.quickLookCompatible);let h;const d=[];this.interactive&&(d.push(new hp),d.push(new lr),globalThis.false&&P.getComponentsInChildren(s,ye).length>0&&(this.physics?(h=new pp,d.push(h)):F()&&console.warn("USDZExporter: Physics export is disabled, but there are active Rigidbody components in the scene. They will not be exported.")),d.push(new uh),d.push(new yp));const u=[c,...d,...this.extensions],p={self:this,exporter:l,extensions:u,object:s};ce.report("export-usdz","Invoking before-export"),this.dispatchEvent(new CustomEvent("before-export",{detail:p})),this.applyWebARSessionRoot(),this._previousTimeScale=this.context.time.timeScale,this.context.time.timeScale=0,ce.report("export-usdz","auto export animations and audio sources");const g=new Array;this.autoExportAnimations&&g.push(...iE(s,c)),this.extensions.find(C=>C.extensionName==="Audio")&&this.autoExportAudioSources&&g.push(...sE(s)),l.debug=Di,l.pruneUnusedNodes=!aE;const y=Vr.instance.objs.map(C=>C.batchedMesh);l.keepObject=C=>{let R=!0;const M=P.getComponent(C,Ze);return M&&!M.enabled&&(R=!1),R&&y.includes(C)&&(R=!1),R&&P.getComponentInParent(C,Os)&&(R=!1),R&&P.getComponentInParent(C,Vs)&&(R=!1),Di&&!R&&console.log("USDZExporter: Discarding object",C),R},l.beforeWritingDocument=()=>{if(F()&&c&&h){const C=c.animatedRoots;for(const R of C){const M=P.getComponentsInChildren(R,ye).filter(D=>D.enabled),E=P.getComponents(R,hi).filter(D=>D.enabled&&!D.isTrigger);(M.length>0||E.length>0)&&console.error("An animated object has physics components in its child hierarchy. This can lead to undefined behaviour due to a bug in Apple's QuickLook (FB15925487). Remove the physics components from child objects or verify that you get the expected results.",R)}}};const f=new Array;this.objectToExport&&this.quickLookCompatible&&this.interactive&&this.objectToExport.traverse(C=>{C.visible||f.push(C)});const v=this.extensions.find(C=>C.extensionName==="Behaviour");this.interactive&&v&&f.length>0&&v.addBehavior(nE(f));let b=!0;this.quickLookCompatible&&!this.interactive&&(b=!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"),ce.report("export-usdz","Invoking exporter.parse");const w=await l.parse(this.objectToExport,{ar:{anchoring:{type:this.anchoringType},planeAnchoring:{alignment:this.planeAnchoringAlignment}},extensions:u,quickLookCompatible:this.quickLookCompatible,maxTextureSize:this.maxTextureSize,exportInvisible:b}),_=new Blob([w],{type:"model/vnd.usdz+zip"});this.revertWebARSessionRoot(),this.context.time.timeScale=this._previousTimeScale,ce.report("export-usdz","Invoking after-export"),this.dispatchEvent(new CustomEvent("after-export",{detail:p}));for(const C of g)P.destroy(C);return Kt.Global.Set(r),ce.end("export-usdz"),_}openInQuickLook(s,t){const i=s instanceof Blob?URL.createObjectURL(s):s,n=this.buildQuicklookOverlay();Di&&console.log("QuickLook Overlay",n);const o=n.callToAction?encodeURIComponent(n.callToAction):"",r=n.checkoutTitle?encodeURIComponent(n.checkoutTitle):"",l=n.checkoutSubtitle?encodeURIComponent(n.checkoutSubtitle):"";this.link.href=i+`#callToAction=${o}&checkoutTitle=${r}&checkoutSubtitle=${l}&callToActionURL=${n.callToActionURL}`,this.lastCallback||(this.lastCallback=this.quicklookCallback.bind(this),this.link.addEventListener("message",this.lastCallback)),this.link.download=t+".usdz",this.link.click()}download(s,t){L0.save(s,t)}static save(s,t){const i=document.createElement("a");i.style.display="none",document.body.appendChild(i),typeof s=="string"?i.href=s:i.href=URL.createObjectURL(s),i.download=t,i.click(),i.remove()}quicklookCallback(s){if(s?.data=="_apple_ar_quicklook_button_tapped"){Di&&_e("Quicklook closed via call to action button");var t=new CustomEvent("quicklook-button-tapped",{detail:this});if(this.dispatchEvent(t),!t.defaultPrevented){const i=new URLSearchParams(this.link.href);if(i){const n=i.get("callToActionURL");Di&&Le("Quicklook url: "+n),n&&(bo()?globalThis.open(n,"_blank"):console.warn("Quicklook closed: custom redirects require a Needle Engine Pro license: https://needle.tools/pricing",n))}}}}buildQuicklookOverlay(){var s,t,i,n,o,r;const l={};return this.customBranding&&Object.assign(l,this.customBranding),bo()||(console.log("Custom Quicklook banner text requires pro license: https://needle.tools/pricing"),l.callToAction="Close",l.checkoutTitle="\u{1F335} Made with Needle",l.checkoutSubtitle="_"),(((s=l.callToAction)==null?void 0:s.length)||((t=l.checkoutTitle)==null?void 0:t.length)||((i=l.checkoutSubtitle)==null?void 0:i.length))&&((n=l.callToAction)!=null&&n.length||(l.callToAction="\0"),(o=l.checkoutTitle)!=null&&o.length||(l.checkoutTitle="\0"),(r=l.checkoutSubtitle)!=null&&r.length||(l.checkoutSubtitle="\0")),this.dispatchEvent(new CustomEvent("quicklook-overlay",{detail:l})),l}getARScaleAndTarget(){if(!this.objectToExport)return{scale:1,_invertForward:!1,target:this.gameObject,sessionRoot:null};const s=P.findObjectOfType(Je);let t=P.getComponentInParent(this.objectToExport,Vn);t||(t=P.getComponentInChildren(this.objectToExport,Vn));let i=1,n=!1;const o=this.objectToExport;return s?i=s.arScale:t&&(i=t.arScale,n=t.invertForward),{scale:1/i,_invertForward:n,target:o,sessionRoot:t?.gameObject??null}}applyWebARSessionRoot(){if(!this.objectToExport)return;const{scale:s,_invertForward:t,target:i,sessionRoot:n}=this.getARScaleAndTarget(),o=n?.matrixWorld.clone().invert();this._rootSessionRootWasAppliedTo=i,this._rootPositionBeforeExport.copy(i.position),this._rootRotationBeforeExport.copy(i.quaternion),this._rootScaleBeforeExport.copy(i.scale),i.scale.multiplyScalar(s),t&&i.quaternion.multiply(L0.invertForwardQuaternion),i.updateMatrix(),i.updateMatrixWorld(!0),n&&o&&i.matrix.premultiply(o)}revertWebARSessionRoot(){if(!this.objectToExport||!this._rootSessionRootWasAppliedTo)return;const s=this._rootSessionRootWasAppliedTo;s.position.copy(this._rootPositionBeforeExport),s.quaternion.copy(this._rootRotationBeforeExport),s.scale.copy(this._rootScaleBeforeExport),s.updateMatrix(),s.updateMatrixWorld(!0),this._rootSessionRootWasAppliedTo=null}createQuicklookButton(){const s=Yr.getOrCreate().createQuicklookButton();return s.parentNode||this.context.menu.appendChild(s),s}},a(Sp,"invertForwardMatrix",new ne().makeRotationY(Math.PI)),a(Sp,"invertForwardQuaternion",new V().setFromEuler(new Ft(0,Math.PI,0))),Sp);let Ge=L0;Et([m(j)],Ge.prototype,"objectToExport",2),Et([m()],Ge.prototype,"autoExportAnimations",2),Et([m()],Ge.prototype,"autoExportAudioSources",2),Et([m()],Ge.prototype,"exportFileName",2),Et([m(URL)],Ge.prototype,"customUsdzFile",2),Et([m(Ho)],Ge.prototype,"customBranding",2),Et([m()],Ge.prototype,"anchoringType",2),Et([m()],Ge.prototype,"maxTextureSize",2),Et([m()],Ge.prototype,"planeAnchoringAlignment",2),Et([m()],Ge.prototype,"interactive",2),Et([m()],Ge.prototype,"physics",2),Et([m()],Ge.prototype,"allowCreateQuicklookButton",2),Et([m()],Ge.prototype,"quickLookCompatible",2);var lE=Object.defineProperty,cE=Object.getOwnPropertyDescriptor,D0=(s,t,i,n)=>{for(var o=n>1?void 0:n?cE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&lE(t,i,o),o};class xl extends A{constructor(){super(...arguments),a(this,"_fog")}get fog(){return this._fog||(this._fog=new Gy(0,0,50)),this._fog}get mode(){return 1}set near(t){this.fog.near=t}get near(){return this.fog.near}set far(t){this.fog.far=t}get far(){return this.fog.far}set color(t){this.fog.color.copy(t)}get color(){return this.fog.color}onEnable(){this.scene.fog=this.fog}onDisable(){this.scene.fog===this._fog&&(this.scene.fog=null)}}D0([m()],xl.prototype,"near",1),D0([m()],xl.prototype,"far",1),D0([m(ae)],xl.prototype,"color",1);var hE=Object.defineProperty,dE=Object.getOwnPropertyDescriptor,B0=(s,t,i,n)=>{for(var o=n>1?void 0:n?dE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&hE(t,i,o),o};class Kr extends A{constructor(){super(...arguments),a(this,"objectBounds",!1),a(this,"color"),a(this,"isGizmo",!0),a(this,"_gizmoObject",null),a(this,"_boxHelper",null)}onEnable(){this.isGizmo&&!vc||(this._gizmoObject||(this.objectBounds?this._gizmoObject=new lC(this.gameObject,this.color??16776960):(this.objectBounds=!1,this._gizmoObject=wg(this.color??16776960))),this.objectBounds?(this.scene.add(this._gizmoObject),this._boxHelper=this._gizmoObject,this.startCoroutine(this.syncObjectBounds(),Ce.OnBeforeRender)):this.gameObject.add(this._gizmoObject))}onDisable(){this._gizmoObject&&this.gameObject.remove(this._gizmoObject)}*syncObjectBounds(){for(var t;this._boxHelper;)(t=this._boxHelper)==null||t.update(),yield}}B0([m()],Kr.prototype,"objectBounds",2),B0([m(ae)],Kr.prototype,"color",2),B0([m()],Kr.prototype,"isGizmo",2);var uE=Object.defineProperty,pE=Object.getOwnPropertyDescriptor,F0=(s,t,i,n)=>{for(var o=n>1?void 0:n?pE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&uE(t,i,o),o};class Sl extends A{constructor(){super(...arguments),a(this,"isGizmo",!1),a(this,"color0"),a(this,"color1"),a(this,"gridHelper"),a(this,"size"),a(this,"divisions"),a(this,"offset")}onEnable(){if(this.isGizmo&&!vc)return;const t=this.size,i=this.divisions;this.gridHelper||(this.gridHelper=new lm(t,i,this.color0??new ae(.4,.4,.4),this.color1??new ae(.6,.6,.6)),this.offset!==void 0&&(this.gridHelper.position.y+=this.offset)),this.gridHelper&&this.gameObject.add(this.gridHelper)}onDisable(){this.gridHelper&&(this.gameObject.remove(this.gridHelper),this.gridHelper=null)}}F0([m()],Sl.prototype,"isGizmo",2),F0([m(ae)],Sl.prototype,"color0",2),F0([m(ae)],Sl.prototype,"color1",2);var mE=Object.defineProperty,gE=Object.getOwnPropertyDescriptor,z0=(s,t,i,n)=>{for(var o=n>1?void 0:n?gE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&mE(t,i,o),o};class U0 extends A{constructor(){super(...arguments),a(this,"connectedBody"),a(this,"_rigidBody",null)}get rigidBody(){return this._rigidBody}onEnable(){this._rigidBody||(this._rigidBody=this.gameObject.getComponent(ye)),this.rigidBody&&this.connectedBody&&this.startCoroutine(this.create())}*create(){yield,this.rigidBody&&this.connectedBody&&this.activeAndEnabled&&this.createJoint(this.rigidBody,this.connectedBody)}}z0([m(ye)],U0.prototype,"connectedBody",2);class N0 extends U0{createJoint(t,i){var n;(n=this.context.physics.engine)==null||n.addFixedJoint(t,i)}}class bh extends U0{constructor(){super(...arguments),a(this,"anchor"),a(this,"axis")}createJoint(t,i){var n;this.axis&&this.anchor&&((n=this.context.physics.engine)==null||n.addHingeJoint(t,i,this.anchor,this.axis))}}z0([m(x)],bh.prototype,"anchor",2),z0([m(x)],bh.prototype,"axis",2);var fE=Object.defineProperty,yE=Object.getOwnPropertyDescriptor,cn=(s,t,i,n)=>{for(var o=n>1?void 0:n?yE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&fE(t,i,o),o};function W0(s){return s*Math.PI/180}const t1=300,$o=O("debuglights");class mi extends A{constructor(){super(...arguments),a(this,"type",0),a(this,"range",1),a(this,"spotAngle",1),a(this,"innerSpotAngle",1),a(this,"_color",new ae(16777215)),a(this,"_shadowNearPlane",.1),a(this,"_shadowBias",0),a(this,"_shadowNormalBias",0),a(this,"_overrideShadowBiasSettings",!1),a(this,"_shadows",1),a(this,"lightmapBakeType",4),a(this,"_intensity",-1),a(this,"_shadowDistance"),a(this,"shadowWidth"),a(this,"shadowHeight"),a(this,"_shadowResolution"),a(this,"light"),a(this,"_webXRStartedListener"),a(this,"_webXREndedListener"),a(this,"_webARRoot")}set color(t){this._color=t,this.light!==void 0&&(this.light.color=t)}get color(){return this.light?this.light.color:this._color}set shadowNearPlane(t){var i,n;if(t!==this._shadowNearPlane&&(this._shadowNearPlane=t,((n=(i=this.light)==null?void 0:i.shadow)==null?void 0:n.camera)!==void 0)){const o=this.light.shadow.camera;o.near=t}}get shadowNearPlane(){return this._shadowNearPlane}set shadowBias(t){var i,n;t!==this._shadowBias&&(this._shadowBias=t,((n=(i=this.light)==null?void 0:i.shadow)==null?void 0:n.bias)!==void 0&&(this.light.shadow.bias=t,this.light.shadow.needsUpdate=!0))}get shadowBias(){return this._shadowBias}set shadowNormalBias(t){var i,n;t!==this._shadowNormalBias&&(this._shadowNormalBias=t,((n=(i=this.light)==null?void 0:i.shadow)==null?void 0:n.normalBias)!==void 0&&(this.light.shadow.normalBias=t,this.light.shadow.needsUpdate=!0))}get shadowNormalBias(){return this._shadowNormalBias}set shadows(t){this._shadows=t,this.light&&(this.light.castShadow=t!==0,this.updateShadowSoftHard())}get shadows(){return this._shadows}set intensity(t){var i;if(this._intensity=t,this.light){let n=1;if(this.context.isInXR&&this._webARRoot){const o=(i=this._webARRoot)==null?void 0:i.arScale;typeof o=="number"&&o>0&&(n/=o)}this.light.intensity=t*n}$o&&console.log("Set light intensity to "+this._intensity,t,this)}get intensity(){return this._intensity}get shadowDistance(){const t=this.light;return t!=null&&t.shadow?t.shadow.camera.far:-1}set shadowDistance(t){this._shadowDistance=t;const i=this.light;if(i!=null&&i.shadow){const n=i.shadow.camera;n.far=t,n.updateProjectionMatrix()}}get shadowResolution(){const t=this.light;return t!=null&&t.shadow?t.shadow.mapSize.x:-1}set shadowResolution(t){if(t===this._shadowResolution)return;this._shadowResolution=t;const i=this.light;i!=null&&i.shadow&&(i.shadow.mapSize.set(t,t),i.shadow.needsUpdate=!0)}get isBaked(){return this.lightmapBakeType===2}get selfIsLight(){if(this.gameObject.isLight===!0)return!0;switch(this.gameObject.type){case"SpotLight":case"PointLight":case"DirectionalLight":return!0}return!1}getWorldPosition(t){return this.light?this.type===1?this.light.getWorldPosition(t).multiplyScalar(1):this.light.getWorldPosition(t):t}awake(){this.color=new ae(this.color??16777215),$o&&console.log(this.name,this)}onEnable(){$o&&console.log("ENABLE LIGHT",this.name),this.createLight(),!this.isBaked&&(this.light&&(this.light.visible=!0,this.light.intensity=this._intensity,$o&&console.log("Set light intensity to "+this.light.intensity,this.name),this.selfIsLight||this.light.parent!==this.gameObject&&this.gameObject.add(this.light)),this.type===1&&this.startCoroutine(this.updateMainLightRoutine(),Ce.LateUpdate))}onDisable(){$o&&console.log("DISABLE LIGHT",this.name),this.light&&(this.selfIsLight?this.light.intensity=0:this.light.visible=!1)}onEnterXR(t){this._webARRoot=P.getComponentInParent(this.gameObject,Vn)??void 0}onLeaveXR(t){}createLight(){const t=this.selfIsLight;if(t&&!this.light)switch(this.light=this.gameObject,this.light.name=this.name,this._intensity=this.light.intensity,this.type){case 1:this.setDirectionalLight(this.light);break}else if(!this.light)switch(this.type){case 1:const i=new cm(this.color,this.intensity*Math.PI);if(i.position.set(0,0,-t1*.5).applyQuaternion(this.gameObject.quaternion),this.gameObject.add(i.target),fr(i.target,0,0,0),this.light=i,this.gameObject.position.set(0,0,0),this.gameObject.rotation.set(0,0,0),$o){const l=new hC(this.light,.2,this.color);this.context.scene.add(l)}break;case 0:const n=new cC(this.color,this.intensity*Math.PI,this.range,W0(this.spotAngle/2),1-W0(this.innerSpotAngle/2)/W0(this.spotAngle/2),2);n.position.set(0,0,0),n.rotation.set(0,0,0),this.light=n;const o=n.target;n.add(o),o.position.set(0,0,this.range),o.rotation.set(0,0,0);break;case 2:const r=new Xy(this.color,this.intensity*Math.PI,this.range);this.light=r;break}if(this.light){if(this._intensity>=0?this.light.intensity=this._intensity:this._intensity=this.light.intensity,this.shadows!==0?this.light.castShadow=!0:this.light.castShadow=!1,this.light.shadow){this._shadowResolution!==void 0&&this._shadowResolution>4?(this.light.shadow.mapSize.width=this._shadowResolution,this.light.shadow.mapSize.height=this._shadowResolution):(this.light.shadow.mapSize.width=2048,this.light.shadow.mapSize.height=2048),$o&&console.log("Override shadow bias?",this._overrideShadowBiasSettings,this.shadowBias,this.shadowNormalBias),this.light.shadow.bias=this.shadowBias,this.light.shadow.normalBias=this.shadowNormalBias,this.updateShadowSoftHard();const i=this.light.shadow.camera;if(i.near=this.shadowNearPlane,this._shadowDistance!==void 0&&typeof this._shadowDistance=="number"?i.far=this._shadowDistance:i.far=t1*Math.abs(this.gameObject.scale.z),this.gameObject.scale.set(1,1,1),this.shadowWidth!==void 0)i.left=-this.shadowWidth/2,i.right=this.shadowWidth/2;else{const n=this.gameObject.scale.x;i.left*=n,i.right*=n}if(this.shadowHeight!==void 0)i.top=this.shadowHeight/2,i.bottom=-this.shadowHeight/2;else{const n=this.gameObject.scale.y;i.top*=n,i.bottom*=n}this.light.shadow.needsUpdate=!0,$o&&this.context.scene.add(new dC(i))}this.isBaked?this.light.removeFromParent():t||this.gameObject.add(this.light)}}*updateMainLightRoutine(){for(;;){this.type===1&&((!this.context.mainLight||this.intensity>this.context.mainLight.intensity)&&(this.context.mainLight=this),yield);break}}updateShadowSoftHard(){this.light&&this.light.shadow&&(this.shadows===2||(this.light.shadow.radius=1,this.light.shadow.blurSamples=1))}setDirectionalLight(t){t.add(t.target),t.target.position.set(0,0,-1)}}a(mi,"allowChangingRendererShadowMapType",!0),cn([m()],mi.prototype,"type",2),cn([m(ae)],mi.prototype,"color",1),cn([m()],mi.prototype,"shadowNearPlane",1),cn([m()],mi.prototype,"shadowBias",1),cn([m()],mi.prototype,"shadowNormalBias",1),cn([m()],mi.prototype,"shadows",1),cn([m()],mi.prototype,"lightmapBakeType",2),cn([m()],mi.prototype,"intensity",1),cn([m()],mi.prototype,"shadowDistance",1),cn([m()],mi.prototype,"shadowResolution",1),new x(0,0,0);var vE=Object.defineProperty,bE=Object.getOwnPropertyDescriptor,_h=(s,t,i,n)=>{for(var o=n>1?void 0:n?bE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&vE(t,i,o),o};const V0=O("debuglods"),_E=O("nolods");class Zr{constructor(){a(this,"screenRelativeTransitionHeight"),a(this,"distance"),a(this,"renderers")}}_h([m()],Zr.prototype,"screenRelativeTransitionHeight",2),_h([m()],Zr.prototype,"distance",2),_h([m(Ze)],Zr.prototype,"renderers",2);class wE{constructor(t){a(this,"model"),this.model=t}get renderers(){return this.model.renderers}}class wh extends A{constructor(){super(...arguments),a(this,"fadeMode",0),a(this,"localReferencePoint"),a(this,"lodCount",0),a(this,"size",0),a(this,"animateCrossFading",!1),a(this,"lodModels"),a(this,"_lods",[]),a(this,"_settings",[]),a(this,"_lodsHandler"),a(this,"_distanceFactor",1)}start(){if(V0&&console.log("LODGROUP",this.name,this.lodModels,this),!_E&&!this._lodsHandler&&this.gameObject&&this.lodModels&&Array.isArray(this.lodModels)){const t=[];for(const n of this.lodModels){const o=new wE(n);this._lods.push(o);for(const r of o.renderers)t.includes(r)||t.push(r)}this._lodsHandler=new Array;for(let n=0;n<t.length;n++){const o=new uC;this._lodsHandler.push(o),this.gameObject.add(o)}const i=new j;i.name="Cull "+this.name;for(let n=0;n<t.length;n++){const o=t[n],r=this._lodsHandler[n],l=o.gameObject;V0&&console.log(n,l.name);for(const c of this._lods){const h=c.model.distance;let d=null;if(c.renderers.includes(o)?d=l:d=i,d.type==="Group"){console.warn(`LODGroup ${this.name}: Group or MultiMaterial object's are not supported as LOD object: ${d.name}`);continue}V0&&console.log("LEVEL",d.name,h),r.autoUpdate=!1,this.onAddLodLevel(r,d,c.model.distance)}}}}onAfterRender(){if(!this.gameObject||!this._lodsHandler)return;const t=this.context.mainCamera;if(t)for(const i of this._lodsHandler){i.update(t);const n=i.getCurrentLevel(),o=i.levels[n];i.layers.mask=o.object.layers.mask}}onAddLodLevel(t,i,n){if(i===this.gameObject){console.warn("LODGroup component must be on parent object and not mesh directly at the moment",i.name,i);return}t.addLevel(i,n*this._distanceFactor,.01);const o={lod:t,levelIndex:t.levels.length-1,distance:n};this._settings.push(o)}distanceFactor(t){if(t!==this._distanceFactor){this._distanceFactor=t;for(const i of this._settings){const n=i.lod.levels[i.levelIndex];n.distance=i.distance*t}}}}_h([m(x)],wh.prototype,"localReferencePoint",2),_h([m(Zr)],wh.prototype,"lodModels",2);var xE=Object.defineProperty,SE=Object.getOwnPropertyDescriptor,CE=(s,t,i,n)=>{for(var o=n>1?void 0:n?SE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&xE(t,i,o),o};const Cp=O("debugnestedgltf");class Op extends A{constructor(){super(...arguments),a(this,"filePath"),a(this,"loadAssetInParent",!0),a(this,"_isLoadingOrDoneLoading",!1)}listenToProgress(t){var i;(i=this.filePath)==null||i.beginListenDownload(t)}preload(){var t;(t=this.filePath)==null||t.preload()}async start(){var t,i,n,o,r;if(this._isLoadingOrDoneLoading)return;Cp&&console.log(this,this.guid);const l=this.gameObject.parent;if(l){this._isLoadingOrDoneLoading=!0;const c=new js;c.idProvider=new Bt(this.hash(this.guid)),c.parent=this.loadAssetInParent!==!1?l:this.gameObject,this.gameObject.updateMatrix();const h=this.gameObject.matrix;Cp&&console.log("Load nested:",((t=this.filePath)==null?void 0:t.url)??this.filePath,this.gameObject.position);const d=await((n=(i=this.filePath)==null?void 0:i.instantiate)==null?void 0:n.call(this.filePath,c));Cp&&console.log("Nested loaded:",((o=this.filePath)==null?void 0:o.url)??this.filePath,d),d&&this.loadAssetInParent!==!1&&(d.matrixAutoUpdate=!1,d.matrix.identity(),d.applyMatrix4(h),d.matrixAutoUpdate=!0,d.layers.disableAll(),d.layers.set(this.layer),this.dispatchEvent(new CustomEvent("loaded",{detail:{instance:d,assetReference:this.filePath}}))),Cp&&console.log("Nested loading done:",((r=this.filePath)==null?void 0:r.url)??this.filePath,d)}}onDestroy(){var t;(t=this.filePath)==null||t.unload()}hash(t){let i=0;for(let n=0;n<t.length;n++)i=t.charCodeAt(n)+((i<<5)-i);return i}}CE([m(le)],Op.prototype,"filePath",2);var OE=Object.defineProperty,PE=Object.getOwnPropertyDescriptor,H0=(s,t,i,n)=>{for(var o=n>1?void 0:n?PE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&OE(t,i,o),o};const kE=O("debugnet"),$0=class extends A{constructor(){super(...arguments),a(this,"url",null),a(this,"urlParameterName",null),a(this,"localhost",null)}awake(){kE&&console.log(this),this.context.connection.registerProvider(this)}getWebsocketUrl(){let s=this.url?$0.GetUrl(this.url,this.localhost):null;if(this.urlParameterName){const i=O(this.urlParameterName);i&&typeof i=="string"&&(s=i)}if(!s)return null;const t=new RegExp("(((https?)|(?<socket_prefix>wss?))://)?(www.)?(?<url>.+)","gm").exec(s);return t!=null&&t.groups?t?.groups.socket_prefix?s:"wss://"+t?.groups.url:null}static GetUrl(s,t){let i=s;const n=$0.IsLocalNetwork()&&t;if(n&&(i=t),s!=null&&s.startsWith("/")){const o=n?i:window.location.origin;o!=null&&o.endsWith("/")&&s.startsWith("/")&&(s=s.substring(1)),i=o+s}return i}static IsLocalNetwork(s=window.location.hostname){return Gt(s)}};let Cl=$0;H0([m()],Cl.prototype,"url",2),H0([m()],Cl.prototype,"urlParameterName",2),H0([m()],Cl.prototype,"localhost",2);var ME=Object.defineProperty,RE=Object.getOwnPropertyDescriptor,Pp=(s,t,i,n)=>{for(var o=n>1?void 0:n?RE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&ME(t,i,o),o};class Jr extends A{constructor(){super(...arguments),a(this,"referenceSpace"),a(this,"from"),a(this,"affectPosition",!1),a(this,"affectRotation",!1),a(this,"alignLookDirection",!1),a(this,"levelLookDirection",!1),a(this,"levelPosition",!1),a(this,"positionOffset",new x(0,0,0)),a(this,"rotationOffset",new x(0,0,0)),a(this,"offset",new x(0,0,0))}update(){if(!this.from)return;var t=ee(this.from),i=Se(this.from);this.offset.copy(this.positionOffset);const n=this.offset.length();if(this.referenceSpace&&this.offset.transformDirection(this.referenceSpace.matrixWorld).multiplyScalar(n),t.add(this.offset),this.levelPosition&&this.referenceSpace){const c=new dr(this.gameObject.up,0),h=ee(this.referenceSpace);c.setFromNormalAndCoplanarPoint(this.gameObject.up,h);const d=new x(0,0,0);c.projectPoint(t,d),t.copy(d)}this.affectPosition&&lt(this.gameObject,t);const o=new Ft(this.rotationOffset.x,this.rotationOffset.y,this.rotationOffset.z),r=new V().setFromEuler(o);this.affectRotation&&qi(this.gameObject,i.multiply(r));const l=new x;this.from.getWorldDirection(l).multiplyScalar(50),this.levelLookDirection&&(l.y=0),this.alignLookDirection&&this.gameObject.lookAt(l)}}Pp([m(P)],Jr.prototype,"referenceSpace",2),Pp([m(P)],Jr.prototype,"from",2),Pp([m(x)],Jr.prototype,"positionOffset",2),Pp([m(x)],Jr.prototype,"rotationOffset",2);var TE=Object.defineProperty,EE=Object.getOwnPropertyDescriptor,k=(s,t,i,n)=>{for(var o=n>1?void 0:n?EE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&TE(t,i,o),o};const kp=O("debugparticles");var $n=(s=>(s[s.Billboard=0]="Billboard",s[s.Stretch=1]="Stretch",s[s.HorizontalBillboard=2]="HorizontalBillboard",s[s.VerticalBillboard=3]="VerticalBillboard",s[s.Mesh=4]="Mesh",s))($n||{});class qo{constructor(){a(this,"alphaKeys",[]),a(this,"colorKeys",[])}get duration(){return 1}evaluate(t,i){let n,o=0,r=null,l=0;for(let c=0;c<this.alphaKeys.length;c++){const h=this.alphaKeys[c];(h.time<t||!n)&&(n=h,o=c)}for(let c=0;c<this.colorKeys.length;c++){const h=this.colorKeys[c];(h.time<t||!r)&&(r=h,l=c)}if(r)if(l+1<this.colorKeys.length){const c=this.colorKeys[l+1],h=W.remap(t,r.time,c.time,0,1);i.r=W.lerp(r.color.r,c.color.r,h),i.g=W.lerp(r.color.g,c.color.g,h),i.b=W.lerp(r.color.b,c.color.b,h)}else i.r=r.color.r,i.g=r.color.g,i.b=r.color.b;if(n)if(o+1<this.alphaKeys.length){const c=this.alphaKeys[o+1],h=W.remap(t,n.time,c.time,0,1);i.alpha=W.lerp(n.alpha,c.alpha,h)}else i.alpha=n.alpha;return i}}k([m()],qo.prototype,"alphaKeys",2),k([m()],qo.prototype,"colorKeys",2);var xh=(s=>(s[s.Local=0]="Local",s[s.World=1]="World",s[s.Custom=2]="Custom",s))(xh||{}),Mp=(s=>(s[s.Sphere=0]="Sphere",s[s.SphereShell=1]="SphereShell",s[s.Hemisphere=2]="Hemisphere",s[s.HemisphereShell=3]="HemisphereShell",s[s.Cone=4]="Cone",s[s.Box=5]="Box",s[s.Mesh=6]="Mesh",s[s.ConeShell=7]="ConeShell",s[s.ConeVolume=8]="ConeVolume",s[s.ConeVolumeShell=9]="ConeVolumeShell",s[s.Circle=10]="Circle",s[s.CircleEdge=11]="CircleEdge",s[s.SingleSidedEdge=12]="SingleSidedEdge",s[s.MeshRenderer=13]="MeshRenderer",s[s.SkinnedMeshRenderer=14]="SkinnedMeshRenderer",s[s.BoxShell=15]="BoxShell",s[s.BoxEdge=16]="BoxEdge",s[s.Donut=17]="Donut",s[s.Rectangle=18]="Rectangle",s[s.Sprite=19]="Sprite",s[s.SpriteRenderer=20]="SpriteRenderer",s))(Mp||{});const Sh=class{constructor(){a(this,"mode","Constant"),a(this,"constant"),a(this,"constantMin"),a(this,"constantMax"),a(this,"curve"),a(this,"curveMin"),a(this,"curveMax"),a(this,"curveMultiplier")}static constant(s){const t=new Sh;return t.setConstant(s),t}static betweenTwoConstants(s,t){const i=new Sh;return i.setMinMaxConstant(s,t),i}static curve(s,t=1){const i=new Sh;return i.setCurve(s,t),i}setConstant(s){this.mode=0,this.constant=s}setMinMaxConstant(s,t){this.mode=3,this.constantMin=s,this.constantMax=t}setCurve(s,t=1){this.mode=1,this.curve=s,this.curveMultiplier=t}clone(){var s,t,i;const n=new Sh;return n.mode=this.mode,n.constant=this.constant,n.constantMin=this.constantMin,n.constantMax=this.constantMax,n.curve=(s=this.curve)==null?void 0:s.clone(),n.curveMin=(t=this.curveMin)==null?void 0:t.clone(),n.curveMax=(i=this.curveMax)==null?void 0:i.clone(),n.curveMultiplier=this.curveMultiplier,n}evaluate(s,t){const i=t===void 0?Math.random():t;switch(this.mode){case 0:case"Constant":return this.constant;case 1:case"Curve":return s=W.clamp01(s),this.curve.evaluate(s)*this.curveMultiplier;case 2:case"TwoCurves":const n=s*this.curveMin.duration,o=s*this.curveMax.duration;return W.lerp(this.curveMin.evaluate(n),this.curveMax.evaluate(o),i%1)*this.curveMultiplier;case 3:case"TwoConstants":return W.lerp(this.constantMin,this.constantMax,i%1);default:this.curveMax.evaluate(s)*this.curveMultiplier;break}return 0}getMax(){switch(this.mode){case 0:case"Constant":return this.constant;case 1:case"Curve":return this.getMaxFromCurve(this.curve)*this.curveMultiplier;case 2:case"TwoCurves":return Math.max(this.getMaxFromCurve(this.curveMin),this.getMaxFromCurve(this.curveMax))*this.curveMultiplier;case 3:case"TwoConstants":return Math.max(this.constantMin,this.constantMax);default:return 0}}getMaxFromCurve(s){if(!s)return 0;let t=Number.MIN_VALUE;for(let i=0;i<s.keys.length;i++){const n=s.keys[i];n.value>t&&(t=n.value)}return t}};let X=Sh;k([m()],X.prototype,"mode",2),k([m()],X.prototype,"constant",2),k([m()],X.prototype,"constantMin",2),k([m()],X.prototype,"constantMax",2),k([m(Lr)],X.prototype,"curve",2),k([m(Lr)],X.prototype,"curveMin",2),k([m(Lr)],X.prototype,"curveMax",2),k([m()],X.prototype,"curveMultiplier",2);var Rp;const At=(Rp=class{constructor(){a(this,"mode",0),a(this,"color"),a(this,"colorMin"),a(this,"colorMax"),a(this,"gradient"),a(this,"gradientMin"),a(this,"gradientMax")}static constant(s){const t=new At;return t.constant(s),t}static betweenTwoColors(s,t){const i=new At;return i.betweenTwoColors(s,t),i}constant(s){return this.mode=0,this.color=s,this}betweenTwoColors(s,t){return this.mode=2,this.colorMin=s,this.colorMax=t,this}evaluate(s,t){const i=t===void 0?Math.random():t;switch(this.mode){case 0:case"Color":return this.color;case 1:case"Gradient":return this.gradient.evaluate(s,At._temp),At._temp;case 2:case"TwoColors":return At._temp.lerpColors(this.colorMin,this.colorMax,i);case 3:case"TwoGradients":return this.gradientMin.evaluate(s,At._temp),this.gradientMax.evaluate(s,At._temp2),At._temp.lerp(At._temp2,i);case 4:case"RandomColor":const n=Math.random();return this.gradientMin.evaluate(s,At._temp),this.gradientMax.evaluate(s,At._temp2),At._temp.lerp(At._temp2,n)}return At._temp.set(16777215),At._temp.alpha=1,At._temp}},a(Rp,"_temp",new we(0,0,0,1)),a(Rp,"_temp2",new we(0,0,0,1)),Rp);let ii=At;k([m()],ii.prototype,"mode",2),k([m(we)],ii.prototype,"color",2),k([m(we)],ii.prototype,"colorMin",2),k([m(we)],ii.prototype,"colorMax",2),k([m(qo)],ii.prototype,"gradient",2),k([m(qo)],ii.prototype,"gradientMin",2),k([m(qo)],ii.prototype,"gradientMax",2);var q0=(s=>(s[s.Hierarchy=0]="Hierarchy",s[s.Local=1]="Local",s[s.Shape=2]="Shape",s))(q0||{});class It{constructor(){a(this,"cullingMode"),a(this,"duration"),a(this,"emitterVelocityMode"),a(this,"flipRotation"),a(this,"gravityModifier"),a(this,"gravityModifierMultiplier"),a(this,"loop"),a(this,"maxParticles"),a(this,"playOnAwake"),a(this,"prewarm"),a(this,"ringBufferLoopRange"),a(this,"ringBufferMode"),a(this,"scalingMode"),a(this,"simulationSpace"),a(this,"simulationSpeed"),a(this,"startColor"),a(this,"startDelay"),a(this,"startDelayMultiplier"),a(this,"startLifetime"),a(this,"startLifetimeMultiplier"),a(this,"startRotation"),a(this,"startRotationMultiplier"),a(this,"startRotation3D"),a(this,"startRotationX"),a(this,"startRotationXMultiplier"),a(this,"startRotationY"),a(this,"startRotationYMultiplier"),a(this,"startRotationZ"),a(this,"startRotationZMultiplier"),a(this,"startSize"),a(this,"startSize3D"),a(this,"startSizeMultiplier"),a(this,"startSizeX"),a(this,"startSizeXMultiplier"),a(this,"startSizeY"),a(this,"startSizeYMultiplier"),a(this,"startSizeZ"),a(this,"startSizeZMultiplier"),a(this,"startSpeed"),a(this,"startSpeedMultiplier"),a(this,"stopAction"),a(this,"useUnscaledTime")}}k([m(X)],It.prototype,"gravityModifier",2),k([m(ii)],It.prototype,"startColor",2),k([m(X)],It.prototype,"startDelay",2),k([m(X)],It.prototype,"startLifetime",2),k([m(X)],It.prototype,"startRotation",2),k([m(X)],It.prototype,"startRotationX",2),k([m(X)],It.prototype,"startRotationY",2),k([m(X)],It.prototype,"startRotationZ",2),k([m(X)],It.prototype,"startSize",2),k([m(X)],It.prototype,"startSizeX",2),k([m(X)],It.prototype,"startSizeY",2),k([m(X)],It.prototype,"startSizeZ",2),k([m(X)],It.prototype,"startSpeed",2);class Ch{constructor(){a(this,"cycleCount"),a(this,"maxCount"),a(this,"minCount"),a(this,"probability"),a(this,"repeatInterval"),a(this,"time"),a(this,"count"),a(this,"_performed",0)}reset(){this._performed=0}run(t){if(t<=this.time)return 0;let i=0;if(this.cycleCount===0||this._performed<this.cycleCount){const n=this.time+this.repeatInterval*this._performed;if(t>=n&&(this._performed+=1,Math.random()<this.probability))switch(this.count.mode){case 0:i=this.count.constant;break;case 3:i=W.lerp(this.count.constantMin,this.count.constantMax,Math.random());break;case 1:i=this.count.curve.evaluate(Math.random());break;case 2:const o=Math.random();i=W.lerp(this.count.curveMin.evaluate(o),this.count.curveMax.evaluate(o),Math.random());break}}return i}}class hn{constructor(){a(this,"enabled"),a(this,"bursts"),a(this,"rateOverTime"),a(this,"rateOverTimeMultiplier"),a(this,"rateOverDistance"),a(this,"rateOverDistanceMultiplier"),a(this,"system")}get burstCount(){var t;return((t=this.bursts)==null?void 0:t.length)??0}reset(){var t;(t=this.bursts)==null||t.forEach(i=>i.reset())}getBurst(){let t=0;if(this.burstCount>0)for(let i=0;i<this.burstCount;i++){const n=this.bursts[i];this.system.main.loop&&n.time>=this.system.time&&n.reset(),t+=Math.round(n.run(this.system.time))}return t}}k([m()],hn.prototype,"enabled",2),k([m()],hn.prototype,"bursts",2),k([m(X)],hn.prototype,"rateOverTime",2),k([m()],hn.prototype,"rateOverTimeMultiplier",2),k([m(X)],hn.prototype,"rateOverDistance",2),k([m()],hn.prototype,"rateOverDistanceMultiplier",2);class Oh{constructor(){a(this,"enabled"),a(this,"color")}}k([m(ii)],Oh.prototype,"color",2);class Go{constructor(){a(this,"enabled"),a(this,"separateAxes"),a(this,"size"),a(this,"sizeMultiplier"),a(this,"x"),a(this,"xMultiplier"),a(this,"y"),a(this,"yMultiplier"),a(this,"z"),a(this,"zMultiplier"),a(this,"_time",0),a(this,"_temp",new x)}evaluate(t,i,n){if(i||(i=this._temp),!this.enabled)return i.x=i.y=i.z=1,i;if(this.separateAxes)i.x=this.x.evaluate(t,n)*this.xMultiplier,i.y=this.y.evaluate(t,n)*this.yMultiplier,i.z=this.z.evaluate(t,n)*this.zMultiplier;else{const o=this.size.evaluate(t,n)*this.sizeMultiplier;i.x=o}return i}}k([m(X)],Go.prototype,"size",2),k([m(X)],Go.prototype,"x",2),k([m(X)],Go.prototype,"y",2),k([m(X)],Go.prototype,"z",2);var Tp;const Ph=(Tp=class{constructor(){a(this,"shapeType",5),a(this,"enabled",!0),a(this,"alignToDirection",!1),a(this,"angle",0),a(this,"arc",360),a(this,"arcSpread"),a(this,"arcSpeedMultiplier"),a(this,"arcMode"),a(this,"boxThickness"),a(this,"position"),a(this,"rotation"),a(this,"_rotation",new Ft),a(this,"scale"),a(this,"radius"),a(this,"radiusThickness"),a(this,"sphericalDirectionAmount"),a(this,"randomDirectionAmount"),a(this,"randomPositionAmount"),a(this,"meshShapeType"),a(this,"meshRenderer"),a(this,"_meshObj"),a(this,"_meshGeometry"),a(this,"system"),a(this,"_space"),a(this,"_worldSpaceMatrix",new ne),a(this,"_worldSpaceMatrixInverse",new ne),a(this,"_vector",new x(0,0,0)),a(this,"_temp",new x(0,0,0)),a(this,"_triangle",new pC),a(this,"_dir",new x),a(this,"_loopTime",0),a(this,"_loopDirection",1),kp&&console.log(this)}get type(){return Mp[this.shapeType]}initialize(s){this.onInitialize(s),s.position.x=this._vector.x,s.position.y=this._vector.y,s.position.z=this._vector.z}toJSON(){return this}clone(){return new Ph}setMesh(s){this.meshRenderer=s,s?(this._meshObj=s.sharedMeshes[Math.floor(Math.random()*s.sharedMeshes.length)],this._meshGeometry=this._meshObj.geometry):(this._meshObj=void 0,this._meshGeometry=void 0)}update(s,t){}onUpdate(s,t,i,n){this.system=s,this._space=i,i===1&&(this._worldSpaceMatrix.copy(n.matrixWorld),this._worldSpaceMatrix.elements[0]=1,this._worldSpaceMatrix.elements[5]=1,this._worldSpaceMatrix.elements[10]=1,this._worldSpaceMatrixInverse.copy(this._worldSpaceMatrix).invert())}applyRotation(s){const t=this.rotation.x!==0||this.rotation.y!==0||this.rotation.z!==0;return t&&(this._rotation.x=W.toRadians(this.rotation.x),this._rotation.y=W.toRadians(this.rotation.y),this._rotation.z=W.toRadians(this.rotation.z),this._rotation.order="ZYX",s.applyEuler(this._rotation)),t}onInitialize(s){this._vector.set(0,0,0),s.mesh=void 0,s.mesh_geometry=void 0;const t=this._temp.copy(this.position),i=this._space===1;i&&t.applyQuaternion(this.system.worldQuaternion);let n=this.radius;if(i&&(n*=this.system.worldScale.x),this.enabled){switch(this.shapeType){case 5:kp&&q.DrawWireBox(this.position,this.scale,14540253,1),this._vector.x=Math.random()*this.scale.x-this.scale.x/2,this._vector.y=Math.random()*this.scale.y-this.scale.y/2,this._vector.z=Math.random()*this.scale.z-this.scale.z/2,this._vector.add(t);break;case 4:this.randomConePoint(this.position,this.angle,n,this.radiusThickness,this.arc,this.arcMode,this._vector);break;case 0:this.randomSpherePoint(this.position,n,this.radiusThickness,this.arc,this._vector);break;case 10:this.randomCirclePoint(this.position,n,this.radiusThickness,this.arc,this._vector);break;case 13:const o=this.meshRenderer;o?.destroyed==!1&&this.setMesh(o);const r=s.mesh=this._meshObj,l=s.mesh_geometry=this._meshGeometry;if(r&&l)switch(this.meshShapeType){case 0:{const c=l.getAttribute("position"),h=Math.floor(Math.random()*c.count);this._vector.fromBufferAttribute(c,h),this._vector.applyMatrix4(r.matrixWorld),s.mesh_normal=h}break;case 1:break;case 2:{const c=l.index;if(c){let h=Math.random(),d=Math.random();h+d>1&&(h=1-h,d=1-d);const u=Math.floor(Math.random()*(c.count/3));let p=u*3,g=u*3+1,y=u*3+2;p=c.getX(p),g=c.getX(g),y=c.getX(y);const f=l.getAttribute("position");this._triangle.a.fromBufferAttribute(f,p),this._triangle.b.fromBufferAttribute(f,g),this._triangle.c.fromBufferAttribute(f,y),this._vector.set(0,0,0).addScaledVector(this._triangle.a,h).addScaledVector(this._triangle.b,d).addScaledVector(this._triangle.c,1-(h+d)),this._vector.applyMatrix4(r.matrixWorld),s.mesh_normal=u}}break}break;default:this._vector.set(0,0,0),F()&&!globalThis.__particlesystem_shapetype_unsupported&&(console.warn("ParticleSystem ShapeType is not supported:",Mp[this.shapeType]),globalThis.__particlesystem_shapetype_unsupported=!0);break}this.randomizePosition(this._vector,this.randomPositionAmount)}this.applyRotation(this._vector),i&&(this._vector.applyQuaternion(this.system.worldQuaternion),this._vector.add(this.system.worldPos)),kp&&q.DrawSphere(this._vector,.03,16711680,.5,!0)}getDirection(s,t){var i;if(!this.enabled)return this._dir.set(0,0,1),this._dir;switch(this.shapeType){case 5:this._dir.set(0,0,1);break;case 4:this._dir.set(0,0,1);break;case 10:case 0:const n=t.x,o=t.y,r=t.z;this._dir.set(n,o,r),(i=this.system)!=null&&i.worldspace?this._dir.sub(this.system.worldPos):this._dir.sub(this.position);break;case 13:const l=s.mesh,c=s.mesh_geometry;if(l&&c)switch(this.meshShapeType){case 0:{const h=c.getAttribute("normal"),d=s.mesh_normal;this._dir.fromBufferAttribute(h,d)}break;case 1:break;case 2:{const h=c.index;if(h){const d=s.mesh_normal,u=h.getX(d*3),p=h.getX(d*3+1),g=h.getX(d*3+2),y=c.getAttribute("position"),f=$(),v=$(),b=$();f.fromBufferAttribute(y,u),v.fromBufferAttribute(y,p),b.fromBufferAttribute(y,g),f.sub(v),b.sub(v),f.cross(b),this._dir.copy(f).multiplyScalar(-1);const w=Se(l);this._dir.applyQuaternion(w)}}break}break;default:this._dir.set(0,0,1);break}return this._space===1&&this._dir.applyQuaternion(this.system.worldQuaternion),this.applyRotation(this._dir),this._dir.normalize(),this.spherizeDirection(this._dir,this.sphericalDirectionAmount),this.randomizeDirection(this._dir,this.randomDirectionAmount),kp&&(q.DrawSphere(t,.01,8925952,.5,!0),q.DrawDirection(t,this._dir,8925952,.5,!0)),this._dir}randomizePosition(s,t){if(t<=0)return;const i=Ph._tempVec;i.set(Math.random()*2-1,Math.random()*2-1,Math.random()*2-1),i.x*=t*this.scale.x,i.y*=t*this.scale.y,i.z*=t*this.scale.z,s.add(i)}randomizeDirection(s,t){if(t===0)return;const i=Ph._randomQuat,n=Ph._tempVec;n.set(Math.random()-.5,Math.random()-.5,Math.random()-.5).normalize(),i.setFromAxisAngle(n,t*Math.random()*Math.PI),s.applyQuaternion(i)}spherizeDirection(s,t){if(t===0)return;const i=Math.random()*Math.PI*2,n=Math.acos(1-Math.random()*2),o=Math.sin(n)*Math.cos(i),r=Math.sin(n)*Math.sin(i),l=Math.cos(n),c=new x(o,r,l);s.lerp(c,t)}randomSpherePoint(s,t,i,n,o){const r=Math.random(),l=Math.random(),c=2*Math.PI*r*(n/360),h=Math.acos(2*l-1),d=W.lerp(1,1-Math.pow(1-Math.random(),Math.PI),i)*t,u=s.x+this.scale.x*(-d*Math.sin(h)*Math.cos(c)),p=s.y+this.scale.y*(d*Math.sin(h)*Math.sin(c)),g=s.z+this.scale.z*(d*Math.cos(h));o.x=u,o.y=p,o.z=g}randomCirclePoint(s,t,i,n,o){const r=Math.random(),l=2*Math.PI*r*(n/360),c=W.lerp(1,1-Math.pow(1-Math.random(),Math.PI),i)*t,h=s.x+this.scale.x*c*Math.cos(l),d=s.y+this.scale.y*c*Math.sin(l),u=s.z;o.x=h,o.y=d,o.z=u}randomConePoint(s,t,i,n,o,r,l){let c=0,h=0;switch(r){case 0:c=Math.random(),h=Math.random();break;case 2:this._loopTime>1&&(this._loopDirection=-1),this._loopTime<0&&(this._loopDirection=1);case 1:c=.5,h=Math.random(),this._loopTime+=this.system.deltaTime*this._loopDirection;break}let d=2*Math.PI*c*(o/360);switch(r){case 2:case 1:d+=Math.PI+.5,d+=this._loopTime*Math.PI*2,d%=W.toRadians(o);break}const u=Math.acos(2*h-1),p=W.lerp(1,1-Math.pow(1-Math.random(),Math.PI),n)*i,g=s.x+-p*Math.sin(u)*Math.cos(d),y=s.y+p*Math.sin(u)*Math.sin(d),f=s.z;l.x=g*this.scale.x,l.y=y*this.scale.y,l.z=f*this.scale.z}},a(Tp,"_randomQuat",new V),a(Tp,"_tempVec",new x),Tp);let Xe=Ph;k([m()],Xe.prototype,"shapeType",2),k([m()],Xe.prototype,"enabled",2),k([m()],Xe.prototype,"alignToDirection",2),k([m()],Xe.prototype,"angle",2),k([m()],Xe.prototype,"arc",2),k([m()],Xe.prototype,"arcSpread",2),k([m()],Xe.prototype,"arcSpeedMultiplier",2),k([m()],Xe.prototype,"arcMode",2),k([m(x)],Xe.prototype,"boxThickness",2),k([m(x)],Xe.prototype,"position",2),k([m(x)],Xe.prototype,"rotation",2),k([m(x)],Xe.prototype,"scale",2),k([m()],Xe.prototype,"radius",2),k([m()],Xe.prototype,"radiusThickness",2),k([m()],Xe.prototype,"sphericalDirectionAmount",2),k([m()],Xe.prototype,"randomDirectionAmount",2),k([m()],Xe.prototype,"randomPositionAmount",2),k([m()],Xe.prototype,"meshShapeType",2),k([m(th)],Xe.prototype,"meshRenderer",2);class xe{constructor(){a(this,"damping"),a(this,"enabled"),a(this,"frequency"),a(this,"octaveCount"),a(this,"octaveMultiplier"),a(this,"octaveScale"),a(this,"positionAmount"),a(this,"quality"),a(this,"remap"),a(this,"remapEnabled"),a(this,"remapMultiplier"),a(this,"remapX"),a(this,"remapXMultiplier"),a(this,"remapY"),a(this,"remapYMultiplier"),a(this,"remapZ"),a(this,"remapZMultiplier"),a(this,"scrollSpeedMultiplier"),a(this,"separateAxes"),a(this,"strengthMultiplier"),a(this,"strengthX"),a(this,"strengthXMultiplier"),a(this,"strengthY"),a(this,"strengthYMultiplier"),a(this,"strengthZ"),a(this,"strengthZMultiplier"),a(this,"_noise"),a(this,"_time",0),a(this,"_temp",new x)}update(t){this._time+=t.time.deltaTime*this.scrollSpeedMultiplier}apply(t,i,n,o,r,l){if(!this.enabled)return;this._noise||(this._noise=ZC(()=>0));const c=this._temp.set(i.x,i.y,i.z).multiplyScalar(this.frequency),h=this._noise(c.x,c.y,c.z,this._time),d=this._noise(c.x,c.y,c.z,this._time+1e3*this.frequency),u=this._noise(c.x,c.y,c.z,this._time+2e3*this.frequency);this._temp.set(h,d,u).normalize();const p=r/l;let g=this.positionAmount.evaluate(p);this.separateAxes?(this._temp.x*=g*this.strengthXMultiplier,this._temp.y*=g*this.strengthYMultiplier,this._temp.z*=g*this.strengthZMultiplier):(this.strengthX&&(g*=this.strengthX.evaluate(p)*1.5),this._temp.multiplyScalar(g)),n.x+=this._temp.x,n.y+=this._temp.y,n.z+=this._temp.z}}k([m()],xe.prototype,"damping",2),k([m()],xe.prototype,"enabled",2),k([m()],xe.prototype,"frequency",2),k([m()],xe.prototype,"octaveCount",2),k([m()],xe.prototype,"octaveMultiplier",2),k([m()],xe.prototype,"octaveScale",2),k([m(X)],xe.prototype,"positionAmount",2),k([m()],xe.prototype,"quality",2),k([m(X)],xe.prototype,"remap",2),k([m()],xe.prototype,"remapEnabled",2),k([m()],xe.prototype,"remapMultiplier",2),k([m(X)],xe.prototype,"remapX",2),k([m()],xe.prototype,"remapXMultiplier",2),k([m(X)],xe.prototype,"remapY",2),k([m()],xe.prototype,"remapYMultiplier",2),k([m(X)],xe.prototype,"remapZ",2),k([m()],xe.prototype,"remapZMultiplier",2),k([m()],xe.prototype,"scrollSpeedMultiplier",2),k([m()],xe.prototype,"separateAxes",2),k([m()],xe.prototype,"strengthMultiplier",2),k([m(X)],xe.prototype,"strengthX",2),k([m()],xe.prototype,"strengthXMultiplier",2),k([m(X)],xe.prototype,"strengthY",2),k([m()],xe.prototype,"strengthYMultiplier",2),k([m(X)],xe.prototype,"strengthZ",2),k([m()],xe.prototype,"strengthZMultiplier",2);class ze{constructor(){a(this,"enabled"),a(this,"attachRibbonToTransform",!1),a(this,"colorOverLifetime"),a(this,"colorOverTrail"),a(this,"dieWithParticles",!0),a(this,"inheritParticleColor",!0),a(this,"lifetime"),a(this,"lifetimeMultiplier"),a(this,"minVertexDistance",.2),a(this,"mode",0),a(this,"ratio",1),a(this,"ribbonCount",1),a(this,"shadowBias",0),a(this,"sizeAffectsLifetime",!1),a(this,"sizeAffectsWidth",!1),a(this,"splitSubEmitterRibbons",!1),a(this,"textureMode",0),a(this,"widthOverTrail"),a(this,"widthOverTrailMultiplier"),a(this,"worldSpace",!1)}getWidth(t,i,n,o){const r=this.widthOverTrail.evaluate(n,o);return t*=r,t}getColor(t,i,n){const o=this.colorOverTrail.evaluate(n),r=this.colorOverLifetime.evaluate(i);t.x*=o.r*r.r,t.y*=o.g*r.g,t.z*=o.b*r.b,"alpha"in o&&"alpha"in r&&(t.w*=o.alpha*r.alpha)}}k([m()],ze.prototype,"enabled",2),k([m()],ze.prototype,"attachRibbonToTransform",2),k([m(ii)],ze.prototype,"colorOverLifetime",2),k([m(ii)],ze.prototype,"colorOverTrail",2),k([m()],ze.prototype,"dieWithParticles",2),k([m()],ze.prototype,"inheritParticleColor",2),k([m(X)],ze.prototype,"lifetime",2),k([m()],ze.prototype,"lifetimeMultiplier",2),k([m()],ze.prototype,"minVertexDistance",2),k([m()],ze.prototype,"mode",2),k([m()],ze.prototype,"ratio",2),k([m()],ze.prototype,"ribbonCount",2),k([m()],ze.prototype,"shadowBias",2),k([m()],ze.prototype,"sizeAffectsLifetime",2),k([m()],ze.prototype,"sizeAffectsWidth",2),k([m()],ze.prototype,"splitSubEmitterRibbons",2),k([m()],ze.prototype,"textureMode",2),k([m(X)],ze.prototype,"widthOverTrail",2),k([m()],ze.prototype,"widthOverTrailMultiplier",2),k([m()],ze.prototype,"worldSpace",2);class Qe{constructor(){a(this,"enabled"),a(this,"space",0),a(this,"orbitalX"),a(this,"orbitalY"),a(this,"orbitalZ"),a(this,"orbitalXMultiplier"),a(this,"orbitalYMultiplier"),a(this,"orbitalZMultiplier"),a(this,"orbitalOffsetX"),a(this,"orbitalOffsetY"),a(this,"orbitalOffsetZ"),a(this,"speedModifier"),a(this,"speedModifierMultiplier"),a(this,"x"),a(this,"xMultiplier"),a(this,"y"),a(this,"yMultiplier"),a(this,"z"),a(this,"zMultiplier"),a(this,"_system"),a(this,"_temp",new x),a(this,"_temp2",new x),a(this,"_temp3",new x),a(this,"_hasOrbital",!1),a(this,"_index",0),a(this,"_orbitalMatrix",new ne)}update(t){this._system=t}init(t){this._index==0&&(t.debug=!0),this._index+=1,t.orbitx=this.orbitalX.evaluate(Math.random()),t.orbity=this.orbitalY.evaluate(Math.random()),t.orbitz=this.orbitalZ.evaluate(Math.random()),this._hasOrbital=t.orbitx!=0||t.orbity!=0||t.orbitz!=0}apply(t,i,n,o,r,l,c){var h;if(!this.enabled)return;const d=l/c,u=this.speedModifier.evaluate(d)*this.speedModifierMultiplier,p=this.x.evaluate(d),g=this.y.evaluate(d),y=this.z.evaluate(d);if(this._temp.set(-p,g,y),this._system&&this._system.main.simulationSpace===1&&this._temp.applyQuaternion(this._system.worldQuaternion),this._hasOrbital&&((h=this._system)==null?void 0:h.worldPos)){const f=this._temp2.set(n.x,n.y,n.z),v=this.orbitalXMultiplier,b=this.orbitalYMultiplier,w=this.orbitalZMultiplier,_=u*Math.PI*2*10,C=Math.cos(_*v),R=Math.sin(_*v),M=Math.cos(_*b),E=Math.sin(_*b),D=Math.cos(_*w),L=Math.sin(_*w),U=f.x*(M*D)+f.y*(M*L)+f.z*-E,z=f.x*(R*E*D-C*L)+f.y*(R*E*L+C*D)+f.z*(R*M),H=f.x*(C*E*D+R*L)+f.y*(C*E*L-R*D)+f.z*(C*M),T=this._temp3.set(f.x-U,f.y-z,f.z-H);T.normalize(),T.multiplyScalar(.2/r*Math.max(this.orbitalXMultiplier,this.orbitalYMultiplier,this.orbitalZMultiplier)),o.x+=T.x,o.y+=T.y,o.z+=T.z}o.x+=this._temp.x,o.y+=this._temp.y,o.z+=this._temp.z,o.x*=u,o.y*=u,o.z*=u}}k([m()],Qe.prototype,"enabled",2),k([m()],Qe.prototype,"space",2),k([m(X)],Qe.prototype,"orbitalX",2),k([m(X)],Qe.prototype,"orbitalY",2),k([m(X)],Qe.prototype,"orbitalZ",2),k([m()],Qe.prototype,"orbitalXMultiplier",2),k([m()],Qe.prototype,"orbitalYMultiplier",2),k([m()],Qe.prototype,"orbitalZMultiplier",2),k([m()],Qe.prototype,"orbitalOffsetX",2),k([m()],Qe.prototype,"orbitalOffsetY",2),k([m()],Qe.prototype,"orbitalOffsetZ",2),k([m(X)],Qe.prototype,"speedModifier",2),k([m()],Qe.prototype,"speedModifierMultiplier",2),k([m(X)],Qe.prototype,"x",2),k([m()],Qe.prototype,"xMultiplier",2),k([m(X)],Qe.prototype,"y",2),k([m()],Qe.prototype,"yMultiplier",2),k([m(X)],Qe.prototype,"z",2),k([m()],Qe.prototype,"zMultiplier",2);class jt{constructor(){a(this,"animation"),a(this,"enabled"),a(this,"cycleCount"),a(this,"frameOverTime"),a(this,"frameOverTimeMultiplier"),a(this,"numTilesX"),a(this,"numTilesY"),a(this,"startFrame"),a(this,"startFrameMultiplier"),a(this,"rowMode"),a(this,"rowIndex"),a(this,"spriteCount"),a(this,"timeMode")}sampleOnceAtStart(){if(this.timeMode===0)switch(this.frameOverTime.mode){case 0:case 3:case 2:case 1:return!0}return!1}getStartIndex(){return this.sampleOnceAtStart()?Math.random()*(this.numTilesX*this.numTilesY):0}evaluate(t){if(!this.sampleOnceAtStart())return this.getIndex(t)}getIndex(t){const i=this.numTilesX*this.numTilesY;t=t*this.cycleCount;let n=this.frameOverTime.evaluate(t%1);return n*=this.frameOverTimeMultiplier,n*=i,n=n%i,n=Math.floor(n),n}}k([m()],jt.prototype,"animation",2),k([m()],jt.prototype,"enabled",2),k([m()],jt.prototype,"cycleCount",2),k([m(X)],jt.prototype,"frameOverTime",2),k([m()],jt.prototype,"frameOverTimeMultiplier",2),k([m()],jt.prototype,"numTilesX",2),k([m()],jt.prototype,"numTilesY",2),k([m(X)],jt.prototype,"startFrame",2),k([m()],jt.prototype,"startFrameMultiplier",2),k([m()],jt.prototype,"rowMode",2),k([m()],jt.prototype,"rowIndex",2),k([m()],jt.prototype,"spriteCount",2),k([m()],jt.prototype,"timeMode",2);class ns{constructor(){a(this,"enabled"),a(this,"separateAxes"),a(this,"x"),a(this,"xMultiplier"),a(this,"y"),a(this,"yMultiplier"),a(this,"z"),a(this,"zMultiplier")}evaluate(t,i){return this.enabled?this.separateAxes?0:this.z.evaluate(t,i)*-1:0}}k([m()],ns.prototype,"enabled",2),k([m()],ns.prototype,"separateAxes",2),k([m(X)],ns.prototype,"x",2),k([m()],ns.prototype,"xMultiplier",2),k([m(X)],ns.prototype,"y",2),k([m()],ns.prototype,"yMultiplier",2),k([m(X)],ns.prototype,"z",2),k([m()],ns.prototype,"zMultiplier",2);class Bi{constructor(){a(this,"enabled"),a(this,"range"),a(this,"separateAxes"),a(this,"x"),a(this,"xMultiplier"),a(this,"y"),a(this,"yMultiplier"),a(this,"z"),a(this,"zMultiplier")}evaluate(t,i){if(!this.enabled)return 0;if(!this.separateAxes){const n=W.lerp(this.range.x,this.range.y,i);return this.z.evaluate(n)*-1}return 0}}k([m()],Bi.prototype,"enabled",2),k([m()],Bi.prototype,"range",2),k([m()],Bi.prototype,"separateAxes",2),k([m(X)],Bi.prototype,"x",2),k([m()],Bi.prototype,"xMultiplier",2),k([m(X)],Bi.prototype,"y",2),k([m()],Bi.prototype,"yMultiplier",2),k([m(X)],Bi.prototype,"z",2),k([m()],Bi.prototype,"zMultiplier",2);class ot{constructor(){a(this,"enabled"),a(this,"dampen"),a(this,"drag"),a(this,"dragMultiplier"),a(this,"limit"),a(this,"limitMultiplier"),a(this,"separateAxes"),a(this,"limitX"),a(this,"limitXMultiplier"),a(this,"limitY"),a(this,"limitYMultiplier"),a(this,"limitZ"),a(this,"limitZMultiplier"),a(this,"multiplyDragByParticleSize",!1),a(this,"multiplyDragByParticleVelocity",!1),a(this,"space"),a(this,"_temp",new x),a(this,"_temp2",new x)}apply(t,i,n,o,r,l,c){if(this.enabled){const h=this.limit.evaluate(r)*this.limitMultiplier;if(i.length()>h){this._temp.copy(i).normalize().multiplyScalar(h);const d=this.dampen*.5;i.x=W.lerp(i.x,this._temp.x,d),i.y=W.lerp(i.y,this._temp.y,d),i.z=W.lerp(i.z,this._temp.z,d),n.x=W.lerp(n.x,this._temp.x,d),n.y=W.lerp(n.y,this._temp.y,d),n.z=W.lerp(n.z,this._temp.z,d)}}}}k([m()],ot.prototype,"enabled",2),k([m()],ot.prototype,"dampen",2),k([m(X)],ot.prototype,"drag",2),k([m()],ot.prototype,"dragMultiplier",2),k([m(X)],ot.prototype,"limit",2),k([m()],ot.prototype,"limitMultiplier",2),k([m()],ot.prototype,"separateAxes",2),k([m(X)],ot.prototype,"limitX",2),k([m()],ot.prototype,"limitXMultiplier",2),k([m(X)],ot.prototype,"limitY",2),k([m()],ot.prototype,"limitYMultiplier",2),k([m(X)],ot.prototype,"limitZ",2),k([m()],ot.prototype,"limitZMultiplier",2),k([m()],ot.prototype,"multiplyDragByParticleSize",2),k([m()],ot.prototype,"multiplyDragByParticleVelocity",2),k([m()],ot.prototype,"space",2);const i1=class{constructor(){a(this,"enabled"),a(this,"curve"),a(this,"curveMultiplier"),a(this,"mode"),a(this,"system"),a(this,"_temp",new x),a(this,"_firstUpdate",!0),a(this,"_frames",0)}clone(){var s;const t=new i1;return t.enabled=this.enabled,t.curve=(s=this.curve)==null?void 0:s.clone(),t.curveMultiplier=this.curveMultiplier,t.mode=this.mode,t}get _lastWorldPosition(){return this.system._iv_lastWorldPosition||(this.system._iv_lastWorldPosition=new x),this.system._iv_lastWorldPosition}get _velocity(){return this.system._iv_velocity||(this.system._iv_velocity=new x),this.system._iv_velocity}awake(s){this.system=s,this.reset()}reset(){this._firstUpdate=!0}update(s){this.enabled&&this.system.worldspace!==!1&&(this._firstUpdate?(this._firstUpdate=!1,this._velocity.set(0,0,0),this._lastWorldPosition.copy(this.system.worldPos)):this._lastWorldPosition&&(this._velocity.copy(this.system.worldPos).sub(this._lastWorldPosition).multiplyScalar(1/this.system.deltaTime),this._lastWorldPosition.copy(this.system.worldPos)))}applyInitial(s){if(this.enabled&&this.system.worldspace!==!1&&this.mode===0){const t=this.curve.evaluate(Math.random(),Math.random());this._temp.copy(this._velocity).multiplyScalar(t),s.x+=this._temp.x,s.y+=this._temp.y,s.z+=this._temp.z}}applyCurrent(s,t,i){if(this.enabled&&this.system&&this.system.worldspace!==!1&&this.mode===1){const n=this.curve.evaluate(t,i);this._temp.copy(this._velocity).multiplyScalar(n),s.x+=this._temp.x,s.y+=this._temp.y,s.z+=this._temp.z}}};let Xo=i1;k([m()],Xo.prototype,"enabled",2),k([m(X)],Xo.prototype,"curve",2),k([m()],Xo.prototype,"curveMultiplier",2),k([m()],Xo.prototype,"mode",2);class si{constructor(){a(this,"enabled"),a(this,"range"),a(this,"separateAxes"),a(this,"size"),a(this,"sizeMultiplier"),a(this,"x"),a(this,"xMultiplier"),a(this,"y"),a(this,"yMultiplier"),a(this,"z"),a(this,"zMultiplier")}evaluate(t,i,n,o){const r=t.length(),l=W.remap(r,this.range.x,this.range.y,0,1),c=this.size.evaluate(l,n);return o.x*=c,o.y*=c,o.z*=c,o}}k([m()],si.prototype,"enabled",2),k([m(oe)],si.prototype,"range",2),k([m()],si.prototype,"separateAxes",2),k([m(X)],si.prototype,"size",2),k([m()],si.prototype,"sizeMultiplier",2),k([m(X)],si.prototype,"x",2),k([m()],si.prototype,"xMultiplier",2),k([m(X)],si.prototype,"y",2),k([m()],si.prototype,"yMultiplier",2),k([m(X)],si.prototype,"z",2),k([m()],si.prototype,"zMultiplier",2);class ea{constructor(){a(this,"enabled"),a(this,"range"),a(this,"color")}evaluate(t,i,n){const o=t.length(),r=W.remap(o,this.range.x,this.range.y,0,1),l=this.color.evaluate(r,i);n.x*=l.r,n.y*=l.g,n.z*=l.b,"alpha"in l&&(n.w*=l.alpha)}}k([m()],ea.prototype,"enabled",2),k([m(oe)],ea.prototype,"range",2),k([m(ii)],ea.prototype,"color",2),new x(1,1,1),new x(0,0,1);class Ep{constructor(t,i,n,o){a(this,"type","NeedleParticleSubEmitter"),a(this,"emitterType"),a(this,"emitterProbability"),a(this,"q_",new V),a(this,"v_",new x),a(this,"v2_",new x),a(this,"_emitterMatrix",new Cm),a(this,"_circularBuffer"),this.system=t,this.particleSystem=i,this.subSystem=n,this.subParticleSystem=o,this.subParticleSystem&&this.subParticleSystem&&(this.subParticleSystem.onlyUsedByOther=!0);const r=1e3;this._circularBuffer=new wi(()=>new Cm,r)}clone(){throw new Error("Method not implemented.")}initialize(t){t.emissionState={burstIndex:0,burstWaveIndex:0,time:0,waitEmiting:0},this._emitterMatrix.copy(this.subSystem.matrixWorld).invert().premultiply(this.system.matrixWorld),this._emitterMatrix.setPosition(0,0,0),this.emitterType===G0.Birth&&this.run(t)}update(t,i){this.run(t)}frameUpdate(t){}toJSON(){}reset(){}run(t){if(this.subSystem.currentParticles>=this.subSystem.main.maxParticles||!this.subParticleSystem||!t.emissionState||this.emitterProbability&&Math.random()>this.emitterProbability)return;const i=this.system.deltaTime;if(this.emitterType===G0.Death){let o=t.life;if(t[Ol]!==void 0&&(o=t[Ol]),!(t.age+i*1.2>=o))return;const r=this.subSystem.main.maxParticles-this.subSystem.currentParticles;t.emissionState.waitEmiting=r}const n=new Cm;n.set(1,0,0,t.position.x,0,1,0,t.position.y,0,0,1,t.position.z,0,0,0,1),this.particleSystem.worldSpace||n.multiplyMatrices(this._emitterMatrix,n),this.subParticleSystem.emit(i,t.emissionState,n)}}var AE=Object.defineProperty,IE=Object.getOwnPropertyDescriptor,Ye=(s,t,i,n)=>{for(var o=n>1?void 0:n?IE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&AE(t,i,o),o};const Qo=O("debugparticles"),jE=O("noprogressive"),LE=O("debugprogressive");var G0=(s=>(s[s.Birth=0]="Birth",s[s.Collision=1]="Collision",s[s.Death=2]="Death",s[s.Trigger=3]="Trigger",s[s.Manual=4]="Manual",s))(G0||{});class os extends A{constructor(){super(...arguments),a(this,"renderMode"),a(this,"particleMaterial"),a(this,"trailMaterial"),a(this,"particleMesh"),a(this,"maxParticleSize"),a(this,"minParticleSize"),a(this,"velocityScale"),a(this,"cameraVelocityScale"),a(this,"lengthScale")}start(){if(this.maxParticleSize!==.5&&this.minParticleSize!==0&&F()){const t=`ParticleSystem "${this.name}" has non-default min/max particle size. This may not render correctly. Please set min size to 0 and the max size to 0.5 and use the "StartSize" setting instead`;console.warn(t)}}get transparent(){var t;return((t=this.particleMaterial)==null?void 0:t.transparent)??!1}getMaterial(t=!1){let i=t===!0&&this.trailMaterial?this.trailMaterial:this.particleMaterial;if(i){if(i.type==="MeshStandardMaterial"){Qo&&console.debug("ParticleSystemRenderer.getMaterial: MeshStandardMaterial detected, converting to MeshBasicMaterial. See https://github.com/Alchemist0823/three.quarks/issues/101"),"map"in i&&i.map&&(i.map.colorSpace=pr,i.map.premultiplyAlpha=!1);const n=new Me;n.copy(i),t?this.trailMaterial=n:this.particleMaterial=n}i.map&&(i.map.colorSpace=pr,i.map.premultiplyAlpha=!1),t&&i.side===lo&&(i=i.clone(),i.side=fm,t?this.trailMaterial=i:this.particleMaterial=i)}return i&&!jE&&i._didRequestTextureLOD===void 0&&(i._didRequestTextureLOD=0,LE&&console.log("Load material LOD",i.name),et.assignTextureLOD(i,0)),i}getMesh(t){let i=null;if(!i&&(this.particleMesh instanceof Q&&(i=this.particleMesh.geometry),i===null)){i=new Ds(1,1);const n=i.attributes.uv;for(let o=0;o<n.count;o++)n.setX(o,1-n.getX(o))}return new Q(i,this.getMaterial())}}Ye([m()],os.prototype,"renderMode",2),Ye([m(Oe)],os.prototype,"particleMaterial",2),Ye([m(Oe)],os.prototype,"trailMaterial",2),Ye([m()],os.prototype,"maxParticleSize",2),Ye([m()],os.prototype,"minParticleSize",2),Ye([m()],os.prototype,"velocityScale",2),Ye([m()],os.prototype,"cameraVelocityScale",2),Ye([m()],os.prototype,"lengthScale",2);class Ap{constructor(t,i=1){a(this,"_curve"),a(this,"_factor"),a(this,"type","function"),this._curve=t,this._factor=i}startGen(t){}genValue(t,i){return this._curve.evaluate(i,Math.random())*this._factor}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}}class X0{constructor(t){a(this,"type","value"),a(this,"system"),this.system=t}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}startGen(t){}}class DE extends X0{genValue(){return this.system.textureSheetAnimation.getStartIndex()}}class BE extends X0{constructor(){super(...arguments),a(this,"_lastPosition",new x),a(this,"_lastDistance",0)}update(){const t=ee(this.system.gameObject);this._lastDistance=this._lastPosition.distanceTo(t),this._lastPosition.copy(t)}genValue(){if(!this.system.isPlaying||!this.system.emission.enabled||this.system.currentParticles>=this.system.maxParticles)return 0;let t=this.system.emission.rateOverTime.evaluate(this.system.time/this.system.duration,Math.random());if(this.system.deltaTime>0){const o=this.system.emission.rateOverDistance.evaluate(this.system.time/this.system.duration,Math.random());let r=this._lastDistance/this.system.deltaTime*o;Number.isFinite(r)||(r=0),t+=r}const i=this.system.emission.getBurst();i>0&&(t+=i/this.system.deltaTime);const n=this.system.maxParticles-this.system.currentParticles;return W.clamp(t,0,n/this.system.deltaTime)}}class FE extends X0{genValue(){return this.system.isPlaying,0}}class Yo{constructor(t){a(this,"system"),a(this,"type"),this.type=Object.getPrototypeOf(this).constructor.name||"ParticleSystemBaseBehaviour",t&&(this.system=t)}get context(){return this.system.context}initialize(t){}update(t,i){}frameUpdate(t){}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}reset(){}}class zE extends Yo{constructor(){super(...arguments),a(this,"type","NeedleTextureSheet")}update(t,i){const n=this.system.textureSheetAnimation;if(n.enabled){const o=t.age/t.life,r=n.evaluate(o);r!==void 0&&(t.uvTile=r)}}}const s1=Symbol("particleRotation");class UE extends Yo{constructor(){super(...arguments),a(this,"type","NeedleRotation")}initialize(t){t[s1]=Math.random()}update(t,i){if(t.rotation===void 0)return;const n=t.age/t.life;if(typeof t.rotation=="number"&&(this.system.rotationOverLifetime.enabled?t.rotation+=this.system.rotationOverLifetime.evaluate(n,t[s1])*i:this.system.renderer.renderMode===$n.Billboard&&(t.rotation=Math.PI),this.system.rotationBySpeed.enabled)){const o=t.velocity.length();t.rotation+=this.system.rotationBySpeed.evaluate(n,o)*i}}}const n1=Symbol("sizeLerpFactor"),NE=new x;class WE extends Yo{constructor(){super(...arguments),a(this,"type","NeedleSize"),a(this,"_minSize",0),a(this,"_maxSize",1)}initialize(t){t[n1]=Math.random(),this._minSize=this.system.renderer.minParticleSize,this._maxSize=this.system.renderer.maxParticleSize}update(t,i){const n=t.age/t.life;let o=1;this.system.sizeOverLifetime.enabled&&(o*=this.system.sizeOverLifetime.evaluate(n,void 0,t[n1]).x);let r=1;this.system.renderer.renderMode!==$n.Mesh&&(r=this.system.worldScale.x/this.system.cameraScale);const l=$(t.startSize).multiplyScalar(o*r);if(t.size.set(l.x,l.y,l.z),this.system.localspace){const c=c1(this.system,NE);t.size.x*=c.x,t.size.y*=c.y,t.size.z*=c.z}}}const Ol=Symbol("particleLife"),Q0=Symbol("trailLifetime"),o1=Symbol("trailStartLength"),Y0=Symbol("trailWidthRandom");class VE extends Yo{constructor(){super(...arguments),a(this,"type","NeedleTrail")}initialize(t){t instanceof yv&&(t[Ol]=t.life,this.system.trails.enabled&&this.system.trails.dieWithParticles===!1&&(t[Q0]=this.system.trails.lifetime.evaluate(Math.random(),Math.random()),t.life+=t[Q0]),t[o1]=t.length,t[Y0]=Math.random())}update(t){var i;if((i=this.system.trails)!=null&&i.enabled&&t instanceof yv){const n=t,o=t.age/t[Ol],r=t.previous.values(),l=t.previous.length;for(let c=0;c<l;c++){const h=r.next().value,d=1-c/(l-1),u=t.size;if(u.x<=0&&!this.system.trails.sizeAffectsWidth){const p=20*this.system.trails.widthOverTrail.evaluate(.5,n[Y0]);u.x=p,u.y=p,u.z=p}h.size=this.system.trails.getWidth(u.x,o,d,n[Y0]),h.color.copy(t.color),this.system.trails.getColor(h.color,o,d)}if(t.age>t[Ol]){t.velocity.set(0,0,0);const c=(t.age-t[Ol])/t[Q0];n.length=W.lerp(t[o1],0,c)}}}}const Ip=Symbol("startVelocity"),r1=Symbol("gravityModifier"),K0=Symbol("gravitySpeed"),jp=Symbol("velocity lerp factor"),Z0=new x;class HE extends Yo{constructor(){super(...arguments),a(this,"type","NeedleVelocity"),a(this,"_gravityDirection",new x)}initialize(t){var i,n;const o=this.system.main.simulationSpeed;t.startSpeed=this.system.main.startSpeed.evaluate(Math.random(),Math.random());const r=this.system.shape.getDirection(t,t.position);t.velocity.x=r.x*t.startSpeed,t.velocity.y=r.y*t.startSpeed,t.velocity.z=r.z*t.startSpeed,(i=this.system.inheritVelocity)!=null&&i.enabled&&this.system.inheritVelocity.applyInitial(t.velocity),t[Ip]?t[Ip].copy(t.velocity):t[Ip]=t.velocity.clone();const l=this.system.main.gravityModifier.evaluate(Math.random(),Math.random());t[r1]=l*o,t[K0]=l*o*.5,t[jp]=Math.random(),(n=this.system.velocityOverLifetime)==null||n.init(t),this._gravityDirection.set(0,-1,0),this.system.main.simulationSpace===xh.Local&&this._gravityDirection.applyQuaternion(this.system.worldQuaternionInverted).normalize()}update(t,i){var n;const o=t[Ip],r=t[r1];if(r!==0){const g=r*t[K0];Z0.copy(this._gravityDirection).multiplyScalar(g),t[K0]+=i*.05,o.add(Z0)}t.velocity.copy(o);const l=t.age/t.life;(n=this.system.inheritVelocity)!=null&&n.enabled&&this.system.inheritVelocity.applyCurrent(t.velocity,l,t[jp]);const c=this.system.noise;c.enabled&&c.apply(0,t.position,t.velocity,i,t.age,t.life);const h=this.system.sizeBySpeed;h!=null&&h.enabled&&(t.size=h.evaluate(t.velocity,l,t[jp],t.size));const d=this.system.colorBySpeed;d!=null&&d.enabled&&d.evaluate(t.velocity,t[jp],t.color);const u=this.system.velocityOverLifetime;u.enabled&&u.apply(t,0,t.position,t.velocity,i,t.age,t.life);const p=this.system.limitVelocityOverLifetime;if(p.enabled&&p.apply(t.position,o,t.velocity,t.size,l,i,1),this.system.worldspace){const g=this.system.worldScale;t.velocity.x*=g.x,t.velocity.y*=g.y,t.velocity.z*=g.z}}}const a1=Symbol("colorLerpFactor"),l1=new we(1,1,1,1),ta=new we(1,1,1,1);class $E extends Yo{constructor(){super(...arguments),a(this,"type","NeedleColor")}initialize(t){}_init(t){const i=this.system.renderer.particleMaterial;ta.copy(this.system.main.startColor.evaluate(Math.random())),i!=null&&i.color&&(l1.copy(i.color),ta.multiply(l1)),ta.convertLinearToSRGB(),t.startColor.set(ta.r,ta.g,ta.b,ta.alpha),t.color.copy(t.startColor),t[a1]=Math.random()}update(t,i){if(t.age===0&&this._init(t),this.system.colorOverLifetime.enabled){const n=t.age/t.life,o=this.system.colorOverLifetime.color.evaluate(n,t[a1]);t.color.set(o.r,o.g,o.b,"alpha"in o?o.alpha:1).multiply(t.startColor)}else t.color.copy(t.startColor)}}class qE{constructor(t){a(this,"system"),a(this,"emission"),a(this,"autoDestroy"),a(this,"startLength"),a(this,"emissionBursts"),a(this,"onlyUsedByOther"),a(this,"behaviors",[]),a(this,"rendererEmitterSettings",{startLength:new sO(220),followLocalOrigin:!1}),a(this,"flatWhiteTexture"),a(this,"clonedTexture",{original:void 0,clone:void 0}),this.system=t,this.emission=new BE(this.system)}get anim(){return this.system.textureSheetAnimation}get prewarm(){return!1}get material(){return this.system.renderer.getMaterial(this.system.trails.enabled)}get layers(){return this.system.gameObject.layers}update(){this.emission.update()}get looping(){return this.system.main.loop}get duration(){return this.system.duration}get shape(){return this.system.shape}get startLife(){return new Ap(this.system.main.startLifetime)}get startSpeed(){return new Ap(this.system.main.startSpeed)}get startRotation(){return new Ap(this.system.main.startRotation)}get startSize(){return new Ap(this.system.main.startSize)}get startColor(){return new tO(new iO(1,1,1,1))}get emissionOverTime(){return this.emission}get emissionOverDistance(){return new FE(this.system)}get instancingGeometry(){return this.system.renderer.getMesh(this.system.renderer.renderMode).geometry}get renderMode(){if(this.system.trails.enabled===!0)return wn.Trail;switch(this.system.renderer.renderMode){case $n.Billboard:return wn.BillBoard;case $n.Stretch:return wn.StretchedBillBoard;case $n.HorizontalBillboard:return wn.HorizontalBillBoard;case $n.VerticalBillboard:return wn.VerticalBillBoard;case $n.Mesh:return wn.Mesh}return wn.BillBoard}get speedFactor(){var t;let i=this.system.main.simulationSpeed;return((t=this.system.renderer)==null?void 0:t.renderMode)===$n.Stretch&&(i*=this.system.renderer.velocityScale??1),i}get texture(){const t=this.material;if(t&&t.map){const i=t.map;if(this.clonedTexture.original!==i||!this.clonedTexture.clone){const n=i.clone();n.premultiplyAlpha=!1,n.colorSpace=pr,this.clonedTexture.original=i,this.clonedTexture.clone=n}return this.clonedTexture.clone}return this.flatWhiteTexture||(this.flatWhiteTexture=Zg(new we(1,1,1,1),1)),this.flatWhiteTexture}get startTileIndex(){return new DE(this.system)}get uTileCount(){var t;return this.anim.enabled?(t=this.anim)==null?void 0:t.numTilesX:void 0}get vTileCount(){var t;return this.anim.enabled?(t=this.anim)==null?void 0:t.numTilesY:void 0}get renderOrder(){return 1}get blending(){var t;return((t=this.system.renderer.particleMaterial)==null?void 0:t.blending)??mC}get transparent(){return this.system.renderer.transparent}get worldSpace(){return this.system.main.simulationSpace===xh.World}}class GE{constructor(){a(this,"burstParticleIndex",0),a(this,"burstParticleCount",0),a(this,"isBursting",!1),a(this,"travelDistance",0),a(this,"previousWorldPos"),a(this,"burstIndex",0),a(this,"burstWaveIndex",0),a(this,"time",0),a(this,"waitEmiting",0)}}const Lp=class extends A{constructor(){super(...arguments),a(this,"_state"),a(this,"colorOverLifetime"),a(this,"main"),a(this,"emission"),a(this,"sizeOverLifetime"),a(this,"shape"),a(this,"noise"),a(this,"trails"),a(this,"velocityOverLifetime"),a(this,"limitVelocityOverLifetime"),a(this,"inheritVelocity"),a(this,"colorBySpeed"),a(this,"textureSheetAnimation"),a(this,"rotationOverLifetime"),a(this,"rotationBySpeed"),a(this,"sizeBySpeed"),a(this,"_cameraScale",1),a(this,"__worldQuaternion",new V),a(this,"_worldQuaternionInverted",new V),a(this,"_worldScale",new x),a(this,"_worldPositionFrame",-1),a(this,"_worldPos",new x),a(this,"_renderer"),a(this,"_batchSystem"),a(this,"_particleSystem"),a(this,"_interface"),a(this,"_container"),a(this,"_time",0),a(this,"_isPlaying",!0),a(this,"_isUsedAsSubsystem",!1),a(this,"_didPreWarm",!1),a(this,"_bursts"),a(this,"_subEmitterSystems"),a(this,"_lastBatchesCount",-1)}play(s=!1){var t;s&&P.foreachComponent(this.gameObject,i=>{i instanceof Lp&&i!==this&&i.play(!1)},!0),this._isPlaying=!0,this._particleSystem&&(this._particleSystem.emissionState.time=0,this._particleSystem.emitEnded=!1),(t=this.emission)==null||t.reset()}pause(s=!0){s&&P.foreachComponent(this.gameObject,t=>{t instanceof Lp&&t!==this&&t.pause(!1)},!0),this._isPlaying=!1}stop(s=!0,t=!1){s&&P.foreachComponent(this.gameObject,i=>{i instanceof Lp&&i!==this&&i.stop(!1,t)},!0),this._isPlaying=!1,this._time=0,t&&this.reset()}reset(){var s;this._time=0,this._particleSystem&&(this._particleSystem.particleNum=0,this._particleSystem.emissionState.time=0,this._particleSystem.emitEnded=!1,(s=this.emission)==null||s.reset())}emit(s){if(this._particleSystem){this.onUpdate(),s=Math.min(s,this.maxParticles-this.currentParticles),this._state||(this._state=new GE),this._state.waitEmiting=s,this._state.time=0;const t=this._particleSystem.emitEnded;this._particleSystem.emitEnded=!1,this._particleSystem.emit(this.deltaTime,this._state,this._particleSystem.emitter.matrixWorld),this._particleSystem.emitEnded=t}}get playOnAwake(){return this.main.playOnAwake}set playOnAwake(s){this.main.playOnAwake=s}get renderer(){return this._renderer}get isPlaying(){return this._isPlaying}get currentParticles(){var s;return((s=this._particleSystem)==null?void 0:s.particleNum)??0}get maxParticles(){return this.main.maxParticles}get time(){return this._time}get duration(){return this.main.duration}get deltaTime(){return this.context.time.deltaTime*this.main.simulationSpeed}get scale(){return this.gameObject.scale.x}get cameraScale(){return this._cameraScale}get container(){return this._container}get worldspace(){return this.main.simulationSpace===xh.World}get localspace(){return this.main.simulationSpace===xh.Local}get worldQuaternion(){return this.__worldQuaternion}get worldQuaternionInverted(){return this._worldQuaternionInverted}get worldScale(){return this._worldScale}get worldPos(){return this._worldPositionFrame!==this.context.time.frame&&(this._worldPositionFrame=this.context.time.frame,ee(this.gameObject,this._worldPos)),this._worldPos}get matrixWorld(){return this._container.matrixWorld}get isSubsystem(){return this._isUsedAsSubsystem}addBehaviour(s){return this._particleSystem?(s instanceof Yo&&(s.system=this),(F()||Qo)&&console.debug("Add custom ParticleSystem Behaviour",s),this._particleSystem.addBehavior(s),!0):!1}removeBehaviour(s){if(!this._particleSystem)return!1;const t=this._particleSystem.behaviors,i=t.indexOf(s);return i!==-1&&((F()||Qo)&&console.debug("Remove custom ParticleSystem Behaviour",i,s),t.splice(i,1)),!0}removeAllBehaviours(){return this._particleSystem?(this._particleSystem.behaviors.length=0,!0):!1}get behaviours(){return this._particleSystem?this._particleSystem.behaviors:null}get particleSystem(){return this._particleSystem??null}set bursts(s){for(let t=0;t<s.length;t++){const i=s[t];if(!(i instanceof Ch)){const n=new Ch;La(n,i),s[t]=n}}this._bursts=s}set subEmitterSystems(s){for(let t=0;t<s.length;t++){const i=s[t];if(!(i instanceof kh)){const n=new kh;La(n,i),s[t]=n}}Qo&&s.length>0&&console.log("SubEmitters: ",s,this),this._subEmitterSystems=s}onAfterDeserialize(s){if(this._subEmitterSystems&&Array.isArray(this._subEmitterSystems))for(const t of this._subEmitterSystems)t._deserialize(this.context,this.gameObject)}awake(){if(this._worldPositionFrame=-1,this._renderer=this.gameObject.getComponent(os),!this.main)throw new Error("Not Supported: ParticleSystem needs a serialized MainModule. Creating new particle systems at runtime is currently not supported.");this._container=new j,this._container.matrixAutoUpdate=!1,this.context.scene.add(this._container),this._batchSystem=new JC,this._batchSystem.name=this.gameObject.name,this._container.add(this._batchSystem),this._interface=new qE(this),this._particleSystem=new eO(this._interface),this._particleSystem.addBehavior(new WE(this)),this._particleSystem.addBehavior(new $E(this)),this._particleSystem.addBehavior(new zE(this)),this._particleSystem.addBehavior(new UE(this)),this._particleSystem.addBehavior(new HE(this)),this._particleSystem.addBehavior(new VE(this)),this._batchSystem.addSystem(this._particleSystem);const s=this._particleSystem.emitter;this.context.scene.add(s),this.inheritVelocity.system&&this.inheritVelocity.system!==this&&(this.inheritVelocity=this.inheritVelocity.clone()),this.inheritVelocity.awake(this),Qo&&(console.log(this),this.gameObject.add(new bi(1)))}start(){this.addSubParticleSystems(),this.updateLayers(),this.renderer.particleMesh instanceof Q&&this._interface.renderMode==wn.Mesh&&et.assignMeshLOD(this.renderer.particleMesh,0).then(s=>{s&&this.particleSystem&&this._interface.renderMode==wn.Mesh&&(this.particleSystem.instancingGeometry=s)})}onDestroy(){var s,t,i,n;(s=this._container)==null||s.removeFromParent(),(t=this._batchSystem)==null||t.removeFromParent(),(i=this._particleSystem)==null||i.emitter.removeFromParent(),(n=this._particleSystem)==null||n.dispose()}onEnable(){this.main&&(this.inheritVelocity&&(this.inheritVelocity.system=this),this._batchSystem&&(this._batchSystem.visible=!0),this.playOnAwake&&this.play(),this._isPlaying=this.playOnAwake)}onDisable(){this._batchSystem&&(this._batchSystem.visible=!1)}onBeforeRender(){var s;this.main&&(this._didPreWarm===!1&&((s=this.main)==null?void 0:s.prewarm)===!0&&(this._didPreWarm=!0,this.preWarm()),this.onUpdate(),this.onSimulate(this.deltaTime))}preWarm(){var s;if(!((s=this.emission)!=null&&s.enabled)||this.emission.rateOverTime.getMax()<=0)return;const t=1/60,i=this.main.duration,n=this.main.startLifetime.getMax(),o=1e3,r=Math.min(Math.max(i,n)/Math.max(.01,this.main.simulationSpeed),o),l=Math.ceil(r/t),c=Date.now();Qo&&console.log(`Particles ${this.name} - Prewarm for ${l} frames (${r} sec). Duration: ${i}, Lifetime: ${n}`);for(let h=0;h<l&&!(this.currentParticles>=this.maxParticles);h++){const d=Date.now()-c;if(d>2e3){console.warn(`Particles ${this.name} - Prewarm took too long. Aborting: ${d}`);break}this.onUpdate(),this.onSimulate(t)}}onSimulate(s){if(this._batchSystem){let t=this.context.time.frameCount%60===0;this._lastBatchesCount!==this._batchSystem.batches.length&&(this._lastBatchesCount=this._batchSystem.batches.length,t=!0),t&&this.updateLayers(),this._batchSystem.update(s)}this._time+=s,this._time>this.duration&&(this._time=0)}updateLayers(){if(this._batchSystem)for(let s=0;s<this._batchSystem.batches.length;s++){const t=this._batchSystem.batches[s];t.layers.disableAll();const i=this.layer;t.layers.mask=1<<i}}onUpdate(){var s,t;if(this._bursts&&(this.emission.bursts=this._bursts,delete this._bursts),!this._isPlaying)return;const i=this.context.mainCamera;if(i){const r=Ke(i);this._cameraScale=r.x}const n=!this.worldspace,o=this.gameObject;if(Se(o,this.__worldQuaternion),this._worldQuaternionInverted.copy(this.__worldQuaternion).invert(),Ke(this.gameObject,this._worldScale),n&&this._container&&(s=this.gameObject)!=null&&s.parent){const r=c1(this,Z0);this._container.matrix.makeScale(r.x,r.y,r.z),this._container.matrix.makeRotationFromQuaternion(this.__worldQuaternion),this._container.matrix.setPosition(this.worldPos),this._container.matrix.scale(this.gameObject.scale)}this.emission.system=this,this._interface.update(),this.shape.onUpdate(this,this.context,this.main.simulationSpace,this.gameObject),this.noise.update(this.context),(t=this.inheritVelocity)==null||t.update(this.context),this.velocityOverLifetime.update(this)}addSubParticleSystems(){var s;if(this._subEmitterSystems&&this._particleSystem)for(const t of this._subEmitterSystems){t.particleSystem&&(t.particleSystem.__internalAwake?t.particleSystem.__internalAwake():F()&&console.warn("SubParticleSystem serialization issue(?)",t.particleSystem,t));const i=(s=t.particleSystem)==null?void 0:s._particleSystem;if(i){t.particleSystem._isUsedAsSubsystem=!0;const n=new Ep(this,this._particleSystem,t.particleSystem,i);n.emitterType=t.type,n.emitterProbability=t.emitProbability,this._particleSystem.addBehavior(n)}else Qo&&console.warn("Could not add SubParticleSystem",t,this)}}};let rt=Lp;Ye([m(Oh)],rt.prototype,"colorOverLifetime",2),Ye([m(It)],rt.prototype,"main",2),Ye([m(hn)],rt.prototype,"emission",2),Ye([m(Go)],rt.prototype,"sizeOverLifetime",2),Ye([m(Xe)],rt.prototype,"shape",2),Ye([m(xe)],rt.prototype,"noise",2),Ye([m(ze)],rt.prototype,"trails",2),Ye([m(Qe)],rt.prototype,"velocityOverLifetime",2),Ye([m(ot)],rt.prototype,"limitVelocityOverLifetime",2),Ye([m(Xo)],rt.prototype,"inheritVelocity",2),Ye([m(ea)],rt.prototype,"colorBySpeed",2),Ye([m(jt)],rt.prototype,"textureSheetAnimation",2),Ye([m(ns)],rt.prototype,"rotationOverLifetime",2),Ye([m(Bi)],rt.prototype,"rotationBySpeed",2),Ye([m(si)],rt.prototype,"sizeBySpeed",2);class kh{constructor(){a(this,"particleSystem"),a(this,"emitProbability",1),a(this,"properties"),a(this,"type")}_deserialize(t,i){const n=this.particleSystem;if(n instanceof rt)return;let o="";n&&typeof n.guid=="string"&&(o=n.guid,this.particleSystem=P.findByGuid(o,i)),Qo&&!(this.particleSystem instanceof rt)&&console.warn("Could not find particle system for sub emitter",o,i,this)}}function c1(s,t){if(t.set(1,1,1),s.gameObject.parent&&s.localspace)switch(s.main.scalingMode){case q0.Local:t=Ke(s.gameObject.parent,t),t.x=1/t.x,t.y=1/t.y,t.z=1/t.z;break;default:if(!s.unsupported_scaling_mode){s.unsupported_scaling_mode=!0;const i="ParticleSystem scale mode "+q0[s.main.scalingMode]+" is not supported";F()&&_e(i),console.warn(i,s.name,s)}t=Ke(s.gameObject,t);break}return t}class zl extends A{constructor(){super(...arguments),a(this,"_didAssignPlayerColor",!1),a(this,"tryAssignColor",()=>{const t=P.getComponentInParent(this.gameObject,ji);if(t&&t.owner)return this._didAssignPlayerColor=!0,this.assignUserColor(t.owner),!0;const i=P.getComponentInParent(this.gameObject,Mt);return i!=null&&i.connectionId?(this._didAssignPlayerColor=!0,this.assignUserColor(i.connectionId),!0):!1})}onEnable(){this.context.connection.beginListen(ie.JoinedRoom,this.tryAssignColor),this._didAssignPlayerColor||this.startCoroutine(this.waitForConnection())}onDisable(){this.context.connection.stopListen(ie.JoinedRoom,this.tryAssignColor)}*waitForConnection(){for(;!this.destroyed&&this.activeAndEnabled&&(yield H_(.2),!this.tryAssignColor()););}assignUserColor(t){const i=zl.hashCode(t),n=zl.colorFromHashCode(i);if(this.gameObject.type==="Mesh"){const o=this.gameObject;this.assignColor(n,t,o)}else if(this.gameObject.children)for(const o of this.gameObject.children){const r=o;r.material&&r.material.color&&this.assignColor(n,t,r)}}assignColor(t,i,n){let o=n.material;o&&(o._playerMaterial!==i&&(o=o.clone(),o._playerMaterial=i,n.material=o),o.color=t)}static hashCode(t){var i=0,n,o;if(t.length===0)return i;for(n=0;n<t.length;n++)o=t.charCodeAt(n),i=(i<<5)-i+o,i|=0;return i}static colorFromHashCode(t){const i=(t&16711680)>>16,n=(t&65280)>>8,o=t&255;return new ae(i/255,n/255,o/255)}}const XE=O("debugpost");let J0=null;function QE(s){J0=s}function h1(s){let t=s.gameObject;for(;t;){for(const i of eu(t))if(i.isPostProcessingManager===!0)return i;t=t.parent}return null}function YE(s){let t=h1(s);if(!t)if(J0){XE&&console.warn("Adding postprocessing manager to the scene.");const i=s.scene;t=ki(i,J0)}else F()&&console.warn("No post processing manager found");return t}var KE=Object.defineProperty,ZE=Object.getOwnPropertyDescriptor,d1=(s,t,i,n)=>{for(var o=n>1?void 0:n?ZE(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&KE(t,i,o),o};const JE=O("debugpost");class N{constructor(t){a(this,"isVolumeParameter",!0),a(this,"_isInitialized",!1),a(this,"_active",!0),a(this,"_value"),a(this,"_valueRaw"),a(this,"_defaultValue"),a(this,"valueProcessor"),a(this,"onValueChanged"),t!==void 0&&this.initialize(t)}get isInitialized(){return this._isInitialized}initialize(t){t!==void 0&&(this._value=t,this._defaultValue=t,this._valueRaw=t,this._isInitialized=!0)}get overrideState(){return this._active}set overrideState(t){if(this._active===t)return;this._active=t;const i=t?this._valueRaw:this._defaultValue;this.processValue(i,!0)}get value(){return this._valueRaw}set value(t){this.isInitialized||this.initialize(t),this.processValue(t,!1)}set defaultValue(t){this._defaultValue=t}__init(){this.processValue(this._valueRaw,!0)}processValue(t,i){if(t==null||!i&&this.testIfValueChanged(t)===!1)return;const n=this._value;JE&&typeof n=="number"&&typeof t=="number"&&(n?.toFixed(4),t?.toFixed(4)),!this._active&&this._defaultValue!==void 0?(this._value=this._defaultValue,t=this._defaultValue,this._valueRaw=t):(this._valueRaw=t,this._active&&this.valueProcessor&&(t=this.valueProcessor(t)),this._value=t),this.onValueChanged&&this.onValueChanged(t,n,this)}testIfValueChanged(t){return this._valueRaw!==t}}d1([m()],N.prototype,"overrideState",1),d1([m()],N.prototype,"value",1);class eA extends Ki{constructor(){super([N])}onSerialize(t,i){}onDeserialize(t,i){const n=i.target,o=i.path;let r;if(n&&o&&(r=n[o]),(typeof r!="object"||typeof r=="object"&&r.isVolumeParameter!==!0)&&(r=new N),typeof t=="object"&&"value"in t){const l=t.value;r.initialize(l),r.overrideState=t.overrideState}else r.value=t;return r}}new eA;var tA=Object.defineProperty,iA=Object.getOwnPropertyDescriptor,sA=(s,t,i,n)=>{for(var o=n>1?void 0:n?iA(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&tA(t,i,o),o};const nA=O("debugpost");class at extends A{constructor(t=void 0){if(super(),a(this,"active",!0),a(this,"_manager",null),a(this,"_result"),a(this,"_postprocessingContext",null),t)for(const i of Object.keys(t)){const n=t[i],o=this[i];o instanceof N?o.initialize(n):o!==void 0&&(this[i]=n)}}get isPostProcessingEffect(){return!0}onEnable(){super.onEnable(),this.onEffectEnabled(),this.__internalDidAwakeAndStart&&(this.active=!0)}onDisable(){var t;super.onDisable(),(t=this._manager)==null||t.removeEffect(this),this.active=!1}onEffectEnabled(t){var i;t&&t.isPostProcessingManager===!0?this._manager=t:this._manager||(this._manager=YE(this)),(i=this._manager)==null||i.addEffect(this)}init(){}get postprocessingContext(){return this._postprocessingContext}apply(t){var i;return this._postprocessingContext=t,this._result||(this.initParameters(),this._result=(i=this.onCreateEffect)==null?void 0:i.call(this)),this._result&&this.initParameters(),this._result}unapply(){}dispose(){nA&&console.warn("DISPOSE",this),this._result&&(Array.isArray(this._result)?this._result.forEach(t=>t.dispose()):this._result.dispose()),this._result=void 0}initParameters(){const t=Object.keys(this);for(const i of t){const n=this[i];n instanceof N&&n.__init()}}onEditorModification(t){const i=t.propertyName;if(this[i]instanceof N){const n=t.value;return this[i].value=n,!0}}}sA([m()],at.prototype,"active",2);var oA=Object.defineProperty,rA=Object.getOwnPropertyDescriptor,aA=(s,t,i,n)=>{for(var o=n>1?void 0:n?rA(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&oA(t,i,o),o};const lA=O("debugpost"),ey={};function rs(s,t){ey[s]=t}function cA(s){return s.__type in ey?ey[s.__type]:(lA&&s.__type&&console.warn("Unknown postprocessing type",s.__type,s),at)}class Mh{constructor(){a(this,"components",[])}init(){var t;(t=this.components)==null||t.forEach(i=>i.init())}addEffect(t){this.components.push(t)}removeEffect(t){const i=this.components.indexOf(t);i>=0&&this.components.splice(i,1)}}aA([Ha([s=>cA(s),at])],Mh.prototype,"components",2);var hA=Object.defineProperty,dA=Object.getOwnPropertyDescriptor,uA=(s,t,i,n)=>{for(var o=n>1?void 0:n?dA(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&hA(t,i,o),o};class Rh extends at{constructor(){super(...arguments),a(this,"preset",new N(2))}get typeName(){return"Antialiasing"}onCreateEffect(){const t=new B.POSTPROCESSING.MODULE.SMAAEffect({preset:B.POSTPROCESSING.MODULE.SMAAPreset.HIGH,edgeDetectionMode:B.POSTPROCESSING.MODULE.EdgeDetectionMode.DEPTH});return this.preset.onValueChanged=i=>{t.applyPreset(i)},t}}uA([m(N)],Rh.prototype,"preset",2),rs("Antialiasing",Rh);var pA=Object.defineProperty,mA=Object.getOwnPropertyDescriptor,ty=(s,t,i,n)=>{for(var o=n>1?void 0:n?mA(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&pA(t,i,o),o},iy;const u1=(iy=class extends at{constructor(){super(...arguments),a(this,"threshold",new N(.9)),a(this,"intensity",new N(1)),a(this,"scatter",new N(.3)),a(this,"selectiveBloom")}get typeName(){return"Bloom"}init(){this.threshold.valueProcessor=s=>s,this.intensity.valueProcessor=s=>s,this.scatter.valueProcessor=s=>s}onCreateEffect(){let s;if(this.selectiveBloom==null&&(this.selectiveBloom=u1.useSelectiveBloom),this.selectiveBloom){const t=s=new B.POSTPROCESSING.MODULE.SelectiveBloomEffect(this.context.scene,this.context.mainCamera,{blendFunction:B.POSTPROCESSING.MODULE.BlendFunction.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,radius:.85,intensity:this.intensity.value});t.inverted=!0}else s=new B.POSTPROCESSING.MODULE.BloomEffect({blendFunction:B.POSTPROCESSING.MODULE.BlendFunction.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,radius:.85,intensity:this.intensity.value});return this.intensity.onValueChanged=t=>{s.intensity=t},this.threshold.onValueChanged=t=>{s.luminanceMaterial.threshold=Math.pow(t,2.2)},this.scatter.onValueChanged=t=>{s.luminancePass.enabled=!0,s.luminanceMaterial.smoothing=t,s.mipmapBlurPass&&(s.mipmapBlurPass.radius=vn.lerp(.1,.9,t))},s}},a(iy,"useSelectiveBloom",!1),iy);let ia=u1;ty([m(N)],ia.prototype,"threshold",2),ty([m(N)],ia.prototype,"intensity",2),ty([m(N)],ia.prototype,"scatter",2),rs("Bloom",ia);var gA=Object.defineProperty,fA=Object.getOwnPropertyDescriptor,yA=(s,t,i,n)=>{for(var o=n>1?void 0:n?fA(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&gA(t,i,o),o};class Th extends at{constructor(){super(...arguments),a(this,"intensity",new N(0))}get typeName(){return"ChromaticAberration"}onCreateEffect(){const t=new B.POSTPROCESSING.MODULE.ChromaticAberrationEffect;return t.offset=new oe(0,0),t.radialModulation=!0,t.modulationOffset=.15,this.intensity.valueProcessor=i=>i*.02,this.intensity.onValueChanged=i=>{t.offset.x=-i,t.offset.y=i},t}}yA([m(N)],Th.prototype,"intensity",2),rs("ChromaticAberration",Th);var vA=Object.defineProperty,bA=Object.getOwnPropertyDescriptor,p1=(s,t,i,n)=>{for(var o=n>1?void 0:n?bA(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&vA(t,i,o),o};const m1=O("debugpost");var Dp=(s=>(s[s.None=0]="None",s[s.Neutral=1]="Neutral",s[s.ACES=2]="ACES",s[s.AgX=3]="AgX",s[s.KhronosNeutral=4]="KhronosNeutral",s))(Dp||{});function sy(s){switch(s){case 0:return ud;case 1:return bm;case 2:return vm;case 3:return dd;case 4:return Hl;default:return Hl}}function _A(s){switch(s){case ud:return 0;case vm:return 2;case dd:return 3;case Hl:return 1;case bm:return 1;default:return 0}}function g1(s){switch(s){case ud:return B.POSTPROCESSING.MODULE.ToneMappingMode.LINEAR;case vm:return B.POSTPROCESSING.MODULE.ToneMappingMode.ACES_FILMIC;case dd:return B.POSTPROCESSING.MODULE.ToneMappingMode.AGX;case Hl:return B.POSTPROCESSING.MODULE.ToneMappingMode.NEUTRAL;case bm:return B.POSTPROCESSING.MODULE.ToneMappingMode.REINHARD;default:return B.POSTPROCESSING.MODULE.ToneMappingMode.LINEAR}}const f1=class extends at{constructor(){super(...arguments),a(this,"mode",new N(void 0)),a(this,"exposure",new N(1))}get typeName(){return"ToneMapping"}setMode(s){const t=Dp[s];return t===void 0?(console.error("Invalid ToneMapping mode",s),this):(this.mode.value=t,this)}get isToneMapping(){return!0}onEffectEnabled(){const s=h1(this);s&&super.onEffectEnabled(s)}onCreateEffect(){if(this.postprocessingContext)for(const i of this.postprocessingContext.components){if(i===this)break;if(i!=this&&i instanceof f1){console.warn("Multiple tonemapping effects found in the same postprocessing stack: Please check your scene setup.",{activeEffect:i,ignoredEffect:this});return}}if(this.mode.isInitialized==!1){const i=_A(this.context.renderer.toneMapping);this.mode.initialize(i)}const s=sy(this.mode.value),t=new B.POSTPROCESSING.MODULE.ToneMappingEffect({mode:g1(s)});return this.mode.onValueChanged=i=>{const n=sy(i);t.mode=g1(n),m1&&console.log("ToneMapping mode changed to",Dp[i],n,t.mode)},m1&&console.log("Use ToneMapping",Dp[this.mode.value],s,t.mode,"renderer.tonemapping: "+this.context.renderer.toneMapping),this.exposure.onValueChanged=i=>{this.context.renderer.toneMappingExposure=i},t}onBeforeRender(){this.mode.overrideState&&(this.context.renderer.toneMapping=sy(this.mode.value)),this.exposure.overrideState&&(this.context.renderer.toneMappingExposure=this.exposure.value)}};let Ko=f1;p1([m(N)],Ko.prototype,"mode",2),p1([m(N)],Ko.prototype,"exposure",2),rs("Tonemapping",Ko);var wA=Object.defineProperty,xA=Object.getOwnPropertyDescriptor,Bp=(s,t,i,n)=>{for(var o=n>1?void 0:n?xA(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&wA(t,i,o),o};class Zo extends at{constructor(){super(...arguments),a(this,"postExposure",new N(0)),a(this,"contrast",new N(0)),a(this,"hueShift",new N(0)),a(this,"saturation",new N(0))}get typeName(){return"ColorAdjustments"}init(){this.postExposure.valueProcessor=t=>(t=Math.pow(2,t),t),this.contrast.valueProcessor=t=>{let i=1;return t>0?i=200:t<0&&(i=100),t/i},this.contrast.defaultValue=0,this.hueShift.valueProcessor=t=>Math.PI*t/180,this.hueShift.defaultValue=0,this.saturation.valueProcessor=t=>t<0?t/100:t/(100*Math.PI),this.saturation.defaultValue=0}onCreateEffect(){var t,i;const n=[];this.context.renderer.toneMapping!==_a&&this.postExposure.overrideState&&(this.context.renderer.toneMapping=_a);let o=(t=this.postprocessingContext)==null?void 0:t.components.find(c=>c instanceof Ko);o||(o=new Ko,(i=this.postprocessingContext)==null||i.components.push(o)),this.postExposure.onValueChanged=c=>{this.postExposure.overrideState&&(o.exposure.value=c)};const r=new B.POSTPROCESSING.MODULE.BrightnessContrastEffect;this.contrast.onValueChanged=c=>r.contrast=c;const l=new B.POSTPROCESSING.MODULE.HueSaturationEffect;return n.push(r),n.push(l),this.hueShift.onValueChanged=c=>l.hue=c,this.saturation.onValueChanged=c=>l.saturation=c,n}}Bp([m(N)],Zo.prototype,"postExposure",2),Bp([m(N)],Zo.prototype,"contrast",2),Bp([m(N)],Zo.prototype,"hueShift",2),Bp([m(N)],Zo.prototype,"saturation",2),rs("ColorAdjustments",Zo);var SA=Object.defineProperty,CA=Object.getOwnPropertyDescriptor,sa=(s,t,i,n)=>{for(var o=n>1?void 0:n?CA(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&SA(t,i,o),o};const OA=O("debugpost");class Ts extends at{constructor(){super(...arguments),a(this,"mode"),a(this,"focusDistance",new N(1)),a(this,"focalLength",new N(.2)),a(this,"aperture",new N(20)),a(this,"gaussianMaxRadius",new N),a(this,"resolutionScale",new N(1*1/window.devicePixelRatio)),a(this,"bokehScale",new N)}get typeName(){return"DepthOfField"}init(){this.focalLength.valueProcessor=i=>{const n=i/300,o=2;return W.lerp(o,.01,n)};const t=20;this.aperture.valueProcessor=i=>{const n=1-i/32;return W.lerp(1,t,n)}}onCreateEffect(){if(this.mode===0){OA&&console.warn("DepthOfField: Mode is set to Off");return}const t=new B.POSTPROCESSING.MODULE.DepthOfFieldEffect(this.context.mainCamera,{worldFocusRange:.2,focalLength:1,bokehScale:20,resolutionScale:this.resolutionScale.value});return this.focusDistance.onValueChanged=i=>{t.cocMaterial.worldFocusDistance=i},this.focalLength.onValueChanged=i=>t.cocMaterial.worldFocusRange=i,this.aperture.onValueChanged=i=>t.bokehScale=i,this.resolutionScale&&(this.resolutionScale.onValueChanged=i=>t.resolution.scale=i),[t]}unapply(){}}sa([m()],Ts.prototype,"mode",2),sa([m(N)],Ts.prototype,"focusDistance",2),sa([m(N)],Ts.prototype,"focalLength",2),sa([m(N)],Ts.prototype,"aperture",2),sa([m(N)],Ts.prototype,"gaussianMaxRadius",2),sa([m(N)],Ts.prototype,"resolutionScale",2),sa([m(N)],Ts.prototype,"bokehScale",2),rs("DepthOfField",Ts);class Eh extends at{constructor(t){super(),a(this,"effect"),this.effect=t}get typeName(){return this.effect.constructor.name}onCreateEffect(){return this.effect}}var PA=Object.defineProperty,kA=Object.getOwnPropertyDescriptor,MA=(s,t,i,n)=>{for(var o=n>1?void 0:n?kA(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&PA(t,i,o),o};class Ah extends at{constructor(){super(...arguments),a(this,"granularity",new N(10))}get typeName(){return"PixelationEffect"}onCreateEffect(){const t=new B.POSTPROCESSING.MODULE.PixelationEffect;return this.granularity.onValueChanged=i=>{t.granularity=i},t}}MA([m(N)],Ah.prototype,"granularity",2),rs("PixelationEffect",Ah);var RA=Object.defineProperty,TA=Object.getOwnPropertyDescriptor,Ih=(s,t,i,n)=>{for(var o=n>1?void 0:n?TA(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&RA(t,i,o),o};class qn extends at{constructor(){super(...arguments),a(this,"intensity",new N(2)),a(this,"falloff",new N(1)),a(this,"samples",new N(9)),a(this,"color",new N(new ae(0,0,0))),a(this,"luminanceInfluence",new N(.7)),a(this,"_ssao")}get typeName(){return"ScreenSpaceAmbientOcclusion"}onBeforeRender(){if(this._ssao&&this.context.mainCamera instanceof be){const t=this.context.mainCamera.far-this.context.mainCamera.near;this._ssao.ssaoMaterial.worldDistanceFalloff=t*.01,this._ssao.ssaoMaterial.worldDistanceThreshold=this.context.mainCamera.far}}onCreateEffect(){const t=this.context.mainCamera,i=new B.POSTPROCESSING.MODULE.NormalPass(this.context.scene,t),n=new B.POSTPROCESSING.MODULE.DepthDownsamplingPass({normalBuffer:i.texture,resolutionScale:.5}),o=this._ssao=new B.POSTPROCESSING.MODULE.SSAOEffect(t,i.texture,{normalDepthBuffer:n.texture,worldDistanceThreshold:1,worldDistanceFalloff:1,worldProximityThreshold:.1,worldProximityFalloff:2,intensity:1,blendFunction:B.POSTPROCESSING.MODULE.BlendFunction.MULTIPLY,luminanceInfluence:.5});this.intensity.onValueChanged=l=>{o.intensity=l},this.falloff.onValueChanged=l=>{o.ssaoMaterial.radius=l*.1},this.samples.onValueChanged=l=>{o.ssaoMaterial.samples=l},this.color.onValueChanged=l=>{o.color||(o.color=new ae),o.color.copy(l)},this.luminanceInfluence.onValueChanged=l=>{o.luminanceInfluence=l};const r=new Array;return r.push(i),r.push(n),r.push(o),r}}Ih([m(N)],qn.prototype,"intensity",2),Ih([m(N)],qn.prototype,"falloff",2),Ih([m(N)],qn.prototype,"samples",2),Ih([m(N)],qn.prototype,"color",2),Ih([m(N)],qn.prototype,"luminanceInfluence",2),rs("ScreenSpaceAmbientOcclusion",qn);var EA=Object.defineProperty,AA=Object.getOwnPropertyDescriptor,na=(s,t,i,n)=>{for(var o=n>1?void 0:n?AA(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&EA(t,i,o),o},ny=(s=>(s[s.Performance=0]="Performance",s[s.Low=1]="Low",s[s.Medium=2]="Medium",s[s.High=3]="High",s[s.Ultra=4]="Ultra",s))(ny||{});class Es extends at{constructor(){super(...arguments),a(this,"gammaCorrection",!0),a(this,"aoRadius",new N(1)),a(this,"falloff",new N(1)),a(this,"intensity",new N(1)),a(this,"color",new N(new ae(0,0,0))),a(this,"screenspaceRadius",!1),a(this,"quality",2),a(this,"_ssao")}get typeName(){return"ScreenSpaceAmbientOcclusionN8"}onValidate(){this._ssao&&(this._ssao.setQualityMode(ny[this.quality]),this._ssao.configuration.gammaCorrection=this.gammaCorrection,this._ssao.configuration.screenSpaceRadius=this.screenspaceRadius)}onCreateEffect(){const t=this.context.mainCamera,i=this._ssao=new B.POSTPROCESSING_AO.MODULE.N8AOPostPass(this.context.scene,t,this.context.domWidth,this.context.domHeight),n=ny[this.quality];i.setQualityMode(n),i.configuration.gammaCorrection=this.gammaCorrection,i.configuration.screenSpaceRadius=this.screenspaceRadius,this.intensity.onValueChanged=r=>{i.configuration.intensity=r},this.falloff.onValueChanged=r=>{i.configuration.distanceFalloff=r},this.aoRadius.onValueChanged=r=>{i.configuration.aoRadius=r},this.color.onValueChanged=r=>{i.color||(i.color=new ae),i.configuration.color.copy(r)};const o=new Array;return o.push(i),o}}na([kt(),m()],Es.prototype,"gammaCorrection",2),na([m(N)],Es.prototype,"aoRadius",2),na([m(N)],Es.prototype,"falloff",2),na([m(N)],Es.prototype,"intensity",2),na([m(N)],Es.prototype,"color",2),na([kt(),m()],Es.prototype,"screenspaceRadius",2),na([kt(),m()],Es.prototype,"quality",2),rs("ScreenSpaceAmbientOcclusionN8",Es);var IA=Object.defineProperty,jA=Object.getOwnPropertyDescriptor,y1=(s,t,i,n)=>{for(var o=n>1?void 0:n?jA(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&IA(t,i,o),o};class jh extends at{constructor(){super(...arguments),a(this,"_effect"),a(this,"_amount",1),a(this,"_radius",1)}get typeName(){return"Sharpening"}onCreateEffect(){return this._effect??(this._effect=new(LA())),this.effect}get effect(){return this._effect}set amount(t){this._amount=t,this._effect&&(this._effect.uniforms.get("amount").value=t)}get amount(){return this._effect?this._effect.uniforms.get("amount").value:this._amount}set radius(t){this._radius=t,this._effect&&(this._effect.uniforms.get("radius").value=t)}get radius(){return this._effect?this._effect.uniforms.get("radius").value:this._radius}}y1([m()],jh.prototype,"amount",1),y1([m()],jh.prototype,"radius",1);function LA(){const s=`
1202
1202
  void mainSupport() {
1203
1203
  vUv = uv;
1204
1204
  gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
@@ -1357,7 +1357,7 @@ void main() {
1357
1357
  #include <colorspace_fragment>
1358
1358
  }
1359
1359
  `;var cj=Object.defineProperty,hj=Object.getOwnPropertyDescriptor,rr=(s,t,i,n)=>{for(var o=n>1?void 0:n?hj(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&cj(t,i,o),o};const F1=O("debugimagetracking"),Py=class{constructor(s,t,i,n,o,r){a(this,"measuredSize"),a(this,"state"),a(this,"_position"),a(this,"_rotation"),a(this,"_trackingComponent"),a(this,"_trackedImage"),a(this,"_bitmap"),a(this,"_pose"),this._trackingComponent=s,this._trackedImage=t,this._bitmap=i,this.measuredSize=n,this.state=o,this._pose=r}get url(){return this._trackedImage.image??""}get widthInMeters(){return this._trackedImage.widthInMeters??void 0}get bitmap(){return this._bitmap}get model(){return this._trackedImage}getPosition(s){return this.ensureTransformData(),s.copy(this._position),s}getQuaternion(s){return this.ensureTransformData(),s.copy(this._rotation),s}applyToObject(s,t=void 0){this.ensureTransformData();const i=s.position.distanceToSquared(this._position)/.05+s.quaternion.angleTo(this._rotation)/.05;t&&(t*=Math.max(1,i)),t===void 0||t>=1?(s.position.copy(this._position),s.quaternion.copy(this._rotation)):(t=Math.max(0,Math.min(1,t)),s.position.lerp(this._position,t),s.quaternion.slerp(this._rotation,t))}ensureTransformData(){if(!this._position){this._position=Py._positionBuffer.get(),this._rotation=Py._rotationBuffer.get();const s=this._pose.transform,t=Z.active.convertSpace(s);this._position.copy(t?.position),this._rotation.copy(t?.quaternion)}}};let Il=Py;a(Il,"_positionBuffer",new wi(()=>new x,20)),a(Il,"_rotationBuffer",new wi(()=>new V,20));class fn{constructor(){a(this,"image"),a(this,"widthInMeters",.25),a(this,"object"),a(this,"createObjectInstance",!1),a(this,"imageDoesNotMove",!1),a(this,"hideWhenTrackingIsLost",!0)}}rr([m(URL)],fn.prototype,"image",2),rr([m()],fn.prototype,"widthInMeters",2),rr([m(le)],fn.prototype,"object",2),rr([m()],fn.prototype,"createObjectInstance",2),rr([m()],fn.prototype,"imageDoesNotMove",2),rr([m()],fn.prototype,"hideWhenTrackingIsLost",2);class dj{constructor(t,i,n){a(this,"filename"),a(this,"widthInMeters"),a(this,"imageData"),this.filename=t,this.imageData=i,this.widthInMeters=n}get extensionName(){return"image-tracking"}onAfterHierarchy(t,i){i.beginBlock('def Preliminary_ReferenceImage "AnchoringReferenceImage"'),i.appendLine("uniform asset image = @image_tracking/"+this.filename+"@"),i.appendLine("uniform double physicalWidth = "+(this.widthInMeters*100).toFixed(8)),i.closeBlock()}onBeforeBuildDocument(t){const i=P.findObjectOfType(ha);!i||!i.trackedImages||i.trackedImages.length>1&&(F()&&_e("USDZ: Only one tracked image is supported."),console.warn("USDZ: Only one tracked image is supported."))}onAfterSerialize(t){t.files["image_tracking/"+this.filename]=this.imageData}onExportObject(t,i,n){var o;const r=P.findObjectOfType(ha);if(!(!r||!r.trackedImages)){for(const l of r.trackedImages)if(((o=l.object)==null?void 0:o.asset)===t){const c=P.findObjectOfType(Ge);if(!c)continue;const{scale:h,target:d}=c.getARScaleAndTarget();let u=t;const p=new ne;if(t!==d)for(;u.parent&&u.parent!==d;)u=u.parent,p.premultiply(u.matrix);const g=p.clone().invert();i.setMatrix(g.scale(new x(h,h,h)));break}}}}var ky;const Kh=(ky=class extends A{constructor(){super(...arguments),a(this,"trackedImages"),a(this,"smooth",!0),a(this,"trackedImageIndexMap",new Map),a(this,"_supported",!0),a(this,"imageToObjectMap",new Map),a(this,"currentImages",[]),a(this,"webXRIncubationsWarning",`Image tracking is currently not supported on this device. On Chrome for Android, you can enable the <a target="_blank" href="#" onclick="() => console.log('I')">chrome://flags/#webxr-incubations</a> flag.`),a(this,"onImageTrackingUpdate",s=>{const t=Z.active;if(t)for(const i of s){const n=i.model,o=i.state==="tracked";if(!n.object)continue;let r=this.imageToObjectMap.get(n);if(r===void 0)r={object:null,frames:0,lastTrackingTime:Date.now()},this.imageToObjectMap.set(n,r),n.object.loadAssetAsync().then(l=>{if(n.createObjectInstance&&l&&(l=P.instantiate(l)),l){r.object=l;for(const c of l.getComponentsInChildren(Ze))c.setInstancingEnabled(!1);t.rig?(t.rig.gameObject.add(l),i.applyToObject(l),l.activeSelf||P.setActive(l,!0)):console.warn("XRImageTracking: missing XRRig")}});else{if(r.frames++,o&&(r.lastTrackingTime=Date.now()),n.imageDoesNotMove&&r.frames>10||!r.object)continue;t.rig&&(t.rig.gameObject.add(r.object),i.applyToObject(r.object,this.smooth?this.context.time.deltaTimeUnscaled*3:void 0),r.object.activeSelf||P.setActive(r.object,!0))}}})}get supported(){return this._supported}awake(){if(F1&&console.log(this),!!this.trackedImages){for(const s of this.trackedImages)if(s.image&&!Kh._imageElements.has(s.image)){const t=s.image;Kh._imageElements.set(t,null);const i=document.createElement("img");i.src=t,i.addEventListener("load",async()=>{const n=await createImageBitmap(i);Kh._imageElements.set(t,n);const o=await kx(n);if(o){const r=await(await o.convertToBlob({type:"image/png"})).arrayBuffer(),l=P.findObjectOfType(Ge);l&&this.trackedImages&&(l.extensions.push(new dj("marker.png",new Uint8Array(r),this.trackedImages[0].widthInMeters)),l.anchoringType="image")}})}}}onBeforeXR(s,t){var i;if(this.trackedImages){t.optionalFeatures=t.optionalFeatures||[],t.optionalFeatures.includes("image-tracking")||t.optionalFeatures.push("image-tracking"),t.trackedImages=[];for(const n of this.trackedImages)if((i=n.image)!=null&&i.length&&n.widthInMeters>0){const o=Kh._imageElements.get(n.image);o&&(this.trackedImageIndexMap.set(t.trackedImages.length,n),t.trackedImages.push({image:o,widthInMeters:n.widthInMeters}))}}}onEnterXR(s){var t;if(this.trackedImages){for(const i of this.trackedImages)if((t=i.object)!=null&&t.asset){const n=i.object.asset;n.userData||(n.userData={});const o={visible:n.visible,parent:n.parent,matrix:n.matrix.clone()};n.userData["image-tracking"]=o}}for(const i of this.imageToObjectMap.values())i.frames=0}onLeaveXR(s){var t,i;if(!this.supported&&Y.isAndroidDevice()&&_e(this.webXRIncubationsWarning),this.trackedImages){for(const n of this.trackedImages)if((t=n.object)!=null&&t.asset){const o=n.object.asset;if(o.userData){const r=o.userData["image-tracking"];r&&(o.visible=r.visible,(i=r.parent)==null||i.add(o),o.matrix.copy(r.matrix),o.matrix.decompose(o.position,o.quaternion,o.scale)),delete o.userData["image-tracking"]}}}}onUpdateXR(s){var t;this.currentImages.length=0;const i=s.xr.frame;if(!i)return;if("getImageTrackingResults"in i){if(((t=s.xr.session.enabledFeatures)==null?void 0:t.includes("image-tracking"))===!1)return;if(i.session&&typeof i.getImageTrackingResults=="function"){const o=i.getImageTrackingResults();if(o.length>0){const r=this.context.renderer.xr.getReferenceSpace();if(r){for(const l of o){const c=l.trackingState,h=l.index,d=this.trackedImageIndexMap.get(h);if(d){const u=i.getPose(l.imageSpace,r),p=new Il(this,d,l.image,l.measuredSize,c,u);this.currentImages.push(p)}else F1&&console.warn("No tracked image for index",h)}if(this.currentImages.length>0)try{this.dispatchEvent(new CustomEvent("image-tracking",{detail:this.currentImages})),this.onImageTrackingUpdate(this.currentImages)}catch(l){console.error(l)}}}}}else{this.didPrintWarning||(this.didPrintWarning=!0,console.log(this.webXRIncubationsWarning)),this._supported=!1,_e(this.webXRIncubationsWarning);return}const n=1e3;for(const[o,r]of this.imageToObjectMap){if(!r.object||!o||o.hideWhenTrackingIsLost===!1)continue;let l=!1;for(const c of this.currentImages)if(c.model===o){const h=Date.now()-r.lastTrackingTime;if(o.imageDoesNotMove||c.state==="tracked"||h<=n){l=!0;break}}l||P.setActive(r.object,!1)}}},a(ky,"_imageElements",new Map),ky);let ha=Kh;rr([m(fn)],ha.prototype,"trackedImages",2),rr([m()],ha.prototype,"smooth",2);var uj=Object.defineProperty,pj=Object.getOwnPropertyDescriptor,jl=(s,t,i,n)=>{for(var o=n>1?void 0:n?pj(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&uj(t,i,o),o};const da=O("debugplanetracking");class Zn extends A{constructor(){super(...arguments),a(this,"dataTemplate"),a(this,"occluder",!0),a(this,"initiateRoomCaptureIfNoData",!0),a(this,"usePlaneData",!0),a(this,"useMeshData",!0),a(this,"runInVR",!0),a(this,"bounds",new vi),a(this,"center",new x),a(this,"labelOffset",new x),a(this,"_dataId",1),a(this,"_allPlanes",new Map),a(this,"_allMeshes",new Map),a(this,"firstTimeNoPlanesDetected",-100),a(this,"makeOccluder",(t,i,n=!1)=>{if(i){if(i instanceof Array){for(const o of i)this.makeOccluder(t,o,n);return}!n&&!i.name.toLowerCase().includes("occlu")||(i.colorWrite=!1,i.depthTest=!0,i.depthWrite=!0,i.transparent=!1,i.polygonOffset=!0,i.polygonOffsetFactor=1,i.polygonOffsetUnits=.1,t.renderOrder=-1e3)}}),a(this,"_flipForwardMatrix",new ne().makeRotationY(Math.PI)),a(this,"_verticesCache",new Map)}get trackedPlanes(){return this._allPlanes.values()}get trackedMeshes(){return this._allMeshes.values()}onBeforeXR(t,i){t==="immersive-vr"&&!this.runInVR||(i.optionalFeatures=i.optionalFeatures||[],this.usePlaneData&&!i.optionalFeatures.includes("plane-detection")&&i.optionalFeatures.push("plane-detection"),this.useMeshData&&!i.optionalFeatures.includes("mesh-detection")&&i.optionalFeatures.push("mesh-detection"))}onEnterXR(t){for(const i of this._allPlanes.keys())this.removeData(i,this._allPlanes);for(const i of this._allMeshes.keys())this.removeData(i,this._allMeshes)}onLeaveXR(t){for(const i of this._allPlanes.keys())this.removeData(i,this._allPlanes);for(const i of this._allMeshes.keys())this.removeData(i,this._allMeshes)}onUpdateXR(t){if(!this.runInVR&&t.xr.isVR)return;const i=t.xr.rig;if(!i){console.warn("No XR rig found, cannot parent tracked planes to it");return}const n=t.xr.frame;if(!this.context.renderer.xr.getReferenceSpace())return;const o=n.detectedPlanes,r=n.detectedMeshes,l=o!==void 0&&o.size>0,c=r!==void 0&&r.size>0;if(this.initiateRoomCaptureIfNoData&&(!l&&!c&&this.firstTimeNoPlanesDetected<-10&&(this.firstTimeNoPlanesDetected=Date.now()),(l||c)&&(this.firstTimeNoPlanesDetected=-1),this.firstTimeNoPlanesDetected>0&&Date.now()-this.firstTimeNoPlanesDetected>2500&&"initiateRoomCapture"in n.session&&(n.session.initiateRoomCapture(),this.firstTimeNoPlanesDetected=-1)),o!==void 0&&this.processFrameData(t.xr,i.gameObject,n,o,this._allPlanes),r!==void 0&&this.processFrameData(t.xr,i.gameObject,n,r,this._allMeshes),da){const h=this.context.mainCameraComponent.gameObject.worldPosition;for(const d of this._allPlanes.values())!d.mesh||!d.mesh.visible||(this.bounds.makeEmpty(),d.mesh.traverse(u=>{u instanceof Q&&this.bounds.expandByObject(u)}),this.bounds.getCenter(this.center),this.labelOffset.copy(h).sub(this.center).normalize().multiplyScalar(.1),q.DrawLabel(this.center.add(this.labelOffset),(d.xrData.semanticLabel||"plane").toUpperCase()+`
1360
- `+d.xrData.lastChangedTime.toFixed(2),.02))}}removeData(t,i){const n=i.get(t);if(!n)return;i.delete(t),da&&console.log("Plane no longer tracked, id="+n.id),n.mesh&&(n.mesh.removeFromParent(),n.mesh.traverse(r=>{const l=r.userData.normalsHelper;l?(l.dispose(),l.removeFromParent()):da&&console.warn("No normals helper found for mesh",n.mesh)}),Mi(n.mesh,!0,!0));const o=new CustomEvent("plane-tracking",{detail:{type:"plane-removed",context:n}});this.dispatchEvent(o)}processFrameData(t,i,n,o,r){const l=this.context.renderer.xr.getReferenceSpace();if(l){for(const c of r.keys())o.has(c)||this.removeData(c,r);for(const c of o){const h="planeSpace"in c?c.planeSpace:"meshSpace"in c?c.meshSpace:void 0;if(!h)continue;const d=n.getPose(h,l);let u;if(r.has(c)){const p=r.get(c);if(u=p.mesh,p.timestamp<c.lastChangedTime){if(p.timestamp=c.lastChangedTime,p.mesh){const y=this.createGeometry(c);if(p.mesh instanceof Q)p.mesh.geometry.dispose(),p.mesh.geometry=y,this.makeOccluder(p.mesh,p.mesh.material);else if(p.mesh instanceof ro)for(const f of p.mesh.children)f instanceof Q&&(f.geometry.dispose(),f.geometry=y,this.makeOccluder(f,f.material));if(p.collider){const f=p.mesh;p.collider.sharedMesh=f,p.collider.convex=this.checkIfContextShouldBeConvex(f,p.xrData),p.collider.onDisable(),p.collider.onEnable()}da&&(console.log("Plane updated, id="+p.id,p),p.mesh.traverse(f=>{if(!(f instanceof Q))return;const v=f.userData.normalsHelper;v&&v.update()}))}const g=new CustomEvent("plane-tracking",{detail:{type:"plane-updated",context:p}});this.dispatchEvent(g)}}else{if(!this.dataTemplate){const p=new Q;da?p.material=new SC:this.occluder?(p.material=new Me,this.makeOccluder(p,p.material,!0)):p.material=new Me({wireframe:!0,opacity:.5,transparent:!0,color:3355443}),this.dataTemplate=new le("","",p)}if(!this.dataTemplate.asset)this.dataTemplate.loadAssetAsync();else{const p=P.instantiate(this.dataTemplate.asset);if(p.name="xr-tracked-plane",u=p,Ym(p,!1),p instanceof Q)Te(p.geometry),p.geometry=this.createGeometry(c),this.makeOccluder(p,p.material,this.occluder);else if(p instanceof ro)for(const f of p.children)f instanceof Q&&(Te(f.geometry),f.geometry=this.createGeometry(c),this.makeOccluder(f,f.material,this.occluder));const g=p.getComponent(Eo);if(g){const f=p;g.sharedMesh=f,g.convex=this.checkIfContextShouldBeConvex(f,c),g.onDisable(),g.onEnable()}p.matrixAutoUpdate=!1,p.matrixWorldNeedsUpdate=!0,i.add(p);const y={id:this._dataId++,xrData:c,timestamp:c.lastChangedTime,mesh:p,collider:g};r.set(c,y),da&&console.log("New plane detected, id="+y.id,y,{hasCollider:!!g,isGroup:p instanceof ro});try{const f=new CustomEvent("plane-tracking",{detail:{type:"plane-added",context:y}});this.dispatchEvent(f)}catch(f){console.error(f)}}}u&&(d?(u.visible=!0,u.matrix.fromArray(d.transform.matrix),u.matrix.premultiply(this._flipForwardMatrix)):u.visible=!1,da&&u.traverse(p=>{if(p instanceof Q)if(p.userData.normalsHelper)p.userData.normalsHelper.update();else{const g=new GC(p,.05,255);g.layers.disableAll(),g.layers.set(2),this.context.scene.add(g),p.userData.normalsHelper=g}}))}}}checkIfContextShouldBeConvex(t,i){if(!t)return!0;if(t){const n=new vi;n.expandByObject(t);const o=new x;n.getSize(o);let r=!0;return o.x>2&&o.y>2&&o.z>1.5&&(r=!1),r&&"semanticLabel"in i&&i.semanticLabel==="wall"&&(r=!0),r}return!0}createGeometry(t){return"polygon"in t?this.createPlaneGeometry(t.polygon):"vertices"in t&&"indices"in t?this.createMeshGeometry(t.vertices,t.indices):new oo}createMeshGeometry(t,i){const n=t.toString()+"_"+i.toString();if(this._verticesCache.has(n))return this._verticesCache.get(n);const o=new oo;o.setIndex(new mt(i,1)),o.setAttribute("position",new mt(t,3));const r=Array();for(let l=0;l<t.length;l+=3)r.push(t[l],t[l+2]);return o.setAttribute("uv",new mt(t,3)),o.computeVertexNormals(),this._verticesCache.set(n,o),o}createPlaneGeometry(t){const i=new oo,n=[],o=[];t.forEach(g=>{n.push(g.x,g.y,g.z),o.push(g.x,g.z)});const r=new x(n[0],n[1],n[2]),l=new x(n[3],n[4],n[5]),c=new x(n[6],n[7],n[8]),h=new x,d=new x;h.subVectors(l,r),d.subVectors(c,r),h.cross(d),h.normalize();const u=[];for(let g=0;g<n.length/3;g++)u.push(h.x,h.y,h.z);const p=[];for(let g=2;g<t.length;++g)p.push(0,g-1,g);return i.setAttribute("position",new mt(new Float32Array(n),3)),i.setAttribute("uv",new mt(new Float32Array(o),2)),i.setAttribute("normal",new mt(new Float32Array(u),3)),i.setIndex(p),i.computeBoundingBox(),i.computeBoundingSphere(),i}}jl([m(le)],Zn.prototype,"dataTemplate",2),jl([m()],Zn.prototype,"occluder",2),jl([m()],Zn.prototype,"initiateRoomCaptureIfNoData",2),jl([m()],Zn.prototype,"usePlaneData",2),jl([m()],Zn.prototype,"useMeshData",2),jl([m()],Zn.prototype,"runInVR",2);var mj=Object.defineProperty,gj=Object.getOwnPropertyDescriptor,fj=(s,t,i,n)=>{for(var o=n>1?void 0:n?gj(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&mj(t,i,o),o};const z1=O("debugwebxr");class tm extends A{constructor(){super(...arguments),a(this,"priority",0),a(this,"_startScale")}get isActive(){return this.activeAndEnabled&&this.gameObject.visible}setAsActiveXRRig(){var t;(t=Z.active)==null||t.setRigActive(this)}setPriority(t){this.priority=t}awake(){if(z1){const t=new j;t.position.y+=.5,this.gameObject.add(t);const i=t.addNewComponent(Kr);i&&(i.isGizmo=!1);const n=new bi(.5);this.gameObject.add(n)}}isXRRig(){return!0}supportsXR(t){return!0}onEnterXR(t){this._startScale=this.gameObject.scale.clone(),t.xr.addRig(this),z1&&console.log("WebXR: add Rig",this.name,this.priority)}onLeaveXR(t){t.xr.removeRig(this),this._startScale&&this.gameObject&&this.gameObject.scale.copy(this._startScale)}}fj([m()],tm.prototype,"priority",2);class My{}const yj=Object.freeze(Object.defineProperty({__proto__:null,ActionBuilder:ue,ActionCollection:d0,ActionModel:Ai,AlignmentConstraint:Tc,Animation:Ut,AnimationCurve:Lr,AnimationExtension:nh,AnimationTrackHandler:Xp,Animator:Pt,AnimatorController:Vi,Antialiasing:Rh,AudioExtension:lr,AudioListener:Mo,AudioSource:We,AudioTrackHandler:$h,Avatar:No,AvatarBlink_Simple:Fr,AvatarEyeLook_Rotation:Ya,AvatarLoader:Tf,AvatarMarker:Mt,AvatarModel:zu,Avatar_Brain_LookAt:Nc,Avatar_MouthShapes:Hc,Avatar_MustacheShake:kf,Avatar_POI:Xs,AxesHelper:Ka,BaseUIComponent:ls,BasicIKConstraint:Af,BehaviorExtension:hp,BehaviorModel:bt,BloomEffect:ia,BoxCollider:Ja,BoxGizmo:Kr,BoxHelperComponent:is,Button:Yn,CallInfo:qs,Camera:Pe,CameraTargetReachedEvent:zc,Canvas:Rt,CanvasGroup:Fo,CapsuleCollider:In,ChangeMaterialOnClick:ml,ChangeTransformOnClick:$r,CharacterController:zr,CharacterControllerInput:Ln,ChromaticAberration:Th,Collider:hi,ColorAdjustments:Zo,ColorBySpeedModule:ea,ColorOverLifetimeModule:Oh,ContactShadows:Os,ControlTrackHandler:Qp,CustomBranding:Ho,Deletable:Bf,DeleteBox:Yc,DepthOfField:Ts,DeviceFlag:Nu,DocumentExtension:m0,DragControls:di,DropListener:Dn,DropListenerAddedEvent:Wu,Duplicatable:Nr,EffectWrapper:Eh,EmissionModule:hn,EmphasizeOnClick:fl,EventList:ke,EventListEvent:ku,EventSystem:ts,EventTrigger:$u,FieldWithDefault:Yf,FixedJoint:N0,Fog:xl,GltfExport:ih,GltfExportBox:Zf,Gradient:qo,Graphic:Xr,GraphicRaycaster:Tu,GridHelper:Sl,GridLayoutGroup:S0,GroundProjectedEnv:Vs,GroupActionModel:Un,HideOnStart:u0,HingeJoint:bh,HorizontalLayoutGroup:x0,Image:Rl,InheritVelocityModule:Xo,InputField:la,InstanceHandle:Zc,InstancingHandler:Vr,Interactable:Df,Keyframe:Qt,LODGroup:wh,LODModel:Zr,Light:mi,LimitVelocityOverLifetimeModule:ot,LogStats:Lf,LookAt:ca,LookAtConstraint:Dr,MainModule:It,MaskableGraphic:dh,MeshCollider:Eo,MeshRenderer:th,MinMaxCurve:X,MinMaxGradient:ii,NeedleMenu:an,NestedGltf:Op,Networking:Cl,NoiseModule:xe,ObjectRaycaster:Ti,OffsetConstraint:Jr,OpenURL:El,OrbitControls:ve,Outline:vl,Padding:Do,ParticleBurst:Ch,ParticleSubEmitter:Ep,ParticleSystem:rt,ParticleSystemRenderer:os,PhysicsExtension:pp,PixelationEffect:Ah,PlayAnimationOnClick:Gr,PlayAudioOnClick:jo,PlayableDirector:sr,PlayerColor:zl,PointerEventData:Fl,PostProcessingHandler:Fp,PreliminaryAction:yl,PreliminaryTrigger:rh,RawImage:Zp,Rect:v0,RectTransform:Wt,ReflectionProbe:rl,RegisteredAnimationInfo:to,RemoteSkybox:un,Renderer:Ze,RendererLightmap:Jc,Rigidbody:ye,RotationBySpeedModule:Bi,RotationOverLifetimeModule:ns,SceneSwitcher:ut,ScreenCapture:er,ScreenSpaceAmbientOcclusion:qn,ScreenSpaceAmbientOcclusionN8:Es,SetActiveOnClick:qr,ShadowCatcher:Bh,ShapeModule:Xe,SharpeningEffect:jh,SignalAsset:Wh,SignalReceiver:Ml,SignalReceiverEvent:kl,SignalTrackHandler:qh,Size:y0,SizeBySpeedModule:si,SizeOverLifetimeModule:Go,SkinnedMeshRenderer:Kf,SmoothFollow:tr,SpatialGrabRaycaster:Ga,SpatialHtml:Gh,SpatialTrigger:Nh,SpatialTriggerReceiver:pn,SpectatorCamera:Hp,SphereCollider:Za,Sprite:rn,SpriteData:Wn,SpriteRenderer:pi,SpriteSheet:zo,SubEmitterSystem:kh,SyncedCamera:qp,SyncedRoom:As,SyncedTransform:$s,TapGestureTrigger:p0,TeleportTarget:xp,TestRunner:fy,TestSimulateUserData:yy,Text:Vt,TextBuilder:fp,TextExtension:uh,TextureSheetAnimationModule:jt,TiltShiftEffect:dn,ToneMappingEffect:Ko,TrailModule:ze,TransformData:He,TransformGizmo:ra,TriggerBuilder:_t,TriggerModel:Io,UIRaycastUtils:Eu,UIRootComponent:Bc,USDZExporter:Ge,USDZText:Lo,USDZUIExtension:yp,UsageMarker:Qc,VariantAction:h0,VelocityOverLifetimeModule:Qe,VerticalLayoutGroup:w0,VideoPlayer:pt,Vignette:oa,VisibilityAction:ah,Voip:To,Volume:Lh,VolumeParameter:N,VolumeProfile:Mh,WebARCameraBackground:Yh,WebARSessionRoot:Vn,WebXR:Je,WebXRImageTracking:ha,WebXRImageTrackingModel:fn,WebXRPlaneTracking:Zn,WebXRTrackedImage:Il,XRControllerFollow:Kn,XRControllerModel:ln,XRControllerMovement:Li,XRFlag:Ei,XRRig:tm,XRState:Kt,__Ignore:My},Symbol.toStringTag,{value:"Module"}));class vj extends A{constructor(){super(...arguments),a(this,"toggleKey","KeyP")}update(){this.context.input.isKeyDown(this.toggleKey)&&this.context.domElement.classList.toggle("presentation-mode")}}S.add("AlignmentConstraint",Tc),S.add("Animation",Ut),S.add("Keyframe",Qt),S.add("AnimationCurve",Lr),S.add("Animator",Pt),S.add("AnimatorController",Vi),S.add("AudioListener",Mo),S.add("AudioSource",We),S.add("Avatar_POI",Xs),S.add("Avatar_Brain_LookAt",Nc),S.add("Avatar_MouthShapes",Hc),S.add("Avatar_MustacheShake",kf),S.add("AvatarBlink_Simple",Fr),S.add("AvatarEyeLook_Rotation",Ya),S.add("AvatarModel",zu),S.add("AvatarLoader",Tf),S.add("AxesHelper",Ka),S.add("BasicIKConstraint",Af),S.add("BoxHelperComponent",is),S.add("Camera",Pe),S.add("CharacterController",zr),S.add("CharacterControllerInput",Ln),S.add("__Ignore",My),S.add("Collider",hi),S.add("SphereCollider",Za),S.add("BoxCollider",Ja),S.add("MeshCollider",Eo),S.add("CapsuleCollider",In),S.add("ContactShadows",Os),S.add("LogStats",Lf),S.add("DeleteBox",Yc),S.add("Deletable",Bf),S.add("DeviceFlag",Nu),S.add("DragControls",di),S.add("DropListenerAddedEvent",Wu),S.add("DropListener",Dn),S.add("Duplicatable",Nr),S.add("CallInfo",qs),S.add("EventListEvent",ku),S.add("EventList",ke),S.add("EventTrigger",$u),S.add("GltfExportBox",Zf),S.add("GltfExport",ih),S.add("RegisteredAnimationInfo",to),S.add("TransformData",He),S.add("AnimationExtension",nh),S.add("VariantAction",h0),S.add("ActionCollection",d0),S.add("AudioExtension",lr),S.add("BehaviorExtension",hp),S.add("ChangeTransformOnClick",$r),S.add("ChangeMaterialOnClick",ml),S.add("SetActiveOnClick",qr),S.add("HideOnStart",u0),S.add("EmphasizeOnClick",fl),S.add("PlayAudioOnClick",jo),S.add("PlayAnimationOnClick",Gr),S.add("PreliminaryAction",yl),S.add("PreliminaryTrigger",rh),S.add("VisibilityAction",ah),S.add("TapGestureTrigger",p0),S.add("BehaviorModel",bt),S.add("TriggerModel",Io),S.add("TriggerBuilder",_t),S.add("GroupActionModel",Un),S.add("ActionModel",Ai),S.add("ActionBuilder",ue),S.add("PhysicsExtension",pp),S.add("DocumentExtension",m0),S.add("USDZText",Lo),S.add("TextBuilder",fp),S.add("TextExtension",uh),S.add("USDZUIExtension",yp),S.add("CustomBranding",Ho),S.add("USDZExporter",Ge),S.add("Fog",xl),S.add("BoxGizmo",Kr),S.add("GridHelper",Sl),S.add("GroundProjectedEnv",Vs),S.add("UsageMarker",Qc),S.add("Interactable",Df),S.add("FixedJoint",N0),S.add("HingeJoint",bh),S.add("Light",mi),S.add("LODModel",Zr),S.add("LODGroup",wh),S.add("LookAtConstraint",Dr),S.add("NeedleMenu",an),S.add("NestedGltf",Op),S.add("Networking",Cl),S.add("OffsetConstraint",Jr),S.add("CameraTargetReachedEvent",zc),S.add("OrbitControls",ve),S.add("ParticleSystemRenderer",os),S.add("ParticleSystem",rt),S.add("SubEmitterSystem",kh),S.add("Gradient",qo),S.add("MinMaxCurve",X),S.add("MinMaxGradient",ii),S.add("MainModule",It),S.add("ParticleBurst",Ch),S.add("EmissionModule",hn),S.add("ColorOverLifetimeModule",Oh),S.add("SizeOverLifetimeModule",Go),S.add("ShapeModule",Xe),S.add("NoiseModule",xe),S.add("TrailModule",ze),S.add("VelocityOverLifetimeModule",Qe),S.add("TextureSheetAnimationModule",jt),S.add("RotationOverLifetimeModule",ns),S.add("RotationBySpeedModule",Bi),S.add("LimitVelocityOverLifetimeModule",ot),S.add("InheritVelocityModule",Xo),S.add("SizeBySpeedModule",si),S.add("ColorBySpeedModule",ea),S.add("ParticleSubEmitter",Ep),S.add("PlayerColor",zl),S.add("Antialiasing",Rh),S.add("BloomEffect",ia),S.add("ChromaticAberration",Th),S.add("ColorAdjustments",Zo),S.add("DepthOfField",Ts),S.add("EffectWrapper",Eh),S.add("PixelationEffect",Ah),S.add("ScreenSpaceAmbientOcclusion",qn),S.add("ScreenSpaceAmbientOcclusionN8",Es),S.add("SharpeningEffect",jh),S.add("TiltShiftEffect",dn),S.add("ToneMappingEffect",Ko),S.add("Vignette",oa),S.add("PostProcessingHandler",Fp),S.add("Volume",Lh),S.add("VolumeParameter",N),S.add("VolumeProfile",Mh),S.add("ReflectionProbe",rl),S.add("FieldWithDefault",Yf),S.add("Renderer",Ze),S.add("MeshRenderer",th),S.add("SkinnedMeshRenderer",Kf),S.add("InstancingHandler",Vr),S.add("InstanceHandle",Zc),S.add("RendererLightmap",Jc),S.add("Rigidbody",ye),S.add("SceneSwitcher",ut),S.add("ScreenCapture",er),S.add("ShadowCatcher",Bh),S.add("RemoteSkybox",un),S.add("SmoothFollow",tr),S.add("SpatialTriggerReceiver",pn),S.add("SpatialTrigger",Nh),S.add("SpectatorCamera",Hp),S.add("Sprite",rn),S.add("SpriteSheet",zo),S.add("SpriteData",Wn),S.add("SpriteRenderer",pi),S.add("SyncedCamera",qp),S.add("SyncedRoom",As),S.add("SyncedTransform",$s),S.add("TestRunner",fy),S.add("TestSimulateUserData",yy),S.add("PlayableDirector",sr),S.add("SignalAsset",Wh),S.add("SignalReceiverEvent",kl),S.add("SignalReceiver",Ml),S.add("AnimationTrackHandler",Xp),S.add("AudioTrackHandler",$h),S.add("SignalTrackHandler",qh),S.add("ControlTrackHandler",Qp),S.add("TransformGizmo",ra),S.add("BaseUIComponent",ls),S.add("UIRootComponent",Bc),S.add("Button",Yn),S.add("Canvas",Rt),S.add("CanvasGroup",Fo),S.add("EventSystem",ts),S.add("Graphic",Xr),S.add("MaskableGraphic",dh),S.add("Image",Rl),S.add("RawImage",Zp),S.add("InputField",la),S.add("Padding",Do),S.add("VerticalLayoutGroup",w0),S.add("HorizontalLayoutGroup",x0),S.add("GridLayoutGroup",S0),S.add("Outline",vl),S.add("PointerEventData",Fl),S.add("ObjectRaycaster",Ti),S.add("GraphicRaycaster",Tu),S.add("SpatialGrabRaycaster",Ga),S.add("UIRaycastUtils",Eu),S.add("Size",y0),S.add("Rect",v0),S.add("RectTransform",Wt),S.add("SpatialHtml",Gh),S.add("Text",Vt),S.add("LookAt",ca),S.add("OpenURL",El),S.add("VideoPlayer",pt),S.add("Voip",To),S.add("Avatar",No),S.add("XRControllerFollow",Kn),S.add("XRControllerModel",ln),S.add("XRControllerMovement",Li),S.add("TeleportTarget",xp),S.add("WebARCameraBackground",Yh),S.add("WebARSessionRoot",Vn),S.add("WebXR",Je),S.add("AvatarMarker",Mt),S.add("WebXRTrackedImage",Il),S.add("WebXRImageTrackingModel",fn),S.add("WebXRImageTracking",ha),S.add("WebXRPlaneTracking",Zn),S.add("XRRig",tm),S.add("XRState",Kt),S.add("XRFlag",Ei),S.add("PlayerSync",bl),S.add("PlayerState",ji),S.add("PresentationMode",vj);const Zh=ft,bj=O("debugtypestore");bj&&console.log(S);function _j(s,t){const i=b_(s,t);return i!==void 0?i:null}const wj=new Rk,Ry=Symbol("deserialize-queue");async function xj(s,t,i,n=null,o){if(!i){console.debug("Can not create component instances: gltf is null");return}let r=n;typeof r=="number"&&(r=new Bt(n));const l=t.indexOf("?");t=l===-1?t:t.substring(0,l);const c=new Vg(i.scene);c.gltfId=t,c.context=s,c.gltf=i,c.nodeToObject=o?.nodeToObjectMap,c.implementationInformation=wj;let h=s[Ry];if(h||(h=s[Ry]=[]),i.scenes)for(const d of i.scenes)await Ay(c,d,h);if(i.children)for(const d of i.children)await Ay(c,d,h);s.new_scripts_pre_setup_callbacks.push(()=>{const d=s[Ry];if(d){for(const u of d)Sj(u,c);d.length=0}if(r){const u={},p=[];Ey(i,r,u,p);for(const g of i.scenes)Ey(g,r,u,p);for(const g of p)g.resolveGuids(u)}})}const Ty=Symbol("original-component-name"),Ll=new Map;function Ey(s,t,i,n){if(t===null||!s)return;const o=s.guid,r=s.guid;r!=null&&r.length&&(Ll.has(r)||(Zh&&console.log('Creating InstanceIdProvider with key "'+r+'" for object '+s.name),Ll.set(r,new Bt(r))));const l=r&&Ll.get(r)||t;if(s.guid=l.generateUUID(),o&&o!=="invalid"&&(i[o]=s.guid),s&&s.userData&&s.userData.components)for(const c of s.userData.components){if(c===null)continue;const h=c.guid;h?Ll.has(h)||(Zh&&console.log('Creating InstanceIdProvider with key "'+h+'" for component '+c[Ty]),Ll.set(h,new Bt(h))):Zh&&console.warn("Can not create IdProvider: component "+c[Ty]+" has no guid",c.guid);const d=Ll.get(h)||t,u=c.guid;c.guid=d.generateUUID(),u&&u!=="invalid"&&(i[u]=c.guid),c.resolveGuids&&n.push(c)}if(s.children)for(const c of s.children)Ey(c,t,i,n)}const Jh=[];async function Ay(s,t,i,n){var o,r,l,c,h;if(!t)return;const d=t.userData;if(d){const u=d.builtin_components;if(u&&u.length>0)for(const p of u)try{if(p===null)continue;const g=S.get(p.name);if(g!=null){const y=new g;y.sourceId=s.gltfId,La(y,p,s.implementationInformation),y.context=s.context,"guid"in p&&(y[rc]=p.guid),y[Ty]=p.name,Cr(t,y,!1),i.push({instance:y,compData:p,obj:t}),y.isCamera&&s.context&&s.context.mainCamera===null&&y.tag==="MainCamera"&&s.context.setCurrentCamera(y),((l=(r=(o=s.context)==null?void 0:o.physics)==null?void 0:r.engine)==null?void 0:l.isInitialized)===!1&&(y.isCollider||y.isRigidbody)&&((h=(c=s.context)==null?void 0:c.physics.engine)==null||h.initialize())}else Zh&&console.debug("unknown component: "+p.name),Jh.includes(p.name)||Jh.push(p.name)}catch(g){console.error(p.name+" - "+g.message,g)}if(Jh.length>0){const p=Jh.join(", ");console.warn("unknown components: "+p),Jh.length=0,Gt()&&Le(`<strong>Unknown components in scene</strong>:
1360
+ `+d.xrData.lastChangedTime.toFixed(2),.02))}}removeData(t,i){const n=i.get(t);if(!n)return;i.delete(t),da&&console.log("Plane no longer tracked, id="+n.id),n.mesh&&(n.mesh.removeFromParent(),n.mesh.traverse(r=>{const l=r.userData.normalsHelper;l?(l.dispose(),l.removeFromParent()):da&&console.warn("No normals helper found for mesh",n.mesh)}),Mi(n.mesh,!0,!0));const o=new CustomEvent("plane-tracking",{detail:{type:"plane-removed",context:n}});this.dispatchEvent(o)}processFrameData(t,i,n,o,r){const l=this.context.renderer.xr.getReferenceSpace();if(l){for(const c of r.keys())o.has(c)||this.removeData(c,r);for(const c of o){const h="planeSpace"in c?c.planeSpace:"meshSpace"in c?c.meshSpace:void 0;if(!h)continue;const d=n.getPose(h,l);let u;if(r.has(c)){const p=r.get(c);if(u=p.mesh,p.timestamp<c.lastChangedTime){if(p.timestamp=c.lastChangedTime,p.mesh){const y=this.createGeometry(c);if(p.mesh instanceof Q)p.mesh.geometry.dispose(),p.mesh.geometry=y,this.makeOccluder(p.mesh,p.mesh.material);else if(p.mesh instanceof ro)for(const f of p.mesh.children)f instanceof Q&&(f.geometry.dispose(),f.geometry=y,this.makeOccluder(f,f.material));if(p.collider){const f=p.mesh;p.collider.sharedMesh=f,p.collider.convex=this.checkIfContextShouldBeConvex(f,p.xrData),p.collider.onDisable(),p.collider.onEnable()}da&&(console.log("Plane updated, id="+p.id,p),p.mesh.traverse(f=>{if(!(f instanceof Q))return;const v=f.userData.normalsHelper;v&&v.update()}))}const g=new CustomEvent("plane-tracking",{detail:{type:"plane-updated",context:p}});this.dispatchEvent(g)}}else{if(!this.dataTemplate){const p=new Q;da?p.material=new SC:this.occluder?(p.material=new Me,this.makeOccluder(p,p.material,!0)):p.material=new Me({wireframe:!0,opacity:.5,transparent:!0,color:3355443}),this.dataTemplate=new le("","",p)}if(!this.dataTemplate.asset)this.dataTemplate.loadAssetAsync();else{const p=P.instantiate(this.dataTemplate.asset);if(p.name="xr-tracked-plane",u=p,Ym(p,!1),p instanceof Q)Te(p.geometry),p.geometry=this.createGeometry(c),this.makeOccluder(p,p.material,this.occluder);else if(p instanceof ro)for(const f of p.children)f instanceof Q&&(Te(f.geometry),f.geometry=this.createGeometry(c),this.makeOccluder(f,f.material,this.occluder));const g=p.getComponent(Eo);if(g){const f=p;g.sharedMesh=f,g.convex=this.checkIfContextShouldBeConvex(f,c),g.onDisable(),g.onEnable()}p.matrixAutoUpdate=!1,p.matrixWorldNeedsUpdate=!0,i.add(p);const y={id:this._dataId++,xrData:c,timestamp:c.lastChangedTime,mesh:p,collider:g};r.set(c,y),da&&console.log("New plane detected, id="+y.id,y,{hasCollider:!!g,isGroup:p instanceof ro});try{const f=new CustomEvent("plane-tracking",{detail:{type:"plane-added",context:y}});this.dispatchEvent(f)}catch(f){console.error(f)}}}u&&(d?(u.visible=!0,u.matrix.fromArray(d.transform.matrix),u.matrix.premultiply(this._flipForwardMatrix)):u.visible=!1,da&&u.traverse(p=>{if(p instanceof Q)if(p.userData.normalsHelper)p.userData.normalsHelper.update();else{const g=new GC(p,.05,255);g.layers.disableAll(),g.layers.set(2),this.context.scene.add(g),p.userData.normalsHelper=g}}))}}}checkIfContextShouldBeConvex(t,i){if(!t)return!0;if(t){const n=new vi;n.expandByObject(t);const o=new x;n.getSize(o);let r=!0;return o.x>2&&o.y>2&&o.z>1.5&&(r=!1),r&&"semanticLabel"in i&&i.semanticLabel==="wall"&&(r=!0),r}return!0}createGeometry(t){return"polygon"in t?this.createPlaneGeometry(t.polygon):"vertices"in t&&"indices"in t?this.createMeshGeometry(t.vertices,t.indices):new oo}createMeshGeometry(t,i){const n=t.toString()+"_"+i.toString();if(this._verticesCache.has(n))return this._verticesCache.get(n);const o=new oo;o.setIndex(new mt(i,1)),o.setAttribute("position",new mt(t,3));const r=Array();for(let l=0;l<t.length;l+=3)r.push(t[l],t[l+2]);return o.setAttribute("uv",new mt(t,3)),o.computeVertexNormals(),this._verticesCache.set(n,o),o}createPlaneGeometry(t){const i=new oo,n=[],o=[];t.forEach(g=>{n.push(g.x,g.y,g.z),o.push(g.x,g.z)});const r=new x(n[0],n[1],n[2]),l=new x(n[3],n[4],n[5]),c=new x(n[6],n[7],n[8]),h=new x,d=new x;h.subVectors(l,r),d.subVectors(c,r),h.cross(d),h.normalize();const u=[];for(let g=0;g<n.length/3;g++)u.push(h.x,h.y,h.z);const p=[];for(let g=2;g<t.length;++g)p.push(0,g-1,g);return i.setAttribute("position",new mt(new Float32Array(n),3)),i.setAttribute("uv",new mt(new Float32Array(o),2)),i.setAttribute("normal",new mt(new Float32Array(u),3)),i.setIndex(p),i.computeBoundingBox(),i.computeBoundingSphere(),i}}jl([m(le)],Zn.prototype,"dataTemplate",2),jl([m()],Zn.prototype,"occluder",2),jl([m()],Zn.prototype,"initiateRoomCaptureIfNoData",2),jl([m()],Zn.prototype,"usePlaneData",2),jl([m()],Zn.prototype,"useMeshData",2),jl([m()],Zn.prototype,"runInVR",2);var mj=Object.defineProperty,gj=Object.getOwnPropertyDescriptor,fj=(s,t,i,n)=>{for(var o=n>1?void 0:n?gj(t,i):t,r=s.length-1,l;r>=0;r--)(l=s[r])&&(o=(n?l(t,i,o):l(o))||o);return n&&o&&mj(t,i,o),o};const z1=O("debugwebxr");class tm extends A{constructor(){super(...arguments),a(this,"priority",0),a(this,"_startScale")}get isActive(){return this.activeAndEnabled&&this.gameObject.visible}setAsActiveXRRig(){var t;(t=Z.active)==null||t.setRigActive(this)}setPriority(t){this.priority=t}awake(){if(z1){const t=new j;t.position.y+=.5,this.gameObject.add(t);const i=t.addNewComponent(Kr);i&&(i.isGizmo=!1);const n=new bi(.5);this.gameObject.add(n)}}isXRRig(){return!0}supportsXR(t){return!0}onEnterXR(t){this._startScale=this.gameObject.scale.clone(),t.xr.addRig(this),z1&&console.log("WebXR: add Rig",this.name,this.priority)}onLeaveXR(t){t.xr.removeRig(this),this._startScale&&this.gameObject&&this.gameObject.scale.copy(this._startScale)}}fj([m()],tm.prototype,"priority",2);class My{}const yj=Object.freeze(Object.defineProperty({__proto__:null,ActionBuilder:ue,ActionCollection:d0,ActionModel:Ai,AlignmentConstraint:Tc,Animation:Ut,AnimationCurve:Lr,AnimationExtension:nh,AnimationTrackHandler:Xp,Animator:Pt,AnimatorController:Vi,Antialiasing:Rh,AudioExtension:lr,AudioListener:Mo,AudioSource:We,AudioTrackHandler:$h,Avatar:No,AvatarBlink_Simple:Fr,AvatarEyeLook_Rotation:Ya,AvatarLoader:Tf,AvatarMarker:Mt,AvatarModel:zu,Avatar_Brain_LookAt:Nc,Avatar_MouthShapes:Hc,Avatar_MustacheShake:kf,Avatar_POI:Xs,AxesHelper:Ka,BaseUIComponent:ls,BasicIKConstraint:Af,BehaviorExtension:hp,BehaviorModel:bt,BloomEffect:ia,BoxCollider:Ja,BoxGizmo:Kr,BoxHelperComponent:is,Button:Yn,CallInfo:qs,Camera:Pe,CameraTargetReachedEvent:zc,Canvas:Rt,CanvasGroup:Fo,CapsuleCollider:In,ChangeMaterialOnClick:ml,ChangeTransformOnClick:$r,CharacterController:zr,CharacterControllerInput:Ln,ChromaticAberration:Th,Collider:hi,ColorAdjustments:Zo,ColorBySpeedModule:ea,ColorOverLifetimeModule:Oh,ContactShadows:Os,ControlTrackHandler:Qp,CustomBranding:Ho,Deletable:Bf,DeleteBox:Yc,DepthOfField:Ts,DeviceFlag:Nu,DocumentExtension:m0,DragControls:di,DropListener:Dn,DropListenerAddedEvent:Wu,Duplicatable:Nr,EffectWrapper:Eh,EmissionModule:hn,EmphasizeOnClick:fl,EventList:ke,EventListEvent:ku,EventSystem:ts,EventTrigger:$u,FieldWithDefault:Yf,FixedJoint:N0,Fog:xl,GltfExport:ih,GltfExportBox:Zf,Gradient:qo,Graphic:Xr,GraphicRaycaster:Tu,GridHelper:Sl,GridLayoutGroup:S0,GroundProjectedEnv:Vs,GroupActionModel:Un,HideOnStart:u0,HingeJoint:bh,HorizontalLayoutGroup:x0,Image:Rl,InheritVelocityModule:Xo,InputField:la,InstanceHandle:Zc,InstancingHandler:Vr,Interactable:Df,Keyframe:Qt,LODGroup:wh,LODModel:Zr,Light:mi,LimitVelocityOverLifetimeModule:ot,LogStats:Lf,LookAt:ca,LookAtConstraint:Dr,MainModule:It,MaskableGraphic:dh,MeshCollider:Eo,MeshRenderer:th,MinMaxCurve:X,MinMaxGradient:ii,NeedleMenu:an,NestedGltf:Op,Networking:Cl,NoiseModule:xe,ObjectRaycaster:Ti,OffsetConstraint:Jr,OpenURL:El,OrbitControls:ve,Outline:vl,Padding:Do,ParticleBurst:Ch,ParticleSubEmitter:Ep,ParticleSystem:rt,ParticleSystemRenderer:os,PhysicsExtension:pp,PixelationEffect:Ah,PlayAnimationOnClick:Gr,PlayAudioOnClick:jo,PlayableDirector:sr,PlayerColor:zl,PointerEventData:Fl,PostProcessingHandler:Fp,PreliminaryAction:yl,PreliminaryTrigger:rh,RawImage:Zp,Rect:v0,RectTransform:Wt,ReflectionProbe:rl,RegisteredAnimationInfo:to,RemoteSkybox:un,Renderer:Ze,RendererLightmap:Jc,Rigidbody:ye,RotationBySpeedModule:Bi,RotationOverLifetimeModule:ns,SceneSwitcher:ut,ScreenCapture:er,ScreenSpaceAmbientOcclusion:qn,ScreenSpaceAmbientOcclusionN8:Es,SetActiveOnClick:qr,ShadowCatcher:Bh,ShapeModule:Xe,SharpeningEffect:jh,SignalAsset:Wh,SignalReceiver:Ml,SignalReceiverEvent:kl,SignalTrackHandler:qh,Size:y0,SizeBySpeedModule:si,SizeOverLifetimeModule:Go,SkinnedMeshRenderer:Kf,SmoothFollow:tr,SpatialGrabRaycaster:Ga,SpatialHtml:Gh,SpatialTrigger:Nh,SpatialTriggerReceiver:pn,SpectatorCamera:Hp,SphereCollider:Za,Sprite:rn,SpriteData:Wn,SpriteRenderer:pi,SpriteSheet:zo,SubEmitterSystem:kh,SyncedCamera:qp,SyncedRoom:As,SyncedTransform:$s,TapGestureTrigger:p0,TeleportTarget:xp,TestRunner:fy,TestSimulateUserData:yy,Text:Vt,TextBuilder:fp,TextExtension:uh,TextureSheetAnimationModule:jt,TiltShiftEffect:dn,ToneMappingEffect:Ko,TrailModule:ze,TransformData:He,TransformGizmo:ra,TriggerBuilder:_t,TriggerModel:Io,UIRaycastUtils:Eu,UIRootComponent:Bc,USDZExporter:Ge,USDZText:Lo,USDZUIExtension:yp,UsageMarker:Qc,VariantAction:h0,VelocityOverLifetimeModule:Qe,VerticalLayoutGroup:w0,VideoPlayer:pt,Vignette:oa,VisibilityAction:ah,Voip:To,Volume:Lh,VolumeParameter:N,VolumeProfile:Mh,WebARCameraBackground:Yh,WebARSessionRoot:Vn,WebXR:Je,WebXRImageTracking:ha,WebXRImageTrackingModel:fn,WebXRPlaneTracking:Zn,WebXRTrackedImage:Il,XRControllerFollow:Kn,XRControllerModel:ln,XRControllerMovement:Li,XRFlag:Ei,XRRig:tm,XRState:Kt,__Ignore:My},Symbol.toStringTag,{value:"Module"}));class vj extends A{constructor(){super(...arguments),a(this,"toggleKey","KeyP")}update(){this.context.input.isKeyDown(this.toggleKey)&&this.context.domElement.classList.toggle("presentation-mode")}}S.add("AlignmentConstraint",Tc),S.add("Animation",Ut),S.add("Keyframe",Qt),S.add("AnimationCurve",Lr),S.add("Animator",Pt),S.add("AnimatorController",Vi),S.add("AudioListener",Mo),S.add("AudioSource",We),S.add("Avatar_POI",Xs),S.add("Avatar_Brain_LookAt",Nc),S.add("Avatar_MouthShapes",Hc),S.add("Avatar_MustacheShake",kf),S.add("AvatarBlink_Simple",Fr),S.add("AvatarEyeLook_Rotation",Ya),S.add("AvatarModel",zu),S.add("AvatarLoader",Tf),S.add("AxesHelper",Ka),S.add("BasicIKConstraint",Af),S.add("BoxHelperComponent",is),S.add("Camera",Pe),S.add("CharacterController",zr),S.add("CharacterControllerInput",Ln),S.add("__Ignore",My),S.add("Collider",hi),S.add("SphereCollider",Za),S.add("BoxCollider",Ja),S.add("MeshCollider",Eo),S.add("CapsuleCollider",In),S.add("ContactShadows",Os),S.add("LogStats",Lf),S.add("DeleteBox",Yc),S.add("Deletable",Bf),S.add("DeviceFlag",Nu),S.add("DragControls",di),S.add("DropListenerAddedEvent",Wu),S.add("DropListener",Dn),S.add("Duplicatable",Nr),S.add("CallInfo",qs),S.add("EventListEvent",ku),S.add("EventList",ke),S.add("EventTrigger",$u),S.add("GltfExportBox",Zf),S.add("GltfExport",ih),S.add("RegisteredAnimationInfo",to),S.add("TransformData",He),S.add("AnimationExtension",nh),S.add("VariantAction",h0),S.add("ActionCollection",d0),S.add("AudioExtension",lr),S.add("BehaviorExtension",hp),S.add("ChangeTransformOnClick",$r),S.add("ChangeMaterialOnClick",ml),S.add("SetActiveOnClick",qr),S.add("HideOnStart",u0),S.add("EmphasizeOnClick",fl),S.add("PlayAudioOnClick",jo),S.add("PlayAnimationOnClick",Gr),S.add("PreliminaryAction",yl),S.add("PreliminaryTrigger",rh),S.add("VisibilityAction",ah),S.add("TapGestureTrigger",p0),S.add("BehaviorModel",bt),S.add("TriggerModel",Io),S.add("TriggerBuilder",_t),S.add("GroupActionModel",Un),S.add("ActionModel",Ai),S.add("ActionBuilder",ue),S.add("PhysicsExtension",pp),S.add("DocumentExtension",m0),S.add("USDZText",Lo),S.add("TextBuilder",fp),S.add("TextExtension",uh),S.add("USDZUIExtension",yp),S.add("CustomBranding",Ho),S.add("USDZExporter",Ge),S.add("Fog",xl),S.add("BoxGizmo",Kr),S.add("GridHelper",Sl),S.add("GroundProjectedEnv",Vs),S.add("UsageMarker",Qc),S.add("Interactable",Df),S.add("FixedJoint",N0),S.add("HingeJoint",bh),S.add("Light",mi),S.add("LODModel",Zr),S.add("LODGroup",wh),S.add("LookAtConstraint",Dr),S.add("NeedleMenu",an),S.add("NestedGltf",Op),S.add("Networking",Cl),S.add("OffsetConstraint",Jr),S.add("CameraTargetReachedEvent",zc),S.add("OrbitControls",ve),S.add("ParticleSystemRenderer",os),S.add("ParticleSystem",rt),S.add("SubEmitterSystem",kh),S.add("Gradient",qo),S.add("MinMaxCurve",X),S.add("MinMaxGradient",ii),S.add("MainModule",It),S.add("ParticleBurst",Ch),S.add("EmissionModule",hn),S.add("ColorOverLifetimeModule",Oh),S.add("SizeOverLifetimeModule",Go),S.add("ShapeModule",Xe),S.add("NoiseModule",xe),S.add("TrailModule",ze),S.add("VelocityOverLifetimeModule",Qe),S.add("TextureSheetAnimationModule",jt),S.add("RotationOverLifetimeModule",ns),S.add("RotationBySpeedModule",Bi),S.add("LimitVelocityOverLifetimeModule",ot),S.add("InheritVelocityModule",Xo),S.add("SizeBySpeedModule",si),S.add("ColorBySpeedModule",ea),S.add("ParticleSubEmitter",Ep),S.add("PlayerColor",zl),S.add("Antialiasing",Rh),S.add("BloomEffect",ia),S.add("ChromaticAberration",Th),S.add("ColorAdjustments",Zo),S.add("DepthOfField",Ts),S.add("EffectWrapper",Eh),S.add("PixelationEffect",Ah),S.add("ScreenSpaceAmbientOcclusion",qn),S.add("ScreenSpaceAmbientOcclusionN8",Es),S.add("SharpeningEffect",jh),S.add("TiltShiftEffect",dn),S.add("ToneMappingEffect",Ko),S.add("Vignette",oa),S.add("PostProcessingHandler",Fp),S.add("Volume",Lh),S.add("VolumeParameter",N),S.add("VolumeProfile",Mh),S.add("ReflectionProbe",rl),S.add("FieldWithDefault",Yf),S.add("Renderer",Ze),S.add("MeshRenderer",th),S.add("SkinnedMeshRenderer",Kf),S.add("InstancingHandler",Vr),S.add("InstanceHandle",Zc),S.add("RendererLightmap",Jc),S.add("Rigidbody",ye),S.add("SceneSwitcher",ut),S.add("ScreenCapture",er),S.add("ShadowCatcher",Bh),S.add("RemoteSkybox",un),S.add("SmoothFollow",tr),S.add("SpatialTriggerReceiver",pn),S.add("SpatialTrigger",Nh),S.add("SpectatorCamera",Hp),S.add("Sprite",rn),S.add("SpriteSheet",zo),S.add("SpriteData",Wn),S.add("SpriteRenderer",pi),S.add("SyncedCamera",qp),S.add("SyncedRoom",As),S.add("SyncedTransform",$s),S.add("TestRunner",fy),S.add("TestSimulateUserData",yy),S.add("PlayableDirector",sr),S.add("SignalAsset",Wh),S.add("SignalReceiverEvent",kl),S.add("SignalReceiver",Ml),S.add("AnimationTrackHandler",Xp),S.add("AudioTrackHandler",$h),S.add("SignalTrackHandler",qh),S.add("ControlTrackHandler",Qp),S.add("TransformGizmo",ra),S.add("BaseUIComponent",ls),S.add("UIRootComponent",Bc),S.add("Button",Yn),S.add("Canvas",Rt),S.add("CanvasGroup",Fo),S.add("EventSystem",ts),S.add("Graphic",Xr),S.add("MaskableGraphic",dh),S.add("Image",Rl),S.add("RawImage",Zp),S.add("InputField",la),S.add("Padding",Do),S.add("VerticalLayoutGroup",w0),S.add("HorizontalLayoutGroup",x0),S.add("GridLayoutGroup",S0),S.add("Outline",vl),S.add("PointerEventData",Fl),S.add("ObjectRaycaster",Ti),S.add("GraphicRaycaster",Tu),S.add("SpatialGrabRaycaster",Ga),S.add("UIRaycastUtils",Eu),S.add("Size",y0),S.add("Rect",v0),S.add("RectTransform",Wt),S.add("SpatialHtml",Gh),S.add("Text",Vt),S.add("LookAt",ca),S.add("OpenURL",El),S.add("VideoPlayer",pt),S.add("Voip",To),S.add("Avatar",No),S.add("XRControllerFollow",Kn),S.add("XRControllerModel",ln),S.add("XRControllerMovement",Li),S.add("TeleportTarget",xp),S.add("WebARCameraBackground",Yh),S.add("WebARSessionRoot",Vn),S.add("WebXR",Je),S.add("AvatarMarker",Mt),S.add("WebXRTrackedImage",Il),S.add("WebXRImageTrackingModel",fn),S.add("WebXRImageTracking",ha),S.add("WebXRPlaneTracking",Zn),S.add("XRRig",tm),S.add("XRState",Kt),S.add("XRFlag",Ei),S.add("PlayerSync",bl),S.add("PlayerState",ji),S.add("PresentationMode",vj);const Zh=ft,bj=O("debugtypestore");bj&&console.log(S);function _j(s,t){const i=b_(s,t);return i!==void 0?i:null}const wj=new R2,Ry=Symbol("deserialize-queue");async function xj(s,t,i,n=null,o){if(!i){console.debug("Can not create component instances: gltf is null");return}let r=n;typeof r=="number"&&(r=new Bt(n));const l=t.indexOf("?");t=l===-1?t:t.substring(0,l);const c=new Vg(i.scene);c.gltfId=t,c.context=s,c.gltf=i,c.nodeToObject=o?.nodeToObjectMap,c.implementationInformation=wj;let h=s[Ry];if(h||(h=s[Ry]=[]),i.scenes)for(const d of i.scenes)await Ay(c,d,h);if(i.children)for(const d of i.children)await Ay(c,d,h);s.new_scripts_pre_setup_callbacks.push(()=>{const d=s[Ry];if(d){for(const u of d)Sj(u,c);d.length=0}if(r){const u={},p=[];Ey(i,r,u,p);for(const g of i.scenes)Ey(g,r,u,p);for(const g of p)g.resolveGuids(u)}})}const Ty=Symbol("original-component-name"),Ll=new Map;function Ey(s,t,i,n){if(t===null||!s)return;const o=s.guid,r=s.guid;r!=null&&r.length&&(Ll.has(r)||(Zh&&console.log('Creating InstanceIdProvider with key "'+r+'" for object '+s.name),Ll.set(r,new Bt(r))));const l=r&&Ll.get(r)||t;if(s.guid=l.generateUUID(),o&&o!=="invalid"&&(i[o]=s.guid),s&&s.userData&&s.userData.components)for(const c of s.userData.components){if(c===null)continue;const h=c.guid;h?Ll.has(h)||(Zh&&console.log('Creating InstanceIdProvider with key "'+h+'" for component '+c[Ty]),Ll.set(h,new Bt(h))):Zh&&console.warn("Can not create IdProvider: component "+c[Ty]+" has no guid",c.guid);const d=Ll.get(h)||t,u=c.guid;c.guid=d.generateUUID(),u&&u!=="invalid"&&(i[u]=c.guid),c.resolveGuids&&n.push(c)}if(s.children)for(const c of s.children)Ey(c,t,i,n)}const Jh=[];async function Ay(s,t,i,n){var o,r,l,c,h;if(!t)return;const d=t.userData;if(d){const u=d.builtin_components;if(u&&u.length>0)for(const p of u)try{if(p===null)continue;const g=S.get(p.name);if(g!=null){const y=new g;y.sourceId=s.gltfId,La(y,p,s.implementationInformation),y.context=s.context,"guid"in p&&(y[rc]=p.guid),y[Ty]=p.name,Cr(t,y,!1),i.push({instance:y,compData:p,obj:t}),y.isCamera&&s.context&&s.context.mainCamera===null&&y.tag==="MainCamera"&&s.context.setCurrentCamera(y),((l=(r=(o=s.context)==null?void 0:o.physics)==null?void 0:r.engine)==null?void 0:l.isInitialized)===!1&&(y.isCollider||y.isRigidbody)&&((h=(c=s.context)==null?void 0:c.physics.engine)==null||h.initialize())}else Zh&&console.debug("unknown component: "+p.name),Jh.includes(p.name)||Jh.push(p.name)}catch(g){console.error(p.name+" - "+g.message,g)}if(Jh.length>0){const p=Jh.join(", ");console.warn("unknown components: "+p),Jh.length=0,Gt()&&Le(`<strong>Unknown components in scene</strong>:
1361
1361
 
1362
1362
  ${p}
1363
1363
 
@@ -1366,8 +1366,8 @@ This could mean you forgot to add a npmdef to your ExportInfo
1366
1366
  `,'"'+new TextDecoder().decode(s)+`"
1367
1367
  `,i),i[0]==103&&i[1]==108&&i[2]==84&&i[3]==70)return console.debug("GLTF detected"),"glb";if(i[0]==80&&i[1]==75&&i[2]==3&&i[3]==4)return console.debug("USDZ detected"),"usdz";if(i[0]==80&&i[1]==88&&i[2]==82&&i[3]==45&&i[4]==85&&i[5]==83&&i[6]==68&&i[7]==67)return console.debug("Binary USD detected"),"usd";if(i[0]==35&&i[1]==117&&i[2]==115&&i[3]==100&&i[4]==97)return console.debug("ASCII USD detected"),"usda";if(i[0]==75&&i[1]==97&&i[2]==121&&i[3]==100&&i[4]==97&&i[5]==114&&i[6]==97&&i[7]==32)return console.debug("Binary FBX detected"),"fbx";if(i[0]==59&&i[1]==32&&i[2]==70&&i[3]==66&&i[4]==88&&i[5]==32)return console.debug("ASCII FBX detected"),"fbx";if(i[0]==35&&i[1]==32&&i[2]==66&&i[3]==108&&i[4]==101&&i[5]==110&&i[6]==100&&i[7]==101&&i[8]==114&&i[9]==32||i[0]==35&&i[1]==32&&i[2]==65&&i[3]==108&&i[4]==105&&i[5]==97&&i[6]==115&&i[7]==32&&i[8]==79&&i[9]==66&&i[10]==74)return console.debug("OBJ detected"),"obj";if(t.headers.has("content-type")){const n=t.headers.get("content-type");switch(console.debug("Content-Type: "+n),n){case"model/gltf+json":return"gltf";case"model/gltf-binary":return"glb";case"model/vrm":return"vrm";case"model/vnd.usdz+zip":return"usdz";case"model/vnd.usd+zip":return"usd";case"model/vnd.usda+zip":return"usda";case"model/fbx":return"fbx";case"model/obj":return"obj"}}if(i[0]==118&&i[1]==32||i[0]==102&&i[1]==32)return console.debug("OBJ detected (the file has no header and starts with vertex or face)"),"obj";if(i[0]==35&&i[1]==32&&i[2]==70&&i[3]==105&&i[4]==108&&i[5]==101&&i[6]==32&&i[7]==101&&i[8]==120&&i[9]==112&&i[10]==111&&i[11]==114&&i[12]==116&&i[13]==101&&i[14]==100&&i[15]==32&&i[16]==98&&i[17]==121&&i[18]==32&&i[19]==90&&i[20]==66&&i[21]==114&&i[22]==117&&i[23]==115&&i[24]==104)return console.debug("OBJ detected (exported by ZBrush)"),"obj";if(i[0]==109&&i[1]==116&&i[2]==108&&i[3]==108&&i[4]==105&&i[5]==98)return console.debug("OBJ detected (mtllib)"),"obj";if(F()||im){const n=new TextDecoder().decode(s.slice(0,16));console.debug('Could not determine file type from binary data: "'+n+'..."',i)}else console.debug("Could not determine file type from binary data",i);return"unknown"}class Iy{createBuiltinComponents(t,i,n,o,r){return xj(t,i,n,o,r)}writeBuiltinComponentData(t,i){return _j(t,i)}parseSync(t,i,n,o){return q1(t,i,n,o)}loadSync(t,i,n,o,r){return G1(t,i,n,o,r)}}Pm(Iy);const W1=O("printGltf")||O("printgltf"),V1=O("downloadgltf"),Cj=O("debugfileformat");var H1=(s=>(s[s.BeforeLoad=0]="BeforeLoad",s[s.AfterLoaded=1]="AfterLoaded",s[s.FinishedSetup=10]="FinishedSetup",s))(H1||{});class ua{constructor(t,i,n,o){a(this,"context"),a(this,"loader"),a(this,"path"),a(this,"gltf"),this.context=t,this.path=i,this.loader=n,this.gltf=o}}const ar={};function Oj(s,t){ar[s]=ar[s]||[],ar[s].push(t)}function Pj(s,t){if(ar[s]){const i=ar[s].indexOf(t);i>=0&&ar[s].splice(i,1)}}function Dl(s,t){if(ar[s])for(const i of ar[s])i(t)}async function $1(s,t,i,n,o){W1&&console.warn("glTF",t,i),t.includes("?")&&(t=t.split("?")[0]),await ms().createBuiltinComponents(s,t,i,n,o)}async function jy(s,t){const i=await U1(s)||"unknown";switch(Cj&&console.debug("Determined file type: "+i+" for url",s),i){case"unknown":{console.warn("Unknown file type. Assuming glTF:",s);const n=new mr;return await Yu(n,t,s),n}case"fbx":return new uv;case"obj":return new xm;case"usd":case"usda":case"usdz":return console.warn(i.toUpperCase()+" files are not supported."),null;default:console.warn("Unknown file type:",i);case"gltf":case"glb":case"vrm":{const n=new mr;return await Yu(n,t,s),n}}}async function q1(s,t,i,n){typeof i!="string"&&(console.warn("Parse gltf binary without path, this might lead to errors in resolving extensions. Please provide the source path of the gltf/glb file",i,typeof i),i=""),W1&&console.log("Parse glTF",i);const o=await jy(i,s);if(!o)return;if(o instanceof xm){typeof t!="string"&&(t=new TextDecoder().decode(t));const l=o.parse(t);return{animations:l.animations,scene:l,scenes:[l]}}if(!(o instanceof mr)){const l=o.parse(t,i);return Y1(o,l),{animations:l.animations,scene:l,scenes:[l]}}const r=Qu(o);return new Promise((l,c)=>{try{let h=i.split("?")[0].trimEnd();{const u=h.split("/");u.length>0&&u[u.length-1]!==""&&u.pop(),h=u.join("/"),h.endsWith("/")||(h+="/")}o.resourcePath=h,bu(o,s),Dl(0,new ua(s,i,o));const d=s.mainCamera;o.parse(t,"",async u=>{Xf(i,u,s),Dl(1,new ua(s,i,o,u)),await $1(s,i,u,n,r),await X1(u.scene,s,d),Dl(10,new ua(s,i,o,u)),l(u),V1&&Q1(t)},u=>{console.error('Loading asset at "'+i+`" failed
1368
1368
  `,u),l(void 0)})}catch(h){console.error(h),c(h)}})}async function G1(s,t,i,n,o){kj(t);const r=await jy(t,s);if(!r)return;if(!(r instanceof mr)){const c=await r.loadAsync(t,o);return Y1(r,c),{animations:c.animations,scene:c,scenes:[c]}}const l=Qu(r);return new Promise((c,h)=>{try{bu(r,s),Dl(0,new ua(s,t,r));const d=s.mainCamera;r.load(t,async u=>{Xf(t,u,s),Dl(1,new ua(s,t,r,u)),await $1(s,i,u,n,l),await X1(u.scene,s,d),Dl(10,new ua(s,t,r,u)),c(u),V1&&Q1(t)},u=>{o?.call(r,u)},u=>{console.error('Loading asset at "'+t+`" failed
1369
- `,u),c(void 0)})}catch(d){console.error(d),h(d)}})}async function X1(s,t,i){i||(i=t.mainCamera);try{i?await t.renderer.compileAsync(s,i,t.scene).catch(n=>{console.warn(n.message)}):mk(s,t)}catch(n){console.warn(n?.message||n)}}function kj(s){if(new URL(s,window.location.href).href.startsWith("file://")){const t=`Hi - it looks like you are trying to load a local file which will not work. You need to use a webserver to serve your files.
1370
- Please refer to the documentation on <a href="https://fwd.needle.tools/needle-engine/docs/local-server">https://docs.needle.tools</a> or ask for help in our <a href="https://discord.needle.tools">discord community</a>`;Le(t),console.warn(t)}}function Q1(s){if(typeof s=="string"){const t=document.createElement("a");t.href=s,t.download=s.split("/").pop(),t.click()}else{const t=new Blob([s],{type:"application/octet-stream"}),i=window.URL.createObjectURL(t),n=document.createElement("a");n.href=i,n.download="download.glb",n.click()}}function Y1(s,t){if(t!=null&&t.isObject3D){const i=t;(s instanceof uv||s instanceof xm)&&i.traverse(n=>{const o=n;o!=null&&o.isMesh&&Km(o,o.material)})}}Pm(Iy);const Ue=O("debugwebcomponent"),K1="needle-engine",Z1="vr",J1="desktop",Mj=[gw,Z1,J1],ed="ar-session-active",td="desktop-session-active",Rj=["public-key","version","hash","src","camera-controls","loadstart","progress","loadfinished","dracoDecoderPath","dracoDecoderType","ktx2DecoderPath","tone-mapping","tone-mapping-exposure","background-blurriness","background-color"];class Ly extends HTMLElement{constructor(){super(),a(this,"_context"),a(this,"_overlay_ar"),a(this,"_loadingProgress01",0),a(this,"_loadingView"),a(this,"_previousSrc",null),a(this,"_didFullyLoad",!1),a(this,"_loadId",0),a(this,"_abortController",null),a(this,"_lastSourceFiles",null),a(this,"_createContextPromise",null),a(this,"onXRSessionStarted",()=>{var i;const n=this.context.xrSessionMode;n==="immersive-ar"?this.onEnterAR(this.context.xrSession):n==="immersive-vr"&&this.onEnterVR(this.context.xrSession),(i=this.context.xrSession)==null||i.addEventListener("end",()=>{this.dispatchEvent(new CustomEvent("xr-session-ended",{detail:{session:this.context.xrSession,context:this._context,sessionMode:n}})),n==="immersive-ar"?this.onExitAR(this.context.xrSession):n==="immersive-vr"&&this.onExitVR(this.context.xrSession)})}),a(this,"onReady",()=>{var i;return(i=this._loadingView)==null?void 0:i.onLoadingFinished()}),a(this,"onError",()=>{var i;return(i=this._loadingView)==null?void 0:i.setMessage("Loading failed!")}),a(this,"_previouslyRegisteredMap",new Map),this._overlay_ar=new S2,this.addEventListener("ready",this.onReady),ow(),this.attachShadow({mode:"open"});const t=document.createElement("template");t.innerHTML=`<style>
1369
+ `,u),c(void 0)})}catch(d){console.error(d),h(d)}})}async function X1(s,t,i){i||(i=t.mainCamera);try{i?await t.renderer.compileAsync(s,i,t.scene).catch(n=>{console.warn(n.message)}):m2(s,t)}catch(n){console.warn(n?.message||n)}}function kj(s){if(new URL(s,window.location.href).href.startsWith("file://")){const t=`Hi - it looks like you are trying to load a local file which will not work. You need to use a webserver to serve your files.
1370
+ Please refer to the documentation on <a href="https://fwd.needle.tools/needle-engine/docs/local-server">https://docs.needle.tools</a> or ask for help in our <a href="https://discord.needle.tools">discord community</a>`;Le(t),console.warn(t)}}function Q1(s){if(typeof s=="string"){const t=document.createElement("a");t.href=s,t.download=s.split("/").pop(),t.click()}else{const t=new Blob([s],{type:"application/octet-stream"}),i=window.URL.createObjectURL(t),n=document.createElement("a");n.href=i,n.download="download.glb",n.click()}}function Y1(s,t){if(t!=null&&t.isObject3D){const i=t;(s instanceof uv||s instanceof xm)&&i.traverse(n=>{const o=n;o!=null&&o.isMesh&&Km(o,o.material)})}}Pm(Iy);const Ue=O("debugwebcomponent"),K1="needle-engine",Z1="vr",J1="desktop",Mj=[gw,Z1,J1],ed="ar-session-active",td="desktop-session-active",Rj=["public-key","version","hash","src","camera-controls","loadstart","progress","loadfinished","dracoDecoderPath","dracoDecoderType","ktx2DecoderPath","tone-mapping","tone-mapping-exposure","background-blurriness","background-color"];class Ly extends HTMLElement{constructor(){super(),a(this,"_context"),a(this,"_overlay_ar"),a(this,"_loadingProgress01",0),a(this,"_loadingView"),a(this,"_previousSrc",null),a(this,"_didFullyLoad",!1),a(this,"_loadId",0),a(this,"_abortController",null),a(this,"_lastSourceFiles",null),a(this,"_createContextPromise",null),a(this,"onXRSessionStarted",()=>{var i;const n=this.context.xrSessionMode;n==="immersive-ar"?this.onEnterAR(this.context.xrSession):n==="immersive-vr"&&this.onEnterVR(this.context.xrSession),(i=this.context.xrSession)==null||i.addEventListener("end",()=>{this.dispatchEvent(new CustomEvent("xr-session-ended",{detail:{session:this.context.xrSession,context:this._context,sessionMode:n}})),n==="immersive-ar"?this.onExitAR(this.context.xrSession):n==="immersive-vr"&&this.onExitVR(this.context.xrSession)})}),a(this,"onReady",()=>{var i;return(i=this._loadingView)==null?void 0:i.onLoadingFinished()}),a(this,"onError",()=>{var i;return(i=this._loadingView)==null?void 0:i.setMessage("Loading failed!")}),a(this,"_previouslyRegisteredMap",new Map),this._overlay_ar=new Sk,this.addEventListener("ready",this.onReady),ow(),this.attachShadow({mode:"open"});const t=document.createElement("template");t.innerHTML=`<style>
1371
1371
  @import url('https://fonts.googleapis.com/css2?family=Roboto+Flex:opsz,wght@8..144,100..1000&display=swap');
1372
1372
 
1373
1373
  :host {
@@ -1482,4 +1482,4 @@ Error:`,l),null}}updateColliderCollisionGroups(s){const t=s[ni],i=s.membership;l
1482
1482
  justify-content: center;
1483
1483
  gap: .5rem;
1484
1484
  }
1485
- `),pe(this,ma).innerHTML=pe(this,yi).innerHTML,pe(this,ma).style.cssText="display: flex; align-items: center; justify-content: center;",pe(this,yi).innerHTML=pe(this,ma).outerHTML,pe(this,pa).innerHTML=pe(this,yi).outerHTML,pe(this,pa).prepend(pe(this,ga)),uu(nf,{element:pe(this,pa)}),(t=pe(this,Bl))==null||t.disconnect(),pe(this,Bl)??Ls(this,Bl,new MutationObserver(()=>ya(this,Wy,rS).call(this))),pe(this,Bl).observe(pe(this,yi),{attributes:!0}),Uy&&console.log("Needle Button updated")},Wy=new WeakSet,rS=function(){pe(this,yi)&&(pe(this,yi).style.display==="none"?this.style.display="none":this.style.display==="none"&&(this.style.display=""))},om=new WeakMap,a(Vy,"observedAttributes",["ar","vr","quicklook"]),typeof window<"u"&&!window.customElements.get(nS)&&window.customElements.define(nS,Vy);const rm=O("debugmissingcamera");ge.registerCallback(fe.MissingCamera,s=>{var t,i,n;rm&&console.warn("Creating missing camera");const o=s.context.scene,r=new be;r.name="Default Fallback Camera",o.add(r);const l=new Pe;l.sourceId=((i=(t=s.files)==null?void 0:t[0])==null?void 0:i.src)??"unknown",(n=s.context.domElement.getAttribute("skybox-image"))!=null&&n.length||0>0||s.context.lightmaps.tryGetSkybox(l.sourceId)?l.clearFlags=Po.Skybox:l.clearFlags=Po.SolidColor,l.backgroundColor=new we(.5,.5,.5,1),l.fieldOfView=35,s.context.domElement.getAttribute("transparent")!=null&&(l.clearFlags=Po.Uninitialized),l.backgroundBlurriness=.2;const c=Cr(r,l,!0);r.position.x=0,r.position.y=1,r.position.z=2;const h=s.context.domElement;return h?.cameraControls!=!1&&aS(s.context,c),c}),ge.registerCallback(fe.ContextCreated,s=>{if(!s.context.mainCamera){rm&&console.log("Will not auto-fit because a default camera exists");return}const t=s.context.domElement;if(t?.cameraControls==!0){const i=Vv(s.context.mainCamera);if(i?.isCameraController==!0){rm&&console.log("Will not auto-fit because a camera controller exists");return}aS(s.context)}});function aS(s,t){t=t??s.mainCameraComponent;const i=t?.gameObject;if(rm&&console.log("Creating default camera controls",t?.name),i){const n=bc(i,ve);n.sourceId=t?.sourceId??"unknown";const o=s.domElement.getAttribute("auto-rotate");if(n.autoRotate=o!=null&&o!="0"&&o?.toLowerCase()!="false",n.autoRotateSpeed=.5,n.autoFit=!0,n.autoRotate&&o){const r=parseFloat(o);isNaN(r)||(n.autoRotateSpeed=r)}}else console.warn("Missing camera object, can not add orbit controls")}ge.registerCallback(fe.ContextCreated,s=>{const t=s.context.domElement.getAttribute("autoplay");if(t!==void 0&&(t===""||t==="true"||t==="1")&&s.files)for(const i of s.files)P.foreachComponent(i.file.scene,n=>{if(n.enabled!==!1){if(n instanceof Ut&&n.playAutomatically||n instanceof Pt||n instanceof sr&&n.playOnAwake===!0)return!0;if(n instanceof Ut)return n.playAutomatically=!0,!0;if(n instanceof sr)return n.playOnAwake=!0,!0}},!0)!==!0&&Na.assignAnimationsFromFile(i.file,{createAnimationComponent:(n,o)=>ki(n,Ut)})});class qj extends nO{constructor(){super(new oO),this.name="GenerateMeshBVHWorker"}runTask(t,i,n={}){return new Promise((o,r)=>{if(i.getAttribute("position").isInterleavedBufferAttribute||i.index&&i.index.isInterleavedBufferAttribute)throw new Error("GenerateMeshBVHWorker: InterleavedBufferAttribute are not supported for the geometry attributes.");t.onerror=d=>{r(new Error(`GenerateMeshBVHWorker: ${d.message}`))},t.onmessage=d=>{const{data:u}=d;if(u.error)r(new Error(u.error)),t.onmessage=null;else if(u.serialized){const{serialized:p,position:g}=u,y=rO.deserialize(p,i,{setIndex:!1}),f=Object.assign({setBoundingBox:!0},n);if(i.attributes.position.array=g,p.index)if(i.index)i.index.array=p.index;else{const v=new mt(p.index,1,!1);i.setIndex(v)}f.setBoundingBox&&(i.boundingBox=y.getBoundingBox(new vi)),n.onProgress&&n.onProgress(u.progress),o(y),t.onmessage=null}else n.onProgress&&n.onProgress(u.progress)};const l=i.index?i.index.array:null,c=i.attributes.position.array,h=[c];l&&h.push(l),t.postMessage({index:l,position:c,options:{...n,onProgress:null,includedProgressCallback:!!n.onProgress,groups:[...i.groups]}},h.map(d=>d.buffer).filter(d=>typeof SharedArrayBuffer>"u"||!(d instanceof SharedArrayBuffer)))})}}const Gj=Object.freeze(Object.defineProperty({__proto__:null,GenerateMeshBVHWorker:qj},Symbol.toStringTag,{value:"Module"}));export{kg as $,Na as A,vr as B,te as C,tg as D,rb as E,U_ as F,P as G,le as H,cs as I,iu as J,N_ as K,xi as L,B as M,Z as N,nu as O,W_ as P,ou as Q,kn as R,Xb as S,S as T,ok as U,vs as V,Yb as W,Pg as X,rk as Y,Te as Z,Jb as _,kw as a,H2 as a$,lk as a0,qg as a1,bc as a2,Cr as a3,ki as a4,R_ as a5,Or as a6,_c as a7,wc as a8,Da as a9,js as aA,Ba as aB,Sc as aC,I_ as aD,j_ as aE,Kd as aF,Gg as aG,Pr as aH,D_ as aI,Fa as aJ,Mi as aK,kr as aL,eu as aM,za as aN,ms as aO,Pm as aP,Ij as aQ,jj as aR,Lj as aS,Bj as aT,Md as aU,De as aV,Sn as aW,ac as aX,AP as aY,Ci as aZ,yb as a_,xc as aa,qd as ab,Gd as ac,A_ as ad,pc as ae,Cd as af,ig as ag,oc as ah,xn as ai,br as aj,rc as ak,u2 as al,p2 as am,Ce as an,fu as ao,fe as ap,ge as aq,H_ as ar,qk as as,$_ as at,_r as au,mo as av,Ly as aw,w2 as ax,hf as ay,uf as az,G2 as b,Iy as b$,$2 as b0,q2 as b1,X2 as b2,W as b3,bd as b4,Fm as b5,li as b6,lc as b7,Tb as b8,ie as b9,Of as bA,Uw as bB,Nw as bC,Vc as bD,od as bE,Ys as bF,bs as bG,Gt as bH,Cv as bI,Od as bJ,MP as bK,Pd as bL,Ns as bM,Sg as bN,Id as bO,vt as bP,Ou as bQ,tt as bR,qa as bS,nd as bT,vo as bU,X_ as bV,Q_ as bW,Va as bX,hu as bY,Z_ as bZ,J_ as b_,VP as ba,HP as bb,$P as bc,Eb as bd,ug as be,Ab as bf,Mr as bg,Zw as bh,dR as bi,Ao as bj,Bt as bk,a_ as bl,yc as bm,Dg as bn,l_ as bo,yk as bp,c_ as bq,Bg as br,h_ as bs,d_ as bt,p_ as bu,zP as bv,UP as bw,Pb as bx,Mb as by,Qs as bz,C2 as c,cO as c$,H1 as c0,ua as c1,Oj as c2,Pj as c3,jy as c4,q1 as c5,$d as c6,Vg as c7,b_ as c8,m as c9,Gm as cA,Xm as cB,Zl as cC,Qm as cD,Jl as cE,xd as cF,tP as cG,Zv as cH,Gi as cI,Jv as cJ,iP as cK,Ym as cL,eb as cM,Si as cN,tb as cO,ib as cP,Km as cQ,tw as cR,fx as cS,ce as cT,Bu as cU,Dw as cV,RM as cW,Bw as cX,Fw as cY,zw as cZ,Ov as c_,Ha as ca,oM as cb,aM as cc,Tw as cd,Mu as ce,dM as cf,Ew as cg,Aw as ch,Uj as ci,$a as cj,HO as ck,$O as cl,Kl as cm,$ as cn,qv as co,fs as cp,ee as cq,lt as cr,fr as cs,Se as ct,qi as cu,$m as cv,Ke as cw,Oa as cx,ZO as cy,qm as cz,yj as d,Sw as d$,hO as d0,wi as d1,$l as d2,O as d3,dO as d4,ql as d5,Rm as d6,Pv as d7,Tm as d8,uO as d9,MO as dA,RO as dB,TO as dC,Av as dD,Iv as dE,Am as dF,yd as dG,jv as dH,U1 as dI,N1 as dJ,sj as dK,Oy as dL,D1 as dM,Qh as dN,Nj as dO,Vj as dP,g_ as dQ,Gu as dR,ks as dS,LR as dT,DR as dU,Qu as dV,Yu as dW,Gf as dX,Xf as dY,I2 as dZ,Ac as d_,pO as da,Rv as db,Tv as dc,Sa as dd,Gl as de,gs as df,Xl as dg,Ev as dh,mO as di,co as dj,Jn as dk,fd as dl,Em as dm,Y as dn,fO as dp,yO as dq,vO as dr,bO as ds,_O as dt,wO as du,xO as dv,SO as dw,CO as dx,OO as dy,PO as dz,zm as e,ke as e$,xo as e0,gf as e1,O_ as e2,P_ as e3,Xd as e4,we as e5,Mn as e6,Vy as e7,Yr as e8,Ot as e9,kf as eA,Fr as eB,Ya as eC,zu as eD,Tf as eE,Ka as eF,Af as eG,is as eH,Pe as eI,zr as eJ,Ln as eK,hi as eL,Za as eM,Ja as eN,Eo as eO,In as eP,Os as eQ,Lf as eR,Yc as eS,Bf as eT,Nu as eU,di as eV,Wu as eW,Dn as eX,Nr as eY,qs as eZ,ku as e_,nw as ea,tf as eb,kd as ec,TP as ed,og as ee,EP as ef,gb as eg,fb as eh,rg as ei,Ib as ej,Wb as ek,A as el,Po as em,zf as en,My as eo,Tc as ep,Ut as eq,Qt as er,Lr as es,Pt as et,Vi as eu,Mo as ev,We as ew,Xs as ex,Nc as ey,Hc as ez,q as f,Go as f$,$u as f0,Zf as f1,ih as f2,to as f3,He as f4,nh as f5,h0 as f6,d0 as f7,lr as f8,hp as f9,Kr as fA,Sl as fB,Vs as fC,Qc as fD,Df as fE,N0 as fF,bh as fG,mi as fH,Zr as fI,wh as fJ,Dr as fK,an as fL,Op as fM,Cl as fN,Jr as fO,zc as fP,ve as fQ,os as fR,rt as fS,kh as fT,qo as fU,X as fV,ii as fW,It as fX,Ch as fY,hn as fZ,Oh as f_,$r as fa,ml as fb,qr as fc,u0 as fd,fl as fe,jo as ff,Gr as fg,yl as fh,rh as fi,ah as fj,p0 as fk,bt as fl,Io as fm,_t as fn,Un as fo,Ai as fp,ue as fq,pp as fr,m0 as fs,Lo as ft,fp as fu,uh as fv,yp as fw,Ho as fx,Ge as fy,xl as fz,Vv as g,Qp as g$,Xe as g0,xe as g1,ze as g2,Qe as g3,jt as g4,ns as g5,Bi as g6,ot as g7,Xo as g8,si as g9,Zc as gA,Jc as gB,ye as gC,ut as gD,er as gE,Bh as gF,un as gG,tr as gH,pn as gI,Nh as gJ,Hp as gK,rn as gL,zo as gM,Wn as gN,pi as gO,qp as gP,As as gQ,$s as gR,fy as gS,yy as gT,sr as gU,Wh as gV,kl as gW,Ml as gX,Xp as gY,$h as gZ,qh as g_,ea as ga,Ep as gb,zl as gc,Rh as gd,ia as ge,Th as gf,Zo as gg,Ts as gh,Eh as gi,Ah as gj,qn as gk,Es as gl,jh as gm,dn as gn,Ko as go,oa as gp,Fp as gq,Lh as gr,N as gs,Mh as gt,rl as gu,Yf as gv,Ze as gw,th as gx,Kf as gy,Vr as gz,Ss as h,Mp as h$,ra as h0,ls as h1,Bc as h2,Yn as h3,Rt as h4,Fo as h5,ts as h6,Xr as h7,dh as h8,Rl as h9,Yh as hA,Vn as hB,Je as hC,Mt as hD,Il as hE,fn as hF,ha as hG,Zn as hH,tm as hI,Kt as hJ,Ei as hK,Px as hL,kx as hM,Ms as hN,wx as hO,Jf as hP,Zt as hQ,_x as hR,at as hS,rs as hT,Ni as hU,mn as hV,by as hW,Vh as hX,Pu as hY,Ks as hZ,Yo as h_,Zp as ha,la as hb,Do as hc,w0 as hd,x0 as he,S0 as hf,vl as hg,Fl as hh,Ti as hi,Tu as hj,Ga as hk,Eu as hl,y0 as hm,v0 as hn,Wt as ho,Gh as hp,Vt as hq,ca as hr,El as hs,pt as ht,To as hu,No as hv,Kn as hw,ln as hx,Li as hy,xp as hz,af as i,bl as i0,Zx as i1,ji as i2,lg as i3,cg as i4,Cb as i5,Ob as i6,bo as j,E0 as k,G1 as l,FO as m,Fv as n,Pw as o,Y2 as p,jO as q,xk as r,Nm as s,Le as t,Hv as u,kt as v,_e as w,ic as x,F as y,cP as z};
1485
+ `),pe(this,ma).innerHTML=pe(this,yi).innerHTML,pe(this,ma).style.cssText="display: flex; align-items: center; justify-content: center;",pe(this,yi).innerHTML=pe(this,ma).outerHTML,pe(this,pa).innerHTML=pe(this,yi).outerHTML,pe(this,pa).prepend(pe(this,ga)),uu(nf,{element:pe(this,pa)}),(t=pe(this,Bl))==null||t.disconnect(),pe(this,Bl)??Ls(this,Bl,new MutationObserver(()=>ya(this,Wy,rS).call(this))),pe(this,Bl).observe(pe(this,yi),{attributes:!0}),Uy&&console.log("Needle Button updated")},Wy=new WeakSet,rS=function(){pe(this,yi)&&(pe(this,yi).style.display==="none"?this.style.display="none":this.style.display==="none"&&(this.style.display=""))},om=new WeakMap,a(Vy,"observedAttributes",["ar","vr","quicklook"]),typeof window<"u"&&!window.customElements.get(nS)&&window.customElements.define(nS,Vy);const rm=O("debugmissingcamera");ge.registerCallback(fe.MissingCamera,s=>{var t,i,n;rm&&console.warn("Creating missing camera");const o=s.context.scene,r=new be;r.name="Default Fallback Camera",o.add(r);const l=new Pe;l.sourceId=((i=(t=s.files)==null?void 0:t[0])==null?void 0:i.src)??"unknown",(n=s.context.domElement.getAttribute("skybox-image"))!=null&&n.length||0>0||s.context.lightmaps.tryGetSkybox(l.sourceId)?l.clearFlags=Po.Skybox:l.clearFlags=Po.SolidColor,l.backgroundColor=new we(.5,.5,.5,1),l.fieldOfView=35,s.context.domElement.getAttribute("transparent")!=null&&(l.clearFlags=Po.Uninitialized),l.backgroundBlurriness=.2;const c=Cr(r,l,!0);r.position.x=0,r.position.y=1,r.position.z=2;const h=s.context.domElement;return h?.cameraControls!=!1&&aS(s.context,c),c}),ge.registerCallback(fe.ContextCreated,s=>{if(!s.context.mainCamera){rm&&console.log("Will not auto-fit because a default camera exists");return}const t=s.context.domElement;if(t?.cameraControls==!0){const i=Vv(s.context.mainCamera);if(i?.isCameraController==!0){rm&&console.log("Will not auto-fit because a camera controller exists");return}aS(s.context)}});function aS(s,t){t=t??s.mainCameraComponent;const i=t?.gameObject;if(rm&&console.log("Creating default camera controls",t?.name),i){const n=bc(i,ve);n.sourceId=t?.sourceId??"unknown";const o=s.domElement.getAttribute("auto-rotate");if(n.autoRotate=o!=null&&o!="0"&&o?.toLowerCase()!="false",n.autoRotateSpeed=.5,n.autoFit=!0,n.autoRotate&&o){const r=parseFloat(o);isNaN(r)||(n.autoRotateSpeed=r)}}else console.warn("Missing camera object, can not add orbit controls")}ge.registerCallback(fe.ContextCreated,s=>{const t=s.context.domElement.getAttribute("autoplay");if(t!==void 0&&(t===""||t==="true"||t==="1")&&s.files)for(const i of s.files)P.foreachComponent(i.file.scene,n=>{if(n.enabled!==!1){if(n instanceof Ut&&n.playAutomatically||n instanceof Pt||n instanceof sr&&n.playOnAwake===!0)return!0;if(n instanceof Ut)return n.playAutomatically=!0,!0;if(n instanceof sr)return n.playOnAwake=!0,!0}},!0)!==!0&&Na.assignAnimationsFromFile(i.file,{createAnimationComponent:(n,o)=>ki(n,Ut)})});class qj extends nO{constructor(){super(new oO),this.name="GenerateMeshBVHWorker"}runTask(t,i,n={}){return new Promise((o,r)=>{if(i.getAttribute("position").isInterleavedBufferAttribute||i.index&&i.index.isInterleavedBufferAttribute)throw new Error("GenerateMeshBVHWorker: InterleavedBufferAttribute are not supported for the geometry attributes.");t.onerror=d=>{r(new Error(`GenerateMeshBVHWorker: ${d.message}`))},t.onmessage=d=>{const{data:u}=d;if(u.error)r(new Error(u.error)),t.onmessage=null;else if(u.serialized){const{serialized:p,position:g}=u,y=rO.deserialize(p,i,{setIndex:!1}),f=Object.assign({setBoundingBox:!0},n);if(i.attributes.position.array=g,p.index)if(i.index)i.index.array=p.index;else{const v=new mt(p.index,1,!1);i.setIndex(v)}f.setBoundingBox&&(i.boundingBox=y.getBoundingBox(new vi)),n.onProgress&&n.onProgress(u.progress),o(y),t.onmessage=null}else n.onProgress&&n.onProgress(u.progress)};const l=i.index?i.index.array:null,c=i.attributes.position.array,h=[c];l&&h.push(l),t.postMessage({index:l,position:c,options:{...n,onProgress:null,includedProgressCallback:!!n.onProgress,groups:[...i.groups]}},h.map(d=>d.buffer).filter(d=>typeof SharedArrayBuffer>"u"||!(d instanceof SharedArrayBuffer)))})}}const Gj=Object.freeze(Object.defineProperty({__proto__:null,GenerateMeshBVHWorker:qj},Symbol.toStringTag,{value:"Module"}));export{kg as $,Na as A,vr as B,te as C,tg as D,rb as E,U_ as F,P as G,le as H,cs as I,iu as J,N_ as K,xi as L,B as M,Z as N,nu as O,W_ as P,ou as Q,kn as R,Xb as S,S as T,o2 as U,vs as V,Yb as W,Pg as X,r2 as Y,Te as Z,Jb as _,kw as a,Hk as a$,l2 as a0,qg as a1,bc as a2,Cr as a3,ki as a4,R_ as a5,Or as a6,_c as a7,wc as a8,Da as a9,js as aA,Ba as aB,Sc as aC,I_ as aD,j_ as aE,Kd as aF,Gg as aG,Pr as aH,D_ as aI,Fa as aJ,Mi as aK,kr as aL,eu as aM,za as aN,ms as aO,Pm as aP,Ij as aQ,jj as aR,Lj as aS,Bj as aT,Md as aU,De as aV,Sn as aW,ac as aX,AP as aY,Ci as aZ,yb as a_,xc as aa,qd as ab,Gd as ac,A_ as ad,pc as ae,Cd as af,ig as ag,oc as ah,xn as ai,br as aj,rc as ak,uk as al,pk as am,Ce as an,fu as ao,fe as ap,ge as aq,H_ as ar,q2 as as,$_ as at,_r as au,mo as av,Ly as aw,wk as ax,hf as ay,uf as az,Gk as b,Iy as b$,$k as b0,qk as b1,Xk as b2,W as b3,bd as b4,Fm as b5,li as b6,lc as b7,Tb as b8,ie as b9,Of as bA,Uw as bB,Nw as bC,Vc as bD,od as bE,Ys as bF,bs as bG,Gt as bH,Cv as bI,Od as bJ,MP as bK,Pd as bL,Ns as bM,Sg as bN,Id as bO,vt as bP,Ou as bQ,tt as bR,qa as bS,nd as bT,vo as bU,X_ as bV,Q_ as bW,Va as bX,hu as bY,Z_ as bZ,J_ as b_,VP as ba,HP as bb,$P as bc,Eb as bd,ug as be,Ab as bf,Mr as bg,Zw as bh,dR as bi,Ao as bj,Bt as bk,a_ as bl,yc as bm,Dg as bn,l_ as bo,y2 as bp,c_ as bq,Bg as br,h_ as bs,d_ as bt,p_ as bu,zP as bv,UP as bw,Pb as bx,Mb as by,Qs as bz,Ck as c,cO as c$,H1 as c0,ua as c1,Oj as c2,Pj as c3,jy as c4,q1 as c5,$d as c6,Vg as c7,b_ as c8,m as c9,Gm as cA,Xm as cB,Zl as cC,Qm as cD,Jl as cE,xd as cF,tP as cG,Zv as cH,Gi as cI,Jv as cJ,iP as cK,Ym as cL,eb as cM,Si as cN,tb as cO,ib as cP,Km as cQ,tw as cR,fx as cS,ce as cT,Bu as cU,Dw as cV,RM as cW,Bw as cX,Fw as cY,zw as cZ,Ov as c_,Ha as ca,oM as cb,aM as cc,Tw as cd,Mu as ce,dM as cf,Ew as cg,Aw as ch,Uj as ci,$a as cj,HO as ck,$O as cl,Kl as cm,$ as cn,qv as co,fs as cp,ee as cq,lt as cr,fr as cs,Se as ct,qi as cu,$m as cv,Ke as cw,Oa as cx,ZO as cy,qm as cz,yj as d,Sw as d$,hO as d0,wi as d1,$l as d2,O as d3,dO as d4,ql as d5,Rm as d6,Pv as d7,Tm as d8,uO as d9,MO as dA,RO as dB,TO as dC,Av as dD,Iv as dE,Am as dF,yd as dG,jv as dH,U1 as dI,N1 as dJ,sj as dK,Oy as dL,D1 as dM,Qh as dN,Nj as dO,Vj as dP,g_ as dQ,Gu as dR,ks as dS,LR as dT,DR as dU,Qu as dV,Yu as dW,Gf as dX,Xf as dY,Ik as dZ,Ac as d_,pO as da,Rv as db,Tv as dc,Sa as dd,Gl as de,gs as df,Xl as dg,Ev as dh,mO as di,co as dj,Jn as dk,fd as dl,Em as dm,Y as dn,fO as dp,yO as dq,vO as dr,bO as ds,_O as dt,wO as du,xO as dv,SO as dw,CO as dx,OO as dy,PO as dz,zm as e,ke as e$,xo as e0,gf as e1,O_ as e2,P_ as e3,Xd as e4,we as e5,Mn as e6,Vy as e7,Yr as e8,Ot as e9,kf as eA,Fr as eB,Ya as eC,zu as eD,Tf as eE,Ka as eF,Af as eG,is as eH,Pe as eI,zr as eJ,Ln as eK,hi as eL,Za as eM,Ja as eN,Eo as eO,In as eP,Os as eQ,Lf as eR,Yc as eS,Bf as eT,Nu as eU,di as eV,Wu as eW,Dn as eX,Nr as eY,qs as eZ,ku as e_,nw as ea,tf as eb,kd as ec,TP as ed,og as ee,EP as ef,gb as eg,fb as eh,rg as ei,Ib as ej,Wb as ek,A as el,Po as em,zf as en,My as eo,Tc as ep,Ut as eq,Qt as er,Lr as es,Pt as et,Vi as eu,Mo as ev,We as ew,Xs as ex,Nc as ey,Hc as ez,q as f,Go as f$,$u as f0,Zf as f1,ih as f2,to as f3,He as f4,nh as f5,h0 as f6,d0 as f7,lr as f8,hp as f9,Kr as fA,Sl as fB,Vs as fC,Qc as fD,Df as fE,N0 as fF,bh as fG,mi as fH,Zr as fI,wh as fJ,Dr as fK,an as fL,Op as fM,Cl as fN,Jr as fO,zc as fP,ve as fQ,os as fR,rt as fS,kh as fT,qo as fU,X as fV,ii as fW,It as fX,Ch as fY,hn as fZ,Oh as f_,$r as fa,ml as fb,qr as fc,u0 as fd,fl as fe,jo as ff,Gr as fg,yl as fh,rh as fi,ah as fj,p0 as fk,bt as fl,Io as fm,_t as fn,Un as fo,Ai as fp,ue as fq,pp as fr,m0 as fs,Lo as ft,fp as fu,uh as fv,yp as fw,Ho as fx,Ge as fy,xl as fz,Vv as g,Qp as g$,Xe as g0,xe as g1,ze as g2,Qe as g3,jt as g4,ns as g5,Bi as g6,ot as g7,Xo as g8,si as g9,Zc as gA,Jc as gB,ye as gC,ut as gD,er as gE,Bh as gF,un as gG,tr as gH,pn as gI,Nh as gJ,Hp as gK,rn as gL,zo as gM,Wn as gN,pi as gO,qp as gP,As as gQ,$s as gR,fy as gS,yy as gT,sr as gU,Wh as gV,kl as gW,Ml as gX,Xp as gY,$h as gZ,qh as g_,ea as ga,Ep as gb,zl as gc,Rh as gd,ia as ge,Th as gf,Zo as gg,Ts as gh,Eh as gi,Ah as gj,qn as gk,Es as gl,jh as gm,dn as gn,Ko as go,oa as gp,Fp as gq,Lh as gr,N as gs,Mh as gt,rl as gu,Yf as gv,Ze as gw,th as gx,Kf as gy,Vr as gz,Ss as h,Mp as h$,ra as h0,ls as h1,Bc as h2,Yn as h3,Rt as h4,Fo as h5,ts as h6,Xr as h7,dh as h8,Rl as h9,Yh as hA,Vn as hB,Je as hC,Mt as hD,Il as hE,fn as hF,ha as hG,Zn as hH,tm as hI,Kt as hJ,Ei as hK,Px as hL,kx as hM,Ms as hN,wx as hO,Jf as hP,Zt as hQ,_x as hR,at as hS,rs as hT,Ni as hU,mn as hV,by as hW,Vh as hX,Pu as hY,Ks as hZ,Yo as h_,Zp as ha,la as hb,Do as hc,w0 as hd,x0 as he,S0 as hf,vl as hg,Fl as hh,Ti as hi,Tu as hj,Ga as hk,Eu as hl,y0 as hm,v0 as hn,Wt as ho,Gh as hp,Vt as hq,ca as hr,El as hs,pt as ht,To as hu,No as hv,Kn as hw,ln as hx,Li as hy,xp as hz,af as i,bl as i0,Zx as i1,ji as i2,lg as i3,cg as i4,Cb as i5,Ob as i6,bo as j,E0 as k,G1 as l,FO as m,Fv as n,Pw as o,Yk as p,jO as q,x2 as r,Nm as s,Le as t,Hv as u,kt as v,_e as w,ic as x,F as y,cP as z};