@needle-tools/engine 4.8.3-next.1a41273 → 4.8.3-next.30abed3

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.
Files changed (37) hide show
  1. package/dist/{gltf-progressive-Do1XJNMG.js → gltf-progressive-B3JW4cAu.js} +247 -248
  2. package/dist/gltf-progressive-DorC035H.min.js +8 -0
  3. package/dist/{gltf-progressive-CHV7_60B.umd.cjs → gltf-progressive-PB_58h1b.umd.cjs} +6 -6
  4. package/dist/{needle-engine.bundle-CcYGQALb.umd.cjs → needle-engine.bundle-Dfge2eam.umd.cjs} +27 -17
  5. package/dist/{needle-engine.bundle-CvDGadt9.min.js → needle-engine.bundle-hqzbYg51.min.js} +38 -28
  6. package/dist/{needle-engine.bundle-DbnDoLkt.js → needle-engine.bundle-rCfjUm0B.js} +171 -162
  7. package/dist/needle-engine.js +3 -3
  8. package/dist/needle-engine.min.js +1 -1
  9. package/dist/needle-engine.umd.cjs +1 -1
  10. package/dist/{vendor-CGONwIc0.js → vendor-B_ytQUuR.js} +6 -6
  11. package/dist/{vendor-BlSxe9JJ.min.js → vendor-C31T0mYm.min.js} +2 -2
  12. package/dist/{vendor-Cty8Dnri.umd.cjs → vendor-D51IT5ns.umd.cjs} +9 -9
  13. package/lib/engine/engine_context.d.ts +1 -1
  14. package/lib/engine/engine_context.js +5 -12
  15. package/lib/engine/engine_context.js.map +1 -1
  16. package/lib/engine/engine_networking_streams.js +7 -2
  17. package/lib/engine/engine_networking_streams.js.map +1 -1
  18. package/lib/engine/webcomponents/buttons.js +6 -2
  19. package/lib/engine/webcomponents/buttons.js.map +1 -1
  20. package/lib/engine/webcomponents/needle menu/needle-menu.js +10 -0
  21. package/lib/engine/webcomponents/needle menu/needle-menu.js.map +1 -1
  22. package/lib/engine/webcomponents/needle-engine.loading.js +1 -1
  23. package/lib/engine/webcomponents/needle-engine.loading.js.map +1 -1
  24. package/lib/engine-components/OrbitControls.d.ts +1 -0
  25. package/lib/engine-components/OrbitControls.js +6 -0
  26. package/lib/engine-components/OrbitControls.js.map +1 -1
  27. package/package.json +3 -3
  28. package/plugins/vite/peer.js +60 -2
  29. package/plugins/vite/poster-client.js +35 -51
  30. package/plugins/vite/poster.js +2 -3
  31. package/src/engine/engine_context.ts +7 -12
  32. package/src/engine/engine_networking_streams.ts +8 -4
  33. package/src/engine/webcomponents/buttons.ts +6 -2
  34. package/src/engine/webcomponents/needle menu/needle-menu.ts +10 -0
  35. package/src/engine/webcomponents/needle-engine.loading.ts +1 -1
  36. package/src/engine-components/OrbitControls.ts +5 -0
  37. package/dist/gltf-progressive-B--ZfCTJ.min.js +0 -8
@@ -1,4 +1,4 @@
1
- "use strict";const c=require("./three-B_hneGZr.umd.cjs"),ne=require("./gltf-progressive-CHV7_60B.umd.cjs"),G=require("./three-examples-CNRuT27G.umd.cjs"),se=require("./vendor-Cty8Dnri.umd.cjs"),J=require("./three-mesh-ui-tt0buEDC.umd.cjs"),Dw=require("./postprocessing-BgC7XZwK.umd.cjs");var Au=typeof document<"u"?document.currentScript:null;const Lu=new Map;function Bt(s=globalThis.location?.hostname){if(Lu.has(s))return Lu.get(s);const e=/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})|localhost/.test(s);return Lu.set(s,e),e===!0}function W_(){return window.location.hostname.includes("glitch.me")}const Iw='<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>',jw=btoa(Iw),Bw="data:image/svg+xml;base64,"+jw,G_=Bw,Fw=`<?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(Fw);const Uw='<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>',zw=btoa(Uw),Nw="data:image/svg+xml;charset=utf-8;base64,"+zw,Vw=Nw,Gg=typeof window!==void 0?window.location.search.includes("debugcontext"):!1;var oe=(s=>(s.ContextRegistered="ContextRegistered",s.ContextCreationStart="ContextCreationStart",s.ContextCreated="ContextCreated",s.ContextFirstFrameRendered="ContextFirstFrameRendered",s.ContextDestroying="ContextDestroying",s.ContextDestroyed="ContextDestroyed",s.MissingCamera="MissingCamera",s.ContextClearing="ContextClearing",s.ContextCleared="ContextCleared",s))(oe||{});class re{static get Current(){return globalThis["NeedleEngine.Context.Current"]}static set Current(e){globalThis["NeedleEngine.Context.Current"]=e}static get All(){return this.Registered}static Registered=[];static register(e){this.Registered.indexOf(e)===-1&&(Gg&&console.warn("Registering context"),this.Registered.push(e),this.dispatchCallback("ContextRegistered",e))}static unregister(e){const t=this.Registered.indexOf(e);t!==-1&&(Gg&&console.warn("Unregistering context"),this.Registered.splice(t,1))}static _callbacks={};static registerCallback(e,t){this._callbacks[e]||(this._callbacks[e]=[]),this._callbacks[e].push(t)}static unregisterCallback(e,t){if(!this._callbacks[e])return;const i=this._callbacks[e].indexOf(t);i!==-1&&this._callbacks[e].splice(i,1)}static dispatchCallback(e,t,i){if(!this._callbacks[e])return!0;const n={event:e,context:t};if(i)for(const r in i)n[r]=i[r];const o=new Array;return this._callbacks[e].forEach(r=>{const a=r(n);a instanceof Promise&&o.push(a)}),Promise.all(o)}static addContextCreatedCallback(e){this.registerCallback("ContextCreated",e)}static addContextDestroyedCallback(e){this.registerCallback("ContextDestroyed",e)}}const H_=()=>s=>s;function $w(s){return H_()(s)}function Ww(){return!!w("debug")}class hi{_factory;_cache=[];_maxSize;_index=0;constructor(e,t){this._factory=e,this._maxSize=t}get(){const e=this._index%this._maxSize;return this._index++,this._cache.length<=e&&(this._cache[e]=this._factory()),this._cache[e]}}let wo=!1;const Ff=new Array;typeof window<"u"&&setTimeout(()=>{if(wo){const s={},e=new URL(window.location.href),t=new URL(e);t.searchParams.append("console","");const i=t.toString().replace(/=$|=(?=&)/g,"");for(const o of Ff){const r=new URL(e);r.searchParams.append(o,""),s[o]=r.toString().replace(/=$|=(?=&)/g,"")}console.log(`🌵 ?help: Debug Options for Needle Engine.
1
+ "use strict";const c=require("./three-B_hneGZr.umd.cjs"),ne=require("./gltf-progressive-PB_58h1b.umd.cjs"),G=require("./three-examples-CNRuT27G.umd.cjs"),se=require("./vendor-D51IT5ns.umd.cjs"),J=require("./three-mesh-ui-tt0buEDC.umd.cjs"),Dw=require("./postprocessing-BgC7XZwK.umd.cjs");var Au=typeof document<"u"?document.currentScript:null;const Lu=new Map;function Bt(s=globalThis.location?.hostname){if(Lu.has(s))return Lu.get(s);const e=/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})|localhost/.test(s);return Lu.set(s,e),e===!0}function W_(){return window.location.hostname.includes("glitch.me")}const Iw='<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>',jw=btoa(Iw),Bw="data:image/svg+xml;base64,"+jw,G_=Bw,Fw=`<?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(Fw);const Uw='<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>',zw=btoa(Uw),Nw="data:image/svg+xml;charset=utf-8;base64,"+zw,Vw=Nw,Gg=typeof window!==void 0?window.location.search.includes("debugcontext"):!1;var oe=(s=>(s.ContextRegistered="ContextRegistered",s.ContextCreationStart="ContextCreationStart",s.ContextCreated="ContextCreated",s.ContextFirstFrameRendered="ContextFirstFrameRendered",s.ContextDestroying="ContextDestroying",s.ContextDestroyed="ContextDestroyed",s.MissingCamera="MissingCamera",s.ContextClearing="ContextClearing",s.ContextCleared="ContextCleared",s))(oe||{});class re{static get Current(){return globalThis["NeedleEngine.Context.Current"]}static set Current(e){globalThis["NeedleEngine.Context.Current"]=e}static get All(){return this.Registered}static Registered=[];static register(e){this.Registered.indexOf(e)===-1&&(Gg&&console.warn("Registering context"),this.Registered.push(e),this.dispatchCallback("ContextRegistered",e))}static unregister(e){const t=this.Registered.indexOf(e);t!==-1&&(Gg&&console.warn("Unregistering context"),this.Registered.splice(t,1))}static _callbacks={};static registerCallback(e,t){this._callbacks[e]||(this._callbacks[e]=[]),this._callbacks[e].push(t)}static unregisterCallback(e,t){if(!this._callbacks[e])return;const i=this._callbacks[e].indexOf(t);i!==-1&&this._callbacks[e].splice(i,1)}static dispatchCallback(e,t,i){if(!this._callbacks[e])return!0;const n={event:e,context:t};if(i)for(const r in i)n[r]=i[r];const o=new Array;return this._callbacks[e].forEach(r=>{const a=r(n);a instanceof Promise&&o.push(a)}),Promise.all(o)}static addContextCreatedCallback(e){this.registerCallback("ContextCreated",e)}static addContextDestroyedCallback(e){this.registerCallback("ContextDestroyed",e)}}const H_=()=>s=>s;function $w(s){return H_()(s)}function Ww(){return!!w("debug")}class hi{_factory;_cache=[];_maxSize;_index=0;constructor(e,t){this._factory=e,this._maxSize=t}get(){const e=this._index%this._maxSize;return this._index++,this._cache.length<=e&&(this._cache[e]=this._factory()),this._cache[e]}}let wo=!1;const Ff=new Array;typeof window<"u"&&setTimeout(()=>{if(wo){const s={},e=new URL(window.location.href),t=new URL(e);t.searchParams.append("console","");const i=t.toString().replace(/=$|=(?=&)/g,"");for(const o of Ff){const r=new URL(e);r.searchParams.append(o,""),s[o]=r.toString().replace(/=$|=(?=&)/g,"")}console.log(`🌵 ?help: Debug Options for Needle Engine.
2
2
  Append any of these parameters to the URL to enable specific debug options.
3
3
  Example: ${i} will show an onscreen console window.`);const n=wo===!0?"":` (containing "${wo}")`;console.group("Available URL parameters:"+n);for(const o of Object.keys(s).sort())typeof wo=="string"&&!o.toLowerCase().includes(wo.toLowerCase())||(console.groupCollapsed(o),console.log("Reload with this flag enabled:"),console.log(s[o]),console.groupEnd());console.groupEnd()}},100);function Zl(){return new URLSearchParams(globalThis.location?.search)}function w(s){wo&&!Ff.includes(s)&&Ff.push(s);const e=Zl();if(e.has(s)){const t=e.get(s);if(t){const i=Number(t);return isNaN(i)?t:i}else return!0}return!1}wo=w("help");function Gw(s,e){const t=Zl();t.has(s)?t.set(s,e):t.append(s,e),document.location.search=t.toString()}function Dl(s,e,t=!0){const i=Zl();i.has(s)?e===null?i.delete(s):i.set(s,e):e!==null&&i.append(s,e),t?q_(s,i):Ip(s,i)}function Uf(s,e,t){s.has(e)?s.set(e,t.toString()):s.append(e,t.toString())}function q_(s,e,t){window.history.pushState(t,s,"?"+e.toString())}function Ip(s,e,t){window.history.replaceState(t,s,"?"+e.toString())}function Hw(s){for(var e="",t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",i=t.length,n=0;n<s;n++)e+=t.charAt(Math.floor(Math.random()*i));return e}function qw(s,e){return Math.floor(Math.random()*(e-s+1))+s}const Hg=["smol","tiny","giant","interesting","smart","bright","dull","extreme","beautiful","pretty","dark","epic","salty","silly","funny","lame","lazy","loud","lucky","mad","mean","mighty","mysterious","nasty","odd","old","powerful","quiet","rapid","scary","shiny","shy","silly","smooth","sour","spicy","stupid","sweet","tasty","terrible","ugly","unusual","vast","wet","wild","witty","wrong","zany","zealous","zippy","zombie","zorro"],qg=["cat","dog","mouse","pig","cow","horse","sheep","chicken","duck","goat","panda","tiger","lion","elephant","monkey","bird","fish","snake","frog","turtle","hamster","penguin","kangaroo","whale","dolphin","crocodile","snail","ant","bee","beetle","butterfly","dragon","eagle","fish","giraffe","lizard","panda","penguin","rabbit","snake","spider","tiger","zebra"];function X_(){const s=Hg[Math.floor(Math.random()*Hg.length)],e=qg[Math.floor(Math.random()*qg.length)];return s+"_"+e}function Q_(s){return s=s.replace(/[^a-z0-9áéíóúñü \.,_-]/gim,""),s.trim()}function Zr(s,e,t=!0,i=!1){if(e==null)return null;if(e.userData&&e.userData.guid===s)return e;if(e.guid==s)return e;if(i&&e.userData?.components){for(const n of e.userData.components)if(n.guid===s)return n}if(t){if(e.scenes)for(const n in e.scenes){const o=e.scenes[n],r=Zr(s,o,t,i);if(r)return r}if(e.children)for(const n in e.children){const o=e.children[n],r=Zr(s,o,t,i);if(r)return r}}}function Jl(s,e){if(s!=null&&typeof s=="object"){let t;Array.isArray(s)?t=[]:(t=Object.create(s),Object.assign(t,s));for(const i of Object.keys(s)){const n=s[i];e&&!e(s,i,n)?t[i]=n:n?.clone!==void 0&&typeof n.clone=="function"?t[i]=n.clone():t[i]=Jl(n,e)}return t}return s}function An(s){return new Promise((e,t)=>{setTimeout(e,s)})}function ec(s,e){if(s<=0)return Promise.resolve();if(e||(e=re.Current),!e)return Promise.reject("No context");const t=e.time.frameCount+s;return new Promise((i,n)=>{if(!e)return n("No context");const o=()=>{e.time.frameCount>=t&&(e.pre_update_callbacks.splice(e.pre_update_callbacks.indexOf(o),1),i())};e.pre_update_callbacks.push(o)})}const Kc=w("debugresolveurl"),Y_="rel:";function Xw(s,e){return Ks(s,e)}function Ks(s,e){if(e===void 0)return Kc&&console.warn("getPath: uri is undefined, returning uri",e),e;if(e.startsWith("./"))return e;if(e.startsWith("http"))return Kc&&console.warn("getPath: uri is absolute, returning uri",e),e;if(s===void 0)return Kc&&console.warn("getPath: source is undefined, returning uri",e),e;e.startsWith(Y_)&&(e=e.substring(4));const t=s.lastIndexOf("/");if(t>=0){const i=s.substring(0,t+1);for(;i.endsWith("/")&&e.startsWith("/");)e=e.substring(1);const n=i+e;return Kc&&console.log("source:",s,`changed uri
4
4
  from`,e,`
@@ -142,7 +142,7 @@ Open this page to get the console: `+e.toString())}const s=exports.DeviceUtiliti
142
142
  #__vconsole .vc-mask {
143
143
  overflow: hidden;
144
144
  }
145
- `,Qi?.prepend(i),s===!0&&Fp()<=0&&bb(),console.log("🌵 Debug console has loaded")}},e.onerror=()=>{console.warn("🌵 Debug console failed to load."+(window.crossOriginIsolated?"This page is using cross-origin isolation, so external scripts can't be loaded.":"")),Ba=!1,ni=null},e.src="https://cdn.jsdelivr.net/npm/vconsole@3.9.1/dist/vconsole.min.js",document.body.appendChild(e)}function qx(){if(!globalThis.VConsole)return;const s=new VConsole.VConsolePlugin("needle-console","🌵 Inspect glTF"),e=()=>document.querySelector("#__vc_plug_"+s._id+" iframe");return s.on("renderTab",function(t){const i=globalThis["needle:codegen_files"];if(!i||i.length===0)return;let n=globalThis["needle:codegen_files"][0];const o=n.indexOf("?");o>-1&&(n=n.substring(0,o));const a=location.protocol+"//"+location.host+location.pathname+"/"+n,l=encodeURIComponent(a);s.fullUrl="https://viewer.needle.tools?inspect&file="+l;var h='<iframe src="" style="width: 100%; height: 99%; border: none;"></iframe>';t(h)}),s.on("show",function(){const t=e();t&&t.src!==s.fullUrl&&(t.src=s.fullUrl)}),s.on("hide",function(){const t=e();t&&(t.src="")}),s.on("addTopBar",function(t){var i=new Array;i.push({name:"Open in new window ↗",onClick:function(n){window.open(s.fullUrl,"_blank"),ni?.hide()}}),i.push({name:"Reload",onClick:function(n){const o=e();o&&(o.src=s.fullUrl)}}),i.push({name:"Fullscreen",onClick:function(n){const o=e();o.requestFullscreen?o.requestFullscreen():o.webkitRequestFullscreen instanceof Function&&o.webkitRequestFullscreen()}}),t(i)}),s}function Xx(){const s=document.querySelector("#__vconsole .vc-switch");return s||null}function Qx(){const s=document.querySelector("#__vconsole");return s||null}const xb=w("debugdefines");Zs('if(!globalThis["NEEDLE_ENGINE_VERSION"]) globalThis["NEEDLE_ENGINE_VERSION"] = "0.0.0";');Zs('if(!globalThis["NEEDLE_ENGINE_GENERATOR"]) globalThis["NEEDLE_ENGINE_GENERATOR"] = "unknown";');Zs('if(!globalThis["NEEDLE_PROJECT_BUILD_TIME"]) globalThis["NEEDLE_PROJECT_BUILD_TIME"] = "unknown";');Zs('if(!globalThis["NEEDLE_PUBLIC_KEY"]) globalThis["NEEDLE_PUBLIC_KEY"] = "unknown";');Zs('globalThis["__NEEDLE_ENGINE_VERSION__"] = "4.8.3";');Zs('globalThis["__NEEDLE_ENGINE_GENERATOR__"] = "undefined";');Zs('globalThis["__NEEDLE_PROJECT_BUILD_TIME__"] = "Mon Aug 18 2025 11:25:17 GMT+0000 (Coordinated Universal Time)";');Zs('globalThis["__NEEDLE_PUBLIC_KEY__"] = "'+NEEDLE_PUBLIC_KEY+'";');const Ji="4.8.3",kd="undefined",qp="Mon Aug 18 2025 11:25:17 GMT+0000 (Coordinated Universal Time)";xb&&console.log(`Engine version: ${Ji} (generator: ${kd})
145
+ `,Qi?.prepend(i),s===!0&&Fp()<=0&&bb(),console.log("🌵 Debug console has loaded")}},e.onerror=()=>{console.warn("🌵 Debug console failed to load."+(window.crossOriginIsolated?"This page is using cross-origin isolation, so external scripts can't be loaded.":"")),Ba=!1,ni=null},e.src="https://cdn.jsdelivr.net/npm/vconsole@3.9.1/dist/vconsole.min.js",document.body.appendChild(e)}function qx(){if(!globalThis.VConsole)return;const s=new VConsole.VConsolePlugin("needle-console","🌵 Inspect glTF"),e=()=>document.querySelector("#__vc_plug_"+s._id+" iframe");return s.on("renderTab",function(t){const i=globalThis["needle:codegen_files"];if(!i||i.length===0)return;let n=globalThis["needle:codegen_files"][0];const o=n.indexOf("?");o>-1&&(n=n.substring(0,o));const a=location.protocol+"//"+location.host+location.pathname+"/"+n,l=encodeURIComponent(a);s.fullUrl="https://viewer.needle.tools?inspect&file="+l;var h='<iframe src="" style="width: 100%; height: 99%; border: none;"></iframe>';t(h)}),s.on("show",function(){const t=e();t&&t.src!==s.fullUrl&&(t.src=s.fullUrl)}),s.on("hide",function(){const t=e();t&&(t.src="")}),s.on("addTopBar",function(t){var i=new Array;i.push({name:"Open in new window ↗",onClick:function(n){window.open(s.fullUrl,"_blank"),ni?.hide()}}),i.push({name:"Reload",onClick:function(n){const o=e();o&&(o.src=s.fullUrl)}}),i.push({name:"Fullscreen",onClick:function(n){const o=e();o.requestFullscreen?o.requestFullscreen():o.webkitRequestFullscreen instanceof Function&&o.webkitRequestFullscreen()}}),t(i)}),s}function Xx(){const s=document.querySelector("#__vconsole .vc-switch");return s||null}function Qx(){const s=document.querySelector("#__vconsole");return s||null}const xb=w("debugdefines");Zs('if(!globalThis["NEEDLE_ENGINE_VERSION"]) globalThis["NEEDLE_ENGINE_VERSION"] = "0.0.0";');Zs('if(!globalThis["NEEDLE_ENGINE_GENERATOR"]) globalThis["NEEDLE_ENGINE_GENERATOR"] = "unknown";');Zs('if(!globalThis["NEEDLE_PROJECT_BUILD_TIME"]) globalThis["NEEDLE_PROJECT_BUILD_TIME"] = "unknown";');Zs('if(!globalThis["NEEDLE_PUBLIC_KEY"]) globalThis["NEEDLE_PUBLIC_KEY"] = "unknown";');Zs('globalThis["__NEEDLE_ENGINE_VERSION__"] = "4.8.3";');Zs('globalThis["__NEEDLE_ENGINE_GENERATOR__"] = "undefined";');Zs('globalThis["__NEEDLE_PROJECT_BUILD_TIME__"] = "Mon Aug 18 2025 15:24:11 GMT+0000 (Coordinated Universal Time)";');Zs('globalThis["__NEEDLE_PUBLIC_KEY__"] = "'+NEEDLE_PUBLIC_KEY+'";');const Ji="4.8.3",kd="undefined",qp="Mon Aug 18 2025 15:24:11 GMT+0000 (Coordinated Universal Time)";xb&&console.log(`Engine version: ${Ji} (generator: ${kd})
146
146
  Project built at ${qp}`);const Br=NEEDLE_PUBLIC_KEY,rs="needle_isActiveInHierarchy",xo="builtin_components",xl="needle_editor_guid";function Zs(s){try{(0,eval)(s)}catch(e){xb&&console.error(e)}}let Sb,ny=null;function en(){return Sb}function Xp(s){if(s==null){console.warn("Oh no: someone tried registering a non-existend gltf-loader. When you see this log it might mean that needle-engine is being imported multiple times. Please check your project setup.");return}ny!==s&&(ny=s,Sb=new s)}const si=Symbol("shadowDomOwner"),Yx=w("debugpatch");function Rd(s,e,t,i){const n=Yx===e;if(!t&&!i)return;const o=e+"___needle";Zx(s,e,t,i);const r=Object.getOwnPropertyDescriptor(s,e),a=s[e];n&&console.log("Patch",s.constructor.name,e,r,a),r?(n&&console.log("Apply patch with existing descriptor",s.constructor.name,e,r),typeof r.value=="function"&&(s[e]=oy(r.value,s,e))):(n&&console.log("Create patch with new property",s.constructor.name,e,r),Object.defineProperty(s,e,{set:function(l){if(typeof l=="function")this[o]=oy(l,s,e);else{const h=this[o];Cb(s,e,this,h,l),this[o]=l,Pb(s,e,this,h,l)}},get:function(){const l=this[o];return typeof l=="function"&&l[o]?l[o]:l}}))}function Kx(s,e,t){const i=Qp(s,e);if(i)for(let n=i.length-1;n>=0;n--){const o=i[n];o.prefix===t&&(o.prefix=null),o.postfix===t&&(o.postfix=null),!o.prefix&&!o.postfix&&i.splice(n,1)}}const sy=Symbol("Needle:Patches:WrappedFunction");function oy(s,e,t){if(s[sy])return s;const i=function(...n){Cb(e,t,this,...n);const o=s.apply(this,n);return Pb(e,t,this,o,...n),o};return i[sy]=!0,i}const Eh="Needle:Patches";function qf(){return globalThis[Eh]||(globalThis[Eh]=new WeakMap),globalThis[Eh]}function Qp(s,e){const t=qf().get(s);return t?t.get(e):null}function Zx(s,e,t,i){let n=qf().get(s);n||(n=new Map,qf().set(s,n));let o=n.get(e);o||(o=[],n.set(e,o)),o.push({prefix:t,postfix:i})}function Cb(s,e,t,...i){if(!t)return;const n=Qp(s,e);if(n)for(const o of n)o.prefix?.call(t,...i)}function Pb(s,e,t,i,...n){if(!t)return;const o=Qp(s,e);if(o)for(const r of o)r.postfix?.call(t,i,...n)}const ea=[];function Ed(s){ea.indexOf(s)===-1&&ea.push(s)}function Jx(s){const e=ea.indexOf(s);e!==-1&&ea.splice(e,1)}const ta=[];function Yp(s){ta.indexOf(s)===-1&&ta.push(s)}function eS(s){const e=ta.indexOf(s);e!==-1&&ta.splice(e,1)}function Mb(s){globalThis.dispatchEvent(new CustomEvent("needle-xrsession-start",{detail:s}));for(let e=0;e<ea.length;e++)ea[e](s)}function Ob(s){globalThis.dispatchEvent(new CustomEvent("needle-xrsession-end",{detail:s}));for(let e=0;e<ta.length;e++)ta[e](s)}const He=w("debuginput");var Td=(s=>(s.Mouse="mouse",s.Touch="touch",s.Controller="controller",s.Hand="hand",s))(Td||{}),we=(s=>(s.PointerDown="pointerdown",s.PointerUp="pointerup",s.PointerMove="pointermove",s.KeyDown="keydown",s.KeyUp="keyup",s.KeyPressed="keypress",s))(we||{});class Yn extends PointerEvent{clientZ;deviceIndex;origin;source;mode;get isSpatial(){return this.mode!="screen"}get ray(){return this._ray||(this._ray=new c.Ray(this.space.worldPosition.clone(),this.space.worldForward.clone())),this._ray}set ray(e){this._ray=e}get hasRay(){return this._ray!==void 0}_ray;space;isClick=!1;isDoubleClick=!1;get used(){return this._used}_used=!1;use(){this._used=!0}get pointerId(){return this._pointerid}_pointerid;get pointerType(){return this._pointerType}_pointerType;get type(){return this._type}_type;metadata={};intersections=new Array;constructor(e,t,i){super(e,i),this.clientZ=i.clientZ,this._pointerid=i.pointerId,this._pointerType=i.pointerType,this._type=e,this.deviceIndex=i.deviceIndex,this.origin=i.origin,this.source=t,this.mode=i.mode,this._ray=i.ray,this.space=i.device}_immediatePropagationStopped=!1;get immediatePropagationStopped(){return this._immediatePropagationStopped}_propagationStopped=!1;get propagationStopped(){return this._immediatePropagationStopped||this._propagationStopped}stopImmediatePropagation(){this._immediatePropagationStopped=!0,super.stopImmediatePropagation(),this.source?.stopImmediatePropagation()}stopPropagation(){this._propagationStopped=!0,super.stopPropagation(),this.source?.stopPropagation(),He&&console.warn("Stop propagation...",this.pointerId,this.pointerType)}}class nl extends KeyboardEvent{source;constructor(e,t,i){super(e,i),this.source=t}stopImmediatePropagation(){super.stopImmediatePropagation(),this.source?.stopImmediatePropagation()}}class tS{key;keyType;source;constructor(e){this.key=e.key,this.keyType=e.type,this.source=e}}var $t=(s=>(s[s.Early=-100]="Early",s[s.Default=0]="Default",s[s.Late=100]="Late",s))($t||{});class kb{_eventListeners={};addEventListener(e,t,i){if(this._eventListeners[e]||(this._eventListeners[e]=[]),!t||typeof t!="function"){console.error("Invalid call to addEventListener: callback is required and must be a function!");return}i?i={...i}:i={};let n=0;i?.queue!=null&&(n=i.queue);const o=this._eventListeners[e],r=o.find(a=>a.priority===n);r?r.listeners.push({callback:t,options:i}):(o.push({priority:n,listeners:[{callback:t,options:i}]}),o.sort((a,l)=>a.priority-l.priority))}removeEventListener(e,t,i){if(!this._eventListeners[e]||!t)return;const n=this._eventListeners[e];if(i?.queue!=null){const o=n.find(a=>a.priority===i.queue);if(!o)return;const r=o.listeners.findIndex(a=>a.callback===t);r>=0&&o.listeners.splice(r,1)}else for(const o of n){const r=o.listeners.findIndex(a=>a.callback===t);r>=0&&o.listeners.splice(r,1)}}dispatchEvent(e){let t=!1;if(e instanceof nl){const i=this._eventListeners[e.type];if(i)for(const n of i)for(let o=0;o<n.listeners.length;o++){const r=n.listeners[o];if(r.options?.signal?.aborted){n.listeners.splice(o,1),o--;continue}r.options.once&&(n.listeners.splice(o,1),o--),r.callback(e)}}if(e instanceof Yn){const i=this._eventListeners[e.type];if(i)for(const n of i){if(t)break;for(let o=0;o<n.listeners.length;o++){const r=n.listeners[o];if(r.options?.signal?.aborted){n.listeners.splice(o,1),o--;continue}if(e.immediatePropagationStopped){t=!0,He&&console.log("immediatePropagationStopped",e.type);break}else e.propagationStopped&&(t=!0,He&&console.log("propagationStopped",e.type));r.options.once&&(n.listeners.splice(o,1),o--),r.callback(e)}}}}_doubleClickTimeThreshold=.2;_longPressTimeThreshold=1;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]}getGamepad(e=0){return typeof navigator<"u"&&"getGamepads"in navigator&&navigator.getGamepads()[e]||null}_setCursorTypes=[];setCursorPointer(){this.setCursor("pointer")}setCursorNormal(){this.unsetCursor("pointer")}setCursor(e){this._setCursorTypes.push(e),this._setCursorTypes.length>10&&this._setCursorTypes.shift(),this.updateCursor()}unsetCursor(e){for(let t=this._setCursorTypes.length-1;t>=0;t--)if(this._setCursorTypes[t]===e){this._setCursorTypes.splice(t,1),this.updateCursor();break}}updateCursor(){this._setCursorTypes?.length==0?this.context.domElement.style.cursor="default":this.context.domElement.style.cursor=this._setCursorTypes[this._setCursorTypes.length-1]}getIsPointerIdInUse(e){for(const t of this._pointerEventsPressed)if(t.pointerId===e&&t.used)return!0;return!1}getPointerPressedCount(){let e=0;for(let t=0;t<this._pointerPressed.length;t++)this._pointerPressed[t]&&e++;return e}getPointerPosition(e){return e>=this._pointerPositions.length?null:this._pointerPositions[e]}getPointerPositionLastFrame(e){return e>=this._pointerPositionsLastFrame.length?null:this._pointerPositionsLastFrame[e]}getPointerPositionDelta(e){return e>=this._pointerPositionsDelta.length?null:this._pointerPositionsDelta[e]}getPointerPositionRC(e){return e>=this._pointerPositionsRC.length?null:this._pointerPositionsRC[e]}getPointerDown(e){return e>=this._pointerDown.length?!1:this._pointerDown[e]}getPointerUp(e){return e>=this._pointerUp.length?!1:this._pointerUp[e]}getPointerPressed(e){return e>=this._pointerPressed.length?!1:this._pointerPressed[e]}getPointerClicked(e){return e>=this._pointerClick.length?!1:this._pointerClick[e]}getPointerDoubleClicked(e){return e>=this._pointerDoubleClick.length?!1:this._pointerDoubleClick[e]}getPointerDownTime(e){return e>=this._pointerDownTime.length?-1:this._pointerDownTime[e]}getPointerUpTime(e){return e>=this._pointerUpTime.length?-1:this._pointerUpTime[e]}getPointerLongPress(e){return e>=this._pointerDownTime.length?!1:this.getPointerPressed(e)&&this.context.time.time-this._pointerDownTime[e]>this._longPressTimeThreshold}getIsMouse(e){return e<0||e>=this._pointerTypes.length?!1:this._pointerTypes[e]==="mouse"}getIsTouch(e){return e<0||e>=this._pointerTypes.length?!1:this._pointerTypes[e]==="touch"}getTouchesPressedCount(){let e=0;for(let t=0;t<this._pointerPressed.length;t++)this._pointerPressed[t]&&this.getIsTouch(t)&&e++;return e}getMouseWheelChanged(e=0){return e>=this._mouseWheelChanged.length?!1:this._mouseWheelChanged[e]}getMouseWheelDeltaY(e=0){return e>=this._mouseWheelDeltaY.length?0:this._mouseWheelDeltaY[e]}getPointerEvent(e){if(!(e>=this._pointerEvent.length))return this._pointerEvent[e]??void 0}*foreachPointerId(e){for(let t=0;t<this._pointerTypes.length;t++)if(this._pointerIsActive(t)){if(e!==void 0){const i=this._pointerTypes[t];if(Array.isArray(e)){let n=!1;for(const o of e)if(i===o){n=!0;break}if(!n)continue}else if(e!==i)continue}yield t}}*foreachTouchId(){for(let e=0;e<this._pointerTypes.length;e++)this._pointerTypes[e]==="touch"&&this._pointerIsActive[e]&&(yield e)}_pointerIsActive(e){return e<0?!1:this._pointerPressed[e]||this._pointerDown[e]||this._pointerUp[e]}context;_pointerDown=[!1];_pointerUp=[!1];_pointerClick=[!1];_pointerDoubleClick=[!1];_pointerPressed=[!1];_pointerPositions=[new c.Vector2];_pointerPositionsLastFrame=[new c.Vector2];_pointerPositionsDelta=[new c.Vector2];_pointerPositionsRC=[new c.Vector2];_pointerPositionDown=[new c.Vector3];_pointerDownTime=[];_pointerUpTime=[];_pointerUpTimestamp=[];_pointerIds=[];_pointerTypes=[""];_mouseWheelChanged=[!1];_mouseWheelDeltaY=[0];_pointerEvent=[];_pointerEventsPressed=[];_pointerSpace=[];_pressedStack=new Map;onDownButton(e,t){let i=this._pressedStack.get(e);i||(i=[],this._pressedStack.set(e,i)),i.push(t)}onReleaseButton(e,t){const i=this._pressedStack.get(e);if(!i)return;const n=i.indexOf(t);n>=0&&i.splice(n,1)}getFirstPressedButtonForPointer(e){const t=this._pressedStack.get(e);if(t)return t[0]}getLatestPressedButtonForPointer(e){const t=this._pressedStack.get(e);if(t)return t[t.length-1]}getKeyDown(e){if(e!==void 0)return this.isKeyDown(e);for(const t in this.keysPressed){const i=this.keysPressed[t];if(i.startFrame===this.context.time.frameCount)return i.key}return null}getKeyPressed(e){if(e!==void 0)return this.isKeyPressed(e);for(const t in this.keysPressed){const i=this.keysPressed[t];if(i.pressed)return i.key}return null}getKeyUp(e){if(e!==void 0)return this.isKeyUp(e);for(const t in this.keysPressed){const i=this.keysPressed[t];return i.pressed===!1&&i.frame===this.context.time.frameCount}return null}isKeyDown(e){if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const t=this.getCodeForCommonKeyName(e);if(t!==null){for(const n of t)if(this.isKeyDown(n))return!0;return!1}const i=this.keysPressed[e];return i?i.startFrame===this.context.time.frameCount&&i.pressed:!1}isKeyUp(e){if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const t=this.getCodeForCommonKeyName(e);if(t!==null){for(const n of t)if(this.isKeyUp(n))return!0;return!1}const i=this.keysPressed[e];return i?i.frame===this.context.time.frameCount&&i.pressed===!1:!1}isKeyPressed(e){if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const t=this.getCodeForCommonKeyName(e);if(t!==null){for(const n of t)if(this.isKeyPressed(n))return!0;return!1}const i=this.keysPressed[e];return i&&i.pressed||!1}getCodeForCommonKeyName(e){if(e.length===1){if(e>="0"&&e<="9")return["Digit"+e];if(e>="a"&&e<="z")return["Key"+e.toUpperCase()];if(e==" ")return["Space"]}switch(e){case"shift":case"Shift":return["ShiftLeft","ShiftRight"];case"control":case"Control":return["ControlLeft","ControlRight"];case"alt":case"Alt":return["AltLeft","AltRight"]}return null}createInputEvent(e){switch(e.type){case"pointerdown":He&&Se("Create Pointer down"),this.onDownButton(e.deviceIndex,e.button),this.onDown(e);break;case"pointermove":He&&Se("Create Pointer move"),this.onMove(e);break;case"pointerup":He&&Se("Create Pointer up"),this.onUp(e),this.onReleaseButton(e.deviceIndex,e.button);break}}convertScreenspaceToRaycastSpace(e){return e.x=(e.x-this.context.domX)/this.context.domWidth*2-1,e.y=-((e.y-this.context.domY)/this.context.domHeight)*2+1,e}constructor(e){this.context=e,this.context.post_render_callbacks.push(this.onEndOfFrame)}_htmlEventSource;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(){for(const e in this._eventListeners)this._eventListeners[e].length=0;window.removeEventListener("contextmenu",this.onContextMenu),this._htmlEventSource?.removeEventListener("pointerdown",this.onPointerDown),window.removeEventListener("pointermove",this.onPointerMove),window.removeEventListener("pointerup",this.onPointerUp),window.removeEventListener("pointercancel",this.onPointerCancel),window.removeEventListener("touchstart",this.onTouchStart),window.removeEventListener("touchmove",this.onTouchMove),window.removeEventListener("touchend",this.onTouchEnd),this._htmlEventSource?.removeEventListener("wheel",this.onMouseWheel,!1),window.removeEventListener("wheel",this.onWheelWindow,!1),window.removeEventListener("keydown",this.onKeyDown,!1),window.removeEventListener("keypress",this.onKeyPressed,!1),window.removeEventListener("keyup",this.onKeyUp,!1),window.removeEventListener("blur",this.onLostFocus)}dispose(){const e=this.context.post_render_callbacks.indexOf(this.onEndOfFrame);e>=0&&this.context.post_render_callbacks.splice(e,1),this.unbindEvents()}onLostFocus=()=>{for(const e in this.keysPressed)this.keysPressed[e].pressed=!1};_receivedPointerMoveEventsThisFrame=new Array;onEndOfFrame=()=>{this._receivedPointerMoveEventsThisFrame.length=0;for(let e=0;e<this._pointerUp.length;e++)this._pointerUp[e]=!1;for(let e=0;e<this._pointerDown.length;e++)this._pointerDown[e]=!1;for(let e=0;e<this._pointerClick.length;e++)this._pointerClick[e]=!1;for(let e=0;e<this._pointerDoubleClick.length;e++)this._pointerDoubleClick[e]=!1;for(const e of this._pointerPositionsDelta)e.set(0,0);for(let e=0;e<this._mouseWheelChanged.length;e++)this._mouseWheelChanged[e]=!1;for(let e=0;e<this._mouseWheelDeltaY.length;e++)this._mouseWheelDeltaY[e]=0};canReceiveInput(e){return e.target===this.context.renderer?.domElement||e.target===this.context.domElement||this.context.isInAR||this.context.isInAR&&e.target===document.body&&exports.DeviceUtilities.isMozillaXR()?!0:(He&&console.warn("CanReceiveInput:False for",e.target),!1)}onContextMenu=e=>{this.canReceiveInput(e)!==!1&&e instanceof PointerEvent&&e.pointerType};keysPressed={};onKeyDown=e=>{if(He&&console.log(`key down ${e.code}, ${this.context.application.hasFocus}`,e),!this.context.application.hasFocus)return;const t=this.keysPressed[e.code];if(t&&t.pressed)return;this.keysPressed[e.code]={pressed:!0,frame:this.context.time.frameCount+1,startFrame:this.context.time.frameCount+1,key:e.key,code:e.code};const i=new nl("keydown",e,e);this.onDispatchEvent(i)};onKeyPressed=e=>{if(!this.context.application.hasFocus)return;const t=this.keysPressed[e.code];if(!t)return;t.pressed=!0,t.frame=this.context.time.frameCount+1;const i=new nl("keypress",e,e);this.onDispatchEvent(i)};onKeyUp=e=>{if(!this.context.application.hasFocus)return;const t=this.keysPressed[e.code];if(!t)return;t.pressed=!1,t.frame=this.context.time.frameCount+1;const i=new nl("keyup",e,e);this.onDispatchEvent(i)};onWheelWindow=e=>{document.pointerLockElement&&this.onMouseWheel(e)};onMouseWheel=e=>{if(this.canReceiveInput(e)===!1)return;this._mouseWheelDeltaY.length<=0&&this._mouseWheelDeltaY.push(0),this._mouseWheelChanged.length<=0&&this._mouseWheelChanged.push(!1),this._mouseWheelChanged[0]=!0;const t=this._mouseWheelDeltaY[0];this._mouseWheelDeltaY[0]=t+e.deltaY};onPointerDown=e=>{if(this.context.isInAR||this.canReceiveInput(e)===!1)return;e.target instanceof HTMLElement&&e.target.setPointerCapture(e.pointerId);const t=this.getPointerId(e);He&&Se(`pointer down #${t}, identifier:${e.pointerId}`);const i=this.getAndUpdateSpatialObjectForScreenPosition(t,e.clientX,e.clientY),n=new Yn("pointerdown",e,{origin:this,mode:"screen",deviceIndex:0,pointerId:t,button:e.button,clientX:e.clientX,clientY:e.clientY,pointerType:e.pointerType,buttonName:this.getButtonName(e),device:i,pressure:e.pressure});this.onDown(n)};onPointerMove=e=>{if(this.context.isInAR||this._receivedPointerMoveEventsThisFrame.includes(e.pointerId))return;this._receivedPointerMoveEventsThisFrame.push(e.pointerId);let t=e.button;e.pointerType==="mouse"&&(t=this.getFirstPressedButtonForPointer(0)??0);const i=this.getPointerId(e,t);t===-1&&(t=i);const n=this.getAndUpdateSpatialObjectForScreenPosition(i,e.clientX,e.clientY),o=new Yn("pointermove",e,{origin:this,mode:"screen",deviceIndex:0,pointerId:i,button:t,clientX:e.clientX,clientY:e.clientY,pointerType:e.pointerType,buttonName:this.getButtonName(e),device:n,pressure:e.pressure});this.onMove(o)};onPointerCancel=e=>{this.context.isInAR||(He&&console.log("Pointer cancel",e),this.onPointerUp(e))};onPointerUp=e=>{if(this.context.isInAR)return;e.target instanceof HTMLElement&&e.target.releasePointerCapture(e.pointerId);const t=this.getPointerId(e),i=new Yn("pointerup",e,{origin:this,mode:"screen",deviceIndex:0,pointerId:t,button:e.button,clientX:e.clientX,clientY:e.clientY,pointerType:e.pointerType,buttonName:this.getButtonName(e),device:this.getAndUpdateSpatialObjectForScreenPosition(t,e.clientX,e.clientY),pressure:e.pressure});this.onUp(i),this._pointerIds[t]=-1,He&&console.log("ID="+t,"PointerId="+e.pointerId,"ALL:",[...this._pointerIds])};getPointerId(e,t){return e.pointerType==="mouse"?0+(t??e.button):this.getPointerIndex(e.pointerId)}getButtonName(e){const t=e.button;if(e.pointerType==="mouse")switch(t){case 0:return"left";case 1:return"middle";case 2:return"right"}return"unknown"}onTouchStart=e=>{if(this.context.isInAR)for(let t=0;t<e.changedTouches.length;t++){const i=e.changedTouches[t],n=this.getPointerIndex(i.identifier),o=this.getAndUpdateSpatialObjectForScreenPosition(n,i.clientX,i.clientY),r=new Yn("pointerdown",e,{origin:this,mode:"screen",deviceIndex:0,pointerId:n,button:0,clientX:i.clientX,clientY:i.clientY,pointerType:"touch",buttonName:"unknown",device:o,pressure:i.force});this.onDown(r)}};onTouchMove=e=>{if(this.context.isInAR)for(let t=0;t<e.changedTouches.length;t++){const i=e.changedTouches[t],n=this.getPointerIndex(i.identifier),o=this.getAndUpdateSpatialObjectForScreenPosition(n,i.clientX,i.clientY),r=new Yn("pointermove",e,{origin:this,mode:"screen",deviceIndex:0,pointerId:n,button:0,clientX:i.clientX,clientY:i.clientY,pointerType:"touch",buttonName:"unknown",device:o,pressure:i.force});this.onMove(r)}};onTouchEnd=e=>{if(this.context.isInAR)for(let t=0;t<e.changedTouches.length;t++){const i=e.changedTouches[t],n=this.getPointerIndex(i.identifier),o=new Yn("pointerup",e,{origin:this,mode:"screen",deviceIndex:0,pointerId:n,button:0,clientX:i.clientX,clientY:i.clientY,pointerType:"touch",buttonName:"unknown",device:this.getAndUpdateSpatialObjectForScreenPosition(n,i.clientX,i.clientY),pressure:i.force});this.onUp(o),this._pointerIds[n]=-1}};tempNearPlaneVector=new c.Vector3;tempFarPlaneVector=new c.Vector3;tempLookMatrix=new c.Matrix4;getAndUpdateSpatialObjectForScreenPosition(e,t,i){let n=this._pointerSpace[e];n||(n=new c.Object3D,this._pointerSpace[e]=n),this._pointerSpace[e]=n;const o=this.context.mainCamera;if(o){const r=this.tempNearPlaneVector.set(t,i,-1);this.convertScreenspaceToRaycastSpace(r);const a=this.tempFarPlaneVector.set(r.x,r.y,1);r.unproject(o),a.unproject(o);const l=o.worldUp||V(0,1,0).applyQuaternion(ue(o));this.tempLookMatrix.lookAt(a,r,l),n.position.set(r.x,r.y,r.z),n.quaternion.setFromRotationMatrix(this.tempLookMatrix)}return n}isInRect(e){if(this.context.isInXR)return!0;const t=this.context.domElement.getBoundingClientRect(),i=e.clientX,n=e.clientY,o=i>=t.x&&i<=t.right&&n>=t.y&&n<=t.bottom;return He&&!o&&console.log("Not in rect",t,i,n),o}onDown(e){const t=e.pointerId;if(this.getPointerPressed(t)&&console.warn(`Received pointerDown for pointerId that is already pressed: ${t}`,He?e:""),He&&console.log(e.pointerType,"DOWN",t),!!this.isInRect(e)){for(this.setPointerState(t,this._pointerPressed,!0),this.setPointerState(t,this._pointerDown,!0),this.setPointerStateT(t,this._pointerEvent,e.source);t>=this._pointerTypes.length;)this._pointerTypes.push(e.pointerType);for(this._pointerTypes[t]=e.pointerType;t>=this._pointerPositionDown.length;)this._pointerPositionDown.push(new c.Vector3);for(this._pointerPositionDown[t].set(e.clientX,e.clientY,e.clientZ??0);t>=this._pointerPositions.length;)this._pointerPositions.push(new c.Vector2);this._pointerPositions[t].set(e.clientX,e.clientY),t>=this._pointerDownTime.length&&this._pointerDownTime.push(0),this._pointerDownTime[t]=this.context.time.realtimeSinceStartup,this.updatePointerPosition(e),this._pointerEventsPressed.push(e),this.onDispatchEvent(e)}}onMove(e){const t=e.pointerId,i=this.getPointerPressed(t);i===!1&&!this.isInRect(e)||e.pointerType==="touch"&&!i||(this.updatePointerPosition(e),this.setPointerStateT(t,this._pointerEvent,e.source),this.onDispatchEvent(e))}onUp(e){const t=e.pointerId;if(!this.getPointerPressed(t)){He&&console.log(e.pointerType,"UP",t,"was not down");return}He&&console.log(e.pointerType,"UP",t),this.setPointerState(t,this._pointerPressed,!1),this.setPointerStateT(t,this._pointerEvent,e.source),this.setPointerState(t,this._pointerUp,!0),this.updatePointerPosition(e);for(let l=this._pointerEventsPressed.length-1;l>=0;l--)if(this._pointerEventsPressed[l].pointerId===t){this._pointerEventsPressed.splice(l,1);break}if(!this._pointerPositionDown[t]){He&&ce("Received pointer up event without matching down event for button: "+t),console.warn("Received pointer up event without matching down event for button: "+t);return}const n=this._pointerUpTime[t],o=this._pointerDownTime[t],r=this.context.time.realtimeSinceStartup,a=r-o;if(t>=this._pointerUpTime.length&&this._pointerUpTime.push(-99),this._pointerUpTime[t]=r,a<1){let l=e.clientX-this._pointerPositionDown[t].x,h=e.clientY-this._pointerPositionDown[t].y,d=0;if(e.isSpatial&&e.clientZ!=null&&(d=e.clientZ-this._pointerPositionDown[t].z,l*=200,h*=200,d*=200),Math.abs(l)<5&&Math.abs(h)<5&&Math.abs(d)<5){this.setPointerState(t,this._pointerClick,!0),e.isClick=!0;const u=r-n;He&&console.log("CLICK",t,l,h,d,u),u<this._doubleClickTimeThreshold&&u>0&&(this.setPointerState(t,this._pointerDoubleClick,!0),e.isDoubleClick=!0)}}this.onDispatchEvent(e)}updatePointerPosition(e){const t=e.pointerId;for(;t>=this._pointerPositions.length;)this._pointerPositions.push(new c.Vector2);for(;t>=this._pointerPositionsLastFrame.length;)this._pointerPositionsLastFrame.push(new c.Vector2);for(;t>=this._pointerPositionsDelta.length;)this._pointerPositionsDelta.push(new c.Vector2);const i=this._pointerPositionsLastFrame[t];i.copy(this._pointerPositions[t]);const n=this._pointerPositionsDelta[t];let o=e.clientX-i.x,r=e.clientY-i.y;if(e.source instanceof MouseEvent||e.source instanceof TouchEvent){const d=e.source;o===0&&d.movementX!==0&&(o=d.movementX||0),r===0&&d.movementY!==0&&(r=d.movementY||0)}n.x+=o,n.y+=r,this._pointerPositions[t].x=e.clientX,this._pointerPositions[t].y=e.clientY;const a=e.clientX,l=e.clientY;for(;t>=this._pointerPositionsRC.length;)this._pointerPositionsRC.push(new c.Vector2);const h=this._pointerPositionsRC[t];h.set(a,l),this.convertScreenspaceToRaycastSpace(h)}getPointerIndex(e){let t=-1;for(let i=0;i<this._pointerIds.length;i++){if(this._pointerIds[i]===e)return i;t===-1&&this._pointerIds[i]===-1&&(t=i)}return t!==-1?(this._pointerIds[t]=e,t):(He&&console.log("PUSH pointerId:",e),this._pointerIds.push(e),this._pointerIds.length-1)}setPointerState(e,t,i){t[e]=i}setPointerStateT(e,t,i){return t[e]=i,i}onDispatchEvent(e){const t=U.Current;try{U.Current=this.context,this.dispatchEvent(e)}finally{U.Current=t}}}const Wr=new c.Matrix4().makeRotationY(Math.PI),ki=new c.Quaternion().setFromAxisAngle(new c.Vector3(0,1,0),Math.PI),iS=w("debugwebxr");class nS{priority=-1e5;gameObject;isXRRig(){return!0}get isActive(){return this.gameObject.visible}constructor(){if(this.gameObject=new c.Object3D,this.gameObject.name="Implicit XR Rig",iS){const e=nm(16733661);e.position.y+=.5,this.gameObject.add(e)}}}const zn=w("debugwebxr"),Jc=w("debugcustomgesture"),sS="https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles",oS="generic-trigger",rS=new c.Quaternion().setFromEuler(new c.Euler(c.MathUtils.degToRad(0),c.MathUtils.degToRad(-90),c.MathUtils.degToRad(-90))),aS=new c.Vector3(.04,-.04,0);class Kp{xr;get context(){return this.xr.context}inputSource;index=0;emitEvents=!0;get connected(){return this._connected}_connected=!0;get isTracking(){return this._isTracking}_isTracking=!1;get gamepad(){return this.__gamepad??=this.inputSource.gamepad}__gamepad;get isHand(){return this.hand!=null}get hand(){return this.__hand??=this.inputSource.hand}__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.inputSource.handedness}__side=void 0;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)}_hitTestSource=void 0;_hasSelectEvent=!1;get hasSelectEvent(){return this._hasSelectEvent}_isMxInk=!1;_isMetaQuestTouchController=!1;getHitTest(){return this.xr.getHitTest(this)}_handJointPoses=new Map;getHandJointPose(e,t){if(t=t||this.xr.frame,!this.hand||!t?.getJointPose||!this.xr.referenceSpace)return null;let i=this._handJointPoses?.get(e);return i||(i=t.getJointPose(e,this.xr.referenceSpace),i&&this._handJointPoses.set(e,i),i)}_gripMatrix=new c.Matrix4;_gripPosition=new c.Vector3;_gripQuaternion=new c.Quaternion;_linearVelocity=new c.Vector3;_rayPositionRaw=new c.Vector3;_rayRotationRaw=new c.Quaternion;_rayMatrix=new c.Matrix4;_rayPosition=new c.Vector3;_rayQuaternion=new c.Quaternion;get gripPosition(){return V(this._gripPosition)}get gripQuaternion(){return Xi(this._gripQuaternion)}get gripMatrix(){return this._gripMatrix}get gripLinearVelocity(){return V(this._linearVelocity).applyQuaternion(ki)}get rayPosition(){return V(this._rayPosition)}get rayQuaternion(){return Xi(this._rayQuaternion)}get gripWorldPosition(){return V(this._gripWorldPosition)}_gripWorldPosition=new c.Vector3;get gripWorldQuaternion(){return Xi(this._gripWorldQuaternion)}_gripWorldQuaternion=new c.Quaternion;get rayWorldPosition(){return V(this._rayWorldPosition)}_rayWorldPosition=new c.Vector3;updateRayWorldPosition(){const e=this.xr.context.mainCamera?.parent;this._rayWorldPosition.copy(this._rayPositionRaw),e&&this._rayWorldPosition.applyMatrix4(e.matrixWorld)}get rayWorldQuaternion(){return Xi(this._rayWorldQuaternion)}_rayWorldQuaternion=new c.Quaternion;get pinchPosition(){return V(this._pinchPosition)}_pinchPosition=new c.Vector3;updateRayWorldQuaternion(){const e=this.xr.context.mainCamera?.parent,t=e?ue(e):void 0;this._rayWorldQuaternion.copy(this._rayRotationRaw).multiply(ki),t&&this._rayWorldQuaternion.premultiply(t)}get ray(){return this._ray.origin.copy(this.rayWorldPosition),this._ray.direction.copy(V(0,0,1).applyQuaternion(this.rayWorldQuaternion)),this._ray}_ray;_hand_wristDotUp=void 0;get handWristDotUp(){if(this._hand_wristDotUp!==void 0)return this._hand_wristDotUp;const e=this.handObject?.joints.wrist;if(e){const t=V(0,1,0).applyQuaternion(e.quaternion),i=V(0,1,0).dot(t);return this._hand_wristDotUp=i}}get isHandUpsideDown(){return this.handWristDotUp!==void 0?this.handWristDotUp<-.7:!1}get isTeleportGesture(){return this.isHandUpsideDown&&this.getGesture("pinch")?.isDown}get object(){return this._object}_object;_gripSpaceObject;_raySpaceObject;model=null;_debugAxesHelper=new c.AxesHelper(.15);_debugGripAxesHelper=new c.AxesHelper(.07);_debugRayAxesHelper=new c.AxesHelper(.07);async getModelUrl(){return this.getMotionController?.then(e=>e?.assetUrl||null)}constructor(e,t,i){this.xr=e,this.inputSource=t,this.index=i,this._object=new c.Object3D,this._object.name=`NeedleXRController_${i}`,zn&&(this._object.add(this._debugAxesHelper),this._gripSpaceObject=new c.Object3D,this._raySpaceObject=new c.Object3D,this._gripSpaceObject.name=`NeedleXRController_${i}_gripSpace`,this._raySpaceObject.name=`NeedleXRController_${i}_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 c.Ray,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()}_hitTestSourcePromise=null;_requestHitTestSource(){return this._hitTestSourcePromise?this._hitTestSourcePromise:this.xr.mode==="immersive-ar"&&this.inputSource.targetRayMode==="tracked-pointer"&&this.xr.session.requestHitTestSourceForTransientInput?this._hitTestSourcePromise=this.xr.session.requestHitTestSourceForTransientInput({profile:this.inputSource.profiles[0],offsetRay:new XRRay})?.then(e=>(this._hitTestSourcePromise=null,this.connected?this._hitTestSource=e:(e.cancel(),null)))??null:null}onPointerHits=e=>{};onUpdate(e){this.onUpdateFrame(e),this.updateInputEvents(),this.onUpdateMove()}onRenderDebug(){j.DrawSphere(this.rayWorldPosition,.003),j.DrawDirection(this.rayWorldPosition,V(0,0,10).applyQuaternion(this.rayWorldQuaternion));const t=(this.inputSource.gripSpace?this.gripWorldPosition:this.object.worldPosition).sub(this.object.worldForward.multiplyScalar(.1)),i=this.inputSource.profiles.join(`
147
147
  `);let n=`Controller[${this.index}] (${this.inputSource.targetRayMode}, ${this.side})
148
148
  C:${this.connected?"x":"-"} T:${this.isTracking?"x":"-"} Hand:${this.inputSource.hand?"x":"-"} Pen: ${this._isMxInk?"x":"-"}`;if(this.inputSource.hand&&(n+=`
@@ -159,11 +159,11 @@ To unregister you can call the function returned by your event hook (e.g.const u
159
159
 
160
160
  or by using the once option like onStart(()=>{}, { once:true }).
161
161
 
162
- See https://engine.needle.tools/docs/scripting.html#special-lifecycle-hooks for more information.`))}}function Js(s,e){const t=Ur.get(e);if(t){for(let n=0;n<t.length;n++)if(t[n].method===s){t.splice(n,1);return}}const i=Gr.get(e);if(i){for(let n=0;n<i.length;n++)if(i[n].method===s){i.splice(n,1);return}}}function hn(s,e){e===oe.ContextCreated&&Qf.delete(s),Rb(s,e)}function Rb(s,e){e===pe.Start&&Gr.get(oe.ContextCreated)&&Rb(s,oe.ContextCreated);const t=e===pe.Start||e===oe.ContextCreated,i=Ur.get(e);i&&i.length>0&&hy(s,i,t);const n=Gr.get(e);if(n&&n.length>0){const o=[...n];n.length=0,hy(s,o,t),o.length>0&&(Ur.has(e)||Ur.set(e,new Array),Ur.get(e).push(...o))}}const eh=new Array,cy={context:null};function hy(s,e,t){eh.length=0;for(let n=0;n<e.length;n++)eh.push(e[n]);let i=Qf.get(s);for(let n=0;n<eh.length;n++){const o=eh[n];let r=!0;if(i&&i.has(o)&&(r=!1),r)try{cy.context=s,o.method?.call(cy,s)}catch(a){console.error("Error in lifecycle method",a)}if(o.options?.once){for(let a=0;a<e.length;a++)if(e[a]===o){e.splice(a,1);break}}else t&&(i||(i=new Set,Qf.set(s,i)),i.add(o))}}const Qf=new WeakMap,Zp={};function Jp(s,e){Zp[s]=e}function Eb(s){const e=s.getBufferIdentifier(),t=Zp[e];return t(s)}function Tb(s){return typeof s.guid=="function"?s.guid():null}let em;function lS(){return em}function cS(s){em=s}function Ab(s,e){return e||(e={}),e={...em,...e},s?new se.$70d766613f57b014$export$2e2bcd8739ae039(s,e):new se.$70d766613f57b014$export$2e2bcd8739ae039(e)}async function dy(){const s=await Promise.resolve().then(()=>require("./vendor-Cty8Dnri.umd.cjs")).then(e=>e.bundler);return console.log(s),s.default===void 0?s:s.default}class Lb{get isHost(){return this._host!==void 0}_host;_client;_clientData;constructor(){this.onEnable()}onEnable(){this.trySetupHost("HOST-5980e65c-8438-453e-8b35-f13c736dcd81")}async trySetupHost(e){const t=await dy(),i=new t(e);i.on("error",n=>{console.error(n),this._host=void 0,this.trySetupClient(e)}),i.on("open",n=>{this._host=new dS(i)})}async trySetupClient(e){const t=await dy();this._client=new t,this._client.on("error",i=>{console.error("Client error",i)}),this._client.on("open",i=>{console.log("client connected",i),this._clientData=this._client.connect(e,{metadata:{id:i}}),this._clientData.on("open",()=>{console.log("Connected to host")}),this._clientData.on("data",n=>{console.log("<<",n)})})}}class hS{_peer;constructor(e){this._peer=e}}class dS extends hS{get isHost(){return!0}_connections=[];constructor(e){super(e),console.log("I AM THE HOST"),this._peer?.on("connection",this.onConnection.bind(this)),this._peer.on("close",()=>{this.broadcast("BYE")}),setInterval(()=>{this.broadcast("HELLO")},2e3)}onConnection(e){console.log("host connection",e),e.on("open",()=>{this._connections.push(e),this.broadcastConnection(e)})}broadcastConnection(e){const t=this._connections.map(i=>i.metadata?.id).filter(i=>i!==void 0);this.broadcast({type:"connection-list",connections:t})}broadcast(e){if(e!=null){console.log(">>",e);for(const t in this._peer.connections){const i=this._peer.connections[t];if(i)if(Array.isArray(i))for(const n of i)n&&n.send(e);else console.warn(i)}}}}var Yi=(s=>(s[s.OnConnection=0]="OnConnection",s[s.OnRoomJoin=1]="OnRoomJoin",s[s.Queued=2]="Queued",s[s.Immediate=3]="Immediate",s))(Yi||{});const uy="https://urls.needle.tools/default-networking-backend/index";let wi="wss://networking.needle.tools/socket";const Ut=!!w("debugnet"),sl=!!(Ut||w("debugowner")),th=w("debugnetbin");var Db=(s=>(s.ConnectionInfo="connection-start-info",s))(Db||{}),Q=(s=>(s.Join="join-room",s.Leave="leave-room",s.JoinedRoom="joined-room",s.LeftRoom="left-room",s.UserJoinedRoom="user-joined-room",s.UserLeftRoom="user-left-room",s.RoomStateSent="room-state-sent",s))(Q||{});class uS{room;viewId;allowEditing;inRoom}class fS{room}class pS{userId}var Ib=(s=>(s.RequestHasOwner="request-has-owner",s.ResponseHasOwner="response-has-owner",s.RequestIsOwner="request-is-owner",s.ResponseIsOwner="response-is-owner",s.RequestOwnership="request-ownership",s.GainedOwnership="gained-ownership",s.RemoveOwnership="remove-ownership",s.LostOwnership="lost-ownership",s.GainedOwnershipBroadcast="gained-ownership-broadcast",s.LostOwnershipBroadcast="lost-ownership-broadcast",s))(Ib||{});class tm{guid;connection;get hasOwnership(){return this._hasOwnership}get isOwned(){return this._isOwned}get isConnected(){return this.connection.isConnected}_hasOwnership=!1;_isOwned=void 0;_gainSubscription;_lostSubscription;_hasOwnerResponse;constructor(e,t){this.connection=e,this.guid=t,this._gainSubscription=this.onGainedOwnership.bind(this),this._lostSubscription=this.onLostOwnership.bind(this),e.beginListen("lost-ownership",this._lostSubscription),e.beginListen("gained-ownership-broadcast",this._gainSubscription),this._hasOwnerResponse=this.onHasOwnerResponse.bind(this),e.beginListen("response-has-owner",this._hasOwnerResponse)}_isWaitingForOwnershipResponseCallback=null;updateIsOwned(){this.connection.send("request-has-owner",{guid:this.guid})}onHasOwnerResponse(e){e.guid===this.guid&&(this._isOwned=e.value)}requestOwnershipIfNotOwned(){return this._isWaitingForOwnershipResponseCallback!==null?this:(this._isWaitingForOwnershipResponseCallback=this.waitForHasOwnershipRequestResponse.bind(this),this.connection.beginListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this.connection.send("request-has-owner",{guid:this.guid}),this)}waitForHasOwnershipRequestResponse(e){e.guid===this.guid&&(this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this._isOwned=e.value,e.value||(sl&&console.log("request ownership",this.guid),this.requestOwnership()))}requestOwnershipAsync(){return new Promise((e,t)=>{this.requestOwnership();let i=0;const n=()=>{if(i++>10)return t("Timeout");setTimeout(()=>{this.hasOwnership?e(this):n()},100)};n()})}requestOwnership(){return sl&&console.log("Request ownership",this.guid),this.connection.send("request-ownership",{guid:this.guid}),this}freeOwnership(){return this.connection.send("remove-ownership",{guid:this.guid}),this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this}destroy(){this.connection.stopListen("gained-ownership",this._gainSubscription),this.connection.stopListen("lost-ownership",this._lostSubscription),this.connection.stopListen("response-has-owner",this._hasOwnerResponse),this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null)}onGainedOwnership(e){e.guid===this.guid&&(this._isOwned=!0,this.connection.connectionId===e.owner?(sl&&console.log("GAINED OWNERSHIP",this.guid),this._hasOwnership=!0):this._hasOwnership=!1)}onLostOwnership(e){e===this.guid&&(sl&&console.log("LOST OWNERSHIP",this.guid),this._hasOwnership=!1,this._isOwned=!1)}}class jb{context;_peer=null;constructor(e){this.context=e}get peer(){return this._peer||(this._peer=new Lb),this._peer}tryGetState(e){return e==="invalid"?null:this._state[e]}get connectionId(){return this._connectionId}get isDebugEnabled(){return Ut}get isConnected(){return this.connected}get currentRoomName(){return this._currentRoomName}get allowEditing(){return this._currentRoomAllowEditing}get currentRoomViewId(){return this._currentRoomViewId}getViewOnlyUrl(){if(this.currentRoomViewId===null)return null;const e=new URL(window.location.href);return e.searchParams.set("view",this.currentRoomViewId),e.href}get isInRoom(){return this._isInRoom}get currentLatency(){return this._currentDelay}get currentServerUrl(){return this._ws?.url??null}sendPing(){this.send("ping",{time:this.context.time.time})}userIsInRoom(e){return this._currentInRoom.indexOf(e)!==-1}_usersInRoomCopy=[];usersInRoom(e=null){e||(e=this._usersInRoomCopy),e.length=0;for(const t of this._currentInRoom)e.push(t);return e}joinRoom(e,t=!1){return e?e.length>1024?(console.error('Room name too long, can not join: "'+e+'". Max length is 1024 characters.'),!1):(this.isInRoom&&this.currentRoomName!==e&&console.warn("Needle Engine is already connected to a networking room. Connecting to multiple rooms is not supported"),this.connect(),Ut&&console.log("join: "+e),this.send("join-room",{room:e,viewOnly:t},Yi.OnConnection),!0):(console.error('Missing room name, can not join: "'+e+'"'),!1)}leaveRoom(e=null){return e||(e=this.currentRoomName),e?(this.send("leave-room",{room:e}),!0):(console.error('Missing room name, can not join: "'+e+'"'),!1)}send(e,t=null,i=Yi.Queued){if(t===null&&(t={}),i===Yi.Queued){this._defaultMessagesBuffer.push({key:e,value:t});return}return this.sendWithWebsocket(e,t,i)}sendDeleteRemoteState(e){this.send("delete-state",{guid:e,dontSave:!0}),delete this._state[e]}sendDeleteRemoteStateAll(){this.send("delete-all-state"),this._state={}}sendBinary(e){th&&console.log("<< send binary",this.context.time.frame,e.length/1024+" KB"),this._ws?.send(e)}_defaultMessagesBuffer=[];_defaultMessagesBufferArray=[];sendBufferedMessagesNow(){if(!this._ws)return;this._defaultMessagesBufferArray.length=0;const e=Object.keys(this._defaultMessagesBuffer).length;for(const i in this._defaultMessagesBuffer){const n=this._defaultMessagesBuffer[i];if(e<=1){this.sendWithWebsocket(n.key,n.value,Yi.Immediate);break}const o=this.toMessage(n.key,n.value);this._defaultMessagesBufferArray.push(o)}if(this._defaultMessagesBuffer.length=0,this._defaultMessagesBufferArray.length>0&&Ut&&console.log("SEND BUFFERED",this._defaultMessagesBufferArray.length),this._defaultMessagesBufferArray.length<=0)return;const t=JSON.stringify(this._defaultMessagesBufferArray);this._ws?.send(t)}beginListen(e,t){return this._listeners[e]||(this._listeners[e]=[]),this._listeners[e].push(t),t}stopListening(e,t){return this.stopListen(e,t)}stopListen(e,t){if(!t||!this._listeners[e])return;const i=this._listeners[e].indexOf(t);i>=0&&this._listeners[e].splice(i,1)}beginListenBinary(e,t){return this._listenersBinary[e]||(this._listenersBinary[e]=[]),this._listenersBinary[e].push(t),t}stopListenBinary(e,t){if(!this._listenersBinary[e])return;const i=this._listenersBinary[e].indexOf(t);i>=0&&this._listenersBinary[e].splice(i,1)}netWebSocketUrlProvider;registerProvider(e){this.netWebSocketUrlProvider=e}async connect(e){if(this.connected&&e&&e!==wi)return Promise.reject("Can not connect to different server url. Please disconnect first.");if(this.connected)return Promise.resolve(!0);e&&console.debug("Connecting to user provided url "+e);const t=e||this.netWebSocketUrlProvider?.getWebsocketUrl();return t?wi=t:W_()&&(wi="wss://"+window.location.host+"/socket"),this.connectWebsocket()}disconnect(){this._ws?.close(),this._ws=void 0,wi=void 0,this._currentRoomAllowEditing=!0,this._currentRoomName=null,this._currentRoomViewId=null,this._isInRoom=!1,this._currentInRoom.length=0,this._state={},this._currentDelay=-1}_listeners={};_listenersBinary={};connected=!1;channelId;_connectionId=null;_ws;_waitingForSocket={};_isInRoom=!1;_currentRoomName=null;_currentRoomViewId=null;_currentRoomAllowEditing=!0;_currentInRoom=[];_state={};_currentDelay=-1;_connectingToWebsocketPromise=null;connectWebsocket(){return this._connectingToWebsocketPromise?this._connectingToWebsocketPromise:this._connectingToWebsocketPromise=new Promise(async(e,t)=>{let i=!1;const n=h=>{i||(i=!0,e(h))};if(wi===void 0&&(console.log("Fetch default backend url: "+uy),wi=await(await fetch(uy)).text()),wi===void 0){n(!1);return}console.debug(`⊡ Connecting to networking backend on
163
- `+wi);const o=await Promise.resolve().then(()=>require("./vendor-Cty8Dnri.umd.cjs")).then(h=>h.index),r=o.default?.WebsocketBuilder??o.WebsocketBuilder,a=o.default?.ExponentialBackoff??o.ExponentialBackoff,l=new r(wi).withMaxRetries(10).withBackoff(new a(2e3,4)).onOpen(()=>{this._connectingToWebsocketPromise=null,this._ws=l,this.connected=!0,A()||Ut?console.log(`⊞ Connected to networking backend
162
+ See https://engine.needle.tools/docs/scripting.html#special-lifecycle-hooks for more information.`))}}function Js(s,e){const t=Ur.get(e);if(t){for(let n=0;n<t.length;n++)if(t[n].method===s){t.splice(n,1);return}}const i=Gr.get(e);if(i){for(let n=0;n<i.length;n++)if(i[n].method===s){i.splice(n,1);return}}}function hn(s,e){e===oe.ContextCreated&&Qf.delete(s),Rb(s,e)}function Rb(s,e){e===pe.Start&&Gr.get(oe.ContextCreated)&&Rb(s,oe.ContextCreated);const t=e===pe.Start||e===oe.ContextCreated,i=Ur.get(e);i&&i.length>0&&hy(s,i,t);const n=Gr.get(e);if(n&&n.length>0){const o=[...n];n.length=0,hy(s,o,t),o.length>0&&(Ur.has(e)||Ur.set(e,new Array),Ur.get(e).push(...o))}}const eh=new Array,cy={context:null};function hy(s,e,t){eh.length=0;for(let n=0;n<e.length;n++)eh.push(e[n]);let i=Qf.get(s);for(let n=0;n<eh.length;n++){const o=eh[n];let r=!0;if(i&&i.has(o)&&(r=!1),r)try{cy.context=s,o.method?.call(cy,s)}catch(a){console.error("Error in lifecycle method",a)}if(o.options?.once){for(let a=0;a<e.length;a++)if(e[a]===o){e.splice(a,1);break}}else t&&(i||(i=new Set,Qf.set(s,i)),i.add(o))}}const Qf=new WeakMap,Zp={};function Jp(s,e){Zp[s]=e}function Eb(s){const e=s.getBufferIdentifier(),t=Zp[e];return t(s)}function Tb(s){return typeof s.guid=="function"?s.guid():null}let em;function lS(){return em}function cS(s){em=s}function Ab(s,e){return e||(e={}),e={...em,...e},s?new se.$70d766613f57b014$export$2e2bcd8739ae039(s,e):new se.$70d766613f57b014$export$2e2bcd8739ae039(e)}async function dy(){const s=await Promise.resolve().then(()=>require("./vendor-D51IT5ns.umd.cjs")).then(e=>e.bundler);return console.log(s),s.default===void 0?s:s.default}class Lb{get isHost(){return this._host!==void 0}_host;_client;_clientData;constructor(){this.onEnable()}onEnable(){this.trySetupHost("HOST-5980e65c-8438-453e-8b35-f13c736dcd81")}async trySetupHost(e){const t=await dy(),i=new t(e);i.on("error",n=>{console.error(n),this._host=void 0,this.trySetupClient(e)}),i.on("open",n=>{this._host=new dS(i)})}async trySetupClient(e){const t=await dy();this._client=new t,this._client.on("error",i=>{console.error("Client error",i)}),this._client.on("open",i=>{console.log("client connected",i),this._clientData=this._client.connect(e,{metadata:{id:i}}),this._clientData.on("open",()=>{console.log("Connected to host")}),this._clientData.on("data",n=>{console.log("<<",n)})})}}class hS{_peer;constructor(e){this._peer=e}}class dS extends hS{get isHost(){return!0}_connections=[];constructor(e){super(e),console.log("I AM THE HOST"),this._peer?.on("connection",this.onConnection.bind(this)),this._peer.on("close",()=>{this.broadcast("BYE")}),setInterval(()=>{this.broadcast("HELLO")},2e3)}onConnection(e){console.log("host connection",e),e.on("open",()=>{this._connections.push(e),this.broadcastConnection(e)})}broadcastConnection(e){const t=this._connections.map(i=>i.metadata?.id).filter(i=>i!==void 0);this.broadcast({type:"connection-list",connections:t})}broadcast(e){if(e!=null){console.log(">>",e);for(const t in this._peer.connections){const i=this._peer.connections[t];if(i)if(Array.isArray(i))for(const n of i)n&&n.send(e);else console.warn(i)}}}}var Yi=(s=>(s[s.OnConnection=0]="OnConnection",s[s.OnRoomJoin=1]="OnRoomJoin",s[s.Queued=2]="Queued",s[s.Immediate=3]="Immediate",s))(Yi||{});const uy="https://urls.needle.tools/default-networking-backend/index";let wi="wss://networking.needle.tools/socket";const Ut=!!w("debugnet"),sl=!!(Ut||w("debugowner")),th=w("debugnetbin");var Db=(s=>(s.ConnectionInfo="connection-start-info",s))(Db||{}),Q=(s=>(s.Join="join-room",s.Leave="leave-room",s.JoinedRoom="joined-room",s.LeftRoom="left-room",s.UserJoinedRoom="user-joined-room",s.UserLeftRoom="user-left-room",s.RoomStateSent="room-state-sent",s))(Q||{});class uS{room;viewId;allowEditing;inRoom}class fS{room}class pS{userId}var Ib=(s=>(s.RequestHasOwner="request-has-owner",s.ResponseHasOwner="response-has-owner",s.RequestIsOwner="request-is-owner",s.ResponseIsOwner="response-is-owner",s.RequestOwnership="request-ownership",s.GainedOwnership="gained-ownership",s.RemoveOwnership="remove-ownership",s.LostOwnership="lost-ownership",s.GainedOwnershipBroadcast="gained-ownership-broadcast",s.LostOwnershipBroadcast="lost-ownership-broadcast",s))(Ib||{});class tm{guid;connection;get hasOwnership(){return this._hasOwnership}get isOwned(){return this._isOwned}get isConnected(){return this.connection.isConnected}_hasOwnership=!1;_isOwned=void 0;_gainSubscription;_lostSubscription;_hasOwnerResponse;constructor(e,t){this.connection=e,this.guid=t,this._gainSubscription=this.onGainedOwnership.bind(this),this._lostSubscription=this.onLostOwnership.bind(this),e.beginListen("lost-ownership",this._lostSubscription),e.beginListen("gained-ownership-broadcast",this._gainSubscription),this._hasOwnerResponse=this.onHasOwnerResponse.bind(this),e.beginListen("response-has-owner",this._hasOwnerResponse)}_isWaitingForOwnershipResponseCallback=null;updateIsOwned(){this.connection.send("request-has-owner",{guid:this.guid})}onHasOwnerResponse(e){e.guid===this.guid&&(this._isOwned=e.value)}requestOwnershipIfNotOwned(){return this._isWaitingForOwnershipResponseCallback!==null?this:(this._isWaitingForOwnershipResponseCallback=this.waitForHasOwnershipRequestResponse.bind(this),this.connection.beginListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this.connection.send("request-has-owner",{guid:this.guid}),this)}waitForHasOwnershipRequestResponse(e){e.guid===this.guid&&(this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this._isOwned=e.value,e.value||(sl&&console.log("request ownership",this.guid),this.requestOwnership()))}requestOwnershipAsync(){return new Promise((e,t)=>{this.requestOwnership();let i=0;const n=()=>{if(i++>10)return t("Timeout");setTimeout(()=>{this.hasOwnership?e(this):n()},100)};n()})}requestOwnership(){return sl&&console.log("Request ownership",this.guid),this.connection.send("request-ownership",{guid:this.guid}),this}freeOwnership(){return this.connection.send("remove-ownership",{guid:this.guid}),this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this}destroy(){this.connection.stopListen("gained-ownership",this._gainSubscription),this.connection.stopListen("lost-ownership",this._lostSubscription),this.connection.stopListen("response-has-owner",this._hasOwnerResponse),this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null)}onGainedOwnership(e){e.guid===this.guid&&(this._isOwned=!0,this.connection.connectionId===e.owner?(sl&&console.log("GAINED OWNERSHIP",this.guid),this._hasOwnership=!0):this._hasOwnership=!1)}onLostOwnership(e){e===this.guid&&(sl&&console.log("LOST OWNERSHIP",this.guid),this._hasOwnership=!1,this._isOwned=!1)}}class jb{context;_peer=null;constructor(e){this.context=e}get peer(){return this._peer||(this._peer=new Lb),this._peer}tryGetState(e){return e==="invalid"?null:this._state[e]}get connectionId(){return this._connectionId}get isDebugEnabled(){return Ut}get isConnected(){return this.connected}get currentRoomName(){return this._currentRoomName}get allowEditing(){return this._currentRoomAllowEditing}get currentRoomViewId(){return this._currentRoomViewId}getViewOnlyUrl(){if(this.currentRoomViewId===null)return null;const e=new URL(window.location.href);return e.searchParams.set("view",this.currentRoomViewId),e.href}get isInRoom(){return this._isInRoom}get currentLatency(){return this._currentDelay}get currentServerUrl(){return this._ws?.url??null}sendPing(){this.send("ping",{time:this.context.time.time})}userIsInRoom(e){return this._currentInRoom.indexOf(e)!==-1}_usersInRoomCopy=[];usersInRoom(e=null){e||(e=this._usersInRoomCopy),e.length=0;for(const t of this._currentInRoom)e.push(t);return e}joinRoom(e,t=!1){return e?e.length>1024?(console.error('Room name too long, can not join: "'+e+'". Max length is 1024 characters.'),!1):(this.isInRoom&&this.currentRoomName!==e&&console.warn("Needle Engine is already connected to a networking room. Connecting to multiple rooms is not supported"),this.connect(),Ut&&console.log("join: "+e),this.send("join-room",{room:e,viewOnly:t},Yi.OnConnection),!0):(console.error('Missing room name, can not join: "'+e+'"'),!1)}leaveRoom(e=null){return e||(e=this.currentRoomName),e?(this.send("leave-room",{room:e}),!0):(console.error('Missing room name, can not join: "'+e+'"'),!1)}send(e,t=null,i=Yi.Queued){if(t===null&&(t={}),i===Yi.Queued){this._defaultMessagesBuffer.push({key:e,value:t});return}return this.sendWithWebsocket(e,t,i)}sendDeleteRemoteState(e){this.send("delete-state",{guid:e,dontSave:!0}),delete this._state[e]}sendDeleteRemoteStateAll(){this.send("delete-all-state"),this._state={}}sendBinary(e){th&&console.log("<< send binary",this.context.time.frame,e.length/1024+" KB"),this._ws?.send(e)}_defaultMessagesBuffer=[];_defaultMessagesBufferArray=[];sendBufferedMessagesNow(){if(!this._ws)return;this._defaultMessagesBufferArray.length=0;const e=Object.keys(this._defaultMessagesBuffer).length;for(const i in this._defaultMessagesBuffer){const n=this._defaultMessagesBuffer[i];if(e<=1){this.sendWithWebsocket(n.key,n.value,Yi.Immediate);break}const o=this.toMessage(n.key,n.value);this._defaultMessagesBufferArray.push(o)}if(this._defaultMessagesBuffer.length=0,this._defaultMessagesBufferArray.length>0&&Ut&&console.log("SEND BUFFERED",this._defaultMessagesBufferArray.length),this._defaultMessagesBufferArray.length<=0)return;const t=JSON.stringify(this._defaultMessagesBufferArray);this._ws?.send(t)}beginListen(e,t){return this._listeners[e]||(this._listeners[e]=[]),this._listeners[e].push(t),t}stopListening(e,t){return this.stopListen(e,t)}stopListen(e,t){if(!t||!this._listeners[e])return;const i=this._listeners[e].indexOf(t);i>=0&&this._listeners[e].splice(i,1)}beginListenBinary(e,t){return this._listenersBinary[e]||(this._listenersBinary[e]=[]),this._listenersBinary[e].push(t),t}stopListenBinary(e,t){if(!this._listenersBinary[e])return;const i=this._listenersBinary[e].indexOf(t);i>=0&&this._listenersBinary[e].splice(i,1)}netWebSocketUrlProvider;registerProvider(e){this.netWebSocketUrlProvider=e}async connect(e){if(this.connected&&e&&e!==wi)return Promise.reject("Can not connect to different server url. Please disconnect first.");if(this.connected)return Promise.resolve(!0);e&&console.debug("Connecting to user provided url "+e);const t=e||this.netWebSocketUrlProvider?.getWebsocketUrl();return t?wi=t:W_()&&(wi="wss://"+window.location.host+"/socket"),this.connectWebsocket()}disconnect(){this._ws?.close(),this._ws=void 0,wi=void 0,this._currentRoomAllowEditing=!0,this._currentRoomName=null,this._currentRoomViewId=null,this._isInRoom=!1,this._currentInRoom.length=0,this._state={},this._currentDelay=-1}_listeners={};_listenersBinary={};connected=!1;channelId;_connectionId=null;_ws;_waitingForSocket={};_isInRoom=!1;_currentRoomName=null;_currentRoomViewId=null;_currentRoomAllowEditing=!0;_currentInRoom=[];_state={};_currentDelay=-1;_connectingToWebsocketPromise=null;connectWebsocket(){return this._connectingToWebsocketPromise?this._connectingToWebsocketPromise:this._connectingToWebsocketPromise=new Promise(async(e,t)=>{let i=!1;const n=h=>{i||(i=!0,e(h))};if(wi===void 0&&(console.log("Fetch default backend url: "+uy),wi=await(await fetch(uy)).text()),wi===void 0){n(!1);return}console.debug(`⊡ Connecting to networking backend on
163
+ `+wi);const o=await Promise.resolve().then(()=>require("./vendor-D51IT5ns.umd.cjs")).then(h=>h.index),r=o.default?.WebsocketBuilder??o.WebsocketBuilder,a=o.default?.ExponentialBackoff??o.ExponentialBackoff,l=new r(wi).withMaxRetries(10).withBackoff(new a(2e3,4)).onOpen(()=>{this._connectingToWebsocketPromise=null,this._ws=l,this.connected=!0,A()||Ut?console.log(`⊞ Connected to networking backend
164
164
  `+wi):console.debug("⊞ Connected to networking backend",wi),n(!0),this.onSendQueued(Yi.OnConnection)}).onClose(h=>{this._connectingToWebsocketPromise=null,this.connected=!1,this._isInRoom=!1,n(!1);let d="Websocket connection closed...";wi?.includes("/socket")||(d+=' Do you perhaps mean to connect to "/socket"?'),console.error(d)}).onError(h=>{console.error("⊠ Websocket connection failed..."),n(!1)}).onRetry(()=>{console.log("→ Retry connecting to networking websocket")}).build();l.addEventListener(o.WebsocketEvent.message,(h,d)=>{this.onMessage(h,d)})})}onMessage(e,t){const i=t.data;try{if(typeof i!="string"){i.size&&this.handleIncomingBinaryMessage(i);return}const n=JSON.parse(i);if(Array.isArray(n))for(const o of n)this.handleIncomingStringMessage(o);else this.handleIncomingStringMessage(n);return}catch(n){Ut&&i==="pong"?console.log("<<",i):A()&&console.error("Failed to parse message",n)}}async handleIncomingBinaryMessage(e){th&&console.log("<< bin",this.context.time.frame);const t=await e.arrayBuffer();var i=new Uint8Array(t);const n=new se.ByteBuffer(i),o=n.getBufferIdentifier(),r=this._listenersBinary[o],a=Eb(n),l=Tb(a);if(l&&typeof l=="string"&&(this._state[l]=a),!r)return;const h=a??n;for(const d of r)d(h)}handleIncomingStringMessage(e){if(Ut&&console.log("<<",e.key??e),e.key)switch(e.key){case"connection-start-info":if(e.data){const r=e.data;r&&(console.assert(r.id!==void 0&&r.id!==null&&r.id.length>0,"server did not send connection id",r.id),console.debug("Your id is: "+r.id,this.context.alias??""),this._connectionId=r.id)}else console.warn("Expected connection id in "+e.key);break;case"joined-room":if(Ut&&console.log(e),e){this._isInRoom=!0;const r=e;this._currentRoomName=r.room,this._currentRoomViewId=r.viewId,this._currentRoomAllowEditing=r.allowEditing??!0,this._currentInRoom.length=0,this._currentInRoom.push(...r.inRoom),(th||A())&&console.debug("Joined Needle Engine Room: "+r.room);const a=new URL(window.location.href);a.searchParams.has("room")&&a.searchParams.delete("room"),a.searchParams.set("view",this._currentRoomViewId),console.debug(`Room view id: ${this._currentRoomViewId}
165
165
  ${a.href}`)}this.onSendQueued(Yi.OnRoomJoin);break;case"left-room":const n=e;n.room===this.currentRoomName&&(this._isInRoom=!1,this._currentRoomName=null,this._currentRoomAllowEditing=!0,this._currentInRoom.length=0,(th||A())&&console.debug("Left Needle Engine Room: "+n.room));break;case"user-joined-room":if(e.data){const r=e.data;this._currentInRoom.push(r.userId),Ut&&console.log(r.userId+" joined","now in room:",this._currentInRoom)}break;case"user-left-room":if(e.data){const r=e.data,a=this._currentInRoom.indexOf(r.userId);a>=0&&(Ut&&console.log(r.userId+" left","now in room:",this._currentInRoom),this._currentInRoom.splice(a,1)),r.userId===this.connectionId&&console.log("you left the room")}break;case"all-room-state-deleted":Ut&&console.log("RECEIVED all-room-state-deleted"),this._state={};break;case"ping":case"pong":const o=e.data?.time;o&&(this._currentDelay=this.context.time.time-o),Ut&&console.log(`Current latency: ${(this._currentDelay*1e3).toFixed()} ms`,"Clients in room: "+this._currentInRoom?.length);break}const t=e.data;t&&(this._state[t.guid]=t);let i=this._listeners[e.key];if(i){i=[...i];for(const n of i)try{n(e.data)}catch(o){console.error('Error invoking callback for "'+e.key+'"',o)}}}toMessage(e,t){return{key:e,data:t}}sendWithWebsocket(e,t,i=Yi.OnRoomJoin){if(!this._ws){const o=this._waitingForSocket[i]||[];o.push(()=>this.sendWithWebsocket(e,t,i)),this._waitingForSocket[i]=o;return}const n=JSON.stringify(this.toMessage(e,t));Ut&&console.log(">>",e),this._ws.send(n)}onSendQueued(e){const t=this._waitingForSocket[e];if(t){for(const i of t)i();t.length=0}}}const Sl=w("debugwebxr");class Uu{controllerStates=[];userId;context;userStateEvtName;constructor(e,t){this.userId=e,this.context=t,this.userStateEvtName="xr-sync-user-state-"+e,this.context.connection.beginListen(this.userStateEvtName,this.onReceivedControllerState)}dispose(){this.context.connection.stopListen(this.userStateEvtName,this.onReceivedControllerState)}onReceivedControllerState=e=>{Sl&&console.log(`XRSync: Received change for ${this.userId}: ${e.type} ${e.handedness}; tracked=${e.isTracking}`);let t=!1;for(let i=0;i<this.controllerStates.length;i++)if(this.controllerStates[i].index===e.index){this.controllerStates[i]=e,t=!0;break}t||this.controllerStates.push(e)};update(e){if(this.context.connection.isConnected!=!1){for(let t=this.controllerStates.length-1;t>=0;t--){const i=this.controllerStates[t];let n=!1;for(let o=0;o<e.controllers.length;o++)e.controllers[o].index===i.index&&(n=!0);n||(Sl&&console.log(`XRSync: ${i.type} ${i.handedness} removed`,i.index),this.controllerStates.splice(t,1),this.sendControllerRemoved(i))}for(const t of e.controllers)this.updateControllerStates(t)}}onExitXR(e){for(const t of this.controllerStates)this.sendControllerRemoved(t);this.controllerStates.length=0}sendControllerRemoved(e){e.isTracking=!1,e.guid="",this.context.connection.send(this.userStateEvtName,e),this.context.connection.sendDeleteRemoteState(e.guid)}updateControllerStates(e){const t=this.controllerStates.find(i=>i.index===e.index);if(t){let i=!1;i||=t.isTracking!=e.isTracking,i&&(t.isTracking=e.isTracking,this.context.connection.send(this.userStateEvtName,t))}else{const i={guid:this.userId+"-"+e.index,isTracking:e.isTracking,handedness:e.side,index:e.index,type:e.hand?"hand":"controller"};this.controllerStates.push(i),this.context.connection.send(this.userStateEvtName,i),Sl&&console.log(`XRSync: ${i.type} ${i.handedness} added`,i.index)}}}class Bb{hasState(e){return e?this._states.has(e):!1}isTracking(e,t){if(!e)return;const i=this._states.get(e);return i?i.controllerStates.find(o=>o.handedness===t)?.isTracking||!1:void 0}getDeviceType(e,t){if(!e)return;const i=this._states.get(e);return i?i.controllerStates.find(o=>o.handedness===t)?.type||"unknown":void 0}context;constructor(e){this.context=e,this.context.connection.beginListen(Q.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(Q.LeftRoom,this.onLeftRoom),this.context.connection.beginListen(Q.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.beginListen(Q.UserLeftRoom,this.onOtherUserLeftRoom)}destroy(){this.context.connection.stopListen(Q.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(Q.LeftRoom,this.onLeftRoom),this.context.connection.stopListen(Q.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.stopListen(Q.UserLeftRoom,this.onOtherUserLeftRoom)}onJoinedRoom=()=>{if(this.context.connection.connectionId){this._states.has(this.context.connection.connectionId)||(Sl&&console.log("XRSync: Local user joined room",this.context.connection.connectionId),this._states.set(this.context.connection.connectionId,new Uu(this.context.connection.connectionId,this.context)));for(const e of this.context.connection.usersInRoom())this._states.has(e)||this._states.set(e,new Uu(e,this.context))}};onLeftRoom=()=>{this.context.connection.connectionId&&(this._states.has(this.context.connection.connectionId)||(this._states.get(this.context.connection.connectionId)?.dispose(),this._states.delete(this.context.connection.connectionId)))};onOtherUserJoinedRoom=e=>{const t=e.userId;this._states.has(t)||(Sl&&console.log("XRSync: Remote user joined room",t),this._states.set(t,new Uu(t,this.context)))};onOtherUserLeftRoom=e=>{const t=e.userId;this._states.has(t)||(this._states.get(t)?.dispose(),this._states.delete(t))};_states=new Map;onUpdate(e){this.context.connection.isConnected&&this.context.connection.connectionId&&this._states.get(this.context.connection.connectionId)?.update(e)}onExitXR(e){this.context.connection.isConnected&&this.context.connection.connectionId&&this._states.get(this.context.connection.connectionId)?.onExitXR(e)}}class fy{_fadeToColorQuad;_fadeToColorMaterial;constructor(){this._fadeToColorMaterial=new c.MeshBasicMaterial({color:0,transparent:!0,depthTest:!1,fog:!1,side:c.DoubleSide}),this._fadeToColorQuad=new c.Mesh(new c.PlaneGeometry(10,10),this._fadeToColorMaterial)}dispose(){this._fadeToColorQuad.geometry.dispose(),this._fadeToColorMaterial.dispose()}update(e,t){const i=this._fadeToColorQuad,n=this._fadeToColorMaterial;i.parent!==e&&n.opacity>0?e.add(i):n.opacity===0&&i.removeFromParent(),i.layers.set(2),i.material=this._fadeToColorMaterial,i.position.z=-1,i.renderOrder=1/0;const o=this._requestedFadeValue;n.opacity=I.lerp(n.opacity,o,t/.03),Math.abs(n.opacity-o)<=.01&&this._transitionResolve&&(this._transitionResolve(),this._transitionResolve=null,this._transitionPromise=null,this._requestedFadeValue=0)}remove(){this._fadeToColorQuad.removeFromParent()}fadeTransition(){if(this._transitionPromise)return this._transitionPromise;this._requestedFadeValue=1;const e=new Promise(t=>{this._transitionResolve=t});return this._transitionPromise=e,e}_requestedFadeValue=0;_transitionPromise=null;_transitionResolve=null}var No=(s=>(s[s.Quad=0]="Quad",s[s.Cube=1]="Cube",s[s.Sphere=2]="Sphere",s[s.Cylinder=3]="Cylinder",s[s.RoundedCube=10]="RoundedCube",s))(No||{});class Ko{static createText(e,t){let i=null;const n=t?.font||gS(t?.familyFamily||null);n instanceof G.Font?i=this.#t(e,n,t):i==null&&(i=new c.BufferGeometry);const o=t?.color||16777215,r=new c.Mesh(i,t?.material??new c.MeshStandardMaterial({color:o}));return this.applyDefaultObjectOptions(r,t),n instanceof Promise?n.then(a=>{r.geometry=this.#t(e,a,t),t?.onGeometry&&t.onGeometry(r)}):t?.onGeometry&&t.onGeometry(r),r}static#t(e,t,i){const n=i?.depth||.1;return new G.TextGeometry(e,{font:t,size:1,depth:n,height:n,bevelEnabled:i?.bevel||!1,bevelThickness:.01,bevelOffset:.01,bevelSize:.01})}static createOccluder(e){const t=new c.MeshBasicMaterial({colorWrite:!1,depthWrite:!0,side:c.DoubleSide});return this.createPrimitive(e,{material:t})}static createPrimitive(e,t){let i;const n=t?.color||16777215;switch(e){case"Quad":case 0:{const o=new c.PlaneGeometry(1,1,1,1),r=t?.material??new c.MeshStandardMaterial({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new c.Mesh(o,r),i.name="Quad"}break;case"Cube":case 1:{const o=new c.BoxGeometry(1,1,1),r=t?.material??new c.MeshStandardMaterial({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new c.Mesh(o,r),i.name="Cube"}break;case 10:case"RoundedCube":{const o=mS(1,1,1,.1,2),r=t?.material??new c.MeshStandardMaterial({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new c.Mesh(o,r),i.name="RoundedCube"}break;case"Sphere":case 2:{const o=new c.SphereGeometry(.5,16,16),r=t?.material??new c.MeshStandardMaterial({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new c.Mesh(o,r),i.name="Sphere"}break;case"Cylinder":case 3:{const o=new c.CylinderGeometry(.5,.5,1,32),r=t?.material??new c.MeshStandardMaterial({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new c.Mesh(o,r),i.name="Cylinder"}break;case"ShaderBall":i=new c.Group,i.name="ShaderBall",yS(i,t);break}return this.applyDefaultObjectOptions(i,t),i}static createSprite(e){const i=new c.SpriteMaterial({color:16777215});e?.texture&&"map"in i&&(i.map=e.texture);const n=new c.Sprite(i);return this.applyDefaultObjectOptions(n,e),n}static applyDefaultObjectOptions(e,t){e.receiveShadow=!0,e.castShadow=!0,t?.name&&(e.name=t.name),t?.position&&(Array.isArray(t.position)?e.position.set(t.position[0],t.position[1],t.position[2]):e.position.set(t.position.x,t.position.y,t.position.z)),t?.rotation&&(Array.isArray(t.rotation)?e.rotation.set(t.rotation[0],t.rotation[1],t.rotation[2]):e.rotation.set(t.rotation.x,t.rotation.y,t.rotation.z)),t?.scale&&(typeof t.scale=="number"?e.scale.set(t.scale,t.scale,t.scale):Array.isArray(t.scale)?e.scale.set(t.scale[0],t.scale[1],t.scale[2]):e.scale.set(t.scale.x,t.scale.y,t.scale.z)),t?.receiveShadow!=null&&(e.receiveShadow=t.receiveShadow),t?.castShadow!=null&&(e.castShadow=t.castShadow),t?.parent&&t.parent.add(e)}}function mS(s,e,t,i,n){const o=new c.Shape,r=1e-5,a=i-r;o.absarc(r,r,r,-Math.PI/2,-Math.PI,!0),o.absarc(r,e-a*2,r,Math.PI,Math.PI/2,!0),o.absarc(s-a*2,e-a*2,r,Math.PI/2,0,!0),o.absarc(s-a*2,r,r,0,-Math.PI/2,!0);const l=new c.ExtrudeGeometry(o,{bevelEnabled:!0,bevelSegments:n*2,steps:1,bevelSize:a,bevelThickness:i,curveSegments:n,UVGenerator:{generateTopUV:(h,d)=>{const u=[];for(let p=0;p<d.length;p+=3)u.push(new c.Vector2(d[p]/s,d[p+1]/e));return u},generateSideWallUV:(h,d,u,p,m,y)=>{const b=[];return b.push(new c.Vector2(d[u]/s,d[u+1]/e)),b.push(new c.Vector2(d[p]/s,d[p+1]/e)),b.push(new c.Vector2(d[m]/s,d[m+1]/e)),b.push(new c.Vector2(d[y]/s,d[y+1]/e)),b}}});return l.scale(1,1,1-i),l.center(),l.index||l.setIndex(Array.from({length:l.attributes.position.count},(h,d)=>d)),l.computeVertexNormals(),l}const ih=new Map;function gS(s){let e="";switch(s){default:case"OpenSans":e="https://cdn.needle.tools/static/fonts/facetype/Open Sans_Regular_ascii.json";break;case"Helvetiker":e="https://raw.githubusercontent.com/mrdoob/three.js/master/examples/fonts/helvetiker_regular.typeface.json";break}if(ih.has(e)){const n=ih.get(e);if(n)return n}const t=new G.FontLoader,i=new Promise((n,o)=>{t.load(e,r=>{ih.set(e,r),n(r)},void 0,o)});return ih.set(e,i),i}let zu=!1,Nu=null;function yS(s,e){if(Nu===null){const t="https://cdn.needle.tools/static/models/shaderball.glb",i=new G.GLTFLoader,n=ne.createLoaders(null);i.setDRACOLoader(n.dracoLoader),i.setKTX2Loader(n.ktx2Loader),zu=!0,Nu=i.loadAsync(t).then(o=>{const r=o.scene;return r.position.y-=.5,r}).catch(o=>(console.warn("Failed to load shaderball mesh: "+o.message),my())).finally(()=>{zu=!1})}if(zu){const t=my();t.name="ShaderBall-Placeholder";const i=t.children[0];i?.type==="Mesh"&&py(i,e),s.add(t)}Nu.then(t=>{s.children.forEach(o=>{o.name==="ShaderBall-Placeholder"&&s.remove(o)});const i=t.clone(),n=i.children[0];n?.type==="Mesh"&&(n.geometry.attributes.tangent||n.geometry.computeTangents(),py(n,e)),s.add(i)})}function py(s,e){if(e?.color||e?.material||e?.texture){const i=e?.material??s.material?.clone()??new c.MeshStandardMaterial;e.color&&"color"in i&&i.color instanceof c.Color&&i.color.set(e.color),e?.texture&&"map"in i&&(i.map=e.texture),s.material=i}}function my(){return new c.Group().add(Ko.createPrimitive("Sphere",{material:new c.MeshBasicMaterial({transparent:!0,opacity:.1})}))}class ia{static _active=null;static get active(){return this._active}static _requestInFlight=!1;static async start(e,t){if(this._active)return console.error("Cannot start a new XR session while one is already active"),null;if(this._requestInFlight)return console.error("Cannot start a new XR session while a request is already in flight"),null;if("xr"in navigator&&navigator.xr){if(!t)return console.error("XRSessionInit must be provided"),null;this._requestInFlight=!0;const i=await navigator.xr.requestSession(e,t);return i.addEventListener("end",()=>{this._active=null}),this._requestInFlight?(this._requestInFlight=!1,this._active=new ia(e,t,i),this._active):(i.end(),null)}return null}static async handoff(){return this._active?this._active.handoff():null}static async stop(){this._requestInFlight=!1,this._active&&(await this._active.end(),await An(100)),this._active=null}_session;_mode;_init;get isAR(){return this._mode==="immersive-ar"}_renderer;_camera;_scene;constructor(e,t,i){this._mode=e,this._init=t,this._session=i,this._session.addEventListener("end",this.onEnd),this._renderer=new c.WebGLRenderer({alpha:!0}),this._renderer.setAnimationLoop(this.onFrame),this._renderer.xr.setSession(i),this._renderer.xr.enabled=!0,this._camera=new c.PerspectiveCamera,this._scene=new c.Scene,this._scene.fog=new c.Fog(4473924,10,250),this._scene.add(this._camera),this.setupScene()}end(){return this._session?this._session.end():Promise.resolve()}async handoff(){if(!this._session)throw new Error("Cannot handoff a session that has already ended");const e={session:this._session,mode:this._mode,init:this._init};return await this.onBeforeHandoff(),this.onEnd(),this._session=null,e}onEnd=()=>{this._session?.removeEventListener("end",this.onEnd),this._renderer.setAnimationLoop(null),this._renderer.dispose(),this._scene.clear()};_lastTime=0;onFrame=(e,t)=>{const i=e-this._lastTime;this.update(e,i),this._camera.parent!==this._scene&&this._scene.add(this._camera),this._renderer.render(this._scene,this._camera)};async onBeforeHandoff(){await An(1e3),this._scene.clear()}_objects=[];setupScene(){this._scene.background=new c.Color(0),this._scene.add(new c.GridHelper(5,10,1118481,1118481));const e=new c.DirectionalLight(16777215,1);e.position.set(0,20,0),e.castShadow=!1,this._scene.add(e);const t=new c.DirectionalLight(16777215,1);t.position.set(0,-1,0),t.castShadow=!1,this._scene.add(t);const i=new c.PointLight(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 c.MeshStandardMaterial({color:2236962,metalness:1,roughness:.8});this.isAR&&(r.emissive=new c.Color(Math.random(),Math.random(),Math.random()),r.emissiveIntensity=Math.random());const a=I.random(0,1)>.5?No.Sphere:No.Cube,l=Ko.createPrimitive(a,{material:r});l.position.x=I.random(-n,n),l.position.y=I.random(-2,n),l.position.z=I.random(-n,n),l.rotation.x=I.random(0,Math.PI*2),l.rotation.y=I.random(0,Math.PI*2),l.rotation.z=I.random(0,Math.PI*2),l.scale.multiplyScalar(.5+Math.random()*10);const h=l.position.distanceTo(this._camera.position)-l.scale.x;h<1&&l.position.multiplyScalar(1+1/h),this._objects.push(l),this._scene.add(l)}}update(e,t){const i=e*4e-4;for(let n=0;n<this._objects.length;n++){const o=this._objects[n];o.position.y+=Math.sin(i+n*.5)*.005,o.rotateY(.002)}}}var jl;(s=>{const e=[];function t(){if(!e?.length)return!1;for(const o of e)o.exportAndOpen();return!0}s.exportAndOpen=t;function i(o){e.push(o)}s.registerExporter=i;function n(o){if(!e)return;const r=e.indexOf(o);r>=0&&e.splice(r,1)}s.unregisterExporter=n})(jl||(jl={}));const je=w("debugwebxr"),gy=w("stats");let Vu=0;function _S(s){let e=null;const t=s;return t.getAROverlayContainer?e=t.getAROverlayContainer():e=s,e}bS();async function bS(){if(w("debugasap")){let s=globalThis["needle:XRSession"];if(s instanceof Promise){delete globalThis["needle:XRSession"],re.addContextCreatedCallback(async e=>{if(!s)return;Ro(!0);const t=await s;if(t){const i=q.getDefaultSessionInit("immersive-vr");q.setSession("immersive-vr",t,i,e.context)}else console.error("NeedleXRSession: ASAP session was rejected");s=void 0});return}}if("xr"in navigator){if(/WebXRViewer\//i.test(navigator.userAgent)){console.warn("WebXRViewer does not support addEventListener");return}navigator.xr?.addEventListener("sessiongranted",async()=>{Ro(!0),console.log("Received Session Granted..."),await An(100);const s=sessionStorage.getItem("needle_xr_session_mode"),e=sessionStorage.getItem("needle_xr_session_init")??null,t=e?JSON.parse(e):null;let i=null;if(Fb()&&(await ia.start(s||"immersive-vr",t||q.getDefaultSessionInit("immersive-vr")),await xS(),i=await ia.handoff()),i)q.setSession(i.mode,i.session,i.init,U.Current);else if(s&&e){console.log("Session Granted: Restore last session");const n=JSON.parse(e);q.start(s,n).catch(o=>console.warn(o))}else q.start("immersive-vr").catch(n=>console.warn("Session Granted failed:",n))},{once:!0})}}function vS(s,e){sessionStorage.setItem("needle_xr_session_mode",s),sessionStorage.setItem("needle_xr_session_init",JSON.stringify(e))}function wS(){sessionStorage.removeItem("needle_xr_session_mode"),sessionStorage.removeItem("needle_xr_session_init")}const im=new Set;re.registerCallback(oe.ContextCreationStart,async s=>{im.add(s.context)});re.registerCallback(oe.ContextCreated,async s=>{im.delete(s.context);const e=s.context?.domElement.getAttribute("autostart")||null;SS(e)});function Fb(){return im.size>0}function xS(){return new Promise(s=>{const e=Date.now(),t=setInterval(()=>{(!Fb()||Date.now()-e>6e4)&&(clearInterval(t),s())},100)})}exports.DeviceUtilities.isDesktop()&&A()&&window.addEventListener("keydown",s=>{(s.key==="x"||s.key==="Escape")&&q.active&&q.stop()});function SS(s){if(s)switch(s?.toLowerCase()){case"ar":tn.registerWaitForInteraction(()=>{q.start("ar")});break}}class q{static _sync=null;static getXRSync(e){return this._sync||(this._sync=new Bb(e)),this._sync}static get currentSessionRequest(){return this._currentSessionRequestMode}static _currentSessionRequestMode=null;static get active(){return this._activeSession}static get activeMode(){return this._activeSession?.mode??null}static get xrSystem(){return"xr"in navigator?navigator.xr:void 0}static isXRSupported(){return Promise.all([this.isVRSupported(),this.isARSupported()]).then(e=>e.some(t=>t)).catch(()=>!1)}static isVRSupported(){return this.isSessionSupported("immersive-vr")}static isARSupported(){return this.isSessionSupported("immersive-ar")}static isSessionSupported(e){return this.xrSystem?.isSessionSupported(e).catch(t=>(je&&console.error(t),!1))??Promise.resolve(!1)}static _currentSessionRequest;static _activeSession;static onSessionRequestStart(e){this._sessionRequestStartListeners.push(e)}static offSessionRequestStart(e){const t=this._sessionRequestStartListeners.indexOf(e);t>=0&&this._sessionRequestStartListeners.splice(t,1)}static _sessionRequestStartListeners=[];static onSessionRequestEnd(e){this._sessionRequestEndListeners.push(e)}static offSessionRequestEnd(e){const t=this._sessionRequestEndListeners.indexOf(e);t>=0&&this._sessionRequestEndListeners.splice(t,1)}static _sessionRequestEndListeners=[];static onXRSessionStart(e){this._xrStartListeners.push(e)}static offXRSessionStart(e){const t=this._xrStartListeners.indexOf(e);t>=0&&this._xrStartListeners.splice(t,1)}static _xrStartListeners=[];static onXRSessionEnd(e){this._xrEndListeners.push(e)}static offXRSessionEnd(e){const t=this._xrEndListeners.indexOf(e);t>=0&&this._xrEndListeners.splice(t,1)}static _xrEndListeners=[];static onControllerAdded(e){this._controllerAddedListeners.push(e)}static offControllerAdded(e){const t=this._controllerAddedListeners.indexOf(e);t>=0&&this._controllerAddedListeners.splice(t,1)}static _controllerAddedListeners=[];static onControllerRemoved(e){this._controllerRemovedListeners.push(e)}static offControllerRemoved(e){const t=this._controllerRemovedListeners.indexOf(e);t>=0&&this._controllerRemovedListeners.splice(t,1)}static _controllerRemovedListeners=[];static offerSession(e,t,i){return"xr"in navigator&&navigator.xr&&"offerSession"in navigator.xr?(typeof navigator.xr.offerSession=="function"&&(console.log("WebXR offerSession is available - requesting mode: "+e),t=="default"&&(t=this.getDefaultSessionInit(e)),navigator.xr.offerSession(e,{...t}).then(n=>q.setSession(e,n,t,i)).catch(n=>{console.log("XRSession offer rejected (perhaps because another call to offerSession was made or a call to requestSession was made)")})),!0):!1}static getDefaultSessionInit(e){switch(e){case"immersive-ar":const t=["anchors","local-floor","layers","dom-overlay","hit-test","unbounded"];return exports.DeviceUtilities.isVisionOS()||t.push("hand-tracking"),{optionalFeatures:t};case"immersive-vr":const i=["local-floor","bounded-floor","high-fixed-foveation-level","layers"];return exports.DeviceUtilities.isVisionOS()||i.push("hand-tracking"),{optionalFeatures:i};default:return console.warn("No default session init for mode",e),{}}}static async start(e,t,i){if(exports.DeviceUtilities.isiOS()){if(e==="ar")if(await this.isARSupported())e="immersive-ar";else return jl.exportAndOpen(),null}else e=="ar"&&(e="immersive-ar");if(A()&&w("debugxrpreroom"))return console.warn("Debug: Starting temporary XR session"),await ia.start(e,t||q.getDefaultSessionInit(e)),null;if(this._currentSessionRequest)return console.warn("A XRSession is already being requested"),(je||A())&&ce("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=U.Current),i||(i=re.All[0]),!i)throw new Error("No Needle Engine Context found");switch(t||(t={}),e){case"immersive-ar":{if(await this.xrSystem?.isSessionSupported("immersive-ar")!==!0)return console.error(e+" is not supported by this browser."),null;const l=this.getDefaultSessionInit(e),h=_S(i.domElement);h&&!exports.DeviceUtilities.isQuest()&&(l.domOverlay={root:h},l.optionalFeatures.push("dom-overlay")),t={...l,...t}}break;case"immersive-vr":{if(await this.xrSystem?.isSessionSupported("immersive-vr")!==!0)return console.error(e+" is not supported by this browser."),null;t={...this.getDefaultSessionInit(e),...t}}break;default:console.warn("No default session init for mode",e);break}t.optionalFeatures??=[],t.requiredFeatures??=[],await ia.stop();const n=e=="immersive-ar"?i.scripts_immersive_ar:i.scripts_immersive_vr;je?console.log(`%cRequesting ${e} session`,"font-weight:bold;",t,n):console.log(`%cRequesting ${e} session`,"font-weight:bold;");for(const a of n)a.onBeforeXR&&a.onBeforeXR(e,t);for(const a of this._sessionRequestStartListeners)a({mode:e,init:t});je&&Se("Requesting "+e+" session ("+Date.now()+")"),this._currentSessionRequest=navigator.xr?.requestSession(e,t),this._currentSessionRequestMode=e;const o=await this._currentSessionRequest?.catch(a=>{console.error(a,"Code: "+a.code),a.code===9&&ce("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:"&&ce("XR requires a secure connection (HTTPS)")});this._currentSessionRequest=void 0,this._currentSessionRequestMode=null;for(const a of this._sessionRequestEndListeners)a({mode:e,init:t,newSession:o||null});return o?this.setSession(e,o,t,i):(console.warn("XR Session request was rejected"),null)}static setSession(e,t,i,n){if(this._activeSession)return console.error("A XRSession is already running"),this._activeSession;const o=e=="immersive-ar"?n.scripts_immersive_ar:n.scripts_immersive_vr;return this._activeSession=new q(e,t,n,{scripts:o,controller_added:this._controllerAddedListeners,controller_removed:this._controllerRemovedListeners,init:i}),t.addEventListener("end",this.onEnd),je?console.log(`%cStarted ${e} session`,"font-weight:bold;",o):console.log(`%cStarted ${e} session`,"font-weight:bold;"),this._activeSession}static $_stop_request=Symbol();static stop(){const e=this._activeSession;e&&(e[this.$_stop_request]===void 0?(je&&console.log("[NeedleXRSession] Stopping XR Session... (new)"),e[this.$_stop_request]=setTimeout(()=>{e.end()})):je&&console.warn("[NeedleXRSession] XR Session stop already requested"))}static onEnd=()=>{je&&console.log("XR Session ended"),this._activeSession=null};context;get sync(){return q._sync}get running(){return!this._ended&&this.session!=null}session;mode;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}controllers=[];get leftController(){return this.controllers.find(e=>e.side==="left")}get rightController(){return this.controllers.find(e=>e.side==="right")}getController(e){return typeof e=="number"?this.controllers[e]||null:this.controllers.find(t=>t.side===e)||null}get isPassThrough(){return!!(this.environmentBlendMode!=="opaque"&&this.interactionMode==="world-space"||this.mode==="immersive-ar"&&this.environmentBlendMode!=="opaque"&&this.controllers.some(e=>e.inputSource.targetRayMode==="tracked-pointer")||A()&&exports.DeviceUtilities.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 e=this.frame.getImageTrackingResults();for(const t of e)if(t.trackingState==="tracked")return!0}catch{return!1}return!1}get rig(){const e=this._rigs[0]??null;return e?.gameObject&&Vo(e.gameObject)||e?.isActive===!1?(this.updateActiveXRRig(),this._rigs[0]??null):e}_rigScale=1;_lastRigScaleUpdate=-1;get rigScale(){return this._rigs[0]?(this._lastRigScaleUpdate!==this.context.time.frame&&(this._lastRigScaleUpdate=this.context.time.frame,this._rigScale=this._rigs[0].gameObject.worldScale.x),this._rigScale):1}addRig(e){this._rigs.indexOf(e)>=0||(e.priority===void 0&&(e.priority=0),this._rigs.push(e),this.updateActiveXRRig())}removeRig(e){const t=this._rigs.indexOf(e);t!==-1&&(this._rigs.splice(t,1),this.updateActiveXRRig())}setRigActive(e){const t=this._rigs.indexOf(e),i=this._rigs[0];this._rigs.splice(t,1),this._rigs.unshift(e),e.priority=i?.priority??0,this.updateActiveXRRig()}getUserOffsetInRig(){const e=this.context.mainCamera?.position;if(!e||!this.rig)return V(0,0,0);const t=V(e);return t.x*=-1,t.z*=-1,t.applyQuaternion(Xi(this.rig.gameObject.quaternion)),t}updateActiveXRRig(){const e=this._rigs[0]??null;this._defaultRig.gameObject.parent!==this.context.scene&&this.context.scene.add(this._defaultRig.gameObject),this._defaultRig.gameObject.visible=!0,this._rigs.includes(this._defaultRig)||this._rigs.push(this._defaultRig);let t=this._rigs[0];t&&t.priority===void 0&&(t.priority=0);for(let i=1;i<this._rigs.length;i++){const n=this._rigs[i];if(n.isActive){if(Vo(n.gameObject)){this._rigs.splice(i,1),i--;continue}(!t||t.isActive===!1||n.priority!==void 0&&n.priority>t.priority)&&(t=n)}}if(e!==t){const i=this._rigs.indexOf(t);i>=0&&this._rigs.splice(i,1),this._rigs.unshift(t)}je&&(e===t?console.log("Updated Active XR Rig:",t,"prev:",e):console.log("Updated Active XRRig:",t," (the same as before)"))}_rigs=[];_viewerHitTestSource=null;getHitTest(e){if(e)return this.getControllerHitTest(e);if(!this._viewerHitTestSource)return null;const t=this._viewerHitTestSource,i=this.frame.getHitTestResults(t);if(i.length>0){const n=i[0];return this.convertHitTestResult(n)}return null}getControllerHitTest(e){const t=e.getHitTestSource();if(!t)return null;const i=this.frame.getHitTestResultsForTransientInput(t);for(const n of i)if(n.inputSource===e.inputSource)for(const o of n.results)return this.convertHitTestResult(o);return null}convertHitTestResult(e){const t=this.context.renderer.xr.getReferenceSpace(),i=t&&e.getPose(t);if(i){const n=V(i.transform.position),o=Xi(i.transform.orientation),r=this.context.mainCamera;if(r?.parent!==this._cameraRenderParent&&n.applyMatrix4(Wr),r?.parent){n.applyMatrix4(r.parent.matrixWorld),o.multiply(ki);const a=ue(r.parent);a.premultiply(ki),o.premultiply(a)}return{hit:e,position:n,quaternion:o}}return null}convertSpace(e){const t=V(e.position);t.applyMatrix4(Wr);const i=Xi(e.orientation);return i.premultiply(ki),{position:t,quaternion:i}}_defaultRig;_xr_scripts;_xr_update_scripts=[];_inactive_scripts=[];_controllerAdded;_controllerRemoved;_originalCameraWorldPosition;_originalCameraWorldRotation;_originalCameraWorldScale;_originalCameraParent;_mainCamera=null;constructor(e,t,i,n){vS(e,n.init),this.session=t,this.mode=e,this.context=i,(je||w("console"))&&Ro(!0),this._xr_scripts=[...n.scripts],this._xr_update_scripts=this._xr_scripts.filter(o=>typeof o.onUpdateXR=="function"),this._controllerAdded=n.controller_added,this._controllerRemoved=n.controller_removed,cs(this.onBefore,pe.LateUpdate),this.context.pre_render_callbacks.push(this.onBeforeRender),this.context.post_render_callbacks.push(this.onAfterRender),(n.init.optionalFeatures?.includes("hit-test")||n.init.requiredFeatures?.includes("hit-test"))&&t.requestReferenceSpace("viewer").then(o=>t.requestHitTestSource?.call(t,{space:o})?.then(r=>this._viewerHitTestSource=r).catch(r=>console.error(r))).catch(o=>console.error(o)),this.context.mainCamera&&(this._originalCameraWorldPosition=X(this.context.mainCamera,new c.Vector3),this._originalCameraWorldRotation=ue(this.context.mainCamera,new c.Quaternion),this._originalCameraWorldScale=Ae(this.context.mainCamera,new c.Vector3),this._originalCameraParent=this.context.mainCamera.parent),this._defaultRig=new nS,this.context.scene.add(this._defaultRig.gameObject),this.addRig(this._defaultRig);for(let o=0;o<t.inputSources.length;o++){const r=t.inputSources[o];if(!r.handedness){console.warn("Input source in xr session has no handedness - ignoring",o);continue}this.onInputSourceAdded(r)}this.session.addEventListener("end",this.onEnd),this.session.addEventListener("inputsourceschange",o=>{for(const r of o.removed)this.disconnectInputSource(r);for(const r of o.added)this.onInputSourceAdded(r)}),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):je&&console.warn("controllerAutoUpdate is not available in three.js - cannot disable it")}onRendererSessionSet=()=>{this.running&&(this.context.renderer.xr.enabled=!0,this.context.renderer.xr.updateCamera(this.context.mainCamera),this.context.mainCameraComponent?.applyClearFlags())};onInputSourceAdded=e=>{if(e.targetRayMode==="screen")return;let t=0;for(let n=0;n<this.session.inputSources.length;n++)if(this.session.inputSources[n]===e){t=n;break}if(this.controllers.find(n=>n.inputSource===e)){console.debug("Controller already exists for input source",t);return}else if(this._newControllers.find(n=>n.inputSource===e)){console.debug("Controller already registered for input source",t);return}const i=new Kp(this,e,t);this._newControllers.push(i)};disconnectInputSource(e){const t=(i,n,o)=>{if(i.inputSource===e){je&&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 a of this._xr_scripts)a.onXRControllerRemoved&&a.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(e=>console.warn(e))}_ended=!1;_newControllers=[];onEnd=e=>{if(this._ended)return;this._ended=!0,console.debug("XR Session ended"),wS(),this.onAfterRender(),this.revertCustomForward(),this._didStart=!1,this._previousCameraParent=null,Js(this.onBefore,pe.LateUpdate);const t=this.context.pre_render_callbacks.indexOf(this.onBeforeRender);t>=0&&this.context.pre_render_callbacks.splice(t,1);const i=this.context.post_render_callbacks.indexOf(this.onAfterRender);i>=0&&this.context.post_render_callbacks.splice(i,1),this.context.xr=null,this.context.renderer.xr.enabled=!1,this.context.pre_update_oneshot_callbacks.push(()=>{this.context.mainCameraComponent?.applyClearFlags(),this.context.mainCameraComponent?.applyClippingPlane()}),Ob({session:this});for(const o of q._xrEndListeners)o({xr:this});const n=[...this.controllers];for(let o=0;o<n.length;o++)this.disconnectInputSource(n[o].inputSource);this._newControllers.length=0,this.controllers.length=0;for(const o of this._xr_scripts)o?.onLeaveXR?.({xr:this});this.sync?.onExitXR(this),this.context.mainCamera&&(this._originalCameraParent?.add(this.context.mainCamera),this._originalCameraWorldPosition&&Ye(this.context.mainCamera,this._originalCameraWorldPosition),this._originalCameraWorldRotation&&Di(this.context.mainCamera,this._originalCameraWorldRotation),this._originalCameraWorldScale&&Jr(this.context.mainCamera,this._originalCameraWorldScale)),this.context.requestSizeUpdate(),this._defaultRig.gameObject.removeFromParent(),Ro(!1)};_didStart=!1;onBefore=e=>{const t=e.xrFrame;if(!t)return;this.context.xr=this,this.context.mainCameraComponent&&this.context.mainCameraComponent!==this._mainCamera&&(this._mainCamera=this.context.mainCameraComponent),this.rig?.isActive==!1&&(je&&console.warn("Latest rig is not active - trying to activate a different rig",this.rig),this.updateActiveXRRig()),this.rig&&this._mainCamera?.gameObject&&this._mainCamera?.gameObject?.parent!==this.rig.gameObject&&this.rig.gameObject.add(this._mainCamera?.gameObject),this.internalUpdateState(),this.applyCustomForward();const i={xr:this};if(this._didStart){if(this.context.new_scripts_xr.length>0){const n=[...this.context.new_scripts_xr];for(let o=0;o<n.length;o++){const r=this.context.new_scripts_xr[o];if(!r||r.destroyed||r.supportsXR?.(this.mode)==!1){this.context.new_scripts_xr.splice(o,1);continue}if(!r.activeAndEnabled){this.context.new_scripts_xr.splice(o,1),this.markInactive(r);continue}if(this.addScript(r)){this.invokeCallback_EnterXR(r);for(const a of this.controllers)this.invokeCallback_ControllerAdded(r,a)}}}}else{if(this._didStart=!0,this.mode==="immersive-vr"){const o=Ht(this.context.scene.children);if(o){const r=o.getSize(V());if(r.length()>0){const a=this._defaultRig.gameObject;a.position.set(o.min.x+r.x*.5,o.min.y,o.max.z+r.z*.5+1.5);const l=o.getCenter(V());l.y=a.position.y,a.lookAt(l)}}}Mb({session:this}),Yo();for(const o of q._xrStartListeners)o(i);const n=[...this._xr_scripts];je&&console.log("NeedleXRSession start, handle scripts:",n);for(const o of n){if(o.destroyed){this._script_to_remove.push(o);continue}if(!o.activeAndEnabled){this.markInactive(o);continue}this.invokeCallback_EnterXR(o);for(const r of this.controllers)this.invokeCallback_ControllerAdded(o,r)}}this.syncCameraCullingMask();for(const n of this.controllers)n.onUpdate(t);if(this._newControllers.length>0){const n=[...this._newControllers];this._newControllers.length=0;for(const o of n){if(!o.connected){console.warn("New controller is not connected",o);continue}this.controllers.push(o);for(const r of this._xr_scripts){if(r.destroyed){this._script_to_remove.push(r);continue}r.activeAndEnabled!==!1&&this.invokeCallback_ControllerAdded(r,o)}}this.controllers.sort((o,r)=>o.index-r.index)}je&&this.context.time.frame%30===0&&this.controllers.length<=0&&this.session.inputSources.length>0&&(Ro(!0),console.error("XRControllers are not added but inputSources are present"));for(const n of this._xr_update_scripts){if(n.destroyed===!0){this._script_to_remove.push(n);continue}if(n.activeAndEnabled===!1){this.markInactive(n);continue}n.onUpdateXR&&n.onUpdateXR(i)}if(this.handleInactiveScripts(),this._script_to_remove.length>0){const n=[...new Set(this._script_to_remove)];this._script_to_remove.length=0;for(const o of n)!o.destroyed&&this.running&&o.onLeaveXR?.(i),this.removeScript(o)}this.sync?.onUpdate(this),this.onRenderDebug()};onRenderDebug(){if(je)for(const e of this.controllers)e.onRenderDebug();if((je||gy)&&this.rig&&(Vu++,Vu>=20)){const e=this.rig.gameObject.worldPosition,t=this.rig.gameObject.worldForward;e.add(t.multiplyScalar(1.5));const i=this.rig.gameObject.worldUp;e.add(i.multiplyScalar(2.5));let n="";if(n+=`${this.context.time.smoothedFps.toFixed(0)} FPS`,n+=`, calls: ${this.context.renderer.info.render.calls}, tris: ${this.context.renderer.info.render.triangles.toLocaleString()}`,je||gy)for(const o of this.controllers)n+=`
166
- ${o.hand?"hand":"ctrl"} ${o.inputSource.handedness}[${o.index}] con:${o.connected} tr:${o.isTracking} hts:${o.hasHitTestSource?"yes":"no"}`;Vu=0,j.DrawLabel(e,n,void 0,1/60*20)}}onBeforeRender=()=>{this.context.mainCamera&&this.updateFade(this.context.mainCamera)};onAfterRender=()=>{if(this.onUpdateFade_PostRender(),exports.DeviceUtilities.isDesktop()||!this._renderOnceOnDevice){const e=this.context.renderer;if(e.xr.isPresenting&&this.context.mainCamera){this._renderOnceOnDevice=!0;const t=e.xr.enabled,i=e.getRenderTarget(),n=this.context.scene.background;e.xr.enabled=!1,e.setRenderTarget(null),this.isPassThrough&&(this.context.scene.background=null),this.context.composer?this.context.composer.render(this.context.time.deltaTime):e.render(this.context.scene,this.context.mainCamera),e.xr.enabled=t,e.setRenderTarget(i),this.context.scene.background=n}}};addScript(e){return this._xr_scripts.includes(e)?!1:(je&&console.log("Register new XRScript",e),this._xr_scripts.push(e),typeof e.onUpdateXR=="function"&&this._xr_update_scripts.push(e),!0)}markInactive(e){if(!(this._inactive_scripts.indexOf(e)>=0)){this.removeScript(e,!1),this._inactive_scripts.push(e);for(const t of this.controllers)this.invokeCallback_ControllerRemoved(e,t);this.invokeCallback_LeaveXR(e)}}handleInactiveScripts(){if(this._inactive_scripts.length>0)for(let e=this._inactive_scripts.length-1;e>=0;e--){const t=this._inactive_scripts[e];if(t.activeAndEnabled){this._inactive_scripts.splice(e,1),this.addScript(t),this.invokeCallback_EnterXR(t);for(const i of this.controllers)this.invokeCallback_ControllerAdded(t,i)}}}_script_to_remove=[];removeScript(e,t=!0){je&&console.log("Remove XRScript",e);const i=this._xr_scripts.indexOf(e);i>=0&&this._xr_scripts.splice(i,1);const n=this._xr_update_scripts.indexOf(e);if(n>=0&&this._xr_update_scripts.splice(n,1),t){const o=this._inactive_scripts.indexOf(e);o>=0&&this._inactive_scripts.splice(o,1)}}invokeCallback_EnterXR(e){e.onEnterXR&&e.onEnterXR({xr:this})}invokeCallback_ControllerAdded(e,t){e.onXRControllerAdded&&e.onXRControllerAdded({xr:this,controller:t,change:"added"})}invokeCallback_ControllerRemoved(e,t){e.onXRControllerRemoved&&e.onXRControllerRemoved({xr:this,controller:t,change:"removed"})}invokeCallback_LeaveXR(e){e.onLeaveXR&&!e.destroyed&&e.onLeaveXR({xr:this})}syncCameraCullingMask(){const e=this.context.xrCamera,t=this.context.mainCameraComponent?.cullingMask;if(e&&t!==void 0){for(const i of e.cameras)i.layers.mask=t;e.layers.mask=t}else if(e){for(const i of e.cameras)i.layers.enableAll();e.layers.enableAll()}}invokeControllerEvent(e,t,i){for(let n=t.length-1;n>=0;n--){const o=t[n];if(o)try{o({xr:this,controller:e,change:i})}catch(r){console.error(r)}}}_camera;_cameraRenderParent=new c.Object3D().rotateY(Math.PI);_previousCameraParent;_customforward=!0;originalCameraNearPlane;applyCustomForward(){if(this.context.mainCamera&&this._customforward){this._camera=this.context.mainCamera,this._camera.parent!==this._cameraRenderParent&&(this._previousCameraParent=this._camera.parent,this._previousCameraParent?.add(this._cameraRenderParent)),this._cameraRenderParent.name="XR Camera Render Parent",this._cameraRenderParent.add(this._camera);let e=.02;if(this.rig){const t=Ae(this.rig.gameObject);e*=t.x}this._camera instanceof c.PerspectiveCamera&&this._camera.near>e&&(this.originalCameraNearPlane=this._camera.near,this._camera.near=e)}}revertCustomForward(){this._camera&&this._previousCameraParent&&this._previousCameraParent.add(this._camera),this._previousCameraParent=null,this._camera instanceof c.PerspectiveCamera&&this.originalCameraNearPlane!=null&&(this._camera.near=this.originalCameraNearPlane)}_viewerPose;_transformOrientation=new c.Quaternion;_transformPosition=new c.Vector3;internalUpdateState(){const e=this.context.renderer.xr.getReferenceSpace();if(!e){this._viewerPose=void 0;return}if(this._viewerPose=this.frame.getViewerPose(e),this._viewerPose){const t=this._viewerPose.transform;this._transformPosition.set(t.position.x,t.position.y,t.position.z),this._transformOrientation.set(t.orientation.x,t.orientation.y,t.orientation.z,t.orientation.w)}}_transition;get transition(){return this._transition||(this._transition=new fy),this._transition}fadeTransition(){return this._transition||(this._transition=new fy),this._transition.fadeTransition()}updateFade(e){this._transition&&e instanceof c.PerspectiveCamera&&this._transition.update(e,this.context.time.deltaTime)}onUpdateFade_PostRender(){this._transition?.remove()}}const $u=w("debugwebxr");class Ub{static tryFindAvatarObjects(e,t,i){if(i.head&&i.leftHand&&i.rightHand)return;const n=e.name.toLocaleLowerCase();!i.head&&n.includes("head")&&($u&&console.log("FOUND AVATAR HEAD",e.name),i.head=new Y("",t,e)),n.includes("hand")&&(!i.leftHand&&n.includes("left")&&($u&&console.log("FOUND AVATAR LEFT HAND",e.name),i.leftHand=new Y("",t,e)),!i.rightHand&&n.includes("right")&&($u&&console.log("FOUND AVATAR RIGHT HAND",e.name),i.rightHand=new Y("",t,e)));for(let o=0;o<e.children.length;o++){if(i.head&&i.leftHand&&i.rightHand)return;const r=e.children[o];this.tryFindAvatarObjects(r,t,i)}}}const _t=new c.Vector3,yy=new c.Vector3,_y=new c.Quaternion,CS=w("debuggizmos"),Gi=8947848,Wu=32;class j{constructor(){}static enabled=!0;static isGizmo(e){return e[Yf]!==void 0}static setVisible(e){for(const t of xi.timedObjectsBuffer)t.visible=e}static DrawLabel(e,t,i=.05,n=0,o,r,a){if(!j.enabled)return null;o||(o=Gi);const l=q.active?.rigScale??1,h=xi.getTextLabel(n,t,i*l,o,r);return a instanceof c.Object3D&&a.add(h),h.position.x=e.x,h.position.y=e.y,h.position.z=e.z,h}static DrawRay(e,t,i=Gi,n=0,o=!0){if(!j.enabled)return;const r=xi.getLine(n),a=r.geometry.getAttribute("position");a.setXYZ(0,e.x,e.y,e.z),_t.set(t.x,t.y,t.z).multiplyScalar(999999999),a.setXYZ(1,e.x+_t.x,e.y+_t.y,e.z+_t.z),a.needsUpdate=!0,r.material.color.set(i),r.material.depthTest=o,r.material.depthWrite=!1}static DrawDirection(e,t,i=Gi,n=0,o=!0,r=1){if(!j.enabled)return;const a=xi.getLine(n),l=a.geometry.getAttribute("position");l.setXYZ(0,e.x,e.y,e.z),t.w!==void 0?(_t.set(0,0,-r),_y.set(t.x,t.y,t.z,t.w),_t.applyQuaternion(_y)):(_t.set(t.x,t.y,t.z),_t.multiplyScalar(r)),l.setXYZ(1,e.x+_t.x,e.y+_t.y,e.z+_t.z),l.needsUpdate=!0,a.material.color.set(i),a.material.depthTest=o,a.material.depthWrite=!1}static DrawLine(e,t,i=Gi,n=0,o=!0){if(!j.enabled)return;const r=xi.getLine(n),a=r.geometry.getAttribute("position");a.setXYZ(0,e.x,e.y,e.z),a.setXYZ(1,t.x,t.y,t.z),a.needsUpdate=!0,r.material.color.set(i),r.material.depthTest=o,r.material.depthWrite=!1,r.material.fog=!1}static DrawCircle(e,t,i,n=Gi,o=0,r=!0){if(!j.enabled)return;const a=xi.getCircle(o);a.position.set(e.x,e.y,e.z),a.scale.set(i,i,i),a.quaternion.setFromUnitVectors(this._up,_t.set(t.x,t.y,t.z).normalize()),a.material.color.set(n),a.material.depthTest=r,a.material.depthWrite=!1,a.material.fog=!1}static DrawWireSphere(e,t,i=Gi,n=0,o=!0){if(!j.enabled)return;const r=xi.getSphere(t,n,!0);zo(r,e.x,e.y,e.z),r.material.color.set(i),r.material.depthTest=o,r.material.depthWrite=!1,r.material.fog=!1}static DrawSphere(e,t,i=Gi,n=0,o=!0){if(!j.enabled)return;const r=xi.getSphere(t,n,!1);zo(r,e.x,e.y,e.z),r.material.color.set(i),r.material.depthTest=o,r.material.depthWrite=!1}static DrawWireBox(e,t,i=Gi,n=0,o=!0,r=void 0){if(!j.enabled)return;const a=xi.getBox(n);a.position.set(e.x,e.y,e.z),a.scale.set(t.x,t.y,t.z),r?a.quaternion.copy(r):a.quaternion.identity(),a.material.color.set(i),a.material.depthTest=o,a.material.wireframe=!0,a.material.depthWrite=!1,a.material.fog=!1}static DrawWireBox3(e,t=Gi,i=0,n=!0){if(!j.enabled)return;const o=xi.getBox(i);o.position.copy(e.getCenter(_t)),o.scale.copy(e.getSize(_t)),o.material.color.set(t),o.material.depthTest=n,o.material.wireframe=!0,o.material.depthWrite=!1,o.material.fog=!1}static _up=new c.Vector3(0,1,0);static DrawArrow(e,t,i=Gi,n=0,o=!0,r=!1){if(!j.enabled)return;const a=xi.getArrowHead(n);a.position.set(t.x,t.y,t.z),a.quaternion.setFromUnitVectors(this._up.set(0,1,0),_t.set(t.x,t.y,t.z).sub(yy.set(e.x,e.y,e.z)).normalize());const h=_t.set(t.x,t.y,t.z).sub(yy.set(e.x,e.y,e.z)).length()*.1;a.scale.set(h,h,h),a.material.color.set(i),a.material.depthTest=o,a.material.wireframe=r,this.DrawLine(e,t,i,n,o)}static DrawWireMesh(e){const t=xi.getMesh(e.duration??0);"mesh"in e?(t.geometry=e.mesh.geometry,t.matrix.copy(e.mesh.matrixWorld)):(t.geometry=e.geometry,t.matrix.copy(e.matrix)),t.matrixAutoUpdate=!1,t.matrixWorldAutoUpdate=!1,t.material.color.set(e.color??Gi),t.material.depthTest=e.depthTest??!0,t.material.wireframe=!0}}const PS=new c.BoxGeometry(1,1,1);function nm(s=null){const e=new c.Color(s??14540253),t=new c.EdgesGeometry(PS);return new c.LineSegments(t,new c.LineBasicMaterial({color:e}))}const Yf=Symbol("GizmoCache");class xi{static familyName="needle-gizmos";static ensureFont(){let e=J.__webpack_exports__default.FontLibrary.getFontFamily(this.familyName);e||(e=J.__webpack_exports__default.FontLibrary.addFontFamily(this.familyName),e.addVariant("normal","normal","https://uploads.needle.tools/include/font-msdf.json","https://uploads.needle.tools/include/font.png")?.addEventListener("ready",()=>{J.__webpack_exports__default.update()}))}static getTextLabel(e,t,i,n,o){this.ensureFont();let r=this.textLabelCache.pop(),a=1;o&&typeof o=="string"&&o?.length>=8&&o.startsWith("#")?(a=parseInt(o.substring(7),16)/255,o=o.substring(0,7),CS&&console.log(o,a)):typeof o=="object"&&o.a!==void 0&&(a=o.a);const l={boxSizing:"border-box",fontFamily:this.familyName,width:"auto",fontSize:i,color:n,lineHeight:1,backgroundColor:o??void 0,backgroundOpacity:a,textContent:t,borderRadius:.5*i,padding:.8*i,whiteSpace:"pre",offset:.05*i};if(r)r.set(l);else{r=new J.__webpack_exports__Text(l);const h=this,d=r;d.setText=function(u){this.set({textContent:u}),h.tmuiNeedsUpdate=!0}}return this.tmuiNeedsUpdate=!0,this.registerTimedObject(U.Current,r,e,this.textLabelCache),r}static getBox(e){let t=this.boxesCache.pop();if(!t){const i=new c.BoxGeometry(1,1,1);t=new c.Mesh(i)}return this.registerTimedObject(U.Current,t,e,this.boxesCache),t}static getLine(e){let t=this.linesCache.pop();if(!t){t=new c.Line;let i=t.geometry.getAttribute("position");i||(i=new c.BufferAttribute(new Float32Array(6),3),t.geometry.setAttribute("position",i))}return t.frustumCulled=!1,this.registerTimedObject(U.Current,t,e,this.linesCache),t}static getCircle(e){let t=this.circlesCache.pop();if(!t){t=new c.Line;let i=t.geometry.getAttribute("position");if(!i){i=new c.BufferAttribute(new Float32Array(Wu*3),3),t.geometry.setAttribute("position",i);const n=V(0,1,0),o=V(0,0,1),r=V(o);r.cross(n).normalize();const a=V(r),l=Math.PI*2/(Wu-1);for(let h=0;h<Wu+1;h++){const d=l*h;n.copy(a).multiplyScalar(Math.cos(d)*1),r.copy(o).multiplyScalar(Math.sin(d)*1);const u=n.add(r);i.setXYZ(h,u.x,u.y,u.z)}}}return t.frustumCulled=!1,this.registerTimedObject(U.Current,t,e,this.circlesCache),t}static getSphere(e,t,i){let n=this.spheresCache.pop();return n||(n=new c.Mesh(new c.SphereGeometry(1,8,8))),n.scale.set(e,e,e),n.material.wireframe=i,this.registerTimedObject(U.Current,n,t,this.spheresCache),n}static getArrowHead(e){let t=this.arrowHeadsCache.pop();return t||(t=new c.Mesh(new c.CylinderGeometry(0,.5,1,8))),this.registerTimedObject(U.Current,t,e,this.arrowHeadsCache),t}static getMesh(e){let t=this.mesh.pop();return t||(t=new c.Mesh,t.material=new c.MeshBasicMaterial),this.registerTimedObject(U.Current,t,e,this.mesh),t}static linesCache=[];static circlesCache=[];static spheresCache=[];static boxesCache=[];static arrowHeadsCache=[];static mesh=[];static textLabelCache=[];static registerTimedObject(e,t,i,n){if(!e){console.error("No Needle Engine context available. Did you call a Gizmos function in global scope?");return}const o=this.contextBeforeRenderCallbacks.get(e),r=this.contextPostRenderCallbacks.get(e);if(o){if(e.pre_render_callbacks[e.pre_render_callbacks.length-1]!==o){const a=e.pre_render_callbacks.indexOf(o);a>=0&&e.pre_render_callbacks.splice(a,1),e.pre_render_callbacks.push(o)}}else{const a=()=>{this.onBeforeRender(e,this.timedObjectsBuffer)};this.contextBeforeRenderCallbacks.set(e,a),e.pre_render_callbacks.push(a)}if(r){if(e.post_render_callbacks[e.post_render_callbacks.length-1]!==r){const a=e.post_render_callbacks.indexOf(r);a>=0&&e.post_render_callbacks.splice(a,1),e.post_render_callbacks.push(r)}}else{const a=()=>{this.onPostRender(e,this.timedObjectsBuffer,this.timesBuffer)};this.contextPostRenderCallbacks.set(e,a),e.post_render_callbacks.push(a)}t.traverse(a=>{a.layers.disableAll(),a.layers.enable(2)}),t.renderOrder=999999,t[Yf]=n,t.castShadow=!1,t.receiveShadow=!1,t.isGizmo=!0,this.timedObjectsBuffer.push(t),this.timesBuffer.push(U.Current.time.realtimeSinceStartup+i),e.scene.add(t)}static timedObjectsBuffer=new Array;static timesBuffer=new Array;static contextPostRenderCallbacks=new Map;static contextBeforeRenderCallbacks=new Map;static tmuiNeedsUpdate=!1;static onBeforeRender(e,t){this.tmuiNeedsUpdate&&(this.tmuiNeedsUpdate=!1,J.__webpack_exports__default.update());for(let i=0;i<t.length;i++){const n=t[i];if(e.mainCamera&&n instanceof J.__webpack_exports__default.MeshUIBaseElement){if(Vo(n))continue;const o=e.isInVR,r=!1,a=!o;tc(n,e.mainCamera,r,a)}}}static onPostRender(e,t,i){const n=e.time.realtimeSinceStartup;for(let o=t.length-1;o>=0;o--){const r=t[o];n>=i[o]-1e-6&&(t.splice(o,1),i.splice(o,1),r.removeFromParent(),Vo(r)!=!0&&r[Yf].push(r))}}}const Dt=w("debugphysics"),by=new c.Layers;class eo{static AllLayers=4294967295;ray;cam;screenPoint;raycaster;results;targets;recursive=!0;minDistance;maxDistance;lineThreshold;layerMask;ignore;testObject;useAcceleratedRaycast;allowSlowRaycastFallback=!0;screenPointFromOffset(e,t){this.screenPoint===void 0&&(this.screenPoint=new c.Vector2),this.screenPoint.x=e/window.innerWidth*2-1,this.screenPoint.y=-(t/window.innerHeight)*2+1}setLayer(e){by.set(e),this.layerMask=by}setMask(e){this.layerMask||(this.layerMask=new c.Layers);const t=this.layerMask;t?t.mask=e:this.layerMask=e}}class sm{distance;point;object;constructor(e,t,i){this.object=e,this.distance=t,this.point=i}}class na{static _raycasting=0;static get raycasting(){return this._raycasting>0}raycastPhysicsFast(e,t=void 0,i=1/0,n=!0){return this.context.physics.engine?.raycast(e,t,{maxDistance:i,solid:n})??null}raycastPhysicsFastAndGetNormal(e,t=void 0,i=1/0,n=!0){return this.context.physics.engine?.raycastAndGetNormal(e,t,{maxDistance:i,solid:n})??null}sphereOverlapPhysics(e,t){return this.context.physics.engine?.sphereOverlap(e,t)??null}context;engine;constructor(e){this.context=e}raycaster=new c.Raycaster;defaultRaycastOptions=new eo;targetBuffer=new Array(1);defaultThresholds={Mesh:{},Line:{threshold:-1},LOD:{},Points:{threshold:0},Sprite:{}};sphereResults=new Array;sphereMask=new c.Layers;sphere=new c.Sphere;sphereOverlap(e,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 a of this.context.scene.children)this.intersectSphere(a,e,t,r,this.sphereResults,i,n,o);return this.sphereResults.sort((a,l)=>a.distance-l.distance)}raycastFromRay(e,t=null){const i=t??this.defaultRaycastOptions;i.ray=e;const n=this.raycast(i);return i===this.defaultRaycastOptions&&(i.ray=void 0),n}raycast(e=null){Dt&&performance.mark("raycast.start"),e||(e=this.defaultRaycastOptions);const t=e.screenPoint??this.context.input.mousePositionRC,i=e.raycaster??this.raycaster;if(i.near=e.minDistance??0,i.far=e.maxDistance??1/0,i.params=this.defaultThresholds,e.lineThreshold===void 0&&(e.lineThreshold=-1),i.params.Line={threshold:e.lineThreshold},e.ray)i.ray.copy(e.ray);else{const a=e.cam??this.context.mainCamera;if(!a)return Dt&&console.error("Can not perform raycast - no main camera found"),this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),this.defaultRaycastOptions.results??[];const l=this.context.xrCamera;this.context.isInXR&&l instanceof c.ArrayCamera&&l.cameras.length>0?i.setFromCamera(t,l.cameras[0]):i.setFromCamera(t,a)}let n=e.targets;n||(n=this.targetBuffer,n.length=1,n[0]=this.context.scene);let o=e.results;this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),o||(this.defaultRaycastOptions.results||(this.defaultRaycastOptions.results=new Array),o=this.defaultRaycastOptions.results),e.layerMask!==void 0?e.layerMask instanceof c.Layers?i.layers.mask=e.layerMask.mask:i.layers.mask=e.layerMask:(i.layers.enableAll(),i.layers.disable(2)),Dt&&console.time("raycast"),o.length=0,na._raycasting++,this.intersect(this.raycaster,n,o,e),o.sort((a,l)=>a.distance-l.distance);const r=e.ignore;return r!==void 0&&r.length>0&&(o=o.filter(a=>!r.includes(a.object))),na._raycasting--,Dt&&(console.timeEnd("raycast"),console.warn("#"+this.context.time.frame+", hits:",o?.length?[...o]:"nothing"),performance.mark("raycast.end"),performance.measure("raycast","raycast.start","raycast.end")),o}intersect(e,t,i,n){for(const o of t){if(!o||o.visible===!1||j.isGizmo(o)||n.lineThreshold!==void 0&&n.lineThreshold<0&&o instanceof c.Line)continue;let r=!0;const a=o,l=a.geometry;if(n.testObject){const h=n.testObject?.(o);if(h===!1)continue;h==="continue in children"&&(r=!1)}if(r&&(l&&vy(l)||(r=!1)),r){const h=ne.getRaycastMesh(o);h&&(a.geometry=h);const d=i.length;let u=!0;if(n.precise===!1&&(u=!1),u||=l.getAttribute("position")?.array?.length<64,a instanceof G.GroundedSkybox&&(u=!1),!u&&OS(a,e,i)||(n.useAcceleratedRaycast!==!1?ed.runMeshBVHRaycast(e,a,i,this.context,n):e.intersectObject(a,!1,i)),Dt&&i.length!=d){const p=i[i.length-1],m=h?8969557:7798784;j.DrawWireSphere(p.point,.1,m,1,!1),j.DrawWireMesh({mesh:o,depthTest:!1,duration:.2,color:m})}a.geometry=l}n.recursive!==!1&&this.intersect(e,o.children,i,n)}return i}tempBoundingBox=new c.Box3;intersectSphere(e,t,i,n,o,r,a,l){let h=e&&e.isMesh&&e.layers.test(n)&&!j.isGizmo(e);h&&=e.visible,h&&=!(e instanceof c.Line),h&&=!(e instanceof G.GroundedSkybox);const d=e,u=d.geometry;if(h&&l){const p=l(e);if(p===!1)return;p==="continue in children"&&(h=!1)}if(u&&vy(u)||(h=!1),h){if(a){const p=this.sphere;p.center.copy(t),p.radius=i;const m=o.length;if(ed.runMeshBVHRaycast(this.sphere,d,o,this.context,{}),m!=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),m=this.sphere;if(m.center.copy(t),m.radius=i,m.intersectsBox(p)){const y=X(e),b=y.distanceTo(m.center),g=new sm(e,b,y);if(o.push(g),!r)return}}}if(e.children)for(const p of e.children){const m=o.length;if(this.intersectSphere(p,t,i,n,o,r,a,l),m!=o.length&&!r)return}}}function vy(s){return!(s.index&&s.index.array.length<3)}const mo=new c.Sphere,nh=new c.Plane,MS=new c.Matrix3;function OS(s,e,t){const i=s._computeIntersections;if(!i)return!1;let n=s["_computeIntersections:Needle"];return n||(n=s["_computeIntersections:Needle"]=function(o,r,a){const l=this,h=l.geometry.boundingSphere;if(h){if(l instanceof G.GroundedSkybox){nh.setFromNormalAndCoplanarPoint(V(0,1,0),V(0,-l.position.y,0)),nh.applyMatrix4(l.matrixWorld,MS);const u=o.ray.intersectPlane(nh,V());if(u){mo.copy(h),mo.applyMatrix4(l.matrixWorld);const m=V(u).sub(o.ray.origin).length(),y=mo.radius*.5;m<y&&r.push({distance:m,point:u,object:l,normal:nh.normal.clone()})}return}mo.copy(h),mo.applyMatrix4(l.matrixWorld);const d=o.ray.intersectSphere(mo,V());if(d){const u=V(d).sub(o.ray.origin),p=u.length();if(p>mo.radius){const m=u.clone().normalize();r.push({distance:p,point:d,object:l,normal:m})}}}}),s._computeIntersections=n,e.intersectObject(s,!1,t),s._computeIntersections=i,!0}var ed;(s=>{function e(v,_,S,T,M){if(!_.geometry||!_.geometry.hasAttribute("position"))return!1;const O=_.geometry;if(_?.isSkinnedMesh){const R=_,B=R.bvhNeedsUpdate;if(!R.staticGenerator)a(),o&&(R.staticGenerator=new o(_),R.staticGenerator.applyWorldTransforms=!1,R.staticGeometry=R.staticGenerator.generate(),O.boundsTree=r?.call(R.staticGeometry),R.staticGeometryLastUpdate=performance.now()+Math.random()*200,R.bvhNeedsUpdate=!0);else if(O.boundsTree&&(R.autoUpdateMeshBvhInterval!==void 0&&R.autoUpdateMeshBvhInterval>=0||B===!0)){const L=performance.now(),N=L-R.staticGeometryLastUpdate,$=R.autoUpdateMeshBvhInterval??100;(B||N>$)&&(Dt&&console.warn(`Physics: updating skinned mesh bvh for ${_.name} after ${N.toFixed(2)}ms`),R.bvhNeedsUpdate=!1,R.staticGeometryLastUpdate=L,R.staticGenerator?.generate(R.staticGeometry),O.boundsTree.refit())}}else if(!O.boundsTree){h||g();let R=!0;if((T.xr||O[m]===!1||O.getAttribute("position")?.isInterleavedBufferAttribute||O.index&&O.index?.isInterleavedBufferAttribute)&&(R=!1),R&&u){if(O[p]===void 0){let B=null;if(b.length>0){const L=b.shift();L&&!L.running&&(B=L)}if(!B&&y.length<3&&(B=new u,y.push(B)),B!=null&&!B.running){const L=_.name;Dt&&console.log("<<<< worker start",L,B),O[p]="queued",performance.mark("bvh.create.start");const N=O.clone();try{B.generate(N).then($=>{O[p]="done",O.boundsTree=$}).catch($=>{O[p]="failed - "+$?.message,O[m]=!1,Dt&&console.error("Failed to generate mesh bvh on worker",$)}).finally(()=>{Dt&&console.log(">>>>> worker done",L,{hasBoundsTre:O.boundsTree!=null}),b.push(B),N.dispose(),performance.mark("bvh.create.end"),performance.measure("bvh.create (worker)","bvh.create.start","bvh.create.end")})}catch($){console.error("Failed to generate mesh bvh on worker",$)}}else Dt&&console.warn("No worker available")}}else(!d||!R)&&(a(),n&&(performance.mark("bvh.create.start"),O.boundsTree=new n(O),performance.mark("bvh.create.end"),performance.measure("bvh.create","bvh.create.start","bvh.create.end")))}if(v instanceof c.Raycaster){const R=v,B=_.raycast;if(O.boundsTree)a(),i&&(_.acceleratedRaycast||(_.acceleratedRaycast=i.bind(_),Dt&&console.debug(`Physics: bind acceleratedRaycast fn to "${_.name}"`)),_.raycast=_.acceleratedRaycast);else if(Dt&&console.warn("No bounds tree found for mesh",_.name,{workerTask:O[p],hasAcceleratedRaycast:i!=null}),M.allowSlowRaycastFallback===!1)return Dt&&console.warn("Skipping raycast because no bounds tree is available and allowSlowRaycastFallback is false"),!1;const L=R.firstHitOnly;return R.firstHitOnly=!1,R.intersectObject(_,!1,S),R.firstHitOnly=L,_.raycast=B,!0}else if(v instanceof c.Sphere){const R=O.boundsTree;if(R){const B=v;if(l.copy(_.matrixWorld).invert(),B.applyMatrix4(l),R.intersectsSphere(B)){const N=X(_),$=N.distanceTo(B.center),E=new sm(_,$,N);S.push(E)}}return!0}return!1}s.runMeshBVHRaycast=e;let t=!1,i=null,n=null,o=null,r=null;function a(){t||(t=!0,Promise.resolve().then(()=>require("./vendor-Cty8Dnri.umd.cjs")).then(v=>v.index$1).then(v=>{i=v.acceleratedRaycast,n=v.MeshBVH,o=v.StaticGeometryGenerator,r=v.computeBoundsTree}).catch(v=>{(Dt||A())&&console.error("Failed to load BVH library...",v.message)}))}const l=new c.Matrix4;let h=!1,d=!1,u=null;const p=Symbol("Needle:MeshBVH-Worker"),m=Symbol("Needle:MeshBVH-CanUseWorker"),y=[],b=[];function g(){h=!0,d=!0,Promise.resolve().then(()=>eE).then(v=>{u=v.GenerateMeshBVHWorker}).catch(v=>{(Dt||A())&&console.warn("Failed to setup mesh bvh worker")}).finally(()=>{d=!1})}})(ed||(ed={}));const wy=Symbol("gltf-loader-internal-usage-tracker"),kS=w("debugusers");class Hr{get name(){return"NEEDLE_internal_usage_tracker"}static isLoading(e){return Hr._loadingProcesses>0}static _loadingProcesses=0;parser;_getDependency;_loadingId;_loadedObjects=new Set;constructor(e){this.parser=e,this._getDependency=this.parser.getDependency,this._loadingId=Date.now().toString()}beforeRoot(){Hr._loadingProcesses++;const e=this,t=this._getDependency;return this.parser.getDependency=function(i,n){const o=t.call(this,i,n);return o.then(r=>(r&&(e._loadedObjects.add(r),r[wy]=e._loadingId),r)),o},null}afterRoot(e){Hr._loadingProcesses--,this.parser.getDependency=this._getDependency;for(const t of this._loadedObjects)delete t[wy],t instanceof c.Object3D&&(t.parent||t instanceof c.Mesh&&setTimeout(()=>{kS&&console.warn("> GLTF LOADER: Mesh not used in scene!",t),t.material=null,t.geometry=null},1e3));return null}}class zb{constructor(){window.addEventListener("unhandledrejection",e=>{if(e.defaultPrevented)return;const t=e?.reason?.path;if(t){const i=t[0];i&&i.tagName==="IMG"&&(console.warn(`Could not load image:
166
+ ${o.hand?"hand":"ctrl"} ${o.inputSource.handedness}[${o.index}] con:${o.connected} tr:${o.isTracking} hts:${o.hasHitTestSource?"yes":"no"}`;Vu=0,j.DrawLabel(e,n,void 0,1/60*20)}}onBeforeRender=()=>{this.context.mainCamera&&this.updateFade(this.context.mainCamera)};onAfterRender=()=>{if(this.onUpdateFade_PostRender(),exports.DeviceUtilities.isDesktop()||!this._renderOnceOnDevice){const e=this.context.renderer;if(e.xr.isPresenting&&this.context.mainCamera){this._renderOnceOnDevice=!0;const t=e.xr.enabled,i=e.getRenderTarget(),n=this.context.scene.background;e.xr.enabled=!1,e.setRenderTarget(null),this.isPassThrough&&(this.context.scene.background=null),this.context.composer?this.context.composer.render(this.context.time.deltaTime):e.render(this.context.scene,this.context.mainCamera),e.xr.enabled=t,e.setRenderTarget(i),this.context.scene.background=n}}};addScript(e){return this._xr_scripts.includes(e)?!1:(je&&console.log("Register new XRScript",e),this._xr_scripts.push(e),typeof e.onUpdateXR=="function"&&this._xr_update_scripts.push(e),!0)}markInactive(e){if(!(this._inactive_scripts.indexOf(e)>=0)){this.removeScript(e,!1),this._inactive_scripts.push(e);for(const t of this.controllers)this.invokeCallback_ControllerRemoved(e,t);this.invokeCallback_LeaveXR(e)}}handleInactiveScripts(){if(this._inactive_scripts.length>0)for(let e=this._inactive_scripts.length-1;e>=0;e--){const t=this._inactive_scripts[e];if(t.activeAndEnabled){this._inactive_scripts.splice(e,1),this.addScript(t),this.invokeCallback_EnterXR(t);for(const i of this.controllers)this.invokeCallback_ControllerAdded(t,i)}}}_script_to_remove=[];removeScript(e,t=!0){je&&console.log("Remove XRScript",e);const i=this._xr_scripts.indexOf(e);i>=0&&this._xr_scripts.splice(i,1);const n=this._xr_update_scripts.indexOf(e);if(n>=0&&this._xr_update_scripts.splice(n,1),t){const o=this._inactive_scripts.indexOf(e);o>=0&&this._inactive_scripts.splice(o,1)}}invokeCallback_EnterXR(e){e.onEnterXR&&e.onEnterXR({xr:this})}invokeCallback_ControllerAdded(e,t){e.onXRControllerAdded&&e.onXRControllerAdded({xr:this,controller:t,change:"added"})}invokeCallback_ControllerRemoved(e,t){e.onXRControllerRemoved&&e.onXRControllerRemoved({xr:this,controller:t,change:"removed"})}invokeCallback_LeaveXR(e){e.onLeaveXR&&!e.destroyed&&e.onLeaveXR({xr:this})}syncCameraCullingMask(){const e=this.context.xrCamera,t=this.context.mainCameraComponent?.cullingMask;if(e&&t!==void 0){for(const i of e.cameras)i.layers.mask=t;e.layers.mask=t}else if(e){for(const i of e.cameras)i.layers.enableAll();e.layers.enableAll()}}invokeControllerEvent(e,t,i){for(let n=t.length-1;n>=0;n--){const o=t[n];if(o)try{o({xr:this,controller:e,change:i})}catch(r){console.error(r)}}}_camera;_cameraRenderParent=new c.Object3D().rotateY(Math.PI);_previousCameraParent;_customforward=!0;originalCameraNearPlane;applyCustomForward(){if(this.context.mainCamera&&this._customforward){this._camera=this.context.mainCamera,this._camera.parent!==this._cameraRenderParent&&(this._previousCameraParent=this._camera.parent,this._previousCameraParent?.add(this._cameraRenderParent)),this._cameraRenderParent.name="XR Camera Render Parent",this._cameraRenderParent.add(this._camera);let e=.02;if(this.rig){const t=Ae(this.rig.gameObject);e*=t.x}this._camera instanceof c.PerspectiveCamera&&this._camera.near>e&&(this.originalCameraNearPlane=this._camera.near,this._camera.near=e)}}revertCustomForward(){this._camera&&this._previousCameraParent&&this._previousCameraParent.add(this._camera),this._previousCameraParent=null,this._camera instanceof c.PerspectiveCamera&&this.originalCameraNearPlane!=null&&(this._camera.near=this.originalCameraNearPlane)}_viewerPose;_transformOrientation=new c.Quaternion;_transformPosition=new c.Vector3;internalUpdateState(){const e=this.context.renderer.xr.getReferenceSpace();if(!e){this._viewerPose=void 0;return}if(this._viewerPose=this.frame.getViewerPose(e),this._viewerPose){const t=this._viewerPose.transform;this._transformPosition.set(t.position.x,t.position.y,t.position.z),this._transformOrientation.set(t.orientation.x,t.orientation.y,t.orientation.z,t.orientation.w)}}_transition;get transition(){return this._transition||(this._transition=new fy),this._transition}fadeTransition(){return this._transition||(this._transition=new fy),this._transition.fadeTransition()}updateFade(e){this._transition&&e instanceof c.PerspectiveCamera&&this._transition.update(e,this.context.time.deltaTime)}onUpdateFade_PostRender(){this._transition?.remove()}}const $u=w("debugwebxr");class Ub{static tryFindAvatarObjects(e,t,i){if(i.head&&i.leftHand&&i.rightHand)return;const n=e.name.toLocaleLowerCase();!i.head&&n.includes("head")&&($u&&console.log("FOUND AVATAR HEAD",e.name),i.head=new Y("",t,e)),n.includes("hand")&&(!i.leftHand&&n.includes("left")&&($u&&console.log("FOUND AVATAR LEFT HAND",e.name),i.leftHand=new Y("",t,e)),!i.rightHand&&n.includes("right")&&($u&&console.log("FOUND AVATAR RIGHT HAND",e.name),i.rightHand=new Y("",t,e)));for(let o=0;o<e.children.length;o++){if(i.head&&i.leftHand&&i.rightHand)return;const r=e.children[o];this.tryFindAvatarObjects(r,t,i)}}}const _t=new c.Vector3,yy=new c.Vector3,_y=new c.Quaternion,CS=w("debuggizmos"),Gi=8947848,Wu=32;class j{constructor(){}static enabled=!0;static isGizmo(e){return e[Yf]!==void 0}static setVisible(e){for(const t of xi.timedObjectsBuffer)t.visible=e}static DrawLabel(e,t,i=.05,n=0,o,r,a){if(!j.enabled)return null;o||(o=Gi);const l=q.active?.rigScale??1,h=xi.getTextLabel(n,t,i*l,o,r);return a instanceof c.Object3D&&a.add(h),h.position.x=e.x,h.position.y=e.y,h.position.z=e.z,h}static DrawRay(e,t,i=Gi,n=0,o=!0){if(!j.enabled)return;const r=xi.getLine(n),a=r.geometry.getAttribute("position");a.setXYZ(0,e.x,e.y,e.z),_t.set(t.x,t.y,t.z).multiplyScalar(999999999),a.setXYZ(1,e.x+_t.x,e.y+_t.y,e.z+_t.z),a.needsUpdate=!0,r.material.color.set(i),r.material.depthTest=o,r.material.depthWrite=!1}static DrawDirection(e,t,i=Gi,n=0,o=!0,r=1){if(!j.enabled)return;const a=xi.getLine(n),l=a.geometry.getAttribute("position");l.setXYZ(0,e.x,e.y,e.z),t.w!==void 0?(_t.set(0,0,-r),_y.set(t.x,t.y,t.z,t.w),_t.applyQuaternion(_y)):(_t.set(t.x,t.y,t.z),_t.multiplyScalar(r)),l.setXYZ(1,e.x+_t.x,e.y+_t.y,e.z+_t.z),l.needsUpdate=!0,a.material.color.set(i),a.material.depthTest=o,a.material.depthWrite=!1}static DrawLine(e,t,i=Gi,n=0,o=!0){if(!j.enabled)return;const r=xi.getLine(n),a=r.geometry.getAttribute("position");a.setXYZ(0,e.x,e.y,e.z),a.setXYZ(1,t.x,t.y,t.z),a.needsUpdate=!0,r.material.color.set(i),r.material.depthTest=o,r.material.depthWrite=!1,r.material.fog=!1}static DrawCircle(e,t,i,n=Gi,o=0,r=!0){if(!j.enabled)return;const a=xi.getCircle(o);a.position.set(e.x,e.y,e.z),a.scale.set(i,i,i),a.quaternion.setFromUnitVectors(this._up,_t.set(t.x,t.y,t.z).normalize()),a.material.color.set(n),a.material.depthTest=r,a.material.depthWrite=!1,a.material.fog=!1}static DrawWireSphere(e,t,i=Gi,n=0,o=!0){if(!j.enabled)return;const r=xi.getSphere(t,n,!0);zo(r,e.x,e.y,e.z),r.material.color.set(i),r.material.depthTest=o,r.material.depthWrite=!1,r.material.fog=!1}static DrawSphere(e,t,i=Gi,n=0,o=!0){if(!j.enabled)return;const r=xi.getSphere(t,n,!1);zo(r,e.x,e.y,e.z),r.material.color.set(i),r.material.depthTest=o,r.material.depthWrite=!1}static DrawWireBox(e,t,i=Gi,n=0,o=!0,r=void 0){if(!j.enabled)return;const a=xi.getBox(n);a.position.set(e.x,e.y,e.z),a.scale.set(t.x,t.y,t.z),r?a.quaternion.copy(r):a.quaternion.identity(),a.material.color.set(i),a.material.depthTest=o,a.material.wireframe=!0,a.material.depthWrite=!1,a.material.fog=!1}static DrawWireBox3(e,t=Gi,i=0,n=!0){if(!j.enabled)return;const o=xi.getBox(i);o.position.copy(e.getCenter(_t)),o.scale.copy(e.getSize(_t)),o.material.color.set(t),o.material.depthTest=n,o.material.wireframe=!0,o.material.depthWrite=!1,o.material.fog=!1}static _up=new c.Vector3(0,1,0);static DrawArrow(e,t,i=Gi,n=0,o=!0,r=!1){if(!j.enabled)return;const a=xi.getArrowHead(n);a.position.set(t.x,t.y,t.z),a.quaternion.setFromUnitVectors(this._up.set(0,1,0),_t.set(t.x,t.y,t.z).sub(yy.set(e.x,e.y,e.z)).normalize());const h=_t.set(t.x,t.y,t.z).sub(yy.set(e.x,e.y,e.z)).length()*.1;a.scale.set(h,h,h),a.material.color.set(i),a.material.depthTest=o,a.material.wireframe=r,this.DrawLine(e,t,i,n,o)}static DrawWireMesh(e){const t=xi.getMesh(e.duration??0);"mesh"in e?(t.geometry=e.mesh.geometry,t.matrix.copy(e.mesh.matrixWorld)):(t.geometry=e.geometry,t.matrix.copy(e.matrix)),t.matrixAutoUpdate=!1,t.matrixWorldAutoUpdate=!1,t.material.color.set(e.color??Gi),t.material.depthTest=e.depthTest??!0,t.material.wireframe=!0}}const PS=new c.BoxGeometry(1,1,1);function nm(s=null){const e=new c.Color(s??14540253),t=new c.EdgesGeometry(PS);return new c.LineSegments(t,new c.LineBasicMaterial({color:e}))}const Yf=Symbol("GizmoCache");class xi{static familyName="needle-gizmos";static ensureFont(){let e=J.__webpack_exports__default.FontLibrary.getFontFamily(this.familyName);e||(e=J.__webpack_exports__default.FontLibrary.addFontFamily(this.familyName),e.addVariant("normal","normal","https://uploads.needle.tools/include/font-msdf.json","https://uploads.needle.tools/include/font.png")?.addEventListener("ready",()=>{J.__webpack_exports__default.update()}))}static getTextLabel(e,t,i,n,o){this.ensureFont();let r=this.textLabelCache.pop(),a=1;o&&typeof o=="string"&&o?.length>=8&&o.startsWith("#")?(a=parseInt(o.substring(7),16)/255,o=o.substring(0,7),CS&&console.log(o,a)):typeof o=="object"&&o.a!==void 0&&(a=o.a);const l={boxSizing:"border-box",fontFamily:this.familyName,width:"auto",fontSize:i,color:n,lineHeight:1,backgroundColor:o??void 0,backgroundOpacity:a,textContent:t,borderRadius:.5*i,padding:.8*i,whiteSpace:"pre",offset:.05*i};if(r)r.set(l);else{r=new J.__webpack_exports__Text(l);const h=this,d=r;d.setText=function(u){this.set({textContent:u}),h.tmuiNeedsUpdate=!0}}return this.tmuiNeedsUpdate=!0,this.registerTimedObject(U.Current,r,e,this.textLabelCache),r}static getBox(e){let t=this.boxesCache.pop();if(!t){const i=new c.BoxGeometry(1,1,1);t=new c.Mesh(i)}return this.registerTimedObject(U.Current,t,e,this.boxesCache),t}static getLine(e){let t=this.linesCache.pop();if(!t){t=new c.Line;let i=t.geometry.getAttribute("position");i||(i=new c.BufferAttribute(new Float32Array(6),3),t.geometry.setAttribute("position",i))}return t.frustumCulled=!1,this.registerTimedObject(U.Current,t,e,this.linesCache),t}static getCircle(e){let t=this.circlesCache.pop();if(!t){t=new c.Line;let i=t.geometry.getAttribute("position");if(!i){i=new c.BufferAttribute(new Float32Array(Wu*3),3),t.geometry.setAttribute("position",i);const n=V(0,1,0),o=V(0,0,1),r=V(o);r.cross(n).normalize();const a=V(r),l=Math.PI*2/(Wu-1);for(let h=0;h<Wu+1;h++){const d=l*h;n.copy(a).multiplyScalar(Math.cos(d)*1),r.copy(o).multiplyScalar(Math.sin(d)*1);const u=n.add(r);i.setXYZ(h,u.x,u.y,u.z)}}}return t.frustumCulled=!1,this.registerTimedObject(U.Current,t,e,this.circlesCache),t}static getSphere(e,t,i){let n=this.spheresCache.pop();return n||(n=new c.Mesh(new c.SphereGeometry(1,8,8))),n.scale.set(e,e,e),n.material.wireframe=i,this.registerTimedObject(U.Current,n,t,this.spheresCache),n}static getArrowHead(e){let t=this.arrowHeadsCache.pop();return t||(t=new c.Mesh(new c.CylinderGeometry(0,.5,1,8))),this.registerTimedObject(U.Current,t,e,this.arrowHeadsCache),t}static getMesh(e){let t=this.mesh.pop();return t||(t=new c.Mesh,t.material=new c.MeshBasicMaterial),this.registerTimedObject(U.Current,t,e,this.mesh),t}static linesCache=[];static circlesCache=[];static spheresCache=[];static boxesCache=[];static arrowHeadsCache=[];static mesh=[];static textLabelCache=[];static registerTimedObject(e,t,i,n){if(!e){console.error("No Needle Engine context available. Did you call a Gizmos function in global scope?");return}const o=this.contextBeforeRenderCallbacks.get(e),r=this.contextPostRenderCallbacks.get(e);if(o){if(e.pre_render_callbacks[e.pre_render_callbacks.length-1]!==o){const a=e.pre_render_callbacks.indexOf(o);a>=0&&e.pre_render_callbacks.splice(a,1),e.pre_render_callbacks.push(o)}}else{const a=()=>{this.onBeforeRender(e,this.timedObjectsBuffer)};this.contextBeforeRenderCallbacks.set(e,a),e.pre_render_callbacks.push(a)}if(r){if(e.post_render_callbacks[e.post_render_callbacks.length-1]!==r){const a=e.post_render_callbacks.indexOf(r);a>=0&&e.post_render_callbacks.splice(a,1),e.post_render_callbacks.push(r)}}else{const a=()=>{this.onPostRender(e,this.timedObjectsBuffer,this.timesBuffer)};this.contextPostRenderCallbacks.set(e,a),e.post_render_callbacks.push(a)}t.traverse(a=>{a.layers.disableAll(),a.layers.enable(2)}),t.renderOrder=999999,t[Yf]=n,t.castShadow=!1,t.receiveShadow=!1,t.isGizmo=!0,this.timedObjectsBuffer.push(t),this.timesBuffer.push(U.Current.time.realtimeSinceStartup+i),e.scene.add(t)}static timedObjectsBuffer=new Array;static timesBuffer=new Array;static contextPostRenderCallbacks=new Map;static contextBeforeRenderCallbacks=new Map;static tmuiNeedsUpdate=!1;static onBeforeRender(e,t){this.tmuiNeedsUpdate&&(this.tmuiNeedsUpdate=!1,J.__webpack_exports__default.update());for(let i=0;i<t.length;i++){const n=t[i];if(e.mainCamera&&n instanceof J.__webpack_exports__default.MeshUIBaseElement){if(Vo(n))continue;const o=e.isInVR,r=!1,a=!o;tc(n,e.mainCamera,r,a)}}}static onPostRender(e,t,i){const n=e.time.realtimeSinceStartup;for(let o=t.length-1;o>=0;o--){const r=t[o];n>=i[o]-1e-6&&(t.splice(o,1),i.splice(o,1),r.removeFromParent(),Vo(r)!=!0&&r[Yf].push(r))}}}const Dt=w("debugphysics"),by=new c.Layers;class eo{static AllLayers=4294967295;ray;cam;screenPoint;raycaster;results;targets;recursive=!0;minDistance;maxDistance;lineThreshold;layerMask;ignore;testObject;useAcceleratedRaycast;allowSlowRaycastFallback=!0;screenPointFromOffset(e,t){this.screenPoint===void 0&&(this.screenPoint=new c.Vector2),this.screenPoint.x=e/window.innerWidth*2-1,this.screenPoint.y=-(t/window.innerHeight)*2+1}setLayer(e){by.set(e),this.layerMask=by}setMask(e){this.layerMask||(this.layerMask=new c.Layers);const t=this.layerMask;t?t.mask=e:this.layerMask=e}}class sm{distance;point;object;constructor(e,t,i){this.object=e,this.distance=t,this.point=i}}class na{static _raycasting=0;static get raycasting(){return this._raycasting>0}raycastPhysicsFast(e,t=void 0,i=1/0,n=!0){return this.context.physics.engine?.raycast(e,t,{maxDistance:i,solid:n})??null}raycastPhysicsFastAndGetNormal(e,t=void 0,i=1/0,n=!0){return this.context.physics.engine?.raycastAndGetNormal(e,t,{maxDistance:i,solid:n})??null}sphereOverlapPhysics(e,t){return this.context.physics.engine?.sphereOverlap(e,t)??null}context;engine;constructor(e){this.context=e}raycaster=new c.Raycaster;defaultRaycastOptions=new eo;targetBuffer=new Array(1);defaultThresholds={Mesh:{},Line:{threshold:-1},LOD:{},Points:{threshold:0},Sprite:{}};sphereResults=new Array;sphereMask=new c.Layers;sphere=new c.Sphere;sphereOverlap(e,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 a of this.context.scene.children)this.intersectSphere(a,e,t,r,this.sphereResults,i,n,o);return this.sphereResults.sort((a,l)=>a.distance-l.distance)}raycastFromRay(e,t=null){const i=t??this.defaultRaycastOptions;i.ray=e;const n=this.raycast(i);return i===this.defaultRaycastOptions&&(i.ray=void 0),n}raycast(e=null){Dt&&performance.mark("raycast.start"),e||(e=this.defaultRaycastOptions);const t=e.screenPoint??this.context.input.mousePositionRC,i=e.raycaster??this.raycaster;if(i.near=e.minDistance??0,i.far=e.maxDistance??1/0,i.params=this.defaultThresholds,e.lineThreshold===void 0&&(e.lineThreshold=-1),i.params.Line={threshold:e.lineThreshold},e.ray)i.ray.copy(e.ray);else{const a=e.cam??this.context.mainCamera;if(!a)return Dt&&console.error("Can not perform raycast - no main camera found"),this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),this.defaultRaycastOptions.results??[];const l=this.context.xrCamera;this.context.isInXR&&l instanceof c.ArrayCamera&&l.cameras.length>0?i.setFromCamera(t,l.cameras[0]):i.setFromCamera(t,a)}let n=e.targets;n||(n=this.targetBuffer,n.length=1,n[0]=this.context.scene);let o=e.results;this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),o||(this.defaultRaycastOptions.results||(this.defaultRaycastOptions.results=new Array),o=this.defaultRaycastOptions.results),e.layerMask!==void 0?e.layerMask instanceof c.Layers?i.layers.mask=e.layerMask.mask:i.layers.mask=e.layerMask:(i.layers.enableAll(),i.layers.disable(2)),Dt&&console.time("raycast"),o.length=0,na._raycasting++,this.intersect(this.raycaster,n,o,e),o.sort((a,l)=>a.distance-l.distance);const r=e.ignore;return r!==void 0&&r.length>0&&(o=o.filter(a=>!r.includes(a.object))),na._raycasting--,Dt&&(console.timeEnd("raycast"),console.warn("#"+this.context.time.frame+", hits:",o?.length?[...o]:"nothing"),performance.mark("raycast.end"),performance.measure("raycast","raycast.start","raycast.end")),o}intersect(e,t,i,n){for(const o of t){if(!o||o.visible===!1||j.isGizmo(o)||n.lineThreshold!==void 0&&n.lineThreshold<0&&o instanceof c.Line)continue;let r=!0;const a=o,l=a.geometry;if(n.testObject){const h=n.testObject?.(o);if(h===!1)continue;h==="continue in children"&&(r=!1)}if(r&&(l&&vy(l)||(r=!1)),r){const h=ne.getRaycastMesh(o);h&&(a.geometry=h);const d=i.length;let u=!0;if(n.precise===!1&&(u=!1),u||=l.getAttribute("position")?.array?.length<64,a instanceof G.GroundedSkybox&&(u=!1),!u&&OS(a,e,i)||(n.useAcceleratedRaycast!==!1?ed.runMeshBVHRaycast(e,a,i,this.context,n):e.intersectObject(a,!1,i)),Dt&&i.length!=d){const p=i[i.length-1],m=h?8969557:7798784;j.DrawWireSphere(p.point,.1,m,1,!1),j.DrawWireMesh({mesh:o,depthTest:!1,duration:.2,color:m})}a.geometry=l}n.recursive!==!1&&this.intersect(e,o.children,i,n)}return i}tempBoundingBox=new c.Box3;intersectSphere(e,t,i,n,o,r,a,l){let h=e&&e.isMesh&&e.layers.test(n)&&!j.isGizmo(e);h&&=e.visible,h&&=!(e instanceof c.Line),h&&=!(e instanceof G.GroundedSkybox);const d=e,u=d.geometry;if(h&&l){const p=l(e);if(p===!1)return;p==="continue in children"&&(h=!1)}if(u&&vy(u)||(h=!1),h){if(a){const p=this.sphere;p.center.copy(t),p.radius=i;const m=o.length;if(ed.runMeshBVHRaycast(this.sphere,d,o,this.context,{}),m!=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),m=this.sphere;if(m.center.copy(t),m.radius=i,m.intersectsBox(p)){const y=X(e),b=y.distanceTo(m.center),g=new sm(e,b,y);if(o.push(g),!r)return}}}if(e.children)for(const p of e.children){const m=o.length;if(this.intersectSphere(p,t,i,n,o,r,a,l),m!=o.length&&!r)return}}}function vy(s){return!(s.index&&s.index.array.length<3)}const mo=new c.Sphere,nh=new c.Plane,MS=new c.Matrix3;function OS(s,e,t){const i=s._computeIntersections;if(!i)return!1;let n=s["_computeIntersections:Needle"];return n||(n=s["_computeIntersections:Needle"]=function(o,r,a){const l=this,h=l.geometry.boundingSphere;if(h){if(l instanceof G.GroundedSkybox){nh.setFromNormalAndCoplanarPoint(V(0,1,0),V(0,-l.position.y,0)),nh.applyMatrix4(l.matrixWorld,MS);const u=o.ray.intersectPlane(nh,V());if(u){mo.copy(h),mo.applyMatrix4(l.matrixWorld);const m=V(u).sub(o.ray.origin).length(),y=mo.radius*.5;m<y&&r.push({distance:m,point:u,object:l,normal:nh.normal.clone()})}return}mo.copy(h),mo.applyMatrix4(l.matrixWorld);const d=o.ray.intersectSphere(mo,V());if(d){const u=V(d).sub(o.ray.origin),p=u.length();if(p>mo.radius){const m=u.clone().normalize();r.push({distance:p,point:d,object:l,normal:m})}}}}),s._computeIntersections=n,e.intersectObject(s,!1,t),s._computeIntersections=i,!0}var ed;(s=>{function e(v,_,S,T,M){if(!_.geometry||!_.geometry.hasAttribute("position"))return!1;const O=_.geometry;if(_?.isSkinnedMesh){const R=_,B=R.bvhNeedsUpdate;if(!R.staticGenerator)a(),o&&(R.staticGenerator=new o(_),R.staticGenerator.applyWorldTransforms=!1,R.staticGeometry=R.staticGenerator.generate(),O.boundsTree=r?.call(R.staticGeometry),R.staticGeometryLastUpdate=performance.now()+Math.random()*200,R.bvhNeedsUpdate=!0);else if(O.boundsTree&&(R.autoUpdateMeshBvhInterval!==void 0&&R.autoUpdateMeshBvhInterval>=0||B===!0)){const L=performance.now(),N=L-R.staticGeometryLastUpdate,$=R.autoUpdateMeshBvhInterval??100;(B||N>$)&&(Dt&&console.warn(`Physics: updating skinned mesh bvh for ${_.name} after ${N.toFixed(2)}ms`),R.bvhNeedsUpdate=!1,R.staticGeometryLastUpdate=L,R.staticGenerator?.generate(R.staticGeometry),O.boundsTree.refit())}}else if(!O.boundsTree){h||g();let R=!0;if((T.xr||O[m]===!1||O.getAttribute("position")?.isInterleavedBufferAttribute||O.index&&O.index?.isInterleavedBufferAttribute)&&(R=!1),R&&u){if(O[p]===void 0){let B=null;if(b.length>0){const L=b.shift();L&&!L.running&&(B=L)}if(!B&&y.length<3&&(B=new u,y.push(B)),B!=null&&!B.running){const L=_.name;Dt&&console.log("<<<< worker start",L,B),O[p]="queued",performance.mark("bvh.create.start");const N=O.clone();try{B.generate(N).then($=>{O[p]="done",O.boundsTree=$}).catch($=>{O[p]="failed - "+$?.message,O[m]=!1,Dt&&console.error("Failed to generate mesh bvh on worker",$)}).finally(()=>{Dt&&console.log(">>>>> worker done",L,{hasBoundsTre:O.boundsTree!=null}),b.push(B),N.dispose(),performance.mark("bvh.create.end"),performance.measure("bvh.create (worker)","bvh.create.start","bvh.create.end")})}catch($){console.error("Failed to generate mesh bvh on worker",$)}}else Dt&&console.warn("No worker available")}}else(!d||!R)&&(a(),n&&(performance.mark("bvh.create.start"),O.boundsTree=new n(O),performance.mark("bvh.create.end"),performance.measure("bvh.create","bvh.create.start","bvh.create.end")))}if(v instanceof c.Raycaster){const R=v,B=_.raycast;if(O.boundsTree)a(),i&&(_.acceleratedRaycast||(_.acceleratedRaycast=i.bind(_),Dt&&console.debug(`Physics: bind acceleratedRaycast fn to "${_.name}"`)),_.raycast=_.acceleratedRaycast);else if(Dt&&console.warn("No bounds tree found for mesh",_.name,{workerTask:O[p],hasAcceleratedRaycast:i!=null}),M.allowSlowRaycastFallback===!1)return Dt&&console.warn("Skipping raycast because no bounds tree is available and allowSlowRaycastFallback is false"),!1;const L=R.firstHitOnly;return R.firstHitOnly=!1,R.intersectObject(_,!1,S),R.firstHitOnly=L,_.raycast=B,!0}else if(v instanceof c.Sphere){const R=O.boundsTree;if(R){const B=v;if(l.copy(_.matrixWorld).invert(),B.applyMatrix4(l),R.intersectsSphere(B)){const N=X(_),$=N.distanceTo(B.center),E=new sm(_,$,N);S.push(E)}}return!0}return!1}s.runMeshBVHRaycast=e;let t=!1,i=null,n=null,o=null,r=null;function a(){t||(t=!0,Promise.resolve().then(()=>require("./vendor-D51IT5ns.umd.cjs")).then(v=>v.index$1).then(v=>{i=v.acceleratedRaycast,n=v.MeshBVH,o=v.StaticGeometryGenerator,r=v.computeBoundsTree}).catch(v=>{(Dt||A())&&console.error("Failed to load BVH library...",v.message)}))}const l=new c.Matrix4;let h=!1,d=!1,u=null;const p=Symbol("Needle:MeshBVH-Worker"),m=Symbol("Needle:MeshBVH-CanUseWorker"),y=[],b=[];function g(){h=!0,d=!0,Promise.resolve().then(()=>eE).then(v=>{u=v.GenerateMeshBVHWorker}).catch(v=>{(Dt||A())&&console.warn("Failed to setup mesh bvh worker")}).finally(()=>{d=!1})}})(ed||(ed={}));const wy=Symbol("gltf-loader-internal-usage-tracker"),kS=w("debugusers");class Hr{get name(){return"NEEDLE_internal_usage_tracker"}static isLoading(e){return Hr._loadingProcesses>0}static _loadingProcesses=0;parser;_getDependency;_loadingId;_loadedObjects=new Set;constructor(e){this.parser=e,this._getDependency=this.parser.getDependency,this._loadingId=Date.now().toString()}beforeRoot(){Hr._loadingProcesses++;const e=this,t=this._getDependency;return this.parser.getDependency=function(i,n){const o=t.call(this,i,n);return o.then(r=>(r&&(e._loadedObjects.add(r),r[wy]=e._loadingId),r)),o},null}afterRoot(e){Hr._loadingProcesses--,this.parser.getDependency=this._getDependency;for(const t of this._loadedObjects)delete t[wy],t instanceof c.Object3D&&(t.parent||t instanceof c.Mesh&&setTimeout(()=>{kS&&console.warn("> GLTF LOADER: Mesh not used in scene!",t),t.material=null,t.geometry=null},1e3));return null}}class zb{constructor(){window.addEventListener("unhandledrejection",e=>{if(e.defaultPrevented)return;const t=e?.reason?.path;if(t){const i=t[0];i&&i.tagName==="IMG"&&(console.warn(`Could not load image:
167
167
  `+i.src),e.preventDefault())}})}}const Ad=w("trackresources");function Nb(){return Ad==="dispose"}let Zo=!0;Ad===0&&(Zo=!1);function RS(s){Zo=s}function Vb(){return Zo}const $b=Symbol("disposable");function Ld(s,e){s&&(s[$b]=e,To&&console.warn("Set disposable",e,s))}const Wb=Symbol("disposed");function ES(s){return s[Wb]===!0}function ge(s){if(s){if(s[$b]===!1){To&&console.warn("Object is marked as not disposable",s);return}if(typeof s=="object"&&(s[Wb]=!0),s instanceof c.Scene)ge(s.environment),ge(s.background),ge(s.customDepthMaterial),ge(s.customDistanceMaterial);else if(s instanceof c.SkinnedMesh)ge(s.geometry),ge(s.material),ge(s.skeleton),ge(s.bindMatrix),ge(s.bindMatrixInverse),ge(s.customDepthMaterial),ge(s.customDistanceMaterial),s.geometry=null,s.material=null,s.visible=!1;else if(s instanceof c.Mesh)ge(s.geometry),ge(s.material),ge(s.customDepthMaterial),ge(s.customDistanceMaterial),s.geometry=null,s.material=null,s.visible=!1;else if(s instanceof c.BufferGeometry){wr(s);for(const e of Object.keys(s.attributes)){const t=s.attributes[e];ge(t)}}else if(s instanceof c.BufferAttribute||s instanceof c.InterleavedBufferAttribute)To&&console.warn("BufferAttribute dispose not supported",s.count);else if(s instanceof Array)for(const e of s)e instanceof c.Material&&ge(e);else if(s instanceof c.Material){wr(s);for(const t of Object.keys(s)){const i=s[t];i instanceof c.Texture&&(ge(i),s[t]=null)}const e=s.uniforms;if(e)for(const t of Object.keys(e)){const i=e[t];i instanceof c.Texture?(ge(i),e[t]=null):i instanceof c.Uniform$1&&(ge(i.value),i.value=null)}}else s instanceof c.Texture?(wr(s),wr(s.source),s.source?.data instanceof ImageBitmap&&wr(s.source.data)):s instanceof c.Skeleton?(wr(s.boneTexture),s.boneTexture=null):s instanceof c.Bone||!(s instanceof c.Object3D)&&To&&console.warn("Unknown object type",s)}}function wr(s){s&&((To||Nb()||Ad)&&console.warn("🧨 FREE",s),s instanceof ImageBitmap?s.close():s instanceof c.Source?s.data=null:s.dispose())}function Gb(s){(s instanceof c.Mesh||s instanceof c.SkinnedMesh)&&(s.material=null,s.geometry=null)}const TS=new Set;function om(s,e,t=null,i){if(i||(i=TS,i.clear()),!s)return i;const n=s[Bl];if(n)for(const o of n)i.has(o)||t?.call(null,o)!==!1&&(i.add(o),e&&om(o,!0,t,i));return i}function AS(s){return s[ol]}const To=w("debugresourceusers")||w("debugmemory"),Bl=Symbol("needle-resource-users"),ol=Symbol("needle-resource-users-count");function kt(s,e){Rd(s,e,function(t,i){Zo&&!na.raycasting&&(td(Bl,this,t,!1),td(Bl,this,i,!0))})}Zo&&(kt(c.Mesh.prototype,"material"),kt(c.Mesh.prototype,"geometry"),kt(c.Material.prototype,"map"),kt(c.Material.prototype,"bumpMap"),kt(c.Material.prototype,"alphaMap"),kt(c.Material.prototype,"normalMap"),kt(c.Material.prototype,"displacementMap"),kt(c.Material.prototype,"roughnessMap"),kt(c.Material.prototype,"metalnessMap"),kt(c.Material.prototype,"emissiveMap"),kt(c.Material.prototype,"specularMap"),kt(c.Material.prototype,"envMap"),kt(c.Material.prototype,"lightMap"),kt(c.Material.prototype,"aoMap"),kt(c.Material.prototype,"gradientMap"));function LS(s){if(Zo===!1)return;const e=s[Bl];if(e)for(const t of e)td(Bl,t,s,!1)}Zo&&Rd(c.Material.prototype,"dispose",function(){LS(this)});let Kf=0;function td(s,e,t,i){if(Kf>0)return;if(Array.isArray(t)){for(const o of t)td(s,e,o,i);return}if(!t)return;let n=t[s];if(n||(n=new Set),i){if(e&&!n.has(e)){n.add(e);let o=t[ol]||0;o+=1,t[ol]=o,To&&console.warn(`🟢 Added user of "${t.type}"`,e,t,o,"users:",n)}}else if(e&&n.has(e)){n.delete(e);let o=t[ol]||0;o>0&&(o-=1,t[ol]=o),To&&console.warn(`🔴 Removed user of "${t.type}"`,e,t,o,"users:",n),o<=0&&(Hr.isLoading(t)||(Ad&&console.warn(`🔴 Removed all user of "${t.type}"`,t),Nb()&&ge(t)))}t[s]=n}try{Rd(c.WebGLRenderer.prototype,"render",function(){Kf++},function(){Kf--})}catch(s){console.warn("Could not wrap WebGLRenderer.render",s)}const xy=w("debugcomponentevents");class Dd{static eventListeners=new Map;static addComponentLifecylceEventListener(e,t){this.eventListeners.has(e)&&this.eventListeners.set(e,[]);let i=this.eventListeners.get(e);i||(i=[]),i.push(t),this.eventListeners.set(e,i),xy&&console.log("Added event listener for "+e,this.eventListeners)}static removeComponentLifecylceEventListener(e,t){const i=this.eventListeners.get(e);if(!i)return;const n=i.indexOf(t);n<0||i.splice(n,1)}static dispatchComponentLifecycleEvent(e,t){const i=this.eventListeners.get(e);if(xy&&console.log("Dispatching event "+e,i),!!i)for(const n of i)n(t)}}const Fl=Symbol("NEEDLE_NEED_UPDATE_INSTANCE"),Hb=Symbol("isUsingInstancing"),qb=Symbol("instancingRenderer"),rl=Symbol("instancingAutoUpdateBounds");class Ai{static isUsingInstancing(e){return e[Hb]===!0}static getRenderer(e){return e[qb]||null}setAutoUpdateBounds(e,t){const i=Ai.getRenderer(e);i&&(i[rl]=t)}static markDirty(e,t=!0){if(e&&(this.isUsingInstancing(e)&&(e[Fl]=!0,e.matrixWorldNeedsUpdate=!0),t))for(const i of e.children)Ai.markDirty(i,!0)}}function qr(s,e){try{e||s()}catch(t){return console.error(t),!1}return!0}const Zf=w("debugnewscripts"),DS=w("debughierarchy"),ve=[];function IS(){return ve.length>0}function id(s){if(Zf&&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 e of s.new_scripts_pre_setup_callbacks)e&&e();s.new_scripts_pre_setup_callbacks.length=0}if(!(s.new_scripts.length<=0)){ve.length=0,s.new_scripts.length>0&&ve.push(...s.new_scripts),s.new_scripts.length=0;for(let e=0;e<ve.length;e++)try{const t=ve[e];if(t.isComponent!==!0){(A()||Zf)&&console.error(`Registered script is not a Needle Engine component.
168
168
  The script will be ignored. Please make sure your component extends "Behaviour" imported from "@needle-tools/engine"
169
169
  `,t),ve.splice(e,1),e--;continue}if(t.destroyed)continue;if(!t.gameObject){console.warn(`Component can not be initialized: no GameObject assigned.
@@ -358,7 +358,7 @@ vec3 AgXToneMapping( vec3 color ) {
358
358
  cursor: pointer;
359
359
  z-index: 1000;
360
360
  box-shadow: 0 0 12px rgba(0, 0, 0, 0.2);
361
- `;const n=document.createElement("div");n.classList.add("qr-code-container"),i.appendChild(n),t.addEventListener("click",()=>{if(i.parentNode)return r();A()&&window.location.href.includes("://localhost")&&ce("To access your website from another device in the same local network you have to use the IP address instead of localhost. The IP address is logged in your development server console when you start the server."),o()});async function o(){await a(),document.body.appendChild(i);const l=n.getBoundingClientRect(),h=t.getBoundingClientRect();i.style.left=h.left+h.width*.5-l.width*.5+"px";const d=h.top<l.height,u="1.3rem";d?i.style.top=`calc(${h.bottom}px + ${i.style.padding} + 0.0rem)`:i.style.top=`calc(${h.top-l.height}px - ${i.style.padding} - ${u})`,i.style.opacity="0",i.style.pointerEvents="all",i.style.transition="opacity 0.2s ease-in-out",setTimeout(()=>{i.style.opacity="1",window.addEventListener("click",r,{once:!0})}),window.addEventListener("resize",r),window.addEventListener("scroll",r),document.fullscreenElement?document.fullscreenElement.appendChild(i):document.body.appendChild(i)}function r(){i.style.pointerEvents="none",i.style.transition="opacity 0.2s",i.style.opacity="0",setTimeout(()=>i.parentNode?.removeChild(i),500),window.removeEventListener("click",r),window.removeEventListener("resize",r),window.removeEventListener("scroll",r)}async function a(){const h=await J_({text:e.qrButtonUrl,width:200,height:200});n.innerHTML="",n.appendChild(h)}return t.addEventListener("pointerenter",()=>{a()},{once:!0}),t}hideElementDuringXRSession(e){Ed(t=>{e["previous-display"]=e.style.display,e.style.display="none"}),Yp(t=>{e["previous-display"]!=null&&(e.style.display=e["previous-display"])})}}function ld(s,e){const t=e?.element||document.head,i=Array.from(t.querySelectorAll(`link[rel=stylesheet][href*='${s}']`));if(i.length<=0){const n=document.createElement("link");n.href=s,n.rel="stylesheet",t.appendChild(n),i.push(n)}if(e?.loadedCallback)for(let n=0;n<i.length;n++)e?.loadedCallback&&i[n].addEventListener("load",e.loadedCallback)}function I0(){ld("https://fonts.googleapis.com/css2?family=Roboto+Flex:opsz,wght@8..144,100..1000&display=swap")}const lp="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@24,400,0,0&display=block",cd="needle-logo-element";class j0 extends HTMLElement{static get elementName(){return cd}static create(){return document.createElement(cd)}constructor(){super(),this._root=this.attachShadow({mode:"closed"});const e=document.createElement("template");e.innerHTML=`<style>
361
+ `;const n=document.createElement("div");n.classList.add("qr-code-container"),i.appendChild(n),t.addEventListener("click",()=>{if(i.parentNode)return r();A()&&window.location.href.includes("://localhost")&&ce("To access your website from another device in the same local network you have to use the IP address instead of localhost. The IP address is logged in your development server console when you start the server."),o()});async function o(){await a();const h=document.body.querySelector("needle-engine")||document.body;h.appendChild(i);const d=n.getBoundingClientRect(),u=t.getBoundingClientRect();i.style.left=u.left+u.width*.5-d.width*.5+"px";const p=u.top<d.height,m="1.3rem";p?i.style.top=`calc(${u.bottom}px + ${i.style.padding} + 0.0rem)`:i.style.top=`calc(${u.top-d.height}px - ${i.style.padding} - ${m})`,i.style.opacity="0",i.style.pointerEvents="all",i.style.transition="opacity 0.2s ease-in-out",setTimeout(()=>{i.style.opacity="1",window.addEventListener("click",r,{once:!0})}),window.addEventListener("resize",r),window.addEventListener("scroll",r),document.fullscreenElement?document.fullscreenElement.appendChild(i):h.appendChild(i)}function r(){i.style.pointerEvents="none",i.style.transition="opacity 0.2s",i.style.opacity="0",setTimeout(()=>i.parentNode?.removeChild(i),500),window.removeEventListener("click",r),window.removeEventListener("resize",r),window.removeEventListener("scroll",r)}async function a(){const h=await J_({text:e.qrButtonUrl,width:200,height:200});n.innerHTML="",n.appendChild(h)}return t.addEventListener("pointerenter",()=>{a()},{once:!0}),t}hideElementDuringXRSession(e){Ed(t=>{e["previous-display"]=e.style.display,e.style.display="none"}),Yp(t=>{e["previous-display"]!=null&&(e.style.display=e["previous-display"])})}}function ld(s,e){const t=e?.element||document.head,i=Array.from(t.querySelectorAll(`link[rel=stylesheet][href*='${s}']`));if(i.length<=0){const n=document.createElement("link");n.href=s,n.rel="stylesheet",t.appendChild(n),i.push(n)}if(e?.loadedCallback)for(let n=0;n<i.length;n++)e?.loadedCallback&&i[n].addEventListener("load",e.loadedCallback)}function I0(){ld("https://fonts.googleapis.com/css2?family=Roboto+Flex:opsz,wght@8..144,100..1000&display=swap")}const lp="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@24,400,0,0&display=block",cd="needle-logo-element";class j0 extends HTMLElement{static get elementName(){return cd}static create(){return document.createElement(cd)}constructor(){super(),this._root=this.attachShadow({mode:"closed"});const e=document.createElement("template");e.innerHTML=`<style>
362
362
  :host {
363
363
  position: relative;
364
364
  min-width: fit-content;
@@ -391,6 +391,16 @@ vec3 AgXToneMapping( vec3 color ) {
391
391
  </div>
392
392
  `,this._root.appendChild(e.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")}_root;wrapper;logoElement=document.createElement("img");textElement=document.createElement("span");setLogoVisible(e){this.logoElement.style.display=e?"block":"none"}}customElements.get(cd)||customElements.define(cd,j0);const Ku=w("debugspatialmenu");class RC{_context;needleMenu;htmlButtonsMap=new Map;enabled=!0;constructor(e,t){this._context=e,this._context.pre_render_callbacks.push(this.preRender),this.needleMenu=t;const i=this.needleMenu.shadowRoot?.querySelector(".options");i?new MutationObserver(o=>{if(this.enabled&&!(this._context.isInXR==!1&&!Ku))for(const r of o)r.type==="childList"&&(r.addedNodes.forEach(a=>{this.createButtonFromHTMLNode(a)}),r.removedNodes.forEach(a=>{const l=a,h=this.htmlButtonsMap.get(l);h&&(this.htmlButtonsMap.delete(l),h.remove(),J.__webpack_exports__default.update())}))}).observe(i,{childList:!0}):console.error("Could not find options container in needle menu")}setEnabled(e){this.enabled=e,e||this.menu?.removeFromParent()}userRequestedMenu=!1;setDisplay(e){return this.enabled?(this.userRequestedMenu=e,!0):!1}onDestroy(){const e=this._context.pre_render_callbacks.indexOf(this.preRender);e>-1&&this._context.pre_render_callbacks.splice(e,1)}uiisDirty=!1;markDirty(){this.uiisDirty=!0}_showNeedleLogo;showNeedleLogo(e){this._showNeedleLogo=e}_wasInXR=!1;preRender=()=>{if(!this.enabled){this.menu?.removeFromParent();return}if(Ku&&exports.DeviceUtilities.isDesktop()&&this.updateMenu(),!this._context.xr?.running){this._wasInXR&&(this._wasInXR=!1,this.onExitXR());return}this._wasInXR||(this._wasInXR=!0,this.onEnterXR()),this.updateMenu()};onEnterXR(){const e=this.needleMenu.shadowRoot?.querySelector(".options");e&&e.childNodes.forEach(t=>{this.createButtonFromHTMLNode(t)})}onExitXR(){this.menu?.removeFromParent()}createButtonFromHTMLNode(e){const t=this.getMenu(),i=this.htmlButtonsMap.get(e);if(i){i.add();return}if(e instanceof HTMLButtonElement){const n=this.createButton(t,e);this.htmlButtonsMap.set(e,n),n.add()}else e instanceof HTMLSlotElement&&e.assignedNodes().forEach(n=>{this.createButtonFromHTMLNode(n)})}_menuTarget=new c.Object3D;positionFilter=new Up(90,.5);updateMenu(){const e=this.getMenu();this.handleNeedleWatermark(),this._context.scene.add(e);const t=this._context.mainCamera,n=this._context.xr?.rigScale||1;if(t){const o=t.worldPosition,r=t.worldForward.multiplyScalar(-1),a=r.y>.6,l=r.y>.4,h=(e.visible?l:a)||this.userRequestedMenu,d=!e.visible&&h;e.visible=h||exports.DeviceUtilities.isDesktop()&&Ku,r.multiplyScalar(3*n),o.add(r),(d||!1)&&(e.position.copy(this._menuTarget.position),e.position.y+=.25,this._menuTarget.position.copy(e.position),this.positionFilter.reset(e.position),e.quaternion.copy(this._menuTarget.quaternion),this.markDirty());const p=this._menuTarget.position.distanceTo(o);(d||p>1.5*n)&&(this.ensureRenderOnTop(this.menu),this._menuTarget.position.copy(o),this._context.scene.add(this._menuTarget),tc(this._menuTarget,this._context.mainCamera,!0,!0),this._menuTarget.removeFromParent()),this.positionFilter.filter(this._menuTarget.position,e.position,this._context.time.time),this.menu?.quaternion.slerp(this._menuTarget.quaternion,this._context.time.deltaTime*5),this.menu?.scale.setScalar(n)}this.uiisDirty&&(this.uiisDirty=!1,J.__webpack_exports__default.update())}ensureRenderOnTop(e,t=0){e instanceof c.Mesh&&(e.material.depthTest=!1,e.material.depthWrite=!1),e.renderOrder=1e3+t*2;for(const i of e.children)this.ensureRenderOnTop(i,t+1)}familyName="Needle Spatial Menu";menu;get isVisible(){return this.menu?.visible}getMenu(){if(this.menu)return this.menu;this.ensureFont(),this.menu=new J.__webpack_exports__default.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 c.Vector4(0,.05,0,.05),borderColor:0,borderOpacity:.05,borderWidth:.005});const e=P.get("ObjectRaycaster");return e&&Ao(this.menu,new e),this.menu}_poweredByNeedleElement;handleNeedleWatermark(){if(!this._poweredByNeedleElement){this._poweredByNeedleElement=new J.__webpack_exports__default.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 e=new Fy(this._context,()=>globalThis.open("https://needle.tools","_self"));Ao(this._poweredByNeedleElement,e);const t=new J.__webpack_exports__default.Text({textContent:"Powered by",width:"auto",height:"auto"}),i=new J.__webpack_exports__default.Text({textContent:"needle",width:"auto",height:"auto",fontSize:.07,margin:new c.Vector4(0,0,0,.02)});this._poweredByNeedleElement.add(t),this._poweredByNeedleElement.add(i),this.menu?.add(this._poweredByNeedleElement),this.markDirty(),new c.TextureLoader().load("./include/needle/poweredbyneedle.webp",o=>{e.allowModifyUI=!1,t.removeFromParent(),i.removeFromParent();const r=o.image.width/o.image.height;this._poweredByNeedleElement?.set({backgroundImage:o,backgroundOpacity:1,width:.1*r,height:.1}),this.markDirty()})}if(this.menu){const e=this.menu.children.indexOf(this._poweredByNeedleElement);if(!this._showNeedleLogo&&kn())e>=0&&(this._poweredByNeedleElement.removeFromParent(),this.markDirty());else{this._poweredByNeedleElement.visible=!0,this.menu.add(this._poweredByNeedleElement);const t=this.menu.children.indexOf(this._poweredByNeedleElement);e!==t&&this.markDirty()}}}ensureFont(){let e=J.__webpack_exports__default.FontLibrary.getFontFamily(this.familyName);e||(e=J.__webpack_exports__default.FontLibrary.addFontFamily(this.familyName),e.addVariant("normal","normal","./include/needle/arial-msdf.json","./include/needle/arial.png")?.addEventListener("ready",()=>{this.markDirty()}))}createButton(e,t){const i=new J.__webpack_exports__default.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}),n=new J.__webpack_exports__default.Text({textContent:"",width:"auto",justifyContent:"center",alignItems:"center",backgroundOpacity:0,backgroundColor:16777215,fontFamily:this.familyName,color:0,borderRadius:.02,padding:.01});i.add(n),i["needle:use_eventsystem"]=!0;const o=new Fy(this._context,()=>t.click());return Ao(i,o),new EC(this,e,t,i,n)}}class EC{menu;root;htmlbutton;spatialContainer;spatialText;spatialIcon;constructor(e,t,i,n,o){this.menu=e,this.root=t,this.htmlbutton=i,this.spatialContainer=n,this.spatialText=o,new MutationObserver(a=>{for(const l of a)l.type==="attributes"?l.attributeName==="style"&&this.updateVisible():l.type==="childList"&&this.updateText()}).observe(i,{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 e=this.spatialContainer.visible;this.spatialContainer.visible=this.htmlbutton.style.display!=="none",e!==this.spatialContainer.visible&&this.menu.markDirty()}_lastText="";updateText(){let e="",t="";this.htmlbutton.childNodes.forEach(i=>{i.nodeType===Node.TEXT_NODE?e+=i.textContent:i instanceof HTMLElement&&D0(i)&&i.textContent&&(t=i.textContent)}),this._lastText!==e&&(this._lastText=e,this.spatialText.name=e,this.spatialText.set({textContent:e}),this.menu.markDirty()),e.length<=0?this.spatialText.parent&&(this.spatialText.removeFromParent(),this.menu.markDirty()):this.spatialText.parent||(this.spatialContainer.add(this.spatialText),this.menu.markDirty()),t&&this.createIcon(t)}_lastTexture;async createIcon(e){if(!this.spatialIcon){const i=await ap(e);if(i&&!this.spatialIcon){const o=new J.__webpack_exports__default.Block({width:.08,height:.08,backgroundColor:16777215,backgroundImage:i,backgroundOpacity:1,margin:new c.Vector4(0,.005,0,0)});this.spatialIcon=o,this.spatialContainer.add(o),this.menu.markDirty()}}if(e!=this._lastTexture){this._lastTexture=e;const i=await ap(e);i&&(this.spatialIcon?.set({backgroundImage:i}),this.menu.markDirty())}const t=this.spatialContainer.children.indexOf(this.spatialIcon);t>0&&(this.spatialContainer.children.splice(t,1),this.spatialContainer.children.unshift(this.spatialIcon),this.menu.markDirty())}}class Fy{isComponent=!0;enabled=!0;get activeAndEnabled(){return!0}__internalAwake(){}__internalEnable(){}__internalDisable(){}__internalStart(){}onEnable(){}onDisable(){}gameObject;allowModifyUI=!0;get element(){return this.gameObject}context;onclick;constructor(e,t){this.context=e,this.onclick=t}onPointerEnter(){this.context.input.setCursor("pointer"),this.allowModifyUI&&(this.element.set({backgroundOpacity:1}),J.__webpack_exports__default.update())}onPointerExit(){this.context.input.unsetCursor("pointer"),this.allowModifyUI&&(this.element.set({backgroundOpacity:0}),J.__webpack_exports__default.update())}onPointerDown(e){e.use()}onPointerUp(e){e.use()}onPointerClick(e){e.use(),this.onclick()}}const So="needle-menu",Ml=w("debugmenu"),Uy=w("debugnoncommercial");let TC=class{_context;_menu;_spatialMenu;constructor(e){this._menu=Ud.getOrCreate(e.domElement,e),this._context=e,this._spatialMenu=new RC(e,this._menu),window.addEventListener("message",this.onPostMessage),Ed(this.onStartXR)}onDestroy(){window.removeEventListener("message",this.onPostMessage),this._menu.remove(),this._spatialMenu.onDestroy()}onPostMessage=e=>{if(e.origin===globalThis.location.origin&&typeof e.data=="object"){const t=e.data,i=t.type;if(i==="needle:menu"){const n=t.button;if(n){if(!n.label)return console.error("NeedleMenu: buttoninfo.label is required");if(!n.onclick)return console.error("NeedleMenu: buttoninfo.onclick is required");const o=document.createElement("button");if(o.textContent=n.label,n.icon){const r=ut(n.icon);o.prepend(r)}n.priority&&o.setAttribute("priority",n.priority.toString()),o.onclick=()=>{if(n.onclick){const r=n.onclick.startsWith("http")||n.onclick.startsWith("www."),a=n.target||"_blank";r?globalThis.open(n.onclick,a):console.error("NeedleMenu: onclick is not a valid link",n.onclick)}},this._menu.appendChild(o)}else Ml&&console.error("NeedleMenu: unknown postMessage event",t)}else Ml&&console.warn("NeedleMenu: unknown postMessage type",i,t)}};onStartXR=e=>{e.session.isScreenBasedAR&&(this._menu.previousParent=this._menu.parentNode,this._context.arOverlayElement.appendChild(this._menu),e.session.session.addEventListener("end",this.onExitXR),this._menu.closeFoldout())};onExitXR=()=>{this._menu.previousParent&&(this._menu.previousParent.appendChild(this._menu),delete this._menu.previousParent)};setPosition(e){this._menu.setPosition(e)}setVisible(e){this._menu.setVisible(e)}showNeedleLogo(e){this._menu.showNeedleLogo(e),this._spatialMenu?.showNeedleLogo(e)}get logoIsVisible(){return this._menu.logoIsVisible}showSpatialMenu(e){this._spatialMenu.setEnabled(e)}setSpatialMenuVisible(e){this._spatialMenu.setDisplay(e)}get spatialMenuIsVisible(){return this._spatialMenu.isVisible}showQRCodeButton(e){if(e==="desktop-only"&&(e=!exports.DeviceUtilities.isMobileDevice()),e){const t=Ki.getOrCreate().createQRCode();return t.style.display="",this._menu.appendChild(t),t}else{const t=Ki.getOrCreate().qrButton;return t&&(t.style.display="none"),t??null}}showAudioPlaybackOption(e){if(!e){this._muteButton?.remove();return}this._muteButton=Ki.getOrCreate().createMuteButton(this._context),this._muteButton.setAttribute("priority","100"),this._menu.appendChild(this._muteButton)}_muteButton;showFullscreenOption(e){if(!e){this._fullscreenButton?.remove();return}this._fullscreenButton=Ki.getOrCreate().createFullscreenButton(this._context),this._fullscreenButton&&(this._fullscreenButton.setAttribute("priority","150"),this._menu.appendChild(this._fullscreenButton))}_fullscreenButton;appendChild(e){return this._menu.appendChild(e)}};class Ud extends HTMLElement{static create(){return document.createElement(So,{is:So})}static getOrCreate(e,t){let i=e.querySelector(So);return!i&&e.shadowRoot&&(i=e.shadowRoot.querySelector(So)),i||(i=window.document.body.querySelector(So)),i||(i=Ud.create(),e.shadowRoot?e.shadowRoot.appendChild(i):e.appendChild(i)),i._domElement=e,i._context=t,i}_domElement=null;_context=null;constructor(){super();const e=document.createElement("template");e.innerHTML=`<style>
393
393
 
394
+ /** Styling attributes that ensure the nested menu z-index does not cause it to overlay elements outside of <needle-engine> */
395
+ :host {
396
+ position: absolute;
397
+ width: 100%;
398
+ height: 100%;
399
+ z-index: 0;
400
+ top: 0;
401
+ pointer-events: none;
402
+ }
403
+
394
404
  #root {
395
405
  position: absolute;
396
406
  width: auto;
@@ -770,7 +780,7 @@ vec3 AgXToneMapping( vec3 color ) {
770
780
  The script will be ignored. Please make sure your component extends "Behaviour" imported from "@needle-tools/engine"
771
781
  `,s);return}e||(e=U.Current,Fe&&console.warn("> Registering component without context"));const t=e?.new_scripts;t.includes(s)||t.push(s)}class U{static _defaultTargetFramerate={value:90,toString(){return this.value}};static get DefaultTargetFrameRate(){return U._defaultTargetFramerate.value}static set DefaultTargetFrameRate(e){U._defaultTargetFramerate.value=e}static _defaultWebglRendererParameters={antialias:!0,alpha:!1,powerPreference:exports.DeviceUtilities.isiOS()||exports.DeviceUtilities.isMacOS()?"default":"high-performance",stencil:!0};static get DefaultWebGLRendererParameters(){return U._defaultWebglRendererParameters}get version(){return Ji}static get Current(){return re.Current}static set Current(e){re.Current=e}static get All(){return re.All}name;alias;isManagedExternally=!1;isPaused=!1;runInBackground=!1;targetFrameRate;physicsSteps=1;hash;domElement;appendHTMLElement(e){return this.domElement.shadowRoot?this.domElement.shadowRoot.appendChild(e):this.domElement.appendChild(e)}get resolutionScaleFactor(){return this._resolutionScaleFactor}set resolutionScaleFactor(e){if(e!==this._resolutionScaleFactor&&typeof e=="number"){if(e<=0){console.error("Invalid resolution scale factor",e);return}this._resolutionScaleFactor=e,this.updateSize()}}_resolutionScaleFactor=1;_boundingClientRectFrame=-1;_boundingClientRect=null;_domX;_domY;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(){return this.renderer?.xr?.isPresenting||!1}xr=null;get xrSessionMode(){return this.xr?.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(){return this.renderer?.xr?.getSession()}get xrFrame(){return this._xrFrame}get xrCamera(){return this.renderer.xr.isPresenting?this.renderer?.xr?.getCamera():void 0}_xrFrame=null;get arOverlayElement(){const e=this.domElement;return typeof e.getAROverlayContainer=="function"?e.getAROverlayContainer():this.domElement}get currentFrameEvent(){return this._currentFrameEvent}_currentFrameEvent=-1;scene;renderer;composer=null;scripts=[];scripts_pausedChanged=[];scripts_earlyUpdate=[];scripts_update=[];scripts_lateUpdate=[];scripts_onBeforeRender=[];scripts_onAfterRender=[];scripts_WithCorroutines=[];scripts_immersive_vr=[];scripts_immersive_ar=[];coroutines={};post_setup_callbacks=[];pre_update_callbacks=[];pre_render_callbacks=[];post_render_callbacks=[];pre_update_oneshot_callbacks=[];new_scripts=[];new_script_start=[];new_scripts_pre_setup_callbacks=[];new_scripts_post_setup_callbacks=[];new_scripts_xr=[];mainCameraComponent=void 0;get mainCamera(){if(this._mainCamera)return this._mainCamera;if(this.mainCameraComponent){const e=this.mainCameraComponent;return e.threeCamera||e.buildCamera(),e.threeCamera}return this._fallbackCamera||(this._fallbackCamera=new c.PerspectiveCamera(75,this.domWidth/this.domHeight,.1,1e3)),this._fallbackCamera}set mainCamera(e){this._mainCamera=e}_mainCamera=null;_fallbackCamera=null;application;animations;time;input;physics;connection;assets;mainLight=null;get rendererData(){return this.sceneLighting}sceneLighting;addressables;lightmaps;players;lodsManager;menu;get isCreated(){return this._isCreated}_needsUpdateSize=!1;_isCreated=!1;_isCreating=!1;_isVisible=!1;_stats=AC?new G.Stats:null;constructor(e){this.name=e?.name||"",this.alias=e?.alias,this.domElement=e?.domElement||document.body,this.hash=e?.hash,e?.renderer&&(this.renderer=e.renderer,this.isManagedExternally=!0),e?.runInBackground!==void 0&&(this.runInBackground=e.runInBackground),e?.scene?this.scene=e.scene:this.scene=new c.Scene,e?.camera&&(this._mainCamera=e.camera),this.application=new tn(this),this.time=new T0,this.input=new kb(this),this.physics=new na(this),this.connection=new jb(this),this.assets=new zb,this.sceneLighting=new R0(this),this.addressables=new S0(this),this.lightmaps=new _C(this),this.players=new k0(this),this.menu=new TC(this),this.lodsManager=new bC(this),this.animations=new mC(this);const t=()=>this._needsUpdateSize=!0;window.addEventListener("resize",t),this._disposeCallbacks.push(()=>window.removeEventListener("resize",t));const i=new ResizeObserver(n=>this._needsUpdateSize=!0);i.observe(this.domElement),this._disposeCallbacks.push(()=>i.disconnect()),this._intersectionObserver=new IntersectionObserver(n=>{this._isVisible=n[0].isIntersecting}),this._disposeCallbacks.push(()=>this._intersectionObserver?.disconnect()),re.register(this)}createNewRenderer(e){if(this.renderer?.dispose(),e={...U.DefaultWebGLRendererParameters,...e},!e.canvas){const t=this.domElement?.shadowRoot?.querySelector("canvas");t&&(e.canvas=t,Fe&&console.log("Using canvas from shadow root",t))}return Fe&&console.log("Using Renderer Parameters:",e,this.domElement),this.renderer=new c.WebGLRenderer(e),this.renderer.debug.checkShaderErrors=A()||w("checkshadererrors")===!0,this.renderer.toneMappingExposure=1,this.renderer.toneMapping=c.NoToneMapping,this.renderer.setClearColor(new c.Color("lightgrey"),0),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=c.PCFSoftShadowMap$1,this.renderer.setSize(this.domWidth,this.domHeight),this.renderer.outputColorSpace=c.SRGBColorSpace,this.renderer.nodes={library:new c.BasicNodeLibrary,modelViewMatrix:null,modelNormalViewMatrix:null},this.lodsManager.setRenderer(this.renderer),this.input.bindEvents(),this.renderer}_intersectionObserver=null;internalOnUpdateVisible(){this._intersectionObserver?.disconnect(),this._intersectionObserver?.observe(this.domElement)}_disposeCallbacks=[];requestSizeUpdate(){this._needsUpdateSize=!0}maxRenderResolution;get devicePixelRatio(){return this._devicePixelRatio}set devicePixelRatio(e){e!==this._devicePixelRatio&&(this._devicePixelRatio=e,this._needsUpdateSize=!0)}_devicePixelRatio="auto";updateSize(e=!1){if(e||!this.isManagedExternally&&this.renderer.xr?.isPresenting===!1){this._needsUpdateSize=!1;const t=this.resolutionScaleFactor;let i=this.domWidth*t,n=this.domHeight*t;this.maxRenderResolution&&(this.maxRenderResolution.x=Math.max(1,this.maxRenderResolution.x),i=Math.min(this.maxRenderResolution.x,i),this.maxRenderResolution.y=Math.max(1,this.maxRenderResolution.y),n=Math.min(this.maxRenderResolution.y,n));const o=this.mainCamera;this.updateAspect(o),this.renderer.setSize(i,n,!0),this.renderer.domElement.style.width="100%",this.renderer.domElement.style.height="100%";const r=typeof this.devicePixelRatio=="number"?this.devicePixelRatio:this.devicePixelRatio==="auto"?Math.min(2,window.devicePixelRatio):void 0;r!==void 0&&this.renderer.setPixelRatio(r),this.composer&&(this.composer.setSize?.call(this.composer,i,n),r!==void 0&&"setPixelRatio"in this.composer&&typeof this.composer.setPixelRatio=="function"&&this.composer.setPixelRatio?.call(this.composer,window.devicePixelRatio))}}updateAspect(e,t,i){if(!e)return;t===void 0&&(t=this.domWidth),i===void 0&&(i=this.domHeight);const n=t/i;if(e.isPerspectiveCamera){const o=e,r=o.aspect;o.aspect=n,r!==o.aspect&&e.updateProjectionMatrix()}else if(e.isOrthographicCamera){const o=e,r=o.top-o.bottom,l=r*n/2,h=r/2;(o.left!=-l||o.top!=h)&&(o.left=-l,o.right=l,o.top=h,o.bottom=-h,e.updateProjectionMatrix())}}recreate(){this.clear(),this.create(this._originalCreationArgs)}_originalCreationArgs;async onCreate(e){return this.create(e)}async create(e){try{this._isCreating=!0,e!==this._originalCreationArgs&&(this._originalCreationArgs=Jl(e)),window.addEventListener("unhandledrejection",this.onUnhandledRejection);const t=await this.internalOnCreate(e);return this._isCreated=t,t}finally{window.removeEventListener("unhandledrejection",this.onUnhandledRejection),this._isCreating=!1}}onUnhandledRejection=e=>{this.onError(e.reason)};onError(e){this.domElement.dispatchEvent(new CustomEvent("error",{detail:e}))}clear(){re.dispatchCallback(oe.ContextClearing,this),hn(this,oe.ContextClearing),di(this.scene,!0,!0),this.scene=new c.Scene,this.addressables?.dispose(),this.lightmaps?.clear(),this.physics?.engine?.clearCaches(),this.lodsManager.disable(),this._onBeforeRenderListeners.clear(),this._onAfterRenderListeners.clear(),this.isManagedExternally||this.renderer&&(this.renderer.renderLists.dispose(),this.renderer.state.reset(),this.renderer.resetState()),re.dispatchCallback(oe.ContextCleared,this)}dispose(){this.internalOnDestroy()}onDestroy(){this.internalOnDestroy()}internalOnDestroy(){U.Current=this,re.dispatchCallback(oe.ContextDestroying,this),hn(this,oe.ContextDestroying),this.clear(),this.renderer?.setAnimationLoop(null),this.renderer&&(this.renderer.setClearAlpha(0),this.renderer.clear(),this.isManagedExternally||(Fe&&console.log("Disposing renderer"),this.renderer.dispose())),this.scene=null,this.renderer=null,this.input.dispose(),this.menu.onDestroy(),this.animations.onDestroy();for(const e of this._disposeCallbacks)try{e()}catch(t){console.error("Error in on dispose callback:",t,e)}this.domElement?.parentElement&&this.domElement.parentElement.removeChild(this.domElement),this._isCreated=!1,re.dispatchCallback(oe.ContextDestroyed,this),hn(this,oe.ContextDestroyed),re.unregister(this),U.Current===this&&(U.Current=null)}registerCoroutineUpdate(e,t,i){return typeof t?.next!="function"?(console.error("Registered invalid coroutine function from "+e.name+`
772
782
  Coroutine functions must be generators: "*myCoroutine() {...}"
773
- Start a coroutine from a component by calling "this.startCoroutine(myCoroutine())"`),t):(this.coroutines[i]||(this.coroutines[i]=[]),this.coroutines[i].push({comp:e,main:t}),t)}unregisterCoroutineUpdate(e,t){if(!this.coroutines[t])return;const i=this.coroutines[t].findIndex(n=>n.main===e);i>=0&&this.coroutines[t].splice(i,1)}stopAllCoroutinesFrom(e){for(const t in this.coroutines){const i=this.coroutines[t];for(let n=i.length-1;n>=0;n--)i[n].comp===e&&i.splice(n,1)}}_cameraStack=[];setCurrentCamera(e){if(!e)return;if(e.threeCamera||e.buildCamera(),!e.threeCamera){console.warn("Camera component is missing camera",e);return}const t=this._cameraStack.indexOf(e);t>=0&&this._cameraStack.splice(t,1),this._cameraStack.push(e),this.mainCameraComponent=e;const i=e.threeCamera;i.isPerspectiveCamera&&this.updateAspect(i),this.mainCameraComponent?.applyClearFlagsIfIsActiveCamera()}removeCamera(e){if(!e)return;const t=this._cameraStack.indexOf(e);if(t>=0&&this._cameraStack.splice(t,1),this.mainCameraComponent===e&&(this.mainCameraComponent=void 0,this._cameraStack.length>0)){const i=this._cameraStack[this._cameraStack.length-1];this.setCurrentCamera(i)}}_onBeforeRenderListeners=new Map;_onAfterRenderListeners=new Map;addBeforeRenderListener(e,t){if(!this._onBeforeRenderListeners.has(e.uuid)){const i=[];this._onBeforeRenderListeners.set(e.uuid,i),e.onBeforeRender=this._createRenderCallbackWrapper(i)}this._onBeforeRenderListeners.get(e.uuid).push(t)}removeBeforeRenderListener(e,t){if(this._onBeforeRenderListeners.has(e.uuid)){const i=this._onBeforeRenderListeners.get(e.uuid),n=i.indexOf(t);n>=0&&i.splice(n,1)}}addAfterRenderListener(e,t){if(!this._onAfterRenderListeners.has(e.uuid)){const i=[];this._onAfterRenderListeners.set(e.uuid,i),e.onAfterRender=this._createRenderCallbackWrapper(i)}this._onAfterRenderListeners.get(e.uuid)?.push(t)}removeAfterRenderListener(e,t){if(this._onAfterRenderListeners.has(e.uuid)){const i=this._onAfterRenderListeners.get(e.uuid),n=i.indexOf(t);n>=0&&i.splice(n,1)}}_createRenderCallbackWrapper(e){return(t,i,n,o,r,a)=>{for(let l=0;l<e.length;l++){const h=e[l];h(t,i,n,o,r,a)}}}_requireDepthTexture=!1;_requireColorTexture=!1;_renderTarget;_isRendering=!1;get isRendering(){return this._isRendering}setRequireDepth(e){this._requireDepthTexture=e}setRequireColor(e){this._requireColorTexture=e}get depthTexture(){return this._renderTarget?.depthTexture||null}get opaqueColorTexture(){return this._renderTarget?.texture||null}get isVisibleToUser(){if(this.isInXR)return!0;if(!this._isVisible)return!1;if(this.time.frame===this._lastStyleComputedFrame)return this._lastStyleComputedResult;this._lastStyleComputedFrame=this.time.frame;const e=getComputedStyle(this.domElement);return this._lastStyleComputedResult=e.visibility!=="hidden"&&e.display!=="none"&&e.opacity!=="0",this._lastStyleComputedResult}_lastStyleComputedFrame=-1;_lastStyleComputedResult=!0;_createId=0;async internalOnCreate(e){const t=++this._createId;Fe&&console.log("Creating context",this.name,e);const i=globalThis["needle:dependencies:ready"];i instanceof Promise&&(Fe&&console.log("Waiting for dependencies to be ready"),await i.catch(h=>{if(Fe||A()){if(nc("Needle Engine dependencies failed to load. Please check the console for more details"),h instanceof ReferenceError){let d="YourComponentName";const u=h.message.indexOf("'");if(u>0){const p=h.message.indexOf("'",u+1);if(p>0){const m=h.message.substring(u+1,p);m.length>3&&(d=m)}}console.error(`Needle Engine dependencies failed to load:
783
+ Start a coroutine from a component by calling "this.startCoroutine(myCoroutine())"`),t):(this.coroutines[i]||(this.coroutines[i]=[]),this.coroutines[i].push({comp:e,main:t}),t)}unregisterCoroutineUpdate(e,t){if(!this.coroutines[t])return;const i=this.coroutines[t].findIndex(n=>n.main===e);i>=0&&this.coroutines[t].splice(i,1)}stopAllCoroutinesFrom(e){for(const t in this.coroutines){const i=this.coroutines[t];for(let n=i.length-1;n>=0;n--)i[n].comp===e&&i.splice(n,1)}}_cameraStack=[];setCurrentCamera(e){if(!e)return;if(e.threeCamera||e.buildCamera(),!e.threeCamera){console.warn("Camera component is missing camera",e);return}const t=this._cameraStack.indexOf(e);t>=0&&this._cameraStack.splice(t,1),this._cameraStack.push(e),this.mainCameraComponent=e;const i=e.threeCamera;i.isPerspectiveCamera&&this.updateAspect(i),this.mainCameraComponent?.applyClearFlagsIfIsActiveCamera()}removeCamera(e){if(!e)return;const t=this._cameraStack.indexOf(e);if(t>=0&&this._cameraStack.splice(t,1),this.mainCameraComponent===e&&(this.mainCameraComponent=void 0,this._cameraStack.length>0)){const i=this._cameraStack[this._cameraStack.length-1];this.setCurrentCamera(i)}}_onBeforeRenderListeners=new Map;_onAfterRenderListeners=new Map;addBeforeRenderListener(e,t){if(!this._onBeforeRenderListeners.has(e.uuid)){const i=[];this._onBeforeRenderListeners.set(e.uuid,i),e.onBeforeRender=this._createRenderCallbackWrapper(i)}this._onBeforeRenderListeners.get(e.uuid).push(t)}removeBeforeRenderListener(e,t){if(this._onBeforeRenderListeners.has(e.uuid)){const i=this._onBeforeRenderListeners.get(e.uuid),n=i.indexOf(t);n>=0&&i.splice(n,1)}}addAfterRenderListener(e,t){if(!this._onAfterRenderListeners.has(e.uuid)){const i=[];this._onAfterRenderListeners.set(e.uuid,i),e.onAfterRender=this._createRenderCallbackWrapper(i)}this._onAfterRenderListeners.get(e.uuid)?.push(t)}removeAfterRenderListener(e,t){if(this._onAfterRenderListeners.has(e.uuid)){const i=this._onAfterRenderListeners.get(e.uuid),n=i.indexOf(t);n>=0&&i.splice(n,1)}}_createRenderCallbackWrapper(e){return(t,i,n,o,r,a)=>{for(let l=0;l<e.length;l++){const h=e[l];h(t,i,n,o,r,a)}}}_requireDepthTexture=!1;_requireColorTexture=!1;_renderTarget;_isRendering=!1;get isRendering(){return this._isRendering}setRequireDepth(e){this._requireDepthTexture=e}setRequireColor(e){this._requireColorTexture=e}get depthTexture(){return this._renderTarget?.depthTexture||null}get opaqueColorTexture(){return this._renderTarget?.texture||null}get isVisibleToUser(){if(this.isInXR)return!0;if(!this._isVisible)return!1;if(!this._needsVisibleUpdate&&this._lastStyleComputedResult!==void 0)return this._lastStyleComputedResult;this._needsVisibleUpdate=!1;const e=getComputedStyle(this.domElement);return this._lastStyleComputedResult=e.visibility!=="hidden"&&e.display!=="none"&&e.opacity!=="0",this._lastStyleComputedResult}_needsVisibleUpdate=!0;_lastStyleComputedResult=void 0;_createId=0;async internalOnCreate(e){const t=++this._createId;Fe&&console.log("Creating context",this.name,e);const i=globalThis["needle:dependencies:ready"];i instanceof Promise&&(Fe&&console.log("Waiting for dependencies to be ready"),await i.catch(h=>{if(Fe||A()){if(nc("Needle Engine dependencies failed to load. Please check the console for more details"),h instanceof ReferenceError){let d="YourComponentName";const u=h.message.indexOf("'");if(u>0){const p=h.message.indexOf("'",u+1);if(p>0){const m=h.message.substring(u+1,p);m.length>3&&(d=m)}}console.error(`Needle Engine dependencies failed to load:
774
784
 
775
785
  # Make sure you don't have circular imports in your scripts!
776
786
 
@@ -779,7 +789,7 @@ Possible solutions:
779
789
  → If you only need type information try importing the type only, e.g: import { type ${d} }
780
790
 
781
791
  ---`,h);return}console.error("Needle Engine dependencies failed to load",h)}}).then(()=>{Fe&&console.log("Needle Engine dependencies are ready")})),this.clear();const n=this.renderer,o=!n||n.isDisposed===!0;this.isManagedExternally===!1&&o?this.createNewRenderer():this.lodsManager.setRenderer(this.renderer),this.renderer?.setAnimationLoop(null),U.Current=this,await re.dispatchCallback(oe.ContextCreationStart,this);let r=!0,a;try{U.Current=this,e?a=await this.internalLoadInitialContent(t,e):a=[]}catch(h){console.error(h),r=!1}if(!r)return this.onError("Failed to load initial content"),!1;if(t!==this._createId||e?.abortSignal?.aborted)return!1;if(this.internalOnUpdateVisible(),!this.renderer)return Fe&&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),U.Current=this,U.Current=this;for(let h=0;h<this.new_scripts.length;h++){const d=this.new_scripts[h];if(d.gameObject!==void 0&&d.gameObject!==null){d.gameObject.userData===void 0&&(d.gameObject.userData={}),d.gameObject.userData.components===void 0&&(d.gameObject.userData.components=[]);const u=d.gameObject.userData.components;u.includes(d)||u.push(d)}}if(this.post_setup_callbacks)for(let h=0;h<this.post_setup_callbacks.length;h++)U.Current=this,await this.post_setup_callbacks[h](this);if(!this._mainCamera){U.Current=this;let h=null;$o(this.scene,d=>{const u=d;if(u?.isCamera){if(Cl(u.gameObject),!u.activeAndEnabled)return;if(u.tag==="MainCamera")return h=u,!0;h=u}}),h?this.setCurrentCamera(h):!re.dispatchCallback(oe.MissingCamera,this,{files:a})&&!this.mainCamera&&!this.isManagedExternally&&console.warn("Missing camera in main scene",this)}this.input.bindEvents(),U.Current=this,id(this),this.physics.engine&&(this.physics.engine?.step(0),this.physics.engine?.postStep()),!this.isManagedExternally&&this.composer&&this.mainCamera,this._needsUpdateSize=!0,this._stats&&(this._stats.showPanel(0),this._stats.dom.style.position="absolute",this.domElement.shadowRoot?.appendChild(this._stats.dom)),Fe&&Kh(this.scene,!0),this.targetFrameRate===void 0?(Fe&&console.warn("No target framerate set, using default",U.DefaultTargetFrameRate),this.targetFrameRate=U._defaultTargetFramerate):Fe&&console.log("Target framerate set to",this.targetFrameRate),this._dispatchReadyAfterFrame=!0;const l=re.dispatchCallback(oe.ContextCreated,this,{files:a});if(l){const h=this.domElement;"internalSetLoadingMessage"in h&&typeof h.internalSetLoadingMessage=="function"&&h?.internalSetLoadingMessage("finish loading"),await l}return e?.abortSignal?.aborted?!1:(hn(this,oe.ContextCreated),Fe&&console.log("Context Created...",this.renderer,this.renderer.domElement),this._isCreating=!1,!this.isManagedExternally&&!e?.abortSignal?.aborted&&this.restartRenderLoop(),!0)}async internalLoadInitialContent(e,t){const i=new Array;if(t.files.length===0)return i;const n=[...t.files],o={name:"",progress:null,index:0,count:n.length},r=en(),a=0;for(let l=0;l<n.length;l++){if(t.abortSignal?.aborted){Fe&&console.log("Aborting loading because of abort signal");break}if(e!==this._createId){Fe&&console.log("Aborting loading because create id changed",e,this._createId);break}const h=n[l];t?.onLoadingStart?.call(this,l,h),Fe&&console.log("Context Load "+h);const d=await r.loadSync(this,h,h,a,u=>{t.abortSignal?.aborted||(o.name=h,o.progress=u,o.index=l,o.count=n.length,t.onLoadingProgress?.call(this,o))});t?.onLoadingFinished?.call(this,l,h,d??null),d?i.push({src:h,file:d}):console.warn("Could not load file: "+h)}if(e!==this._createId||t.abortSignal?.aborted){Fe&&console.log("Aborting loading because create id changed or abort signal was set",e,this._createId);for(const l of i)if(l&&l.file)for(const h of l.file.scenes)di(h,!0,!0)}else{let l=!1;for(const h of i)h&&h.file&&(h.file.scene?(l=!0,this.scene.add(h.file.scene)):console.warn("No scene found in loaded file"));if(!l){for(const h of i)if(h&&h.file&&"parser"in h.file){let d=0;if(!Array.isArray(h.file.parser.json.materials))continue;for(let u=0;u<h.file.parser.json.materials.length;u++){const p=await h.file.parser.getDependency("material",u),m=new c.Object3D;m.position.x=u*1.1,m.position.y=d,this.scene.add(m),Ko.createPrimitive("ShaderBall",{parent:m,material:p})}d+=1}}}return i}restartRenderLoop(){return this.renderer?this._isCreating?(console.warn("Can not start render loop while creating context"),!1):(this.renderer.setAnimationLoop((e,t)=>{this.isManagedExternally||this.update(e,t)}),!0):(console.error("Can not start render loop without renderer"),!1)}_renderlooperrors=0;update(e,t){if(t===void 0&&(t=null),A()||Fe||IS())try{this.internalStep(e,t),this._renderlooperrors=0}catch(i){this._renderlooperrors+=1,(A()||Fe)&&(i instanceof Error||i instanceof TypeError)&&Se("Caught unhandled exception during render-loop - see console for details.",ai.Error),console.error("Frame #"+this.time.frame+`
782
- `,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(e,t)}updatePhysics(e){this.internalUpdatePhysics(e)}_lastTimestamp=0;_accumulatedTime=0;_dispatchReadyAfterFrame=!1;internalStep(e,t){this.internalOnBeforeRender(e,t)!==!1&&(this.internalOnRender(),this.internalOnAfterRender())}internalOnBeforeRender(e,t){this.renderer.info.autoReset=!!t,this.renderer.info.autoReset===!1&&this.renderer.info.reset();const i=t!==null&&this._xrFrame===null;if(this._xrFrame=t,i&&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=e),this._accumulatedTime+=(e-this._lastTimestamp)/1e3,this._lastTimestamp=e;let n=this.targetFrameRate;if(typeof n=="object"&&(n=n.value),this._accumulatedTime<1/(n+1))return!1;this._accumulatedTime=0}if(this._stats?.begin(),U.Current=this,this.onHandlePaused())return!1;for(U.Current=this,this.time.update(),DC&&console.log("FPS",this.time.smoothedFps.toFixed(0)),id(this),Th(this.scene),Xb(this),hn(this,-1);this._cameraStack.length>0&&(!this.mainCameraComponent||this.mainCameraComponent.destroyed);){this._cameraStack.splice(this._cameraStack.length-1,1);const n=this._cameraStack[this._cameraStack.length-1];this.setCurrentCamera(n)}if(this.pre_update_oneshot_callbacks){for(const n in this.pre_update_oneshot_callbacks)this.pre_update_oneshot_callbacks[n]();this.pre_update_oneshot_callbacks.length=0}if(this.pre_update_callbacks)for(const n in this.pre_update_callbacks)this.pre_update_callbacks[n]();this._currentFrameEvent=0;for(let n=0;n<this.scripts_earlyUpdate.length;n++){const o=this.scripts_earlyUpdate[n];o.activeAndEnabled&&o.earlyUpdate!==void 0&&(U.Current=this,o.earlyUpdate())}if(this.executeCoroutines(0),hn(this,0),this.onHandlePaused())return!1;this._currentFrameEvent=1;for(let n=0;n<this.scripts_update.length;n++){const o=this.scripts_update[n];o.activeAndEnabled&&o.update!==void 0&&(U.Current=this,o.update())}if(this.executeCoroutines(1),hn(this,1),this.onHandlePaused())return!1;this._currentFrameEvent=2;for(let n=0;n<this.scripts_lateUpdate.length;n++){const o=this.scripts_lateUpdate[n];o.activeAndEnabled&&o.lateUpdate!==void 0&&(U.Current=this,o.lateUpdate())}if(this.executeCoroutines(2),hn(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 n=0;n<this.scripts_onBeforeRender.length;n++){const o=this.scripts_onBeforeRender[n];o.activeAndEnabled&&o.onBeforeRender!==void 0&&(U.Current=this,o.onBeforeRender(t))}if(this.executeCoroutines(3),hn(this,3),this._needsUpdateSize&&this.updateSize(),this.pre_render_callbacks)for(const n in this.pre_render_callbacks)this.pre_render_callbacks[n](t)}return!0}internalUpdatePhysics(e){if(!this.physics.engine)return!1;const t=e,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||(US(this),this._currentFrameEvent=-1,G.nodeFrame.update(),this.renderNow(),this._currentFrameEvent=4)}internalOnAfterRender(){if(this.isVisibleToUser||this.runInBackground){for(let e=0;e<this.scripts_onAfterRender.length;e++){const t=this.scripts_onAfterRender[e];t.activeAndEnabled&&t.onAfterRender!==void 0&&(U.Current=this,t.onAfterRender())}if(this.executeCoroutines(4),hn(this,4),this.post_render_callbacks)for(const e in this.post_render_callbacks)this.post_render_callbacks[e]()}this._currentFrameEvent=-1,this.connection.sendBufferedMessagesNow(),this._stats&&(this._stats.end(),this.time.frameCount%150===0&&console.log(this.renderer.info.render.calls+" DrawCalls",`
792
+ `,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(e,t)}updatePhysics(e){this.internalUpdatePhysics(e)}_lastTimestamp=0;_accumulatedTime=0;_dispatchReadyAfterFrame=!1;internalStep(e,t){this.internalOnBeforeRender(e,t)!==!1&&(this.internalOnRender(),this.internalOnAfterRender())}internalOnBeforeRender(e,t){this.renderer.info.autoReset=!!t,this.renderer.info.autoReset===!1&&this.renderer.info.reset(),this._needsVisibleUpdate=!0;const i=t!==null&&this._xrFrame===null;if(this._xrFrame=t,i&&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=e),this._accumulatedTime+=(e-this._lastTimestamp)/1e3,this._lastTimestamp=e;let n=this.targetFrameRate;if(typeof n=="object"&&(n=n.value),this._accumulatedTime<1/(n+1))return!1;this._accumulatedTime=0}if(this._stats?.begin(),U.Current=this,this.onHandlePaused())return!1;for(U.Current=this,this.time.update(),DC&&console.log("FPS",this.time.smoothedFps.toFixed(0)),id(this),Th(this.scene),Xb(this),hn(this,-1);this._cameraStack.length>0&&(!this.mainCameraComponent||this.mainCameraComponent.destroyed);){this._cameraStack.splice(this._cameraStack.length-1,1);const n=this._cameraStack[this._cameraStack.length-1];this.setCurrentCamera(n)}if(this.pre_update_oneshot_callbacks){for(const n in this.pre_update_oneshot_callbacks)this.pre_update_oneshot_callbacks[n]();this.pre_update_oneshot_callbacks.length=0}if(this.pre_update_callbacks)for(const n in this.pre_update_callbacks)this.pre_update_callbacks[n]();this._currentFrameEvent=0;for(let n=0;n<this.scripts_earlyUpdate.length;n++){const o=this.scripts_earlyUpdate[n];o.activeAndEnabled&&o.earlyUpdate!==void 0&&(U.Current=this,o.earlyUpdate())}this.executeCoroutines(0),hn(this,0),this._currentFrameEvent=1;for(let n=0;n<this.scripts_update.length;n++){const o=this.scripts_update[n];o.activeAndEnabled&&o.update!==void 0&&(U.Current=this,o.update())}this.executeCoroutines(1),hn(this,1),this._currentFrameEvent=2;for(let n=0;n<this.scripts_lateUpdate.length;n++){const o=this.scripts_lateUpdate[n];o.activeAndEnabled&&o.lateUpdate!==void 0&&(U.Current=this,o.lateUpdate())}if(this.executeCoroutines(2),hn(this,2),this.physicsSteps===void 0&&(this.physicsSteps=1),this.physics.engine&&this.physicsSteps>0&&this.internalUpdatePhysics(this.physicsSteps),this.isVisibleToUser||this.runInBackground){this._currentFrameEvent=3;for(let n=0;n<this.scripts_onBeforeRender.length;n++){const o=this.scripts_onBeforeRender[n];o.activeAndEnabled&&o.onBeforeRender!==void 0&&(U.Current=this,o.onBeforeRender(t))}if(this.executeCoroutines(3),hn(this,3),this._needsUpdateSize&&this.updateSize(),this.pre_render_callbacks)for(const n in this.pre_render_callbacks)this.pre_render_callbacks[n](t)}return!0}internalUpdatePhysics(e){if(!this.physics.engine)return!1;const t=e,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||(US(this),this._currentFrameEvent=-1,G.nodeFrame.update(),this.renderNow(),this._currentFrameEvent=4)}internalOnAfterRender(){if(this.isVisibleToUser||this.runInBackground){for(let e=0;e<this.scripts_onAfterRender.length;e++){const t=this.scripts_onAfterRender[e];t.activeAndEnabled&&t.onAfterRender!==void 0&&(U.Current=this,t.onAfterRender())}if(this.executeCoroutines(4),hn(this,4),this.post_render_callbacks)for(const e in this.post_render_callbacks)this.post_render_callbacks[e]()}this._currentFrameEvent=-1,this.connection.sendBufferedMessagesNow(),this._stats&&(this._stats.end(),this.time.frameCount%150===0&&console.log(this.renderer.info.render.calls+" DrawCalls",`
783
793
  Render:`,{...this.renderer.info.render},`
784
794
  Memory:`,{...this.renderer.info.memory},`
785
795
  Target Framerate: `+this.targetFrameRate)),this._dispatchReadyAfterFrame&&(this._dispatchReadyAfterFrame=!1,this.domElement.dispatchEvent(new CustomEvent("ready")),re.dispatchCallback(oe.ContextFirstFrameRendered,this))}_tempClearColor=new c.Color;_tempClearColor2=new c.Color;renderNow(e){if(!e&&(e=this.mainCamera,!e))return!1;if(this.handleRendererContextLost(),this._isRendering=!0,this.renderRequiredTextures(),this.renderer.toneMapping!==c.NoToneMapping&&A0(),this.composer&&!this.isInXR){e&&"setMainCamera"in this.composer&&this.composer.passes[0]?.mainCamera!=e&&this.composer.setMainCamera(e);const t=this.renderer.getClearColor(this._tempClearColor),i=this.renderer.getClearAlpha();this._tempClearColor2.copy(t),this.renderer.setClearColor(t.convertSRGBToLinear(),this.renderer.getClearAlpha()),this.composer.render(this.time.deltaTime),this.renderer.setClearColor(this._tempClearColor2,i)}else e&&(this.isInXR&&exports.DeviceUtilities.isMacOS()&&this.renderer.clearDepth(),this.renderer.render(this.scene,e));return this._isRendering=!1,!0}_contextRestoreTries=0;handleRendererContextLost(){this.time.frame%10&&this.renderer.getContext().isContextLost()&&this._contextRestoreTries++<100&&(console.warn("Attempting to recover WebGL context..."),this.renderer.forceContextRestore())}_wasPaused=!1;onHandlePaused(){const e=this.evaluatePaused();if(this._wasPaused!==e){LC&&console.log("Paused?",e,"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&&(U.Current=this,i.onPausedChanged(e,this._wasPaused))}}return this._wasPaused=e,e}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 c.WebGLRenderTarget(this.domWidth,this.domHeight),this._requireDepthTexture){const i=new c.DepthTexture(this.domWidth,this.domHeight);this._renderTarget.depthTexture=i}this._requireColorTexture&&(this._renderTarget.texture=new c.Texture,this._renderTarget.texture.generateMipmaps=!1,this._renderTarget.texture.minFilter=c.NearestFilter,this._renderTarget.texture.magFilter=c.NearestFilter,this._renderTarget.texture.format=c.RGBAFormat)}const e=this._renderTarget;e.texture&&(e.texture.colorSpace=this.renderer.outputColorSpace);const t=this.renderer.getRenderTarget();this.renderer.setRenderTarget(e),this.renderer.render(this.scene,this.mainCamera),this.renderer.setRenderTarget(t)}executeCoroutines(e){if(this.coroutines[e]){const i=this.coroutines[e];for(let n=0;n<i.length;n++)try{const o=i[n];if(!o.comp||o.comp.destroyed||!o.main||o.comp.enabled===!1){IC&&console.log("Removing coroutine",o.comp,o.comp.enabled),i.splice(n,1),--n;continue}const a=o.chained;if(a&&a.length>0){const u=a[a.length-1].next();if(u.done&&a.pop(),t(u)&&(o.chained||(o.chained=[]),o.chained.push(u.value)),!u.done)continue}const l=o.main.next();if(l.done===!0){i.splice(n,1),--n;continue}const h=l.value;if(t(h)){if(h.next().done)continue;o.chained||(o.chained=[]),o.chained.push(h)}else if(h instanceof Promise){const d=h;o.chained||(o.chained=[]);const u=M0(d);o.chained?.push(u);continue}}catch(o){console.error(o)}}function t(i){return!!(i&&i.next&&i.return)}}}const oi=w("debuglicense"),B0=[];let On="basic";oi&&console.log("License Type: "+On);function kn(){switch(On){case"pro":case"enterprise":return!0}return!1}function dc(){switch(On){case"indie":return!0}return!1}function gm(){switch(On){case"edu":return!0}return!1}function Rn(){return kn()||dc()||gm()}function FC(s){if(kn()||dc()||gm())return s(!0);B0.push(s)}function ah(s){for(const e of B0)try{e(s)}catch{}}re.registerCallback(oe.ContextRegistered,s=>{NC(s.context),zC(s.context),setTimeout(()=>$C(s.context),2e3)});let ra,cp=!1,hp="";async function UC(){if(ra)return ra;if(On==="basic")try{const s="https://engine.needle.tools/licensing/check?location="+encodeURIComponent(window.location.href)+"&version="+Ji+"&generator="+encodeURIComponent(kd),e=await fetch(s,{method:"GET"}).catch(t=>{oi&&console.error("License check failed",t)});e?.status===200?(cp=!1,oi&&console.log("License check succeeded"),On="pro",ah(!0)):e?.status===403?(ah(!1),cp=!0,hp=await e.text()):(ah(!1),oi&&console.log("License check failed with status "+e?.status))}catch(s){ah(!1),oi&&console.error("License check failed",s)}else oi&&console.log('Runtime license check is skipped because license is already applied as "'+On+'"')}ra=UC();async function zC(s){function e(){const n=document.createElement("div");n.className="needle-forbidden",n.style.cssText=`
@@ -937,12 +947,12 @@ ${t.path}! : AssetReference;
937
947
  Could not find method ${r.method} on object ${l.name}. Please rename ${r.method} to ${p}?
938
948
  `,l[p],`
939
949
  in script: `,l),ce("EventList methods must start with lowercase letter, see console for details");return}else console.warn(`EventList method:
940
- Could not find method ${r.method} on object ${l.name}`,l,typeof l[r.method])};if(typeof l[r.method]!="function"){let p=!1,m=l;for(;m;){const y=Object.getOwnPropertyDescriptor(m,r.method);if(y&&(y.writable===!0||y.set)){p=!0;break}m=Object.getPrototypeOf(m)}!p&&(A()||st)&&d()}}if(l){let d=r.argument;if(d!==void 0?d=a(d):r.arguments!==void 0&&(d=r.arguments.map(a)),!l[r.method])console.warn(`EventList method not found: "${r.method}" on ${l?.name}`);else{d!==void 0&&!Array.isArray(d)&&(d=[d]);const p=new ts(l,r.method,d,r.enabled);i.push(p)}}else A()&&console.warn(`[Dev] EventList: Could not find event listener in scene (${t.object?.name})`,r)}const n=new de(i);st&&console.log(n);const o=t.target;return o!==void 0&&t.path!==void 0&&n.setEventTarget(t.path,o),n}}}const O1=new M1,dd=new WeakMap,k1=c.Texture.prototype.clone;c.Texture.prototype.clone=function(){const s=k1.call(this);return dd.has(s)||dd.set(s,this),s};class Y0 extends Ui{constructor(){super([xn,c.WebGLRenderTarget])}onSerialize(e,t){}onDeserialize(e,t){if(e instanceof c.Texture&&t.type===xn){let i=e;dd.has(i)&&(i=dd.get(i)),i.isRenderTargetTexture=!0,i.flipY=!0,i.offset.y=1,i.repeat.y=-1,i.needsUpdate=!0,i.mipmaps=[],i instanceof c.CompressedTexture&&(i.isCompressedTexture=!1,i.format=c.RGBAFormat);const n=new xn(i.image.width,i.image.height,{colorSpace:c.LinearSRGBColorSpace});return n.texture=i,n}}}new Y0;class K0 extends Ui{constructor(){super([URL])}onSerialize(e,t){return null}onDeserialize(e,t){if(typeof e=="string"&&e.length>0)return Ks(t.gltfId,e)}}new K0;var R1=Object.defineProperty,E1=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&R1(e,t,n),n};class aa extends k{awake(){jt.createIfNoneExists(this.context)}onEnable(){jt.get(this.context)?.register(this)}onDisable(){jt.get(this.context)?.unregister(this)}}class ui extends aa{targets=null;raycastHits=[];ignoreSkinnedMeshes=!1;start(){this.targets=[this.gameObject]}performRaycast(e=null){if(!this.targets)return null;e??=new eo,e.targets=this.targets,e.results=this.raycastHits,e.useAcceleratedRaycast=!0;const t=e.testObject;this.ignoreSkinnedMeshes&&(e.testObject=n=>n instanceof c.SkinnedMesh?"continue in children":t?t(n):!0);const i=this.context.physics.raycast(e);return e.testObject=t,i}}E1([f()],ui.prototype,"ignoreSkinnedMeshes");class Wd extends ui{constructor(){super(),this.ignoreSkinnedMeshes=!0}}class Go extends aa{static allow=!0;performRaycast(e){if(!q.active||!Go.allow||!e?.ray)return null;const t=e.ray.origin;return this.context.physics.sphereOverlap(t,.015,!1,!0)}}class wm{static getObject(e){const t=e[si];return t&&(t.isComponent===!0?e=t.gameObject:e=t),e}static isInteractable(e,t){if(t&&(t.canvasGroup=void 0,t.graphic=void 0),e==null||!e.visible||(e=this.getObject(e),!e.visible))return!1;const i=this.tryFindCanvasGroup(e);if(i?.isCanvasGroup===!0&&(t&&(t.canvasGroup=i),i.blocksRaycasts===!1||i.interactable===!1))return!1;const n=$o(e,o=>{if(o.isGraphic===!0)return o},!1);return t&&n?.isGraphic===!0&&(t.graphic=n),!(n?.raycastTarget===!1||n?.layer===2)}static tryFindCanvasGroup(e){if(!e)return null;const t=$o(e,i=>{const n=i;if(n.blocksRaycasts!==void 0&&n.interactable!==void 0)return n},!1);return t!==void 0?t:this.tryFindCanvasGroup(e.parent)}}function xm(s){const e=s[si];return e||(s.parent?xm(s.parent):null)}function T1(s){return s.isUI===!0||typeof s[si]=="object"}function ud(s,e){if(!s)return;const t=s.material;if(t?.isMaterial===!0){const i=s.parent;i&&i.isText,t.side=e.doubleSided??!0?c.DoubleSide:c.FrontSide,t.shadowSide=e.doubleSided?c.DoubleSide:c.FrontSide,s.castShadow=e.castShadows?e.castShadows:!1,s.receiveShadow=e.receiveShadows?e.receiveShadows:!1}for(const i of s.children)ud(i,e)}function Ar(s,e,t){s[e]===void 0&&console.warn("Field",e,"is undefined on",s);const i=Proxy.revocable(s[e],{set(r,a,l,h){const d=r[a],u=Reflect.set(r,a,l,h);return t(l,d),u}}),n=i.revoke,o=s[e];return i.revoke=()=>{s[e]=o,n()},s[e]=i.proxy,i}const Qy=Symbol("Scheduled action");function A1(s,e,t=pe.OnBeforeRender){let i=s[Qy];i||(i=s[Qy]={});const n=e.name;i[t]||(i[t]={});const o=i[t];if(o[n])return;function*a(){e?.call(s),o[n]=null}const l=s.startCoroutine(a(),t);o[n]=l}const As=w("debugeventsystem");var pp=(s=>(s.BeforeHandleInput="BeforeHandleInput",s.AfterHandleInput="AfterHandleInput",s))(pp||{});U0(s=>{jt.createIfNoneExists(s)});class jt extends k{static ensureUpdateMeshUI(e,t,i=!1){Ua.update(e,t,i)}static markUIDirty(e){Ua.markDirty()}static createIfNoneExists(e){e.scene.getComponent(jt)||e.scene.addComponent(jt)}static get(e){return this.createIfNoneExists(e),e.scene.getComponent(jt)}static get instance(){return this.get(U.Current)}raycaster=[];register(e){e&&this.raycaster&&!this.raycaster.includes(e)&&this.raycaster?.push(e)}unregister(e){const t=this.raycaster?.indexOf(e);t!==void 0&&t!==-1&&this.raycaster?.splice(t,1)}get hasActiveUI(){return this.currentActiveMeshUIComponents.length>0}get isHoveringObjects(){return this.hoveredByID.size>0}awake(){this.gameObject!==this.context.scene&&(console.debug(`[Needle Engine] EventSystem is only allowed on the scene root. Disabling EventSystem on '${this.gameObject.name}'`),this.enabled=!1)}start(){this.context.scene.getComponent(aa)||this.context.scene.addComponent(ui)}onEnable(){this.context.input.addEventListener(we.PointerDown,this.onPointerEvent),this.context.input.addEventListener(we.PointerUp,this.onPointerEvent),this.context.input.addEventListener(we.PointerMove,this.onPointerEvent)}onDisable(){this.context.input.removeEventListener(we.PointerDown,this.onPointerEvent),this.context.input.removeEventListener(we.PointerUp,this.onPointerEvent),this.context.input.removeEventListener(we.PointerMove,this.onPointerEvent)}pressedByID=new Map;hoveredByID=new Map;onBeforeRender(){this.resetMeshUIStates()}onPointerEvent=e=>{if(e===void 0||e.propagationStopped||e.defaultPrevented||e.used)return;const t=new pc(this.context.input,e);this._currentPointerEventName=e.type,t.inputSource=this.context.input,t.isClick=e.isClick,t.isDoubleClick=e.isDoubleClick,t.isDown=e.type==we.PointerDown,t.isUp=e.type==we.PointerUp,t.isPressed=this.context.input.getPointerPressed(e.pointerId);const i=new eo;e.hasRay?i.ray=e.ray:i.screenPoint=this.context.input.getPointerPositionRC(e.pointerId),i.allowSlowRaycastFallback=e.isClick||e.isDoubleClick;const n=this.performRaycast(i);if(As&&(t.isDown?console.log("DOWN",{id:t.pointerId,hits:n.length}):t.isUp&&console.log("UP",{id:t.pointerId,hits:n.length}),t.isClick&&console.log("CLICK",{id:t.pointerId,hits:n.length})),n){for(const r of n)r.event=e,e.intersections.push(r);e.origin.onPointerHits&&e.origin.onPointerHits({sender:this,event:e,hits:n})}As&&t.isClick&&Se("EventSystem: "+t.pointerId+" - "+this.context.time.frame+" - Up:"+t.isUp+", Down:"+t.isDown);const o={sender:this,args:t,hasActiveUI:this.currentActiveMeshUIComponents.length>0};this.dispatchEvent(new CustomEvent("BeforeHandleInput",{detail:o})),this.handleIntersections(n,t),this.dispatchEvent(new CustomEvent("AfterHandleInput",{detail:o}))};_sortedHits=[];_testObjectsCache=new Map;_currentlyActiveRaycaster=null;_currentPointerEventName=null;shouldRaycastObject=e=>{const t=e&&"getComponent"in e?e.getComponent(aa):null;if(t&&t!=this._currentlyActiveRaycaster)return!1;let i=null;if(T1(e)&&(i=e[si]?.gameObject),this._testObjectsCache.has(e)||i&&this._testObjectsCache.has(i))return this._testObjectsCache.get(e)===!1?"continue in children":!0;{let o=hd(e,this._currentPointerEventName);if(!o&&i&&(o=hd(i,this._currentPointerEventName)),o){this._testObjectsCache.set(e,!0);for(const r of e.children)this.shouldRaycastObject_AddToYesCache(r);return!0}return this._testObjectsCache.set(e,!1),"continue in children"}};shouldRaycastObject_AddToYesCache(e){this._testObjectsCache.set(e,!0);for(const t of e.children)this.shouldRaycastObject_AddToYesCache(t)}performRaycast(e){if(!this.raycaster)return null;this._testObjectsCache.clear(),this._sortedHits.length=0,e.testObject=this.shouldRaycastObject;for(const t of this.raycaster){if(!t.activeAndEnabled)continue;this._currentlyActiveRaycaster=t;const i=t.performRaycast(e);this._currentlyActiveRaycaster=null,i&&i.length>0&&this._sortedHits.push(...i)}return this._sortedHits.sort((t,i)=>t.distance-i.distance),this._sortedHits}assignHitInformation(e,t){t?(e.intersection=t,e.point=t.point,e.normal=t.normal,e.face=t.face,e.distance=t.distance,e.instanceId=t.instanceId):(e.intersection=void 0,e.point=void 0,e.normal=void 0,e.face=void 0,e.distance=void 0,e.instanceId=void 0)}handleIntersections(e,t){if(e?.length){e=this.sortCandidates(e);for(const n of e){if(t.event.immediatePropagationStopped)return!1;if(this.assignHitInformation(t,n),this.handleEventOnObject(n.object,t))return!0}}this.assignHitInformation(t,e?.[0]),this.invokePointerCapture(t);const i=this.hoveredByID.get(t.pointerId);return i&&this.propagatePointerExit(i.obj,i.data,null),this.hoveredByID.delete(t.pointerId),t.isUp&&(this.pressedByID.get(t.pointerId)?.handlers.forEach(n=>this.invokeOnPointerUp(t,n)),this.pressedByID.delete(t.pointerId)),!1}_sortingBuffer=[];_noDepthTestingResults=[];sortCandidates(e){this._sortingBuffer.length=0,this._noDepthTestingResults.length=0;for(let t=0;t<e.length;t++){const i=e[t],n=i.object;if(n.material&&n.material.depthTest===!1){this._noDepthTestingResults.push(i);continue}this._sortingBuffer.push(i)}for(const t of this._sortingBuffer)this._noDepthTestingResults.push(t);return this._noDepthTestingResults}out={};handleEventOnObject(e,t){if(!this.testIsVisible(e))return t.isClick&&As&&console.log("not allowed",e),!1;if(t.pointerId===void 0)return As&&console.error("Event without pointer can't be handled",t),!1;t.object=e;const i=e.parent,n=t.isClick??!1;let o=null;if(i&&i.isUI){const d=(t.isPressed||t.isClick)??!1;if(i[si]){const u=i[si].gameObject;if(u){if(!wm.isInteractable(u,this.out))return!1;o=this.out.canvasGroup??null,this.handleMeshUIIntersection(e,d),e=u}}}n&&As&&console.log(this.context.time.frame,e);const r=this.hoveredByID.get(t.pointerId),a=r?.obj;a!==e&&a&&this.propagatePointerExit(a,r.data,e);const h=this.hoveredByID.get(t.pointerId);if(h?(h.obj=e,h.data=t):this.hoveredByID.set(t.pointerId,{obj:e,data:t}),t.isDown){const d=this.pressedByID.get(t.pointerId);d?(d.obj=e,d.data=t):this.pressedByID.set(t.pointerId,{obj:e,data:t,handlers:new Set})}return(o===null||o.interactable)&&this.handleMainInteraction(e,t,a??null),!0}propagate(e,t){for(;e;)x.foreachComponent(e,i=>{t(i)},!1),e=e.parent}handleMainInteraction(e,t,i){const n=this.pressedByID.get(t.pointerId),o=i!==e;let r=!0;switch(t.event.pointerType){case"mouse":case"touch":const a=this.context.input.getPointerPositionLastFrame(t.pointerId),l=this.context.input.getPointerPosition(t.pointerId);r=a&&!I.approximately(a,l);break}this.propagate(e,a=>{const l=a;l.interactable!==!1&&(!l.activeAndEnabled||!l.enabled||(l.onPointerEnter&&o&&this.handlePointerEnter(l,t),t.isDown&&l.onPointerDown&&(l.onPointerDown(t),n?.handlers.add(l),this.handlePointerCapture(t,l)),l.onPointerMove&&(r&&l.onPointerMove(t),this.handlePointerCapture(t,l)),t.isUp&&(l.onPointerUp&&(this.invokeOnPointerUp(t,l),n?.handlers.delete(l)),l.onPointerExit&&t.event?.pointerType===Td.Touch&&(this.handlePointerExit(l,t),this.hoveredByID.delete(t.pointerId))),t.isClick&&l.onPointerClick&&l.onPointerClick(t)))}),t.isUp&&(n?.handlers.forEach(a=>{this.invokeOnPointerUp(t,a)}),this.pressedByID.delete(t.pointerId))}propagatePointerExit(e,t,i){this.propagate(e,n=>{if(!n.gameObject||n.destroyed)return;const o=n;if(o.onPointerExit||o.onPointerEnter){if(i&&this.isChild(i,n.gameObject))return;this.handlePointerExit(o,t)}})}invokeOnPointerUp(e,t){t.onPointerUp?.call(t,e),this.releasePointerCapture(e,t)}handlePointerEnter(e,t){e.onPointerEnter&&this.updatePointerState(e,t.pointerId,this.pointerEnterSymbol,!0)&&e.onPointerEnter(t),this.updatePointerState(e,t.pointerId,this.pointerExitSymbol,!1)}handlePointerExit(e,t){e.onPointerExit&&this.updatePointerState(e,t.pointerId,this.pointerExitSymbol,!0)&&e.onPointerExit(t),this.updatePointerState(e,t.pointerId,this.pointerEnterSymbol,!1)}updatePointerState(e,t,i,n){let o=e[i];if(n)return o&&o.includes(t)?!1:(o=o||[],o.push(t),e[i]=o,!0);{if(!o||!o.includes(t))return!1;const r=o.indexOf(t);return r!==-1&&o.splice(r,1),!0}}_capturedPointer={};handlePointerCapture(e,t){if(e.z__pointer_ctured){e.z__pointer_ctured=!1;const i=e.pointerId;if(t.onPointerMove){const n=this._capturedPointer[i]||[];n.push(t),this._capturedPointer[i]=n}else A()&&!t.z__warned_no_pointermove&&(t.z__warned_no_pointermove=!0,console.warn("PointerCapture was requested but the component doesn't implement onPointerMove. It will not receive any pointer events"))}else e.z__pointer_cture_rleased&&(e.z__pointer_cture_rleased=!1,this.releasePointerCapture(e,t))}releasePointerCapture(e,t){const i=e.pointerId;if(this._capturedPointer[i]){const n=this._capturedPointer[i].indexOf(t);n!==-1&&(this._capturedPointer[i].splice(n,1),As&&console.log("released pointer capture",i,t,this._capturedPointer))}}invokePointerCapture(e){if(e.event.type===we.PointerMove){const t=e.pointerId,i=this._capturedPointer[t];if(i){As&&console.log("Captured",t,i);for(let n=0;n<i.length;n++){const o=i[n];if(o.destroyed){i.splice(n,1),n--;continue}o.onPointerMove?.call(o,e)}}}}pointerEnterSymbol=Symbol("pointerEnter");pointerExitSymbol=Symbol("pointerExit");isChild(e,t){return!e||!t?!1:e===t?!0:e.parent?this.isChild(e.parent,t):!1}handleMeshUiObjectWithoutShadowDom(e,t){return!e||!e.isUI?!0:this.handleMeshUIIntersection(e,t)}currentActiveMeshUIComponents=[];handleMeshUIIntersection(e,t){const i=Ua.updateState(e,t);return i&&this.currentActiveMeshUIComponents.push(i),i!==null}resetMeshUIStates(){if(this.context.input.getPointerPressedCount()>0&&Ua.resetLastSelected(),!(!this.currentActiveMeshUIComponents||this.currentActiveMeshUIComponents.length<=0)){for(let e=0;e<this.currentActiveMeshUIComponents.length;e++){const t=this.currentActiveMeshUIComponents[e];Ua.resetState(t)}this.currentActiveMeshUIComponents.length=0}}testIsVisible(e){return e?x.isActiveSelf(e)?this.testIsVisible(e.parent):!1:!0}}class Ua{static lastSelected=null;static lastUpdateFrame=[];static needsUpdate=!1;static markDirty(){this.needsUpdate=!0}static update(e,t,i=!1){if(i){e.update();return}const n=t.time.frameCount;for(const o of this.lastUpdateFrame)if(o.context===t){if(n===o.frame)return;o.frame=n;let r=this.needsUpdate||n<1;o.nextUpdate<=n&&(r=!0),r&&(As&&console.log("Update threemeshui"),this.needsUpdate=!1,o.nextUpdate=n+60,e.update());return}this.lastUpdateFrame=[{context:t,frame:n,nextUpdate:n+60}],e.update(),this.needsUpdate=!1}static updateState(e,t){let i=null;if(e&&(i=this.findBlockOrTextInParent(e),i&&i!==this.lastSelected)){if(i.interactable===!1)return null;this.needsUpdate=!0}return i}static resetLastSelected(){const e=this.lastSelected;e&&(this.lastSelected=null,this.resetState(e))}static resetState(e){e&&(this.needsUpdate=!0)}static findBlockOrTextInParent(e){return e?e.isBlock||e.isText?e:this.findBlockOrTextInParent(e.parent):null}}var L1=Object.defineProperty,Ce=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&L1(e,t,n),n};const Pi=w("debugorbit"),ef=w("freecam"),za=w("debugcamerafit"),hh=w("smoothcam"),D1={LEFT:"",UP:"",RIGHT:"",BOTTOM:""};let tf;class Vl extends CustomEvent{constructor(e,t){super("target-reached",{detail:{controls:e,type:t}})}}class he extends k{get isCameraController(){return!0}get controls(){return this._controls}get controllerObject(){return this._cameraObject}onStartInteraction(e){this.controls?.addEventListener("start",e)}autoTarget=!0;autoFit=!1;enableRotate=!0;autoRotate=!1;autoRotateSpeed=1;minAzimuthAngle=1/0;maxAzimuthAngle=1/0;minPolarAngle=0;maxPolarAngle=Math.PI;enableKeys=!1;enableDamping=!0;dampingFactor=.1;enableZoom=!0;minZoom=0;maxZoom=1/0;zoomSpeed=1;zoomToCursor=!1;enablePan=!0;lookAtConstraint=null;lookAtConstraint01=1;allowInterrupt=!0;middleClickToFocus=!0;doubleClickToFocus=!0;clickBackgroundToFitScene=2;get targetElement(){return this._controls?.domElement??this._targetElement}set targetElement(e){this._targetElement=e,this._controls&&this._controls.domElement!==e&&(this._controls.disconnect(),this._controls.domElement=e,this._controls.connect())}_targetElement=null;debugLog=!1;get targetLerpSpeed(){return 5}set targetLerpSpeed(e){this.targetLerpDuration=1/e}targetLerpDuration=1;rotateLeft(e){this._controls?._rotateLeft(e)}rotateUp(e){this._controls?._rotateUp(e)}pan(e,t){this._controls?._pan(e,t)}zoomIn(e){e>0?this._controls?._dollyIn(1-e):e<0&&this._controls?._dollyOut(1+e)}_controls=null;_cameraObject=null;_lookTargetLerpActive=!1;_lookTargetStartPosition=new c.Vector3;_lookTargetEndPosition=new c.Vector3;_lookTargetLerp01=0;_lookTargetLerpDuration=0;_cameraLerpActive=!1;_cameraStartPosition=new c.Vector3;_cameraEndPosition=new c.Vector3;_cameraLerp01=0;_cameraLerpDuration=0;_fovLerpActive=!1;_fovLerpStartValue=0;_fovLerpEndValue=0;_fovLerp01=0;_fovLerpDuration=0;_inputs=0;_enableTime=0;_startedListeningToKeyEvents=!1;_eventSystem;_afterHandleInputFn;_camera=null;_syncedTransform;_didSetTarget=0;awake(){Pi&&console.debug("OrbitControls",this),this._didSetTarget=0,this._startedListeningToKeyEvents=!1}start(){this._eventSystem=jt.get(this.context)??void 0,this._eventSystem&&(this._afterHandleInputFn=this.afterHandleInput.bind(this),this._eventSystem.addEventListener(pp.AfterHandleInput,this._afterHandleInputFn))}onDestroy(){this._controls?.dispose(),this._eventSystem?.removeEventListener(pp.AfterHandleInput,this._afterHandleInputFn)}onEnable(){this._didSetTarget=0,this._enableTime=this.context.time.time;const e=x.getComponent(this.gameObject,Wt);this._camera=e;let t=e?.threeCamera;if(!t&&this.gameObject instanceof c.PerspectiveCamera&&(t=this.gameObject),t&&$f(t,this,!0),!this._controls&&t instanceof c.Object3D){this._cameraObject=t;const i=this.targetElement??this.context.renderer.domElement,n=t?.quaternion.clone();this._controls=new G.OrbitControls(t,i),t?.quaternion.copy(n),tf===void 0&&(tf={...this._controls.keys});const o=X(t),r=this.gameObject.worldForward,l=o.clone().sub(r.multiplyScalar(2.5));this._controls.target.copy(l)}if(this._controls)if(ef&&(this.enablePan=!0,this.enableZoom=!0,this.middleClickToFocus=!0,exports.DeviceUtilities.isMobileDevice()&&(this.doubleClickToFocus=!0)),this._controls.addEventListener("start",this.onControlsChangeStarted),this._controls.addEventListener("endMovement",this.onControlsChangeEnded),!this._startedListeningToKeyEvents&&this.enableKeys)this._startedListeningToKeyEvents=!0,this._controls.listenToKeyEvents(this.context.domElement);else try{this._controls.stopListenToKeyEvents()}catch{}this._syncedTransform=x.getComponent(this.gameObject,Ln)??void 0,this.context.pre_render_callbacks.push(this.__onPreRender),this._activePointerEvents=[],this.context.input.addEventListener("pointerdown",this._onPointerDown,{queue:$t.Early}),this.context.input.addEventListener("pointerdown",this._onPointerDownLate,{queue:$t.Late}),this.context.input.addEventListener("pointerup",this._onPointerUp,{queue:$t.Early}),this.context.input.addEventListener("pointerup",this._onPointerUpLate,{queue:$t.Late})}onDisable(){if(this._camera?.threeCamera&&$f(this._camera.threeCamera,this,!1),this._controls){this._controls.enabled=!1,this._controls.autoRotate=!1,this._controls.removeEventListener("start",this.onControlsChangeStarted),this._controls.removeEventListener("endMovement",this.onControlsChangeEnded);try{this._controls.stopListenToKeyEvents()}catch{}this._startedListeningToKeyEvents=!1}this._activePointerEvents.length=0,this.context.input.removeEventListener("pointerdown",this._onPointerDown),this.context.input.removeEventListener("pointerdown",this._onPointerDownLate),this.context.input.removeEventListener("pointerup",this._onPointerUp),this.context.input.removeEventListener("pointerup",this._onPointerUpLate)}_activePointerEvents;_lastTimeClickOnBackground=-1;_clickOnBackgroundCount=0;_onPointerDown=e=>{this._activePointerEvents.push(e)};_onPointerDownLate=e=>{e.used&&this._controls&&(this._controls.enabled=!1)};_onPointerUp=e=>{for(let t=this._activePointerEvents.length-1;t>=0;t--){const i=this._activePointerEvents[t];if(i.pointerId===e.pointerId&&i.button===e.button){this._activePointerEvents.splice(t,1);break}}if(this.clickBackgroundToFitScene>0&&e.isClick&&e.button===0){if(e.hasRay||e.intersections.push(...this.context.physics.raycast()),e.intersections.length<=0){const t=this.context.time.time-this._lastTimeClickOnBackground;this._lastTimeClickOnBackground=this.context.time.time,this.clickBackgroundToFitScene<=1||t<this.clickBackgroundToFitScene*.15?(this._clickOnBackgroundCount+=1,this._clickOnBackgroundCount>=this.clickBackgroundToFitScene-1&&this.fitCamera(this.context.scene.children,{immediate:!1})):this._clickOnBackgroundCount=0}Pi&&console.log(this.clickBackgroundToFitScene,e.intersections.length,this._clickOnBackgroundCount)}};_onPointerUpLate=e=>{this.doubleClickToFocus&&e.isDoubleClick&&!e.used&&this.setTargetFromRaycast()};updateTargetNow(e){const t=new c.Ray(this._cameraObject?.worldPosition,this._cameraObject?.worldForward.multiplyScalar(-1)),i=this.context.physics.raycastFromRay(t,e),n=i.length>0?i[0]:void 0;n&&n.distance>this.minZoom&&n.distance<this.maxZoom&&(Pi&&j.DrawWireSphere(n.point,.1,16711680,2),this._controls?.target.copy(i[0].point))}_orbitStartAngle=0;_zoomStartDistance=0;onControlsChangeStarted=()=>{this._controls&&(this._orbitStartAngle=this._controls.getAzimuthalAngle()+this._controls.getPolarAngle(),this._zoomStartDistance=this._controls.getDistance()),this._syncedTransform&&this._syncedTransform.requestOwnership()};onControlsChangeEnded=()=>{if(this._controls&&this.autoTarget){const t=this._controls.getAzimuthalAngle()+this._controls.getPolarAngle()-this._orbitStartAngle;Math.abs(t)<.01?(Pi&&console.debug("OrbitControls: Update target",{deltaAngle:t}),this.updateTargetNow({allowSlowRaycastFallback:!1})):Pi&&console.debug("OrbitControls: No target update",{deltaAngle:t})}};_shouldDisable=!1;afterHandleInput(e){e.detail.args.pointerId===0&&(e.detail.args.isDown?this._controls&&this._eventSystem&&(this._shouldDisable=this._eventSystem.hasActiveUI):(!e.detail.args.isPressed||e.detail.args.isUp)&&(this._shouldDisable=!1))}onBeforeRender(){if(!this._controls)return;if(this._cameraObject!==this.context.mainCamera){this._controls.enabled=!1;return}if(this._controls.enabled=!0,(this.context.input.getPointerDown(1)||this.context.input.getPointerDown(2)||this.context.input.mouseWheelChanged||this.context.input.getPointerPressed(0)&&this.context.input.getPointerPositionDelta(0)?.length())&&(this._inputs+=1),this._inputs>0&&this.allowInterrupt&&(this.enableRotate&&(this.autoRotate=!1),this._cameraLerpActive=!1,this._lookTargetLerpActive=!1),this._inputs=0,this.autoTarget&&this._didSetTarget++===0){const t=x.getComponent(this.gameObject,Wt);if(t&&!this.setLookTargetFromConstraint()){this.debugLog&&console.log("NO TARGET");const i=X(t.threeCamera),n=Math.max(.01,i.length()),o=new c.Vector3(0,0,-n).applyMatrix4(t.threeCamera.matrixWorld);Pi&&j.DrawLine(i,o,5592575,10),this.setLookTargetPosition(o,!0)}if(!this.setLookTargetFromConstraint()){const i=new eo;i.screenPoint=new c.Vector2(0,0),i.lineThreshold=.1;const n=this.context.physics.raycast(i);n.length>0&&this.setLookTargetPosition(n[0].point,!0),za&&console.log("OrbitControls hits",...n)}}if(this.middleClickToFocus&&this.context.input.getPointerClicked(1)&&this.setTargetFromRaycast(),this._lookTargetLerpActive||this._cameraLerpActive||this._fovLerpActive){if(this._cameraLerpActive&&this._cameraObject)if(this._cameraLerp01+=this.context.time.deltaTime/this._cameraLerpDuration,this._cameraLerp01>=1)this._cameraObject.position.copy(this._cameraEndPosition),this._cameraLerpActive=!1,this.dispatchEvent(new Vl(this,"camera"));else{const t=I.easeInOutCubic(this._cameraLerp01);this._cameraObject.position.lerpVectors(this._cameraStartPosition,this._cameraEndPosition,t)}if(this._lookTargetLerpActive)if(this._lookTargetLerp01+=this.context.time.deltaTime/this._lookTargetLerpDuration,this._lookTargetLerp01>=1)this._controls.target.copy(this._lookTargetEndPosition),this._lookTargetLerpActive=!1,this.dispatchEvent(new Vl(this,"lookat"));else{const t=I.easeInOutCubic(this._lookTargetLerp01);this._controls.target.lerpVectors(this._lookTargetStartPosition,this._lookTargetEndPosition,t)}if(this._fovLerpActive&&this._cameraObject){const t=this._cameraObject;if(this._fovLerp01+=this.context.time.deltaTime/this._fovLerpDuration,this._fovLerp01>=1)t.fov=this._fovLerpEndValue,this._fovLerpActive=!1;else{const i=I.easeInOutCubic(this._fovLerp01);t.fov=I.lerp(this._fovLerpStartValue,this._fovLerpEndValue,i)}t.updateProjectionMatrix()}}if(this._controls){if(this.debugLog&&(this._controls.domElement=this.context.renderer.domElement),this._controls.enabled=!this._shouldDisable&&this._camera===this.context.mainCameraComponent&&!this.context.isInXR&&!this._activePointerEvents.some(t=>t.used),this._controls.keys=this.enableKeys?tf:D1,this._controls.autoRotate=this.autoRotate,this._controls.autoRotateSpeed=this.autoRotateSpeed,this._controls.enableZoom=this.enableZoom,this._controls.zoomSpeed=this.zoomSpeed,this._controls.zoomToCursor=this.zoomToCursor,this._controls.enableDamping=this.enableDamping,this._controls.dampingFactor=this.dampingFactor,this._controls.enablePan=this.enablePan,this._controls.enableRotate=this.enableRotate,this._controls.minAzimuthAngle=this.minAzimuthAngle,this._controls.maxAzimuthAngle=this.maxAzimuthAngle,this._controls.minPolarAngle=this.minPolarAngle,this._controls.maxPolarAngle=this.maxPolarAngle,ef||(this._camera?.threeCamera?.type==="PerspectiveCamera"?(this._controls.minDistance=this.minZoom,this._controls.maxDistance=this.maxZoom,this._controls.minZoom=0,this._controls.maxZoom=1/0):(this._controls.minDistance=0,this._controls.maxDistance=1/0,this._controls.minZoom=this.minZoom,this._controls.maxZoom=this.maxZoom)),typeof hh=="number"||hh===!0){this._controls.enableDamping=!0;const t=typeof hh=="number"?hh:.99;this._controls.dampingFactor=Math.max(.001,1-Math.min(1,t))}this.allowInterrupt||(this._lookTargetLerpActive&&(this._controls.enablePan=!1),this._cameraLerpActive&&(this._controls.enableRotate=!1,this._controls.autoRotate=!1),(this._lookTargetLerpActive||this._cameraLerpActive)&&(this._controls.enableZoom=!1)),this.context.isInXR||(!ef&&this.lookAtConstraint?.locked&&this.setLookTargetFromConstraint(0,this.lookAtConstraint01),this._controls.update(this.context.time.deltaTime),Pi&&j.DrawWireSphere(this._controls.target,.1,65280))}}__onPreRender=()=>{const e=this.context.pre_render_callbacks.indexOf(this.__onPreRender);e>=0&&this.context.pre_render_callbacks.splice(e,1),this.autoFit&&(this.autoFit=!1,this.fitCamera({centerCamera:"y",immediate:!0,objects:this.scene.children}))};setCameraAndLookTarget(e,t=!1){if(!e)return(A()||Pi)&&console.warn("[OrbitControls] setCameraAndLookTarget target is null"),!1;if(!(e instanceof c.Object3D)&&!(e instanceof Wt))return(A()||Pi)&&console.warn("[OrbitControls] setCameraAndLookTarget target is not an Object3D or Camera"),!1;e instanceof Wt&&(e=e.gameObject);const i=e.worldPosition,n=e.worldForward;e instanceof c.Camera&&(Pi&&console.debug("[OrbitControls] setCameraAndLookTarget flip forward direction for camera"),n.multiplyScalar(-1));const o=new c.Ray(i,n);return Pi&&j.DrawRay(o.origin,o.direction,16711680,10),this.setTargetFromRaycast(o,t)||this.setLookTargetPosition(o.at(2,V()),t),this.setCameraTargetPosition(i,t),!0}setCameraTargetPosition(e,t=!1){e&&(e instanceof c.Object3D&&(e=X(e)),this._cameraEndPosition||(this._cameraEndPosition=new c.Vector3),this._cameraEndPosition.copy(e),t===!0?(this._cameraLerpActive=!1,this._cameraObject&&this._cameraObject.position.copy(this._cameraEndPosition)):this._cameraObject&&(this._cameraLerpActive=!0,this._cameraLerp01=0,this._cameraStartPosition.copy(this._cameraObject?.position),typeof t=="number"?this._cameraLerpDuration=t:this._cameraLerpDuration=this.targetLerpDuration))}get cameraLerpActive(){return this._cameraLerpActive}stopCameraLerp(){this._cameraLerpActive=!1}setFieldOfView(e,t=!1){if(!this._controls||typeof e!="number")return;const i=this._camera?.threeCamera;i&&(t===!0?i.fov=e:(this._fovLerpActive=!0,this._fovLerp01=0,this._fovLerpStartValue=i.fov,this._fovLerpEndValue=e,typeof t=="number"?this._fovLerpDuration=t:this._fovLerpDuration=this.targetLerpDuration))}setLookTargetPosition(e=null,t=!1){this._controls&&e&&(e instanceof c.Object3D&&(e=X(e)),this._lookTargetEndPosition.copy(e),this._didSetTarget++,Pi&&(console.warn("OrbitControls: setLookTargetPosition",e,t),j.DrawWireSphere(this._lookTargetEndPosition,.2,16711680,2)),t===!0?this._controls.target.copy(this._lookTargetEndPosition):(this._lookTargetLerpActive=!0,this._lookTargetLerp01=0,this._lookTargetStartPosition.copy(this._controls.target),typeof t=="number"?this._lookTargetLerpDuration=t:this._lookTargetLerpDuration=this.targetLerpDuration))}get lookTargetLerpActive(){return this._lookTargetLerpActive}stopLookTargetLerp(){this._lookTargetLerpActive=!1}setLookTargetFromConstraint(e=0,t=1){if(!this._controls||this.lookAtConstraint?.enabled===!1)return!1;const i=this.lookAtConstraint?.sources;if(i&&i.length>0){const n=i[e];if(n)return n.getWorldPosition(this._lookTargetEndPosition),this.lerpLookTarget(this._lookTargetEndPosition,t),!0}return!1}lerpTarget(e,t){return this.lerpLookTarget(e,t)}lerpLookTarget(e,t){this._controls&&(t>=1?this._controls.target.copy(e):this._controls.target.lerp(e,t))}setTargetFromRaycast(e,t=!1){if(!this.controls)return!1;const i=e?this.context.physics.raycastFromRay(e):this.context.physics.raycast();for(const n of i)if(n.distance>0&&x.isActiveInHierarchy(n.object)){const o=xm(n.object);if(o&&o.canvas?.screenspace)break;return this.setLookTargetPosition(n.point,t),!0}return!1}fitCamera(e,t){if(this.context.isInXR)return;let i;if(Array.isArray(e)?i=e:e&&"type"in e?i=e.children:e&&typeof e=="object"&&!(e instanceof c.Object3D)&&!Array.isArray(e)&&(t=e,i=t.objects),i&&!Array.isArray(i)&&(i=i.children),(!Array.isArray(i)||i&&i.length<=0)&&(i=this.context.scene.children),!Array.isArray(i)||i.length<=0){console.warn("No objects to fit camera to...");return}const n=this._cameraObject,o=this._controls;if(!n||!o){console.warn("No camera or controls found to fit camera to objects...");return}t||(t={});const{immediate:r=!1,centerCamera:a="y",cameraNearFar:l="auto",fitOffset:h=1.1,fov:d=n?.fov}=t,u=new c.Vector3,p=new c.Vector3,m=Ht(i,void 0,this._camera?.threeCamera?.layers),y=m.clone();n.updateMatrixWorld(),n.updateProjectionMatrix(),m.getCenter(p);const b=new c.Vector3;if(m.getSize(b),m.applyMatrix4(n.matrixWorldInverse),m.getSize(u),m.setFromCenterAndSize(p,u),Number.isNaN(u.x)||Number.isNaN(u.y)||Number.isNaN(u.z)){console.warn("Camera fit size resultet in NaN",n,m,[...i]);return}if(u.length()<=1e-10){za&&console.warn("Camera fit size is zero",m,[...i]);return}const g=t.fov||n.fov,v=2*Math.atan(Math.tan(g*Math.PI/360/2)*n.aspect)/Math.PI*360,_=u.y/(2*Math.atan(Math.PI*g/360)),S=u.x/(2*Math.atan(Math.PI*v/360)),T=h*Math.max(_,S)+u.z/2;za&&console.log("Fit camera to objects",{fitHeightDistance:_,fitWidthDistance:S,distance:T,verticalFov:g,horizontalFov:v}),this.maxZoom=T*10,this.minZoom=T*.01;const M=.05,O=p.clone();if(O.y-=u.y*M,this.setLookTargetPosition(O,r),this.setFieldOfView(t.fov,r),l==null||l=="auto"){const $=x.findObjectOfType(Dn),E=$?$.radius:0,F=Math.max(b.x,b.y,b.z,E);n.near=T/100,n.far=F+T*10,$&&(this.maxZoom=Math.max(Math.min(this.maxZoom,E*.5),T))}const R=o.getDistance();R<this.minZoom&&(this.minZoom=R*.9),R>this.maxZoom&&(this.maxZoom=R*1.1),n.updateMatrixWorld(),n.updateProjectionMatrix();const B=X(n),L=p.clone();L.sub(B),a==="y"&&(L.y=0),L.normalize(),L.multiplyScalar(T),a==="y"&&(L.y+=-M*4*T);let N=p.clone().sub(L);n.parent&&(N=n.parent.worldToLocal(N)),this.setCameraTargetPosition(N,r),(za||t.debug)&&(j.DrawWireBox3(m,16777011,10),j.DrawWireBox3(y,65280,10),!this._haveAttachedKeyboardEvents&&za&&(this._haveAttachedKeyboardEvents=!0,document.body.addEventListener("keydown",$=>{if($.code==="KeyF"){let E;this._cameraObject instanceof c.PerspectiveCamera&&(E=Math.random()*Math.random()*170+10),this.fitCamera({objects:i,fitOffset:h,immediate:!1,fov:E})}$.code==="KeyV"&&this._cameraObject instanceof c.PerspectiveCamera&&(this._cameraObject.fov=60)}))),this.onBeforeRender()}_haveAttachedKeyboardEvents=!1}Ce([f()],he.prototype,"autoTarget");Ce([f()],he.prototype,"autoFit");Ce([f()],he.prototype,"enableRotate");Ce([f()],he.prototype,"autoRotate");Ce([f()],he.prototype,"autoRotateSpeed");Ce([f()],he.prototype,"minAzimuthAngle");Ce([f()],he.prototype,"maxAzimuthAngle");Ce([f()],he.prototype,"minPolarAngle");Ce([f()],he.prototype,"maxPolarAngle");Ce([f()],he.prototype,"enableKeys");Ce([f()],he.prototype,"enableDamping");Ce([f()],he.prototype,"dampingFactor");Ce([f()],he.prototype,"enableZoom");Ce([f()],he.prototype,"minZoom");Ce([f()],he.prototype,"maxZoom");Ce([f()],he.prototype,"zoomSpeed");Ce([f()],he.prototype,"enablePan");Ce([f(ir)],he.prototype,"lookAtConstraint");Ce([f()],he.prototype,"lookAtConstraint01");Ce([f()],he.prototype,"allowInterrupt");Ce([f()],he.prototype,"middleClickToFocus");Ce([f()],he.prototype,"doubleClickToFocus");Ce([f()],he.prototype,"clickBackgroundToFitScene");Ce([f()],he.prototype,"targetLerpDuration");var I1=Object.defineProperty,j1=Object.getOwnPropertyDescriptor,Ft=(s,e,t,i)=>{for(var n=i>1?void 0:i?j1(e,t):e,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&I1(e,t,n),n},Bo=(s=>(s[s.None=0]="None",s[s.Skybox=1]="Skybox",s[s.SolidColor=2]="SolidColor",s[s.Uninitialized=4]="Uninitialized",s))(Bo||{});const Ls=w("debugcam"),Yy=w("debugscreenpointtoray"),St=class ll extends k{get isCamera(){return!0}get aspect(){return this._cam instanceof c.PerspectiveCamera?this._cam.aspect:this.context.domWidth/this.context.domHeight}set aspect(e){this._cam instanceof c.PerspectiveCamera&&this._cam.aspect!==e&&(this._cam.aspect=e,this._cam.updateProjectionMatrix())}get fieldOfView(){return this._cam instanceof c.PerspectiveCamera?this._cam.fov:this._fov}set fieldOfView(e){const t=this.fieldOfView!=e;if(this._fov=e,t&&this._cam&&this._cam instanceof c.PerspectiveCamera){if(this._fov===void 0){console.warn("Can not set undefined fov on PerspectiveCamera");return}this._cam.fov=this._fov,this._cam.updateProjectionMatrix()}}get nearClipPlane(){return this._nearClipPlane}set nearClipPlane(e){const t=this._nearClipPlane!=e;this._nearClipPlane=e,this._cam&&(t||this._cam.near!=e)&&(this._cam.near=e,this._cam.updateProjectionMatrix())}_nearClipPlane=.1;get farClipPlane(){return this._farClipPlane}set farClipPlane(e){const t=this._farClipPlane!=e;this._farClipPlane=e,this._cam&&(t||this._cam.far!=e)&&(this._cam.far=e,this._cam.updateProjectionMatrix())}_farClipPlane=1e3;applyClippingPlane(){this._cam&&(this._cam.near=this._nearClipPlane,this._cam.far=this._farClipPlane,this._cam.updateProjectionMatrix())}get clearFlags(){return this._clearFlags}set clearFlags(e){if(typeof e=="string")switch(e){case"skybox":e=1;break;case"solidcolor":e=2;break;default:e=0;break}e!==this._clearFlags&&(this._clearFlags=e,this.applyClearFlagsIfIsActiveCamera())}orthographic=!1;orthographicSize=5;ARBackgroundAlpha=0;set cullingMask(e){this._cullingMask=e,this._cam&&(this._cam.layers.mask=e)}get cullingMask(){return this._cam?this._cam.layers.mask:this._cullingMask}_cullingMask=4294967295;set cullingLayer(e){this.cullingMask=(1<<e|0)>>>0}set backgroundBlurriness(e){e!==this._backgroundBlurriness&&(e===void 0?this._backgroundBlurriness=void 0:this._backgroundBlurriness=Math.min(Math.max(e,0),1),this.applyClearFlagsIfIsActiveCamera())}get backgroundBlurriness(){return this._backgroundBlurriness}_backgroundBlurriness=void 0;set backgroundIntensity(e){e!==this._backgroundIntensity&&(e===void 0?this._backgroundIntensity=void 0:this._backgroundIntensity=Math.min(Math.max(e,0),10),this.applyClearFlagsIfIsActiveCamera())}get backgroundIntensity(){return this._backgroundIntensity}_backgroundIntensity=void 0;set backgroundRotation(e){e!==this._backgroundRotation&&(e===void 0?this._backgroundRotation=void 0:this._backgroundRotation=e,this.applyClearFlagsIfIsActiveCamera())}get backgroundRotation(){return this._backgroundRotation}_backgroundRotation=void 0;set environmentIntensity(e){this._environmentIntensity=e}get environmentIntensity(){return this._environmentIntensity}_environmentIntensity=void 0;get backgroundColor(){return this._backgroundColor??null}set backgroundColor(e){e&&(this._backgroundColor||(this._backgroundColor=new Z(1,1,1,1)),this._backgroundColor.copy(e),(!("alpha"in e)||e.alpha===void 0)&&(this._backgroundColor.alpha=1),this.applyClearFlagsIfIsActiveCamera())}set targetTexture(e){this._targetTexture=e}get targetTexture(){return this._targetTexture}_targetTexture=null;_backgroundColor;_fov;_cam=null;_clearFlags=2;_skybox;get cam(){return this.threeCamera}get threeCamera(){return this.activeAndEnabled&&this.buildCamera(),this._cam}static _origin=new c.Vector3;static _direction=new c.Vector3;screenPointToRay(e,t,i){const n=this.threeCamera,o=ll._origin;o.set(e,t,-1),this.context.input.convertScreenspaceToRaycastSpace(o),Yy&&console.log("screenPointToRay",e.toFixed(2),t.toFixed(2),"now:",o.x.toFixed(2),o.y.toFixed(2),"isInXR:"+this.context.isInXR),o.z=-1,o.unproject(n);const r=ll._direction.set(o.x,o.y,o.z),a=X(n);return r.sub(a),r.normalize(),i?(i.set(a,r),i):new c.Ray(a.clone(),r.clone())}_frustum;getFrustum(){return this._frustum||(this._frustum=new c.Frustum,this.updateFrustum()),this._frustum}updateFrustum(){this._frustum||(this._frustum=new c.Frustum),this._frustum.setFromProjectionMatrix(this.getProjectionScreenMatrix(this._projScreenMatrix,!0),this.context.renderer.coordinateSystem)}getProjectionScreenMatrix(e,t){return t&&this._projScreenMatrix.multiplyMatrices(this.threeCamera.projectionMatrix,this.threeCamera.matrixWorldInverse),e===this._projScreenMatrix?e:e.copy(this._projScreenMatrix)}_projScreenMatrix=new c.Matrix4;awake(){Yy&&window.addEventListener("pointerdown",e=>{const t=e.clientX,i=e.clientY;console.log("touch",t.toFixed(2),i.toFixed(2));const n=this.screenPointToRay(t,i),o="#"+Math.floor(Math.random()*16777215).toString(16);j.DrawRay(n.origin,n.direction,o,10)})}onEnable(){Ls&&console.log(`Camera enabled: "${this.name}". ClearFlags=${Bo[this._clearFlags]}`,this),this.buildCamera(),(this.tag=="MainCamera"||!this.context.mainCameraComponent)&&(this.context.setCurrentCamera(this),F1(this)),this.applyClearFlagsIfIsActiveCamera({applySkybox:!0})}onDisable(){this.context.removeCamera(this)}onBeforeRender(){if(this._cam&&(this._frustum&&this.updateFrustum(),this._clearFlags===2&&this.applyClearFlagsIfIsActiveCamera(),this._targetTexture)){this.context.isManagedExternally&&(this._warnedAboutExternalRenderer||(this._warnedAboutExternalRenderer=!0,console.warn("Rendering with external renderer is not supported yet. This may not work or throw errors. Please remove the the target texture from your camera: "+this.name,this.targetTexture))),this.context.composer;const e=this.context.renderer;if(e){const t=this.context.mainCameraComponent;this.applyClearFlags(),this._targetTexture.render(this.context.scene,this._cam,e),t?.applyClearFlags()}}}buildCamera(){if(this._cam)return;const e=this.gameObject.isCamera;let t=null;if(e?(t=this.gameObject,t?.layers.enableAll(),t instanceof c.PerspectiveCamera&&(this._fov=t.fov)):t=this.gameObject.children[0],t&&t.isCamera)t instanceof c.PerspectiveCamera&&(this._fov&&(t.fov=this._fov),t.near=this._nearClipPlane,t.far=this._farClipPlane,t.updateProjectionMatrix());else if(!this.orthographic)t=new c.PerspectiveCamera(this.fieldOfView,window.innerWidth/window.innerHeight,this._nearClipPlane,this._farClipPlane),this.fieldOfView&&(t.fov=this.fieldOfView),this.gameObject.add(t);else{const i=this.orthographicSize*100;t=new c.OrthographicCamera(window.innerWidth/-i,window.innerWidth/i,window.innerHeight/i,window.innerHeight/-i,this._nearClipPlane,this._farClipPlane),this.gameObject.add(t)}this._cam=t,this._cam.layers.mask=this._cullingMask,this.tag=="MainCamera"&&this.context.setCurrentCamera(this)}applyClearFlagsIfIsActiveCamera(e){this.context.mainCameraComponent===this&&this.applyClearFlags(e)}applyClearFlags(e){if(!this._cam){Ls&&console.log("Camera does not exist (apply clear flags)");return}if(this.fieldOfView=this._fov,Ls){const i=`[Camera] Apply ClearFlags: ${Bo[this._clearFlags]} - "${this.name}"`;console.debug(i)}const t=this.context.domElement.getAttribute("background-image")||this.context.domElement.getAttribute("background-color");switch(this._clearFlags){case 0:return;case 1:if(ll.backgroundShouldBeTransparent(this.context)&&(!this.ARBackgroundAlpha||this.ARBackgroundAlpha<.001)){this.context.scene.background=null,this.context.renderer.setClearColor(0,0);return}(!this.scene.background||!this._skybox||e?.applySkybox===!0)&&this.applySceneSkybox(),this._backgroundBlurriness!==void 0&&!this.context.domElement.getAttribute("background-blurriness")?this.context.scene.backgroundBlurriness=this._backgroundBlurriness:Ls&&console.warn(`Camera "${this.name}" has no background blurriness`),this._backgroundIntensity!==void 0&&!this.context.domElement.getAttribute("background-intensity")&&(this.context.scene.backgroundIntensity=this._backgroundIntensity),this._backgroundRotation!==void 0&&!this.context.domElement.getAttribute("background-rotation")?this.context.scene.backgroundRotation=this._backgroundRotation:Ls&&console.warn(`Camera "${this.name}" has no background intensity`);break;case 2:if(this._backgroundColor&&!t){let i=this._backgroundColor.alpha;ll.backgroundShouldBeTransparent(this.context)&&(i=this.ARBackgroundAlpha??0),this.context.scene.background=null,this.context.xr?.isVR?this.context.renderer.setClearColor(cb(this._backgroundColor).convertLinearToSRGB()):this.context.renderer.setClearColor(this._backgroundColor,i)}else this._backgroundColor||Ls&&console.warn(`[Camera] has no background color "${this.name}" `);break;case 4:t||(this.context.scene.background=null,this.context.renderer.setClearColor(0,0));break}}applySceneSkybox(){this._skybox||(this._skybox=new B1(this)),this._skybox.apply()}static backgroundShouldBeTransparent(e){const t=e.renderer.xr?.getSession();if(!t)return!1;if(typeof t._transparent=="boolean")return t._transparent;const i=t.environmentBlendMode;Ls&&Se("Environment blend mode: "+i+" on "+navigator.userAgent);let n=i==="additive"||i==="alpha-blend";return e.isInAR&&i==="opaque"&&(navigator.userAgent?.includes("OculusBrowser")||navigator.userAgent?.includes("Mozilla")&&navigator.userAgent?.includes("Mobile WebXRViewer/v2"))&&(n=!0),t._transparent=n,n}};Ft([f()],St.prototype,"aspect",1);Ft([f()],St.prototype,"fieldOfView",1);Ft([f()],St.prototype,"nearClipPlane",1);Ft([f()],St.prototype,"farClipPlane",1);Ft([f()],St.prototype,"clearFlags",1);Ft([f()],St.prototype,"orthographic",2);Ft([f()],St.prototype,"orthographicSize",2);Ft([f()],St.prototype,"ARBackgroundAlpha",2);Ft([f()],St.prototype,"cullingMask",1);Ft([f()],St.prototype,"backgroundBlurriness",1);Ft([f()],St.prototype,"backgroundIntensity",1);Ft([f(c.Euler)],St.prototype,"backgroundRotation",1);Ft([f()],St.prototype,"environmentIntensity",1);Ft([f(Z)],St.prototype,"backgroundColor",1);Ft([f(xn)],St.prototype,"targetTexture",1);let Wt=St;class B1{_camera;_skybox;get context(){return this._camera?.context}constructor(e){this._camera=e}apply(){if(this._skybox=this.context.lightmaps.tryGetSkybox(this._camera.sourceId),!this._skybox)this._did_log_failed_to_find_skybox||(this._did_log_failed_to_find_skybox=!0,console.warn(`Camera "${this._camera.name}" has no skybox texture. ${this._camera.sourceId}`));else if(this.context.scene.background!==this._skybox){const e=this.context.domElement.getAttribute("background-image")||this.context.domElement.getAttribute("background-color")||this.context.domElement.getAttribute("skybox-image");Ls&&console.debug(`[Camera] Apply Skybox ${this._skybox?.name} ${e} - "${this._camera.name}"`),e?.length||(this._skybox.mapping=c.EquirectangularReflectionMapping,this.context.scene.background=this._skybox)}}}function F1(s){w("freecam")&&s.context.mainCameraComponent===s&&x.getOrAddComponent(s.gameObject,he)}class is extends k{get listener(){return this._listener==null&&(this._listener=new c.AudioListener),this._listener}_listener=null;onEnable(){tn.registerWaitForInteraction(this.onInteraction),this.addListenerIfItExists()}onDisable(){tn.unregisterWaitForInteraction(this.onInteraction),this.removeListenerIfItExists()}onInteraction=()=>{this.destroyed||this.listener==null||this.addListenerIfItExists()};addListenerIfItExists(){const e=this._listener;if(!e||e?.parent)return;const t=this.context.mainCameraComponent||x.getComponentInParent(this.gameObject,Wt);t?.threeCamera?t.threeCamera.add(e):this.gameObject.add(e),e.filter?(e.gain.connect(e.filter),e.filter.connect(e.context.destination)):e.gain.connect(e.context.destination)}removeListenerIfItExists(){const e=this._listener;e&&(e.removeFromParent(),e.filter&&e.filter.disconnect(),e.gain&&e.gain.disconnect())}}var U1=Object.defineProperty,z1=Object.getOwnPropertyDescriptor,on=(s,e,t,i)=>{for(var n=i>1?void 0:i?z1(e,t):e,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&U1(e,t,n),n};const lt=w("debugaudio"),zi=class Ds extends k{static get userInteractionRegistered(){return tn.userInteractionRegistered}static registerWaitForAllowAudio(e){tn.registerWaitForInteraction(e)}clip="";playOnAwake=!1;preload=!0;playInBackground=!0;get isPlaying(){return this.sound?.isPlaying??!1}get duration(){return this.sound?.buffer?.duration}get time01(){const e=this.duration;return e&&this.sound?this.sound?.context.currentTime/e:0}set time01(e){const t=this.duration;t&&this.sound&&(this.time=e*t)}get time(){return this.sound?.source?this.sound.source?.context.currentTime-this._lastContextTime+this.sound.offset:0}set time(e){if(this.sound){if(e===this.sound.offset)return;const t=this.isPlaying;this.stop(),this.sound.offset=e,t&&this.play()}}get loop(){return this.sound&&(this._loop=this.sound.getLoop()),this._loop}set loop(e){this._loop=e,this.sound&&this.sound.setLoop(e)}get spatialBlend(){return this._spatialBlend}set spatialBlend(e){e!==this._spatialBlend&&(this._spatialBlend=e,this._needUpdateSpatialDistanceSettings=!0)}get minDistance(){return this._minDistance}set minDistance(e){this._minDistance!==e&&(this._minDistance=e,this._needUpdateSpatialDistanceSettings=!0)}get maxDistance(){return this._maxDistance}set maxDistance(e){this._maxDistance!==e&&(this._maxDistance=e,this._needUpdateSpatialDistanceSettings=!0)}_spatialBlend=0;_minDistance=1;_maxDistance=100;get volume(){return this._volume}set volume(e){this._volume=e,this.sound&&!this.context.application.muted&&(lt&&console.log(this.name,"audio set volume",e),this.sound.setVolume(e))}_volume=1;set pitch(e){this.sound&&this.sound.setPlaybackRate(e)}get pitch(){return this.sound?this.sound.getPlaybackRate():1}rollOffMode=0;_loop=!1;sound=null;helper=null;wasPlaying=!1;audioLoader=null;shouldPlay=!1;_lastClipStartedLoading=null;_audioElement=null;get Sound(){if(!this.sound&&Ds.userInteractionRegistered){let e=this.gameObject.getComponent(is)??this.context.mainCamera.getComponent(is)??cc(is,this.context,!1);!e&&this.context.mainCamera&&(e=this.context.mainCamera.addComponent(is)),e?.listener?(this.sound=new c.PositionalAudio(e.listener),this.gameObject?.add(this.sound)):lt&&console.warn("No audio listener found in scene - can not play audio")}return this.sound}get ShouldPlay(){return this.shouldPlay}get audioContext(){return this.sound?.context}awake(){lt&&console.log("[AudioSource]",this),this.audioLoader=new c.AudioLoader,this.playOnAwake&&(this.shouldPlay=!0),this.preload&&typeof this.clip=="string"&&this.audioLoader.load(this.clip,this.createAudio,()=>{},console.error)}onEnable(){this.sound&&this.gameObject.add(this.sound),Ds.userInteractionRegistered?this.playOnAwake&&this.context.application.isVisible&&this.play():Ds.registerWaitForAllowAudio(()=>{this.enabled&&!this.destroyed&&this.shouldPlay&&this.onNewClip(this.clip)}),globalThis.addEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.addEventListener(Xf.MuteChanged,this.onApplicationMuteChanged)}onDisable(){globalThis.removeEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.removeEventListener(Xf.MuteChanged,this.onApplicationMuteChanged),this.pause()}onVisibilityChanged=()=>{switch(document.visibilityState){case"hidden":(this.playInBackground===!1||exports.DeviceUtilities.isMobileDevice())&&(this.wasPlaying=this.isPlaying,this.isPlaying&&this.pause());break;case"visible":lt&&console.log("visible",this.enabled,this.playOnAwake,!this.isPlaying,Ds.userInteractionRegistered,this.wasPlaying),this.enabled&&this.playOnAwake&&!this.isPlaying&&Ds.userInteractionRegistered&&this.wasPlaying&&this.play();break}};onApplicationMuteChanged=()=>{this.context.application.muted?this.sound?.setVolume(0):this.sound?.setVolume(this.volume)};createAudio=e=>{if(this.destroyed){lt&&console.warn("AudioSource destroyed, not creating audio",this.name);return}lt&&console.log("AudioBuffer finished loading",e);const t=this.Sound;if(!t){lt&&console.warn("Failed getting sound?",this.name);return}t.isPlaying&&t.stop(),e&&t.setBuffer(e),t.loop=this._loop,this.context.application.muted?t.setVolume(0):t.setVolume(this.volume),t.autoplay=this.shouldPlay&&Ds.userInteractionRegistered,this.applySpatialDistanceSettings(),t.isPlaying&&t.stop(),Ds.registerWaitForAllowAudio(this.__onAllowAudioCallback)};__onAllowAudioCallback=()=>{this.shouldPlay&&this.play()};applySpatialDistanceSettings(){const e=this.sound;if(!e)return;this._needUpdateSpatialDistanceSettings=!1;const t=I.lerp(10*this._maxDistance/Math.max(1e-4,this.spatialBlend),this._minDistance,this.spatialBlend);switch(lt&&console.log(this.name,this._minDistance,this._maxDistance,this.spatialBlend,"Ref distance="+t),e.setRefDistance(t),e.setMaxDistance(Math.max(.01,this._maxDistance)),this.rollOffMode){case 0:e.setDistanceModel("exponential");break;case 1:e.setDistanceModel("linear");break;case 2:console.warn("Custom rolloff for AudioSource is not supported: "+this.name);break}this.spatialBlend>0?lt&&!this.helper&&(this.helper=new G.PositionalAudioHelper(e,e.getRefDistance()),e.add(this.helper)):this.helper&&this.helper.parent&&this.helper.removeFromParent()}async onNewClip(e){if(e&&(this.clip=e),typeof e=="string")if(lt&&console.log(e),e.endsWith(".mp3")||e.endsWith(".wav")){if(this.audioLoader||(this.audioLoader=new c.AudioLoader),this.shouldPlay=!0,this._lastClipStartedLoading===e){lt&&console.log("Is currently loading:",this._lastClipStartedLoading,this);return}this._lastClipStartedLoading=e,lt&&console.log("load audio",e);const t=await this.audioLoader.loadAsync(e).catch(console.error);if(this.destroyed)return;this._lastClipStartedLoading===e&&(this._lastClipStartedLoading=null),t&&this.createAudio(t)}else console.warn("Unsupported audio clip type",e);else this.shouldPlay=!0,this.createAudio()}play(e=void 0){!e&&this.clip&&(e=this.clip),e!==void 0&&typeof e!="string"&&!(e instanceof MediaStream)&&(A()&&console.warn("Called play on AudioSource with unknown argument type:",e+`
941
- Using the assigned clip instead:`,this.clip),e=this.clip);let t=!this.sound||e&&e!==this.clip;if(typeof e=="string"&&!this.audioLoader&&(t=!0),(e instanceof MediaStream||typeof e=="string")&&(this.clip=e),t){this.shouldPlay=!0,this.onNewClip(e);return}if(this.shouldPlay=!0,this._hasEnded=!1,lt&&console.log("play",this.sound?.getVolume(),this.sound),this.sound&&!this.sound.isPlaying){const i=this.context.application.muted;i&&this.sound.setVolume(0),this.gameObject?.add(this.sound),this.clip instanceof MediaStream?(this.sound.setMediaStreamSource(this.clip),this._audioElement||(this._audioElement=document.createElement("audio"),this._audioElement.style.display="none"),this._audioElement.parentNode||this.context.domElement.shadowRoot?.append(this._audioElement),this._audioElement.srcObject=this.clip,this._audioElement.autoplay=!1):(this._audioElement&&this._audioElement.remove(),this.sound.play(i?.1:0))}}pause(){lt&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.isPlaying&&this.sound.source&&(this._lastContextTime=this.sound?.context.currentTime,this.sound.pause()),this._audioElement?.remove()}stop(){lt&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.source&&(this._lastContextTime=this.sound?.context.currentTime,lt&&console.log(this._lastContextTime),this.sound.stop()),this._audioElement?.remove()}_lastContextTime=0;_hasEnded=!0;_needUpdateSpatialDistanceSettings=!1;update(){this.helper&&(this.isPlaying&&this.helper.update(),this.helper.visible=this.isPlaying),this._needUpdateSpatialDistanceSettings&&this.applySpatialDistanceSettings(),this.sound&&!this.sound.isPlaying&&this.shouldPlay&&!this._hasEnded&&(this._hasEnded=!0,lt&&console.log("Audio clip ended",this.clip),this.dispatchEvent(new CustomEvent("ended",{detail:this})))}};on([f(URL)],zi.prototype,"clip",2);on([f()],zi.prototype,"playOnAwake",2);on([f()],zi.prototype,"preload",2);on([f()],zi.prototype,"playInBackground",2);on([f()],zi.prototype,"loop",1);on([f()],zi.prototype,"spatialBlend",1);on([f()],zi.prototype,"minDistance",1);on([f()],zi.prototype,"maxDistance",1);on([f()],zi.prototype,"volume",1);on([f()],zi.prototype,"pitch",1);on([f()],zi.prototype,"rollOffMode",2);let Ii=zi;const N1=w("debugavatar");class xe extends k{static getAvatar(e){return e>=0&&e<xe.instances.length?xe.instances[e]:null}static instances=[];static onAvatarMarkerCreated(e){return xe._onNewAvatarMarkerAdded.push(e),e}static onAvatarMarkerDestroyed(e){return xe._onAvatarMarkerDestroyed.push(e),e}static _onNewAvatarMarkerAdded=[];static _onAvatarMarkerDestroyed=[];connectionId;avatar;awake(){xe.instances.push(this),N1&&console.log(this);for(const e of xe._onNewAvatarMarkerAdded)e({avatarMarker:this,gameObject:this.gameObject})}onDestroy(){xe.instances.splice(xe.instances.indexOf(this),1);for(const e of xe._onAvatarMarkerDestroyed)e({avatarMarker:this,gameObject:this.gameObject})}isLocalAvatar(){return this.connectionId===this.context.connection.connectionId}}class Fo{static Pois=[];static LastChangeTime=0;static Add(e,t,i=null){if(t){for(const n of this.Pois)if(n.obj===t)return;this.Pois.push({obj:t,avatar:i}),this.LastChangeTime=e.time.time}}static Remove(e,t){if(t){for(const i of this.Pois)if(i.obj===t){this.Pois.splice(this.Pois.indexOf(i),1),this.LastChangeTime=e?.time.time??U.Current?.time.time;return}}}}class V1{guid;position=new c.Vector3}class $l extends k{set controlledTarget(e){this.target=e;const t=P.get("MoveRandom");if(t&&this.target){const i=x.getComponent(this.target,t);i&&i.destroy()}}target=null;avatar=null;_model=null;_targetModel=new V1;_currentTargetObject=null;_lastUpdateTime=0;_lookDuration=0;_lastPoiChangedTime=0;awake(){if(this.avatar=x.getComponentInParent(this.gameObject,xe),this.avatar){const e=x.getComponentInParent(this.gameObject,xe);this._model=new tm(this.context.connection,this.guid),e?.isLocalAvatar&&this._model.requestOwnership()}this.context.connection.beginListen("avatar-look-target-changed",e=>{this.target&&e&&e.guid===this.avatar?.guid&&Ye(this.target,e.position)})}update(){if((!this.context.connection.isConnected||this._model?.hasOwnership)&&(Fo.LastChangeTime!==this._lastPoiChangedTime&&(this._lastPoiChangedTime=Fo.LastChangeTime,this._lookDuration=0),this.selectTarget(),this._currentTargetObject&&this.context.time.frameCount%10===0&&this.target)){const t=X(this._currentTargetObject);Ye(this.target,t),this.context.connection.isConnected&&this.avatar&&(this.context.connection.send("avatar-look-target-changed",this._targetModel),this._targetModel.guid=this.avatar.guid,this._targetModel.position.copy(t))}}selectTarget(){if(this.context.time.time-this._lastUpdateTime>this._lookDuration){this._lastUpdateTime=this.context.time.time,this._lookDuration=Math.random()*.5+.2;const t=Fo.Pois;if(t.length>0){const i=t[Math.floor(Math.random()*t.length)];if(i&&i.obj){if(i.avatar&&i.avatar===this.avatar)return;this._currentTargetObject=i.obj}}}}}function Z0(s){const e=s;return!!(e.parser&&e.parser.json)}var Gd=(s=>(s[s.None=0]="None",s[s.DontExport=1]="DontExport",s))(Gd||{});function J0(s){return s&&s.isComponent}const $1=Symbol("object"),nf=new hi(()=>new c.Vector3,20);class ev{_point;_normal;_tangentVelocity;distance;impulse;friction;get point(){return nf.get().set(this._point.x,this._point.y,this._point.z)}get normal(){return nf.get().set(this._normal.x,this._normal.y,this._normal.z)}get tangentVelocity(){return nf.get().set(this._tangentVelocity.x,this._tangentVelocity.y,this._tangentVelocity.z)}constructor(e,t,i,n,o,r){this._point=e,this.distance=t,this._normal=i,this.impulse=n,this.friction=o,this._tangentVelocity=r}}class tv{contacts;constructor(e,t,i){this.me=e,this._collider=t,this._gameObject=t.gameObject,this.contacts=i}me;_collider;get collider(){return this._collider}_gameObject;get gameObject(){return this._gameObject}get rigidBody(){return this.collider?.attachedRigidbody}}class iv{object;collider;constructor(e,t){this.object=e,this.collider=t}}const Te=w("debugnetworkingstreams");var Sn=(s=>(s.Connected="peer-user-connected",s.StreamReceived="receive-stream",s.StreamEnded="call-ended",s.Disconnected="peer-user-disconnected",s.UserJoined="user-joined",s))(Sn||{});class Sm{type="call-ended";userId;direction;constructor(e,t){this.userId=e,this.direction=t}}class nv{type="receive-stream";userId;stream;target;constructor(e,t,i){this.userId=e,this.stream=t,this.target=i}}class W1{guid;peerId;dontSave=!0;constructor(e,t){this.guid=e.id,this.peerId=t}}var sv=(s=>(s.Incoming="incoming",s.Outgoing="outgoing",s))(sv||{});class G1 extends c.EventDispatcher{peerId;userId;direction;call;get stream(){return this._stream}_stream=null;_isDisposed=!1;close(){this._isDisposed||(this._isDisposed=!0,this.call.close(),Cn(this._stream))}get isOpen(){return this.call.peerConnection?.connectionState==="connected"}get isOpening(){return this.call.peerConnection?.connectionState==="connecting"}get isClosed(){return!this.isOpen||this._isDisposed}constructor(e,t,i,n=null){super(),this.peerId=t.peer,this.userId=e,this.call=t,this.direction=i,this._stream=n,t.on("stream",o=>{if(Te&&console.log("Receive stream",`
950
+ Could not find method ${r.method} on object ${l.name}`,l,typeof l[r.method])};if(typeof l[r.method]!="function"){let p=!1,m=l;for(;m;){const y=Object.getOwnPropertyDescriptor(m,r.method);if(y&&(y.writable===!0||y.set)){p=!0;break}m=Object.getPrototypeOf(m)}!p&&(A()||st)&&d()}}if(l){let d=r.argument;if(d!==void 0?d=a(d):r.arguments!==void 0&&(d=r.arguments.map(a)),!l[r.method])console.warn(`EventList method not found: "${r.method}" on ${l?.name}`);else{d!==void 0&&!Array.isArray(d)&&(d=[d]);const p=new ts(l,r.method,d,r.enabled);i.push(p)}}else A()&&console.warn(`[Dev] EventList: Could not find event listener in scene (${t.object?.name})`,r)}const n=new de(i);st&&console.log(n);const o=t.target;return o!==void 0&&t.path!==void 0&&n.setEventTarget(t.path,o),n}}}const O1=new M1,dd=new WeakMap,k1=c.Texture.prototype.clone;c.Texture.prototype.clone=function(){const s=k1.call(this);return dd.has(s)||dd.set(s,this),s};class Y0 extends Ui{constructor(){super([xn,c.WebGLRenderTarget])}onSerialize(e,t){}onDeserialize(e,t){if(e instanceof c.Texture&&t.type===xn){let i=e;dd.has(i)&&(i=dd.get(i)),i.isRenderTargetTexture=!0,i.flipY=!0,i.offset.y=1,i.repeat.y=-1,i.needsUpdate=!0,i.mipmaps=[],i instanceof c.CompressedTexture&&(i.isCompressedTexture=!1,i.format=c.RGBAFormat);const n=new xn(i.image.width,i.image.height,{colorSpace:c.LinearSRGBColorSpace});return n.texture=i,n}}}new Y0;class K0 extends Ui{constructor(){super([URL])}onSerialize(e,t){return null}onDeserialize(e,t){if(typeof e=="string"&&e.length>0)return Ks(t.gltfId,e)}}new K0;var R1=Object.defineProperty,E1=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&R1(e,t,n),n};class aa extends k{awake(){jt.createIfNoneExists(this.context)}onEnable(){jt.get(this.context)?.register(this)}onDisable(){jt.get(this.context)?.unregister(this)}}class ui extends aa{targets=null;raycastHits=[];ignoreSkinnedMeshes=!1;start(){this.targets=[this.gameObject]}performRaycast(e=null){if(!this.targets)return null;e??=new eo,e.targets=this.targets,e.results=this.raycastHits,e.useAcceleratedRaycast=!0;const t=e.testObject;this.ignoreSkinnedMeshes&&(e.testObject=n=>n instanceof c.SkinnedMesh?"continue in children":t?t(n):!0);const i=this.context.physics.raycast(e);return e.testObject=t,i}}E1([f()],ui.prototype,"ignoreSkinnedMeshes");class Wd extends ui{constructor(){super(),this.ignoreSkinnedMeshes=!0}}class Go extends aa{static allow=!0;performRaycast(e){if(!q.active||!Go.allow||!e?.ray)return null;const t=e.ray.origin;return this.context.physics.sphereOverlap(t,.015,!1,!0)}}class wm{static getObject(e){const t=e[si];return t&&(t.isComponent===!0?e=t.gameObject:e=t),e}static isInteractable(e,t){if(t&&(t.canvasGroup=void 0,t.graphic=void 0),e==null||!e.visible||(e=this.getObject(e),!e.visible))return!1;const i=this.tryFindCanvasGroup(e);if(i?.isCanvasGroup===!0&&(t&&(t.canvasGroup=i),i.blocksRaycasts===!1||i.interactable===!1))return!1;const n=$o(e,o=>{if(o.isGraphic===!0)return o},!1);return t&&n?.isGraphic===!0&&(t.graphic=n),!(n?.raycastTarget===!1||n?.layer===2)}static tryFindCanvasGroup(e){if(!e)return null;const t=$o(e,i=>{const n=i;if(n.blocksRaycasts!==void 0&&n.interactable!==void 0)return n},!1);return t!==void 0?t:this.tryFindCanvasGroup(e.parent)}}function xm(s){const e=s[si];return e||(s.parent?xm(s.parent):null)}function T1(s){return s.isUI===!0||typeof s[si]=="object"}function ud(s,e){if(!s)return;const t=s.material;if(t?.isMaterial===!0){const i=s.parent;i&&i.isText,t.side=e.doubleSided??!0?c.DoubleSide:c.FrontSide,t.shadowSide=e.doubleSided?c.DoubleSide:c.FrontSide,s.castShadow=e.castShadows?e.castShadows:!1,s.receiveShadow=e.receiveShadows?e.receiveShadows:!1}for(const i of s.children)ud(i,e)}function Ar(s,e,t){s[e]===void 0&&console.warn("Field",e,"is undefined on",s);const i=Proxy.revocable(s[e],{set(r,a,l,h){const d=r[a],u=Reflect.set(r,a,l,h);return t(l,d),u}}),n=i.revoke,o=s[e];return i.revoke=()=>{s[e]=o,n()},s[e]=i.proxy,i}const Qy=Symbol("Scheduled action");function A1(s,e,t=pe.OnBeforeRender){let i=s[Qy];i||(i=s[Qy]={});const n=e.name;i[t]||(i[t]={});const o=i[t];if(o[n])return;function*a(){e?.call(s),o[n]=null}const l=s.startCoroutine(a(),t);o[n]=l}const As=w("debugeventsystem");var pp=(s=>(s.BeforeHandleInput="BeforeHandleInput",s.AfterHandleInput="AfterHandleInput",s))(pp||{});U0(s=>{jt.createIfNoneExists(s)});class jt extends k{static ensureUpdateMeshUI(e,t,i=!1){Ua.update(e,t,i)}static markUIDirty(e){Ua.markDirty()}static createIfNoneExists(e){e.scene.getComponent(jt)||e.scene.addComponent(jt)}static get(e){return this.createIfNoneExists(e),e.scene.getComponent(jt)}static get instance(){return this.get(U.Current)}raycaster=[];register(e){e&&this.raycaster&&!this.raycaster.includes(e)&&this.raycaster?.push(e)}unregister(e){const t=this.raycaster?.indexOf(e);t!==void 0&&t!==-1&&this.raycaster?.splice(t,1)}get hasActiveUI(){return this.currentActiveMeshUIComponents.length>0}get isHoveringObjects(){return this.hoveredByID.size>0}awake(){this.gameObject!==this.context.scene&&(console.debug(`[Needle Engine] EventSystem is only allowed on the scene root. Disabling EventSystem on '${this.gameObject.name}'`),this.enabled=!1)}start(){this.context.scene.getComponent(aa)||this.context.scene.addComponent(ui)}onEnable(){this.context.input.addEventListener(we.PointerDown,this.onPointerEvent),this.context.input.addEventListener(we.PointerUp,this.onPointerEvent),this.context.input.addEventListener(we.PointerMove,this.onPointerEvent)}onDisable(){this.context.input.removeEventListener(we.PointerDown,this.onPointerEvent),this.context.input.removeEventListener(we.PointerUp,this.onPointerEvent),this.context.input.removeEventListener(we.PointerMove,this.onPointerEvent)}pressedByID=new Map;hoveredByID=new Map;onBeforeRender(){this.resetMeshUIStates()}onPointerEvent=e=>{if(e===void 0||e.propagationStopped||e.defaultPrevented||e.used)return;const t=new pc(this.context.input,e);this._currentPointerEventName=e.type,t.inputSource=this.context.input,t.isClick=e.isClick,t.isDoubleClick=e.isDoubleClick,t.isDown=e.type==we.PointerDown,t.isUp=e.type==we.PointerUp,t.isPressed=this.context.input.getPointerPressed(e.pointerId);const i=new eo;e.hasRay?i.ray=e.ray:i.screenPoint=this.context.input.getPointerPositionRC(e.pointerId),i.allowSlowRaycastFallback=e.isClick||e.isDoubleClick;const n=this.performRaycast(i);if(As&&(t.isDown?console.log("DOWN",{id:t.pointerId,hits:n.length}):t.isUp&&console.log("UP",{id:t.pointerId,hits:n.length}),t.isClick&&console.log("CLICK",{id:t.pointerId,hits:n.length})),n){for(const r of n)r.event=e,e.intersections.push(r);e.origin.onPointerHits&&e.origin.onPointerHits({sender:this,event:e,hits:n})}As&&t.isClick&&Se("EventSystem: "+t.pointerId+" - "+this.context.time.frame+" - Up:"+t.isUp+", Down:"+t.isDown);const o={sender:this,args:t,hasActiveUI:this.currentActiveMeshUIComponents.length>0};this.dispatchEvent(new CustomEvent("BeforeHandleInput",{detail:o})),this.handleIntersections(n,t),this.dispatchEvent(new CustomEvent("AfterHandleInput",{detail:o}))};_sortedHits=[];_testObjectsCache=new Map;_currentlyActiveRaycaster=null;_currentPointerEventName=null;shouldRaycastObject=e=>{const t=e&&"getComponent"in e?e.getComponent(aa):null;if(t&&t!=this._currentlyActiveRaycaster)return!1;let i=null;if(T1(e)&&(i=e[si]?.gameObject),this._testObjectsCache.has(e)||i&&this._testObjectsCache.has(i))return this._testObjectsCache.get(e)===!1?"continue in children":!0;{let o=hd(e,this._currentPointerEventName);if(!o&&i&&(o=hd(i,this._currentPointerEventName)),o){this._testObjectsCache.set(e,!0);for(const r of e.children)this.shouldRaycastObject_AddToYesCache(r);return!0}return this._testObjectsCache.set(e,!1),"continue in children"}};shouldRaycastObject_AddToYesCache(e){this._testObjectsCache.set(e,!0);for(const t of e.children)this.shouldRaycastObject_AddToYesCache(t)}performRaycast(e){if(!this.raycaster)return null;this._testObjectsCache.clear(),this._sortedHits.length=0,e.testObject=this.shouldRaycastObject;for(const t of this.raycaster){if(!t.activeAndEnabled)continue;this._currentlyActiveRaycaster=t;const i=t.performRaycast(e);this._currentlyActiveRaycaster=null,i&&i.length>0&&this._sortedHits.push(...i)}return this._sortedHits.sort((t,i)=>t.distance-i.distance),this._sortedHits}assignHitInformation(e,t){t?(e.intersection=t,e.point=t.point,e.normal=t.normal,e.face=t.face,e.distance=t.distance,e.instanceId=t.instanceId):(e.intersection=void 0,e.point=void 0,e.normal=void 0,e.face=void 0,e.distance=void 0,e.instanceId=void 0)}handleIntersections(e,t){if(e?.length){e=this.sortCandidates(e);for(const n of e){if(t.event.immediatePropagationStopped)return!1;if(this.assignHitInformation(t,n),this.handleEventOnObject(n.object,t))return!0}}this.assignHitInformation(t,e?.[0]),this.invokePointerCapture(t);const i=this.hoveredByID.get(t.pointerId);return i&&this.propagatePointerExit(i.obj,i.data,null),this.hoveredByID.delete(t.pointerId),t.isUp&&(this.pressedByID.get(t.pointerId)?.handlers.forEach(n=>this.invokeOnPointerUp(t,n)),this.pressedByID.delete(t.pointerId)),!1}_sortingBuffer=[];_noDepthTestingResults=[];sortCandidates(e){this._sortingBuffer.length=0,this._noDepthTestingResults.length=0;for(let t=0;t<e.length;t++){const i=e[t],n=i.object;if(n.material&&n.material.depthTest===!1){this._noDepthTestingResults.push(i);continue}this._sortingBuffer.push(i)}for(const t of this._sortingBuffer)this._noDepthTestingResults.push(t);return this._noDepthTestingResults}out={};handleEventOnObject(e,t){if(!this.testIsVisible(e))return t.isClick&&As&&console.log("not allowed",e),!1;if(t.pointerId===void 0)return As&&console.error("Event without pointer can't be handled",t),!1;t.object=e;const i=e.parent,n=t.isClick??!1;let o=null;if(i&&i.isUI){const d=(t.isPressed||t.isClick)??!1;if(i[si]){const u=i[si].gameObject;if(u){if(!wm.isInteractable(u,this.out))return!1;o=this.out.canvasGroup??null,this.handleMeshUIIntersection(e,d),e=u}}}n&&As&&console.log(this.context.time.frame,e);const r=this.hoveredByID.get(t.pointerId),a=r?.obj;a!==e&&a&&this.propagatePointerExit(a,r.data,e);const h=this.hoveredByID.get(t.pointerId);if(h?(h.obj=e,h.data=t):this.hoveredByID.set(t.pointerId,{obj:e,data:t}),t.isDown){const d=this.pressedByID.get(t.pointerId);d?(d.obj=e,d.data=t):this.pressedByID.set(t.pointerId,{obj:e,data:t,handlers:new Set})}return(o===null||o.interactable)&&this.handleMainInteraction(e,t,a??null),!0}propagate(e,t){for(;e;)x.foreachComponent(e,i=>{t(i)},!1),e=e.parent}handleMainInteraction(e,t,i){const n=this.pressedByID.get(t.pointerId),o=i!==e;let r=!0;switch(t.event.pointerType){case"mouse":case"touch":const a=this.context.input.getPointerPositionLastFrame(t.pointerId),l=this.context.input.getPointerPosition(t.pointerId);r=a&&!I.approximately(a,l);break}this.propagate(e,a=>{const l=a;l.interactable!==!1&&(!l.activeAndEnabled||!l.enabled||(l.onPointerEnter&&o&&this.handlePointerEnter(l,t),t.isDown&&l.onPointerDown&&(l.onPointerDown(t),n?.handlers.add(l),this.handlePointerCapture(t,l)),l.onPointerMove&&(r&&l.onPointerMove(t),this.handlePointerCapture(t,l)),t.isUp&&(l.onPointerUp&&(this.invokeOnPointerUp(t,l),n?.handlers.delete(l)),l.onPointerExit&&t.event?.pointerType===Td.Touch&&(this.handlePointerExit(l,t),this.hoveredByID.delete(t.pointerId))),t.isClick&&l.onPointerClick&&l.onPointerClick(t)))}),t.isUp&&(n?.handlers.forEach(a=>{this.invokeOnPointerUp(t,a)}),this.pressedByID.delete(t.pointerId))}propagatePointerExit(e,t,i){this.propagate(e,n=>{if(!n.gameObject||n.destroyed)return;const o=n;if(o.onPointerExit||o.onPointerEnter){if(i&&this.isChild(i,n.gameObject))return;this.handlePointerExit(o,t)}})}invokeOnPointerUp(e,t){t.onPointerUp?.call(t,e),this.releasePointerCapture(e,t)}handlePointerEnter(e,t){e.onPointerEnter&&this.updatePointerState(e,t.pointerId,this.pointerEnterSymbol,!0)&&e.onPointerEnter(t),this.updatePointerState(e,t.pointerId,this.pointerExitSymbol,!1)}handlePointerExit(e,t){e.onPointerExit&&this.updatePointerState(e,t.pointerId,this.pointerExitSymbol,!0)&&e.onPointerExit(t),this.updatePointerState(e,t.pointerId,this.pointerEnterSymbol,!1)}updatePointerState(e,t,i,n){let o=e[i];if(n)return o&&o.includes(t)?!1:(o=o||[],o.push(t),e[i]=o,!0);{if(!o||!o.includes(t))return!1;const r=o.indexOf(t);return r!==-1&&o.splice(r,1),!0}}_capturedPointer={};handlePointerCapture(e,t){if(e.z__pointer_ctured){e.z__pointer_ctured=!1;const i=e.pointerId;if(t.onPointerMove){const n=this._capturedPointer[i]||[];n.push(t),this._capturedPointer[i]=n}else A()&&!t.z__warned_no_pointermove&&(t.z__warned_no_pointermove=!0,console.warn("PointerCapture was requested but the component doesn't implement onPointerMove. It will not receive any pointer events"))}else e.z__pointer_cture_rleased&&(e.z__pointer_cture_rleased=!1,this.releasePointerCapture(e,t))}releasePointerCapture(e,t){const i=e.pointerId;if(this._capturedPointer[i]){const n=this._capturedPointer[i].indexOf(t);n!==-1&&(this._capturedPointer[i].splice(n,1),As&&console.log("released pointer capture",i,t,this._capturedPointer))}}invokePointerCapture(e){if(e.event.type===we.PointerMove){const t=e.pointerId,i=this._capturedPointer[t];if(i){As&&console.log("Captured",t,i);for(let n=0;n<i.length;n++){const o=i[n];if(o.destroyed){i.splice(n,1),n--;continue}o.onPointerMove?.call(o,e)}}}}pointerEnterSymbol=Symbol("pointerEnter");pointerExitSymbol=Symbol("pointerExit");isChild(e,t){return!e||!t?!1:e===t?!0:e.parent?this.isChild(e.parent,t):!1}handleMeshUiObjectWithoutShadowDom(e,t){return!e||!e.isUI?!0:this.handleMeshUIIntersection(e,t)}currentActiveMeshUIComponents=[];handleMeshUIIntersection(e,t){const i=Ua.updateState(e,t);return i&&this.currentActiveMeshUIComponents.push(i),i!==null}resetMeshUIStates(){if(this.context.input.getPointerPressedCount()>0&&Ua.resetLastSelected(),!(!this.currentActiveMeshUIComponents||this.currentActiveMeshUIComponents.length<=0)){for(let e=0;e<this.currentActiveMeshUIComponents.length;e++){const t=this.currentActiveMeshUIComponents[e];Ua.resetState(t)}this.currentActiveMeshUIComponents.length=0}}testIsVisible(e){return e?x.isActiveSelf(e)?this.testIsVisible(e.parent):!1:!0}}class Ua{static lastSelected=null;static lastUpdateFrame=[];static needsUpdate=!1;static markDirty(){this.needsUpdate=!0}static update(e,t,i=!1){if(i){e.update();return}const n=t.time.frameCount;for(const o of this.lastUpdateFrame)if(o.context===t){if(n===o.frame)return;o.frame=n;let r=this.needsUpdate||n<1;o.nextUpdate<=n&&(r=!0),r&&(As&&console.log("Update threemeshui"),this.needsUpdate=!1,o.nextUpdate=n+60,e.update());return}this.lastUpdateFrame=[{context:t,frame:n,nextUpdate:n+60}],e.update(),this.needsUpdate=!1}static updateState(e,t){let i=null;if(e&&(i=this.findBlockOrTextInParent(e),i&&i!==this.lastSelected)){if(i.interactable===!1)return null;this.needsUpdate=!0}return i}static resetLastSelected(){const e=this.lastSelected;e&&(this.lastSelected=null,this.resetState(e))}static resetState(e){e&&(this.needsUpdate=!0)}static findBlockOrTextInParent(e){return e?e.isBlock||e.isText?e:this.findBlockOrTextInParent(e.parent):null}}var L1=Object.defineProperty,Ce=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&L1(e,t,n),n};const Pi=w("debugorbit"),ef=w("freecam"),za=w("debugcamerafit"),hh=w("smoothcam"),D1={LEFT:"",UP:"",RIGHT:"",BOTTOM:""};let tf;class Vl extends CustomEvent{constructor(e,t){super("target-reached",{detail:{controls:e,type:t}})}}class he extends k{get isCameraController(){return!0}get controls(){return this._controls}get controllerObject(){return this._cameraObject}onStartInteraction(e){this.controls?.addEventListener("start",e)}autoTarget=!0;autoFit=!1;enableRotate=!0;autoRotate=!1;autoRotateSpeed=1;minAzimuthAngle=1/0;maxAzimuthAngle=1/0;minPolarAngle=0;maxPolarAngle=Math.PI;enableKeys=!1;enableDamping=!0;dampingFactor=.1;enableZoom=!0;minZoom=0;maxZoom=1/0;zoomSpeed=1;zoomToCursor=!1;enablePan=!0;lookAtConstraint=null;lookAtConstraint01=1;allowInterrupt=!0;middleClickToFocus=!0;doubleClickToFocus=!0;clickBackgroundToFitScene=2;get targetElement(){return this._controls?.domElement??this._targetElement}set targetElement(e){this._targetElement=e,this._controls&&this._controls.domElement!==e&&(this._controls.disconnect(),this._controls.domElement=e,this._controls.connect())}_targetElement=null;debugLog=!1;get targetLerpSpeed(){return 5}set targetLerpSpeed(e){this.targetLerpDuration=1/e}targetLerpDuration=1;rotateLeft(e){this._controls?._rotateLeft(e)}rotateUp(e){this._controls?._rotateUp(e)}pan(e,t){this._controls?._pan(e,t)}zoomIn(e){e>0?this._controls?._dollyIn(1-e):e<0&&this._controls?._dollyOut(1+e)}_controls=null;_cameraObject=null;_lookTargetLerpActive=!1;_lookTargetStartPosition=new c.Vector3;_lookTargetEndPosition=new c.Vector3;_lookTargetLerp01=0;_lookTargetLerpDuration=0;_cameraLerpActive=!1;_cameraStartPosition=new c.Vector3;_cameraEndPosition=new c.Vector3;_cameraLerp01=0;_cameraLerpDuration=0;_fovLerpActive=!1;_fovLerpStartValue=0;_fovLerpEndValue=0;_fovLerp01=0;_fovLerpDuration=0;_inputs=0;_enableTime=0;_startedListeningToKeyEvents=!1;_eventSystem;_afterHandleInputFn;_camera=null;_syncedTransform;_didSetTarget=0;awake(){Pi&&console.debug("OrbitControls",this),this._didSetTarget=0,this._startedListeningToKeyEvents=!1}start(){this._eventSystem=jt.get(this.context)??void 0,this._eventSystem&&(this._afterHandleInputFn=this.afterHandleInput.bind(this),this._eventSystem.addEventListener(pp.AfterHandleInput,this._afterHandleInputFn))}onDestroy(){this._controls?.dispose(),this._eventSystem?.removeEventListener(pp.AfterHandleInput,this._afterHandleInputFn)}onEnable(){this._didSetTarget=0,this._enableTime=this.context.time.time;const e=x.getComponent(this.gameObject,Wt);this._camera=e;let t=e?.threeCamera;if(!t&&this.gameObject instanceof c.PerspectiveCamera&&(t=this.gameObject),t&&$f(t,this,!0),!this._controls&&t instanceof c.Object3D){this._cameraObject=t;const i=this.targetElement??this.context.renderer.domElement,n=t?.quaternion.clone();this._controls=new G.OrbitControls(t,i),t?.quaternion.copy(n),tf===void 0&&(tf={...this._controls.keys});const o=X(t),r=this.gameObject.worldForward,l=o.clone().sub(r.multiplyScalar(2.5));this._controls.target.copy(l)}if(this._controls)if(ef&&(this.enablePan=!0,this.enableZoom=!0,this.middleClickToFocus=!0,exports.DeviceUtilities.isMobileDevice()&&(this.doubleClickToFocus=!0)),this._controls.addEventListener("start",this.onControlsChangeStarted),this._controls.addEventListener("endMovement",this.onControlsChangeEnded),!this._startedListeningToKeyEvents&&this.enableKeys)this._startedListeningToKeyEvents=!0,this._controls.listenToKeyEvents(this.context.domElement);else try{this._controls.stopListenToKeyEvents()}catch{}this._syncedTransform=x.getComponent(this.gameObject,Ln)??void 0,this.context.pre_render_callbacks.push(this.__onPreRender),this._activePointerEvents=[],this.context.input.addEventListener("pointerdown",this._onPointerDown,{queue:$t.Early}),this.context.input.addEventListener("pointerdown",this._onPointerDownLate,{queue:$t.Late}),this.context.input.addEventListener("pointerup",this._onPointerUp,{queue:$t.Early}),this.context.input.addEventListener("pointerup",this._onPointerUpLate,{queue:$t.Late})}onDisable(){if(this._camera?.threeCamera&&$f(this._camera.threeCamera,this,!1),this._controls){this._controls.enabled=!1,this._controls.autoRotate=!1,this._controls.removeEventListener("start",this.onControlsChangeStarted),this._controls.removeEventListener("endMovement",this.onControlsChangeEnded);try{this._controls.stopListenToKeyEvents()}catch{}this._startedListeningToKeyEvents=!1}this._activePointerEvents.length=0,this.context.input.removeEventListener("pointerdown",this._onPointerDown),this.context.input.removeEventListener("pointerdown",this._onPointerDownLate),this.context.input.removeEventListener("pointerup",this._onPointerUp),this.context.input.removeEventListener("pointerup",this._onPointerUpLate)}_activePointerEvents;_lastTimeClickOnBackground=-1;_clickOnBackgroundCount=0;_onPointerDown=e=>{this._activePointerEvents.push(e)};_onPointerDownLate=e=>{e.used&&this._controls&&(this._controls.enabled=!1)};_onPointerUp=e=>{for(let t=this._activePointerEvents.length-1;t>=0;t--){const i=this._activePointerEvents[t];if(i.pointerId===e.pointerId&&i.button===e.button){this._activePointerEvents.splice(t,1);break}}if(this.clickBackgroundToFitScene>0&&e.isClick&&e.button===0){if(e.hasRay||e.intersections.push(...this.context.physics.raycast()),e.intersections.length<=0){const t=this.context.time.time-this._lastTimeClickOnBackground;this._lastTimeClickOnBackground=this.context.time.time,this.clickBackgroundToFitScene<=1||t<this.clickBackgroundToFitScene*.15?(this._clickOnBackgroundCount+=1,this._clickOnBackgroundCount>=this.clickBackgroundToFitScene-1&&this.fitCamera(this.context.scene.children,{immediate:!1})):this._clickOnBackgroundCount=0}Pi&&console.log(this.clickBackgroundToFitScene,e.intersections.length,this._clickOnBackgroundCount)}};_onPointerUpLate=e=>{this.doubleClickToFocus&&e.isDoubleClick&&!e.used&&this.setTargetFromRaycast()};updateTargetNow(e){const t=new c.Ray(this._cameraObject?.worldPosition,this._cameraObject?.worldForward.multiplyScalar(-1)),i=this.context.physics.raycastFromRay(t,e),n=i.length>0?i[0]:void 0;n&&n.distance>this.minZoom&&n.distance<this.maxZoom&&(Pi&&j.DrawWireSphere(n.point,.1,16711680,2),this._controls?.target.copy(i[0].point))}_orbitStartAngle=0;_zoomStartDistance=0;onControlsChangeStarted=()=>{this._controls&&(this._orbitStartAngle=this._controls.getAzimuthalAngle()+this._controls.getPolarAngle(),this._zoomStartDistance=this._controls.getDistance()),this._syncedTransform&&this._syncedTransform.requestOwnership()};onControlsChangeEnded=()=>{if(this._controls&&this.autoTarget){const t=this._controls.getAzimuthalAngle()+this._controls.getPolarAngle()-this._orbitStartAngle;Math.abs(t)<.01?(Pi&&console.debug("OrbitControls: Update target",{deltaAngle:t}),this.updateTargetNow({allowSlowRaycastFallback:!1})):Pi&&console.debug("OrbitControls: No target update",{deltaAngle:t})}};_shouldDisable=!1;afterHandleInput(e){e.detail.args.pointerId===0&&(e.detail.args.isDown?this._controls&&this._eventSystem&&(this._shouldDisable=this._eventSystem.hasActiveUI):(!e.detail.args.isPressed||e.detail.args.isUp)&&(this._shouldDisable=!1))}onPausedChanged(e){this._controls&&e&&(this._controls.enabled=!1)}onBeforeRender(){if(!this._controls)return;if(this._cameraObject!==this.context.mainCamera){this._controls.enabled=!1;return}if(this._controls.enabled=!0,(this.context.input.getPointerDown(1)||this.context.input.getPointerDown(2)||this.context.input.mouseWheelChanged||this.context.input.getPointerPressed(0)&&this.context.input.getPointerPositionDelta(0)?.length())&&(this._inputs+=1),this._inputs>0&&this.allowInterrupt&&(this.enableRotate&&(this.autoRotate=!1),this._cameraLerpActive=!1,this._lookTargetLerpActive=!1),this._inputs=0,this.autoTarget&&this._didSetTarget++===0){const t=x.getComponent(this.gameObject,Wt);if(t&&!this.setLookTargetFromConstraint()){this.debugLog&&console.log("NO TARGET");const i=X(t.threeCamera),n=Math.max(.01,i.length()),o=new c.Vector3(0,0,-n).applyMatrix4(t.threeCamera.matrixWorld);Pi&&j.DrawLine(i,o,5592575,10),this.setLookTargetPosition(o,!0)}if(!this.setLookTargetFromConstraint()){const i=new eo;i.screenPoint=new c.Vector2(0,0),i.lineThreshold=.1;const n=this.context.physics.raycast(i);n.length>0&&this.setLookTargetPosition(n[0].point,!0),za&&console.log("OrbitControls hits",...n)}}if(this.middleClickToFocus&&this.context.input.getPointerClicked(1)&&this.setTargetFromRaycast(),this._lookTargetLerpActive||this._cameraLerpActive||this._fovLerpActive){if(this._cameraLerpActive&&this._cameraObject)if(this._cameraLerp01+=this.context.time.deltaTime/this._cameraLerpDuration,this._cameraLerp01>=1)this._cameraObject.position.copy(this._cameraEndPosition),this._cameraLerpActive=!1,this.dispatchEvent(new Vl(this,"camera"));else{const t=I.easeInOutCubic(this._cameraLerp01);this._cameraObject.position.lerpVectors(this._cameraStartPosition,this._cameraEndPosition,t)}if(this._lookTargetLerpActive)if(this._lookTargetLerp01+=this.context.time.deltaTime/this._lookTargetLerpDuration,this._lookTargetLerp01>=1)this._controls.target.copy(this._lookTargetEndPosition),this._lookTargetLerpActive=!1,this.dispatchEvent(new Vl(this,"lookat"));else{const t=I.easeInOutCubic(this._lookTargetLerp01);this._controls.target.lerpVectors(this._lookTargetStartPosition,this._lookTargetEndPosition,t)}if(this._fovLerpActive&&this._cameraObject){const t=this._cameraObject;if(this._fovLerp01+=this.context.time.deltaTime/this._fovLerpDuration,this._fovLerp01>=1)t.fov=this._fovLerpEndValue,this._fovLerpActive=!1;else{const i=I.easeInOutCubic(this._fovLerp01);t.fov=I.lerp(this._fovLerpStartValue,this._fovLerpEndValue,i)}t.updateProjectionMatrix()}}if(this._controls){if(this.debugLog&&(this._controls.domElement=this.context.renderer.domElement),this._controls.enabled=!this._shouldDisable&&this._camera===this.context.mainCameraComponent&&!this.context.isInXR&&!this._activePointerEvents.some(t=>t.used),this._controls.keys=this.enableKeys?tf:D1,this._controls.autoRotate=this.autoRotate,this._controls.autoRotateSpeed=this.autoRotateSpeed,this._controls.enableZoom=this.enableZoom,this._controls.zoomSpeed=this.zoomSpeed,this._controls.zoomToCursor=this.zoomToCursor,this._controls.enableDamping=this.enableDamping,this._controls.dampingFactor=this.dampingFactor,this._controls.enablePan=this.enablePan,this._controls.enableRotate=this.enableRotate,this._controls.minAzimuthAngle=this.minAzimuthAngle,this._controls.maxAzimuthAngle=this.maxAzimuthAngle,this._controls.minPolarAngle=this.minPolarAngle,this._controls.maxPolarAngle=this.maxPolarAngle,ef||(this._camera?.threeCamera?.type==="PerspectiveCamera"?(this._controls.minDistance=this.minZoom,this._controls.maxDistance=this.maxZoom,this._controls.minZoom=0,this._controls.maxZoom=1/0):(this._controls.minDistance=0,this._controls.maxDistance=1/0,this._controls.minZoom=this.minZoom,this._controls.maxZoom=this.maxZoom)),typeof hh=="number"||hh===!0){this._controls.enableDamping=!0;const t=typeof hh=="number"?hh:.99;this._controls.dampingFactor=Math.max(.001,1-Math.min(1,t))}this.allowInterrupt||(this._lookTargetLerpActive&&(this._controls.enablePan=!1),this._cameraLerpActive&&(this._controls.enableRotate=!1,this._controls.autoRotate=!1),(this._lookTargetLerpActive||this._cameraLerpActive)&&(this._controls.enableZoom=!1)),this.context.isInXR||(!ef&&this.lookAtConstraint?.locked&&this.setLookTargetFromConstraint(0,this.lookAtConstraint01),this._controls.update(this.context.time.deltaTime),Pi&&j.DrawWireSphere(this._controls.target,.1,65280))}}__onPreRender=()=>{const e=this.context.pre_render_callbacks.indexOf(this.__onPreRender);e>=0&&this.context.pre_render_callbacks.splice(e,1),this.autoFit&&(this.autoFit=!1,this.fitCamera({centerCamera:"y",immediate:!0,objects:this.scene.children}))};setCameraAndLookTarget(e,t=!1){if(!e)return(A()||Pi)&&console.warn("[OrbitControls] setCameraAndLookTarget target is null"),!1;if(!(e instanceof c.Object3D)&&!(e instanceof Wt))return(A()||Pi)&&console.warn("[OrbitControls] setCameraAndLookTarget target is not an Object3D or Camera"),!1;e instanceof Wt&&(e=e.gameObject);const i=e.worldPosition,n=e.worldForward;e instanceof c.Camera&&(Pi&&console.debug("[OrbitControls] setCameraAndLookTarget flip forward direction for camera"),n.multiplyScalar(-1));const o=new c.Ray(i,n);return Pi&&j.DrawRay(o.origin,o.direction,16711680,10),this.setTargetFromRaycast(o,t)||this.setLookTargetPosition(o.at(2,V()),t),this.setCameraTargetPosition(i,t),!0}setCameraTargetPosition(e,t=!1){e&&(e instanceof c.Object3D&&(e=X(e)),this._cameraEndPosition||(this._cameraEndPosition=new c.Vector3),this._cameraEndPosition.copy(e),t===!0?(this._cameraLerpActive=!1,this._cameraObject&&this._cameraObject.position.copy(this._cameraEndPosition)):this._cameraObject&&(this._cameraLerpActive=!0,this._cameraLerp01=0,this._cameraStartPosition.copy(this._cameraObject?.position),typeof t=="number"?this._cameraLerpDuration=t:this._cameraLerpDuration=this.targetLerpDuration))}get cameraLerpActive(){return this._cameraLerpActive}stopCameraLerp(){this._cameraLerpActive=!1}setFieldOfView(e,t=!1){if(!this._controls||typeof e!="number")return;const i=this._camera?.threeCamera;i&&(t===!0?i.fov=e:(this._fovLerpActive=!0,this._fovLerp01=0,this._fovLerpStartValue=i.fov,this._fovLerpEndValue=e,typeof t=="number"?this._fovLerpDuration=t:this._fovLerpDuration=this.targetLerpDuration))}setLookTargetPosition(e=null,t=!1){this._controls&&e&&(e instanceof c.Object3D&&(e=X(e)),this._lookTargetEndPosition.copy(e),this._didSetTarget++,Pi&&(console.warn("OrbitControls: setLookTargetPosition",e,t),j.DrawWireSphere(this._lookTargetEndPosition,.2,16711680,2)),t===!0?this._controls.target.copy(this._lookTargetEndPosition):(this._lookTargetLerpActive=!0,this._lookTargetLerp01=0,this._lookTargetStartPosition.copy(this._controls.target),typeof t=="number"?this._lookTargetLerpDuration=t:this._lookTargetLerpDuration=this.targetLerpDuration))}get lookTargetLerpActive(){return this._lookTargetLerpActive}stopLookTargetLerp(){this._lookTargetLerpActive=!1}setLookTargetFromConstraint(e=0,t=1){if(!this._controls||this.lookAtConstraint?.enabled===!1)return!1;const i=this.lookAtConstraint?.sources;if(i&&i.length>0){const n=i[e];if(n)return n.getWorldPosition(this._lookTargetEndPosition),this.lerpLookTarget(this._lookTargetEndPosition,t),!0}return!1}lerpTarget(e,t){return this.lerpLookTarget(e,t)}lerpLookTarget(e,t){this._controls&&(t>=1?this._controls.target.copy(e):this._controls.target.lerp(e,t))}setTargetFromRaycast(e,t=!1){if(!this.controls)return!1;const i=e?this.context.physics.raycastFromRay(e):this.context.physics.raycast();for(const n of i)if(n.distance>0&&x.isActiveInHierarchy(n.object)){const o=xm(n.object);if(o&&o.canvas?.screenspace)break;return this.setLookTargetPosition(n.point,t),!0}return!1}fitCamera(e,t){if(this.context.isInXR)return;let i;if(Array.isArray(e)?i=e:e&&"type"in e?i=e.children:e&&typeof e=="object"&&!(e instanceof c.Object3D)&&!Array.isArray(e)&&(t=e,i=t.objects),i&&!Array.isArray(i)&&(i=i.children),(!Array.isArray(i)||i&&i.length<=0)&&(i=this.context.scene.children),!Array.isArray(i)||i.length<=0){console.warn("No objects to fit camera to...");return}const n=this._cameraObject,o=this._controls;if(!n||!o){console.warn("No camera or controls found to fit camera to objects...");return}t||(t={});const{immediate:r=!1,centerCamera:a="y",cameraNearFar:l="auto",fitOffset:h=1.1,fov:d=n?.fov}=t,u=new c.Vector3,p=new c.Vector3,m=Ht(i,void 0,this._camera?.threeCamera?.layers),y=m.clone();n.updateMatrixWorld(),n.updateProjectionMatrix(),m.getCenter(p);const b=new c.Vector3;if(m.getSize(b),m.applyMatrix4(n.matrixWorldInverse),m.getSize(u),m.setFromCenterAndSize(p,u),Number.isNaN(u.x)||Number.isNaN(u.y)||Number.isNaN(u.z)){console.warn("Camera fit size resultet in NaN",n,m,[...i]);return}if(u.length()<=1e-10){za&&console.warn("Camera fit size is zero",m,[...i]);return}const g=t.fov||n.fov,v=2*Math.atan(Math.tan(g*Math.PI/360/2)*n.aspect)/Math.PI*360,_=u.y/(2*Math.atan(Math.PI*g/360)),S=u.x/(2*Math.atan(Math.PI*v/360)),T=h*Math.max(_,S)+u.z/2;za&&console.log("Fit camera to objects",{fitHeightDistance:_,fitWidthDistance:S,distance:T,verticalFov:g,horizontalFov:v}),this.maxZoom=T*10,this.minZoom=T*.01;const M=.05,O=p.clone();if(O.y-=u.y*M,this.setLookTargetPosition(O,r),this.setFieldOfView(t.fov,r),l==null||l=="auto"){const $=x.findObjectOfType(Dn),E=$?$.radius:0,F=Math.max(b.x,b.y,b.z,E);n.near=T/100,n.far=F+T*10,$&&(this.maxZoom=Math.max(Math.min(this.maxZoom,E*.5),T))}const R=o.getDistance();R<this.minZoom&&(this.minZoom=R*.9),R>this.maxZoom&&(this.maxZoom=R*1.1),n.updateMatrixWorld(),n.updateProjectionMatrix();const B=X(n),L=p.clone();L.sub(B),a==="y"&&(L.y=0),L.normalize(),L.multiplyScalar(T),a==="y"&&(L.y+=-M*4*T);let N=p.clone().sub(L);n.parent&&(N=n.parent.worldToLocal(N)),this.setCameraTargetPosition(N,r),(za||t.debug)&&(j.DrawWireBox3(m,16777011,10),j.DrawWireBox3(y,65280,10),!this._haveAttachedKeyboardEvents&&za&&(this._haveAttachedKeyboardEvents=!0,document.body.addEventListener("keydown",$=>{if($.code==="KeyF"){let E;this._cameraObject instanceof c.PerspectiveCamera&&(E=Math.random()*Math.random()*170+10),this.fitCamera({objects:i,fitOffset:h,immediate:!1,fov:E})}$.code==="KeyV"&&this._cameraObject instanceof c.PerspectiveCamera&&(this._cameraObject.fov=60)}))),this.onBeforeRender()}_haveAttachedKeyboardEvents=!1}Ce([f()],he.prototype,"autoTarget");Ce([f()],he.prototype,"autoFit");Ce([f()],he.prototype,"enableRotate");Ce([f()],he.prototype,"autoRotate");Ce([f()],he.prototype,"autoRotateSpeed");Ce([f()],he.prototype,"minAzimuthAngle");Ce([f()],he.prototype,"maxAzimuthAngle");Ce([f()],he.prototype,"minPolarAngle");Ce([f()],he.prototype,"maxPolarAngle");Ce([f()],he.prototype,"enableKeys");Ce([f()],he.prototype,"enableDamping");Ce([f()],he.prototype,"dampingFactor");Ce([f()],he.prototype,"enableZoom");Ce([f()],he.prototype,"minZoom");Ce([f()],he.prototype,"maxZoom");Ce([f()],he.prototype,"zoomSpeed");Ce([f()],he.prototype,"enablePan");Ce([f(ir)],he.prototype,"lookAtConstraint");Ce([f()],he.prototype,"lookAtConstraint01");Ce([f()],he.prototype,"allowInterrupt");Ce([f()],he.prototype,"middleClickToFocus");Ce([f()],he.prototype,"doubleClickToFocus");Ce([f()],he.prototype,"clickBackgroundToFitScene");Ce([f()],he.prototype,"targetLerpDuration");var I1=Object.defineProperty,j1=Object.getOwnPropertyDescriptor,Ft=(s,e,t,i)=>{for(var n=i>1?void 0:i?j1(e,t):e,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&I1(e,t,n),n},Bo=(s=>(s[s.None=0]="None",s[s.Skybox=1]="Skybox",s[s.SolidColor=2]="SolidColor",s[s.Uninitialized=4]="Uninitialized",s))(Bo||{});const Ls=w("debugcam"),Yy=w("debugscreenpointtoray"),St=class ll extends k{get isCamera(){return!0}get aspect(){return this._cam instanceof c.PerspectiveCamera?this._cam.aspect:this.context.domWidth/this.context.domHeight}set aspect(e){this._cam instanceof c.PerspectiveCamera&&this._cam.aspect!==e&&(this._cam.aspect=e,this._cam.updateProjectionMatrix())}get fieldOfView(){return this._cam instanceof c.PerspectiveCamera?this._cam.fov:this._fov}set fieldOfView(e){const t=this.fieldOfView!=e;if(this._fov=e,t&&this._cam&&this._cam instanceof c.PerspectiveCamera){if(this._fov===void 0){console.warn("Can not set undefined fov on PerspectiveCamera");return}this._cam.fov=this._fov,this._cam.updateProjectionMatrix()}}get nearClipPlane(){return this._nearClipPlane}set nearClipPlane(e){const t=this._nearClipPlane!=e;this._nearClipPlane=e,this._cam&&(t||this._cam.near!=e)&&(this._cam.near=e,this._cam.updateProjectionMatrix())}_nearClipPlane=.1;get farClipPlane(){return this._farClipPlane}set farClipPlane(e){const t=this._farClipPlane!=e;this._farClipPlane=e,this._cam&&(t||this._cam.far!=e)&&(this._cam.far=e,this._cam.updateProjectionMatrix())}_farClipPlane=1e3;applyClippingPlane(){this._cam&&(this._cam.near=this._nearClipPlane,this._cam.far=this._farClipPlane,this._cam.updateProjectionMatrix())}get clearFlags(){return this._clearFlags}set clearFlags(e){if(typeof e=="string")switch(e){case"skybox":e=1;break;case"solidcolor":e=2;break;default:e=0;break}e!==this._clearFlags&&(this._clearFlags=e,this.applyClearFlagsIfIsActiveCamera())}orthographic=!1;orthographicSize=5;ARBackgroundAlpha=0;set cullingMask(e){this._cullingMask=e,this._cam&&(this._cam.layers.mask=e)}get cullingMask(){return this._cam?this._cam.layers.mask:this._cullingMask}_cullingMask=4294967295;set cullingLayer(e){this.cullingMask=(1<<e|0)>>>0}set backgroundBlurriness(e){e!==this._backgroundBlurriness&&(e===void 0?this._backgroundBlurriness=void 0:this._backgroundBlurriness=Math.min(Math.max(e,0),1),this.applyClearFlagsIfIsActiveCamera())}get backgroundBlurriness(){return this._backgroundBlurriness}_backgroundBlurriness=void 0;set backgroundIntensity(e){e!==this._backgroundIntensity&&(e===void 0?this._backgroundIntensity=void 0:this._backgroundIntensity=Math.min(Math.max(e,0),10),this.applyClearFlagsIfIsActiveCamera())}get backgroundIntensity(){return this._backgroundIntensity}_backgroundIntensity=void 0;set backgroundRotation(e){e!==this._backgroundRotation&&(e===void 0?this._backgroundRotation=void 0:this._backgroundRotation=e,this.applyClearFlagsIfIsActiveCamera())}get backgroundRotation(){return this._backgroundRotation}_backgroundRotation=void 0;set environmentIntensity(e){this._environmentIntensity=e}get environmentIntensity(){return this._environmentIntensity}_environmentIntensity=void 0;get backgroundColor(){return this._backgroundColor??null}set backgroundColor(e){e&&(this._backgroundColor||(this._backgroundColor=new Z(1,1,1,1)),this._backgroundColor.copy(e),(!("alpha"in e)||e.alpha===void 0)&&(this._backgroundColor.alpha=1),this.applyClearFlagsIfIsActiveCamera())}set targetTexture(e){this._targetTexture=e}get targetTexture(){return this._targetTexture}_targetTexture=null;_backgroundColor;_fov;_cam=null;_clearFlags=2;_skybox;get cam(){return this.threeCamera}get threeCamera(){return this.activeAndEnabled&&this.buildCamera(),this._cam}static _origin=new c.Vector3;static _direction=new c.Vector3;screenPointToRay(e,t,i){const n=this.threeCamera,o=ll._origin;o.set(e,t,-1),this.context.input.convertScreenspaceToRaycastSpace(o),Yy&&console.log("screenPointToRay",e.toFixed(2),t.toFixed(2),"now:",o.x.toFixed(2),o.y.toFixed(2),"isInXR:"+this.context.isInXR),o.z=-1,o.unproject(n);const r=ll._direction.set(o.x,o.y,o.z),a=X(n);return r.sub(a),r.normalize(),i?(i.set(a,r),i):new c.Ray(a.clone(),r.clone())}_frustum;getFrustum(){return this._frustum||(this._frustum=new c.Frustum,this.updateFrustum()),this._frustum}updateFrustum(){this._frustum||(this._frustum=new c.Frustum),this._frustum.setFromProjectionMatrix(this.getProjectionScreenMatrix(this._projScreenMatrix,!0),this.context.renderer.coordinateSystem)}getProjectionScreenMatrix(e,t){return t&&this._projScreenMatrix.multiplyMatrices(this.threeCamera.projectionMatrix,this.threeCamera.matrixWorldInverse),e===this._projScreenMatrix?e:e.copy(this._projScreenMatrix)}_projScreenMatrix=new c.Matrix4;awake(){Yy&&window.addEventListener("pointerdown",e=>{const t=e.clientX,i=e.clientY;console.log("touch",t.toFixed(2),i.toFixed(2));const n=this.screenPointToRay(t,i),o="#"+Math.floor(Math.random()*16777215).toString(16);j.DrawRay(n.origin,n.direction,o,10)})}onEnable(){Ls&&console.log(`Camera enabled: "${this.name}". ClearFlags=${Bo[this._clearFlags]}`,this),this.buildCamera(),(this.tag=="MainCamera"||!this.context.mainCameraComponent)&&(this.context.setCurrentCamera(this),F1(this)),this.applyClearFlagsIfIsActiveCamera({applySkybox:!0})}onDisable(){this.context.removeCamera(this)}onBeforeRender(){if(this._cam&&(this._frustum&&this.updateFrustum(),this._clearFlags===2&&this.applyClearFlagsIfIsActiveCamera(),this._targetTexture)){this.context.isManagedExternally&&(this._warnedAboutExternalRenderer||(this._warnedAboutExternalRenderer=!0,console.warn("Rendering with external renderer is not supported yet. This may not work or throw errors. Please remove the the target texture from your camera: "+this.name,this.targetTexture))),this.context.composer;const e=this.context.renderer;if(e){const t=this.context.mainCameraComponent;this.applyClearFlags(),this._targetTexture.render(this.context.scene,this._cam,e),t?.applyClearFlags()}}}buildCamera(){if(this._cam)return;const e=this.gameObject.isCamera;let t=null;if(e?(t=this.gameObject,t?.layers.enableAll(),t instanceof c.PerspectiveCamera&&(this._fov=t.fov)):t=this.gameObject.children[0],t&&t.isCamera)t instanceof c.PerspectiveCamera&&(this._fov&&(t.fov=this._fov),t.near=this._nearClipPlane,t.far=this._farClipPlane,t.updateProjectionMatrix());else if(!this.orthographic)t=new c.PerspectiveCamera(this.fieldOfView,window.innerWidth/window.innerHeight,this._nearClipPlane,this._farClipPlane),this.fieldOfView&&(t.fov=this.fieldOfView),this.gameObject.add(t);else{const i=this.orthographicSize*100;t=new c.OrthographicCamera(window.innerWidth/-i,window.innerWidth/i,window.innerHeight/i,window.innerHeight/-i,this._nearClipPlane,this._farClipPlane),this.gameObject.add(t)}this._cam=t,this._cam.layers.mask=this._cullingMask,this.tag=="MainCamera"&&this.context.setCurrentCamera(this)}applyClearFlagsIfIsActiveCamera(e){this.context.mainCameraComponent===this&&this.applyClearFlags(e)}applyClearFlags(e){if(!this._cam){Ls&&console.log("Camera does not exist (apply clear flags)");return}if(this.fieldOfView=this._fov,Ls){const i=`[Camera] Apply ClearFlags: ${Bo[this._clearFlags]} - "${this.name}"`;console.debug(i)}const t=this.context.domElement.getAttribute("background-image")||this.context.domElement.getAttribute("background-color");switch(this._clearFlags){case 0:return;case 1:if(ll.backgroundShouldBeTransparent(this.context)&&(!this.ARBackgroundAlpha||this.ARBackgroundAlpha<.001)){this.context.scene.background=null,this.context.renderer.setClearColor(0,0);return}(!this.scene.background||!this._skybox||e?.applySkybox===!0)&&this.applySceneSkybox(),this._backgroundBlurriness!==void 0&&!this.context.domElement.getAttribute("background-blurriness")?this.context.scene.backgroundBlurriness=this._backgroundBlurriness:Ls&&console.warn(`Camera "${this.name}" has no background blurriness`),this._backgroundIntensity!==void 0&&!this.context.domElement.getAttribute("background-intensity")&&(this.context.scene.backgroundIntensity=this._backgroundIntensity),this._backgroundRotation!==void 0&&!this.context.domElement.getAttribute("background-rotation")?this.context.scene.backgroundRotation=this._backgroundRotation:Ls&&console.warn(`Camera "${this.name}" has no background intensity`);break;case 2:if(this._backgroundColor&&!t){let i=this._backgroundColor.alpha;ll.backgroundShouldBeTransparent(this.context)&&(i=this.ARBackgroundAlpha??0),this.context.scene.background=null,this.context.xr?.isVR?this.context.renderer.setClearColor(cb(this._backgroundColor).convertLinearToSRGB()):this.context.renderer.setClearColor(this._backgroundColor,i)}else this._backgroundColor||Ls&&console.warn(`[Camera] has no background color "${this.name}" `);break;case 4:t||(this.context.scene.background=null,this.context.renderer.setClearColor(0,0));break}}applySceneSkybox(){this._skybox||(this._skybox=new B1(this)),this._skybox.apply()}static backgroundShouldBeTransparent(e){const t=e.renderer.xr?.getSession();if(!t)return!1;if(typeof t._transparent=="boolean")return t._transparent;const i=t.environmentBlendMode;Ls&&Se("Environment blend mode: "+i+" on "+navigator.userAgent);let n=i==="additive"||i==="alpha-blend";return e.isInAR&&i==="opaque"&&(navigator.userAgent?.includes("OculusBrowser")||navigator.userAgent?.includes("Mozilla")&&navigator.userAgent?.includes("Mobile WebXRViewer/v2"))&&(n=!0),t._transparent=n,n}};Ft([f()],St.prototype,"aspect",1);Ft([f()],St.prototype,"fieldOfView",1);Ft([f()],St.prototype,"nearClipPlane",1);Ft([f()],St.prototype,"farClipPlane",1);Ft([f()],St.prototype,"clearFlags",1);Ft([f()],St.prototype,"orthographic",2);Ft([f()],St.prototype,"orthographicSize",2);Ft([f()],St.prototype,"ARBackgroundAlpha",2);Ft([f()],St.prototype,"cullingMask",1);Ft([f()],St.prototype,"backgroundBlurriness",1);Ft([f()],St.prototype,"backgroundIntensity",1);Ft([f(c.Euler)],St.prototype,"backgroundRotation",1);Ft([f()],St.prototype,"environmentIntensity",1);Ft([f(Z)],St.prototype,"backgroundColor",1);Ft([f(xn)],St.prototype,"targetTexture",1);let Wt=St;class B1{_camera;_skybox;get context(){return this._camera?.context}constructor(e){this._camera=e}apply(){if(this._skybox=this.context.lightmaps.tryGetSkybox(this._camera.sourceId),!this._skybox)this._did_log_failed_to_find_skybox||(this._did_log_failed_to_find_skybox=!0,console.warn(`Camera "${this._camera.name}" has no skybox texture. ${this._camera.sourceId}`));else if(this.context.scene.background!==this._skybox){const e=this.context.domElement.getAttribute("background-image")||this.context.domElement.getAttribute("background-color")||this.context.domElement.getAttribute("skybox-image");Ls&&console.debug(`[Camera] Apply Skybox ${this._skybox?.name} ${e} - "${this._camera.name}"`),e?.length||(this._skybox.mapping=c.EquirectangularReflectionMapping,this.context.scene.background=this._skybox)}}}function F1(s){w("freecam")&&s.context.mainCameraComponent===s&&x.getOrAddComponent(s.gameObject,he)}class is extends k{get listener(){return this._listener==null&&(this._listener=new c.AudioListener),this._listener}_listener=null;onEnable(){tn.registerWaitForInteraction(this.onInteraction),this.addListenerIfItExists()}onDisable(){tn.unregisterWaitForInteraction(this.onInteraction),this.removeListenerIfItExists()}onInteraction=()=>{this.destroyed||this.listener==null||this.addListenerIfItExists()};addListenerIfItExists(){const e=this._listener;if(!e||e?.parent)return;const t=this.context.mainCameraComponent||x.getComponentInParent(this.gameObject,Wt);t?.threeCamera?t.threeCamera.add(e):this.gameObject.add(e),e.filter?(e.gain.connect(e.filter),e.filter.connect(e.context.destination)):e.gain.connect(e.context.destination)}removeListenerIfItExists(){const e=this._listener;e&&(e.removeFromParent(),e.filter&&e.filter.disconnect(),e.gain&&e.gain.disconnect())}}var U1=Object.defineProperty,z1=Object.getOwnPropertyDescriptor,on=(s,e,t,i)=>{for(var n=i>1?void 0:i?z1(e,t):e,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&U1(e,t,n),n};const lt=w("debugaudio"),zi=class Ds extends k{static get userInteractionRegistered(){return tn.userInteractionRegistered}static registerWaitForAllowAudio(e){tn.registerWaitForInteraction(e)}clip="";playOnAwake=!1;preload=!0;playInBackground=!0;get isPlaying(){return this.sound?.isPlaying??!1}get duration(){return this.sound?.buffer?.duration}get time01(){const e=this.duration;return e&&this.sound?this.sound?.context.currentTime/e:0}set time01(e){const t=this.duration;t&&this.sound&&(this.time=e*t)}get time(){return this.sound?.source?this.sound.source?.context.currentTime-this._lastContextTime+this.sound.offset:0}set time(e){if(this.sound){if(e===this.sound.offset)return;const t=this.isPlaying;this.stop(),this.sound.offset=e,t&&this.play()}}get loop(){return this.sound&&(this._loop=this.sound.getLoop()),this._loop}set loop(e){this._loop=e,this.sound&&this.sound.setLoop(e)}get spatialBlend(){return this._spatialBlend}set spatialBlend(e){e!==this._spatialBlend&&(this._spatialBlend=e,this._needUpdateSpatialDistanceSettings=!0)}get minDistance(){return this._minDistance}set minDistance(e){this._minDistance!==e&&(this._minDistance=e,this._needUpdateSpatialDistanceSettings=!0)}get maxDistance(){return this._maxDistance}set maxDistance(e){this._maxDistance!==e&&(this._maxDistance=e,this._needUpdateSpatialDistanceSettings=!0)}_spatialBlend=0;_minDistance=1;_maxDistance=100;get volume(){return this._volume}set volume(e){this._volume=e,this.sound&&!this.context.application.muted&&(lt&&console.log(this.name,"audio set volume",e),this.sound.setVolume(e))}_volume=1;set pitch(e){this.sound&&this.sound.setPlaybackRate(e)}get pitch(){return this.sound?this.sound.getPlaybackRate():1}rollOffMode=0;_loop=!1;sound=null;helper=null;wasPlaying=!1;audioLoader=null;shouldPlay=!1;_lastClipStartedLoading=null;_audioElement=null;get Sound(){if(!this.sound&&Ds.userInteractionRegistered){let e=this.gameObject.getComponent(is)??this.context.mainCamera.getComponent(is)??cc(is,this.context,!1);!e&&this.context.mainCamera&&(e=this.context.mainCamera.addComponent(is)),e?.listener?(this.sound=new c.PositionalAudio(e.listener),this.gameObject?.add(this.sound)):lt&&console.warn("No audio listener found in scene - can not play audio")}return this.sound}get ShouldPlay(){return this.shouldPlay}get audioContext(){return this.sound?.context}awake(){lt&&console.log("[AudioSource]",this),this.audioLoader=new c.AudioLoader,this.playOnAwake&&(this.shouldPlay=!0),this.preload&&typeof this.clip=="string"&&this.audioLoader.load(this.clip,this.createAudio,()=>{},console.error)}onEnable(){this.sound&&this.gameObject.add(this.sound),Ds.userInteractionRegistered?this.playOnAwake&&this.context.application.isVisible&&this.play():Ds.registerWaitForAllowAudio(()=>{this.enabled&&!this.destroyed&&this.shouldPlay&&this.onNewClip(this.clip)}),globalThis.addEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.addEventListener(Xf.MuteChanged,this.onApplicationMuteChanged)}onDisable(){globalThis.removeEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.removeEventListener(Xf.MuteChanged,this.onApplicationMuteChanged),this.pause()}onVisibilityChanged=()=>{switch(document.visibilityState){case"hidden":(this.playInBackground===!1||exports.DeviceUtilities.isMobileDevice())&&(this.wasPlaying=this.isPlaying,this.isPlaying&&this.pause());break;case"visible":lt&&console.log("visible",this.enabled,this.playOnAwake,!this.isPlaying,Ds.userInteractionRegistered,this.wasPlaying),this.enabled&&this.playOnAwake&&!this.isPlaying&&Ds.userInteractionRegistered&&this.wasPlaying&&this.play();break}};onApplicationMuteChanged=()=>{this.context.application.muted?this.sound?.setVolume(0):this.sound?.setVolume(this.volume)};createAudio=e=>{if(this.destroyed){lt&&console.warn("AudioSource destroyed, not creating audio",this.name);return}lt&&console.log("AudioBuffer finished loading",e);const t=this.Sound;if(!t){lt&&console.warn("Failed getting sound?",this.name);return}t.isPlaying&&t.stop(),e&&t.setBuffer(e),t.loop=this._loop,this.context.application.muted?t.setVolume(0):t.setVolume(this.volume),t.autoplay=this.shouldPlay&&Ds.userInteractionRegistered,this.applySpatialDistanceSettings(),t.isPlaying&&t.stop(),Ds.registerWaitForAllowAudio(this.__onAllowAudioCallback)};__onAllowAudioCallback=()=>{this.shouldPlay&&this.play()};applySpatialDistanceSettings(){const e=this.sound;if(!e)return;this._needUpdateSpatialDistanceSettings=!1;const t=I.lerp(10*this._maxDistance/Math.max(1e-4,this.spatialBlend),this._minDistance,this.spatialBlend);switch(lt&&console.log(this.name,this._minDistance,this._maxDistance,this.spatialBlend,"Ref distance="+t),e.setRefDistance(t),e.setMaxDistance(Math.max(.01,this._maxDistance)),this.rollOffMode){case 0:e.setDistanceModel("exponential");break;case 1:e.setDistanceModel("linear");break;case 2:console.warn("Custom rolloff for AudioSource is not supported: "+this.name);break}this.spatialBlend>0?lt&&!this.helper&&(this.helper=new G.PositionalAudioHelper(e,e.getRefDistance()),e.add(this.helper)):this.helper&&this.helper.parent&&this.helper.removeFromParent()}async onNewClip(e){if(e&&(this.clip=e),typeof e=="string")if(lt&&console.log(e),e.endsWith(".mp3")||e.endsWith(".wav")){if(this.audioLoader||(this.audioLoader=new c.AudioLoader),this.shouldPlay=!0,this._lastClipStartedLoading===e){lt&&console.log("Is currently loading:",this._lastClipStartedLoading,this);return}this._lastClipStartedLoading=e,lt&&console.log("load audio",e);const t=await this.audioLoader.loadAsync(e).catch(console.error);if(this.destroyed)return;this._lastClipStartedLoading===e&&(this._lastClipStartedLoading=null),t&&this.createAudio(t)}else console.warn("Unsupported audio clip type",e);else this.shouldPlay=!0,this.createAudio()}play(e=void 0){!e&&this.clip&&(e=this.clip),e!==void 0&&typeof e!="string"&&!(e instanceof MediaStream)&&(A()&&console.warn("Called play on AudioSource with unknown argument type:",e+`
951
+ Using the assigned clip instead:`,this.clip),e=this.clip);let t=!this.sound||e&&e!==this.clip;if(typeof e=="string"&&!this.audioLoader&&(t=!0),(e instanceof MediaStream||typeof e=="string")&&(this.clip=e),t){this.shouldPlay=!0,this.onNewClip(e);return}if(this.shouldPlay=!0,this._hasEnded=!1,lt&&console.log("play",this.sound?.getVolume(),this.sound),this.sound&&!this.sound.isPlaying){const i=this.context.application.muted;i&&this.sound.setVolume(0),this.gameObject?.add(this.sound),this.clip instanceof MediaStream?(this.sound.setMediaStreamSource(this.clip),this._audioElement||(this._audioElement=document.createElement("audio"),this._audioElement.style.display="none"),this._audioElement.parentNode||this.context.domElement.shadowRoot?.append(this._audioElement),this._audioElement.srcObject=this.clip,this._audioElement.autoplay=!1):(this._audioElement&&this._audioElement.remove(),this.sound.play(i?.1:0))}}pause(){lt&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.isPlaying&&this.sound.source&&(this._lastContextTime=this.sound?.context.currentTime,this.sound.pause()),this._audioElement?.remove()}stop(){lt&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.source&&(this._lastContextTime=this.sound?.context.currentTime,lt&&console.log(this._lastContextTime),this.sound.stop()),this._audioElement?.remove()}_lastContextTime=0;_hasEnded=!0;_needUpdateSpatialDistanceSettings=!1;update(){this.helper&&(this.isPlaying&&this.helper.update(),this.helper.visible=this.isPlaying),this._needUpdateSpatialDistanceSettings&&this.applySpatialDistanceSettings(),this.sound&&!this.sound.isPlaying&&this.shouldPlay&&!this._hasEnded&&(this._hasEnded=!0,lt&&console.log("Audio clip ended",this.clip),this.dispatchEvent(new CustomEvent("ended",{detail:this})))}};on([f(URL)],zi.prototype,"clip",2);on([f()],zi.prototype,"playOnAwake",2);on([f()],zi.prototype,"preload",2);on([f()],zi.prototype,"playInBackground",2);on([f()],zi.prototype,"loop",1);on([f()],zi.prototype,"spatialBlend",1);on([f()],zi.prototype,"minDistance",1);on([f()],zi.prototype,"maxDistance",1);on([f()],zi.prototype,"volume",1);on([f()],zi.prototype,"pitch",1);on([f()],zi.prototype,"rollOffMode",2);let Ii=zi;const N1=w("debugavatar");class xe extends k{static getAvatar(e){return e>=0&&e<xe.instances.length?xe.instances[e]:null}static instances=[];static onAvatarMarkerCreated(e){return xe._onNewAvatarMarkerAdded.push(e),e}static onAvatarMarkerDestroyed(e){return xe._onAvatarMarkerDestroyed.push(e),e}static _onNewAvatarMarkerAdded=[];static _onAvatarMarkerDestroyed=[];connectionId;avatar;awake(){xe.instances.push(this),N1&&console.log(this);for(const e of xe._onNewAvatarMarkerAdded)e({avatarMarker:this,gameObject:this.gameObject})}onDestroy(){xe.instances.splice(xe.instances.indexOf(this),1);for(const e of xe._onAvatarMarkerDestroyed)e({avatarMarker:this,gameObject:this.gameObject})}isLocalAvatar(){return this.connectionId===this.context.connection.connectionId}}class Fo{static Pois=[];static LastChangeTime=0;static Add(e,t,i=null){if(t){for(const n of this.Pois)if(n.obj===t)return;this.Pois.push({obj:t,avatar:i}),this.LastChangeTime=e.time.time}}static Remove(e,t){if(t){for(const i of this.Pois)if(i.obj===t){this.Pois.splice(this.Pois.indexOf(i),1),this.LastChangeTime=e?.time.time??U.Current?.time.time;return}}}}class V1{guid;position=new c.Vector3}class $l extends k{set controlledTarget(e){this.target=e;const t=P.get("MoveRandom");if(t&&this.target){const i=x.getComponent(this.target,t);i&&i.destroy()}}target=null;avatar=null;_model=null;_targetModel=new V1;_currentTargetObject=null;_lastUpdateTime=0;_lookDuration=0;_lastPoiChangedTime=0;awake(){if(this.avatar=x.getComponentInParent(this.gameObject,xe),this.avatar){const e=x.getComponentInParent(this.gameObject,xe);this._model=new tm(this.context.connection,this.guid),e?.isLocalAvatar&&this._model.requestOwnership()}this.context.connection.beginListen("avatar-look-target-changed",e=>{this.target&&e&&e.guid===this.avatar?.guid&&Ye(this.target,e.position)})}update(){if((!this.context.connection.isConnected||this._model?.hasOwnership)&&(Fo.LastChangeTime!==this._lastPoiChangedTime&&(this._lastPoiChangedTime=Fo.LastChangeTime,this._lookDuration=0),this.selectTarget(),this._currentTargetObject&&this.context.time.frameCount%10===0&&this.target)){const t=X(this._currentTargetObject);Ye(this.target,t),this.context.connection.isConnected&&this.avatar&&(this.context.connection.send("avatar-look-target-changed",this._targetModel),this._targetModel.guid=this.avatar.guid,this._targetModel.position.copy(t))}}selectTarget(){if(this.context.time.time-this._lastUpdateTime>this._lookDuration){this._lastUpdateTime=this.context.time.time,this._lookDuration=Math.random()*.5+.2;const t=Fo.Pois;if(t.length>0){const i=t[Math.floor(Math.random()*t.length)];if(i&&i.obj){if(i.avatar&&i.avatar===this.avatar)return;this._currentTargetObject=i.obj}}}}}function Z0(s){const e=s;return!!(e.parser&&e.parser.json)}var Gd=(s=>(s[s.None=0]="None",s[s.DontExport=1]="DontExport",s))(Gd||{});function J0(s){return s&&s.isComponent}const $1=Symbol("object"),nf=new hi(()=>new c.Vector3,20);class ev{_point;_normal;_tangentVelocity;distance;impulse;friction;get point(){return nf.get().set(this._point.x,this._point.y,this._point.z)}get normal(){return nf.get().set(this._normal.x,this._normal.y,this._normal.z)}get tangentVelocity(){return nf.get().set(this._tangentVelocity.x,this._tangentVelocity.y,this._tangentVelocity.z)}constructor(e,t,i,n,o,r){this._point=e,this.distance=t,this._normal=i,this.impulse=n,this.friction=o,this._tangentVelocity=r}}class tv{contacts;constructor(e,t,i){this.me=e,this._collider=t,this._gameObject=t.gameObject,this.contacts=i}me;_collider;get collider(){return this._collider}_gameObject;get gameObject(){return this._gameObject}get rigidBody(){return this.collider?.attachedRigidbody}}class iv{object;collider;constructor(e,t){this.object=e,this.collider=t}}const Oe=w("debugnetworkingstreams");var Sn=(s=>(s.Connected="peer-user-connected",s.StreamReceived="receive-stream",s.StreamEnded="call-ended",s.Disconnected="peer-user-disconnected",s.UserJoined="user-joined",s))(Sn||{});class Sm{type="call-ended";userId;direction;constructor(e,t){this.userId=e,this.direction=t}}class nv{type="receive-stream";userId;stream;target;constructor(e,t,i){this.userId=e,this.stream=t,this.target=i}}class W1{guid;peerId;dontSave=!0;constructor(e,t){this.guid=e.id,this.peerId=t}}var sv=(s=>(s.Incoming="incoming",s.Outgoing="outgoing",s))(sv||{});class G1 extends c.EventDispatcher{peerId;userId;direction;call;get stream(){return this._stream}_stream=null;_isDisposed=!1;close(){this._isDisposed||(this._isDisposed=!0,this.call.close(),Cn(this._stream))}get isOpen(){return this.call.peerConnection?.connectionState==="connected"}get isOpening(){return this.call.peerConnection?.connectionState==="connecting"}get isClosed(){return!this.isOpen||this._isDisposed}constructor(e,t,i,n=null){super(),this.peerId=t.peer,this.userId=e,this.call=t,this.direction=i,this._stream=n,t.on("stream",o=>{if(Oe&&console.log("Receive stream",`
942
952
  Audio:`,o.getAudioTracks(),`
943
- Video:`,o.getVideoTracks()),this._stream=o,i==="incoming"){const r=new nv(e,o,this);this.dispatchEvent(r)}}),t.on("close",()=>{this.dispatchEvent(new Sm(e,i))})}}function Ky(s){return s=s.replace("a=fmtp:111 minptime=10;useinbandfec=1","a=fmtp:111 ptime=5;useinbandfec=1;stereo=1;maxplaybackrate=48000;maxaveragebitrat=128000;sprop-stereo=1"),s}class ns extends c.EventDispatcher{static instances=new Map;static getOrCreate(e,t){if(ns.instances.has(t))return ns.instances.get(t);const i=new ns(e,t);return ns.instances.set(t,i),i}getMyPeerId(){if(this.context.connection.connectionId)return this.getPeerIdFromUserId(this.context.connection.connectionId)}getPeerIdFromUserId(e){return this.id+"-"+e}getUserIdFromPeerId(e){return e.substring(this.id.length+1)}makeCall(e,t){if(!t?.id){Te?console.warn("Can not make a call: mediastream has no id or is undefined"):console.debug("Can not make a call: mediastream has no id or is undefined");return}const i={metadata:{userId:this.context.connection.connectionId,streamId:t.id},sdpTransform:o=>Ky(o)},n=this._peer?.call(e,t,i);if(n){const o=this.registerCall(n,"outgoing",t);return Te&&console.warn(`📞 CALL ${e}`,`
953
+ Video:`,o.getVideoTracks()),this._stream=o,i==="incoming"){const r=new nv(e,o,this);this.dispatchEvent(r)}}),t.on("close",()=>{this.dispatchEvent(new Sm(e,i))})}}function Ky(s){return s=s.replace("a=fmtp:111 minptime=10;useinbandfec=1","a=fmtp:111 ptime=5;useinbandfec=1;stereo=1;maxplaybackrate=48000;maxaveragebitrat=128000;sprop-stereo=1"),s}class ns extends c.EventDispatcher{static instances=new Map;static getOrCreate(e,t){if(ns.instances.has(t))return ns.instances.get(t);const i=new ns(e,t);return ns.instances.set(t,i),i}getMyPeerId(){if(this.context.connection.connectionId)return this.getPeerIdFromUserId(this.context.connection.connectionId)}getPeerIdFromUserId(e){return this.id+"-"+e}getUserIdFromPeerId(e){return e.substring(this.id.length+1)}makeCall(e,t){if(!t?.id){Oe?console.warn("Can not make a call: mediastream has no id or is undefined"):console.debug("Can not make a call: mediastream has no id or is undefined");return}const i={metadata:{userId:this.context.connection.connectionId,streamId:t.id},sdpTransform:o=>Ky(o)},n=this._peer?.call(e,t,i);if(n){const o=this.registerCall(n,"outgoing",t);return Oe&&console.warn(`📞 CALL ${e}`,`
944
954
  Outgoing:`,this._outgoingCalls,`
945
- Incoming:`,this._incomingCalls),o}else Te&&console.error("Failed to make call",e,t,this._peer)}closeAll(){for(const e of this._incomingCalls)e.close();for(const e of this._outgoingCalls)e.close();this.updateCalls()}updateCalls=()=>{for(let e=this._incomingCalls.length-1;e>=0;e--){const t=this._incomingCalls[e];t.isClosed&&!t.isOpening&&this._incomingCalls.splice(e,1)}for(let e=this._outgoingCalls.length-1;e>=0;e--){const t=this._outgoingCalls[e];let i=!1;t.isClosed&&!t.isOpening&&(t.stream?.active?Te&&console.warn("!!! Stream is still active, don't remove call",t.userId,"Your id: "+this.context.connection.connectionId):(Te&&console.warn("!!! Remove closed call",t.userId),i=!0)),this.context.connection.userIsInRoom(t.userId)===!1&&(Te&&console.warn("!!! User is not in room anymore, remove call",t.userId),i=!0),i&&(t.close(),this._outgoingCalls.splice(e,1))}};get peer(){return this._peer}get incomingCalls(){return this._incomingCalls}id;context;_incomingCalls=[];_outgoingCalls=[];_peer;constructor(e,t){super(),this.context=e,this.id=t,this.setupPeer();try{navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia}catch(i){Te&&console.error("[PeerJs] Error setting getUserMedia",i)}}_enabled=!1;_enabledPeer=!1;onConnectRoomFn=this.onConnectRoom.bind(this);enable(){this._enabled||(this._enabled=!0,this.context.connection.beginListen(Q.JoinedRoom,this.onConnectRoomFn),this.subscribePeerEvents())}disable(){this._enabled&&(this._enabled=!1,this.context.connection.stopListen(Q.JoinedRoom,this.onConnectRoomFn),this.unsubscribePeerEvents())}onConnectRoom(){this.setupPeer()}setupPeer(){if(this.context.connection.connectionId&&!this._enabledPeer){if(this._enabledPeer=!0,!this._peer){const e=this.getMyPeerId();e?this._peer=Ab(e):console.error("Failed to setup peerjs because we dont have a connection id",this.context.connection.connectionId)}this._enabled&&this.subscribePeerEvents()}}subscribePeerEvents(){this._peer&&(this._peer.on("open",this.onPeerConnect),this._peer.on("close",this.onPeerClose),this._peer.on("call",this.onPeerReceivingCall),this._peer.on("disconnected",this.onPeerDisconnected),this._peer.on("error",this.onPeerError))}unsubscribePeerEvents(){this._peer&&(this._peer.off("open",this.onPeerConnect),this._peer.off("close",this.onPeerClose),this._peer.off("call",this.onPeerReceivingCall),this._peer.off("disconnected",this.onPeerDisconnected),this._peer.off("error",this.onPeerError))}onPeerConnect=e=>{if(Te&&console.log("PEER opened as",e),e===null){console.error("Peer connection failed",e);return}this.context.connection.send("peer-user-connected",new W1(this,e))};onPeerClose=()=>{Te&&console.log("PEER closed"),this.updateCalls()};onPeerDisconnected=()=>{Te&&console.log("PEER disconnected"),this.updateCalls()};onPeerError=e=>{Te&&console.error("PEER error",e)};onPeerReceivingCall=e=>{e.answer(void 0,{sdpTransform:t=>Ky(t)}),this.registerCall(e,"incoming",null)};registerCall(e,t,i){const n=e.metadata;(!n||!n.userId)&&console.error("Missing call metadata",e);const o=n.userId;t==="incoming"&&Te?console.warn("← Receive call from",e.metadata,e.connectionId):Te&&console.warn("→ Make call to",e.metadata);const r=t==="incoming"?this._incomingCalls:this._outgoingCalls,a=new G1(o,e,t,i);return r.push(a),e.on("error",l=>{console.error("Call error",l)}),e.on("close",()=>{Te&&console.log("Call ended",e.metadata);const l=r.indexOf(a);l!==-1&&r.splice(l,1),a.close(),this.dispatchEvent(new Sm(o,t))}),a.addEventListener("call-ended",l=>{this.dispatchEvent(l)}),t==="incoming"&&(a.addEventListener("receive-stream",l=>{this.dispatchEvent(l)}),e.on("stream",()=>{Te&&console.log("Received stream for call",e.metadata);let l=0;const h=setInterval(()=>{const d=l===0;!a.isOpen&&d&&(Te&&console.warn("Close call because stream is not active",e.metadata),l+=1,clearInterval(h),a.close())},2e3)})),a}}class mc extends c.EventDispatcher{static create(e,t){const i=ns.getOrCreate(e.context,t||e.context.connection.connectionId||e.guid);return new mc(e.context,i)}context;peer;_sendingStreams=new Map;debug=!1;constructor(e,t){if(super(),J0(e)){const i=e;e=i.context,t=ns.getOrCreate(i.context,i.guid)}else typeof t=="string"&&(t=ns.getOrCreate(e,t));if(e){if(!(e instanceof U))throw new Error("Failed to create NetworkedStreams because context is not an instance of Context")}else throw new Error("Failed to create NetworkedStreams because context is undefined");if(!t)throw new Error("Failed to create NetworkedStreams because peer is undefined");this.context=e,this.peer=t,Te&&(this.debug=!0)}startSendingStream(e){this._sendingStreams.has(e)?console.warn("Received start sending stream with stream that is already being sent"):(this._sendingStreams.set(e,[]),this.updateSendingCalls())}stopSendingStream(e){if(e){const t=this._sendingStreams.get(e);if(t){for(const i of t)i.close();t.length=0}this._sendingStreams.delete(e),t&&this.debug&&this.debugLogCurrentState()}this.updateSendingCalls()}_enabled=!1;get enabled(){return this._enabled}enable(){this._enabled||(this._enabled=!0,this.peer.enable(),this.peer.addEventListener("receive-stream",this.onCallStreamReceived),this.peer.addEventListener("call-ended",this.onCallEnded),this.context.connection.beginListen("peer-user-connected",this.onUserConnected),this.context.connection.beginListen(Q.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(Q.UserJoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(Q.UserLeftRoom,this.onUserLeft),this.context.connection.beginListen(Q.LeftRoom,this.onLeftRoom),this._tickIntervalId=setInterval(this.tick,5e3))}disable(){this._enabled&&(this._enabled=!1,this.peer.disable(),this.peer.removeEventListener("receive-stream",this.onCallStreamReceived),this.peer.removeEventListener("call-ended",this.onCallEnded),this.context.connection.stopListen("peer-user-connected",this.onUserConnected),this.context.connection.stopListen(Q.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(Q.UserJoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(Q.UserLeftRoom,this.onUserLeft),this.context.connection.stopListen(Q.LeftRoom,this.onLeftRoom),this._tickIntervalId!=null&&(clearInterval(this._tickIntervalId),this._tickIntervalId=void 0))}_tickIntervalId;tick=()=>{this.updateSendingCalls()};onJoinedRoom=e=>{this._sendingStreams.size>0&&(this.debug&&console.warn(`${e?.userId?`User ${e.userId}`:"You"} joined room`,e,this._sendingStreams.size),this.updateSendingCalls())};onLeftRoom=e=>{this.debug&&console.warn(`${e?.userId||"You"} left room`,e),this.stopCallsToUsersThatAreNotInTheRoomAnymore(),this.peer.closeAll()};onCallStreamReceived=e=>{this.debug&&console.log("Call with "+e.userId+" started"),this.dispatchEvent({type:"receive-stream",target:this,stream:e.stream,userId:e.userId}),this.debug&&this.debugLogCurrentState()};onCallEnded=e=>{this.debug&&console.log("Call with "+e.userId+" ended"),this.dispatchEvent(e),this.debug&&this.debugLogCurrentState()};onUserConnected=e=>{if(this.peer.id===e.guid){this.debug&&console.log("PEER USER CONNECTED",e.guid,e,this._sendingStreams.size);const t=this._sendingStreams.keys().next().value;this.peer.makeCall(e.peerId,t)}else Te&&console.log("Unknown user connected",e.guid,e.peerId)};onUserLeft=e=>{this.debug&&console.log("User left room: "+e.userId),this.stopCallsToUsersThatAreNotInTheRoomAnymore()};updateSendingCalls(){const e=this.context.connection.connectionId;for(const t of this._sendingStreams.keys()){const i=this._sendingStreams.get(t)||[];for(const n of this.context.connection.usersInRoom()){if(n===e)continue;const o=this.peer.getPeerIdFromUserId(n);if(i.find(a=>a.peerId===o&&a.direction==="outgoing"&&!a.isClosed&&a.stream?.active))Te&&console.debug("Already have a call with user "+n+" / peer "+o);else{const a=this.peer.makeCall(o,t);a&&i.push(a)}}this._sendingStreams.set(t,i)}this.stopCallsToUsersThatAreNotInTheRoomAnymore()}stopCallsToUsersThatAreNotInTheRoomAnymore(){for(const e of this._sendingStreams.keys()){const t=this._sendingStreams.get(e);if(t)for(let i=t.length-1;i>=0;i--){const n=t[i];this.context.connection.userIsInRoom(n.userId)?Te&&(this.context.connection.connectionId===n.userId?console.warn(`You are still in the room [${i}] ${n.userId}`):console.log(`User is still in room [${i}] ${n.userId}`)):(Te&&console.log(`Remove call ${[i]} to user that is not in room anymore ${n.userId}`),n.close(),t.splice(i,1))}}this.peer.updateCalls(),this.debug&&this.debugLogCurrentState()}debugLogCurrentState(){console.warn(`You (${this.context.connection.connectionId}) are currently sending ${this._sendingStreams.size} and receiving ${this.peer.incomingCalls.length} calls (${this.peer.incomingCalls.map(e=>e.userId).join(", ")})`,this.peer.incomingCalls)}}function Cn(s){if(s&&s instanceof MediaStream)for(const e of s.getTracks())e.stop()}var H1=Object.defineProperty,Cm=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&H1(e,t,n),n};const q1="noVoip",X1=w("debugvoip");class to extends k{autoConnect=!0;runInBackground=!0;createMenuButton=!0;debug=!1;_net;_menubutton;awake(){X1&&(this.debug=!0),this.debug&&(console.log("VOIP debugging: press 'v' to toggle mute or 'c' to toggle connect/disconnect"),window.addEventListener("keydown",async e=>{switch(e.key.toLowerCase()){case"v":console.log("MUTE?",!this.isMuted),this.setMuted(!this.isMuted);break;case"c":this.isSending?this.disconnect():this.connect();break}}),window.addEventListener("blur",()=>{console.log("VOIP: MUTE ON BLUR"),this.setMuted(!0)}),window.addEventListener("focus",()=>{console.log("VOIP: UNMUTE ON FOCUS"),this.setMuted(!1)}))}onEnable(){this._net||(this._net=mc.create(this)),this.debug&&(this._net.debug=!0),this._net.addEventListener(Sn.StreamReceived,this.onReceiveStream),this._net.addEventListener(Sn.StreamEnded,this.onStreamEnded),this._net.enable(),this.autoConnect&&this.context.connection.isConnected&&this.connect(),this.context.connection.beginListen(Q.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(Q.LeftRoom,this.onLeftRoom),this.onEnabledChanged(),this.updateButton(),window.addEventListener("visibilitychange",this.onVisibilityChanged)}onDisable(){this._net&&(this._net.stopSendingStream(this._outputStream),this._net.removeEventListener(Sn.StreamReceived,this.onReceiveStream),this._net.removeEventListener(Sn.StreamEnded,this.onStreamEnded),this._net?.disable()),this.context.connection.stopListen(Q.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(Q.LeftRoom,this.onLeftRoom),this.onEnabledChanged(),this.updateButton(),window.removeEventListener("visibilitychange",this.onVisibilityChanged)}onDestroy(){this._menubutton?.remove(),this._menubutton=void 0}_allowSending=!0;_outputStream=null;get isSending(){return this._outputStream!=null&&this._outputStream.active}async connect(e){if(!this._net)return console.error("Cannot connect to voice chat - NetworkedStreams not initialized. Make sure the component is enabled before calling this method."),!1;if(this.context.connection.isConnected){if(!await exports.DeviceUtilities.microphonePermissionsGranted())return console.error("Cannot connect to voice chat - microphone permissions not granted"),this.updateButton(),!1}else return console.error("Cannot connect to voice chat - not connected to server"),this.updateButton(),!1;return this._allowSending=!0,this._net?.stopSendingStream(this._outputStream),Cn(this._outputStream),this._outputStream=await this.getAudioStream(e),this._outputStream?(this.debug&&console.log("VOIP: Got audio stream"),this._net?.startSendingStream(this._outputStream),this.updateButton(),!0):(this.updateButton(),await exports.DeviceUtilities.microphonePermissionsGranted()?console.error("VOIP: Could not get audio stream - please make sure to connect an audio device and grant microphone permissions"):nc("Microphone permissions not granted: Please grant microphone permissions to use voice chat"),(this.debug||A())&&console.log("VOIP: Failed to get audio stream"),!1)}disconnect(e){e?.remember&&(this._allowSending=!1),this._net?.stopSendingStream(this._outputStream),Cn(this._outputStream),this._outputStream=null,this.updateButton()}setMuted(e){const t=this._outputStream?.getAudioTracks();if(t)for(const i of t)i.enabled=!e}get isMuted(){if(this._outputStream===null)return!1;const e=this._outputStream?.getAudioTracks();if(e){for(const t of e)if(!t.enabled)return!0}return!1}async updateButton(){if(this.createMenuButton){if(this._menubutton||(this._menubutton=document.createElement("button"),this._menubutton.addEventListener("click",()=>{this.isSending?this.disconnect({remember:!0}):this.connect(),exports.DeviceUtilities.microphonePermissionsGranted().then(e=>{e||ce("<strong>Microphone permissions not granted</strong>. Please allow your browser to use the microphone to be able to talk. Click on the button on the left side of your browser's address bar to allow microphone permissions.")})})),this._menubutton){this.context.menu.appendChild(this._menubutton),this.activeAndEnabled?this._menubutton.style.display="":this._menubutton.style.display="none",this._menubutton.title=this.isSending?"Click to disable your microphone":"Click to enable your microphone";let e=(this.isSending,""),t=this.isSending?"mic":"mic_off";await exports.DeviceUtilities.microphonePermissionsGranted()||(e="No Permission",t="mic_off",this._menubutton.title="Microphone permissions not granted. Please allow your browser to use the microphone to be able to talk. This can usually be done in the addressbar of the webpage."),this._menubutton.innerText=e,this._menubutton.prepend(ut(t)),this.context.connection.isConnected==!1?this._menubutton.setAttribute("disabled",""):this._menubutton.removeAttribute("disabled")}}else this.activeAndEnabled||this._menubutton?.remove()}getFrequency(e){return this.unsupported_getfrequency||(this.unsupported_getfrequency=!0,A()&&ce("VOIP: getFrequency is currently not supported"),console.warn("VOIP: getFrequency is currently not supported")),null}async getAudioStream(e){if(!navigator.mediaDevices.getUserMedia)return console.error("No getDisplayMedia support"),null;const t=async n=>await navigator.mediaDevices.getUserMedia({audio:n??!0,video:!1}).catch(o=>(console.warn("VOIP failed getting audio stream",o),null)),i=await t(e);if(!i)return null;if(exports.DeviceUtilities.isiOS()&&e?.deviceId===void 0){const o=(await navigator.mediaDevices.enumerateDevices()).find(r=>(r.kind==="audioinput"||r.kind==="audiooutput")&&!r.label.includes("iPhone"));if(o){const r=Object.assign({},e);return r.deviceId=o.deviceId,await t(r)}}return i}onJoinedRoom=async()=>{this.debug&&console.log("VOIP: Joined room"),await An(300),this.autoConnect&&!this.isSending&&this._allowSending&&this.connect()};onLeftRoom=()=>{this.debug&&console.log("VOIP: Left room"),this.disconnect();for(const e of this._incomingStreams.values())Cn(e.srcObject);this._incomingStreams.clear()};_incomingStreams=new Map;onReceiveStream=e=>{const t=e.target.userId,i=e.stream;let n=this._incomingStreams.get(t);n||(n=new Audio,this._incomingStreams.set(t,n)),n.srcObject=i,n.setAttribute("autoplay","true"),tn.registerWaitForInteraction(()=>{n?.play().catch(o=>{console.error("VOIP: Failed to play audio",o)})})};onStreamEnded=e=>{const t=this._incomingStreams.get(e.userId);Cn(t?.srcObject),this._incomingStreams.delete(e.userId)};onEnabledChanged=()=>{for(const e of this._incomingStreams){const t=e[1];t.muted=!this.enabled}};onVisibilityChanged=()=>{if(this.runInBackground)return;const t=!(document.visibilityState==="visible");this.setMuted(t);for(const i of this._incomingStreams){const n=i[1];n.muted=t}}}Cm([f()],to.prototype,"autoConnect");Cm([f()],to.prototype,"runInBackground");Cm([f()],to.prototype,"createMenuButton");var Q1=Object.defineProperty,ov=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&Q1(e,t,n),n};const Y1=w("debugmouth");class gc extends k{idle=[];talking=[];marker=null;voip=null;lastMouthChangeTime=0;mouthChangeLength=0;awake(){setTimeout(()=>{this.voip=x.findObjectOfType(to,this.context),this.marker||(this.marker=x.getComponentInParent(this.gameObject,xe))},3e3)}update(){if(!this.voip||this.context.time.frameCount%10!==0)return;let e=this.marker?.connectionId??null;if(!e){Y1&&(e=null);return}const t=this.voip.getFrequency(e)??0;this.updateLips(t)}updateLips(e){if(this.context.time.time-this.lastMouthChangeTime>this.mouthChangeLength){if(this.mouthChangeLength=.05+Math.random()*.1,this.talking&&this.talking.length>0&&e>30){this.lastMouthChangeTime=this.context.time.time;const t=Math.floor(Math.random()*this.talking.length);this.setMouthShapeActive(this.talking,t)}else if(this.idle.length>0&&this.context.time.time-this.lastMouthChangeTime>.5){this.lastMouthChangeTime=this.context.time.time;const t=Math.floor(Math.random()*this.idle.length);this.setMouthShapeActive(this.idle,t)}}}setMouthShapeActive(e,t){if(e){e!=this.idle?this.idle.map(i=>i.visible=!1):this.talking.map(i=>i.visible=!1);for(let i=0;i<e.length;i++){const n=e[i];n&&(n.visible=i===t)}}}}ov([f(c.Object3D)],gc.prototype,"idle");ov([f(c.Object3D)],gc.prototype,"talking");class Pm extends k{voip=null;marker=null;_startPosition=null;awake(){this.voip=x.findObjectOfType(to,this.context),this.marker=x.getComponentInParent(this.gameObject,xe)}update(){if(!this.voip||!this.marker||this.context.time.frameCount%10!==0)return;const e=this.marker.connectionId,t=this.voip.getFrequency(e);if(t==null)return;this._startPosition||(this._startPosition=this.gameObject.position.clone());const i=t/100;this.gameObject.position.y=this._startPosition.y+i*.07}}var K1=Object.defineProperty,Z1=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&K1(e,t,n),n};const Lr=w("debugxrflags"),rv=w("disablexrflags");rv&&console.warn("XRFlags are disabled");var bn=(s=>(s[s.Never=0]="Never",s[s.Browser=1]="Browser",s[s.AR=2]="AR",s[s.VR=4]="VR",s[s.FirstPerson=8]="FirstPerson",s[s.ThirdPerson=16]="ThirdPerson",s[s.All=4294967295]="All",s))(bn||{});class It{static Global=new It;Mask=17;Has(e){return(this.Mask&e)!==0}Set(e){Lr&&console.warn("Set XR flag state to",e),this.Mask=e,Ei.Apply()}Enable(e){this.Mask|=e,Ei.Apply()}Disable(e){this.Mask&=~e,Ei.Apply()}Toggle(e){this.Mask^=e,Ei.Apply()}EnableAll(){this.Mask=-1,Ei.Apply()}DisableAll(){this.Mask=0,Ei.Apply()}}const av=class Hn extends k{static registry=[];static Apply(){for(const e of this.registry)e.UpdateVisible(It.Global)}static firstApply;static buffer=new It;visibleIn;awake(){Hn.registry.push(this)}onEnable(){Hn.firstApply?this.UpdateVisible(It.Global):(Hn.firstApply=!0,Hn.Apply())}onDestroy(){const e=Hn.registry.indexOf(this);e>=0&&Hn.registry.splice(e,1)}get isOn(){return this.gameObject.visible}UpdateVisible(e=null){if(rv)return;let t;const i=e;if(i&&typeof i=="number"&&(console.assert(typeof i=="number","XRFlag.UpdateVisible: state must be a number",i),Lr&&console.log(i),Hn.buffer.Mask=i,e=Hn.buffer),e instanceof It?(Lr&&console.warn(this.name,"use passed in mask",e.Mask,this.visibleIn),t=e.Has(this.visibleIn)):(Lr&&console.log(this.name,"use global mask"),It.Global.Has(this.visibleIn)),t!==void 0)if(t)Lr&&console.log(this.name,"is visible",this.gameObject.uuid),x.setActive(this.gameObject,!0);else{if(Lr&&console.log(this.name,"is not visible",this.gameObject.uuid),!this.gameObject.visible)return;this.gameObject.visible=!1}}};Z1([f()],av.prototype,"visibleIn");let Ei=av;var J1=Object.defineProperty,Hd=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&J1(e,t,n),n};class nr extends k{eyes=[];lastBlinkTime=0;blinkLength=0;eyesOpen=!0;state=null;awake(){this.state=x.getComponentInParent(this.gameObject,Ei)}update(){if(!this.gameObject||!this.gameObject.visible||!this.eyes||!Array.isArray(this.eyes)||this.eyes.length===0)return;if(this.context.time.time-this.lastBlinkTime>this.blinkLength){if(this.lastBlinkTime=this.context.time.time,this.state&&!this.state.isOn||!this.activeAndEnabled)return;if(this.eyesOpen=!this.eyesOpen,this.blinkLength=Math.random(),this.eyesOpen?(this.blinkLength*=3,this.blinkLength+=.5,Math.random()<.1&&(this.blinkLength=.1+Math.random()*.2)):(this.blinkLength*=Math.random()*.2,this.blinkLength+=.1),Math.random()<.1&&(this.blinkLength*=3),this.blinkLength=Math.max(.2,this.blinkLength),this.blinkLength=Math.min(3,this.blinkLength),this.eyes)for(const t of this.eyes)t&&(t.visible=this.eyesOpen)}}}Hd([f(c.Object3D)],nr.prototype,"eyes");Hd([f()],nr.prototype,"lastBlinkTime");Hd([f()],nr.prototype,"blinkLength");Hd([f()],nr.prototype,"eyesOpen");var eP=Object.defineProperty,Mm=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&eP(e,t,n),n};const qd=class lv extends k{head=null;eyes=null;target=null;brain=null;awake(){this.brain||(this.brain=x.getComponentInParent(this.gameObject,$l)),this.brain||(this.brain=x.addComponent(this.gameObject,$l)),this.brain&&this.target&&(this.brain.controlledTarget=this.target)}vec=new c.Vector3;static forward=new c.Vector3(0,0,1);currentTargetPoint=new c.Vector3;update(){const e=this.target;if(e&&this.head){const t=this.eyes;if(t){const i=X(e);this.currentTargetPoint.lerp(i,this.context.time.deltaTime/.1);const n=X(this.head),o=this.vec.copy(this.currentTargetPoint).sub(n).normalize();if(o.length()<.1)return;const r=lv.forward;if(r.set(0,0,1),r.applyQuaternion(ue(this.head)),r.dot(o)>.45)for(let l=0;l<t.length;l++)t[l].lookAt(this.currentTargetPoint)}}}};Mm([f(c.Object3D)],qd.prototype,"head");Mm([f(c.Object3D)],qd.prototype,"eyes");Mm([f(c.Object3D)],qd.prototype,"target");let Om=qd;var tP=Object.defineProperty,km=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&tP(e,t,n),n};class ma extends k{length=1;depthTest=!0;isGizmo=!1;_axes=null;onEnable(){if(this.isGizmo&&!oc)return;this._axes||(this._axes=new c.AxesHelper(this.length)),this._axes.layers.disableAll(),this._axes.layers.set(this.layer),this.gameObject.add(this._axes);const e=this._axes.material;e&&e.depthTest!==void 0&&(e.depthTest=this.depthTest)}onDisable(){this._axes&&this.gameObject.remove(this._axes)}}km([f()],ma.prototype,"length");km([f()],ma.prototype,"depthTest");km([f()],ma.prototype,"isGizmo");class Rm extends k{from;to;hint;desiredDistance=1;onEnable(){}update(){if(!this.from||!this.to||!this.hint)return;const e=X(this.to).clone(),t=X(this.from).clone(),i=e.distanceTo(t),n=e.clone();n.sub(t);const o=t.clone();o.add(e),o.multiplyScalar(.5);const r=X(this.hint).clone();r.sub(o);const a=new c.Vector3;a.crossVectors(r,n),a.crossVectors(n,a),a.normalize();const l=i*.5,h=Math.max(this.desiredDistance,l),d=Math.sqrt(h*h-l*l),u=a.clone();u.multiplyScalar(d),u.add(o),Ye(this.gameObject,u);const p=o.clone();p.sub(a),this.gameObject.lookAt(p)}}const iP=w("gizmos"),nP=w("debugboxhelper");class nt extends k{box=null;static testBox=new c.Box3;_lastMatrixUpdateFrame=-1;static _position=new c.Vector3;static _size=new c.Vector3(.01,.01,.01);static _emptyObjectSize=new c.Vector3(.01,.01,.01);isInBox(e){if(!e)return;if(this.box||(this.box=new c.Box3),Ht([e],void 0,void 0,nt.testBox),nt.testBox.isEmpty()){const i=X(e,nt._position);nt.testBox.setFromCenterAndSize(i,nt._emptyObjectSize)}this.updateBox();const t=this.box?.intersectsBox(nt.testBox);return t&&nP&&j.DrawWireBox3(nt.testBox,16711680,5),t}intersects(e){return e?this.updateBox(!1).intersectsBox(e):!1}updateBox(e=!1){if(this.box||(this.box=new c.Box3),e||this.context.time.frameCount!=this._lastMatrixUpdateFrame){const t=this._lastMatrixUpdateFrame<0;this._lastMatrixUpdateFrame=this.context.time.frameCount;const i=t,n=X(this.gameObject,nt._position,i),o=Ae(this.gameObject,nt._size);this.box.setFromCenterAndSize(n,o)}return this.box}_helper=null;_color=null;awake(){this._helper=null,this._color=null,this.box=null}showHelper(e=null,t=!1){if(!(!iP&&!t)){if(this._helper){e&&this._color?.set(e),this.gameObject.add(this._helper);return}this._helper=nm(e),this.gameObject.add(this._helper)}}}var sP=Object.defineProperty,Xt=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&sP(e,t,n),n};class Qt extends k{get isCollider(){return!0}attachedRigidbody=null;isTrigger=!1;sharedMaterial;membership=[0];filter;awake(){super.awake(),this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(Ke))}start(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(Ke))}onEnable(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(Ke))}onDisable(){this.context.physics.engine?.removeBody(this)}get body(){return this.context.physics.engine?.getBody(this)}updateProperties=()=>{this.context.physics.engine?.updateProperties(this)};updatePhysicsMaterial(){this.context.physics.engine?.updatePhysicsMaterial(this)}}Xt([f(Ke)],Qt.prototype,"attachedRigidbody");Xt([f()],Qt.prototype,"isTrigger");Xt([f()],Qt.prototype,"sharedMaterial");Xt([f()],Qt.prototype,"membership");Xt([f()],Qt.prototype,"filter");class ga extends Qt{radius=.5;center=new c.Vector3(0,0,0);onEnable(){super.onEnable(),this.context.physics.engine?.addSphereCollider(this),Md(this.gameObject.scale,this.updateProperties)}onDisable(){super.onDisable(),jp(this.gameObject.scale,this.updateProperties)}onValidate(){this.updateProperties()}}Xt([gt(),f()],ga.prototype,"radius");Xt([f(c.Vector3)],ga.prototype,"center");const Em=class cv extends Qt{static add(e,t){const i=ci(e,cv);return i.autoFit(),t?.rigidbody===!0&&ci(e,Ke,{isKinematic:!1}),i}size=new c.Vector3(1,1,1);center=new c.Vector3(0,0,0);onEnable(){super.onEnable(),this.context.physics.engine?.addBoxCollider(this,this.size),Md(this.gameObject.scale,this.updateProperties)}onDisable(){super.onDisable(),jp(this.gameObject.scale,this.updateProperties)}onValidate(){this.updateProperties()}autoFit(e){const t=this.gameObject,i=t.position.clone(),n=t.quaternion.clone(),o=t.scale.clone(),r=t.parent;t.position.set(0,0,0),t.quaternion.set(0,0,0,1),t.scale.set(1,1,1),t.parent=null,t.updateMatrix();const a=Ht([t]);t.position.copy(i),t.quaternion.copy(n),t.scale.copy(o),t.parent=r,e?.debug===!0&&j.DrawWireBox3(a,16768256,20),this.size=a.getSize(new c.Vector3)||new c.Vector3(1,1,1),this.center=a.getCenter(new c.Vector3)||new c.Vector3(0,0,0),this.size.length()<=0&&this.size.set(.01,.01,.01)}};Xt([gt(),f(c.Vector3)],Em.prototype,"size");Xt([f(c.Vector3)],Em.prototype,"center");let Xd=Em;class io extends Qt{sharedMesh;convex=!1;onEnable(){if(super.onEnable(),!this.context.physics.engine)return;this.sharedMesh?.isMesh||(this.gameObject instanceof c.Mesh||this.gameObject instanceof c.Group)&&(this.sharedMesh=this.gameObject);const e=0;if(this.sharedMesh?.isMesh)this.context.physics.engine.addMeshCollider(this,this.sharedMesh,this.convex),ne.NEEDLE_progressive.assignMeshLOD(this.sharedMesh,e).then(t=>{t&&this.activeAndEnabled&&this.context.physics.engine&&this.sharedMesh&&(this.context.physics.engine.removeBody(this),this.sharedMesh.geometry=t,this.context.physics.engine.addMeshCollider(this,this.sharedMesh,this.convex))});else{const t=this.sharedMesh;if(t?.isGroup){console.warn(`MeshCollider mesh is a group "${this.sharedMesh?.name||this.gameObject.name}", adding all children as colliders. This is currently not fully supported (colliders can not be removed from world again)`,this);const i=new Array;for(const n in t.children){const o=t.children[n];o.isMesh&&(this.context.physics.engine.addMeshCollider(this,o,this.convex),i.push(ne.NEEDLE_progressive.assignMeshLOD(o,e)))}Promise.all(i).then(n=>{if(n.some(r=>r)==!1)return;this.context.physics.engine?.removeBody(this);const o=new c.Mesh;for(const r of n)r&&this.activeAndEnabled&&(o.geometry=r,this.context.physics.engine?.addMeshCollider(this,o,this.convex))})}else(A()||w("showcolliders"))&&console.warn(`[MeshCollider] A MeshCollider mesh is assigned to an unknown object on "${this.gameObject.name}", but it's neither a Mesh nor a Group. Please double check that you attached the collider component to the right object and report a bug otherwise!`,this)}}}Xt([f(c.Mesh)],io.prototype,"sharedMesh");Xt([f()],io.prototype,"convex");class as extends Qt{center=new c.Vector3(0,0,0);radius=.5;height=2;onEnable(){super.onEnable(),this.context.physics.engine?.addCapsuleCollider(this,this.height,this.radius)}}Xt([f(c.Vector3)],as.prototype,"center");Xt([f()],as.prototype,"radius");Xt([f()],as.prototype,"height");var oP=Object.defineProperty,hs=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&oP(e,t,n),n};const Zy=w("debugcharactercontroller");class sr extends k{center=new c.Vector3(0,0,0);radius=.5;height=2;_rigidbody=null;get rigidbody(){return this._rigidbody?this._rigidbody:(this._rigidbody=this.gameObject.getComponent(Ke),this._rigidbody||(this._rigidbody=this.gameObject.addComponent(Ke)),this.rigidbody)}_activeGroundCollisions;awake(){this._activeGroundCollisions=new Set}onEnable(){const e=this.rigidbody;let t=this.gameObject.getComponent(as);t||(t=this.gameObject.addComponent(as)),t.center.copy(this.center),t.radius=this.radius,t.height=this.height;const i=new c.Vector3(0,0,1),n=new c.Vector3(1,0,0),o=new c.Vector3(0,1,0),r=this.gameObject.getWorldDirection(new c.Vector3);r.y=0;const a=n.dot(r)<0?-1:1,l=i.angleTo(r)*a;this.gameObject.setRotationFromAxisAngle(o,l),e.lockRotationX=!0,e.lockRotationY=!0,e.lockRotationZ=!0}move(e){this.gameObject.position.add(e)}onCollisionEnter(e){(e.contacts.length==0||e.contacts.some(t=>t.normal.y>.2))&&(this._activeGroundCollisions.add(e),Zy&&console.log(`Collision(${this._activeGroundCollisions.size}): ${e.contacts.map(t=>t.normal.y.toFixed(2)).join(", ")} - ${this.isGrounded}`))}onCollisionExit(e){this._activeGroundCollisions.delete(e),Zy&&console.log(`Collision(${this._activeGroundCollisions.size}) - ${this.isGrounded}`)}get isGrounded(){return this._activeGroundCollisions.size>0}_contactVelocity=new c.Vector3;get contactVelocity(){this._contactVelocity.set(0,0,0);for(const e of this._activeGroundCollisions){const t=this.context.physics.engine?.getLinearVelocity(e.collider);t&&(this._contactVelocity.x+=t.x,this._contactVelocity.y+=t.y,this._contactVelocity.z+=t.z)}return this._contactVelocity}}hs([f(c.Vector3)],sr.prototype,"center");hs([f()],sr.prototype,"radius");hs([f()],sr.prototype,"height");class ds extends k{controller;movementSpeed=2;rotationSpeed=2;jumpForce=1;doubleJumpForce=2;animator;lookForward=!0;awake(){this._currentRotation=new c.Quaternion}update(){const e=this.context.input;e.isKeyPressed("KeyW")?this.moveInput.y+=1:e.isKeyPressed("KeyS")&&(this.moveInput.y-=1),e.isKeyPressed("KeyD")?this.lookInput.x+=1:e.isKeyPressed("KeyA")&&(this.lookInput.x-=1),this.jumpInput||=e.isKeyDown("Space")}move(e){this.moveInput.add(e)}look(e){this.lookInput.add(e)}jump(){this.jumpInput=!0}lookInput=new c.Vector2(0,0);moveInput=new c.Vector2(0,0);jumpInput=!1;onBeforeRender(){this.handleInput(this.moveInput,this.lookInput,this.jumpInput),this.lookInput.set(0,0),this.moveInput.set(0,0),this.jumpInput=!1}_currentSpeed=new c.Vector3(0,0,0);_currentAngularSpeed=new c.Vector3(0,0,0);_temp=new c.Vector3(0,0,0);_jumpCount=0;_currentRotation;handleInput(e,t,i){if(this.controller?.isGrounded&&(this._jumpCount=0,this.doubleJumpForce>0&&this.animator?.setBool("doubleJump",!1)),this._currentSpeed.z+=e.y*this.movementSpeed*this.context.time.deltaTime,this.animator?.setBool("running",e.length()>.01),this.animator?.setBool("jumping",this.controller?.isGrounded===!0&&i),this._temp.copy(this._currentSpeed),this._temp.applyQuaternion(this.gameObject.quaternion),this.controller?this.controller.move(this._temp):this.gameObject.position.add(this._temp),this._currentAngularSpeed.y+=I.toRadians(-t.x*this.rotationSpeed)*this.context.time.deltaTime,this.lookForward&&Math.abs(this._currentAngularSpeed.y)<.01){const n=this.context.mainCameraComponent.forward;n.y=0,n.normalize(),this._currentRotation.setFromUnitVectors(new c.Vector3(0,0,1),n),this.gameObject.quaternion.slerp(this._currentRotation,this.context.time.deltaTime*10)}if(this.gameObject.rotateY(this._currentAngularSpeed.y),this._currentSpeed.multiplyScalar(1-this.context.time.deltaTime*10),this._currentAngularSpeed.y*=1-this.context.time.deltaTime*10,this.controller&&i&&this.jumpForce>0){let n=this.controller?.isGrounded;if(this.doubleJumpForce>0&&!this.controller?.isGrounded&&this._jumpCount===1&&(n=!0,this.animator?.setBool("doubleJump",!0)),n){this._jumpCount+=1;const o=this.controller.rigidbody,r=this._jumpCount===2?this.doubleJumpForce:this.jumpForce;o.applyImpulse(new c.Vector3(0,1,0).multiplyScalar(r))}}if(this.controller){const n=this.controller?.rigidbody.getVelocity().y;if(n<-1){this._raycastOptions.ray||(this._raycastOptions.ray=new c.Ray),this._raycastOptions.ray.origin.copy(X(this.gameObject)),this._raycastOptions.ray.direction.set(0,-1,0);const o=this.layer;this.gameObject.layers.disableAll(),this.gameObject.layers.set(2);const r=this.context.physics.raycast(this._raycastOptions);this.gameObject.layers.set(o),(r.length&&r[0].distance>2||n<-10)&&this.animator?.setBool("falling",!0)}else this.animator?.setBool("falling",!1)}}_raycastOptions=new eo}hs([f(sr)],ds.prototype,"controller");hs([f()],ds.prototype,"movementSpeed");hs([f()],ds.prototype,"rotationSpeed");hs([f()],ds.prototype,"jumpForce");hs([f()],ds.prototype,"doubleJumpForce");hs([f(mt)],ds.prototype,"animator");var rP=Object.defineProperty,ya=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&rP(e,t,n),n};const Na=w("debugcontactshadows");ym(s=>{const e=s.domElement.getAttribute("contactshadows")||s.domElement.getAttribute("contact-shadows");if(e!=null&&e!="0"&&e!="false"){console.debug("Auto-creating ContactShadows because of `contactshadows` attribute");const t=yc.auto(s),i=parseFloat(e);isNaN(i)||(t.opacity=i,t.darkness=i)}});const or=class cl extends k{static _instances=new Map;static auto(e){if(e||(e=U.Current),!e)throw new Error("No context provided and no current context set.");let t=this._instances.get(e);if(!t||t.destroyed){const i=new c.Object3D;t=ci(i,cl,{autoFit:!1,occludeBelowGround:!1}),this._instances.set(e,t)}return e.scene.add(t.gameObject),t.fitShadows(),t}autoFit=!1;darkness=.5;opacity=.5;blur=4;occludeBelowGround=!1;backfaceShadows=!0;minSize;manualUpdate=!1;set needsUpdate(e){this._needsUpdate=e}get needsUpdate(){return this._needsUpdate}_needsUpdate=!1;shadowsRoot=new c.Object3D;shadowCamera;shadowGroup=new c.Group;renderTarget;renderTargetBlur;plane;occluderMesh;blurPlane;depthMaterial;horizontalBlurMaterial;verticalBlurMaterial;textureSize=512;fitShadows(){Na&&console.warn("Fitting shadows to scene"),Qh(this.shadowsRoot,!1);const e=Ht(this.context.scene.children,[this.shadowsRoot]),t=Math.max(1,this.blur/32),i=e.max.x-e.min.x,n=e.max.z-e.min.z;e.expandByVector(new c.Vector3(t*i,0,t*n)),Na&&j.DrawWireBox3(e,16776960,60),this.gameObject.parent&&e.applyMatrix4(this.gameObject.parent.matrixWorld.clone().invert());const o=e.min,r=Math.max(1e-5,(e.max.y-o.y)*.002);e.max.y+=r,this.shadowsRoot.position.set((o.x+e.max.x)/2,o.y-r,(o.z+e.max.z)/2),this.shadowsRoot.scale.set(e.max.x-o.x,e.max.y-o.y,e.max.z-o.z),this.applyMinSize(),this.shadowsRoot.matrixWorldNeedsUpdate=!0,Na&&console.log("Fitted shadows to scene",this.shadowsRoot.scale.clone())}awake(){cl._instances.set(this.context,this),this.shadowsRoot.hideFlags=Gd.DontExport,Qh(this.shadowsRoot,!1)}start(){Na&&console.log("Create ContactShadows on "+this.gameObject.name,this),this.gameObject.add(this.shadowsRoot),this.shadowsRoot.add(this.shadowGroup),this.renderTarget=new c.WebGLRenderTarget(this.textureSize,this.textureSize),this.renderTarget.texture.generateMipmaps=!1,this.renderTargetBlur=new c.WebGLRenderTarget(this.textureSize,this.textureSize),this.renderTargetBlur.texture.generateMipmaps=!1;const e=new c.PlaneGeometry(1,1).rotateX(Math.PI/2);this.gameObject instanceof c.Mesh&&(console.warn("ContactShadows can not be added to a Mesh. Please add it to a Group or an empty Object"),Jn(this.gameObject,!1));const t=new c.MeshBasicMaterial({map:this.renderTarget.texture,opacity:this.opacity,color:0,transparent:!0,depthWrite:!1,side:c.FrontSide});this.plane=new c.Mesh(e,t),this.plane.scale.y=-1,this.plane.layers.set(2),this.shadowsRoot.add(this.plane),this.plane&&(this.plane.renderOrder=1),this.occluderMesh=new c.Mesh(this.plane.geometry,new c.MeshBasicMaterial({depthWrite:!0,stencilWrite:!0,colorWrite:!1,side:c.BackSide})).translateY(-1e-4),this.occluderMesh.renderOrder=-100,this.occluderMesh.layers.set(2),this.shadowsRoot.add(this.occluderMesh),this.blurPlane=new c.Mesh(e),this.blurPlane.visible=!1,this.shadowGroup.add(this.blurPlane);const i=0,n=1;this.shadowCamera=new c.OrthographicCamera(-1/2,1/2,1/2,-1/2,i,n),this.shadowCamera.layers.enableAll(),this.shadowCamera.rotation.x=Math.PI/2,this.shadowGroup.add(this.shadowCamera),this.depthMaterial=new c.MeshDepthMaterial,this.depthMaterial.userData.darkness={value:this.darkness},this.depthMaterial.blending=c.CustomBlending,this.depthMaterial.blendEquation=c.MaxEquation,this.depthMaterial.onBeforeCompile=o=>{this.depthMaterial&&(o.uniforms.darkness=this.depthMaterial.userData.darkness,o.fragmentShader=`
955
+ Incoming:`,this._incomingCalls),o}else Oe&&console.error("Failed to make call",e,t,this._peer)}closeAll(){for(const e of this._incomingCalls)e.close();for(const e of this._outgoingCalls)e.close();this.updateCalls()}updateCalls=()=>{for(let e=this._incomingCalls.length-1;e>=0;e--){const t=this._incomingCalls[e];t.isClosed&&!t.isOpening&&this._incomingCalls.splice(e,1)}for(let e=this._outgoingCalls.length-1;e>=0;e--){const t=this._outgoingCalls[e];let i=!1;t.isClosed&&!t.isOpening&&(t.stream?.active?Oe&&console.warn("!!! Stream is still active, don't remove call",t.userId,"Your id: "+this.context.connection.connectionId):(Oe&&console.warn("!!! Remove closed call",t.userId),i=!0)),this.context.connection.userIsInRoom(t.userId)===!1&&(Oe&&console.warn("!!! User is not in room anymore, remove call",t.userId),i=!0),i&&(t.close(),this._outgoingCalls.splice(e,1))}};get peer(){return this._peer}get incomingCalls(){return this._incomingCalls}id;context;_incomingCalls=[];_outgoingCalls=[];_peer;constructor(e,t){super(),this.context=e,this.id=t,this.setupPeer();const i=Object.getOwnPropertyDescriptor(navigator,"getUserMedia")?.writable;try{i?navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia:Oe&&console.warn("[PeerJs] getUserMedia is not writable")}catch(n){Oe&&console.error("[PeerJs] Error setting getUserMedia",n)}}_enabled=!1;_enabledPeer=!1;onConnectRoomFn=this.onConnectRoom.bind(this);enable(){this._enabled||(this._enabled=!0,this.context.connection.beginListen(Q.JoinedRoom,this.onConnectRoomFn),this.subscribePeerEvents())}disable(){this._enabled&&(this._enabled=!1,this.context.connection.stopListen(Q.JoinedRoom,this.onConnectRoomFn),this.unsubscribePeerEvents())}onConnectRoom(){this.setupPeer()}setupPeer(){if(this.context.connection.connectionId&&!this._enabledPeer){if(this._enabledPeer=!0,!this._peer){const e=this.getMyPeerId();e?this._peer=Ab(e):console.error("Failed to setup peerjs because we dont have a connection id",this.context.connection.connectionId)}this._enabled&&this.subscribePeerEvents()}}subscribePeerEvents(){this._peer&&(this._peer.on("open",this.onPeerConnect),this._peer.on("close",this.onPeerClose),this._peer.on("call",this.onPeerReceivingCall),this._peer.on("disconnected",this.onPeerDisconnected),this._peer.on("error",this.onPeerError))}unsubscribePeerEvents(){this._peer&&(this._peer.off("open",this.onPeerConnect),this._peer.off("close",this.onPeerClose),this._peer.off("call",this.onPeerReceivingCall),this._peer.off("disconnected",this.onPeerDisconnected),this._peer.off("error",this.onPeerError))}onPeerConnect=e=>{if(Oe&&console.log("PEER opened as",e),e===null){console.error("Peer connection failed",e);return}this.context.connection.send("peer-user-connected",new W1(this,e))};onPeerClose=()=>{Oe&&console.log("PEER closed"),this.updateCalls()};onPeerDisconnected=()=>{Oe&&console.log("PEER disconnected"),this.updateCalls()};onPeerError=e=>{Oe&&console.error("PEER error",e)};onPeerReceivingCall=e=>{e.answer(void 0,{sdpTransform:t=>Ky(t)}),this.registerCall(e,"incoming",null)};registerCall(e,t,i){const n=e.metadata;(!n||!n.userId)&&console.error("Missing call metadata",e);const o=n.userId;t==="incoming"&&Oe?console.warn("← Receive call from",e.metadata,e.connectionId):Oe&&console.warn("→ Make call to",e.metadata);const r=t==="incoming"?this._incomingCalls:this._outgoingCalls,a=new G1(o,e,t,i);return r.push(a),e.on("error",l=>{console.error("Call error",l)}),e.on("close",()=>{Oe&&console.log("Call ended",e.metadata);const l=r.indexOf(a);l!==-1&&r.splice(l,1),a.close(),this.dispatchEvent(new Sm(o,t))}),a.addEventListener("call-ended",l=>{this.dispatchEvent(l)}),t==="incoming"&&(a.addEventListener("receive-stream",l=>{this.dispatchEvent(l)}),e.on("stream",()=>{Oe&&console.log("Received stream for call",e.metadata);let l=0;const h=setInterval(()=>{const d=l===0;!a.isOpen&&d&&(Oe&&console.warn("Close call because stream is not active",e.metadata),l+=1,clearInterval(h),a.close())},2e3)})),a}}class mc extends c.EventDispatcher{static create(e,t){const i=ns.getOrCreate(e.context,t||e.context.connection.connectionId||e.guid);return new mc(e.context,i)}context;peer;_sendingStreams=new Map;debug=!1;constructor(e,t){if(super(),J0(e)){const i=e;e=i.context,t=ns.getOrCreate(i.context,i.guid)}else typeof t=="string"&&(t=ns.getOrCreate(e,t));if(e){if(!(e instanceof U))throw new Error("Failed to create NetworkedStreams because context is not an instance of Context")}else throw new Error("Failed to create NetworkedStreams because context is undefined");if(!t)throw new Error("Failed to create NetworkedStreams because peer is undefined");this.context=e,this.peer=t,Oe&&(this.debug=!0)}startSendingStream(e){this._sendingStreams.has(e)?console.warn("Received start sending stream with stream that is already being sent"):(this._sendingStreams.set(e,[]),this.updateSendingCalls())}stopSendingStream(e){if(e){const t=this._sendingStreams.get(e);if(t){for(const i of t)i.close();t.length=0}this._sendingStreams.delete(e),t&&this.debug&&this.debugLogCurrentState()}this.updateSendingCalls()}_enabled=!1;get enabled(){return this._enabled}enable(){this._enabled||(this._enabled=!0,this.peer.enable(),this.peer.addEventListener("receive-stream",this.onCallStreamReceived),this.peer.addEventListener("call-ended",this.onCallEnded),this.context.connection.beginListen("peer-user-connected",this.onUserConnected),this.context.connection.beginListen(Q.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(Q.UserJoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(Q.UserLeftRoom,this.onUserLeft),this.context.connection.beginListen(Q.LeftRoom,this.onLeftRoom),this._tickIntervalId=setInterval(this.tick,5e3))}disable(){this._enabled&&(this._enabled=!1,this.peer.disable(),this.peer.removeEventListener("receive-stream",this.onCallStreamReceived),this.peer.removeEventListener("call-ended",this.onCallEnded),this.context.connection.stopListen("peer-user-connected",this.onUserConnected),this.context.connection.stopListen(Q.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(Q.UserJoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(Q.UserLeftRoom,this.onUserLeft),this.context.connection.stopListen(Q.LeftRoom,this.onLeftRoom),this._tickIntervalId!=null&&(clearInterval(this._tickIntervalId),this._tickIntervalId=void 0))}_tickIntervalId;tick=()=>{this.updateSendingCalls()};onJoinedRoom=e=>{this._sendingStreams.size>0&&(this.debug&&console.warn(`${e?.userId?`User ${e.userId}`:"You"} joined room`,e,this._sendingStreams.size),this.updateSendingCalls())};onLeftRoom=e=>{this.debug&&console.warn(`${e?.userId||"You"} left room`,e),this.stopCallsToUsersThatAreNotInTheRoomAnymore(),this.peer.closeAll()};onCallStreamReceived=e=>{this.debug&&console.log("Call with "+e.userId+" started"),this.dispatchEvent({type:"receive-stream",target:this,stream:e.stream,userId:e.userId}),this.debug&&this.debugLogCurrentState()};onCallEnded=e=>{this.debug&&console.log("Call with "+e.userId+" ended"),this.dispatchEvent(e),this.debug&&this.debugLogCurrentState()};onUserConnected=e=>{if(this.peer.id===e.guid){this.debug&&console.log("PEER USER CONNECTED",e.guid,e,this._sendingStreams.size);const t=this._sendingStreams.keys().next().value;this.peer.makeCall(e.peerId,t)}else Oe&&console.log("Unknown user connected",e.guid,e.peerId)};onUserLeft=e=>{this.debug&&console.log("User left room: "+e.userId),this.stopCallsToUsersThatAreNotInTheRoomAnymore()};updateSendingCalls(){const e=this.context.connection.connectionId;for(const t of this._sendingStreams.keys()){const i=this._sendingStreams.get(t)||[];for(const n of this.context.connection.usersInRoom()){if(n===e)continue;const o=this.peer.getPeerIdFromUserId(n);if(i.find(a=>a.peerId===o&&a.direction==="outgoing"&&!a.isClosed&&a.stream?.active))Oe&&console.debug("Already have a call with user "+n+" / peer "+o);else{const a=this.peer.makeCall(o,t);a&&i.push(a)}}this._sendingStreams.set(t,i)}this.stopCallsToUsersThatAreNotInTheRoomAnymore()}stopCallsToUsersThatAreNotInTheRoomAnymore(){for(const e of this._sendingStreams.keys()){const t=this._sendingStreams.get(e);if(t)for(let i=t.length-1;i>=0;i--){const n=t[i];this.context.connection.userIsInRoom(n.userId)?Oe&&(this.context.connection.connectionId===n.userId?console.warn(`You are still in the room [${i}] ${n.userId}`):console.log(`User is still in room [${i}] ${n.userId}`)):(Oe&&console.log(`Remove call ${[i]} to user that is not in room anymore ${n.userId}`),n.close(),t.splice(i,1))}}this.peer.updateCalls(),this.debug&&this.debugLogCurrentState()}debugLogCurrentState(){console.warn(`You (${this.context.connection.connectionId}) are currently sending ${this._sendingStreams.size} and receiving ${this.peer.incomingCalls.length} calls (${this.peer.incomingCalls.map(e=>e.userId).join(", ")})`,this.peer.incomingCalls)}}function Cn(s){if(s&&s instanceof MediaStream)for(const e of s.getTracks())e.stop()}var H1=Object.defineProperty,Cm=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&H1(e,t,n),n};const q1="noVoip",X1=w("debugvoip");class to extends k{autoConnect=!0;runInBackground=!0;createMenuButton=!0;debug=!1;_net;_menubutton;awake(){X1&&(this.debug=!0),this.debug&&(console.log("VOIP debugging: press 'v' to toggle mute or 'c' to toggle connect/disconnect"),window.addEventListener("keydown",async e=>{switch(e.key.toLowerCase()){case"v":console.log("MUTE?",!this.isMuted),this.setMuted(!this.isMuted);break;case"c":this.isSending?this.disconnect():this.connect();break}}),window.addEventListener("blur",()=>{console.log("VOIP: MUTE ON BLUR"),this.setMuted(!0)}),window.addEventListener("focus",()=>{console.log("VOIP: UNMUTE ON FOCUS"),this.setMuted(!1)}))}onEnable(){this._net||(this._net=mc.create(this)),this.debug&&(this._net.debug=!0),this._net.addEventListener(Sn.StreamReceived,this.onReceiveStream),this._net.addEventListener(Sn.StreamEnded,this.onStreamEnded),this._net.enable(),this.autoConnect&&this.context.connection.isConnected&&this.connect(),this.context.connection.beginListen(Q.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(Q.LeftRoom,this.onLeftRoom),this.onEnabledChanged(),this.updateButton(),window.addEventListener("visibilitychange",this.onVisibilityChanged)}onDisable(){this._net&&(this._net.stopSendingStream(this._outputStream),this._net.removeEventListener(Sn.StreamReceived,this.onReceiveStream),this._net.removeEventListener(Sn.StreamEnded,this.onStreamEnded),this._net?.disable()),this.context.connection.stopListen(Q.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(Q.LeftRoom,this.onLeftRoom),this.onEnabledChanged(),this.updateButton(),window.removeEventListener("visibilitychange",this.onVisibilityChanged)}onDestroy(){this._menubutton?.remove(),this._menubutton=void 0}_allowSending=!0;_outputStream=null;get isSending(){return this._outputStream!=null&&this._outputStream.active}async connect(e){if(!this._net)return console.error("Cannot connect to voice chat - NetworkedStreams not initialized. Make sure the component is enabled before calling this method."),!1;if(this.context.connection.isConnected){if(!await exports.DeviceUtilities.microphonePermissionsGranted())return console.error("Cannot connect to voice chat - microphone permissions not granted"),this.updateButton(),!1}else return console.error("Cannot connect to voice chat - not connected to server"),this.updateButton(),!1;return this._allowSending=!0,this._net?.stopSendingStream(this._outputStream),Cn(this._outputStream),this._outputStream=await this.getAudioStream(e),this._outputStream?(this.debug&&console.log("VOIP: Got audio stream"),this._net?.startSendingStream(this._outputStream),this.updateButton(),!0):(this.updateButton(),await exports.DeviceUtilities.microphonePermissionsGranted()?console.error("VOIP: Could not get audio stream - please make sure to connect an audio device and grant microphone permissions"):nc("Microphone permissions not granted: Please grant microphone permissions to use voice chat"),(this.debug||A())&&console.log("VOIP: Failed to get audio stream"),!1)}disconnect(e){e?.remember&&(this._allowSending=!1),this._net?.stopSendingStream(this._outputStream),Cn(this._outputStream),this._outputStream=null,this.updateButton()}setMuted(e){const t=this._outputStream?.getAudioTracks();if(t)for(const i of t)i.enabled=!e}get isMuted(){if(this._outputStream===null)return!1;const e=this._outputStream?.getAudioTracks();if(e){for(const t of e)if(!t.enabled)return!0}return!1}async updateButton(){if(this.createMenuButton){if(this._menubutton||(this._menubutton=document.createElement("button"),this._menubutton.addEventListener("click",()=>{this.isSending?this.disconnect({remember:!0}):this.connect(),exports.DeviceUtilities.microphonePermissionsGranted().then(e=>{e||ce("<strong>Microphone permissions not granted</strong>. Please allow your browser to use the microphone to be able to talk. Click on the button on the left side of your browser's address bar to allow microphone permissions.")})})),this._menubutton){this.context.menu.appendChild(this._menubutton),this.activeAndEnabled?this._menubutton.style.display="":this._menubutton.style.display="none",this._menubutton.title=this.isSending?"Click to disable your microphone":"Click to enable your microphone";let e=(this.isSending,""),t=this.isSending?"mic":"mic_off";await exports.DeviceUtilities.microphonePermissionsGranted()||(e="No Permission",t="mic_off",this._menubutton.title="Microphone permissions not granted. Please allow your browser to use the microphone to be able to talk. This can usually be done in the addressbar of the webpage."),this._menubutton.innerText=e,this._menubutton.prepend(ut(t)),this.context.connection.isConnected==!1?this._menubutton.setAttribute("disabled",""):this._menubutton.removeAttribute("disabled")}}else this.activeAndEnabled||this._menubutton?.remove()}getFrequency(e){return this.unsupported_getfrequency||(this.unsupported_getfrequency=!0,A()&&ce("VOIP: getFrequency is currently not supported"),console.warn("VOIP: getFrequency is currently not supported")),null}async getAudioStream(e){if(!navigator.mediaDevices.getUserMedia)return console.error("No getDisplayMedia support"),null;const t=async n=>await navigator.mediaDevices.getUserMedia({audio:n??!0,video:!1}).catch(o=>(console.warn("VOIP failed getting audio stream",o),null)),i=await t(e);if(!i)return null;if(exports.DeviceUtilities.isiOS()&&e?.deviceId===void 0){const o=(await navigator.mediaDevices.enumerateDevices()).find(r=>(r.kind==="audioinput"||r.kind==="audiooutput")&&!r.label.includes("iPhone"));if(o){const r=Object.assign({},e);return r.deviceId=o.deviceId,await t(r)}}return i}onJoinedRoom=async()=>{this.debug&&console.log("VOIP: Joined room"),await An(300),this.autoConnect&&!this.isSending&&this._allowSending&&this.connect()};onLeftRoom=()=>{this.debug&&console.log("VOIP: Left room"),this.disconnect();for(const e of this._incomingStreams.values())Cn(e.srcObject);this._incomingStreams.clear()};_incomingStreams=new Map;onReceiveStream=e=>{const t=e.target.userId,i=e.stream;let n=this._incomingStreams.get(t);n||(n=new Audio,this._incomingStreams.set(t,n)),n.srcObject=i,n.setAttribute("autoplay","true"),tn.registerWaitForInteraction(()=>{n?.play().catch(o=>{console.error("VOIP: Failed to play audio",o)})})};onStreamEnded=e=>{const t=this._incomingStreams.get(e.userId);Cn(t?.srcObject),this._incomingStreams.delete(e.userId)};onEnabledChanged=()=>{for(const e of this._incomingStreams){const t=e[1];t.muted=!this.enabled}};onVisibilityChanged=()=>{if(this.runInBackground)return;const t=!(document.visibilityState==="visible");this.setMuted(t);for(const i of this._incomingStreams){const n=i[1];n.muted=t}}}Cm([f()],to.prototype,"autoConnect");Cm([f()],to.prototype,"runInBackground");Cm([f()],to.prototype,"createMenuButton");var Q1=Object.defineProperty,ov=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&Q1(e,t,n),n};const Y1=w("debugmouth");class gc extends k{idle=[];talking=[];marker=null;voip=null;lastMouthChangeTime=0;mouthChangeLength=0;awake(){setTimeout(()=>{this.voip=x.findObjectOfType(to,this.context),this.marker||(this.marker=x.getComponentInParent(this.gameObject,xe))},3e3)}update(){if(!this.voip||this.context.time.frameCount%10!==0)return;let e=this.marker?.connectionId??null;if(!e){Y1&&(e=null);return}const t=this.voip.getFrequency(e)??0;this.updateLips(t)}updateLips(e){if(this.context.time.time-this.lastMouthChangeTime>this.mouthChangeLength){if(this.mouthChangeLength=.05+Math.random()*.1,this.talking&&this.talking.length>0&&e>30){this.lastMouthChangeTime=this.context.time.time;const t=Math.floor(Math.random()*this.talking.length);this.setMouthShapeActive(this.talking,t)}else if(this.idle.length>0&&this.context.time.time-this.lastMouthChangeTime>.5){this.lastMouthChangeTime=this.context.time.time;const t=Math.floor(Math.random()*this.idle.length);this.setMouthShapeActive(this.idle,t)}}}setMouthShapeActive(e,t){if(e){e!=this.idle?this.idle.map(i=>i.visible=!1):this.talking.map(i=>i.visible=!1);for(let i=0;i<e.length;i++){const n=e[i];n&&(n.visible=i===t)}}}}ov([f(c.Object3D)],gc.prototype,"idle");ov([f(c.Object3D)],gc.prototype,"talking");class Pm extends k{voip=null;marker=null;_startPosition=null;awake(){this.voip=x.findObjectOfType(to,this.context),this.marker=x.getComponentInParent(this.gameObject,xe)}update(){if(!this.voip||!this.marker||this.context.time.frameCount%10!==0)return;const e=this.marker.connectionId,t=this.voip.getFrequency(e);if(t==null)return;this._startPosition||(this._startPosition=this.gameObject.position.clone());const i=t/100;this.gameObject.position.y=this._startPosition.y+i*.07}}var K1=Object.defineProperty,Z1=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&K1(e,t,n),n};const Lr=w("debugxrflags"),rv=w("disablexrflags");rv&&console.warn("XRFlags are disabled");var bn=(s=>(s[s.Never=0]="Never",s[s.Browser=1]="Browser",s[s.AR=2]="AR",s[s.VR=4]="VR",s[s.FirstPerson=8]="FirstPerson",s[s.ThirdPerson=16]="ThirdPerson",s[s.All=4294967295]="All",s))(bn||{});class It{static Global=new It;Mask=17;Has(e){return(this.Mask&e)!==0}Set(e){Lr&&console.warn("Set XR flag state to",e),this.Mask=e,Ei.Apply()}Enable(e){this.Mask|=e,Ei.Apply()}Disable(e){this.Mask&=~e,Ei.Apply()}Toggle(e){this.Mask^=e,Ei.Apply()}EnableAll(){this.Mask=-1,Ei.Apply()}DisableAll(){this.Mask=0,Ei.Apply()}}const av=class Hn extends k{static registry=[];static Apply(){for(const e of this.registry)e.UpdateVisible(It.Global)}static firstApply;static buffer=new It;visibleIn;awake(){Hn.registry.push(this)}onEnable(){Hn.firstApply?this.UpdateVisible(It.Global):(Hn.firstApply=!0,Hn.Apply())}onDestroy(){const e=Hn.registry.indexOf(this);e>=0&&Hn.registry.splice(e,1)}get isOn(){return this.gameObject.visible}UpdateVisible(e=null){if(rv)return;let t;const i=e;if(i&&typeof i=="number"&&(console.assert(typeof i=="number","XRFlag.UpdateVisible: state must be a number",i),Lr&&console.log(i),Hn.buffer.Mask=i,e=Hn.buffer),e instanceof It?(Lr&&console.warn(this.name,"use passed in mask",e.Mask,this.visibleIn),t=e.Has(this.visibleIn)):(Lr&&console.log(this.name,"use global mask"),It.Global.Has(this.visibleIn)),t!==void 0)if(t)Lr&&console.log(this.name,"is visible",this.gameObject.uuid),x.setActive(this.gameObject,!0);else{if(Lr&&console.log(this.name,"is not visible",this.gameObject.uuid),!this.gameObject.visible)return;this.gameObject.visible=!1}}};Z1([f()],av.prototype,"visibleIn");let Ei=av;var J1=Object.defineProperty,Hd=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&J1(e,t,n),n};class nr extends k{eyes=[];lastBlinkTime=0;blinkLength=0;eyesOpen=!0;state=null;awake(){this.state=x.getComponentInParent(this.gameObject,Ei)}update(){if(!this.gameObject||!this.gameObject.visible||!this.eyes||!Array.isArray(this.eyes)||this.eyes.length===0)return;if(this.context.time.time-this.lastBlinkTime>this.blinkLength){if(this.lastBlinkTime=this.context.time.time,this.state&&!this.state.isOn||!this.activeAndEnabled)return;if(this.eyesOpen=!this.eyesOpen,this.blinkLength=Math.random(),this.eyesOpen?(this.blinkLength*=3,this.blinkLength+=.5,Math.random()<.1&&(this.blinkLength=.1+Math.random()*.2)):(this.blinkLength*=Math.random()*.2,this.blinkLength+=.1),Math.random()<.1&&(this.blinkLength*=3),this.blinkLength=Math.max(.2,this.blinkLength),this.blinkLength=Math.min(3,this.blinkLength),this.eyes)for(const t of this.eyes)t&&(t.visible=this.eyesOpen)}}}Hd([f(c.Object3D)],nr.prototype,"eyes");Hd([f()],nr.prototype,"lastBlinkTime");Hd([f()],nr.prototype,"blinkLength");Hd([f()],nr.prototype,"eyesOpen");var eP=Object.defineProperty,Mm=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&eP(e,t,n),n};const qd=class lv extends k{head=null;eyes=null;target=null;brain=null;awake(){this.brain||(this.brain=x.getComponentInParent(this.gameObject,$l)),this.brain||(this.brain=x.addComponent(this.gameObject,$l)),this.brain&&this.target&&(this.brain.controlledTarget=this.target)}vec=new c.Vector3;static forward=new c.Vector3(0,0,1);currentTargetPoint=new c.Vector3;update(){const e=this.target;if(e&&this.head){const t=this.eyes;if(t){const i=X(e);this.currentTargetPoint.lerp(i,this.context.time.deltaTime/.1);const n=X(this.head),o=this.vec.copy(this.currentTargetPoint).sub(n).normalize();if(o.length()<.1)return;const r=lv.forward;if(r.set(0,0,1),r.applyQuaternion(ue(this.head)),r.dot(o)>.45)for(let l=0;l<t.length;l++)t[l].lookAt(this.currentTargetPoint)}}}};Mm([f(c.Object3D)],qd.prototype,"head");Mm([f(c.Object3D)],qd.prototype,"eyes");Mm([f(c.Object3D)],qd.prototype,"target");let Om=qd;var tP=Object.defineProperty,km=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&tP(e,t,n),n};class ma extends k{length=1;depthTest=!0;isGizmo=!1;_axes=null;onEnable(){if(this.isGizmo&&!oc)return;this._axes||(this._axes=new c.AxesHelper(this.length)),this._axes.layers.disableAll(),this._axes.layers.set(this.layer),this.gameObject.add(this._axes);const e=this._axes.material;e&&e.depthTest!==void 0&&(e.depthTest=this.depthTest)}onDisable(){this._axes&&this.gameObject.remove(this._axes)}}km([f()],ma.prototype,"length");km([f()],ma.prototype,"depthTest");km([f()],ma.prototype,"isGizmo");class Rm extends k{from;to;hint;desiredDistance=1;onEnable(){}update(){if(!this.from||!this.to||!this.hint)return;const e=X(this.to).clone(),t=X(this.from).clone(),i=e.distanceTo(t),n=e.clone();n.sub(t);const o=t.clone();o.add(e),o.multiplyScalar(.5);const r=X(this.hint).clone();r.sub(o);const a=new c.Vector3;a.crossVectors(r,n),a.crossVectors(n,a),a.normalize();const l=i*.5,h=Math.max(this.desiredDistance,l),d=Math.sqrt(h*h-l*l),u=a.clone();u.multiplyScalar(d),u.add(o),Ye(this.gameObject,u);const p=o.clone();p.sub(a),this.gameObject.lookAt(p)}}const iP=w("gizmos"),nP=w("debugboxhelper");class nt extends k{box=null;static testBox=new c.Box3;_lastMatrixUpdateFrame=-1;static _position=new c.Vector3;static _size=new c.Vector3(.01,.01,.01);static _emptyObjectSize=new c.Vector3(.01,.01,.01);isInBox(e){if(!e)return;if(this.box||(this.box=new c.Box3),Ht([e],void 0,void 0,nt.testBox),nt.testBox.isEmpty()){const i=X(e,nt._position);nt.testBox.setFromCenterAndSize(i,nt._emptyObjectSize)}this.updateBox();const t=this.box?.intersectsBox(nt.testBox);return t&&nP&&j.DrawWireBox3(nt.testBox,16711680,5),t}intersects(e){return e?this.updateBox(!1).intersectsBox(e):!1}updateBox(e=!1){if(this.box||(this.box=new c.Box3),e||this.context.time.frameCount!=this._lastMatrixUpdateFrame){const t=this._lastMatrixUpdateFrame<0;this._lastMatrixUpdateFrame=this.context.time.frameCount;const i=t,n=X(this.gameObject,nt._position,i),o=Ae(this.gameObject,nt._size);this.box.setFromCenterAndSize(n,o)}return this.box}_helper=null;_color=null;awake(){this._helper=null,this._color=null,this.box=null}showHelper(e=null,t=!1){if(!(!iP&&!t)){if(this._helper){e&&this._color?.set(e),this.gameObject.add(this._helper);return}this._helper=nm(e),this.gameObject.add(this._helper)}}}var sP=Object.defineProperty,Xt=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&sP(e,t,n),n};class Qt extends k{get isCollider(){return!0}attachedRigidbody=null;isTrigger=!1;sharedMaterial;membership=[0];filter;awake(){super.awake(),this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(Ke))}start(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(Ke))}onEnable(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(Ke))}onDisable(){this.context.physics.engine?.removeBody(this)}get body(){return this.context.physics.engine?.getBody(this)}updateProperties=()=>{this.context.physics.engine?.updateProperties(this)};updatePhysicsMaterial(){this.context.physics.engine?.updatePhysicsMaterial(this)}}Xt([f(Ke)],Qt.prototype,"attachedRigidbody");Xt([f()],Qt.prototype,"isTrigger");Xt([f()],Qt.prototype,"sharedMaterial");Xt([f()],Qt.prototype,"membership");Xt([f()],Qt.prototype,"filter");class ga extends Qt{radius=.5;center=new c.Vector3(0,0,0);onEnable(){super.onEnable(),this.context.physics.engine?.addSphereCollider(this),Md(this.gameObject.scale,this.updateProperties)}onDisable(){super.onDisable(),jp(this.gameObject.scale,this.updateProperties)}onValidate(){this.updateProperties()}}Xt([gt(),f()],ga.prototype,"radius");Xt([f(c.Vector3)],ga.prototype,"center");const Em=class cv extends Qt{static add(e,t){const i=ci(e,cv);return i.autoFit(),t?.rigidbody===!0&&ci(e,Ke,{isKinematic:!1}),i}size=new c.Vector3(1,1,1);center=new c.Vector3(0,0,0);onEnable(){super.onEnable(),this.context.physics.engine?.addBoxCollider(this,this.size),Md(this.gameObject.scale,this.updateProperties)}onDisable(){super.onDisable(),jp(this.gameObject.scale,this.updateProperties)}onValidate(){this.updateProperties()}autoFit(e){const t=this.gameObject,i=t.position.clone(),n=t.quaternion.clone(),o=t.scale.clone(),r=t.parent;t.position.set(0,0,0),t.quaternion.set(0,0,0,1),t.scale.set(1,1,1),t.parent=null,t.updateMatrix();const a=Ht([t]);t.position.copy(i),t.quaternion.copy(n),t.scale.copy(o),t.parent=r,e?.debug===!0&&j.DrawWireBox3(a,16768256,20),this.size=a.getSize(new c.Vector3)||new c.Vector3(1,1,1),this.center=a.getCenter(new c.Vector3)||new c.Vector3(0,0,0),this.size.length()<=0&&this.size.set(.01,.01,.01)}};Xt([gt(),f(c.Vector3)],Em.prototype,"size");Xt([f(c.Vector3)],Em.prototype,"center");let Xd=Em;class io extends Qt{sharedMesh;convex=!1;onEnable(){if(super.onEnable(),!this.context.physics.engine)return;this.sharedMesh?.isMesh||(this.gameObject instanceof c.Mesh||this.gameObject instanceof c.Group)&&(this.sharedMesh=this.gameObject);const e=0;if(this.sharedMesh?.isMesh)this.context.physics.engine.addMeshCollider(this,this.sharedMesh,this.convex),ne.NEEDLE_progressive.assignMeshLOD(this.sharedMesh,e).then(t=>{t&&this.activeAndEnabled&&this.context.physics.engine&&this.sharedMesh&&(this.context.physics.engine.removeBody(this),this.sharedMesh.geometry=t,this.context.physics.engine.addMeshCollider(this,this.sharedMesh,this.convex))});else{const t=this.sharedMesh;if(t?.isGroup){console.warn(`MeshCollider mesh is a group "${this.sharedMesh?.name||this.gameObject.name}", adding all children as colliders. This is currently not fully supported (colliders can not be removed from world again)`,this);const i=new Array;for(const n in t.children){const o=t.children[n];o.isMesh&&(this.context.physics.engine.addMeshCollider(this,o,this.convex),i.push(ne.NEEDLE_progressive.assignMeshLOD(o,e)))}Promise.all(i).then(n=>{if(n.some(r=>r)==!1)return;this.context.physics.engine?.removeBody(this);const o=new c.Mesh;for(const r of n)r&&this.activeAndEnabled&&(o.geometry=r,this.context.physics.engine?.addMeshCollider(this,o,this.convex))})}else(A()||w("showcolliders"))&&console.warn(`[MeshCollider] A MeshCollider mesh is assigned to an unknown object on "${this.gameObject.name}", but it's neither a Mesh nor a Group. Please double check that you attached the collider component to the right object and report a bug otherwise!`,this)}}}Xt([f(c.Mesh)],io.prototype,"sharedMesh");Xt([f()],io.prototype,"convex");class as extends Qt{center=new c.Vector3(0,0,0);radius=.5;height=2;onEnable(){super.onEnable(),this.context.physics.engine?.addCapsuleCollider(this,this.height,this.radius)}}Xt([f(c.Vector3)],as.prototype,"center");Xt([f()],as.prototype,"radius");Xt([f()],as.prototype,"height");var oP=Object.defineProperty,hs=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&oP(e,t,n),n};const Zy=w("debugcharactercontroller");class sr extends k{center=new c.Vector3(0,0,0);radius=.5;height=2;_rigidbody=null;get rigidbody(){return this._rigidbody?this._rigidbody:(this._rigidbody=this.gameObject.getComponent(Ke),this._rigidbody||(this._rigidbody=this.gameObject.addComponent(Ke)),this.rigidbody)}_activeGroundCollisions;awake(){this._activeGroundCollisions=new Set}onEnable(){const e=this.rigidbody;let t=this.gameObject.getComponent(as);t||(t=this.gameObject.addComponent(as)),t.center.copy(this.center),t.radius=this.radius,t.height=this.height;const i=new c.Vector3(0,0,1),n=new c.Vector3(1,0,0),o=new c.Vector3(0,1,0),r=this.gameObject.getWorldDirection(new c.Vector3);r.y=0;const a=n.dot(r)<0?-1:1,l=i.angleTo(r)*a;this.gameObject.setRotationFromAxisAngle(o,l),e.lockRotationX=!0,e.lockRotationY=!0,e.lockRotationZ=!0}move(e){this.gameObject.position.add(e)}onCollisionEnter(e){(e.contacts.length==0||e.contacts.some(t=>t.normal.y>.2))&&(this._activeGroundCollisions.add(e),Zy&&console.log(`Collision(${this._activeGroundCollisions.size}): ${e.contacts.map(t=>t.normal.y.toFixed(2)).join(", ")} - ${this.isGrounded}`))}onCollisionExit(e){this._activeGroundCollisions.delete(e),Zy&&console.log(`Collision(${this._activeGroundCollisions.size}) - ${this.isGrounded}`)}get isGrounded(){return this._activeGroundCollisions.size>0}_contactVelocity=new c.Vector3;get contactVelocity(){this._contactVelocity.set(0,0,0);for(const e of this._activeGroundCollisions){const t=this.context.physics.engine?.getLinearVelocity(e.collider);t&&(this._contactVelocity.x+=t.x,this._contactVelocity.y+=t.y,this._contactVelocity.z+=t.z)}return this._contactVelocity}}hs([f(c.Vector3)],sr.prototype,"center");hs([f()],sr.prototype,"radius");hs([f()],sr.prototype,"height");class ds extends k{controller;movementSpeed=2;rotationSpeed=2;jumpForce=1;doubleJumpForce=2;animator;lookForward=!0;awake(){this._currentRotation=new c.Quaternion}update(){const e=this.context.input;e.isKeyPressed("KeyW")?this.moveInput.y+=1:e.isKeyPressed("KeyS")&&(this.moveInput.y-=1),e.isKeyPressed("KeyD")?this.lookInput.x+=1:e.isKeyPressed("KeyA")&&(this.lookInput.x-=1),this.jumpInput||=e.isKeyDown("Space")}move(e){this.moveInput.add(e)}look(e){this.lookInput.add(e)}jump(){this.jumpInput=!0}lookInput=new c.Vector2(0,0);moveInput=new c.Vector2(0,0);jumpInput=!1;onBeforeRender(){this.handleInput(this.moveInput,this.lookInput,this.jumpInput),this.lookInput.set(0,0),this.moveInput.set(0,0),this.jumpInput=!1}_currentSpeed=new c.Vector3(0,0,0);_currentAngularSpeed=new c.Vector3(0,0,0);_temp=new c.Vector3(0,0,0);_jumpCount=0;_currentRotation;handleInput(e,t,i){if(this.controller?.isGrounded&&(this._jumpCount=0,this.doubleJumpForce>0&&this.animator?.setBool("doubleJump",!1)),this._currentSpeed.z+=e.y*this.movementSpeed*this.context.time.deltaTime,this.animator?.setBool("running",e.length()>.01),this.animator?.setBool("jumping",this.controller?.isGrounded===!0&&i),this._temp.copy(this._currentSpeed),this._temp.applyQuaternion(this.gameObject.quaternion),this.controller?this.controller.move(this._temp):this.gameObject.position.add(this._temp),this._currentAngularSpeed.y+=I.toRadians(-t.x*this.rotationSpeed)*this.context.time.deltaTime,this.lookForward&&Math.abs(this._currentAngularSpeed.y)<.01){const n=this.context.mainCameraComponent.forward;n.y=0,n.normalize(),this._currentRotation.setFromUnitVectors(new c.Vector3(0,0,1),n),this.gameObject.quaternion.slerp(this._currentRotation,this.context.time.deltaTime*10)}if(this.gameObject.rotateY(this._currentAngularSpeed.y),this._currentSpeed.multiplyScalar(1-this.context.time.deltaTime*10),this._currentAngularSpeed.y*=1-this.context.time.deltaTime*10,this.controller&&i&&this.jumpForce>0){let n=this.controller?.isGrounded;if(this.doubleJumpForce>0&&!this.controller?.isGrounded&&this._jumpCount===1&&(n=!0,this.animator?.setBool("doubleJump",!0)),n){this._jumpCount+=1;const o=this.controller.rigidbody,r=this._jumpCount===2?this.doubleJumpForce:this.jumpForce;o.applyImpulse(new c.Vector3(0,1,0).multiplyScalar(r))}}if(this.controller){const n=this.controller?.rigidbody.getVelocity().y;if(n<-1){this._raycastOptions.ray||(this._raycastOptions.ray=new c.Ray),this._raycastOptions.ray.origin.copy(X(this.gameObject)),this._raycastOptions.ray.direction.set(0,-1,0);const o=this.layer;this.gameObject.layers.disableAll(),this.gameObject.layers.set(2);const r=this.context.physics.raycast(this._raycastOptions);this.gameObject.layers.set(o),(r.length&&r[0].distance>2||n<-10)&&this.animator?.setBool("falling",!0)}else this.animator?.setBool("falling",!1)}}_raycastOptions=new eo}hs([f(sr)],ds.prototype,"controller");hs([f()],ds.prototype,"movementSpeed");hs([f()],ds.prototype,"rotationSpeed");hs([f()],ds.prototype,"jumpForce");hs([f()],ds.prototype,"doubleJumpForce");hs([f(mt)],ds.prototype,"animator");var rP=Object.defineProperty,ya=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&rP(e,t,n),n};const Na=w("debugcontactshadows");ym(s=>{const e=s.domElement.getAttribute("contactshadows")||s.domElement.getAttribute("contact-shadows");if(e!=null&&e!="0"&&e!="false"){console.debug("Auto-creating ContactShadows because of `contactshadows` attribute");const t=yc.auto(s),i=parseFloat(e);isNaN(i)||(t.opacity=i,t.darkness=i)}});const or=class cl extends k{static _instances=new Map;static auto(e){if(e||(e=U.Current),!e)throw new Error("No context provided and no current context set.");let t=this._instances.get(e);if(!t||t.destroyed){const i=new c.Object3D;t=ci(i,cl,{autoFit:!1,occludeBelowGround:!1}),this._instances.set(e,t)}return e.scene.add(t.gameObject),t.fitShadows(),t}autoFit=!1;darkness=.5;opacity=.5;blur=4;occludeBelowGround=!1;backfaceShadows=!0;minSize;manualUpdate=!1;set needsUpdate(e){this._needsUpdate=e}get needsUpdate(){return this._needsUpdate}_needsUpdate=!1;shadowsRoot=new c.Object3D;shadowCamera;shadowGroup=new c.Group;renderTarget;renderTargetBlur;plane;occluderMesh;blurPlane;depthMaterial;horizontalBlurMaterial;verticalBlurMaterial;textureSize=512;fitShadows(){Na&&console.warn("Fitting shadows to scene"),Qh(this.shadowsRoot,!1);const e=Ht(this.context.scene.children,[this.shadowsRoot]),t=Math.max(1,this.blur/32),i=e.max.x-e.min.x,n=e.max.z-e.min.z;e.expandByVector(new c.Vector3(t*i,0,t*n)),Na&&j.DrawWireBox3(e,16776960,60),this.gameObject.parent&&e.applyMatrix4(this.gameObject.parent.matrixWorld.clone().invert());const o=e.min,r=Math.max(1e-5,(e.max.y-o.y)*.002);e.max.y+=r,this.shadowsRoot.position.set((o.x+e.max.x)/2,o.y-r,(o.z+e.max.z)/2),this.shadowsRoot.scale.set(e.max.x-o.x,e.max.y-o.y,e.max.z-o.z),this.applyMinSize(),this.shadowsRoot.matrixWorldNeedsUpdate=!0,Na&&console.log("Fitted shadows to scene",this.shadowsRoot.scale.clone())}awake(){cl._instances.set(this.context,this),this.shadowsRoot.hideFlags=Gd.DontExport,Qh(this.shadowsRoot,!1)}start(){Na&&console.log("Create ContactShadows on "+this.gameObject.name,this),this.gameObject.add(this.shadowsRoot),this.shadowsRoot.add(this.shadowGroup),this.renderTarget=new c.WebGLRenderTarget(this.textureSize,this.textureSize),this.renderTarget.texture.generateMipmaps=!1,this.renderTargetBlur=new c.WebGLRenderTarget(this.textureSize,this.textureSize),this.renderTargetBlur.texture.generateMipmaps=!1;const e=new c.PlaneGeometry(1,1).rotateX(Math.PI/2);this.gameObject instanceof c.Mesh&&(console.warn("ContactShadows can not be added to a Mesh. Please add it to a Group or an empty Object"),Jn(this.gameObject,!1));const t=new c.MeshBasicMaterial({map:this.renderTarget.texture,opacity:this.opacity,color:0,transparent:!0,depthWrite:!1,side:c.FrontSide});this.plane=new c.Mesh(e,t),this.plane.scale.y=-1,this.plane.layers.set(2),this.shadowsRoot.add(this.plane),this.plane&&(this.plane.renderOrder=1),this.occluderMesh=new c.Mesh(this.plane.geometry,new c.MeshBasicMaterial({depthWrite:!0,stencilWrite:!0,colorWrite:!1,side:c.BackSide})).translateY(-1e-4),this.occluderMesh.renderOrder=-100,this.occluderMesh.layers.set(2),this.shadowsRoot.add(this.occluderMesh),this.blurPlane=new c.Mesh(e),this.blurPlane.visible=!1,this.shadowGroup.add(this.blurPlane);const i=0,n=1;this.shadowCamera=new c.OrthographicCamera(-1/2,1/2,1/2,-1/2,i,n),this.shadowCamera.layers.enableAll(),this.shadowCamera.rotation.x=Math.PI/2,this.shadowGroup.add(this.shadowCamera),this.depthMaterial=new c.MeshDepthMaterial,this.depthMaterial.userData.darkness={value:this.darkness},this.depthMaterial.blending=c.CustomBlending,this.depthMaterial.blendEquation=c.MaxEquation,this.depthMaterial.onBeforeCompile=o=>{this.depthMaterial&&(o.uniforms.darkness=this.depthMaterial.userData.darkness,o.fragmentShader=`
946
956
  uniform float darkness;
947
957
  ${o.fragmentShader.replace("gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );","gl_FragColor = vec4( vec3( 1.0 ), ( 1.0 - fragCoordZ ) * darkness * opacity * (gl_FrontFacing ? 1.0 : 0.66) );")}
948
958
  `)},this.depthMaterial.depthTest=!1,this.depthMaterial.depthWrite=!1,this.horizontalBlurMaterial=new c.ShaderMaterial(G.HorizontalBlurShader),this.horizontalBlurMaterial.depthTest=!1,this.verticalBlurMaterial=new c.ShaderMaterial(G.VerticalBlurShader),this.verticalBlurMaterial.depthTest=!1,this.shadowGroup.visible=!1,this.autoFit?this.fitShadows():this.applyMinSize()}onEnable(){this._needsUpdate=!0}onDestroy(){cl._instances.get(this.context)===this&&cl._instances.delete(this.context),this.renderTarget?.dispose(),this.renderTargetBlur?.dispose(),this.depthMaterial?.dispose(),this.horizontalBlurMaterial?.dispose(),this.verticalBlurMaterial?.dispose(),this.blurPlane?.geometry.dispose(),this.plane?.geometry.dispose(),this.occluderMesh?.geometry.dispose()}onBeforeRender(e){if(this.manualUpdate&&!this._needsUpdate)return;if(this._needsUpdate=!1,!this.renderTarget||!this.renderTargetBlur||!this.depthMaterial||!this.shadowCamera||!this.blurPlane||!this.shadowGroup||!this.plane||!this.horizontalBlurMaterial||!this.verticalBlurMaterial){Na&&console.error("ContactShadows: not initialized yet");return}const t=this.context.scene,i=this.context.renderer,n=i.getRenderTarget();this.shadowGroup.visible=!0,this.occluderMesh&&(this.occluderMesh.visible=!1);const o=this.plane.visible;this.plane.visible=!1,this.gameObject instanceof c.Mesh&&Jn(this.gameObject,!1);const r=t.background;t.background=null,t.overrideMaterial=this.depthMaterial,this.backfaceShadows?this.depthMaterial.side=c.DoubleSide:this.depthMaterial.side=c.FrontSide;const a=i.getClearAlpha();i.setClearAlpha(0);const l=i.xr.enabled;i.xr.enabled=!1;const h=this.context.scene.matrixWorldAutoUpdate;this.context.scene.matrixWorldAutoUpdate=!1;const d=i.renderLists.get(t,0),u=d.transparent;Jy.length=0,d.transparent=Jy,sf.length=0;for(const m of d.opaque){if(!m.object.visible)continue;const y=m.material;let b=m.material.colorWrite==!1||y.wireframe===!0||pb(m.object)===!1;!b&&m.material.isLineMaterial&&(b=!0),!b&&m.material.isPointsMaterial&&(b=!0),b&&(sf.push(m.object),m.object["needle:visible"]=m.object.visible,m.object.visible=!1)}i.setRenderTarget(this.renderTarget),i.clear(),i.render(t,this.shadowCamera),d.transparent=u;for(const m of sf)m["needle:visible"]!=null&&(m.visible=m["needle:visible"]);t.overrideMaterial=null;const p=Math.max(this.blur,.05);this.blurShadow(p*2),this.blurShadow(p*.5),this.shadowGroup.visible=!1,this.occluderMesh&&(this.occluderMesh.visible=this.occludeBelowGround),this.plane.visible=o,i.setRenderTarget(n),i.setClearAlpha(a),t.background=r,i.xr.enabled=l,this.context.scene.matrixWorldAutoUpdate=h}blurShadow(e){if(!this.blurPlane||!this.shadowCamera||!this.renderTarget||!this.renderTargetBlur||!this.horizontalBlurMaterial||!this.verticalBlurMaterial)return;this.blurPlane.visible=!0;const t=this.shadowsRoot.worldScale,i=(t.x+t.z)/2,n=t.z/i,o=t.x/i;this.blurPlane.material=this.horizontalBlurMaterial,this.blurPlane.material.uniforms.tDiffuse.value=this.renderTarget.texture,this.horizontalBlurMaterial.uniforms.h.value=e*1/this.textureSize*n;const r=this.context.renderer,a=r.getRenderTarget();r.setRenderTarget(this.renderTargetBlur),r.render(this.blurPlane,this.shadowCamera),this.blurPlane.material=this.verticalBlurMaterial,this.blurPlane.material.uniforms.tDiffuse.value=this.renderTargetBlur.texture,this.verticalBlurMaterial.uniforms.v.value=e*1/this.textureSize*o,r.setRenderTarget(this.renderTarget),r.render(this.blurPlane,this.shadowCamera),this.blurPlane.visible=!1,r.setRenderTarget(a)}applyMinSize(){this.minSize&&this.shadowsRoot.scale.set(Math.max(this.minSize.x||0,this.shadowsRoot.scale.x),Math.max(this.minSize.y||0,this.shadowsRoot.scale.y),Math.max(this.minSize.z||0,this.shadowsRoot.scale.z))}};ya([f()],or.prototype,"autoFit");ya([f()],or.prototype,"darkness");ya([f()],or.prototype,"opacity");ya([f()],or.prototype,"blur");ya([f()],or.prototype,"occludeBelowGround");ya([f()],or.prototype,"backfaceShadows");let yc=or;const Jy=[],sf=new Array,aP=w("logstats");class Tm extends k{onEnable(){console.log(this),aP&&this.startCoroutine(this.run(),pe.OnAfterRender)}*run(){for(;this.enabled;){const e=this.context.renderer.info;console.log(e.memory,e.render,e.programs),yield}}}class _c extends k{isUsed=!0;usedBy=null}class Am extends k{}const e_=w("debugdeletable");class $s extends nt{static _instances=[];onEnable(){$s._instances.push(this)}onDisable(){const e=$s._instances.indexOf(this);e>=0&&$s._instances.splice(e,1)}}class Lm extends k{update(){for(const e of $s._instances){const t=this.gameObject;if(e.isInBox(t)===!0){const n=x.getComponentInParent(this.gameObject,_c);if(n)e_&&console.warn("DeleteBox: Not deleting object with usage marker",this.guid,n);else{if(e_)try{if(e.box){const o=e.box,r=nt.testBox;j.DrawWireBox3(o,16711680,5),j.DrawWireBox3(r,255,5),console.log("DeleteBox: Destroying",this.gameObject,{deleteBoxArea:o,deletedObjectArea:r})}else console.log("DeleteBox: Destroying",this.gameObject)}catch{}sc(this.gameObject,this.context.connection)}}}}}var lP=Object.defineProperty,cP=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&lP(e,t,n),n};class Qd extends k{visibleOn;onEnable(){this.apply()}apply(){this.test()||x.setActive(this.gameObject,!1)}test(){return this.visibleOn<0?!0:exports.DeviceUtilities.isMobileDevice()?(this.visibleOn&2)!==0:(this.visibleOn&1)!==0}}cP([f()],Qd.prototype,"visibleOn");var hP=Object.defineProperty,rr=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&hP(e,t,n),n};const Pn=w("debugdrag"),of=[];var Dm=(s=>(s[s.XZPlane=0]="XZPlane",s[s.Attached=1]="Attached",s[s.HitNormal=2]="HitNormal",s[s.DynamicViewAngle=3]="DynamicViewAngle",s[s.SnapToSurfaces=4]="SnapToSurfaces",s[s.None=5]="None",s))(Dm||{});const no=class Mi extends k{static get HasAnySelected(){return this._active>0}static _active=0;static get CurrentlySelected(){of.length=0;for(const e of this._instances)e._isDragging&&of.push(e);return of}static _instances=[];dragMode=3;snapGridResolution=0;keepRotation=!0;xrDragMode=1;xrKeepRotation=!1;xrDistanceDragFactor=1;showGizmo=!1;get draggedObject(){return this._targetObject}setTargetObject(e){this._targetObject=e;for(const i of this._dragHandlers.values())i.setTargetObject(e);const t="_rigidbody-was-kinematic";this._rigidbody?.[t]===!1&&(this._rigidbody.isKinematic=!1,this._rigidbody[t]=void 0),this._rigidbody=null,e&&(this._rigidbody=x.getComponentInChildren(e,Ke),this._rigidbody?.isKinematic===!1&&(this._rigidbody.isKinematic=!0,this._rigidbody[t]=!1))}_rigidbody=null;_targetObject=null;_dragHelper=null;static lastHovered;_draggingRigidbodies=[];_potentialDragStartEvt=null;_dragHandlers=new Map;_totalMovement=new c.Vector3;_marker=null;_isDragging=!1;_didDrag=!1;awake(){this._potentialDragStartEvt=null,this._dragHandlers=new Map,this._totalMovement=new c.Vector3,this._marker=null,this._isDragging=!1,this._didDrag=!1,this._dragHelper=null,this._draggingRigidbodies=[]}start(){this.gameObject.getComponentInParent(ui)||this.gameObject.addComponent(ui)}onEnable(){Mi._instances.push(this)}onDisable(){Mi._instances=Mi._instances.filter(e=>e!==this)}allowEdit(e=null){return this.context.connection.allowEditing}onPointerEnter(e){if(!this.allowEdit(this.gameObject)||e.mode!=="screen"||(e.event.mode==="tracked-pointer"||e.event.mode==="transient-pointer"?this.xrDragMode:this.dragMode)===5)return;const n=x.getComponentInParent(e.object,Mi);!n||n!==this||(Mi.lastHovered=e.object,this.context.domElement.style.cursor="pointer")}onPointerMove(e){(this._isDragging||this._potentialDragStartEvt!==null)&&e.use()}onPointerExit(e){this.allowEdit(this.gameObject)&&e.mode==="screen"&&Mi.lastHovered===e.object&&(this.context.domElement.style.cursor="auto")}onPointerDown(e){if(!(!this.allowEdit(this.gameObject)||e.used||(e.mode==="tracked-pointer"||e.mode==="transient-pointer"?this.xrDragMode:this.dragMode)===5)&&(Mi.lastHovered=e.object,e.button===0)){this._dragHandlers.size===0&&(this._didDrag=!1,this._totalMovement.set(0,0,0),this._potentialDragStartEvt=e),this._targetObject||this.setTargetObject(this.gameObject),Mi._active+=1;const n=new rf(this,this._targetObject);if(this._dragHandlers.set(e.event.space,n),n.onDragStart(e),this._dragHandlers.size===2){const o=this._dragHandlers.values(),r=o.next().value,a=o.next().value;if(r instanceof rf&&a instanceof rf){const l=new dP(this,this._targetObject,r,a);this._dragHandlers.set(this.gameObject,l),l.onDragStart(e)}else console.error("Attempting to construct a MultiTouchDragHandler with invalid DragPointerHandlers. This is likely a bug.",{a:r,b:a})}e.use()}}onPointerUp(e){if(Pn&&j.DrawLabel(e.point??this.gameObject.worldPosition,"POINTERUP:"+e.pointerId+", "+e.button,.03,3),!this.allowEdit(this.gameObject)||e.button!==0)return;this._potentialDragStartEvt=null;const t=this._dragHandlers.get(e.event.space),i=this._dragHandlers.get(this.gameObject);i&&(i.handlerA===t||i.handlerB===t)&&(this._dragHandlers.delete(this.gameObject),i.onDragEnd(e)),t&&(Mi._active>0&&(Mi._active-=1),this.setTargetObject(null),t.onDragEnd&&t.onDragEnd(e),this._dragHandlers.delete(e.event.space),this._dragHandlers.size===0&&this.onLastDragEnd(e),e.use())}update(){for(const e of this._dragHandlers.values())e.collectMovementInfo&&e.collectMovementInfo(),e.getTotalMovement&&this._totalMovement.add(e.getTotalMovement());if(this._potentialDragStartEvt){if(!this._didDrag)if(this._totalMovement.length()>3e-4)this._didDrag=!0;else return;const e=this._potentialDragStartEvt;this._potentialDragStartEvt=null,this.onFirstDragStart(e)}for(const e of this._dragHandlers.values())e.onDragUpdate&&e.onDragUpdate(this._dragHandlers.size);this._dragHelper&&this._dragHelper.hasSelected&&this.onAnyDragUpdate()}onFirstDragStart(e){if(!e||!e.object)return;const t=x.getComponentInParent(e.object,Mi);if(!t||t!==this&&t._isDragging)return;const i=this._targetObject||this.gameObject;if(!i)return;this._isDragging=!0;const n=x.getComponentInChildren(i,Ln);Pn&&console.log("DRAG START",n,i),n&&(n.fastMode=!0,n?.requestOwnership()),this._marker=x.addComponent(i,_c),this._draggingRigidbodies.length=0;const o=x.getComponentsInChildren(i,Ke);o&&this._draggingRigidbodies.push(...o)}onAnyDragUpdate(){if(!this._dragHelper)return;this._dragHelper.showGizmo=this.showGizmo,this._dragHelper.onUpdate(this.context);for(const t of this._draggingRigidbodies)t.wakeUp(),t.resetVelocities(),t.resetForcesAndTorques();const e=this._targetObject||this.gameObject;Ai.markDirty(e)}onLastDragEnd(e){if(!this||!this._isDragging)return;this._isDragging=!1;for(const i of this._draggingRigidbodies)i.setVelocity(i.smoothedVelocity);if(this._draggingRigidbodies.length=0,this._targetObject=null,e?.object){const i=x.getComponentInChildren(e.object,Ln);i&&(i.fastMode=!1)}if(this._marker&&this._marker.destroy(),!this._dragHelper)return;const t=this._dragHelper.selected;Pn&&console.log("DRAG END",t,t?.visible),this._dragHelper.setSelected(null,this.context)}};rr([f()],no.prototype,"dragMode");rr([f()],no.prototype,"snapGridResolution");rr([f()],no.prototype,"keepRotation");rr([f()],no.prototype,"xrDragMode");rr([f()],no.prototype,"xrKeepRotation");rr([f()],no.prototype,"xrDistanceDragFactor");rr([f()],no.prototype,"showGizmo");let Mo=no;class dP{handlerA;handlerB;context;settings;gameObject;_handlerAAttachmentPoint=new c.Vector3;_handlerBAttachmentPoint=new c.Vector3;_followObject;_manipulatorObject;_deviceMode;_followObjectStartWorldQuaternion=new c.Quaternion;constructor(e,t,i,n){this.context=e.context,this.settings=e,this.gameObject=t,this.handlerA=i,this.handlerB=n,this._followObject=new c.Object3D,this._manipulatorObject=new c.Object3D,this.context.scene.add(this._manipulatorObject);const o=q.active?.rig?.gameObject;if(!this.handlerA||!this.handlerB||!this.handlerA.hitPointInLocalSpace||!this.handlerB.hitPointInLocalSpace){console.error("Invalid: MultiTouchDragHandler needs two valid DragPointerHandlers with hitPointInLocalSpace set.");return}if(this._tempVec1.copy(this.handlerA.hitPointInLocalSpace),this._tempVec2.copy(this.handlerB.hitPointInLocalSpace),this.gameObject.localToWorld(this._tempVec1),this.gameObject.localToWorld(this._tempVec2),o&&(o.worldToLocal(this._tempVec1),o.worldToLocal(this._tempVec2)),this._initialDistance=this._tempVec1.distanceTo(this._tempVec2),this._initialDistance<.02?(Pn&&console.log("Finding alternative drag attachment points since initial distance is too low: "+this._initialDistance.toFixed(2)),this.handlerA.followObject.parent.getWorldPosition(this._tempVec1),this.handlerB.followObject.parent.getWorldPosition(this._tempVec2),this._handlerAAttachmentPoint.copy(this._tempVec1),this._handlerBAttachmentPoint.copy(this._tempVec2),this.gameObject.worldToLocal(this._handlerAAttachmentPoint),this.gameObject.worldToLocal(this._handlerBAttachmentPoint),this._initialDistance=this._tempVec1.distanceTo(this._tempVec2),this._initialDistance<.001&&(console.warn("Not supported right now – controller drag points for multitouch are too close!"),this._initialDistance=1)):(this._handlerAAttachmentPoint.copy(this.handlerA.hitPointInLocalSpace),this._handlerBAttachmentPoint.copy(this.handlerB.hitPointInLocalSpace)),this._tempVec3.lerpVectors(this._tempVec1,this._tempVec2,.5),this._initialScale.copy(t.scale),Pn){this._followObject.add(new c.AxesHelper(2)),this._manipulatorObject.add(new c.AxesHelper(5));const r=a=>`${a.x.toFixed(2)}, ${a.y.toFixed(2)}, ${a.z.toFixed(2)}`;j.DrawLine(this._tempVec1,this._tempVec2,65535,0,!1),j.DrawLabel(this._tempVec3,"A:B "+this._initialDistance.toFixed(2)+`
@@ -1247,9 +1257,9 @@ ${l.has(1)?`
1247
1257
  `:""}
1248
1258
  ${a.join(`
1249
1259
  `)}`:""}
1250
- }`}function u_(s){return`(${s.r}, ${s.g}, ${s.b})`}function f_(s){return`(${s.x}, ${s.y})`}const qm=[1023,33777,33778,33779,35842,35843,37496,37808,37809,37810,37811,37812,37813,37814,37815,37816,37817,37818,37819,37820,37821,36492];w("debugusdz");class pt{static global_id=0;id;trigger;action;exclusive=!1;makeExclusive(e){return this.exclusive=e,this}constructor(e,t,i){this.id="Behavior_"+ji(e)+"_"+pt.global_id++,this.trigger=t,this.action=i}writeTo(e,t,i){if(!this.trigger||!this.action)return;i.beginBlock(`def Preliminary_Behavior "${this.id}"`);let n="";if(Array.isArray(this.trigger)){n="[";for(let o=0;o<this.trigger.length;o++){const r=this.trigger[o];n+="<"+r.id+">",o+1<this.trigger.length&&(n+=", ")}n+="]"}else n=`<${this.trigger.id}>`;if(i.appendLine(`rel triggers = ${n}`),i.appendLine(`rel actions = <${this.action.id}>`),i.appendLine(`uniform bool exclusive = ${this.exclusive?1:0}`),i.appendLine(),Array.isArray(this.trigger))for(const o of this.trigger)o.writeTo(t,i),i.appendLine();else this.trigger.writeTo(t,i);i.appendLine(),this.action.writeTo(t,i),i.closeBlock()}}const Or=new Set;function yp(s,e){let t="";if(Array.isArray(s)){Or.clear();let i="[ ";for(let n=0;n<s.length;n++){let o=s[n];if(!o){console.warn("Invalid target object in behavior",s+". Is the object exported?");continue}if(typeof o=="string"){if(Or.has(o))continue;i+=o,Or.add(o)}else if(typeof o=="object"){if(o.isObject3D&&(o=e.findById(o.uuid),!o)){console.warn("Invalid target object in behavior",s+". Is the object exported?");continue}const r=o.getPath?.call(o);if(Or.has(r))continue;i+=r,Or.add(r)}n+1<s.length&&(i+=", ")}i+=" ]",t=i,Or.clear()}else if(typeof s=="object"){const i=s;if(i.isObject3D&&(s=e.findById(i.uuid)),!s)throw console.error("Invalid target object in behavior, the target object is likely missing from USDZ export. Is the object exported?",i),new Error(`Invalid target object in behavior, the target object is likely missing from USDZ export. Please report a bug. uuid: ${i.uuid}.`);t=s.getPath?.call(s)}return t}class Ws{static global_id=0;id;targetId;tokenId;type;distance;constructor(e,t){e&&(this.targetId=e),t?this.id=t:this.id="Trigger_"+Ws.global_id++}writeTo(e,t){t.beginBlock(`def Preliminary_Trigger "${this.id}"`),this.targetId&&(typeof this.targetId!="string"&&(this.targetId=yp(this.targetId,e)),t.appendLine("rel affectedObjects = "+this.targetId)),this.tokenId&&t.appendLine(`token info:id = "${this.tokenId}"`),this.type&&t.appendLine(`token type = "${this.type}"`),typeof this.distance=="number"&&t.appendLine(`double distance = ${this.distance}`),t.closeBlock()}}function p_(s,e={direct:!0,indirect:!0}){const t=ze.createEmpty();t.name="InputTarget_"+t.name,t.displayName=void 0,t.type="RealityKitComponent",t.onSerialize=i=>{i.appendLine("bool allowsDirectInput = "+(e.direct?1:0)),i.appendLine("bool allowsIndirectInput = "+(e.indirect?1:0)),i.appendLine('uniform token info:id = "RealityKit.InputTarget"')},s.add(t)}class xt{static __sceneStartTrigger;static sceneStartTrigger(){if(this.__sceneStartTrigger!==void 0)return this.__sceneStartTrigger;const e=new Ws(void 0,"SceneStart");return e.tokenId="SceneTransition",e.type="enter",this.__sceneStartTrigger=e,e}static tapTrigger(e,t={direct:!0,indirect:!0}){const i=new Ws(e);if(Array.isArray(e)&&e.length>1)for(const n of e)n instanceof ze&&p_(n,t);else e instanceof ze&&p_(e,t);return i.tokenId="TapGesture",i}static isTapTrigger(e){return e?.tokenId==="TapGesture"}static proximityToCameraTrigger(e,t){const i=new Ws(e);return i.tokenId="ProximityToCamera",i.distance=t,i}}class Oo{static global_id=0;static getId(){return this.global_id++}id;actions;loops=0;performCount=1;type="serial";multiplePerformOperation=void 0;constructor(e,t){this.id=e,this.actions=t}addAction(e){return this.actions.push(e),this}makeParallel(){return this.type="parallel",this}makeSequence(){return this.type="serial",this}makeLooping(){return this.loops=1,this.performCount=0,this}makeRepeat(e){return this.performCount=e,this}writeTo(e,t){t.beginBlock(`def Preliminary_Action "${this.id}"`),t.beginArray("rel actions");for(const i of this.actions){if(!i)continue;const n=i===this.actions[this.actions.length-1];t.appendLine("<"+i.id+">"+(n?"":", "))}t.closeArray(),t.appendLine(),t.appendLine('token info:id = "Group"'),t.appendLine(`bool loops = ${this.loops}`),t.appendLine(`int performCount = ${this.loops>0?0:Math.max(0,this.performCount)}`),t.appendLine(`token type = "${this.type}"`),typeof this.multiplePerformOperation=="string"&&t.appendLine(`token multiplePerformOperation = "${this.multiplePerformOperation}"`),t.appendLine();for(const i of this.actions)i&&(i.writeTo(e,t),t.appendLine());t.closeBlock()}}class Vt{static global_id=0;id;tokenId;affectedObjects;easeType;motionType=void 0;duration;moveDistance;style;type;front;up;start;animationSpeed;reversed;pingPong;xFormTarget;audio;gain;auralMode;multiplePerformOperation;velocity;comment;animationName;clone(){const e=new Vt,t=e.id;return Object.assign(e,this),e.id=t,e}constructor(e,t){e&&(this.affectedObjects=e),t?this.id=t:this.id="Action",this.id+="_"+Vt.global_id++}writeTo(e,t){t.beginBlock(`def Preliminary_Action "${this.id}"`),this.comment&&t.appendLine(`# ${this.comment}`),this.affectedObjects&&(typeof this.affectedObjects!="string"&&(this.affectedObjects=yp(this.affectedObjects,e)),t.appendLine("rel affectedObjects = "+this.affectedObjects)),typeof this.duration=="number"&&(typeof this.animationSpeed=="number"&&this.animationSpeed!==1?t.appendLine(`double duration = ${this.duration/this.animationSpeed} `):t.appendLine(`double duration = ${this.duration} `)),this.easeType&&t.appendLine(`token easeType = "${this.easeType}"`),this.tokenId&&t.appendLine(`token info:id = "${this.tokenId}"`),this.tokenId==="ChangeScene"&&t.appendLine("rel scene = </StageRoot/Scenes/Scene>"),this.motionType!==void 0&&t.appendLine(`token motionType = "${this.motionType}"`),typeof this.moveDistance=="number"&&t.appendLine(`double moveDistance = ${this.moveDistance} `),this.style&&t.appendLine(`token style = "${this.style}"`),this.type&&t.appendLine(`token type = "${this.type}"`),this.front&&t.appendLine(`vector3d front = (${this.front.x}, ${this.front.y}, ${this.front.z})`),this.up&&t.appendLine(`vector3d upVector = (${this.up.x}, ${this.up.y}, ${this.up.z})`),typeof this.start=="number"&&t.appendLine(`double start = ${this.start} `),typeof this.animationSpeed=="number"&&t.appendLine(`double animationSpeed = ${this.animationSpeed.toFixed(2)} `),typeof this.reversed=="boolean"&&t.appendLine(`bool reversed = ${this.reversed}`),typeof this.pingPong=="boolean"&&t.appendLine(`bool reverses = ${this.pingPong}`),this.xFormTarget&&(typeof this.xFormTarget!="string"&&(this.xFormTarget=yp(this.xFormTarget,e)),t.appendLine(`rel xformTarget = ${this.xFormTarget}`)),typeof this.audio=="string"&&t.appendLine(`asset audio = @${this.audio}@`),typeof this.gain=="number"&&t.appendLine(`double gain = ${this.gain}`),typeof this.auralMode=="string"&&t.appendLine(`token auralMode = "${this.auralMode}"`),typeof this.multiplePerformOperation=="string"&&t.appendLine(`token multiplePerformOperation = "${this.multiplePerformOperation}"`),typeof this.velocity=="object"&&t.appendLine(`vector3d velocity = (${this.velocity.x}, ${this.velocity.y}, ${this.velocity.z})`),t.closeBlock()}}class Ti{x=0;y=0;z=0;constructor(e,t,i){this.x=e,this.y=t,this.z=i}static get up(){return new Ti(0,1,0)}static get right(){return new Ti(1,0,0)}static get forward(){return new Ti(0,0,1)}static get back(){return new Ti(0,0,-1)}static get zero(){return new Ti(0,0,0)}}class ae{static sequence(...e){return new Oo("Group_"+Oo.getId(),e).makeSequence()}static parallel(...e){return new Oo("Group_"+Oo.getId(),e).makeParallel()}static fadeAction(e,t,i){const n=new Vt(e);return n.tokenId="Visibility",n.type=i?"show":"hide",n.duration=t,n.style="basic",n.motionType="none",n.moveDistance=0,n.easeType="none",n}static startAnimationAction(e,t,i=!1,n=!1){const o=new Vt(e);o.tokenId="StartAnimation";const r=t.start,a=t.duration,l=t.speed,h=t.clipName;if(o.comment=`Animation: ${h}, start=${r*60}, length=${a*60}, end=${(r+a)*60}`,o.animationName=h,o.start=r,o.duration=a,o.animationSpeed=l,o.reversed=i,o.pingPong=n,o.multiplePerformOperation="allow",i&&(o.start-=a),n){o.pingPong=!1;const d=o.clone();return d.reversed=!i,d.start=o.start,d.reversed&&(d.start-=a),ae.sequence(o,d)}return o}static waitAction(e){const t=new Vt;return t.tokenId="Wait",t.duration=e,t.motionType=void 0,t}static lookAtCameraAction(e,t,i,n){const o=new Vt(e);return o.tokenId="LookAtCamera",o.duration=t===void 0?9999999999999:t,o.front=i??Ti.forward,o.up=n??Ti.up,o}static emphasize(e,t,i="bounce",n=1,o="basic"){const r=new Vt(e);return r.tokenId="Emphasize",r.duration=t,r.style=o??"basic",r.motionType=i,r.moveDistance=n,r}static transformAction(e,t,i,n,o="inout"){const r=new Vt(e);return r.tokenId="Transform",r.duration=i,r.duration=Math.max(1e-6,i),r.type=n,r.easeType=i>0?o:"none",Array.isArray(t)&&console.error("Transform target must not be an array",t),r.xFormTarget=t,r}static playAudioAction(e,t,i="play",n=1,o="spatial"){const r=new Vt(e);return r.tokenId="Audio",r.type=i,r.audio=t,r.gain=n,r.auralMode=o,r.multiplePerformOperation="allow",r}static impulseAction(e,t){const i=new Vt(e);return i.tokenId="Impulse",i.velocity=t,i}}class hM{get id(){return this.object.uuid}object;model;constructor(e){this.object=e}apply(e){if(!this.model&&(this.model=e.findById(this.object.uuid),!this.model)){console.error("could not find model with id "+this.object.uuid);return}this.onApply(e)}}class Xm extends hM{constructor(e,t,i,n){super(e),this.matrix=t,this.material=i,this.geometry=n}matrix;material;geometry;onApply(e){const t=this.model;if(!t)return;t.parent?.isDynamic||ze.createEmptyParent(t);const i=t.clone();this.matrix&&i.setMatrix(this.matrix),this.material&&(i.material=this.material),this.geometry&&(i.geometry=this.geometry),t.parent?.add(i)}_enableAction;_disableAction;enable(){return this._enableAction?this._enableAction:(this._enableAction=ae.fadeAction(this.object,0,!0),this._enableAction)}disable(){return this._disableAction?this._disableAction:(this._disableAction=ae.fadeAction(this.object,0,!1),this._disableAction)}}class Uv{actions;sortedActions;constructor(e){this.actions=[...e]}organize(){this.sortedActions={};for(const e of this.actions){const t=e.id;this.sortedActions[t]||(this.sortedActions[t]=[]),this.sortedActions[t].push(e)}}getActions(e){return this.sortedActions||this.organize(),this.sortedActions[e.uuid]}}const yn=w("debugusdzanimation"),_p=w("debugusdzanimationserialization");class zs{_start;get start(){return this._start===void 0&&(this._start=this.ext.getStartTimeByClip(this.clip)),this._start}get duration(){return this.clip?.duration??Oe.restPoseClipDuration}get nearestAnimatedRoot(){return this._nearestAnimatedRoot}get clipName(){return this.clip?.name??"rest"}ext;root;_nearestAnimatedRoot=void 0;clip;speed;constructor(e,t,i){this.ext=e,this.root=t,this.clip=i,this._nearestAnimatedRoot=this.getNearestAnimatedRoot()}static isDescendantOf(e,t){let i=t;if(!i||!e)return!1;for(;i;){if(!i)return!1;if(i===e)return!0;i=i.parent}return!1}getNearestAnimatedRoot(){let e;try{for(const t of this.clip?.tracks??[]){const i=c.PropertyBinding.parseTrackName(t.name);let n=c.PropertyBinding.findNode(this.root,i.nodeName);if(n)if(!e)e=n;else{if(n===e||zs.isDescendantOf(e,n))continue;if(!zs.isDescendantOf(n,e)){for(;!zs.isDescendantOf(n,e)&&n.parent;)n=n.parent;zs.isDescendantOf(n,e)||console.error("USDZExporter: Animation clip targets multiple roots that are not parent/child. Please report a bug",this.root,this.clip,e,n)}e=n}}}catch(t){console.error("USDZExporter: Exception when trying to find nearest animated root. Please report a bug",t),e=void 0}return e}}class Oe{clip;pos;rot;scale;root;target;duration=0;useRootMotion=!1;static frameRate=60;static animationDurationPadding=6/60;static restPoseClipDuration=6/60;constructor(e,t,i){if(this.root=e,this.target=t,this.clip=i,i?this.duration=i.duration:this.duration=Oe.restPoseClipDuration,i&&i.tracks){const o=Math.max(...i.tracks.map(r=>r.times[r.times.length-1]));o!==this.duration&&(console.warn("USDZExporter: Animation clip duration does not match the maximum time value in the tracks.",i,o,this.duration),this.duration=o)}const n=x.getComponent(e,mt);n&&(this.useRootMotion=n.applyRootMotion)}addTrack(e){if(!this.clip){console.error("This is a rest clip but you're trying to add tracks to it – this is likely a bug");return}e.name.endsWith("position")?this.pos=e:e.name.endsWith("quaternion")?this.rot=e:e.name.endsWith("scale")?this.scale=e:(e.name.endsWith("activeSelf")?console.warn("[USDZ] Animation of enabled/disabled state is not supported for USDZ export and will NOT be exported: "+e.name+" on "+(this.root?.name??this.target.name)+". Animate scale 0/1 instead."):console.warn("[USDZ] Animation track type not supported for USDZ export and will NOT be exported: "+e.name+" on "+(this.root?.name??this.target.name)+". Only .position, .rotation, .scale are supported."),A()&&ce("[USDZ] Some animations can't be exported. See console for details."))}getFrames(){return this.clip?Math.max(this.pos?.times?.length??0,this.rot?.times?.length??0,this.scale?.times?.length??0):2}getDuration(){return this.duration}getSortedTimesArray(e=!0,t=!0,i=!0){if(!this.clip)return[0,this.duration];const n=this.pos?.times,o=this.rot?.times,r=this.scale?.times,a=[];if(e&&n)for(const l of n)a.push(l);if(t&&o)for(const l of o)a.push(l);if(i&&r)for(const l of r)a.push(l);return a.includes(0)||a.push(0),a.sort((l,h)=>l-h),[...new Set(a)]}*getValues(e,t=!0,i=!0,n=!0){const o=new c.Vector3,r=new c.Quaternion,a=new c.Vector3(1,1,1),l=this.target,h=t?this.pos?.createInterpolant():void 0,d=i?this.rot?.createInterpolant():void 0,u=n?this.scale?.createInterpolant():void 0;h||o.set(l.position.x,l.position.y,l.position.z),d||r.set(l.quaternion.x,l.quaternion.y,l.quaternion.z,l.quaternion.w),u||a.set(l.scale.x,l.scale.y,l.scale.z),h&&h.valueSize!==3&&(h.valueSize=3),d&&d.valueSize!==4&&(d.valueSize=4),u&&u.valueSize!==3&&(u.valueSize=3);const p=0;for(let m=0-p;m<e.length+p;m++){let y=0,b=0;if(m<0?(y=e[0],b=y-Oe.animationDurationPadding/2+1/60):m>=e.length?(y=e[e.length-1],b=y+Oe.animationDurationPadding/2-1/60):(y=e[m],b=y),h){const g=h.evaluate(y);o.set(g[0],g[1],g[2])}if(d){const g=d.evaluate(y);r.set(g[0],g[1],g[2],g[3])}if(u){const g=u.evaluate(y);a.set(g[0],g[1],g[2])}if(this.useRootMotion&&l===this.root){const g=new c.Matrix4;g.compose(o,r,a),g.multiply(l.matrix),g.decompose(o,r,a)}yield{time:b,translation:o,rotation:r,scale:a,index:m}}}}class Jd{get extensionName(){return"animation"}get animationData(){return this.dict}get registeredClips(){return this.clipToStartTime.keys()}get animatedRoots(){return this.rootTargetMap.keys()}get holdClipMap(){return this.clipToHoldClip}dict=new Map;rootTargetMap=new Map;rootAndClipToRegisteredAnimationMap=new Map;rootToRegisteredClip=new Map;lastClipEndTime=0;clipToStartTime=new Map;clipToHoldClip=new Map;serializers=[];injectRestPoses=!1;injectImplicitBehaviours=!1;constructor(e){this.injectRestPoses=e,this.injectImplicitBehaviours=e}getStartTimeCode(){return!this.injectRestPoses||this.rootAndClipToRegisteredAnimationMap.size===0?0:(Oe.restPoseClipDuration+Oe.animationDurationPadding)*60}getEndTimeCode(){let e=0;for(const[t,i]of this.rootAndClipToRegisteredAnimationMap){const n=i.start+i.duration;n>e&&(e=n)}return e*60}getClipCount(e){return this.rootToRegisteredClip.get(e)?.length??0??0}getStartTimeByClip(e){return e?this.clipToStartTime.has(e)?this.clipToStartTime.get(e):(console.error("USDZExporter: Missing start time for clip – please report a bug.",e),0):0}registerAnimation(e,t){if(!e)return null;this.rootTargetMap.has(e)||this.rootTargetMap.set(e,[]);const i=e.uuid+(t?.uuid??"-rest");if(this.rootAndClipToRegisteredAnimationMap.has(i))return this.rootAndClipToRegisteredAnimationMap.get(i);yn&&console.log("registerAnimation",e,t);const n=this.injectRestPoses?1:0,o=(this.rootToRegisteredClip.get(e)?.length??0)+n,r=this.rootTargetMap.get(e),a=new Set(r);if(t&&t.tracks)for(const h of t.tracks){const d=c.PropertyBinding.parseTrackName(h.name),u=c.PropertyBinding.findNode(e,d.nodeName);if(!u){console.warn("no object found for track",h.name,"using "+e.name+" instead");continue}this.dict.has(u)||this.dict.set(u,[]);const p=this.dict.get(u);if(!p){console.warn("no transform data found for target ",u,"at slot "+o+", this is likely a bug");continue}a.delete(u),this.injectRestPoses&&!p[0]&&(console.log("Injecting rest pose",u,t,"at slot",o),p[0]=new Oe(null,u,null));let m=p[o];m||(m=new Oe(e,u,t),p[o]=m),m.addTrack(h),r?.includes(u)||r?.push(u)}yn&&console.log("Unregistered nodes for this clip",a,"clip",t,"at slot",o,"for root",e,"targets",r);for(const h of a){const d=this.dict.get(h);if(!d)continue;if(this.injectRestPoses&&!d[0]){console.warn("Adding rest pose for ",h,t,"at slot",o,"This is likely a bug, should have been added earlier.");const p=new Oe(null,h,null);d[0]=p}let u=d[o];u||(yn&&console.log("Adding padding clip for ",h,t,"at slot",o),u=new Oe(e,h,t),d[o]=u)}const l=new zs(this,e,t);if(this.rootAndClipToRegisteredAnimationMap.set(i,l),yn&&console.log({root:e,clip:t,info:l}),t){const h=this.rootToRegisteredClip.get(e);if(h?h.push(t):this.rootToRegisteredClip.set(e,[t]),!this.clipToStartTime.get(t)){this.lastClipEndTime==null&&(this.lastClipEndTime=Oe.restPoseClipDuration);let u=this.lastClipEndTime+Oe.animationDurationPadding,p=u+t.duration;const m=Math.round(u*60)/60,y=Math.round(p*60)/60;Math.abs(m-u)<.01&&(u=m),Math.abs(y-p)<.01&&(p=y),u=Math.ceil(u),p=u+t.duration,this.clipToStartTime.set(t,u),this.lastClipEndTime=p}}return l}onAfterHierarchy(e){yn&&console.log("Animation clips per animation target node",this.dict)}onAfterBuildDocument(e){yn&&console.log("Animation data",{dict:this.dict,rootTargetMap:this.rootTargetMap,rootToRegisteredClip:this.rootToRegisteredClip});for(const t of this.rootTargetMap.keys()){const i=this.rootTargetMap.get(t);if(!i)continue;let n;const o=[];for(const r of i){const a=this.dict.get(r);if(!a){console.error("No data found for target on USDZ export – please report a bug!",r);continue}n===void 0&&(n=a?.length),n!==a?.length&&console.error("Different array lengths for targets – please report a bug!",a);for(let l=0;l<a.length;l++){let h=a[l];if(!h){const u=l-(this.injectRestPoses?1:0);a[l]=new Oe(null,r,this.rootToRegisteredClip.get(t)[u]),h=a[l]}const d=h.getDuration();if(o[l]===void 0)o[l]=d;else if(o[l]!==d){console.error("Error during UDSZ export: Encountered different animation durations for animated targets. Please report a bug!",{datas:a,target:r}),o[l]=d;continue}}}}for(const t of this.serializers){const i=t.model?.parent,n=i?.isDynamic===!0;_p&&console.log(n,t.model?.parent),n&&t.registerCallback(i)}}onExportObject(e,t,i){x.foreachComponent(e,o=>{const r=o;typeof r.createAnimation=="function"&&r.createAnimation(this,t,i)},!1);const n=new dM(e,this);this.serializers.push(n),n.registerCallback(t)}}class dM{model=void 0;object;animationData;ext;callback;constructor(e,t){this.object=e,this.animationData=t.animationData,this.ext=t}registerCallback(e){this.model&&this.callback&&this.model.removeEventListener("serialize",this.callback),this.callback||(this.callback=this.onSerialize.bind(this)),_p&&console.log("REPARENT",e),this.model=e,this.callback&&this.model.addEventListener("serialize",this.callback)}skinnedMeshExport(e,t,i){const n=this.model,o=this.animationData;if(n&&n.skinnedMesh){let r=function(E){const F=[];for(const[z,K]of E){let ee=`${z} : [`;const le=[];for(const me of K)le.push(`(${te(me.x)}, ${te(me.y)}, ${te(me.z)})`);ee=ee.concat(le.join(", ")),ee=ee.concat("],"),F.push(ee)}return F},a=function(E){const F=[];for(const[z,K]of E){let ee=`${z} : [`;const le=[];for(const me of K)le.push(`(${te(me.w)}, ${te(me.x)}, ${te(me.y)}, ${te(me.z)})`);ee=ee.concat(le.join(", ")),ee=ee.concat("],"),F.push(ee)}return F},l=function(E){let F,z=!0;const K=new Map;for(const[le,me]of E){F===void 0&&(F=me.length),F!==me.length&&(z=!1);let We=0;for(const vi of me)We++,vi||(K.has(le)||K.set(le,[]),K.get(le).push(We))}yn&&console.log("Bone count: ",E.size,"TransformData entries per bone: ",F,"Undefined bone entries: ",K),console.assert(z,"All bones should have the same number of TransformData entries",E),console.assert(K.size===0,"All TransformData entries should be set",K);const ee=[];for(const[le,me]of E)for(let We=0;We<me.length;We++){const vi=me[We],Yc=i.getStartTimeByClip(vi.clip);ee.length<=We&&ee.push({pos:[],rot:[],scale:[],timeOffset:Yc});const Ss=ee[We];Ss.pos.push(...vi.getSortedTimesArray(!0,!1,!1)),Ss.rot.push(...vi.getSortedTimesArray(!1,!0,!1)),Ss.scale.push(...vi.getSortedTimesArray(!1,!1,!0))}for(const le of ee)le.pos.sort((me,We)=>me-We),le.rot.sort((me,We)=>me-We),le.scale.sort((me,We)=>me-We),le.pos=[...new Set(le.pos)],le.rot=[...new Set(le.rot)],le.scale=[...new Set(le.scale)];return ee},h=function(E,F,z){const K=new Map,ee=new Map,le=new Map,me=F.length;for(const We of z){const vi=E.get(We);let Yc;vi?console.assert(vi.length===me,"We should have the same number of TransformData entries for each bone",vi,F):Yc=new Oe(null,We,null);for(let Ss=0;Ss<me;Ss++){const Tu=vi?vi[Ss]:Yc,vr=F[Ss];for(const{time:Da,translation:Ia}of Tu.getValues(vr.pos,!0,!1,!1)){const Wi=(Da+vr.timeOffset)*60;K.has(Wi)||K.set(Wi,new Array),K.get(Wi).push(Ia.clone())}for(const{time:Da,rotation:Ia}of Tu.getValues(vr.rot,!1,!0,!1)){const Wi=(Da+vr.timeOffset)*60;ee.has(Wi)||ee.set(Wi,new Array),ee.get(Wi).push(Ia.clone())}for(const{time:Da,scale:Ia}of Tu.getValues(vr.scale,!1,!1,!0)){const Wi=(Da+vr.timeOffset)*60;le.has(Wi)||le.set(Wi,new Array),le.get(Wi).push(Ia.clone())}}}return{position:K.size==0?void 0:K,quaternion:ee.size==0?void 0:ee,scale:le.size==0?void 0:le}},d=function(E){const F=[];for(const z of E)F.push(`(${te(z.x)}, ${te(z.y)}, ${te(z.z)})`);return F.join(", ")},u=function(E){const F=[];for(const z of E)F.push(`(${te(z.w)}, ${te(z.x)}, ${te(z.y)}, ${te(z.z)})`);return F.join(", ")},p=function(E){const F=new Map;if(yn){const z=new Array;for(const[K,ee]of o)z.push(K.uuid+": "+ee.length+" "+ee.map(le=>le.clip?.uuid.substring(0,6)).join(" "));console.log(`getPerBoneTransformData
1260
+ }`}function u_(s){return`(${s.r}, ${s.g}, ${s.b})`}function f_(s){return`(${s.x}, ${s.y})`}const qm=[1023,33777,33778,33779,35842,35843,37496,37808,37809,37810,37811,37812,37813,37814,37815,37816,37817,37818,37819,37820,37821,36492];w("debugusdz");class pt{static global_id=0;id;trigger;action;exclusive=!1;makeExclusive(e){return this.exclusive=e,this}constructor(e,t,i){this.id="Behavior_"+ji(e)+"_"+pt.global_id++,this.trigger=t,this.action=i}writeTo(e,t,i){if(!this.trigger||!this.action)return;i.beginBlock(`def Preliminary_Behavior "${this.id}"`);let n="";if(Array.isArray(this.trigger)){n="[";for(let o=0;o<this.trigger.length;o++){const r=this.trigger[o];n+="<"+r.id+">",o+1<this.trigger.length&&(n+=", ")}n+="]"}else n=`<${this.trigger.id}>`;if(i.appendLine(`rel triggers = ${n}`),i.appendLine(`rel actions = <${this.action.id}>`),i.appendLine(`uniform bool exclusive = ${this.exclusive?1:0}`),i.appendLine(),Array.isArray(this.trigger))for(const o of this.trigger)o.writeTo(t,i),i.appendLine();else this.trigger.writeTo(t,i);i.appendLine(),this.action.writeTo(t,i),i.closeBlock()}}const Or=new Set;function yp(s,e){let t="";if(Array.isArray(s)){Or.clear();let i="[ ";for(let n=0;n<s.length;n++){let o=s[n];if(!o){console.warn("Invalid target object in behavior",s+". Is the object exported?");continue}if(typeof o=="string"){if(Or.has(o))continue;i+=o,Or.add(o)}else if(typeof o=="object"){if(o.isObject3D&&(o=e.findById(o.uuid),!o)){console.warn("Invalid target object in behavior",s+". Is the object exported?");continue}const r=o.getPath?.call(o);if(Or.has(r))continue;i+=r,Or.add(r)}n+1<s.length&&(i+=", ")}i+=" ]",t=i,Or.clear()}else if(typeof s=="object"){const i=s;if(i.isObject3D&&(s=e.findById(i.uuid)),!s)throw console.error("Invalid target object in behavior, the target object is likely missing from USDZ export. Is the object exported?",i),new Error(`Invalid target object in behavior, the target object is likely missing from USDZ export. Please report a bug. uuid: ${i.uuid}.`);t=s.getPath?.call(s)}return t}class Ws{static global_id=0;id;targetId;tokenId;type;distance;constructor(e,t){e&&(this.targetId=e),t?this.id=t:this.id="Trigger_"+Ws.global_id++}writeTo(e,t){t.beginBlock(`def Preliminary_Trigger "${this.id}"`),this.targetId&&(typeof this.targetId!="string"&&(this.targetId=yp(this.targetId,e)),t.appendLine("rel affectedObjects = "+this.targetId)),this.tokenId&&t.appendLine(`token info:id = "${this.tokenId}"`),this.type&&t.appendLine(`token type = "${this.type}"`),typeof this.distance=="number"&&t.appendLine(`double distance = ${this.distance}`),t.closeBlock()}}function p_(s,e={direct:!0,indirect:!0}){const t=ze.createEmpty();t.name="InputTarget_"+t.name,t.displayName=void 0,t.type="RealityKitComponent",t.onSerialize=i=>{i.appendLine("bool allowsDirectInput = "+(e.direct?1:0)),i.appendLine("bool allowsIndirectInput = "+(e.indirect?1:0)),i.appendLine('uniform token info:id = "RealityKit.InputTarget"')},s.add(t)}class xt{static __sceneStartTrigger;static sceneStartTrigger(){if(this.__sceneStartTrigger!==void 0)return this.__sceneStartTrigger;const e=new Ws(void 0,"SceneStart");return e.tokenId="SceneTransition",e.type="enter",this.__sceneStartTrigger=e,e}static tapTrigger(e,t={direct:!0,indirect:!0}){const i=new Ws(e);if(Array.isArray(e)&&e.length>1)for(const n of e)n instanceof ze&&p_(n,t);else e instanceof ze&&p_(e,t);return i.tokenId="TapGesture",i}static isTapTrigger(e){return e?.tokenId==="TapGesture"}static proximityToCameraTrigger(e,t){const i=new Ws(e);return i.tokenId="ProximityToCamera",i.distance=t,i}}class Oo{static global_id=0;static getId(){return this.global_id++}id;actions;loops=0;performCount=1;type="serial";multiplePerformOperation=void 0;constructor(e,t){this.id=e,this.actions=t}addAction(e){return this.actions.push(e),this}makeParallel(){return this.type="parallel",this}makeSequence(){return this.type="serial",this}makeLooping(){return this.loops=1,this.performCount=0,this}makeRepeat(e){return this.performCount=e,this}writeTo(e,t){t.beginBlock(`def Preliminary_Action "${this.id}"`),t.beginArray("rel actions");for(const i of this.actions){if(!i)continue;const n=i===this.actions[this.actions.length-1];t.appendLine("<"+i.id+">"+(n?"":", "))}t.closeArray(),t.appendLine(),t.appendLine('token info:id = "Group"'),t.appendLine(`bool loops = ${this.loops}`),t.appendLine(`int performCount = ${this.loops>0?0:Math.max(0,this.performCount)}`),t.appendLine(`token type = "${this.type}"`),typeof this.multiplePerformOperation=="string"&&t.appendLine(`token multiplePerformOperation = "${this.multiplePerformOperation}"`),t.appendLine();for(const i of this.actions)i&&(i.writeTo(e,t),t.appendLine());t.closeBlock()}}class Vt{static global_id=0;id;tokenId;affectedObjects;easeType;motionType=void 0;duration;moveDistance;style;type;front;up;start;animationSpeed;reversed;pingPong;xFormTarget;audio;gain;auralMode;multiplePerformOperation;velocity;comment;animationName;clone(){const e=new Vt,t=e.id;return Object.assign(e,this),e.id=t,e}constructor(e,t){e&&(this.affectedObjects=e),t?this.id=t:this.id="Action",this.id+="_"+Vt.global_id++}writeTo(e,t){t.beginBlock(`def Preliminary_Action "${this.id}"`),this.comment&&t.appendLine(`# ${this.comment}`),this.affectedObjects&&(typeof this.affectedObjects!="string"&&(this.affectedObjects=yp(this.affectedObjects,e)),t.appendLine("rel affectedObjects = "+this.affectedObjects)),typeof this.duration=="number"&&(typeof this.animationSpeed=="number"&&this.animationSpeed!==1?t.appendLine(`double duration = ${this.duration/this.animationSpeed} `):t.appendLine(`double duration = ${this.duration} `)),this.easeType&&t.appendLine(`token easeType = "${this.easeType}"`),this.tokenId&&t.appendLine(`token info:id = "${this.tokenId}"`),this.tokenId==="ChangeScene"&&t.appendLine("rel scene = </StageRoot/Scenes/Scene>"),this.motionType!==void 0&&t.appendLine(`token motionType = "${this.motionType}"`),typeof this.moveDistance=="number"&&t.appendLine(`double moveDistance = ${this.moveDistance} `),this.style&&t.appendLine(`token style = "${this.style}"`),this.type&&t.appendLine(`token type = "${this.type}"`),this.front&&t.appendLine(`vector3d front = (${this.front.x}, ${this.front.y}, ${this.front.z})`),this.up&&t.appendLine(`vector3d upVector = (${this.up.x}, ${this.up.y}, ${this.up.z})`),typeof this.start=="number"&&t.appendLine(`double start = ${this.start} `),typeof this.animationSpeed=="number"&&t.appendLine(`double animationSpeed = ${this.animationSpeed.toFixed(2)} `),typeof this.reversed=="boolean"&&t.appendLine(`bool reversed = ${this.reversed}`),typeof this.pingPong=="boolean"&&t.appendLine(`bool reverses = ${this.pingPong}`),this.xFormTarget&&(typeof this.xFormTarget!="string"&&(this.xFormTarget=yp(this.xFormTarget,e)),t.appendLine(`rel xformTarget = ${this.xFormTarget}`)),typeof this.audio=="string"&&t.appendLine(`asset audio = @${this.audio}@`),typeof this.gain=="number"&&t.appendLine(`double gain = ${this.gain}`),typeof this.auralMode=="string"&&t.appendLine(`token auralMode = "${this.auralMode}"`),typeof this.multiplePerformOperation=="string"&&t.appendLine(`token multiplePerformOperation = "${this.multiplePerformOperation}"`),typeof this.velocity=="object"&&t.appendLine(`vector3d velocity = (${this.velocity.x}, ${this.velocity.y}, ${this.velocity.z})`),t.closeBlock()}}class Ti{x=0;y=0;z=0;constructor(e,t,i){this.x=e,this.y=t,this.z=i}static get up(){return new Ti(0,1,0)}static get right(){return new Ti(1,0,0)}static get forward(){return new Ti(0,0,1)}static get back(){return new Ti(0,0,-1)}static get zero(){return new Ti(0,0,0)}}class ae{static sequence(...e){return new Oo("Group_"+Oo.getId(),e).makeSequence()}static parallel(...e){return new Oo("Group_"+Oo.getId(),e).makeParallel()}static fadeAction(e,t,i){const n=new Vt(e);return n.tokenId="Visibility",n.type=i?"show":"hide",n.duration=t,n.style="basic",n.motionType="none",n.moveDistance=0,n.easeType="none",n}static startAnimationAction(e,t,i=!1,n=!1){const o=new Vt(e);o.tokenId="StartAnimation";const r=t.start,a=t.duration,l=t.speed,h=t.clipName;if(o.comment=`Animation: ${h}, start=${r*60}, length=${a*60}, end=${(r+a)*60}`,o.animationName=h,o.start=r,o.duration=a,o.animationSpeed=l,o.reversed=i,o.pingPong=n,o.multiplePerformOperation="allow",i&&(o.start-=a),n){o.pingPong=!1;const d=o.clone();return d.reversed=!i,d.start=o.start,d.reversed&&(d.start-=a),ae.sequence(o,d)}return o}static waitAction(e){const t=new Vt;return t.tokenId="Wait",t.duration=e,t.motionType=void 0,t}static lookAtCameraAction(e,t,i,n){const o=new Vt(e);return o.tokenId="LookAtCamera",o.duration=t===void 0?9999999999999:t,o.front=i??Ti.forward,o.up=n??Ti.up,o}static emphasize(e,t,i="bounce",n=1,o="basic"){const r=new Vt(e);return r.tokenId="Emphasize",r.duration=t,r.style=o??"basic",r.motionType=i,r.moveDistance=n,r}static transformAction(e,t,i,n,o="inout"){const r=new Vt(e);return r.tokenId="Transform",r.duration=i,r.duration=Math.max(1e-6,i),r.type=n,r.easeType=i>0?o:"none",Array.isArray(t)&&console.error("Transform target must not be an array",t),r.xFormTarget=t,r}static playAudioAction(e,t,i="play",n=1,o="spatial"){const r=new Vt(e);return r.tokenId="Audio",r.type=i,r.audio=t,r.gain=n,r.auralMode=o,r.multiplePerformOperation="allow",r}static impulseAction(e,t){const i=new Vt(e);return i.tokenId="Impulse",i.velocity=t,i}}class hM{get id(){return this.object.uuid}object;model;constructor(e){this.object=e}apply(e){if(!this.model&&(this.model=e.findById(this.object.uuid),!this.model)){console.error("could not find model with id "+this.object.uuid);return}this.onApply(e)}}class Xm extends hM{constructor(e,t,i,n){super(e),this.matrix=t,this.material=i,this.geometry=n}matrix;material;geometry;onApply(e){const t=this.model;if(!t)return;t.parent?.isDynamic||ze.createEmptyParent(t);const i=t.clone();this.matrix&&i.setMatrix(this.matrix),this.material&&(i.material=this.material),this.geometry&&(i.geometry=this.geometry),t.parent?.add(i)}_enableAction;_disableAction;enable(){return this._enableAction?this._enableAction:(this._enableAction=ae.fadeAction(this.object,0,!0),this._enableAction)}disable(){return this._disableAction?this._disableAction:(this._disableAction=ae.fadeAction(this.object,0,!1),this._disableAction)}}class Uv{actions;sortedActions;constructor(e){this.actions=[...e]}organize(){this.sortedActions={};for(const e of this.actions){const t=e.id;this.sortedActions[t]||(this.sortedActions[t]=[]),this.sortedActions[t].push(e)}}getActions(e){return this.sortedActions||this.organize(),this.sortedActions[e.uuid]}}const yn=w("debugusdzanimation"),_p=w("debugusdzanimationserialization");class zs{_start;get start(){return this._start===void 0&&(this._start=this.ext.getStartTimeByClip(this.clip)),this._start}get duration(){return this.clip?.duration??ke.restPoseClipDuration}get nearestAnimatedRoot(){return this._nearestAnimatedRoot}get clipName(){return this.clip?.name??"rest"}ext;root;_nearestAnimatedRoot=void 0;clip;speed;constructor(e,t,i){this.ext=e,this.root=t,this.clip=i,this._nearestAnimatedRoot=this.getNearestAnimatedRoot()}static isDescendantOf(e,t){let i=t;if(!i||!e)return!1;for(;i;){if(!i)return!1;if(i===e)return!0;i=i.parent}return!1}getNearestAnimatedRoot(){let e;try{for(const t of this.clip?.tracks??[]){const i=c.PropertyBinding.parseTrackName(t.name);let n=c.PropertyBinding.findNode(this.root,i.nodeName);if(n)if(!e)e=n;else{if(n===e||zs.isDescendantOf(e,n))continue;if(!zs.isDescendantOf(n,e)){for(;!zs.isDescendantOf(n,e)&&n.parent;)n=n.parent;zs.isDescendantOf(n,e)||console.error("USDZExporter: Animation clip targets multiple roots that are not parent/child. Please report a bug",this.root,this.clip,e,n)}e=n}}}catch(t){console.error("USDZExporter: Exception when trying to find nearest animated root. Please report a bug",t),e=void 0}return e}}class ke{clip;pos;rot;scale;root;target;duration=0;useRootMotion=!1;static frameRate=60;static animationDurationPadding=6/60;static restPoseClipDuration=6/60;constructor(e,t,i){if(this.root=e,this.target=t,this.clip=i,i?this.duration=i.duration:this.duration=ke.restPoseClipDuration,i&&i.tracks){const o=Math.max(...i.tracks.map(r=>r.times[r.times.length-1]));o!==this.duration&&(console.warn("USDZExporter: Animation clip duration does not match the maximum time value in the tracks.",i,o,this.duration),this.duration=o)}const n=x.getComponent(e,mt);n&&(this.useRootMotion=n.applyRootMotion)}addTrack(e){if(!this.clip){console.error("This is a rest clip but you're trying to add tracks to it – this is likely a bug");return}e.name.endsWith("position")?this.pos=e:e.name.endsWith("quaternion")?this.rot=e:e.name.endsWith("scale")?this.scale=e:(e.name.endsWith("activeSelf")?console.warn("[USDZ] Animation of enabled/disabled state is not supported for USDZ export and will NOT be exported: "+e.name+" on "+(this.root?.name??this.target.name)+". Animate scale 0/1 instead."):console.warn("[USDZ] Animation track type not supported for USDZ export and will NOT be exported: "+e.name+" on "+(this.root?.name??this.target.name)+". Only .position, .rotation, .scale are supported."),A()&&ce("[USDZ] Some animations can't be exported. See console for details."))}getFrames(){return this.clip?Math.max(this.pos?.times?.length??0,this.rot?.times?.length??0,this.scale?.times?.length??0):2}getDuration(){return this.duration}getSortedTimesArray(e=!0,t=!0,i=!0){if(!this.clip)return[0,this.duration];const n=this.pos?.times,o=this.rot?.times,r=this.scale?.times,a=[];if(e&&n)for(const l of n)a.push(l);if(t&&o)for(const l of o)a.push(l);if(i&&r)for(const l of r)a.push(l);return a.includes(0)||a.push(0),a.sort((l,h)=>l-h),[...new Set(a)]}*getValues(e,t=!0,i=!0,n=!0){const o=new c.Vector3,r=new c.Quaternion,a=new c.Vector3(1,1,1),l=this.target,h=t?this.pos?.createInterpolant():void 0,d=i?this.rot?.createInterpolant():void 0,u=n?this.scale?.createInterpolant():void 0;h||o.set(l.position.x,l.position.y,l.position.z),d||r.set(l.quaternion.x,l.quaternion.y,l.quaternion.z,l.quaternion.w),u||a.set(l.scale.x,l.scale.y,l.scale.z),h&&h.valueSize!==3&&(h.valueSize=3),d&&d.valueSize!==4&&(d.valueSize=4),u&&u.valueSize!==3&&(u.valueSize=3);const p=0;for(let m=0-p;m<e.length+p;m++){let y=0,b=0;if(m<0?(y=e[0],b=y-ke.animationDurationPadding/2+1/60):m>=e.length?(y=e[e.length-1],b=y+ke.animationDurationPadding/2-1/60):(y=e[m],b=y),h){const g=h.evaluate(y);o.set(g[0],g[1],g[2])}if(d){const g=d.evaluate(y);r.set(g[0],g[1],g[2],g[3])}if(u){const g=u.evaluate(y);a.set(g[0],g[1],g[2])}if(this.useRootMotion&&l===this.root){const g=new c.Matrix4;g.compose(o,r,a),g.multiply(l.matrix),g.decompose(o,r,a)}yield{time:b,translation:o,rotation:r,scale:a,index:m}}}}class Jd{get extensionName(){return"animation"}get animationData(){return this.dict}get registeredClips(){return this.clipToStartTime.keys()}get animatedRoots(){return this.rootTargetMap.keys()}get holdClipMap(){return this.clipToHoldClip}dict=new Map;rootTargetMap=new Map;rootAndClipToRegisteredAnimationMap=new Map;rootToRegisteredClip=new Map;lastClipEndTime=0;clipToStartTime=new Map;clipToHoldClip=new Map;serializers=[];injectRestPoses=!1;injectImplicitBehaviours=!1;constructor(e){this.injectRestPoses=e,this.injectImplicitBehaviours=e}getStartTimeCode(){return!this.injectRestPoses||this.rootAndClipToRegisteredAnimationMap.size===0?0:(ke.restPoseClipDuration+ke.animationDurationPadding)*60}getEndTimeCode(){let e=0;for(const[t,i]of this.rootAndClipToRegisteredAnimationMap){const n=i.start+i.duration;n>e&&(e=n)}return e*60}getClipCount(e){return this.rootToRegisteredClip.get(e)?.length??0??0}getStartTimeByClip(e){return e?this.clipToStartTime.has(e)?this.clipToStartTime.get(e):(console.error("USDZExporter: Missing start time for clip – please report a bug.",e),0):0}registerAnimation(e,t){if(!e)return null;this.rootTargetMap.has(e)||this.rootTargetMap.set(e,[]);const i=e.uuid+(t?.uuid??"-rest");if(this.rootAndClipToRegisteredAnimationMap.has(i))return this.rootAndClipToRegisteredAnimationMap.get(i);yn&&console.log("registerAnimation",e,t);const n=this.injectRestPoses?1:0,o=(this.rootToRegisteredClip.get(e)?.length??0)+n,r=this.rootTargetMap.get(e),a=new Set(r);if(t&&t.tracks)for(const h of t.tracks){const d=c.PropertyBinding.parseTrackName(h.name),u=c.PropertyBinding.findNode(e,d.nodeName);if(!u){console.warn("no object found for track",h.name,"using "+e.name+" instead");continue}this.dict.has(u)||this.dict.set(u,[]);const p=this.dict.get(u);if(!p){console.warn("no transform data found for target ",u,"at slot "+o+", this is likely a bug");continue}a.delete(u),this.injectRestPoses&&!p[0]&&(console.log("Injecting rest pose",u,t,"at slot",o),p[0]=new ke(null,u,null));let m=p[o];m||(m=new ke(e,u,t),p[o]=m),m.addTrack(h),r?.includes(u)||r?.push(u)}yn&&console.log("Unregistered nodes for this clip",a,"clip",t,"at slot",o,"for root",e,"targets",r);for(const h of a){const d=this.dict.get(h);if(!d)continue;if(this.injectRestPoses&&!d[0]){console.warn("Adding rest pose for ",h,t,"at slot",o,"This is likely a bug, should have been added earlier.");const p=new ke(null,h,null);d[0]=p}let u=d[o];u||(yn&&console.log("Adding padding clip for ",h,t,"at slot",o),u=new ke(e,h,t),d[o]=u)}const l=new zs(this,e,t);if(this.rootAndClipToRegisteredAnimationMap.set(i,l),yn&&console.log({root:e,clip:t,info:l}),t){const h=this.rootToRegisteredClip.get(e);if(h?h.push(t):this.rootToRegisteredClip.set(e,[t]),!this.clipToStartTime.get(t)){this.lastClipEndTime==null&&(this.lastClipEndTime=ke.restPoseClipDuration);let u=this.lastClipEndTime+ke.animationDurationPadding,p=u+t.duration;const m=Math.round(u*60)/60,y=Math.round(p*60)/60;Math.abs(m-u)<.01&&(u=m),Math.abs(y-p)<.01&&(p=y),u=Math.ceil(u),p=u+t.duration,this.clipToStartTime.set(t,u),this.lastClipEndTime=p}}return l}onAfterHierarchy(e){yn&&console.log("Animation clips per animation target node",this.dict)}onAfterBuildDocument(e){yn&&console.log("Animation data",{dict:this.dict,rootTargetMap:this.rootTargetMap,rootToRegisteredClip:this.rootToRegisteredClip});for(const t of this.rootTargetMap.keys()){const i=this.rootTargetMap.get(t);if(!i)continue;let n;const o=[];for(const r of i){const a=this.dict.get(r);if(!a){console.error("No data found for target on USDZ export – please report a bug!",r);continue}n===void 0&&(n=a?.length),n!==a?.length&&console.error("Different array lengths for targets – please report a bug!",a);for(let l=0;l<a.length;l++){let h=a[l];if(!h){const u=l-(this.injectRestPoses?1:0);a[l]=new ke(null,r,this.rootToRegisteredClip.get(t)[u]),h=a[l]}const d=h.getDuration();if(o[l]===void 0)o[l]=d;else if(o[l]!==d){console.error("Error during UDSZ export: Encountered different animation durations for animated targets. Please report a bug!",{datas:a,target:r}),o[l]=d;continue}}}}for(const t of this.serializers){const i=t.model?.parent,n=i?.isDynamic===!0;_p&&console.log(n,t.model?.parent),n&&t.registerCallback(i)}}onExportObject(e,t,i){x.foreachComponent(e,o=>{const r=o;typeof r.createAnimation=="function"&&r.createAnimation(this,t,i)},!1);const n=new dM(e,this);this.serializers.push(n),n.registerCallback(t)}}class dM{model=void 0;object;animationData;ext;callback;constructor(e,t){this.object=e,this.animationData=t.animationData,this.ext=t}registerCallback(e){this.model&&this.callback&&this.model.removeEventListener("serialize",this.callback),this.callback||(this.callback=this.onSerialize.bind(this)),_p&&console.log("REPARENT",e),this.model=e,this.callback&&this.model.addEventListener("serialize",this.callback)}skinnedMeshExport(e,t,i){const n=this.model,o=this.animationData;if(n&&n.skinnedMesh){let r=function(E){const F=[];for(const[z,K]of E){let ee=`${z} : [`;const le=[];for(const me of K)le.push(`(${te(me.x)}, ${te(me.y)}, ${te(me.z)})`);ee=ee.concat(le.join(", ")),ee=ee.concat("],"),F.push(ee)}return F},a=function(E){const F=[];for(const[z,K]of E){let ee=`${z} : [`;const le=[];for(const me of K)le.push(`(${te(me.w)}, ${te(me.x)}, ${te(me.y)}, ${te(me.z)})`);ee=ee.concat(le.join(", ")),ee=ee.concat("],"),F.push(ee)}return F},l=function(E){let F,z=!0;const K=new Map;for(const[le,me]of E){F===void 0&&(F=me.length),F!==me.length&&(z=!1);let We=0;for(const vi of me)We++,vi||(K.has(le)||K.set(le,[]),K.get(le).push(We))}yn&&console.log("Bone count: ",E.size,"TransformData entries per bone: ",F,"Undefined bone entries: ",K),console.assert(z,"All bones should have the same number of TransformData entries",E),console.assert(K.size===0,"All TransformData entries should be set",K);const ee=[];for(const[le,me]of E)for(let We=0;We<me.length;We++){const vi=me[We],Yc=i.getStartTimeByClip(vi.clip);ee.length<=We&&ee.push({pos:[],rot:[],scale:[],timeOffset:Yc});const Ss=ee[We];Ss.pos.push(...vi.getSortedTimesArray(!0,!1,!1)),Ss.rot.push(...vi.getSortedTimesArray(!1,!0,!1)),Ss.scale.push(...vi.getSortedTimesArray(!1,!1,!0))}for(const le of ee)le.pos.sort((me,We)=>me-We),le.rot.sort((me,We)=>me-We),le.scale.sort((me,We)=>me-We),le.pos=[...new Set(le.pos)],le.rot=[...new Set(le.rot)],le.scale=[...new Set(le.scale)];return ee},h=function(E,F,z){const K=new Map,ee=new Map,le=new Map,me=F.length;for(const We of z){const vi=E.get(We);let Yc;vi?console.assert(vi.length===me,"We should have the same number of TransformData entries for each bone",vi,F):Yc=new ke(null,We,null);for(let Ss=0;Ss<me;Ss++){const Tu=vi?vi[Ss]:Yc,vr=F[Ss];for(const{time:Da,translation:Ia}of Tu.getValues(vr.pos,!0,!1,!1)){const Wi=(Da+vr.timeOffset)*60;K.has(Wi)||K.set(Wi,new Array),K.get(Wi).push(Ia.clone())}for(const{time:Da,rotation:Ia}of Tu.getValues(vr.rot,!1,!0,!1)){const Wi=(Da+vr.timeOffset)*60;ee.has(Wi)||ee.set(Wi,new Array),ee.get(Wi).push(Ia.clone())}for(const{time:Da,scale:Ia}of Tu.getValues(vr.scale,!1,!1,!0)){const Wi=(Da+vr.timeOffset)*60;le.has(Wi)||le.set(Wi,new Array),le.get(Wi).push(Ia.clone())}}}return{position:K.size==0?void 0:K,quaternion:ee.size==0?void 0:ee,scale:le.size==0?void 0:le}},d=function(E){const F=[];for(const z of E)F.push(`(${te(z.x)}, ${te(z.y)}, ${te(z.z)})`);return F.join(", ")},u=function(E){const F=[];for(const z of E)F.push(`(${te(z.w)}, ${te(z.x)}, ${te(z.y)}, ${te(z.z)})`);return F.join(", ")},p=function(E){const F=new Map;if(yn){const z=new Array;for(const[K,ee]of o)z.push(K.uuid+": "+ee.length+" "+ee.map(le=>le.clip?.uuid.substring(0,6)).join(" "));console.log(`getPerBoneTransformData
1251
1261
  `+z.join(`
1252
- `))}for(const z of E){const K=o.get(z);K&&F.set(z,K)}return F},m=function(E){const F=p(E),z=l(F);return h(F,z,E)};const y=n.skinnedMesh.skeleton,b=new Array,g=[],v=[];for(const E of y.bones){g.push(E),v.push(E.uuid);const F=y.boneInverses[y.bones.indexOf(E)];b.push({bone:E,inverse:F})}let _=1e4;for(;v.length<y.bones.length&&_-- >0;)for(const E of g){const F=E.children;for(const z of F)if(v.indexOf(z.uuid)===-1&&y.bones.indexOf(z)!==-1){g.push(z),v.push(z.uuid);const K=y.boneInverses[y.bones.indexOf(z)];b.push({bone:z,inverse:K})}}_<=0&&console.error("Failed to sort bones in skinned mesh",n.skinnedMesh,y.bones,v);for(const E of Rv(y.bones))b.push({bone:E,inverse:E.matrixWorld.clone().invert()});const S=b[0].bone.parent;S||console.error("No bone parent found for skinned mesh during USDZ export",n.skinnedMesh),b.sort((E,F)=>Qr(E.bone,S)>Qr(F.bone,S)?1:-1);const T=t.quickLookCompatible,M=[],O=[],R=[],B=[];for(const{bone:E}of b){if(T){const F=E.scale;F.x==0&&(F.x=1e-5),F.y==0&&(F.y=1e-5),F.z==0&&(F.z=1e-5),M.push(new c.Matrix4().compose(E.position,E.quaternion,E.scale))}else M.push(E.matrix.clone());O.push(E.position),R.push(E.quaternion),B.push(E.scale)}const L=b.map(E=>'"'+Qr(E.bone,S)+'"').join(", "),N=b.map(E=>h_(E.inverse.clone().invert())).join(", ");e.beginBlock('def Skeleton "Rig"'),e.appendLine(`uniform matrix4d[] bindTransforms = [${N}]`),e.appendLine(`uniform token[] joints = [${L}]`),e.appendLine('uniform token purpose = "guide"'),e.appendLine(`uniform matrix4d[] restTransforms = [${M.map(E=>h_(E)).join(", ")}]`);const $=m(b.map(E=>E.bone));if(yn){let E=1e7,F=0;for(const z of $.position?.keys()??[])E=Math.min(E,z),F=Math.max(F,z);console.log("Time samples",E,F,$)}if(e.beginBlock('def SkelAnimation "_anim"'),e.appendLine(`uniform token[] joints = [${L}]`),e.appendLine(`quatf[] rotations = [${u(R)}]`),$&&$.quaternion){e.beginBlock("quatf[] rotations.timeSamples = {","");const E=a($.quaternion);for(const F of E)e.appendLine(F);e.closeBlock()}if(e.appendLine(`half3[] scales = [${d(B)}]`),$&&$.scale){e.beginBlock("half3[] scales.timeSamples = {","");const E=r($.scale);for(const F of E)e.appendLine(F);e.closeBlock()}if(e.appendLine(`float3[] translations = [${d(O)}]`),$&&$.position){e.beginBlock("float3[] translations.timeSamples = {","");const E=r($.position);for(const F of E)e.appendLine(F);e.closeBlock()}e.closeBlock(),e.closeBlock()}}onSerialize(e,t){if(!this.model)return;const i=this.animationData.get(this.object);if(i)for(let d=0;d<i.length;d++)i[d]===void 0&&(i[d]=new Oe(null,this.object,null));const n=this.ext;this.skinnedMeshExport(e,t,n);const o=this.object,r=this.model,a=this.animationData.get(o);if(!a||o.isSkinnedMesh)return;_p&&console.log("SERIALIZE",this.model.name,this.object.type,a);const l=Intl.NumberFormat("en-US",{maximumFractionDigits:3,minimumFractionDigits:0,useGrouping:!1});function h(d,u){if(d.some(m=>m&&{position:m.pos,rotation:m.rot,scale:m.scale}[u])){switch(u){case"position":r.needsTranslate=!0,e.beginBlock("double3 xformOp:translate.timeSamples = {","");break;case"rotation":r.needsOrient=!0,e.beginBlock("quatf xformOp:orient.timeSamples = {","");break;case"scale":r.needsScale=!0,e.beginBlock("double3 xformOp:scale.timeSamples = {","");break}for(let m=0;m<d.length;m++){const y=d[m];if(!y)continue;const b=n.getStartTimeByClip(y.clip),g=y.getSortedTimesArray(u==="position",u==="rotation",u==="scale");if(!g||g.length===0){console.error("got an animated object but no time values?",o,y);continue}const v=!y.clip,_=u==="position"&&(y.pos||v),S=u==="rotation"&&(y.rot||v),T=u==="scale"&&(y.scale||v);if(_||S||T){const M=y.clip?.name??"rest",O=y.getDuration();yn&&console.log("Write .timeSamples:",M,b,O,d),e.appendLine("# "+M+": start="+l.format(b*Oe.frameRate)+", length="+l.format(O*Oe.frameRate)+", frames="+y.getFrames())}if(_)for(const{time:M,translation:O}of y.getValues(g,!0,!1,!1)){const B=`${l.format((b+M)*Oe.frameRate)}: (${te(O.x)}, ${te(O.y)}, ${te(O.z)}),`;e.appendLine(B)}if(S)for(const{time:M,rotation:O}of y.getValues(g,!1,!0,!1)){const B=`${l.format((b+M)*Oe.frameRate)}: (${te(O.w)}, ${te(O.x)}, ${te(O.y)}, ${te(O.z)}),`;e.appendLine(B)}if(T)for(const{time:M,scale:O}of y.getValues(g,!1,!1,!0)){const B=`${l.format((b+M)*Oe.frameRate)}: (${te(O.x)}, ${te(O.y)}, ${te(O.z)}),`;e.appendLine(B)}}e.closeBlock()}}h(a,"position"),h(a,"rotation"),h(a,"scale")}}const uM=w("debugusdz");class ar{static getName(e){const t=e.split(".").pop();let n=e.split(".").slice(0,-1).join(".").split("/").pop()?.replace(".","_");return n||(n="Audio_"+Math.random().toString(36).substring(2,15)),ji(n)+"."+t}get extensionName(){return"Audio"}files=new Array;onExportObject(e,t,i){const n=x.getComponents(e,Ii);if(n.length)for(const o of n){if(!o.clip||typeof o.clip!="string"||!o.playOnAwake)continue;const r=o.clip.split("/").pop()||"Audio",a=ar.getName(o.clip),l=ji(a);if(!this.files.some(h=>h.path===o.clip)){this.files.push({path:o.clip,name:a});const h=a.toLowerCase();i.quickLookCompatible&&!h.endsWith(".mp3")&&!h.endsWith(".wav")&&!h.endsWith(".m4a")&&console.error("Audio file "+o.clip+" from "+o.name+" is not an MP3 or WAV file. QuickLook may not support playing it.")}i.quickLookCompatible||t.addEventListener("serialize",(h,d)=>{h.appendLine(),h.beginBlock(`def SpatialAudio "${l}"`,"(",!1),h.appendLine(`displayName = "${r}"`),h.closeBlock(")"),h.beginBlock(),h.appendLine(`uniform asset filePath = @audio/${a}@`),h.appendLine(`uniform token auralMode = "${o.spatialBlend>0?"spatial":"nonSpatial"}"`),h.appendLine(`uniform token playbackMode = "${o.loop?"loopFromStage":"onceFromStart"}"`),h.appendLine(`uniform float gain = ${o.volume}`),h.closeBlock()})}}async onAfterSerialize(e){for(const t of this.files){const i="audio/"+t.name;if(e.files[i]){uM&&console.warn("Audio file with name "+i+" already exists in the context. Skipping.");continue}const r=await(await(await fetch(t.path)).blob()).arrayBuffer(),a=new Uint8Array(r);e.files[i]=a}}}var fM=Object.defineProperty,ke=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&fM(e,t,n),n};const m_=w("debugusdzbehaviours");function vc(s){s&&(s.getComponentInParent(aa)||(A()&&console.debug('Raycaster on "'+s.name+'" was automatically added, because no raycaster was found in the parent hierarchy.'),s.addComponent(ui)))}class lr extends k{object;target;duration=1;relativeMotion=!1;coroutine=null;targetPos=new c.Vector3;targetRot=new c.Quaternion;targetScale=new c.Vector3;start(){vc(this.gameObject)}onPointerClick(e){e.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 e=X(this.object).clone(),t=X(this.target).clone(),i=ue(this.object).clone(),n=ue(this.target).clone(),o=Ae(this.object).clone(),r=Ae(this.target).clone(),a=e.distanceTo(t),l=i.angleTo(n),h=o.distanceTo(r);if(a<.01&&l<.01&&h<.01){Ye(this.object,t),Di(this.object,n),Jr(this.object,r),this.coroutine=null;return}let d=0,u=0;for(;d<1;)d+=this.context.time.deltaTime/this.duration,d>1&&(d=1),u=d<.5?4*d*d*d:1-Math.pow(-2*d+2,3)/2,this.targetPos.lerpVectors(e,t,u),this.targetRot.slerpQuaternions(i,n,u),this.targetScale.lerpVectors(o,r,u),Ye(this.object,this.targetPos),Di(this.object,this.targetRot),Jr(this.object,this.targetScale),yield;this.coroutine=null}*moveRelative(){if(!this.target||!this.object)return;const e=this.object.position.clone(),t=this.object.quaternion.clone(),i=this.object.scale.clone(),n=this.target.position.clone(),o=this.target.quaternion.clone(),r=this.target.scale.clone();n.applyQuaternion(this.object.quaternion),this.targetPos.copy(this.object.position).add(n),this.targetRot.copy(this.object.quaternion).multiply(o),this.targetScale.copy(this.object.scale).multiply(r);let a=0,l=0;for(;a<1;)a+=this.context.time.deltaTime/this.duration,a>1&&(a=1),l=a<.5?4*a*a*a:1-Math.pow(-2*a+2,3)/2,this.object.position.lerpVectors(e,this.targetPos,l),this.object.quaternion.slerpQuaternions(t,this.targetRot,l),this.object.scale.lerpVectors(i,this.targetScale,l),yield;this.coroutine=null}beforeCreateDocument(e){if(this.target&&this.object&&this.gameObject){const t=new pt("Move to "+this.target?.name,xt.tapTrigger(this.gameObject),ae.transformAction(this.object,this.target,this.duration,this.relativeMotion?"relative":"absolute"));e.addBehavior(t)}}}ke([f(c.Object3D)],lr.prototype,"object");ke([f(c.Object3D)],lr.prototype,"target");ke([f()],lr.prototype,"duration");ke([f()],lr.prototype,"relativeMotion");const eu=class Tt extends k{materialToSwitch;variantMaterial;fadeDuration=0;start(){this._objectsWithThisMaterial=this.objectsWithThisMaterial,vc(this.gameObject),A()&&this._objectsWithThisMaterial.length<=0&&console.warn('ChangeMaterialOnClick: No objects found with material "'+this.materialToSwitch?.name+'"')}onPointerEnter(e){this.context.input.setCursor("pointer")}onPointerExit(e){this.context.input.unsetCursor("pointer")}onPointerClick(e){if(e.use(),!!this.variantMaterial)for(let t=0;t<this.objectsWithThisMaterial.length;t++){const i=this.objectsWithThisMaterial[t];i.material=this.variantMaterial}}_objectsWithThisMaterial=null;get objectsWithThisMaterial(){return this._objectsWithThisMaterial!=null?this._objectsWithThisMaterial:(this._objectsWithThisMaterial=[],this.variantMaterial&&this.materialToSwitch&&this.context.scene.traverse(e=>{if(e instanceof c.Mesh)if(Array.isArray(e.material)){for(const t of e.material)if(t===this.materialToSwitch){this.objectsWithThisMaterial.push(e);break}}else e.material===this.materialToSwitch?this.objectsWithThisMaterial.push(e):o0(e.material,this.materialToSwitch)&&this.objectsWithThisMaterial.push(e)}),this._objectsWithThisMaterial)}selfModel;targetModels;static _materialTriggersPerId={};static _startHiddenBehaviour=null;static _parallelStartHiddenActions=[];async beforeCreateDocument(e,t){this.targetModels=[],Tt._materialTriggersPerId={},Tt.variantSwitchIndex=0,this.materialToSwitch&&await ne.NEEDLE_progressive.assignTextureLOD(this.materialToSwitch,0),this.variantMaterial&&await ne.NEEDLE_progressive.assignTextureLOD(this.variantMaterial,0)}createBehaviours(e,t,i){this.objectsWithThisMaterial.find(o=>o.uuid===t.uuid)&&this.targetModels.push(t),this.gameObject.uuid===t.uuid&&(this.selfModel=t,this.materialToSwitch&&(Tt._materialTriggersPerId[this.materialToSwitch.uuid]||(Tt._materialTriggersPerId[this.materialToSwitch.uuid]=[]),Tt._materialTriggersPerId[this.materialToSwitch.uuid].push(this)))}afterCreateDocument(e,t){if(!this.materialToSwitch)return;const i=Tt._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 a in n)a!==o.selfModel.uuid&&r.push(...n[a]);o.createAndAttachBehaviors(e,n[o.selfModel.uuid],r)}}delete Tt._materialTriggersPerId[this.materialToSwitch.uuid]}createAndAttachBehaviors(e,t,i){const n=[],o=Math.max(0,this.fadeDuration);n.push(ae.fadeAction([...this.targetModels,...i],o,!1)),n.push(ae.fadeAction(t,o,!0)),e.addBehavior(new pt("Select_"+this.selfModel.name,xt.tapTrigger(this.selfModel),ae.parallel(...n))),Tt._parallelStartHiddenActions.push(...t),Tt._startHiddenBehaviour||(Tt._startHiddenBehaviour=new pt("StartHidden_"+this.selfModel.name,xt.sceneStartTrigger(),ae.fadeAction(Tt._parallelStartHiddenActions,o,!1)),e.addBehavior(Tt._startHiddenBehaviour))}static getMaterialName(e){return ji(e.name||"Material")+"_"+e.id}static variantSwitchIndex=0;createVariants(){if(!this.variantMaterial)return null;const e=[];for(const t of this.targetModels){const i=t.clone();i.name+="_Variant_"+Tt.variantSwitchIndex+++"_"+Tt.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())&&ze.createEmptyParent(t),t.parent&&t.parent.add(i),e.push(i)}return e}};ke([f(c.Material)],eu.prototype,"materialToSwitch");ke([f(c.Material)],eu.prototype,"variantMaterial");ke([f()],eu.prototype,"fadeDuration");let Qm=eu;const wc=class Pe extends k{target;toggleOnClick=!1;targetState=!0;hideSelf=!0;start(){vc(this.gameObject)}onPointerClick(e){e.use(),!this.toggleOnClick&&this.hideSelf&&(this.gameObject.visible=!1),this.target&&(this.target.visible=this.toggleOnClick?!this.target.visible:this.targetState)}selfModel;selfModelClone;targetModel;toggleModel;createBehaviours(e,t,i){t.uuid===this.gameObject.uuid&&(this.selfModel=t,this.selfModelClone=t.clone())}stateBeforeCreatingDocument=!1;targetStateBeforeCreatingDocument=!1;static clonedToggleIndex=0;static wasVisible=Symbol("usdz_SetActiveOnClick_wasVisible");static toggleClone=Symbol("clone for toggling");static reverseToggleClone=Symbol("clone for reverse toggling");beforeCreateDocument(){this.target&&(this.gameObject[Pe.wasVisible]===void 0&&(this.gameObject[Pe.wasVisible]=this.gameObject.activeSelf),this.target[Pe.wasVisible]===void 0&&(this.target[Pe.wasVisible]=this.target.activeSelf),this.stateBeforeCreatingDocument=this.gameObject[Pe.wasVisible],this.targetStateBeforeCreatingDocument=this.target[Pe.wasVisible],this.gameObject.visible=!0,this.target.visible=!0)}afterCreateDocument(e,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())&&Hm.createEmptyParent(this.selfModel),this.toggleModel=this.selfModel.deepClone(),this.toggleModel.name+="_toggle",this.selfModel.parent.add(this.toggleModel);else{if(!this.gameObject[Pe.toggleClone]){const l=this.selfModelClone.clone();l.setMatrix(new c.Matrix4),l.name+="_toggle"+Pe.clonedToggleIndex++,i.add(l),this.gameObject[Pe.toggleClone]=l,console.warn("USDZExport: Toggle "+this.gameObject.name+" doesn't have geometry. It will be deep cloned and nested behaviours will likely not work.")}const a=this.gameObject[Pe.toggleClone];if(!this.gameObject[Pe.reverseToggleClone]){const l=this.selfModelClone.clone();l.setMatrix(new c.Matrix4),l.name+="_toggleReverse"+Pe.clonedToggleIndex++,i.add(l),this.gameObject[Pe.reverseToggleClone]=l}this.toggleModel=this.gameObject[Pe.reverseToggleClone],(!this.toggleModel.geometry||!a.geometry)&&console.error("triggers without childs and without geometry won't work!",this,i.geometry),n=a,i.geometry=null,i.material=null}if(this.toggleModel){if(this.toggleOnClick){const a=[];a.push(ae.fadeAction(n,0,!1)),a.push(ae.fadeAction(this.toggleModel,0,!0)),a.push(ae.fadeAction(this.targetModel,0,o)),e.addBehavior(new pt("Toggle_"+n.name+"_ToggleTo"+(o?"On":"Off"),xt.tapTrigger(n),ae.parallel(...a)));const l=[];l.push(ae.fadeAction(this.toggleModel,0,!1)),l.push(ae.fadeAction(n,0,!0)),l.push(ae.fadeAction(this.targetModel,0,!o)),e.addBehavior(new pt("Toggle_"+n.name+"_ToggleTo"+(o?"Off":"On"),xt.tapTrigger(this.toggleModel),ae.parallel(...l)))}}else{const a=[];this.hideSelf&&a.push(ae.fadeAction(n,0,!1)),a.push(ae.fadeAction(this.targetModel,0,o)),e.addBehavior(new pt("Toggle_"+n.name+"_ToggleTo"+(o?"On":"Off"),xt.tapTrigger(n),a.length>1?ae.parallel(...a):a[0]))}const r=new Array;this.targetStateBeforeCreatingDocument||r.push(this.targetModel),this.stateBeforeCreatingDocument||r.push(i),this.toggleModel&&r.push(this.toggleModel),Ri.add(r,e)}}afterSerialize(e,t){this.gameObject[Pe.wasVisible]!==void 0&&(this.gameObject.visible=this.gameObject[Pe.wasVisible],delete this.gameObject[Pe.wasVisible]),this.target&&this.target[Pe.wasVisible]!==void 0&&(this.target.visible=this.target[Pe.wasVisible],delete this.target[Pe.wasVisible]),delete this.gameObject[Pe.toggleClone],delete this.gameObject[Pe.reverseToggleClone]}};ke([f(c.Object3D)],wc.prototype,"target");ke([f()],wc.prototype,"toggleOnClick");ke([f()],wc.prototype,"targetState");ke([f()],wc.prototype,"hideSelf");let Ym=wc;class Ri extends k{static _fadeBehaviour;static _fadeObjects=[];static add(e,t){const i=Array.isArray(e)?e:[e];for(const n of i)Ri._fadeObjects.includes(n)||(console.log("adding hide on start",n),Ri._fadeObjects.push(n));Ri._fadeBehaviour===void 0&&(Ri._fadeBehaviour=new pt("HideOnStart",xt.sceneStartTrigger(),ae.fadeAction(Ri._fadeObjects,0,!1)),t.addBehavior(Ri._fadeBehaviour))}start(){x.setActive(this.gameObject,!1)}createBehaviours(e,t,i){t.uuid===this.gameObject.uuid&&(this.wasVisible||Ri.add(t,e))}wasVisible=!1;beforeCreateDocument(){this.wasVisible=x.isActiveSelf(this.gameObject)}}class ba extends k{target;duration=.5;motionType="bounce";beforeCreateDocument(){}createBehaviours(e,t,i){if(this.target&&t.uuid===this.gameObject.uuid){const n=new pt("emphasize "+this.name,xt.tapTrigger(this.gameObject),ae.emphasize(this.target,this.duration,this.motionType,void 0,"basic"));e.addBehavior(n)}}afterCreateDocument(e,t){}}ke([f()],ba.prototype,"target");ke([f()],ba.prototype,"duration");ke([f()],ba.prototype,"motionType");class qs extends k{target;clip="";toggleOnClick=!1;trigger="tap";start(){vc(this.gameObject)}ensureAudioSource(){if(!this.target){const e=this.gameObject.addComponent(Ii);e&&(this.target=e,e.spatialBlend=1,e.volume=1,e.loop=!1,e.preload=!0)}}onPointerClick(e){e.use(),!(!this.target?.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(e,t,i){if(!(!this.target&&!this.clip)&&t.uuid===this.gameObject.uuid){const n=this.clip?this.clip:this.target?this.target.clip:void 0;if(!n||typeof n!="string")return;const o=this.target?this.target.gameObject:this.gameObject;ar.getName(n);const r=this.target?this.target.volume:1,a=this.target&&this.target.spatialBlend==0?"nonSpatial":"spatial";let l=!1;this.gameObject.traverse(p=>{p instanceof c.Mesh&&p.visible&&(l=!0)}),l=!0;const h=e.addAudioClip(n);let d=ae.playAudioAction(o,h,"play",r,a);this.target&&this.target.loop&&(d=ae.sequence(d).makeLooping());const u=this.name?"_"+this.name:"";if(l&&this.trigger==="tap"){this.toggleOnClick&&(d.multiplePerformOperation="stop");const p=new pt("playAudio"+u,xt.tapTrigger(t),d);e.addBehavior(p)}if(this.target&&this.target.playOnAwake&&this.target.enabled)if(l&&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 p=new pt("playAudioOnStart"+u,xt.sceneStartTrigger(),d);e.addBehavior(p)}}}}ke([f(Ii)],qs.prototype,"target");ke([f(URL)],qs.prototype,"clip");ke([f()],qs.prototype,"toggleOnClick");const Km=class un extends k{animator;stateName;trigger="tap";animation;get target(){return this.animator?.gameObject||this.animation?.gameObject}start(){vc(this.gameObject)}onPointerClick(e){e.use(),this.target&&this.stateName&&this.animator?.play(this.stateName,0,0,.1)}selfModel;stateAnimationModel;animationSequence=new Array;animationLoopAfterSequence=new Array;randomOffsetNormalized=0;createBehaviours(e,t,i){t.uuid===this.gameObject.uuid&&(this.selfModel=t)}static animationActions=[];static rootsWithExclusivePlayback=new Set;afterSerialize(){if(un.rootsWithExclusivePlayback.size>1){const e='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.';A()&&ce(e),console.warn(e,...un.rootsWithExclusivePlayback)}un.animationActions=[],un.rootsWithExclusivePlayback=new Set}afterCreateDocument(e,t){if(this.animationSequence===void 0&&this.animationLoopAfterSequence===void 0||!this.stateAnimationModel||!this.target)return;const i=t.document,n=t.extensions.find(a=>a instanceof Jd);if(!n)return;const o=n.getClipCount(this.target)>1;o&&(A()&&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."),un.rootsWithExclusivePlayback.add(this.target));const r=this.name?this.name:"";i.traverse(a=>{if(a.uuid===this.target?.uuid){const l=un.getActionForSequences(i,a,this.animationSequence,this.animationLoopAfterSequence,this.randomOffsetNormalized),h=new pt(this.trigger+"_"+r+"_toPlayAnimation_"+this.stateName+"_on_"+this.target?.name,this.trigger=="tap"?xt.tapTrigger(this.selfModel):xt.sceneStartTrigger(),l);o&&h.makeExclusive(!0),e.addBehavior(h)}})}static getActionForSequences(e,t,i,n,o){const r=(l,h)=>{let d=un.animationActions.find(u=>u.affectedObjects==l&&u.start==h.start&&u.duration==h.duration&&u.animationSpeed==h.speed);return d||(d=ae.startAnimationAction(l,h),un.animationActions.push(d)),d},a=ae.sequence();if(i&&i.length>0)for(const l of i)a.addAction(r(t,l));if(n&&n.length>0){const l=a.actions.length==0?a:ae.sequence();for(const h of n)l.addAction(r(t,h));l.makeLooping(),a!==l&&a.addAction(l)}return o&&o>0&&a.actions.unshift(ae.waitAction(o)),a}static getAndRegisterAnimationSequences(e,t,i){if(!t)return;const n=t.getComponent(mt),o=t.getComponent(wt);if(!n&&!o)return;if(n&&!i)throw new Error("PlayAnimationOnClick: No stateName specified for animator "+n.name+" on "+t.name);let r=[],a=[];if(o){const y=e.registerAnimation(t,o.clip);y&&(o.loop?a.push(y):r.push(y));let b=0;if(o.minMaxOffsetNormalized){const g=o.minMaxOffsetNormalized.x,v=o.minMaxOffsetNormalized.y;b=(o.clip?.duration||1)*(g+Math.random()*(v-g))}return{animationSequence:r,animationLoopAfterSequence:a,randomTimeOffset:b}}const l=n?.runtimeAnimatorController;let h=l?.findState(i),d=[],u=[];if(l&&h){const y=new Array;y.push(h);let b=!1;for(;y.length<100;){if(!h||h===null||!h.transitions||h.transitions.length===0){h.motion?.isLooping&&(b=!0);break}const g=h.transitions.find(_=>_.conditions.length===0),v=g?l.getState(g.destinationState,0):null;if(v&&y.includes(v)){h=v,b=!0;break}else if(g){if(h=v,!h)break;y.push(h)}else{b=h.motion?.isLooping??!1;break}}if(b&&h){const g=y.indexOf(h);d=y.slice(0,g),u=y.slice(g),m_&&console.log("found loop from "+i,"states until loop",d,"states looping",u)}else d=y,u=[],m_&&console.log("found no loop from "+i,"states",d);if(!u.length){const g=d[d.length-1],v=g.motion?.clip;if(v){let _;if(e.holdClipMap.has(v))_=e.holdClipMap.get(v);else{const S=g.name+"_hold";_=v.clone(),_.duration=1,_.name=S;const T=v.duration;_.tracks=v.tracks.map(M=>{const O=M.clone();O.times=new Float32Array([0,T]);const R=M.values.length,B=M.getValueSize(),L=M.values.slice(R-B,R);return O.values=new Float32Array(2*B),O.values.set(L,0),O.values.set(L,B),O}),_.name=S,e.holdClipMap.set(v,_)}if(_){const S={name:_.name,motion:{clip:_,isLooping:!1,name:_.name},speed:1,transitions:[],behaviours:[],hash:g.hash+1};u.push(S)}}}}if(d.length===1&&(!d[0].motion?.clip||d[0].motion?.clip.tracks?.length===0)){r=new Array;const y=e.registerAnimation(t,null);y&&r.push(y);return}if(d=d.filter(y=>y.motion?.clip&&y.motion?.clip.tracks?.length>0),u=u.filter(y=>y.motion?.clip&&y.motion?.clip.tracks?.length>0),d.length===0&&u.length===0){console.warn("No clips found for state "+i+" on "+n?.name+", can't export animation data");return}const p=(y,b)=>{if(!t)return;const g=e.registerAnimation(t,y.motion.clip??null);g?(g.speed=y.speed,b.push(g)):console.warn("Couldn't register animation for state "+y.name+" on "+n?.name)};if(d.length>0){r=new Array;for(const y of d)p(y,r)}if(u.length>0){a=new Array;for(const y of u)p(y,a)}let m=0;if(n&&l&&n.minMaxOffsetNormalized){const y=n.minMaxOffsetNormalized.x,b=n.minMaxOffsetNormalized.y;m=((d.length?d[0]:u.length?u[0]:null)?.motion.clip?.duration||1)*(y+Math.random()*(b-y))}return{animationSequence:r,animationLoopAfterSequence:a,randomTimeOffset:m}}createAnimation(e,t,i){if(!this.target||!this.animator&&!this.animation)return;const n=un.getAndRegisterAnimationSequences(e,this.target,this.stateName);n&&(this.animationSequence=n.animationSequence,this.animationLoopAfterSequence=n.animationLoopAfterSequence,this.randomOffsetNormalized=n.randomTimeOffset,this.stateAnimationModel=t)}};ke([f(mt)],Km.prototype,"animator");ke([f()],Km.prototype,"stateName");let Gl=Km;class va extends k{getType(){}target;getDuration(){}}ke([f(c.Object3D)],va.prototype,"target");class xc extends k{target}ke([f(va)],xc.prototype,"target");class Sc extends va{type=1;duration=1;getType(){switch(this.type){case 1:return"hide";case 0:return"show"}}getDuration(){return this.duration}}ke([f()],Sc.prototype,"type");ke([f()],Sc.prototype,"duration");class Zm extends xc{}class Gs{static _instance;static create(){return new Gs}static getOrCreate(){return this._instance||(this._instance=this.create()),this._instance}get isSecureConnection(){return window.location.protocol==="https:"}get quicklookButton(){return this._quicklookButton}_quicklookButton;get arButton(){return this._arButton}_arButton;get vrButton(){return this._vrButton}_vrButton;get sendToQuestButton(){return this._sendToQuestButton}_sendToQuestButton;get qrButton(){return Ki.getOrCreate().createQRCode()}createQuicklookButton(){if(this._quicklookButton)return this._quicklookButton;const e=document.createElement("button");this._quicklookButton=e,e.dataset.needle="quicklook-button";const t=exports.DeviceUtilities.supportsQuickLookAR();e.innerText="View in AR",e.prepend(ut("view_in_ar"));let i=!1,n=null;return e.addEventListener("click",()=>{n=cc(En),n||(i=!0,n=new En),i&&(n.objectToExport=U.Current.scene),n?(e.classList.add("this-mode-is-requested"),n.exportAndOpen().then(()=>{e.classList.remove("this-mode-is-requested")}).catch(o=>{e.classList.remove("this-mode-is-requested"),console.error(o)})):console.warn("No USDZExporter component found in the scene")}),this.hideElementDuringXRSession(e),e}createARButton(e){if(this._arButton)return this._arButton;const t="immersive-ar",i=document.createElement("button");return this._arButton=i,i.classList.add("webxr-button"),i.dataset.needle="webxr-ar-button",i.innerText="Enter AR",i.prepend(ut("view_in_ar")),i.title="Click to start an AR session",i.addEventListener("click",()=>q.start(t,e)),this.updateSessionSupported(i,t),this.listenToXRSessionState(i,t),this.hideElementDuringXRSession(i),this.isSecureConnection||(i.disabled=!0,i.title="WebXR requires a secure connection (HTTPS)"),exports.DeviceUtilities.isMozillaXR()||navigator.xr?.addEventListener("devicechange",()=>this.updateSessionSupported(i,t)),i}createVRButton(e){if(this._vrButton)return this._vrButton;const t="immersive-vr",i=document.createElement("button");return this._vrButton=i,i.classList.add("webxr-button"),i.dataset.needle="webxr-vr-button",i.innerText="Enter VR",i.prepend(ut("panorama_photosphere")),i.title="Click to start a VR session",i.addEventListener("click",()=>q.start(t,e)),this.updateSessionSupported(i,t),this.listenToXRSessionState(i,t),this.hideElementDuringXRSession(i),this.isSecureConnection||(i.disabled=!0,i.title="WebXR requires a secure connection (HTTPS)"),exports.DeviceUtilities.isMozillaXR()||navigator.xr?.addEventListener("devicechange",()=>this.updateSessionSupported(i,t)),i}createSendToQuestButton(){if(this._sendToQuestButton)return this._sendToQuestButton;const e="https://oculus.com/open_url/?url=",t=document.createElement("button");return this._sendToQuestButton=t,t.dataset.needle="webxr-sendtoquest-button",t.innerText="Open on Quest",t.prepend(ut("share_windows")),t.title="Click to send this page to the Oculus Browser on your Quest",t.addEventListener("click",()=>{const i=encodeURIComponent(window.location.href),n=e+i;window.open(n)==null&&Se("This page doesn't allow popups. Please paste "+n+" into your browser.")}),this.listenToXRSessionState(t),this.hideElementDuringXRSession(t),exports.DeviceUtilities.isMozillaXR()||navigator.xr?.addEventListener("devicechange",()=>{navigator.xr?.isSessionSupported("immersive-vr")?t.style.display="none":t.style.display=""}),t}createQRCode(){return Ki.getOrCreate().createQRCode()}updateSessionSupported(e,t){if(!("xr"in navigator)){e.style.display="none";return}q.isSessionSupported(t).then(i=>{e.style.display=i?"":"none",A()&&!i&&console.log('[WebXR] "'+t+'" is not supported on this device – make sure your server runs using HTTPS and you have a device connected that supports '+t)})}hideElementDuringXRSession(e){Ed(t=>{e["previous-display"]=e.style.display,e.style.display="none"}),Yp(t=>{e["previous-display"]!=null&&(e.style.display=e["previous-display"])})}listenToXRSessionState(e,t){t&&(q.onSessionRequestStart(i=>{i.mode===t?e.classList.add("this-mode-is-requested"):(e["was-disabled"]=e.disabled,e.disabled=!0,e.classList.add("other-mode-is-requested"))}),q.onSessionRequestEnd(i=>{e.classList.remove("this-mode-is-requested"),e.classList.remove("other-mode-is-requested"),e.disabled=e["was-disabled"]}))}}var pM=Object.defineProperty,mM=Object.getOwnPropertyDescriptor,ot=(s,e,t,i)=>{for(var n=i>1?void 0:i?mM(e,t):e,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&pM(e,t,n),n};const _d=w("debugspriterenderer"),gM=w("wireframe");class Xo{static cache={};static getOrCreateGeometry(e){if(e.__cached_geometry)return e.__cached_geometry;if(e.guid&&Xo.cache[e.guid])return _d&&console.log("Take cached geometry for sprite",e.guid),Xo.cache[e.guid];const t=new c.BufferGeometry;e.__cached_geometry=t;const i=new Float32Array(e.triangles.length*3),n=new Float32Array(e.triangles.length*2);for(let o=0;o<e.triangles.length;o+=1){const r=e.triangles[o];i[o*3]=-e.vertices[r].x,i[o*3+1]=e.vertices[r].y,i[o*3+2]=0;const a=e.uv[r];n[o*2]=a.x,n[o*2+1]=1-a.y}return t.setAttribute("position",new c.BufferAttribute(i,3)),t.setAttribute("uv",new c.BufferAttribute(n,2)),e.guid&&(this.cache[e.guid]=t),_d&&console.log("Built sprite geometry",e,t),t}}class yM{x;y}function zv(s){s&&(s.colorSpace!=c.SRGBColorSpace&&(s.colorSpace=c.SRGBColorSpace,s.needsUpdate=!0),s.minFilter==c.NearestFilter&&s.magFilter==c.NearestFilter&&(s.anisotropy=1,s.needsUpdate=!0))}let ps=class{constructor(e){e&&(this.texture=e,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}])}guid;texture;triangles;uv;vertices;__cached_geometry;get mesh(){return this._mesh||(this._mesh=new c.Mesh(Xo.getOrCreateGeometry(this),this.material)),this._mesh}_mesh;get material(){return this._material||(this.texture&&zv(this.texture),this._material=new c.MeshBasicMaterial({map:this.texture,color:16777215,side:c.DoubleSide,transparent:!0})),this._material}_material;getGeometry(){return Xo.getOrCreateGeometry(this)}};ot([f()],ps.prototype,"guid",2);ot([f(c.Texture)],ps.prototype,"texture",2);ot([er()],ps.prototype,"triangles",2);ot([er()],ps.prototype,"uv",2);ot([er()],ps.prototype,"vertices",2);const gf=Symbol("spriteOwner");class la{sprites;constructor(){this.sprites=[]}}ot([f(ps)],la.prototype,"sprites",2);const Jm=class bp{static create(){const e=new bp;return e.spriteSheet=new la,e}constructor(){}clone(){const e=new bp;return e.index=this.index,e.spriteSheet=this.spriteSheet,e}set sprite(e){e&&(this.spriteSheet?((this.index===null||this.index===void 0)&&(this.index=0),this.spriteSheet.sprites[this.index]=e):(this.spriteSheet=new la,this.spriteSheet.sprites=[e],this.index=0))}get sprite(){if(this.spriteSheet)return this.spriteSheet.sprites[this.index]}spriteSheet;index=0;update(e){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&&(zv(n),!i.__hasLoadedProgressive)){i.__hasLoadedProgressive=!0;const o=n;ne.NEEDLE_progressive.assignTextureLOD(n,0).then(r=>{r instanceof c.Texture&&(i.texture=r,e?.map===o&&(e.map=r,e.needsUpdate=!0))})}}};ot([f(la)],Jm.prototype,"spriteSheet",2);ot([f()],Jm.prototype,"index",2);let Yr=Jm;class Yt extends k{drawMode=0;size={x:1,y:1};color;sharedMaterial;transparent=!0;cutoutThreshold=0;castShadows=!1;renderOrder=0;toneMapped=!0;set texture(e){if(!this._spriteSheet)return;const t=this._spriteSheet.spriteSheet?.sprites[this.spriteIndex];t&&(t.texture=e,this.updateSprite())}addSprite(e,t=!1){if(this._spriteSheet||(this._spriteSheet=Yr.create()),!this._spriteSheet.spriteSheet)return-1;this._spriteSheet.spriteSheet?.sprites.push(e);const i=this._spriteSheet.spriteSheet?.sprites.length-1;return t&&(this.spriteIndex=i),i}get sprite(){return this._spriteSheet}set sprite(e){if(e!==this._spriteSheet)if(typeof e=="number"){const t=Math.floor(e);this.spriteIndex=t}else e instanceof ps?(this._spriteSheet||(this._spriteSheet=Yr.create()),this._spriteSheet.sprite!=e&&(this._spriteSheet.sprite=e),this.updateSprite()):e!=this._spriteSheet&&(this._spriteSheet=e,this.updateSprite())}set spriteIndex(e){this._spriteSheet&&(this._spriteSheet.index=e,this.updateSprite())}get spriteIndex(){return this._spriteSheet?.index??0}get spriteFrames(){return this._spriteSheet?.spriteSheet?.sprites.length??0}_spriteSheet;_currentSprite;awake(){this._currentSprite=void 0,this._spriteSheet?this._spriteSheet=this._spriteSheet.clone():this._spriteSheet=Yr.create(),_d&&console.log("Awake",this.name,this,this.sprite)}start(){this._currentSprite?this.gameObject&&this.gameObject.add(this._currentSprite):this.updateSprite()}updateSprite(e=!1){if(!this.__didAwake&&!e)return!1;const t=this._spriteSheet;if(!t?.spriteSheet?.sprites)return console.warn("SpriteRenderer has no data or spritesheet assigned..."),!1;const i=t.spriteSheet.sprites[this.spriteIndex];if(!i)return _d&&console.warn("Sprite not found",this.spriteIndex,t.spriteSheet.sprites),!1;if(this._currentSprite)this._currentSprite.geometry=Xo.getOrCreateGeometry(i),this._currentSprite.material.map=i.texture;else{const n=new c.MeshBasicMaterial({color:16777215,side:c.DoubleSide});if(gM&&(n.wireframe=!0),this.color&&(n.color||(n.color=new c.Color),n.color.copy(this.color),n.opacity=this.color.alpha),n.transparent=!0,n.toneMapped=this.toneMapped,n.depthWrite=!1,i.texture&&!n.wireframe){let o=i.texture;o[gf]!==void 0&&o[gf]!==this&&this.spriteFrames>1&&(o=i.texture=o.clone()),o[gf]=this,n.map=o}this.sharedMaterial=n,this._currentSprite=new c.Mesh(Xo.getOrCreateGeometry(i),n),this._currentSprite.renderOrder=Math.round(this.renderOrder),ne.NEEDLE_progressive.assignTextureLOD(n,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,t?.update(this.sharedMaterial),!0}}ot([f()],Yt.prototype,"drawMode",2);ot([f(yM)],Yt.prototype,"size",2);ot([f(Z)],Yt.prototype,"color",2);ot([f(c.Material)],Yt.prototype,"sharedMaterial",2);ot([f()],Yt.prototype,"transparent",2);ot([f()],Yt.prototype,"cutoutThreshold",2);ot([f()],Yt.prototype,"castShadows",2);ot([f()],Yt.prototype,"renderOrder",2);ot([f()],Yt.prototype,"toneMapped",2);ot([f(Yr)],Yt.prototype,"sprite",1);const g_=w("debugwebxr"),_M=new c.Matrix4().makeRotationY(Math.PI);class li extends k{static _eventListeners={};static onPlaced(e){const t="placed";return this._eventListeners[t]||(this._eventListeners[t]=[]),this._eventListeners[t].push(e),()=>{const i=this._eventListeners[t].indexOf(e);i>=0&&this._eventListeners[t].splice(i,1)}}static _hasPlaced=!1;static get hasPlaced(){return this._hasPlaced}get arScale(){return this._arScale}set arScale(e){this._arScale=Math.max(1e-6,e),this.onSetScale()}_arScale=1;invertForward=!1;customReticle;arTouchTransform=!0;autoPlace=!1;autoCenter=!1;useXRAnchor=!1;_isPlacing=!0;_startOffset=new c.Matrix4;_createdPlacementObject=null;_reparentedComponents=[];_placementScene=new c.Scene;_reticle=[];_hits=[];_placementStartTime=-1;_rigPlacementMatrix;_anchor=null;userInput;onEnable(){this.customReticle?.preload()}supportsXR(e){return e==="immersive-ar"}onEnterXR(e){g_&&console.log("ENTER WEBXR: SessionRoot start..."),this._anchor=null,li._hasPlaced=!1,this.gameObject.updateMatrixWorld(),this._startOffset.copy(this.gameObject.matrixWorld);const t=new c.Object3D;this._createdPlacementObject=t,t.name="AR Session Root",this._placementScene.name="AR Placement Scene",this._placementScene.children.length=0;for(let i=this.context.scene.children.length-1;i>=0;i--){const n=this.context.scene.children[i];this._placementScene.add(n)}if(this.context.scene.add(t),this.autoCenter){const i=Ht(this._placementScene.children),n=i.getCenter(new c.Vector3),o=i.getSize(new c.Vector3),r=new c.Matrix4;r.makeTranslation(n.x,n.y-o.y*.5,n.z),this._startOffset.multiply(r)}this._reparentedComponents.length=0,this._reparentedComponents.push({comp:this,originalObject:this.gameObject}),x.addComponent(t,this);for(const i of this._reticle)di(i);this._reticle.length=0,this._isPlacing=!0,this.context.input.addEventListener("pointerup",this.onPlaceScene,{queue:$t.Early})}onLeaveXR(){this.context.input.removeEventListener("pointerup",this.onPlaceScene,{queue:$t.Early}),this.onRevertSceneChanges(),this._anchor=null,li._hasPlaced=!1,this._rigPlacementMatrix=void 0}onUpdateXR(e){if(e.xr.isTrackingImages){for(const t of this._reticle)t.visible=!1;return}if(this._isPlacing){const t=e.xr.rig?.gameObject;t&&t.parent!==this.context.scene&&this.context.scene.add(t);let i=!1;if(e.xr.isPassThrough&&e.xr.controllers.length>0&&!this.autoPlace)for(const n of e.xr.controllers){const o=n.getHitTest();o&&(i=!0,this.updateReticleAndHits(e.xr,n.index,o,e.xr.rigScale))}if(!i){const n=e.xr.getHitTest();n&&this.updateReticleAndHits(e.xr,0,n,e.xr.rigScale)}}else{if(this._anchor&&e.xr.referenceSpace){const t=e.xr.frame.getPose(this._anchor.anchorSpace,e.xr.referenceSpace);if(t&&this.context.time.frame%20===0){const i=e.xr.convertSpace(t.transform),n=this._reticle[0];n&&(n.position.copy(i.position),n.quaternion.copy(i.quaternion),this.onApplyPose(n))}}if(this.arTouchTransform?(this.userInput||(this.userInput=new bd(this.context)),this.userInput?.enable()):this.userInput?.disable(),this.arTouchTransform&&this.userInput?.hasChanged){if(e.xr.rig){const t=e.xr.rig.gameObject;this.userInput.applyMatrixTo(t.matrix,!0),t.matrix.decompose(t.position,t.quaternion,t.scale),this.userInput.factor=t.scale.x}this.userInput.reset()}}}updateReticleAndHits(e,t,i,n){this._hits[t]=i.hit;let o=this._reticle[t];if(!o){if(this.customReticle)if(this.customReticle.asset)o=Wo(this.customReticle.asset);else{this.customReticle.loadAssetAsync();return}else o=new c.Mesh(new c.RingGeometry(.07,.09,32).rotateX(-Math.PI/2),new c.MeshBasicMaterial({side:c.DoubleSide,depthTest:!1,depthWrite:!1,transparent:!0,opacity:1,color:15658734})),o.name="AR Placement Reticle";if(g_){const r=new c.AxesHelper(1);r.position.y+=.01,o.add(r)}this._reticle[t]=o,o.matrixAutoUpdate=!1,o.visible=!1}if(o.lastPos=o.lastPos||i.position.clone(),o.lastQuat=o.lastQuat||i.quaternion.clone(),o.position.copy(o.lastPos.lerp(i.position,this.context.time.deltaTime/.1)),o.lastPos.copy(o.position),o.quaternion.copy(o.lastQuat.slerp(i.quaternion,this.context.time.deltaTime/.05)),o.lastQuat.copy(o.quaternion),o.scale.set(n,n,n),this.customReticle&&this.applyViewBasedTransform(o),o.updateMatrix(),o.visible=!0,o.parent!==this.context.scene&&this.context.scene.add(o),this._placementStartTime<0&&(this._placementStartTime=this.context.time.realtimeSinceStartup),this.autoPlace)if(this.upVec.set(0,1,0).applyQuaternion(o.quaternion),this.upVec.dot(V(0,1,0))>.9){let a=o["autoplace:timer"]||0;a>=1?(o.visible=!1,this.onPlaceScene(null)):(a+=this.context.time.deltaTime,o["autoplace:timer"]=a)}else o["autoplace:timer"]=0}onPlaceScene=e=>{if(this._isPlacing==!1||e?.used)return;let t=this._reticle[0];if(!t){console.warn("No reticle to place...");return}if(!t.visible&&!this.autoPlace){console.warn("Reticle is not visible (can not place)");return}if(q.active?.isTrackingImages){console.warn("Scene Placement is disabled while images are being tracked");return}let i=this._hits[0];if(e&&e.origin instanceof Kp){const n=this._reticle[e.origin.index];n&&(t=n,i=this._hits[e.origin.index])}if(e&&(e.stopImmediatePropagation(),e.stopPropagation(),e.use()),this._isPlacing=!1,this.context.input.removeEventListener("pointerup",this.onPlaceScene),this.onRevertSceneChanges(),t.position.copy(t.lastPos),t.quaternion.copy(t.lastQuat),this.onApplyPose(t),li._hasPlaced=!0,this.useXRAnchor&&this.onCreateAnchor(q.active,i),this.context.xr)for(const n of this.context.xr.controllers)n.cancelHitTestSource()};onSetScale(){if(!li._hasPlaced)return;const e=q.active?.rig?.gameObject;if(e){const t=q.active?.rigScale||1,i=1/this._arScale*t,n=new c.Matrix4().makeScale(i,i,i).invert();e.matrix.premultiply(n),e.matrix.decompose(e.position,e.quaternion,e.scale)}}onRevertSceneChanges(){for(const e of this._reticle)e&&(e.visible=!1,e?.removeFromParent());this._reticle.length=0;for(let e=this._placementScene.children.length-1;e>=0;e--){const t=this._placementScene.children[e];this.context.scene.add(t)}this._createdPlacementObject?.removeFromParent();for(const e of this._reparentedComponents)x.addComponent(e.originalObject,e.comp)}async onCreateAnchor(e,t){if(t.createAnchor===void 0){console.warn("Hit does not support creating an anchor",t),A()&&ce("Hit does not support creating an anchor");return}else{const i=await t.createAnchor(e.viewerPose.transform);e.running&&i&&(this._anchor=i)}}upVec=new c.Vector3(0,1,0);lookPoint=new c.Vector3;worldUpVec=new c.Vector3(0,1,0);applyViewBasedTransform(e){const t=this.context.mainCamera,i=e,n=t.worldPosition,o=i.worldPosition;this.upVec.set(0,1,0).applyQuaternion(e.quaternion);const r=t.worldPosition;r&&e.position.clone().sub(r).angleTo(this.upVec)<Math.PI/2&&this.upVec.negate();const a=this.upVec.angleTo(this.worldUpVec)*180/Math.PI,l=30;a>l&&a<180-l||a<-l&&a>-180+l?(this.lookPoint.copy(e.position).add(this.upVec),this.lookPoint.y=e.position.y,e.lookAt(this.lookPoint)):(n.y=o.y,e.lookAt(n))}onApplyPose(e){const t=q.active?.rig?.gameObject;if(!t){console.warn("No rig object to place");return}const i=t.parent||this.context.scene;this._rigPlacementMatrix?this._rigPlacementMatrix?.decompose(t.position,t.quaternion,t.scale):this._rigPlacementMatrix=t.matrix.clone(),this.applyViewBasedTransform(e),e.updateMatrix(),this.context.scene.add(e),e.attach(t),e.removeFromParent(),t.scale.set(this.arScale,this.arScale,this.arScale),t.position.multiplyScalar(this.arScale),t.updateMatrix(),this.invertForward&&t.matrix.premultiply(_M),t.matrix.premultiply(this._startOffset),t.matrix.decompose(t.position,t.quaternion,t.scale),i.add(t)}}class bd{static up=new c.Vector3(0,1,0);static zero=new c.Vector3(0,0,0);static one=new c.Vector3(1,1,1);oneFingerDrag=!0;twoFingerRotate=!0;twoFingerScale=!0;factor=1;context;offset;plane;_scale=1;_hasChanged=!1;get scale(){return this._scale}constructor(e){this.context=e,this.offset=new c.Matrix4,this.plane=new c.Plane,this.plane.setFromNormalAndCoplanarPoint(bd.up,bd.zero)}_enabled=!1;reset(){this._scale=1,this.offset.identity(),this._hasChanged=!0}get hasChanged(){return this._hasChanged}applyMatrixTo(e,t){this._hasChanged=!1,t?(this.offset.invert(),e.premultiply(this.offset)):e.multiply(this.offset)}currentlyUsedPointerIds=new Set;currentlyUnusedPointerIds=new Set;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:$t.Early}),this.context.input.addEventListener("pointerdown",this.onPointerDownLate,{queue:$t.Late}),this.context.input.addEventListener("pointerup",this.onPointerUpEarly,{queue:$t.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:$t.Early}),this.context.input.removeEventListener("pointerdown",this.onPointerDownLate,{queue:$t.Late}),this.context.input.removeEventListener("pointerup",this.onPointerUpEarly,{queue:$t.Early}),window.removeEventListener("touchstart",this.touchStart),window.removeEventListener("touchmove",this.touchMove),window.removeEventListener("touchend",this.touchEnd))}onPointerDownEarly=e=>{this.isActive&&e.stopPropagation()};onPointerDownLate=e=>{e.used?this.currentlyUsedPointerIds.add(e.pointerId):this.currentlyUsedPointerIds.size<=0&&this.currentlyUnusedPointerIds.add(e.pointerId)};onPointerUpEarly=e=>{this.currentlyUsedPointerIds.delete(e.pointerId),this.currentlyUnusedPointerIds.delete(e.pointerId)};prev=new Map;_didMultitouch=!1;touchStart=e=>{if(!e.defaultPrevented)for(let t=0;t<e.changedTouches.length;t++){const i=e.changedTouches[t],n=exports.DeviceUtilities.isAndroidDevice()&&i.clientY<window.innerHeight*.1;this.prev.has(i.identifier)||this.prev.set(i.identifier,{ignore:n,x:0,z:0,screenx:0,screeny:0});const o=this.prev.get(i.identifier);if(o){const r=this.getPositionOnPlane(i.clientX,i.clientY);o.x=r.x,o.z=r.z,o.screenx=i.clientX,o.screeny=i.clientY}}};touchEnd=e=>{e.touches.length<=0&&(this._didMultitouch=!1);for(let t=0;t<e.changedTouches.length;t++){const i=e.changedTouches[t];this.prev.delete(i.identifier)}};touchMove=e=>{if(!e.defaultPrevented&&this.isActive){if(e.touches.length===1){if(this._didMultitouch)return;const t=e.touches[0],i=this.prev.get(t.identifier);if(!i||i.ignore)return;const n=this.getPositionOnPlane(t.clientX,t.clientY),o=n.x-i.x,r=n.z-i.z;if(o===0&&r===0)return;this.oneFingerDrag&&this.addMovement(o,r),i.x=n.x,i.z=n.z,i.screenx=t.clientX,i.screeny=t.clientY;return}else if(e.touches.length===2){this._didMultitouch=!0;const t=e.touches[0],i=e.touches[1],n=this.prev.get(t.identifier),o=this.prev.get(i.identifier);if(!n||!o)return;if(this.twoFingerRotate){const r=Math.atan2(t.clientY-i.clientY,t.clientX-i.clientX),a=Math.atan2(n.screeny-o.screeny,n.screenx-o.screenx),l=r-a;Math.abs(l)>.001&&this.addRotation(l)}if(this.twoFingerScale){const r=t.clientX-i.clientX,a=t.clientY-i.clientY,l=Math.sqrt(r*r+a*a),h=n.screenx-o.screenx,d=n.screeny-o.screeny,u=Math.sqrt(h*h+d*d),p=l-u;Math.abs(p)>2&&this.addScale(p)}n.screenx=t.clientX,n.screeny=t.clientY,o.screenx=i.clientX,o.screeny=i.clientY}}};_raycaster=new c.Raycaster;_intersection=new c.Vector3;_screenPos=new c.Vector3;getPositionOnPlane(e,t){const i=this.context.mainCamera;return this._screenPos.x=e/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(e,t){e/=this._scale,t/=this._scale,e*=this.factor,t*=this.factor,this.offset.elements[12]+=e,this.offset.elements[14]+=t,(e!==0||t!==0)&&(this._hasChanged=!0)}_tempMatrix=new c.Matrix4;addScale(e){e/=window.innerWidth,e*=-1,this._scale*=1+e,this._tempMatrix.makeScale(1-e,1-e,1-e),this.offset.premultiply(this._tempMatrix),e!==0&&(this._hasChanged=!0)}addRotation(e){e*=-1,this._tempMatrix.makeRotationY(e),this.offset.premultiply(this._tempMatrix),e!==0&&(this._hasChanged=!0)}}const Fs=w("debugautosync"),yf=Symbol("syncerId");class bM{_syncers={};getOrCreateSyncer(e){if(!e.guid)return null;if(this._syncers[e.guid])return this._syncers[e.guid];const t=new vM(e);return t[yf]=e.guid,this._syncers[t[yf]]=t,t}removeSyncer(e){delete this._syncers[e[yf]]}}const eg=new bM;class vM{comp;constructor(e){this.comp=e}hasChanges=!1;changedProperties={};get networkingKey(){return this.comp.guid}_isReceiving=!1;_isInit=!1;init(e){if(this._isInit)return;this._isInit=!0,this.comp=e,this.comp.context.post_render_callbacks.push(this.onHandleSending),this.comp.context.connection.beginListen(this.networkingKey,this.onHandleReceiving);const t=this.comp.context.connection.tryGetState(this.comp.guid);t&&this.onHandleReceiving(t)}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(e,t){this._isReceiving||(Fs&&console.log("Property changed: "+e,t),this.hasChanges=!0,this.changedProperties[e]=t)}onHandleSending=()=>{if(!this.hasChanges)return;this.hasChanges=!1;const e=this.comp.context.connection;if(!e||!e.isConnected||!e.isInRoom){for(const t in this.changedProperties)delete this.changedProperties[t];return}for(const t in this.changedProperties){const i=this.changedProperties[t];Fs&&console.log("SEND",this.comp.guid,this.networkingKey),e.send(this.networkingKey,{guid:this.comp.guid,property:t,data:i},Yi.Queued),delete this.changedProperties[t]}};onHandleReceiving=e=>{if(Fs&&console.log("SYNCFIELD RECEIVE",this.comp.name,this.comp.guid,e),!!this._isInit&&this.comp&&e.guid===this.comp.guid)try{this._isReceiving=!0,this.comp[e.property]=e.data}catch(t){console.error(t)}finally{this._isReceiving=!1}}}function wM(s,e){let t=e!==s;return!t&&s&&e&&(Array.isArray(s)&&Array.isArray(e)||typeof s=="object"&&typeof e=="object")&&(t=!0),t}const El=Symbol("AutoSyncHandler");function xM(s){if(s[El])return s[El];const e=eg.getOrCreateSyncer(s);return e?.init(s),s[El]=e,e}function SM(s){const e=s[El];e&&(eg.removeSyncer(e),e.destroy(),delete s[El])}const tg=function(s=null){return function(e,t){let i="";typeof t=="string"?i=t:i=t.name;let n=null,o;typeof s=="string"?o=e[s]:typeof s=="function"&&(o=s),o==null&&(A()||Fs)&&s!=null&&console.warn('syncField: no callback function found for property "'+i+'"','"'+s+'"');const r=e,a=r.__internalAwake;if(typeof a!="function"){(Fs||A())&&console.error('@syncField can currently only used on Needle Engine Components, custom object of type "'+e?.constructor?.name+'" is not supported',e);return}Fs&&console.log(i);const l=Symbol(i);r.__internalAwake=function(){if(this[l]!==void 0)return;if(this[l]=this[i],n=eg.getOrCreateSyncer(this),Object.getOwnPropertyDescriptor(this,i)?.set===void 0){let u=!1;Object.defineProperty(this,i,{set:function(p){const m=this[l];if(this[l]=p,u){(A()||Fs)&&console.warn("Recursive call detected",i);return}u=!0;try{const y=wM(p,m);Fs&&console.log("SyncField assignment",i,"changed?",y,p,o),y&&o?.call(this,p,m)!==!1&&xM(this)?.notifyChanged(i,p)}finally{u=!1}},get:function(){return this[l]},configurable:!0,enumerable:!0})}n?.init(this),a.call(this)};const h=r.__internalDestroy;r.__internalDestroy=function(){SM(this),h.call(this)}}};var CM=Object.defineProperty,tu=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&CM(e,t,n),n};const Lt=w("debugplayersync"),iu=class Nv extends k{static async setupFrom(e,t){const i=Y.getOrCreateFromUrl(e);if(!i.asset){const r=await i.loadAssetAsync();r&&x.getOrAddComponent(r,Zi)}const n=new Nv;n._internalInit(t),n.asset=i;const o=new c.Object3D;return o.guid=e,x.addComponent(o,n),n}autoSync=!0;asset;onPlayerSpawned;_localInstance;awake(){this.watchTabVisible(),this.onPlayerSpawned||(this.onPlayerSpawned=new de)}onEnable(){this.context.connection.beginListen(Q.RoomStateSent,this.onJoinedRoom),this.context.connection.beginListen(Q.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(Q.LeftRoom,this.destroyInstance),this.context.connection.isInRoom&&this.onJoinedRoom()}onDisable(){this.context.connection.stopListen(Q.RoomStateSent,this.onJoinedRoom),this.context.connection.stopListen(Q.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(Q.LeftRoom,this.destroyInstance)}onJoinedRoom=()=>{Lt&&console.log("PlayerSync.joinedRoom. autoSync is set to "+this.autoSync),this.autoSync&&this.getInstance()};async getInstance(){if(this._localInstance)return this._localInstance;if(Lt&&console.log("PlayerSync.createInstance",this.asset?.url),!this.asset?.asset&&!this.asset?.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=this.asset?.instantiateSynced({parent:this.gameObject,deleteOnDisconnect:!0},!0);const e=await this._localInstance;if(e){const t=x.getComponentsInChildren(e,Zi);if(Lt&&console.log(`PlayerSync.createInstance: found ${t?.length} PlayerState components. Owner: ${this.context.connection.connectionId}`),t?.length){for(const i of t)i.owner=this.context.connection.connectionId;this.onPlayerSpawned?.invoke(e)}else this._localInstance=void 0,console.error("<strong>Failed finding PlayerState on "+this.asset?.url+"</strong>: please make sure the asset has a PlayerState component!"),x.destroySynced(e)}else this._localInstance=void 0,console.warn("PlayerSync: failed instantiating asset!");return this._localInstance}destroyInstance=()=>{this._localInstance?.then(e=>{Lt&&console.log("PlayerSync.destroyInstance",e),sc(e,this.context.connection,!0,{saveInRoom:!1})}),this._localInstance=void 0};watchTabVisible(){window.addEventListener("visibilitychange",e=>{if(document.visibilityState==="visible")for(let t=Zi.all.length-1;t>=0;t--){const i=Zi.all[t];(!i.owner||!this.context.connection.userIsInRoom(i.owner))&&i.doDestroy()}})}};tu([f()],iu.prototype,"autoSync");tu([f(Y)],iu.prototype,"asset");tu([f(de)],iu.prototype,"onPlayerSpawned");let ig=iu;var Vv=(s=>(s.OwnerChanged="ownerChanged",s))(Vv||{});const vp=class ht extends k{static _all=[];static get all(){return ht._all}static _local=[];static get local(){return ht._local}static getFor(e){if(e instanceof c.Object3D)return x.getComponentInParent(e,ht);if(e instanceof k)return x.getComponentInParent(e.gameObject,ht)}static isLocalPlayer(e){return ht.getFor(e)?.isLocalPlayer??!1}static _callbacks={};static addEventListener(e,t){return this._callbacks[e]||(this._callbacks[e]=[]),this._callbacks[e].push(t),t}static removeEventListener(e,t){if(!this._callbacks[e])return;const i=this._callbacks[e].indexOf(t);i>=0&&this._callbacks[e].splice(i,1)}static dispatchEvent(e,t){if(this._callbacks[e])for(const i of this._callbacks[e])i(t)}onOwnerChangeEvent=new de;onFirstOwnerChangeEvent=new de;hasOwner=!1;owner;dontDestroy=!1;get isLocalPlayer(){return this.owner===this.context.connection.connectionId}onOwnerChange(e,t){Lt&&console.log(`PlayerSync.onOwnerChange: ${t} → ${e} (me: ${this.context.connection.connectionId})`);const i=ht._local.indexOf(this);i>=0&&ht._local.splice(i,1);const n={playerState:this,oldValue:t,newValue:e};if(this.hasOwner||(this.hasOwner=!0,this.onFirstOwnerChangeEvent?.invoke(n)),this.onOwnerChangeEvent?.invoke(n),this.owner===this.context.connection.connectionId){ht._local.push(this);const r=new CustomEvent("local-owner-changed",{detail:n});this.dispatchEvent(r)}const o=new CustomEvent("owner-changed",{detail:n});this.dispatchEvent(o),ht.dispatchEvent("ownerChanged",o)}awake(){ht.all.push(this),Lt&&console.log("Registered new PlayerState",this.guid,ht.all.length-1,ht.all),this.context.connection.beginListen(Q.UserLeftRoom,this.onUserLeftRoom)}async start(){Lt&&console.log("PLAYERSTATE.START, owner: "+this.owner,this.context.connection.usersInRoom([])),this.owner?(this.context.connection.isInRoom||await An(300),this.context.connection.userIsInRoom(this.owner)==!1&&(Lt&&console.log(`PlayerSync.start → doDestroy "${this.name}" because user "${this.owner}" is not in room anymore...`,"Currently in room:",...this.context.connection.usersInRoom()),this.doDestroy())):this.owner||(Lt&&console.warn("PlayerState.start → owner is undefined!",this.name),setTimeout(()=>{!this.destroyed&&!this.owner?this.dontDestroy?Lt&&console.warn("PlayerState.start → owner is still undefined but dontDestroy is set to true",this.name):(Lt&&console.warn(`PlayerState.start → owner is still undefined: destroying "${this.name}" instance now`),this.doDestroy()):Lt&&console.log("PlayerState.start → owner is assigned",this.owner)},2e3))}doDestroy(){Lt&&console.log("PlayerSync.doDestroy → syncDestroy",this.name),sc(this.gameObject,this.context.connection,!0,{saveInRoom:!1})}onDestroy(){if(Lt&&console.warn("PlayerState.onDestroy",this.owner),this.context.connection.stopListen(Q.UserLeftRoom,this.onUserLeftRoom),ht.all.splice(ht.all.indexOf(this),1),this.isLocalPlayer){const e=ht._local.indexOf(this);e>=0&&ht._local.splice(e,1)}}onUserLeftRoom=e=>{if(e.userId===this.owner){Lt&&console.log("PLAYERSYNC LEFT",this.owner),this.doDestroy();return}}};tu([tg(vp.prototype.onOwnerChange)],vp.prototype,"owner");let Zi=vp;var PM=Object.defineProperty,wa=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&PM(e,t,n),n};class jn extends k{position="bottom";showNeedleLogo=!1;showSpatialMenu;createFullscreenButton;createMuteButton;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&&(exports.DeviceUtilities.isMobileDevice()||this.context.menu.showQRCodeButton(!0))}}wa([f()],jn.prototype,"position");wa([f()],jn.prototype,"showNeedleLogo");wa([f()],jn.prototype,"showSpatialMenu");wa([f()],jn.prototype,"createFullscreenButton");wa([f()],jn.prototype,"createMuteButton");wa([f()],jn.prototype,"createQRCodeButton");var MM=Object.defineProperty,ng=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&MM(e,t,n),n};const $a=w("debugwebxr"),y_=new c.Quaternion().setFromAxisAngle(new c.Vector3(0,1,0),Math.PI);class Xs extends k{head;leftHand;rightHand;_leftHandMeshes;_rightHandMeshes;_syncTransforms;async onEnterXR(e){if(!this.activeAndEnabled)return;$a&&console.warn("AVATAR ENTER XR",this.guid,this.sourceId,this,this.activeAndEnabled),this._syncTransforms&&(this._syncTransforms.length=0),await this.prepareAvatar();const t=Zi.getFor(this);if(t?.owner){const i=this.gameObject.addComponent(xe);i.avatar=this.gameObject,i.connectionId=t.owner}else this.context.connection.isConnected?console.error("No player state found for avatar",this):t&&!this.context.connection.isConnected&&(t.dontDestroy=!0)}onLeaveXR(e){const t=this.gameObject.getComponent(xe);t&&t.destroy()}onUpdateXR(e){if(!this.activeAndEnabled)return;const t=Zi.isLocalPlayer(this);if(!t)return;const i=e.xr;if(i.rig&&i.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),i.rig.gameObject.add(this.gameObject)),this._syncTransforms&&t)for(const l of this._syncTransforms)l.fastMode=!0,l.isOwned()||l.requestOwnership();if(this.head&&this.context.mainCamera){const l=this.head.asset;if(l.position.copy(this.context.mainCamera.position),l.position.x*=-1,l.position.z*=-1,l.quaternion.copy(this.context.mainCamera.quaternion),l.quaternion.x*=-1,this.context.time.frameCount%10===0&&this.head.asset){const h=x.getComponentsInChildren(this.head.asset,Ei);for(const d of h)d.enabled=!1,d.gameObject.visible=!1}}const n=e.xr.leftController,o=this.leftHand?.asset;n&&o?(o.position.copy(n.gripPosition),o.quaternion.copy(n.gripQuaternion),o.quaternion.multiply(y_),o.visible=n.isTracking,this.updateHandVisibility(n,o,this._leftHandMeshes)):o&&o.visible&&(o.visible=!1);const r=e.xr.rightController,a=this.rightHand?.asset;r&&a?(a.position.copy(r.gripPosition),a.quaternion.copy(r.gripQuaternion),a.quaternion.multiply(y_),a.visible=r.isTracking,this.updateHandVisibility(r,a,this._rightHandMeshes)):a&&a.visible&&(a.visible=!1)}onBeforeRender(){this.context.xr&&this.context.time.frame%10===0&&this.updateRemoteAvatarVisibility()}updateHandVisibility(e,t,i){if(i){const n=e.model&&e.model.visible&&e.model!==t;i.forEach(o=>{Jn(o,!n)})}}updateRemoteAvatarVisibility(){if(this.context.connection.isConnected){const e=Zi.getFor(this);if(e&&e.isLocalPlayer==!1){const t=q.getXRSync(this.context);if(t&&t.hasState(e.owner)){this.tryFindAvatarObjectsIfMissing();const i=this.leftHand?.asset;i&&(i.visible=t?.isTracking(e.owner,"left")??!1);const n=this.rightHand?.asset;n&&(n.visible=t?.isTracking(e.owner,"right")??!1)}if(this.head?.asset){const i=x.getComponentsInChildren(this.head.asset,Ei);for(const n of i)n.enabled=!1,n.gameObject.visible=!0}}}}tryFindAvatarObjectsIfMissing(){if(!this.head||!this.leftHand||!this.rightHand){const e={head:this.head,leftHand:this.leftHand,rightHand:this.rightHand};Ub.tryFindAvatarObjects(this.gameObject,this.sourceId||"",e),e.head&&(this.head=e.head),e.leftHand&&(this.leftHand=e.leftHand),e.rightHand&&(this.rightHand=e.rightHand)}}async prepareAvatar(){if(this.tryFindAvatarObjectsIfMissing(),this.head)this.head instanceof c.Object3D&&(this.head=new Y("",this.sourceId,this.head));else{const e=new c.Object3D;e.name="Head";const t=Ko.createPrimitive(No.Cube);e.add(t),this.gameObject.add(e),this.head=new Y("",this.sourceId,e),$a&&console.log("Create head",e)}if(this.rightHand)this.rightHand instanceof c.Object3D&&(this.rightHand=new Y("",this.sourceId,this.rightHand));else{const e=new c.Object3D;e.name="Right Hand",this.gameObject.add(e),this.rightHand=new Y("",this.sourceId,e),$a&&console.log("Create right hand",e)}if(this.leftHand)this.leftHand instanceof c.Object3D&&(this.leftHand=new Y("",this.sourceId,this.leftHand));else{const e=new c.Object3D;e.name="Left Hand",this.gameObject.add(e),this.leftHand=new Y("",this.sourceId,e),$a&&console.log("Create left hand",e)}await this.loadAvatarObjects(this.head,this.leftHand,this.rightHand),this._leftHandMeshes=[],this.leftHand.asset?.traverse(e=>{e?.isMesh&&this._leftHandMeshes.push(e)}),this._rightHandMeshes=[],this.rightHand.asset?.traverse(e=>{e?.isMesh&&this._rightHandMeshes.push(e)}),Zi.isLocalPlayer(this.gameObject)&&(this._syncTransforms=x.getComponentsInChildren(this.gameObject,Ln))}async loadAvatarObjects(e,t,i){const n=e.loadAssetAsync(),o=t.loadAssetAsync(),r=i.loadAssetAsync(),a=new Array;n&&a.push(n),o&&a.push(o),r&&a.push(r);const l=await Bp(a);$a&&console.log("Avatar loaded results:",l)}}ng([f(Y)],Xs.prototype,"head");ng([f(Y)],Xs.prototype,"leftHand");ng([f(Y)],Xs.prototype,"rightHand");var OM=Object.defineProperty,nu=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&OM(e,t,n),n};const $n=w("debugwebxr"),Os=new Array;class ls extends k{createControllerModel=!0;createHandModel=!0;customLeftHand;customRightHand;static factory=new G.XRControllerModelFactory;supportsXR(e){return e==="immersive-vr"||e==="immersive-ar"}_models=new Array;async onXRControllerAdded(e){if(!(e.xr.isVR||e.xr.isPassThrough))return;const{controller:i}=e;if($n&&console.warn("Add Controller Model for",i.side,i.index),this.createControllerModel||this.createHandModel){if(i.hand){if(this.createHandModel){const n=await this.loadHandModel(this,i);if(!n||!i.connected||!i.isHand){n?.handObject&&Tr(n.handObject,!1),n?.handObject?.destroy();return}this._models.push({controller:i,model:n.handObject,handmesh:n.handmesh}),this._models.sort((o,r)=>o.controller.index-r.controller.index),this.scene.add(n.handObject),i.model=n.handObject}}else if(this.createControllerModel){const n=await i.getModelUrl();if(n){const o=await this.loadModel(i,n);if(!o||!i.connected||i.isHand)return;this._models.push({controller:i,model:o}),this._models.sort((r,a)=>r.controller.index-a.controller.index),this.scene.add(o),o.traverse(r=>{r.layers.set(2),r.matrixAutoUpdate=!1,r.updateMatrix()}),i.model=o}else i.targetRayMode!=="transient-pointer"&&console.warn("XRControllerModel: no model found for "+i.side)}}}onXRControllerRemoved(e){console.debug("XR Controller Removed",e.controller.side,e.controller.index);const t=this._models.findIndex(n=>n.controller===e.controller),i=this._models[t];i&&(this._models.splice(t,1),i.model&&(Tr(i.model,!1),i.model.destroy(),i.model=void 0))}onBeforeXR(e,t){this.createHandModel&&(this.customLeftHand||this.customRightHand)&&(t.optionalFeatures=t.optionalFeatures||[],t.optionalFeatures.includes("hand-tracking")||t.optionalFeatures.push("hand-tracking"))}onLeaveXR(e){for(const t of this._models)t&&(t.model&&(Tr(t.model,!1),t.model.destroy(),t.model=void 0),t.controller.model===t.model&&(t.controller.model=null));this._models.length=0}onBeforeRender(){if(q.active&&($n&&(Os[0]=Date.now()),this.updateRendering(q.active),$n)){const e=Date.now()-Os[0];Os.push(e),Os.length>=30&&(Os[0]=0,Os.reduce((t,i)=>t+i,0)/Os.length,Os.length=0)}}updateRendering(e){for(let t=0;t<this._models.length;t++){const i=this._models[t];if(!i)continue;const n=i.controller;if(!n.connected){$n&&console.warn("XRControllerModel.onUpdateXR: controller is not connected anymore",n.side,n.hand);continue}if(i.model&&!i.handmesh)i.model.matrixAutoUpdate=!1,i.model.matrix.copy(n.gripMatrix),i.model.visible=n.isTracking,e.rig?.gameObject.add(i.model);else if(n.inputSource.hand&&i.handmesh){const o=e.referenceSpace,r=this.context.renderer.xr.getHand(n.index);if(o&&e.frame.getJointPose){for(const a of n.inputSource.hand.values()){const l=r.joints[a.jointName];if(l){const h=n.getHandJointPose(a);if(h){const d=h.transform.position,u=h.transform.orientation;l.position.copy(d),l.quaternion.copy(u),l.matrixAutoUpdate=!1}l.visible=h!=null}}i.model&&(i.model.visible=n.isTracking,i.model.visible&&i.model.parent!==e.rig?.gameObject&&e.rig?.gameObject.add(i.model)),i.model?.visible&&(i.handmesh?.updateMesh(),i.model.matrixAutoUpdate=!1,i.model.matrix.identity(),i.model.applyMatrix4(Wr))}}}}async loadModel(e,t){if(!e.connected)return console.warn("XRControllerModel.onXRControllerAdded: controller is not connected anymore",e.side),null;const n=await Y.getOrCreate("",t).instantiate();return Tr(n),q.active?.isPassThrough&&n.traverseVisible(o=>{this.makeOccluder(o)}),n}async loadHandModel(e,t){const i=this.context,n=i.renderer.xr.getHand(t.index);n||($n?j.DrawLabel(t.rayWorldPosition,"No hand found for index "+t.index,.05,5):console.warn("No hand found for index "+t.index));const o=new G.GLTFLoader;_m(o,i),await gd(o,i,this.sourceId??"");const r=Um(o);let a="";const l=t.side==="left"?this.customLeftHand:this.customRightHand;l?(a=l.url.split(".").slice(0,-1).join("."),o.setPath("")):(a=t.inputSource.handedness==="left"?"left":"right",o.setPath("https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles/generic-hand/"));const h=new c.Object3D;Tr(h);const d=new G.XRHandMeshModel(h,n,o.path,a,o,u=>{const p=r?.gltf;p?.scene.children?.length===0&&(p.scene.children[0]=u),r?.gltf&&en().createBuiltinComponents(e.context,e.sourceId||a,r.gltf,null,r),u.traverse(m=>{m.layers.set(2),q.active?.isPassThrough&&!l&&this.makeOccluder(m),m instanceof c.Mesh&&ne.NEEDLE_progressive.assignMeshLOD(m,0)}),t.connected||($n&&j.DrawLabel(t.rayWorldPosition,"Hand is loaded but not connected anymore",.05,5),u.removeFromParent())});if($n&&h.add(new c.AxesHelper(.5)),t.inputSource.hand){$n&&console.log(t.inputSource.hand);for(const u of t.inputSource.hand.values())if(n.joints[u.jointName]===void 0){const p=new c.Group;p.matrixAutoUpdate=!1,p.visible=!0,n.joints[u.jointName]=p,n.add(p)}}else $n&&j.DrawLabel(t.rayWorldPosition,"No inputSource.hand found for index "+t.index,.05,5);return{handObject:h,handmesh:d}}makeOccluder(e){if(e instanceof c.Mesh){let t=e.material;t instanceof c.Material&&(t=e.material=t.clone(),t.depthWrite=!0,t.depthTest=!0,t.colorWrite=!1,e.receiveShadow=!1,e.renderOrder=-100)}}}nu([f()],ls.prototype,"createControllerModel");nu([f()],ls.prototype,"createHandModel");nu([f(Y)],ls.prototype,"customLeftHand");nu([f(Y)],ls.prototype,"customRightHand");class su extends k{}var kM=Object.defineProperty,so=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&kM(e,t,n),n};const _f=w("debugwebxr");class pi extends k{movementSpeed=1.5;rotationStep=30;useTeleport=!0;usePinchToTeleport=!0;useTeleportTarget=!1;useTeleportFade=!1;showRays=!0;showHits=!0;isXRMovementHandler=!0;xrSessionMode="immersive-vr";_didApplyRotation=!1;_didTeleport=!1;onUpdateXR(e){const t=e.xr.rig;if(!t?.gameObject||e.xr.isPassThrough)return;const i=e.xr.leftController,n=e.xr.rightController;i&&this.onHandleMovement(i,t.gameObject),n&&(this.onHandleRotation(n,t.gameObject),this.useTeleport&&this.onHandleTeleport(n,t.gameObject))}onLeaveXR(e){for(const t of this._lines)t.removeFromParent();for(const t of this._hitDiscs)t?.removeFromParent()}onBeforeRender(){this.context.xr?.running&&(this.showRays&&this.renderRays(this.context.xr),this.showHits&&this.renderHits(this.context.xr))}onHandleMovement(e,t){const i=e.getStick("xr-standard-thumbstick");if(i.x!=0||i.y!=0){const n=V(i.x,0,i.y);n.multiplyScalar(this.context.time.deltaTimeUnscaled*this.movementSpeed);const o=Ae(t);n.multiplyScalar(o.x),n.applyQuaternion(e.xr.poseOrientation),n.y=0,n.applyQuaternion(t.worldQuaternion),t.position.add(n),t.updateWorldMatrix(!1,!1);for(const r of t.children)r.updateWorldMatrix(!1,!1)}}onHandleRotation(e,t){if(e._isMxInk)return;const n=e.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=X(this.context.mainCamera).clone();t.rotateY(o*I.toRadians(this.rotationStep));const l=X(this.context.mainCamera).clone().sub(r);l.y=0,t.position.sub(l)}}_teleportBuffer=new Array;onHandleTeleport(e,t){let i=0;if(e.hand&&this.usePinchToTeleport&&e.isTeleportGesture){const n=e.getPointerId("primary");if(n!=null&&this.context.input.getIsPointerIdInUse(n))return;const o=e.getGesture("pinch");o&&(i=o.value)}else i=e.getStick("xr-standard-thumbstick")?.y;if(this._didTeleport)i>=0&&i<.4?this._didTeleport=!1:i<0&&i>-.4&&(this._didTeleport=!1);else if(i>.8){this._didTeleport=!0;const n=this.context.physics.raycastFromRay(e.ray)[0];if(n&&n.object instanceof G.GroundedSkybox){const r=n.normal?.dot(V(0,1,0));if(r!==void 0&&r<.4)return}let o=n?.point;if(!o&&!this.useTeleportTarget){this._plane||(this._plane=new c.Plane(new c.Vector3(0,1,0),0));const r=t.worldPosition;this._plane.setFromNormalAndCoplanarPoint(new c.Vector3(0,1,0),r);const a=e.ray;o=r.clone(),this._plane.intersectLine(new c.Line3(a.origin,V(a.direction).multiplyScalar(1e4).add(a.origin)),o),o.distanceTo(r)>t.scale.x*10&&(o=null)}if(o){if(this.useTeleportTarget&&!x.getComponentInParent(n.object,su))return;const r=o.clone();if(_f&&j.DrawSphere(o,.025,16711680,5),this.context.mainCamera?.position){const l=this.context.xr?.getUserOffsetInRig();l&&(l.y=0,r.sub(l),_f&&j.DrawWireSphere(l.add(r),.025,65280,5))}this._teleportBuffer.push(t.matrix.clone()),this._teleportBuffer.length>10&&this._teleportBuffer.shift(),this.useTeleportFade?e.xr.fadeTransition()?.then(()=>{t.worldPosition=r}):t.worldPosition=r}}else if(i<-.8&&(this._didTeleport=!0,this._teleportBuffer.length>0)){const n=this._teleportBuffer.pop();n&&n.decompose(t.position,t.quaternion,t.scale)}}_plane=null;_lines=[];_hitDiscs=[];_hitDistances=[];_lastHitDistances=[];renderRays(e){for(let t=0;t<this._lines.length;t++){const i=this._lines[t];i&&(i.visible=!1)}for(let t=0;t<e.controllers.length;t++){const i=e.controllers[t];let n=this._lines[t];if(!i.connected||!i.isTracking||!i.ray||i.targetRayMode==="transient-pointer"||!i.hasSelectEvent){n&&(n.visible=!1);continue}n||(n=this.createRayLineObject(),n.scale.z=.5,this._lines[t]=n),i.updateRayWorldPosition(),i.updateRayWorldQuaternion();const o=i.rayWorldPosition,r=i.rayWorldQuaternion;n.position.copy(o),n.quaternion.copy(r);const a=e.rigScale,l=this.usePinchToTeleport&&i.isTeleportGesture,h=this._lastHitDistances[t],d=this._hitDistances[t]!=null,u=h??a;n.scale.set(a,a,u),n.visible=!0,n.layers.disableAll(),n.layers.enable(2);let p=n.material.opacity;l?p=1:this.showHits&&u<e.rigScale*.5?p=0:i.getButton("primary")?.pressed?p=.5:p=d?.2:.1,n.material.opacity=I.lerp(n.material.opacity,p,this.context.time.deltaTimeUnscaled/.1),n.parent!==this.context.scene&&this.context.scene.add(n)}}renderHits(e){for(const t of this._hitDiscs){if(!t)continue;const i=t.controller;if(!i||!i.connected||!i.isTracking){t.visible=!1;continue}}for(let t=0;t<e.controllers.length;t++){const i=e.controllers[t];if(!i.connected||!i.isTracking||!i.ray||!i.hasSelectEvent)continue;let n=this._hitDiscs[t],o=!0;const r=i.getPointerId("primary");r!=null&&this.context.input.getIsPointerIdInUse(r)&&(n&&(n.visible=!1),this._hitDistances[t]=null,this._lastHitDistances[t]=0,o=!1);const a=this.context.time.smoothedFps>=59?1:10;if((this.context.time.frame+i.index)%a!==0&&(o=!1),!o){const d=this._hitDiscs[t];d&&d.visible&&d.hit&&this.updateHitPointerPosition(i,d,d.hit.distance);continue}const l=this.context.physics.raycastFromRay(i.ray,{testObject:this.hitPointRaycastFilter,precise:!1});let h=l.find(d=>this.usePinchToTeleport&&i.isTeleportGesture?!0:this.isObjectWithInteractiveComponent(d.object));if(h||(h=l[0]),n&&(n.controller=i,n.hit=h),this._hitDistances[t]=h?.distance||null,h){this._lastHitDistances[t]=h.distance;const d=e.rigScale??1;_f&&(j.DrawWireSphere(h.point,.025*d,16711680),j.DrawLabel(V(0,.2,0).add(h.point),h.object.name,.02,0)),n||(n=this.createHitPointObject(),this._hitDiscs[t]=n),n.hit=h,n.visible=h.distance>d*.05;let u=.01*(d+h.distance);const p=i.getButton("primary")?.pressed;p&&(u*=1.1),n.scale.set(u,u,u),n.layers.set(2);let m=n.material.opacity;if(p?m=1:m=h.distance<.15*d?.2:.6,n.material.opacity=I.lerp(n.material.opacity,m,this.context.time.deltaTimeUnscaled/.1),n.visible){if(h.normal){this.updateHitPointerPosition(i,n,h.distance);const y=h.normal.applyQuaternion(ue(h.object));n.quaternion.setFromUnitVectors(RM,y)}else this.updateHitPointerPosition(i,n,h.distance);n.parent!==this.context.scene&&this.context.scene.add(n)}}else this._hitDiscs[t]&&(this._hitDiscs[t].visible=!1)}}isObjectWithInteractiveComponent(e,t=0){return hd(e)||e.isUI===!0?!0:e.isScene?!1:e.parent?this.isObjectWithInteractiveComponent(e.parent,t+1):!1}updateHitPointerPosition(e,t,i){const n=V(e.rayWorldPosition);n.add(V(0,0,i-.01).applyQuaternion(e.rayWorldQuaternion)),t.position.lerp(n,this.context.time.deltaTimeUnscaled/.05)}hitPointRaycastFilter=e=>e.type==="SkinnedMesh"?"continue in children":!0;createHitPointObject(){const e=new c.Mesh(new c.SphereGeometry(.3,6,6),new c.MeshBasicMaterial({color:15658734,opacity:.7,transparent:!0,depthTest:!1,depthWrite:!1,side:c.DoubleSide}));return e.layers.disableAll(),e.layers.enable(2),e}createRayLineObject(){const e=new G.Line2;e.layers.disableAll(),e.layers.enable(2);const t=new G.LineGeometry;e.geometry=t;const i=new Float32Array(9);i.set([0,0,.02,0,0,.4,0,0,1]),t.setPositions(i);const n=new Float32Array(9);n.set([1,1,1,.1,.1,.1,0,0,0]),t.setColors(n);const o=new G.LineMaterial({color:16777215,vertexColors:!0,worldUnits:!0,linewidth:.004,transparent:!0,depthWrite:!1,blending:c.AdditiveBlending,dashed:!1});return e.material=o,e}}so([f()],pi.prototype,"movementSpeed");so([f()],pi.prototype,"rotationStep");so([f()],pi.prototype,"useTeleport");so([f()],pi.prototype,"usePinchToTeleport");so([f()],pi.prototype,"useTeleportTarget");so([f()],pi.prototype,"useTeleportFade");so([f()],pi.prototype,"showRays");so([f()],pi.prototype,"showHits");const RM=new c.Vector3(0,1,0);var EM=Object.defineProperty,rt=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&EM(e,t,n),n};const Wa=w("debugwebxr"),TM=w("debugusdz"),Je=class jr extends k{createVRButton=!0;createARButton=!0;createSendToQuestButton=!0;createQRCode=!0;useDefaultControls=!0;showControllerModels=!0;showHandModels=!0;usePlacementReticle=!0;customARPlacementReticle;usePlacementAdjustment=!0;arScale=1;useXRAnchor=!1;autoPlace=!1;autoCenter=!1;useQuicklookExport=!1;useDepthSensing=!1;useSpatialGrab=!0;defaultAvatar;_playerSync;_createdComponentsInSession=[];_usdzExporter;static activeWebXRComponent=null;awake(){q.getXRSync(this.context)}onEnable(){window.location.protocol!=="https:"&&ce('<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&&(x.findObjectOfType(En)||(Wa&&console.log("WebXR: Adding USDZExporter"),this._usdzExporter=x.addComponent(this.gameObject,En),this._usdzExporter.objectToExport=this.context.scene,this._usdzExporter.autoExportAnimations=!0,this._usdzExporter.autoExportAudioSources=!0)),this.handleCreatingHTML(),this.handleOfferSession(),this.defaultAvatar===!0&&(Wa&&console.warn("WebXR: No default avatar set, using static default avatar"),this.defaultAvatar=new Y("https://cdn.needle.tools/static/avatars/DefaultAvatar.glb")),this.defaultAvatar&&(this._playerSync=this.gameObject.getOrAddComponent(ig),this._playerSync.autoSync=!1),this._playerSync&&typeof this.defaultAvatar!="boolean"&&(this._playerSync.asset=this.defaultAvatar,this._playerSync.onPlayerSpawned?.removeEventListener(this.onAvatarSpawned),this._playerSync.onPlayerSpawned?.addEventListener(this.onAvatarSpawned))}onDisable(){this._usdzExporter?.destroy(),this.removeButtons()}async handleOfferSession(){return this.createVRButton&&await q.isVRSupported()&&this.createVRButton?q.offerSession("immersive-vr","default",this.context):this.createARButton&&await q.isARSupported()&&this.createARButton?q.offerSession("immersive-ar","default",this.context):!1}get session(){return q.active??null}get sessionMode(){return q.activeMode??null}get arSessionRoot(){return this._activeWebARSessionRoot}async enterVR(e){return q.start("immersive-vr",e,this.context)}async enterAR(e){return q.start("immersive-ar",e,this.context)}exitXR(){q.stop()}_exitXRMenuButton;_previousXRState=0;_spatialGrabRaycaster;_activeWebARSessionRoot=null;get isActiveWebXR(){return!jr.activeWebXRComponent||jr.activeWebXRComponent===this}onBeforeXR(e,t){if(!this.isActiveWebXR){console.warn(`WebXR: another WebXR component is already active (${jr.activeWebXRComponent?.name}). This is ignored: ${this.name}`);return}jr.activeWebXRComponent=this,e=="immersive-ar"&&this.useDepthSensing&&(t.optionalFeatures=t.optionalFeatures||[],t.optionalFeatures.push("depth-sensing"))}async onEnterXR(e){if(!this.isActiveWebXR)return;Wa&&console.log("WebXR onEnterXR"),this._previousXRState=It.Global.Mask;const t=e.xr.isVR;if(It.Global.Set(t?bn.VR:bn.AR),e.xr.isAR){let i=x.findObjectOfType(li);if(!i)if(this.usePlacementReticle){const n=new c.Object3D;for(const o of this.context.scene.children)n.add(o);this.context.scene.add(n),i=x.addComponent(n,li),this._createdComponentsInSession.push(i)}else(Wa||A())&&console.warn("WebXR: No WebARSessionRoot found in scene and usePlacementReticle is disabled in WebXR component.");this._activeWebARSessionRoot=i,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=x.findObjectOfType(Go)??void 0,this._spatialGrabRaycaster||(this._spatialGrabRaycaster=this.gameObject.addComponent(Go))),this.createLocalAvatar(e.xr),e.xr.isScreenBasedAR||(this._exitXRMenuButton=this.context.menu.appendChild({label:"Quit XR",onClick:()=>this.exitXR(),icon:"exit_to_app",priority:2e4}))}onUpdateXR(e){this.isActiveWebXR&&this._spatialGrabRaycaster&&(this._spatialGrabRaycaster.enabled=this.useSpatialGrab)}onLeaveXR(e){if(this._exitXRMenuButton?.remove(),!!this.isActiveWebXR){It.Global.Set(this._previousXRState),this._playerSync?.destroyInstance();for(const t of this._createdComponentsInSession)t.destroy();this._createdComponentsInSession.length=0,this._activeWebARSessionRoot=null,this.handleOfferSession(),ec(1).then(()=>jr.activeWebXRComponent=null)}}setDefaultMovementEnabled(e){let t=this.gameObject.getComponent(pi);return!t&&e&&(t=this.gameObject.addComponent(pi),this._createdComponentsInSession.push(t)),t&&(t.enabled=e),t}setDefaultControllerRenderingEnabled(e){let t=this.gameObject.getComponent(ls);return!t&&e&&(t=this.gameObject.addComponent(ls),this._createdComponentsInSession.push(t),t.createControllerModel=this.showControllerModels,t.createHandModel==this.showHandModels),t&&(t.enabled=e),t}async createLocalAvatar(e){this._playerSync&&e.running&&typeof this.defaultAvatar!="boolean"&&(this._playerSync.asset=this.defaultAvatar,await this._playerSync.getInstance())}onAvatarSpawned=e=>{Wa&&console.log("WebXR.onAvatarSpawned",e);let t=x.getComponentInChildren(e,Xs);t??=x.addComponent(e,Xs)};getButtonsContainer(){return this.getButtonsFactory()}getButtonsFactory(){return this._buttonFactory||(this._buttonFactory=Gs.getOrCreate()),this._buttonFactory}_buttonFactory;handleCreatingHTML(){if(this.createARButton||this.createVRButton||this.useQuicklookExport){if((exports.DeviceUtilities.isiOS()&&exports.DeviceUtilities.isSafari()||TM)&&this.useQuicklookExport){const t=x.findObjectOfType(En);if(!t||t&&t.allowCreateQuicklookButton){const i=this.getButtonsFactory().createQuicklookButton();this.addButton(i,50)}}if(this.createARButton){const t=this.getButtonsFactory().createARButton();this.addButton(t,50)}if(this.createVRButton){const t=this.getButtonsFactory().createVRButton();this.addButton(t,50)}}if(this.createSendToQuestButton&&!exports.DeviceUtilities.isQuest()&&q.isVRSupported().then(t=>{if(!t){const i=this.getButtonsFactory().createSendToQuestButton();this.addButton(i,50)}}),this.createQRCode){const t=cc(jn);if(t&&t.createQRCodeButton===!1)A()&&console.warn("WebXR: QRCode button is disabled in the Needle Menu component");else if(!exports.DeviceUtilities.isMobileDevice()){const i=Ki.getOrCreate().createQRCode();this.addButton(i,50)}}}_buttons=[];addButton(e,t){this._buttons.push(e),e.setAttribute("priority",t.toString()),this.context.menu.appendChild(e)}removeButtons(){for(const e of this._buttons)e.remove();this._buttons.length=0}};rt([f()],Je.prototype,"createVRButton");rt([f()],Je.prototype,"createARButton");rt([f()],Je.prototype,"createSendToQuestButton");rt([f()],Je.prototype,"createQRCode");rt([f()],Je.prototype,"useDefaultControls");rt([f()],Je.prototype,"showControllerModels");rt([f()],Je.prototype,"showHandModels");rt([f()],Je.prototype,"usePlacementReticle");rt([f(Y)],Je.prototype,"customARPlacementReticle");rt([f()],Je.prototype,"usePlacementAdjustment");rt([f()],Je.prototype,"arScale");rt([f()],Je.prototype,"useXRAnchor");rt([f()],Je.prototype,"autoPlace");rt([f()],Je.prototype,"autoCenter");rt([f()],Je.prototype,"useQuicklookExport");rt([f()],Je.prototype,"useDepthSensing");rt([f()],Je.prototype,"useSpatialGrab");rt([f(Y)],Je.prototype,"defaultAvatar");let ou=Je;const _h=w("debugusdzbehaviours");class sg{get extensionName(){return"Behaviour"}behaviours=[];addBehavior(e){this.behaviours.push(e)}addAudioClip(e){if(!e||typeof e!="string")return"";const i="audio/"+ar.getName(e);return this.audioClips.push({clipUrl:e,filesKey:i}),i}behaviourComponents=[];behaviourComponentsCopy=[];audioClips=[];audioClipsCopy=[];targetUuids=new Set;getAllTargetUuids(){return this.targetUuids}onBeforeBuildDocument(e){if(!e.root)return Promise.resolve();const t=[];return e.root.traverse(i=>{x.foreachComponent(i,n=>{const o=n;if(typeof o.createBehaviours=="function"||typeof o.beforeCreateDocument=="function"||typeof o.afterCreateDocument=="function"||typeof o.afterSerialize=="function"){this.behaviourComponents.push(o);const r=o.beforeCreateDocument?.call(o,this,e);r instanceof Promise&&t.push(r)}},!1)}),_h&&console.log("onBeforeBuildDocument: all components",this.behaviourComponents),Promise.all(t)}onExportObject(e,t,i){for(const n of this.behaviourComponents)n.createBehaviours?.call(n,this,t,i)}onAfterBuildDocument(e){for(const u of this.behaviourComponents)typeof u.afterCreateDocument=="function"&&u.afterCreateDocument(this,e);this.behaviourComponentsCopy=this.behaviourComponents.slice(),this.behaviourComponents.length=0,this.audioClipsCopy=this.audioClips.slice(),this.audioClips.length=0;const t=new Set,i=new Set,n=new Set,o=new Set,r=_h;let a=`graph LR
1262
+ `))}for(const z of E){const K=o.get(z);K&&F.set(z,K)}return F},m=function(E){const F=p(E),z=l(F);return h(F,z,E)};const y=n.skinnedMesh.skeleton,b=new Array,g=[],v=[];for(const E of y.bones){g.push(E),v.push(E.uuid);const F=y.boneInverses[y.bones.indexOf(E)];b.push({bone:E,inverse:F})}let _=1e4;for(;v.length<y.bones.length&&_-- >0;)for(const E of g){const F=E.children;for(const z of F)if(v.indexOf(z.uuid)===-1&&y.bones.indexOf(z)!==-1){g.push(z),v.push(z.uuid);const K=y.boneInverses[y.bones.indexOf(z)];b.push({bone:z,inverse:K})}}_<=0&&console.error("Failed to sort bones in skinned mesh",n.skinnedMesh,y.bones,v);for(const E of Rv(y.bones))b.push({bone:E,inverse:E.matrixWorld.clone().invert()});const S=b[0].bone.parent;S||console.error("No bone parent found for skinned mesh during USDZ export",n.skinnedMesh),b.sort((E,F)=>Qr(E.bone,S)>Qr(F.bone,S)?1:-1);const T=t.quickLookCompatible,M=[],O=[],R=[],B=[];for(const{bone:E}of b){if(T){const F=E.scale;F.x==0&&(F.x=1e-5),F.y==0&&(F.y=1e-5),F.z==0&&(F.z=1e-5),M.push(new c.Matrix4().compose(E.position,E.quaternion,E.scale))}else M.push(E.matrix.clone());O.push(E.position),R.push(E.quaternion),B.push(E.scale)}const L=b.map(E=>'"'+Qr(E.bone,S)+'"').join(", "),N=b.map(E=>h_(E.inverse.clone().invert())).join(", ");e.beginBlock('def Skeleton "Rig"'),e.appendLine(`uniform matrix4d[] bindTransforms = [${N}]`),e.appendLine(`uniform token[] joints = [${L}]`),e.appendLine('uniform token purpose = "guide"'),e.appendLine(`uniform matrix4d[] restTransforms = [${M.map(E=>h_(E)).join(", ")}]`);const $=m(b.map(E=>E.bone));if(yn){let E=1e7,F=0;for(const z of $.position?.keys()??[])E=Math.min(E,z),F=Math.max(F,z);console.log("Time samples",E,F,$)}if(e.beginBlock('def SkelAnimation "_anim"'),e.appendLine(`uniform token[] joints = [${L}]`),e.appendLine(`quatf[] rotations = [${u(R)}]`),$&&$.quaternion){e.beginBlock("quatf[] rotations.timeSamples = {","");const E=a($.quaternion);for(const F of E)e.appendLine(F);e.closeBlock()}if(e.appendLine(`half3[] scales = [${d(B)}]`),$&&$.scale){e.beginBlock("half3[] scales.timeSamples = {","");const E=r($.scale);for(const F of E)e.appendLine(F);e.closeBlock()}if(e.appendLine(`float3[] translations = [${d(O)}]`),$&&$.position){e.beginBlock("float3[] translations.timeSamples = {","");const E=r($.position);for(const F of E)e.appendLine(F);e.closeBlock()}e.closeBlock(),e.closeBlock()}}onSerialize(e,t){if(!this.model)return;const i=this.animationData.get(this.object);if(i)for(let d=0;d<i.length;d++)i[d]===void 0&&(i[d]=new ke(null,this.object,null));const n=this.ext;this.skinnedMeshExport(e,t,n);const o=this.object,r=this.model,a=this.animationData.get(o);if(!a||o.isSkinnedMesh)return;_p&&console.log("SERIALIZE",this.model.name,this.object.type,a);const l=Intl.NumberFormat("en-US",{maximumFractionDigits:3,minimumFractionDigits:0,useGrouping:!1});function h(d,u){if(d.some(m=>m&&{position:m.pos,rotation:m.rot,scale:m.scale}[u])){switch(u){case"position":r.needsTranslate=!0,e.beginBlock("double3 xformOp:translate.timeSamples = {","");break;case"rotation":r.needsOrient=!0,e.beginBlock("quatf xformOp:orient.timeSamples = {","");break;case"scale":r.needsScale=!0,e.beginBlock("double3 xformOp:scale.timeSamples = {","");break}for(let m=0;m<d.length;m++){const y=d[m];if(!y)continue;const b=n.getStartTimeByClip(y.clip),g=y.getSortedTimesArray(u==="position",u==="rotation",u==="scale");if(!g||g.length===0){console.error("got an animated object but no time values?",o,y);continue}const v=!y.clip,_=u==="position"&&(y.pos||v),S=u==="rotation"&&(y.rot||v),T=u==="scale"&&(y.scale||v);if(_||S||T){const M=y.clip?.name??"rest",O=y.getDuration();yn&&console.log("Write .timeSamples:",M,b,O,d),e.appendLine("# "+M+": start="+l.format(b*ke.frameRate)+", length="+l.format(O*ke.frameRate)+", frames="+y.getFrames())}if(_)for(const{time:M,translation:O}of y.getValues(g,!0,!1,!1)){const B=`${l.format((b+M)*ke.frameRate)}: (${te(O.x)}, ${te(O.y)}, ${te(O.z)}),`;e.appendLine(B)}if(S)for(const{time:M,rotation:O}of y.getValues(g,!1,!0,!1)){const B=`${l.format((b+M)*ke.frameRate)}: (${te(O.w)}, ${te(O.x)}, ${te(O.y)}, ${te(O.z)}),`;e.appendLine(B)}if(T)for(const{time:M,scale:O}of y.getValues(g,!1,!1,!0)){const B=`${l.format((b+M)*ke.frameRate)}: (${te(O.x)}, ${te(O.y)}, ${te(O.z)}),`;e.appendLine(B)}}e.closeBlock()}}h(a,"position"),h(a,"rotation"),h(a,"scale")}}const uM=w("debugusdz");class ar{static getName(e){const t=e.split(".").pop();let n=e.split(".").slice(0,-1).join(".").split("/").pop()?.replace(".","_");return n||(n="Audio_"+Math.random().toString(36).substring(2,15)),ji(n)+"."+t}get extensionName(){return"Audio"}files=new Array;onExportObject(e,t,i){const n=x.getComponents(e,Ii);if(n.length)for(const o of n){if(!o.clip||typeof o.clip!="string"||!o.playOnAwake)continue;const r=o.clip.split("/").pop()||"Audio",a=ar.getName(o.clip),l=ji(a);if(!this.files.some(h=>h.path===o.clip)){this.files.push({path:o.clip,name:a});const h=a.toLowerCase();i.quickLookCompatible&&!h.endsWith(".mp3")&&!h.endsWith(".wav")&&!h.endsWith(".m4a")&&console.error("Audio file "+o.clip+" from "+o.name+" is not an MP3 or WAV file. QuickLook may not support playing it.")}i.quickLookCompatible||t.addEventListener("serialize",(h,d)=>{h.appendLine(),h.beginBlock(`def SpatialAudio "${l}"`,"(",!1),h.appendLine(`displayName = "${r}"`),h.closeBlock(")"),h.beginBlock(),h.appendLine(`uniform asset filePath = @audio/${a}@`),h.appendLine(`uniform token auralMode = "${o.spatialBlend>0?"spatial":"nonSpatial"}"`),h.appendLine(`uniform token playbackMode = "${o.loop?"loopFromStage":"onceFromStart"}"`),h.appendLine(`uniform float gain = ${o.volume}`),h.closeBlock()})}}async onAfterSerialize(e){for(const t of this.files){const i="audio/"+t.name;if(e.files[i]){uM&&console.warn("Audio file with name "+i+" already exists in the context. Skipping.");continue}const r=await(await(await fetch(t.path)).blob()).arrayBuffer(),a=new Uint8Array(r);e.files[i]=a}}}var fM=Object.defineProperty,Re=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&fM(e,t,n),n};const m_=w("debugusdzbehaviours");function vc(s){s&&(s.getComponentInParent(aa)||(A()&&console.debug('Raycaster on "'+s.name+'" was automatically added, because no raycaster was found in the parent hierarchy.'),s.addComponent(ui)))}class lr extends k{object;target;duration=1;relativeMotion=!1;coroutine=null;targetPos=new c.Vector3;targetRot=new c.Quaternion;targetScale=new c.Vector3;start(){vc(this.gameObject)}onPointerClick(e){e.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 e=X(this.object).clone(),t=X(this.target).clone(),i=ue(this.object).clone(),n=ue(this.target).clone(),o=Ae(this.object).clone(),r=Ae(this.target).clone(),a=e.distanceTo(t),l=i.angleTo(n),h=o.distanceTo(r);if(a<.01&&l<.01&&h<.01){Ye(this.object,t),Di(this.object,n),Jr(this.object,r),this.coroutine=null;return}let d=0,u=0;for(;d<1;)d+=this.context.time.deltaTime/this.duration,d>1&&(d=1),u=d<.5?4*d*d*d:1-Math.pow(-2*d+2,3)/2,this.targetPos.lerpVectors(e,t,u),this.targetRot.slerpQuaternions(i,n,u),this.targetScale.lerpVectors(o,r,u),Ye(this.object,this.targetPos),Di(this.object,this.targetRot),Jr(this.object,this.targetScale),yield;this.coroutine=null}*moveRelative(){if(!this.target||!this.object)return;const e=this.object.position.clone(),t=this.object.quaternion.clone(),i=this.object.scale.clone(),n=this.target.position.clone(),o=this.target.quaternion.clone(),r=this.target.scale.clone();n.applyQuaternion(this.object.quaternion),this.targetPos.copy(this.object.position).add(n),this.targetRot.copy(this.object.quaternion).multiply(o),this.targetScale.copy(this.object.scale).multiply(r);let a=0,l=0;for(;a<1;)a+=this.context.time.deltaTime/this.duration,a>1&&(a=1),l=a<.5?4*a*a*a:1-Math.pow(-2*a+2,3)/2,this.object.position.lerpVectors(e,this.targetPos,l),this.object.quaternion.slerpQuaternions(t,this.targetRot,l),this.object.scale.lerpVectors(i,this.targetScale,l),yield;this.coroutine=null}beforeCreateDocument(e){if(this.target&&this.object&&this.gameObject){const t=new pt("Move to "+this.target?.name,xt.tapTrigger(this.gameObject),ae.transformAction(this.object,this.target,this.duration,this.relativeMotion?"relative":"absolute"));e.addBehavior(t)}}}Re([f(c.Object3D)],lr.prototype,"object");Re([f(c.Object3D)],lr.prototype,"target");Re([f()],lr.prototype,"duration");Re([f()],lr.prototype,"relativeMotion");const eu=class Tt extends k{materialToSwitch;variantMaterial;fadeDuration=0;start(){this._objectsWithThisMaterial=this.objectsWithThisMaterial,vc(this.gameObject),A()&&this._objectsWithThisMaterial.length<=0&&console.warn('ChangeMaterialOnClick: No objects found with material "'+this.materialToSwitch?.name+'"')}onPointerEnter(e){this.context.input.setCursor("pointer")}onPointerExit(e){this.context.input.unsetCursor("pointer")}onPointerClick(e){if(e.use(),!!this.variantMaterial)for(let t=0;t<this.objectsWithThisMaterial.length;t++){const i=this.objectsWithThisMaterial[t];i.material=this.variantMaterial}}_objectsWithThisMaterial=null;get objectsWithThisMaterial(){return this._objectsWithThisMaterial!=null?this._objectsWithThisMaterial:(this._objectsWithThisMaterial=[],this.variantMaterial&&this.materialToSwitch&&this.context.scene.traverse(e=>{if(e instanceof c.Mesh)if(Array.isArray(e.material)){for(const t of e.material)if(t===this.materialToSwitch){this.objectsWithThisMaterial.push(e);break}}else e.material===this.materialToSwitch?this.objectsWithThisMaterial.push(e):o0(e.material,this.materialToSwitch)&&this.objectsWithThisMaterial.push(e)}),this._objectsWithThisMaterial)}selfModel;targetModels;static _materialTriggersPerId={};static _startHiddenBehaviour=null;static _parallelStartHiddenActions=[];async beforeCreateDocument(e,t){this.targetModels=[],Tt._materialTriggersPerId={},Tt.variantSwitchIndex=0,this.materialToSwitch&&await ne.NEEDLE_progressive.assignTextureLOD(this.materialToSwitch,0),this.variantMaterial&&await ne.NEEDLE_progressive.assignTextureLOD(this.variantMaterial,0)}createBehaviours(e,t,i){this.objectsWithThisMaterial.find(o=>o.uuid===t.uuid)&&this.targetModels.push(t),this.gameObject.uuid===t.uuid&&(this.selfModel=t,this.materialToSwitch&&(Tt._materialTriggersPerId[this.materialToSwitch.uuid]||(Tt._materialTriggersPerId[this.materialToSwitch.uuid]=[]),Tt._materialTriggersPerId[this.materialToSwitch.uuid].push(this)))}afterCreateDocument(e,t){if(!this.materialToSwitch)return;const i=Tt._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 a in n)a!==o.selfModel.uuid&&r.push(...n[a]);o.createAndAttachBehaviors(e,n[o.selfModel.uuid],r)}}delete Tt._materialTriggersPerId[this.materialToSwitch.uuid]}createAndAttachBehaviors(e,t,i){const n=[],o=Math.max(0,this.fadeDuration);n.push(ae.fadeAction([...this.targetModels,...i],o,!1)),n.push(ae.fadeAction(t,o,!0)),e.addBehavior(new pt("Select_"+this.selfModel.name,xt.tapTrigger(this.selfModel),ae.parallel(...n))),Tt._parallelStartHiddenActions.push(...t),Tt._startHiddenBehaviour||(Tt._startHiddenBehaviour=new pt("StartHidden_"+this.selfModel.name,xt.sceneStartTrigger(),ae.fadeAction(Tt._parallelStartHiddenActions,o,!1)),e.addBehavior(Tt._startHiddenBehaviour))}static getMaterialName(e){return ji(e.name||"Material")+"_"+e.id}static variantSwitchIndex=0;createVariants(){if(!this.variantMaterial)return null;const e=[];for(const t of this.targetModels){const i=t.clone();i.name+="_Variant_"+Tt.variantSwitchIndex+++"_"+Tt.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())&&ze.createEmptyParent(t),t.parent&&t.parent.add(i),e.push(i)}return e}};Re([f(c.Material)],eu.prototype,"materialToSwitch");Re([f(c.Material)],eu.prototype,"variantMaterial");Re([f()],eu.prototype,"fadeDuration");let Qm=eu;const wc=class Pe extends k{target;toggleOnClick=!1;targetState=!0;hideSelf=!0;start(){vc(this.gameObject)}onPointerClick(e){e.use(),!this.toggleOnClick&&this.hideSelf&&(this.gameObject.visible=!1),this.target&&(this.target.visible=this.toggleOnClick?!this.target.visible:this.targetState)}selfModel;selfModelClone;targetModel;toggleModel;createBehaviours(e,t,i){t.uuid===this.gameObject.uuid&&(this.selfModel=t,this.selfModelClone=t.clone())}stateBeforeCreatingDocument=!1;targetStateBeforeCreatingDocument=!1;static clonedToggleIndex=0;static wasVisible=Symbol("usdz_SetActiveOnClick_wasVisible");static toggleClone=Symbol("clone for toggling");static reverseToggleClone=Symbol("clone for reverse toggling");beforeCreateDocument(){this.target&&(this.gameObject[Pe.wasVisible]===void 0&&(this.gameObject[Pe.wasVisible]=this.gameObject.activeSelf),this.target[Pe.wasVisible]===void 0&&(this.target[Pe.wasVisible]=this.target.activeSelf),this.stateBeforeCreatingDocument=this.gameObject[Pe.wasVisible],this.targetStateBeforeCreatingDocument=this.target[Pe.wasVisible],this.gameObject.visible=!0,this.target.visible=!0)}afterCreateDocument(e,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())&&Hm.createEmptyParent(this.selfModel),this.toggleModel=this.selfModel.deepClone(),this.toggleModel.name+="_toggle",this.selfModel.parent.add(this.toggleModel);else{if(!this.gameObject[Pe.toggleClone]){const l=this.selfModelClone.clone();l.setMatrix(new c.Matrix4),l.name+="_toggle"+Pe.clonedToggleIndex++,i.add(l),this.gameObject[Pe.toggleClone]=l,console.warn("USDZExport: Toggle "+this.gameObject.name+" doesn't have geometry. It will be deep cloned and nested behaviours will likely not work.")}const a=this.gameObject[Pe.toggleClone];if(!this.gameObject[Pe.reverseToggleClone]){const l=this.selfModelClone.clone();l.setMatrix(new c.Matrix4),l.name+="_toggleReverse"+Pe.clonedToggleIndex++,i.add(l),this.gameObject[Pe.reverseToggleClone]=l}this.toggleModel=this.gameObject[Pe.reverseToggleClone],(!this.toggleModel.geometry||!a.geometry)&&console.error("triggers without childs and without geometry won't work!",this,i.geometry),n=a,i.geometry=null,i.material=null}if(this.toggleModel){if(this.toggleOnClick){const a=[];a.push(ae.fadeAction(n,0,!1)),a.push(ae.fadeAction(this.toggleModel,0,!0)),a.push(ae.fadeAction(this.targetModel,0,o)),e.addBehavior(new pt("Toggle_"+n.name+"_ToggleTo"+(o?"On":"Off"),xt.tapTrigger(n),ae.parallel(...a)));const l=[];l.push(ae.fadeAction(this.toggleModel,0,!1)),l.push(ae.fadeAction(n,0,!0)),l.push(ae.fadeAction(this.targetModel,0,!o)),e.addBehavior(new pt("Toggle_"+n.name+"_ToggleTo"+(o?"Off":"On"),xt.tapTrigger(this.toggleModel),ae.parallel(...l)))}}else{const a=[];this.hideSelf&&a.push(ae.fadeAction(n,0,!1)),a.push(ae.fadeAction(this.targetModel,0,o)),e.addBehavior(new pt("Toggle_"+n.name+"_ToggleTo"+(o?"On":"Off"),xt.tapTrigger(n),a.length>1?ae.parallel(...a):a[0]))}const r=new Array;this.targetStateBeforeCreatingDocument||r.push(this.targetModel),this.stateBeforeCreatingDocument||r.push(i),this.toggleModel&&r.push(this.toggleModel),Ri.add(r,e)}}afterSerialize(e,t){this.gameObject[Pe.wasVisible]!==void 0&&(this.gameObject.visible=this.gameObject[Pe.wasVisible],delete this.gameObject[Pe.wasVisible]),this.target&&this.target[Pe.wasVisible]!==void 0&&(this.target.visible=this.target[Pe.wasVisible],delete this.target[Pe.wasVisible]),delete this.gameObject[Pe.toggleClone],delete this.gameObject[Pe.reverseToggleClone]}};Re([f(c.Object3D)],wc.prototype,"target");Re([f()],wc.prototype,"toggleOnClick");Re([f()],wc.prototype,"targetState");Re([f()],wc.prototype,"hideSelf");let Ym=wc;class Ri extends k{static _fadeBehaviour;static _fadeObjects=[];static add(e,t){const i=Array.isArray(e)?e:[e];for(const n of i)Ri._fadeObjects.includes(n)||(console.log("adding hide on start",n),Ri._fadeObjects.push(n));Ri._fadeBehaviour===void 0&&(Ri._fadeBehaviour=new pt("HideOnStart",xt.sceneStartTrigger(),ae.fadeAction(Ri._fadeObjects,0,!1)),t.addBehavior(Ri._fadeBehaviour))}start(){x.setActive(this.gameObject,!1)}createBehaviours(e,t,i){t.uuid===this.gameObject.uuid&&(this.wasVisible||Ri.add(t,e))}wasVisible=!1;beforeCreateDocument(){this.wasVisible=x.isActiveSelf(this.gameObject)}}class ba extends k{target;duration=.5;motionType="bounce";beforeCreateDocument(){}createBehaviours(e,t,i){if(this.target&&t.uuid===this.gameObject.uuid){const n=new pt("emphasize "+this.name,xt.tapTrigger(this.gameObject),ae.emphasize(this.target,this.duration,this.motionType,void 0,"basic"));e.addBehavior(n)}}afterCreateDocument(e,t){}}Re([f()],ba.prototype,"target");Re([f()],ba.prototype,"duration");Re([f()],ba.prototype,"motionType");class qs extends k{target;clip="";toggleOnClick=!1;trigger="tap";start(){vc(this.gameObject)}ensureAudioSource(){if(!this.target){const e=this.gameObject.addComponent(Ii);e&&(this.target=e,e.spatialBlend=1,e.volume=1,e.loop=!1,e.preload=!0)}}onPointerClick(e){e.use(),!(!this.target?.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(e,t,i){if(!(!this.target&&!this.clip)&&t.uuid===this.gameObject.uuid){const n=this.clip?this.clip:this.target?this.target.clip:void 0;if(!n||typeof n!="string")return;const o=this.target?this.target.gameObject:this.gameObject;ar.getName(n);const r=this.target?this.target.volume:1,a=this.target&&this.target.spatialBlend==0?"nonSpatial":"spatial";let l=!1;this.gameObject.traverse(p=>{p instanceof c.Mesh&&p.visible&&(l=!0)}),l=!0;const h=e.addAudioClip(n);let d=ae.playAudioAction(o,h,"play",r,a);this.target&&this.target.loop&&(d=ae.sequence(d).makeLooping());const u=this.name?"_"+this.name:"";if(l&&this.trigger==="tap"){this.toggleOnClick&&(d.multiplePerformOperation="stop");const p=new pt("playAudio"+u,xt.tapTrigger(t),d);e.addBehavior(p)}if(this.target&&this.target.playOnAwake&&this.target.enabled)if(l&&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 p=new pt("playAudioOnStart"+u,xt.sceneStartTrigger(),d);e.addBehavior(p)}}}}Re([f(Ii)],qs.prototype,"target");Re([f(URL)],qs.prototype,"clip");Re([f()],qs.prototype,"toggleOnClick");const Km=class un extends k{animator;stateName;trigger="tap";animation;get target(){return this.animator?.gameObject||this.animation?.gameObject}start(){vc(this.gameObject)}onPointerClick(e){e.use(),this.target&&this.stateName&&this.animator?.play(this.stateName,0,0,.1)}selfModel;stateAnimationModel;animationSequence=new Array;animationLoopAfterSequence=new Array;randomOffsetNormalized=0;createBehaviours(e,t,i){t.uuid===this.gameObject.uuid&&(this.selfModel=t)}static animationActions=[];static rootsWithExclusivePlayback=new Set;afterSerialize(){if(un.rootsWithExclusivePlayback.size>1){const e='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.';A()&&ce(e),console.warn(e,...un.rootsWithExclusivePlayback)}un.animationActions=[],un.rootsWithExclusivePlayback=new Set}afterCreateDocument(e,t){if(this.animationSequence===void 0&&this.animationLoopAfterSequence===void 0||!this.stateAnimationModel||!this.target)return;const i=t.document,n=t.extensions.find(a=>a instanceof Jd);if(!n)return;const o=n.getClipCount(this.target)>1;o&&(A()&&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."),un.rootsWithExclusivePlayback.add(this.target));const r=this.name?this.name:"";i.traverse(a=>{if(a.uuid===this.target?.uuid){const l=un.getActionForSequences(i,a,this.animationSequence,this.animationLoopAfterSequence,this.randomOffsetNormalized),h=new pt(this.trigger+"_"+r+"_toPlayAnimation_"+this.stateName+"_on_"+this.target?.name,this.trigger=="tap"?xt.tapTrigger(this.selfModel):xt.sceneStartTrigger(),l);o&&h.makeExclusive(!0),e.addBehavior(h)}})}static getActionForSequences(e,t,i,n,o){const r=(l,h)=>{let d=un.animationActions.find(u=>u.affectedObjects==l&&u.start==h.start&&u.duration==h.duration&&u.animationSpeed==h.speed);return d||(d=ae.startAnimationAction(l,h),un.animationActions.push(d)),d},a=ae.sequence();if(i&&i.length>0)for(const l of i)a.addAction(r(t,l));if(n&&n.length>0){const l=a.actions.length==0?a:ae.sequence();for(const h of n)l.addAction(r(t,h));l.makeLooping(),a!==l&&a.addAction(l)}return o&&o>0&&a.actions.unshift(ae.waitAction(o)),a}static getAndRegisterAnimationSequences(e,t,i){if(!t)return;const n=t.getComponent(mt),o=t.getComponent(wt);if(!n&&!o)return;if(n&&!i)throw new Error("PlayAnimationOnClick: No stateName specified for animator "+n.name+" on "+t.name);let r=[],a=[];if(o){const y=e.registerAnimation(t,o.clip);y&&(o.loop?a.push(y):r.push(y));let b=0;if(o.minMaxOffsetNormalized){const g=o.minMaxOffsetNormalized.x,v=o.minMaxOffsetNormalized.y;b=(o.clip?.duration||1)*(g+Math.random()*(v-g))}return{animationSequence:r,animationLoopAfterSequence:a,randomTimeOffset:b}}const l=n?.runtimeAnimatorController;let h=l?.findState(i),d=[],u=[];if(l&&h){const y=new Array;y.push(h);let b=!1;for(;y.length<100;){if(!h||h===null||!h.transitions||h.transitions.length===0){h.motion?.isLooping&&(b=!0);break}const g=h.transitions.find(_=>_.conditions.length===0),v=g?l.getState(g.destinationState,0):null;if(v&&y.includes(v)){h=v,b=!0;break}else if(g){if(h=v,!h)break;y.push(h)}else{b=h.motion?.isLooping??!1;break}}if(b&&h){const g=y.indexOf(h);d=y.slice(0,g),u=y.slice(g),m_&&console.log("found loop from "+i,"states until loop",d,"states looping",u)}else d=y,u=[],m_&&console.log("found no loop from "+i,"states",d);if(!u.length){const g=d[d.length-1],v=g.motion?.clip;if(v){let _;if(e.holdClipMap.has(v))_=e.holdClipMap.get(v);else{const S=g.name+"_hold";_=v.clone(),_.duration=1,_.name=S;const T=v.duration;_.tracks=v.tracks.map(M=>{const O=M.clone();O.times=new Float32Array([0,T]);const R=M.values.length,B=M.getValueSize(),L=M.values.slice(R-B,R);return O.values=new Float32Array(2*B),O.values.set(L,0),O.values.set(L,B),O}),_.name=S,e.holdClipMap.set(v,_)}if(_){const S={name:_.name,motion:{clip:_,isLooping:!1,name:_.name},speed:1,transitions:[],behaviours:[],hash:g.hash+1};u.push(S)}}}}if(d.length===1&&(!d[0].motion?.clip||d[0].motion?.clip.tracks?.length===0)){r=new Array;const y=e.registerAnimation(t,null);y&&r.push(y);return}if(d=d.filter(y=>y.motion?.clip&&y.motion?.clip.tracks?.length>0),u=u.filter(y=>y.motion?.clip&&y.motion?.clip.tracks?.length>0),d.length===0&&u.length===0){console.warn("No clips found for state "+i+" on "+n?.name+", can't export animation data");return}const p=(y,b)=>{if(!t)return;const g=e.registerAnimation(t,y.motion.clip??null);g?(g.speed=y.speed,b.push(g)):console.warn("Couldn't register animation for state "+y.name+" on "+n?.name)};if(d.length>0){r=new Array;for(const y of d)p(y,r)}if(u.length>0){a=new Array;for(const y of u)p(y,a)}let m=0;if(n&&l&&n.minMaxOffsetNormalized){const y=n.minMaxOffsetNormalized.x,b=n.minMaxOffsetNormalized.y;m=((d.length?d[0]:u.length?u[0]:null)?.motion.clip?.duration||1)*(y+Math.random()*(b-y))}return{animationSequence:r,animationLoopAfterSequence:a,randomTimeOffset:m}}createAnimation(e,t,i){if(!this.target||!this.animator&&!this.animation)return;const n=un.getAndRegisterAnimationSequences(e,this.target,this.stateName);n&&(this.animationSequence=n.animationSequence,this.animationLoopAfterSequence=n.animationLoopAfterSequence,this.randomOffsetNormalized=n.randomTimeOffset,this.stateAnimationModel=t)}};Re([f(mt)],Km.prototype,"animator");Re([f()],Km.prototype,"stateName");let Gl=Km;class va extends k{getType(){}target;getDuration(){}}Re([f(c.Object3D)],va.prototype,"target");class xc extends k{target}Re([f(va)],xc.prototype,"target");class Sc extends va{type=1;duration=1;getType(){switch(this.type){case 1:return"hide";case 0:return"show"}}getDuration(){return this.duration}}Re([f()],Sc.prototype,"type");Re([f()],Sc.prototype,"duration");class Zm extends xc{}class Gs{static _instance;static create(){return new Gs}static getOrCreate(){return this._instance||(this._instance=this.create()),this._instance}get isSecureConnection(){return window.location.protocol==="https:"}get quicklookButton(){return this._quicklookButton}_quicklookButton;get arButton(){return this._arButton}_arButton;get vrButton(){return this._vrButton}_vrButton;get sendToQuestButton(){return this._sendToQuestButton}_sendToQuestButton;get qrButton(){return Ki.getOrCreate().createQRCode()}createQuicklookButton(){if(this._quicklookButton)return this._quicklookButton;const e=document.createElement("button");this._quicklookButton=e,e.dataset.needle="quicklook-button";const t=exports.DeviceUtilities.supportsQuickLookAR();e.innerText="View in AR",e.prepend(ut("view_in_ar"));let i=!1,n=null;return e.addEventListener("click",()=>{n=cc(En),n||(i=!0,n=new En),i&&(n.objectToExport=U.Current.scene),n?(e.classList.add("this-mode-is-requested"),n.exportAndOpen().then(()=>{e.classList.remove("this-mode-is-requested")}).catch(o=>{e.classList.remove("this-mode-is-requested"),console.error(o)})):console.warn("No USDZExporter component found in the scene")}),this.hideElementDuringXRSession(e),e}createARButton(e){if(this._arButton)return this._arButton;const t="immersive-ar",i=document.createElement("button");return this._arButton=i,i.classList.add("webxr-button"),i.dataset.needle="webxr-ar-button",i.innerText="Enter AR",i.prepend(ut("view_in_ar")),i.title="Click to start an AR session",i.addEventListener("click",()=>q.start(t,e)),this.updateSessionSupported(i,t),this.listenToXRSessionState(i,t),this.hideElementDuringXRSession(i),this.isSecureConnection||(i.disabled=!0,i.title="WebXR requires a secure connection (HTTPS)"),exports.DeviceUtilities.isMozillaXR()||navigator.xr?.addEventListener("devicechange",()=>this.updateSessionSupported(i,t)),i}createVRButton(e){if(this._vrButton)return this._vrButton;const t="immersive-vr",i=document.createElement("button");return this._vrButton=i,i.classList.add("webxr-button"),i.dataset.needle="webxr-vr-button",i.innerText="Enter VR",i.prepend(ut("panorama_photosphere")),i.title="Click to start a VR session",i.addEventListener("click",()=>q.start(t,e)),this.updateSessionSupported(i,t),this.listenToXRSessionState(i,t),this.hideElementDuringXRSession(i),this.isSecureConnection||(i.disabled=!0,i.title="WebXR requires a secure connection (HTTPS)"),exports.DeviceUtilities.isMozillaXR()||navigator.xr?.addEventListener("devicechange",()=>this.updateSessionSupported(i,t)),i}createSendToQuestButton(){if(this._sendToQuestButton)return this._sendToQuestButton;const e="https://oculus.com/open_url/?url=",t=document.createElement("button");return this._sendToQuestButton=t,t.dataset.needle="webxr-sendtoquest-button",t.innerText="Open on Quest",t.prepend(ut("share_windows")),t.title="Click to send this page to the Oculus Browser on your Quest",t.addEventListener("click",()=>{const i=encodeURIComponent(window.location.href),n=e+i;window.open(n)==null&&Se("This page doesn't allow popups. Please paste "+n+" into your browser.")}),this.listenToXRSessionState(t),this.hideElementDuringXRSession(t),exports.DeviceUtilities.isMozillaXR()||navigator.xr?.addEventListener("devicechange",()=>{navigator.xr?.isSessionSupported("immersive-vr")?t.style.display="none":t.style.display=""}),t}createQRCode(){return Ki.getOrCreate().createQRCode()}updateSessionSupported(e,t){if(!("xr"in navigator)){e.style.display="none";return}q.isSessionSupported(t).then(i=>{e.style.display=i?"":"none",A()&&!i&&console.log('[WebXR] "'+t+'" is not supported on this device – make sure your server runs using HTTPS and you have a device connected that supports '+t)})}hideElementDuringXRSession(e){Ed(t=>{e["previous-display"]=e.style.display,e.style.display="none"}),Yp(t=>{e["previous-display"]!=null&&(e.style.display=e["previous-display"])})}listenToXRSessionState(e,t){t&&(q.onSessionRequestStart(i=>{i.mode===t?e.classList.add("this-mode-is-requested"):(e["was-disabled"]=e.disabled,e.disabled=!0,e.classList.add("other-mode-is-requested"))}),q.onSessionRequestEnd(i=>{e.classList.remove("this-mode-is-requested"),e.classList.remove("other-mode-is-requested"),e.disabled=e["was-disabled"]}))}}var pM=Object.defineProperty,mM=Object.getOwnPropertyDescriptor,ot=(s,e,t,i)=>{for(var n=i>1?void 0:i?mM(e,t):e,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&pM(e,t,n),n};const _d=w("debugspriterenderer"),gM=w("wireframe");class Xo{static cache={};static getOrCreateGeometry(e){if(e.__cached_geometry)return e.__cached_geometry;if(e.guid&&Xo.cache[e.guid])return _d&&console.log("Take cached geometry for sprite",e.guid),Xo.cache[e.guid];const t=new c.BufferGeometry;e.__cached_geometry=t;const i=new Float32Array(e.triangles.length*3),n=new Float32Array(e.triangles.length*2);for(let o=0;o<e.triangles.length;o+=1){const r=e.triangles[o];i[o*3]=-e.vertices[r].x,i[o*3+1]=e.vertices[r].y,i[o*3+2]=0;const a=e.uv[r];n[o*2]=a.x,n[o*2+1]=1-a.y}return t.setAttribute("position",new c.BufferAttribute(i,3)),t.setAttribute("uv",new c.BufferAttribute(n,2)),e.guid&&(this.cache[e.guid]=t),_d&&console.log("Built sprite geometry",e,t),t}}class yM{x;y}function zv(s){s&&(s.colorSpace!=c.SRGBColorSpace&&(s.colorSpace=c.SRGBColorSpace,s.needsUpdate=!0),s.minFilter==c.NearestFilter&&s.magFilter==c.NearestFilter&&(s.anisotropy=1,s.needsUpdate=!0))}let ps=class{constructor(e){e&&(this.texture=e,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}])}guid;texture;triangles;uv;vertices;__cached_geometry;get mesh(){return this._mesh||(this._mesh=new c.Mesh(Xo.getOrCreateGeometry(this),this.material)),this._mesh}_mesh;get material(){return this._material||(this.texture&&zv(this.texture),this._material=new c.MeshBasicMaterial({map:this.texture,color:16777215,side:c.DoubleSide,transparent:!0})),this._material}_material;getGeometry(){return Xo.getOrCreateGeometry(this)}};ot([f()],ps.prototype,"guid",2);ot([f(c.Texture)],ps.prototype,"texture",2);ot([er()],ps.prototype,"triangles",2);ot([er()],ps.prototype,"uv",2);ot([er()],ps.prototype,"vertices",2);const gf=Symbol("spriteOwner");class la{sprites;constructor(){this.sprites=[]}}ot([f(ps)],la.prototype,"sprites",2);const Jm=class bp{static create(){const e=new bp;return e.spriteSheet=new la,e}constructor(){}clone(){const e=new bp;return e.index=this.index,e.spriteSheet=this.spriteSheet,e}set sprite(e){e&&(this.spriteSheet?((this.index===null||this.index===void 0)&&(this.index=0),this.spriteSheet.sprites[this.index]=e):(this.spriteSheet=new la,this.spriteSheet.sprites=[e],this.index=0))}get sprite(){if(this.spriteSheet)return this.spriteSheet.sprites[this.index]}spriteSheet;index=0;update(e){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&&(zv(n),!i.__hasLoadedProgressive)){i.__hasLoadedProgressive=!0;const o=n;ne.NEEDLE_progressive.assignTextureLOD(n,0).then(r=>{r instanceof c.Texture&&(i.texture=r,e?.map===o&&(e.map=r,e.needsUpdate=!0))})}}};ot([f(la)],Jm.prototype,"spriteSheet",2);ot([f()],Jm.prototype,"index",2);let Yr=Jm;class Yt extends k{drawMode=0;size={x:1,y:1};color;sharedMaterial;transparent=!0;cutoutThreshold=0;castShadows=!1;renderOrder=0;toneMapped=!0;set texture(e){if(!this._spriteSheet)return;const t=this._spriteSheet.spriteSheet?.sprites[this.spriteIndex];t&&(t.texture=e,this.updateSprite())}addSprite(e,t=!1){if(this._spriteSheet||(this._spriteSheet=Yr.create()),!this._spriteSheet.spriteSheet)return-1;this._spriteSheet.spriteSheet?.sprites.push(e);const i=this._spriteSheet.spriteSheet?.sprites.length-1;return t&&(this.spriteIndex=i),i}get sprite(){return this._spriteSheet}set sprite(e){if(e!==this._spriteSheet)if(typeof e=="number"){const t=Math.floor(e);this.spriteIndex=t}else e instanceof ps?(this._spriteSheet||(this._spriteSheet=Yr.create()),this._spriteSheet.sprite!=e&&(this._spriteSheet.sprite=e),this.updateSprite()):e!=this._spriteSheet&&(this._spriteSheet=e,this.updateSprite())}set spriteIndex(e){this._spriteSheet&&(this._spriteSheet.index=e,this.updateSprite())}get spriteIndex(){return this._spriteSheet?.index??0}get spriteFrames(){return this._spriteSheet?.spriteSheet?.sprites.length??0}_spriteSheet;_currentSprite;awake(){this._currentSprite=void 0,this._spriteSheet?this._spriteSheet=this._spriteSheet.clone():this._spriteSheet=Yr.create(),_d&&console.log("Awake",this.name,this,this.sprite)}start(){this._currentSprite?this.gameObject&&this.gameObject.add(this._currentSprite):this.updateSprite()}updateSprite(e=!1){if(!this.__didAwake&&!e)return!1;const t=this._spriteSheet;if(!t?.spriteSheet?.sprites)return console.warn("SpriteRenderer has no data or spritesheet assigned..."),!1;const i=t.spriteSheet.sprites[this.spriteIndex];if(!i)return _d&&console.warn("Sprite not found",this.spriteIndex,t.spriteSheet.sprites),!1;if(this._currentSprite)this._currentSprite.geometry=Xo.getOrCreateGeometry(i),this._currentSprite.material.map=i.texture;else{const n=new c.MeshBasicMaterial({color:16777215,side:c.DoubleSide});if(gM&&(n.wireframe=!0),this.color&&(n.color||(n.color=new c.Color),n.color.copy(this.color),n.opacity=this.color.alpha),n.transparent=!0,n.toneMapped=this.toneMapped,n.depthWrite=!1,i.texture&&!n.wireframe){let o=i.texture;o[gf]!==void 0&&o[gf]!==this&&this.spriteFrames>1&&(o=i.texture=o.clone()),o[gf]=this,n.map=o}this.sharedMaterial=n,this._currentSprite=new c.Mesh(Xo.getOrCreateGeometry(i),n),this._currentSprite.renderOrder=Math.round(this.renderOrder),ne.NEEDLE_progressive.assignTextureLOD(n,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,t?.update(this.sharedMaterial),!0}}ot([f()],Yt.prototype,"drawMode",2);ot([f(yM)],Yt.prototype,"size",2);ot([f(Z)],Yt.prototype,"color",2);ot([f(c.Material)],Yt.prototype,"sharedMaterial",2);ot([f()],Yt.prototype,"transparent",2);ot([f()],Yt.prototype,"cutoutThreshold",2);ot([f()],Yt.prototype,"castShadows",2);ot([f()],Yt.prototype,"renderOrder",2);ot([f()],Yt.prototype,"toneMapped",2);ot([f(Yr)],Yt.prototype,"sprite",1);const g_=w("debugwebxr"),_M=new c.Matrix4().makeRotationY(Math.PI);class li extends k{static _eventListeners={};static onPlaced(e){const t="placed";return this._eventListeners[t]||(this._eventListeners[t]=[]),this._eventListeners[t].push(e),()=>{const i=this._eventListeners[t].indexOf(e);i>=0&&this._eventListeners[t].splice(i,1)}}static _hasPlaced=!1;static get hasPlaced(){return this._hasPlaced}get arScale(){return this._arScale}set arScale(e){this._arScale=Math.max(1e-6,e),this.onSetScale()}_arScale=1;invertForward=!1;customReticle;arTouchTransform=!0;autoPlace=!1;autoCenter=!1;useXRAnchor=!1;_isPlacing=!0;_startOffset=new c.Matrix4;_createdPlacementObject=null;_reparentedComponents=[];_placementScene=new c.Scene;_reticle=[];_hits=[];_placementStartTime=-1;_rigPlacementMatrix;_anchor=null;userInput;onEnable(){this.customReticle?.preload()}supportsXR(e){return e==="immersive-ar"}onEnterXR(e){g_&&console.log("ENTER WEBXR: SessionRoot start..."),this._anchor=null,li._hasPlaced=!1,this.gameObject.updateMatrixWorld(),this._startOffset.copy(this.gameObject.matrixWorld);const t=new c.Object3D;this._createdPlacementObject=t,t.name="AR Session Root",this._placementScene.name="AR Placement Scene",this._placementScene.children.length=0;for(let i=this.context.scene.children.length-1;i>=0;i--){const n=this.context.scene.children[i];this._placementScene.add(n)}if(this.context.scene.add(t),this.autoCenter){const i=Ht(this._placementScene.children),n=i.getCenter(new c.Vector3),o=i.getSize(new c.Vector3),r=new c.Matrix4;r.makeTranslation(n.x,n.y-o.y*.5,n.z),this._startOffset.multiply(r)}this._reparentedComponents.length=0,this._reparentedComponents.push({comp:this,originalObject:this.gameObject}),x.addComponent(t,this);for(const i of this._reticle)di(i);this._reticle.length=0,this._isPlacing=!0,this.context.input.addEventListener("pointerup",this.onPlaceScene,{queue:$t.Early})}onLeaveXR(){this.context.input.removeEventListener("pointerup",this.onPlaceScene,{queue:$t.Early}),this.onRevertSceneChanges(),this._anchor=null,li._hasPlaced=!1,this._rigPlacementMatrix=void 0}onUpdateXR(e){if(e.xr.isTrackingImages){for(const t of this._reticle)t.visible=!1;return}if(this._isPlacing){const t=e.xr.rig?.gameObject;t&&t.parent!==this.context.scene&&this.context.scene.add(t);let i=!1;if(e.xr.isPassThrough&&e.xr.controllers.length>0&&!this.autoPlace)for(const n of e.xr.controllers){const o=n.getHitTest();o&&(i=!0,this.updateReticleAndHits(e.xr,n.index,o,e.xr.rigScale))}if(!i){const n=e.xr.getHitTest();n&&this.updateReticleAndHits(e.xr,0,n,e.xr.rigScale)}}else{if(this._anchor&&e.xr.referenceSpace){const t=e.xr.frame.getPose(this._anchor.anchorSpace,e.xr.referenceSpace);if(t&&this.context.time.frame%20===0){const i=e.xr.convertSpace(t.transform),n=this._reticle[0];n&&(n.position.copy(i.position),n.quaternion.copy(i.quaternion),this.onApplyPose(n))}}if(this.arTouchTransform?(this.userInput||(this.userInput=new bd(this.context)),this.userInput?.enable()):this.userInput?.disable(),this.arTouchTransform&&this.userInput?.hasChanged){if(e.xr.rig){const t=e.xr.rig.gameObject;this.userInput.applyMatrixTo(t.matrix,!0),t.matrix.decompose(t.position,t.quaternion,t.scale),this.userInput.factor=t.scale.x}this.userInput.reset()}}}updateReticleAndHits(e,t,i,n){this._hits[t]=i.hit;let o=this._reticle[t];if(!o){if(this.customReticle)if(this.customReticle.asset)o=Wo(this.customReticle.asset);else{this.customReticle.loadAssetAsync();return}else o=new c.Mesh(new c.RingGeometry(.07,.09,32).rotateX(-Math.PI/2),new c.MeshBasicMaterial({side:c.DoubleSide,depthTest:!1,depthWrite:!1,transparent:!0,opacity:1,color:15658734})),o.name="AR Placement Reticle";if(g_){const r=new c.AxesHelper(1);r.position.y+=.01,o.add(r)}this._reticle[t]=o,o.matrixAutoUpdate=!1,o.visible=!1}if(o.lastPos=o.lastPos||i.position.clone(),o.lastQuat=o.lastQuat||i.quaternion.clone(),o.position.copy(o.lastPos.lerp(i.position,this.context.time.deltaTime/.1)),o.lastPos.copy(o.position),o.quaternion.copy(o.lastQuat.slerp(i.quaternion,this.context.time.deltaTime/.05)),o.lastQuat.copy(o.quaternion),o.scale.set(n,n,n),this.customReticle&&this.applyViewBasedTransform(o),o.updateMatrix(),o.visible=!0,o.parent!==this.context.scene&&this.context.scene.add(o),this._placementStartTime<0&&(this._placementStartTime=this.context.time.realtimeSinceStartup),this.autoPlace)if(this.upVec.set(0,1,0).applyQuaternion(o.quaternion),this.upVec.dot(V(0,1,0))>.9){let a=o["autoplace:timer"]||0;a>=1?(o.visible=!1,this.onPlaceScene(null)):(a+=this.context.time.deltaTime,o["autoplace:timer"]=a)}else o["autoplace:timer"]=0}onPlaceScene=e=>{if(this._isPlacing==!1||e?.used)return;let t=this._reticle[0];if(!t){console.warn("No reticle to place...");return}if(!t.visible&&!this.autoPlace){console.warn("Reticle is not visible (can not place)");return}if(q.active?.isTrackingImages){console.warn("Scene Placement is disabled while images are being tracked");return}let i=this._hits[0];if(e&&e.origin instanceof Kp){const n=this._reticle[e.origin.index];n&&(t=n,i=this._hits[e.origin.index])}if(e&&(e.stopImmediatePropagation(),e.stopPropagation(),e.use()),this._isPlacing=!1,this.context.input.removeEventListener("pointerup",this.onPlaceScene),this.onRevertSceneChanges(),t.position.copy(t.lastPos),t.quaternion.copy(t.lastQuat),this.onApplyPose(t),li._hasPlaced=!0,this.useXRAnchor&&this.onCreateAnchor(q.active,i),this.context.xr)for(const n of this.context.xr.controllers)n.cancelHitTestSource()};onSetScale(){if(!li._hasPlaced)return;const e=q.active?.rig?.gameObject;if(e){const t=q.active?.rigScale||1,i=1/this._arScale*t,n=new c.Matrix4().makeScale(i,i,i).invert();e.matrix.premultiply(n),e.matrix.decompose(e.position,e.quaternion,e.scale)}}onRevertSceneChanges(){for(const e of this._reticle)e&&(e.visible=!1,e?.removeFromParent());this._reticle.length=0;for(let e=this._placementScene.children.length-1;e>=0;e--){const t=this._placementScene.children[e];this.context.scene.add(t)}this._createdPlacementObject?.removeFromParent();for(const e of this._reparentedComponents)x.addComponent(e.originalObject,e.comp)}async onCreateAnchor(e,t){if(t.createAnchor===void 0){console.warn("Hit does not support creating an anchor",t),A()&&ce("Hit does not support creating an anchor");return}else{const i=await t.createAnchor(e.viewerPose.transform);e.running&&i&&(this._anchor=i)}}upVec=new c.Vector3(0,1,0);lookPoint=new c.Vector3;worldUpVec=new c.Vector3(0,1,0);applyViewBasedTransform(e){const t=this.context.mainCamera,i=e,n=t.worldPosition,o=i.worldPosition;this.upVec.set(0,1,0).applyQuaternion(e.quaternion);const r=t.worldPosition;r&&e.position.clone().sub(r).angleTo(this.upVec)<Math.PI/2&&this.upVec.negate();const a=this.upVec.angleTo(this.worldUpVec)*180/Math.PI,l=30;a>l&&a<180-l||a<-l&&a>-180+l?(this.lookPoint.copy(e.position).add(this.upVec),this.lookPoint.y=e.position.y,e.lookAt(this.lookPoint)):(n.y=o.y,e.lookAt(n))}onApplyPose(e){const t=q.active?.rig?.gameObject;if(!t){console.warn("No rig object to place");return}const i=t.parent||this.context.scene;this._rigPlacementMatrix?this._rigPlacementMatrix?.decompose(t.position,t.quaternion,t.scale):this._rigPlacementMatrix=t.matrix.clone(),this.applyViewBasedTransform(e),e.updateMatrix(),this.context.scene.add(e),e.attach(t),e.removeFromParent(),t.scale.set(this.arScale,this.arScale,this.arScale),t.position.multiplyScalar(this.arScale),t.updateMatrix(),this.invertForward&&t.matrix.premultiply(_M),t.matrix.premultiply(this._startOffset),t.matrix.decompose(t.position,t.quaternion,t.scale),i.add(t)}}class bd{static up=new c.Vector3(0,1,0);static zero=new c.Vector3(0,0,0);static one=new c.Vector3(1,1,1);oneFingerDrag=!0;twoFingerRotate=!0;twoFingerScale=!0;factor=1;context;offset;plane;_scale=1;_hasChanged=!1;get scale(){return this._scale}constructor(e){this.context=e,this.offset=new c.Matrix4,this.plane=new c.Plane,this.plane.setFromNormalAndCoplanarPoint(bd.up,bd.zero)}_enabled=!1;reset(){this._scale=1,this.offset.identity(),this._hasChanged=!0}get hasChanged(){return this._hasChanged}applyMatrixTo(e,t){this._hasChanged=!1,t?(this.offset.invert(),e.premultiply(this.offset)):e.multiply(this.offset)}currentlyUsedPointerIds=new Set;currentlyUnusedPointerIds=new Set;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:$t.Early}),this.context.input.addEventListener("pointerdown",this.onPointerDownLate,{queue:$t.Late}),this.context.input.addEventListener("pointerup",this.onPointerUpEarly,{queue:$t.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:$t.Early}),this.context.input.removeEventListener("pointerdown",this.onPointerDownLate,{queue:$t.Late}),this.context.input.removeEventListener("pointerup",this.onPointerUpEarly,{queue:$t.Early}),window.removeEventListener("touchstart",this.touchStart),window.removeEventListener("touchmove",this.touchMove),window.removeEventListener("touchend",this.touchEnd))}onPointerDownEarly=e=>{this.isActive&&e.stopPropagation()};onPointerDownLate=e=>{e.used?this.currentlyUsedPointerIds.add(e.pointerId):this.currentlyUsedPointerIds.size<=0&&this.currentlyUnusedPointerIds.add(e.pointerId)};onPointerUpEarly=e=>{this.currentlyUsedPointerIds.delete(e.pointerId),this.currentlyUnusedPointerIds.delete(e.pointerId)};prev=new Map;_didMultitouch=!1;touchStart=e=>{if(!e.defaultPrevented)for(let t=0;t<e.changedTouches.length;t++){const i=e.changedTouches[t],n=exports.DeviceUtilities.isAndroidDevice()&&i.clientY<window.innerHeight*.1;this.prev.has(i.identifier)||this.prev.set(i.identifier,{ignore:n,x:0,z:0,screenx:0,screeny:0});const o=this.prev.get(i.identifier);if(o){const r=this.getPositionOnPlane(i.clientX,i.clientY);o.x=r.x,o.z=r.z,o.screenx=i.clientX,o.screeny=i.clientY}}};touchEnd=e=>{e.touches.length<=0&&(this._didMultitouch=!1);for(let t=0;t<e.changedTouches.length;t++){const i=e.changedTouches[t];this.prev.delete(i.identifier)}};touchMove=e=>{if(!e.defaultPrevented&&this.isActive){if(e.touches.length===1){if(this._didMultitouch)return;const t=e.touches[0],i=this.prev.get(t.identifier);if(!i||i.ignore)return;const n=this.getPositionOnPlane(t.clientX,t.clientY),o=n.x-i.x,r=n.z-i.z;if(o===0&&r===0)return;this.oneFingerDrag&&this.addMovement(o,r),i.x=n.x,i.z=n.z,i.screenx=t.clientX,i.screeny=t.clientY;return}else if(e.touches.length===2){this._didMultitouch=!0;const t=e.touches[0],i=e.touches[1],n=this.prev.get(t.identifier),o=this.prev.get(i.identifier);if(!n||!o)return;if(this.twoFingerRotate){const r=Math.atan2(t.clientY-i.clientY,t.clientX-i.clientX),a=Math.atan2(n.screeny-o.screeny,n.screenx-o.screenx),l=r-a;Math.abs(l)>.001&&this.addRotation(l)}if(this.twoFingerScale){const r=t.clientX-i.clientX,a=t.clientY-i.clientY,l=Math.sqrt(r*r+a*a),h=n.screenx-o.screenx,d=n.screeny-o.screeny,u=Math.sqrt(h*h+d*d),p=l-u;Math.abs(p)>2&&this.addScale(p)}n.screenx=t.clientX,n.screeny=t.clientY,o.screenx=i.clientX,o.screeny=i.clientY}}};_raycaster=new c.Raycaster;_intersection=new c.Vector3;_screenPos=new c.Vector3;getPositionOnPlane(e,t){const i=this.context.mainCamera;return this._screenPos.x=e/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(e,t){e/=this._scale,t/=this._scale,e*=this.factor,t*=this.factor,this.offset.elements[12]+=e,this.offset.elements[14]+=t,(e!==0||t!==0)&&(this._hasChanged=!0)}_tempMatrix=new c.Matrix4;addScale(e){e/=window.innerWidth,e*=-1,this._scale*=1+e,this._tempMatrix.makeScale(1-e,1-e,1-e),this.offset.premultiply(this._tempMatrix),e!==0&&(this._hasChanged=!0)}addRotation(e){e*=-1,this._tempMatrix.makeRotationY(e),this.offset.premultiply(this._tempMatrix),e!==0&&(this._hasChanged=!0)}}const Fs=w("debugautosync"),yf=Symbol("syncerId");class bM{_syncers={};getOrCreateSyncer(e){if(!e.guid)return null;if(this._syncers[e.guid])return this._syncers[e.guid];const t=new vM(e);return t[yf]=e.guid,this._syncers[t[yf]]=t,t}removeSyncer(e){delete this._syncers[e[yf]]}}const eg=new bM;class vM{comp;constructor(e){this.comp=e}hasChanges=!1;changedProperties={};get networkingKey(){return this.comp.guid}_isReceiving=!1;_isInit=!1;init(e){if(this._isInit)return;this._isInit=!0,this.comp=e,this.comp.context.post_render_callbacks.push(this.onHandleSending),this.comp.context.connection.beginListen(this.networkingKey,this.onHandleReceiving);const t=this.comp.context.connection.tryGetState(this.comp.guid);t&&this.onHandleReceiving(t)}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(e,t){this._isReceiving||(Fs&&console.log("Property changed: "+e,t),this.hasChanges=!0,this.changedProperties[e]=t)}onHandleSending=()=>{if(!this.hasChanges)return;this.hasChanges=!1;const e=this.comp.context.connection;if(!e||!e.isConnected||!e.isInRoom){for(const t in this.changedProperties)delete this.changedProperties[t];return}for(const t in this.changedProperties){const i=this.changedProperties[t];Fs&&console.log("SEND",this.comp.guid,this.networkingKey),e.send(this.networkingKey,{guid:this.comp.guid,property:t,data:i},Yi.Queued),delete this.changedProperties[t]}};onHandleReceiving=e=>{if(Fs&&console.log("SYNCFIELD RECEIVE",this.comp.name,this.comp.guid,e),!!this._isInit&&this.comp&&e.guid===this.comp.guid)try{this._isReceiving=!0,this.comp[e.property]=e.data}catch(t){console.error(t)}finally{this._isReceiving=!1}}}function wM(s,e){let t=e!==s;return!t&&s&&e&&(Array.isArray(s)&&Array.isArray(e)||typeof s=="object"&&typeof e=="object")&&(t=!0),t}const El=Symbol("AutoSyncHandler");function xM(s){if(s[El])return s[El];const e=eg.getOrCreateSyncer(s);return e?.init(s),s[El]=e,e}function SM(s){const e=s[El];e&&(eg.removeSyncer(e),e.destroy(),delete s[El])}const tg=function(s=null){return function(e,t){let i="";typeof t=="string"?i=t:i=t.name;let n=null,o;typeof s=="string"?o=e[s]:typeof s=="function"&&(o=s),o==null&&(A()||Fs)&&s!=null&&console.warn('syncField: no callback function found for property "'+i+'"','"'+s+'"');const r=e,a=r.__internalAwake;if(typeof a!="function"){(Fs||A())&&console.error('@syncField can currently only used on Needle Engine Components, custom object of type "'+e?.constructor?.name+'" is not supported',e);return}Fs&&console.log(i);const l=Symbol(i);r.__internalAwake=function(){if(this[l]!==void 0)return;if(this[l]=this[i],n=eg.getOrCreateSyncer(this),Object.getOwnPropertyDescriptor(this,i)?.set===void 0){let u=!1;Object.defineProperty(this,i,{set:function(p){const m=this[l];if(this[l]=p,u){(A()||Fs)&&console.warn("Recursive call detected",i);return}u=!0;try{const y=wM(p,m);Fs&&console.log("SyncField assignment",i,"changed?",y,p,o),y&&o?.call(this,p,m)!==!1&&xM(this)?.notifyChanged(i,p)}finally{u=!1}},get:function(){return this[l]},configurable:!0,enumerable:!0})}n?.init(this),a.call(this)};const h=r.__internalDestroy;r.__internalDestroy=function(){SM(this),h.call(this)}}};var CM=Object.defineProperty,tu=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&CM(e,t,n),n};const Lt=w("debugplayersync"),iu=class Nv extends k{static async setupFrom(e,t){const i=Y.getOrCreateFromUrl(e);if(!i.asset){const r=await i.loadAssetAsync();r&&x.getOrAddComponent(r,Zi)}const n=new Nv;n._internalInit(t),n.asset=i;const o=new c.Object3D;return o.guid=e,x.addComponent(o,n),n}autoSync=!0;asset;onPlayerSpawned;_localInstance;awake(){this.watchTabVisible(),this.onPlayerSpawned||(this.onPlayerSpawned=new de)}onEnable(){this.context.connection.beginListen(Q.RoomStateSent,this.onJoinedRoom),this.context.connection.beginListen(Q.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(Q.LeftRoom,this.destroyInstance),this.context.connection.isInRoom&&this.onJoinedRoom()}onDisable(){this.context.connection.stopListen(Q.RoomStateSent,this.onJoinedRoom),this.context.connection.stopListen(Q.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(Q.LeftRoom,this.destroyInstance)}onJoinedRoom=()=>{Lt&&console.log("PlayerSync.joinedRoom. autoSync is set to "+this.autoSync),this.autoSync&&this.getInstance()};async getInstance(){if(this._localInstance)return this._localInstance;if(Lt&&console.log("PlayerSync.createInstance",this.asset?.url),!this.asset?.asset&&!this.asset?.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=this.asset?.instantiateSynced({parent:this.gameObject,deleteOnDisconnect:!0},!0);const e=await this._localInstance;if(e){const t=x.getComponentsInChildren(e,Zi);if(Lt&&console.log(`PlayerSync.createInstance: found ${t?.length} PlayerState components. Owner: ${this.context.connection.connectionId}`),t?.length){for(const i of t)i.owner=this.context.connection.connectionId;this.onPlayerSpawned?.invoke(e)}else this._localInstance=void 0,console.error("<strong>Failed finding PlayerState on "+this.asset?.url+"</strong>: please make sure the asset has a PlayerState component!"),x.destroySynced(e)}else this._localInstance=void 0,console.warn("PlayerSync: failed instantiating asset!");return this._localInstance}destroyInstance=()=>{this._localInstance?.then(e=>{Lt&&console.log("PlayerSync.destroyInstance",e),sc(e,this.context.connection,!0,{saveInRoom:!1})}),this._localInstance=void 0};watchTabVisible(){window.addEventListener("visibilitychange",e=>{if(document.visibilityState==="visible")for(let t=Zi.all.length-1;t>=0;t--){const i=Zi.all[t];(!i.owner||!this.context.connection.userIsInRoom(i.owner))&&i.doDestroy()}})}};tu([f()],iu.prototype,"autoSync");tu([f(Y)],iu.prototype,"asset");tu([f(de)],iu.prototype,"onPlayerSpawned");let ig=iu;var Vv=(s=>(s.OwnerChanged="ownerChanged",s))(Vv||{});const vp=class ht extends k{static _all=[];static get all(){return ht._all}static _local=[];static get local(){return ht._local}static getFor(e){if(e instanceof c.Object3D)return x.getComponentInParent(e,ht);if(e instanceof k)return x.getComponentInParent(e.gameObject,ht)}static isLocalPlayer(e){return ht.getFor(e)?.isLocalPlayer??!1}static _callbacks={};static addEventListener(e,t){return this._callbacks[e]||(this._callbacks[e]=[]),this._callbacks[e].push(t),t}static removeEventListener(e,t){if(!this._callbacks[e])return;const i=this._callbacks[e].indexOf(t);i>=0&&this._callbacks[e].splice(i,1)}static dispatchEvent(e,t){if(this._callbacks[e])for(const i of this._callbacks[e])i(t)}onOwnerChangeEvent=new de;onFirstOwnerChangeEvent=new de;hasOwner=!1;owner;dontDestroy=!1;get isLocalPlayer(){return this.owner===this.context.connection.connectionId}onOwnerChange(e,t){Lt&&console.log(`PlayerSync.onOwnerChange: ${t} → ${e} (me: ${this.context.connection.connectionId})`);const i=ht._local.indexOf(this);i>=0&&ht._local.splice(i,1);const n={playerState:this,oldValue:t,newValue:e};if(this.hasOwner||(this.hasOwner=!0,this.onFirstOwnerChangeEvent?.invoke(n)),this.onOwnerChangeEvent?.invoke(n),this.owner===this.context.connection.connectionId){ht._local.push(this);const r=new CustomEvent("local-owner-changed",{detail:n});this.dispatchEvent(r)}const o=new CustomEvent("owner-changed",{detail:n});this.dispatchEvent(o),ht.dispatchEvent("ownerChanged",o)}awake(){ht.all.push(this),Lt&&console.log("Registered new PlayerState",this.guid,ht.all.length-1,ht.all),this.context.connection.beginListen(Q.UserLeftRoom,this.onUserLeftRoom)}async start(){Lt&&console.log("PLAYERSTATE.START, owner: "+this.owner,this.context.connection.usersInRoom([])),this.owner?(this.context.connection.isInRoom||await An(300),this.context.connection.userIsInRoom(this.owner)==!1&&(Lt&&console.log(`PlayerSync.start → doDestroy "${this.name}" because user "${this.owner}" is not in room anymore...`,"Currently in room:",...this.context.connection.usersInRoom()),this.doDestroy())):this.owner||(Lt&&console.warn("PlayerState.start → owner is undefined!",this.name),setTimeout(()=>{!this.destroyed&&!this.owner?this.dontDestroy?Lt&&console.warn("PlayerState.start → owner is still undefined but dontDestroy is set to true",this.name):(Lt&&console.warn(`PlayerState.start → owner is still undefined: destroying "${this.name}" instance now`),this.doDestroy()):Lt&&console.log("PlayerState.start → owner is assigned",this.owner)},2e3))}doDestroy(){Lt&&console.log("PlayerSync.doDestroy → syncDestroy",this.name),sc(this.gameObject,this.context.connection,!0,{saveInRoom:!1})}onDestroy(){if(Lt&&console.warn("PlayerState.onDestroy",this.owner),this.context.connection.stopListen(Q.UserLeftRoom,this.onUserLeftRoom),ht.all.splice(ht.all.indexOf(this),1),this.isLocalPlayer){const e=ht._local.indexOf(this);e>=0&&ht._local.splice(e,1)}}onUserLeftRoom=e=>{if(e.userId===this.owner){Lt&&console.log("PLAYERSYNC LEFT",this.owner),this.doDestroy();return}}};tu([tg(vp.prototype.onOwnerChange)],vp.prototype,"owner");let Zi=vp;var PM=Object.defineProperty,wa=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&PM(e,t,n),n};class jn extends k{position="bottom";showNeedleLogo=!1;showSpatialMenu;createFullscreenButton;createMuteButton;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&&(exports.DeviceUtilities.isMobileDevice()||this.context.menu.showQRCodeButton(!0))}}wa([f()],jn.prototype,"position");wa([f()],jn.prototype,"showNeedleLogo");wa([f()],jn.prototype,"showSpatialMenu");wa([f()],jn.prototype,"createFullscreenButton");wa([f()],jn.prototype,"createMuteButton");wa([f()],jn.prototype,"createQRCodeButton");var MM=Object.defineProperty,ng=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&MM(e,t,n),n};const $a=w("debugwebxr"),y_=new c.Quaternion().setFromAxisAngle(new c.Vector3(0,1,0),Math.PI);class Xs extends k{head;leftHand;rightHand;_leftHandMeshes;_rightHandMeshes;_syncTransforms;async onEnterXR(e){if(!this.activeAndEnabled)return;$a&&console.warn("AVATAR ENTER XR",this.guid,this.sourceId,this,this.activeAndEnabled),this._syncTransforms&&(this._syncTransforms.length=0),await this.prepareAvatar();const t=Zi.getFor(this);if(t?.owner){const i=this.gameObject.addComponent(xe);i.avatar=this.gameObject,i.connectionId=t.owner}else this.context.connection.isConnected?console.error("No player state found for avatar",this):t&&!this.context.connection.isConnected&&(t.dontDestroy=!0)}onLeaveXR(e){const t=this.gameObject.getComponent(xe);t&&t.destroy()}onUpdateXR(e){if(!this.activeAndEnabled)return;const t=Zi.isLocalPlayer(this);if(!t)return;const i=e.xr;if(i.rig&&i.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),i.rig.gameObject.add(this.gameObject)),this._syncTransforms&&t)for(const l of this._syncTransforms)l.fastMode=!0,l.isOwned()||l.requestOwnership();if(this.head&&this.context.mainCamera){const l=this.head.asset;if(l.position.copy(this.context.mainCamera.position),l.position.x*=-1,l.position.z*=-1,l.quaternion.copy(this.context.mainCamera.quaternion),l.quaternion.x*=-1,this.context.time.frameCount%10===0&&this.head.asset){const h=x.getComponentsInChildren(this.head.asset,Ei);for(const d of h)d.enabled=!1,d.gameObject.visible=!1}}const n=e.xr.leftController,o=this.leftHand?.asset;n&&o?(o.position.copy(n.gripPosition),o.quaternion.copy(n.gripQuaternion),o.quaternion.multiply(y_),o.visible=n.isTracking,this.updateHandVisibility(n,o,this._leftHandMeshes)):o&&o.visible&&(o.visible=!1);const r=e.xr.rightController,a=this.rightHand?.asset;r&&a?(a.position.copy(r.gripPosition),a.quaternion.copy(r.gripQuaternion),a.quaternion.multiply(y_),a.visible=r.isTracking,this.updateHandVisibility(r,a,this._rightHandMeshes)):a&&a.visible&&(a.visible=!1)}onBeforeRender(){this.context.xr&&this.context.time.frame%10===0&&this.updateRemoteAvatarVisibility()}updateHandVisibility(e,t,i){if(i){const n=e.model&&e.model.visible&&e.model!==t;i.forEach(o=>{Jn(o,!n)})}}updateRemoteAvatarVisibility(){if(this.context.connection.isConnected){const e=Zi.getFor(this);if(e&&e.isLocalPlayer==!1){const t=q.getXRSync(this.context);if(t&&t.hasState(e.owner)){this.tryFindAvatarObjectsIfMissing();const i=this.leftHand?.asset;i&&(i.visible=t?.isTracking(e.owner,"left")??!1);const n=this.rightHand?.asset;n&&(n.visible=t?.isTracking(e.owner,"right")??!1)}if(this.head?.asset){const i=x.getComponentsInChildren(this.head.asset,Ei);for(const n of i)n.enabled=!1,n.gameObject.visible=!0}}}}tryFindAvatarObjectsIfMissing(){if(!this.head||!this.leftHand||!this.rightHand){const e={head:this.head,leftHand:this.leftHand,rightHand:this.rightHand};Ub.tryFindAvatarObjects(this.gameObject,this.sourceId||"",e),e.head&&(this.head=e.head),e.leftHand&&(this.leftHand=e.leftHand),e.rightHand&&(this.rightHand=e.rightHand)}}async prepareAvatar(){if(this.tryFindAvatarObjectsIfMissing(),this.head)this.head instanceof c.Object3D&&(this.head=new Y("",this.sourceId,this.head));else{const e=new c.Object3D;e.name="Head";const t=Ko.createPrimitive(No.Cube);e.add(t),this.gameObject.add(e),this.head=new Y("",this.sourceId,e),$a&&console.log("Create head",e)}if(this.rightHand)this.rightHand instanceof c.Object3D&&(this.rightHand=new Y("",this.sourceId,this.rightHand));else{const e=new c.Object3D;e.name="Right Hand",this.gameObject.add(e),this.rightHand=new Y("",this.sourceId,e),$a&&console.log("Create right hand",e)}if(this.leftHand)this.leftHand instanceof c.Object3D&&(this.leftHand=new Y("",this.sourceId,this.leftHand));else{const e=new c.Object3D;e.name="Left Hand",this.gameObject.add(e),this.leftHand=new Y("",this.sourceId,e),$a&&console.log("Create left hand",e)}await this.loadAvatarObjects(this.head,this.leftHand,this.rightHand),this._leftHandMeshes=[],this.leftHand.asset?.traverse(e=>{e?.isMesh&&this._leftHandMeshes.push(e)}),this._rightHandMeshes=[],this.rightHand.asset?.traverse(e=>{e?.isMesh&&this._rightHandMeshes.push(e)}),Zi.isLocalPlayer(this.gameObject)&&(this._syncTransforms=x.getComponentsInChildren(this.gameObject,Ln))}async loadAvatarObjects(e,t,i){const n=e.loadAssetAsync(),o=t.loadAssetAsync(),r=i.loadAssetAsync(),a=new Array;n&&a.push(n),o&&a.push(o),r&&a.push(r);const l=await Bp(a);$a&&console.log("Avatar loaded results:",l)}}ng([f(Y)],Xs.prototype,"head");ng([f(Y)],Xs.prototype,"leftHand");ng([f(Y)],Xs.prototype,"rightHand");var OM=Object.defineProperty,nu=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&OM(e,t,n),n};const $n=w("debugwebxr"),Os=new Array;class ls extends k{createControllerModel=!0;createHandModel=!0;customLeftHand;customRightHand;static factory=new G.XRControllerModelFactory;supportsXR(e){return e==="immersive-vr"||e==="immersive-ar"}_models=new Array;async onXRControllerAdded(e){if(!(e.xr.isVR||e.xr.isPassThrough))return;const{controller:i}=e;if($n&&console.warn("Add Controller Model for",i.side,i.index),this.createControllerModel||this.createHandModel){if(i.hand){if(this.createHandModel){const n=await this.loadHandModel(this,i);if(!n||!i.connected||!i.isHand){n?.handObject&&Tr(n.handObject,!1),n?.handObject?.destroy();return}this._models.push({controller:i,model:n.handObject,handmesh:n.handmesh}),this._models.sort((o,r)=>o.controller.index-r.controller.index),this.scene.add(n.handObject),i.model=n.handObject}}else if(this.createControllerModel){const n=await i.getModelUrl();if(n){const o=await this.loadModel(i,n);if(!o||!i.connected||i.isHand)return;this._models.push({controller:i,model:o}),this._models.sort((r,a)=>r.controller.index-a.controller.index),this.scene.add(o),o.traverse(r=>{r.layers.set(2),r.matrixAutoUpdate=!1,r.updateMatrix()}),i.model=o}else i.targetRayMode!=="transient-pointer"&&console.warn("XRControllerModel: no model found for "+i.side)}}}onXRControllerRemoved(e){console.debug("XR Controller Removed",e.controller.side,e.controller.index);const t=this._models.findIndex(n=>n.controller===e.controller),i=this._models[t];i&&(this._models.splice(t,1),i.model&&(Tr(i.model,!1),i.model.destroy(),i.model=void 0))}onBeforeXR(e,t){this.createHandModel&&(this.customLeftHand||this.customRightHand)&&(t.optionalFeatures=t.optionalFeatures||[],t.optionalFeatures.includes("hand-tracking")||t.optionalFeatures.push("hand-tracking"))}onLeaveXR(e){for(const t of this._models)t&&(t.model&&(Tr(t.model,!1),t.model.destroy(),t.model=void 0),t.controller.model===t.model&&(t.controller.model=null));this._models.length=0}onBeforeRender(){if(q.active&&($n&&(Os[0]=Date.now()),this.updateRendering(q.active),$n)){const e=Date.now()-Os[0];Os.push(e),Os.length>=30&&(Os[0]=0,Os.reduce((t,i)=>t+i,0)/Os.length,Os.length=0)}}updateRendering(e){for(let t=0;t<this._models.length;t++){const i=this._models[t];if(!i)continue;const n=i.controller;if(!n.connected){$n&&console.warn("XRControllerModel.onUpdateXR: controller is not connected anymore",n.side,n.hand);continue}if(i.model&&!i.handmesh)i.model.matrixAutoUpdate=!1,i.model.matrix.copy(n.gripMatrix),i.model.visible=n.isTracking,e.rig?.gameObject.add(i.model);else if(n.inputSource.hand&&i.handmesh){const o=e.referenceSpace,r=this.context.renderer.xr.getHand(n.index);if(o&&e.frame.getJointPose){for(const a of n.inputSource.hand.values()){const l=r.joints[a.jointName];if(l){const h=n.getHandJointPose(a);if(h){const d=h.transform.position,u=h.transform.orientation;l.position.copy(d),l.quaternion.copy(u),l.matrixAutoUpdate=!1}l.visible=h!=null}}i.model&&(i.model.visible=n.isTracking,i.model.visible&&i.model.parent!==e.rig?.gameObject&&e.rig?.gameObject.add(i.model)),i.model?.visible&&(i.handmesh?.updateMesh(),i.model.matrixAutoUpdate=!1,i.model.matrix.identity(),i.model.applyMatrix4(Wr))}}}}async loadModel(e,t){if(!e.connected)return console.warn("XRControllerModel.onXRControllerAdded: controller is not connected anymore",e.side),null;const n=await Y.getOrCreate("",t).instantiate();return Tr(n),q.active?.isPassThrough&&n.traverseVisible(o=>{this.makeOccluder(o)}),n}async loadHandModel(e,t){const i=this.context,n=i.renderer.xr.getHand(t.index);n||($n?j.DrawLabel(t.rayWorldPosition,"No hand found for index "+t.index,.05,5):console.warn("No hand found for index "+t.index));const o=new G.GLTFLoader;_m(o,i),await gd(o,i,this.sourceId??"");const r=Um(o);let a="";const l=t.side==="left"?this.customLeftHand:this.customRightHand;l?(a=l.url.split(".").slice(0,-1).join("."),o.setPath("")):(a=t.inputSource.handedness==="left"?"left":"right",o.setPath("https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles/generic-hand/"));const h=new c.Object3D;Tr(h);const d=new G.XRHandMeshModel(h,n,o.path,a,o,u=>{const p=r?.gltf;p?.scene.children?.length===0&&(p.scene.children[0]=u),r?.gltf&&en().createBuiltinComponents(e.context,e.sourceId||a,r.gltf,null,r),u.traverse(m=>{m.layers.set(2),q.active?.isPassThrough&&!l&&this.makeOccluder(m),m instanceof c.Mesh&&ne.NEEDLE_progressive.assignMeshLOD(m,0)}),t.connected||($n&&j.DrawLabel(t.rayWorldPosition,"Hand is loaded but not connected anymore",.05,5),u.removeFromParent())});if($n&&h.add(new c.AxesHelper(.5)),t.inputSource.hand){$n&&console.log(t.inputSource.hand);for(const u of t.inputSource.hand.values())if(n.joints[u.jointName]===void 0){const p=new c.Group;p.matrixAutoUpdate=!1,p.visible=!0,n.joints[u.jointName]=p,n.add(p)}}else $n&&j.DrawLabel(t.rayWorldPosition,"No inputSource.hand found for index "+t.index,.05,5);return{handObject:h,handmesh:d}}makeOccluder(e){if(e instanceof c.Mesh){let t=e.material;t instanceof c.Material&&(t=e.material=t.clone(),t.depthWrite=!0,t.depthTest=!0,t.colorWrite=!1,e.receiveShadow=!1,e.renderOrder=-100)}}}nu([f()],ls.prototype,"createControllerModel");nu([f()],ls.prototype,"createHandModel");nu([f(Y)],ls.prototype,"customLeftHand");nu([f(Y)],ls.prototype,"customRightHand");class su extends k{}var kM=Object.defineProperty,so=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&kM(e,t,n),n};const _f=w("debugwebxr");class pi extends k{movementSpeed=1.5;rotationStep=30;useTeleport=!0;usePinchToTeleport=!0;useTeleportTarget=!1;useTeleportFade=!1;showRays=!0;showHits=!0;isXRMovementHandler=!0;xrSessionMode="immersive-vr";_didApplyRotation=!1;_didTeleport=!1;onUpdateXR(e){const t=e.xr.rig;if(!t?.gameObject||e.xr.isPassThrough)return;const i=e.xr.leftController,n=e.xr.rightController;i&&this.onHandleMovement(i,t.gameObject),n&&(this.onHandleRotation(n,t.gameObject),this.useTeleport&&this.onHandleTeleport(n,t.gameObject))}onLeaveXR(e){for(const t of this._lines)t.removeFromParent();for(const t of this._hitDiscs)t?.removeFromParent()}onBeforeRender(){this.context.xr?.running&&(this.showRays&&this.renderRays(this.context.xr),this.showHits&&this.renderHits(this.context.xr))}onHandleMovement(e,t){const i=e.getStick("xr-standard-thumbstick");if(i.x!=0||i.y!=0){const n=V(i.x,0,i.y);n.multiplyScalar(this.context.time.deltaTimeUnscaled*this.movementSpeed);const o=Ae(t);n.multiplyScalar(o.x),n.applyQuaternion(e.xr.poseOrientation),n.y=0,n.applyQuaternion(t.worldQuaternion),t.position.add(n),t.updateWorldMatrix(!1,!1);for(const r of t.children)r.updateWorldMatrix(!1,!1)}}onHandleRotation(e,t){if(e._isMxInk)return;const n=e.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=X(this.context.mainCamera).clone();t.rotateY(o*I.toRadians(this.rotationStep));const l=X(this.context.mainCamera).clone().sub(r);l.y=0,t.position.sub(l)}}_teleportBuffer=new Array;onHandleTeleport(e,t){let i=0;if(e.hand&&this.usePinchToTeleport&&e.isTeleportGesture){const n=e.getPointerId("primary");if(n!=null&&this.context.input.getIsPointerIdInUse(n))return;const o=e.getGesture("pinch");o&&(i=o.value)}else i=e.getStick("xr-standard-thumbstick")?.y;if(this._didTeleport)i>=0&&i<.4?this._didTeleport=!1:i<0&&i>-.4&&(this._didTeleport=!1);else if(i>.8){this._didTeleport=!0;const n=this.context.physics.raycastFromRay(e.ray)[0];if(n&&n.object instanceof G.GroundedSkybox){const r=n.normal?.dot(V(0,1,0));if(r!==void 0&&r<.4)return}let o=n?.point;if(!o&&!this.useTeleportTarget){this._plane||(this._plane=new c.Plane(new c.Vector3(0,1,0),0));const r=t.worldPosition;this._plane.setFromNormalAndCoplanarPoint(new c.Vector3(0,1,0),r);const a=e.ray;o=r.clone(),this._plane.intersectLine(new c.Line3(a.origin,V(a.direction).multiplyScalar(1e4).add(a.origin)),o),o.distanceTo(r)>t.scale.x*10&&(o=null)}if(o){if(this.useTeleportTarget&&!x.getComponentInParent(n.object,su))return;const r=o.clone();if(_f&&j.DrawSphere(o,.025,16711680,5),this.context.mainCamera?.position){const l=this.context.xr?.getUserOffsetInRig();l&&(l.y=0,r.sub(l),_f&&j.DrawWireSphere(l.add(r),.025,65280,5))}this._teleportBuffer.push(t.matrix.clone()),this._teleportBuffer.length>10&&this._teleportBuffer.shift(),this.useTeleportFade?e.xr.fadeTransition()?.then(()=>{t.worldPosition=r}):t.worldPosition=r}}else if(i<-.8&&(this._didTeleport=!0,this._teleportBuffer.length>0)){const n=this._teleportBuffer.pop();n&&n.decompose(t.position,t.quaternion,t.scale)}}_plane=null;_lines=[];_hitDiscs=[];_hitDistances=[];_lastHitDistances=[];renderRays(e){for(let t=0;t<this._lines.length;t++){const i=this._lines[t];i&&(i.visible=!1)}for(let t=0;t<e.controllers.length;t++){const i=e.controllers[t];let n=this._lines[t];if(!i.connected||!i.isTracking||!i.ray||i.targetRayMode==="transient-pointer"||!i.hasSelectEvent){n&&(n.visible=!1);continue}n||(n=this.createRayLineObject(),n.scale.z=.5,this._lines[t]=n),i.updateRayWorldPosition(),i.updateRayWorldQuaternion();const o=i.rayWorldPosition,r=i.rayWorldQuaternion;n.position.copy(o),n.quaternion.copy(r);const a=e.rigScale,l=this.usePinchToTeleport&&i.isTeleportGesture,h=this._lastHitDistances[t],d=this._hitDistances[t]!=null,u=h??a;n.scale.set(a,a,u),n.visible=!0,n.layers.disableAll(),n.layers.enable(2);let p=n.material.opacity;l?p=1:this.showHits&&u<e.rigScale*.5?p=0:i.getButton("primary")?.pressed?p=.5:p=d?.2:.1,n.material.opacity=I.lerp(n.material.opacity,p,this.context.time.deltaTimeUnscaled/.1),n.parent!==this.context.scene&&this.context.scene.add(n)}}renderHits(e){for(const t of this._hitDiscs){if(!t)continue;const i=t.controller;if(!i||!i.connected||!i.isTracking){t.visible=!1;continue}}for(let t=0;t<e.controllers.length;t++){const i=e.controllers[t];if(!i.connected||!i.isTracking||!i.ray||!i.hasSelectEvent)continue;let n=this._hitDiscs[t],o=!0;const r=i.getPointerId("primary");r!=null&&this.context.input.getIsPointerIdInUse(r)&&(n&&(n.visible=!1),this._hitDistances[t]=null,this._lastHitDistances[t]=0,o=!1);const a=this.context.time.smoothedFps>=59?1:10;if((this.context.time.frame+i.index)%a!==0&&(o=!1),!o){const d=this._hitDiscs[t];d&&d.visible&&d.hit&&this.updateHitPointerPosition(i,d,d.hit.distance);continue}const l=this.context.physics.raycastFromRay(i.ray,{testObject:this.hitPointRaycastFilter,precise:!1});let h=l.find(d=>this.usePinchToTeleport&&i.isTeleportGesture?!0:this.isObjectWithInteractiveComponent(d.object));if(h||(h=l[0]),n&&(n.controller=i,n.hit=h),this._hitDistances[t]=h?.distance||null,h){this._lastHitDistances[t]=h.distance;const d=e.rigScale??1;_f&&(j.DrawWireSphere(h.point,.025*d,16711680),j.DrawLabel(V(0,.2,0).add(h.point),h.object.name,.02,0)),n||(n=this.createHitPointObject(),this._hitDiscs[t]=n),n.hit=h,n.visible=h.distance>d*.05;let u=.01*(d+h.distance);const p=i.getButton("primary")?.pressed;p&&(u*=1.1),n.scale.set(u,u,u),n.layers.set(2);let m=n.material.opacity;if(p?m=1:m=h.distance<.15*d?.2:.6,n.material.opacity=I.lerp(n.material.opacity,m,this.context.time.deltaTimeUnscaled/.1),n.visible){if(h.normal){this.updateHitPointerPosition(i,n,h.distance);const y=h.normal.applyQuaternion(ue(h.object));n.quaternion.setFromUnitVectors(RM,y)}else this.updateHitPointerPosition(i,n,h.distance);n.parent!==this.context.scene&&this.context.scene.add(n)}}else this._hitDiscs[t]&&(this._hitDiscs[t].visible=!1)}}isObjectWithInteractiveComponent(e,t=0){return hd(e)||e.isUI===!0?!0:e.isScene?!1:e.parent?this.isObjectWithInteractiveComponent(e.parent,t+1):!1}updateHitPointerPosition(e,t,i){const n=V(e.rayWorldPosition);n.add(V(0,0,i-.01).applyQuaternion(e.rayWorldQuaternion)),t.position.lerp(n,this.context.time.deltaTimeUnscaled/.05)}hitPointRaycastFilter=e=>e.type==="SkinnedMesh"?"continue in children":!0;createHitPointObject(){const e=new c.Mesh(new c.SphereGeometry(.3,6,6),new c.MeshBasicMaterial({color:15658734,opacity:.7,transparent:!0,depthTest:!1,depthWrite:!1,side:c.DoubleSide}));return e.layers.disableAll(),e.layers.enable(2),e}createRayLineObject(){const e=new G.Line2;e.layers.disableAll(),e.layers.enable(2);const t=new G.LineGeometry;e.geometry=t;const i=new Float32Array(9);i.set([0,0,.02,0,0,.4,0,0,1]),t.setPositions(i);const n=new Float32Array(9);n.set([1,1,1,.1,.1,.1,0,0,0]),t.setColors(n);const o=new G.LineMaterial({color:16777215,vertexColors:!0,worldUnits:!0,linewidth:.004,transparent:!0,depthWrite:!1,blending:c.AdditiveBlending,dashed:!1});return e.material=o,e}}so([f()],pi.prototype,"movementSpeed");so([f()],pi.prototype,"rotationStep");so([f()],pi.prototype,"useTeleport");so([f()],pi.prototype,"usePinchToTeleport");so([f()],pi.prototype,"useTeleportTarget");so([f()],pi.prototype,"useTeleportFade");so([f()],pi.prototype,"showRays");so([f()],pi.prototype,"showHits");const RM=new c.Vector3(0,1,0);var EM=Object.defineProperty,rt=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&EM(e,t,n),n};const Wa=w("debugwebxr"),TM=w("debugusdz"),Je=class jr extends k{createVRButton=!0;createARButton=!0;createSendToQuestButton=!0;createQRCode=!0;useDefaultControls=!0;showControllerModels=!0;showHandModels=!0;usePlacementReticle=!0;customARPlacementReticle;usePlacementAdjustment=!0;arScale=1;useXRAnchor=!1;autoPlace=!1;autoCenter=!1;useQuicklookExport=!1;useDepthSensing=!1;useSpatialGrab=!0;defaultAvatar;_playerSync;_createdComponentsInSession=[];_usdzExporter;static activeWebXRComponent=null;awake(){q.getXRSync(this.context)}onEnable(){window.location.protocol!=="https:"&&ce('<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&&(x.findObjectOfType(En)||(Wa&&console.log("WebXR: Adding USDZExporter"),this._usdzExporter=x.addComponent(this.gameObject,En),this._usdzExporter.objectToExport=this.context.scene,this._usdzExporter.autoExportAnimations=!0,this._usdzExporter.autoExportAudioSources=!0)),this.handleCreatingHTML(),this.handleOfferSession(),this.defaultAvatar===!0&&(Wa&&console.warn("WebXR: No default avatar set, using static default avatar"),this.defaultAvatar=new Y("https://cdn.needle.tools/static/avatars/DefaultAvatar.glb")),this.defaultAvatar&&(this._playerSync=this.gameObject.getOrAddComponent(ig),this._playerSync.autoSync=!1),this._playerSync&&typeof this.defaultAvatar!="boolean"&&(this._playerSync.asset=this.defaultAvatar,this._playerSync.onPlayerSpawned?.removeEventListener(this.onAvatarSpawned),this._playerSync.onPlayerSpawned?.addEventListener(this.onAvatarSpawned))}onDisable(){this._usdzExporter?.destroy(),this.removeButtons()}async handleOfferSession(){return this.createVRButton&&await q.isVRSupported()&&this.createVRButton?q.offerSession("immersive-vr","default",this.context):this.createARButton&&await q.isARSupported()&&this.createARButton?q.offerSession("immersive-ar","default",this.context):!1}get session(){return q.active??null}get sessionMode(){return q.activeMode??null}get arSessionRoot(){return this._activeWebARSessionRoot}async enterVR(e){return q.start("immersive-vr",e,this.context)}async enterAR(e){return q.start("immersive-ar",e,this.context)}exitXR(){q.stop()}_exitXRMenuButton;_previousXRState=0;_spatialGrabRaycaster;_activeWebARSessionRoot=null;get isActiveWebXR(){return!jr.activeWebXRComponent||jr.activeWebXRComponent===this}onBeforeXR(e,t){if(!this.isActiveWebXR){console.warn(`WebXR: another WebXR component is already active (${jr.activeWebXRComponent?.name}). This is ignored: ${this.name}`);return}jr.activeWebXRComponent=this,e=="immersive-ar"&&this.useDepthSensing&&(t.optionalFeatures=t.optionalFeatures||[],t.optionalFeatures.push("depth-sensing"))}async onEnterXR(e){if(!this.isActiveWebXR)return;Wa&&console.log("WebXR onEnterXR"),this._previousXRState=It.Global.Mask;const t=e.xr.isVR;if(It.Global.Set(t?bn.VR:bn.AR),e.xr.isAR){let i=x.findObjectOfType(li);if(!i)if(this.usePlacementReticle){const n=new c.Object3D;for(const o of this.context.scene.children)n.add(o);this.context.scene.add(n),i=x.addComponent(n,li),this._createdComponentsInSession.push(i)}else(Wa||A())&&console.warn("WebXR: No WebARSessionRoot found in scene and usePlacementReticle is disabled in WebXR component.");this._activeWebARSessionRoot=i,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=x.findObjectOfType(Go)??void 0,this._spatialGrabRaycaster||(this._spatialGrabRaycaster=this.gameObject.addComponent(Go))),this.createLocalAvatar(e.xr),e.xr.isScreenBasedAR||(this._exitXRMenuButton=this.context.menu.appendChild({label:"Quit XR",onClick:()=>this.exitXR(),icon:"exit_to_app",priority:2e4}))}onUpdateXR(e){this.isActiveWebXR&&this._spatialGrabRaycaster&&(this._spatialGrabRaycaster.enabled=this.useSpatialGrab)}onLeaveXR(e){if(this._exitXRMenuButton?.remove(),!!this.isActiveWebXR){It.Global.Set(this._previousXRState),this._playerSync?.destroyInstance();for(const t of this._createdComponentsInSession)t.destroy();this._createdComponentsInSession.length=0,this._activeWebARSessionRoot=null,this.handleOfferSession(),ec(1).then(()=>jr.activeWebXRComponent=null)}}setDefaultMovementEnabled(e){let t=this.gameObject.getComponent(pi);return!t&&e&&(t=this.gameObject.addComponent(pi),this._createdComponentsInSession.push(t)),t&&(t.enabled=e),t}setDefaultControllerRenderingEnabled(e){let t=this.gameObject.getComponent(ls);return!t&&e&&(t=this.gameObject.addComponent(ls),this._createdComponentsInSession.push(t),t.createControllerModel=this.showControllerModels,t.createHandModel==this.showHandModels),t&&(t.enabled=e),t}async createLocalAvatar(e){this._playerSync&&e.running&&typeof this.defaultAvatar!="boolean"&&(this._playerSync.asset=this.defaultAvatar,await this._playerSync.getInstance())}onAvatarSpawned=e=>{Wa&&console.log("WebXR.onAvatarSpawned",e);let t=x.getComponentInChildren(e,Xs);t??=x.addComponent(e,Xs)};getButtonsContainer(){return this.getButtonsFactory()}getButtonsFactory(){return this._buttonFactory||(this._buttonFactory=Gs.getOrCreate()),this._buttonFactory}_buttonFactory;handleCreatingHTML(){if(this.createARButton||this.createVRButton||this.useQuicklookExport){if((exports.DeviceUtilities.isiOS()&&exports.DeviceUtilities.isSafari()||TM)&&this.useQuicklookExport){const t=x.findObjectOfType(En);if(!t||t&&t.allowCreateQuicklookButton){const i=this.getButtonsFactory().createQuicklookButton();this.addButton(i,50)}}if(this.createARButton){const t=this.getButtonsFactory().createARButton();this.addButton(t,50)}if(this.createVRButton){const t=this.getButtonsFactory().createVRButton();this.addButton(t,50)}}if(this.createSendToQuestButton&&!exports.DeviceUtilities.isQuest()&&q.isVRSupported().then(t=>{if(!t){const i=this.getButtonsFactory().createSendToQuestButton();this.addButton(i,50)}}),this.createQRCode){const t=cc(jn);if(t&&t.createQRCodeButton===!1)A()&&console.warn("WebXR: QRCode button is disabled in the Needle Menu component");else if(!exports.DeviceUtilities.isMobileDevice()){const i=Ki.getOrCreate().createQRCode();this.addButton(i,50)}}}_buttons=[];addButton(e,t){this._buttons.push(e),e.setAttribute("priority",t.toString()),this.context.menu.appendChild(e)}removeButtons(){for(const e of this._buttons)e.remove();this._buttons.length=0}};rt([f()],Je.prototype,"createVRButton");rt([f()],Je.prototype,"createARButton");rt([f()],Je.prototype,"createSendToQuestButton");rt([f()],Je.prototype,"createQRCode");rt([f()],Je.prototype,"useDefaultControls");rt([f()],Je.prototype,"showControllerModels");rt([f()],Je.prototype,"showHandModels");rt([f()],Je.prototype,"usePlacementReticle");rt([f(Y)],Je.prototype,"customARPlacementReticle");rt([f()],Je.prototype,"usePlacementAdjustment");rt([f()],Je.prototype,"arScale");rt([f()],Je.prototype,"useXRAnchor");rt([f()],Je.prototype,"autoPlace");rt([f()],Je.prototype,"autoCenter");rt([f()],Je.prototype,"useQuicklookExport");rt([f()],Je.prototype,"useDepthSensing");rt([f()],Je.prototype,"useSpatialGrab");rt([f(Y)],Je.prototype,"defaultAvatar");let ou=Je;const _h=w("debugusdzbehaviours");class sg{get extensionName(){return"Behaviour"}behaviours=[];addBehavior(e){this.behaviours.push(e)}addAudioClip(e){if(!e||typeof e!="string")return"";const i="audio/"+ar.getName(e);return this.audioClips.push({clipUrl:e,filesKey:i}),i}behaviourComponents=[];behaviourComponentsCopy=[];audioClips=[];audioClipsCopy=[];targetUuids=new Set;getAllTargetUuids(){return this.targetUuids}onBeforeBuildDocument(e){if(!e.root)return Promise.resolve();const t=[];return e.root.traverse(i=>{x.foreachComponent(i,n=>{const o=n;if(typeof o.createBehaviours=="function"||typeof o.beforeCreateDocument=="function"||typeof o.afterCreateDocument=="function"||typeof o.afterSerialize=="function"){this.behaviourComponents.push(o);const r=o.beforeCreateDocument?.call(o,this,e);r instanceof Promise&&t.push(r)}},!1)}),_h&&console.log("onBeforeBuildDocument: all components",this.behaviourComponents),Promise.all(t)}onExportObject(e,t,i){for(const n of this.behaviourComponents)n.createBehaviours?.call(n,this,t,i)}onAfterBuildDocument(e){for(const u of this.behaviourComponents)typeof u.afterCreateDocument=="function"&&u.afterCreateDocument(this,e);this.behaviourComponentsCopy=this.behaviourComponents.slice(),this.behaviourComponents.length=0,this.audioClipsCopy=this.audioClips.slice(),this.audioClips.length=0;const t=new Set,i=new Set,n=new Set,o=new Set,r=_h;let a=`graph LR
1253
1263
  `,l="";function h(u){if(u instanceof Oo){r&&(a+=`subgraph Group_${u.id}
1254
1264
  `);for(const p of u.actions)r&&(a+=`${u.id}[${u.id}] -- ${u.type},loops:${u.loops} --> ${p.id}[${p.id}]
1255
1265
  `),h(p);r&&(a+=`end
@@ -1271,7 +1281,7 @@ dateFormat X
1271
1281
  axisFormat %s
1272
1282
  `;const p=Array.from(o),m=new Set;for(const v of p)if(v.affectedObjects&&typeof v.affectedObjects!="string"){if(Array.isArray(v.affectedObjects))for(const _ of v.affectedObjects)m.add(_);else m.add(v.affectedObjects);r&&(u+=`section ${v.animationName} (${v.id})
1273
1283
  `,u+=`${v.id} : ${v.start}, ${v.duration}s
1274
- `)}r&&o.size&&console.log(u);const y=new Set;for(const v of m){v.getPath||console.error("USDZExporter: Animation target object has no getPath method. This is likely a bug",v);let _=v.getPath();_.startsWith("<")&&(_=_.substring(1)),_.endsWith(">")&&(_=_.substring(0,_.length-1)),y.add({path:_,obj:v})}const b=Array.from(y).sort((v,_)=>v.path.length-_.path.length),g=new Array;for(let v=0;v<b.length;v++)for(let _=v+1;_<b.length;_++)if(b[_].path.startsWith(b[v].path)){const S=b[_],T=b[v];g.push({child:S.obj.displayName+" ("+S.path+")",parent:T.obj.displayName+" ("+T.path+")"})}g.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:g,playAnimationActions:o})}for(const u of new Set([...t,...i]))if(Array.isArray(u))for(const p of u)n.add(p.uuid);else n.add(u.uuid);_h&&console.log("All Behavior trigger sources and action targets",t,i,n),this.targetUuids=new Set(n)}onAfterHierarchy(e,t){if(this.behaviours?.length){t.beginBlock('def Scope "Behaviors"');for(const i of this.behaviours)i.writeTo(this,e.document,t);t.closeBlock()}}async onAfterSerialize(e){_h&&console.log("onAfterSerialize behaviours",this.behaviourComponentsCopy);for(const t of this.behaviourComponentsCopy)typeof t.afterSerialize=="function"&&(t.afterSerialize.constructor.name==="AsyncFunction"?await t.afterSerialize(this,e):t.afterSerialize(this,e));for(const{clipUrl:t,filesKey:i}of this.audioClipsCopy){if(e.files[i])return;const r=await(await(await fetch(t)).blob()).arrayBuffer(),a=new Uint8Array(r);e.files[i]=a}this.behaviourComponentsCopy.length=0,this.audioClipsCopy.length=0}}class og{get extensionName(){return"Physics"}onExportObject(e,t,i){const n=x.getComponents(e,Ke).filter(l=>l.enabled),o=x.getComponents(e,Qt).filter(l=>l.enabled&&!l.isTrigger);let r=n.length>0?n[0]:null;const a=o.length>0?o[0]:null;a&&!r&&(r=new Ke,r.isKinematic=!0),r&&t.addEventListener("serialize",(l,h)=>{if(r){if(l.appendLine(),l.beginBlock('def RealityKitComponent "RigidBody"',"{",!0),r.useGravity||l.appendLine("bool gravityEnabled = 0"),l.appendLine('uniform token info:id = "RealityKit.RigidBody"'),r.isKinematic&&l.appendLine('token motionType = "Kinematic"'),l.beginBlock('def RealityKitStruct "massFrame"',"{",!0),l.appendLine(`float m_mass = ${r.mass}`),l.beginBlock('def RealityKitStruct "m_pose"',"{",!0),l.appendLine(`float3 position = (${r.centerOfMass.x}, ${r.centerOfMass.y}, ${r.centerOfMass.z})`),l.closeBlock("}"),l.closeBlock("}"),o.length>0){const d=o[0];l.beginBlock('def RealityKitStruct "material"',"{",!0);const u=d.sharedMaterial;u&&u.dynamicFriction!==void 0&&l.appendLine(`double dynamicFriction = ${d.sharedMaterial?.dynamicFriction}`),u&&u.bounciness!==void 0&&l.appendLine(`double restitution = ${d.sharedMaterial?.bounciness}`),u&&u.staticFriction!==void 0&&l.appendLine(`double staticFriction = ${d.sharedMaterial?.staticFriction}`),l.closeBlock("}")}l.closeBlock("}")}}),a&&(t.addEventListener("serialize",(l,h)=>{l.beginBlock('def RealityKitComponent "Collider"',"{",!0),l.appendLine("uint group = 1"),l.appendLine('uniform token info:id = "RealityKit.Collider"'),l.appendLine("uint mask = 4294967295");const u=a.isTrigger?"Trigger":"Default";if(l.appendLine(`token type = "${u}"`),l.beginBlock('def RealityKitStruct "Shape"',"{",!0),a instanceof ga){const p=a;l.appendLine('token shapeType = "Sphere"'),l.appendLine(`float radius = ${p.radius}`)}else if(a instanceof Xd){const p=a;l.appendLine('token shapeType = "Box"'),l.appendLine(`float3 extent = (${p.size.x}, ${p.size.y}, ${p.size.z})`)}else if(a instanceof as){const p=a;l.appendLine('token shapeType = "Capsule"'),l.appendLine(`float radius = ${p.radius}`),l.appendLine(`float height = ${p.height}`)}else if(a instanceof io&&a.sharedMesh?.geometry){const p=a.sharedMesh.geometry;p.boundingBox||p.computeBoundingBox();const m=a.sharedMesh.geometry.boundingBox;m&&(l.appendLine('token shapeType = "Box"'),l.appendLine(`float3 extent = (${m.max.x-m.min.x}, ${m.max.y-m.min.y}, ${m.max.z-m.min.z})`),console.log("[USDZ] Only Box, Sphere, and Capsule colliders are supported in visionOS/iOS. MeshCollider will be exported as Box",a))}else console.warn("[USDZ] Only Box, Sphere, and Capsule colliders are supported in visionOS/iOS. Ignoring collider:",a);l.beginBlock('def RealityKitStruct "pose"',"{",!0),l.closeBlock("}"),l.closeBlock("}"),l.closeBlock("}")}),o.length>1&&console.log("WARNING: Multiple colliders detected. visionOS / iOS can only support objects with a single collider, only exporting the first collider: ",a))}}const AM=w("debugshadowcomponents");J.__webpack_exports__Block.prototype.interactable={get(){return this.interactive},set(s){this.interactable=s}};class Bi extends k{isRoot(){return this.Root?.gameObject===this.gameObject}get canvas(){const e=this.Root;return e?.isCanvas?e:null}get Canvas(){return this.canvas}markDirty(){jt.markUIDirty(this.context)}get shadowComponent(){return this._shadowComponent}set shadowComponent(e){this._shadowComponent=e}_shadowComponent=null;_controlsChildLayout=!0;get controlsChildLayout(){return this._controlsChildLayout}set controlsChildLayout(e){this._controlsChildLayout=e,this.shadowComponent&&(this.shadowComponent.autoLayout=e)}_root=void 0;get Root(){return this._root===void 0&&(this._root=x.getComponentInParent(this.gameObject,Cc)),this._root}_parentComponent=void 0;__internalNewInstanceCreated(e){return super.__internalNewInstanceCreated(e),this.shadowComponent=null,this._root=void 0,this._parentComponent=void 0,this}onEnable(){super.onEnable()}addShadowComponent(e,t){if(!e)return;this.removeShadowComponent();const i=this.isRoot()?this.gameObject:this.gameObject.parent;if(this._parentComponent=x.getComponentInParent(i,Bi),!this._parentComponent){console.warn(`Component "${this.name}" doesn't have a UI parent anywhere. Do you have an UI element outside a Canvas? UI components must be a child of a Canvas component`,this);return}e.name=this.name+" ("+(this.constructor.name??"UI")+")",e.autoLayout=this._parentComponent.controlsChildLayout,e[si]=this,this.setShadowComponentOwner(e);let n=!1;if(this.Root?.gameObject===this.gameObject)this.gameObject.add(e);else{const o=this._parentComponent.shadowComponent;o&&(o?.add(e),n=!0)}this.shadowComponent=e,t&&t.shadowComponent&&this.shadowComponent&&t.shadowComponent.add(this.shadowComponent),oc&&e.add(new c.AxesHelper(.5)),this.onAfterAddedToScene(),n&&J.__webpack_exports__update(),AM&&console.warn("Added shadow component",this.shadowComponent)}setShadowComponentOwner(e){if(e&&(e[si]===void 0||e[si]===this)&&(e[si]=this,e.children))for(const t of e.children)this.setShadowComponentOwner(t)}traverseOwnedShadowComponents(e,t,i){if(e&&e[si]===t){i(e);for(const n of e.children)this.traverseOwnedShadowComponents(n,t,i)}}removeShadowComponent(){this.shadowComponent&&this.shadowComponent.removeFromParent()}onAfterAddedToScene(){}setInteractable(e){this.shadowComponent&&(this.shadowComponent.interactable=e)}}class Cc extends Bi{awake(){super.awake()}}var LM=Object.defineProperty,DM=Object.getOwnPropertyDescriptor,Pc=(s,e,t,i)=>{for(var n=i>1?void 0:i?DM(e,t):e,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&LM(e,t,n),n};const bf=w("debugui"),vf=w("debuguilayout");class $v{width;height}class Wv{x;y;width;height}const qi=new c.Vector3,Ga=new c.Matrix4,bh=new c.Quaternion,xa=class Gv extends Bi{get parent(){return this._parentRectTransform}get translation(){return this.gameObject.position}get rotation(){return this.gameObject.quaternion}get scale(){return this.gameObject.scale}_anchoredPosition;get anchoredPosition(){return this._anchoredPosition||(this._anchoredPosition=new c.Vector2),this._anchoredPosition}set anchoredPosition(e){this._anchoredPosition=e}sizeDelta=new c.Vector2(100,100);pivot=new c.Vector2(.5,.5);anchorMin=new c.Vector2(0,0);anchorMax=new c.Vector2(1,1);minWidth;minHeight;get width(){let e=this.sizeDelta.x;if(this.anchorMin.x!==this.anchorMax.x&&this._parentRectTransform){const t=this._parentRectTransform.width,i=this.anchorMax.x-this.anchorMin.x;e=t*i,e+=this.sizeDelta.x}return this.minWidth!==void 0&&e<this.minWidth?this.minWidth:e}get height(){let e=this.sizeDelta.y;if(this.anchorMin.y!==this.anchorMax.y&&this._parentRectTransform){const t=this._parentRectTransform.height,i=this.anchorMax.y-this.anchorMin.y;e=t*i,e+=this.sizeDelta.y}return this.minHeight!==void 0&&e<this.minHeight?this.minHeight:e}lastMatrix;rectBlock;_transformNeedsUpdate=!1;_initialPosition;_parentRectTransform;_lastUpdateFrame=-1;awake(){super.awake(),this._lastUpdateFrame=-1,this._parentRectTransform=void 0,this.rectBlock=new c.Object3D,this.rectBlock.name=this.name,this.lastMatrix=new c.Matrix4,this._lastAnchoring=null,this._initialPosition=this.gameObject.position.clone(),this._initialPosition.z=0,this._anchoredPosition||(this._anchoredPosition=new c.Vector2),Ar(this,"_anchoredPosition",()=>{this.markDirty()}),Ar(this,"sizeDelta",()=>{this.markDirty()}),Ar(this,"pivot",()=>{this.markDirty()}),Ar(this,"anchorMin",()=>{this.markDirty()}),Ar(this,"anchorMax",()=>{this.markDirty()})}onEnable(){super.onEnable(),this.rectBlock||(this.rectBlock=new c.Object3D),this.lastMatrix||(this.lastMatrix=new c.Matrix4),this._lastAnchoring||(this._lastAnchoring=new c.Vector2),this._initialPosition||(this._initialPosition=new c.Vector3),this._anchoredPosition||(this._anchoredPosition=new c.Vector2),this.addShadowComponent(this.rectBlock),this._transformNeedsUpdate=!0,this.canvas?.registerTransform(this)}onDisable(){super.onDisable(),this.removeShadowComponent(),this.canvas?.unregisterTransform(this)}onParentRectTransformChanged(e){this._transformNeedsUpdate||this.onApplyTransform(vf?`${e.name} changed`:void 0)}get isDirty(){return this._transformNeedsUpdate||(this._transformNeedsUpdate=!this.lastMatrix.equals(this.gameObject.matrix)),this._transformNeedsUpdate}markDirty(){this._transformNeedsUpdate||(vf&&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(e){if(this.context.time.frameCount===this._lastUpdateFrame)return;this._lastUpdateFrame=this.context.time.frameCount;const t=this.shadowComponent;if(!t)return;this.gameObject.parent?this._parentRectTransform=x.getComponentInParent(this.gameObject.parent,Gv):this._parentRectTransform=void 0,this._transformNeedsUpdate=!1,vf&&console.warn("RectTransform → ApplyTransform",this.name+" because "+e),this.isRoot()?this.Root.screenspace||(t.rotation.y=Math.PI):(t.matrix.identity(),t.matrixAutoUpdate=!1,qi.set(0,0,0),this.applyPivot(qi),t.matrix.setPosition(qi.x,qi.y,0),(this.gameObject.quaternion.x||this.gameObject.quaternion.y||this.gameObject.quaternion.z)&&(bh.copy(this.gameObject.quaternion),bh.x*=-1,bh.z*=-1,Ga.makeRotationFromQuaternion(bh),t.matrix.premultiply(Ga)),qi.set(0,0,0),this.applyAnchoring(qi),this.canvas?.screenspace?qi.z+=.1:qi.z+=.01,Ga.identity(),Ga.setPosition(qi.x,qi.y,qi.z),t.matrix.premultiply(Ga),t.matrix.scale(this.gameObject.scale)),this.lastMatrix.copy(this.gameObject.matrix);const i=!0;for(const n of Fd(this.gameObject,Bi,i,1)){if(n===this||!n.activeAndEnabled)continue;const o=n;o.onParentRectTransformChanged&&o.onParentRectTransformChanged(this)}}_lastAnchoring;applyAnchoring(e){this._lastAnchoring||(this._lastAnchoring=new c.Vector2);const t=this._lastAnchoring.sub(this._anchoredPosition);this.gameObject.position.x+=t.x,this.gameObject.position.y+=t.y,this._lastAnchoring.copy(this._anchoredPosition),e.x+=this._initialPosition.x-this.gameObject.position.x,e.y+=this._initialPosition.y-this.gameObject.position.y,e.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,e.y+=n;let r=0;const a=1-this.anchorMax.x-this.anchorMin.x;r-=i.width*.5*a,e.x+=r}}applyPivot(e){if(this.pivot&&!this.isRoot()){const t=this.pivot.x-.5;e.x-=t*this.sizeDelta.x*this.gameObject.scale.x;const i=this.pivot.y-.5;e.y-=i*this.sizeDelta.y*this.gameObject.scale.y}}getBasicOptions(){const e={width:this.sizeDelta.x,height:this.sizeDelta.y,offset:0,backgroundOpacity:0,borderWidth:0,borderRadius:0,borderOpacity:0,letterSpacing:-.03};return this.ensureValidSize(e),e}ensureValidSize(e,t=1e-4){return e.width<=0&&(e.width=t),e.height<=0&&(e.height=1e-4),e}_createdBlocks=[];_createdTextBlocks=[];createNewBlock(e){e={...this.getBasicOptions(),...e},bf&&console.log(this.name,e);const t=new J.__webpack_exports__Block(e);return this._createdBlocks.push(t),t}createNewText(e){bf&&console.log(e),e={...this.getBasicOptions(),...e},bf&&console.log(this.name,e);const t=new J.__webpack_exports__Text(e);return this._createdTextBlocks.push(t),t}};Pc([f(c.Vector2)],xa.prototype,"anchoredPosition",1);Pc([f(c.Vector2)],xa.prototype,"sizeDelta",2);Pc([f(c.Vector2)],xa.prototype,"pivot",2);Pc([f(c.Vector2)],xa.prototype,"anchorMin",2);Pc([f(c.Vector2)],xa.prototype,"anchorMax",2);let nn=xa;var IM=Object.defineProperty,Hv=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&IM(e,t,n),n};class Sa extends k{effectColor;effectDistance}Hv([f(Z)],Sa.prototype,"effectColor");Hv([f(c.Vector2)],Sa.prototype,"effectDistance");var jM=Object.defineProperty,BM=Object.getOwnPropertyDescriptor,qv=(s,e,t,i)=>{for(var n=i>1?void 0:i?BM(e,t):e,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&jM(e,t,n),n};const vh={backgroundColor:new c.Color(1,1,1),backgroundOpacity:1,borderColor:new c.Color(1,1,1),borderOpacity:1},rg=class ul extends Bi{get isGraphic(){return!0}get color(){return this._color||(this._color=new Z(1,1,1,1)),this._color}set color(e){(!this._color||this._color.r!==e.r||this._color.g!==e.g||this._color.b!==e.b||this._color.alpha!==e.alpha)&&(this._color||(this._color=new Z(1,1,1,1)),this._color.copy(e),this.onColorChanged())}_alphaFactor=1;setAlphaFactor(e){this._alphaFactor=e,this.onColorChanged()}get alphaFactor(){return this._alphaFactor}sRGBColor=new c.Color(1,0,1);onColorChanged(){this.uiObject&&(this.sRGBColor.copy(this._color),this.sRGBColor.convertLinearToSRGB(),vh.backgroundColor=this.sRGBColor,vh.backgroundOpacity=this._color.alpha*this._alphaFactor,this.applyEffects(vh,this._alphaFactor),this.uiObject.set(vh),this.markDirty())}get m_Color(){return this._color}raycastTarget=!0;uiObject=null;_color=null;_rect=null;_stateManager=null;get rectTransform(){if(this._rect||(this._rect=x.getComponent(this.gameObject,nn)),!this._rect)throw new Error("Not Supported: Make sure to add a RectTransform component before adding a UI Graphic component.");return this._rect}onParentRectTransformChanged(){this.uiObject?.set({width:this.rectTransform.width,height:this.rectTransform.height}),this.markDirty()}__internalNewInstanceCreated(e){return super.__internalNewInstanceCreated(e),this._rect=null,this.uiObject=null,this._stateManager=null,this._color&&(this._color=this._color.clone()),this}setState(e){this.makePanel(),this.uiObject&&(this.uiObject.setState(e),this?.markDirty())}setupState(e){this.makePanel(),this.uiObject&&(this._stateManager||(this._stateManager=new J.SimpleStateBehavior(this.uiObject)),this.uiObject.setupState(e.state,e.attributes))}setOptions(e){this.makePanel(),this.uiObject&&this.uiObject.set(e)}awake(){super.awake(),this.makePanel(),Ar(this,"_color",()=>A1(this,this.onColorChanged))}onEnable(){super.onEnable(),this.uiObject&&(this.rectTransform.shadowComponent?.add(this.uiObject),this.addShadowComponent(this.uiObject,this.rectTransform))}onDisable(){super.onDisable(),this.uiObject&&this.removeShadowComponent()}_currentlyCreatingPanel=!1;makePanel(){if(this.uiObject||this._currentlyCreatingPanel)return;this._currentlyCreatingPanel=!0;const t={backgroundColor:this.color,backgroundOpacity:this.color.alpha,offset:.015};this.onBeforeCreate(t),this.applyEffects(t),this.onCreate(t),this.controlsChildLayout=!1,this._currentlyCreatingPanel=!1,this.onAfterCreated(),this.onColorChanged()}onBeforeCreate(e){}onCreate(e){this.uiObject=this.rectTransform.createNewBlock(e),this.uiObject.name=this.name}onAfterCreated(){}applyEffects(e,t=1){const i=this.gameObject?.getComponent(Sa);i&&(i.effectDistance&&(e.borderWidth=Math.max(Math.abs(i.effectDistance.x),Math.abs(i.effectDistance.y))),i.effectColor&&(e.borderColor=i.effectColor,e.borderOpacity=i.effectColor.alpha*t))}static textureCache=new Map;async setTexture(e){if(this.setOptions({backgroundOpacity:0}),e){if(ul.textureCache.has(e))e=ul.textureCache.get(e);else if(!e.isRenderTargetTexture){const t=e.clone();t.colorSpace=c.LinearSRGBColorSpace,ul.textureCache.set(e,t),e=t}this.setOptions({backgroundImage:e,borderRadius:0,backgroundOpacity:this.color.alpha,backgroundSize:"stretch"}),ne.NEEDLE_progressive.assignTextureLOD(e,0).then(t=>{t instanceof c.Texture&&(e&&ul.textureCache.set(e,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)}};qv([f(Z)],rg.prototype,"color",1);qv([f()],rg.prototype,"raycastTarget",2);let Mc=rg;class Oc extends Mc{_flippedObject=!1;onAfterCreated(){this.uiObject&&!this._flippedObject&&(this._flippedObject=!0,this.uiObject.scale.y*=-1)}}var FM=Object.defineProperty,UM=Object.getOwnPropertyDescriptor,ms=(s,e,t,i)=>{for(var n=i>1?void 0:i?UM(e,t):e,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&FM(e,t,n),n};const go=w("debugtext");var qe=(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))(qe||{}),Xv=(s=>(s[s.Normal=0]="Normal",s[s.Bold=1]="Bold",s[s.Italic=2]="Italic",s[s.BoldAndItalic=3]="BoldAndItalic",s))(Xv||{});class Ct extends Mc{alignment=0;verticalOverflow=0;horizontalOverflow=0;lineSpacing=1;supportRichText=!1;font;fontStyle=0;setAlphaFactor(e){super.setAlphaFactor(e),this.uiObject?.set({fontOpacity:this.color.alpha*this.alphaFactor}),this.markDirty()}get text(){return this._text}set text(e){e!==this._text&&(this._text=e,this.feedText(this.text,this.supportRichText),this.markDirty())}set_text(e){this.text=e}get fontSize(){return this._fontSize}set fontSize(e){this._fontSize=e,this.uiObject?.set({fontSize:e})}sRGBTextColor=new c.Color(1,0,1);onColorChanged(){this.sRGBTextColor.copy(this.color),this.sRGBTextColor.convertLinearToSRGB(),this.uiObject?.set({color:this.sRGBTextColor,fontOpacity:this.color.alpha})}onParentRectTransformChanged(){super.onParentRectTransformChanged(),this.uiObject&&this.updateOverflow()}onBeforeCanvasRender(e){this.updateOverflow()}updateOverflow(){const e=this.uiObject?._overflow;e&&(e._needsUpdate=!0)}onCreate(e){go&&console.log(this),this.horizontalOverflow==1&&(e.whiteSpace="pre"),this.verticalOverflow==0&&(this.context.renderer.localClippingEnabled=!0,e.overflow="hidden"),this.horizontalOverflow==1&&this.verticalOverflow==0,e.lineHeight=this.lineSpacing,delete e.backgroundOpacity,delete e.backgroundColor,go&&(e.backgroundColor=16750848,e.backgroundOpacity=.5);const t=this.rectTransform;e={...e,...this.getTextOpts()},this.getAlignment(e),go&&(e.backgroundColor=Math.random()*16777215,e.backgroundOpacity=.1),this.uiObject=t.createNewText(e),this.feedText(this.text,this.supportRichText)}onAfterAddedToScene(){super.onAfterAddedToScene(),this.handleTextRenderOnTop()}_text="";_fontSize=12;_textMeshUi=null;getTextOpts(){const e=this.fontSize,t={color:this.color,fontOpacity:this.color.alpha,fontSize:e,fontKerning:"normal"};return this.setFont(t,this.fontStyle),t}onEnable(){super.onEnable(),this._didHandleTextRenderOnTop=!1,this.uiObject&&this.uiObject.addAfterUpdate(()=>{this.setShadowComponentOwner(this.uiObject),this.markDirty()}),setTimeout(()=>this.markDirty(),10),this.canvas?.registerEventReceiver(this)}onDisable(){super.onDisable(),this.canvas?.unregisterEventReceiver(this)}getAlignment(e){switch(e.flexDirection="column",this.alignment){case 0:case 3:case 6:e.textAlign="left";break;case 1:case 4:case 7:e.textAlign="center";break;case 2:case 5:case 8:e.textAlign="right";break}switch(this.alignment){default:case 0:case 1:case 2:e.alignItems="start";break;case 3:case 4:case 5:e.alignItems="center";break;case 6:case 7:case 8:e.alignItems="end";break}return e}feedText(e,t){if(go&&console.log("feedText",this.uiObject,e,t),!!this.uiObject)if(this._textMeshUi||(this._textMeshUi=[]),this.uiObject.children.length=0,!t||e.length===0)this.uiObject.textContent=e;else{let i=this.getNextTag(e);if(i){if(i.startIndex>0){for(let r=this.uiObject.children.length-1;r>=0;r--){const a=this.uiObject.children[r];a.isUI&&(this.uiObject.remove(a),a.clear())}const o=new J.__webpack_exports__Inline({textContent:e.substring(0,i.startIndex),color:"inherit"});this.uiObject.add(o)}}else{this.uiObject.textContent="",this.setOptions({textContent:e});return}const n=[];for(;i;){const o=this.getNextTag(e,i.endIndex),r={fontFamily:this.uiObject?.get("fontFamily"),color:"inherit",textContent:""};if(o){r.textContent=this.getText(e,i,o),this.handleTag(i,r,n);const a=new J.__webpack_exports__Inline(r);this.uiObject?.add(a)}else{r.textContent=e.substring(i.endIndex),this.handleTag(i,r,n);const a=new J.__webpack_exports__Inline(r);this.uiObject?.add(a)}i=o}}}_didHandleTextRenderOnTop=!1;handleTextRenderOnTop(){this._didHandleTextRenderOnTop||(this._didHandleTextRenderOnTop=!0,this.startCoroutine(this.renderOnTopCoroutine()))}*renderOnTopCoroutine(){if(!this.canvas)return;const e=[],t=this.canvas,i={renderOnTop:t.renderOnTop,depthWrite:t.depthWrite,doubleSided:t.doubleSided};for(;;){let n=!1;if(this._textMeshUi)for(let o=0;o<this._textMeshUi.length;o++){if(e[o]===!0)continue;n=!0;const r=this._textMeshUi[o];r.textContent&&(ud(r,i),e[o]=!0)}if(!n)break;yield}}handleTag(e,t,i){if(!e.isEndTag){if(e.type.includes("color")){const n=new wf(e,{color:t.color});if(i.push(n),e.type.length>6){const o=parseInt("0x"+e.type.substring(7));t.color=o}else t.color=new c.Color(1,1,1)}else if(e.type=="b"){this.setFont(t,1);const n=new wf(e,{fontWeight:700});i.push(n)}else if(e.type=="i"){this.setFont(t,2);const n=new wf(e,{fontStyle:"italic"});i.push(n)}}}getText(e,t,i){return e.substring(t.endIndex,i.startIndex)}getNextTag(e,t=0){const i=e.indexOf("<",t),n=e.indexOf(">",i);if(i>=0&&n>=0){const o=e.substring(i+1,n);return{type:o,startIndex:i,endIndex:n+1,isEndTag:o.startsWith("/")}}return null}setFont(e,t){if(!this.font)return;const i=this.font,n=this.getFamilyNameWithCorrectSuffix(i,t);go&&console.log("Selected font family:"+n);let o=J.__webpack_exports__FontLibrary.getFontFamily(n);switch(o||(o=J.__webpack_exports__FontLibrary.addFontFamily(n)),e.fontFamily=o,t){default:case 0:e.fontWeight=400,e.fontStyle="normal";break;case 1:e.fontWeight=700,e.fontStyle="normal";break;case 2:e.fontWeight=400,e.fontStyle="italic";break;case 3:e.fontStyle="italic",e.fontWeight=400}let r=o.getVariant(e.fontWeight,e.fontStyle);if(!r){let a=n;a?.endsWith("-msdf.json")||(a+="-msdf.json");let l=n;l?.endsWith(".png")||(l+=".png"),r=o.addVariant(e.fontWeight,e.fontStyle,a,l),r?.addEventListener("ready",()=>{this.markDirty()})}}getFamilyNameWithCorrectSuffix(e,t){const i=e.lastIndexOf("-");if(i<0)return e;const n=e.substring(i+1)?.toLowerCase();if(zM.includes(n))return go&&console.warn("Unsupported font style: "+n),e;const o=e.lastIndexOf("/");let r=e;o>=0&&(r=r.substring(o+1));const a=r[0]===r[0].toUpperCase(),l=e.substring(0,i);switch(go&&console.log("Select font: ",e,Xv[t],r,a,l),t){case 0:return a?l+"-Regular":l+"-regular";case 1:return a?l+"-Bold":l+"-bold";case 2:return a?l+"-Italic":l+"-italic";case 3:return a?l+"-BoldItalic":l+"-bolditalic";default:return e}}}ms([f()],Ct.prototype,"alignment",2);ms([f()],Ct.prototype,"verticalOverflow",2);ms([f()],Ct.prototype,"horizontalOverflow",2);ms([f()],Ct.prototype,"lineSpacing",2);ms([f()],Ct.prototype,"supportRichText",2);ms([f(URL)],Ct.prototype,"font",2);ms([f()],Ct.prototype,"fontStyle",2);ms([f()],Ct.prototype,"text",1);ms([f()],Ct.prototype,"fontSize",1);class wf{tag;previousValues;constructor(e,t){this.tag=e,this.previousValues=t}}const zM=["medium","mediumitalic","black","blackitalic","thin","thinitalic","extrabold","light","lightitalic","semibold"];class Vr{static global_id=0;static getId(){return this.global_id++}id;content="";font=[];pointSize=144;width;height;depth;wrapMode;horizontalAlignment;verticalAlignment;material;setDepth(e){return this.depth=e,this}setPointSize(e){return this.pointSize=e,this}setHorizontalAlignment(e){return this.horizontalAlignment=e,this}setVerticalAlignment(e){return this.verticalAlignment=e,this}constructor(e){this.id=e}writeTo(e,t){t.beginBlock(`def Preliminary_Text "${this.id}"`,"(",!1),t.appendLine('prepend apiSchemas = ["MaterialBindingAPI"]'),t.closeBlock(")"),t.beginBlock(),this.content&&t.appendLine(`string content = "${this.content}"`),(!this.font||this.font.length<=0)&&(this.font||=[],this.font?.push("sans-serif"));const i=this.font.map(n=>`"${n}"`).join(", ");t.appendLine(`string[] font = [ ${i} ]`),t.appendLine(`double pointSize = ${this.pointSize}`),typeof this.width=="number"&&t.appendLine(`double width = ${this.width}`),typeof this.height=="number"&&t.appendLine(`double height = ${this.height}`),typeof this.depth=="number"&&t.appendLine(`double depth = ${this.depth}`),this.wrapMode&&t.appendLine(`token wrapMode = "${this.wrapMode}"`),this.horizontalAlignment&&t.appendLine(`token horizontalAlignment = "${this.horizontalAlignment}"`),this.verticalAlignment&&t.appendLine(`token verticalAlignment = "${this.verticalAlignment}"`),this.material!==void 0&&t.appendLine(`rel material:binding = </StageRoot/Materials/${Zd(this.material)}>`),t.closeBlock()}}class ag{static singleLine(e,t,i){const n=new Vr("text_"+Vr.getId());return n.content=e,t&&(n.pointSize=t),i&&(n.depth=i),n}static multiLine(e,t,i,n,o,r){const a=new Vr("text_"+Vr.getId());return a.content=e,a.width=t,a.height=i,a.horizontalAlignment=n,a.verticalAlignment=o,r!==void 0&&(a.wrapMode=r),a}}const NM=new c.Matrix4().makeRotationY(Math.PI),VM=new c.Matrix4().makeScale(-1,1,-1);class ru{get extensionName(){return"text"}exportText(e,t,i){const n=x.getComponent(e,Ct);if(!n)return;const o=x.getComponent(e,nn);let r=100,a=100;o&&(r=o.width,a=o.height);const l=NM.clone();o&&l.premultiply(VM),t.setMatrix(l);const h=n.color.clone();t.material=new c.MeshStandardMaterial({color:h,emissive:h}),t.addEventListener("serialize",(d,u)=>{let p=n.text;p=p.replace(/\r/g,""),p=p.replace(/\n/g,"\\n");const m=ag.multiLine(p,r,a,"center","bottom","flowing");this.setTextAlignment(m,n.alignment),this.setOverflow(m,n),t.material&&(m.material=t.material),m.pointSize=this.convertToTextSize(n.fontSize),m.depth=.001,m.writeTo(void 0,d)})}convertToTextSize(e){return 1/.0502*144*e}setOverflow(e,t){t.horizontalOverflow?e.wrapMode="singleLine":e.wrapMode="flowing"}setTextAlignment(e,t){switch(t){case qe.LowerLeft:case qe.MiddleLeft:case qe.UpperLeft:e.horizontalAlignment="left";break;case qe.LowerCenter:case qe.MiddleCenter:case qe.UpperCenter:e.horizontalAlignment="center";break;case qe.LowerRight:case qe.MiddleRight:case qe.UpperRight:e.horizontalAlignment="right";break}switch(t){case qe.LowerLeft:case qe.LowerCenter:case qe.LowerRight:e.verticalAlignment="bottom";break;case qe.MiddleLeft:case qe.MiddleCenter:case qe.MiddleRight:e.verticalAlignment="middle";break;case qe.UpperLeft:case qe.UpperCenter:case qe.UpperRight:e.verticalAlignment="top";break}}}var $M=Object.defineProperty,Ve=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&$M(e,t,n),n};const __=w("debuguilayout");class cr{left=0;right=0;top=0;bottom=0;get vertical(){return this.top+this.bottom}get horizontal(){return this.left+this.right}}Ve([f()],cr.prototype,"left");Ve([f()],cr.prototype,"right");Ve([f()],cr.prototype,"top");Ve([f()],cr.prototype,"bottom");class gi extends k{_rectTransform=null;get rectTransform(){return this._rectTransform}onParentRectTransformChanged(e){this._needsUpdate=!0}_needsUpdate=!1;get isDirty(){return this._needsUpdate}get isLayoutGroup(){return!0}updateLayout(){this._rectTransform&&(__&&console.warn("Layout Update",this.context.time.frame,this.name),this._needsUpdate=!1,this.onCalculateLayout(this._rectTransform))}childAlignment=0;reverseArrangement=!1;spacing=0;padding;minWidth=0;minHeight=0;flexibleHeight=0;flexibleWidth=0;preferredHeight=0;preferredWidth=0;start(){this._needsUpdate=!0}onEnable(){__&&console.log(this.name,this),this._rectTransform=this.gameObject.getComponent(nn);const e=this.gameObject.getComponentInParent(ca);e&&e.registerLayoutGroup(this),this._needsUpdate=!0}onDisable(){const e=this.gameObject.getComponentInParent(ca);e&&e.unregisterLayoutGroup(this)}set m_Spacing(e){e!==this.spacing&&(this._needsUpdate=!0,this.spacing=e)}get m_Spacing(){return this.spacing}}Ve([f()],gi.prototype,"childAlignment");Ve([f()],gi.prototype,"reverseArrangement");Ve([f()],gi.prototype,"spacing");Ve([f(cr)],gi.prototype,"padding");Ve([f()],gi.prototype,"minWidth");Ve([f()],gi.prototype,"minHeight");Ve([f()],gi.prototype,"flexibleHeight");Ve([f()],gi.prototype,"flexibleWidth");Ve([f()],gi.prototype,"preferredHeight");Ve([f()],gi.prototype,"preferredWidth");class oo extends gi{childControlHeight=!0;childControlWidth=!0;childForceExpandHeight=!1;childForceExpandWidth=!1;childScaleHeight=!1;childScaleWidth=!1;onCalculateLayout(e){const t=this.primaryAxis,i=e.width;let n=i;const o=e.height;let r=o;n-=this.padding.horizontal,r-=this.padding.vertical,t==="x"?this.padding.horizontal:this.padding.vertical;const a=t==="x",l=a?"y":"x",h=a?this.childControlWidth:this.childControlHeight,d=a?this.childControlHeight:this.childControlWidth,u=a?this.childForceExpandWidth:this.childForceExpandHeight,p=a?this.childForceExpandHeight:this.childForceExpandWidth,m=a?r:n,y=a?i:o,b=.5*(a?this.childAlignment%3:Math.floor(this.childAlignment/3));let g=0;a?g+=this.padding.left:g+=this.padding.top;let v=0,_=0;for(let R=0;R<this.gameObject.children.length;R++){const B=this.gameObject.children[R],L=x.getComponent(B,nn);L?.activeAndEnabled&&(_+=1,a?v+=L.width:v+=L.height)}let S=0;const T=this.spacing*(_-1);if(u||h){let R=0;a?R=n-=T:R=r-=T,_>0&&(S=R/_)}let M=0;M+=this.padding.left,M-=this.padding.right,b!==0&&(g=y-v,g*=b,g-=T*b,a?(g-=this.padding.right*b,g+=this.padding.left*(1-b),g<this.padding.left&&(g=this.padding.left)):(g-=this.padding.bottom*b,g+=this.padding.top*(1-b),g<this.padding.top&&(g=this.padding.top)));let O=1;for(let R=0;R<this.gameObject.children.length;R++){const B=this.gameObject.children[R],L=x.getComponent(B,nn);if(L?.activeAndEnabled){L.pivot?.set(.5,.5),L.anchorMin.set(0,1),L.anchorMax.set(0,1);const N=i*.5+M*.5;L.anchoredPosition.x!==N&&(L.anchoredPosition.x=N);const $=o*-.5;L.anchoredPosition.y!==$&&(L.anchoredPosition.y=$),p&&d&&L.sizeDelta[l]!==m&&(L.sizeDelta[l]=m),u&&h&&L.sizeDelta[t]!==S&&(L.sizeDelta[t]=S);const E=a?L.width:L.height,F=E*.5;if(g+=F,u){const K=S*O-S*.5;K>g&&(g=K-S*.5+E+this.padding.left,g-=F)}let z=g;t==="y"&&(z=-z),L.anchoredPosition[t]!==z&&(L.anchoredPosition[t]=z),g+=F,g+=this.spacing,O+=1}}}}Ve([f()],oo.prototype,"childControlHeight");Ve([f()],oo.prototype,"childControlWidth");Ve([f()],oo.prototype,"childForceExpandHeight");Ve([f()],oo.prototype,"childForceExpandWidth");Ve([f()],oo.prototype,"childScaleHeight");Ve([f()],oo.prototype,"childScaleWidth");class lg extends oo{get primaryAxis(){return"y"}}class cg extends oo{get primaryAxis(){return"x"}}class hg extends gi{onCalculateLayout(){}}var WM=Object.defineProperty,GM=Object.getOwnPropertyDescriptor,Bn=(s,e,t,i)=>{for(var n=i>1?void 0:i?GM(e,t):e,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&WM(e,t,n),n},Qv=(s=>(s[s.ScreenSpaceOverlay=0]="ScreenSpaceOverlay",s[s.ScreenSpaceCamera=1]="ScreenSpaceCamera",s[s.WorldSpace=2]="WorldSpace",s[s.Undefined=-1]="Undefined",s))(Qv||{});const xf=w("debuguilayout"),Fi=class Yv extends Cc{get isCanvas(){return!0}get screenspace(){return this.renderMode!==2}set renderOnTop(e){e!==this._renderOnTop&&(this._renderOnTop=e,this.onRenderSettingsChanged())}get renderOnTop(){return this._renderOnTop!==void 0?this._renderOnTop:!!(this.screenspace&&this._renderMode===0)}_renderOnTop;set depthWrite(e){this._depthWrite!==e&&(this._depthWrite=e,this.onRenderSettingsChanged())}get depthWrite(){return this._depthWrite}_depthWrite=!1;set doubleSided(e){this._doubleSided!==e&&(this._doubleSided=e,this.onRenderSettingsChanged())}get doubleSided(){return this._doubleSided}_doubleSided=!0;set castShadows(e){this._castShadows!==e&&(this._castShadows=e,this.onRenderSettingsChanged())}get castShadows(){return this._castShadows}_castShadows=!1;set receiveShadows(e){this._receiveShadows!==e&&(this._receiveShadows=e,this.onRenderSettingsChanged())}get receiveShadows(){return this._receiveShadows}_receiveShadows=!1;get renderMode(){return this._renderMode}set renderMode(e){this._renderMode!==e&&(this._renderMode=e,this.onRenderSettingsChanged())}_renderMode=-1;_rootCanvas;set rootCanvas(e){this._rootCanvas instanceof Yv||(this._rootCanvas=e)}get rootCanvas(){return this._rootCanvas}_scaleFactor=1;get scaleFactor(){return this._scaleFactor}set scaleFactor(e){this._scaleFactor=e}worldCamera;planeDistance=-1;awake(){this.shadowComponent=this.gameObject,this.previousParent=this.gameObject.parent,xf&&console.log("Canvas.Awake()",this.previousParent?.name+"/"+this.gameObject.name),super.awake()}start(){this.applyRenderSettings()}onEnable(){super.onEnable(),this._updateRenderSettingsRoutine=void 0,this._lastMatrixWorld=new c.Matrix4,this.applyRenderSettings(),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 e=this.context.pre_render_callbacks.indexOf(this.onBeforeRenderRoutine);e!==-1&&this.context.pre_render_callbacks.splice(e,1);const t=this.context.post_render_callbacks.indexOf(this.onAfterRenderRoutine);t!==-1&&this.context.post_render_callbacks.splice(t,1)}_boundRenderSettingsChanged=this.onRenderSettingsChanged.bind(this);previousParent=null;_lastMatrixWorld=null;_rectTransforms=[];registerTransform(e){this._rectTransforms.push(e)}unregisterTransform(e){const t=this._rectTransforms.indexOf(e);t!==-1&&this._rectTransforms.splice(t,1)}_layoutGroups=new Map;registerLayoutGroup(e){const t=e.gameObject;this._layoutGroups.set(t,e)}unregisterLayoutGroup(e){const t=e.gameObject;this._layoutGroups.delete(t)}_receivers=[];registerEventReceiver(e){this._receivers.push(e)}unregisterEventReceiver(e){const t=this._receivers.indexOf(e);t!==-1&&this._receivers.splice(t,1)}async onEnterXR(e){this.screenspace?(e.xr.isVR||e.xr.isPassThrough)&&(this.gameObject.visible=!1):(this.gameObject.visible=!1,await ec(1).then(()=>{this.gameObject.visible=!0}))}onLeaveXR(e){this.screenspace&&(e.xr.isVR||e.xr.isPassThrough)&&(this.gameObject.visible=!0)}onBeforeRenderRoutine=()=>{if(this.previousParent=this.gameObject.parent,(this.context.xr?.isVR||this.context.xr?.isPassThrough)&&this.screenspace){this.gameObject.visible=!1,this.gameObject.removeFromParent();return}this.renderOnTop||this.screenspace?this.gameObject.removeFromParent():(this.onUpdateRenderMode(),this.handleLayoutUpdates(),this.shadowComponent?.updateMatrixWorld(!0),this.shadowComponent?.updateWorldMatrix(!0,!0),this.invokeBeforeRenderEvents(),jt.ensureUpdateMeshUI(J.ThreeMeshUI,this.context))};onAfterRenderRoutine=()=>{if((this.context.xr?.isVR||this.context.xr?.isPassThrough)&&this.screenspace){this.previousParent?.add(this.gameObject);return}if((this.screenspace||this.renderOnTop)&&this.previousParent&&this.context.mainCamera){this.screenspace?this.context.mainCamera?.add(this.gameObject):this.previousParent.add(this.gameObject);const e=this.context.renderer.autoClear,t=this.context.renderer.autoClearColor;this.context.renderer.autoClear=!1,this.context.renderer.autoClearColor=!1,this.context.renderer.clearDepth(),this.onUpdateRenderMode(!0),this.handleLayoutUpdates(),this.shadowComponent?.updateMatrixWorld(!0),this.invokeBeforeRenderEvents(),jt.ensureUpdateMeshUI(J.ThreeMeshUI,this.context,!0),this.context.renderer.render(this.gameObject,this.context.mainCamera),this.context.renderer.autoClear=e,this.context.renderer.autoClearColor=t,this.previousParent.add(this.gameObject)}this._lastMatrixWorld?.copy(this.gameObject.matrixWorld)};invokeBeforeRenderEvents(){for(const e of this._receivers)e.onBeforeCanvasRender?.(this)}handleLayoutUpdates(){this._lastMatrixWorld===null&&(this._lastMatrixWorld=new c.Matrix4);const e=!this._lastMatrixWorld.equals(this.gameObject.matrixWorld);xf&&e&&console.log("Canvas Layout changed",this.context.time.frameCount,this.name);for(const t of this._rectTransforms){e&&t.markDirty();let i=this._layoutGroups.get(t.gameObject);t.isDirty&&!i&&(i=t.gameObject.getComponentInParent(gi)),(t.isDirty||i?.isDirty)&&(xf&&console.log("CANVAS UPDATE ### "+t.name+" ##################################### "+this.context.time.frame),i?.updateLayout(),t.updateTransform())}}applyRenderSettings(){this.onRenderSettingsChanged()}_updateRenderSettingsRoutine;onRenderSettingsChanged(){this._updateRenderSettingsRoutine||(this._updateRenderSettingsRoutine=this.startCoroutine(this._updateRenderSettingsDelayed(),pe.OnBeforeRender))}*_updateRenderSettingsDelayed(){if(yield,this._updateRenderSettingsRoutine=void 0,this.shadowComponent){this.onUpdateRenderMode(),ud(this.shadowComponent,this);for(const e of x.getComponentsInChildren(this.gameObject,Bi))ud(e.shadowComponent,this)}}_activeRenderMode=-1;_lastWidth=-1;_lastHeight=-1;onUpdateRenderMode(e=!1){if(!e&&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=I.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(nn);let r=!1;o.sizeDelta.x!==this.context.domWidth&&(r=!0),o.sizeDelta.y!==this.context.domHeight&&(r=!0);const a=t.fieldOfView*Math.PI/180,l=2*Math.tan(a/2)*Math.abs(n);this.gameObject.scale.x=l/this.context.domHeight,this.gameObject.scale.y=l/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}}};Bn([f()],Fi.prototype,"renderOnTop",1);Bn([f()],Fi.prototype,"depthWrite",1);Bn([f()],Fi.prototype,"doubleSided",1);Bn([f()],Fi.prototype,"castShadows",1);Bn([f()],Fi.prototype,"receiveShadows",1);Bn([f()],Fi.prototype,"renderMode",1);Bn([f(Fi)],Fi.prototype,"rootCanvas",1);Bn([f()],Fi.prototype,"scaleFactor",1);Bn([f(Wt)],Fi.prototype,"worldCamera",2);Bn([f()],Fi.prototype,"planeDistance",2);let ca=Fi;var HM=Object.defineProperty,qM=Object.getOwnPropertyDescriptor,dg=(s,e,t,i)=>{for(var n=i>1?void 0:i?qM(e,t):e,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&HM(e,t,n),n};class Qs extends k{get alpha(){return this._alpha}set alpha(e){e!==this._alpha&&(this._alpha=e,this.markDirty())}get isCanvasGroup(){return!0}_alpha=1;interactable=!0;blocksRaycasts=!0;_isDirty=!1;markDirty(){this._isDirty||(this._isDirty=!0,this.startCoroutine(this.applyChangesDelayed(),pe.OnBeforeRender))}*applyChangesDelayed(){this._isDirty=!1,this.applyChangesNow()}_buffer=[];applyChangesNow(){this._buffer.length=0;for(const e of x.getComponentsInChildren(this.gameObject,Bi,this._buffer)){const t=e;t.setAlphaFactor&&t.setAlphaFactor(this._alpha)}}}dg([f()],Qs.prototype,"alpha",1);dg([f()],Qs.prototype,"interactable",2);dg([f()],Qs.prototype,"blocksRaycasts",2);class ug{get extensionName(){return"tmui"}onExportObject(e,t,i){const n=x.getComponent(e,ca);if(n&&n.enabled&&n.renderMode===Qv.WorldSpace){const o=new ru,r=x.getComponent(e,nn),a=x.getComponent(e,Qs),l=new Array;if(r){if(!x.isActiveSelf(e)){const u=x.isActiveSelf(e);x.setActive(e,!0),r.onEnable(),r.updateTransform(),l.push(()=>{r.onDisable(),x.setActive(e,u)})}e.traverse(u=>{if(!x.isActiveInHierarchy(u)){const p=x.isActiveSelf(u);x.setActive(u,!0);const m=x.getComponent(u,Bi);m&&(m.onEnable(),l.push(()=>{m.onDisable()}));const y=x.getComponent(u,nn);y&&(y.onEnable(),y.updateTransform(),y.onApplyTransform(),l.push(()=>{y.onDisable()}));const b=x.getComponent(u,Ct);b&&(b.onEnable(),l.push(()=>{b.onDisable()})),l.push(()=>{x.setActive(u,p)})}}),r.width,r.height;const h=ze.createEmpty(),d=r.shadowComponent;if(t.add(h),d){const u=d.matrix;h.setMatrix(u);const p=new Map,m=new Map;p.set(d,h),m.set(d,a?a.alpha:1),d.traverse(y=>{if(y===d)return;const b=ze.createEmpty();b.setMatrix(y.matrix);const g=y.parent,v=!!g&&typeof g.textContent=="string"&&g.textContent.length>0;let _=m.get(g)||1;const S=x.getComponent(y,Qs);if(S&&(_*=S.alpha),y instanceof c.Mesh&&v){const M=y[si];M?o.exportText(M.gameObject,b,i):console.error("Error when exporting UI: shadow component owner not found. This is likely a bug.",y)}if(y instanceof c.Mesh&&!v){const M=y.geometry.clone();M.scale(1,1,-1),this.flipWindingOrder(M),b.geometry=M;const O=new c.Color,R=y.material.opacity;O.copy(y.material.color),b.material=new c.MeshBasicMaterial({color:O,opacity:R*_,map:y.material.map,transparent:!0})}p.set(y,b),m.set(y,_);const T=p.get(g);if(!T){console.error("Error when exporting UI: shadow component parent not found!",y,y.parent);return}T.add(b)})}}for(const h of l)h()}}flipWindingOrder(e){const t=e.index.array;for(let i=0,n=t.length/3;i<n;i++){const o=t[i*3];t[i*3]=t[i*3+2],t[i*3+2]=o}e.index.needsUpdate=!0}}const fl=w("debugusdz");function XM(s,e){const t=[],i=x.getComponentsInChildren(s,mt),n=x.getComponentsInChildren(s,wt),o=new Array,r=new Array;if(e.injectImplicitBehaviours)for(const a of i){if(!a||!a.runtimeAnimatorController||!a.enabled)continue;const l=a.runtimeAnimatorController.activeState;if(!l||!l.motion||!l.motion.clip||l.motion.clip.tracks?.length<1||o.includes(a))continue;const h=new Gl;h.animator=a,h.stateName=l.name,h.trigger="start",h.name="PlayAnimationOnClick_implicitAtStart_"+h.stateName;const d=new c.Object3D;x.addComponent(d,h),r.push(d),o.push(a),s.add(d)}else for(const a of i){if(!a||!a.runtimeAnimatorController||!a.enabled)continue;fl&&console.log(a);const l=[];for(const h of a.runtimeAnimatorController.enumerateActions()){fl&&console.log(h);const d=h.getClip();l.includes(d)||l.push(d)}t.push({root:a.gameObject,clips:l})}if(e.injectImplicitBehaviours)for(const a of n){if(!a||!a.clip||!a.enabled||!a.playAutomatically||o.includes(a))continue;const l=new Gl;l.animation=a,l.stateName=a.clip.name,l.trigger="start",l.name="PlayAnimationOnClick_implicitAtStart_"+l.stateName;const h=new c.Object3D;x.addComponent(h,l),r.push(h),o.push(a),s.add(h)}else for(const a of n){fl&&console.log(a);const l=[];for(const h of a.animations)l.includes(h)||l.push(h);t.push({root:a.gameObject,clips:l})}fl&&t?.length>0&&console.log("USDZ Animation Clips without behaviours",t);for(const a of t)for(const l of a.clips)e.registerAnimation(a.root,l);return r}function QM(s,e){const t=x.getComponentsInChildren(s,Ii),i=x.getComponentsInChildren(s,qs),n=new Array,o=new Array;fl&&console.log({audioSources:t,playAudioOnClicks:i});for(const r of i){if(!r.target)continue;const a=t.indexOf(r.target);a>-1&&t.splice(a,1)}for(const r of t){if(!r||!r.clip||r.volume<=0||n.includes(r))continue;const a=new qs;a.target=r,a.name="PlayAudioOnClick_implicitAtStart_",a.trigger="start";const l=new c.Object3D;x.addComponent(l,a),console.log("implicit PlayAudioOnStart",l,a),o.push(l),n.push(r),s.add(l)}return o}function YM(s){return new pt("DisableAtStart",xt.sceneStartTrigger(),ae.fadeAction(s,0,!1))}function b_(s,e){const t=s.domElement.shadowRoot.querySelector("link[rel='ar']");if(t)return t;const i=document.createElement("div");i.classList.add("menu"),i.classList.add("quicklook-menu"),i.style.display="none",i.style.visibility="hidden";const n=document.createElement("button");n.id="open-in-ar",e?(n.innerText="View in AR",n.title="View this scene in AR. The scene will be exported to USDZ and opened with Apple's QuickLook."):(n.innerText="View in AR",n.title="Download this scene for AR. Open the downloaded USDZ file to view it in AR using Apple's QuickLook."),i.appendChild(n);const o=document.createElement("a");o.id="needle-usdz-link",o.style.display="none",o.rel="ar",o.href="",o.target="_blank",i.appendChild(o);const r=document.createElement("img");return r.id="button",o.appendChild(r),s.domElement.shadowRoot.appendChild(i),o}var KM=Object.defineProperty,yt=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&KM(e,t,n),n};const Jt=w("debugusdz"),ZM=w("debugusdzpruning");class hr{callToAction;checkoutTitle;checkoutSubtitle;callToActionURL}yt([f()],hr.prototype,"callToAction");yt([f()],hr.prototype,"checkoutTitle");yt([f()],hr.prototype,"checkoutSubtitle");yt([f()],hr.prototype,"callToActionURL");const Kt=class wp extends k{objectToExport=void 0;autoExportAnimations=!0;autoExportAudioSources=!0;exportFileName=void 0;customUsdzFile=void 0;customBranding;anchoringType="plane";maxTextureSize=2048;planeAnchoringAlignment="horizontal";interactive=!0;physics=!0;allowCreateQuicklookButton=!0;quickLookCompatible=!0;extensions=[];link;button;start(){Jt&&(console.log("USDZExporter",this),console.log("Debug USDZ Mode. Press 'T' to export"),window.addEventListener("keydown",e=>{switch(e.key){case"t":this.exportAndOpen();break}})),this.objectToExport||(this.objectToExport=this.gameObject),!this.objectToExport?.children?.length&&!this.objectToExport?.isMesh&&(this.objectToExport=this.context.scene)}onEnable(){const e=exports.DeviceUtilities.supportsQuickLookAR(),t=exports.DeviceUtilities.isiOS()||exports.DeviceUtilities.isiPad();!this.button&&(Jt||e||t)&&(this.allowCreateQuicklookButton&&(this.button=this.createQuicklookButton()),this.lastCallback=this.quicklookCallback.bind(this),this.link=b_(this.context,e),this.link.addEventListener("message",this.lastCallback)),Jt&&Se("USDZ Exporter enabled: "+this.name),document.getElementById("open-in-ar")?.addEventListener("click",this.onClickedOpenInARElement),jl.registerExporter(this)}onDisable(){this.button?.remove(),this.link?.removeEventListener("message",this.lastCallback),Jt&&Se("USDZ Exporter disabled: "+this.name),document.getElementById("open-in-ar")?.removeEventListener("click",this.onClickedOpenInARElement),jl.unregisterExporter(this)}onClickedOpenInARElement=e=>{e.preventDefault(),this.exportAndOpen()};async exportAsync(){return this.exportAndOpen()}async exportAndOpen(){let e=this.exportFileName??this.objectToExport?.name??this.name;if(e+="-"+Mv(),kn()||(e!==""&&(e+="-"),e+="MadeWithNeedle"),this.link||(this.link=b_(this.context,exports.DeviceUtilities.supportsQuickLookAR())),this.customUsdzFile)return Jt&&console.log("Exporting custom usdz",this.customUsdzFile),this.openInQuickLook(this.customUsdzFile,e),null;if(!this.objectToExport)return console.warn("No object to export",this),null;const t=await this.export(this.objectToExport);return t?(Jt&&console.log("USDZ generation done. Downloading as "+e),this.openInQuickLook(t,e),t):(console.error("USDZ generation failed. Please report a bug",this),null)}async export(e){if(!e)return console.warn("No object to export"),null;const t=this._currentExportTasks.get(e);if(t)return t;const i=this.internalExport(e);return i instanceof Promise?(this._currentExportTasks.set(e,i),i.then(n=>(this._currentExportTasks.delete(e),n)).catch(n=>(this._currentExportTasks.delete(e),console.error("Error during USDZ export – please report a bug!",n),null))):i}_currentExportTasks=new Map;_previousTimeScale=1;async internalExport(e){ie.start("export-usdz",{onProgress:M=>{this.dispatchEvent(new CustomEvent("export-progress",{detail:{progress:M}}))}}),ie.report("export-usdz",{message:"Starting export",totalSteps:40,currentStep:0}),ie.report("export-usdz",{message:"Load progressive textures",autoStep:5}),ie.start("export-usdz-textures","export-usdz");const t=x.getComponentsInChildren(e,Yt);for(const M of t)M&&M.enabled&&M.updateSprite(!0);const i=x.getComponentsInChildren(e,fi),n=new Array;let o=0;for(const M of i){for(const O of M.sharedMeshes)if(O){const R=ne.NEEDLE_progressive.assignMeshLOD(O,0);R instanceof Promise&&n.push(new Promise((B,L)=>{R.then(()=>{o++,ie.report("export-usdz-textures",{message:"Loaded progressive mesh",currentStep:o,totalSteps:n.length}),B()}).catch(N=>L(N))}))}for(const O of M.sharedMaterials)if(O){const R=ne.NEEDLE_progressive.assignTextureLOD(O,0);R instanceof Promise&&n.push(new Promise((B,L)=>{R.then(()=>{o++,ie.report("export-usdz-textures",{message:"Loaded progressive texture",currentStep:o,totalSteps:n.length}),B()}).catch(N=>L(N))}))}}Jt&&Se("Progressive Loading: "+n.length),await Promise.all(n),Jt&&Se("Progressive Loading: done"),ie.end("export-usdz-textures");const r=It.Global.Mask;It.Global.Set(bn.AR);const a=new Tv,l=new Jd(this.quickLookCompatible);let h;const d=[];this.interactive&&(d.push(new sg),d.push(new ar),globalThis.NEEDLE_USE_RAPIER&&x.getComponentsInChildren(e,Ke).length>0&&(this.physics?(h=new og,d.push(h)):A()&&console.warn("USDZExporter: Physics export is disabled, but there are active Rigidbody components in the scene. They will not be exported.")),d.push(new ru),d.push(new ug));const u=[l,...d,...this.extensions],p={self:this,exporter:a,extensions:u,object:e};ie.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,ie.report("export-usdz","auto export animations and audio sources");const m=new Array;this.autoExportAnimations&&m.push(...XM(e,l)),u.find(M=>M.extensionName==="Audio")&&this.autoExportAudioSources&&m.push(...QM(e)),a.debug=Jt,a.pruneUnusedNodes=!ZM;const b=qo.instance.objs.map(M=>M.batchedMesh);a.keepObject=M=>{let O=!0;const R=x.getComponent(M,fi);return R&&!R.enabled&&(O=!1),O&&b.includes(M)&&(O=!1),O&&x.getComponentInParent(M,yc)&&(O=!1),O&&x.getComponentInParent(M,Dn)&&(O=!1),Jt&&!O&&console.log("USDZExporter: Discarding object",M),O},a.beforeWritingDocument=()=>{if(A()&&l&&h){const M=l.animatedRoots;for(const O of M){const R=x.getComponentsInChildren(O,Ke).filter(L=>L.enabled),B=x.getComponents(O,Qt).filter(L=>L.enabled&&!L.isTrigger);(R.length>0||B.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.",O)}}};const g=new Array;this.objectToExport&&this.quickLookCompatible&&this.interactive&&this.objectToExport.traverse(M=>{M.visible||g.push(M)});const v=u.find(M=>M.extensionName==="Behaviour");this.interactive&&v&&g.length>0&&v.addBehavior(YM(g));let _=!0;this.quickLookCompatible&&!this.interactive&&(_=!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"),ie.report("export-usdz","Invoking exporter.parse");const S=await a.parse(this.objectToExport,{ar:{anchoring:{type:this.anchoringType},planeAnchoring:{alignment:this.planeAnchoringAlignment}},extensions:u,quickLookCompatible:this.quickLookCompatible,maxTextureSize:this.maxTextureSize,exportInvisible:_}),T=new Blob([S],{type:"model/vnd.usdz+zip"});this.revertWebARSessionRoot(),this.context.time.timeScale=this._previousTimeScale,ie.report("export-usdz","Invoking after-export"),this.dispatchEvent(new CustomEvent("after-export",{detail:p}));for(const M of m)x.destroy(M);return It.Global.Set(r),ie.end("export-usdz"),T}openInQuickLook(e,t){const i=e instanceof Blob?URL.createObjectURL(e):e,n=this.buildQuicklookOverlay();Jt&&console.log("QuickLook Overlay",n);const o=n.callToAction?encodeURIComponent(n.callToAction):"",r=n.checkoutTitle?encodeURIComponent(n.checkoutTitle):"",a=n.checkoutSubtitle?encodeURIComponent(n.checkoutSubtitle):"";this.link.href=i+`#callToAction=${o}&checkoutTitle=${r}&checkoutSubtitle=${a}&callToActionURL=${n.callToActionURL}`,this.lastCallback||(this.lastCallback=this.quicklookCallback.bind(this),this.link.addEventListener("message",this.lastCallback)),this.link.download=t+".usdz",this.link.click()}download(e,t){wp.save(e,t)}static save(e,t){const i=document.createElement("a");i.style.display="none",document.body.appendChild(i),typeof e=="string"?i.href=e:i.href=URL.createObjectURL(e),i.download=t,i.click(),i.remove()}lastCallback;quicklookCallback(e){if(e?.data=="_apple_ar_quicklook_button_tapped"){Jt&&ce("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");Jt&&Se("Quicklook url: "+n),n&&(kn()?globalThis.open(n,"_blank"):console.warn("Quicklook closed: custom redirects require a Needle Engine Pro license: https://needle.tools/pricing",n))}}}}buildQuicklookOverlay(){const e={};return this.customBranding&&Object.assign(e,this.customBranding),kn()||(console.log("Custom Quicklook banner text requires pro license: https://needle.tools/pricing"),e.callToAction="Close",e.checkoutTitle="🌵 Made with Needle",e.checkoutSubtitle="_"),(e.callToAction?.length||e.checkoutTitle?.length||e.checkoutSubtitle?.length)&&(e.callToAction?.length||(e.callToAction="\0"),e.checkoutTitle?.length||(e.checkoutTitle="\0"),e.checkoutSubtitle?.length||(e.checkoutSubtitle="\0")),this.dispatchEvent(new CustomEvent("quicklook-overlay",{detail:e})),e}static invertForwardMatrix=new c.Matrix4().makeRotationY(Math.PI);static invertForwardQuaternion=new c.Quaternion().setFromEuler(new c.Euler(0,Math.PI,0));_rootSessionRootWasAppliedTo=null;_rootPositionBeforeExport=new c.Vector3;_rootRotationBeforeExport=new c.Quaternion;_rootScaleBeforeExport=new c.Vector3;getARScaleAndTarget(){if(!this.objectToExport)return{scale:1,_invertForward:!1,target:this.gameObject,sessionRoot:null};const e=x.findObjectOfType(ou);let t=x.getComponentInParent(this.objectToExport,li);t||(t=x.getComponentInChildren(this.objectToExport,li));let i=1,n=!1;const o=this.objectToExport;return e?i=e.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:e,_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(e),t&&i.quaternion.multiply(wp.invertForwardQuaternion),i.updateMatrix(),i.updateMatrixWorld(!0),n&&o&&i.matrix.premultiply(o)}revertWebARSessionRoot(){if(!this.objectToExport||!this._rootSessionRootWasAppliedTo)return;const e=this._rootSessionRootWasAppliedTo;e.position.copy(this._rootPositionBeforeExport),e.quaternion.copy(this._rootRotationBeforeExport),e.scale.copy(this._rootScaleBeforeExport),e.updateMatrix(),e.updateMatrixWorld(!0),this._rootSessionRootWasAppliedTo=null}createQuicklookButton(){const t=Gs.getOrCreate().createQuicklookButton();return t.parentNode||this.context.menu.appendChild(t),t}};yt([f(c.Object3D)],Kt.prototype,"objectToExport");yt([f()],Kt.prototype,"autoExportAnimations");yt([f()],Kt.prototype,"autoExportAudioSources");yt([f()],Kt.prototype,"exportFileName");yt([f(URL)],Kt.prototype,"customUsdzFile");yt([f(hr)],Kt.prototype,"customBranding");yt([f()],Kt.prototype,"anchoringType");yt([f()],Kt.prototype,"maxTextureSize");yt([f()],Kt.prototype,"planeAnchoringAlignment");yt([f()],Kt.prototype,"interactive");yt([f()],Kt.prototype,"physics");yt([f()],Kt.prototype,"allowCreateQuicklookButton");yt([f()],Kt.prototype,"quickLookCompatible");let En=Kt;var JM=Object.defineProperty,eO=Object.getOwnPropertyDescriptor,fg=(s,e,t,i)=>{for(var n=eO(e,t),o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&JM(e,t,n),n};class Ca extends k{get fog(){return this._fog||(this._fog=new c.Fog(0,0,50)),this._fog}get mode(){return 1}set near(e){this.fog.near=e}get near(){return this.fog.near}set far(e){this.fog.far=e}get far(){return this.fog.far}set color(e){this.fog.color.copy(e)}get color(){return this.fog.color}_fog;onEnable(){this.scene.fog=this.fog}onDisable(){this.scene.fog===this._fog&&(this.scene.fog=null)}}fg([f()],Ca.prototype,"near");fg([f()],Ca.prototype,"far");fg([f(c.Color)],Ca.prototype,"color");var tO=Object.defineProperty,pg=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&tO(e,t,n),n};class dr extends k{objectBounds=!1;color;isGizmo=!0;_gizmoObject=null;_boxHelper=null;onEnable(){this.isGizmo&&!oc||(this._gizmoObject||(this.objectBounds?this._gizmoObject=new c.BoxHelper(this.gameObject,this.color??16776960):(this.objectBounds=!1,this._gizmoObject=nm(this.color??16776960))),this.objectBounds?(this.scene.add(this._gizmoObject),this._boxHelper=this._gizmoObject,this.startCoroutine(this.syncObjectBounds(),pe.OnBeforeRender)):this.gameObject.add(this._gizmoObject))}onDisable(){this._gizmoObject&&this.gameObject.remove(this._gizmoObject)}*syncObjectBounds(){for(;this._boxHelper;)this._boxHelper?.update(),yield}}pg([f()],dr.prototype,"objectBounds");pg([f(c.Color)],dr.prototype,"color");pg([f()],dr.prototype,"isGizmo");var iO=Object.defineProperty,mg=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&iO(e,t,n),n};class Pa extends k{isGizmo=!1;color0;color1;gridHelper;size;divisions;offset;onEnable(){if(this.isGizmo&&!oc)return;const e=this.size,t=this.divisions;this.gridHelper||(this.gridHelper=new c.GridHelper(e,t,this.color0??new c.Color(.4,.4,.4),this.color1??new c.Color(.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)}}mg([f()],Pa.prototype,"isGizmo");mg([f(c.Color)],Pa.prototype,"color0");mg([f(c.Color)],Pa.prototype,"color1");var nO=Object.defineProperty,gg=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&nO(e,t,n),n};class yg extends k{connectedBody;get rigidBody(){return this._rigidBody}_rigidBody=null;onEnable(){this._rigidBody||(this._rigidBody=this.gameObject.getComponent(Ke)),this.rigidBody&&this.connectedBody&&this.startCoroutine(this.create())}*create(){yield,this.rigidBody&&this.connectedBody&&this.activeAndEnabled&&this.createJoint(this.rigidBody,this.connectedBody)}}gg([f(Ke)],yg.prototype,"connectedBody");class _g extends yg{createJoint(e,t){this.context.physics.engine?.addFixedJoint(e,t)}}class kc extends yg{anchor;axis;createJoint(e,t){this.axis&&this.anchor&&this.context.physics.engine?.addHingeJoint(e,t,this.anchor,this.axis)}}gg([f(c.Vector3)],kc.prototype,"anchor");gg([f(c.Vector3)],kc.prototype,"axis");var sO=Object.defineProperty,oO=Object.getOwnPropertyDescriptor,Fn=(s,e,t,i)=>{for(var n=i>1?void 0:i?oO(e,t):e,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&sO(e,t,n),n};function Sf(s){return s*Math.PI/180}const v_=300,ks=w("debuglights");class yi extends k{type=0;range=1;spotAngle=1;innerSpotAngle=1;set color(e){this._color=e,this.light!==void 0&&(this.light.color=e)}get color(){return this.light?this.light.color:this._color}_color=new c.Color(16777215);set shadowNearPlane(e){if(e!==this._shadowNearPlane&&(this._shadowNearPlane=e,this.light?.shadow?.camera!==void 0)){const t=this.light.shadow.camera;t.near=e}}get shadowNearPlane(){return this._shadowNearPlane}_shadowNearPlane=.1;set shadowBias(e){e!==this._shadowBias&&(this._shadowBias=e,this.light?.shadow?.bias!==void 0&&(this.light.shadow.bias=e,this.light.shadow.needsUpdate=!0))}get shadowBias(){return this._shadowBias}_shadowBias=0;set shadowNormalBias(e){e!==this._shadowNormalBias&&(this._shadowNormalBias=e,this.light?.shadow?.normalBias!==void 0&&(this.light.shadow.normalBias=e,this.light.shadow.needsUpdate=!0))}get shadowNormalBias(){return this._shadowNormalBias}_shadowNormalBias=0;_overrideShadowBiasSettings=!1;set shadows(e){this._shadows=e,this.light&&(this.light.castShadow=e!==0,this.updateShadowSoftHard())}get shadows(){return this._shadows}_shadows=1;lightmapBakeType=4;set intensity(e){if(this._intensity=e,this.light){let t=1;if(this.context.isInXR&&this._webARRoot){const i=this._webARRoot?.arScale;typeof i=="number"&&i>0&&(t/=i)}this.light.intensity=e*t}ks&&console.log("Set light intensity to "+this._intensity,e,this)}get intensity(){return this._intensity}_intensity=-1;get shadowDistance(){const e=this.light;return e?.shadow?e.shadow.camera.far:-1}set shadowDistance(e){this._shadowDistance=e;const t=this.light;if(t?.shadow){const i=t.shadow.camera;i.far=e,i.updateProjectionMatrix()}}_shadowDistance;shadowWidth;shadowHeight;get shadowResolution(){const e=this.light;return e?.shadow?e.shadow.mapSize.x:-1}set shadowResolution(e){if(e===this._shadowResolution)return;this._shadowResolution=e;const t=this.light;t?.shadow&&(t.shadow.mapSize.set(e,e),t.shadow.needsUpdate=!0)}_shadowResolution=void 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}light=void 0;getWorldPosition(e){return this.light?this.type===1?this.light.getWorldPosition(e).multiplyScalar(1):this.light.getWorldPosition(e):e}awake(){this.color=new c.Color(this.color??16777215),ks&&console.log(this.name,this)}onEnable(){ks&&console.log("ENABLE LIGHT",this.name),this.createLight(),!this.isBaked&&(this.light&&(this.light.visible=!0,this.light.intensity=this._intensity,ks&&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(),pe.LateUpdate))}onDisable(){ks&&console.log("DISABLE LIGHT",this.name),this.light&&(this.selfIsLight?this.light.intensity=0:this.light.visible=!1)}_webXRStartedListener;_webXREndedListener;_webARRoot;onEnterXR(e){this._webARRoot=x.getComponentInParent(this.gameObject,li)??void 0}onLeaveXR(e){}createLight(){const e=this.selfIsLight;if(e&&!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 t=new c.DirectionalLight(this.color,this.intensity*Math.PI);if(t.position.set(0,0,-v_*.5).applyQuaternion(this.gameObject.quaternion),this.gameObject.add(t.target),zo(t.target,0,0,0),this.light=t,this.gameObject.position.set(0,0,0),this.gameObject.rotation.set(0,0,0),ks){const r=new c.DirectionalLightHelper(this.light,.2,this.color);this.context.scene.add(r)}break;case 0:const i=new c.SpotLight(this.color,this.intensity*Math.PI,this.range,Sf(this.spotAngle/2),1-Sf(this.innerSpotAngle/2)/Sf(this.spotAngle/2),2);i.position.set(0,0,0),i.rotation.set(0,0,0),this.light=i;const n=i.target;i.add(n),n.position.set(0,0,this.range),n.rotation.set(0,0,0);break;case 2:const o=new c.PointLight(this.color,this.intensity*Math.PI,this.range);this.light=o;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),ks&&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 t=this.light.shadow.camera;if(t.near=this.shadowNearPlane,this._shadowDistance!==void 0&&typeof this._shadowDistance=="number"?t.far=this._shadowDistance:t.far=v_*Math.abs(this.gameObject.scale.z),this.gameObject.scale.set(1,1,1),this.shadowWidth!==void 0)t.left=-this.shadowWidth/2,t.right=this.shadowWidth/2;else{const i=this.gameObject.scale.x;t.left*=i,t.right*=i}if(this.shadowHeight!==void 0)t.top=this.shadowHeight/2,t.bottom=-this.shadowHeight/2;else{const i=this.gameObject.scale.y;t.top*=i,t.bottom*=i}this.light.shadow.needsUpdate=!0,ks&&this.context.scene.add(new c.CameraHelper(t))}this.isBaked?this.light.removeFromParent():e||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}}static allowChangingRendererShadowMapType=!0;updateShadowSoftHard(){this.light&&this.light.shadow&&(this.shadows===2||(this.light.shadow.radius=1,this.light.shadow.blurSamples=1))}setDirectionalLight(e){e.add(e.target),e.target.position.set(0,0,-1)}}Fn([f()],yi.prototype,"type",2);Fn([f(c.Color)],yi.prototype,"color",1);Fn([f()],yi.prototype,"shadowNearPlane",1);Fn([f()],yi.prototype,"shadowBias",1);Fn([f()],yi.prototype,"shadowNormalBias",1);Fn([f()],yi.prototype,"shadows",1);Fn([f()],yi.prototype,"lightmapBakeType",2);Fn([f()],yi.prototype,"intensity",1);Fn([f()],yi.prototype,"shadowDistance",1);Fn([f()],yi.prototype,"shadowResolution",1);new c.Vector3(0,0,0);var rO=Object.defineProperty,Rc=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&rO(e,t,n),n};const Cf=w("debuglods"),aO=w("nolods");class Ma{screenRelativeTransitionHeight;distance;renderers}Rc([f()],Ma.prototype,"screenRelativeTransitionHeight");Rc([f()],Ma.prototype,"distance");Rc([f(fi)],Ma.prototype,"renderers");class lO{model;get renderers(){return this.model.renderers}constructor(e){this.model=e}}class Ec extends k{fadeMode=0;localReferencePoint=void 0;lodCount=0;size=0;animateCrossFading=!1;lodModels;_lods=[];_settings=[];_lodsHandler;start(){if(Cf&&console.log("LODGROUP",this.name,this.lodModels,this),!aO&&!this._lodsHandler&&this.gameObject&&this.lodModels&&Array.isArray(this.lodModels)){const e=[];for(const i of this.lodModels){const n=new lO(i);this._lods.push(n);for(const o of n.renderers)e.includes(o)||e.push(o)}this._lodsHandler=new Array;for(let i=0;i<e.length;i++){const n=new c.LOD;this._lodsHandler.push(n),this.gameObject.add(n)}const t=new c.Object3D;t.name="Cull "+this.name;for(let i=0;i<e.length;i++){const n=e[i],o=this._lodsHandler[i],r=n.gameObject;Cf&&console.log(i,r.name);for(const a of this._lods){const l=a.model.distance;let h=null;if(a.renderers.includes(n)?h=r:h=t,h.type==="Group"){console.warn(`LODGroup ${this.name}: Group or MultiMaterial object's are not supported as LOD object: ${h.name}`);continue}Cf&&console.log("LEVEL",h.name,l),o.autoUpdate=!1,this.onAddLodLevel(o,h,a.model.distance)}}}}onAfterRender(){if(!this.gameObject||!this._lodsHandler)return;const e=this.context.mainCamera;if(e)for(const t of this._lodsHandler){t.update(e);const i=t.getCurrentLevel(),n=t.levels[i];t.layers.mask=n.object.layers.mask}}onAddLodLevel(e,t,i){if(t===this.gameObject){console.warn("LODGroup component must be on parent object and not mesh directly at the moment",t.name,t);return}e.addLevel(t,i*this._distanceFactor,.01);const n={lod:e,levelIndex:e.levels.length-1,distance:i};this._settings.push(n)}_distanceFactor=1;distanceFactor(e){if(e!==this._distanceFactor){this._distanceFactor=e;for(const t of this._settings){const i=t.lod.levels[t.levelIndex];i.distance=t.distance*e}}}}Rc([f(c.Vector3)],Ec.prototype,"localReferencePoint");Rc([f(Ma)],Ec.prototype,"lodModels");var cO=Object.defineProperty,hO=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&cO(e,t,n),n};const wh=w("debugnestedgltf");class au extends k{filePath;loadAssetInParent=!0;_isLoadingOrDoneLoading=!1;listenToProgress(e){this.filePath?.beginListenDownload(e)}preload(){this.filePath?.preload()}async start(){if(this._isLoadingOrDoneLoading)return;wh&&console.log(this,this.guid);const e=this.gameObject.parent;if(e){this._isLoadingOrDoneLoading=!0;const t=new sn;t.idProvider=new ft(this.hash(this.guid)),t.parent=this.loadAssetInParent!==!1?e:this.gameObject,this.gameObject.updateMatrix();const i=this.gameObject.matrix;wh&&console.log("Load nested:",this.filePath?.url??this.filePath,this.gameObject.position);const n=await this.filePath?.instantiate?.call(this.filePath,t);wh&&console.log("Nested loaded:",this.filePath?.url??this.filePath,n),n&&this.loadAssetInParent!==!1&&(n.matrixAutoUpdate=!1,n.matrix.identity(),n.applyMatrix4(i),n.matrixAutoUpdate=!0,n.layers.disableAll(),n.layers.set(this.layer),this.dispatchEvent(new CustomEvent("loaded",{detail:{instance:n,assetReference:this.filePath}}))),wh&&console.log("Nested loading done:",this.filePath?.url??this.filePath,n)}}onDestroy(){this.filePath?.unload()}hash(e){let t=0;for(let i=0;i<e.length;i++)t=e.charCodeAt(i)+((t<<5)-t);return t}}hO([f(Y)],au.prototype,"filePath");var dO=Object.defineProperty,bg=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&dO(e,t,n),n};const uO=w("debugnet"),lu=class xp extends k{url=null;urlParameterName=null;localhost=null;awake(){uO&&console.log(this),this.context.connection.registerProvider(this)}getWebsocketUrl(){let e=this.url?xp.GetUrl(this.url,this.localhost):null;if(this.urlParameterName){const o=w(this.urlParameterName);o&&typeof o=="string"&&(e=o)}if(!e)return null;const i=new RegExp("(((https?)|(?<socket_prefix>wss?))://)?(www.)?(?<url>.+)","gm").exec(e);return i?.groups?i?.groups.socket_prefix?e:"wss://"+i?.groups.url:null}static GetUrl(e,t){let i=e;const n=xp.IsLocalNetwork()&&t;if(n&&(i=t),e?.startsWith("/")){const o=n?i:window.location.origin;o?.endsWith("/")&&e.startsWith("/")&&(e=e.substring(1)),i=o+e}return i}static IsLocalNetwork(e=window.location.hostname){return Bt(e)}};bg([f()],lu.prototype,"url");bg([f()],lu.prototype,"urlParameterName");bg([f()],lu.prototype,"localhost");let vg=lu;var fO=Object.defineProperty,cu=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&fO(e,t,n),n};class ur extends k{referenceSpace;from;affectPosition=!1;affectRotation=!1;alignLookDirection=!1;levelLookDirection=!1;levelPosition=!1;positionOffset=new c.Vector3(0,0,0);rotationOffset=new c.Vector3(0,0,0);offset=new c.Vector3(0,0,0);update(){if(!this.from)return;var e=X(this.from),t=ue(this.from);this.offset.copy(this.positionOffset);const i=this.offset.length();if(this.referenceSpace&&this.offset.transformDirection(this.referenceSpace.matrixWorld).multiplyScalar(i),e.add(this.offset),this.levelPosition&&this.referenceSpace){const a=new c.Plane(this.gameObject.up,0),l=X(this.referenceSpace);a.setFromNormalAndCoplanarPoint(this.gameObject.up,l);const h=new c.Vector3(0,0,0);a.projectPoint(e,h),e.copy(h)}this.affectPosition&&Ye(this.gameObject,e);const n=new c.Euler(this.rotationOffset.x,this.rotationOffset.y,this.rotationOffset.z),o=new c.Quaternion().setFromEuler(n);this.affectRotation&&Di(this.gameObject,t.multiply(o));const r=new c.Vector3;this.from.getWorldDirection(r).multiplyScalar(50),this.levelLookDirection&&(r.y=0),this.alignLookDirection&&this.gameObject.lookAt(r)}}cu([f(x)],ur.prototype,"referenceSpace");cu([f(x)],ur.prototype,"from");cu([f(c.Vector3)],ur.prototype,"positionOffset");cu([f(c.Vector3)],ur.prototype,"rotationOffset");var pO=Object.defineProperty,ro=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&pO(e,t,n),n};class Gt{time=0;value=0;inTangent=1/0;inWeight;outTangent=1/0;outWeight;weightedMode;constructor(e=0,t=0){this.time=e,this.value=t}}ro([f()],Gt.prototype,"time");ro([f()],Gt.prototype,"value");ro([f()],Gt.prototype,"inTangent");ro([f()],Gt.prototype,"inWeight");ro([f()],Gt.prototype,"outTangent");ro([f()],Gt.prototype,"outWeight");ro([f()],Gt.prototype,"weightedMode");const Kv=class pl{static linearFromTo(e,t,i){const n=new pl,o=new Gt;o.time=0,o.value=e;const r=new Gt;return r.time=i,r.value=t,n.keys.push(o,r),n}static constant(e){const t=new pl,i=new Gt;return i.time=0,i.value=e,t.keys.push(i),t}keys=[];clone(){const e=new pl;return e.keys=this.keys?.map(t=>{const i=new Gt;return i.time=t.time,i.value=t.value,i.inTangent=t.inTangent,i.inWeight=t.inWeight,i.outTangent=t.outTangent,i.outWeight=t.outWeight,i.weightedMode=t.weightedMode,i})||[],e}get duration(){return!this.keys||this.keys.length==0?0:this.keys[this.keys.length-1].time}evaluate(e){if(!this.keys||this.keys.length==0)return 0;if(this.keys.length===1)return this.keys[0].value;if(this.keys[0].time>=e)return this.keys[0].value;for(let t=0;t<this.keys.length;t++){const i=this.keys[t];if(i.time<=e)if(t+1<this.keys.length){const o=this.keys[t+1];if(o.time<e)continue;return!isFinite(i.outTangent)||!isFinite(o.inTangent)?i.value:pl.interpolateValue(e,i,o)}else return i.value}return this.keys[this.keys.length-1].value}static interpolateValue(e,t,i){const n=t.time,o=t.value,r=t.outTangent,a=i.time,l=i.value,h=i.inTangent,d=a-n,u=d*d,p=u*d,m=((r+h)*d-2*(l-o))/p,y=(3*(l-o)-(h+2*r)*d)/u,b=r,g=o,v=e-n,_=v*v,S=_*v;return m*S+y*_+b*v+g}};ro([f(Gt)],Kv.prototype,"keys");let Tc=Kv;var mO=Object.defineProperty,C=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&mO(e,t,n),n};const xh=w("debugparticles");var Kn=(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))(Kn||{});class fr{alphaKeys=[];colorKeys=[];get duration(){return 1}evaluate(e,t){let i,n=0,o=null,r=0;for(let a=0;a<this.alphaKeys.length;a++){const l=this.alphaKeys[a];(l.time<e||!i)&&(i=l,n=a)}for(let a=0;a<this.colorKeys.length;a++){const l=this.colorKeys[a];(l.time<e||!o)&&(o=l,r=a)}if(o)if(r+1<this.colorKeys.length){const l=this.colorKeys[r+1],h=I.remap(e,o.time,l.time,0,1);t.r=I.lerp(o.color.r,l.color.r,h),t.g=I.lerp(o.color.g,l.color.g,h),t.b=I.lerp(o.color.b,l.color.b,h)}else t.r=o.color.r,t.g=o.color.g,t.b=o.color.b;if(i)if(n+1<this.alphaKeys.length){const l=this.alphaKeys[n+1],h=I.remap(e,i.time,l.time,0,1);t.alpha=I.lerp(i.alpha,l.alpha,h)}else t.alpha=i.alpha;return t}}C([f()],fr.prototype,"alphaKeys");C([f()],fr.prototype,"colorKeys");var Hl=(s=>(s[s.Local=0]="Local",s[s.World=1]="World",s[s.Custom=2]="Custom",s))(Hl||{}),vd=(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))(vd||{});const gs=class ml{static constant(e){const t=new ml;return t.setConstant(e),t}static betweenTwoConstants(e,t){const i=new ml;return i.setMinMaxConstant(e,t),i}static curve(e,t=1){const i=new ml;return i.setCurve(e,t),i}setConstant(e){this.mode=0,this.constant=e}setMinMaxConstant(e,t){this.mode=3,this.constantMin=e,this.constantMax=t}setCurve(e,t=1){this.mode=1,this.curve=e,this.curveMultiplier=t}mode="Constant";constant;constantMin;constantMax;curve;curveMin;curveMax;curveMultiplier;clone(){const e=new ml;return e.mode=this.mode,e.constant=this.constant,e.constantMin=this.constantMin,e.constantMax=this.constantMax,e.curve=this.curve?.clone(),e.curveMin=this.curveMin?.clone(),e.curveMax=this.curveMax?.clone(),e.curveMultiplier=this.curveMultiplier,e}evaluate(e,t){const i=t===void 0?Math.random():t;switch(this.mode){case 0:case"Constant":return this.constant;case 1:case"Curve":return e=I.clamp01(e),this.curve.evaluate(e)*this.curveMultiplier;case 2:case"TwoCurves":const n=e*this.curveMin.duration,o=e*this.curveMax.duration;return I.lerp(this.curveMin.evaluate(n),this.curveMax.evaluate(o),i%1)*this.curveMultiplier;case 3:case"TwoConstants":return I.lerp(this.constantMin,this.constantMax,i%1);default:this.curveMax.evaluate(e)*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(e){if(!e)return 0;let t=Number.MIN_VALUE;for(let i=0;i<e.keys.length;i++){const n=e.keys[i];n.value>t&&(t=n.value)}return t}};C([f()],gs.prototype,"mode");C([f()],gs.prototype,"constant");C([f()],gs.prototype,"constantMin");C([f()],gs.prototype,"constantMax");C([f(Tc)],gs.prototype,"curve");C([f(Tc)],gs.prototype,"curveMin");C([f(Tc)],gs.prototype,"curveMax");C([f()],gs.prototype,"curveMultiplier");let H=gs;const ao=class dt{static constant(e){const t=new dt;return t.constant(e),t}static betweenTwoColors(e,t){const i=new dt;return i.betweenTwoColors(e,t),i}constant(e){return this.mode=0,this.color=e,this}betweenTwoColors(e,t){return this.mode=2,this.colorMin=e,this.colorMax=t,this}mode=0;color;colorMin;colorMax;gradient;gradientMin;gradientMax;static _temp=new Z(0,0,0,1);static _temp2=new Z(0,0,0,1);evaluate(e,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(e,dt._temp),dt._temp;case 2:case"TwoColors":return dt._temp.lerpColors(this.colorMin,this.colorMax,i);case 3:case"TwoGradients":return this.gradientMin.evaluate(e,dt._temp),this.gradientMax.evaluate(e,dt._temp2),dt._temp.lerp(dt._temp2,i);case 4:case"RandomColor":const o=Math.random();return this.gradientMin.evaluate(e,dt._temp),this.gradientMax.evaluate(e,dt._temp2),dt._temp.lerp(dt._temp2,o)}return dt._temp.set(16777215),dt._temp.alpha=1,dt._temp}};C([f()],ao.prototype,"mode");C([f(Z)],ao.prototype,"color");C([f(Z)],ao.prototype,"colorMin");C([f(Z)],ao.prototype,"colorMax");C([f(fr)],ao.prototype,"gradient");C([f(fr)],ao.prototype,"gradientMin");C([f(fr)],ao.prototype,"gradientMax");let pr=ao;var Sp=(s=>(s[s.Hierarchy=0]="Hierarchy",s[s.Local=1]="Local",s[s.Shape=2]="Shape",s))(Sp||{});class Pt{cullingMode;duration;emitterVelocityMode;flipRotation;gravityModifier;gravityModifierMultiplier;loop;maxParticles;playOnAwake;prewarm;ringBufferLoopRange;ringBufferMode;scalingMode;simulationSpace;simulationSpeed;startColor;startDelay;startDelayMultiplier;startLifetime;startLifetimeMultiplier;startRotation;startRotationMultiplier;startRotation3D;startRotationX;startRotationXMultiplier;startRotationY;startRotationYMultiplier;startRotationZ;startRotationZMultiplier;startSize;startSize3D;startSizeMultiplier;startSizeX;startSizeXMultiplier;startSizeY;startSizeYMultiplier;startSizeZ;startSizeZMultiplier;startSpeed;startSpeedMultiplier;stopAction;useUnscaledTime}C([f(H)],Pt.prototype,"gravityModifier");C([f(pr)],Pt.prototype,"startColor");C([f(H)],Pt.prototype,"startDelay");C([f(H)],Pt.prototype,"startLifetime");C([f(H)],Pt.prototype,"startRotation");C([f(H)],Pt.prototype,"startRotationX");C([f(H)],Pt.prototype,"startRotationY");C([f(H)],Pt.prototype,"startRotationZ");C([f(H)],Pt.prototype,"startSize");C([f(H)],Pt.prototype,"startSizeX");C([f(H)],Pt.prototype,"startSizeY");C([f(H)],Pt.prototype,"startSizeZ");C([f(H)],Pt.prototype,"startSpeed");class wd{cycleCount;maxCount;minCount;probability;repeatInterval;time;count;_performed=0;reset(){this._performed=0}run(e){if(e<=this.time)return 0;let t=0;if(this.cycleCount===0||this._performed<this.cycleCount){const i=this.time+this.repeatInterval*this._performed;if(e>=i&&(this._performed+=1,Math.random()<this.probability))switch(this.count.mode){case 0:t=this.count.constant;break;case 3:t=I.lerp(this.count.constantMin,this.count.constantMax,Math.random());break;case 1:t=this.count.curve.evaluate(Math.random());break;case 2:const n=Math.random();t=I.lerp(this.count.curveMin.evaluate(n),this.count.curveMax.evaluate(n),Math.random());break}}return t}}class ys{enabled;get burstCount(){return this.bursts?.length??0}bursts;rateOverTime;rateOverTimeMultiplier;rateOverDistance;rateOverDistanceMultiplier;system;reset(){this.bursts?.forEach(e=>e.reset())}getBurst(){let e=0;if(this.burstCount>0)for(let t=0;t<this.burstCount;t++){const i=this.bursts[t];this.system.main.loop&&i.time>=this.system.time&&i.reset(),e+=Math.round(i.run(this.system.time))}return e}}C([f()],ys.prototype,"enabled");C([f()],ys.prototype,"bursts");C([f(H)],ys.prototype,"rateOverTime");C([f()],ys.prototype,"rateOverTimeMultiplier");C([f(H)],ys.prototype,"rateOverDistance");C([f()],ys.prototype,"rateOverDistanceMultiplier");class hu{enabled;color}C([f(pr)],hu.prototype,"color");class mr{enabled;separateAxes;size;sizeMultiplier;x;xMultiplier;y;yMultiplier;z;zMultiplier;_time=0;_temp=new c.Vector3;evaluate(e,t,i){if(t||(t=this._temp),!this.enabled)return t.x=t.y=t.z=1,t;if(this.separateAxes)t.x=this.x.evaluate(e,i)*this.xMultiplier,t.y=this.y.evaluate(e,i)*this.yMultiplier,t.z=this.z.evaluate(e,i)*this.zMultiplier;else{const n=this.size.evaluate(e,i)*this.sizeMultiplier;t.x=n}return t}}C([f(H)],mr.prototype,"size");C([f(H)],mr.prototype,"x");C([f(H)],mr.prototype,"y");C([f(H)],mr.prototype,"z");const $e=class gl{get type(){return vd[this.shapeType]}initialize(e){this.onInitialize(e),e.position.x=this._vector.x,e.position.y=this._vector.y,e.position.z=this._vector.z}toJSON(){return this}clone(){return new gl}shapeType=5;enabled=!0;alignToDirection=!1;angle=0;arc=360;arcSpread;arcSpeedMultiplier;arcMode;boxThickness;position;rotation;_rotation=new c.Euler;scale;radius;radiusThickness;sphericalDirectionAmount;randomDirectionAmount;randomPositionAmount;meshShapeType;meshRenderer;_meshObj;_meshGeometry;setMesh(e){this.meshRenderer=e,e?(this._meshObj=e.sharedMeshes[Math.floor(Math.random()*e.sharedMeshes.length)],this._meshGeometry=this._meshObj.geometry):(this._meshObj=void 0,this._meshGeometry=void 0)}system;_space;_worldSpaceMatrix=new c.Matrix4;_worldSpaceMatrixInverse=new c.Matrix4;constructor(){xh&&console.log(this)}update(e,t){}onUpdate(e,t,i,n){this.system=e,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(e){const t=this.rotation.x!==0||this.rotation.y!==0||this.rotation.z!==0;return t&&(this._rotation.x=I.toRadians(this.rotation.x),this._rotation.y=I.toRadians(this.rotation.y),this._rotation.z=I.toRadians(this.rotation.z),this._rotation.order="ZYX",e.applyEuler(this._rotation)),t}_vector=new c.Vector3(0,0,0);_temp=new c.Vector3(0,0,0);_triangle=new c.Triangle;onInitialize(e){this._vector.set(0,0,0),e.mesh=void 0,e.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:xh&&j.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=e.mesh=this._meshObj,a=e.mesh_geometry=this._meshGeometry;if(r&&a)switch(this.meshShapeType){case 0:{const l=a.getAttribute("position"),h=Math.floor(Math.random()*l.count);this._vector.fromBufferAttribute(l,h),this._vector.applyMatrix4(r.matrixWorld),e.mesh_normal=h}break;case 1:break;case 2:{const l=a.index;if(l){let h=Math.random(),d=Math.random();h+d>1&&(h=1-h,d=1-d);const u=Math.floor(Math.random()*(l.count/3));let p=u*3,m=u*3+1,y=u*3+2;p=l.getX(p),m=l.getX(m),y=l.getX(y);const b=a.getAttribute("position");this._triangle.a.fromBufferAttribute(b,p),this._triangle.b.fromBufferAttribute(b,m),this._triangle.c.fromBufferAttribute(b,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),e.mesh_normal=u}}break}break;default:this._vector.set(0,0,0),A()&&!globalThis.__particlesystem_shapetype_unsupported&&(console.warn("ParticleSystem ShapeType is not supported:",vd[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)),xh&&j.DrawSphere(this._vector,.03,16711680,.5,!0)}_dir=new c.Vector3;getDirection(e,t){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 i=t.x,n=t.y,o=t.z;this._dir.set(i,n,o),this.system?.worldspace?this._dir.sub(this.system.worldPos):this._dir.sub(this.position);break;case 13:const r=e.mesh,a=e.mesh_geometry;if(r&&a)switch(this.meshShapeType){case 0:{const l=a.getAttribute("normal"),h=e.mesh_normal;this._dir.fromBufferAttribute(l,h)}break;case 1:break;case 2:{const l=a.index;if(l){const h=e.mesh_normal,d=l.getX(h*3),u=l.getX(h*3+1),p=l.getX(h*3+2),m=a.getAttribute("position"),y=V(),b=V(),g=V();y.fromBufferAttribute(m,d),b.fromBufferAttribute(m,u),g.fromBufferAttribute(m,p),y.sub(b),g.sub(b),y.cross(g),this._dir.copy(y).multiplyScalar(-1);const v=ue(r);this._dir.applyQuaternion(v)}}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),xh&&(j.DrawSphere(t,.01,8925952,.5,!0),j.DrawDirection(t,this._dir,8925952,.5,!0)),this._dir}static _randomQuat=new c.Quaternion;static _tempVec=new c.Vector3;randomizePosition(e,t){if(t<=0)return;const i=gl._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,e.add(i)}randomizeDirection(e,t){if(t===0)return;const i=gl._randomQuat,n=gl._tempVec;n.set(Math.random()-.5,Math.random()-.5,Math.random()-.5).normalize(),i.setFromAxisAngle(n,t*Math.random()*Math.PI),e.applyQuaternion(i)}spherizeDirection(e,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),a=Math.cos(n),l=new c.Vector3(o,r,a);e.lerp(l,t)}randomSpherePoint(e,t,i,n,o){const r=Math.random(),a=Math.random(),l=2*Math.PI*r*(n/360),h=Math.acos(2*a-1),d=I.lerp(1,1-Math.pow(1-Math.random(),Math.PI),i)*t,u=e.x+this.scale.x*(-d*Math.sin(h)*Math.cos(l)),p=e.y+this.scale.y*(d*Math.sin(h)*Math.sin(l)),m=e.z+this.scale.z*(d*Math.cos(h));o.x=u,o.y=p,o.z=m}randomCirclePoint(e,t,i,n,o){const r=Math.random(),a=2*Math.PI*r*(n/360),l=I.lerp(1,1-Math.pow(1-Math.random(),Math.PI),i)*t,h=e.x+this.scale.x*l*Math.cos(a),d=e.y+this.scale.y*l*Math.sin(a),u=e.z;o.x=h,o.y=d,o.z=u}_loopTime=0;_loopDirection=1;randomConePoint(e,t,i,n,o,r,a){let l=0,h=0;switch(r){case 0:l=Math.random(),h=Math.random();break;case 2:this._loopTime>1&&(this._loopDirection=-1),this._loopTime<0&&(this._loopDirection=1);case 1:l=.5,h=Math.random(),this._loopTime+=this.system.deltaTime*this._loopDirection;break}let d=2*Math.PI*l*(o/360);switch(r){case 2:case 1:d+=Math.PI+.5,d+=this._loopTime*Math.PI*2,d%=I.toRadians(o);break}const u=Math.acos(2*h-1),p=I.lerp(1,1-Math.pow(1-Math.random(),Math.PI),n)*i,m=e.x+-p*Math.sin(u)*Math.cos(d),y=e.y+p*Math.sin(u)*Math.sin(d),b=e.z;a.x=m*this.scale.x,a.y=y*this.scale.y,a.z=b*this.scale.z}};C([f()],$e.prototype,"shapeType");C([f()],$e.prototype,"enabled");C([f()],$e.prototype,"alignToDirection");C([f()],$e.prototype,"angle");C([f()],$e.prototype,"arc");C([f()],$e.prototype,"arcSpread");C([f()],$e.prototype,"arcSpeedMultiplier");C([f()],$e.prototype,"arcMode");C([f(c.Vector3)],$e.prototype,"boxThickness");C([f(c.Vector3)],$e.prototype,"position");C([f(c.Vector3)],$e.prototype,"rotation");C([f(c.Vector3)],$e.prototype,"scale");C([f()],$e.prototype,"radius");C([f()],$e.prototype,"radiusThickness");C([f()],$e.prototype,"sphericalDirectionAmount");C([f()],$e.prototype,"randomDirectionAmount");C([f()],$e.prototype,"randomPositionAmount");C([f()],$e.prototype,"meshShapeType");C([f(bc)],$e.prototype,"meshRenderer");let wg=$e;class fe{damping;enabled;frequency;octaveCount;octaveMultiplier;octaveScale;positionAmount;quality;remap;remapEnabled;remapMultiplier;remapX;remapXMultiplier;remapY;remapYMultiplier;remapZ;remapZMultiplier;scrollSpeedMultiplier;separateAxes;strengthMultiplier;strengthX;strengthXMultiplier;strengthY;strengthYMultiplier;strengthZ;strengthZMultiplier;_noise;_time=0;update(e){this._time+=e.time.deltaTime*this.scrollSpeedMultiplier}_temp=new c.Vector3;apply(e,t,i,n,o,r){if(!this.enabled)return;this._noise||(this._noise=se.createNoise4D(()=>0));const a=this._temp.set(t.x,t.y,t.z).multiplyScalar(this.frequency),l=this._noise(a.x,a.y,a.z,this._time),h=this._noise(a.x,a.y,a.z,this._time+1e3*this.frequency),d=this._noise(a.x,a.y,a.z,this._time+2e3*this.frequency);this._temp.set(l,h,d).normalize();const u=o/r;let p=this.positionAmount.evaluate(u);this.separateAxes?(this._temp.x*=p*this.strengthXMultiplier,this._temp.y*=p*this.strengthYMultiplier,this._temp.z*=p*this.strengthZMultiplier):(this.strengthX&&(p*=this.strengthX.evaluate(u)*1.5),this._temp.multiplyScalar(p)),i.x+=this._temp.x,i.y+=this._temp.y,i.z+=this._temp.z}}C([f()],fe.prototype,"damping");C([f()],fe.prototype,"enabled");C([f()],fe.prototype,"frequency");C([f()],fe.prototype,"octaveCount");C([f()],fe.prototype,"octaveMultiplier");C([f()],fe.prototype,"octaveScale");C([f(H)],fe.prototype,"positionAmount");C([f()],fe.prototype,"quality");C([f(H)],fe.prototype,"remap");C([f()],fe.prototype,"remapEnabled");C([f()],fe.prototype,"remapMultiplier");C([f(H)],fe.prototype,"remapX");C([f()],fe.prototype,"remapXMultiplier");C([f(H)],fe.prototype,"remapY");C([f()],fe.prototype,"remapYMultiplier");C([f(H)],fe.prototype,"remapZ");C([f()],fe.prototype,"remapZMultiplier");C([f()],fe.prototype,"scrollSpeedMultiplier");C([f()],fe.prototype,"separateAxes");C([f()],fe.prototype,"strengthMultiplier");C([f(H)],fe.prototype,"strengthX");C([f()],fe.prototype,"strengthXMultiplier");C([f(H)],fe.prototype,"strengthY");C([f()],fe.prototype,"strengthYMultiplier");C([f(H)],fe.prototype,"strengthZ");C([f()],fe.prototype,"strengthZMultiplier");class Re{enabled;attachRibbonToTransform=!1;colorOverLifetime;colorOverTrail;dieWithParticles=!0;inheritParticleColor=!0;lifetime;lifetimeMultiplier;minVertexDistance=.2;mode=0;ratio=1;ribbonCount=1;shadowBias=0;sizeAffectsLifetime=!1;sizeAffectsWidth=!1;splitSubEmitterRibbons=!1;textureMode=0;widthOverTrail;widthOverTrailMultiplier;worldSpace=!1;getWidth(e,t,i,n){const o=this.widthOverTrail.evaluate(i,n);return e*=o,e}getColor(e,t,i){const n=this.colorOverTrail.evaluate(i),o=this.colorOverLifetime.evaluate(t);e.x*=n.r*o.r,e.y*=n.g*o.g,e.z*=n.b*o.b,"alpha"in n&&"alpha"in o&&(e.w*=n.alpha*o.alpha)}}C([f()],Re.prototype,"enabled");C([f()],Re.prototype,"attachRibbonToTransform");C([f(pr)],Re.prototype,"colorOverLifetime");C([f(pr)],Re.prototype,"colorOverTrail");C([f()],Re.prototype,"dieWithParticles");C([f()],Re.prototype,"inheritParticleColor");C([f(H)],Re.prototype,"lifetime");C([f()],Re.prototype,"lifetimeMultiplier");C([f()],Re.prototype,"minVertexDistance");C([f()],Re.prototype,"mode");C([f()],Re.prototype,"ratio");C([f()],Re.prototype,"ribbonCount");C([f()],Re.prototype,"shadowBias");C([f()],Re.prototype,"sizeAffectsLifetime");C([f()],Re.prototype,"sizeAffectsWidth");C([f()],Re.prototype,"splitSubEmitterRibbons");C([f()],Re.prototype,"textureMode");C([f(H)],Re.prototype,"widthOverTrail");C([f()],Re.prototype,"widthOverTrailMultiplier");C([f()],Re.prototype,"worldSpace");class Le{enabled;space=0;orbitalX;orbitalY;orbitalZ;orbitalXMultiplier;orbitalYMultiplier;orbitalZMultiplier;orbitalOffsetX;orbitalOffsetY;orbitalOffsetZ;speedModifier;speedModifierMultiplier;x;xMultiplier;y;yMultiplier;z;zMultiplier;_system;update(e){this._system=e}_temp=new c.Vector3;_temp2=new c.Vector3;_temp3=new c.Vector3;_hasOrbital=!1;_index=0;_orbitalMatrix=new c.Matrix4;init(e){this._index==0&&(e.debug=!0),this._index+=1,e.orbitx=this.orbitalX.evaluate(Math.random()),e.orbity=this.orbitalY.evaluate(Math.random()),e.orbitz=this.orbitalZ.evaluate(Math.random()),this._hasOrbital=e.orbitx!=0||e.orbity!=0||e.orbitz!=0}apply(e,t,i,n,o,r,a){if(!this.enabled)return;const l=r/a,h=this.speedModifier.evaluate(l)*this.speedModifierMultiplier,d=this.x.evaluate(l),u=this.y.evaluate(l),p=this.z.evaluate(l);if(this._temp.set(-d,u,p),this._system&&this._system.main.simulationSpace===1&&this._temp.applyQuaternion(this._system.worldQuaternion),this._hasOrbital&&this._system?.worldPos){const y=this._temp2.set(i.x,i.y,i.z),b=this.orbitalXMultiplier,g=this.orbitalYMultiplier,v=this.orbitalZMultiplier,_=h*Math.PI*2*10,S=Math.cos(_*b),T=Math.sin(_*b),M=Math.cos(_*g),O=Math.sin(_*g),R=Math.cos(_*v),B=Math.sin(_*v),L=y.x*(M*R)+y.y*(M*B)+y.z*-O,N=y.x*(T*O*R-S*B)+y.y*(T*O*B+S*R)+y.z*(T*M),$=y.x*(S*O*R+T*B)+y.y*(S*O*B-T*R)+y.z*(S*M),E=this._temp3.set(y.x-L,y.y-N,y.z-$);E.normalize(),E.multiplyScalar(.2/o*Math.max(this.orbitalXMultiplier,this.orbitalYMultiplier,this.orbitalZMultiplier)),n.x+=E.x,n.y+=E.y,n.z+=E.z}n.x+=this._temp.x,n.y+=this._temp.y,n.z+=this._temp.z,n.x*=h,n.y*=h,n.z*=h}}C([f()],Le.prototype,"enabled");C([f()],Le.prototype,"space");C([f(H)],Le.prototype,"orbitalX");C([f(H)],Le.prototype,"orbitalY");C([f(H)],Le.prototype,"orbitalZ");C([f()],Le.prototype,"orbitalXMultiplier");C([f()],Le.prototype,"orbitalYMultiplier");C([f()],Le.prototype,"orbitalZMultiplier");C([f()],Le.prototype,"orbitalOffsetX");C([f()],Le.prototype,"orbitalOffsetY");C([f()],Le.prototype,"orbitalOffsetZ");C([f(H)],Le.prototype,"speedModifier");C([f()],Le.prototype,"speedModifierMultiplier");C([f(H)],Le.prototype,"x");C([f()],Le.prototype,"xMultiplier");C([f(H)],Le.prototype,"y");C([f()],Le.prototype,"yMultiplier");C([f(H)],Le.prototype,"z");C([f()],Le.prototype,"zMultiplier");class Mt{animation;enabled;cycleCount;frameOverTime;frameOverTimeMultiplier;numTilesX;numTilesY;startFrame;startFrameMultiplier;rowMode;rowIndex;spriteCount;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(e){if(!this.sampleOnceAtStart())return this.getIndex(e)}getIndex(e){const t=this.numTilesX*this.numTilesY;e=e*this.cycleCount;let i=this.frameOverTime.evaluate(e%1);return i*=this.frameOverTimeMultiplier,i*=t,i=i%t,i=Math.floor(i),i}}C([f()],Mt.prototype,"animation");C([f()],Mt.prototype,"enabled");C([f()],Mt.prototype,"cycleCount");C([f(H)],Mt.prototype,"frameOverTime");C([f()],Mt.prototype,"frameOverTimeMultiplier");C([f()],Mt.prototype,"numTilesX");C([f()],Mt.prototype,"numTilesY");C([f(H)],Mt.prototype,"startFrame");C([f()],Mt.prototype,"startFrameMultiplier");C([f()],Mt.prototype,"rowMode");C([f()],Mt.prototype,"rowIndex");C([f()],Mt.prototype,"spriteCount");C([f()],Mt.prototype,"timeMode");class rn{enabled;separateAxes;x;xMultiplier;y;yMultiplier;z;zMultiplier;evaluate(e,t){return this.enabled?this.separateAxes?0:this.z.evaluate(e,t)*-1:0}}C([f()],rn.prototype,"enabled");C([f()],rn.prototype,"separateAxes");C([f(H)],rn.prototype,"x");C([f()],rn.prototype,"xMultiplier");C([f(H)],rn.prototype,"y");C([f()],rn.prototype,"yMultiplier");C([f(H)],rn.prototype,"z");C([f()],rn.prototype,"zMultiplier");class Ni{enabled;range;separateAxes;x;xMultiplier;y;yMultiplier;z;zMultiplier;evaluate(e,t){if(!this.enabled)return 0;if(!this.separateAxes){const i=I.lerp(this.range.x,this.range.y,t);return this.z.evaluate(i)*-1}return 0}}C([f()],Ni.prototype,"enabled");C([f()],Ni.prototype,"range");C([f()],Ni.prototype,"separateAxes");C([f(H)],Ni.prototype,"x");C([f()],Ni.prototype,"xMultiplier");C([f(H)],Ni.prototype,"y");C([f()],Ni.prototype,"yMultiplier");C([f(H)],Ni.prototype,"z");C([f()],Ni.prototype,"zMultiplier");class et{enabled;dampen;drag;dragMultiplier;limit;limitMultiplier;separateAxes;limitX;limitXMultiplier;limitY;limitYMultiplier;limitZ;limitZMultiplier;multiplyDragByParticleSize=!1;multiplyDragByParticleVelocity=!1;space;_temp=new c.Vector3;_temp2=new c.Vector3;apply(e,t,i,n,o,r,a){if(this.enabled){const l=this.limit.evaluate(o)*this.limitMultiplier;if(t.length()>l){this._temp.copy(t).normalize().multiplyScalar(l);const d=this.dampen*.5;t.x=I.lerp(t.x,this._temp.x,d),t.y=I.lerp(t.y,this._temp.y,d),t.z=I.lerp(t.z,this._temp.z,d),i.x=I.lerp(i.x,this._temp.x,d),i.y=I.lerp(i.y,this._temp.y,d),i.z=I.lerp(i.z,this._temp.z,d)}}}}C([f()],et.prototype,"enabled");C([f()],et.prototype,"dampen");C([f(H)],et.prototype,"drag");C([f()],et.prototype,"dragMultiplier");C([f(H)],et.prototype,"limit");C([f()],et.prototype,"limitMultiplier");C([f()],et.prototype,"separateAxes");C([f(H)],et.prototype,"limitX");C([f()],et.prototype,"limitXMultiplier");C([f(H)],et.prototype,"limitY");C([f()],et.prototype,"limitYMultiplier");C([f(H)],et.prototype,"limitZ");C([f()],et.prototype,"limitZMultiplier");C([f()],et.prototype,"multiplyDragByParticleSize");C([f()],et.prototype,"multiplyDragByParticleVelocity");C([f()],et.prototype,"space");const Ac=class Zv{enabled;curve;curveMultiplier;mode;clone(){const e=new Zv;return e.enabled=this.enabled,e.curve=this.curve?.clone(),e.curveMultiplier=this.curveMultiplier,e.mode=this.mode,e}system;get _lastWorldPosition(){return this.system._iv_lastWorldPosition||(this.system._iv_lastWorldPosition=new c.Vector3),this.system._iv_lastWorldPosition}get _velocity(){return this.system._iv_velocity||(this.system._iv_velocity=new c.Vector3),this.system._iv_velocity}_temp=new c.Vector3;_firstUpdate=!0;awake(e){this.system=e,this.reset()}reset(){this._firstUpdate=!0}update(e){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(e){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),e.x+=this._temp.x,e.y+=this._temp.y,e.z+=this._temp.z}}_frames=0;applyCurrent(e,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),e.x+=this._temp.x,e.y+=this._temp.y,e.z+=this._temp.z}}};C([f()],Ac.prototype,"enabled");C([f(H)],Ac.prototype,"curve");C([f()],Ac.prototype,"curveMultiplier");C([f()],Ac.prototype,"mode");let xg=Ac;class Zt{enabled;range;separateAxes;size;sizeMultiplier;x;xMultiplier;y;yMultiplier;z;zMultiplier;evaluate(e,t,i,n){const o=e.length(),r=I.remap(o,this.range.x,this.range.y,0,1),a=this.size.evaluate(r,i);return n.x*=a,n.y*=a,n.z*=a,n}}C([f()],Zt.prototype,"enabled");C([f(c.Vector2)],Zt.prototype,"range");C([f()],Zt.prototype,"separateAxes");C([f(H)],Zt.prototype,"size");C([f()],Zt.prototype,"sizeMultiplier");C([f(H)],Zt.prototype,"x");C([f()],Zt.prototype,"xMultiplier");C([f(H)],Zt.prototype,"y");C([f()],Zt.prototype,"yMultiplier");C([f(H)],Zt.prototype,"z");C([f()],Zt.prototype,"zMultiplier");class Oa{enabled;range;color;evaluate(e,t,i){const n=e.length(),o=I.remap(n,this.range.x,this.range.y,0,1),r=this.color.evaluate(o,t);i.x*=r.r,i.y*=r.g,i.z*=r.b,"alpha"in r&&(i.w*=r.alpha)}}C([f()],Oa.prototype,"enabled");C([f(c.Vector2)],Oa.prototype,"range");C([f(pr)],Oa.prototype,"color");new c.Vector3(1,1,1);new c.Vector3(0,0,1);class Sg{constructor(e,t,i,n){this.system=e,this.particleSystem=t,this.subSystem=i,this.subParticleSystem=n,this.subParticleSystem&&this.subParticleSystem&&(this.subParticleSystem.onlyUsedByOther=!0);const o=1e3;this._circularBuffer=new hi(()=>new se.Matrix4,o)}type="NeedleParticleSubEmitter";emitterType;emitterProbability;q_=new c.Quaternion;v_=new c.Vector3;v2_=new c.Vector3;_emitterMatrix=new se.Matrix4;_circularBuffer;clone(){throw new Error("Method not implemented.")}initialize(e){e.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===Cp.Birth&&this.run(e)}update(e,t){this.run(e)}frameUpdate(e){}toJSON(){}reset(){}run(e){if(this.subSystem.currentParticles>=this.subSystem.main.maxParticles||!this.subParticleSystem||!e.emissionState||this.emitterProbability&&Math.random()>this.emitterProbability)return;const t=this.system.deltaTime;if(this.emitterType===Cp.Death){let n=e.life;if(e[$r]!==void 0&&(n=e[$r]),!(e.age+t*1.2>=n))return;const r=this.subSystem.main.maxParticles-this.subSystem.currentParticles;e.emissionState.waitEmiting=r}const i=new se.Matrix4;i.set(1,0,0,e.position.x,0,1,0,e.position.y,0,0,1,e.position.z,0,0,0,1),this.particleSystem.worldSpace||i.multiplyMatrices(this._emitterMatrix,i),this.subParticleSystem.emit(t,e.emissionState,i)}}var gO=Object.defineProperty,Ee=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&gO(e,t,n),n};const js=w("debugparticles"),yO=w("noprogressive"),_O=w("debugprogressive");var Cp=(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))(Cp||{});class Vi extends k{renderMode;particleMaterial;trailMaterial;particleMesh;maxParticleSize;minParticleSize;velocityScale;cameraVelocityScale;lengthScale;start(){if(this.maxParticleSize!==.5&&this.minParticleSize!==0&&A()){const e=`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(e)}}get transparent(){return this.particleMaterial?.transparent??!1}getMaterial(e=!1){let t=e===!0&&this.trailMaterial?this.trailMaterial:this.particleMaterial;if(t){if(t.type==="MeshStandardMaterial"){js&&console.debug("ParticleSystemRenderer.getMaterial: MeshStandardMaterial detected, converting to MeshBasicMaterial. See https://github.com/Alchemist0823/three.quarks/issues/101"),"map"in t&&t.map&&(t.map.colorSpace=c.LinearSRGBColorSpace,t.map.premultiplyAlpha=!1);const i=new c.MeshBasicMaterial;i.copy(t),e?this.trailMaterial=i:this.particleMaterial=i}t.map&&(t.map.colorSpace=c.LinearSRGBColorSpace,t.map.premultiplyAlpha=!1),e&&t.side===c.FrontSide&&(t=t.clone(),t.side=c.BackSide,e?this.trailMaterial=t:this.particleMaterial=t)}return t&&!yO&&t._didRequestTextureLOD===void 0&&(t._didRequestTextureLOD=0,_O&&console.log("Load material LOD",t.name),ne.NEEDLE_progressive.assignTextureLOD(t,0)),t}getMesh(e){let t=null;if(!t&&(this.particleMesh instanceof c.Mesh&&(t=this.particleMesh.geometry),t===null)){t=new c.PlaneGeometry(1,1);const n=t.attributes.uv;for(let o=0;o<n.count;o++)n.setX(o,1-n.getX(o))}return new c.Mesh(t,this.getMaterial())}}Ee([f()],Vi.prototype,"renderMode");Ee([f(c.Material)],Vi.prototype,"particleMaterial");Ee([f(c.Material)],Vi.prototype,"trailMaterial");Ee([f()],Vi.prototype,"maxParticleSize");Ee([f()],Vi.prototype,"minParticleSize");Ee([f()],Vi.prototype,"velocityScale");Ee([f()],Vi.prototype,"cameraVelocityScale");Ee([f()],Vi.prototype,"lengthScale");class Sh{_curve;_factor;constructor(e,t=1){this._curve=e,this._factor=t}type="function";startGen(e){}genValue(e,t){return this._curve.evaluate(t,Math.random())*this._factor}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}}class Cg{type="value";toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}startGen(e){}system;constructor(e){this.system=e}}class bO extends Cg{genValue(){return this.system.textureSheetAnimation.getStartIndex()}}class vO extends Cg{_lastPosition=new c.Vector3;_lastDistance=0;update(){const e=X(this.system.gameObject);this._lastDistance=this._lastPosition.distanceTo(e),this._lastPosition.copy(e)}genValue(){if(!this.system.isPlaying||!this.system.emission.enabled||this.system.currentParticles>=this.system.maxParticles)return 0;let e=this.system.emission.rateOverTime.evaluate(this.system.time/this.system.duration,Math.random());if(this.system.deltaTime>0){const n=this.system.emission.rateOverDistance.evaluate(this.system.time/this.system.duration,Math.random());let r=this._lastDistance/this.system.deltaTime*n;Number.isFinite(r)||(r=0),e+=r}const t=this.system.emission.getBurst();t>0&&(e+=t/this.system.deltaTime);const i=this.system.maxParticles-this.system.currentParticles;return I.clamp(e,0,i/this.system.deltaTime)}}class wO extends Cg{genValue(){return this.system.isPlaying,0}}class lo{system;get context(){return this.system.context}constructor(e){this.type=Object.getPrototypeOf(this).constructor.name||"ParticleSystemBaseBehaviour",e&&(this.system=e)}type;initialize(e){}update(e,t){}frameUpdate(e){}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}reset(){}}class xO extends lo{type="NeedleTextureSheet";update(e,t){const i=this.system.textureSheetAnimation;if(i.enabled){const n=e.age/e.life,o=i.evaluate(n);o!==void 0&&(e.uvTile=o)}}}const w_=Symbol("particleRotation");class SO extends lo{type="NeedleRotation";initialize(e){e[w_]=Math.random()}update(e,t){if(e.rotation===void 0)return;const i=e.age/e.life;if(typeof e.rotation=="number"&&(this.system.rotationOverLifetime.enabled?e.rotation+=this.system.rotationOverLifetime.evaluate(i,e[w_])*t:this.system.renderer.renderMode===Kn.Billboard&&(e.rotation=Math.PI),this.system.rotationBySpeed.enabled)){const n=e.velocity.length();e.rotation+=this.system.rotationBySpeed.evaluate(i,n)*t}}}const x_=Symbol("sizeLerpFactor"),CO=new c.Vector3;class PO extends lo{type="NeedleSize";_minSize=0;_maxSize=1;initialize(e){e[x_]=Math.random(),this._minSize=this.system.renderer.minParticleSize,this._maxSize=this.system.renderer.maxParticleSize}update(e,t){const i=e.age/e.life;let n=1;this.system.sizeOverLifetime.enabled&&(n*=this.system.sizeOverLifetime.evaluate(i,void 0,e[x_]).x);let o=1;this.system.renderer.renderMode!==Kn.Mesh&&(o=this.system.worldScale.x/this.system.cameraScale);const r=V(e.startSize).multiplyScalar(n*o);if(e.size.set(r.x,r.y,r.z),this.system.localspace){const a=Jv(this.system,CO);e.size.x*=a.x,e.size.y*=a.y,e.size.z*=a.z}}}const $r=Symbol("particleLife"),Pf=Symbol("trailLifetime"),S_=Symbol("trailStartLength"),Mf=Symbol("trailWidthRandom");class MO extends lo{type="NeedleTrail";initialize(e){e instanceof se.TrailParticle&&(e[$r]=e.life,this.system.trails.enabled&&this.system.trails.dieWithParticles===!1&&(e[Pf]=this.system.trails.lifetime.evaluate(Math.random(),Math.random()),e.life+=e[Pf]),e[S_]=e.length,e[Mf]=Math.random())}update(e){if(this.system.trails?.enabled&&e instanceof se.TrailParticle){const t=e,i=e.age/e[$r],n=e.previous.values(),o=e.previous.length;for(let r=0;r<o;r++){const l=n.next().value,h=1-r/(o-1),d=e.size;if(d.x<=0&&!this.system.trails.sizeAffectsWidth){const u=20*this.system.trails.widthOverTrail.evaluate(.5,t[Mf]);d.x=u,d.y=u,d.z=u}l.size=this.system.trails.getWidth(d.x,i,h,t[Mf]),l.color.copy(e.color),this.system.trails.getColor(l.color,i,h)}if(e.age>e[$r]){e.velocity.set(0,0,0);const r=(e.age-e[$r])/e[Pf];t.length=I.lerp(e[S_],0,r)}}}}const Ch=Symbol("startVelocity"),C_=Symbol("gravityModifier"),Of=Symbol("gravitySpeed"),Ph=Symbol("velocity lerp factor"),Pp=new c.Vector3;class OO extends lo{type="NeedleVelocity";_gravityDirection=new c.Vector3;initialize(e){const t=this.system.main.simulationSpeed;e.startSpeed=this.system.main.startSpeed.evaluate(Math.random(),Math.random());const i=this.system.shape.getDirection(e,e.position);e.velocity.x=i.x*e.startSpeed,e.velocity.y=i.y*e.startSpeed,e.velocity.z=i.z*e.startSpeed,this.system.inheritVelocity?.enabled&&this.system.inheritVelocity.applyInitial(e.velocity),e[Ch]?e[Ch].copy(e.velocity):e[Ch]=e.velocity.clone();const n=this.system.main.gravityModifier.evaluate(Math.random(),Math.random());e[C_]=n*t,e[Of]=n*t*.5,e[Ph]=Math.random(),this.system.velocityOverLifetime?.init(e),this._gravityDirection.set(0,-1,0),this.system.main.simulationSpace===Hl.Local&&this._gravityDirection.applyQuaternion(this.system.worldQuaternionInverted).normalize()}update(e,t){const i=e[Ch],n=e[C_];if(n!==0){const u=n*e[Of];Pp.copy(this._gravityDirection).multiplyScalar(u),e[Of]+=t*.05,i.add(Pp)}e.velocity.copy(i);const o=e.age/e.life;this.system.inheritVelocity?.enabled&&this.system.inheritVelocity.applyCurrent(e.velocity,o,e[Ph]);const r=this.system.noise;r.enabled&&r.apply(0,e.position,e.velocity,t,e.age,e.life);const a=this.system.sizeBySpeed;a?.enabled&&(e.size=a.evaluate(e.velocity,o,e[Ph],e.size));const l=this.system.colorBySpeed;l?.enabled&&l.evaluate(e.velocity,e[Ph],e.color);const h=this.system.velocityOverLifetime;h.enabled&&h.apply(e,0,e.position,e.velocity,t,e.age,e.life);const d=this.system.limitVelocityOverLifetime;if(d.enabled&&d.apply(e.position,i,e.velocity,e.size,o,t,1),this.system.worldspace){const u=this.system.worldScale;e.velocity.x*=u.x,e.velocity.y*=u.y,e.velocity.z*=u.z}}}const P_=Symbol("colorLerpFactor"),M_=new Z(1,1,1,1),yo=new Z(1,1,1,1);class kO extends lo{type="NeedleColor";initialize(e){}_init(e){const t=this.system.renderer.particleMaterial;yo.copy(this.system.main.startColor.evaluate(Math.random())),t?.color&&(M_.copy(t.color),yo.multiply(M_)),yo.convertLinearToSRGB(),e.startColor.set(yo.r,yo.g,yo.b,yo.alpha),e.color.copy(e.startColor),e[P_]=Math.random()}update(e,t){if(e.age===0&&this._init(e),this.system.colorOverLifetime.enabled){const i=e.age/e.life,n=this.system.colorOverLifetime.color.evaluate(i,e[P_]);e.color.set(n.r,n.g,n.b,"alpha"in n?n.alpha:1).multiply(e.startColor)}else e.color.copy(e.startColor)}}class RO{system;emission;get anim(){return this.system.textureSheetAnimation}constructor(e){this.system=e,this.emission=new vO(this.system)}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()}autoDestroy;get looping(){return this.system.main.loop}get duration(){return this.system.duration}get shape(){return this.system.shape}get startLife(){return new Sh(this.system.main.startLifetime)}get startSpeed(){return new Sh(this.system.main.startSpeed)}get startRotation(){return new Sh(this.system.main.startRotation)}get startSize(){return new Sh(this.system.main.startSize)}startLength;get startColor(){return new se.ConstantColor(new se.Vector4(1,1,1,1))}get emissionOverTime(){return this.emission}get emissionOverDistance(){return new wO(this.system)}emissionBursts;onlyUsedByOther;behaviors=[];get instancingGeometry(){return this.system.renderer.getMesh(this.system.renderer.renderMode).geometry}get renderMode(){if(this.system.trails.enabled===!0)return se.RenderMode.Trail;switch(this.system.renderer.renderMode){case Kn.Billboard:return se.RenderMode.BillBoard;case Kn.Stretch:return se.RenderMode.StretchedBillBoard;case Kn.HorizontalBillboard:return se.RenderMode.HorizontalBillBoard;case Kn.VerticalBillboard:return se.RenderMode.VerticalBillBoard;case Kn.Mesh:return se.RenderMode.Mesh}return se.RenderMode.BillBoard}rendererEmitterSettings={startLength:new se.ConstantValue(220),followLocalOrigin:!1};get speedFactor(){let e=this.system.main.simulationSpeed;return this.system.renderer?.renderMode===Kn.Stretch&&(e*=this.system.renderer.velocityScale??1),e}flatWhiteTexture;clonedTexture={original:void 0,clone:void 0};get texture(){const e=this.material;if(e&&e.map){const t=e.map;if(this.clonedTexture.original!==t||!this.clonedTexture.clone){const i=t.clone();i.premultiplyAlpha=!1,i.colorSpace=c.LinearSRGBColorSpace,this.clonedTexture.original=t,this.clonedTexture.clone=i}return this.clonedTexture.clone}return this.flatWhiteTexture||(this.flatWhiteTexture=mm(new Z(1,1,1,1),1)),this.flatWhiteTexture}get startTileIndex(){return new bO(this.system)}get uTileCount(){return this.anim.enabled?this.anim?.numTilesX:void 0}get vTileCount(){return this.anim.enabled?this.anim?.numTilesY:void 0}get renderOrder(){return 1}get blending(){return this.system.renderer.particleMaterial?.blending??c.NormalBlending}get transparent(){return this.system.renderer.transparent}get worldSpace(){return this.system.main.simulationSpace===Hl.World}}class EO{burstParticleIndex=0;burstParticleCount=0;isBursting=!1;travelDistance=0;previousWorldPos;burstIndex=0;burstWaveIndex=0;time=0;waitEmiting=0}const Ot=class Wh extends k{play(e=!1){e&&x.foreachComponent(this.gameObject,t=>{t instanceof Wh&&t!==this&&t.play(!1)},!0),this._isPlaying=!0,this._particleSystem&&(this._particleSystem.emissionState.time=0,this._particleSystem.emitEnded=!1),this.emission?.reset()}pause(e=!0){e&&x.foreachComponent(this.gameObject,t=>{t instanceof Wh&&t!==this&&t.pause(!1)},!0),this._isPlaying=!1}stop(e=!0,t=!1){e&&x.foreachComponent(this.gameObject,i=>{i instanceof Wh&&i!==this&&i.stop(!1,t)},!0),this._isPlaying=!1,this._time=0,t&&this.reset()}reset(){this._time=0,this._particleSystem&&(this._particleSystem.particleNum=0,this._particleSystem.emissionState.time=0,this._particleSystem.emitEnded=!1,this.emission?.reset())}_state;emit(e){if(this._particleSystem){this.onUpdate(),e=Math.min(e,this.maxParticles-this.currentParticles),this._state||(this._state=new EO),this._state.waitEmiting=e,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(e){this.main.playOnAwake=e}colorOverLifetime;main;emission;sizeOverLifetime;shape;noise;trails;velocityOverLifetime;limitVelocityOverLifetime;inheritVelocity;colorBySpeed;textureSheetAnimation;rotationOverLifetime;rotationBySpeed;sizeBySpeed;get renderer(){return this._renderer}get isPlaying(){return this._isPlaying}get currentParticles(){return this._particleSystem?.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}_cameraScale=1;get container(){return this._container}get worldspace(){return this.main.simulationSpace===Hl.World}get localspace(){return this.main.simulationSpace===Hl.Local}__worldQuaternion=new c.Quaternion;get worldQuaternion(){return this.__worldQuaternion}_worldQuaternionInverted=new c.Quaternion;get worldQuaternionInverted(){return this._worldQuaternionInverted}_worldScale=new c.Vector3;get worldScale(){return this._worldScale}_worldPositionFrame=-1;_worldPos=new c.Vector3;get worldPos(){return this._worldPositionFrame!==this.context.time.frame&&(this._worldPositionFrame=this.context.time.frame,X(this.gameObject,this._worldPos)),this._worldPos}get matrixWorld(){return this._container.matrixWorld}get isSubsystem(){return this._isUsedAsSubsystem}addBehaviour(e){return this._particleSystem?(e instanceof lo&&(e.system=this),js&&console.debug("Add custom ParticleSystem Behaviour",e),this._particleSystem.addBehavior(e),!0):!1}removeBehaviour(e){if(!this._particleSystem)return!1;const t=this._particleSystem.behaviors,i=t.indexOf(e);return i!==-1&&((A()||js)&&console.debug("Remove custom ParticleSystem Behaviour",i,e),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}_renderer;_batchSystem;_particleSystem;_interface;_container;_time=0;_isPlaying=!0;_isUsedAsSubsystem=!1;_didPreWarm=!1;set bursts(e){for(let t=0;t<e.length;t++){const i=e[t];if(!(i instanceof wd)){const n=new wd;sa(n,i),e[t]=n}}this._bursts=e}_bursts;set subEmitterSystems(e){for(let t=0;t<e.length;t++){const i=e[t];if(!(i instanceof xd)){const n=new xd;sa(n,i),e[t]=n}}js&&e.length>0&&console.log("SubEmitters: ",e,this),this._subEmitterSystems=e}_subEmitterSystems;onAfterDeserialize(e){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(Vi),!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 c.Object3D,this._container.matrixAutoUpdate=!1,this.context.scene.add(this._container),this._batchSystem=new se.BatchedParticleRenderer,this._batchSystem.name=this.gameObject.name,this._container.add(this._batchSystem),this._interface=new RO(this),this._particleSystem=new se.ParticleSystem(this._interface),this._particleSystem.addBehavior(new PO(this)),this._particleSystem.addBehavior(new kO(this)),this._particleSystem.addBehavior(new xO(this)),this._particleSystem.addBehavior(new SO(this)),this._particleSystem.addBehavior(new OO(this)),this._particleSystem.addBehavior(new MO(this)),this._batchSystem.addSystem(this._particleSystem);const e=this._particleSystem.emitter;this.context.scene.add(e),this.inheritVelocity.system&&this.inheritVelocity.system!==this&&(this.inheritVelocity=this.inheritVelocity.clone()),this.inheritVelocity.awake(this),js&&(console.log(this),this.gameObject.add(new c.AxesHelper(1)))}start(){this.addSubParticleSystems(),this.updateLayers(),this.renderer.particleMesh instanceof c.Mesh&&this._interface.renderMode==se.RenderMode.Mesh&&ne.NEEDLE_progressive.assignMeshLOD(this.renderer.particleMesh,0).then(e=>{e&&this.particleSystem&&this._interface.renderMode==se.RenderMode.Mesh&&(this.particleSystem.instancingGeometry=e)})}onDestroy(){this._container?.removeFromParent(),this._batchSystem?.removeFromParent(),this._particleSystem?.emitter.removeFromParent(),this._particleSystem?.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(){this.main&&(this._didPreWarm===!1&&this.main?.prewarm===!0&&(this._didPreWarm=!0,this.preWarm()),this.onUpdate(),this.onSimulate(this.deltaTime))}preWarm(){if(!this.emission?.enabled||this.emission.rateOverTime.getMax()<=0)return;const t=1/60,i=this.main.duration,n=this.main.startLifetime.getMax(),r=Math.min(Math.max(i,n)/Math.max(.01,this.main.simulationSpeed),1e3),a=Math.ceil(r/t),l=Date.now();js&&console.log(`Particles ${this.name} - Prewarm for ${a} frames (${r} sec). Duration: ${i}, Lifetime: ${n}`);for(let h=0;h<a&&!(this.currentParticles>=this.maxParticles);h++){const d=Date.now()-l;if(d>2e3){console.warn(`Particles ${this.name} - Prewarm took too long. Aborting: ${d}`);break}this.onUpdate(),this.onSimulate(t)}}_lastBatchesCount=-1;onSimulate(e){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(e)}this._time+=e,this._time>this.duration&&(this._time=0)}updateLayers(){if(this._batchSystem)for(let e=0;e<this._batchSystem.batches.length;e++){const t=this._batchSystem.batches[e];t.layers.disableAll();const i=this.layer;t.layers.mask=1<<i}}onUpdate(){if(this._bursts&&(this.emission.bursts=this._bursts,delete this._bursts),!this._isPlaying)return;const e=this.context.mainCamera;if(e){const n=Ae(e);this._cameraScale=n.x}const t=!this.worldspace,i=this.gameObject;if(ue(i,this.__worldQuaternion),this._worldQuaternionInverted.copy(this.__worldQuaternion).invert(),Ae(this.gameObject,this._worldScale),t&&this._container&&this.gameObject?.parent){const n=Jv(this,Pp);this._container.matrix.makeScale(n.x,n.y,n.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),this.inheritVelocity?.update(this.context),this.velocityOverLifetime.update(this)}addSubParticleSystems(){if(this._subEmitterSystems&&this._particleSystem)for(const e of this._subEmitterSystems){e.particleSystem&&(e.particleSystem.__internalAwake?e.particleSystem.__internalAwake():A()&&console.warn("SubParticleSystem serialization issue(?)",e.particleSystem,e));const t=e.particleSystem?._particleSystem;if(t){e.particleSystem._isUsedAsSubsystem=!0;const i=new Sg(this,this._particleSystem,e.particleSystem,t);i.emitterType=e.type,i.emitterProbability=e.emitProbability,this._particleSystem.addBehavior(i)}else js&&console.warn("Could not add SubParticleSystem",e,this)}}};Ee([f(hu)],Ot.prototype,"colorOverLifetime");Ee([f(Pt)],Ot.prototype,"main");Ee([f(ys)],Ot.prototype,"emission");Ee([f(mr)],Ot.prototype,"sizeOverLifetime");Ee([f(wg)],Ot.prototype,"shape");Ee([f(fe)],Ot.prototype,"noise");Ee([f(Re)],Ot.prototype,"trails");Ee([f(Le)],Ot.prototype,"velocityOverLifetime");Ee([f(et)],Ot.prototype,"limitVelocityOverLifetime");Ee([f(xg)],Ot.prototype,"inheritVelocity");Ee([f(Oa)],Ot.prototype,"colorBySpeed");Ee([f(Mt)],Ot.prototype,"textureSheetAnimation");Ee([f(rn)],Ot.prototype,"rotationOverLifetime");Ee([f(Ni)],Ot.prototype,"rotationBySpeed");Ee([f(Zt)],Ot.prototype,"sizeBySpeed");let ql=Ot;class xd{particleSystem;emitProbability=1;properties;type;_deserialize(e,t){const i=this.particleSystem;if(i instanceof ql)return;let n="";i&&typeof i.guid=="string"&&(n=i.guid,this.particleSystem=x.findByGuid(n,t)),js&&!(this.particleSystem instanceof ql)&&console.warn("Could not find particle system for sub emitter",n,t,this)}}function Jv(s,e){if(e.set(1,1,1),s.gameObject.parent&&s.localspace)switch(s.main.scalingMode){case Sp.Local:e=Ae(s.gameObject.parent,e),e.x=1/e.x,e.y=1/e.y,e.z=1/e.z;break;default:if(!s.unsupported_scaling_mode){s.unsupported_scaling_mode=!0;const t="ParticleSystem scale mode "+Sp[s.main.scalingMode]+" is not supported";A()&&ce(t),console.warn(t,s.name,s)}e=Ae(s.gameObject,e);break}return e}class ha extends k{_didAssignPlayerColor=!1;onEnable(){this.context.connection.beginListen(Q.JoinedRoom,this.tryAssignColor),this._didAssignPlayerColor||this.startCoroutine(this.waitForConnection())}onDisable(){this.context.connection.stopListen(Q.JoinedRoom,this.tryAssignColor)}*waitForConnection(){for(;!this.destroyed&&this.activeAndEnabled&&(yield pm(.2),!this.tryAssignColor()););}tryAssignColor=()=>{const e=x.getComponentInParent(this.gameObject,Zi);if(e&&e.owner)return this._didAssignPlayerColor=!0,this.assignUserColor(e.owner),!0;const t=x.getComponentInParent(this.gameObject,xe);return t?.connectionId?(this._didAssignPlayerColor=!0,this.assignUserColor(t.connectionId),!0):!1};assignUserColor(e){const t=ha.hashCode(e),i=ha.colorFromHashCode(t);if(this.gameObject.type==="Mesh"){const n=this.gameObject;this.assignColor(i,e,n)}else if(this.gameObject.children)for(const n of this.gameObject.children){const o=n;o.material&&o.material.color&&this.assignColor(i,e,o)}}assignColor(e,t,i){let n=i.material;n&&(n._playerMaterial!==t&&(n=n.clone(),n._playerMaterial=t,i.material=n),n.color=e)}static hashCode(e){var t=0,i,n;if(e.length===0)return t;for(i=0;i<e.length;i++)n=e.charCodeAt(i),t=(t<<5)-t+n,t|=0;return t}static colorFromHashCode(e){const t=(e&16711680)>>16,i=(e&65280)>>8,n=e&255;return new c.Color(t/255,i/255,n/255)}}const yl=w("debugpost");let Mp=null;function TO(s){Mp=s}function ew(s){let e=s.gameObject;for(;e;){for(const t of Fd(e))if(t.isPostProcessingManager===!0)return t;e=e.parent}return null}function AO(s){let e=ew(s);if(!e)if(Mp){yl&&console.warn("Adding postprocessing manager to the scene.");const t=s.scene;e=ci(t,Mp)}else A()&&console.warn("No post processing manager found");return e}const Qe={AT_START:-1e4,NormalPass:0,DepthDownsamplingPass:10,SSAO:20,SMAA:30,TiltShift:40,DepthOfField:50,ChromaticAberration:60,Bloom:70,Vignette:80,Pixelation:90,ToneMapping:100,HueSaturation:110,BrightnessContrast:120,Sharpening:130,AT_END:1e4};let Be=null;function LO(s){yl==="verbose"&&console.debug("Before ordering effects",[...s]),Be||(Be=new Map,Be.set(exports.MODULES.POSTPROCESSING.MODULE.NormalPass,Qe.NormalPass),Be.set(exports.MODULES.POSTPROCESSING.MODULE.DepthDownsamplingPass,Qe.DepthDownsamplingPass),Be.set(exports.MODULES.POSTPROCESSING.MODULE.SMAAEffect,Qe.SMAA),Be.set(exports.MODULES.POSTPROCESSING.MODULE.SSAOEffect,Qe.SSAO),Be.set(exports.MODULES.POSTPROCESSING_AO.MODULE.N8AOPostPass,Qe.SSAO),Be.set(exports.MODULES.POSTPROCESSING_AO.MODULE.N8AOPass,Qe.SSAO),Be.set(exports.MODULES.POSTPROCESSING.MODULE.TiltShiftEffect,Qe.TiltShift),Be.set(exports.MODULES.POSTPROCESSING.MODULE.DepthOfFieldEffect,Qe.DepthOfField),Be.set(exports.MODULES.POSTPROCESSING.MODULE.ChromaticAberrationEffect,Qe.ChromaticAberration),Be.set(exports.MODULES.POSTPROCESSING.MODULE.BloomEffect,Qe.Bloom),Be.set(exports.MODULES.POSTPROCESSING.MODULE.SelectiveBloomEffect,Qe.Bloom),Be.set(exports.MODULES.POSTPROCESSING.MODULE.VignetteEffect,Qe.Vignette),Be.set(exports.MODULES.POSTPROCESSING.MODULE.PixelationEffect,Qe.Pixelation),Be.set(exports.MODULES.POSTPROCESSING.MODULE.ToneMappingEffect,Qe.ToneMapping),Be.set(exports.MODULES.POSTPROCESSING.MODULE.HueSaturationEffect,Qe.HueSaturation),Be.set(exports.MODULES.POSTPROCESSING.MODULE.BrightnessContrastEffect,Qe.BrightnessContrast)),s.sort((e,t)=>{const i=typeof e.priority=="number"?e.priority:Be.get(e.effect.constructor)??Number.NEGATIVE_INFINITY,n=typeof t.priority=="number"?t.priority:Be.get(t.effect.constructor)??Number.NEGATIVE_INFINITY;return i===Number.NEGATIVE_INFINITY?(yl&&console.warn("Unknown effect found: ",e.constructor.name,e),1):n===Number.NEGATIVE_INFINITY?(yl&&console.warn("Unknown effect found: ",t.constructor.name,t),-1):i-n}),yl==="verbose"&&console.debug("After ordering effects",[...s])}var DO=Object.defineProperty,IO=Object.getOwnPropertyDescriptor,tw=(s,e,t,i)=>{for(var n=IO(e,t),o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&DO(e,t,n),n};const jO=w("debugpost");class D{isVolumeParameter=!0;constructor(e){e!==void 0&&this.initialize(e)}_isInitialized=!1;get isInitialized(){return this._isInitialized}initialize(e){e!==void 0&&(this._value=e,this._defaultValue=e,this._valueRaw=e,this._isInitialized=!0)}get overrideState(){return this._active}set overrideState(e){if(this._active===e)return;this._active=e;const t=e?this._valueRaw:this._defaultValue;this.processValue(t,!0)}_active=!0;get value(){return this._valueRaw}set value(e){this.isInitialized||this.initialize(e),this.processValue(e,!1)}_value;_valueRaw;set defaultValue(e){this._defaultValue=e}_defaultValue=void 0;__init(){this.processValue(this._valueRaw,!0)}valueProcessor;onValueChanged;processValue(e,t){if(e==null||!t&&this.testIfValueChanged(e)===!1)return;const i=this._value;jO&&typeof i=="number"&&typeof e=="number"&&(i?.toFixed(4),e?.toFixed(4)),!this._active&&this._defaultValue!==void 0?(this._value=this._defaultValue,e=this._defaultValue,this._valueRaw=e):(this._valueRaw=e,this._active&&this.valueProcessor&&(e=this.valueProcessor(e)),this._value=e),this.onValueChanged&&this.onValueChanged(e,i,this)}testIfValueChanged(e){return this._valueRaw!==e}}tw([f()],D.prototype,"overrideState");tw([f()],D.prototype,"value");class BO extends Ui{constructor(){super([D])}onSerialize(e,t){}onDeserialize(e,t){const i=t.target,n=t.path;let o;if(i&&n&&(o=i[n]),(typeof o!="object"||typeof o=="object"&&o.isVolumeParameter!==!0)&&(o=new D),typeof e=="object"&&"value"in e){const r=e.value;o.initialize(r),o.overrideState=e.overrideState}else o.value=e;return o}}new BO;var FO=Object.defineProperty,UO=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&FO(e,t,n),n};const kf=w("debugpost");class Ne extends k{get isPostProcessingEffect(){return!0}order=void 0;constructor(e=void 0){if(super(),e)for(const t of Object.keys(e)){const i=e[t],n=this[t];n instanceof D?n.initialize(i):n!==void 0&&(this[t]=i)}}active=!0;_manager=null;onEnable(){super.onEnable(),kf&&console.warn("Enable",this.constructor.name+(this.__internalDidAwakeAndStart?"":" (awake)")),this.__internalDidAwakeAndStart&&(this.active=!0),this.onEffectEnabled()}onDisable(){super.onDisable(),kf&&console.warn("Disable",this.constructor.name),this._manager?.removeEffect(this),this.active=!1}onEffectEnabled(e){e&&e.isPostProcessingManager===!0?this._manager=e:this._manager||(this._manager=AO(this)),this._manager.addEffect(this),this._manager.dirty=!0}init(){}_result;_postprocessingContext=null;get postprocessingContext(){return this._postprocessingContext}apply(e){return this._postprocessingContext=e,this._result||(this.initParameters(),this._result=this.onCreateEffect?.call(this)),this._result&&this.initParameters(),this._result}unapply(){}dispose(){kf&&console.warn("DISPOSE",this),this._result&&(Array.isArray(this._result)?this._result.forEach(e=>e.dispose()):this._result.dispose()),this._result=void 0}initParameters(){const e=Object.keys(this);for(const t of e){const i=this[t];i instanceof D&&i.__init()}}onEditorModification(e){const t=e.propertyName;if(this[t]instanceof D){const i=e.value;return this[t].value=i,!0}}}UO([f()],Ne.prototype,"active");var zO=Object.defineProperty,NO=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&zO(e,t,n),n};const VO=w("debugpost"),Op={};function $i(s,e){Op[s]=e}function $O(s){return s.__type in Op?Op[s.__type]:(VO&&s.__type&&console.warn("Unknown postprocessing type",s.__type,s),Ne)}class du{components=[];__init(e){this.components?.forEach(t=>{t.gameObject===void 0&&e.gameObject.addComponent(t),t.init()})}addEffect(e){this.components.push(e)}removeEffect(e){const t=this.components.indexOf(e);t>=0&&this.components.splice(t,1)}}NO([er([s=>$O(s),Ne])],du.prototype,"components");var WO=Object.defineProperty,GO=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&WO(e,t,n),n};const HO=w("debugpost");class Lc extends Ne{get typeName(){return"Antialiasing"}preset=new D(2);onCreateEffect(){const e=new exports.MODULES.POSTPROCESSING.MODULE.SMAAEffect({preset:this.preset?.value??exports.MODULES.POSTPROCESSING.MODULE.SMAAPreset.HIGH,edgeDetectionMode:exports.MODULES.POSTPROCESSING.MODULE.EdgeDetectionMode.LUMA});return this.preset.onValueChanged=t=>{HO&&console.log("Antialiasing preset changed to",t),e.applyPreset(t)},e}}GO([f(D)],Lc.prototype,"preset");$i("Antialiasing",Lc);var qO=Object.defineProperty,Pg=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&qO(e,t,n),n};const uu=class iw extends Ne{static useSelectiveBloom=!1;get typeName(){return"Bloom"}threshold=new D(.9);intensity=new D(1);scatter=new D(.7);selectiveBloom;init(){this.threshold.valueProcessor=e=>e,this.intensity.valueProcessor=e=>e,this.scatter.valueProcessor=e=>e}onCreateEffect(){let e;if(this.selectiveBloom==null&&(this.selectiveBloom=iw.useSelectiveBloom),this.selectiveBloom){const t=e=new exports.MODULES.POSTPROCESSING.MODULE.SelectiveBloomEffect(this.context.scene,this.context.mainCamera,{blendFunction:exports.MODULES.POSTPROCESSING.MODULE.BlendFunction.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,radius:.85,intensity:this.intensity.value});t.inverted=!0}else e=new exports.MODULES.POSTPROCESSING.MODULE.BloomEffect({blendFunction:exports.MODULES.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=>{e.intensity=t},this.threshold.onValueChanged=t=>{e.luminanceMaterial.threshold=Math.pow(t,2.2)},this.scatter.onValueChanged=t=>{e.luminancePass.enabled=!0,e.luminanceMaterial.smoothing=t,e.mipmapBlurPass&&(e.mipmapBlurPass.radius=c.MathUtils.lerp(.1,.9,t))},e}};Pg([f(D)],uu.prototype,"threshold");Pg([f(D)],uu.prototype,"intensity");Pg([f(D)],uu.prototype,"scatter");let fu=uu;$i("Bloom",fu);var XO=Object.defineProperty,QO=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&XO(e,t,n),n};class Dc extends Ne{get typeName(){return"ChromaticAberration"}intensity=new D(0);onCreateEffect(){const e=new exports.MODULES.POSTPROCESSING.MODULE.ChromaticAberrationEffect;return e.offset=new c.Vector2(0,0),e.radialModulation=!0,e.modulationOffset=.15,this.intensity.valueProcessor=t=>t*.02,this.intensity.onValueChanged=t=>{e.offset.x=-t,e.offset.y=t},e}}QO([f(D)],Dc.prototype,"intensity");$i("ChromaticAberration",Dc);var _l=(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))(_l||{});const O_=new Map;function Rf(s){switch(s){case 0:return c.LinearToneMapping;case 1:return c.ReinhardToneMapping;case 2:return c.ACESFilmicToneMapping;case 3:return c.AgXToneMapping;case 4:return c.NeutralToneMapping;default:return O_.has(s)||(O_.set(s,!0),console.warn("[Postprocessing] Unknown tone mapping mode",s)),c.NeutralToneMapping}}function YO(s){switch(s){case c.LinearToneMapping:return 0;case c.ACESFilmicToneMapping:return 2;case c.AgXToneMapping:return 3;case c.NeutralToneMapping:return 1;case c.ReinhardToneMapping:return 1;default:return 0}}function Gh(s){switch(s){case c.LinearToneMapping:return exports.MODULES.POSTPROCESSING.MODULE.ToneMappingMode.LINEAR;case c.ACESFilmicToneMapping:return exports.MODULES.POSTPROCESSING.MODULE.ToneMappingMode.ACES_FILMIC;case c.AgXToneMapping:return exports.MODULES.POSTPROCESSING.MODULE.ToneMappingMode.AGX;case c.NeutralToneMapping:return exports.MODULES.POSTPROCESSING.MODULE.ToneMappingMode.NEUTRAL;case c.ReinhardToneMapping:return exports.MODULES.POSTPROCESSING.MODULE.ToneMappingMode.REINHARD;default:return exports.MODULES.POSTPROCESSING.MODULE.ToneMappingMode.LINEAR}}var KO=Object.defineProperty,nw=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&KO(e,t,n),n};const Ef=w("debugpost");class Ys extends Ne{get typeName(){return"ToneMapping"}mode=new D(void 0);exposure=new D(1);setMode(e){const t=_l[e];return t===void 0?(console.error("[PostProcessing] Invalid ToneMapping mode",e),this):(this.mode.value=t,this)}get isToneMapping(){return!0}onEffectEnabled(){const e=ew(this);e&&super.onEffectEnabled(e)}_tonemappingEffect=null;onCreateEffect(){if(this.mode.isInitialized==!1){const i=YO(this.context.renderer.toneMapping);Ef&&console.log("[PostProcessing] Initializing ToneMapping mode to renderer.toneMapping",this.context.renderer.toneMapping+" → "+i),this.mode.initialize(i)}this._tonemappingEffect?.dispose();const e=Rf(this.mode.value),t=this._tonemappingEffect=new exports.MODULES.POSTPROCESSING.MODULE.ToneMappingEffect({mode:Gh(e)});return this.mode.onValueChanged=i=>{if(typeof i=="string")i=L0(i),t.mode=Gh(i);else{const n=Rf(i);t.mode=Gh(n)}t.name="ToneMapping ("+_l[i]+")",Ef&&console.log("[PostProcessing] ToneMapping mode changed to",_l[i],e,t.mode)},Ef&&console.log("[PostProcessing] Use ToneMapping",_l[this.mode.value],e,t.mode,"renderer.tonemapping: "+this.context.renderer.toneMapping),t}onBeforeRender(){if(this._tonemappingEffect&&this.postprocessingContext?.handler.getEffectIsActive(this._tonemappingEffect)&&(this.mode.overrideState&&(this.context.renderer.toneMapping=Rf(this.mode.value)),this.exposure.overrideState&&this.exposure.value!==void 0)){const e=Math.max(0,this.exposure.value);this.context.renderer.toneMappingExposure=e}}}nw([f(D)],Ys.prototype,"mode");nw([f(D)],Ys.prototype,"exposure");$i("Tonemapping",Ys);var ZO=Object.defineProperty,pu=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&ZO(e,t,n),n};class co extends Ne{get typeName(){return"ColorAdjustments"}remap=!0;postExposure=new D(1);contrast=new D(0);hueShift=new D(0);saturation=new D(0);init(){this.postExposure.valueProcessor=e=>(this.remap&&(e=Math.pow(2,e)),e),this.contrast.valueProcessor=e=>{if(!this.remap)return e;let t=1;return e>0?t=200:e<0&&(t=100),e/t},this.contrast.defaultValue=0,this.hueShift.valueProcessor=e=>this.remap?Math.PI*e/180:e,this.hueShift.defaultValue=0,this.saturation.valueProcessor=e=>this.remap?e<0?e/100:e/(100*Math.PI):e,this.saturation.defaultValue=0}onCreateEffect(){const e=[];let t=this.postprocessingContext?.components.find(o=>o instanceof Ys);t||(t=new Ys,this.postprocessingContext?.components.push(t)),this.postExposure.onValueChanged=o=>{this.postExposure.overrideState&&t?t.exposure.value=o:console.warn("[PostProcessing] PostExposure is set to override but no ToneMappingEffect found in the postprocessing stack. Please add a ToneMappingEffect to your postprocessing stack to use PostExposure.")};const i=new exports.MODULES.POSTPROCESSING.MODULE.BrightnessContrastEffect;this.contrast.onValueChanged=o=>i.contrast=o;const n=new exports.MODULES.POSTPROCESSING.MODULE.HueSaturationEffect;return this.hueShift.onValueChanged=o=>n.hue=o,this.saturation.onValueChanged=o=>n.saturation=o,e.push(i),e.push(n),e}}pu([f(D)],co.prototype,"postExposure");pu([f(D)],co.prototype,"contrast");pu([f(D)],co.prototype,"hueShift");pu([f(D)],co.prototype,"saturation");$i("ColorAdjustments",co);var JO=Object.defineProperty,gr=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&JO(e,t,n),n};const ek=w("debugpost");class an extends Ne{get typeName(){return"DepthOfField"}mode;focusDistance=new D(1);focalLength=new D(.2);aperture=new D(20);gaussianMaxRadius=new D;resolutionScale=new D(1/window.devicePixelRatio);bokehScale=new D;init(){this.focalLength.valueProcessor=t=>{const i=t/300;return I.lerp(2,.01,i)};const e=20;this.aperture.valueProcessor=t=>{const i=1-t/32;return I.lerp(1,e,i)}}onCreateEffect(){if(this.mode===0){ek&&console.warn("DepthOfField: Mode is set to Off");return}const e=new exports.MODULES.POSTPROCESSING.MODULE.DepthOfFieldEffect(this.context.mainCamera,{worldFocusRange:.2,focalLength:1,bokehScale:20,resolutionScale:this.resolutionScale.value});return this.focusDistance.onValueChanged=t=>{e.cocMaterial.worldFocusDistance=t},this.focalLength.onValueChanged=t=>e.cocMaterial.worldFocusRange=t,this.aperture.onValueChanged=t=>e.bokehScale=t,this.resolutionScale&&(this.resolutionScale.onValueChanged=t=>e.resolution.scale=t),[e]}unapply(){}}gr([f()],an.prototype,"mode");gr([f(D)],an.prototype,"focusDistance");gr([f(D)],an.prototype,"focalLength");gr([f(D)],an.prototype,"aperture");gr([f(D)],an.prototype,"gaussianMaxRadius");gr([f(D)],an.prototype,"resolutionScale");gr([f(D)],an.prototype,"bokehScale");$i("DepthOfField",an);class Xl extends Ne{effect;constructor(e){super(),this.effect=e}get typeName(){return this.effect.constructor.name}onCreateEffect(){return this.effect}}var tk=Object.defineProperty,ik=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&tk(e,t,n),n};class Ic extends Ne{get typeName(){return"PixelationEffect"}granularity=new D(10);onCreateEffect(){const e=new exports.MODULES.POSTPROCESSING.MODULE.PixelationEffect;return this.granularity.onValueChanged=t=>{e.granularity=t},e}}ik([f(D)],Ic.prototype,"granularity");$i("PixelationEffect",Ic);var nk=Object.defineProperty,jc=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&nk(e,t,n),n};class _s extends Ne{get typeName(){return"ScreenSpaceAmbientOcclusion"}intensity=new D(2);falloff=new D(1);samples=new D(9);color=new D(new c.Color(0,0,0));luminanceInfluence=new D(.7);onBeforeRender(){if(this._ssao&&this.context.mainCamera instanceof c.PerspectiveCamera){const e=this.context.mainCamera.far-this.context.mainCamera.near;this._ssao.ssaoMaterial.worldDistanceFalloff=e*.01,this._ssao.ssaoMaterial.worldDistanceThreshold=this.context.mainCamera.far}}_ssao;onCreateEffect(){const e=this.context.mainCamera,t=new exports.MODULES.POSTPROCESSING.MODULE.NormalPass(this.context.scene,e),i=new exports.MODULES.POSTPROCESSING.MODULE.DepthDownsamplingPass({normalBuffer:t.texture,resolutionScale:.5}),n=this._ssao=new exports.MODULES.POSTPROCESSING.MODULE.SSAOEffect(e,t.texture,{normalDepthBuffer:i.texture,worldDistanceThreshold:1,worldDistanceFalloff:1,worldProximityThreshold:.1,worldProximityFalloff:2,intensity:1,blendFunction:exports.MODULES.POSTPROCESSING.MODULE.BlendFunction.MULTIPLY,luminanceInfluence:.5});this.intensity.onValueChanged=r=>{n.intensity=r},this.falloff.onValueChanged=r=>{n.ssaoMaterial.radius=r*.1},this.samples.onValueChanged=r=>{n.ssaoMaterial.samples=r},this.color.onValueChanged=r=>{n.color||(n.color=new c.Color),n.color.copy(r)},this.luminanceInfluence.onValueChanged=r=>{n.luminanceInfluence=r};const o=new Array;return o.push(t),o.push(i),o.push(n),o}}jc([f(D)],_s.prototype,"intensity");jc([f(D)],_s.prototype,"falloff");jc([f(D)],_s.prototype,"samples");jc([f(D)],_s.prototype,"color");jc([f(D)],_s.prototype,"luminanceInfluence");$i("ScreenSpaceAmbientOcclusion",_s);var sk=Object.defineProperty,yr=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&sk(e,t,n),n};const ok=w("debugN8AO");var kp=(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))(kp||{});class ln extends Ne{get typeName(){return"ScreenSpaceAmbientOcclusionN8"}get pass(){return this._ssao}gammaCorrection=!0;aoRadius=new D(1);falloff=new D(1);intensity=new D(1);color=new D(new c.Color(0,0,0));screenspaceRadius=!1;quality=2;_ssao;onValidate(){this._ssao&&(this._ssao.setQualityMode(kp[this.quality]),this._ssao.configuration.gammaCorrection=this.gammaCorrection,this._ssao.configuration.screenSpaceRadius=this.screenspaceRadius)}onCreateEffect(){const e=this.context.mainCamera,t=this.context.domWidth,i=this.context.domHeight,n=this._ssao=new exports.MODULES.POSTPROCESSING_AO.MODULE.N8AOPostPass(this.context.scene,e,t,i);n.name="SSAO_N8";const o=kp[this.quality];n.setQualityMode(o),n.configuration.transparencyAware=!1;const r=new c.WebGLRenderTarget(t,i);return n.configuration.beautyRenderTarget=r,n.configuration.autoRenderBeauty=!1,n.configuration.gammaCorrection=this.gammaCorrection,n.configuration.screenSpaceRadius=this.screenspaceRadius,ok&&(n.enableDebugMode(),console.log(n),setInterval(()=>{console.log("SSAO",n.lastTime)},1e3),setInterval(()=>{console.log("SSAO",n.enabled,{ssao:n,autoRenderBeauty:n.configuration.autoRenderBeauty})},4e3)),this.intensity.onValueChanged=a=>{n.configuration.intensity=a},this.falloff.onValueChanged=a=>{n.configuration.distanceFalloff=a},this.aoRadius.onValueChanged=a=>{n.configuration.aoRadius=a},this.color.onValueChanged=a=>{n.color||(n.color=new c.Color),n.configuration.color.copy(a)},n}}yr([gt(),f()],ln.prototype,"gammaCorrection");yr([f(D)],ln.prototype,"aoRadius");yr([f(D)],ln.prototype,"falloff");yr([f(D)],ln.prototype,"intensity");yr([f(D)],ln.prototype,"color");yr([gt(),f()],ln.prototype,"screenspaceRadius");yr([gt(),f()],ln.prototype,"quality");$i("ScreenSpaceAmbientOcclusionN8",ln);var rk=Object.defineProperty,ak=Object.getOwnPropertyDescriptor,sw=(s,e,t,i)=>{for(var n=ak(e,t),o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&rk(e,t,n),n};class Bc extends Ne{get typeName(){return"Sharpening"}order=Qe.Sharpening;_effect;onCreateEffect(){return this._effect??=new(lk()),this.effect}get effect(){return this._effect}set amount(e){this._amount=e,this._effect&&(this._effect.uniforms.get("amount").value=e)}get amount(){return this._effect?this._effect.uniforms.get("amount").value:this._amount}_amount=1;set radius(e){this._radius=e,this._effect&&(this._effect.uniforms.get("radius").value=e)}get radius(){return this._effect?this._effect.uniforms.get("radius").value:this._radius}_radius=1}sw([f()],Bc.prototype,"amount");sw([f()],Bc.prototype,"radius");function lk(){const s=`
1284
+ `)}r&&o.size&&console.log(u);const y=new Set;for(const v of m){v.getPath||console.error("USDZExporter: Animation target object has no getPath method. This is likely a bug",v);let _=v.getPath();_.startsWith("<")&&(_=_.substring(1)),_.endsWith(">")&&(_=_.substring(0,_.length-1)),y.add({path:_,obj:v})}const b=Array.from(y).sort((v,_)=>v.path.length-_.path.length),g=new Array;for(let v=0;v<b.length;v++)for(let _=v+1;_<b.length;_++)if(b[_].path.startsWith(b[v].path)){const S=b[_],T=b[v];g.push({child:S.obj.displayName+" ("+S.path+")",parent:T.obj.displayName+" ("+T.path+")"})}g.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:g,playAnimationActions:o})}for(const u of new Set([...t,...i]))if(Array.isArray(u))for(const p of u)n.add(p.uuid);else n.add(u.uuid);_h&&console.log("All Behavior trigger sources and action targets",t,i,n),this.targetUuids=new Set(n)}onAfterHierarchy(e,t){if(this.behaviours?.length){t.beginBlock('def Scope "Behaviors"');for(const i of this.behaviours)i.writeTo(this,e.document,t);t.closeBlock()}}async onAfterSerialize(e){_h&&console.log("onAfterSerialize behaviours",this.behaviourComponentsCopy);for(const t of this.behaviourComponentsCopy)typeof t.afterSerialize=="function"&&(t.afterSerialize.constructor.name==="AsyncFunction"?await t.afterSerialize(this,e):t.afterSerialize(this,e));for(const{clipUrl:t,filesKey:i}of this.audioClipsCopy){if(e.files[i])return;const r=await(await(await fetch(t)).blob()).arrayBuffer(),a=new Uint8Array(r);e.files[i]=a}this.behaviourComponentsCopy.length=0,this.audioClipsCopy.length=0}}class og{get extensionName(){return"Physics"}onExportObject(e,t,i){const n=x.getComponents(e,Ke).filter(l=>l.enabled),o=x.getComponents(e,Qt).filter(l=>l.enabled&&!l.isTrigger);let r=n.length>0?n[0]:null;const a=o.length>0?o[0]:null;a&&!r&&(r=new Ke,r.isKinematic=!0),r&&t.addEventListener("serialize",(l,h)=>{if(r){if(l.appendLine(),l.beginBlock('def RealityKitComponent "RigidBody"',"{",!0),r.useGravity||l.appendLine("bool gravityEnabled = 0"),l.appendLine('uniform token info:id = "RealityKit.RigidBody"'),r.isKinematic&&l.appendLine('token motionType = "Kinematic"'),l.beginBlock('def RealityKitStruct "massFrame"',"{",!0),l.appendLine(`float m_mass = ${r.mass}`),l.beginBlock('def RealityKitStruct "m_pose"',"{",!0),l.appendLine(`float3 position = (${r.centerOfMass.x}, ${r.centerOfMass.y}, ${r.centerOfMass.z})`),l.closeBlock("}"),l.closeBlock("}"),o.length>0){const d=o[0];l.beginBlock('def RealityKitStruct "material"',"{",!0);const u=d.sharedMaterial;u&&u.dynamicFriction!==void 0&&l.appendLine(`double dynamicFriction = ${d.sharedMaterial?.dynamicFriction}`),u&&u.bounciness!==void 0&&l.appendLine(`double restitution = ${d.sharedMaterial?.bounciness}`),u&&u.staticFriction!==void 0&&l.appendLine(`double staticFriction = ${d.sharedMaterial?.staticFriction}`),l.closeBlock("}")}l.closeBlock("}")}}),a&&(t.addEventListener("serialize",(l,h)=>{l.beginBlock('def RealityKitComponent "Collider"',"{",!0),l.appendLine("uint group = 1"),l.appendLine('uniform token info:id = "RealityKit.Collider"'),l.appendLine("uint mask = 4294967295");const u=a.isTrigger?"Trigger":"Default";if(l.appendLine(`token type = "${u}"`),l.beginBlock('def RealityKitStruct "Shape"',"{",!0),a instanceof ga){const p=a;l.appendLine('token shapeType = "Sphere"'),l.appendLine(`float radius = ${p.radius}`)}else if(a instanceof Xd){const p=a;l.appendLine('token shapeType = "Box"'),l.appendLine(`float3 extent = (${p.size.x}, ${p.size.y}, ${p.size.z})`)}else if(a instanceof as){const p=a;l.appendLine('token shapeType = "Capsule"'),l.appendLine(`float radius = ${p.radius}`),l.appendLine(`float height = ${p.height}`)}else if(a instanceof io&&a.sharedMesh?.geometry){const p=a.sharedMesh.geometry;p.boundingBox||p.computeBoundingBox();const m=a.sharedMesh.geometry.boundingBox;m&&(l.appendLine('token shapeType = "Box"'),l.appendLine(`float3 extent = (${m.max.x-m.min.x}, ${m.max.y-m.min.y}, ${m.max.z-m.min.z})`),console.log("[USDZ] Only Box, Sphere, and Capsule colliders are supported in visionOS/iOS. MeshCollider will be exported as Box",a))}else console.warn("[USDZ] Only Box, Sphere, and Capsule colliders are supported in visionOS/iOS. Ignoring collider:",a);l.beginBlock('def RealityKitStruct "pose"',"{",!0),l.closeBlock("}"),l.closeBlock("}"),l.closeBlock("}")}),o.length>1&&console.log("WARNING: Multiple colliders detected. visionOS / iOS can only support objects with a single collider, only exporting the first collider: ",a))}}const AM=w("debugshadowcomponents");J.__webpack_exports__Block.prototype.interactable={get(){return this.interactive},set(s){this.interactable=s}};class Bi extends k{isRoot(){return this.Root?.gameObject===this.gameObject}get canvas(){const e=this.Root;return e?.isCanvas?e:null}get Canvas(){return this.canvas}markDirty(){jt.markUIDirty(this.context)}get shadowComponent(){return this._shadowComponent}set shadowComponent(e){this._shadowComponent=e}_shadowComponent=null;_controlsChildLayout=!0;get controlsChildLayout(){return this._controlsChildLayout}set controlsChildLayout(e){this._controlsChildLayout=e,this.shadowComponent&&(this.shadowComponent.autoLayout=e)}_root=void 0;get Root(){return this._root===void 0&&(this._root=x.getComponentInParent(this.gameObject,Cc)),this._root}_parentComponent=void 0;__internalNewInstanceCreated(e){return super.__internalNewInstanceCreated(e),this.shadowComponent=null,this._root=void 0,this._parentComponent=void 0,this}onEnable(){super.onEnable()}addShadowComponent(e,t){if(!e)return;this.removeShadowComponent();const i=this.isRoot()?this.gameObject:this.gameObject.parent;if(this._parentComponent=x.getComponentInParent(i,Bi),!this._parentComponent){console.warn(`Component "${this.name}" doesn't have a UI parent anywhere. Do you have an UI element outside a Canvas? UI components must be a child of a Canvas component`,this);return}e.name=this.name+" ("+(this.constructor.name??"UI")+")",e.autoLayout=this._parentComponent.controlsChildLayout,e[si]=this,this.setShadowComponentOwner(e);let n=!1;if(this.Root?.gameObject===this.gameObject)this.gameObject.add(e);else{const o=this._parentComponent.shadowComponent;o&&(o?.add(e),n=!0)}this.shadowComponent=e,t&&t.shadowComponent&&this.shadowComponent&&t.shadowComponent.add(this.shadowComponent),oc&&e.add(new c.AxesHelper(.5)),this.onAfterAddedToScene(),n&&J.__webpack_exports__update(),AM&&console.warn("Added shadow component",this.shadowComponent)}setShadowComponentOwner(e){if(e&&(e[si]===void 0||e[si]===this)&&(e[si]=this,e.children))for(const t of e.children)this.setShadowComponentOwner(t)}traverseOwnedShadowComponents(e,t,i){if(e&&e[si]===t){i(e);for(const n of e.children)this.traverseOwnedShadowComponents(n,t,i)}}removeShadowComponent(){this.shadowComponent&&this.shadowComponent.removeFromParent()}onAfterAddedToScene(){}setInteractable(e){this.shadowComponent&&(this.shadowComponent.interactable=e)}}class Cc extends Bi{awake(){super.awake()}}var LM=Object.defineProperty,DM=Object.getOwnPropertyDescriptor,Pc=(s,e,t,i)=>{for(var n=i>1?void 0:i?DM(e,t):e,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&LM(e,t,n),n};const bf=w("debugui"),vf=w("debuguilayout");class $v{width;height}class Wv{x;y;width;height}const qi=new c.Vector3,Ga=new c.Matrix4,bh=new c.Quaternion,xa=class Gv extends Bi{get parent(){return this._parentRectTransform}get translation(){return this.gameObject.position}get rotation(){return this.gameObject.quaternion}get scale(){return this.gameObject.scale}_anchoredPosition;get anchoredPosition(){return this._anchoredPosition||(this._anchoredPosition=new c.Vector2),this._anchoredPosition}set anchoredPosition(e){this._anchoredPosition=e}sizeDelta=new c.Vector2(100,100);pivot=new c.Vector2(.5,.5);anchorMin=new c.Vector2(0,0);anchorMax=new c.Vector2(1,1);minWidth;minHeight;get width(){let e=this.sizeDelta.x;if(this.anchorMin.x!==this.anchorMax.x&&this._parentRectTransform){const t=this._parentRectTransform.width,i=this.anchorMax.x-this.anchorMin.x;e=t*i,e+=this.sizeDelta.x}return this.minWidth!==void 0&&e<this.minWidth?this.minWidth:e}get height(){let e=this.sizeDelta.y;if(this.anchorMin.y!==this.anchorMax.y&&this._parentRectTransform){const t=this._parentRectTransform.height,i=this.anchorMax.y-this.anchorMin.y;e=t*i,e+=this.sizeDelta.y}return this.minHeight!==void 0&&e<this.minHeight?this.minHeight:e}lastMatrix;rectBlock;_transformNeedsUpdate=!1;_initialPosition;_parentRectTransform;_lastUpdateFrame=-1;awake(){super.awake(),this._lastUpdateFrame=-1,this._parentRectTransform=void 0,this.rectBlock=new c.Object3D,this.rectBlock.name=this.name,this.lastMatrix=new c.Matrix4,this._lastAnchoring=null,this._initialPosition=this.gameObject.position.clone(),this._initialPosition.z=0,this._anchoredPosition||(this._anchoredPosition=new c.Vector2),Ar(this,"_anchoredPosition",()=>{this.markDirty()}),Ar(this,"sizeDelta",()=>{this.markDirty()}),Ar(this,"pivot",()=>{this.markDirty()}),Ar(this,"anchorMin",()=>{this.markDirty()}),Ar(this,"anchorMax",()=>{this.markDirty()})}onEnable(){super.onEnable(),this.rectBlock||(this.rectBlock=new c.Object3D),this.lastMatrix||(this.lastMatrix=new c.Matrix4),this._lastAnchoring||(this._lastAnchoring=new c.Vector2),this._initialPosition||(this._initialPosition=new c.Vector3),this._anchoredPosition||(this._anchoredPosition=new c.Vector2),this.addShadowComponent(this.rectBlock),this._transformNeedsUpdate=!0,this.canvas?.registerTransform(this)}onDisable(){super.onDisable(),this.removeShadowComponent(),this.canvas?.unregisterTransform(this)}onParentRectTransformChanged(e){this._transformNeedsUpdate||this.onApplyTransform(vf?`${e.name} changed`:void 0)}get isDirty(){return this._transformNeedsUpdate||(this._transformNeedsUpdate=!this.lastMatrix.equals(this.gameObject.matrix)),this._transformNeedsUpdate}markDirty(){this._transformNeedsUpdate||(vf&&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(e){if(this.context.time.frameCount===this._lastUpdateFrame)return;this._lastUpdateFrame=this.context.time.frameCount;const t=this.shadowComponent;if(!t)return;this.gameObject.parent?this._parentRectTransform=x.getComponentInParent(this.gameObject.parent,Gv):this._parentRectTransform=void 0,this._transformNeedsUpdate=!1,vf&&console.warn("RectTransform → ApplyTransform",this.name+" because "+e),this.isRoot()?this.Root.screenspace||(t.rotation.y=Math.PI):(t.matrix.identity(),t.matrixAutoUpdate=!1,qi.set(0,0,0),this.applyPivot(qi),t.matrix.setPosition(qi.x,qi.y,0),(this.gameObject.quaternion.x||this.gameObject.quaternion.y||this.gameObject.quaternion.z)&&(bh.copy(this.gameObject.quaternion),bh.x*=-1,bh.z*=-1,Ga.makeRotationFromQuaternion(bh),t.matrix.premultiply(Ga)),qi.set(0,0,0),this.applyAnchoring(qi),this.canvas?.screenspace?qi.z+=.1:qi.z+=.01,Ga.identity(),Ga.setPosition(qi.x,qi.y,qi.z),t.matrix.premultiply(Ga),t.matrix.scale(this.gameObject.scale)),this.lastMatrix.copy(this.gameObject.matrix);const i=!0;for(const n of Fd(this.gameObject,Bi,i,1)){if(n===this||!n.activeAndEnabled)continue;const o=n;o.onParentRectTransformChanged&&o.onParentRectTransformChanged(this)}}_lastAnchoring;applyAnchoring(e){this._lastAnchoring||(this._lastAnchoring=new c.Vector2);const t=this._lastAnchoring.sub(this._anchoredPosition);this.gameObject.position.x+=t.x,this.gameObject.position.y+=t.y,this._lastAnchoring.copy(this._anchoredPosition),e.x+=this._initialPosition.x-this.gameObject.position.x,e.y+=this._initialPosition.y-this.gameObject.position.y,e.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,e.y+=n;let r=0;const a=1-this.anchorMax.x-this.anchorMin.x;r-=i.width*.5*a,e.x+=r}}applyPivot(e){if(this.pivot&&!this.isRoot()){const t=this.pivot.x-.5;e.x-=t*this.sizeDelta.x*this.gameObject.scale.x;const i=this.pivot.y-.5;e.y-=i*this.sizeDelta.y*this.gameObject.scale.y}}getBasicOptions(){const e={width:this.sizeDelta.x,height:this.sizeDelta.y,offset:0,backgroundOpacity:0,borderWidth:0,borderRadius:0,borderOpacity:0,letterSpacing:-.03};return this.ensureValidSize(e),e}ensureValidSize(e,t=1e-4){return e.width<=0&&(e.width=t),e.height<=0&&(e.height=1e-4),e}_createdBlocks=[];_createdTextBlocks=[];createNewBlock(e){e={...this.getBasicOptions(),...e},bf&&console.log(this.name,e);const t=new J.__webpack_exports__Block(e);return this._createdBlocks.push(t),t}createNewText(e){bf&&console.log(e),e={...this.getBasicOptions(),...e},bf&&console.log(this.name,e);const t=new J.__webpack_exports__Text(e);return this._createdTextBlocks.push(t),t}};Pc([f(c.Vector2)],xa.prototype,"anchoredPosition",1);Pc([f(c.Vector2)],xa.prototype,"sizeDelta",2);Pc([f(c.Vector2)],xa.prototype,"pivot",2);Pc([f(c.Vector2)],xa.prototype,"anchorMin",2);Pc([f(c.Vector2)],xa.prototype,"anchorMax",2);let nn=xa;var IM=Object.defineProperty,Hv=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&IM(e,t,n),n};class Sa extends k{effectColor;effectDistance}Hv([f(Z)],Sa.prototype,"effectColor");Hv([f(c.Vector2)],Sa.prototype,"effectDistance");var jM=Object.defineProperty,BM=Object.getOwnPropertyDescriptor,qv=(s,e,t,i)=>{for(var n=i>1?void 0:i?BM(e,t):e,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&jM(e,t,n),n};const vh={backgroundColor:new c.Color(1,1,1),backgroundOpacity:1,borderColor:new c.Color(1,1,1),borderOpacity:1},rg=class ul extends Bi{get isGraphic(){return!0}get color(){return this._color||(this._color=new Z(1,1,1,1)),this._color}set color(e){(!this._color||this._color.r!==e.r||this._color.g!==e.g||this._color.b!==e.b||this._color.alpha!==e.alpha)&&(this._color||(this._color=new Z(1,1,1,1)),this._color.copy(e),this.onColorChanged())}_alphaFactor=1;setAlphaFactor(e){this._alphaFactor=e,this.onColorChanged()}get alphaFactor(){return this._alphaFactor}sRGBColor=new c.Color(1,0,1);onColorChanged(){this.uiObject&&(this.sRGBColor.copy(this._color),this.sRGBColor.convertLinearToSRGB(),vh.backgroundColor=this.sRGBColor,vh.backgroundOpacity=this._color.alpha*this._alphaFactor,this.applyEffects(vh,this._alphaFactor),this.uiObject.set(vh),this.markDirty())}get m_Color(){return this._color}raycastTarget=!0;uiObject=null;_color=null;_rect=null;_stateManager=null;get rectTransform(){if(this._rect||(this._rect=x.getComponent(this.gameObject,nn)),!this._rect)throw new Error("Not Supported: Make sure to add a RectTransform component before adding a UI Graphic component.");return this._rect}onParentRectTransformChanged(){this.uiObject?.set({width:this.rectTransform.width,height:this.rectTransform.height}),this.markDirty()}__internalNewInstanceCreated(e){return super.__internalNewInstanceCreated(e),this._rect=null,this.uiObject=null,this._stateManager=null,this._color&&(this._color=this._color.clone()),this}setState(e){this.makePanel(),this.uiObject&&(this.uiObject.setState(e),this?.markDirty())}setupState(e){this.makePanel(),this.uiObject&&(this._stateManager||(this._stateManager=new J.SimpleStateBehavior(this.uiObject)),this.uiObject.setupState(e.state,e.attributes))}setOptions(e){this.makePanel(),this.uiObject&&this.uiObject.set(e)}awake(){super.awake(),this.makePanel(),Ar(this,"_color",()=>A1(this,this.onColorChanged))}onEnable(){super.onEnable(),this.uiObject&&(this.rectTransform.shadowComponent?.add(this.uiObject),this.addShadowComponent(this.uiObject,this.rectTransform))}onDisable(){super.onDisable(),this.uiObject&&this.removeShadowComponent()}_currentlyCreatingPanel=!1;makePanel(){if(this.uiObject||this._currentlyCreatingPanel)return;this._currentlyCreatingPanel=!0;const t={backgroundColor:this.color,backgroundOpacity:this.color.alpha,offset:.015};this.onBeforeCreate(t),this.applyEffects(t),this.onCreate(t),this.controlsChildLayout=!1,this._currentlyCreatingPanel=!1,this.onAfterCreated(),this.onColorChanged()}onBeforeCreate(e){}onCreate(e){this.uiObject=this.rectTransform.createNewBlock(e),this.uiObject.name=this.name}onAfterCreated(){}applyEffects(e,t=1){const i=this.gameObject?.getComponent(Sa);i&&(i.effectDistance&&(e.borderWidth=Math.max(Math.abs(i.effectDistance.x),Math.abs(i.effectDistance.y))),i.effectColor&&(e.borderColor=i.effectColor,e.borderOpacity=i.effectColor.alpha*t))}static textureCache=new Map;async setTexture(e){if(this.setOptions({backgroundOpacity:0}),e){if(ul.textureCache.has(e))e=ul.textureCache.get(e);else if(!e.isRenderTargetTexture){const t=e.clone();t.colorSpace=c.LinearSRGBColorSpace,ul.textureCache.set(e,t),e=t}this.setOptions({backgroundImage:e,borderRadius:0,backgroundOpacity:this.color.alpha,backgroundSize:"stretch"}),ne.NEEDLE_progressive.assignTextureLOD(e,0).then(t=>{t instanceof c.Texture&&(e&&ul.textureCache.set(e,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)}};qv([f(Z)],rg.prototype,"color",1);qv([f()],rg.prototype,"raycastTarget",2);let Mc=rg;class Oc extends Mc{_flippedObject=!1;onAfterCreated(){this.uiObject&&!this._flippedObject&&(this._flippedObject=!0,this.uiObject.scale.y*=-1)}}var FM=Object.defineProperty,UM=Object.getOwnPropertyDescriptor,ms=(s,e,t,i)=>{for(var n=i>1?void 0:i?UM(e,t):e,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&FM(e,t,n),n};const go=w("debugtext");var qe=(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))(qe||{}),Xv=(s=>(s[s.Normal=0]="Normal",s[s.Bold=1]="Bold",s[s.Italic=2]="Italic",s[s.BoldAndItalic=3]="BoldAndItalic",s))(Xv||{});class Ct extends Mc{alignment=0;verticalOverflow=0;horizontalOverflow=0;lineSpacing=1;supportRichText=!1;font;fontStyle=0;setAlphaFactor(e){super.setAlphaFactor(e),this.uiObject?.set({fontOpacity:this.color.alpha*this.alphaFactor}),this.markDirty()}get text(){return this._text}set text(e){e!==this._text&&(this._text=e,this.feedText(this.text,this.supportRichText),this.markDirty())}set_text(e){this.text=e}get fontSize(){return this._fontSize}set fontSize(e){this._fontSize=e,this.uiObject?.set({fontSize:e})}sRGBTextColor=new c.Color(1,0,1);onColorChanged(){this.sRGBTextColor.copy(this.color),this.sRGBTextColor.convertLinearToSRGB(),this.uiObject?.set({color:this.sRGBTextColor,fontOpacity:this.color.alpha})}onParentRectTransformChanged(){super.onParentRectTransformChanged(),this.uiObject&&this.updateOverflow()}onBeforeCanvasRender(e){this.updateOverflow()}updateOverflow(){const e=this.uiObject?._overflow;e&&(e._needsUpdate=!0)}onCreate(e){go&&console.log(this),this.horizontalOverflow==1&&(e.whiteSpace="pre"),this.verticalOverflow==0&&(this.context.renderer.localClippingEnabled=!0,e.overflow="hidden"),this.horizontalOverflow==1&&this.verticalOverflow==0,e.lineHeight=this.lineSpacing,delete e.backgroundOpacity,delete e.backgroundColor,go&&(e.backgroundColor=16750848,e.backgroundOpacity=.5);const t=this.rectTransform;e={...e,...this.getTextOpts()},this.getAlignment(e),go&&(e.backgroundColor=Math.random()*16777215,e.backgroundOpacity=.1),this.uiObject=t.createNewText(e),this.feedText(this.text,this.supportRichText)}onAfterAddedToScene(){super.onAfterAddedToScene(),this.handleTextRenderOnTop()}_text="";_fontSize=12;_textMeshUi=null;getTextOpts(){const e=this.fontSize,t={color:this.color,fontOpacity:this.color.alpha,fontSize:e,fontKerning:"normal"};return this.setFont(t,this.fontStyle),t}onEnable(){super.onEnable(),this._didHandleTextRenderOnTop=!1,this.uiObject&&this.uiObject.addAfterUpdate(()=>{this.setShadowComponentOwner(this.uiObject),this.markDirty()}),setTimeout(()=>this.markDirty(),10),this.canvas?.registerEventReceiver(this)}onDisable(){super.onDisable(),this.canvas?.unregisterEventReceiver(this)}getAlignment(e){switch(e.flexDirection="column",this.alignment){case 0:case 3:case 6:e.textAlign="left";break;case 1:case 4:case 7:e.textAlign="center";break;case 2:case 5:case 8:e.textAlign="right";break}switch(this.alignment){default:case 0:case 1:case 2:e.alignItems="start";break;case 3:case 4:case 5:e.alignItems="center";break;case 6:case 7:case 8:e.alignItems="end";break}return e}feedText(e,t){if(go&&console.log("feedText",this.uiObject,e,t),!!this.uiObject)if(this._textMeshUi||(this._textMeshUi=[]),this.uiObject.children.length=0,!t||e.length===0)this.uiObject.textContent=e;else{let i=this.getNextTag(e);if(i){if(i.startIndex>0){for(let r=this.uiObject.children.length-1;r>=0;r--){const a=this.uiObject.children[r];a.isUI&&(this.uiObject.remove(a),a.clear())}const o=new J.__webpack_exports__Inline({textContent:e.substring(0,i.startIndex),color:"inherit"});this.uiObject.add(o)}}else{this.uiObject.textContent="",this.setOptions({textContent:e});return}const n=[];for(;i;){const o=this.getNextTag(e,i.endIndex),r={fontFamily:this.uiObject?.get("fontFamily"),color:"inherit",textContent:""};if(o){r.textContent=this.getText(e,i,o),this.handleTag(i,r,n);const a=new J.__webpack_exports__Inline(r);this.uiObject?.add(a)}else{r.textContent=e.substring(i.endIndex),this.handleTag(i,r,n);const a=new J.__webpack_exports__Inline(r);this.uiObject?.add(a)}i=o}}}_didHandleTextRenderOnTop=!1;handleTextRenderOnTop(){this._didHandleTextRenderOnTop||(this._didHandleTextRenderOnTop=!0,this.startCoroutine(this.renderOnTopCoroutine()))}*renderOnTopCoroutine(){if(!this.canvas)return;const e=[],t=this.canvas,i={renderOnTop:t.renderOnTop,depthWrite:t.depthWrite,doubleSided:t.doubleSided};for(;;){let n=!1;if(this._textMeshUi)for(let o=0;o<this._textMeshUi.length;o++){if(e[o]===!0)continue;n=!0;const r=this._textMeshUi[o];r.textContent&&(ud(r,i),e[o]=!0)}if(!n)break;yield}}handleTag(e,t,i){if(!e.isEndTag){if(e.type.includes("color")){const n=new wf(e,{color:t.color});if(i.push(n),e.type.length>6){const o=parseInt("0x"+e.type.substring(7));t.color=o}else t.color=new c.Color(1,1,1)}else if(e.type=="b"){this.setFont(t,1);const n=new wf(e,{fontWeight:700});i.push(n)}else if(e.type=="i"){this.setFont(t,2);const n=new wf(e,{fontStyle:"italic"});i.push(n)}}}getText(e,t,i){return e.substring(t.endIndex,i.startIndex)}getNextTag(e,t=0){const i=e.indexOf("<",t),n=e.indexOf(">",i);if(i>=0&&n>=0){const o=e.substring(i+1,n);return{type:o,startIndex:i,endIndex:n+1,isEndTag:o.startsWith("/")}}return null}setFont(e,t){if(!this.font)return;const i=this.font,n=this.getFamilyNameWithCorrectSuffix(i,t);go&&console.log("Selected font family:"+n);let o=J.__webpack_exports__FontLibrary.getFontFamily(n);switch(o||(o=J.__webpack_exports__FontLibrary.addFontFamily(n)),e.fontFamily=o,t){default:case 0:e.fontWeight=400,e.fontStyle="normal";break;case 1:e.fontWeight=700,e.fontStyle="normal";break;case 2:e.fontWeight=400,e.fontStyle="italic";break;case 3:e.fontStyle="italic",e.fontWeight=400}let r=o.getVariant(e.fontWeight,e.fontStyle);if(!r){let a=n;a?.endsWith("-msdf.json")||(a+="-msdf.json");let l=n;l?.endsWith(".png")||(l+=".png"),r=o.addVariant(e.fontWeight,e.fontStyle,a,l),r?.addEventListener("ready",()=>{this.markDirty()})}}getFamilyNameWithCorrectSuffix(e,t){const i=e.lastIndexOf("-");if(i<0)return e;const n=e.substring(i+1)?.toLowerCase();if(zM.includes(n))return go&&console.warn("Unsupported font style: "+n),e;const o=e.lastIndexOf("/");let r=e;o>=0&&(r=r.substring(o+1));const a=r[0]===r[0].toUpperCase(),l=e.substring(0,i);switch(go&&console.log("Select font: ",e,Xv[t],r,a,l),t){case 0:return a?l+"-Regular":l+"-regular";case 1:return a?l+"-Bold":l+"-bold";case 2:return a?l+"-Italic":l+"-italic";case 3:return a?l+"-BoldItalic":l+"-bolditalic";default:return e}}}ms([f()],Ct.prototype,"alignment",2);ms([f()],Ct.prototype,"verticalOverflow",2);ms([f()],Ct.prototype,"horizontalOverflow",2);ms([f()],Ct.prototype,"lineSpacing",2);ms([f()],Ct.prototype,"supportRichText",2);ms([f(URL)],Ct.prototype,"font",2);ms([f()],Ct.prototype,"fontStyle",2);ms([f()],Ct.prototype,"text",1);ms([f()],Ct.prototype,"fontSize",1);class wf{tag;previousValues;constructor(e,t){this.tag=e,this.previousValues=t}}const zM=["medium","mediumitalic","black","blackitalic","thin","thinitalic","extrabold","light","lightitalic","semibold"];class Vr{static global_id=0;static getId(){return this.global_id++}id;content="";font=[];pointSize=144;width;height;depth;wrapMode;horizontalAlignment;verticalAlignment;material;setDepth(e){return this.depth=e,this}setPointSize(e){return this.pointSize=e,this}setHorizontalAlignment(e){return this.horizontalAlignment=e,this}setVerticalAlignment(e){return this.verticalAlignment=e,this}constructor(e){this.id=e}writeTo(e,t){t.beginBlock(`def Preliminary_Text "${this.id}"`,"(",!1),t.appendLine('prepend apiSchemas = ["MaterialBindingAPI"]'),t.closeBlock(")"),t.beginBlock(),this.content&&t.appendLine(`string content = "${this.content}"`),(!this.font||this.font.length<=0)&&(this.font||=[],this.font?.push("sans-serif"));const i=this.font.map(n=>`"${n}"`).join(", ");t.appendLine(`string[] font = [ ${i} ]`),t.appendLine(`double pointSize = ${this.pointSize}`),typeof this.width=="number"&&t.appendLine(`double width = ${this.width}`),typeof this.height=="number"&&t.appendLine(`double height = ${this.height}`),typeof this.depth=="number"&&t.appendLine(`double depth = ${this.depth}`),this.wrapMode&&t.appendLine(`token wrapMode = "${this.wrapMode}"`),this.horizontalAlignment&&t.appendLine(`token horizontalAlignment = "${this.horizontalAlignment}"`),this.verticalAlignment&&t.appendLine(`token verticalAlignment = "${this.verticalAlignment}"`),this.material!==void 0&&t.appendLine(`rel material:binding = </StageRoot/Materials/${Zd(this.material)}>`),t.closeBlock()}}class ag{static singleLine(e,t,i){const n=new Vr("text_"+Vr.getId());return n.content=e,t&&(n.pointSize=t),i&&(n.depth=i),n}static multiLine(e,t,i,n,o,r){const a=new Vr("text_"+Vr.getId());return a.content=e,a.width=t,a.height=i,a.horizontalAlignment=n,a.verticalAlignment=o,r!==void 0&&(a.wrapMode=r),a}}const NM=new c.Matrix4().makeRotationY(Math.PI),VM=new c.Matrix4().makeScale(-1,1,-1);class ru{get extensionName(){return"text"}exportText(e,t,i){const n=x.getComponent(e,Ct);if(!n)return;const o=x.getComponent(e,nn);let r=100,a=100;o&&(r=o.width,a=o.height);const l=NM.clone();o&&l.premultiply(VM),t.setMatrix(l);const h=n.color.clone();t.material=new c.MeshStandardMaterial({color:h,emissive:h}),t.addEventListener("serialize",(d,u)=>{let p=n.text;p=p.replace(/\r/g,""),p=p.replace(/\n/g,"\\n");const m=ag.multiLine(p,r,a,"center","bottom","flowing");this.setTextAlignment(m,n.alignment),this.setOverflow(m,n),t.material&&(m.material=t.material),m.pointSize=this.convertToTextSize(n.fontSize),m.depth=.001,m.writeTo(void 0,d)})}convertToTextSize(e){return 1/.0502*144*e}setOverflow(e,t){t.horizontalOverflow?e.wrapMode="singleLine":e.wrapMode="flowing"}setTextAlignment(e,t){switch(t){case qe.LowerLeft:case qe.MiddleLeft:case qe.UpperLeft:e.horizontalAlignment="left";break;case qe.LowerCenter:case qe.MiddleCenter:case qe.UpperCenter:e.horizontalAlignment="center";break;case qe.LowerRight:case qe.MiddleRight:case qe.UpperRight:e.horizontalAlignment="right";break}switch(t){case qe.LowerLeft:case qe.LowerCenter:case qe.LowerRight:e.verticalAlignment="bottom";break;case qe.MiddleLeft:case qe.MiddleCenter:case qe.MiddleRight:e.verticalAlignment="middle";break;case qe.UpperLeft:case qe.UpperCenter:case qe.UpperRight:e.verticalAlignment="top";break}}}var $M=Object.defineProperty,Ve=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&$M(e,t,n),n};const __=w("debuguilayout");class cr{left=0;right=0;top=0;bottom=0;get vertical(){return this.top+this.bottom}get horizontal(){return this.left+this.right}}Ve([f()],cr.prototype,"left");Ve([f()],cr.prototype,"right");Ve([f()],cr.prototype,"top");Ve([f()],cr.prototype,"bottom");class gi extends k{_rectTransform=null;get rectTransform(){return this._rectTransform}onParentRectTransformChanged(e){this._needsUpdate=!0}_needsUpdate=!1;get isDirty(){return this._needsUpdate}get isLayoutGroup(){return!0}updateLayout(){this._rectTransform&&(__&&console.warn("Layout Update",this.context.time.frame,this.name),this._needsUpdate=!1,this.onCalculateLayout(this._rectTransform))}childAlignment=0;reverseArrangement=!1;spacing=0;padding;minWidth=0;minHeight=0;flexibleHeight=0;flexibleWidth=0;preferredHeight=0;preferredWidth=0;start(){this._needsUpdate=!0}onEnable(){__&&console.log(this.name,this),this._rectTransform=this.gameObject.getComponent(nn);const e=this.gameObject.getComponentInParent(ca);e&&e.registerLayoutGroup(this),this._needsUpdate=!0}onDisable(){const e=this.gameObject.getComponentInParent(ca);e&&e.unregisterLayoutGroup(this)}set m_Spacing(e){e!==this.spacing&&(this._needsUpdate=!0,this.spacing=e)}get m_Spacing(){return this.spacing}}Ve([f()],gi.prototype,"childAlignment");Ve([f()],gi.prototype,"reverseArrangement");Ve([f()],gi.prototype,"spacing");Ve([f(cr)],gi.prototype,"padding");Ve([f()],gi.prototype,"minWidth");Ve([f()],gi.prototype,"minHeight");Ve([f()],gi.prototype,"flexibleHeight");Ve([f()],gi.prototype,"flexibleWidth");Ve([f()],gi.prototype,"preferredHeight");Ve([f()],gi.prototype,"preferredWidth");class oo extends gi{childControlHeight=!0;childControlWidth=!0;childForceExpandHeight=!1;childForceExpandWidth=!1;childScaleHeight=!1;childScaleWidth=!1;onCalculateLayout(e){const t=this.primaryAxis,i=e.width;let n=i;const o=e.height;let r=o;n-=this.padding.horizontal,r-=this.padding.vertical,t==="x"?this.padding.horizontal:this.padding.vertical;const a=t==="x",l=a?"y":"x",h=a?this.childControlWidth:this.childControlHeight,d=a?this.childControlHeight:this.childControlWidth,u=a?this.childForceExpandWidth:this.childForceExpandHeight,p=a?this.childForceExpandHeight:this.childForceExpandWidth,m=a?r:n,y=a?i:o,b=.5*(a?this.childAlignment%3:Math.floor(this.childAlignment/3));let g=0;a?g+=this.padding.left:g+=this.padding.top;let v=0,_=0;for(let R=0;R<this.gameObject.children.length;R++){const B=this.gameObject.children[R],L=x.getComponent(B,nn);L?.activeAndEnabled&&(_+=1,a?v+=L.width:v+=L.height)}let S=0;const T=this.spacing*(_-1);if(u||h){let R=0;a?R=n-=T:R=r-=T,_>0&&(S=R/_)}let M=0;M+=this.padding.left,M-=this.padding.right,b!==0&&(g=y-v,g*=b,g-=T*b,a?(g-=this.padding.right*b,g+=this.padding.left*(1-b),g<this.padding.left&&(g=this.padding.left)):(g-=this.padding.bottom*b,g+=this.padding.top*(1-b),g<this.padding.top&&(g=this.padding.top)));let O=1;for(let R=0;R<this.gameObject.children.length;R++){const B=this.gameObject.children[R],L=x.getComponent(B,nn);if(L?.activeAndEnabled){L.pivot?.set(.5,.5),L.anchorMin.set(0,1),L.anchorMax.set(0,1);const N=i*.5+M*.5;L.anchoredPosition.x!==N&&(L.anchoredPosition.x=N);const $=o*-.5;L.anchoredPosition.y!==$&&(L.anchoredPosition.y=$),p&&d&&L.sizeDelta[l]!==m&&(L.sizeDelta[l]=m),u&&h&&L.sizeDelta[t]!==S&&(L.sizeDelta[t]=S);const E=a?L.width:L.height,F=E*.5;if(g+=F,u){const K=S*O-S*.5;K>g&&(g=K-S*.5+E+this.padding.left,g-=F)}let z=g;t==="y"&&(z=-z),L.anchoredPosition[t]!==z&&(L.anchoredPosition[t]=z),g+=F,g+=this.spacing,O+=1}}}}Ve([f()],oo.prototype,"childControlHeight");Ve([f()],oo.prototype,"childControlWidth");Ve([f()],oo.prototype,"childForceExpandHeight");Ve([f()],oo.prototype,"childForceExpandWidth");Ve([f()],oo.prototype,"childScaleHeight");Ve([f()],oo.prototype,"childScaleWidth");class lg extends oo{get primaryAxis(){return"y"}}class cg extends oo{get primaryAxis(){return"x"}}class hg extends gi{onCalculateLayout(){}}var WM=Object.defineProperty,GM=Object.getOwnPropertyDescriptor,Bn=(s,e,t,i)=>{for(var n=i>1?void 0:i?GM(e,t):e,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&WM(e,t,n),n},Qv=(s=>(s[s.ScreenSpaceOverlay=0]="ScreenSpaceOverlay",s[s.ScreenSpaceCamera=1]="ScreenSpaceCamera",s[s.WorldSpace=2]="WorldSpace",s[s.Undefined=-1]="Undefined",s))(Qv||{});const xf=w("debuguilayout"),Fi=class Yv extends Cc{get isCanvas(){return!0}get screenspace(){return this.renderMode!==2}set renderOnTop(e){e!==this._renderOnTop&&(this._renderOnTop=e,this.onRenderSettingsChanged())}get renderOnTop(){return this._renderOnTop!==void 0?this._renderOnTop:!!(this.screenspace&&this._renderMode===0)}_renderOnTop;set depthWrite(e){this._depthWrite!==e&&(this._depthWrite=e,this.onRenderSettingsChanged())}get depthWrite(){return this._depthWrite}_depthWrite=!1;set doubleSided(e){this._doubleSided!==e&&(this._doubleSided=e,this.onRenderSettingsChanged())}get doubleSided(){return this._doubleSided}_doubleSided=!0;set castShadows(e){this._castShadows!==e&&(this._castShadows=e,this.onRenderSettingsChanged())}get castShadows(){return this._castShadows}_castShadows=!1;set receiveShadows(e){this._receiveShadows!==e&&(this._receiveShadows=e,this.onRenderSettingsChanged())}get receiveShadows(){return this._receiveShadows}_receiveShadows=!1;get renderMode(){return this._renderMode}set renderMode(e){this._renderMode!==e&&(this._renderMode=e,this.onRenderSettingsChanged())}_renderMode=-1;_rootCanvas;set rootCanvas(e){this._rootCanvas instanceof Yv||(this._rootCanvas=e)}get rootCanvas(){return this._rootCanvas}_scaleFactor=1;get scaleFactor(){return this._scaleFactor}set scaleFactor(e){this._scaleFactor=e}worldCamera;planeDistance=-1;awake(){this.shadowComponent=this.gameObject,this.previousParent=this.gameObject.parent,xf&&console.log("Canvas.Awake()",this.previousParent?.name+"/"+this.gameObject.name),super.awake()}start(){this.applyRenderSettings()}onEnable(){super.onEnable(),this._updateRenderSettingsRoutine=void 0,this._lastMatrixWorld=new c.Matrix4,this.applyRenderSettings(),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 e=this.context.pre_render_callbacks.indexOf(this.onBeforeRenderRoutine);e!==-1&&this.context.pre_render_callbacks.splice(e,1);const t=this.context.post_render_callbacks.indexOf(this.onAfterRenderRoutine);t!==-1&&this.context.post_render_callbacks.splice(t,1)}_boundRenderSettingsChanged=this.onRenderSettingsChanged.bind(this);previousParent=null;_lastMatrixWorld=null;_rectTransforms=[];registerTransform(e){this._rectTransforms.push(e)}unregisterTransform(e){const t=this._rectTransforms.indexOf(e);t!==-1&&this._rectTransforms.splice(t,1)}_layoutGroups=new Map;registerLayoutGroup(e){const t=e.gameObject;this._layoutGroups.set(t,e)}unregisterLayoutGroup(e){const t=e.gameObject;this._layoutGroups.delete(t)}_receivers=[];registerEventReceiver(e){this._receivers.push(e)}unregisterEventReceiver(e){const t=this._receivers.indexOf(e);t!==-1&&this._receivers.splice(t,1)}async onEnterXR(e){this.screenspace?(e.xr.isVR||e.xr.isPassThrough)&&(this.gameObject.visible=!1):(this.gameObject.visible=!1,await ec(1).then(()=>{this.gameObject.visible=!0}))}onLeaveXR(e){this.screenspace&&(e.xr.isVR||e.xr.isPassThrough)&&(this.gameObject.visible=!0)}onBeforeRenderRoutine=()=>{if(this.previousParent=this.gameObject.parent,(this.context.xr?.isVR||this.context.xr?.isPassThrough)&&this.screenspace){this.gameObject.visible=!1,this.gameObject.removeFromParent();return}this.renderOnTop||this.screenspace?this.gameObject.removeFromParent():(this.onUpdateRenderMode(),this.handleLayoutUpdates(),this.shadowComponent?.updateMatrixWorld(!0),this.shadowComponent?.updateWorldMatrix(!0,!0),this.invokeBeforeRenderEvents(),jt.ensureUpdateMeshUI(J.ThreeMeshUI,this.context))};onAfterRenderRoutine=()=>{if((this.context.xr?.isVR||this.context.xr?.isPassThrough)&&this.screenspace){this.previousParent?.add(this.gameObject);return}if((this.screenspace||this.renderOnTop)&&this.previousParent&&this.context.mainCamera){this.screenspace?this.context.mainCamera?.add(this.gameObject):this.previousParent.add(this.gameObject);const e=this.context.renderer.autoClear,t=this.context.renderer.autoClearColor;this.context.renderer.autoClear=!1,this.context.renderer.autoClearColor=!1,this.context.renderer.clearDepth(),this.onUpdateRenderMode(!0),this.handleLayoutUpdates(),this.shadowComponent?.updateMatrixWorld(!0),this.invokeBeforeRenderEvents(),jt.ensureUpdateMeshUI(J.ThreeMeshUI,this.context,!0),this.context.renderer.render(this.gameObject,this.context.mainCamera),this.context.renderer.autoClear=e,this.context.renderer.autoClearColor=t,this.previousParent.add(this.gameObject)}this._lastMatrixWorld?.copy(this.gameObject.matrixWorld)};invokeBeforeRenderEvents(){for(const e of this._receivers)e.onBeforeCanvasRender?.(this)}handleLayoutUpdates(){this._lastMatrixWorld===null&&(this._lastMatrixWorld=new c.Matrix4);const e=!this._lastMatrixWorld.equals(this.gameObject.matrixWorld);xf&&e&&console.log("Canvas Layout changed",this.context.time.frameCount,this.name);for(const t of this._rectTransforms){e&&t.markDirty();let i=this._layoutGroups.get(t.gameObject);t.isDirty&&!i&&(i=t.gameObject.getComponentInParent(gi)),(t.isDirty||i?.isDirty)&&(xf&&console.log("CANVAS UPDATE ### "+t.name+" ##################################### "+this.context.time.frame),i?.updateLayout(),t.updateTransform())}}applyRenderSettings(){this.onRenderSettingsChanged()}_updateRenderSettingsRoutine;onRenderSettingsChanged(){this._updateRenderSettingsRoutine||(this._updateRenderSettingsRoutine=this.startCoroutine(this._updateRenderSettingsDelayed(),pe.OnBeforeRender))}*_updateRenderSettingsDelayed(){if(yield,this._updateRenderSettingsRoutine=void 0,this.shadowComponent){this.onUpdateRenderMode(),ud(this.shadowComponent,this);for(const e of x.getComponentsInChildren(this.gameObject,Bi))ud(e.shadowComponent,this)}}_activeRenderMode=-1;_lastWidth=-1;_lastHeight=-1;onUpdateRenderMode(e=!1){if(!e&&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=I.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(nn);let r=!1;o.sizeDelta.x!==this.context.domWidth&&(r=!0),o.sizeDelta.y!==this.context.domHeight&&(r=!0);const a=t.fieldOfView*Math.PI/180,l=2*Math.tan(a/2)*Math.abs(n);this.gameObject.scale.x=l/this.context.domHeight,this.gameObject.scale.y=l/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}}};Bn([f()],Fi.prototype,"renderOnTop",1);Bn([f()],Fi.prototype,"depthWrite",1);Bn([f()],Fi.prototype,"doubleSided",1);Bn([f()],Fi.prototype,"castShadows",1);Bn([f()],Fi.prototype,"receiveShadows",1);Bn([f()],Fi.prototype,"renderMode",1);Bn([f(Fi)],Fi.prototype,"rootCanvas",1);Bn([f()],Fi.prototype,"scaleFactor",1);Bn([f(Wt)],Fi.prototype,"worldCamera",2);Bn([f()],Fi.prototype,"planeDistance",2);let ca=Fi;var HM=Object.defineProperty,qM=Object.getOwnPropertyDescriptor,dg=(s,e,t,i)=>{for(var n=i>1?void 0:i?qM(e,t):e,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&HM(e,t,n),n};class Qs extends k{get alpha(){return this._alpha}set alpha(e){e!==this._alpha&&(this._alpha=e,this.markDirty())}get isCanvasGroup(){return!0}_alpha=1;interactable=!0;blocksRaycasts=!0;_isDirty=!1;markDirty(){this._isDirty||(this._isDirty=!0,this.startCoroutine(this.applyChangesDelayed(),pe.OnBeforeRender))}*applyChangesDelayed(){this._isDirty=!1,this.applyChangesNow()}_buffer=[];applyChangesNow(){this._buffer.length=0;for(const e of x.getComponentsInChildren(this.gameObject,Bi,this._buffer)){const t=e;t.setAlphaFactor&&t.setAlphaFactor(this._alpha)}}}dg([f()],Qs.prototype,"alpha",1);dg([f()],Qs.prototype,"interactable",2);dg([f()],Qs.prototype,"blocksRaycasts",2);class ug{get extensionName(){return"tmui"}onExportObject(e,t,i){const n=x.getComponent(e,ca);if(n&&n.enabled&&n.renderMode===Qv.WorldSpace){const o=new ru,r=x.getComponent(e,nn),a=x.getComponent(e,Qs),l=new Array;if(r){if(!x.isActiveSelf(e)){const u=x.isActiveSelf(e);x.setActive(e,!0),r.onEnable(),r.updateTransform(),l.push(()=>{r.onDisable(),x.setActive(e,u)})}e.traverse(u=>{if(!x.isActiveInHierarchy(u)){const p=x.isActiveSelf(u);x.setActive(u,!0);const m=x.getComponent(u,Bi);m&&(m.onEnable(),l.push(()=>{m.onDisable()}));const y=x.getComponent(u,nn);y&&(y.onEnable(),y.updateTransform(),y.onApplyTransform(),l.push(()=>{y.onDisable()}));const b=x.getComponent(u,Ct);b&&(b.onEnable(),l.push(()=>{b.onDisable()})),l.push(()=>{x.setActive(u,p)})}}),r.width,r.height;const h=ze.createEmpty(),d=r.shadowComponent;if(t.add(h),d){const u=d.matrix;h.setMatrix(u);const p=new Map,m=new Map;p.set(d,h),m.set(d,a?a.alpha:1),d.traverse(y=>{if(y===d)return;const b=ze.createEmpty();b.setMatrix(y.matrix);const g=y.parent,v=!!g&&typeof g.textContent=="string"&&g.textContent.length>0;let _=m.get(g)||1;const S=x.getComponent(y,Qs);if(S&&(_*=S.alpha),y instanceof c.Mesh&&v){const M=y[si];M?o.exportText(M.gameObject,b,i):console.error("Error when exporting UI: shadow component owner not found. This is likely a bug.",y)}if(y instanceof c.Mesh&&!v){const M=y.geometry.clone();M.scale(1,1,-1),this.flipWindingOrder(M),b.geometry=M;const O=new c.Color,R=y.material.opacity;O.copy(y.material.color),b.material=new c.MeshBasicMaterial({color:O,opacity:R*_,map:y.material.map,transparent:!0})}p.set(y,b),m.set(y,_);const T=p.get(g);if(!T){console.error("Error when exporting UI: shadow component parent not found!",y,y.parent);return}T.add(b)})}}for(const h of l)h()}}flipWindingOrder(e){const t=e.index.array;for(let i=0,n=t.length/3;i<n;i++){const o=t[i*3];t[i*3]=t[i*3+2],t[i*3+2]=o}e.index.needsUpdate=!0}}const fl=w("debugusdz");function XM(s,e){const t=[],i=x.getComponentsInChildren(s,mt),n=x.getComponentsInChildren(s,wt),o=new Array,r=new Array;if(e.injectImplicitBehaviours)for(const a of i){if(!a||!a.runtimeAnimatorController||!a.enabled)continue;const l=a.runtimeAnimatorController.activeState;if(!l||!l.motion||!l.motion.clip||l.motion.clip.tracks?.length<1||o.includes(a))continue;const h=new Gl;h.animator=a,h.stateName=l.name,h.trigger="start",h.name="PlayAnimationOnClick_implicitAtStart_"+h.stateName;const d=new c.Object3D;x.addComponent(d,h),r.push(d),o.push(a),s.add(d)}else for(const a of i){if(!a||!a.runtimeAnimatorController||!a.enabled)continue;fl&&console.log(a);const l=[];for(const h of a.runtimeAnimatorController.enumerateActions()){fl&&console.log(h);const d=h.getClip();l.includes(d)||l.push(d)}t.push({root:a.gameObject,clips:l})}if(e.injectImplicitBehaviours)for(const a of n){if(!a||!a.clip||!a.enabled||!a.playAutomatically||o.includes(a))continue;const l=new Gl;l.animation=a,l.stateName=a.clip.name,l.trigger="start",l.name="PlayAnimationOnClick_implicitAtStart_"+l.stateName;const h=new c.Object3D;x.addComponent(h,l),r.push(h),o.push(a),s.add(h)}else for(const a of n){fl&&console.log(a);const l=[];for(const h of a.animations)l.includes(h)||l.push(h);t.push({root:a.gameObject,clips:l})}fl&&t?.length>0&&console.log("USDZ Animation Clips without behaviours",t);for(const a of t)for(const l of a.clips)e.registerAnimation(a.root,l);return r}function QM(s,e){const t=x.getComponentsInChildren(s,Ii),i=x.getComponentsInChildren(s,qs),n=new Array,o=new Array;fl&&console.log({audioSources:t,playAudioOnClicks:i});for(const r of i){if(!r.target)continue;const a=t.indexOf(r.target);a>-1&&t.splice(a,1)}for(const r of t){if(!r||!r.clip||r.volume<=0||n.includes(r))continue;const a=new qs;a.target=r,a.name="PlayAudioOnClick_implicitAtStart_",a.trigger="start";const l=new c.Object3D;x.addComponent(l,a),console.log("implicit PlayAudioOnStart",l,a),o.push(l),n.push(r),s.add(l)}return o}function YM(s){return new pt("DisableAtStart",xt.sceneStartTrigger(),ae.fadeAction(s,0,!1))}function b_(s,e){const t=s.domElement.shadowRoot.querySelector("link[rel='ar']");if(t)return t;const i=document.createElement("div");i.classList.add("menu"),i.classList.add("quicklook-menu"),i.style.display="none",i.style.visibility="hidden";const n=document.createElement("button");n.id="open-in-ar",e?(n.innerText="View in AR",n.title="View this scene in AR. The scene will be exported to USDZ and opened with Apple's QuickLook."):(n.innerText="View in AR",n.title="Download this scene for AR. Open the downloaded USDZ file to view it in AR using Apple's QuickLook."),i.appendChild(n);const o=document.createElement("a");o.id="needle-usdz-link",o.style.display="none",o.rel="ar",o.href="",o.target="_blank",i.appendChild(o);const r=document.createElement("img");return r.id="button",o.appendChild(r),s.domElement.shadowRoot.appendChild(i),o}var KM=Object.defineProperty,yt=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&KM(e,t,n),n};const Jt=w("debugusdz"),ZM=w("debugusdzpruning");class hr{callToAction;checkoutTitle;checkoutSubtitle;callToActionURL}yt([f()],hr.prototype,"callToAction");yt([f()],hr.prototype,"checkoutTitle");yt([f()],hr.prototype,"checkoutSubtitle");yt([f()],hr.prototype,"callToActionURL");const Kt=class wp extends k{objectToExport=void 0;autoExportAnimations=!0;autoExportAudioSources=!0;exportFileName=void 0;customUsdzFile=void 0;customBranding;anchoringType="plane";maxTextureSize=2048;planeAnchoringAlignment="horizontal";interactive=!0;physics=!0;allowCreateQuicklookButton=!0;quickLookCompatible=!0;extensions=[];link;button;start(){Jt&&(console.log("USDZExporter",this),console.log("Debug USDZ Mode. Press 'T' to export"),window.addEventListener("keydown",e=>{switch(e.key){case"t":this.exportAndOpen();break}})),this.objectToExport||(this.objectToExport=this.gameObject),!this.objectToExport?.children?.length&&!this.objectToExport?.isMesh&&(this.objectToExport=this.context.scene)}onEnable(){const e=exports.DeviceUtilities.supportsQuickLookAR(),t=exports.DeviceUtilities.isiOS()||exports.DeviceUtilities.isiPad();!this.button&&(Jt||e||t)&&(this.allowCreateQuicklookButton&&(this.button=this.createQuicklookButton()),this.lastCallback=this.quicklookCallback.bind(this),this.link=b_(this.context,e),this.link.addEventListener("message",this.lastCallback)),Jt&&Se("USDZ Exporter enabled: "+this.name),document.getElementById("open-in-ar")?.addEventListener("click",this.onClickedOpenInARElement),jl.registerExporter(this)}onDisable(){this.button?.remove(),this.link?.removeEventListener("message",this.lastCallback),Jt&&Se("USDZ Exporter disabled: "+this.name),document.getElementById("open-in-ar")?.removeEventListener("click",this.onClickedOpenInARElement),jl.unregisterExporter(this)}onClickedOpenInARElement=e=>{e.preventDefault(),this.exportAndOpen()};async exportAsync(){return this.exportAndOpen()}async exportAndOpen(){let e=this.exportFileName??this.objectToExport?.name??this.name;if(e+="-"+Mv(),kn()||(e!==""&&(e+="-"),e+="MadeWithNeedle"),this.link||(this.link=b_(this.context,exports.DeviceUtilities.supportsQuickLookAR())),this.customUsdzFile)return Jt&&console.log("Exporting custom usdz",this.customUsdzFile),this.openInQuickLook(this.customUsdzFile,e),null;if(!this.objectToExport)return console.warn("No object to export",this),null;const t=await this.export(this.objectToExport);return t?(Jt&&console.log("USDZ generation done. Downloading as "+e),this.openInQuickLook(t,e),t):(console.error("USDZ generation failed. Please report a bug",this),null)}async export(e){if(!e)return console.warn("No object to export"),null;const t=this._currentExportTasks.get(e);if(t)return t;const i=this.internalExport(e);return i instanceof Promise?(this._currentExportTasks.set(e,i),i.then(n=>(this._currentExportTasks.delete(e),n)).catch(n=>(this._currentExportTasks.delete(e),console.error("Error during USDZ export – please report a bug!",n),null))):i}_currentExportTasks=new Map;_previousTimeScale=1;async internalExport(e){ie.start("export-usdz",{onProgress:M=>{this.dispatchEvent(new CustomEvent("export-progress",{detail:{progress:M}}))}}),ie.report("export-usdz",{message:"Starting export",totalSteps:40,currentStep:0}),ie.report("export-usdz",{message:"Load progressive textures",autoStep:5}),ie.start("export-usdz-textures","export-usdz");const t=x.getComponentsInChildren(e,Yt);for(const M of t)M&&M.enabled&&M.updateSprite(!0);const i=x.getComponentsInChildren(e,fi),n=new Array;let o=0;for(const M of i){for(const O of M.sharedMeshes)if(O){const R=ne.NEEDLE_progressive.assignMeshLOD(O,0);R instanceof Promise&&n.push(new Promise((B,L)=>{R.then(()=>{o++,ie.report("export-usdz-textures",{message:"Loaded progressive mesh",currentStep:o,totalSteps:n.length}),B()}).catch(N=>L(N))}))}for(const O of M.sharedMaterials)if(O){const R=ne.NEEDLE_progressive.assignTextureLOD(O,0);R instanceof Promise&&n.push(new Promise((B,L)=>{R.then(()=>{o++,ie.report("export-usdz-textures",{message:"Loaded progressive texture",currentStep:o,totalSteps:n.length}),B()}).catch(N=>L(N))}))}}Jt&&Se("Progressive Loading: "+n.length),await Promise.all(n),Jt&&Se("Progressive Loading: done"),ie.end("export-usdz-textures");const r=It.Global.Mask;It.Global.Set(bn.AR);const a=new Tv,l=new Jd(this.quickLookCompatible);let h;const d=[];this.interactive&&(d.push(new sg),d.push(new ar),globalThis.NEEDLE_USE_RAPIER&&x.getComponentsInChildren(e,Ke).length>0&&(this.physics?(h=new og,d.push(h)):A()&&console.warn("USDZExporter: Physics export is disabled, but there are active Rigidbody components in the scene. They will not be exported.")),d.push(new ru),d.push(new ug));const u=[l,...d,...this.extensions],p={self:this,exporter:a,extensions:u,object:e};ie.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,ie.report("export-usdz","auto export animations and audio sources");const m=new Array;this.autoExportAnimations&&m.push(...XM(e,l)),u.find(M=>M.extensionName==="Audio")&&this.autoExportAudioSources&&m.push(...QM(e)),a.debug=Jt,a.pruneUnusedNodes=!ZM;const b=qo.instance.objs.map(M=>M.batchedMesh);a.keepObject=M=>{let O=!0;const R=x.getComponent(M,fi);return R&&!R.enabled&&(O=!1),O&&b.includes(M)&&(O=!1),O&&x.getComponentInParent(M,yc)&&(O=!1),O&&x.getComponentInParent(M,Dn)&&(O=!1),Jt&&!O&&console.log("USDZExporter: Discarding object",M),O},a.beforeWritingDocument=()=>{if(A()&&l&&h){const M=l.animatedRoots;for(const O of M){const R=x.getComponentsInChildren(O,Ke).filter(L=>L.enabled),B=x.getComponents(O,Qt).filter(L=>L.enabled&&!L.isTrigger);(R.length>0||B.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.",O)}}};const g=new Array;this.objectToExport&&this.quickLookCompatible&&this.interactive&&this.objectToExport.traverse(M=>{M.visible||g.push(M)});const v=u.find(M=>M.extensionName==="Behaviour");this.interactive&&v&&g.length>0&&v.addBehavior(YM(g));let _=!0;this.quickLookCompatible&&!this.interactive&&(_=!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"),ie.report("export-usdz","Invoking exporter.parse");const S=await a.parse(this.objectToExport,{ar:{anchoring:{type:this.anchoringType},planeAnchoring:{alignment:this.planeAnchoringAlignment}},extensions:u,quickLookCompatible:this.quickLookCompatible,maxTextureSize:this.maxTextureSize,exportInvisible:_}),T=new Blob([S],{type:"model/vnd.usdz+zip"});this.revertWebARSessionRoot(),this.context.time.timeScale=this._previousTimeScale,ie.report("export-usdz","Invoking after-export"),this.dispatchEvent(new CustomEvent("after-export",{detail:p}));for(const M of m)x.destroy(M);return It.Global.Set(r),ie.end("export-usdz"),T}openInQuickLook(e,t){const i=e instanceof Blob?URL.createObjectURL(e):e,n=this.buildQuicklookOverlay();Jt&&console.log("QuickLook Overlay",n);const o=n.callToAction?encodeURIComponent(n.callToAction):"",r=n.checkoutTitle?encodeURIComponent(n.checkoutTitle):"",a=n.checkoutSubtitle?encodeURIComponent(n.checkoutSubtitle):"";this.link.href=i+`#callToAction=${o}&checkoutTitle=${r}&checkoutSubtitle=${a}&callToActionURL=${n.callToActionURL}`,this.lastCallback||(this.lastCallback=this.quicklookCallback.bind(this),this.link.addEventListener("message",this.lastCallback)),this.link.download=t+".usdz",this.link.click()}download(e,t){wp.save(e,t)}static save(e,t){const i=document.createElement("a");i.style.display="none",document.body.appendChild(i),typeof e=="string"?i.href=e:i.href=URL.createObjectURL(e),i.download=t,i.click(),i.remove()}lastCallback;quicklookCallback(e){if(e?.data=="_apple_ar_quicklook_button_tapped"){Jt&&ce("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");Jt&&Se("Quicklook url: "+n),n&&(kn()?globalThis.open(n,"_blank"):console.warn("Quicklook closed: custom redirects require a Needle Engine Pro license: https://needle.tools/pricing",n))}}}}buildQuicklookOverlay(){const e={};return this.customBranding&&Object.assign(e,this.customBranding),kn()||(console.log("Custom Quicklook banner text requires pro license: https://needle.tools/pricing"),e.callToAction="Close",e.checkoutTitle="🌵 Made with Needle",e.checkoutSubtitle="_"),(e.callToAction?.length||e.checkoutTitle?.length||e.checkoutSubtitle?.length)&&(e.callToAction?.length||(e.callToAction="\0"),e.checkoutTitle?.length||(e.checkoutTitle="\0"),e.checkoutSubtitle?.length||(e.checkoutSubtitle="\0")),this.dispatchEvent(new CustomEvent("quicklook-overlay",{detail:e})),e}static invertForwardMatrix=new c.Matrix4().makeRotationY(Math.PI);static invertForwardQuaternion=new c.Quaternion().setFromEuler(new c.Euler(0,Math.PI,0));_rootSessionRootWasAppliedTo=null;_rootPositionBeforeExport=new c.Vector3;_rootRotationBeforeExport=new c.Quaternion;_rootScaleBeforeExport=new c.Vector3;getARScaleAndTarget(){if(!this.objectToExport)return{scale:1,_invertForward:!1,target:this.gameObject,sessionRoot:null};const e=x.findObjectOfType(ou);let t=x.getComponentInParent(this.objectToExport,li);t||(t=x.getComponentInChildren(this.objectToExport,li));let i=1,n=!1;const o=this.objectToExport;return e?i=e.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:e,_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(e),t&&i.quaternion.multiply(wp.invertForwardQuaternion),i.updateMatrix(),i.updateMatrixWorld(!0),n&&o&&i.matrix.premultiply(o)}revertWebARSessionRoot(){if(!this.objectToExport||!this._rootSessionRootWasAppliedTo)return;const e=this._rootSessionRootWasAppliedTo;e.position.copy(this._rootPositionBeforeExport),e.quaternion.copy(this._rootRotationBeforeExport),e.scale.copy(this._rootScaleBeforeExport),e.updateMatrix(),e.updateMatrixWorld(!0),this._rootSessionRootWasAppliedTo=null}createQuicklookButton(){const t=Gs.getOrCreate().createQuicklookButton();return t.parentNode||this.context.menu.appendChild(t),t}};yt([f(c.Object3D)],Kt.prototype,"objectToExport");yt([f()],Kt.prototype,"autoExportAnimations");yt([f()],Kt.prototype,"autoExportAudioSources");yt([f()],Kt.prototype,"exportFileName");yt([f(URL)],Kt.prototype,"customUsdzFile");yt([f(hr)],Kt.prototype,"customBranding");yt([f()],Kt.prototype,"anchoringType");yt([f()],Kt.prototype,"maxTextureSize");yt([f()],Kt.prototype,"planeAnchoringAlignment");yt([f()],Kt.prototype,"interactive");yt([f()],Kt.prototype,"physics");yt([f()],Kt.prototype,"allowCreateQuicklookButton");yt([f()],Kt.prototype,"quickLookCompatible");let En=Kt;var JM=Object.defineProperty,eO=Object.getOwnPropertyDescriptor,fg=(s,e,t,i)=>{for(var n=eO(e,t),o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&JM(e,t,n),n};class Ca extends k{get fog(){return this._fog||(this._fog=new c.Fog(0,0,50)),this._fog}get mode(){return 1}set near(e){this.fog.near=e}get near(){return this.fog.near}set far(e){this.fog.far=e}get far(){return this.fog.far}set color(e){this.fog.color.copy(e)}get color(){return this.fog.color}_fog;onEnable(){this.scene.fog=this.fog}onDisable(){this.scene.fog===this._fog&&(this.scene.fog=null)}}fg([f()],Ca.prototype,"near");fg([f()],Ca.prototype,"far");fg([f(c.Color)],Ca.prototype,"color");var tO=Object.defineProperty,pg=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&tO(e,t,n),n};class dr extends k{objectBounds=!1;color;isGizmo=!0;_gizmoObject=null;_boxHelper=null;onEnable(){this.isGizmo&&!oc||(this._gizmoObject||(this.objectBounds?this._gizmoObject=new c.BoxHelper(this.gameObject,this.color??16776960):(this.objectBounds=!1,this._gizmoObject=nm(this.color??16776960))),this.objectBounds?(this.scene.add(this._gizmoObject),this._boxHelper=this._gizmoObject,this.startCoroutine(this.syncObjectBounds(),pe.OnBeforeRender)):this.gameObject.add(this._gizmoObject))}onDisable(){this._gizmoObject&&this.gameObject.remove(this._gizmoObject)}*syncObjectBounds(){for(;this._boxHelper;)this._boxHelper?.update(),yield}}pg([f()],dr.prototype,"objectBounds");pg([f(c.Color)],dr.prototype,"color");pg([f()],dr.prototype,"isGizmo");var iO=Object.defineProperty,mg=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&iO(e,t,n),n};class Pa extends k{isGizmo=!1;color0;color1;gridHelper;size;divisions;offset;onEnable(){if(this.isGizmo&&!oc)return;const e=this.size,t=this.divisions;this.gridHelper||(this.gridHelper=new c.GridHelper(e,t,this.color0??new c.Color(.4,.4,.4),this.color1??new c.Color(.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)}}mg([f()],Pa.prototype,"isGizmo");mg([f(c.Color)],Pa.prototype,"color0");mg([f(c.Color)],Pa.prototype,"color1");var nO=Object.defineProperty,gg=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&nO(e,t,n),n};class yg extends k{connectedBody;get rigidBody(){return this._rigidBody}_rigidBody=null;onEnable(){this._rigidBody||(this._rigidBody=this.gameObject.getComponent(Ke)),this.rigidBody&&this.connectedBody&&this.startCoroutine(this.create())}*create(){yield,this.rigidBody&&this.connectedBody&&this.activeAndEnabled&&this.createJoint(this.rigidBody,this.connectedBody)}}gg([f(Ke)],yg.prototype,"connectedBody");class _g extends yg{createJoint(e,t){this.context.physics.engine?.addFixedJoint(e,t)}}class kc extends yg{anchor;axis;createJoint(e,t){this.axis&&this.anchor&&this.context.physics.engine?.addHingeJoint(e,t,this.anchor,this.axis)}}gg([f(c.Vector3)],kc.prototype,"anchor");gg([f(c.Vector3)],kc.prototype,"axis");var sO=Object.defineProperty,oO=Object.getOwnPropertyDescriptor,Fn=(s,e,t,i)=>{for(var n=i>1?void 0:i?oO(e,t):e,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&sO(e,t,n),n};function Sf(s){return s*Math.PI/180}const v_=300,ks=w("debuglights");class yi extends k{type=0;range=1;spotAngle=1;innerSpotAngle=1;set color(e){this._color=e,this.light!==void 0&&(this.light.color=e)}get color(){return this.light?this.light.color:this._color}_color=new c.Color(16777215);set shadowNearPlane(e){if(e!==this._shadowNearPlane&&(this._shadowNearPlane=e,this.light?.shadow?.camera!==void 0)){const t=this.light.shadow.camera;t.near=e}}get shadowNearPlane(){return this._shadowNearPlane}_shadowNearPlane=.1;set shadowBias(e){e!==this._shadowBias&&(this._shadowBias=e,this.light?.shadow?.bias!==void 0&&(this.light.shadow.bias=e,this.light.shadow.needsUpdate=!0))}get shadowBias(){return this._shadowBias}_shadowBias=0;set shadowNormalBias(e){e!==this._shadowNormalBias&&(this._shadowNormalBias=e,this.light?.shadow?.normalBias!==void 0&&(this.light.shadow.normalBias=e,this.light.shadow.needsUpdate=!0))}get shadowNormalBias(){return this._shadowNormalBias}_shadowNormalBias=0;_overrideShadowBiasSettings=!1;set shadows(e){this._shadows=e,this.light&&(this.light.castShadow=e!==0,this.updateShadowSoftHard())}get shadows(){return this._shadows}_shadows=1;lightmapBakeType=4;set intensity(e){if(this._intensity=e,this.light){let t=1;if(this.context.isInXR&&this._webARRoot){const i=this._webARRoot?.arScale;typeof i=="number"&&i>0&&(t/=i)}this.light.intensity=e*t}ks&&console.log("Set light intensity to "+this._intensity,e,this)}get intensity(){return this._intensity}_intensity=-1;get shadowDistance(){const e=this.light;return e?.shadow?e.shadow.camera.far:-1}set shadowDistance(e){this._shadowDistance=e;const t=this.light;if(t?.shadow){const i=t.shadow.camera;i.far=e,i.updateProjectionMatrix()}}_shadowDistance;shadowWidth;shadowHeight;get shadowResolution(){const e=this.light;return e?.shadow?e.shadow.mapSize.x:-1}set shadowResolution(e){if(e===this._shadowResolution)return;this._shadowResolution=e;const t=this.light;t?.shadow&&(t.shadow.mapSize.set(e,e),t.shadow.needsUpdate=!0)}_shadowResolution=void 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}light=void 0;getWorldPosition(e){return this.light?this.type===1?this.light.getWorldPosition(e).multiplyScalar(1):this.light.getWorldPosition(e):e}awake(){this.color=new c.Color(this.color??16777215),ks&&console.log(this.name,this)}onEnable(){ks&&console.log("ENABLE LIGHT",this.name),this.createLight(),!this.isBaked&&(this.light&&(this.light.visible=!0,this.light.intensity=this._intensity,ks&&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(),pe.LateUpdate))}onDisable(){ks&&console.log("DISABLE LIGHT",this.name),this.light&&(this.selfIsLight?this.light.intensity=0:this.light.visible=!1)}_webXRStartedListener;_webXREndedListener;_webARRoot;onEnterXR(e){this._webARRoot=x.getComponentInParent(this.gameObject,li)??void 0}onLeaveXR(e){}createLight(){const e=this.selfIsLight;if(e&&!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 t=new c.DirectionalLight(this.color,this.intensity*Math.PI);if(t.position.set(0,0,-v_*.5).applyQuaternion(this.gameObject.quaternion),this.gameObject.add(t.target),zo(t.target,0,0,0),this.light=t,this.gameObject.position.set(0,0,0),this.gameObject.rotation.set(0,0,0),ks){const r=new c.DirectionalLightHelper(this.light,.2,this.color);this.context.scene.add(r)}break;case 0:const i=new c.SpotLight(this.color,this.intensity*Math.PI,this.range,Sf(this.spotAngle/2),1-Sf(this.innerSpotAngle/2)/Sf(this.spotAngle/2),2);i.position.set(0,0,0),i.rotation.set(0,0,0),this.light=i;const n=i.target;i.add(n),n.position.set(0,0,this.range),n.rotation.set(0,0,0);break;case 2:const o=new c.PointLight(this.color,this.intensity*Math.PI,this.range);this.light=o;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),ks&&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 t=this.light.shadow.camera;if(t.near=this.shadowNearPlane,this._shadowDistance!==void 0&&typeof this._shadowDistance=="number"?t.far=this._shadowDistance:t.far=v_*Math.abs(this.gameObject.scale.z),this.gameObject.scale.set(1,1,1),this.shadowWidth!==void 0)t.left=-this.shadowWidth/2,t.right=this.shadowWidth/2;else{const i=this.gameObject.scale.x;t.left*=i,t.right*=i}if(this.shadowHeight!==void 0)t.top=this.shadowHeight/2,t.bottom=-this.shadowHeight/2;else{const i=this.gameObject.scale.y;t.top*=i,t.bottom*=i}this.light.shadow.needsUpdate=!0,ks&&this.context.scene.add(new c.CameraHelper(t))}this.isBaked?this.light.removeFromParent():e||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}}static allowChangingRendererShadowMapType=!0;updateShadowSoftHard(){this.light&&this.light.shadow&&(this.shadows===2||(this.light.shadow.radius=1,this.light.shadow.blurSamples=1))}setDirectionalLight(e){e.add(e.target),e.target.position.set(0,0,-1)}}Fn([f()],yi.prototype,"type",2);Fn([f(c.Color)],yi.prototype,"color",1);Fn([f()],yi.prototype,"shadowNearPlane",1);Fn([f()],yi.prototype,"shadowBias",1);Fn([f()],yi.prototype,"shadowNormalBias",1);Fn([f()],yi.prototype,"shadows",1);Fn([f()],yi.prototype,"lightmapBakeType",2);Fn([f()],yi.prototype,"intensity",1);Fn([f()],yi.prototype,"shadowDistance",1);Fn([f()],yi.prototype,"shadowResolution",1);new c.Vector3(0,0,0);var rO=Object.defineProperty,Rc=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&rO(e,t,n),n};const Cf=w("debuglods"),aO=w("nolods");class Ma{screenRelativeTransitionHeight;distance;renderers}Rc([f()],Ma.prototype,"screenRelativeTransitionHeight");Rc([f()],Ma.prototype,"distance");Rc([f(fi)],Ma.prototype,"renderers");class lO{model;get renderers(){return this.model.renderers}constructor(e){this.model=e}}class Ec extends k{fadeMode=0;localReferencePoint=void 0;lodCount=0;size=0;animateCrossFading=!1;lodModels;_lods=[];_settings=[];_lodsHandler;start(){if(Cf&&console.log("LODGROUP",this.name,this.lodModels,this),!aO&&!this._lodsHandler&&this.gameObject&&this.lodModels&&Array.isArray(this.lodModels)){const e=[];for(const i of this.lodModels){const n=new lO(i);this._lods.push(n);for(const o of n.renderers)e.includes(o)||e.push(o)}this._lodsHandler=new Array;for(let i=0;i<e.length;i++){const n=new c.LOD;this._lodsHandler.push(n),this.gameObject.add(n)}const t=new c.Object3D;t.name="Cull "+this.name;for(let i=0;i<e.length;i++){const n=e[i],o=this._lodsHandler[i],r=n.gameObject;Cf&&console.log(i,r.name);for(const a of this._lods){const l=a.model.distance;let h=null;if(a.renderers.includes(n)?h=r:h=t,h.type==="Group"){console.warn(`LODGroup ${this.name}: Group or MultiMaterial object's are not supported as LOD object: ${h.name}`);continue}Cf&&console.log("LEVEL",h.name,l),o.autoUpdate=!1,this.onAddLodLevel(o,h,a.model.distance)}}}}onAfterRender(){if(!this.gameObject||!this._lodsHandler)return;const e=this.context.mainCamera;if(e)for(const t of this._lodsHandler){t.update(e);const i=t.getCurrentLevel(),n=t.levels[i];t.layers.mask=n.object.layers.mask}}onAddLodLevel(e,t,i){if(t===this.gameObject){console.warn("LODGroup component must be on parent object and not mesh directly at the moment",t.name,t);return}e.addLevel(t,i*this._distanceFactor,.01);const n={lod:e,levelIndex:e.levels.length-1,distance:i};this._settings.push(n)}_distanceFactor=1;distanceFactor(e){if(e!==this._distanceFactor){this._distanceFactor=e;for(const t of this._settings){const i=t.lod.levels[t.levelIndex];i.distance=t.distance*e}}}}Rc([f(c.Vector3)],Ec.prototype,"localReferencePoint");Rc([f(Ma)],Ec.prototype,"lodModels");var cO=Object.defineProperty,hO=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&cO(e,t,n),n};const wh=w("debugnestedgltf");class au extends k{filePath;loadAssetInParent=!0;_isLoadingOrDoneLoading=!1;listenToProgress(e){this.filePath?.beginListenDownload(e)}preload(){this.filePath?.preload()}async start(){if(this._isLoadingOrDoneLoading)return;wh&&console.log(this,this.guid);const e=this.gameObject.parent;if(e){this._isLoadingOrDoneLoading=!0;const t=new sn;t.idProvider=new ft(this.hash(this.guid)),t.parent=this.loadAssetInParent!==!1?e:this.gameObject,this.gameObject.updateMatrix();const i=this.gameObject.matrix;wh&&console.log("Load nested:",this.filePath?.url??this.filePath,this.gameObject.position);const n=await this.filePath?.instantiate?.call(this.filePath,t);wh&&console.log("Nested loaded:",this.filePath?.url??this.filePath,n),n&&this.loadAssetInParent!==!1&&(n.matrixAutoUpdate=!1,n.matrix.identity(),n.applyMatrix4(i),n.matrixAutoUpdate=!0,n.layers.disableAll(),n.layers.set(this.layer),this.dispatchEvent(new CustomEvent("loaded",{detail:{instance:n,assetReference:this.filePath}}))),wh&&console.log("Nested loading done:",this.filePath?.url??this.filePath,n)}}onDestroy(){this.filePath?.unload()}hash(e){let t=0;for(let i=0;i<e.length;i++)t=e.charCodeAt(i)+((t<<5)-t);return t}}hO([f(Y)],au.prototype,"filePath");var dO=Object.defineProperty,bg=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&dO(e,t,n),n};const uO=w("debugnet"),lu=class xp extends k{url=null;urlParameterName=null;localhost=null;awake(){uO&&console.log(this),this.context.connection.registerProvider(this)}getWebsocketUrl(){let e=this.url?xp.GetUrl(this.url,this.localhost):null;if(this.urlParameterName){const o=w(this.urlParameterName);o&&typeof o=="string"&&(e=o)}if(!e)return null;const i=new RegExp("(((https?)|(?<socket_prefix>wss?))://)?(www.)?(?<url>.+)","gm").exec(e);return i?.groups?i?.groups.socket_prefix?e:"wss://"+i?.groups.url:null}static GetUrl(e,t){let i=e;const n=xp.IsLocalNetwork()&&t;if(n&&(i=t),e?.startsWith("/")){const o=n?i:window.location.origin;o?.endsWith("/")&&e.startsWith("/")&&(e=e.substring(1)),i=o+e}return i}static IsLocalNetwork(e=window.location.hostname){return Bt(e)}};bg([f()],lu.prototype,"url");bg([f()],lu.prototype,"urlParameterName");bg([f()],lu.prototype,"localhost");let vg=lu;var fO=Object.defineProperty,cu=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&fO(e,t,n),n};class ur extends k{referenceSpace;from;affectPosition=!1;affectRotation=!1;alignLookDirection=!1;levelLookDirection=!1;levelPosition=!1;positionOffset=new c.Vector3(0,0,0);rotationOffset=new c.Vector3(0,0,0);offset=new c.Vector3(0,0,0);update(){if(!this.from)return;var e=X(this.from),t=ue(this.from);this.offset.copy(this.positionOffset);const i=this.offset.length();if(this.referenceSpace&&this.offset.transformDirection(this.referenceSpace.matrixWorld).multiplyScalar(i),e.add(this.offset),this.levelPosition&&this.referenceSpace){const a=new c.Plane(this.gameObject.up,0),l=X(this.referenceSpace);a.setFromNormalAndCoplanarPoint(this.gameObject.up,l);const h=new c.Vector3(0,0,0);a.projectPoint(e,h),e.copy(h)}this.affectPosition&&Ye(this.gameObject,e);const n=new c.Euler(this.rotationOffset.x,this.rotationOffset.y,this.rotationOffset.z),o=new c.Quaternion().setFromEuler(n);this.affectRotation&&Di(this.gameObject,t.multiply(o));const r=new c.Vector3;this.from.getWorldDirection(r).multiplyScalar(50),this.levelLookDirection&&(r.y=0),this.alignLookDirection&&this.gameObject.lookAt(r)}}cu([f(x)],ur.prototype,"referenceSpace");cu([f(x)],ur.prototype,"from");cu([f(c.Vector3)],ur.prototype,"positionOffset");cu([f(c.Vector3)],ur.prototype,"rotationOffset");var pO=Object.defineProperty,ro=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&pO(e,t,n),n};class Gt{time=0;value=0;inTangent=1/0;inWeight;outTangent=1/0;outWeight;weightedMode;constructor(e=0,t=0){this.time=e,this.value=t}}ro([f()],Gt.prototype,"time");ro([f()],Gt.prototype,"value");ro([f()],Gt.prototype,"inTangent");ro([f()],Gt.prototype,"inWeight");ro([f()],Gt.prototype,"outTangent");ro([f()],Gt.prototype,"outWeight");ro([f()],Gt.prototype,"weightedMode");const Kv=class pl{static linearFromTo(e,t,i){const n=new pl,o=new Gt;o.time=0,o.value=e;const r=new Gt;return r.time=i,r.value=t,n.keys.push(o,r),n}static constant(e){const t=new pl,i=new Gt;return i.time=0,i.value=e,t.keys.push(i),t}keys=[];clone(){const e=new pl;return e.keys=this.keys?.map(t=>{const i=new Gt;return i.time=t.time,i.value=t.value,i.inTangent=t.inTangent,i.inWeight=t.inWeight,i.outTangent=t.outTangent,i.outWeight=t.outWeight,i.weightedMode=t.weightedMode,i})||[],e}get duration(){return!this.keys||this.keys.length==0?0:this.keys[this.keys.length-1].time}evaluate(e){if(!this.keys||this.keys.length==0)return 0;if(this.keys.length===1)return this.keys[0].value;if(this.keys[0].time>=e)return this.keys[0].value;for(let t=0;t<this.keys.length;t++){const i=this.keys[t];if(i.time<=e)if(t+1<this.keys.length){const o=this.keys[t+1];if(o.time<e)continue;return!isFinite(i.outTangent)||!isFinite(o.inTangent)?i.value:pl.interpolateValue(e,i,o)}else return i.value}return this.keys[this.keys.length-1].value}static interpolateValue(e,t,i){const n=t.time,o=t.value,r=t.outTangent,a=i.time,l=i.value,h=i.inTangent,d=a-n,u=d*d,p=u*d,m=((r+h)*d-2*(l-o))/p,y=(3*(l-o)-(h+2*r)*d)/u,b=r,g=o,v=e-n,_=v*v,S=_*v;return m*S+y*_+b*v+g}};ro([f(Gt)],Kv.prototype,"keys");let Tc=Kv;var mO=Object.defineProperty,C=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&mO(e,t,n),n};const xh=w("debugparticles");var Kn=(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))(Kn||{});class fr{alphaKeys=[];colorKeys=[];get duration(){return 1}evaluate(e,t){let i,n=0,o=null,r=0;for(let a=0;a<this.alphaKeys.length;a++){const l=this.alphaKeys[a];(l.time<e||!i)&&(i=l,n=a)}for(let a=0;a<this.colorKeys.length;a++){const l=this.colorKeys[a];(l.time<e||!o)&&(o=l,r=a)}if(o)if(r+1<this.colorKeys.length){const l=this.colorKeys[r+1],h=I.remap(e,o.time,l.time,0,1);t.r=I.lerp(o.color.r,l.color.r,h),t.g=I.lerp(o.color.g,l.color.g,h),t.b=I.lerp(o.color.b,l.color.b,h)}else t.r=o.color.r,t.g=o.color.g,t.b=o.color.b;if(i)if(n+1<this.alphaKeys.length){const l=this.alphaKeys[n+1],h=I.remap(e,i.time,l.time,0,1);t.alpha=I.lerp(i.alpha,l.alpha,h)}else t.alpha=i.alpha;return t}}C([f()],fr.prototype,"alphaKeys");C([f()],fr.prototype,"colorKeys");var Hl=(s=>(s[s.Local=0]="Local",s[s.World=1]="World",s[s.Custom=2]="Custom",s))(Hl||{}),vd=(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))(vd||{});const gs=class ml{static constant(e){const t=new ml;return t.setConstant(e),t}static betweenTwoConstants(e,t){const i=new ml;return i.setMinMaxConstant(e,t),i}static curve(e,t=1){const i=new ml;return i.setCurve(e,t),i}setConstant(e){this.mode=0,this.constant=e}setMinMaxConstant(e,t){this.mode=3,this.constantMin=e,this.constantMax=t}setCurve(e,t=1){this.mode=1,this.curve=e,this.curveMultiplier=t}mode="Constant";constant;constantMin;constantMax;curve;curveMin;curveMax;curveMultiplier;clone(){const e=new ml;return e.mode=this.mode,e.constant=this.constant,e.constantMin=this.constantMin,e.constantMax=this.constantMax,e.curve=this.curve?.clone(),e.curveMin=this.curveMin?.clone(),e.curveMax=this.curveMax?.clone(),e.curveMultiplier=this.curveMultiplier,e}evaluate(e,t){const i=t===void 0?Math.random():t;switch(this.mode){case 0:case"Constant":return this.constant;case 1:case"Curve":return e=I.clamp01(e),this.curve.evaluate(e)*this.curveMultiplier;case 2:case"TwoCurves":const n=e*this.curveMin.duration,o=e*this.curveMax.duration;return I.lerp(this.curveMin.evaluate(n),this.curveMax.evaluate(o),i%1)*this.curveMultiplier;case 3:case"TwoConstants":return I.lerp(this.constantMin,this.constantMax,i%1);default:this.curveMax.evaluate(e)*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(e){if(!e)return 0;let t=Number.MIN_VALUE;for(let i=0;i<e.keys.length;i++){const n=e.keys[i];n.value>t&&(t=n.value)}return t}};C([f()],gs.prototype,"mode");C([f()],gs.prototype,"constant");C([f()],gs.prototype,"constantMin");C([f()],gs.prototype,"constantMax");C([f(Tc)],gs.prototype,"curve");C([f(Tc)],gs.prototype,"curveMin");C([f(Tc)],gs.prototype,"curveMax");C([f()],gs.prototype,"curveMultiplier");let H=gs;const ao=class dt{static constant(e){const t=new dt;return t.constant(e),t}static betweenTwoColors(e,t){const i=new dt;return i.betweenTwoColors(e,t),i}constant(e){return this.mode=0,this.color=e,this}betweenTwoColors(e,t){return this.mode=2,this.colorMin=e,this.colorMax=t,this}mode=0;color;colorMin;colorMax;gradient;gradientMin;gradientMax;static _temp=new Z(0,0,0,1);static _temp2=new Z(0,0,0,1);evaluate(e,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(e,dt._temp),dt._temp;case 2:case"TwoColors":return dt._temp.lerpColors(this.colorMin,this.colorMax,i);case 3:case"TwoGradients":return this.gradientMin.evaluate(e,dt._temp),this.gradientMax.evaluate(e,dt._temp2),dt._temp.lerp(dt._temp2,i);case 4:case"RandomColor":const o=Math.random();return this.gradientMin.evaluate(e,dt._temp),this.gradientMax.evaluate(e,dt._temp2),dt._temp.lerp(dt._temp2,o)}return dt._temp.set(16777215),dt._temp.alpha=1,dt._temp}};C([f()],ao.prototype,"mode");C([f(Z)],ao.prototype,"color");C([f(Z)],ao.prototype,"colorMin");C([f(Z)],ao.prototype,"colorMax");C([f(fr)],ao.prototype,"gradient");C([f(fr)],ao.prototype,"gradientMin");C([f(fr)],ao.prototype,"gradientMax");let pr=ao;var Sp=(s=>(s[s.Hierarchy=0]="Hierarchy",s[s.Local=1]="Local",s[s.Shape=2]="Shape",s))(Sp||{});class Pt{cullingMode;duration;emitterVelocityMode;flipRotation;gravityModifier;gravityModifierMultiplier;loop;maxParticles;playOnAwake;prewarm;ringBufferLoopRange;ringBufferMode;scalingMode;simulationSpace;simulationSpeed;startColor;startDelay;startDelayMultiplier;startLifetime;startLifetimeMultiplier;startRotation;startRotationMultiplier;startRotation3D;startRotationX;startRotationXMultiplier;startRotationY;startRotationYMultiplier;startRotationZ;startRotationZMultiplier;startSize;startSize3D;startSizeMultiplier;startSizeX;startSizeXMultiplier;startSizeY;startSizeYMultiplier;startSizeZ;startSizeZMultiplier;startSpeed;startSpeedMultiplier;stopAction;useUnscaledTime}C([f(H)],Pt.prototype,"gravityModifier");C([f(pr)],Pt.prototype,"startColor");C([f(H)],Pt.prototype,"startDelay");C([f(H)],Pt.prototype,"startLifetime");C([f(H)],Pt.prototype,"startRotation");C([f(H)],Pt.prototype,"startRotationX");C([f(H)],Pt.prototype,"startRotationY");C([f(H)],Pt.prototype,"startRotationZ");C([f(H)],Pt.prototype,"startSize");C([f(H)],Pt.prototype,"startSizeX");C([f(H)],Pt.prototype,"startSizeY");C([f(H)],Pt.prototype,"startSizeZ");C([f(H)],Pt.prototype,"startSpeed");class wd{cycleCount;maxCount;minCount;probability;repeatInterval;time;count;_performed=0;reset(){this._performed=0}run(e){if(e<=this.time)return 0;let t=0;if(this.cycleCount===0||this._performed<this.cycleCount){const i=this.time+this.repeatInterval*this._performed;if(e>=i&&(this._performed+=1,Math.random()<this.probability))switch(this.count.mode){case 0:t=this.count.constant;break;case 3:t=I.lerp(this.count.constantMin,this.count.constantMax,Math.random());break;case 1:t=this.count.curve.evaluate(Math.random());break;case 2:const n=Math.random();t=I.lerp(this.count.curveMin.evaluate(n),this.count.curveMax.evaluate(n),Math.random());break}}return t}}class ys{enabled;get burstCount(){return this.bursts?.length??0}bursts;rateOverTime;rateOverTimeMultiplier;rateOverDistance;rateOverDistanceMultiplier;system;reset(){this.bursts?.forEach(e=>e.reset())}getBurst(){let e=0;if(this.burstCount>0)for(let t=0;t<this.burstCount;t++){const i=this.bursts[t];this.system.main.loop&&i.time>=this.system.time&&i.reset(),e+=Math.round(i.run(this.system.time))}return e}}C([f()],ys.prototype,"enabled");C([f()],ys.prototype,"bursts");C([f(H)],ys.prototype,"rateOverTime");C([f()],ys.prototype,"rateOverTimeMultiplier");C([f(H)],ys.prototype,"rateOverDistance");C([f()],ys.prototype,"rateOverDistanceMultiplier");class hu{enabled;color}C([f(pr)],hu.prototype,"color");class mr{enabled;separateAxes;size;sizeMultiplier;x;xMultiplier;y;yMultiplier;z;zMultiplier;_time=0;_temp=new c.Vector3;evaluate(e,t,i){if(t||(t=this._temp),!this.enabled)return t.x=t.y=t.z=1,t;if(this.separateAxes)t.x=this.x.evaluate(e,i)*this.xMultiplier,t.y=this.y.evaluate(e,i)*this.yMultiplier,t.z=this.z.evaluate(e,i)*this.zMultiplier;else{const n=this.size.evaluate(e,i)*this.sizeMultiplier;t.x=n}return t}}C([f(H)],mr.prototype,"size");C([f(H)],mr.prototype,"x");C([f(H)],mr.prototype,"y");C([f(H)],mr.prototype,"z");const $e=class gl{get type(){return vd[this.shapeType]}initialize(e){this.onInitialize(e),e.position.x=this._vector.x,e.position.y=this._vector.y,e.position.z=this._vector.z}toJSON(){return this}clone(){return new gl}shapeType=5;enabled=!0;alignToDirection=!1;angle=0;arc=360;arcSpread;arcSpeedMultiplier;arcMode;boxThickness;position;rotation;_rotation=new c.Euler;scale;radius;radiusThickness;sphericalDirectionAmount;randomDirectionAmount;randomPositionAmount;meshShapeType;meshRenderer;_meshObj;_meshGeometry;setMesh(e){this.meshRenderer=e,e?(this._meshObj=e.sharedMeshes[Math.floor(Math.random()*e.sharedMeshes.length)],this._meshGeometry=this._meshObj.geometry):(this._meshObj=void 0,this._meshGeometry=void 0)}system;_space;_worldSpaceMatrix=new c.Matrix4;_worldSpaceMatrixInverse=new c.Matrix4;constructor(){xh&&console.log(this)}update(e,t){}onUpdate(e,t,i,n){this.system=e,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(e){const t=this.rotation.x!==0||this.rotation.y!==0||this.rotation.z!==0;return t&&(this._rotation.x=I.toRadians(this.rotation.x),this._rotation.y=I.toRadians(this.rotation.y),this._rotation.z=I.toRadians(this.rotation.z),this._rotation.order="ZYX",e.applyEuler(this._rotation)),t}_vector=new c.Vector3(0,0,0);_temp=new c.Vector3(0,0,0);_triangle=new c.Triangle;onInitialize(e){this._vector.set(0,0,0),e.mesh=void 0,e.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:xh&&j.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=e.mesh=this._meshObj,a=e.mesh_geometry=this._meshGeometry;if(r&&a)switch(this.meshShapeType){case 0:{const l=a.getAttribute("position"),h=Math.floor(Math.random()*l.count);this._vector.fromBufferAttribute(l,h),this._vector.applyMatrix4(r.matrixWorld),e.mesh_normal=h}break;case 1:break;case 2:{const l=a.index;if(l){let h=Math.random(),d=Math.random();h+d>1&&(h=1-h,d=1-d);const u=Math.floor(Math.random()*(l.count/3));let p=u*3,m=u*3+1,y=u*3+2;p=l.getX(p),m=l.getX(m),y=l.getX(y);const b=a.getAttribute("position");this._triangle.a.fromBufferAttribute(b,p),this._triangle.b.fromBufferAttribute(b,m),this._triangle.c.fromBufferAttribute(b,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),e.mesh_normal=u}}break}break;default:this._vector.set(0,0,0),A()&&!globalThis.__particlesystem_shapetype_unsupported&&(console.warn("ParticleSystem ShapeType is not supported:",vd[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)),xh&&j.DrawSphere(this._vector,.03,16711680,.5,!0)}_dir=new c.Vector3;getDirection(e,t){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 i=t.x,n=t.y,o=t.z;this._dir.set(i,n,o),this.system?.worldspace?this._dir.sub(this.system.worldPos):this._dir.sub(this.position);break;case 13:const r=e.mesh,a=e.mesh_geometry;if(r&&a)switch(this.meshShapeType){case 0:{const l=a.getAttribute("normal"),h=e.mesh_normal;this._dir.fromBufferAttribute(l,h)}break;case 1:break;case 2:{const l=a.index;if(l){const h=e.mesh_normal,d=l.getX(h*3),u=l.getX(h*3+1),p=l.getX(h*3+2),m=a.getAttribute("position"),y=V(),b=V(),g=V();y.fromBufferAttribute(m,d),b.fromBufferAttribute(m,u),g.fromBufferAttribute(m,p),y.sub(b),g.sub(b),y.cross(g),this._dir.copy(y).multiplyScalar(-1);const v=ue(r);this._dir.applyQuaternion(v)}}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),xh&&(j.DrawSphere(t,.01,8925952,.5,!0),j.DrawDirection(t,this._dir,8925952,.5,!0)),this._dir}static _randomQuat=new c.Quaternion;static _tempVec=new c.Vector3;randomizePosition(e,t){if(t<=0)return;const i=gl._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,e.add(i)}randomizeDirection(e,t){if(t===0)return;const i=gl._randomQuat,n=gl._tempVec;n.set(Math.random()-.5,Math.random()-.5,Math.random()-.5).normalize(),i.setFromAxisAngle(n,t*Math.random()*Math.PI),e.applyQuaternion(i)}spherizeDirection(e,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),a=Math.cos(n),l=new c.Vector3(o,r,a);e.lerp(l,t)}randomSpherePoint(e,t,i,n,o){const r=Math.random(),a=Math.random(),l=2*Math.PI*r*(n/360),h=Math.acos(2*a-1),d=I.lerp(1,1-Math.pow(1-Math.random(),Math.PI),i)*t,u=e.x+this.scale.x*(-d*Math.sin(h)*Math.cos(l)),p=e.y+this.scale.y*(d*Math.sin(h)*Math.sin(l)),m=e.z+this.scale.z*(d*Math.cos(h));o.x=u,o.y=p,o.z=m}randomCirclePoint(e,t,i,n,o){const r=Math.random(),a=2*Math.PI*r*(n/360),l=I.lerp(1,1-Math.pow(1-Math.random(),Math.PI),i)*t,h=e.x+this.scale.x*l*Math.cos(a),d=e.y+this.scale.y*l*Math.sin(a),u=e.z;o.x=h,o.y=d,o.z=u}_loopTime=0;_loopDirection=1;randomConePoint(e,t,i,n,o,r,a){let l=0,h=0;switch(r){case 0:l=Math.random(),h=Math.random();break;case 2:this._loopTime>1&&(this._loopDirection=-1),this._loopTime<0&&(this._loopDirection=1);case 1:l=.5,h=Math.random(),this._loopTime+=this.system.deltaTime*this._loopDirection;break}let d=2*Math.PI*l*(o/360);switch(r){case 2:case 1:d+=Math.PI+.5,d+=this._loopTime*Math.PI*2,d%=I.toRadians(o);break}const u=Math.acos(2*h-1),p=I.lerp(1,1-Math.pow(1-Math.random(),Math.PI),n)*i,m=e.x+-p*Math.sin(u)*Math.cos(d),y=e.y+p*Math.sin(u)*Math.sin(d),b=e.z;a.x=m*this.scale.x,a.y=y*this.scale.y,a.z=b*this.scale.z}};C([f()],$e.prototype,"shapeType");C([f()],$e.prototype,"enabled");C([f()],$e.prototype,"alignToDirection");C([f()],$e.prototype,"angle");C([f()],$e.prototype,"arc");C([f()],$e.prototype,"arcSpread");C([f()],$e.prototype,"arcSpeedMultiplier");C([f()],$e.prototype,"arcMode");C([f(c.Vector3)],$e.prototype,"boxThickness");C([f(c.Vector3)],$e.prototype,"position");C([f(c.Vector3)],$e.prototype,"rotation");C([f(c.Vector3)],$e.prototype,"scale");C([f()],$e.prototype,"radius");C([f()],$e.prototype,"radiusThickness");C([f()],$e.prototype,"sphericalDirectionAmount");C([f()],$e.prototype,"randomDirectionAmount");C([f()],$e.prototype,"randomPositionAmount");C([f()],$e.prototype,"meshShapeType");C([f(bc)],$e.prototype,"meshRenderer");let wg=$e;class fe{damping;enabled;frequency;octaveCount;octaveMultiplier;octaveScale;positionAmount;quality;remap;remapEnabled;remapMultiplier;remapX;remapXMultiplier;remapY;remapYMultiplier;remapZ;remapZMultiplier;scrollSpeedMultiplier;separateAxes;strengthMultiplier;strengthX;strengthXMultiplier;strengthY;strengthYMultiplier;strengthZ;strengthZMultiplier;_noise;_time=0;update(e){this._time+=e.time.deltaTime*this.scrollSpeedMultiplier}_temp=new c.Vector3;apply(e,t,i,n,o,r){if(!this.enabled)return;this._noise||(this._noise=se.createNoise4D(()=>0));const a=this._temp.set(t.x,t.y,t.z).multiplyScalar(this.frequency),l=this._noise(a.x,a.y,a.z,this._time),h=this._noise(a.x,a.y,a.z,this._time+1e3*this.frequency),d=this._noise(a.x,a.y,a.z,this._time+2e3*this.frequency);this._temp.set(l,h,d).normalize();const u=o/r;let p=this.positionAmount.evaluate(u);this.separateAxes?(this._temp.x*=p*this.strengthXMultiplier,this._temp.y*=p*this.strengthYMultiplier,this._temp.z*=p*this.strengthZMultiplier):(this.strengthX&&(p*=this.strengthX.evaluate(u)*1.5),this._temp.multiplyScalar(p)),i.x+=this._temp.x,i.y+=this._temp.y,i.z+=this._temp.z}}C([f()],fe.prototype,"damping");C([f()],fe.prototype,"enabled");C([f()],fe.prototype,"frequency");C([f()],fe.prototype,"octaveCount");C([f()],fe.prototype,"octaveMultiplier");C([f()],fe.prototype,"octaveScale");C([f(H)],fe.prototype,"positionAmount");C([f()],fe.prototype,"quality");C([f(H)],fe.prototype,"remap");C([f()],fe.prototype,"remapEnabled");C([f()],fe.prototype,"remapMultiplier");C([f(H)],fe.prototype,"remapX");C([f()],fe.prototype,"remapXMultiplier");C([f(H)],fe.prototype,"remapY");C([f()],fe.prototype,"remapYMultiplier");C([f(H)],fe.prototype,"remapZ");C([f()],fe.prototype,"remapZMultiplier");C([f()],fe.prototype,"scrollSpeedMultiplier");C([f()],fe.prototype,"separateAxes");C([f()],fe.prototype,"strengthMultiplier");C([f(H)],fe.prototype,"strengthX");C([f()],fe.prototype,"strengthXMultiplier");C([f(H)],fe.prototype,"strengthY");C([f()],fe.prototype,"strengthYMultiplier");C([f(H)],fe.prototype,"strengthZ");C([f()],fe.prototype,"strengthZMultiplier");class Ee{enabled;attachRibbonToTransform=!1;colorOverLifetime;colorOverTrail;dieWithParticles=!0;inheritParticleColor=!0;lifetime;lifetimeMultiplier;minVertexDistance=.2;mode=0;ratio=1;ribbonCount=1;shadowBias=0;sizeAffectsLifetime=!1;sizeAffectsWidth=!1;splitSubEmitterRibbons=!1;textureMode=0;widthOverTrail;widthOverTrailMultiplier;worldSpace=!1;getWidth(e,t,i,n){const o=this.widthOverTrail.evaluate(i,n);return e*=o,e}getColor(e,t,i){const n=this.colorOverTrail.evaluate(i),o=this.colorOverLifetime.evaluate(t);e.x*=n.r*o.r,e.y*=n.g*o.g,e.z*=n.b*o.b,"alpha"in n&&"alpha"in o&&(e.w*=n.alpha*o.alpha)}}C([f()],Ee.prototype,"enabled");C([f()],Ee.prototype,"attachRibbonToTransform");C([f(pr)],Ee.prototype,"colorOverLifetime");C([f(pr)],Ee.prototype,"colorOverTrail");C([f()],Ee.prototype,"dieWithParticles");C([f()],Ee.prototype,"inheritParticleColor");C([f(H)],Ee.prototype,"lifetime");C([f()],Ee.prototype,"lifetimeMultiplier");C([f()],Ee.prototype,"minVertexDistance");C([f()],Ee.prototype,"mode");C([f()],Ee.prototype,"ratio");C([f()],Ee.prototype,"ribbonCount");C([f()],Ee.prototype,"shadowBias");C([f()],Ee.prototype,"sizeAffectsLifetime");C([f()],Ee.prototype,"sizeAffectsWidth");C([f()],Ee.prototype,"splitSubEmitterRibbons");C([f()],Ee.prototype,"textureMode");C([f(H)],Ee.prototype,"widthOverTrail");C([f()],Ee.prototype,"widthOverTrailMultiplier");C([f()],Ee.prototype,"worldSpace");class Le{enabled;space=0;orbitalX;orbitalY;orbitalZ;orbitalXMultiplier;orbitalYMultiplier;orbitalZMultiplier;orbitalOffsetX;orbitalOffsetY;orbitalOffsetZ;speedModifier;speedModifierMultiplier;x;xMultiplier;y;yMultiplier;z;zMultiplier;_system;update(e){this._system=e}_temp=new c.Vector3;_temp2=new c.Vector3;_temp3=new c.Vector3;_hasOrbital=!1;_index=0;_orbitalMatrix=new c.Matrix4;init(e){this._index==0&&(e.debug=!0),this._index+=1,e.orbitx=this.orbitalX.evaluate(Math.random()),e.orbity=this.orbitalY.evaluate(Math.random()),e.orbitz=this.orbitalZ.evaluate(Math.random()),this._hasOrbital=e.orbitx!=0||e.orbity!=0||e.orbitz!=0}apply(e,t,i,n,o,r,a){if(!this.enabled)return;const l=r/a,h=this.speedModifier.evaluate(l)*this.speedModifierMultiplier,d=this.x.evaluate(l),u=this.y.evaluate(l),p=this.z.evaluate(l);if(this._temp.set(-d,u,p),this._system&&this._system.main.simulationSpace===1&&this._temp.applyQuaternion(this._system.worldQuaternion),this._hasOrbital&&this._system?.worldPos){const y=this._temp2.set(i.x,i.y,i.z),b=this.orbitalXMultiplier,g=this.orbitalYMultiplier,v=this.orbitalZMultiplier,_=h*Math.PI*2*10,S=Math.cos(_*b),T=Math.sin(_*b),M=Math.cos(_*g),O=Math.sin(_*g),R=Math.cos(_*v),B=Math.sin(_*v),L=y.x*(M*R)+y.y*(M*B)+y.z*-O,N=y.x*(T*O*R-S*B)+y.y*(T*O*B+S*R)+y.z*(T*M),$=y.x*(S*O*R+T*B)+y.y*(S*O*B-T*R)+y.z*(S*M),E=this._temp3.set(y.x-L,y.y-N,y.z-$);E.normalize(),E.multiplyScalar(.2/o*Math.max(this.orbitalXMultiplier,this.orbitalYMultiplier,this.orbitalZMultiplier)),n.x+=E.x,n.y+=E.y,n.z+=E.z}n.x+=this._temp.x,n.y+=this._temp.y,n.z+=this._temp.z,n.x*=h,n.y*=h,n.z*=h}}C([f()],Le.prototype,"enabled");C([f()],Le.prototype,"space");C([f(H)],Le.prototype,"orbitalX");C([f(H)],Le.prototype,"orbitalY");C([f(H)],Le.prototype,"orbitalZ");C([f()],Le.prototype,"orbitalXMultiplier");C([f()],Le.prototype,"orbitalYMultiplier");C([f()],Le.prototype,"orbitalZMultiplier");C([f()],Le.prototype,"orbitalOffsetX");C([f()],Le.prototype,"orbitalOffsetY");C([f()],Le.prototype,"orbitalOffsetZ");C([f(H)],Le.prototype,"speedModifier");C([f()],Le.prototype,"speedModifierMultiplier");C([f(H)],Le.prototype,"x");C([f()],Le.prototype,"xMultiplier");C([f(H)],Le.prototype,"y");C([f()],Le.prototype,"yMultiplier");C([f(H)],Le.prototype,"z");C([f()],Le.prototype,"zMultiplier");class Mt{animation;enabled;cycleCount;frameOverTime;frameOverTimeMultiplier;numTilesX;numTilesY;startFrame;startFrameMultiplier;rowMode;rowIndex;spriteCount;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(e){if(!this.sampleOnceAtStart())return this.getIndex(e)}getIndex(e){const t=this.numTilesX*this.numTilesY;e=e*this.cycleCount;let i=this.frameOverTime.evaluate(e%1);return i*=this.frameOverTimeMultiplier,i*=t,i=i%t,i=Math.floor(i),i}}C([f()],Mt.prototype,"animation");C([f()],Mt.prototype,"enabled");C([f()],Mt.prototype,"cycleCount");C([f(H)],Mt.prototype,"frameOverTime");C([f()],Mt.prototype,"frameOverTimeMultiplier");C([f()],Mt.prototype,"numTilesX");C([f()],Mt.prototype,"numTilesY");C([f(H)],Mt.prototype,"startFrame");C([f()],Mt.prototype,"startFrameMultiplier");C([f()],Mt.prototype,"rowMode");C([f()],Mt.prototype,"rowIndex");C([f()],Mt.prototype,"spriteCount");C([f()],Mt.prototype,"timeMode");class rn{enabled;separateAxes;x;xMultiplier;y;yMultiplier;z;zMultiplier;evaluate(e,t){return this.enabled?this.separateAxes?0:this.z.evaluate(e,t)*-1:0}}C([f()],rn.prototype,"enabled");C([f()],rn.prototype,"separateAxes");C([f(H)],rn.prototype,"x");C([f()],rn.prototype,"xMultiplier");C([f(H)],rn.prototype,"y");C([f()],rn.prototype,"yMultiplier");C([f(H)],rn.prototype,"z");C([f()],rn.prototype,"zMultiplier");class Ni{enabled;range;separateAxes;x;xMultiplier;y;yMultiplier;z;zMultiplier;evaluate(e,t){if(!this.enabled)return 0;if(!this.separateAxes){const i=I.lerp(this.range.x,this.range.y,t);return this.z.evaluate(i)*-1}return 0}}C([f()],Ni.prototype,"enabled");C([f()],Ni.prototype,"range");C([f()],Ni.prototype,"separateAxes");C([f(H)],Ni.prototype,"x");C([f()],Ni.prototype,"xMultiplier");C([f(H)],Ni.prototype,"y");C([f()],Ni.prototype,"yMultiplier");C([f(H)],Ni.prototype,"z");C([f()],Ni.prototype,"zMultiplier");class et{enabled;dampen;drag;dragMultiplier;limit;limitMultiplier;separateAxes;limitX;limitXMultiplier;limitY;limitYMultiplier;limitZ;limitZMultiplier;multiplyDragByParticleSize=!1;multiplyDragByParticleVelocity=!1;space;_temp=new c.Vector3;_temp2=new c.Vector3;apply(e,t,i,n,o,r,a){if(this.enabled){const l=this.limit.evaluate(o)*this.limitMultiplier;if(t.length()>l){this._temp.copy(t).normalize().multiplyScalar(l);const d=this.dampen*.5;t.x=I.lerp(t.x,this._temp.x,d),t.y=I.lerp(t.y,this._temp.y,d),t.z=I.lerp(t.z,this._temp.z,d),i.x=I.lerp(i.x,this._temp.x,d),i.y=I.lerp(i.y,this._temp.y,d),i.z=I.lerp(i.z,this._temp.z,d)}}}}C([f()],et.prototype,"enabled");C([f()],et.prototype,"dampen");C([f(H)],et.prototype,"drag");C([f()],et.prototype,"dragMultiplier");C([f(H)],et.prototype,"limit");C([f()],et.prototype,"limitMultiplier");C([f()],et.prototype,"separateAxes");C([f(H)],et.prototype,"limitX");C([f()],et.prototype,"limitXMultiplier");C([f(H)],et.prototype,"limitY");C([f()],et.prototype,"limitYMultiplier");C([f(H)],et.prototype,"limitZ");C([f()],et.prototype,"limitZMultiplier");C([f()],et.prototype,"multiplyDragByParticleSize");C([f()],et.prototype,"multiplyDragByParticleVelocity");C([f()],et.prototype,"space");const Ac=class Zv{enabled;curve;curveMultiplier;mode;clone(){const e=new Zv;return e.enabled=this.enabled,e.curve=this.curve?.clone(),e.curveMultiplier=this.curveMultiplier,e.mode=this.mode,e}system;get _lastWorldPosition(){return this.system._iv_lastWorldPosition||(this.system._iv_lastWorldPosition=new c.Vector3),this.system._iv_lastWorldPosition}get _velocity(){return this.system._iv_velocity||(this.system._iv_velocity=new c.Vector3),this.system._iv_velocity}_temp=new c.Vector3;_firstUpdate=!0;awake(e){this.system=e,this.reset()}reset(){this._firstUpdate=!0}update(e){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(e){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),e.x+=this._temp.x,e.y+=this._temp.y,e.z+=this._temp.z}}_frames=0;applyCurrent(e,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),e.x+=this._temp.x,e.y+=this._temp.y,e.z+=this._temp.z}}};C([f()],Ac.prototype,"enabled");C([f(H)],Ac.prototype,"curve");C([f()],Ac.prototype,"curveMultiplier");C([f()],Ac.prototype,"mode");let xg=Ac;class Zt{enabled;range;separateAxes;size;sizeMultiplier;x;xMultiplier;y;yMultiplier;z;zMultiplier;evaluate(e,t,i,n){const o=e.length(),r=I.remap(o,this.range.x,this.range.y,0,1),a=this.size.evaluate(r,i);return n.x*=a,n.y*=a,n.z*=a,n}}C([f()],Zt.prototype,"enabled");C([f(c.Vector2)],Zt.prototype,"range");C([f()],Zt.prototype,"separateAxes");C([f(H)],Zt.prototype,"size");C([f()],Zt.prototype,"sizeMultiplier");C([f(H)],Zt.prototype,"x");C([f()],Zt.prototype,"xMultiplier");C([f(H)],Zt.prototype,"y");C([f()],Zt.prototype,"yMultiplier");C([f(H)],Zt.prototype,"z");C([f()],Zt.prototype,"zMultiplier");class Oa{enabled;range;color;evaluate(e,t,i){const n=e.length(),o=I.remap(n,this.range.x,this.range.y,0,1),r=this.color.evaluate(o,t);i.x*=r.r,i.y*=r.g,i.z*=r.b,"alpha"in r&&(i.w*=r.alpha)}}C([f()],Oa.prototype,"enabled");C([f(c.Vector2)],Oa.prototype,"range");C([f(pr)],Oa.prototype,"color");new c.Vector3(1,1,1);new c.Vector3(0,0,1);class Sg{constructor(e,t,i,n){this.system=e,this.particleSystem=t,this.subSystem=i,this.subParticleSystem=n,this.subParticleSystem&&this.subParticleSystem&&(this.subParticleSystem.onlyUsedByOther=!0);const o=1e3;this._circularBuffer=new hi(()=>new se.Matrix4,o)}type="NeedleParticleSubEmitter";emitterType;emitterProbability;q_=new c.Quaternion;v_=new c.Vector3;v2_=new c.Vector3;_emitterMatrix=new se.Matrix4;_circularBuffer;clone(){throw new Error("Method not implemented.")}initialize(e){e.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===Cp.Birth&&this.run(e)}update(e,t){this.run(e)}frameUpdate(e){}toJSON(){}reset(){}run(e){if(this.subSystem.currentParticles>=this.subSystem.main.maxParticles||!this.subParticleSystem||!e.emissionState||this.emitterProbability&&Math.random()>this.emitterProbability)return;const t=this.system.deltaTime;if(this.emitterType===Cp.Death){let n=e.life;if(e[$r]!==void 0&&(n=e[$r]),!(e.age+t*1.2>=n))return;const r=this.subSystem.main.maxParticles-this.subSystem.currentParticles;e.emissionState.waitEmiting=r}const i=new se.Matrix4;i.set(1,0,0,e.position.x,0,1,0,e.position.y,0,0,1,e.position.z,0,0,0,1),this.particleSystem.worldSpace||i.multiplyMatrices(this._emitterMatrix,i),this.subParticleSystem.emit(t,e.emissionState,i)}}var gO=Object.defineProperty,Te=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&gO(e,t,n),n};const js=w("debugparticles"),yO=w("noprogressive"),_O=w("debugprogressive");var Cp=(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))(Cp||{});class Vi extends k{renderMode;particleMaterial;trailMaterial;particleMesh;maxParticleSize;minParticleSize;velocityScale;cameraVelocityScale;lengthScale;start(){if(this.maxParticleSize!==.5&&this.minParticleSize!==0&&A()){const e=`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(e)}}get transparent(){return this.particleMaterial?.transparent??!1}getMaterial(e=!1){let t=e===!0&&this.trailMaterial?this.trailMaterial:this.particleMaterial;if(t){if(t.type==="MeshStandardMaterial"){js&&console.debug("ParticleSystemRenderer.getMaterial: MeshStandardMaterial detected, converting to MeshBasicMaterial. See https://github.com/Alchemist0823/three.quarks/issues/101"),"map"in t&&t.map&&(t.map.colorSpace=c.LinearSRGBColorSpace,t.map.premultiplyAlpha=!1);const i=new c.MeshBasicMaterial;i.copy(t),e?this.trailMaterial=i:this.particleMaterial=i}t.map&&(t.map.colorSpace=c.LinearSRGBColorSpace,t.map.premultiplyAlpha=!1),e&&t.side===c.FrontSide&&(t=t.clone(),t.side=c.BackSide,e?this.trailMaterial=t:this.particleMaterial=t)}return t&&!yO&&t._didRequestTextureLOD===void 0&&(t._didRequestTextureLOD=0,_O&&console.log("Load material LOD",t.name),ne.NEEDLE_progressive.assignTextureLOD(t,0)),t}getMesh(e){let t=null;if(!t&&(this.particleMesh instanceof c.Mesh&&(t=this.particleMesh.geometry),t===null)){t=new c.PlaneGeometry(1,1);const n=t.attributes.uv;for(let o=0;o<n.count;o++)n.setX(o,1-n.getX(o))}return new c.Mesh(t,this.getMaterial())}}Te([f()],Vi.prototype,"renderMode");Te([f(c.Material)],Vi.prototype,"particleMaterial");Te([f(c.Material)],Vi.prototype,"trailMaterial");Te([f()],Vi.prototype,"maxParticleSize");Te([f()],Vi.prototype,"minParticleSize");Te([f()],Vi.prototype,"velocityScale");Te([f()],Vi.prototype,"cameraVelocityScale");Te([f()],Vi.prototype,"lengthScale");class Sh{_curve;_factor;constructor(e,t=1){this._curve=e,this._factor=t}type="function";startGen(e){}genValue(e,t){return this._curve.evaluate(t,Math.random())*this._factor}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}}class Cg{type="value";toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}startGen(e){}system;constructor(e){this.system=e}}class bO extends Cg{genValue(){return this.system.textureSheetAnimation.getStartIndex()}}class vO extends Cg{_lastPosition=new c.Vector3;_lastDistance=0;update(){const e=X(this.system.gameObject);this._lastDistance=this._lastPosition.distanceTo(e),this._lastPosition.copy(e)}genValue(){if(!this.system.isPlaying||!this.system.emission.enabled||this.system.currentParticles>=this.system.maxParticles)return 0;let e=this.system.emission.rateOverTime.evaluate(this.system.time/this.system.duration,Math.random());if(this.system.deltaTime>0){const n=this.system.emission.rateOverDistance.evaluate(this.system.time/this.system.duration,Math.random());let r=this._lastDistance/this.system.deltaTime*n;Number.isFinite(r)||(r=0),e+=r}const t=this.system.emission.getBurst();t>0&&(e+=t/this.system.deltaTime);const i=this.system.maxParticles-this.system.currentParticles;return I.clamp(e,0,i/this.system.deltaTime)}}class wO extends Cg{genValue(){return this.system.isPlaying,0}}class lo{system;get context(){return this.system.context}constructor(e){this.type=Object.getPrototypeOf(this).constructor.name||"ParticleSystemBaseBehaviour",e&&(this.system=e)}type;initialize(e){}update(e,t){}frameUpdate(e){}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}reset(){}}class xO extends lo{type="NeedleTextureSheet";update(e,t){const i=this.system.textureSheetAnimation;if(i.enabled){const n=e.age/e.life,o=i.evaluate(n);o!==void 0&&(e.uvTile=o)}}}const w_=Symbol("particleRotation");class SO extends lo{type="NeedleRotation";initialize(e){e[w_]=Math.random()}update(e,t){if(e.rotation===void 0)return;const i=e.age/e.life;if(typeof e.rotation=="number"&&(this.system.rotationOverLifetime.enabled?e.rotation+=this.system.rotationOverLifetime.evaluate(i,e[w_])*t:this.system.renderer.renderMode===Kn.Billboard&&(e.rotation=Math.PI),this.system.rotationBySpeed.enabled)){const n=e.velocity.length();e.rotation+=this.system.rotationBySpeed.evaluate(i,n)*t}}}const x_=Symbol("sizeLerpFactor"),CO=new c.Vector3;class PO extends lo{type="NeedleSize";_minSize=0;_maxSize=1;initialize(e){e[x_]=Math.random(),this._minSize=this.system.renderer.minParticleSize,this._maxSize=this.system.renderer.maxParticleSize}update(e,t){const i=e.age/e.life;let n=1;this.system.sizeOverLifetime.enabled&&(n*=this.system.sizeOverLifetime.evaluate(i,void 0,e[x_]).x);let o=1;this.system.renderer.renderMode!==Kn.Mesh&&(o=this.system.worldScale.x/this.system.cameraScale);const r=V(e.startSize).multiplyScalar(n*o);if(e.size.set(r.x,r.y,r.z),this.system.localspace){const a=Jv(this.system,CO);e.size.x*=a.x,e.size.y*=a.y,e.size.z*=a.z}}}const $r=Symbol("particleLife"),Pf=Symbol("trailLifetime"),S_=Symbol("trailStartLength"),Mf=Symbol("trailWidthRandom");class MO extends lo{type="NeedleTrail";initialize(e){e instanceof se.TrailParticle&&(e[$r]=e.life,this.system.trails.enabled&&this.system.trails.dieWithParticles===!1&&(e[Pf]=this.system.trails.lifetime.evaluate(Math.random(),Math.random()),e.life+=e[Pf]),e[S_]=e.length,e[Mf]=Math.random())}update(e){if(this.system.trails?.enabled&&e instanceof se.TrailParticle){const t=e,i=e.age/e[$r],n=e.previous.values(),o=e.previous.length;for(let r=0;r<o;r++){const l=n.next().value,h=1-r/(o-1),d=e.size;if(d.x<=0&&!this.system.trails.sizeAffectsWidth){const u=20*this.system.trails.widthOverTrail.evaluate(.5,t[Mf]);d.x=u,d.y=u,d.z=u}l.size=this.system.trails.getWidth(d.x,i,h,t[Mf]),l.color.copy(e.color),this.system.trails.getColor(l.color,i,h)}if(e.age>e[$r]){e.velocity.set(0,0,0);const r=(e.age-e[$r])/e[Pf];t.length=I.lerp(e[S_],0,r)}}}}const Ch=Symbol("startVelocity"),C_=Symbol("gravityModifier"),Of=Symbol("gravitySpeed"),Ph=Symbol("velocity lerp factor"),Pp=new c.Vector3;class OO extends lo{type="NeedleVelocity";_gravityDirection=new c.Vector3;initialize(e){const t=this.system.main.simulationSpeed;e.startSpeed=this.system.main.startSpeed.evaluate(Math.random(),Math.random());const i=this.system.shape.getDirection(e,e.position);e.velocity.x=i.x*e.startSpeed,e.velocity.y=i.y*e.startSpeed,e.velocity.z=i.z*e.startSpeed,this.system.inheritVelocity?.enabled&&this.system.inheritVelocity.applyInitial(e.velocity),e[Ch]?e[Ch].copy(e.velocity):e[Ch]=e.velocity.clone();const n=this.system.main.gravityModifier.evaluate(Math.random(),Math.random());e[C_]=n*t,e[Of]=n*t*.5,e[Ph]=Math.random(),this.system.velocityOverLifetime?.init(e),this._gravityDirection.set(0,-1,0),this.system.main.simulationSpace===Hl.Local&&this._gravityDirection.applyQuaternion(this.system.worldQuaternionInverted).normalize()}update(e,t){const i=e[Ch],n=e[C_];if(n!==0){const u=n*e[Of];Pp.copy(this._gravityDirection).multiplyScalar(u),e[Of]+=t*.05,i.add(Pp)}e.velocity.copy(i);const o=e.age/e.life;this.system.inheritVelocity?.enabled&&this.system.inheritVelocity.applyCurrent(e.velocity,o,e[Ph]);const r=this.system.noise;r.enabled&&r.apply(0,e.position,e.velocity,t,e.age,e.life);const a=this.system.sizeBySpeed;a?.enabled&&(e.size=a.evaluate(e.velocity,o,e[Ph],e.size));const l=this.system.colorBySpeed;l?.enabled&&l.evaluate(e.velocity,e[Ph],e.color);const h=this.system.velocityOverLifetime;h.enabled&&h.apply(e,0,e.position,e.velocity,t,e.age,e.life);const d=this.system.limitVelocityOverLifetime;if(d.enabled&&d.apply(e.position,i,e.velocity,e.size,o,t,1),this.system.worldspace){const u=this.system.worldScale;e.velocity.x*=u.x,e.velocity.y*=u.y,e.velocity.z*=u.z}}}const P_=Symbol("colorLerpFactor"),M_=new Z(1,1,1,1),yo=new Z(1,1,1,1);class kO extends lo{type="NeedleColor";initialize(e){}_init(e){const t=this.system.renderer.particleMaterial;yo.copy(this.system.main.startColor.evaluate(Math.random())),t?.color&&(M_.copy(t.color),yo.multiply(M_)),yo.convertLinearToSRGB(),e.startColor.set(yo.r,yo.g,yo.b,yo.alpha),e.color.copy(e.startColor),e[P_]=Math.random()}update(e,t){if(e.age===0&&this._init(e),this.system.colorOverLifetime.enabled){const i=e.age/e.life,n=this.system.colorOverLifetime.color.evaluate(i,e[P_]);e.color.set(n.r,n.g,n.b,"alpha"in n?n.alpha:1).multiply(e.startColor)}else e.color.copy(e.startColor)}}class RO{system;emission;get anim(){return this.system.textureSheetAnimation}constructor(e){this.system=e,this.emission=new vO(this.system)}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()}autoDestroy;get looping(){return this.system.main.loop}get duration(){return this.system.duration}get shape(){return this.system.shape}get startLife(){return new Sh(this.system.main.startLifetime)}get startSpeed(){return new Sh(this.system.main.startSpeed)}get startRotation(){return new Sh(this.system.main.startRotation)}get startSize(){return new Sh(this.system.main.startSize)}startLength;get startColor(){return new se.ConstantColor(new se.Vector4(1,1,1,1))}get emissionOverTime(){return this.emission}get emissionOverDistance(){return new wO(this.system)}emissionBursts;onlyUsedByOther;behaviors=[];get instancingGeometry(){return this.system.renderer.getMesh(this.system.renderer.renderMode).geometry}get renderMode(){if(this.system.trails.enabled===!0)return se.RenderMode.Trail;switch(this.system.renderer.renderMode){case Kn.Billboard:return se.RenderMode.BillBoard;case Kn.Stretch:return se.RenderMode.StretchedBillBoard;case Kn.HorizontalBillboard:return se.RenderMode.HorizontalBillBoard;case Kn.VerticalBillboard:return se.RenderMode.VerticalBillBoard;case Kn.Mesh:return se.RenderMode.Mesh}return se.RenderMode.BillBoard}rendererEmitterSettings={startLength:new se.ConstantValue(220),followLocalOrigin:!1};get speedFactor(){let e=this.system.main.simulationSpeed;return this.system.renderer?.renderMode===Kn.Stretch&&(e*=this.system.renderer.velocityScale??1),e}flatWhiteTexture;clonedTexture={original:void 0,clone:void 0};get texture(){const e=this.material;if(e&&e.map){const t=e.map;if(this.clonedTexture.original!==t||!this.clonedTexture.clone){const i=t.clone();i.premultiplyAlpha=!1,i.colorSpace=c.LinearSRGBColorSpace,this.clonedTexture.original=t,this.clonedTexture.clone=i}return this.clonedTexture.clone}return this.flatWhiteTexture||(this.flatWhiteTexture=mm(new Z(1,1,1,1),1)),this.flatWhiteTexture}get startTileIndex(){return new bO(this.system)}get uTileCount(){return this.anim.enabled?this.anim?.numTilesX:void 0}get vTileCount(){return this.anim.enabled?this.anim?.numTilesY:void 0}get renderOrder(){return 1}get blending(){return this.system.renderer.particleMaterial?.blending??c.NormalBlending}get transparent(){return this.system.renderer.transparent}get worldSpace(){return this.system.main.simulationSpace===Hl.World}}class EO{burstParticleIndex=0;burstParticleCount=0;isBursting=!1;travelDistance=0;previousWorldPos;burstIndex=0;burstWaveIndex=0;time=0;waitEmiting=0}const Ot=class Wh extends k{play(e=!1){e&&x.foreachComponent(this.gameObject,t=>{t instanceof Wh&&t!==this&&t.play(!1)},!0),this._isPlaying=!0,this._particleSystem&&(this._particleSystem.emissionState.time=0,this._particleSystem.emitEnded=!1),this.emission?.reset()}pause(e=!0){e&&x.foreachComponent(this.gameObject,t=>{t instanceof Wh&&t!==this&&t.pause(!1)},!0),this._isPlaying=!1}stop(e=!0,t=!1){e&&x.foreachComponent(this.gameObject,i=>{i instanceof Wh&&i!==this&&i.stop(!1,t)},!0),this._isPlaying=!1,this._time=0,t&&this.reset()}reset(){this._time=0,this._particleSystem&&(this._particleSystem.particleNum=0,this._particleSystem.emissionState.time=0,this._particleSystem.emitEnded=!1,this.emission?.reset())}_state;emit(e){if(this._particleSystem){this.onUpdate(),e=Math.min(e,this.maxParticles-this.currentParticles),this._state||(this._state=new EO),this._state.waitEmiting=e,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(e){this.main.playOnAwake=e}colorOverLifetime;main;emission;sizeOverLifetime;shape;noise;trails;velocityOverLifetime;limitVelocityOverLifetime;inheritVelocity;colorBySpeed;textureSheetAnimation;rotationOverLifetime;rotationBySpeed;sizeBySpeed;get renderer(){return this._renderer}get isPlaying(){return this._isPlaying}get currentParticles(){return this._particleSystem?.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}_cameraScale=1;get container(){return this._container}get worldspace(){return this.main.simulationSpace===Hl.World}get localspace(){return this.main.simulationSpace===Hl.Local}__worldQuaternion=new c.Quaternion;get worldQuaternion(){return this.__worldQuaternion}_worldQuaternionInverted=new c.Quaternion;get worldQuaternionInverted(){return this._worldQuaternionInverted}_worldScale=new c.Vector3;get worldScale(){return this._worldScale}_worldPositionFrame=-1;_worldPos=new c.Vector3;get worldPos(){return this._worldPositionFrame!==this.context.time.frame&&(this._worldPositionFrame=this.context.time.frame,X(this.gameObject,this._worldPos)),this._worldPos}get matrixWorld(){return this._container.matrixWorld}get isSubsystem(){return this._isUsedAsSubsystem}addBehaviour(e){return this._particleSystem?(e instanceof lo&&(e.system=this),js&&console.debug("Add custom ParticleSystem Behaviour",e),this._particleSystem.addBehavior(e),!0):!1}removeBehaviour(e){if(!this._particleSystem)return!1;const t=this._particleSystem.behaviors,i=t.indexOf(e);return i!==-1&&((A()||js)&&console.debug("Remove custom ParticleSystem Behaviour",i,e),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}_renderer;_batchSystem;_particleSystem;_interface;_container;_time=0;_isPlaying=!0;_isUsedAsSubsystem=!1;_didPreWarm=!1;set bursts(e){for(let t=0;t<e.length;t++){const i=e[t];if(!(i instanceof wd)){const n=new wd;sa(n,i),e[t]=n}}this._bursts=e}_bursts;set subEmitterSystems(e){for(let t=0;t<e.length;t++){const i=e[t];if(!(i instanceof xd)){const n=new xd;sa(n,i),e[t]=n}}js&&e.length>0&&console.log("SubEmitters: ",e,this),this._subEmitterSystems=e}_subEmitterSystems;onAfterDeserialize(e){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(Vi),!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 c.Object3D,this._container.matrixAutoUpdate=!1,this.context.scene.add(this._container),this._batchSystem=new se.BatchedParticleRenderer,this._batchSystem.name=this.gameObject.name,this._container.add(this._batchSystem),this._interface=new RO(this),this._particleSystem=new se.ParticleSystem(this._interface),this._particleSystem.addBehavior(new PO(this)),this._particleSystem.addBehavior(new kO(this)),this._particleSystem.addBehavior(new xO(this)),this._particleSystem.addBehavior(new SO(this)),this._particleSystem.addBehavior(new OO(this)),this._particleSystem.addBehavior(new MO(this)),this._batchSystem.addSystem(this._particleSystem);const e=this._particleSystem.emitter;this.context.scene.add(e),this.inheritVelocity.system&&this.inheritVelocity.system!==this&&(this.inheritVelocity=this.inheritVelocity.clone()),this.inheritVelocity.awake(this),js&&(console.log(this),this.gameObject.add(new c.AxesHelper(1)))}start(){this.addSubParticleSystems(),this.updateLayers(),this.renderer.particleMesh instanceof c.Mesh&&this._interface.renderMode==se.RenderMode.Mesh&&ne.NEEDLE_progressive.assignMeshLOD(this.renderer.particleMesh,0).then(e=>{e&&this.particleSystem&&this._interface.renderMode==se.RenderMode.Mesh&&(this.particleSystem.instancingGeometry=e)})}onDestroy(){this._container?.removeFromParent(),this._batchSystem?.removeFromParent(),this._particleSystem?.emitter.removeFromParent(),this._particleSystem?.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(){this.main&&(this._didPreWarm===!1&&this.main?.prewarm===!0&&(this._didPreWarm=!0,this.preWarm()),this.onUpdate(),this.onSimulate(this.deltaTime))}preWarm(){if(!this.emission?.enabled||this.emission.rateOverTime.getMax()<=0)return;const t=1/60,i=this.main.duration,n=this.main.startLifetime.getMax(),r=Math.min(Math.max(i,n)/Math.max(.01,this.main.simulationSpeed),1e3),a=Math.ceil(r/t),l=Date.now();js&&console.log(`Particles ${this.name} - Prewarm for ${a} frames (${r} sec). Duration: ${i}, Lifetime: ${n}`);for(let h=0;h<a&&!(this.currentParticles>=this.maxParticles);h++){const d=Date.now()-l;if(d>2e3){console.warn(`Particles ${this.name} - Prewarm took too long. Aborting: ${d}`);break}this.onUpdate(),this.onSimulate(t)}}_lastBatchesCount=-1;onSimulate(e){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(e)}this._time+=e,this._time>this.duration&&(this._time=0)}updateLayers(){if(this._batchSystem)for(let e=0;e<this._batchSystem.batches.length;e++){const t=this._batchSystem.batches[e];t.layers.disableAll();const i=this.layer;t.layers.mask=1<<i}}onUpdate(){if(this._bursts&&(this.emission.bursts=this._bursts,delete this._bursts),!this._isPlaying)return;const e=this.context.mainCamera;if(e){const n=Ae(e);this._cameraScale=n.x}const t=!this.worldspace,i=this.gameObject;if(ue(i,this.__worldQuaternion),this._worldQuaternionInverted.copy(this.__worldQuaternion).invert(),Ae(this.gameObject,this._worldScale),t&&this._container&&this.gameObject?.parent){const n=Jv(this,Pp);this._container.matrix.makeScale(n.x,n.y,n.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),this.inheritVelocity?.update(this.context),this.velocityOverLifetime.update(this)}addSubParticleSystems(){if(this._subEmitterSystems&&this._particleSystem)for(const e of this._subEmitterSystems){e.particleSystem&&(e.particleSystem.__internalAwake?e.particleSystem.__internalAwake():A()&&console.warn("SubParticleSystem serialization issue(?)",e.particleSystem,e));const t=e.particleSystem?._particleSystem;if(t){e.particleSystem._isUsedAsSubsystem=!0;const i=new Sg(this,this._particleSystem,e.particleSystem,t);i.emitterType=e.type,i.emitterProbability=e.emitProbability,this._particleSystem.addBehavior(i)}else js&&console.warn("Could not add SubParticleSystem",e,this)}}};Te([f(hu)],Ot.prototype,"colorOverLifetime");Te([f(Pt)],Ot.prototype,"main");Te([f(ys)],Ot.prototype,"emission");Te([f(mr)],Ot.prototype,"sizeOverLifetime");Te([f(wg)],Ot.prototype,"shape");Te([f(fe)],Ot.prototype,"noise");Te([f(Ee)],Ot.prototype,"trails");Te([f(Le)],Ot.prototype,"velocityOverLifetime");Te([f(et)],Ot.prototype,"limitVelocityOverLifetime");Te([f(xg)],Ot.prototype,"inheritVelocity");Te([f(Oa)],Ot.prototype,"colorBySpeed");Te([f(Mt)],Ot.prototype,"textureSheetAnimation");Te([f(rn)],Ot.prototype,"rotationOverLifetime");Te([f(Ni)],Ot.prototype,"rotationBySpeed");Te([f(Zt)],Ot.prototype,"sizeBySpeed");let ql=Ot;class xd{particleSystem;emitProbability=1;properties;type;_deserialize(e,t){const i=this.particleSystem;if(i instanceof ql)return;let n="";i&&typeof i.guid=="string"&&(n=i.guid,this.particleSystem=x.findByGuid(n,t)),js&&!(this.particleSystem instanceof ql)&&console.warn("Could not find particle system for sub emitter",n,t,this)}}function Jv(s,e){if(e.set(1,1,1),s.gameObject.parent&&s.localspace)switch(s.main.scalingMode){case Sp.Local:e=Ae(s.gameObject.parent,e),e.x=1/e.x,e.y=1/e.y,e.z=1/e.z;break;default:if(!s.unsupported_scaling_mode){s.unsupported_scaling_mode=!0;const t="ParticleSystem scale mode "+Sp[s.main.scalingMode]+" is not supported";A()&&ce(t),console.warn(t,s.name,s)}e=Ae(s.gameObject,e);break}return e}class ha extends k{_didAssignPlayerColor=!1;onEnable(){this.context.connection.beginListen(Q.JoinedRoom,this.tryAssignColor),this._didAssignPlayerColor||this.startCoroutine(this.waitForConnection())}onDisable(){this.context.connection.stopListen(Q.JoinedRoom,this.tryAssignColor)}*waitForConnection(){for(;!this.destroyed&&this.activeAndEnabled&&(yield pm(.2),!this.tryAssignColor()););}tryAssignColor=()=>{const e=x.getComponentInParent(this.gameObject,Zi);if(e&&e.owner)return this._didAssignPlayerColor=!0,this.assignUserColor(e.owner),!0;const t=x.getComponentInParent(this.gameObject,xe);return t?.connectionId?(this._didAssignPlayerColor=!0,this.assignUserColor(t.connectionId),!0):!1};assignUserColor(e){const t=ha.hashCode(e),i=ha.colorFromHashCode(t);if(this.gameObject.type==="Mesh"){const n=this.gameObject;this.assignColor(i,e,n)}else if(this.gameObject.children)for(const n of this.gameObject.children){const o=n;o.material&&o.material.color&&this.assignColor(i,e,o)}}assignColor(e,t,i){let n=i.material;n&&(n._playerMaterial!==t&&(n=n.clone(),n._playerMaterial=t,i.material=n),n.color=e)}static hashCode(e){var t=0,i,n;if(e.length===0)return t;for(i=0;i<e.length;i++)n=e.charCodeAt(i),t=(t<<5)-t+n,t|=0;return t}static colorFromHashCode(e){const t=(e&16711680)>>16,i=(e&65280)>>8,n=e&255;return new c.Color(t/255,i/255,n/255)}}const yl=w("debugpost");let Mp=null;function TO(s){Mp=s}function ew(s){let e=s.gameObject;for(;e;){for(const t of Fd(e))if(t.isPostProcessingManager===!0)return t;e=e.parent}return null}function AO(s){let e=ew(s);if(!e)if(Mp){yl&&console.warn("Adding postprocessing manager to the scene.");const t=s.scene;e=ci(t,Mp)}else A()&&console.warn("No post processing manager found");return e}const Qe={AT_START:-1e4,NormalPass:0,DepthDownsamplingPass:10,SSAO:20,SMAA:30,TiltShift:40,DepthOfField:50,ChromaticAberration:60,Bloom:70,Vignette:80,Pixelation:90,ToneMapping:100,HueSaturation:110,BrightnessContrast:120,Sharpening:130,AT_END:1e4};let Be=null;function LO(s){yl==="verbose"&&console.debug("Before ordering effects",[...s]),Be||(Be=new Map,Be.set(exports.MODULES.POSTPROCESSING.MODULE.NormalPass,Qe.NormalPass),Be.set(exports.MODULES.POSTPROCESSING.MODULE.DepthDownsamplingPass,Qe.DepthDownsamplingPass),Be.set(exports.MODULES.POSTPROCESSING.MODULE.SMAAEffect,Qe.SMAA),Be.set(exports.MODULES.POSTPROCESSING.MODULE.SSAOEffect,Qe.SSAO),Be.set(exports.MODULES.POSTPROCESSING_AO.MODULE.N8AOPostPass,Qe.SSAO),Be.set(exports.MODULES.POSTPROCESSING_AO.MODULE.N8AOPass,Qe.SSAO),Be.set(exports.MODULES.POSTPROCESSING.MODULE.TiltShiftEffect,Qe.TiltShift),Be.set(exports.MODULES.POSTPROCESSING.MODULE.DepthOfFieldEffect,Qe.DepthOfField),Be.set(exports.MODULES.POSTPROCESSING.MODULE.ChromaticAberrationEffect,Qe.ChromaticAberration),Be.set(exports.MODULES.POSTPROCESSING.MODULE.BloomEffect,Qe.Bloom),Be.set(exports.MODULES.POSTPROCESSING.MODULE.SelectiveBloomEffect,Qe.Bloom),Be.set(exports.MODULES.POSTPROCESSING.MODULE.VignetteEffect,Qe.Vignette),Be.set(exports.MODULES.POSTPROCESSING.MODULE.PixelationEffect,Qe.Pixelation),Be.set(exports.MODULES.POSTPROCESSING.MODULE.ToneMappingEffect,Qe.ToneMapping),Be.set(exports.MODULES.POSTPROCESSING.MODULE.HueSaturationEffect,Qe.HueSaturation),Be.set(exports.MODULES.POSTPROCESSING.MODULE.BrightnessContrastEffect,Qe.BrightnessContrast)),s.sort((e,t)=>{const i=typeof e.priority=="number"?e.priority:Be.get(e.effect.constructor)??Number.NEGATIVE_INFINITY,n=typeof t.priority=="number"?t.priority:Be.get(t.effect.constructor)??Number.NEGATIVE_INFINITY;return i===Number.NEGATIVE_INFINITY?(yl&&console.warn("Unknown effect found: ",e.constructor.name,e),1):n===Number.NEGATIVE_INFINITY?(yl&&console.warn("Unknown effect found: ",t.constructor.name,t),-1):i-n}),yl==="verbose"&&console.debug("After ordering effects",[...s])}var DO=Object.defineProperty,IO=Object.getOwnPropertyDescriptor,tw=(s,e,t,i)=>{for(var n=IO(e,t),o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&DO(e,t,n),n};const jO=w("debugpost");class D{isVolumeParameter=!0;constructor(e){e!==void 0&&this.initialize(e)}_isInitialized=!1;get isInitialized(){return this._isInitialized}initialize(e){e!==void 0&&(this._value=e,this._defaultValue=e,this._valueRaw=e,this._isInitialized=!0)}get overrideState(){return this._active}set overrideState(e){if(this._active===e)return;this._active=e;const t=e?this._valueRaw:this._defaultValue;this.processValue(t,!0)}_active=!0;get value(){return this._valueRaw}set value(e){this.isInitialized||this.initialize(e),this.processValue(e,!1)}_value;_valueRaw;set defaultValue(e){this._defaultValue=e}_defaultValue=void 0;__init(){this.processValue(this._valueRaw,!0)}valueProcessor;onValueChanged;processValue(e,t){if(e==null||!t&&this.testIfValueChanged(e)===!1)return;const i=this._value;jO&&typeof i=="number"&&typeof e=="number"&&(i?.toFixed(4),e?.toFixed(4)),!this._active&&this._defaultValue!==void 0?(this._value=this._defaultValue,e=this._defaultValue,this._valueRaw=e):(this._valueRaw=e,this._active&&this.valueProcessor&&(e=this.valueProcessor(e)),this._value=e),this.onValueChanged&&this.onValueChanged(e,i,this)}testIfValueChanged(e){return this._valueRaw!==e}}tw([f()],D.prototype,"overrideState");tw([f()],D.prototype,"value");class BO extends Ui{constructor(){super([D])}onSerialize(e,t){}onDeserialize(e,t){const i=t.target,n=t.path;let o;if(i&&n&&(o=i[n]),(typeof o!="object"||typeof o=="object"&&o.isVolumeParameter!==!0)&&(o=new D),typeof e=="object"&&"value"in e){const r=e.value;o.initialize(r),o.overrideState=e.overrideState}else o.value=e;return o}}new BO;var FO=Object.defineProperty,UO=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&FO(e,t,n),n};const kf=w("debugpost");class Ne extends k{get isPostProcessingEffect(){return!0}order=void 0;constructor(e=void 0){if(super(),e)for(const t of Object.keys(e)){const i=e[t],n=this[t];n instanceof D?n.initialize(i):n!==void 0&&(this[t]=i)}}active=!0;_manager=null;onEnable(){super.onEnable(),kf&&console.warn("Enable",this.constructor.name+(this.__internalDidAwakeAndStart?"":" (awake)")),this.__internalDidAwakeAndStart&&(this.active=!0),this.onEffectEnabled()}onDisable(){super.onDisable(),kf&&console.warn("Disable",this.constructor.name),this._manager?.removeEffect(this),this.active=!1}onEffectEnabled(e){e&&e.isPostProcessingManager===!0?this._manager=e:this._manager||(this._manager=AO(this)),this._manager.addEffect(this),this._manager.dirty=!0}init(){}_result;_postprocessingContext=null;get postprocessingContext(){return this._postprocessingContext}apply(e){return this._postprocessingContext=e,this._result||(this.initParameters(),this._result=this.onCreateEffect?.call(this)),this._result&&this.initParameters(),this._result}unapply(){}dispose(){kf&&console.warn("DISPOSE",this),this._result&&(Array.isArray(this._result)?this._result.forEach(e=>e.dispose()):this._result.dispose()),this._result=void 0}initParameters(){const e=Object.keys(this);for(const t of e){const i=this[t];i instanceof D&&i.__init()}}onEditorModification(e){const t=e.propertyName;if(this[t]instanceof D){const i=e.value;return this[t].value=i,!0}}}UO([f()],Ne.prototype,"active");var zO=Object.defineProperty,NO=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&zO(e,t,n),n};const VO=w("debugpost"),Op={};function $i(s,e){Op[s]=e}function $O(s){return s.__type in Op?Op[s.__type]:(VO&&s.__type&&console.warn("Unknown postprocessing type",s.__type,s),Ne)}class du{components=[];__init(e){this.components?.forEach(t=>{t.gameObject===void 0&&e.gameObject.addComponent(t),t.init()})}addEffect(e){this.components.push(e)}removeEffect(e){const t=this.components.indexOf(e);t>=0&&this.components.splice(t,1)}}NO([er([s=>$O(s),Ne])],du.prototype,"components");var WO=Object.defineProperty,GO=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&WO(e,t,n),n};const HO=w("debugpost");class Lc extends Ne{get typeName(){return"Antialiasing"}preset=new D(2);onCreateEffect(){const e=new exports.MODULES.POSTPROCESSING.MODULE.SMAAEffect({preset:this.preset?.value??exports.MODULES.POSTPROCESSING.MODULE.SMAAPreset.HIGH,edgeDetectionMode:exports.MODULES.POSTPROCESSING.MODULE.EdgeDetectionMode.LUMA});return this.preset.onValueChanged=t=>{HO&&console.log("Antialiasing preset changed to",t),e.applyPreset(t)},e}}GO([f(D)],Lc.prototype,"preset");$i("Antialiasing",Lc);var qO=Object.defineProperty,Pg=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&qO(e,t,n),n};const uu=class iw extends Ne{static useSelectiveBloom=!1;get typeName(){return"Bloom"}threshold=new D(.9);intensity=new D(1);scatter=new D(.7);selectiveBloom;init(){this.threshold.valueProcessor=e=>e,this.intensity.valueProcessor=e=>e,this.scatter.valueProcessor=e=>e}onCreateEffect(){let e;if(this.selectiveBloom==null&&(this.selectiveBloom=iw.useSelectiveBloom),this.selectiveBloom){const t=e=new exports.MODULES.POSTPROCESSING.MODULE.SelectiveBloomEffect(this.context.scene,this.context.mainCamera,{blendFunction:exports.MODULES.POSTPROCESSING.MODULE.BlendFunction.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,radius:.85,intensity:this.intensity.value});t.inverted=!0}else e=new exports.MODULES.POSTPROCESSING.MODULE.BloomEffect({blendFunction:exports.MODULES.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=>{e.intensity=t},this.threshold.onValueChanged=t=>{e.luminanceMaterial.threshold=Math.pow(t,2.2)},this.scatter.onValueChanged=t=>{e.luminancePass.enabled=!0,e.luminanceMaterial.smoothing=t,e.mipmapBlurPass&&(e.mipmapBlurPass.radius=c.MathUtils.lerp(.1,.9,t))},e}};Pg([f(D)],uu.prototype,"threshold");Pg([f(D)],uu.prototype,"intensity");Pg([f(D)],uu.prototype,"scatter");let fu=uu;$i("Bloom",fu);var XO=Object.defineProperty,QO=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&XO(e,t,n),n};class Dc extends Ne{get typeName(){return"ChromaticAberration"}intensity=new D(0);onCreateEffect(){const e=new exports.MODULES.POSTPROCESSING.MODULE.ChromaticAberrationEffect;return e.offset=new c.Vector2(0,0),e.radialModulation=!0,e.modulationOffset=.15,this.intensity.valueProcessor=t=>t*.02,this.intensity.onValueChanged=t=>{e.offset.x=-t,e.offset.y=t},e}}QO([f(D)],Dc.prototype,"intensity");$i("ChromaticAberration",Dc);var _l=(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))(_l||{});const O_=new Map;function Rf(s){switch(s){case 0:return c.LinearToneMapping;case 1:return c.ReinhardToneMapping;case 2:return c.ACESFilmicToneMapping;case 3:return c.AgXToneMapping;case 4:return c.NeutralToneMapping;default:return O_.has(s)||(O_.set(s,!0),console.warn("[Postprocessing] Unknown tone mapping mode",s)),c.NeutralToneMapping}}function YO(s){switch(s){case c.LinearToneMapping:return 0;case c.ACESFilmicToneMapping:return 2;case c.AgXToneMapping:return 3;case c.NeutralToneMapping:return 1;case c.ReinhardToneMapping:return 1;default:return 0}}function Gh(s){switch(s){case c.LinearToneMapping:return exports.MODULES.POSTPROCESSING.MODULE.ToneMappingMode.LINEAR;case c.ACESFilmicToneMapping:return exports.MODULES.POSTPROCESSING.MODULE.ToneMappingMode.ACES_FILMIC;case c.AgXToneMapping:return exports.MODULES.POSTPROCESSING.MODULE.ToneMappingMode.AGX;case c.NeutralToneMapping:return exports.MODULES.POSTPROCESSING.MODULE.ToneMappingMode.NEUTRAL;case c.ReinhardToneMapping:return exports.MODULES.POSTPROCESSING.MODULE.ToneMappingMode.REINHARD;default:return exports.MODULES.POSTPROCESSING.MODULE.ToneMappingMode.LINEAR}}var KO=Object.defineProperty,nw=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&KO(e,t,n),n};const Ef=w("debugpost");class Ys extends Ne{get typeName(){return"ToneMapping"}mode=new D(void 0);exposure=new D(1);setMode(e){const t=_l[e];return t===void 0?(console.error("[PostProcessing] Invalid ToneMapping mode",e),this):(this.mode.value=t,this)}get isToneMapping(){return!0}onEffectEnabled(){const e=ew(this);e&&super.onEffectEnabled(e)}_tonemappingEffect=null;onCreateEffect(){if(this.mode.isInitialized==!1){const i=YO(this.context.renderer.toneMapping);Ef&&console.log("[PostProcessing] Initializing ToneMapping mode to renderer.toneMapping",this.context.renderer.toneMapping+" → "+i),this.mode.initialize(i)}this._tonemappingEffect?.dispose();const e=Rf(this.mode.value),t=this._tonemappingEffect=new exports.MODULES.POSTPROCESSING.MODULE.ToneMappingEffect({mode:Gh(e)});return this.mode.onValueChanged=i=>{if(typeof i=="string")i=L0(i),t.mode=Gh(i);else{const n=Rf(i);t.mode=Gh(n)}t.name="ToneMapping ("+_l[i]+")",Ef&&console.log("[PostProcessing] ToneMapping mode changed to",_l[i],e,t.mode)},Ef&&console.log("[PostProcessing] Use ToneMapping",_l[this.mode.value],e,t.mode,"renderer.tonemapping: "+this.context.renderer.toneMapping),t}onBeforeRender(){if(this._tonemappingEffect&&this.postprocessingContext?.handler.getEffectIsActive(this._tonemappingEffect)&&(this.mode.overrideState&&(this.context.renderer.toneMapping=Rf(this.mode.value)),this.exposure.overrideState&&this.exposure.value!==void 0)){const e=Math.max(0,this.exposure.value);this.context.renderer.toneMappingExposure=e}}}nw([f(D)],Ys.prototype,"mode");nw([f(D)],Ys.prototype,"exposure");$i("Tonemapping",Ys);var ZO=Object.defineProperty,pu=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&ZO(e,t,n),n};class co extends Ne{get typeName(){return"ColorAdjustments"}remap=!0;postExposure=new D(1);contrast=new D(0);hueShift=new D(0);saturation=new D(0);init(){this.postExposure.valueProcessor=e=>(this.remap&&(e=Math.pow(2,e)),e),this.contrast.valueProcessor=e=>{if(!this.remap)return e;let t=1;return e>0?t=200:e<0&&(t=100),e/t},this.contrast.defaultValue=0,this.hueShift.valueProcessor=e=>this.remap?Math.PI*e/180:e,this.hueShift.defaultValue=0,this.saturation.valueProcessor=e=>this.remap?e<0?e/100:e/(100*Math.PI):e,this.saturation.defaultValue=0}onCreateEffect(){const e=[];let t=this.postprocessingContext?.components.find(o=>o instanceof Ys);t||(t=new Ys,this.postprocessingContext?.components.push(t)),this.postExposure.onValueChanged=o=>{this.postExposure.overrideState&&t?t.exposure.value=o:console.warn("[PostProcessing] PostExposure is set to override but no ToneMappingEffect found in the postprocessing stack. Please add a ToneMappingEffect to your postprocessing stack to use PostExposure.")};const i=new exports.MODULES.POSTPROCESSING.MODULE.BrightnessContrastEffect;this.contrast.onValueChanged=o=>i.contrast=o;const n=new exports.MODULES.POSTPROCESSING.MODULE.HueSaturationEffect;return this.hueShift.onValueChanged=o=>n.hue=o,this.saturation.onValueChanged=o=>n.saturation=o,e.push(i),e.push(n),e}}pu([f(D)],co.prototype,"postExposure");pu([f(D)],co.prototype,"contrast");pu([f(D)],co.prototype,"hueShift");pu([f(D)],co.prototype,"saturation");$i("ColorAdjustments",co);var JO=Object.defineProperty,gr=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&JO(e,t,n),n};const ek=w("debugpost");class an extends Ne{get typeName(){return"DepthOfField"}mode;focusDistance=new D(1);focalLength=new D(.2);aperture=new D(20);gaussianMaxRadius=new D;resolutionScale=new D(1/window.devicePixelRatio);bokehScale=new D;init(){this.focalLength.valueProcessor=t=>{const i=t/300;return I.lerp(2,.01,i)};const e=20;this.aperture.valueProcessor=t=>{const i=1-t/32;return I.lerp(1,e,i)}}onCreateEffect(){if(this.mode===0){ek&&console.warn("DepthOfField: Mode is set to Off");return}const e=new exports.MODULES.POSTPROCESSING.MODULE.DepthOfFieldEffect(this.context.mainCamera,{worldFocusRange:.2,focalLength:1,bokehScale:20,resolutionScale:this.resolutionScale.value});return this.focusDistance.onValueChanged=t=>{e.cocMaterial.worldFocusDistance=t},this.focalLength.onValueChanged=t=>e.cocMaterial.worldFocusRange=t,this.aperture.onValueChanged=t=>e.bokehScale=t,this.resolutionScale&&(this.resolutionScale.onValueChanged=t=>e.resolution.scale=t),[e]}unapply(){}}gr([f()],an.prototype,"mode");gr([f(D)],an.prototype,"focusDistance");gr([f(D)],an.prototype,"focalLength");gr([f(D)],an.prototype,"aperture");gr([f(D)],an.prototype,"gaussianMaxRadius");gr([f(D)],an.prototype,"resolutionScale");gr([f(D)],an.prototype,"bokehScale");$i("DepthOfField",an);class Xl extends Ne{effect;constructor(e){super(),this.effect=e}get typeName(){return this.effect.constructor.name}onCreateEffect(){return this.effect}}var tk=Object.defineProperty,ik=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&tk(e,t,n),n};class Ic extends Ne{get typeName(){return"PixelationEffect"}granularity=new D(10);onCreateEffect(){const e=new exports.MODULES.POSTPROCESSING.MODULE.PixelationEffect;return this.granularity.onValueChanged=t=>{e.granularity=t},e}}ik([f(D)],Ic.prototype,"granularity");$i("PixelationEffect",Ic);var nk=Object.defineProperty,jc=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&nk(e,t,n),n};class _s extends Ne{get typeName(){return"ScreenSpaceAmbientOcclusion"}intensity=new D(2);falloff=new D(1);samples=new D(9);color=new D(new c.Color(0,0,0));luminanceInfluence=new D(.7);onBeforeRender(){if(this._ssao&&this.context.mainCamera instanceof c.PerspectiveCamera){const e=this.context.mainCamera.far-this.context.mainCamera.near;this._ssao.ssaoMaterial.worldDistanceFalloff=e*.01,this._ssao.ssaoMaterial.worldDistanceThreshold=this.context.mainCamera.far}}_ssao;onCreateEffect(){const e=this.context.mainCamera,t=new exports.MODULES.POSTPROCESSING.MODULE.NormalPass(this.context.scene,e),i=new exports.MODULES.POSTPROCESSING.MODULE.DepthDownsamplingPass({normalBuffer:t.texture,resolutionScale:.5}),n=this._ssao=new exports.MODULES.POSTPROCESSING.MODULE.SSAOEffect(e,t.texture,{normalDepthBuffer:i.texture,worldDistanceThreshold:1,worldDistanceFalloff:1,worldProximityThreshold:.1,worldProximityFalloff:2,intensity:1,blendFunction:exports.MODULES.POSTPROCESSING.MODULE.BlendFunction.MULTIPLY,luminanceInfluence:.5});this.intensity.onValueChanged=r=>{n.intensity=r},this.falloff.onValueChanged=r=>{n.ssaoMaterial.radius=r*.1},this.samples.onValueChanged=r=>{n.ssaoMaterial.samples=r},this.color.onValueChanged=r=>{n.color||(n.color=new c.Color),n.color.copy(r)},this.luminanceInfluence.onValueChanged=r=>{n.luminanceInfluence=r};const o=new Array;return o.push(t),o.push(i),o.push(n),o}}jc([f(D)],_s.prototype,"intensity");jc([f(D)],_s.prototype,"falloff");jc([f(D)],_s.prototype,"samples");jc([f(D)],_s.prototype,"color");jc([f(D)],_s.prototype,"luminanceInfluence");$i("ScreenSpaceAmbientOcclusion",_s);var sk=Object.defineProperty,yr=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&sk(e,t,n),n};const ok=w("debugN8AO");var kp=(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))(kp||{});class ln extends Ne{get typeName(){return"ScreenSpaceAmbientOcclusionN8"}get pass(){return this._ssao}gammaCorrection=!0;aoRadius=new D(1);falloff=new D(1);intensity=new D(1);color=new D(new c.Color(0,0,0));screenspaceRadius=!1;quality=2;_ssao;onValidate(){this._ssao&&(this._ssao.setQualityMode(kp[this.quality]),this._ssao.configuration.gammaCorrection=this.gammaCorrection,this._ssao.configuration.screenSpaceRadius=this.screenspaceRadius)}onCreateEffect(){const e=this.context.mainCamera,t=this.context.domWidth,i=this.context.domHeight,n=this._ssao=new exports.MODULES.POSTPROCESSING_AO.MODULE.N8AOPostPass(this.context.scene,e,t,i);n.name="SSAO_N8";const o=kp[this.quality];n.setQualityMode(o),n.configuration.transparencyAware=!1;const r=new c.WebGLRenderTarget(t,i);return n.configuration.beautyRenderTarget=r,n.configuration.autoRenderBeauty=!1,n.configuration.gammaCorrection=this.gammaCorrection,n.configuration.screenSpaceRadius=this.screenspaceRadius,ok&&(n.enableDebugMode(),console.log(n),setInterval(()=>{console.log("SSAO",n.lastTime)},1e3),setInterval(()=>{console.log("SSAO",n.enabled,{ssao:n,autoRenderBeauty:n.configuration.autoRenderBeauty})},4e3)),this.intensity.onValueChanged=a=>{n.configuration.intensity=a},this.falloff.onValueChanged=a=>{n.configuration.distanceFalloff=a},this.aoRadius.onValueChanged=a=>{n.configuration.aoRadius=a},this.color.onValueChanged=a=>{n.color||(n.color=new c.Color),n.configuration.color.copy(a)},n}}yr([gt(),f()],ln.prototype,"gammaCorrection");yr([f(D)],ln.prototype,"aoRadius");yr([f(D)],ln.prototype,"falloff");yr([f(D)],ln.prototype,"intensity");yr([f(D)],ln.prototype,"color");yr([gt(),f()],ln.prototype,"screenspaceRadius");yr([gt(),f()],ln.prototype,"quality");$i("ScreenSpaceAmbientOcclusionN8",ln);var rk=Object.defineProperty,ak=Object.getOwnPropertyDescriptor,sw=(s,e,t,i)=>{for(var n=ak(e,t),o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&rk(e,t,n),n};class Bc extends Ne{get typeName(){return"Sharpening"}order=Qe.Sharpening;_effect;onCreateEffect(){return this._effect??=new(lk()),this.effect}get effect(){return this._effect}set amount(e){this._amount=e,this._effect&&(this._effect.uniforms.get("amount").value=e)}get amount(){return this._effect?this._effect.uniforms.get("amount").value:this._amount}_amount=1;set radius(e){this._radius=e,this._effect&&(this._effect.uniforms.get("radius").value=e)}get radius(){return this._effect?this._effect.uniforms.get("radius").value:this._radius}_radius=1}sw([f()],Bc.prototype,"amount");sw([f()],Bc.prototype,"radius");function lk(){const s=`
1275
1285
  void mainSupport() {
1276
1286
  vUv = uv;
1277
1287
  gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
@@ -1477,7 +1487,7 @@ Please refer to the documentation on <a href="https://fwd.needle.tools/needle-en
1477
1487
  align-items: center;
1478
1488
  `,n.appendChild(o);var r=document.createElementNS("http://www.w3.org/2000/svg","path");r.setAttribute("d","M 12,12 L 28,28 M 28,12 12,28"),r.setAttribute("stroke","#000000"),r.setAttribute("stroke-width","2px"),r.style.cssText=`
1479
1489
  /**filter: drop-shadow(0 0px 1.2px rgba(0,0,0,.7));**/
1480
- `,o.appendChild(r),Ya&&console.log("Created fallback close button",o,e)}appendElement(e,t){return t.shadowRoot?t.shadowRoot.appendChild(e):t.appendChild(e)}}const Po=w("debugloading"),Ka=w("debugloadingrendering"),B_=w("debuglicense");class BR{className;additionalClasses}let Za=0,F_;function Ng(s){Po&&console.log(s.progress.loaded.toFixed(0)+"/"+s.progress.total.toFixed(0),s);const e=s.count,t=s.progress.total;t===0||t===void 0?(F_!==s.name&&(Za=0),F_=s.name,Za+=(1-Za)*.001,Po&&ce("Loading "+s.name+" did not report total size")):Za=s.progress.loaded/t;const i=s.index/e+Za/e;return I.clamp01(i)}class Kl{static LoadingContainerClassName="loading";loadingProgress=0;_element;_progress=0;_allowCustomLoadingElement=!0;_loadingElement;_loadingTextContainer=null;_loadingBar=null;_messageContainer=null;_loadingElementOptions;constructor(e,t){this._element=e,this._loadingElementOptions=t}async onLoadingBegin(e){const t=this._element.shadowRoot||this._element;if(Po&&console.warn("Begin Loading"),!this._loadingElement){for(let i=0;i<t.children.length;i++){const n=t.children[i];if(n.classList.contains(Kl.LoadingContainerClassName)){if(!this._allowCustomLoadingElement){Po&&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(e??"")}onLoadingUpdate(e,t){if(!this._loadingElement?.parentNode)return;let i=0;typeof e=="number"?i=e:("index"in e&&(i=Ng(e)),!t&&"name"in e&&this.setMessage("loading "+e.name)),this.loadingProgress=i,t&&this.setMessage(t),this.updateDisplay()}onLoadingFinished(){Po&&console.warn("Finished Loading"),Ka||(this.loadingProgress=1,this.onDoneLoading())}setMessage(e){this._messageContainer&&(this._messageContainer.innerText=e)}_progressLoop;smoothProgressLoop(){if(this._progressLoop)return;let e=1/12;Ka&&(e=1/500,typeof Ka=="number"&&(e*=Ka)),this._progressLoop=setInterval(()=>{this.loadingProgress>=.95&&!Ka&&(e=.9),this._progress=I.lerp(this._progress,this.loadingProgress,e*this.loadingProgress),this.updateDisplay()},e)}onDoneLoading(){this._loadingElement&&(Po&&console.log("Hiding loading element"),this._loadingElement.style.display="none",this._loadingElement.remove()),this._progressLoop&&clearInterval(this._progressLoop),this._progressLoop=null}updateDisplay(){const e=this._progress,t=(e*100).toFixed(0)+"%";this._loadingBar&&(this._loadingBar.style.width=e*100+"%"),this._loadingTextContainer&&(this._loadingTextContainer.textContent=t)}createLoadingElement(e){Po&&!e&&console.log("Creating loading element"),this._loadingElement=e||document.createElement("div");let t=this._element.getAttribute("loading-style");(!t||t==="auto")&&(window.matchMedia("(prefers-color-scheme: dark)").matches?t="dark":t="light");const i=kn();if(!e){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";const p=this._element.getAttribute("loading-background");p?this._loadingElement.style.background=p:this._loadingElement.style.backgroundColor="transparent",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",t==="light"?this._loadingElement.style.color="rgba(0,0,0,.6)":this._loadingElement.style.color="rgba(255,255,255,.3)"}const n=this._loadingElementOptions?.className??Kl.LoadingContainerClassName;if(this._loadingElement.classList.add(n),this._loadingElementOptions?.additionalClasses)for(const p of this._loadingElementOptions.additionalClasses)this._loadingElement.classList.add(p);const o=document.createElement("div");this._loadingElement.appendChild(o);const r=document.createElement("img"),a=120;if(r.style.width=`${a}px`,r.style.height=`${a}px`,r.style.paddingTop="20px",r.style.paddingBottom="10px",r.style.margin="0px",r.style.userSelect="none",r.style.objectFit="contain",r.style.transition="transform 1.5s ease-out, opacity .3s ease-in-out",r.style.transform="translateY(30px)",r.style.opacity="0.05",setTimeout(()=>{r.style.opacity="1",r.style.transform="translateY(0px)"},1),r.src=G_,i&&this._element){const p=this._element.getAttribute("loading-logo-src");p&&(r.src=p)}o.appendChild(r);const l=document.createElement("div");l.style.cssText=`
1490
+ `,o.appendChild(r),Ya&&console.log("Created fallback close button",o,e)}appendElement(e,t){return t.shadowRoot?t.shadowRoot.appendChild(e):t.appendChild(e)}}const Po=w("debugloading"),Ka=w("debugloadingrendering"),B_=w("debuglicense");class BR{className;additionalClasses}let Za=0,F_;function Ng(s){Po&&console.log(s.progress.loaded.toFixed(0)+"/"+s.progress.total.toFixed(0),s);const e=s.count,t=s.progress.total;t===0||t===void 0?(F_!==s.name&&(Za=0),F_=s.name,Za+=(1-Za)*.001,Po&&ce("Loading "+s.name+" did not report total size")):Za=s.progress.loaded/t;const i=s.index/e+Za/e;return I.clamp01(i)}class Kl{static LoadingContainerClassName="loading";loadingProgress=0;_element;_progress=0;_allowCustomLoadingElement=!0;_loadingElement;_loadingTextContainer=null;_loadingBar=null;_messageContainer=null;_loadingElementOptions;constructor(e,t){this._element=e,this._loadingElementOptions=t}async onLoadingBegin(e){const t=this._element.shadowRoot||this._element;if(Po&&console.warn("Begin Loading"),!this._loadingElement){for(let i=0;i<t.children.length;i++){const n=t.children[i];if(n.classList.contains(Kl.LoadingContainerClassName)){if(!this._allowCustomLoadingElement){Po&&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(e??"")}onLoadingUpdate(e,t){if(!this._loadingElement?.parentNode)return;let i=0;typeof e=="number"?i=e:("index"in e&&(i=Ng(e)),!t&&"name"in e&&this.setMessage("loading "+e.name)),this.loadingProgress=i,t&&this.setMessage(t),this.updateDisplay()}onLoadingFinished(){Po&&console.warn("Finished Loading"),Ka||(this.loadingProgress=1,this.onDoneLoading())}setMessage(e){this._messageContainer&&(this._messageContainer.innerText=e)}_progressLoop;smoothProgressLoop(){if(this._progressLoop)return;let e=1/12;Ka&&(e=1/500,typeof Ka=="number"&&(e*=Ka)),this._progressLoop=setInterval(()=>{this.loadingProgress>=.95&&!Ka&&(e=.9),this._progress=I.lerp(this._progress,this.loadingProgress,e*this.loadingProgress),this.updateDisplay()},e)}onDoneLoading(){this._loadingElement&&(Po&&console.log("Hiding loading element"),this._loadingElement.style.display="none",this._loadingElement.remove()),this._progressLoop&&clearInterval(this._progressLoop),this._progressLoop=null}updateDisplay(){const e=this._progress,t=(e*100).toFixed(0)+"%";this._loadingBar&&(this._loadingBar.style.width=e*100+"%"),this._loadingTextContainer&&(this._loadingTextContainer.textContent=t)}createLoadingElement(e){Po&&!e&&console.log("Creating loading element"),this._loadingElement=e||document.createElement("div");let t=this._element.getAttribute("loading-style");(!t||t==="auto")&&(window.matchMedia("(prefers-color-scheme: dark)").matches?t="dark":t="light");const i=kn();if(!e){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";const p=this._element.getAttribute("loading-background");p?this._loadingElement.style.background=p:this._loadingElement.style.backgroundColor="transparent",this._loadingElement.style.display="flex",this._loadingElement.style.alignItems="center",this._loadingElement.style.justifyContent="center",this._loadingElement.style.zIndex="0",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",t==="light"?this._loadingElement.style.color="rgba(0,0,0,.6)":this._loadingElement.style.color="rgba(255,255,255,.3)"}const n=this._loadingElementOptions?.className??Kl.LoadingContainerClassName;if(this._loadingElement.classList.add(n),this._loadingElementOptions?.additionalClasses)for(const p of this._loadingElementOptions.additionalClasses)this._loadingElement.classList.add(p);const o=document.createElement("div");this._loadingElement.appendChild(o);const r=document.createElement("img"),a=120;if(r.style.width=`${a}px`,r.style.height=`${a}px`,r.style.paddingTop="20px",r.style.paddingBottom="10px",r.style.margin="0px",r.style.userSelect="none",r.style.objectFit="contain",r.style.transition="transform 1.5s ease-out, opacity .3s ease-in-out",r.style.transform="translateY(30px)",r.style.opacity="0.05",setTimeout(()=>{r.style.opacity="1",r.style.transform="translateY(0px)"},1),r.src=G_,i&&this._element){const p=this._element.getAttribute("loading-logo-src");p&&(r.src=p)}o.appendChild(r);const l=document.createElement("div");l.style.cssText=`
1481
1491
  display: flex;
1482
1492
  flex-direction: column;
1483
1493
  align-items: center;
@@ -1604,4 +1614,4 @@ Error:`,r),null}}updateColliderCollisionGroups(e){const t=e[Et],i=e.membership;l
1604
1614
  justify-content: center;
1605
1615
  gap: .5rem;
1606
1616
  }
1607
- `),this.#n.innerHTML=this.#e.innerHTML,this.#n.style.cssText="display: flex; align-items: center; justify-content: center;",this.#e.innerHTML=this.#n.outerHTML,this.#t.innerHTML=this.#e.outerHTML,this.#t.prepend(this.#s),ld(lp,{element:this.#t}),this.#o?.disconnect(),this.#o??=new MutationObserver(()=>this.#l()),this.#o.observe(this.#e,{attributes:!0}),Bf&&console.log("Needle Button updated")}#l(){this.#e&&(this.#e.style.display==="none"?this.style.display="none":this.style.display==="none"&&(this.style.display=""))}#r=e=>{Bf&&console.log("Needle Button clicked"),!e.defaultPrevented&&this.#e&&this.#e.click()}}typeof window<"u"&&!window.customElements.get($_)&&window.customElements.define($_,Rw);const tl=w("debugavatar");class $g{root;head;leftHand;rigthHand;get isValid(){return this.head!==null&&this.head!==void 0}constructor(e,t,i,n){this.root=e,this.head=t,this.leftHand=i,this.rigthHand=n,this.root?.traverse(o=>o.layers.set(2))}}class Ew{avatarRegistryUrl=null;async getOrCreateNewAvatarInstance(e,t){if(!t)return console.error("Can not create avatar: failed to provide id or root object"),null;let i=null;if(typeof t=="string"){if(i=await this.loadAvatar(e,t),!i){const o=new sn;i=x.instantiate(Zr(t,e.scene),o)}}else i=t;if(!i)return null;const n=this.findAvatar(i);return n.isValid?(tl&&console.log("[Custom Avatar] valid config",t,tl?n:""),n):(console.warn("[Custom Avatar] config isn't valid",t,tl?n:""),null)}async loadAvatar(e,t){if(console.assert(t!=null&&typeof t=="string","Avatar id must not be null"),t.length<=0||!t)return null;if(tl&&console.log("[Custom Avatar] "+t+", loading..."),t.endsWith(".glb")||(t+=".glb"),this.avatarRegistryUrl===null){const n=await fetch("./"+t);let o=null;if(n.ok){const a=await n.blob();a&&(o=await a.arrayBuffer())}return o?(await en().parseSync(e,o,null,0))?.scene??null:null}const i=new G.GLTFLoader;return _m(i,e),new Promise((n,o)=>{const r=this.avatarRegistryUrl+"/"+t;i.load(r,async a=>{await en().createBuiltinComponents(e,r,a,null,void 0),n(a.scene)},a=>{tl&&console.log("[Custom Avatar] "+a.loaded/a.total*100+"% loaded of "+a.total/1024+"kB")},a=>{console.error("[Custom Avatar] Error when loading: "+a),n(null)})})}cacheModel(e,t){}findAvatar(e){const t=e;let i=t;i.children.length==1&&(i=e.children[0]);let n=this.findAvatarPart(i,["head"]);const o=this.findAvatarPart(i,["left","hand"]),r=this.findAvatarPart(i,["right","hand"]);if(!n){n=t;const l=new c.Vector3;new c.Box3().setFromObject(n).getSize(l);const h=Math.max(l.x,l.y,l.z);console.warn("[Custom Avatar] Normalizing head scale, it's too big: "+h+" meters! Should be < 0.3m"),h>.3&&n.scale.multiplyScalar(1/h*.3)}return new $g(t,n,o,r)}findAvatarPart(e,t){const i=e.name.toLowerCase();let n=!0;for(const o of t){if(!n)break;i.indexOf(o)===-1&&(n=!1)}if(n)return e;if(e.children)for(const o of e.children){const r=this.findAvatarPart(o,t);if(r)return r}return null}handleCustomAvatarErrors(e){if(!e.ok)throw Error(e.statusText);return e}}class Tw{get extensionName(){return"DocumentExtension"}onAfterBuildDocument(e){}}class Aw{}const ZR=Object.freeze(Object.defineProperty({__proto__:null,ActionBuilder:ae,ActionCollection:Uv,ActionModel:Vt,AlignmentConstraint:uc,Animation:wt,AnimationCurve:Tc,AnimationExtension:Jd,AnimationTrackHandler:xu,Animator:mt,AnimatorController:Li,Antialiasing:Lc,AudioExtension:ar,AudioListener:is,AudioSource:Ii,AudioTrackHandler:ss,Avatar:Xs,AvatarBlink_Simple:nr,AvatarEyeLook_Rotation:Om,AvatarLoader:Ew,AvatarMarker:xe,AvatarModel:$g,Avatar_Brain_LookAt:$l,Avatar_MouthShapes:gc,Avatar_MustacheShake:Pm,Avatar_POI:Fo,AxesHelper:ma,BaseUIComponent:Bi,BasicIKConstraint:Rm,BehaviorExtension:sg,BehaviorModel:pt,BloomEffect:fu,BoxCollider:Xd,BoxGizmo:dr,BoxHelperComponent:nt,Button:bs,CallInfo:ts,Camera:Wt,CameraTargetReachedEvent:Vl,Canvas:ca,CanvasGroup:Qs,CapsuleCollider:as,ChangeMaterialOnClick:Qm,ChangeTransformOnClick:lr,CharacterController:sr,CharacterControllerInput:ds,ChromaticAberration:Dc,Collider:Qt,ColorAdjustments:co,ColorBySpeedModule:Oa,ColorOverLifetimeModule:hu,ContactShadows:yc,ControlTrackHandler:Su,CustomBranding:hr,Deletable:Lm,DeleteBox:$s,DepthOfField:an,DeviceFlag:Qd,DocumentExtension:Tw,DragControls:Mo,DropListener:us,Duplicatable:jm,EffectWrapper:Xl,EmissionModule:ys,EmphasizeOnClick:ba,EnvironmentScene:ku,EventList:de,EventListEvent:$d,EventSystem:jt,EventTrigger:Kd,FieldWithDefault:Cv,FixedJoint:_g,Fog:Ca,GltfExport:Gm,GltfExportBox:$m,Gradient:fr,Graphic:Mc,GraphicRaycaster:Wd,GridHelper:Pa,GridLayoutGroup:hg,GroundProjectedEnv:Dn,GroupActionModel:Oo,HideOnStart:Ri,HingeJoint:kc,HorizontalLayoutGroup:cg,Image:Ea,InheritVelocityModule:xg,InputField:Ig,InstanceHandle:Uo,InstancingHandler:qo,Interactable:Am,Keyframe:Gt,LODGroup:Ec,LODModel:Ma,Light:yi,LimitVelocityOverLifetimeModule:et,LogStats:Tm,LookAt:jg,LookAtConstraint:ir,MainModule:Pt,MaskableGraphic:Oc,MeshCollider:io,MeshRenderer:bc,MinMaxCurve:H,MinMaxGradient:pr,NeedleMenu:jn,NestedGltf:au,Networking:vg,NoiseModule:fe,ObjectRaycaster:ui,OffsetConstraint:ur,OpenURL:Ta,OrbitControls:he,Outline:Sa,Padding:cr,ParticleBurst:wd,ParticleSubEmitter:Sg,ParticleSystem:ql,ParticleSystemRenderer:Vi,PhysicsExtension:og,PixelationEffect:Ic,PlayAnimationOnClick:Gl,PlayAudioOnClick:qs,PlayableDirector:da,PlayerColor:ha,PointerEventData:pc,PostProcessingHandler:Og,PreliminaryAction:va,PreliminaryTrigger:xc,RawImage:Mu,Rect:Wv,RectTransform:nn,ReflectionProbe:Wl,RegisteredAnimationInfo:zs,RemoteSkybox:mu,Renderer:fi,RendererLightmap:yd,Rigidbody:Ke,RotationBySpeedModule:Ni,RotationOverLifetimeModule:rn,SceneSwitcher:Ie,ScreenCapture:ho,ScreenSpaceAmbientOcclusion:_s,ScreenSpaceAmbientOcclusionN8:ln,SetActiveOnClick:Ym,ShadowCatcher:Uc,ShapeModule:wg,SharpeningEffect:Bc,SignalAsset:wu,SignalReceiver:Wc,SignalReceiverEvent:$c,SignalTrackHandler:Ql,Size:$v,SizeBySpeedModule:Zt,SizeOverLifetimeModule:mr,SkinnedMeshRenderer:Vm,SmoothFollow:yu,SpatialGrabRaycaster:Go,SpatialHtml:qc,SpatialTrigger:_u,SpatialTriggerReceiver:Tn,SpectatorCamera:bu,SphereCollider:ga,Sprite:ps,SpriteData:Yr,SpriteRenderer:Yt,SpriteSheet:la,SubEmitterSystem:xd,SyncedCamera:Rg,SyncedRoom:cn,SyncedTransform:Ln,TapGestureTrigger:Zm,TeleportTarget:su,TestRunner:Eg,TestSimulateUserData:Tg,Text:Ct,TextBuilder:ag,TextExtension:ru,TextureSheetAnimationModule:Mt,TiltShiftEffect:Un,ToneMappingEffect:Ys,TrailModule:Re,TransformData:Oe,TransformGizmo:br,TriggerBuilder:xt,TriggerModel:Ws,UIRaycastUtils:wm,UIRootComponent:Cc,USDZExporter:En,USDZText:Vr,USDZUIExtension:ug,UsageMarker:_c,VariantAction:Xm,VelocityOverLifetimeModule:Le,VerticalLayoutGroup:lg,VideoPlayer:Ze,Vignette:_r,VisibilityAction:Sc,Voip:to,Volume:Ra,VolumeParameter:D,VolumeProfile:du,WebARCameraBackground:Qc,WebARSessionRoot:li,WebXR:ou,WebXRImageTracking:Yl,WebXRImageTrackingModel:ws,WebXRPlaneTracking:xs,WebXRTrackedImage:ua,XRControllerFollow:vs,XRControllerModel:ls,XRControllerMovement:pi,XRFlag:Ei,XRRig:Eu,XRState:It,__Ignore:Aw},Symbol.toStringTag,{value:"Module"})),Pd=w("debugmissingcamera");re.registerCallback(oe.MissingCamera,s=>{Pd&&console.warn("Creating missing camera");const e=s.context.scene,t=new c.PerspectiveCamera;t.name="Default Fallback Camera",e.add(t);const i=new Wt;if(i.sourceId=s.files?.[0]?.src??"unknown",i.fieldOfView=35,s.context.domElement.getAttribute("transparent")!=null)i.clearFlags=Bo.Uninitialized;else if(s.context.domElement.getAttribute("background-image")?.length||s.context.lightmaps.tryGetSkybox(i.sourceId))i.clearFlags=Bo.Skybox,s.context.domElement.getAttribute("background-blurriness")===null&&(s.context.scene.backgroundBlurriness=.2);else{if(i.clearFlags=Bo.SolidColor,!s.context.domElement.getAttribute("background-color")){let a="#efefef";typeof window!==void 0&&window.matchMedia("(prefers-color-scheme: dark)").matches&&(a="#1f1f1f"),e.background=new c.Color(a)}if(!e.environment){const a=new c.PMREMGenerator$1(s.context.renderer),l=new ku("neutral");e.environment=a.fromScene(l,.025).texture}}const o=Ao(t,i,!0);return t.position.x=0,t.position.y=1,t.position.z=2,s.context.domElement?.cameraControls!=!1&&Lw(s.context,o),o});re.registerCallback(oe.ContextCreated,s=>{if(!s.context.mainCamera){Pd&&console.log("Will not auto-fit because a default camera exists");return}if(s.context.domElement?.cameraControls==!0){if(rb(s.context.mainCamera)?.isCameraController==!0){Pd&&console.log("Will not auto-fit because a camera controller exists");return}Lw(s.context)}});function Lw(s,e){e=e??s.mainCameraComponent;const t=e?.gameObject;if(Pd&&console.log("Creating default camera controls",e?.name),t){const i=rc(t,he);i.sourceId=e?.sourceId??"unknown";const n=s.domElement.getAttribute("auto-rotate");if(i.autoRotate=n!=null&&n!="0"&&n?.toLowerCase()!="false",i.autoRotateSpeed=.5,i.autoFit=!0,i.autoRotate&&n){const o=parseFloat(n);isNaN(o)||(i.autoRotateSpeed=o)}}else console.warn("Missing camera object, can not add orbit controls")}re.registerCallback(oe.ContextCreated,s=>{const e=s.context.domElement.getAttribute("autoplay");if(e!==void 0&&(e===""||e==="true"||e==="1")&&s.files)for(const t of s.files)x.foreachComponent(t.file.scene,n=>{if(n.enabled!==!1){if(n instanceof wt&&n.playAutomatically||n instanceof mt||n instanceof da&&n.playOnAwake===!0)return!0;if(n instanceof wt)return n.playAutomatically=!0,!0;if(n instanceof da)return n.playOnAwake=!0,!0}},!0)!==!0&&oa.assignAnimationsFromFile(t.file,{createAnimationComponent:(n,o)=>ci(n,wt)})});class JR extends se.WorkerBase{constructor(){super(new Worker(new URL("/generateMeshBVH.worker-2qGLkQjg.js",typeof document>"u"?require("url").pathToFileURL(__filename).href:Au&&Au.tagName.toUpperCase()==="SCRIPT"&&Au.src||new URL("needle-engine.bundle-CcYGQALb.umd.cjs",document.baseURI).href),{type:"module"})),this.name="GenerateMeshBVHWorker"}runTask(e,t,i={}){return new Promise((n,o)=>{if(t.getAttribute("position").isInterleavedBufferAttribute||t.index&&t.index.isInterleavedBufferAttribute)throw new Error("GenerateMeshBVHWorker: InterleavedBufferAttribute are not supported for the geometry attributes.");e.onerror=h=>{o(new Error(`[GenerateMeshBVHWorker] ${h.message||"Unknown error. Please check the server console. If you're using vite try adding 'three-mesh-bvh' to 'optimizeDeps.exclude' in your vite.config.js"}`))},e.onmessage=h=>{const{data:d}=h;if(d.error)o(new Error(d.error)),e.onmessage=null;else if(d.serialized){const{serialized:u,position:p}=d,m=se.MeshBVH.deserialize(u,t,{setIndex:!1}),y=Object.assign({setBoundingBox:!0},i);if(t.attributes.position.array=p,u.index)if(t.index)t.index.array=u.index;else{const b=new c.BufferAttribute(u.index,1,!1);t.setIndex(b)}y.setBoundingBox&&(t.boundingBox=m.getBoundingBox(new c.Box3)),i.onProgress&&i.onProgress(d.progress),n(m),e.onmessage=null}else i.onProgress&&i.onProgress(d.progress)};const r=t.index?t.index.array:null,a=t.attributes.position.array,l=[a];r&&l.push(r),e.postMessage({index:r,position:a,options:{...i,onProgress:null,includedProgressCallback:!!i.onProgress,groups:[...t.groups]}},l.map(h=>h.buffer).filter(h=>typeof SharedArrayBuffer>"u"||!(h instanceof SharedArrayBuffer)))})}}const eE=Object.freeze(Object.defineProperty({__proto__:null,GenerateMeshBVHWorker:JR},Symbol.toStringTag,{value:"Module"}));exports.$physicsKey=$1;exports.ActionBuilder=ae;exports.ActionCollection=Uv;exports.ActionModel=Vt;exports.Addressables=S0;exports.AlignmentConstraint=uc;exports.AmbientMode=Xr;exports.Animation=wt;exports.AnimationCurve=Tc;exports.AnimationExtension=Jd;exports.AnimationTrackHandler=xu;exports.AnimationUtils=oa;exports.Animator=mt;exports.AnimatorConditionMode=Is;exports.AnimatorController=Li;exports.AnimatorControllerParameterType=bm;exports.AnimatorStateInfo=al;exports.Antialiasing=Lc;exports.Application=tn;exports.AssetDatabase=zb;exports.AssetReference=Y;exports.AudioExtension=ar;exports.AudioListener=is;exports.AudioSource=Ii;exports.AudioTrackHandler=ss;exports.Avatar=Xs;exports.AvatarBlink_Simple=nr;exports.AvatarEyeLook_Rotation=Om;exports.AvatarLoader=Ew;exports.AvatarMarker=xe;exports.AvatarModel=$g;exports.Avatar_Brain_LookAt=$l;exports.Avatar_MouthShapes=gc;exports.Avatar_MustacheShake=Pm;exports.Avatar_POI=Fo;exports.Axes=zr;exports.AxesHelper=ma;exports.BUILD_TIME=qp;exports.BaseUIComponent=Bi;exports.BasicIKConstraint=Rm;exports.BehaviorExtension=sg;exports.BehaviorModel=pt;exports.BloomEffect=fu;exports.BoxCollider=Xd;exports.BoxGizmo=dr;exports.BoxHelperComponent=nt;exports.Button=bs;exports.ButtonsFactory=Ki;exports.CallDirection=sv;exports.CallInfo=ts;exports.Camera=Wt;exports.CameraTargetReachedEvent=Vl;exports.Canvas=ca;exports.CanvasGroup=Qs;exports.CapsuleCollider=as;exports.ChangeMaterialOnClick=Qm;exports.ChangeTransformOnClick=lr;exports.CharacterController=sr;exports.CharacterControllerInput=ds;exports.ChromaticAberration=Dc;exports.CircularBuffer=hi;exports.ClearFlags=Bo;exports.ClipExtrapolation=pn;exports.Collider=Qt;exports.Collision=tv;exports.CollisionDetectionMode=Vd;exports.ColorAdjustments=co;exports.ColorBySpeedModule=Oa;exports.ColorOverLifetimeModule=hu;exports.Component=ZC;exports.Component$1=k;exports.ComponentLifecycleEvents=Dd;exports.Components=ZR;exports.ConnectionEvents=Db;exports.ContactPoint=ev;exports.ContactShadows=yc;exports.Context=U;exports.ContextArgs=BC;exports.ContextEvent=oe;exports.ContextRegistry=re;exports.ControlTrackHandler=Su;exports.CustomBranding=hr;exports.CustomShader=_e;exports.DefaultReflectionMode=ad;exports.Deletable=Lm;exports.DeleteBox=$s;exports.DepthOfField=an;exports.DeviceFlag=Qd;exports.DocumentExtension=Tw;exports.DragControls=Mo;exports.DragMode=Dm;exports.DropListener=us;exports.Duplicatable=jm;exports.EffectWrapper=Xl;exports.EmissionModule=ys;exports.EmphasizeOnClick=ba;exports.EngineLoadingView=Kl;exports.EnvironmentScene=ku;exports.EventList=de;exports.EventListEvent=$d;exports.EventSystem=jt;exports.EventTrigger=Kd;exports.FieldWithDefault=Cv;exports.FileReference=Io;exports.FileReferenceSerializer=P0;exports.FileSpawnModel=uP;exports.File_Event=dv;exports.FixedJoint=_g;exports.Fog=Ca;exports.FrameEvent=pe;exports.GENERATOR=kd;exports.GameObject=x;exports.Gizmos=j;exports.GltfExport=Gm;exports.GltfExportBox=$m;exports.Gradient=fr;exports.Graphic=Mc;exports.GraphicRaycaster=Wd;exports.Graphics=Hs;exports.GridHelper=Pa;exports.GridLayoutGroup=hg;exports.GroundProjectedEnv=Dn;exports.GroupActionModel=Oo;exports.HideFlags=Gd;exports.HideOnStart=Ri;exports.HingeJoint=kc;exports.HorizontalLayoutGroup=cg;exports.HostData=NS;exports.Image=Ea;exports.ImageReference=Do;exports.ImageReferenceSerializer=C0;exports.InheritVelocityModule=xg;exports.Input=kb;exports.InputEventQueue=$t;exports.InputEvents=we;exports.InputField=Ig;exports.InstanceHandle=Uo;exports.InstancingHandler=qo;exports.InstancingUtil=Ai;exports.InstantiateEvent=Kb;exports.InstantiateIdProvider=ft;exports.InstantiateOptions=sn;exports.Interactable=Am;exports.JoinedRoomResponse=uS;exports.KeyEventArgs=tS;exports.Keyframe=Gt;exports.LODGroup=Ec;exports.LODModel=Ma;exports.LeftRoomResponse=fS;exports.Light=yi;exports.LightData=E0;exports.LimitVelocityOverLifetimeModule=et;exports.LoadingElementOptions=BR;exports.LogStats=Tm;exports.LogType=ai;exports.LookAt=jg;exports.LookAtConstraint=ir;exports.MainModule=Pt;exports.MarkerType=Ag;exports.MaskableGraphic=Oc;exports.Mathf=I;exports.MeshCollider=io;exports.MeshRenderer=bc;exports.MinMaxCurve=H;exports.MinMaxGradient=pr;exports.NEKeyboardEvent=nl;exports.NEPointerEvent=Yn;exports.NeedleButtonElement=Rw;exports.NeedleEngineWebComponent=Vg;exports.NeedleMenu=jn;exports.NeedlePatchesKey=Eh;exports.NeedleXRController=Kp;exports.NeedleXRSession=q;exports.NeedleXRSync=Bb;exports.NeedleXRUtils=Ub;exports.NestedGltf=au;exports.NetworkConnection=jb;exports.NetworkedStreamEvents=Sn;exports.NetworkedStreams=mc;exports.Networking=vg;exports.NewInstanceModel=Jb;exports.NoiseModule=fe;exports.ObjectRaycaster=ui;exports.ObjectUtils=Ko;exports.OffsetConstraint=ur;exports.OneEuroFilter=kh;exports.OneEuroFilterXYZ=Up;exports.OpenURL=Ta;exports.OrbitControls=he;exports.Outline=Sa;exports.OwnershipEvent=Ib;exports.OwnershipModel=tm;exports.PUBLIC_KEY=Br;exports.Padding=cr;exports.ParticleBurst=wd;exports.ParticleSubEmitter=Sg;exports.ParticleSystem=ql;exports.ParticleSystemBaseBehaviour=lo;exports.ParticleSystemRenderer=Vi;exports.ParticleSystemShapeType=vd;exports.PeerHandle=ns;exports.PeerNetworking=Lb;exports.Physics=na;exports.PhysicsExtension=og;exports.PhysicsMaterialCombine=it;exports.PixelationEffect=Ic;exports.PlayAnimationOnClick=Gl;exports.PlayAudioOnClick=qs;exports.PlayableDirector=da;exports.PlayerColor=ha;exports.PlayerState=Zi;exports.PlayerStateEvent=Vv;exports.PlayerSync=ig;exports.PlayerView=O0;exports.PlayerViewManager=k0;exports.PointerEventData=pc;exports.PointerType=Td;exports.PostProcessingEffect=Ne;exports.PostProcessingEffectOrder=Qe;exports.PostProcessingHandler=Og;exports.PreliminaryAction=va;exports.PreliminaryTrigger=xc;exports.PrimitiveType=No;exports.Progress=ie;exports.PromiseAllWithErrors=Bp;exports.PromiseErrorResult=zf;exports.RGBAColor=Z;exports.RapierPhysics=Kr;exports.RawImage=Mu;exports.RaycastOptions=eo;exports.Rect=Wv;exports.RectTransform=nn;exports.ReflectionProbe=Wl;exports.RegisteredAnimationInfo=zs;exports.RemoteSkybox=mu;exports.RenderTexture=xn;exports.RenderTextureSerializer=Y0;exports.Renderer=fi;exports.RendererData=R0;exports.RendererLightmap=yd;exports.Rigidbody=Ke;exports.RigidbodyConstraints=De;exports.RoomEvents=Q;exports.RotationBySpeedModule=Ni;exports.RotationOverLifetimeModule=rn;exports.SceneLightSettings=pd;exports.SceneSwitcher=Ie;exports.ScreenCapture=ho;exports.ScreenSpaceAmbientOcclusion=_s;exports.ScreenSpaceAmbientOcclusionN8=ln;exports.SendQueue=Yi;exports.SerializationContext=dm;exports.SetActiveOnClick=Ym;exports.ShadowCatcher=Uc;exports.ShapeModule=wg;exports.ShapeOverlapResult=iv;exports.SharpeningEffect=Bc;exports.SignalAsset=wu;exports.SignalReceiver=Wc;exports.SignalReceiverEvent=$c;exports.SignalTrackHandler=Ql;exports.Size=$v;exports.SizeBySpeedModule=Zt;exports.SizeOverLifetimeModule=mr;exports.SkinnedMeshRenderer=Vm;exports.SmoothFollow=yu;exports.SpatialGrabRaycaster=Go;exports.SpatialHtml=qc;exports.SpatialTrigger=_u;exports.SpatialTriggerReceiver=Tn;exports.SpectatorCamera=bu;exports.SphereCollider=ga;exports.SphereIntersection=sm;exports.Sprite=ps;exports.SpriteData=Yr;exports.SpriteRenderer=Yt;exports.SpriteSheet=la;exports.StateMachineBehaviour=s1;exports.StreamEndedEvent=Sm;exports.StreamReceivedEvent=nv;exports.SubEmitterSystem=xd;exports.SyncedCamera=Rg;exports.SyncedRoom=cn;exports.SyncedTransform=Ln;exports.TapGestureTrigger=Zm;exports.TeleportTarget=su;exports.TestRunner=Eg;exports.TestSceneUtils=HR;exports.TestSimulateUserData=Tg;exports.Text=Ct;exports.TextBuilder=ag;exports.TextExtension=ru;exports.TextureSheetAnimationModule=Mt;exports.TiltShiftEffect=Un;exports.Time=T0;exports.ToneMappingEffect=Ys;exports.TrackHandler=Gc;exports.TrackType=ti;exports.TrailModule=Re;exports.TransformData=Oe;exports.TransformGizmo=br;exports.TriggerBuilder=xt;exports.TriggerModel=Ws;exports.TypeStore=P;exports.UIRaycastUtils=wm;exports.UIRootComponent=Cc;exports.USDDocument=Hm;exports.USDObject=ze;exports.USDWriter=Ev;exports.USDZExporter=En;exports.USDZExporter$1=Tv;exports.USDZText=Vr;exports.USDZUIExtension=ug;exports.UriSerializer=K0;exports.UsageMarker=_c;exports.UserJoinedOrLeftRoomModel=pS;exports.VERSION=Ji;exports.VariantAction=Xm;exports.VelocityOverLifetimeModule=Le;exports.VerticalLayoutGroup=lg;exports.VideoPlayer=Ze;exports.ViewDevice=Ns;exports.Vignette=_r;exports.VisibilityAction=Sc;exports.Voip=to;exports.Volume=Ra;exports.VolumeParameter=D;exports.VolumeProfile=du;exports.WaitForFrames=gC;exports.WaitForPromise=M0;exports.WaitForSeconds=pm;exports.Watch=os;exports.WebARCameraBackground=Qc;exports.WebARSessionRoot=li;exports.WebXR=ou;exports.WebXRButtonFactory=Gs;exports.WebXRImageTracking=Yl;exports.WebXRImageTrackingModel=ws;exports.WebXRPlaneTracking=xs;exports.WebXRTrackedImage=ua;exports.XRControllerFollow=vs;exports.XRControllerModel=ls;exports.XRControllerMovement=pi;exports.XRFlag=Ei;exports.XRRig=Eu;exports.XRState=It;exports.XRStateFlag=bn;exports.__Ignore=Aw;exports.__internalNotifyObjectDestroyed=Gb;exports.activeInHierarchyFieldName=rs;exports.addAttributeChangeCallback=K_;exports.addComponent=ci;exports.addCustomExtensionPlugin=DP;exports.addNewComponent=Ao;exports.addPatch=Rd;exports.apply=jd;exports.applyHMRChanges=KC;exports.applyPrototypeExtensions=d0;exports.beginListenDestroy=Zb;exports.beginListenInstantiate=t0;exports.binaryIdentifierCasts=Zp;exports.build_scene_functions=jC;exports.builtinComponentKeyName=xo;exports.calculateProgress01=Ng;exports.clearMessages=mx;exports.colorSerializer=w1;exports.compareAssociation=o0;exports.componentSerializer=Uh;exports.copyTexture=fb;exports.createMotion=H0;exports.debugNet=Ut;exports.debugOwner=sl;exports.decompressGpuTexture=Iv;exports.deepClone=Jl;exports.delay=An;exports.delayForFrames=ec;exports.deserializeObject=od;exports.destroy=di;exports.destroyComponentInstance=p0;exports.determineMimeTypeFromExtension=uv;exports.disposeObjectResources=ge;exports.disposeStream=Cn;exports.editorGuidKeyName=xl;exports.enableSpatialConsole=Ro;exports.euler=S1;exports.eventListSerializer=O1;exports.exportAsGLTF=QR;exports.findByGuid=fm;exports.findObjectOfType=cc;exports.findObjectsOfType=g0;exports.findResourceUsers=om;exports.fitObjectIntoVolume=mb;exports.foreachComponent=$o;exports.foreachComponentEnumerator=Fd;exports.forward=Ex;exports.generateQRCode=J_;exports.generateSeed=e0;exports.getBoundingBox=Ht;exports.getCameraController=rb;exports.getComponent=Jo;exports.getComponentInChildren=lc;exports.getComponentInParent=Ul;exports.getComponents=ac;exports.getComponentsInChildren=fa;exports.getComponentsInParent=Id;exports.getFormattedDate=Mv;exports.getIconElement=ut;exports.getIconTexture=ap;exports.getLoader=en;exports.getOrAddComponent=rc;exports.getParam=w;exports.getParentHierarchyPath=Lx;exports.getPath=Xw;exports.getPeerOptions=lS;exports.getPeerjsInstance=Ab;exports.getResourceUserCount=AS;exports.getTempColor=cb;exports.getTempQuaternion=Xi;exports.getTempVector=V;exports.getUrlParams=Zl;exports.getVisibleInCustomShadowRendering=pb;exports.getWorldDirection=hb;exports.getWorldEuler=Vp;exports.getWorldPosition=X;exports.getWorldQuaternion=ue;exports.getWorldRotation=Od;exports.getWorldScale=Ae;exports.hasCommercialLicense=Rn;exports.hasIndieLicense=dc;exports.hasPointerEventComponent=hd;exports.hasProLicense=kn;exports.hideDebugConsole=bb;exports.imageToCanvas=jv;exports.instantiate=Wo;exports.invokeLoadedImportPluginHooks=wv;exports.invokeXRSessionEnd=Ob;exports.invokeXRSessionStart=Mb;exports.isActiveInHierarchy=y0;exports.isActiveSelf=pa;exports.isAndroidDevice=ex;exports.isAnimationAction=ub;exports.isComponent=J0;exports.isDebugMode=Ww;exports.isDesktop=Yw;exports.isDestroyed=Vo;exports.isDevEnvironment=A;exports.isDisposed=ES;exports.isExporting=qR;exports.isGLTFModel=Z0;exports.isHostedOnGlitch=W_;exports.isHotReloadEnabled=up;exports.isHotReloading=QC;exports.isIPad=Zw;exports.isIconElement=D0;exports.isLocalNetwork=Bt;exports.isMacOS=ix;exports.isMobileDevice=Kw;exports.isMozillaXR=tx;exports.isQuest=ox;exports.isResourceTrackingEnabled=Vb;exports.isSafari=sx;exports.isUsingInstancing=Bd;exports.isiOS=nx;exports.isiPad=Jw;exports.loadAsset=TR;exports.loadSync=zg;exports.logHierarchy=Kh;exports.lookAtInverse=xx;exports.lookAtObject=tc;exports.lookAtScreenPoint=Sx;exports.makeId=Hw;exports.makeIdFromRandomWords=X_;exports.makeNameSafe=ji;exports.markAsInstancedRendered=_0;exports.microphonePermissionsGranted=rx;exports.nameof=$w;exports.nameofFactory=H_;exports.objectSerializer=Q0;exports.offXRSessionEnd=eS;exports.offXRSessionStart=Jx;exports.onAfterRender=qC;exports.onBeforeRender=HC;exports.onClear=WC;exports.onDestroy=GC;exports.onInitialized=U0;exports.onStart=ym;exports.onUpdate=z0;exports.onXRSessionEnd=Yp;exports.onXRSessionStart=Ed;exports.parseSync=Cw;exports.placeOnSurface=gb;exports.postprocessFBXMaterials=Gp;exports.prefix=m1;exports.pushState=q_;exports.randomNumber=qw;exports.registerBinaryType=Jp;exports.registerComponent=zd;exports.registerComponentExtension=Um;exports.registerCustomEffectType=$i;exports.registerExportExtensions=zm;exports.registerExtensions=gd;exports.registerHotReloadType=V0;exports.registerLoader=Xp;exports.registerPrefabProvider=n0;exports.registerPrototypeExtensions=u0;exports.registerType=HS;exports.relativePathPrefix=Y_;exports.removeAttributeChangeCallback=Z_;exports.removeComponent=um;exports.removeCustomImportExtensionType=IP;exports.removePatch=Kx;exports.resolveUrl=Ks;exports.sanitizeString=Q_;exports.saveImage=vw;exports.screenshot=pR;exports.screenshot2=Fg;exports.sendDestroyed=am;exports.serializable=f;exports.serializeObject=a0;exports.serializeable=er;exports.setActive=Pl;exports.setAllowBalloonMessages=nb;exports.setAllowOverlayMessages=dx;exports.setAutoFitEnabled=Qh;exports.setCameraController=$f;exports.setDestroyed=v0;exports.setDevEnvironment=Nx;exports.setDisposable=Ld;exports.setDontDestroy=Tr;exports.setOrAddParamsToUrl=Uf;exports.setParam=Gw;exports.setParamWithoutReload=Dl;exports.setPeerOptions=cS;exports.setResourceTrackingEnabled=RS;exports.setState=Ip;exports.setVisibleInCustomShadowRendering=Wp;exports.setWorldEuler=$p;exports.setWorldPosition=Ye;exports.setWorldPositionXYZ=zo;exports.setWorldQuaternion=Di;exports.setWorldQuaternionXYZW=Np;exports.setWorldRotation=db;exports.setWorldRotationXYZ=ic;exports.setWorldScale=Jr;exports.showBalloonError=nc;exports.showBalloonMessage=Se;exports.showBalloonWarning=ce;exports.showDebugConsole=Hp;exports.slerp=wx;exports.syncDestroy=sc;exports.syncField=tg;exports.syncInstantiate=lm;exports.textureToCanvas=Dx;exports.tryCastBinary=Eb;exports.tryDetermineMimetypeFromBinary=pv;exports.tryDetermineMimetypeFromURL=fv;exports.tryFindObject=Zr;exports.tryGetGuid=Tb;exports.unregisterHotReloadType=$0;exports.unwatchWrite=jp;exports.useForAutoFit=ab;exports.validate=gt;exports.watchWrite=Md;
1617
+ `),this.#n.innerHTML=this.#e.innerHTML,this.#n.style.cssText="display: flex; align-items: center; justify-content: center;",this.#e.innerHTML=this.#n.outerHTML,this.#t.innerHTML=this.#e.outerHTML,this.#t.prepend(this.#s),ld(lp,{element:this.#t}),this.#o?.disconnect(),this.#o??=new MutationObserver(()=>this.#l()),this.#o.observe(this.#e,{attributes:!0}),Bf&&console.log("Needle Button updated")}#l(){this.#e&&(this.#e.style.display==="none"?this.style.display="none":this.style.display==="none"&&(this.style.display=""))}#r=e=>{Bf&&console.log("Needle Button clicked"),!e.defaultPrevented&&this.#e&&this.#e.click()}}typeof window<"u"&&!window.customElements.get($_)&&window.customElements.define($_,Rw);const tl=w("debugavatar");class $g{root;head;leftHand;rigthHand;get isValid(){return this.head!==null&&this.head!==void 0}constructor(e,t,i,n){this.root=e,this.head=t,this.leftHand=i,this.rigthHand=n,this.root?.traverse(o=>o.layers.set(2))}}class Ew{avatarRegistryUrl=null;async getOrCreateNewAvatarInstance(e,t){if(!t)return console.error("Can not create avatar: failed to provide id or root object"),null;let i=null;if(typeof t=="string"){if(i=await this.loadAvatar(e,t),!i){const o=new sn;i=x.instantiate(Zr(t,e.scene),o)}}else i=t;if(!i)return null;const n=this.findAvatar(i);return n.isValid?(tl&&console.log("[Custom Avatar] valid config",t,tl?n:""),n):(console.warn("[Custom Avatar] config isn't valid",t,tl?n:""),null)}async loadAvatar(e,t){if(console.assert(t!=null&&typeof t=="string","Avatar id must not be null"),t.length<=0||!t)return null;if(tl&&console.log("[Custom Avatar] "+t+", loading..."),t.endsWith(".glb")||(t+=".glb"),this.avatarRegistryUrl===null){const n=await fetch("./"+t);let o=null;if(n.ok){const a=await n.blob();a&&(o=await a.arrayBuffer())}return o?(await en().parseSync(e,o,null,0))?.scene??null:null}const i=new G.GLTFLoader;return _m(i,e),new Promise((n,o)=>{const r=this.avatarRegistryUrl+"/"+t;i.load(r,async a=>{await en().createBuiltinComponents(e,r,a,null,void 0),n(a.scene)},a=>{tl&&console.log("[Custom Avatar] "+a.loaded/a.total*100+"% loaded of "+a.total/1024+"kB")},a=>{console.error("[Custom Avatar] Error when loading: "+a),n(null)})})}cacheModel(e,t){}findAvatar(e){const t=e;let i=t;i.children.length==1&&(i=e.children[0]);let n=this.findAvatarPart(i,["head"]);const o=this.findAvatarPart(i,["left","hand"]),r=this.findAvatarPart(i,["right","hand"]);if(!n){n=t;const l=new c.Vector3;new c.Box3().setFromObject(n).getSize(l);const h=Math.max(l.x,l.y,l.z);console.warn("[Custom Avatar] Normalizing head scale, it's too big: "+h+" meters! Should be < 0.3m"),h>.3&&n.scale.multiplyScalar(1/h*.3)}return new $g(t,n,o,r)}findAvatarPart(e,t){const i=e.name.toLowerCase();let n=!0;for(const o of t){if(!n)break;i.indexOf(o)===-1&&(n=!1)}if(n)return e;if(e.children)for(const o of e.children){const r=this.findAvatarPart(o,t);if(r)return r}return null}handleCustomAvatarErrors(e){if(!e.ok)throw Error(e.statusText);return e}}class Tw{get extensionName(){return"DocumentExtension"}onAfterBuildDocument(e){}}class Aw{}const ZR=Object.freeze(Object.defineProperty({__proto__:null,ActionBuilder:ae,ActionCollection:Uv,ActionModel:Vt,AlignmentConstraint:uc,Animation:wt,AnimationCurve:Tc,AnimationExtension:Jd,AnimationTrackHandler:xu,Animator:mt,AnimatorController:Li,Antialiasing:Lc,AudioExtension:ar,AudioListener:is,AudioSource:Ii,AudioTrackHandler:ss,Avatar:Xs,AvatarBlink_Simple:nr,AvatarEyeLook_Rotation:Om,AvatarLoader:Ew,AvatarMarker:xe,AvatarModel:$g,Avatar_Brain_LookAt:$l,Avatar_MouthShapes:gc,Avatar_MustacheShake:Pm,Avatar_POI:Fo,AxesHelper:ma,BaseUIComponent:Bi,BasicIKConstraint:Rm,BehaviorExtension:sg,BehaviorModel:pt,BloomEffect:fu,BoxCollider:Xd,BoxGizmo:dr,BoxHelperComponent:nt,Button:bs,CallInfo:ts,Camera:Wt,CameraTargetReachedEvent:Vl,Canvas:ca,CanvasGroup:Qs,CapsuleCollider:as,ChangeMaterialOnClick:Qm,ChangeTransformOnClick:lr,CharacterController:sr,CharacterControllerInput:ds,ChromaticAberration:Dc,Collider:Qt,ColorAdjustments:co,ColorBySpeedModule:Oa,ColorOverLifetimeModule:hu,ContactShadows:yc,ControlTrackHandler:Su,CustomBranding:hr,Deletable:Lm,DeleteBox:$s,DepthOfField:an,DeviceFlag:Qd,DocumentExtension:Tw,DragControls:Mo,DropListener:us,Duplicatable:jm,EffectWrapper:Xl,EmissionModule:ys,EmphasizeOnClick:ba,EnvironmentScene:ku,EventList:de,EventListEvent:$d,EventSystem:jt,EventTrigger:Kd,FieldWithDefault:Cv,FixedJoint:_g,Fog:Ca,GltfExport:Gm,GltfExportBox:$m,Gradient:fr,Graphic:Mc,GraphicRaycaster:Wd,GridHelper:Pa,GridLayoutGroup:hg,GroundProjectedEnv:Dn,GroupActionModel:Oo,HideOnStart:Ri,HingeJoint:kc,HorizontalLayoutGroup:cg,Image:Ea,InheritVelocityModule:xg,InputField:Ig,InstanceHandle:Uo,InstancingHandler:qo,Interactable:Am,Keyframe:Gt,LODGroup:Ec,LODModel:Ma,Light:yi,LimitVelocityOverLifetimeModule:et,LogStats:Tm,LookAt:jg,LookAtConstraint:ir,MainModule:Pt,MaskableGraphic:Oc,MeshCollider:io,MeshRenderer:bc,MinMaxCurve:H,MinMaxGradient:pr,NeedleMenu:jn,NestedGltf:au,Networking:vg,NoiseModule:fe,ObjectRaycaster:ui,OffsetConstraint:ur,OpenURL:Ta,OrbitControls:he,Outline:Sa,Padding:cr,ParticleBurst:wd,ParticleSubEmitter:Sg,ParticleSystem:ql,ParticleSystemRenderer:Vi,PhysicsExtension:og,PixelationEffect:Ic,PlayAnimationOnClick:Gl,PlayAudioOnClick:qs,PlayableDirector:da,PlayerColor:ha,PointerEventData:pc,PostProcessingHandler:Og,PreliminaryAction:va,PreliminaryTrigger:xc,RawImage:Mu,Rect:Wv,RectTransform:nn,ReflectionProbe:Wl,RegisteredAnimationInfo:zs,RemoteSkybox:mu,Renderer:fi,RendererLightmap:yd,Rigidbody:Ke,RotationBySpeedModule:Ni,RotationOverLifetimeModule:rn,SceneSwitcher:Ie,ScreenCapture:ho,ScreenSpaceAmbientOcclusion:_s,ScreenSpaceAmbientOcclusionN8:ln,SetActiveOnClick:Ym,ShadowCatcher:Uc,ShapeModule:wg,SharpeningEffect:Bc,SignalAsset:wu,SignalReceiver:Wc,SignalReceiverEvent:$c,SignalTrackHandler:Ql,Size:$v,SizeBySpeedModule:Zt,SizeOverLifetimeModule:mr,SkinnedMeshRenderer:Vm,SmoothFollow:yu,SpatialGrabRaycaster:Go,SpatialHtml:qc,SpatialTrigger:_u,SpatialTriggerReceiver:Tn,SpectatorCamera:bu,SphereCollider:ga,Sprite:ps,SpriteData:Yr,SpriteRenderer:Yt,SpriteSheet:la,SubEmitterSystem:xd,SyncedCamera:Rg,SyncedRoom:cn,SyncedTransform:Ln,TapGestureTrigger:Zm,TeleportTarget:su,TestRunner:Eg,TestSimulateUserData:Tg,Text:Ct,TextBuilder:ag,TextExtension:ru,TextureSheetAnimationModule:Mt,TiltShiftEffect:Un,ToneMappingEffect:Ys,TrailModule:Ee,TransformData:ke,TransformGizmo:br,TriggerBuilder:xt,TriggerModel:Ws,UIRaycastUtils:wm,UIRootComponent:Cc,USDZExporter:En,USDZText:Vr,USDZUIExtension:ug,UsageMarker:_c,VariantAction:Xm,VelocityOverLifetimeModule:Le,VerticalLayoutGroup:lg,VideoPlayer:Ze,Vignette:_r,VisibilityAction:Sc,Voip:to,Volume:Ra,VolumeParameter:D,VolumeProfile:du,WebARCameraBackground:Qc,WebARSessionRoot:li,WebXR:ou,WebXRImageTracking:Yl,WebXRImageTrackingModel:ws,WebXRPlaneTracking:xs,WebXRTrackedImage:ua,XRControllerFollow:vs,XRControllerModel:ls,XRControllerMovement:pi,XRFlag:Ei,XRRig:Eu,XRState:It,__Ignore:Aw},Symbol.toStringTag,{value:"Module"})),Pd=w("debugmissingcamera");re.registerCallback(oe.MissingCamera,s=>{Pd&&console.warn("Creating missing camera");const e=s.context.scene,t=new c.PerspectiveCamera;t.name="Default Fallback Camera",e.add(t);const i=new Wt;if(i.sourceId=s.files?.[0]?.src??"unknown",i.fieldOfView=35,s.context.domElement.getAttribute("transparent")!=null)i.clearFlags=Bo.Uninitialized;else if(s.context.domElement.getAttribute("background-image")?.length||s.context.lightmaps.tryGetSkybox(i.sourceId))i.clearFlags=Bo.Skybox,s.context.domElement.getAttribute("background-blurriness")===null&&(s.context.scene.backgroundBlurriness=.2);else{if(i.clearFlags=Bo.SolidColor,!s.context.domElement.getAttribute("background-color")){let a="#efefef";typeof window!==void 0&&window.matchMedia("(prefers-color-scheme: dark)").matches&&(a="#1f1f1f"),e.background=new c.Color(a)}if(!e.environment){const a=new c.PMREMGenerator$1(s.context.renderer),l=new ku("neutral");e.environment=a.fromScene(l,.025).texture}}const o=Ao(t,i,!0);return t.position.x=0,t.position.y=1,t.position.z=2,s.context.domElement?.cameraControls!=!1&&Lw(s.context,o),o});re.registerCallback(oe.ContextCreated,s=>{if(!s.context.mainCamera){Pd&&console.log("Will not auto-fit because a default camera exists");return}if(s.context.domElement?.cameraControls==!0){if(rb(s.context.mainCamera)?.isCameraController==!0){Pd&&console.log("Will not auto-fit because a camera controller exists");return}Lw(s.context)}});function Lw(s,e){e=e??s.mainCameraComponent;const t=e?.gameObject;if(Pd&&console.log("Creating default camera controls",e?.name),t){const i=rc(t,he);i.sourceId=e?.sourceId??"unknown";const n=s.domElement.getAttribute("auto-rotate");if(i.autoRotate=n!=null&&n!="0"&&n?.toLowerCase()!="false",i.autoRotateSpeed=.5,i.autoFit=!0,i.autoRotate&&n){const o=parseFloat(n);isNaN(o)||(i.autoRotateSpeed=o)}}else console.warn("Missing camera object, can not add orbit controls")}re.registerCallback(oe.ContextCreated,s=>{const e=s.context.domElement.getAttribute("autoplay");if(e!==void 0&&(e===""||e==="true"||e==="1")&&s.files)for(const t of s.files)x.foreachComponent(t.file.scene,n=>{if(n.enabled!==!1){if(n instanceof wt&&n.playAutomatically||n instanceof mt||n instanceof da&&n.playOnAwake===!0)return!0;if(n instanceof wt)return n.playAutomatically=!0,!0;if(n instanceof da)return n.playOnAwake=!0,!0}},!0)!==!0&&oa.assignAnimationsFromFile(t.file,{createAnimationComponent:(n,o)=>ci(n,wt)})});class JR extends se.WorkerBase{constructor(){super(new Worker(new URL("/generateMeshBVH.worker-2qGLkQjg.js",typeof document>"u"?require("url").pathToFileURL(__filename).href:Au&&Au.tagName.toUpperCase()==="SCRIPT"&&Au.src||new URL("needle-engine.bundle-Dfge2eam.umd.cjs",document.baseURI).href),{type:"module"})),this.name="GenerateMeshBVHWorker"}runTask(e,t,i={}){return new Promise((n,o)=>{if(t.getAttribute("position").isInterleavedBufferAttribute||t.index&&t.index.isInterleavedBufferAttribute)throw new Error("GenerateMeshBVHWorker: InterleavedBufferAttribute are not supported for the geometry attributes.");e.onerror=h=>{o(new Error(`[GenerateMeshBVHWorker] ${h.message||"Unknown error. Please check the server console. If you're using vite try adding 'three-mesh-bvh' to 'optimizeDeps.exclude' in your vite.config.js"}`))},e.onmessage=h=>{const{data:d}=h;if(d.error)o(new Error(d.error)),e.onmessage=null;else if(d.serialized){const{serialized:u,position:p}=d,m=se.MeshBVH.deserialize(u,t,{setIndex:!1}),y=Object.assign({setBoundingBox:!0},i);if(t.attributes.position.array=p,u.index)if(t.index)t.index.array=u.index;else{const b=new c.BufferAttribute(u.index,1,!1);t.setIndex(b)}y.setBoundingBox&&(t.boundingBox=m.getBoundingBox(new c.Box3)),i.onProgress&&i.onProgress(d.progress),n(m),e.onmessage=null}else i.onProgress&&i.onProgress(d.progress)};const r=t.index?t.index.array:null,a=t.attributes.position.array,l=[a];r&&l.push(r),e.postMessage({index:r,position:a,options:{...i,onProgress:null,includedProgressCallback:!!i.onProgress,groups:[...t.groups]}},l.map(h=>h.buffer).filter(h=>typeof SharedArrayBuffer>"u"||!(h instanceof SharedArrayBuffer)))})}}const eE=Object.freeze(Object.defineProperty({__proto__:null,GenerateMeshBVHWorker:JR},Symbol.toStringTag,{value:"Module"}));exports.$physicsKey=$1;exports.ActionBuilder=ae;exports.ActionCollection=Uv;exports.ActionModel=Vt;exports.Addressables=S0;exports.AlignmentConstraint=uc;exports.AmbientMode=Xr;exports.Animation=wt;exports.AnimationCurve=Tc;exports.AnimationExtension=Jd;exports.AnimationTrackHandler=xu;exports.AnimationUtils=oa;exports.Animator=mt;exports.AnimatorConditionMode=Is;exports.AnimatorController=Li;exports.AnimatorControllerParameterType=bm;exports.AnimatorStateInfo=al;exports.Antialiasing=Lc;exports.Application=tn;exports.AssetDatabase=zb;exports.AssetReference=Y;exports.AudioExtension=ar;exports.AudioListener=is;exports.AudioSource=Ii;exports.AudioTrackHandler=ss;exports.Avatar=Xs;exports.AvatarBlink_Simple=nr;exports.AvatarEyeLook_Rotation=Om;exports.AvatarLoader=Ew;exports.AvatarMarker=xe;exports.AvatarModel=$g;exports.Avatar_Brain_LookAt=$l;exports.Avatar_MouthShapes=gc;exports.Avatar_MustacheShake=Pm;exports.Avatar_POI=Fo;exports.Axes=zr;exports.AxesHelper=ma;exports.BUILD_TIME=qp;exports.BaseUIComponent=Bi;exports.BasicIKConstraint=Rm;exports.BehaviorExtension=sg;exports.BehaviorModel=pt;exports.BloomEffect=fu;exports.BoxCollider=Xd;exports.BoxGizmo=dr;exports.BoxHelperComponent=nt;exports.Button=bs;exports.ButtonsFactory=Ki;exports.CallDirection=sv;exports.CallInfo=ts;exports.Camera=Wt;exports.CameraTargetReachedEvent=Vl;exports.Canvas=ca;exports.CanvasGroup=Qs;exports.CapsuleCollider=as;exports.ChangeMaterialOnClick=Qm;exports.ChangeTransformOnClick=lr;exports.CharacterController=sr;exports.CharacterControllerInput=ds;exports.ChromaticAberration=Dc;exports.CircularBuffer=hi;exports.ClearFlags=Bo;exports.ClipExtrapolation=pn;exports.Collider=Qt;exports.Collision=tv;exports.CollisionDetectionMode=Vd;exports.ColorAdjustments=co;exports.ColorBySpeedModule=Oa;exports.ColorOverLifetimeModule=hu;exports.Component=ZC;exports.Component$1=k;exports.ComponentLifecycleEvents=Dd;exports.Components=ZR;exports.ConnectionEvents=Db;exports.ContactPoint=ev;exports.ContactShadows=yc;exports.Context=U;exports.ContextArgs=BC;exports.ContextEvent=oe;exports.ContextRegistry=re;exports.ControlTrackHandler=Su;exports.CustomBranding=hr;exports.CustomShader=_e;exports.DefaultReflectionMode=ad;exports.Deletable=Lm;exports.DeleteBox=$s;exports.DepthOfField=an;exports.DeviceFlag=Qd;exports.DocumentExtension=Tw;exports.DragControls=Mo;exports.DragMode=Dm;exports.DropListener=us;exports.Duplicatable=jm;exports.EffectWrapper=Xl;exports.EmissionModule=ys;exports.EmphasizeOnClick=ba;exports.EngineLoadingView=Kl;exports.EnvironmentScene=ku;exports.EventList=de;exports.EventListEvent=$d;exports.EventSystem=jt;exports.EventTrigger=Kd;exports.FieldWithDefault=Cv;exports.FileReference=Io;exports.FileReferenceSerializer=P0;exports.FileSpawnModel=uP;exports.File_Event=dv;exports.FixedJoint=_g;exports.Fog=Ca;exports.FrameEvent=pe;exports.GENERATOR=kd;exports.GameObject=x;exports.Gizmos=j;exports.GltfExport=Gm;exports.GltfExportBox=$m;exports.Gradient=fr;exports.Graphic=Mc;exports.GraphicRaycaster=Wd;exports.Graphics=Hs;exports.GridHelper=Pa;exports.GridLayoutGroup=hg;exports.GroundProjectedEnv=Dn;exports.GroupActionModel=Oo;exports.HideFlags=Gd;exports.HideOnStart=Ri;exports.HingeJoint=kc;exports.HorizontalLayoutGroup=cg;exports.HostData=NS;exports.Image=Ea;exports.ImageReference=Do;exports.ImageReferenceSerializer=C0;exports.InheritVelocityModule=xg;exports.Input=kb;exports.InputEventQueue=$t;exports.InputEvents=we;exports.InputField=Ig;exports.InstanceHandle=Uo;exports.InstancingHandler=qo;exports.InstancingUtil=Ai;exports.InstantiateEvent=Kb;exports.InstantiateIdProvider=ft;exports.InstantiateOptions=sn;exports.Interactable=Am;exports.JoinedRoomResponse=uS;exports.KeyEventArgs=tS;exports.Keyframe=Gt;exports.LODGroup=Ec;exports.LODModel=Ma;exports.LeftRoomResponse=fS;exports.Light=yi;exports.LightData=E0;exports.LimitVelocityOverLifetimeModule=et;exports.LoadingElementOptions=BR;exports.LogStats=Tm;exports.LogType=ai;exports.LookAt=jg;exports.LookAtConstraint=ir;exports.MainModule=Pt;exports.MarkerType=Ag;exports.MaskableGraphic=Oc;exports.Mathf=I;exports.MeshCollider=io;exports.MeshRenderer=bc;exports.MinMaxCurve=H;exports.MinMaxGradient=pr;exports.NEKeyboardEvent=nl;exports.NEPointerEvent=Yn;exports.NeedleButtonElement=Rw;exports.NeedleEngineWebComponent=Vg;exports.NeedleMenu=jn;exports.NeedlePatchesKey=Eh;exports.NeedleXRController=Kp;exports.NeedleXRSession=q;exports.NeedleXRSync=Bb;exports.NeedleXRUtils=Ub;exports.NestedGltf=au;exports.NetworkConnection=jb;exports.NetworkedStreamEvents=Sn;exports.NetworkedStreams=mc;exports.Networking=vg;exports.NewInstanceModel=Jb;exports.NoiseModule=fe;exports.ObjectRaycaster=ui;exports.ObjectUtils=Ko;exports.OffsetConstraint=ur;exports.OneEuroFilter=kh;exports.OneEuroFilterXYZ=Up;exports.OpenURL=Ta;exports.OrbitControls=he;exports.Outline=Sa;exports.OwnershipEvent=Ib;exports.OwnershipModel=tm;exports.PUBLIC_KEY=Br;exports.Padding=cr;exports.ParticleBurst=wd;exports.ParticleSubEmitter=Sg;exports.ParticleSystem=ql;exports.ParticleSystemBaseBehaviour=lo;exports.ParticleSystemRenderer=Vi;exports.ParticleSystemShapeType=vd;exports.PeerHandle=ns;exports.PeerNetworking=Lb;exports.Physics=na;exports.PhysicsExtension=og;exports.PhysicsMaterialCombine=it;exports.PixelationEffect=Ic;exports.PlayAnimationOnClick=Gl;exports.PlayAudioOnClick=qs;exports.PlayableDirector=da;exports.PlayerColor=ha;exports.PlayerState=Zi;exports.PlayerStateEvent=Vv;exports.PlayerSync=ig;exports.PlayerView=O0;exports.PlayerViewManager=k0;exports.PointerEventData=pc;exports.PointerType=Td;exports.PostProcessingEffect=Ne;exports.PostProcessingEffectOrder=Qe;exports.PostProcessingHandler=Og;exports.PreliminaryAction=va;exports.PreliminaryTrigger=xc;exports.PrimitiveType=No;exports.Progress=ie;exports.PromiseAllWithErrors=Bp;exports.PromiseErrorResult=zf;exports.RGBAColor=Z;exports.RapierPhysics=Kr;exports.RawImage=Mu;exports.RaycastOptions=eo;exports.Rect=Wv;exports.RectTransform=nn;exports.ReflectionProbe=Wl;exports.RegisteredAnimationInfo=zs;exports.RemoteSkybox=mu;exports.RenderTexture=xn;exports.RenderTextureSerializer=Y0;exports.Renderer=fi;exports.RendererData=R0;exports.RendererLightmap=yd;exports.Rigidbody=Ke;exports.RigidbodyConstraints=De;exports.RoomEvents=Q;exports.RotationBySpeedModule=Ni;exports.RotationOverLifetimeModule=rn;exports.SceneLightSettings=pd;exports.SceneSwitcher=Ie;exports.ScreenCapture=ho;exports.ScreenSpaceAmbientOcclusion=_s;exports.ScreenSpaceAmbientOcclusionN8=ln;exports.SendQueue=Yi;exports.SerializationContext=dm;exports.SetActiveOnClick=Ym;exports.ShadowCatcher=Uc;exports.ShapeModule=wg;exports.ShapeOverlapResult=iv;exports.SharpeningEffect=Bc;exports.SignalAsset=wu;exports.SignalReceiver=Wc;exports.SignalReceiverEvent=$c;exports.SignalTrackHandler=Ql;exports.Size=$v;exports.SizeBySpeedModule=Zt;exports.SizeOverLifetimeModule=mr;exports.SkinnedMeshRenderer=Vm;exports.SmoothFollow=yu;exports.SpatialGrabRaycaster=Go;exports.SpatialHtml=qc;exports.SpatialTrigger=_u;exports.SpatialTriggerReceiver=Tn;exports.SpectatorCamera=bu;exports.SphereCollider=ga;exports.SphereIntersection=sm;exports.Sprite=ps;exports.SpriteData=Yr;exports.SpriteRenderer=Yt;exports.SpriteSheet=la;exports.StateMachineBehaviour=s1;exports.StreamEndedEvent=Sm;exports.StreamReceivedEvent=nv;exports.SubEmitterSystem=xd;exports.SyncedCamera=Rg;exports.SyncedRoom=cn;exports.SyncedTransform=Ln;exports.TapGestureTrigger=Zm;exports.TeleportTarget=su;exports.TestRunner=Eg;exports.TestSceneUtils=HR;exports.TestSimulateUserData=Tg;exports.Text=Ct;exports.TextBuilder=ag;exports.TextExtension=ru;exports.TextureSheetAnimationModule=Mt;exports.TiltShiftEffect=Un;exports.Time=T0;exports.ToneMappingEffect=Ys;exports.TrackHandler=Gc;exports.TrackType=ti;exports.TrailModule=Ee;exports.TransformData=ke;exports.TransformGizmo=br;exports.TriggerBuilder=xt;exports.TriggerModel=Ws;exports.TypeStore=P;exports.UIRaycastUtils=wm;exports.UIRootComponent=Cc;exports.USDDocument=Hm;exports.USDObject=ze;exports.USDWriter=Ev;exports.USDZExporter=En;exports.USDZExporter$1=Tv;exports.USDZText=Vr;exports.USDZUIExtension=ug;exports.UriSerializer=K0;exports.UsageMarker=_c;exports.UserJoinedOrLeftRoomModel=pS;exports.VERSION=Ji;exports.VariantAction=Xm;exports.VelocityOverLifetimeModule=Le;exports.VerticalLayoutGroup=lg;exports.VideoPlayer=Ze;exports.ViewDevice=Ns;exports.Vignette=_r;exports.VisibilityAction=Sc;exports.Voip=to;exports.Volume=Ra;exports.VolumeParameter=D;exports.VolumeProfile=du;exports.WaitForFrames=gC;exports.WaitForPromise=M0;exports.WaitForSeconds=pm;exports.Watch=os;exports.WebARCameraBackground=Qc;exports.WebARSessionRoot=li;exports.WebXR=ou;exports.WebXRButtonFactory=Gs;exports.WebXRImageTracking=Yl;exports.WebXRImageTrackingModel=ws;exports.WebXRPlaneTracking=xs;exports.WebXRTrackedImage=ua;exports.XRControllerFollow=vs;exports.XRControllerModel=ls;exports.XRControllerMovement=pi;exports.XRFlag=Ei;exports.XRRig=Eu;exports.XRState=It;exports.XRStateFlag=bn;exports.__Ignore=Aw;exports.__internalNotifyObjectDestroyed=Gb;exports.activeInHierarchyFieldName=rs;exports.addAttributeChangeCallback=K_;exports.addComponent=ci;exports.addCustomExtensionPlugin=DP;exports.addNewComponent=Ao;exports.addPatch=Rd;exports.apply=jd;exports.applyHMRChanges=KC;exports.applyPrototypeExtensions=d0;exports.beginListenDestroy=Zb;exports.beginListenInstantiate=t0;exports.binaryIdentifierCasts=Zp;exports.build_scene_functions=jC;exports.builtinComponentKeyName=xo;exports.calculateProgress01=Ng;exports.clearMessages=mx;exports.colorSerializer=w1;exports.compareAssociation=o0;exports.componentSerializer=Uh;exports.copyTexture=fb;exports.createMotion=H0;exports.debugNet=Ut;exports.debugOwner=sl;exports.decompressGpuTexture=Iv;exports.deepClone=Jl;exports.delay=An;exports.delayForFrames=ec;exports.deserializeObject=od;exports.destroy=di;exports.destroyComponentInstance=p0;exports.determineMimeTypeFromExtension=uv;exports.disposeObjectResources=ge;exports.disposeStream=Cn;exports.editorGuidKeyName=xl;exports.enableSpatialConsole=Ro;exports.euler=S1;exports.eventListSerializer=O1;exports.exportAsGLTF=QR;exports.findByGuid=fm;exports.findObjectOfType=cc;exports.findObjectsOfType=g0;exports.findResourceUsers=om;exports.fitObjectIntoVolume=mb;exports.foreachComponent=$o;exports.foreachComponentEnumerator=Fd;exports.forward=Ex;exports.generateQRCode=J_;exports.generateSeed=e0;exports.getBoundingBox=Ht;exports.getCameraController=rb;exports.getComponent=Jo;exports.getComponentInChildren=lc;exports.getComponentInParent=Ul;exports.getComponents=ac;exports.getComponentsInChildren=fa;exports.getComponentsInParent=Id;exports.getFormattedDate=Mv;exports.getIconElement=ut;exports.getIconTexture=ap;exports.getLoader=en;exports.getOrAddComponent=rc;exports.getParam=w;exports.getParentHierarchyPath=Lx;exports.getPath=Xw;exports.getPeerOptions=lS;exports.getPeerjsInstance=Ab;exports.getResourceUserCount=AS;exports.getTempColor=cb;exports.getTempQuaternion=Xi;exports.getTempVector=V;exports.getUrlParams=Zl;exports.getVisibleInCustomShadowRendering=pb;exports.getWorldDirection=hb;exports.getWorldEuler=Vp;exports.getWorldPosition=X;exports.getWorldQuaternion=ue;exports.getWorldRotation=Od;exports.getWorldScale=Ae;exports.hasCommercialLicense=Rn;exports.hasIndieLicense=dc;exports.hasPointerEventComponent=hd;exports.hasProLicense=kn;exports.hideDebugConsole=bb;exports.imageToCanvas=jv;exports.instantiate=Wo;exports.invokeLoadedImportPluginHooks=wv;exports.invokeXRSessionEnd=Ob;exports.invokeXRSessionStart=Mb;exports.isActiveInHierarchy=y0;exports.isActiveSelf=pa;exports.isAndroidDevice=ex;exports.isAnimationAction=ub;exports.isComponent=J0;exports.isDebugMode=Ww;exports.isDesktop=Yw;exports.isDestroyed=Vo;exports.isDevEnvironment=A;exports.isDisposed=ES;exports.isExporting=qR;exports.isGLTFModel=Z0;exports.isHostedOnGlitch=W_;exports.isHotReloadEnabled=up;exports.isHotReloading=QC;exports.isIPad=Zw;exports.isIconElement=D0;exports.isLocalNetwork=Bt;exports.isMacOS=ix;exports.isMobileDevice=Kw;exports.isMozillaXR=tx;exports.isQuest=ox;exports.isResourceTrackingEnabled=Vb;exports.isSafari=sx;exports.isUsingInstancing=Bd;exports.isiOS=nx;exports.isiPad=Jw;exports.loadAsset=TR;exports.loadSync=zg;exports.logHierarchy=Kh;exports.lookAtInverse=xx;exports.lookAtObject=tc;exports.lookAtScreenPoint=Sx;exports.makeId=Hw;exports.makeIdFromRandomWords=X_;exports.makeNameSafe=ji;exports.markAsInstancedRendered=_0;exports.microphonePermissionsGranted=rx;exports.nameof=$w;exports.nameofFactory=H_;exports.objectSerializer=Q0;exports.offXRSessionEnd=eS;exports.offXRSessionStart=Jx;exports.onAfterRender=qC;exports.onBeforeRender=HC;exports.onClear=WC;exports.onDestroy=GC;exports.onInitialized=U0;exports.onStart=ym;exports.onUpdate=z0;exports.onXRSessionEnd=Yp;exports.onXRSessionStart=Ed;exports.parseSync=Cw;exports.placeOnSurface=gb;exports.postprocessFBXMaterials=Gp;exports.prefix=m1;exports.pushState=q_;exports.randomNumber=qw;exports.registerBinaryType=Jp;exports.registerComponent=zd;exports.registerComponentExtension=Um;exports.registerCustomEffectType=$i;exports.registerExportExtensions=zm;exports.registerExtensions=gd;exports.registerHotReloadType=V0;exports.registerLoader=Xp;exports.registerPrefabProvider=n0;exports.registerPrototypeExtensions=u0;exports.registerType=HS;exports.relativePathPrefix=Y_;exports.removeAttributeChangeCallback=Z_;exports.removeComponent=um;exports.removeCustomImportExtensionType=IP;exports.removePatch=Kx;exports.resolveUrl=Ks;exports.sanitizeString=Q_;exports.saveImage=vw;exports.screenshot=pR;exports.screenshot2=Fg;exports.sendDestroyed=am;exports.serializable=f;exports.serializeObject=a0;exports.serializeable=er;exports.setActive=Pl;exports.setAllowBalloonMessages=nb;exports.setAllowOverlayMessages=dx;exports.setAutoFitEnabled=Qh;exports.setCameraController=$f;exports.setDestroyed=v0;exports.setDevEnvironment=Nx;exports.setDisposable=Ld;exports.setDontDestroy=Tr;exports.setOrAddParamsToUrl=Uf;exports.setParam=Gw;exports.setParamWithoutReload=Dl;exports.setPeerOptions=cS;exports.setResourceTrackingEnabled=RS;exports.setState=Ip;exports.setVisibleInCustomShadowRendering=Wp;exports.setWorldEuler=$p;exports.setWorldPosition=Ye;exports.setWorldPositionXYZ=zo;exports.setWorldQuaternion=Di;exports.setWorldQuaternionXYZW=Np;exports.setWorldRotation=db;exports.setWorldRotationXYZ=ic;exports.setWorldScale=Jr;exports.showBalloonError=nc;exports.showBalloonMessage=Se;exports.showBalloonWarning=ce;exports.showDebugConsole=Hp;exports.slerp=wx;exports.syncDestroy=sc;exports.syncField=tg;exports.syncInstantiate=lm;exports.textureToCanvas=Dx;exports.tryCastBinary=Eb;exports.tryDetermineMimetypeFromBinary=pv;exports.tryDetermineMimetypeFromURL=fv;exports.tryFindObject=Zr;exports.tryGetGuid=Tb;exports.unregisterHotReloadType=$0;exports.unwatchWrite=jp;exports.useForAutoFit=ab;exports.validate=gt;exports.watchWrite=Md;