@needle-tools/engine 4.11.5-next.b4a2f9e → 4.11.5-next.d95d573
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +7 -5
- package/dist/{needle-engine.bundle-DnJ3q6Oa.js → needle-engine.bundle-By_B1saf.js} +8 -4
- package/dist/{needle-engine.bundle-D2_8tEN0.min.js → needle-engine.bundle-D68OTj0O.min.js} +3 -3
- package/dist/{needle-engine.bundle-DG38kMjs.umd.cjs → needle-engine.bundle-DYcVfok9.umd.cjs} +4 -4
- package/dist/needle-engine.js +2 -2
- package/dist/needle-engine.min.js +1 -1
- package/dist/needle-engine.umd.cjs +1 -1
- package/lib/engine/xr/NeedleXRSession.js +2 -1
- package/lib/engine/xr/NeedleXRSession.js.map +1 -1
- package/lib/engine-components/webxr/WebXR.js +4 -0
- package/lib/engine-components/webxr/WebXR.js.map +1 -1
- package/package.json +1 -1
- package/src/engine/xr/NeedleXRSession.ts +3 -1
- package/src/engine-components/webxr/WebXR.ts +4 -0
|
@@ -141,7 +141,7 @@ void main(){
|
|
|
141
141
|
#__vconsole .vc-mask {
|
|
142
142
|
overflow: hidden;
|
|
143
143
|
}
|
|
144
|
-
`,br?.prepend(i),o===!0&&Nb()<=0&&p_(),console.log("\u{1F335} Debug console has loaded")}},e.onerror=()=>{console.warn("\u{1F335} Debug console failed to load."+(window.crossOriginIsolated?"This page is using cross-origin isolation, so external scripts can't be loaded.":"")),lc=!1,Hi=null},e.src="https://cdn.jsdelivr.net/npm/vconsole@3.15.1/dist/vconsole.min.js",document.body.appendChild(e)}function RO(){if(!globalThis.VConsole)return;const o=new VConsole.VConsolePlugin("needle-console","\u{1F335} Inspect glTF"),e=()=>document.querySelector("#__vc_plug_"+o._id+" iframe");return o.on("renderTab",function(t){const i=globalThis["needle:codegen_files"];if(!i||i.length===0)return;let n=globalThis["needle:codegen_files"][0];const s=n.indexOf("?");s>-1&&(n=n.substring(0,s));const r=location.protocol+"//"+location.host+location.pathname+"/"+n,a=encodeURIComponent(r);o.fullUrl="https://viewer.needle.tools?inspect&file="+a;var l='<iframe src="" style="width: 100%; height: 99%; border: none;"></iframe>';t(l)}),o.on("show",function(){const t=e();t&&t.src!==o.fullUrl&&(t.src=o.fullUrl)}),o.on("hide",function(){const t=e();t&&(t.src="")}),o.on("addTopBar",function(t){var i=new Array;i.push({name:"Open in new window \u2197",onClick:function(n){window.open(o.fullUrl,"_blank"),Hi?.hide()}}),i.push({name:"Reload",onClick:function(n){const s=e();s&&(s.src=o.fullUrl)}}),i.push({name:"Fullscreen",onClick:function(n){const s=e();s.requestFullscreen?s.requestFullscreen():s.webkitRequestFullscreen instanceof Function&&s.webkitRequestFullscreen()}}),t(i)}),o}function TO(){return document.querySelector("#__vconsole .vc-switch")||null}function EO(){return document.querySelector("#__vconsole")||null}const g_=v("debugdefines");fs('if(!globalThis["NEEDLE_ENGINE_VERSION"]) globalThis["NEEDLE_ENGINE_VERSION"] = "0.0.0";'),fs('if(!globalThis["NEEDLE_ENGINE_GENERATOR"]) globalThis["NEEDLE_ENGINE_GENERATOR"] = "unknown";'),fs('if(!globalThis["NEEDLE_PROJECT_BUILD_TIME"]) globalThis["NEEDLE_PROJECT_BUILD_TIME"] = "unknown";'),fs('if(!globalThis["NEEDLE_PUBLIC_KEY"]) globalThis["NEEDLE_PUBLIC_KEY"] = "unknown";'),fs('globalThis["__NEEDLE_ENGINE_VERSION__"] = "4.11.5
|
|
144
|
+
`,br?.prepend(i),o===!0&&Nb()<=0&&p_(),console.log("\u{1F335} Debug console has loaded")}},e.onerror=()=>{console.warn("\u{1F335} Debug console failed to load."+(window.crossOriginIsolated?"This page is using cross-origin isolation, so external scripts can't be loaded.":"")),lc=!1,Hi=null},e.src="https://cdn.jsdelivr.net/npm/vconsole@3.15.1/dist/vconsole.min.js",document.body.appendChild(e)}function RO(){if(!globalThis.VConsole)return;const o=new VConsole.VConsolePlugin("needle-console","\u{1F335} Inspect glTF"),e=()=>document.querySelector("#__vc_plug_"+o._id+" iframe");return o.on("renderTab",function(t){const i=globalThis["needle:codegen_files"];if(!i||i.length===0)return;let n=globalThis["needle:codegen_files"][0];const s=n.indexOf("?");s>-1&&(n=n.substring(0,s));const r=location.protocol+"//"+location.host+location.pathname+"/"+n,a=encodeURIComponent(r);o.fullUrl="https://viewer.needle.tools?inspect&file="+a;var l='<iframe src="" style="width: 100%; height: 99%; border: none;"></iframe>';t(l)}),o.on("show",function(){const t=e();t&&t.src!==o.fullUrl&&(t.src=o.fullUrl)}),o.on("hide",function(){const t=e();t&&(t.src="")}),o.on("addTopBar",function(t){var i=new Array;i.push({name:"Open in new window \u2197",onClick:function(n){window.open(o.fullUrl,"_blank"),Hi?.hide()}}),i.push({name:"Reload",onClick:function(n){const s=e();s&&(s.src=o.fullUrl)}}),i.push({name:"Fullscreen",onClick:function(n){const s=e();s.requestFullscreen?s.requestFullscreen():s.webkitRequestFullscreen instanceof Function&&s.webkitRequestFullscreen()}}),t(i)}),o}function TO(){return document.querySelector("#__vconsole .vc-switch")||null}function EO(){return document.querySelector("#__vconsole")||null}const g_=v("debugdefines");fs('if(!globalThis["NEEDLE_ENGINE_VERSION"]) globalThis["NEEDLE_ENGINE_VERSION"] = "0.0.0";'),fs('if(!globalThis["NEEDLE_ENGINE_GENERATOR"]) globalThis["NEEDLE_ENGINE_GENERATOR"] = "unknown";'),fs('if(!globalThis["NEEDLE_PROJECT_BUILD_TIME"]) globalThis["NEEDLE_PROJECT_BUILD_TIME"] = "unknown";'),fs('if(!globalThis["NEEDLE_PUBLIC_KEY"]) globalThis["NEEDLE_PUBLIC_KEY"] = "unknown";'),fs('globalThis["__NEEDLE_ENGINE_VERSION__"] = "4.11.5";'),fs('globalThis["__NEEDLE_ENGINE_GENERATOR__"] = "undefined";'),fs('globalThis["__NEEDLE_PROJECT_BUILD_TIME__"] = "Fri Oct 31 2025 12:26:25 GMT+0000 (Coordinated Universal Time)";'),fs('globalThis["__NEEDLE_PUBLIC_KEY__"] = "'+NEEDLE_PUBLIC_KEY+'";');const bn="4.11.5",Bd="undefined",sg="Fri Oct 31 2025 12:26:25 GMT+0000 (Coordinated Universal Time)";g_&&console.log(`Engine version: ${bn} (generator: ${Bd})
|
|
145
145
|
Project built at ${sg}`);const Ea=NEEDLE_PUBLIC_KEY,ko="needle_isActiveInHierarchy",_r="builtin_components",cc="needle_editor_guid";function fs(o){try{(0,eval)(o)}catch(e){g_&&console.error(e)}}let f_,y_=null;function _n(){return f_}function rg(o){if(o==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}y_!==o&&(y_=o,f_=new o)}const ki=Symbol("shadowDomOwner"),AO=v("debugpatch");function Fd(o,e,t,i){const n=AO===e;if(!t&&!i)return;const s=e+"___needle";LO(o,e,t,i);const r=Object.getOwnPropertyDescriptor(o,e),a=o[e];n&&console.log("Patch",o.constructor.name,e,r,a),r?(n&&console.log("Apply patch with existing descriptor",o.constructor.name,e,r),typeof r.value=="function"&&(o[e]=__(r.value,o,e))):(n&&console.log("Create patch with new property",o.constructor.name,e,r),Object.defineProperty(o,e,{set:function(l){if(typeof l=="function")this[s]=__(l,o,e);else{const c=this[s];v_(o,e,this,c,l),this[s]=l,w_(o,e,this,c,l)}},get:function(){const l=this[s];return typeof l=="function"&&l[s]?l[s]:l}}))}function IO(o,e,t){const i=lg(o,e);if(i)for(let n=i.length-1;n>=0;n--){const s=i[n];s.prefix===t&&(s.prefix=null),s.postfix===t&&(s.postfix=null),!s.prefix&&!s.postfix&&i.splice(n,1)}}const b_=Symbol("Needle:Patches:WrappedFunction");function __(o,e,t){if(o[b_])return o;const i=function(...n){v_(e,t,this,...n);const s=o.apply(this,n);return w_(e,t,this,s,...n),s};return i[b_]=!0,i}const Ud="Needle:Patches";function ag(){return globalThis[Ud]||(globalThis[Ud]=new WeakMap),globalThis[Ud]}function lg(o,e){const t=ag().get(o);return t?t.get(e):null}function LO(o,e,t,i){let n=ag().get(o);n||(n=new Map,ag().set(o,n));let s=n.get(e);s||(s=[],n.set(e,s)),s.push({prefix:t,postfix:i})}function v_(o,e,t,...i){if(!t)return;const n=lg(o,e);if(n)for(const s of n)s.prefix?.call(t,...i)}function w_(o,e,t,i,...n){if(!t)return;const s=lg(o,e);if(s)for(const r of s)r.postfix?.call(t,i,...n)}const Aa=[];function zd(o){Aa.indexOf(o)===-1&&Aa.push(o)}function jO(o){const e=Aa.indexOf(o);e!==-1&&Aa.splice(e,1)}const Ia=[];function cg(o){Ia.indexOf(o)===-1&&Ia.push(o)}function DO(o){const e=Ia.indexOf(o);e!==-1&&Ia.splice(e,1)}function x_(o){globalThis.dispatchEvent(new CustomEvent("needle-xrsession-start",{detail:o}));for(let e=0;e<Aa.length;e++)Aa[e](o)}function S_(o){globalThis.dispatchEvent(new CustomEvent("needle-xrsession-end",{detail:o}));for(let e=0;e<Ia.length;e++)Ia[e](o)}const st=v("debuginput");var Nd=(o=>(o.Mouse="mouse",o.Touch="touch",o.Controller="controller",o.Hand="hand",o))(Nd||{}),Ee=(o=>(o.PointerDown="pointerdown",o.PointerUp="pointerup",o.PointerMove="pointermove",o.KeyDown="keydown",o.KeyUp="keyup",o.KeyPressed="keypress",o))(Ee||{});class Mo extends PointerEvent{clientZ;deviceIndex;origin;source;mode;get isSpatial(){return this.mode!="screen"}get ray(){return this._ray||(this._ray=new vo(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(),st&&console.warn("Stop propagation...",this.pointerId,this.pointerType)}}class hc extends KeyboardEvent{source;constructor(e,t,i){super(e,i),this.source=t}stopImmediatePropagation(){super.stopImmediatePropagation(),this.source?.stopImmediatePropagation()}}class BO{key;keyType;source;constructor(e){this.key=e.key,this.keyType=e.type,this.source=e}}var oi=(o=>(o[o.Early=-100]="Early",o[o.Default=0]="Default",o[o.Late=100]="Late",o))(oi||{});class C_{_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 s=this._eventListeners[e],r=s.find(a=>a.priority===n);r?r.listeners.push({callback:t,options:i}):(s.push({priority:n,listeners:[{callback:t,options:i}]}),s.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 s=n.find(a=>a.priority===i.queue);if(!s)return;const r=s.listeners.findIndex(a=>a.callback===t);r>=0&&s.listeners.splice(r,1)}else for(const s of n){const r=s.listeners.findIndex(a=>a.callback===t);r>=0&&s.listeners.splice(r,1)}}dispatchEvent(e){let t=!1;if(e instanceof hc){const i=this._eventListeners[e.type];if(i)for(const n of i)for(let s=0;s<n.listeners.length;s++){const r=n.listeners[s];if(r.options?.signal?.aborted){n.listeners.splice(s,1),s--;continue}r.options.once&&(n.listeners.splice(s,1),s--),r.callback(e)}}if(e instanceof Mo){const i=this._eventListeners[e.type];if(i)for(const n of i){if(t)break;for(let s=0;s<n.listeners.length;s++){const r=n.listeners[s];if(r.options?.signal?.aborted){n.listeners.splice(s,1),s--;continue}if(e.immediatePropagationStopped){t=!0,st&&console.log("immediatePropagationStopped",e.type);break}else e.propagationStopped&&(t=!0,st&&console.log("propagationStopped",e.type));r.options.once&&(n.listeners.splice(s,1),s--),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 s of e)if(i===s){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 ee];_pointerPositionsLastFrame=[new ee];_pointerPositionsDelta=[new ee];_pointerPositionsRC=[new ee];_pointerPositionDown=[new b];_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":st&&Te("Create Pointer down"),this.onDownButton(e.deviceIndex,e.button),this.onDown(e);break;case"pointermove":st&&Te("Create Pointer move"),this.onMove(e);break;case"pointerup":st&&Te("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&&q.isMozillaXR()?!0:(st&&console.warn("CanReceiveInput:False for",e.target),!1)}onContextMenu=e=>{this.canReceiveInput(e)!==!1&&e instanceof PointerEvent&&e.pointerType};keysPressed={};onKeyDown=e=>{if(st&&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 hc("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 hc("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 hc("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);st&&Te(`pointer down #${t}, identifier:${e.pointerId}`);const i=this.getAndUpdateSpatialObjectForScreenPosition(t,e.clientX,e.clientY),n=new Mo("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),s=new Mo("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(s)};onPointerCancel=e=>{this.context.isInAR||(st&&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 Mo("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,st&&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),s=this.getAndUpdateSpatialObjectForScreenPosition(n,i.clientX,i.clientY),r=new Mo("pointerdown",e,{origin:this,mode:"screen",deviceIndex:0,pointerId:n,button:0,clientX:i.clientX,clientY:i.clientY,pointerType:"touch",buttonName:"unknown",device:s,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),s=this.getAndUpdateSpatialObjectForScreenPosition(n,i.clientX,i.clientY),r=new Mo("pointermove",e,{origin:this,mode:"screen",deviceIndex:0,pointerId:n,button:0,clientX:i.clientX,clientY:i.clientY,pointerType:"touch",buttonName:"unknown",device:s,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),s=new Mo("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(s),this._pointerIds[n]=-1}};tempNearPlaneVector=new b;tempFarPlaneVector=new b;tempLookMatrix=new K;getAndUpdateSpatialObjectForScreenPosition(e,t,i){let n=this._pointerSpace[e];n||(n=new O,this._pointerSpace[e]=n),this._pointerSpace[e]=n;const s=this.context.mainCamera;if(s){const r=this.tempNearPlaneVector.set(t,i,-1);this.convertScreenspaceToRaycastSpace(r);const a=this.tempFarPlaneVector.set(r.x,r.y,1);r.unproject(s),a.unproject(s);const l=s.worldUp||D(0,1,0).applyQuaternion(be(s));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,s=i>=t.x&&i<=t.right&&n>=t.y&&n<=t.bottom;return st&&!s&&console.log("Not in rect",t,i,n),s}onDown(e){const t=e.pointerId;if(this.getPointerPressed(t)&&console.warn(`Received pointerDown for pointerId that is already pressed: ${t}`,st?e:""),st&&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 b);for(this._pointerPositionDown[t].set(e.clientX,e.clientY,e.clientZ??0);t>=this._pointerPositions.length;)this._pointerPositions.push(new ee);this._pointerPositions[t].set(e.clientX,e.clientY),t>=this._pointerDownTime.length&&this._pointerDownTime.push(0),this._pointerDownTime[t]=this.context.time.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)){st&&console.log(e.pointerType,"UP",t,"was not down");return}st&&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 a=this._pointerEventsPressed.length-1;a>=0;a--)if(this._pointerEventsPressed[a].pointerId===t){this._pointerEventsPressed.splice(a,1);break}if(!this._pointerPositionDown[t]){st&&ye("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 i=this._pointerUpTime[t],n=this._pointerDownTime[t],s=this.context.time.realtimeSinceStartup,r=s-n;if(t>=this._pointerUpTime.length&&this._pointerUpTime.push(-99),this._pointerUpTime[t]=s,r<1){let a=e.clientX-this._pointerPositionDown[t].x,l=e.clientY-this._pointerPositionDown[t].y,c=0;if(e.isSpatial&&e.clientZ!=null&&(c=e.clientZ-this._pointerPositionDown[t].z,a*=200,l*=200,c*=200),Math.abs(a)<5&&Math.abs(l)<5&&Math.abs(c)<5){this.setPointerState(t,this._pointerClick,!0),e.isClick=!0;const h=s-i;st&&console.log("CLICK",t,a,l,c,h),h<this._doubleClickTimeThreshold&&h>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 ee);for(;t>=this._pointerPositionsLastFrame.length;)this._pointerPositionsLastFrame.push(new ee);for(;t>=this._pointerPositionsDelta.length;)this._pointerPositionsDelta.push(new ee);const i=this._pointerPositionsLastFrame[t];i.copy(this._pointerPositions[t]);const n=this._pointerPositionsDelta[t];let s=e.clientX-i.x,r=e.clientY-i.y;if(e.source instanceof MouseEvent||e.source instanceof TouchEvent){const h=e.source;s===0&&h.movementX!==0&&(s=h.movementX||0),r===0&&h.movementY!==0&&(r=h.movementY||0)}n.x+=s,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 ee);const c=this._pointerPositionsRC[t];c.set(a,l),this.convertScreenspaceToRaycastSpace(c)}getPointerIndex(e){let t=-1;for(let i=0;i<this._pointerIds.length;i++){if(this._pointerIds[i]===e)return i;t===-1&&this._pointerIds[i]===-1&&(t=i)}return t!==-1?(this._pointerIds[t]=e,t):(st&&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=z.Current;try{z.Current=this.context,this.dispatchEvent(e)}finally{z.Current=t}}}const La=new K().makeRotationY(Math.PI),Gi=new U().setFromAxisAngle(new b(0,1,0),Math.PI),FO=v("debugwebxr");class UO{priority=-1e5;gameObject;isXRRig(){return!0}get isActive(){return this.gameObject.visible}constructor(){if(this.gameObject=new O,this.gameObject.name="Implicit XR Rig",FO){const e=Cg(16733661);e.position.y+=.5,this.gameObject.add(e)}}}const Ro=v("debugwebxr"),Vd=v("debugcustomgesture"),zO="https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles",NO="generic-trigger",VO=new U().setFromEuler(new ot(wo.degToRad(0),wo.degToRad(-90),wo.degToRad(-90))),WO=new b(.04,-.04,0);class hg{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 K;_gripPosition=new b;_gripQuaternion=new U;_linearVelocity=new b;_rayPositionRaw=new b;_rayRotationRaw=new U;_rayMatrix=new K;_rayPosition=new b;_rayQuaternion=new U;get gripPosition(){return D(this._gripPosition)}get gripQuaternion(){return ni(this._gripQuaternion)}get gripMatrix(){return this._gripMatrix}get gripLinearVelocity(){return D(this._linearVelocity).applyQuaternion(Gi)}get rayPosition(){return D(this._rayPosition)}get rayQuaternion(){return ni(this._rayQuaternion)}get gripWorldPosition(){return D(this._gripWorldPosition)}_gripWorldPosition=new b;get gripWorldQuaternion(){return ni(this._gripWorldQuaternion)}_gripWorldQuaternion=new U;get rayWorldPosition(){return D(this._rayWorldPosition)}_rayWorldPosition=new b;updateRayWorldPosition(){const e=this.xr.context.mainCamera?.parent;this._rayWorldPosition.copy(this._rayPositionRaw),e&&this._rayWorldPosition.applyMatrix4(e.matrixWorld)}get rayWorldQuaternion(){return ni(this._rayWorldQuaternion)}_rayWorldQuaternion=new U;get pinchPosition(){return D(this._pinchPosition)}_pinchPosition=new b;updateRayWorldQuaternion(){const e=this.xr.context.mainCamera?.parent,t=e?be(e):void 0;this._rayWorldQuaternion.copy(this._rayRotationRaw).multiply(Gi),t&&this._rayWorldQuaternion.premultiply(t)}get ray(){return this._ray.origin.copy(this.rayWorldPosition),this._ray.direction.copy(D(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=D(0,1,0).applyQuaternion(e.quaternion),i=D(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 xi(.15);_debugGripAxesHelper=new xi(.07);_debugRayAxesHelper=new xi(.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 O,this._object.name=`NeedleXRController_${i}`,Ro&&(this._object.add(this._debugAxesHelper),this._gripSpaceObject=new O,this._raySpaceObject=new O,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 vo,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(){B.DrawSphere(this.rayWorldPosition,.003),B.DrawDirection(this.rayWorldPosition,D(0,0,10).applyQuaternion(this.rayWorldQuaternion));const e=(this.inputSource.gripSpace?this.gripWorldPosition:this.object.worldPosition).sub(this.object.worldForward.multiplyScalar(.1)),t=this.inputSource.profiles.join(`
|
|
146
146
|
`);let i=`Controller[${this.index}] (${this.inputSource.targetRayMode}, ${this.side})
|
|
147
147
|
C:${this.connected?"x":"-"} T:${this.isTracking?"x":"-"} Hand:${this.inputSource.hand?"x":"-"} Pen: ${this._isMxInk?"x":"-"}`;if(this.inputSource.hand&&(i+=`
|
|
@@ -163,7 +163,7 @@ or by using the once option like onStart(()=>{}, { once:true }).
|
|
|
163
163
|
See https://engine.needle.tools/docs/scripting.html#special-lifecycle-hooks for more information.`))}}function ys(o,e){const t=Ba.get(e);if(t){for(let n=0;n<t.length;n++)if(t[n].method===o){t.splice(n,1);return}}const i=Da.get(e);if(i){for(let n=0;n<i.length;n++)if(i[n].method===o){i.splice(n,1);return}}}function Hn(o,e){e===de.ContextCreated&&ug.delete(o),M_(o,e)}function M_(o,e){e===we.Start&&Da.get(de.ContextCreated)&&M_(o,de.ContextCreated);const t=e===we.Start||e===de.ContextCreated,i=Ba.get(e);i&&i.length>0&&T_(o,i,t);const n=Da.get(e);if(n&&n.length>0){const s=[...n];n.length=0,T_(o,s,t),s.length>0&&(Ba.has(e)||Ba.set(e,new Array),Ba.get(e).push(...s))}}const $d=new Array,R_={context:null};function T_(o,e,t){$d.length=0;for(let n=0;n<e.length;n++)$d.push(e[n]);let i=ug.get(o);for(let n=0;n<$d.length;n++){const s=$d[n];let r=!0;if(i&&i.has(s)&&(r=!1),r)try{R_.context=o,s.method?.call(R_,o)}catch(a){console.error("Error in lifecycle method",a)}if(s.options?.once){for(let a=0;a<e.length;a++)if(e[a]===s){e.splice(a,1);break}}else t&&(i||(i=new Set,ug.set(o,i)),i.add(s))}}const ug=new WeakMap,pg={};function mg(o,e){pg[o]=e}function E_(o){const e=o.getBufferIdentifier(),t=pg[e];return t(o)}function A_(o){return typeof o.guid=="function"?o.guid():null}let gg;function $O(){return gg}function HO(o){gg=o}function I_(o,e){return e||(e={}),e={...gg,...e},o?new xb(o,e):new xb(e)}async function L_(){const o=await import("./vendor-CsyK1CFs.min.js").then(e=>e.bundler);return console.log(o),o.default===void 0?o:o.default}class j_{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 L_(),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 qO(i)})}async trySetupClient(e){const t=await L_();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 GO{_peer;constructor(e){this._peer=e}}class qO extends GO{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 vn=(o=>(o[o.OnConnection=0]="OnConnection",o[o.OnRoomJoin=1]="OnRoomJoin",o[o.Queued=2]="Queued",o[o.Immediate=3]="Immediate",o))(vn||{});const D_="https://urls.needle.tools/default-networking-backend/index";let qi="wss://networking.needle.tools/socket";const si=!!v("debugnet"),dc=!!(si||v("debugowner")),Hd=v("debugnetbin");var B_=(o=>(o.ConnectionInfo="connection-start-info",o))(B_||{}),te=(o=>(o.Join="join-room",o.Leave="leave-room",o.JoinedRoom="joined-room",o.LeftRoom="left-room",o.UserJoinedRoom="user-joined-room",o.UserLeftRoom="user-left-room",o.RoomStateSent="room-state-sent",o))(te||{});class XO{room;viewId;allowEditing;inRoom}class QO{room}class YO{userId}var F_=(o=>(o.RequestHasOwner="request-has-owner",o.ResponseHasOwner="response-has-owner",o.RequestIsOwner="request-is-owner",o.ResponseIsOwner="response-is-owner",o.RequestOwnership="request-ownership",o.GainedOwnership="gained-ownership",o.RemoveOwnership="remove-ownership",o.LostOwnership="lost-ownership",o.GainedOwnershipBroadcast="gained-ownership-broadcast",o.LostOwnershipBroadcast="lost-ownership-broadcast",o))(F_||{});class fg{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||(dc&&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 dc&&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?(dc&&console.log("GAINED OWNERSHIP",this.guid),this._hasOwnership=!0):this._hasOwnership=!1)}onLostOwnership(e){e===this.guid&&(dc&&console.log("LOST OWNERSHIP",this.guid),this._hasOwnership=!1,this._isOwned=!1)}}class U_{context;_peer=null;constructor(e){this.context=e}get peer(){return this._peer||(this._peer=new j_),this._peer}tryGetState(e){return e==="invalid"?null:this._state[e]}get connectionId(){return this._connectionId}get isDebugEnabled(){return si}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(),si&&console.log("join: "+e),this.send("join-room",{room:e,viewOnly:t},vn.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=vn.Queued){if(t===null&&(t={}),i===vn.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){Hd&&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,vn.Immediate);break}const s=this.toMessage(n.key,n.value);this._defaultMessagesBufferArray.push(s)}if(this._defaultMessagesBuffer.length=0,this._defaultMessagesBufferArray.length>0&&si&&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!==qi)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?qi=t:Eb()&&(qi="wss://"+window.location.host+"/socket"),this.connectWebsocket()}disconnect(){this._ws?.close(),this._ws=void 0,qi=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=c=>{i||(i=!0,e(c))};if(qi===void 0&&(console.log("Fetch default backend url: "+D_),qi=await(await fetch(D_)).text()),qi===void 0){n(!1);return}console.debug(`\u22A1 Connecting to networking backend on
|
|
164
164
|
`+qi);const s=await import("./vendor-CsyK1CFs.min.js").then(c=>c.index),r=s.default?.WebsocketBuilder??s.WebsocketBuilder,a=s.default?.ExponentialBackoff??s.ExponentialBackoff,l=new r(qi).withMaxRetries(10).withBackoff(new a(2e3,4)).onOpen(()=>{this._connectingToWebsocketPromise=null,this._ws=l,this.connected=!0,A()||si?console.log(`\u229E Connected to networking backend
|
|
165
165
|
`+qi):console.debug("\u229E Connected to networking backend",qi),n(!0),this.onSendQueued(vn.OnConnection)}).onClose(c=>{this._connectingToWebsocketPromise=null,this.connected=!1,this._isInRoom=!1,n(!1);let h="Websocket connection closed...";qi?.includes("/socket")||(h+=' Do you perhaps mean to connect to "/socket"?'),console.error(h)}).onError(c=>{console.error("\u22A0 Websocket connection failed..."),n(!1)}).onRetry(()=>{console.log("\u2192 Retry connecting to networking websocket")}).build();l.addEventListener(s.WebsocketEvent.message,(c,h)=>{this.onMessage(c,h)})})}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 s of n)this.handleIncomingStringMessage(s);else this.handleIncomingStringMessage(n);return}catch(n){si&&i==="pong"?console.log("<<",i):A()&&console.error("Failed to parse message",n)}}async handleIncomingBinaryMessage(e){Hd&&console.log("<< bin",this.context.time.frame);const t=await e.arrayBuffer();var i=new Uint8Array(t);const n=new aP(i),s=n.getBufferIdentifier(),r=this._listenersBinary[s],a=E_(n),l=A_(a);if(l&&typeof l=="string"&&(this._state[l]=a),!r)return;const c=a??n;for(const h of r)h(c)}handleIncomingStringMessage(e){if(si&&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(si&&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),(Hd||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}
|
|
166
|
-
${a.href}`)}this.onSendQueued(vn.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,(Hd||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),si&&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&&(si&&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":si&&console.log("RECEIVED all-room-state-deleted"),this._state={};break;case"ping":case"pong":const s=e.data?.time;s&&(this._currentDelay=this.context.time.time-s),si&&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(s){console.error('Error invoking callback for "'+e.key+'"',s)}}}toMessage(e,t){return{key:e,data:t}}sendWithWebsocket(e,t,i=vn.OnRoomJoin){if(!this._ws){const s=this._waitingForSocket[i]||[];s.push(()=>this.sendWithWebsocket(e,t,i)),this._waitingForSocket[i]=s;return}const n=JSON.stringify(this.toMessage(e,t));si&&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 uc=v("debugwebxr");class yg{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=>{uc&&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 s=0;s<e.controllers.length;s++)e.controllers[s].index===i.index&&(n=!0);n||(uc&&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),uc&&console.log(`XRSync: ${i.type} ${i.handedness} added`,i.index)}}}class z_{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(n=>n.handedness===t)?.isTracking||!1:void 0}getDeviceType(e,t){if(!e)return;const i=this._states.get(e);return i?i.controllerStates.find(n=>n.handedness===t)?.type||"unknown":void 0}context;constructor(e){this.context=e,this.context.connection.beginListen(te.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(te.LeftRoom,this.onLeftRoom),this.context.connection.beginListen(te.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.beginListen(te.UserLeftRoom,this.onOtherUserLeftRoom)}destroy(){this.context.connection.stopListen(te.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(te.LeftRoom,this.onLeftRoom),this.context.connection.stopListen(te.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.stopListen(te.UserLeftRoom,this.onOtherUserLeftRoom)}onJoinedRoom=()=>{if(this.context.connection.connectionId){this._states.has(this.context.connection.connectionId)||(uc&&console.log("XRSync: Local user joined room",this.context.connection.connectionId),this._states.set(this.context.connection.connectionId,new yg(this.context.connection.connectionId,this.context)));for(const e of this.context.connection.usersInRoom())this._states.has(e)||this._states.set(e,new yg(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)||(uc&&console.log("XRSync: Remote user joined room",t),this._states.set(t,new yg(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 N_{_fadeToColorQuad;_fadeToColorMaterial;constructor(){this._fadeToColorMaterial=new xe({color:0,transparent:!0,depthTest:!1,fog:!1,side:Si}),this._fadeToColorQuad=new G(new Un(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 s=this._requestedFadeValue;n.opacity=I.lerp(n.opacity,s,t/.03),Math.abs(n.opacity-s)<=.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 wr=(o=>(o[o.Quad=0]="Quad",o[o.Cube=1]="Cube",o[o.Sphere=2]="Sphere",o[o.Cylinder=3]="Cylinder",o[o.RoundedCube=10]="RoundedCube",o))(wr||{});class xr{static createText(e,t){let i=null;const n=t?.font||KO(t?.familyFamily||null);n instanceof NC?i=this.#t(e,n,t):i==null&&(i=new gn);const s=t?.color||16777215,r=new G(i,t?.material??new pt({color:s}));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 VC(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 xe({colorWrite:!1,depthWrite:!0,side:Si});return this.createPrimitive(e,{material:t})}static createPrimitive(e,t){let i;const n=t?.color||16777215;switch(e){case"Quad":case 0:{const s=new Un(1,1,1,1),r=t?.material??new pt({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new G(s,r),i.name="Quad"}break;case"Cube":case 1:{const s=new Sa(1,1,1),r=t?.material??new pt({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new G(s,r),i.name="Cube"}break;case 10:case"RoundedCube":{const s=ZO(1,1,1,.1,2),r=t?.material??new pt({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new G(s,r),i.name="RoundedCube"}break;case"Sphere":case 2:{const s=new fd(.5,16,16),r=t?.material??new pt({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new G(s,r),i.name="Sphere"}break;case"Cylinder":case 3:{const s=new eb(.5,.5,1,32),r=t?.material??new pt({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new G(s,r),i.name="Cylinder"}break;case"ShaderBall":i=new xo,i.name="ShaderBall",JO(i,t);break}return this.applyDefaultObjectOptions(i,t),i}static createSprite(e){const t=new SS({color:16777215});e?.texture&&"map"in t&&(t.map=e.texture);const i=new CS(t);return this.applyDefaultObjectOptions(i,e),i}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||0,t.position.y||0,t.position.z||0)),t?.rotation&&(Array.isArray(t.rotation)?e.rotation.set(t.rotation[0],t.rotation[1],t.rotation[2]):e.rotation.set(t.rotation.x||0,t.rotation.y||0,t.rotation.z||0)),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||1,t.scale.y||1,t.scale.z||1)),t?.receiveShadow!=null&&(e.receiveShadow=t.receiveShadow),t?.castShadow!=null&&(e.castShadow=t.castShadow),t?.parent&&t.parent.add(e)}}function ZO(o,e,t,i,n){const s=new PS,r=1e-5,a=i-r;s.absarc(r,r,r,-Math.PI/2,-Math.PI,!0),s.absarc(r,e-a*2,r,Math.PI,Math.PI/2,!0),s.absarc(o-a*2,e-a*2,r,Math.PI/2,0,!0),s.absarc(o-a*2,r,r,0,-Math.PI/2,!0);const l=new OS(s,{bevelEnabled:!0,bevelSegments:n*2,steps:1,bevelSize:a,bevelThickness:i,curveSegments:n,UVGenerator:{generateTopUV:(c,h)=>{const d=[];for(let p=0;p<h.length;p+=3)d.push(new ee(h[p]/o,h[p+1]/e));return d},generateSideWallUV:(c,h,d,p,m,f)=>{const g=[];return g.push(new ee(h[d]/o,h[d+1]/e)),g.push(new ee(h[p]/o,h[p+1]/e)),g.push(new ee(h[m]/o,h[m+1]/e)),g.push(new ee(h[f]/o,h[f+1]/e)),g}}});return l.scale(1,1,1-i),l.center(),l.index||l.setIndex(Array.from({length:l.attributes.position.count},(c,h)=>h)),l.computeVertexNormals(),l}const Gd=new Map;function KO(o){let e="";switch(o){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(Gd.has(e)){const n=Gd.get(e);if(n)return n}const t=new WC,i=new Promise((n,s)=>{t.load(e,r=>{Gd.set(e,r),n(r)},void 0,s)});return Gd.set(e,i),i}let bg=!1,_g=null;function JO(o,e){if(_g===null){const t="https://cdn.needle.tools/static/models/shaderball.glb",i=new Po,n=Om(null);i.setDRACOLoader(n.dracoLoader),i.setKTX2Loader(n.ktx2Loader),bg=!0,_g=i.loadAsync(t).then(s=>{const r=s.scene;return r.position.y-=.5,r}).catch(s=>(console.warn("Failed to load shaderball mesh: "+s.message),W_())).finally(()=>{bg=!1})}if(bg){const t=W_();t.name="ShaderBall-Placeholder";const i=t.children[0];i?.type==="Mesh"&&V_(i,e),o.add(t)}_g.then(t=>{o.children.forEach(s=>{s.name==="ShaderBall-Placeholder"&&o.remove(s)});const i=t.clone(),n=i.children[0];n?.type==="Mesh"&&(n.geometry.attributes.tangent||n.geometry.computeTangents(),V_(n,e)),o.add(i)})}function V_(o,e){if(e?.color||e?.material||e?.texture){const t=e?.material??o.material?.clone()??new pt;e.color&&"color"in t&&t.color instanceof ne&&t.color.set(e.color),e?.texture&&"map"in t&&(t.map=e.texture),o.material=t}}function W_(){return new xo().add(xr.createPrimitive("Sphere",{material:new xe({transparent:!0,opacity:.1})}))}class Wl{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 Wl(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 Wn(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 cr({alpha:!0}),this._renderer.setAnimationLoop(this.onFrame),this._renderer.xr.setSession(i),this._renderer.xr.enabled=!0,this._camera=new re,this._scene=new vi,this._scene.fog=new tb(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 Wn(1e3),this._scene.clear()}_objects=[];setupScene(){this._scene.background=new ne(0),this._scene.add(new um(5,10,1118481,1118481));const e=new pm(16777215,1);e.position.set(0,20,0),e.castShadow=!1,this._scene.add(e);const t=new pm(16777215,1);t.position.set(0,-1,0),t.castShadow=!1,this._scene.add(t);const i=new mm(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 s=0;s<100;s++){const r=new pt({color:2236962,metalness:1,roughness:.8});this.isAR&&(r.emissive=new ne(Math.random(),Math.random(),Math.random()),r.emissiveIntensity=Math.random());const a=I.random(0,1)>.5?wr.Sphere:wr.Cube,l=xr.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 c=l.position.distanceTo(this._camera.position)-l.scale.x;c<1&&l.position.multiplyScalar(1+1/c),this._objects.push(l),this._scene.add(l)}}update(e,t){const i=e*4e-4;for(let n=0;n<this._objects.length;n++){const s=this._objects[n];s.position.y+=Math.sin(i+n*.5)*.005,s.rotateY(.002)}}}var pc;(o=>{const e=[];function t(){if(!e?.length)return!1;for(const s of e)s.exportAndOpen();return!0}o.exportAndOpen=t;function i(s){e.push(s)}o.registerExporter=i;function n(s){if(!e)return;const r=e.indexOf(s);r>=0&&e.splice(r,1)}o.unregisterExporter=n})(pc||(pc={}));const Ge=v("debugwebxr"),$_=v("stats");let vg=0;function ek(o){let e=null;const t=o;return t.getAROverlayContainer?e=t.getAROverlayContainer():e=o,e}tk();async function tk(){if(v("debugasap")){let o=globalThis["needle:XRSession"];if(o instanceof Promise){delete globalThis["needle:XRSession"],ue.addContextCreatedCallback(async e=>{if(!o)return;fr(!0);const t=await o;if(t){const i=Z.getDefaultSessionInit("immersive-vr");Z.setSession("immersive-vr",t,i,e.context)}else console.error("NeedleXRSession: ASAP session was rejected");o=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()=>{fr(!0),console.log("Received Session Granted..."),await Wn(100);const o=sessionStorage.getItem("needle_xr_session_mode"),e=sessionStorage.getItem("needle_xr_session_init")??null,t=e?JSON.parse(e):null;let i=null;if(H_()&&(await Wl.start(o||"immersive-vr",t||Z.getDefaultSessionInit("immersive-vr")),await ok(),i=await Wl.handoff()),i)Z.setSession(i.mode,i.session,i.init,z.Current);else if(o&&e){console.log("Session Granted: Restore last session");const n=JSON.parse(e);Z.start(o,n).catch(s=>console.warn(s))}else Z.start("immersive-vr").catch(n=>console.warn("Session Granted failed:",n))},{once:!0})}}function ik(o,e){sessionStorage.setItem("needle_xr_session_mode",o),sessionStorage.setItem("needle_xr_session_init",JSON.stringify(e))}function nk(){sessionStorage.removeItem("needle_xr_session_mode"),sessionStorage.removeItem("needle_xr_session_init")}const wg=new Set;ue.registerCallback(de.ContextCreationStart,async o=>{wg.add(o.context)}),ue.registerCallback(de.ContextCreated,async o=>{wg.delete(o.context);const e=o.context?.domElement.getAttribute("autostart")||null;sk(e)});function H_(){return wg.size>0}function ok(){return new Promise(o=>{const e=Date.now(),t=setInterval(()=>{(!H_()||Date.now()-e>6e4)&&(clearInterval(t),o())},100)})}q.isDesktop()&&A()&&window.addEventListener("keydown",o=>{(o.key==="x"||o.key==="Escape")&&Z.active&&Z.stop()});function sk(o){if(o)switch(o?.toLowerCase()){case"ar":Dn.registerWaitForInteraction(()=>{Z.start("ar")});break}}const qd=Symbol("initial-fov");class Z{static _sync=null;static getXRSync(e){return this._sync||(this._sync=new z_(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=>(Ge&&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=>Z.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 q.isVisionOS()||t.push("hand-tracking"),{optionalFeatures:t};case"immersive-vr":const i=["local-floor","bounded-floor","high-fixed-foveation-level","layers"];return q.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(q.isiOS()){if(e==="ar")if(await this.isARSupported())e="immersive-ar";else return pc.exportAndOpen(),null}else e=="ar"&&(e="immersive-ar");if(A()&&v("debugxrpreroom"))return console.warn("Debug: Starting temporary XR session"),await Wl.start(e,t||Z.getDefaultSessionInit(e)),null;if(this._currentSessionRequest)return console.warn("A XRSession is already being requested"),(Ge||A())&&ye("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=z.Current),i||(i=ue.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 r=this.getDefaultSessionInit(e),a=ek(i.domElement);a&&!q.isQuest()&&(r.domOverlay={root:a},r.optionalFeatures.push("dom-overlay")),t={...r,...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 Wl.stop();const n=e=="immersive-ar"?i.scripts_immersive_ar:i.scripts_immersive_vr;Ge?console.log(`%cRequesting ${e} session`,"font-weight:bold;",t,n):console.log(`%cRequesting ${e} session`,"font-weight:bold;");for(const r of n)r.onBeforeXR&&r.onBeforeXR(e,t);for(const r of this._sessionRequestStartListeners)r({mode:e,init:t});Ge&&Te("Requesting "+e+" session ("+Date.now()+")"),this._currentSessionRequest=navigator?.xr?.requestSession(e,t),this._currentSessionRequestMode=e;const s=await this._currentSessionRequest?.catch(r=>{console.error(r,"Code: "+r.code),r.code===9&&ye("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:"&&ye("XR requires a secure connection (HTTPS)")});this._currentSessionRequest=void 0,this._currentSessionRequestMode=null;for(const r of this._sessionRequestEndListeners)r({mode:e,init:t,newSession:s||null});return s?this.setSession(e,s,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 s=e=="immersive-ar"?n.scripts_immersive_ar:n.scripts_immersive_vr;return this._activeSession=new Z(e,t,n,{scripts:s,controller_added:this._controllerAddedListeners,controller_removed:this._controllerRemovedListeners,init:i}),t.addEventListener("end",this.onEnd),Ge?console.log(`%cStarted ${e} session`,"font-weight:bold;",s):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?(Ge&&console.log("[NeedleXRSession] Stopping XR Session... (new)"),e[this.$_stop_request]=setTimeout(()=>{e.end()})):Ge&&console.warn("[NeedleXRSession] XR Session stop already requested"))}static onEnd=()=>{Ge&&console.log("XR Session ended"),this._activeSession=null};context;get sync(){return Z._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()&&q.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&&Rr(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 D(0,0,0);const t=D(e);return t.x*=-1,t.z*=-1,t.applyQuaternion(ni(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(Rr(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)}Ge&&(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 s of n.results)return this.convertHitTestResult(s);return null}convertHitTestResult(e){const t=this.context.renderer.xr.getReferenceSpace(),i=t&&e.getPose(t);if(i){const n=D(i.transform.position),s=ni(i.transform.orientation),r=this.context.mainCamera;if(r?.parent!==this._cameraRenderParent&&n.applyMatrix4(La),r?.parent){n.applyMatrix4(r.parent.matrixWorld),s.multiply(Gi);const a=be(r.parent);a.premultiply(Gi),s.premultiply(a)}return{hit:e,position:n,quaternion:s}}return null}convertSpace(e){const t=D(e.position);t.applyMatrix4(La);const i=ni(e.orientation);return i.premultiply(Gi),{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){ik(e,n.init),this.session=t,this.mode=e,this.context=i,(Ge||v("console"))&&fr(!0),this._xr_scripts=[...n.scripts],this._xr_update_scripts=this._xr_scripts.filter(s=>typeof s.onUpdateXR=="function"),this._controllerAdded=n.controller_added,this._controllerRemoved=n.controller_removed,To(this.onBefore,we.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(s=>t.requestHitTestSource?.call(t,{space:s})?.then(r=>this._viewerHitTestSource=r).catch(r=>console.error(r))).catch(s=>console.error(s)),this.context.mainCamera&&(this._originalCameraWorldPosition=J(this.context.mainCamera,new b),this._originalCameraWorldRotation=be(this.context.mainCamera,new U),this._originalCameraWorldScale=He(this.context.mainCamera,new b),this._originalCameraParent=this.context.mainCamera.parent,this.context.mainCamera instanceof re&&(this.context.mainCamera[qd]=this.context.mainCamera.fov)),this._defaultRig=new UO,this.context.scene.add(this._defaultRig.gameObject),this.addRig(this._defaultRig);for(let s=0;s<t.inputSources.length;s++){const r=t.inputSources[s];if(!r.handedness){console.warn("Input source in xr session has no handedness - ignoring",s);continue}this.onInputSourceAdded(r)}this.session.addEventListener("end",this.onEnd),this.session.addEventListener("inputsourceschange",s=>{for(const r of s.removed)this.disconnectInputSource(r);for(const r of s.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):Ge&&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 hg(this,e,t);this._newControllers.push(i)};disconnectInputSource(e){const t=(s,r)=>{if(s.inputSource===e){Ge&&console.log("Disconnecting controller",s.index);const a=r.indexOf(s);a>=0&&r.splice(a,1),this.invokeControllerEvent(s,this._controllerRemoved,"removed");const l={xr:this,controller:s,change:"removed"};for(const c of this._xr_scripts)c.onXRControllerRemoved&&c.onXRControllerRemoved(l);s.onDisconnected()}},i=[...this.controllers];for(let s=i.length-1;s>=0;s--){const r=i[s];t(r,this.controllers)}const n=[...this._newControllers];for(let s=n.length-1;s>=0;s--){const r=n[s];t(r,this._newControllers)}}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"),nk(),this.onAfterRender(),this.revertCustomForward(),this._didStart=!1,this._previousCameraParent=null,this.requestedCameraNearPlane=null,ys(this.onBefore,we.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()}),S_({session:this});for(const s of Z._xrEndListeners)s({xr:this});const n=[...this.controllers];for(let s=0;s<n.length;s++)this.disconnectInputSource(n[s].inputSource);this.controllers.length=0,this._newControllers.length=0;for(const s of this._xr_scripts)s?.onLeaveXR?.({xr:this});this.sync?.onExitXR(this),this.context.mainCamera&&(this._originalCameraParent?.add(this.context.mainCamera),this._originalCameraWorldPosition&>(this.context.mainCamera,this._originalCameraWorldPosition),this._originalCameraWorldRotation&&yn(this.context.mainCamera,this._originalCameraWorldRotation),this._originalCameraWorldScale&&Ta(this.context.mainCamera,this._originalCameraWorldScale),this.context.mainCamera instanceof re&&this.context.mainCamera[qd]&&(this.context.mainCamera.fov=this.context.mainCamera[qd],this.context.mainCamera[qd]=0)),this.context.requestSizeUpdate(),this._defaultRig.gameObject.removeFromParent(),fr(!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&&(Ge&&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 s=0;s<n.length;s++){const r=this.context.new_scripts_xr[s];if(!r||r.destroyed||r.supportsXR?.(this.mode)==!1){this.context.new_scripts_xr.splice(s,1);continue}if(!r.activeAndEnabled){this.context.new_scripts_xr.splice(s,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 s=Gt(this.context.scene.children);if(s){const r=s.getSize(D());if(r.length()>0){const a=this._defaultRig.gameObject;a.position.set(s.min.x+r.x*.5,s.min.y,s.max.z+r.z*.5+1.5);const l=s.getCenter(D());l.y=a.position.y,a.lookAt(l)}}}x_({session:this}),vr();for(const s of Z._xrStartListeners)s(i);const n=[...this._xr_scripts];Ge&&console.log("NeedleXRSession start, handle scripts:",n);for(const s of n){if(s.destroyed){this._script_to_remove.push(s);continue}if(!s.activeAndEnabled){this.markInactive(s);continue}this.invokeCallback_EnterXR(s);for(const r of this.controllers)this.invokeCallback_ControllerAdded(s,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 s of n){if(!s.connected){console.warn("New controller is not connected",s);continue}this.controllers.push(s);for(const r of this._xr_scripts){if(r.destroyed){this._script_to_remove.push(r);continue}r.activeAndEnabled!==!1&&this.invokeCallback_ControllerAdded(r,s)}}this.controllers.sort((s,r)=>s.index-r.index)}Ge&&this.context.time.frame%30===0&&this.controllers.length<=0&&this.session.inputSources.length>0&&(fr(!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 s of n)!s.destroyed&&this.running&&s.onLeaveXR?.(i),this.removeScript(s)}this.sync?.onUpdate(this),this.onRenderDebug()};onRenderDebug(){if(Ge)for(const e of this.controllers)e.onRenderDebug();if((Ge||$_)&&this.rig&&(vg++,vg>=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()}`,Ge||$_)for(const s of this.controllers)n+=`
|
|
166
|
+
${a.href}`)}this.onSendQueued(vn.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,(Hd||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),si&&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&&(si&&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":si&&console.log("RECEIVED all-room-state-deleted"),this._state={};break;case"ping":case"pong":const s=e.data?.time;s&&(this._currentDelay=this.context.time.time-s),si&&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(s){console.error('Error invoking callback for "'+e.key+'"',s)}}}toMessage(e,t){return{key:e,data:t}}sendWithWebsocket(e,t,i=vn.OnRoomJoin){if(!this._ws){const s=this._waitingForSocket[i]||[];s.push(()=>this.sendWithWebsocket(e,t,i)),this._waitingForSocket[i]=s;return}const n=JSON.stringify(this.toMessage(e,t));si&&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 uc=v("debugwebxr");class yg{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=>{uc&&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 s=0;s<e.controllers.length;s++)e.controllers[s].index===i.index&&(n=!0);n||(uc&&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),uc&&console.log(`XRSync: ${i.type} ${i.handedness} added`,i.index)}}}class z_{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(n=>n.handedness===t)?.isTracking||!1:void 0}getDeviceType(e,t){if(!e)return;const i=this._states.get(e);return i?i.controllerStates.find(n=>n.handedness===t)?.type||"unknown":void 0}context;constructor(e){this.context=e,this.context.connection.beginListen(te.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(te.LeftRoom,this.onLeftRoom),this.context.connection.beginListen(te.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.beginListen(te.UserLeftRoom,this.onOtherUserLeftRoom)}destroy(){this.context.connection.stopListen(te.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(te.LeftRoom,this.onLeftRoom),this.context.connection.stopListen(te.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.stopListen(te.UserLeftRoom,this.onOtherUserLeftRoom)}onJoinedRoom=()=>{if(this.context.connection.connectionId){this._states.has(this.context.connection.connectionId)||(uc&&console.log("XRSync: Local user joined room",this.context.connection.connectionId),this._states.set(this.context.connection.connectionId,new yg(this.context.connection.connectionId,this.context)));for(const e of this.context.connection.usersInRoom())this._states.has(e)||this._states.set(e,new yg(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)||(uc&&console.log("XRSync: Remote user joined room",t),this._states.set(t,new yg(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 N_{_fadeToColorQuad;_fadeToColorMaterial;constructor(){this._fadeToColorMaterial=new xe({color:0,transparent:!0,depthTest:!1,fog:!1,side:Si}),this._fadeToColorQuad=new G(new Un(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 s=this._requestedFadeValue;n.opacity=I.lerp(n.opacity,s,t/.03),Math.abs(n.opacity-s)<=.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 wr=(o=>(o[o.Quad=0]="Quad",o[o.Cube=1]="Cube",o[o.Sphere=2]="Sphere",o[o.Cylinder=3]="Cylinder",o[o.RoundedCube=10]="RoundedCube",o))(wr||{});class xr{static createText(e,t){let i=null;const n=t?.font||KO(t?.familyFamily||null);n instanceof NC?i=this.#t(e,n,t):i==null&&(i=new gn);const s=t?.color||16777215,r=new G(i,t?.material??new pt({color:s}));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 VC(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 xe({colorWrite:!1,depthWrite:!0,side:Si});return this.createPrimitive(e,{material:t})}static createPrimitive(e,t){let i;const n=t?.color||16777215;switch(e){case"Quad":case 0:{const s=new Un(1,1,1,1),r=t?.material??new pt({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new G(s,r),i.name="Quad"}break;case"Cube":case 1:{const s=new Sa(1,1,1),r=t?.material??new pt({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new G(s,r),i.name="Cube"}break;case 10:case"RoundedCube":{const s=ZO(1,1,1,.1,2),r=t?.material??new pt({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new G(s,r),i.name="RoundedCube"}break;case"Sphere":case 2:{const s=new fd(.5,16,16),r=t?.material??new pt({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new G(s,r),i.name="Sphere"}break;case"Cylinder":case 3:{const s=new eb(.5,.5,1,32),r=t?.material??new pt({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new G(s,r),i.name="Cylinder"}break;case"ShaderBall":i=new xo,i.name="ShaderBall",JO(i,t);break}return this.applyDefaultObjectOptions(i,t),i}static createSprite(e){const t=new SS({color:16777215});e?.texture&&"map"in t&&(t.map=e.texture);const i=new CS(t);return this.applyDefaultObjectOptions(i,e),i}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||0,t.position.y||0,t.position.z||0)),t?.rotation&&(Array.isArray(t.rotation)?e.rotation.set(t.rotation[0],t.rotation[1],t.rotation[2]):e.rotation.set(t.rotation.x||0,t.rotation.y||0,t.rotation.z||0)),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||1,t.scale.y||1,t.scale.z||1)),t?.receiveShadow!=null&&(e.receiveShadow=t.receiveShadow),t?.castShadow!=null&&(e.castShadow=t.castShadow),t?.parent&&t.parent.add(e)}}function ZO(o,e,t,i,n){const s=new PS,r=1e-5,a=i-r;s.absarc(r,r,r,-Math.PI/2,-Math.PI,!0),s.absarc(r,e-a*2,r,Math.PI,Math.PI/2,!0),s.absarc(o-a*2,e-a*2,r,Math.PI/2,0,!0),s.absarc(o-a*2,r,r,0,-Math.PI/2,!0);const l=new OS(s,{bevelEnabled:!0,bevelSegments:n*2,steps:1,bevelSize:a,bevelThickness:i,curveSegments:n,UVGenerator:{generateTopUV:(c,h)=>{const d=[];for(let p=0;p<h.length;p+=3)d.push(new ee(h[p]/o,h[p+1]/e));return d},generateSideWallUV:(c,h,d,p,m,f)=>{const g=[];return g.push(new ee(h[d]/o,h[d+1]/e)),g.push(new ee(h[p]/o,h[p+1]/e)),g.push(new ee(h[m]/o,h[m+1]/e)),g.push(new ee(h[f]/o,h[f+1]/e)),g}}});return l.scale(1,1,1-i),l.center(),l.index||l.setIndex(Array.from({length:l.attributes.position.count},(c,h)=>h)),l.computeVertexNormals(),l}const Gd=new Map;function KO(o){let e="";switch(o){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(Gd.has(e)){const n=Gd.get(e);if(n)return n}const t=new WC,i=new Promise((n,s)=>{t.load(e,r=>{Gd.set(e,r),n(r)},void 0,s)});return Gd.set(e,i),i}let bg=!1,_g=null;function JO(o,e){if(_g===null){const t="https://cdn.needle.tools/static/models/shaderball.glb",i=new Po,n=Om(null);i.setDRACOLoader(n.dracoLoader),i.setKTX2Loader(n.ktx2Loader),bg=!0,_g=i.loadAsync(t).then(s=>{const r=s.scene;return r.position.y-=.5,r}).catch(s=>(console.warn("Failed to load shaderball mesh: "+s.message),W_())).finally(()=>{bg=!1})}if(bg){const t=W_();t.name="ShaderBall-Placeholder";const i=t.children[0];i?.type==="Mesh"&&V_(i,e),o.add(t)}_g.then(t=>{o.children.forEach(s=>{s.name==="ShaderBall-Placeholder"&&o.remove(s)});const i=t.clone(),n=i.children[0];n?.type==="Mesh"&&(n.geometry.attributes.tangent||n.geometry.computeTangents(),V_(n,e)),o.add(i)})}function V_(o,e){if(e?.color||e?.material||e?.texture){const t=e?.material??o.material?.clone()??new pt;e.color&&"color"in t&&t.color instanceof ne&&t.color.set(e.color),e?.texture&&"map"in t&&(t.map=e.texture),o.material=t}}function W_(){return new xo().add(xr.createPrimitive("Sphere",{material:new xe({transparent:!0,opacity:.1})}))}class Wl{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 Wl(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 Wn(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 cr({alpha:!0}),this._renderer.setAnimationLoop(this.onFrame),this._renderer.xr.setSession(i),this._renderer.xr.enabled=!0,this._camera=new re,this._scene=new vi,this._scene.fog=new tb(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 Wn(1e3),this._scene.clear()}_objects=[];setupScene(){this._scene.background=new ne(0),this._scene.add(new um(5,10,1118481,1118481));const e=new pm(16777215,1);e.position.set(0,20,0),e.castShadow=!1,this._scene.add(e);const t=new pm(16777215,1);t.position.set(0,-1,0),t.castShadow=!1,this._scene.add(t);const i=new mm(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 s=0;s<100;s++){const r=new pt({color:2236962,metalness:1,roughness:.8});this.isAR&&(r.emissive=new ne(Math.random(),Math.random(),Math.random()),r.emissiveIntensity=Math.random());const a=I.random(0,1)>.5?wr.Sphere:wr.Cube,l=xr.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 c=l.position.distanceTo(this._camera.position)-l.scale.x;c<1&&l.position.multiplyScalar(1+1/c),this._objects.push(l),this._scene.add(l)}}update(e,t){const i=e*4e-4;for(let n=0;n<this._objects.length;n++){const s=this._objects[n];s.position.y+=Math.sin(i+n*.5)*.005,s.rotateY(.002)}}}var pc;(o=>{const e=[];function t(){if(!e?.length)return!1;for(const s of e)s.exportAndOpen();return!0}o.exportAndOpen=t;function i(s){e.push(s)}o.registerExporter=i;function n(s){if(!e)return;const r=e.indexOf(s);r>=0&&e.splice(r,1)}o.unregisterExporter=n})(pc||(pc={}));const Ge=v("debugwebxr"),$_=v("stats");let vg=0;function ek(o){let e=null;const t=o;return t.getAROverlayContainer?e=t.getAROverlayContainer():e=o,e}tk();async function tk(){if(v("debugasap")){let o=globalThis["needle:XRSession"];if(o instanceof Promise){delete globalThis["needle:XRSession"],ue.addContextCreatedCallback(async e=>{if(!o)return;fr(!0);const t=await o;if(t){const i=Z.getDefaultSessionInit("immersive-vr");Z.setSession("immersive-vr",t,i,e.context)}else console.error("NeedleXRSession: ASAP session was rejected");o=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()=>{fr(!0),console.log("Received Session Granted..."),await Wn(100);const o=sessionStorage.getItem("needle_xr_session_mode"),e=sessionStorage.getItem("needle_xr_session_init")??null,t=e?JSON.parse(e):null;let i=null;if(H_()&&(await Wl.start(o||"immersive-vr",t||Z.getDefaultSessionInit("immersive-vr")),await ok(),i=await Wl.handoff()),i)Z.setSession(i.mode,i.session,i.init,z.Current);else if(o&&e){console.log("Session Granted: Restore last session");const n=JSON.parse(e);Z.start(o,n).catch(s=>console.warn(s))}else Z.start("immersive-vr").catch(n=>console.warn("Session Granted failed:",n))},{once:!0})}}function ik(o,e){sessionStorage.setItem("needle_xr_session_mode",o),sessionStorage.setItem("needle_xr_session_init",JSON.stringify(e))}function nk(){sessionStorage.removeItem("needle_xr_session_mode"),sessionStorage.removeItem("needle_xr_session_init")}const wg=new Set;ue.registerCallback(de.ContextCreationStart,async o=>{wg.add(o.context)}),ue.registerCallback(de.ContextCreated,async o=>{wg.delete(o.context);const e=o.context?.domElement.getAttribute("autostart")||null;sk(e)});function H_(){return wg.size>0}function ok(){return new Promise(o=>{const e=Date.now(),t=setInterval(()=>{(!H_()||Date.now()-e>6e4)&&(clearInterval(t),o())},100)})}q.isDesktop()&&A()&&window.addEventListener("keydown",o=>{(o.key==="x"||o.key==="Escape")&&Z.active&&Z.stop()});function sk(o){if(o)switch(o?.toLowerCase()){case"ar":Dn.registerWaitForInteraction(()=>{Z.start("ar")});break}}const qd=Symbol("initial-fov");class Z{static _sync=null;static getXRSync(e){return this._sync||(this._sync=new z_(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=>(Ge&&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=>Z.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 q.isVisionOS()||t.push("hand-tracking"),{optionalFeatures:t};case"immersive-vr":const i=["local-floor","bounded-floor","high-fixed-foveation-level","layers"];return q.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(q.isiOS()){if(e==="ar")if(await this.isARSupported())e="immersive-ar";else return pc.exportAndOpen(),null}else e=="ar"&&(e="immersive-ar");if(A()&&v("debugxrpreroom"))return console.warn("Debug: Starting temporary XR session"),await Wl.start(e,t||Z.getDefaultSessionInit(e)),null;if(this._currentSessionRequest)return console.warn("A XRSession is already being requested"),(Ge||A())&&ye("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=z.Current),i||(i=ue.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 r=this.getDefaultSessionInit(e),a=ek(i.domElement);a&&!q.isQuest()&&(r.domOverlay={root:a},r.optionalFeatures.push("dom-overlay")),t={...r,...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 Wl.stop();const n=e=="immersive-ar"?i.scripts_immersive_ar:i.scripts_immersive_vr;Ge?console.log(`%cRequesting ${e} session`,"font-weight:bold;",t,n):console.log(`%cRequesting ${e} session`,"font-weight:bold;");for(const r of n)r.onBeforeXR&&r.activeAndEnabled&&!r.destroyed&&r.onBeforeXR(e,t);for(const r of this._sessionRequestStartListeners)r({mode:e,init:t});Ge&&Te("Requesting "+e+" session ("+Date.now()+")"),this._currentSessionRequest=navigator?.xr?.requestSession(e,t),this._currentSessionRequestMode=e;const s=await this._currentSessionRequest?.catch(r=>{console.error(r,"Code: "+r.code),r.code===9&&ye("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:"&&ye("XR requires a secure connection (HTTPS)")});this._currentSessionRequest=void 0,this._currentSessionRequestMode=null;for(const r of this._sessionRequestEndListeners)r({mode:e,init:t,newSession:s||null});return s?this.setSession(e,s,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 s=e=="immersive-ar"?n.scripts_immersive_ar:n.scripts_immersive_vr;return this._activeSession=new Z(e,t,n,{scripts:s,controller_added:this._controllerAddedListeners,controller_removed:this._controllerRemovedListeners,init:i}),t.addEventListener("end",this.onEnd),Ge?console.log(`%cStarted ${e} session`,"font-weight:bold;",s):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?(Ge&&console.log("[NeedleXRSession] Stopping XR Session... (new)"),e[this.$_stop_request]=setTimeout(()=>{e.end()})):Ge&&console.warn("[NeedleXRSession] XR Session stop already requested"))}static onEnd=()=>{Ge&&console.log("XR Session ended"),this._activeSession=null};context;get sync(){return Z._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()&&q.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&&Rr(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 D(0,0,0);const t=D(e);return t.x*=-1,t.z*=-1,t.applyQuaternion(ni(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(Rr(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)}Ge&&(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 s of n.results)return this.convertHitTestResult(s);return null}convertHitTestResult(e){const t=this.context.renderer.xr.getReferenceSpace(),i=t&&e.getPose(t);if(i){const n=D(i.transform.position),s=ni(i.transform.orientation),r=this.context.mainCamera;if(r?.parent!==this._cameraRenderParent&&n.applyMatrix4(La),r?.parent){n.applyMatrix4(r.parent.matrixWorld),s.multiply(Gi);const a=be(r.parent);a.premultiply(Gi),s.premultiply(a)}return{hit:e,position:n,quaternion:s}}return null}convertSpace(e){const t=D(e.position);t.applyMatrix4(La);const i=ni(e.orientation);return i.premultiply(Gi),{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){ik(e,n.init),this.session=t,this.mode=e,this.context=i,(Ge||v("console"))&&fr(!0),this._xr_scripts=[...n.scripts],this._xr_update_scripts=this._xr_scripts.filter(s=>typeof s.onUpdateXR=="function"),this._controllerAdded=n.controller_added,this._controllerRemoved=n.controller_removed,To(this.onBefore,we.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(s=>t.requestHitTestSource?.call(t,{space:s})?.then(r=>this._viewerHitTestSource=r).catch(r=>console.error(r))).catch(s=>console.error(s)),this.context.mainCamera&&(this._originalCameraWorldPosition=J(this.context.mainCamera,new b),this._originalCameraWorldRotation=be(this.context.mainCamera,new U),this._originalCameraWorldScale=He(this.context.mainCamera,new b),this._originalCameraParent=this.context.mainCamera.parent,this.context.mainCamera instanceof re&&(this.context.mainCamera[qd]=this.context.mainCamera.fov)),this._defaultRig=new UO,this.context.scene.add(this._defaultRig.gameObject),this.addRig(this._defaultRig);for(let s=0;s<t.inputSources.length;s++){const r=t.inputSources[s];if(!r.handedness){console.warn("Input source in xr session has no handedness - ignoring",s);continue}this.onInputSourceAdded(r)}this.session.addEventListener("end",this.onEnd),this.session.addEventListener("inputsourceschange",s=>{for(const r of s.removed)this.disconnectInputSource(r);for(const r of s.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):Ge&&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 hg(this,e,t);this._newControllers.push(i)};disconnectInputSource(e){const t=(s,r)=>{if(s.inputSource===e){Ge&&console.log("Disconnecting controller",s.index);const a=r.indexOf(s);a>=0&&r.splice(a,1),this.invokeControllerEvent(s,this._controllerRemoved,"removed");const l={xr:this,controller:s,change:"removed"};for(const c of this._xr_scripts)c.onXRControllerRemoved&&c.onXRControllerRemoved(l);s.onDisconnected()}},i=[...this.controllers];for(let s=i.length-1;s>=0;s--){const r=i[s];t(r,this.controllers)}const n=[...this._newControllers];for(let s=n.length-1;s>=0;s--){const r=n[s];t(r,this._newControllers)}}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"),nk(),this.onAfterRender(),this.revertCustomForward(),this._didStart=!1,this._previousCameraParent=null,this.requestedCameraNearPlane=null,ys(this.onBefore,we.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()}),S_({session:this});for(const s of Z._xrEndListeners)s({xr:this});const n=[...this.controllers];for(let s=0;s<n.length;s++)this.disconnectInputSource(n[s].inputSource);this.controllers.length=0,this._newControllers.length=0;for(const s of this._xr_scripts)s?.onLeaveXR?.({xr:this});this.sync?.onExitXR(this),this.context.mainCamera&&(this._originalCameraParent?.add(this.context.mainCamera),this._originalCameraWorldPosition&>(this.context.mainCamera,this._originalCameraWorldPosition),this._originalCameraWorldRotation&&yn(this.context.mainCamera,this._originalCameraWorldRotation),this._originalCameraWorldScale&&Ta(this.context.mainCamera,this._originalCameraWorldScale),this.context.mainCamera instanceof re&&this.context.mainCamera[qd]&&(this.context.mainCamera.fov=this.context.mainCamera[qd],this.context.mainCamera[qd]=0)),this.context.requestSizeUpdate(),this._defaultRig.gameObject.removeFromParent(),fr(!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&&(Ge&&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 s=0;s<n.length;s++){const r=this.context.new_scripts_xr[s];if(!r||r.destroyed||r.supportsXR?.(this.mode)==!1){this.context.new_scripts_xr.splice(s,1);continue}if(!r.activeAndEnabled){this.context.new_scripts_xr.splice(s,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 s=Gt(this.context.scene.children);if(s){const r=s.getSize(D());if(r.length()>0){const a=this._defaultRig.gameObject;a.position.set(s.min.x+r.x*.5,s.min.y,s.max.z+r.z*.5+1.5);const l=s.getCenter(D());l.y=a.position.y,a.lookAt(l)}}}x_({session:this}),vr();for(const s of Z._xrStartListeners)s(i);const n=[...this._xr_scripts];Ge&&console.log("NeedleXRSession start, handle scripts:",n);for(const s of n){if(s.destroyed){this._script_to_remove.push(s);continue}if(!s.activeAndEnabled){this.markInactive(s);continue}this.invokeCallback_EnterXR(s);for(const r of this.controllers)this.invokeCallback_ControllerAdded(s,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 s of n){if(!s.connected){console.warn("New controller is not connected",s);continue}this.controllers.push(s);for(const r of this._xr_scripts){if(r.destroyed){this._script_to_remove.push(r);continue}r.activeAndEnabled!==!1&&this.invokeCallback_ControllerAdded(r,s)}}this.controllers.sort((s,r)=>s.index-r.index)}Ge&&this.context.time.frame%30===0&&this.controllers.length<=0&&this.session.inputSources.length>0&&(fr(!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 s of n)!s.destroyed&&this.running&&s.onLeaveXR?.(i),this.removeScript(s)}this.sync?.onUpdate(this),this.onRenderDebug()};onRenderDebug(){if(Ge)for(const e of this.controllers)e.onRenderDebug();if((Ge||$_)&&this.rig&&(vg++,vg>=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()}`,Ge||$_)for(const s of this.controllers)n+=`
|
|
167
167
|
${s.hand?"hand":"ctrl"} ${s.inputSource.handedness}[${s.index}] con:${s.connected} tr:${s.isTracking} hts:${s.hasHitTestSource?"yes":"no"}`;vg=0,B.DrawLabel(e,n,void 0,1/60*20)}}onBeforeRender=()=>{this.context.mainCamera&&(this.updateFade(this.context.mainCamera),this.requestedCameraNearPlane!==null&&this.context.mainCamera instanceof re&&(this.context.mainCamera.near=this.requestedCameraNearPlane,this.requestedCameraNearPlane=null))};onAfterRender=()=>{if(this.onUpdateFade_PostRender(),q.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:(Ge&&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){Ge&&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 s=this._inactive_scripts.indexOf(e);s>=0&&this._inactive_scripts.splice(s,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 s=t[n];if(s)try{s({xr:this,controller:e,change:i})}catch(r){console.error(r)}}}_camera;_cameraRenderParent=new O().rotateY(Math.PI);_previousCameraParent;_customforward=!0;originalCameraNearPlane;requestedCameraNearPlane=null;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;const t=.001;if(this.rig){const i=He(this.rig.gameObject);e*=i.x}this._camera instanceof re&&Math.abs(this._camera.near-e)>t&&(this.isAR?this.originalCameraNearPlane=this._camera.near:this._camera.near=e,Ge&&console.debug(`Setting camera near plane to ${e} (was ${this.originalCameraNearPlane}) to account for XR rendering scale`))}}}revertCustomForward(){this._camera&&this._previousCameraParent&&this._previousCameraParent.add(this._camera),this._previousCameraParent=null,this._camera instanceof re&&this.originalCameraNearPlane!=null&&(this._camera.near=this.originalCameraNearPlane,this.originalCameraNearPlane=void 0)}_viewerPose;_transformOrientation=new U;_transformPosition=new b;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 N_),this._transition}fadeTransition(){return this._transition||(this._transition=new N_),this._transition.fadeTransition()}updateFade(e){this._transition&&e instanceof re&&this._transition.update(e,this.context.time.deltaTime)}onUpdateFade_PostRender(){this._transition?.remove()}}const xg=v("debugwebxr");class G_{static tryFindAvatarObjects(e,t,i){if(i.head&&i.leftHand&&i.rightHand)return;const n=e.name.toLocaleLowerCase();!i.head&&n.includes("head")&&(xg&&console.log("FOUND AVATAR HEAD",e.name),i.head=new ie("",t,e)),n.includes("hand")&&(!i.leftHand&&n.includes("left")&&(xg&&console.log("FOUND AVATAR LEFT HAND",e.name),i.leftHand=new ie("",t,e)),!i.rightHand&&n.includes("right")&&(xg&&console.log("FOUND AVATAR RIGHT HAND",e.name),i.rightHand=new ie("",t,e)));for(let s=0;s<e.children.length;s++){if(i.head&&i.leftHand&&i.rightHand)return;const r=e.children[s];this.tryFindAvatarObjects(r,t,i)}}}class oe extends ne{alpha=1;get isRGBAColor(){return!0}set a(e){this.alpha=e}get a(){return this.alpha}constructor(e,t,i,n){super(),typeof e=="number"&&typeof t=="number"&&typeof i=="number"?(this.set(e,t,i),this.alpha=typeof n=="number"?n:1):e!==void 0&&(this.set(e),this.alpha=1)}clone(){const e=super.clone();return e.alpha=this.alpha,e}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,"alpha"in e&&typeof e.alpha=="number"?this.alpha=e.alpha:typeof e.a=="number"&&(this.alpha=e.a),this}lerp(e,t){const i=e;return i.alpha!=null&&(this.alpha=I.lerp(this.alpha,i.alpha,t)),super.lerp(e,t)}lerpColors(e,t,i){const n=e,s=t;return n.alpha!=null&&s.alpha!=null&&(this.alpha=I.lerp(n.alpha,s.alpha,i)),super.lerpColors(e,t,i)}multiply(e){const t=e;return t.alpha!=null&&(this.alpha=this.alpha*t.alpha),super.multiply(e)}fromArray(e,t=0){return this.alpha=e[t+3],super.fromArray(e,t)}static fromColorRepresentation(e){if(typeof e=="string"){if(e.trim()==="transparent")return new oe(0,0,0,0);if(e.startsWith("#")&&e.length===9){const t=parseInt(e.slice(1,9),16),i=t>>24&255,n=t>>16&255,s=t>>8&255,r=t>>0&255;return new oe(i/255,n/255,s/255,r/255)}else if(e.startsWith("#")){const t=parseInt(e.slice(1),16),i=t>>16&255,n=t>>8&255,s=t>>0&255;return new oe(i/255,n/255,s/255,1)}else if(e.startsWith("rgba")){const t=e.slice(5,-1).split(",").map(Number);return new oe(t[0]/255,t[1]/255,t[2]/255,t[3])}else if(e.startsWith("rgb")){const t=e.slice(4,-1).split(",").map(Number);return new oe(t[0]/255,t[1]/255,t[2]/255,1)}}else if(Array.isArray(e)){if(e.length===4)return new oe(e[0],e[1],e[2],e[3]);if(e.length===3)return new oe(e[0],e[1],e[2],1);console.error("Invalid color array length. Expected 3 or 4, got "+e.length)}return new oe(e)}}const Lt=new b,q_=new b,X_=new U,rk=v("debuggizmos"),wn=8947848,Sg=32;class B{constructor(){}static enabled=!0;static isGizmo(e){return e[Pg]!==void 0}static setVisible(e){for(const t of Xi.timedObjectsBuffer)t.visible=e}static DrawLabel(e,t,i=.05,n=0,s,r,a){if(!B.enabled)return null;s||(s=wn);const l=Z.active?.rigScale??1,c=Xi.getTextLabel(n,t,i*l,s,r);return a instanceof O&&a.add(c),c.position.x=e.x,c.position.y=e.y,c.position.z=e.z,c}static DrawRay(e,t,i=wn,n=0,s=!0){if(!B.enabled)return;const r=Xi.getLine(n),a=r.geometry.getAttribute("position");a.setXYZ(0,e.x,e.y,e.z),Lt.set(t.x,t.y,t.z).multiplyScalar(999999999),a.setXYZ(1,e.x+Lt.x,e.y+Lt.y,e.z+Lt.z),a.needsUpdate=!0,r.material.depthTest=s,r.material.depthWrite=!1,r.material.fog=!1,xn(r.material,i)}static DrawDirection(e,t,i=wn,n=0,s=!0,r=1){if(!B.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?(Lt.set(0,0,-r),X_.set(t.x,t.y,t.z,t.w),Lt.applyQuaternion(X_)):(Lt.set(t.x,t.y,t.z),Lt.multiplyScalar(r)),l.setXYZ(1,e.x+Lt.x,e.y+Lt.y,e.z+Lt.z),l.needsUpdate=!0,a.material.depthTest=s,a.material.depthWrite=!1,xn(a.material,i)}static DrawLine(e,t,i=wn,n=0,s=!0){if(!B.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.depthTest=s,r.material.depthWrite=!1,r.material.fog=!1,xn(r.material,i)}static DrawCircle(e,t,i,n=wn,s=0,r=!0){if(!B.enabled)return;const a=Xi.getCircle(s);a.position.set(e.x,e.y,e.z),a.scale.set(i,i,i),a.quaternion.setFromUnitVectors(this._up,Lt.set(t.x,t.y,t.z).normalize()),a.material.depthTest=r,a.material.depthWrite=!1,a.material.fog=!1,xn(a.material,n)}static DrawWireSphere(e,t,i=wn,n=0,s=!0){if(!B.enabled)return;const r=Xi.getSphere(t,n,!0);mr(r,e.x,e.y,e.z),r.material.depthTest=s,r.material.depthWrite=!1,r.material.fog=!1,xn(r.material,i)}static DrawSphere(e,t,i=wn,n=0,s=!0){if(!B.enabled)return;const r=Xi.getSphere(t,n,!1);mr(r,e.x,e.y,e.z),r.material.depthTest=s,r.material.depthWrite=!1,xn(r.material,i)}static DrawWireBox(e,t,i=wn,n=0,s=!0,r=void 0){if(!B.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.depthTest=s,a.material.wireframe=!0,a.material.depthWrite=!1,a.material.fog=!1,xn(a.material,i)}static DrawWireBox3(e,t=wn,i=0,n=!0){if(!B.enabled)return;const s=Xi.getBox(i);s.position.copy(e.getCenter(Lt)),s.scale.copy(e.getSize(Lt)),s.material.depthTest=n,s.material.wireframe=!0,s.material.depthWrite=!1,s.material.fog=!1,xn(s.material,t)}static _up=new b(0,1,0);static DrawArrow(e,t,i=wn,n=0,s=!0,r=!1){if(!B.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),Lt.set(t.x,t.y,t.z).sub(q_.set(e.x,e.y,e.z)).normalize());const l=Lt.set(t.x,t.y,t.z).sub(q_.set(e.x,e.y,e.z)).length()*.1;a.scale.set(l,l,l),a.material.depthTest=s,a.material.wireframe=r,xn(a.material,i),this.DrawLine(e,t,i,n,s)}static DrawWireMesh(e){const t=Xi.getMesh(e.duration??0);"mesh"in e?(t.geometry=e.mesh.geometry,t.matrixWorld.copy(e.mesh.matrixWorld)):(t.geometry=e.geometry,t.matrixWorld.copy(e.matrix)),t.matrixAutoUpdate=!1,t.matrixWorldAutoUpdate=!1,t.material.depthTest=e.depthTest??!0,t.material.wireframe=!0,xn(t.material,e.color??wn)}}const ak=new Sa(1,1,1);function Cg(o=null){const e=new ne(o??14540253),t=new kS(ak);return new ib(t,new gm({color:e}))}function xn(o,e){if(Array.isArray(o)){for(const i of o)xn(i,e);return}const t=e instanceof oe?e.a:1;o.color.set(e),o.opacity=t,o.transparent=t<1}const Pg=Symbol("GizmoCache");class Xi{static familyName="needle-gizmos";static ensureFont(){let e=Ce.FontLibrary.getFontFamily(this.familyName);e||(e=Ce.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",()=>{Ce.update()}))}static getTextLabel(e,t,i,n,s){this.ensureFont();let r=this.textLabelCache.pop(),a=1;s&&typeof s=="string"&&s?.length>=8&&s.startsWith("#")?(a=parseInt(s.substring(7),16)/255,s=s.substring(0,7),rk&&console.log(s,a)):typeof s=="object"&&s.a!==void 0&&(a=s.a);const l={boxSizing:"border-box",fontFamily:this.familyName,width:"auto",fontSize:i,color:n,lineHeight:1,backgroundColor:s??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 kb(l);const c=this,h=r;h.setText=function(d){this.set({textContent:d}),c.tmuiNeedsUpdate=!0}}return this.tmuiNeedsUpdate=!0,this.registerTimedObject(z.Current,r,e,this.textLabelCache),r}static getBox(e){let t=this.boxesCache.pop();if(!t){const i=new Sa(1,1,1);t=new G(i)}return this.registerTimedObject(z.Current,t,e,this.boxesCache),t}static getLine(e){let t=this.linesCache.pop();if(!t){t=new Ca;let i=t.geometry.getAttribute("position");i||(i=new mt(new Float32Array(6),3),t.geometry.setAttribute("position",i))}return t.frustumCulled=!1,this.registerTimedObject(z.Current,t,e,this.linesCache),t}static getCircle(e){let t=this.circlesCache.pop();if(!t){t=new Ca;let i=t.geometry.getAttribute("position");if(!i){i=new mt(new Float32Array(Sg*3),3),t.geometry.setAttribute("position",i);const n=D(0,1,0),s=D(0,0,1),r=D(s);r.cross(n).normalize();const a=D(r),l=Math.PI*2/(Sg-1);for(let c=0;c<Sg+1;c++){const h=l*c;n.copy(a).multiplyScalar(Math.cos(h)*1),r.copy(s).multiplyScalar(Math.sin(h)*1);const d=n.add(r);i.setXYZ(c,d.x,d.y,d.z)}}}return t.frustumCulled=!1,this.registerTimedObject(z.Current,t,e,this.circlesCache),t}static getSphere(e,t,i){let n=this.spheresCache.pop();return n||(n=new G(new fd(1,8,8))),n.scale.set(e,e,e),n.material.wireframe=i,this.registerTimedObject(z.Current,n,t,this.spheresCache),n}static getArrowHead(e){let t=this.arrowHeadsCache.pop();return t||(t=new G(new eb(0,.5,1,8))),this.registerTimedObject(z.Current,t,e,this.arrowHeadsCache),t}static getMesh(e){let t=this.mesh.pop();return t||(t=new G,t.material=new xe),this.registerTimedObject(z.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 s=this.contextBeforeRenderCallbacks.get(e),r=this.contextPostRenderCallbacks.get(e);if(s){if(e.pre_render_callbacks[e.pre_render_callbacks.length-1]!==s){const a=e.pre_render_callbacks.indexOf(s);a>=0&&e.pre_render_callbacks.splice(a,1),e.pre_render_callbacks.push(s)}}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[Pg]=n,t.castShadow=!1,t.receiveShadow=!1,t.isGizmo=!0,this.timedObjectsBuffer.push(t),this.timesBuffer.push(z.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,Ce.update());for(let i=0;i<t.length;i++){const n=t[i];if(e.mainCamera&&n instanceof Ce.MeshUIBaseElement){if(Rr(n))continue;const s=e.isInVR,r=!1,a=!s;nc(n,e.mainCamera,r,a)}}}static onPostRender(e,t,i){const n=e.time.realtimeSinceStartup;for(let s=t.length-1;s>=0;s--){const r=t[s];n>=i[s]-1e-6&&(t.splice(s,1),i.splice(s,1),r.removeFromParent(),Rr(r)!=!0&&r[Pg].push(r))}}}const qt=v("debugphysics"),Q_=new ds;class bs{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 ee),this.screenPoint.x=e/window.innerWidth*2-1,this.screenPoint.y=-(t/window.innerHeight)*2+1}setLayer(e){Q_.set(e),this.layerMask=Q_}setMask(e){this.layerMask||(this.layerMask=new ds);const t=this.layerMask;t?t.mask=e:this.layerMask=e}}class Og{distance;point;object;constructor(e,t,i){this.object=e,this.distance=t,this.point=i}}class $l{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 yd;defaultRaycastOptions=new bs;targetBuffer=new Array(1);defaultThresholds={Mesh:{},Line:{threshold:-1},LOD:{},Points:{threshold:0},Sprite:{}};sphereResults=new Array;sphereMask=new ds;sphere=new bd;sphereOverlap(e,t,i=!0,n=!1,s=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,s);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){qt&&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 qt&&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 MS&&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 s=e.results;this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),s||(this.defaultRaycastOptions.results||(this.defaultRaycastOptions.results=new Array),s=this.defaultRaycastOptions.results),e.layerMask!==void 0?e.layerMask instanceof ds?i.layers.mask=e.layerMask.mask:i.layers.mask=e.layerMask:(i.layers.enableAll(),i.layers.disable(2)),qt&&console.time("raycast"),s.length=0,$l._raycasting++,this.intersect(this.raycaster,n,s,e),s.sort((a,l)=>a.distance-l.distance);const r=e.ignore;return r!==void 0&&r.length>0&&(s=s.filter(a=>!r.includes(a.object))),$l._raycasting--,qt&&(console.timeEnd("raycast"),console.warn("#"+this.context.time.frame+", hits:",s?.length?[...s]:"nothing"),performance.mark("raycast.end"),performance.measure("raycast","raycast.start","raycast.end")),s}intersect(e,t,i,n){for(const s of t){if(!s||s.visible===!1||B.isGizmo(s)||n.lineThreshold!==void 0&&n.lineThreshold<0&&s instanceof Ca)continue;let r=!0;const a=s,l=a.geometry;if(s.raycastAllowed===!1&&(r=!1),r&&n.testObject){const c=n.testObject?.(s);if(c===!1)continue;c==="continue in children"&&(r=!1)}else r&&(l&&Y_(l)||(r=!1));if(r){const c=i.length,h=s.raycastPreference||"lod";let d=h!=="bounds";if(n.precise===!1&&(d=!1),l&&(d||=l.getAttribute("position")?.array?.length<64),a instanceof ka&&(d=!1),h==="lod"){const p=mb(s);p&&(a.geometry=p)}if(!d&&ck(a,e,i)||(n.useAcceleratedRaycast!==!1?Qd.runMeshBVHRaycast(e,a,i,this.context,n):e.intersectObject(a,!1,i)),a.geometry=l,qt&&i.length!=c){const p=i[i.length-1];B.DrawWireSphere(p.point,.1,7798784,1,!1),B.DrawWireMesh({mesh:s,depthTest:!1,duration:.2,color:7798784})}}n.recursive!==!1&&this.intersect(e,s.children,i,n)}return i}tempBoundingBox=new wi;intersectSphere(e,t,i,n,s,r,a,l){let c=e&&e.isMesh&&e.layers.test(n)&&!B.isGizmo(e);c&&=e.visible,c&&=!(e instanceof Ca),c&&=!(e instanceof ka);const h=e,d=h.geometry;if(c&&l){const p=l(e);if(p===!1)return;p==="continue in children"&&(c=!1)}if(d&&Y_(d)||(c=!1),c){if(a){const p=this.sphere;p.center.copy(t),p.radius=i;const m=s.length;if(Qd.runMeshBVHRaycast(this.sphere,h,s,this.context,{}),m!=s.length&&!r)return}else if(d.boundingBox||d.computeBoundingBox(),d.boundingBox){h.matrixWorldNeedsUpdate&&h.updateWorldMatrix(!1,!1);const p=this.tempBoundingBox.copy(d.boundingBox).applyMatrix4(h.matrixWorld),m=this.sphere;if(m.center.copy(t),m.radius=i,m.intersectsBox(p)){const f=J(e),g=f.distanceTo(m.center),y=new Og(e,g,f);if(s.push(y),!r)return}}}if(e.children)for(const p of e.children){const m=s.length;if(this.intersectSphere(p,t,i,n,s,r,a,l),m!=s.length&&!r)return}}}function Y_(o){return!(o.index&&o.index.array.length<3)}const Sr=new bd,Xd=new hr,lk=new J0;function ck(o,e,t){const i=o._computeIntersections;if(!i)return!1;let n=o["_computeIntersections:Needle"];return n||(n=o["_computeIntersections:Needle"]=function(s,r,a){const l=this,c=l.geometry.boundingSphere;if(c){if(l instanceof ka){Xd.setFromNormalAndCoplanarPoint(D(0,1,0),D(0,-l.position.y,0)),Xd.applyMatrix4(l.matrixWorld,lk);const d=s.ray.intersectPlane(Xd,D());if(d){Sr.copy(c),Sr.applyMatrix4(l.matrixWorld);const p=D(d).sub(s.ray.origin).length(),m=Sr.radius*.5;p<m&&r.push({distance:p,point:d,object:l,normal:Xd.normal.clone()})}return}Sr.copy(c),Sr.applyMatrix4(l.matrixWorld);const h=s.ray.intersectSphere(Sr,D());if(h){const d=D(h).sub(s.ray.origin),p=d.length();if(p>Sr.radius){const m=d.clone().normalize();r.push({distance:p,point:h,object:l,normal:m})}}}}),o._computeIntersections=n,e.intersectObject(o,!1,t),o._computeIntersections=i,!0}var Qd;(o=>{let e=0;function t(w,P,R,k,j){if(!P.geometry||!P.geometry.hasAttribute("position"))return!1;const L=P.geometry;if(P?.isSkinnedMesh){const W=P,N=W.bvhNeedsUpdate;if(!W.staticGenerator)l(),r&&(W.staticGenerator=new r(P),W.staticGenerator.applyWorldTransforms=!1,W.staticGeometry=W.staticGenerator.generate(),L.boundsTree=a?.call(W.staticGeometry),W.staticGeometryLastUpdate=performance.now()+Math.random()*200,W.bvhNeedsUpdate=!0);else if(L.boundsTree&&(W.autoUpdateMeshBvhInterval!==void 0&&W.autoUpdateMeshBvhInterval>=0||N===!0)){const H=performance.now(),X=H-W.staticGeometryLastUpdate,T=W.autoUpdateMeshBvhInterval??100;(N||X>T)&&(qt&&console.warn(`Physics: updating skinned mesh bvh for ${P.name} after ${X.toFixed(2)}ms`),W.bvhNeedsUpdate=!1,W.staticGeometryLastUpdate=H,W.staticGenerator?.generate(W.staticGeometry),L.boundsTree.refit())}}else if(!L.boundsTree){h||_();let W=!0;if((k.xr||L[f]===!1||L.getAttribute("position")?.isInterleavedBufferAttribute||L.index&&L.index?.isInterleavedBufferAttribute||e>10)&&(W=!1),W&&p){if(L[m]===void 0){let N=null;if(y.length>0){const H=y.shift();H&&!H.running&&(N=H)}if(!N&&g.length<3)try{N=new p,g.push(N)}catch(H){H instanceof DOMException&&H.name==="SecurityError"?(console.warn("Failed to create MeshBVH worker, falling back to main thread generation. This can happen when running from file://, if the browser does not support workers or if the browser is blocking workers for other reasons."),console.debug(H),e+=10):(console.error("Failed to create MeshBVH worker"),console.debug(H)),e++}if(N!=null&&!N.running){const H=P.name;qt&&console.log("<<<< worker start",H,N),L[m]="queued",performance.mark("bvh.create.start");const X=L.clone();try{N.generate(X).then(T=>{L[m]="done",L.boundsTree=T}).catch(T=>{L[m]="failed - "+T?.message,L[f]=!1,qt&&console.error("Failed to generate mesh bvh on worker",T)}).finally(()=>{qt&&console.log(">>>>> worker done",H,{hasBoundsTre:L.boundsTree!=null}),y.push(N),X.dispose(),performance.mark("bvh.create.end"),performance.measure("bvh.create (worker)","bvh.create.start","bvh.create.end")})}catch(T){console.error("Failed to generate mesh bvh on worker",T)}}else qt&&console.warn("No worker available")}}else(!d||!W)&&(l(),s&&(performance.mark("bvh.create.start"),L.boundsTree=new s(L),performance.mark("bvh.create.end"),performance.measure("bvh.create","bvh.create.start","bvh.create.end")))}if(w instanceof yd){const W=w,N=P.raycast;if(L.boundsTree)l(),n&&(P.acceleratedRaycast||(P.acceleratedRaycast=n.bind(P),qt&&console.debug(`Physics: bind acceleratedRaycast fn to "${P.name}"`)),P.raycast=P.acceleratedRaycast);else if(qt&&console.warn("No bounds tree found for mesh",P.name,{workerTask:L[m],hasAcceleratedRaycast:n!=null}),j.allowSlowRaycastFallback===!1&&(L.getAttribute("position")?.array?.length??0)>2e3)return qt&&console.warn("Skipping raycast because no bounds tree is available and allowSlowRaycastFallback is false"),!1;const H=W.firstHitOnly;return W.firstHitOnly=!1,W.intersectObject(P,!1,R),W.firstHitOnly=H,P.raycast=N,!0}else if(w instanceof bd){const W=L.boundsTree;if(W){const N=w;if(c.copy(P.matrixWorld).invert(),N.applyMatrix4(c),W.intersectsSphere(N)){const H=J(P),X=H.distanceTo(N.center),T=new Og(P,X,H);R.push(T)}}return!0}return!1}o.runMeshBVHRaycast=t;let i=!1,n=null,s=null,r=null,a=null;function l(){i||(i=!0,import("./vendor-CsyK1CFs.min.js").then(w=>w.index$1).then(w=>{n=w.acceleratedRaycast,s=w.MeshBVH,r=w.StaticGeometryGenerator,a=w.computeBoundsTree}).catch(w=>{(qt||A())&&console.error("Failed to load BVH library...",w.message)}))}const c=new K;let h=!1,d=!1,p=null;const m=Symbol("Needle:MeshBVH-Worker"),f=Symbol("Needle:MeshBVH-CanUseWorker"),g=[],y=[];function _(){h=!0,d=!0,Promise.resolve().then(()=>uL).then(w=>{p=w.GenerateMeshBVHWorker}).catch(w=>{qt||A()?console.warn("Failed to setup mesh bvh worker"):console.debug("Failed to setup mesh bvh worker",w)}).finally(()=>{d=!1})}})(Qd||(Qd={}));const Z_=Symbol("gltf-loader-internal-usage-tracker"),hk=v("debugusers");class Hl{get name(){return"NEEDLE_internal_usage_tracker"}static isLoading(e){return Hl._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(){Hl._loadingProcesses++;const e=this,t=this._getDependency;return this.parser.getDependency=function(i,n){const s=t.call(this,i,n);return s.then(r=>(r&&(e._loadedObjects.add(r),r[Z_]=e._loadingId),r)),s},null}afterRoot(e){Hl._loadingProcesses--,this.parser.getDependency=this._getDependency;for(const t of this._loadedObjects)delete t[Z_],t instanceof O&&(t.parent||t instanceof G&&setTimeout(()=>{hk&&console.warn("> GLTF LOADER: Mesh not used in scene!",t),t.material=null,t.geometry=null},1e3));return null}}class K_{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:
|
|
168
168
|
`+i.src),e.preventDefault())}})}}const Yd=v("trackresources");function J_(){return Yd==="dispose"}let Cr=!0;Yd===0&&(Cr=!1);function dk(o){Cr=o}function ev(){return Cr}const tv=Symbol("disposable");function iv(o,e){o&&(o[tv]=e,Pr&&console.warn("Set disposable",e,o))}const nv=Symbol("disposed");function uk(o){return o[nv]===!0}function Pe(o){if(o){if(o[tv]===!1){Pr&&console.warn("Object is marked as not disposable",o);return}if(typeof o=="object"&&(o[nv]=!0),o instanceof vi)Pe(o.environment),Pe(o.background),Pe(o.customDepthMaterial),Pe(o.customDistanceMaterial);else if(o instanceof us)Pe(o.geometry),Pe(o.material),Pe(o.skeleton),Pe(o.bindMatrix),Pe(o.bindMatrixInverse),Pe(o.customDepthMaterial),Pe(o.customDistanceMaterial),o.visible=!1;else if(o instanceof G)Pe(o.geometry),Pe(o.material),Pe(o.customDepthMaterial),Pe(o.customDistanceMaterial),o.visible=!1;else if(o instanceof O)o.visible=!1;else if(o instanceof gn){Fa(o);for(const e of Object.keys(o.attributes)){const t=o.attributes[e];Pe(t)}}else if(o instanceof mt||o instanceof nb)Pr&&console.warn("BufferAttribute dispose not supported",o.count);else if(o instanceof Array)for(const e of o)e instanceof ve&&Pe(e);else if(o instanceof ve){Fa(o);for(const t of Object.keys(o)){const i=o[t];i instanceof Le&&Pe(i)}const e=o.uniforms;if(e)for(const t of Object.keys(e)){const i=e[t];i instanceof Le?Pe(i):i instanceof Wi&&Pe(i.value)}}else o instanceof Le?(Fa(o),Fa(o.source),o.source?.data instanceof ImageBitmap&&Fa(o.source.data)):o instanceof RS?(Fa(o.boneTexture),o.boneTexture=null):o instanceof TS||!(o instanceof O)&&Pr&&console.warn("Unknown object type",o)}}function Fa(o){o&&((Pr||J_()||Yd)&&console.warn("\u{1F9E8} FREE",o),o instanceof ImageBitmap||"dispose"in o&&typeof o.dispose=="function"&&o.dispose())}function pk(o){}const mk=new Set;function kg(o,e,t=null,i){if(i||(i=mk,i.clear()),!o)return i;const n=o[mc];if(n)for(const s of n)i.has(s)||t?.call(null,s)!==!1&&(i.add(s),e&&kg(s,!0,t,i));return i}function gk(o){return o[gc]}const Pr=v("debugresourceusers")||v("debugmemory"),mc=Symbol("needle-resource-users"),gc=Symbol("needle-resource-users-count");function Xt(o,e){Fd(o,e,function(t,i){Cr&&!$l.raycasting&&(Zd(mc,this,t,!1),Zd(mc,this,i,!0))})}Cr&&(Xt(G.prototype,"material"),Xt(G.prototype,"geometry"),Xt(ve.prototype,"map"),Xt(ve.prototype,"bumpMap"),Xt(ve.prototype,"alphaMap"),Xt(ve.prototype,"normalMap"),Xt(ve.prototype,"displacementMap"),Xt(ve.prototype,"roughnessMap"),Xt(ve.prototype,"metalnessMap"),Xt(ve.prototype,"emissiveMap"),Xt(ve.prototype,"specularMap"),Xt(ve.prototype,"envMap"),Xt(ve.prototype,"lightMap"),Xt(ve.prototype,"aoMap"),Xt(ve.prototype,"gradientMap"));function fk(o){if(Cr===!1)return;const e=o[mc];if(e)for(const t of e)Zd(mc,t,o,!1)}Cr&&Fd(ve.prototype,"dispose",function(){fk(this)});let Mg=0;function Zd(o,e,t,i){if(Mg>0)return;if(Array.isArray(t)){for(const s of t)Zd(o,e,s,i);return}if(!t)return;let n=t[o];if(n||(n=new Set),i){if(e&&!n.has(e)){n.add(e);let s=t[gc]||0;s+=1,t[gc]=s,Pr&&console.warn(`\u{1F7E2} Added user of "${t.type}"`,e,t,s,"users:",n)}}else if(e&&n.has(e)){n.delete(e);let s=t[gc]||0;s>0&&(s-=1,t[gc]=s),Pr&&console.warn(`\u{1F534} Removed user of "${t.type}"`,e,t,s,"users:",n),s<=0&&(Hl.isLoading(t)||(Yd&&console.warn(`\u{1F534} Removed all user of "${t.type}"`,t),J_()&&Pe(t)))}t[o]=n}try{Fd(cr.prototype,"render",function(){Mg++},function(){Mg--})}catch(o){console.warn("Could not wrap WebGLRenderer.render",o)}const ov=v("debugcomponentevents");class Kd{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),ov&&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(ov&&console.log("Dispatching event "+e,i),!!i)for(const n of i)n(t)}}const fc=Symbol("NEEDLE_NEED_UPDATE_INSTANCE"),sv=Symbol("isUsingInstancing"),rv=Symbol("instancingRenderer"),yc=Symbol("instancingAutoUpdateBounds");class hn{static isUsingInstancing(e){return e[sv]===!0}static getRenderer(e){return e[rv]||null}setAutoUpdateBounds(e,t){const i=hn.getRenderer(e);i&&(i[yc]=t)}static markDirty(e,t=!0){if(e&&(this.isUsingInstancing(e)&&(e[fc]=!0,e.matrixWorldNeedsUpdate=!0),t))for(const i of e.children)hn.markDirty(i,!0)}}var bc;(o=>{o.experimentalSmartHierarchyUpdate=!1})(bc||(bc={}));function Ua(o,e){try{e||o()}catch(t){return console.error(t),!1}return!0}const Rg=v("debugnewscripts"),yk=v("debughierarchy"),Ae=[];function bk(){return Ae.length>0}function Jd(o){if(Rg&&console.log("Register new components",o.new_scripts.length,[...o.new_scripts],o.alias?"element: "+o.alias:o.hash,o),o.new_scripts_pre_setup_callbacks.length>0){for(const e of o.new_scripts_pre_setup_callbacks)e&&e();o.new_scripts_pre_setup_callbacks.length=0}if(!(o.new_scripts.length<=0)){Ae.length=0,o.new_scripts.length>0&&Ae.push(...o.new_scripts),o.new_scripts.length=0;for(let e=0;e<Ae.length;e++)try{const t=Ae[e];if(t.isComponent!==!0){(A()||Rg)&&console.error(`Registered script is not a Needle Engine component.
|
|
169
169
|
The script will be ignored. Please make sure your component extends "Behaviour" imported from "@needle-tools/engine"
|
|
@@ -1272,7 +1272,7 @@ ${r.join(`
|
|
|
1272
1272
|
`)}`:""}
|
|
1273
1273
|
}`}function Nx(o){return`(${o.r}, ${o.g}, ${o.b})`}function Vx(o){return`(${o.x}, ${o.y})`}const dy=[1023,33777,33778,33779,35842,35843,37496,37808,37809,37810,37811,37812,37813,37814,37815,37816,37817,37818,37819,37820,37821,36492];v("debugusdz");class At{static global_id=0;id;trigger;action;exclusive=!1;makeExclusive(e){return this.exclusive=e,this}constructor(e,t,i){this.id="Behavior_"+Ai(e)+"_"+At.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 s=0;s<this.trigger.length;s++){const r=this.trigger[s];n+="<"+r.id+">",s+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 s of this.trigger)s.writeTo(t,i),i.appendLine();else this.trigger.writeTo(t,i);i.appendLine(),this.action.writeTo(t,i),i.closeBlock()}}const pl=new Set;function uy(o,e){let t="";if(Array.isArray(o)){pl.clear();let i="[ ";for(let n=0;n<o.length;n++){let s=o[n];if(!s){console.warn("Invalid target object in behavior",o+". Is the object exported?");continue}if(typeof s=="string"){if(pl.has(s))continue;i+=s,pl.add(s)}else if(typeof s=="object"){if(s.isObject3D&&(s=e.findById(s.uuid),!s)){console.warn("Invalid target object in behavior",o+". Is the object exported?");continue}const r=s.getPath?.call(s);if(pl.has(r))continue;i+=r,pl.add(r)}n+1<o.length&&(i+=", ")}i+=" ]",t=i,pl.clear()}else if(typeof o=="object"){const i=o;if(i.isObject3D&&(o=e.findById(i.uuid)),!o)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=o.getPath?.call(o)}return t}class nr{static global_id=0;id;targetId;tokenId;type;distance;constructor(e,t){e&&(this.targetId=e),t?this.id=t:this.id="Trigger_"+nr.global_id++}writeTo(e,t){t.beginBlock(`def Preliminary_Trigger "${this.id}"`),this.targetId&&(typeof this.targetId!="string"&&(this.targetId=uy(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 Wx(o,e={direct:!0,indirect:!0}){const t=nt.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"')},o.add(t)}class Ft{static __sceneStartTrigger;static sceneStartTrigger(){if(this.__sceneStartTrigger!==void 0)return this.__sceneStartTrigger;const e=new nr(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 nr(e);if(Array.isArray(e)&&e.length>1)for(const n of e)n instanceof nt&&Wx(n,t);else e instanceof nt&&Wx(e,t);return i.tokenId="TapGesture",i}static isTapTrigger(e){return e?.tokenId==="TapGesture"}static proximityToCameraTrigger(e,t){const i=new nr(e);return i.tokenId="ProximityToCamera",i.distance=t,i}}class Hr{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 _i{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 _i,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+="_"+_i.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=uy(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=uy(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 pn{x=0;y=0;z=0;constructor(e,t,i){this.x=e,this.y=t,this.z=i}static get up(){return new pn(0,1,0)}static get right(){return new pn(1,0,0)}static get forward(){return new pn(0,0,1)}static get back(){return new pn(0,0,-1)}static get zero(){return new pn(0,0,0)}}class ge{static sequence(...e){return new Hr("Group_"+Hr.getId(),e).makeSequence()}static parallel(...e){return new Hr("Group_"+Hr.getId(),e).makeParallel()}static fadeAction(e,t,i){const n=new _i(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 s=new _i(e);s.tokenId="StartAnimation";const r=t.start,a=t.duration,l=t.speed,c=t.clipName;if(s.comment=`Animation: ${c}, start=${r*60}, length=${a*60}, end=${(r+a)*60}`,s.animationName=c,s.start=r,s.duration=a,s.animationSpeed=l,s.reversed=i,s.pingPong=n,s.multiplePerformOperation="allow",i&&(s.start-=a),n){s.pingPong=!1;const h=s.clone();return h.reversed=!i,h.start=s.start,h.reversed&&(h.start-=a),ge.sequence(s,h)}return s}static waitAction(e){const t=new _i;return t.tokenId="Wait",t.duration=e,t.motionType=void 0,t}static lookAtCameraAction(e,t,i,n){const s=new _i(e);return s.tokenId="LookAtCamera",s.duration=t===void 0?9999999999999:t,s.front=i??pn.forward,s.up=n??pn.up,s}static emphasize(e,t,i="bounce",n=1,s="basic"){const r=new _i(e);return r.tokenId="Emphasize",r.duration=t,r.style=s??"basic",r.motionType=i,r.moveDistance=n,r}static transformAction(e,t,i,n,s="inout"){const r=new _i(e);return r.tokenId="Transform",r.duration=i,r.duration=Math.max(1e-6,i),r.type=n,r.easeType=i>0?s:"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,s="spatial"){const r=new _i(e);return r.tokenId="Audio",r.type=i,r.audio=t,r.gain=n,r.auralMode=s,r.multiplePerformOperation="allow",r}static impulseAction(e,t){const i=new _i(e);return i.tokenId="Impulse",i.velocity=t,i}}class rE{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 py extends rE{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||nt.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=ge.fadeAction(this.object,0,!0),this._enableAction)}disable(){return this._disableAction?this._disableAction:(this._disableAction=ge.fadeAction(this.object,0,!1),this._disableAction)}}class $x{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 so=v("debugusdzanimation"),my=v("debugusdzanimationserialization");class lr{_start;get start(){return this._start===void 0&&(this._start=this.ext.getStartTimeByClip(this.clip)),this._start}get duration(){return this.clip?.duration??Ne.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=Pa.parseTrackName(t.name);let n=Pa.findNode(this.root,i.nodeName);if(n)if(!e)e=n;else{if(n===e||lr.isDescendantOf(e,n))continue;if(!lr.isDescendantOf(n,e)){for(;!lr.isDescendantOf(n,e)&&n.parent;)n=n.parent;lr.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 Ne{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=Ne.restPoseClipDuration,i&&i.tracks){const s=Math.max(...i.tracks.map(r=>r.times[r.times.length-1]));s!==this.duration&&(console.warn("USDZExporter: Animation clip duration does not match the maximum time value in the tracks.",i,s,this.duration),this.duration=s)}const n=x.getComponent(e,yt);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 \u2013 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()&&ye("[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,s=this.rot?.times,r=this.scale?.times,a=[];if(e&&n)for(const l of n)a.push(l);if(t&&s)for(const l of s)a.push(l);if(i&&r)for(const l of r)a.push(l);return a.includes(0)||a.push(0),a.sort((l,c)=>l-c),[...new Set(a)]}*getValues(e,t=!0,i=!0,n=!0){const s=new b,r=new U,a=new b(1,1,1),l=this.target,c=t?this.pos?.createInterpolant():void 0,h=i?this.rot?.createInterpolant():void 0,d=n?this.scale?.createInterpolant():void 0;c||s.set(l.position.x,l.position.y,l.position.z),h||r.set(l.quaternion.x,l.quaternion.y,l.quaternion.z,l.quaternion.w),d||a.set(l.scale.x,l.scale.y,l.scale.z),c&&c.valueSize!==3&&(c.valueSize=3),h&&h.valueSize!==4&&(h.valueSize=4),d&&d.valueSize!==3&&(d.valueSize=3);const p=0;for(let m=0-p;m<e.length+p;m++){let f=0,g=0;if(m<0?(f=e[0],g=f-Ne.animationDurationPadding/2+1/60):m>=e.length?(f=e[e.length-1],g=f+Ne.animationDurationPadding/2-1/60):(f=e[m],g=f),c){const y=c.evaluate(f);s.set(y[0],y[1],y[2])}if(h){const y=h.evaluate(f);r.set(y[0],y[1],y[2],y[3])}if(d){const y=d.evaluate(f);a.set(y[0],y[1],y[2])}if(this.useRootMotion&&l===this.root){const y=new K;y.compose(s,r,a),y.multiply(l.matrix),y.decompose(s,r,a)}yield{time:g,translation:s,rotation:r,scale:a,index:m}}}}class sp{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:(Ne.restPoseClipDuration+Ne.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 \u2013 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);so&&console.log("registerAnimation",e,t);const n=this.injectRestPoses?1:0,s=(this.rootToRegisteredClip.get(e)?.length??0)+n,r=this.rootTargetMap.get(e),a=new Set(r);if(t&&t.tracks)for(const c of t.tracks){const h=Pa.parseTrackName(c.name),d=Pa.findNode(e,h.nodeName);if(!d){console.warn("no object found for track",c.name,"using "+e.name+" instead");continue}this.dict.has(d)||this.dict.set(d,[]);const p=this.dict.get(d);if(!p){console.warn("no transform data found for target ",d,"at slot "+s+", this is likely a bug");continue}a.delete(d),this.injectRestPoses&&!p[0]&&(console.log("Injecting rest pose",d,t,"at slot",s),p[0]=new Ne(null,d,null));let m=p[s];m||(m=new Ne(e,d,t),p[s]=m),m.addTrack(c),r?.includes(d)||r?.push(d)}so&&console.log("Unregistered nodes for this clip",a,"clip",t,"at slot",s,"for root",e,"targets",r);for(const c of a){const h=this.dict.get(c);if(!h)continue;if(this.injectRestPoses&&!h[0]){console.warn("Adding rest pose for ",c,t,"at slot",s,"This is likely a bug, should have been added earlier.");const p=new Ne(null,c,null);h[0]=p}let d=h[s];d||(so&&console.log("Adding padding clip for ",c,t,"at slot",s),d=new Ne(e,c,t),h[s]=d)}const l=new lr(this,e,t);if(this.rootAndClipToRegisteredAnimationMap.set(i,l),so&&console.log({root:e,clip:t,info:l}),t){const c=this.rootToRegisteredClip.get(e);if(c?c.push(t):this.rootToRegisteredClip.set(e,[t]),!this.clipToStartTime.get(t)){this.lastClipEndTime==null&&(this.lastClipEndTime=Ne.restPoseClipDuration);let h=this.lastClipEndTime+Ne.animationDurationPadding,d=h+t.duration;const p=Math.round(h*60)/60,m=Math.round(d*60)/60;Math.abs(p-h)<.01&&(h=p),Math.abs(m-d)<.01&&(d=m),h=Math.ceil(h),d=h+t.duration,this.clipToStartTime.set(t,h),this.lastClipEndTime=d}}return l}onAfterHierarchy(e){so&&console.log("Animation clips per animation target node",this.dict)}onAfterBuildDocument(e){so&&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 s=[];for(const r of i){const a=this.dict.get(r);if(!a){console.error("No data found for target on USDZ export \u2013 please report a bug!",r);continue}n===void 0&&(n=a?.length),n!==a?.length&&console.error("Different array lengths for targets \u2013 please report a bug!",a);for(let l=0;l<a.length;l++){let c=a[l];if(!c){const d=l-(this.injectRestPoses?1:0);a[l]=new Ne(null,r,this.rootToRegisteredClip.get(t)[d]),c=a[l]}const h=c.getDuration();if(s[l]===void 0)s[l]=h;else if(s[l]!==h){console.error("Error during UDSZ export: Encountered different animation durations for animated targets. Please report a bug!",{datas:a,target:r}),s[l]=h;continue}}}}for(const t of this.serializers){const i=t.model?.parent,n=i?.isDynamic===!0;my&&console.log(n,t.model?.parent),n&&t.registerCallback(i)}}onExportObject(e,t,i){x.foreachComponent(e,s=>{const r=s;typeof r.createAnimation=="function"&&r.createAnimation(this,t,i)},!1);const n=new aE(e,this);this.serializers.push(n),n.registerCallback(t)}}class aE{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)),my&&console.log("REPARENT",e),this.model=e,this.callback&&this.model.addEventListener("serialize",this.callback)}skinnedMeshExport(e,t,i){const n=this.model,s=this.animationData;if(n&&n.skinnedMesh){let r=function(T){const $=[];for(const[V,se]of T){let ce=`${V} : [`;const fe=[];for(const Se of se)fe.push(`(${le(Se.x)}, ${le(Se.y)}, ${le(Se.z)})`);ce=ce.concat(fe.join(", ")),ce=ce.concat("],"),$.push(ce)}return $},a=function(T){const $=[];for(const[V,se]of T){let ce=`${V} : [`;const fe=[];for(const Se of se)fe.push(`(${le(Se.w)}, ${le(Se.x)}, ${le(Se.y)}, ${le(Se.z)})`);ce=ce.concat(fe.join(", ")),ce=ce.concat("],"),$.push(ce)}return $},l=function(T){let $,V=!0;const se=new Map;for(const[fe,Se]of T){$===void 0&&($=Se.length),$!==Se.length&&(V=!1);let Ct=0;for(const Vi of Se)Ct++,Vi||(se.has(fe)||se.set(fe,[]),se.get(fe).push(Ct))}so&&console.log("Bone count: ",T.size,"TransformData entries per bone: ",$,"Undefined bone entries: ",se),console.assert(V,"All bones should have the same number of TransformData entries",T),console.assert(se.size===0,"All TransformData entries should be set",se);const ce=[];for(const[fe,Se]of T)for(let Ct=0;Ct<Se.length;Ct++){const Vi=Se[Ct],md=i.getStartTimeByClip(Vi.clip);ce.length<=Ct&&ce.push({pos:[],rot:[],scale:[],timeOffset:md});const hs=ce[Ct];hs.pos.push(...Vi.getSortedTimesArray(!0,!1,!1)),hs.rot.push(...Vi.getSortedTimesArray(!1,!0,!1)),hs.scale.push(...Vi.getSortedTimesArray(!1,!1,!0))}for(const fe of ce)fe.pos.sort((Se,Ct)=>Se-Ct),fe.rot.sort((Se,Ct)=>Se-Ct),fe.scale.sort((Se,Ct)=>Se-Ct),fe.pos=[...new Set(fe.pos)],fe.rot=[...new Set(fe.rot)],fe.scale=[...new Set(fe.scale)];return ce},c=function(T,$,V){const se=new Map,ce=new Map,fe=new Map,Se=$.length;for(const Ct of V){const Vi=T.get(Ct);let md;Vi?console.assert(Vi.length===Se,"We should have the same number of TransformData entries for each bone",Vi,$):md=new Ne(null,Ct,null);for(let hs=0;hs<Se;hs++){const dm=Vi?Vi[hs]:md,xa=$[hs];for(const{time:Ql,translation:Yl}of dm.getValues(xa.pos,!0,!1,!1)){const mn=(Ql+xa.timeOffset)*60;se.has(mn)||se.set(mn,new Array),se.get(mn).push(Yl.clone())}for(const{time:Ql,rotation:Yl}of dm.getValues(xa.rot,!1,!0,!1)){const mn=(Ql+xa.timeOffset)*60;ce.has(mn)||ce.set(mn,new Array),ce.get(mn).push(Yl.clone())}for(const{time:Ql,scale:Yl}of dm.getValues(xa.scale,!1,!1,!0)){const mn=(Ql+xa.timeOffset)*60;fe.has(mn)||fe.set(mn,new Array),fe.get(mn).push(Yl.clone())}}}return{position:se.size==0?void 0:se,quaternion:ce.size==0?void 0:ce,scale:fe.size==0?void 0:fe}},h=function(T){const $=[];for(const V of T)$.push(`(${le(V.x)}, ${le(V.y)}, ${le(V.z)})`);return $.join(", ")},d=function(T){const $=[];for(const V of T)$.push(`(${le(V.w)}, ${le(V.x)}, ${le(V.y)}, ${le(V.z)})`);return $.join(", ")},p=function(T){const $=new Map;if(so){const V=new Array;for(const[se,ce]of s)V.push(se.uuid+": "+ce.length+" "+ce.map(fe=>fe.clip?.uuid.substring(0,6)).join(" "));console.log(`getPerBoneTransformData
|
|
1274
1274
|
`+V.join(`
|
|
1275
|
-
`))}for(const V of T){const se=s.get(V);se&&$.set(V,se)}return $},m=function(T){const $=p(T),V=l($);return c($,V,T)};const f=n.skinnedMesh.skeleton,g=new Array,y=[],_=[];for(const T of f.bones){y.push(T),_.push(T.uuid);const $=f.boneInverses[f.bones.indexOf(T)];g.push({bone:T,inverse:$})}let w=1e4;for(;_.length<f.bones.length&&w-- >0;)for(const T of y){const $=T.children;for(const V of $)if(_.indexOf(V.uuid)===-1&&f.bones.indexOf(V)!==-1){y.push(V),_.push(V.uuid);const se=f.boneInverses[f.bones.indexOf(V)];g.push({bone:V,inverse:se})}}w<=0&&console.error("Failed to sort bones in skinned mesh",n.skinnedMesh,f.bones,_);for(const T of Ox(f.bones))g.push({bone:T,inverse:T.matrixWorld.clone().invert()});const P=g[0].bone.parent;P||console.error("No bone parent found for skinned mesh during USDZ export",n.skinnedMesh),g.sort((T,$)=>ul(T.bone,P)>ul($.bone,P)?1:-1);const R=t.quickLookCompatible,k=[],j=[],L=[],W=[];for(const{bone:T}of g){if(R){const $=T.scale;$.x==0&&($.x=1e-5),$.y==0&&($.y=1e-5),$.z==0&&($.z=1e-5),k.push(new K().compose(T.position,T.quaternion,T.scale))}else k.push(T.matrix.clone());j.push(T.position),L.push(T.quaternion),W.push(T.scale)}const N=g.map(T=>'"'+ul(T.bone,P)+'"').join(", "),H=g.map(T=>Fx(T.inverse.clone().invert())).join(", ");e.beginBlock('def Skeleton "Rig"'),e.appendLine(`uniform matrix4d[] bindTransforms = [${H}]`),e.appendLine(`uniform token[] joints = [${N}]`),e.appendLine('uniform token purpose = "guide"'),e.appendLine(`uniform matrix4d[] restTransforms = [${k.map(T=>Fx(T)).join(", ")}]`);const X=m(g.map(T=>T.bone));if(so){let T=1e7,$=0;for(const V of X.position?.keys()??[])T=Math.min(T,V),$=Math.max($,V);console.log("Time samples",T,$,X)}if(e.beginBlock('def SkelAnimation "_anim"'),e.appendLine(`uniform token[] joints = [${N}]`),e.appendLine(`quatf[] rotations = [${d(L)}]`),X&&X.quaternion){e.beginBlock("quatf[] rotations.timeSamples = {","");const T=a(X.quaternion);for(const $ of T)e.appendLine($);e.closeBlock()}if(e.appendLine(`half3[] scales = [${h(W)}]`),X&&X.scale){e.beginBlock("half3[] scales.timeSamples = {","");const T=r(X.scale);for(const $ of T)e.appendLine($);e.closeBlock()}if(e.appendLine(`float3[] translations = [${h(j)}]`),X&&X.position){e.beginBlock("float3[] translations.timeSamples = {","");const T=r(X.position);for(const $ of T)e.appendLine($);e.closeBlock()}e.closeBlock(),e.closeBlock()}}onSerialize(e,t){if(!this.model)return;const i=this.animationData.get(this.object);if(i)for(let h=0;h<i.length;h++)i[h]===void 0&&(i[h]=new Ne(null,this.object,null));const n=this.ext;this.skinnedMeshExport(e,t,n);const s=this.object,r=this.model,a=this.animationData.get(s);if(!a||s.isSkinnedMesh)return;my&&console.log("SERIALIZE",this.model.name,this.object.type,a);const l=Intl.NumberFormat("en-US",{maximumFractionDigits:3,minimumFractionDigits:0,useGrouping:!1});function c(h,d){if(h.some(p=>p&&{position:p.pos,rotation:p.rot,scale:p.scale}[d])){switch(d){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 p=0;p<h.length;p++){const m=h[p];if(!m)continue;const f=n.getStartTimeByClip(m.clip),g=m.getSortedTimesArray(d==="position",d==="rotation",d==="scale");if(!g||g.length===0){console.error("got an animated object but no time values?",s,m);continue}const y=!m.clip,_=d==="position"&&(m.pos||y),w=d==="rotation"&&(m.rot||y),P=d==="scale"&&(m.scale||y);if(_||w||P){const R=m.clip?.name??"rest",k=m.getDuration();so&&console.log("Write .timeSamples:",R,f,k,h),e.appendLine("# "+R+": start="+l.format(f*Ne.frameRate)+", length="+l.format(k*Ne.frameRate)+", frames="+m.getFrames())}if(_)for(const{time:R,translation:k}of m.getValues(g,!0,!1,!1)){const j=`${l.format((f+R)*Ne.frameRate)}: (${le(k.x)}, ${le(k.y)}, ${le(k.z)}),`;e.appendLine(j)}if(w)for(const{time:R,rotation:k}of m.getValues(g,!1,!0,!1)){const j=`${l.format((f+R)*Ne.frameRate)}: (${le(k.w)}, ${le(k.x)}, ${le(k.y)}, ${le(k.z)}),`;e.appendLine(j)}if(P)for(const{time:R,scale:k}of m.getValues(g,!1,!1,!0)){const j=`${l.format((f+R)*Ne.frameRate)}: (${le(k.x)}, ${le(k.y)}, ${le(k.z)}),`;e.appendLine(j)}}e.closeBlock()}}c(a,"position"),c(a,"rotation"),c(a,"scale")}}const lE=v("debugusdz");class fa{static getName(e){const t=e.split(".").pop();let i=e.split(".").slice(0,-1).join(".").split("/").pop()?.replace(".","_");return i||(i="Audio_"+Math.random().toString(36).substring(2,15)),Ai(i)+"."+t}get extensionName(){return"Audio"}files=new Array;onExportObject(e,t,i){const n=x.getComponents(e,Ei);if(n.length)for(const s of n){if(!s.clip||typeof s.clip!="string"||!s.playOnAwake)continue;const r=s.clip.split("/").pop()||"Audio",a=fa.getName(s.clip),l=Ai(a);if(!this.files.some(c=>c.path===s.clip)){this.files.push({path:s.clip,name:a});const c=a.toLowerCase();i.quickLookCompatible&&!c.endsWith(".mp3")&&!c.endsWith(".wav")&&!c.endsWith(".m4a")&&console.error("Audio file "+s.clip+" from "+s.name+" is not an MP3 or WAV file. QuickLook may not support playing it.")}i.quickLookCompatible||t.addEventListener("serialize",(c,h)=>{c.appendLine(),c.beginBlock(`def SpatialAudio "${l}"`,"(",!1),c.appendLine(`displayName = "${r}"`),c.closeBlock(")"),c.beginBlock(),c.appendLine(`uniform asset filePath = @audio/${a}@`),c.appendLine(`uniform token auralMode = "${s.spatialBlend>0?"spatial":"nonSpatial"}"`),c.appendLine(`uniform token playbackMode = "${s.loop?"loopFromStage":"onceFromStart"}"`),c.appendLine(`uniform float gain = ${s.volume}`),c.closeBlock()})}}async onAfterSerialize(e){for(const t of this.files){const i="audio/"+t.name;if(e.files[i]){lE&&console.warn("Audio file with name "+i+" already exists in the context. Skipping.");continue}const n=await(await(await fetch(t.path)).blob()).arrayBuffer(),s=new Uint8Array(n);e.files[i]=s}}}var cE=Object.defineProperty,Be=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&cE(e,t,n),n};const Hx=v("debugusdzbehaviours");function Qc(o){o&&(o.getComponentInParent(Za)||(A()&&console.debug('Raycaster on "'+o.name+'" was automatically added, because no raycaster was found in the parent hierarchy.'),o.addComponent(Ti)))}class Gr extends M{object;target;duration=1;relativeMotion=!1;coroutine=null;targetPos=new b;targetRot=new U;targetScale=new b;start(){Qc(this.gameObject)}onPointerEnter(){this.context.input.setCursor("pointer")}onPointerExit(){this.context.input.unsetCursor("pointer")}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=J(this.object).clone(),t=J(this.target).clone(),i=be(this.object).clone(),n=be(this.target).clone(),s=He(this.object).clone(),r=He(this.target).clone(),a=e.distanceTo(t),l=i.angleTo(n),c=s.distanceTo(r);if(a<.01&&l<.01&&c<.01){gt(this.object,t),yn(this.object,n),Ta(this.object,r),this.coroutine=null;return}let h=0,d=0;for(;h<1;)h+=this.context.time.deltaTime/this.duration,h>1&&(h=1),d=h<.5?4*h*h*h:1-Math.pow(-2*h+2,3)/2,this.targetPos.lerpVectors(e,t,d),this.targetRot.slerpQuaternions(i,n,d),this.targetScale.lerpVectors(s,r,d),gt(this.object,this.targetPos),yn(this.object,this.targetRot),Ta(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(),s=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(s),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 At("Move to "+this.target?.name,Ft.tapTrigger(this.gameObject),ge.transformAction(this.object,this.target,this.duration,this.relativeMotion?"relative":"absolute"));e.addBehavior(t)}}}Be([u(O)],Gr.prototype,"object"),Be([u(O)],Gr.prototype,"target"),Be([u()],Gr.prototype,"duration"),Be([u()],Gr.prototype,"relativeMotion");const rp=class ei extends M{materialToSwitch;variantMaterial;fadeDuration=0;start(){this._objectsWithThisMaterial=this.objectsWithThisMaterial,Qc(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 G)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):wv(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=[],ei._materialTriggersPerId={},ei.variantSwitchIndex=0,this.materialToSwitch&&await $e.assignTextureLOD(this.materialToSwitch,0),this.variantMaterial&&await $e.assignTextureLOD(this.variantMaterial,0)}createBehaviours(e,t,i){this.objectsWithThisMaterial.find(n=>n.uuid===t.uuid)&&this.targetModels.push(t),this.gameObject.uuid===t.uuid&&(this.selfModel=t,this.materialToSwitch&&(ei._materialTriggersPerId[this.materialToSwitch.uuid]||(ei._materialTriggersPerId[this.materialToSwitch.uuid]=[]),ei._materialTriggersPerId[this.materialToSwitch.uuid].push(this)))}afterCreateDocument(e,t){if(!this.materialToSwitch)return;const i=ei._materialTriggersPerId[this.materialToSwitch.uuid];if(i){const n={};for(const s of i){const r=s.createVariants();r&&r.length>0&&(n[s.selfModel.uuid]=r)}for(const s of i){const r=[];for(const a in n)a!==s.selfModel.uuid&&r.push(...n[a]);s.createAndAttachBehaviors(e,n[s.selfModel.uuid],r)}}delete ei._materialTriggersPerId[this.materialToSwitch.uuid]}createAndAttachBehaviors(e,t,i){const n=[],s=Math.max(0,this.fadeDuration);n.push(ge.fadeAction([...this.targetModels,...i],s,!1)),n.push(ge.fadeAction(t,s,!0)),e.addBehavior(new At("Select_"+this.selfModel.name,Ft.tapTrigger(this.selfModel),ge.parallel(...n))),ei._parallelStartHiddenActions.push(...t),ei._startHiddenBehaviour||(ei._startHiddenBehaviour=new At("StartHidden_"+this.selfModel.name,Ft.sceneStartTrigger(),ge.fadeAction(ei._parallelStartHiddenActions,s,!1)),e.addBehavior(ei._startHiddenBehaviour))}static getMaterialName(e){return Ai(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_"+ei.variantSwitchIndex+++"_"+ei.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())&&nt.createEmptyParent(t),t.parent&&t.parent.add(i),e.push(i)}return e}};Be([u(ve)],rp.prototype,"materialToSwitch"),Be([u(ve)],rp.prototype,"variantMaterial"),Be([u()],rp.prototype,"fadeDuration");let gy=rp;const Yc=class ze extends M{target;toggleOnClick=!1;targetState=!0;hideSelf=!0;start(){Qc(this.gameObject)}onPointerEnter(){this.context.input.setCursor("pointer")}onPointerExit(){this.context.input.unsetCursor("pointer")}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[ze.wasVisible]===void 0&&(this.gameObject[ze.wasVisible]=this.gameObject.activeSelf),this.target[ze.wasVisible]===void 0&&(this.target[ze.wasVisible]=this.target.activeSelf),this.stateBeforeCreatingDocument=this.gameObject[ze.wasVisible],this.targetStateBeforeCreatingDocument=this.target[ze.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,s=this.targetState;if(this.toggleOnClick)if(s=!this.targetStateBeforeCreatingDocument,!this.selfModelClone.geometry)(!this.selfModel.parent||this.selfModel.parent.isEmpty())&&sy.createEmptyParent(this.selfModel),this.toggleModel=this.selfModel.deepClone(),this.toggleModel.name+="_toggle",this.selfModel.parent.add(this.toggleModel);else{if(!this.gameObject[ze.toggleClone]){const l=this.selfModelClone.clone();l.setMatrix(new K),l.name+="_toggle"+ze.clonedToggleIndex++,i.add(l),this.gameObject[ze.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[ze.toggleClone];if(!this.gameObject[ze.reverseToggleClone]){const l=this.selfModelClone.clone();l.setMatrix(new K),l.name+="_toggleReverse"+ze.clonedToggleIndex++,i.add(l),this.gameObject[ze.reverseToggleClone]=l}this.toggleModel=this.gameObject[ze.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(ge.fadeAction(n,0,!1)),a.push(ge.fadeAction(this.toggleModel,0,!0)),a.push(ge.fadeAction(this.targetModel,0,s)),e.addBehavior(new At("Toggle_"+n.name+"_ToggleTo"+(s?"On":"Off"),Ft.tapTrigger(n),ge.parallel(...a)));const l=[];l.push(ge.fadeAction(this.toggleModel,0,!1)),l.push(ge.fadeAction(n,0,!0)),l.push(ge.fadeAction(this.targetModel,0,!s)),e.addBehavior(new At("Toggle_"+n.name+"_ToggleTo"+(s?"Off":"On"),Ft.tapTrigger(this.toggleModel),ge.parallel(...l)))}}else{const a=[];this.hideSelf&&a.push(ge.fadeAction(n,0,!1)),a.push(ge.fadeAction(this.targetModel,0,s)),e.addBehavior(new At("Toggle_"+n.name+"_ToggleTo"+(s?"On":"Off"),Ft.tapTrigger(n),a.length>1?ge.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),un.add(r,e)}}afterSerialize(e,t){this.gameObject[ze.wasVisible]!==void 0&&(this.gameObject.visible=this.gameObject[ze.wasVisible],delete this.gameObject[ze.wasVisible]),this.target&&this.target[ze.wasVisible]!==void 0&&(this.target.visible=this.target[ze.wasVisible],delete this.target[ze.wasVisible]),delete this.gameObject[ze.toggleClone],delete this.gameObject[ze.reverseToggleClone]}};Be([u(O)],Yc.prototype,"target"),Be([u()],Yc.prototype,"toggleOnClick"),Be([u()],Yc.prototype,"targetState"),Be([u()],Yc.prototype,"hideSelf");let fy=Yc;class un extends M{static _fadeBehaviour;static _fadeObjects=[];static add(e,t){const i=Array.isArray(e)?e:[e];for(const n of i)un._fadeObjects.includes(n)||(console.log("adding hide on start",n),un._fadeObjects.push(n));un._fadeBehaviour===void 0&&(un._fadeBehaviour=new At("HideOnStart",Ft.sceneStartTrigger(),ge.fadeAction(un._fadeObjects,0,!1)),t.addBehavior(un._fadeBehaviour))}start(){x.setActive(this.gameObject,!1)}createBehaviours(e,t,i){t.uuid===this.gameObject.uuid&&(this.wasVisible||un.add(t,e))}wasVisible=!1;beforeCreateDocument(){this.wasVisible=x.isActiveSelf(this.gameObject)}}class ml extends M{target;duration=.5;motionType="bounce";beforeCreateDocument(){}createBehaviours(e,t,i){if(this.target&&t.uuid===this.gameObject.uuid){const n=new At("emphasize "+this.name,Ft.tapTrigger(this.gameObject),ge.emphasize(this.target,this.duration,this.motionType,void 0,"basic"));e.addBehavior(n)}}afterCreateDocument(e,t){}}Be([u()],ml.prototype,"target"),Be([u()],ml.prototype,"duration"),Be([u()],ml.prototype,"motionType");class Is extends M{target;clip="";toggleOnClick=!1;trigger="tap";start(){Qc(this.gameObject)}ensureAudioSource(){if(!this.target){const e=this.gameObject.addComponent(Ei);e&&(this.target=e,e.spatialBlend=1,e.volume=1,e.loop=!1,e.preload=!0)}}onPointerEnter(){this.context.input.setCursor("pointer")}onPointerExit(){this.context.input.unsetCursor("pointer")}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 s=this.target?this.target.gameObject:this.gameObject;fa.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 G&&p.visible&&(l=!0)}),l=!0;const c=e.addAudioClip(n);let h=ge.playAudioAction(s,c,"play",r,a);this.target&&this.target.loop&&(h=ge.sequence(h).makeLooping());const d=this.name?"_"+this.name:"";if(l&&this.trigger==="tap"){this.toggleOnClick&&(h.multiplePerformOperation="stop");const p=new At("playAudio"+d,Ft.tapTrigger(t),h);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 At("playAudioOnStart"+d,Ft.sceneStartTrigger(),h);e.addBehavior(p)}}}}Be([u(Ei)],Is.prototype,"target"),Be([u(URL)],Is.prototype,"clip"),Be([u()],Is.prototype,"toggleOnClick");const yy=class yo extends M{animator;stateName;trigger="tap";animation;get target(){return this.animator?.gameObject||this.animation?.gameObject}start(){Qc(this.gameObject)}onPointerEnter(){this.context.input.setCursor("pointer")}onPointerExit(){this.context.input.unsetCursor("pointer")}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(yo.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()&&ye(e),console.warn(e,...yo.rootsWithExclusivePlayback)}yo.animationActions=[],yo.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 sp);if(!n)return;const s=n.getClipCount(this.target)>1;s&&(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."),yo.rootsWithExclusivePlayback.add(this.target));const r=this.name?this.name:"";i.traverse(a=>{if(a.uuid===this.target?.uuid){const l=yo.getActionForSequences(i,a,this.animationSequence,this.animationLoopAfterSequence,this.randomOffsetNormalized),c=new At(this.trigger+"_"+r+"_toPlayAnimation_"+this.stateName+"_on_"+this.target?.name,this.trigger=="tap"?Ft.tapTrigger(this.selfModel):Ft.sceneStartTrigger(),l);s&&c.makeExclusive(!0),e.addBehavior(c)}})}static getActionForSequences(e,t,i,n,s){const r=(l,c)=>{let h=yo.animationActions.find(d=>d.affectedObjects==l&&d.start==c.start&&d.duration==c.duration&&d.animationSpeed==c.speed);return h||(h=ge.startAnimationAction(l,c),yo.animationActions.push(h)),h},a=ge.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:ge.sequence();for(const c of n)l.addAction(r(t,c));l.makeLooping(),a!==l&&a.addAction(l)}return s&&s>0&&a.actions.unshift(ge.waitAction(s)),a}static getAndRegisterAnimationSequences(e,t,i){if(!t)return;const n=t.getComponent(yt),s=t.getComponent(jt);if(!n&&!s)return;if(n&&!i)throw new Error("PlayAnimationOnClick: No stateName specified for animator "+n.name+" on "+t.name);let r=[],a=[];if(s){const f=e.registerAnimation(t,s.clip);f&&(s.loop?a.push(f):r.push(f));let g=0;if(s.minMaxOffsetNormalized){const y=s.minMaxOffsetNormalized.x,_=s.minMaxOffsetNormalized.y;g=(s.clip?.duration||1)*(y+Math.random()*(_-y))}return{animationSequence:r,animationLoopAfterSequence:a,randomTimeOffset:g}}const l=n?.runtimeAnimatorController;let c=l?.findState(i),h=[],d=[];if(l&&c){const f=new Array;f.push(c);let g=!1;for(;f.length<100;){if(!c||c===null||!c.transitions||c.transitions.length===0){c.motion?.isLooping&&(g=!0);break}const y=c.transitions.find(w=>w.conditions.length===0),_=y?l.getState(y.destinationState,0):null;if(_&&f.includes(_)){c=_,g=!0;break}else if(y){if(c=_,!c)break;f.push(c)}else{g=c.motion?.isLooping??!1;break}}if(g&&c){const y=f.indexOf(c);h=f.slice(0,y),d=f.slice(y),Hx&&console.log("found loop from "+i,"states until loop",h,"states looping",d)}else h=f,d=[],Hx&&console.log("found no loop from "+i,"states",h);if(!d.length){const y=h[h.length-1],_=y.motion?.clip;if(_){let w;if(e.holdClipMap.has(_))w=e.holdClipMap.get(_);else{const P=y.name+"_hold";w=_.clone(),w.duration=1,w.name=P;const R=_.duration;w.tracks=_.tracks.map(k=>{const j=k.clone();j.times=new Float32Array([0,R]);const L=k.values.length,W=k.getValueSize(),N=k.values.slice(L-W,L);return j.values=new Float32Array(2*W),j.values.set(N,0),j.values.set(N,W),j}),w.name=P,e.holdClipMap.set(_,w)}if(w){const P={name:w.name,motion:{clip:w,isLooping:!1,name:w.name},speed:1,transitions:[],behaviours:[],hash:y.hash+1};d.push(P)}}}}if(h.length===1&&(!h[0].motion?.clip||h[0].motion?.clip.tracks?.length===0)){r=new Array;const f=e.registerAnimation(t,null);f&&r.push(f);return}if(h=h.filter(f=>f.motion?.clip&&f.motion?.clip.tracks?.length>0),d=d.filter(f=>f.motion?.clip&&f.motion?.clip.tracks?.length>0),h.length===0&&d.length===0){console.warn("No clips found for state "+i+" on "+n?.name+", can't export animation data");return}const p=(f,g)=>{if(!t)return;const y=e.registerAnimation(t,f.motion.clip??null);y?(y.speed=f.speed,g.push(y)):console.warn("Couldn't register animation for state "+f.name+" on "+n?.name)};if(h.length>0){r=new Array;for(const f of h)p(f,r)}if(d.length>0){a=new Array;for(const f of d)p(f,a)}let m=0;if(n&&l&&n.minMaxOffsetNormalized){const f=n.minMaxOffsetNormalized.x,g=n.minMaxOffsetNormalized.y;m=((h.length?h[0]:d.length?d[0]:null)?.motion.clip?.duration||1)*(f+Math.random()*(g-f))}return{animationSequence:r,animationLoopAfterSequence:a,randomTimeOffset:m}}createAnimation(e,t,i){if(!this.target||!this.animator&&!this.animation)return;const n=yo.getAndRegisterAnimationSequences(e,this.target,this.stateName);n&&(this.animationSequence=n.animationSequence,this.animationLoopAfterSequence=n.animationLoopAfterSequence,this.randomOffsetNormalized=n.randomTimeOffset,this.stateAnimationModel=t)}};Be([u(yt)],yy.prototype,"animator"),Be([u()],yy.prototype,"stateName");let Zc=yy;class gl extends M{getType(){}target;getDuration(){}}Be([u(O)],gl.prototype,"target");class Kc extends M{target}Be([u(gl)],Kc.prototype,"target");class Jc extends gl{type=1;duration=1;getType(){switch(this.type){case 1:return"hide";case 0:return"show"}}getDuration(){return this.duration}}Be([u()],Jc.prototype,"type"),Be([u()],Jc.prototype,"duration");class by extends Kc{}class or{static _instance;static create(){return new or}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 Fn.getOrCreate().createQRCode()}createQuicklookButton(){if(this._quicklookButton)return this._quicklookButton;const e=document.createElement("button");this._quicklookButton=e,e.dataset.needle="quicklook-button";const t=q.supportsQuickLookAR();e.innerText="View in AR",e.prepend(Pt("view_in_ar"));let i=!1,n=null;return e.addEventListener("click",()=>{n=Wa(Tn),n||(i=!0,n=new Tn),i&&(n.objectToExport=z.Current.scene),n?(e.classList.add("this-mode-is-requested"),n.exportAndOpen().then(()=>{e.classList.remove("this-mode-is-requested")}).catch(s=>{e.classList.remove("this-mode-is-requested"),console.error(s)})):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(Pt("view_in_ar")),i.title="Click to start an AR session",i.addEventListener("click",()=>Z.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)"),q.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(Pt("panorama_photosphere")),i.title="Click to start a VR session",i.addEventListener("click",()=>Z.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)"),q.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(Pt("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&&Te("This page doesn't allow popups. Please paste "+n+" into your browser.")}),this.listenToXRSessionState(t),this.hideElementDuringXRSession(t),q.isMozillaXR()||navigator.xr?.addEventListener("devicechange",()=>{navigator.xr?.isSessionSupported("immersive-vr")?t.style.display="none":t.style.display=""}),t}createQRCode(){return Fn.getOrCreate().createQRCode()}updateSessionSupported(e,t){if(!("xr"in navigator)){e.style.display="none";return}Z.isSessionSupported(t).then(i=>{e.style.display=i?"":"none",A()&&!i&&console.log('[WebXR] "'+t+'" is not supported on this device \u2013 make sure your server runs using HTTPS and you have a device connected that supports '+t)})}hideElementDuringXRSession(e){zd(t=>{e["previous-display"]=e.style.display,e.style.display="none"}),cg(t=>{e["previous-display"]!=null&&(e.style.display=e["previous-display"])})}listenToXRSessionState(e,t){t&&(Z.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"))}),Z.onSessionRequestEnd(i=>{e.classList.remove("this-mode-is-requested"),e.classList.remove("other-mode-is-requested"),e.disabled=e["was-disabled"]}))}}var hE=Object.defineProperty,dE=Object.getOwnPropertyDescriptor,_t=(o,e,t,i)=>{for(var n=i>1?void 0:i?dE(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&hE(e,t,n),n};const eh=v("debugspriterenderer"),uE=v("wireframe");class ba{static cache={};static getOrCreateGeometry(e){if(e.__cached_geometry)return e.__cached_geometry;if(e.guid&&ba.cache[e.guid])return eh&&console.log("Take cached geometry for sprite",e.guid),ba.cache[e.guid];const t=new gn;e.__cached_geometry=t;const i=new Float32Array(e.triangles.length*3),n=new Float32Array(e.triangles.length*2);for(let s=0;s<e.triangles.length;s+=1){const r=e.triangles[s];i[s*3]=-e.vertices[r].x,i[s*3+1]=e.vertices[r].y,i[s*3+2]=0;const a=e.uv[r];n[s*2]=a.x,n[s*2+1]=1-a.y}return t.setAttribute("position",new mt(i,3)),t.setAttribute("uv",new mt(n,2)),e.guid&&(this.cache[e.guid]=t),eh&&console.log("Built sprite geometry",e,t),t}}class pE{x;y}function Gx(o){o&&(o.colorSpace!=Co&&(o.colorSpace=Co,o.needsUpdate=!0),o.minFilter==Sd&&o.magFilter==Sd&&(o.anisotropy=1,o.needsUpdate=!0))}let Wo=class{constructor(o){o&&(this.texture=o,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 G(ba.getOrCreateGeometry(this),this.material)),this._mesh}_mesh;get material(){return this._material||(this.texture&&Gx(this.texture),this._material=new xe({map:this.texture,color:16777215,side:Si,transparent:!0})),this._material}_material;getGeometry(){return ba.getOrCreateGeometry(this)}};_t([u()],Wo.prototype,"guid",2),_t([u(Le)],Wo.prototype,"texture",2),_t([qe()],Wo.prototype,"triangles",2),_t([qe()],Wo.prototype,"uv",2),_t([qe()],Wo.prototype,"vertices",2);const _y=Symbol("spriteOwner");class fl{sprites;constructor(){this.sprites=[]}}_t([u(Wo)],fl.prototype,"sprites",2);const vy=class X0{static create(){const e=new X0;return e.spriteSheet=new fl,e}constructor(){}clone(){const e=new X0;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 fl,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&&(Gx(n),!i.__hasLoadedProgressive)){i.__hasLoadedProgressive=!0;const s=n;$e.assignTextureLOD(n,0).then(r=>{r instanceof Le&&(i.texture=r,e?.map===s&&(e.map=r,e.needsUpdate=!0))})}}};_t([u(fl)],vy.prototype,"spriteSheet",2),_t([u()],vy.prototype,"index",2);let yl=vy;class ui extends M{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=yl.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.round(e);eh&&console.log("[SpriteSheet] Set index to "+t+" (was "+this.spriteIndex+")",e),this.spriteIndex=t}else e instanceof Wo?(this._spriteSheet||(this._spriteSheet=yl.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=yl.create(),eh&&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 eh&&console.warn("Sprite not found",this.spriteIndex,t.spriteSheet.sprites),!1;if(this._currentSprite)this._currentSprite.geometry=ba.getOrCreateGeometry(i),this._currentSprite.material.map=i.texture;else{const n=new xe({color:16777215,side:Si});if(uE&&(n.wireframe=!0),this.color&&(n.color||(n.color=new ne),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 s=i.texture;s[_y]!==void 0&&s[_y]!==this&&this.spriteFrames>1&&(s=i.texture=s.clone()),s[_y]=this,n.map=s}this.sharedMaterial=n,this._currentSprite=new G(ba.getOrCreateGeometry(i),n),this._currentSprite.renderOrder=Math.round(this.renderOrder),$e.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}}_t([u()],ui.prototype,"drawMode",2),_t([u(pE)],ui.prototype,"size",2),_t([u(oe)],ui.prototype,"color",2),_t([u(ve)],ui.prototype,"sharedMaterial",2),_t([u()],ui.prototype,"transparent",2),_t([u()],ui.prototype,"cutoutThreshold",2),_t([u()],ui.prototype,"castShadows",2),_t([u()],ui.prototype,"renderOrder",2),_t([u()],ui.prototype,"toneMapped",2),_t([u(yl)],ui.prototype,"sprite",1);const qx=v("debugwebxr"),mE=new K().makeRotationY(Math.PI);class Ni extends M{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 K;_createdPlacementObject=null;_reparentedComponents=[];_placementScene=new vi;_reticle=[];_hits=[];_placementStartTime=-1;_rigPlacementMatrix;_anchor=null;userInput;onEnable(){this.customReticle?.preload()}supportsXR(e){return e==="immersive-ar"}onEnterXR(e){qx&&console.log("ENTER WEBXR: SessionRoot start..."),this._anchor=null,Ni._hasPlaced=!1,this.gameObject.updateMatrixWorld(),this._startOffset.copy(this.gameObject.matrixWorld);const t=new O;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=Gt(this._placementScene.children),n=i.getCenter(new b),s=i.getSize(new b),r=new K;r.makeTranslation(n.x,n.y-s.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)Zi(i);this._reticle.length=0,this._isPlacing=!0,this.context.input.addEventListener("pointerup",this.onPlaceScene,{queue:oi.Early})}onLeaveXR(){this.context.input.removeEventListener("pointerup",this.onPlaceScene,{queue:oi.Early}),this.onRevertSceneChanges(),this._anchor=null,Ni._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 s=n.getHitTest();s&&(i=!0,this.updateReticleAndHits(e.xr,n.index,s,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 hm(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 s=this._reticle[t];if(!s){if(this.customReticle)if(this.customReticle.asset)s=Ga(this.customReticle.asset);else{this.customReticle.loadAssetAsync();return}else s=new G(new bC(.07,.09,32).rotateX(-Math.PI/2),new xe({side:Si,depthTest:!1,depthWrite:!1,transparent:!0,opacity:1,color:15658734})),s.name="AR Placement Reticle";if(qx){const r=new xi(1);r.position.y+=.01,s.add(r)}this._reticle[t]=s,s.matrixAutoUpdate=!1,s.visible=!1}if(s.lastPos=s.lastPos||i.position.clone(),s.lastQuat=s.lastQuat||i.quaternion.clone(),s.position.copy(s.lastPos.lerp(i.position,this.context.time.deltaTime/.1)),s.lastPos.copy(s.position),s.quaternion.copy(s.lastQuat.slerp(i.quaternion,this.context.time.deltaTime/.05)),s.lastQuat.copy(s.quaternion),s.scale.set(n,n,n),this.customReticle&&this.applyViewBasedTransform(s),s.updateMatrix(),s.visible=!0,s.parent!==this.context.scene&&this.context.scene.add(s),this._placementStartTime<0&&(this._placementStartTime=this.context.time.realtimeSinceStartup),this.autoPlace)if(this.upVec.set(0,1,0).applyQuaternion(s.quaternion),this.upVec.dot(D(0,1,0))>.9){let r=s["autoplace:timer"]||0;r>=1?(s.visible=!1,this.onPlaceScene(null)):(r+=this.context.time.deltaTime,s["autoplace:timer"]=r)}else s["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(Z.active?.isTrackingImages){console.warn("Scene Placement is disabled while images are being tracked");return}let i=this._hits[0];if(e&&e.origin instanceof hg){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),Ni._hasPlaced=!0,this.useXRAnchor&&this.onCreateAnchor(Z.active,i),this.context.xr)for(const n of this.context.xr.controllers)n.cancelHitTestSource()};onSetScale(){if(!Ni._hasPlaced)return;const e=Z.active?.rig?.gameObject;if(e){const t=Z.active?.rigScale||1,i=1/this._arScale*t,n=new K().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()&&ye("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 b(0,1,0);lookPoint=new b;worldUpVec=new b(0,1,0);applyViewBasedTransform(e){const t=this.context.mainCamera,i=e,n=t.worldPosition,s=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=s.y,e.lookAt(n))}onApplyPose(e){const t=Z.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(mE),t.matrix.premultiply(this._startOffset),t.matrix.decompose(t.position,t.quaternion,t.scale),i.add(t)}}class hm{static up=new b(0,1,0);static zero=new b(0,0,0);static one=new b(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 K,this.plane=new hr,this.plane.setFromNormalAndCoplanarPoint(hm.up,hm.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:oi.Early}),this.context.input.addEventListener("pointerdown",this.onPointerDownLate,{queue:oi.Late}),this.context.input.addEventListener("pointerup",this.onPointerUpEarly,{queue:oi.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:oi.Early}),this.context.input.removeEventListener("pointerdown",this.onPointerDownLate,{queue:oi.Late}),this.context.input.removeEventListener("pointerup",this.onPointerUpEarly,{queue:oi.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=q.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 s=this.prev.get(i.identifier);if(s){const r=this.getPositionOnPlane(i.clientX,i.clientY);s.x=r.x,s.z=r.z,s.screenx=i.clientX,s.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),s=n.x-i.x,r=n.z-i.z;if(s===0&&r===0)return;this.oneFingerDrag&&this.addMovement(s,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),s=this.prev.get(i.identifier);if(!n||!s)return;if(this.twoFingerRotate){const r=Math.atan2(t.clientY-i.clientY,t.clientX-i.clientX),a=Math.atan2(n.screeny-s.screeny,n.screenx-s.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),c=n.screenx-s.screenx,h=n.screeny-s.screeny,d=Math.sqrt(c*c+h*h),p=l-d;Math.abs(p)>2&&this.addScale(p)}n.screenx=t.clientX,n.screeny=t.clientY,s.screenx=i.clientX,s.screeny=i.clientY}}};_raycaster=new yd;_intersection=new b;_screenPos=new b;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 K;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 Ls=v("debugautosync"),wy=Symbol("syncerId");class gE{_syncers={};getOrCreateSyncer(e){if(!e.guid)return null;if(this._syncers[e.guid])return this._syncers[e.guid];const t=new fE(e);return t[wy]=e.guid,this._syncers[t[wy]]=t,t}removeSyncer(e){delete this._syncers[e[wy]]}}const xy=new gE;class fE{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||(Ls&&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];Ls&&console.log("SEND",this.comp.guid,this.networkingKey),e.send(this.networkingKey,{guid:this.comp.guid,property:t,data:i},vn.Queued),delete this.changedProperties[t]}};onHandleReceiving=e=>{if(Ls&&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 yE(o,e){let t=e!==o;return!t&&o&&e&&(Array.isArray(o)&&Array.isArray(e)||typeof o=="object"&&typeof e=="object")&&(t=!0),t}const th=Symbol("AutoSyncHandler");function bE(o){if(o[th])return o[th];const e=xy.getOrCreateSyncer(o);return e?.init(o),o[th]=e,e}function _E(o){const e=o[th];e&&(xy.removeSyncer(e),e.destroy(),delete o[th])}const Sy=function(o=null){return function(e,t){let i="";typeof t=="string"?i=t:i=t.name;let n=null,s;typeof o=="string"?s=e[o]:typeof o=="function"&&(s=o),s==null&&(A()||Ls)&&o!=null&&console.warn('syncField: no callback function found for property "'+i+'"','"'+o+'"');const r=e,a=r.__internalAwake;if(typeof a!="function"){(Ls||A())&&console.error('@syncField can currently only used on Needle Engine Components, custom object of type "'+e?.constructor?.name+'" is not supported',e);return}Ls&&console.log(i);const l=Symbol(i);r.__internalAwake=function(){if(this[l]===void 0){if(this[l]=this[i],n=xy.getOrCreateSyncer(this),Object.getOwnPropertyDescriptor(this,i)?.set===void 0){let h=!1;Object.defineProperty(this,i,{set:function(d){const p=this[l];if(this[l]=d,h){(A()||Ls)&&console.warn("Recursive call detected",i);return}h=!0;try{const m=yE(d,p);Ls&&console.log("SyncField assignment",i,"changed?",m,d,s),m&&s?.call(this,d,p)!==!1&&bE(this)?.notifyChanged(i,d)}finally{h=!1}},get:function(){return this[l]},configurable:!0,enumerable:!0})}n?.init(this),a.call(this)}};const c=r.__internalDestroy;r.__internalDestroy=function(){_E(this),c.call(this)}}};var vE=Object.defineProperty,ap=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&vE(e,t,n),n};const Jt=v("debugplayersync"),lp=class gS extends M{static async setupFrom(e,t){const i=ie.getOrCreateFromUrl(e);if(!i.asset){const r=await i.loadAssetAsync();r&&x.getOrAddComponent(r,kn)}const n=new gS;n._internalInit(t),n.asset=i;const s=new O;return s.guid=e,x.addComponent(s,n),n}autoSync=!0;asset;onPlayerSpawned;_localInstance;awake(){this.watchTabVisible(),this.onPlayerSpawned||(this.onPlayerSpawned=new he)}onEnable(){this.context.connection.beginListen(te.RoomStateSent,this.onJoinedRoom),this.context.connection.beginListen(te.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(te.LeftRoom,this.destroyInstance),this.context.connection.isInRoom&&this.onJoinedRoom()}onDisable(){this.context.connection.stopListen(te.RoomStateSent,this.onJoinedRoom),this.context.connection.stopListen(te.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(te.LeftRoom,this.destroyInstance)}onJoinedRoom=()=>{Jt&&console.log("PlayerSync.joinedRoom. autoSync is set to "+this.autoSync),this.autoSync&&this.getInstance()};async getInstance(){if(this._localInstance)return this._localInstance;if(Jt&&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,kn);if(Jt&&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=>{Jt&&console.log("PlayerSync.destroyInstance",e),vc(e,this.context.connection,!0,{saveInRoom:!1})}),this._localInstance=void 0};watchTabVisible(){window.addEventListener("visibilitychange",e=>{if(document.visibilityState==="visible")for(let t=kn.all.length-1;t>=0;t--){const i=kn.all[t];(!i.owner||!this.context.connection.userIsInRoom(i.owner))&&i.doDestroy()}})}};ap([u()],lp.prototype,"autoSync"),ap([u(ie)],lp.prototype,"asset"),ap([u(he)],lp.prototype,"onPlayerSpawned");let Cy=lp;var Xx=(o=>(o.OwnerChanged="ownerChanged",o))(Xx||{});const Py=class Tt extends M{static _all=[];static get all(){return Tt._all}static _local=[];static get local(){return Tt._local}static getFor(e){if(e instanceof O)return x.getComponentInParent(e,Tt);if(e instanceof M)return x.getComponentInParent(e.gameObject,Tt)}static isLocalPlayer(e){return Tt.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 he;onFirstOwnerChangeEvent=new he;hasOwner=!1;owner;dontDestroy=!1;get isLocalPlayer(){return this.owner===this.context.connection.connectionId}onOwnerChange(e,t){Jt&&console.log(`PlayerSync.onOwnerChange: ${t} \u2192 ${e} (me: ${this.context.connection.connectionId})`);const i=Tt._local.indexOf(this);i>=0&&Tt._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){Tt._local.push(this);const r=new CustomEvent("local-owner-changed",{detail:n});this.dispatchEvent(r)}const s=new CustomEvent("owner-changed",{detail:n});this.dispatchEvent(s),Tt.dispatchEvent("ownerChanged",s)}awake(){Tt.all.push(this),Jt&&console.log("Registered new PlayerState",this.guid,Tt.all.length-1,Tt.all),this.context.connection.beginListen(te.UserLeftRoom,this.onUserLeftRoom)}async start(){Jt&&console.log("PLAYERSTATE.START, owner: "+this.owner,this.context.connection.usersInRoom([])),this.owner?(this.context.connection.isInRoom||await Wn(300),this.context.connection.userIsInRoom(this.owner)==!1&&(Jt&&console.log(`PlayerSync.start \u2192 doDestroy "${this.name}" because user "${this.owner}" is not in room anymore...`,"Currently in room:",...this.context.connection.usersInRoom()),this.doDestroy())):this.owner||(Jt&&console.warn("PlayerState.start \u2192 owner is undefined!",this.name),setTimeout(()=>{!this.destroyed&&!this.owner?this.dontDestroy?Jt&&console.warn("PlayerState.start \u2192 owner is still undefined but dontDestroy is set to true",this.name):(Jt&&console.warn(`PlayerState.start \u2192 owner is still undefined: destroying "${this.name}" instance now`),this.doDestroy()):Jt&&console.log("PlayerState.start \u2192 owner is assigned",this.owner)},2e3))}doDestroy(){Jt&&console.log("PlayerSync.doDestroy \u2192 syncDestroy",this.name),vc(this.gameObject,this.context.connection,!0,{saveInRoom:!1})}onDestroy(){if(Jt&&console.warn("PlayerState.onDestroy",this.owner),this.context.connection.stopListen(te.UserLeftRoom,this.onUserLeftRoom),Tt.all.splice(Tt.all.indexOf(this),1),this.isLocalPlayer){const e=Tt._local.indexOf(this);e>=0&&Tt._local.splice(e,1)}}onUserLeftRoom=e=>{if(e.userId===this.owner){Jt&&console.log("PLAYERSYNC LEFT",this.owner),this.doDestroy();return}}};ap([Sy(Py.prototype.onOwnerChange)],Py.prototype,"owner");let kn=Py;var wE=Object.defineProperty,bl=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&wE(e,t,n),n};class ro extends M{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&&(q.isMobileDevice()||this.context.menu.showQRCodeButton(!0))}}bl([u()],ro.prototype,"position"),bl([u()],ro.prototype,"showNeedleLogo"),bl([u()],ro.prototype,"showSpatialMenu"),bl([u()],ro.prototype,"createFullscreenButton"),bl([u()],ro.prototype,"createMuteButton"),bl([u()],ro.prototype,"createQRCodeButton");var xE=Object.defineProperty,Oy=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&xE(e,t,n),n};const ih=v("debugwebxr"),Qx=new U().setFromAxisAngle(new b(0,1,0),Math.PI);class js extends M{head;leftHand;rightHand;_leftHandMeshes;_rightHandMeshes;_syncTransforms;async onEnterXR(e){if(!this.activeAndEnabled)return;ih&&console.warn("AVATAR ENTER XR",this.guid,this.sourceId,this,this.activeAndEnabled),this._syncTransforms&&(this._syncTransforms.length=0),await this.prepareAvatar();const t=kn.getFor(this);if(t?.owner){const i=this.gameObject.addComponent(Ie);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(Ie);t&&t.destroy()}onUpdateXR(e){if(!this.activeAndEnabled)return;const t=kn.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 c=x.getComponentsInChildren(this.head.asset,en);for(const h of c)h.enabled=!1,h.gameObject.visible=!1}}const n=e.xr.leftController,s=this.leftHand?.asset;n&&s?(s.position.copy(n.gripPosition),s.quaternion.copy(n.gripQuaternion),s.quaternion.multiply(Qx),s.visible=n.isTracking,this.updateHandVisibility(n,s,this._leftHandMeshes)):s&&s.visible&&(s.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(Qx),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(s=>{Ao(s,!n)})}}updateRemoteAvatarVisibility(){if(this.context.connection.isConnected){const e=kn.getFor(this);if(e&&e.isLocalPlayer==!1){const t=Z.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,en);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};G_.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 O&&(this.head=new ie("",this.sourceId,this.head));else{const e=new O;e.name="Head";const t=xr.createPrimitive(wr.Cube);e.add(t),this.gameObject.add(e),this.head=new ie("",this.sourceId,e),ih&&console.log("Create head",e)}if(this.rightHand)this.rightHand instanceof O&&(this.rightHand=new ie("",this.sourceId,this.rightHand));else{const e=new O;e.name="Right Hand",this.gameObject.add(e),this.rightHand=new ie("",this.sourceId,e),ih&&console.log("Create right hand",e)}if(this.leftHand)this.leftHand instanceof O&&(this.leftHand=new ie("",this.sourceId,this.leftHand));else{const e=new O;e.name="Left Hand",this.gameObject.add(e),this.leftHand=new ie("",this.sourceId,e),ih&&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)}),kn.isLocalPlayer(this.gameObject)&&(this._syncTransforms=x.getComponentsInChildren(this.gameObject,Pn))}async loadAvatarObjects(e,t,i){const n=e.loadAssetAsync(),s=t.loadAssetAsync(),r=i.loadAssetAsync(),a=new Array;n&&a.push(n),s&&a.push(s),r&&a.push(r);const l=await zm(a);ih&&console.log("Avatar loaded results:",l)}}Oy([u(ie)],js.prototype,"head"),Oy([u(ie)],js.prototype,"leftHand"),Oy([u(ie)],js.prototype,"rightHand");var SE=Object.defineProperty,cp=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&SE(e,t,n),n};const Ds=v("debugwebxr"),Bs=new Array;class $o extends M{createControllerModel=!0;createHandModel=!0;customLeftHand;customRightHand;static factory=new QC;supportsXR(e){return e==="immersive-vr"||e==="immersive-ar"}_models=new Array;async onXRControllerAdded(e){if(!(e.xr.isVR||e.xr.isPassThrough))return;console.debug("XR Controller Added",e.controller.side,e.controller.index);const{controller:t}=e;if(this.createControllerModel||this.createHandModel){if(t.hand){if(this.createHandModel){const i=await this.loadHandModel(this,t);if(!i||!t.connected||!t.isHand){i?.handObject&&Ha(i.handObject,!1),i?.handObject?.destroy();return}this._models.push({controller:t,model:i.handObject,handmesh:i.handmesh}),this._models.sort((n,s)=>n.controller.index-s.controller.index),this.scene.add(i.handObject),t.model=i.handObject}}else if(this.createControllerModel){const i=await t.getModelUrl();if(i){const n=await this.loadModel(t,i);if(!n||!t.connected||t.isHand)return;this._models.push({controller:t,model:n}),this._models.sort((s,r)=>s.controller.index-r.controller.index),this.scene.add(n),n.traverse(s=>{s.layers.set(2),s.matrixAutoUpdate=!1,s.updateMatrix()}),t.model=n}else t.targetRayMode!=="transient-pointer"&&console.warn("XRControllerModel: no model found for "+t.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&&(Ha(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&&(Ha(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(Z.active&&(Ds&&(Bs[0]=Date.now()),this.updateRendering(Z.active),Ds)){const e=Date.now()-Bs[0];Bs.push(e),Bs.length>=30&&(Bs[0]=0,Bs.reduce((t,i)=>t+i,0)/Bs.length,Bs.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){Ds&&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 s=e.referenceSpace,r=this.context.renderer.xr.getHand(n.index);if(s&&e.frame.getJointPose){for(const a of n.inputSource.hand.values()){const l=r.joints[a.jointName];if(l){const c=n.getHandJointPose(a);if(c){const h=c.transform.position,d=c.transform.orientation;l.position.copy(h),l.quaternion.copy(d),l.matrixAutoUpdate=!1}l.visible=c!=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(La))}}}}async loadModel(e,t){if(!e.connected)return console.warn("XRControllerModel.onXRControllerAdded: controller is not connected anymore",e.side),null;const i=await ie.getOrCreate("",t).instantiate();return Ha(i),Z.active?.isPassThrough&&i.traverseVisible(n=>{this.makeOccluder(n)}),i}async loadHandModel(e,t){const i=this.context,n=i.renderer.xr.getHand(t.index);n||(Ds?B.DrawLabel(t.rayWorldPosition,"No hand found for index "+t.index,.05,5):console.warn("No hand found for index "+t.index));const s=new Po;pf(s,i),await Gu(s,i,this.sourceId??"",this.sourceId??"");const r=Hf(s);let a="";const l=t.side==="left"?this.customLeftHand:this.customRightHand;l?(a=l.url.split(".").slice(0,-1).join("."),s.setPath("")):(a=t.inputSource.handedness==="left"?"left":"right",s.setPath("https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles/generic-hand/"));const c=new O;Ha(c);const h=new YC(c,n,s.path,a,s,d=>{const p=r?.gltf;p?.scene.children?.length===0&&(p.scene.children[0]=d),r?.gltf&&_n().createBuiltinComponents(e.context,e.sourceId||a,r.gltf,null,r),d.traverse(m=>{m.layers.set(2),Z.active?.isPassThrough&&!l&&this.makeOccluder(m),m instanceof G&&$e.assignMeshLOD(m,0)}),t.connected||(Ds&&B.DrawLabel(t.rayWorldPosition,"Hand is loaded but not connected anymore",.05,5),d.removeFromParent())});if(Ds&&c.add(new xi(.5)),t.inputSource.hand){Ds&&console.log(t.inputSource.hand);for(const d of t.inputSource.hand.values())if(n.joints[d.jointName]===void 0){const p=new xo;p.matrixAutoUpdate=!1,p.visible=!0,n.joints[d.jointName]=p,n.add(p)}}else Ds&&B.DrawLabel(t.rayWorldPosition,"No inputSource.hand found for index "+t.index,.05,5);return{handObject:c,handmesh:h}}makeOccluder(e){if(e instanceof G){let t=e.material;t instanceof ve&&(t=e.material=t.clone(),t.depthWrite=!0,t.depthTest=!0,t.colorWrite=!1,e.receiveShadow=!1,e.renderOrder=-100)}}}cp([u()],$o.prototype,"createControllerModel"),cp([u()],$o.prototype,"createHandModel"),cp([u(ie)],$o.prototype,"customLeftHand"),cp([u(ie)],$o.prototype,"customRightHand");class hp extends M{}var CE=Object.defineProperty,Fs=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&CE(e,t,n),n};const ky=v("debugwebxr");class Ii extends M{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=D(i.x,0,i.y);n.multiplyScalar(this.context.time.deltaTimeUnscaled*this.movementSpeed);const s=He(t);n.multiplyScalar(s.x),n.applyQuaternion(e.xr.poseOrientation),n.y=0,n.applyQuaternion(t.worldQuaternion),A()&&Number.isNaN(n.x)&&console.error("Stick movement resulted in NaN",{stick:i,vec:n}),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 i=e.getStick("xr-standard-thumbstick").x;if(this._didApplyRotation)Math.abs(i)<.3&&(this._didApplyRotation=!1);else if(Math.abs(i)>.5){this._didApplyRotation=!0;const n=i>0?1:-1,s=J(this.context.mainCamera).clone();t.rotateY(n*I.toRadians(this.rotationStep));const r=J(this.context.mainCamera).clone().sub(s);r.y=0,t.position.sub(r)}}_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 s=e.getGesture("pinch");s&&(i=s.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 ka){const r=n.normal?.dot(D(0,1,0));if(r!==void 0&&r<.4)return}let s=n?.point;if(!s&&!this.useTeleportTarget){this._plane||(this._plane=new hr(new b(0,1,0),0));const r=t.worldPosition;this._plane.setFromNormalAndCoplanarPoint(new b(0,1,0),r);const a=e.ray;s=r.clone(),this._plane.intersectLine(new _C(a.origin,D(a.direction).multiplyScalar(1e4).add(a.origin)),s),s.distanceTo(r)>t.scale.x*10&&(s=null)}if(s){if(this.useTeleportTarget&&!x.getComponentInParent(n.object,hp))return;const r=s.clone();if(ky&&B.DrawSphere(s,.025,16711680,5),this.context.mainCamera?.position){const a=this.context.xr?.getUserOffsetInRig();a&&(a.y=0,r.sub(a),ky&&B.DrawWireSphere(a.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 s=i.rayWorldPosition,r=i.rayWorldQuaternion;n.position.copy(s),n.quaternion.copy(r);const a=e.rigScale,l=this.usePinchToTeleport&&i.isTeleportGesture,c=this._lastHitDistances[t],h=this._hitDistances[t]!=null,d=c??a;n.scale.set(a,a,d),n.visible=!0,n.layers.disableAll(),n.layers.enable(2);let p=n.material.opacity;l?p=1:this.showHits&&d<e.rigScale*.5?p=0:i.getButton("primary")?.pressed?p=.5:p=h?.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],s=!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,s=!1);const a=this.context.time.smoothedFps>=59?1:10;if((this.context.time.frame+i.index)%a!==0&&(s=!1),!s){const h=this._hitDiscs[t];h&&h.visible&&h.hit&&this.updateHitPointerPosition(i,h,h.hit.distance);continue}const l=this.context.physics.raycastFromRay(i.ray,{testObject:this.hitPointRaycastFilter,precise:!1});let c=l.find(h=>this.usePinchToTeleport&&i.isTeleportGesture?!0:this.isObjectWithInteractiveComponent(h.object));if(c||(c=l[0]),n&&(n.controller=i,n.hit=c),this._hitDistances[t]=c?.distance||null,c){this._lastHitDistances[t]=c.distance;const h=e.rigScale??1;ky&&(B.DrawWireSphere(c.point,.025*h,16711680),B.DrawLabel(D(0,.2,0).add(c.point),c.object.name,.02,0)),n||(n=this.createHitPointObject(),this._hitDiscs[t]=n),n.hit=c,n.visible=c.distance>h*.05;let d=.01*(h+c.distance);const p=i.getButton("primary")?.pressed;p&&(d*=1.1),n.scale.set(d,d,d),n.layers.set(2);let m=n.material.opacity;if(p?m=1:m=c.distance<.15*h?.2:.6,n.material.opacity=I.lerp(n.material.opacity,m,this.context.time.deltaTimeUnscaled/.1),n.visible){if(c.normal){this.updateHitPointerPosition(i,n,c.distance);const f=c.normal.applyQuaternion(be(c.object));n.quaternion.setFromUnitVectors(PE,f)}else this.updateHitPointerPosition(i,n,c.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 Tu(e)||e.isUI===!0?!0:e.isScene?!1:e.parent?this.isObjectWithInteractiveComponent(e.parent,t+1):!1}updateHitPointerPosition(e,t,i){const n=D(e.rayWorldPosition);n.add(D(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 G(new fd(.3,6,6),new xe({color:15658734,opacity:.7,transparent:!0,depthTest:!1,depthWrite:!1,side:Si}));return e.layers.disableAll(),e.layers.enable(2),e}createRayLineObject(){const e=new ZC;e.layers.disableAll(),e.layers.enable(2);const t=new KC;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 s=new JC({color:16777215,vertexColors:!0,worldUnits:!0,linewidth:.004,transparent:!0,depthWrite:!1,blending:hb,dashed:!1});return e.material=s,e}}Fs([u()],Ii.prototype,"movementSpeed"),Fs([u()],Ii.prototype,"rotationStep"),Fs([u()],Ii.prototype,"useTeleport"),Fs([u()],Ii.prototype,"usePinchToTeleport"),Fs([u()],Ii.prototype,"useTeleportTarget"),Fs([u()],Ii.prototype,"useTeleportFade"),Fs([u()],Ii.prototype,"showRays"),Fs([u()],Ii.prototype,"showHits");const PE=new b(0,1,0);var OE=Object.defineProperty,vt=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&OE(e,t,n),n};const nh=v("debugwebxr"),kE=v("debugusdz"),at=class Vl extends M{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(){Z.getXRSync(this.context)}onEnable(){window.location.protocol!=="https:"&&ye('<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(Tn)||(nh&&console.log("WebXR: Adding USDZExporter"),this._usdzExporter=x.addComponent(this.gameObject,Tn),this._usdzExporter.objectToExport=this.context.scene,this._usdzExporter.autoExportAnimations=!0,this._usdzExporter.autoExportAudioSources=!0)),this.handleCreatingHTML(),this.handleOfferSession(),this.defaultAvatar===!0&&(nh&&console.warn("WebXR: No default avatar set, using static default avatar"),this.defaultAvatar=new ie("https://cdn.needle.tools/static/avatars/DefaultAvatar.glb")),this.defaultAvatar&&(this._playerSync=this.gameObject.getOrAddComponent(Cy),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 Z.isVRSupported()&&this.createVRButton?Z.offerSession("immersive-vr","default",this.context):this.createARButton&&await Z.isARSupported()&&this.createARButton?Z.offerSession("immersive-ar","default",this.context):!1}get session(){return Z.active??null}get sessionMode(){return Z.activeMode??null}get arSessionRoot(){return this._activeWebARSessionRoot}async enterVR(e){return Z.start("immersive-vr",e,this.context)}async enterAR(e){return Z.start("immersive-ar",e,this.context)}exitXR(){Z.stop()}_exitXRMenuButton;_previousXRState=0;_spatialGrabRaycaster;_activeWebARSessionRoot=null;get isActiveWebXR(){return!Vl.activeWebXRComponent||Vl.activeWebXRComponent===this}onBeforeXR(e,t){if(!this.isActiveWebXR){console.warn(`WebXR: another WebXR component is already active (${Vl.activeWebXRComponent?.name}). This is ignored: ${this.name}`);return}Vl.activeWebXRComponent=this,e=="immersive-ar"&&this.useDepthSensing&&(t.optionalFeatures=t.optionalFeatures||[],t.optionalFeatures.push("depth-sensing"))}async onEnterXR(e){if(!this.isActiveWebXR)return;nh&&console.log("WebXR onEnterXR"),this._previousXRState=ti.Global.Mask;const t=e.xr.isVR;if(ti.Global.Set(t?eo.VR:eo.AR),e.xr.isAR){let i=x.findObjectOfType(Ni);if(!i)if(this.usePlacementReticle){const n=new O;for(const s of this.context.scene.children)n.add(s);this.context.scene.add(n),i=x.addComponent(n,Ni),this._createdComponentsInSession.push(i)}else(nh||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(ga)??void 0,this._spatialGrabRaycaster||(this._spatialGrabRaycaster=this.gameObject.addComponent(ga))),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){ti.Global.Set(this._previousXRState),this._playerSync?.destroyInstance();for(const t of this._createdComponentsInSession)t.destroy();this._createdComponentsInSession.length=0,this._activeWebARSessionRoot=null,this.handleOfferSession(),tc(1).then(()=>Vl.activeWebXRComponent=null)}}setDefaultMovementEnabled(e){let t=this.gameObject.getComponent(Ii);return!t&&e&&(t=this.gameObject.addComponent(Ii),this._createdComponentsInSession.push(t)),t&&(t.enabled=e),t}setDefaultControllerRenderingEnabled(e){let t=this.gameObject.getComponent($o);return!t&&e&&(t=this.gameObject.addComponent($o),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=>{nh&&console.log("WebXR.onAvatarSpawned",e);let t=x.getComponentInChildren(e,js);t??=x.addComponent(e,js)};getButtonsContainer(){return this.getButtonsFactory()}getButtonsFactory(){return this._buttonFactory||(this._buttonFactory=or.getOrCreate()),this._buttonFactory}_buttonFactory;handleCreatingHTML(){if(this.createARButton||this.createVRButton||this.useQuicklookExport){if((q.isiOS()&&q.isSafari()||kE)&&this.useQuicklookExport){const e=x.findObjectOfType(Tn);if(!e||e&&e.allowCreateQuicklookButton){const t=this.getButtonsFactory().createQuicklookButton();this.addButton(t,50)}}if(this.createARButton){const e=this.getButtonsFactory().createARButton();this.addButton(e,50)}if(this.createVRButton){const e=this.getButtonsFactory().createVRButton();this.addButton(e,50)}}if(this.createSendToQuestButton&&!q.isQuest()&&Z.isVRSupported().then(e=>{if(!e){const t=this.getButtonsFactory().createSendToQuestButton();this.addButton(t,50)}}),this.createQRCode){const e=Wa(ro);if(e&&e.createQRCodeButton===!1)A()&&console.warn("WebXR: QRCode button is disabled in the Needle Menu component");else if(!q.isMobileDevice()){const t=Fn.getOrCreate().createQRCode();this.addButton(t,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}};vt([u()],at.prototype,"createVRButton"),vt([u()],at.prototype,"createARButton"),vt([u()],at.prototype,"createSendToQuestButton"),vt([u()],at.prototype,"createQRCode"),vt([u()],at.prototype,"useDefaultControls"),vt([u()],at.prototype,"showControllerModels"),vt([u()],at.prototype,"showHandModels"),vt([u()],at.prototype,"usePlacementReticle"),vt([u(ie)],at.prototype,"customARPlacementReticle"),vt([u()],at.prototype,"usePlacementAdjustment"),vt([u()],at.prototype,"arScale"),vt([u()],at.prototype,"useXRAnchor"),vt([u()],at.prototype,"autoPlace"),vt([u()],at.prototype,"autoCenter"),vt([u()],at.prototype,"useQuicklookExport"),vt([u()],at.prototype,"useDepthSensing"),vt([u()],at.prototype,"useSpatialGrab"),vt([u(ie)],at.prototype,"defaultAvatar");let dp=at;const up=v("debugusdzbehaviours");class My{get extensionName(){return"Behaviour"}behaviours=[];addBehavior(e){this.behaviours.push(e)}addAudioClip(e){if(!e||typeof e!="string")return"";const t="audio/"+fa.getName(e);return this.audioClips.push({clipUrl:e,filesKey:t}),t}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 s=n;if(typeof s.createBehaviours=="function"||typeof s.beforeCreateDocument=="function"||typeof s.afterCreateDocument=="function"||typeof s.afterSerialize=="function"){this.behaviourComponents.push(s);const r=s.beforeCreateDocument?.call(s,this,e);r instanceof Promise&&t.push(r)}},!1)}),up&&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 d of this.behaviourComponents)typeof d.afterCreateDocument=="function"&&d.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,s=new Set,r=up;let a=`graph LR
|
|
1275
|
+
`))}for(const V of T){const se=s.get(V);se&&$.set(V,se)}return $},m=function(T){const $=p(T),V=l($);return c($,V,T)};const f=n.skinnedMesh.skeleton,g=new Array,y=[],_=[];for(const T of f.bones){y.push(T),_.push(T.uuid);const $=f.boneInverses[f.bones.indexOf(T)];g.push({bone:T,inverse:$})}let w=1e4;for(;_.length<f.bones.length&&w-- >0;)for(const T of y){const $=T.children;for(const V of $)if(_.indexOf(V.uuid)===-1&&f.bones.indexOf(V)!==-1){y.push(V),_.push(V.uuid);const se=f.boneInverses[f.bones.indexOf(V)];g.push({bone:V,inverse:se})}}w<=0&&console.error("Failed to sort bones in skinned mesh",n.skinnedMesh,f.bones,_);for(const T of Ox(f.bones))g.push({bone:T,inverse:T.matrixWorld.clone().invert()});const P=g[0].bone.parent;P||console.error("No bone parent found for skinned mesh during USDZ export",n.skinnedMesh),g.sort((T,$)=>ul(T.bone,P)>ul($.bone,P)?1:-1);const R=t.quickLookCompatible,k=[],j=[],L=[],W=[];for(const{bone:T}of g){if(R){const $=T.scale;$.x==0&&($.x=1e-5),$.y==0&&($.y=1e-5),$.z==0&&($.z=1e-5),k.push(new K().compose(T.position,T.quaternion,T.scale))}else k.push(T.matrix.clone());j.push(T.position),L.push(T.quaternion),W.push(T.scale)}const N=g.map(T=>'"'+ul(T.bone,P)+'"').join(", "),H=g.map(T=>Fx(T.inverse.clone().invert())).join(", ");e.beginBlock('def Skeleton "Rig"'),e.appendLine(`uniform matrix4d[] bindTransforms = [${H}]`),e.appendLine(`uniform token[] joints = [${N}]`),e.appendLine('uniform token purpose = "guide"'),e.appendLine(`uniform matrix4d[] restTransforms = [${k.map(T=>Fx(T)).join(", ")}]`);const X=m(g.map(T=>T.bone));if(so){let T=1e7,$=0;for(const V of X.position?.keys()??[])T=Math.min(T,V),$=Math.max($,V);console.log("Time samples",T,$,X)}if(e.beginBlock('def SkelAnimation "_anim"'),e.appendLine(`uniform token[] joints = [${N}]`),e.appendLine(`quatf[] rotations = [${d(L)}]`),X&&X.quaternion){e.beginBlock("quatf[] rotations.timeSamples = {","");const T=a(X.quaternion);for(const $ of T)e.appendLine($);e.closeBlock()}if(e.appendLine(`half3[] scales = [${h(W)}]`),X&&X.scale){e.beginBlock("half3[] scales.timeSamples = {","");const T=r(X.scale);for(const $ of T)e.appendLine($);e.closeBlock()}if(e.appendLine(`float3[] translations = [${h(j)}]`),X&&X.position){e.beginBlock("float3[] translations.timeSamples = {","");const T=r(X.position);for(const $ of T)e.appendLine($);e.closeBlock()}e.closeBlock(),e.closeBlock()}}onSerialize(e,t){if(!this.model)return;const i=this.animationData.get(this.object);if(i)for(let h=0;h<i.length;h++)i[h]===void 0&&(i[h]=new Ne(null,this.object,null));const n=this.ext;this.skinnedMeshExport(e,t,n);const s=this.object,r=this.model,a=this.animationData.get(s);if(!a||s.isSkinnedMesh)return;my&&console.log("SERIALIZE",this.model.name,this.object.type,a);const l=Intl.NumberFormat("en-US",{maximumFractionDigits:3,minimumFractionDigits:0,useGrouping:!1});function c(h,d){if(h.some(p=>p&&{position:p.pos,rotation:p.rot,scale:p.scale}[d])){switch(d){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 p=0;p<h.length;p++){const m=h[p];if(!m)continue;const f=n.getStartTimeByClip(m.clip),g=m.getSortedTimesArray(d==="position",d==="rotation",d==="scale");if(!g||g.length===0){console.error("got an animated object but no time values?",s,m);continue}const y=!m.clip,_=d==="position"&&(m.pos||y),w=d==="rotation"&&(m.rot||y),P=d==="scale"&&(m.scale||y);if(_||w||P){const R=m.clip?.name??"rest",k=m.getDuration();so&&console.log("Write .timeSamples:",R,f,k,h),e.appendLine("# "+R+": start="+l.format(f*Ne.frameRate)+", length="+l.format(k*Ne.frameRate)+", frames="+m.getFrames())}if(_)for(const{time:R,translation:k}of m.getValues(g,!0,!1,!1)){const j=`${l.format((f+R)*Ne.frameRate)}: (${le(k.x)}, ${le(k.y)}, ${le(k.z)}),`;e.appendLine(j)}if(w)for(const{time:R,rotation:k}of m.getValues(g,!1,!0,!1)){const j=`${l.format((f+R)*Ne.frameRate)}: (${le(k.w)}, ${le(k.x)}, ${le(k.y)}, ${le(k.z)}),`;e.appendLine(j)}if(P)for(const{time:R,scale:k}of m.getValues(g,!1,!1,!0)){const j=`${l.format((f+R)*Ne.frameRate)}: (${le(k.x)}, ${le(k.y)}, ${le(k.z)}),`;e.appendLine(j)}}e.closeBlock()}}c(a,"position"),c(a,"rotation"),c(a,"scale")}}const lE=v("debugusdz");class fa{static getName(e){const t=e.split(".").pop();let i=e.split(".").slice(0,-1).join(".").split("/").pop()?.replace(".","_");return i||(i="Audio_"+Math.random().toString(36).substring(2,15)),Ai(i)+"."+t}get extensionName(){return"Audio"}files=new Array;onExportObject(e,t,i){const n=x.getComponents(e,Ei);if(n.length)for(const s of n){if(!s.clip||typeof s.clip!="string"||!s.playOnAwake)continue;const r=s.clip.split("/").pop()||"Audio",a=fa.getName(s.clip),l=Ai(a);if(!this.files.some(c=>c.path===s.clip)){this.files.push({path:s.clip,name:a});const c=a.toLowerCase();i.quickLookCompatible&&!c.endsWith(".mp3")&&!c.endsWith(".wav")&&!c.endsWith(".m4a")&&console.error("Audio file "+s.clip+" from "+s.name+" is not an MP3 or WAV file. QuickLook may not support playing it.")}i.quickLookCompatible||t.addEventListener("serialize",(c,h)=>{c.appendLine(),c.beginBlock(`def SpatialAudio "${l}"`,"(",!1),c.appendLine(`displayName = "${r}"`),c.closeBlock(")"),c.beginBlock(),c.appendLine(`uniform asset filePath = @audio/${a}@`),c.appendLine(`uniform token auralMode = "${s.spatialBlend>0?"spatial":"nonSpatial"}"`),c.appendLine(`uniform token playbackMode = "${s.loop?"loopFromStage":"onceFromStart"}"`),c.appendLine(`uniform float gain = ${s.volume}`),c.closeBlock()})}}async onAfterSerialize(e){for(const t of this.files){const i="audio/"+t.name;if(e.files[i]){lE&&console.warn("Audio file with name "+i+" already exists in the context. Skipping.");continue}const n=await(await(await fetch(t.path)).blob()).arrayBuffer(),s=new Uint8Array(n);e.files[i]=s}}}var cE=Object.defineProperty,Be=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&cE(e,t,n),n};const Hx=v("debugusdzbehaviours");function Qc(o){o&&(o.getComponentInParent(Za)||(A()&&console.debug('Raycaster on "'+o.name+'" was automatically added, because no raycaster was found in the parent hierarchy.'),o.addComponent(Ti)))}class Gr extends M{object;target;duration=1;relativeMotion=!1;coroutine=null;targetPos=new b;targetRot=new U;targetScale=new b;start(){Qc(this.gameObject)}onPointerEnter(){this.context.input.setCursor("pointer")}onPointerExit(){this.context.input.unsetCursor("pointer")}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=J(this.object).clone(),t=J(this.target).clone(),i=be(this.object).clone(),n=be(this.target).clone(),s=He(this.object).clone(),r=He(this.target).clone(),a=e.distanceTo(t),l=i.angleTo(n),c=s.distanceTo(r);if(a<.01&&l<.01&&c<.01){gt(this.object,t),yn(this.object,n),Ta(this.object,r),this.coroutine=null;return}let h=0,d=0;for(;h<1;)h+=this.context.time.deltaTime/this.duration,h>1&&(h=1),d=h<.5?4*h*h*h:1-Math.pow(-2*h+2,3)/2,this.targetPos.lerpVectors(e,t,d),this.targetRot.slerpQuaternions(i,n,d),this.targetScale.lerpVectors(s,r,d),gt(this.object,this.targetPos),yn(this.object,this.targetRot),Ta(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(),s=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(s),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 At("Move to "+this.target?.name,Ft.tapTrigger(this.gameObject),ge.transformAction(this.object,this.target,this.duration,this.relativeMotion?"relative":"absolute"));e.addBehavior(t)}}}Be([u(O)],Gr.prototype,"object"),Be([u(O)],Gr.prototype,"target"),Be([u()],Gr.prototype,"duration"),Be([u()],Gr.prototype,"relativeMotion");const rp=class ei extends M{materialToSwitch;variantMaterial;fadeDuration=0;start(){this._objectsWithThisMaterial=this.objectsWithThisMaterial,Qc(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 G)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):wv(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=[],ei._materialTriggersPerId={},ei.variantSwitchIndex=0,this.materialToSwitch&&await $e.assignTextureLOD(this.materialToSwitch,0),this.variantMaterial&&await $e.assignTextureLOD(this.variantMaterial,0)}createBehaviours(e,t,i){this.objectsWithThisMaterial.find(n=>n.uuid===t.uuid)&&this.targetModels.push(t),this.gameObject.uuid===t.uuid&&(this.selfModel=t,this.materialToSwitch&&(ei._materialTriggersPerId[this.materialToSwitch.uuid]||(ei._materialTriggersPerId[this.materialToSwitch.uuid]=[]),ei._materialTriggersPerId[this.materialToSwitch.uuid].push(this)))}afterCreateDocument(e,t){if(!this.materialToSwitch)return;const i=ei._materialTriggersPerId[this.materialToSwitch.uuid];if(i){const n={};for(const s of i){const r=s.createVariants();r&&r.length>0&&(n[s.selfModel.uuid]=r)}for(const s of i){const r=[];for(const a in n)a!==s.selfModel.uuid&&r.push(...n[a]);s.createAndAttachBehaviors(e,n[s.selfModel.uuid],r)}}delete ei._materialTriggersPerId[this.materialToSwitch.uuid]}createAndAttachBehaviors(e,t,i){const n=[],s=Math.max(0,this.fadeDuration);n.push(ge.fadeAction([...this.targetModels,...i],s,!1)),n.push(ge.fadeAction(t,s,!0)),e.addBehavior(new At("Select_"+this.selfModel.name,Ft.tapTrigger(this.selfModel),ge.parallel(...n))),ei._parallelStartHiddenActions.push(...t),ei._startHiddenBehaviour||(ei._startHiddenBehaviour=new At("StartHidden_"+this.selfModel.name,Ft.sceneStartTrigger(),ge.fadeAction(ei._parallelStartHiddenActions,s,!1)),e.addBehavior(ei._startHiddenBehaviour))}static getMaterialName(e){return Ai(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_"+ei.variantSwitchIndex+++"_"+ei.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())&&nt.createEmptyParent(t),t.parent&&t.parent.add(i),e.push(i)}return e}};Be([u(ve)],rp.prototype,"materialToSwitch"),Be([u(ve)],rp.prototype,"variantMaterial"),Be([u()],rp.prototype,"fadeDuration");let gy=rp;const Yc=class ze extends M{target;toggleOnClick=!1;targetState=!0;hideSelf=!0;start(){Qc(this.gameObject)}onPointerEnter(){this.context.input.setCursor("pointer")}onPointerExit(){this.context.input.unsetCursor("pointer")}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[ze.wasVisible]===void 0&&(this.gameObject[ze.wasVisible]=this.gameObject.activeSelf),this.target[ze.wasVisible]===void 0&&(this.target[ze.wasVisible]=this.target.activeSelf),this.stateBeforeCreatingDocument=this.gameObject[ze.wasVisible],this.targetStateBeforeCreatingDocument=this.target[ze.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,s=this.targetState;if(this.toggleOnClick)if(s=!this.targetStateBeforeCreatingDocument,!this.selfModelClone.geometry)(!this.selfModel.parent||this.selfModel.parent.isEmpty())&&sy.createEmptyParent(this.selfModel),this.toggleModel=this.selfModel.deepClone(),this.toggleModel.name+="_toggle",this.selfModel.parent.add(this.toggleModel);else{if(!this.gameObject[ze.toggleClone]){const l=this.selfModelClone.clone();l.setMatrix(new K),l.name+="_toggle"+ze.clonedToggleIndex++,i.add(l),this.gameObject[ze.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[ze.toggleClone];if(!this.gameObject[ze.reverseToggleClone]){const l=this.selfModelClone.clone();l.setMatrix(new K),l.name+="_toggleReverse"+ze.clonedToggleIndex++,i.add(l),this.gameObject[ze.reverseToggleClone]=l}this.toggleModel=this.gameObject[ze.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(ge.fadeAction(n,0,!1)),a.push(ge.fadeAction(this.toggleModel,0,!0)),a.push(ge.fadeAction(this.targetModel,0,s)),e.addBehavior(new At("Toggle_"+n.name+"_ToggleTo"+(s?"On":"Off"),Ft.tapTrigger(n),ge.parallel(...a)));const l=[];l.push(ge.fadeAction(this.toggleModel,0,!1)),l.push(ge.fadeAction(n,0,!0)),l.push(ge.fadeAction(this.targetModel,0,!s)),e.addBehavior(new At("Toggle_"+n.name+"_ToggleTo"+(s?"Off":"On"),Ft.tapTrigger(this.toggleModel),ge.parallel(...l)))}}else{const a=[];this.hideSelf&&a.push(ge.fadeAction(n,0,!1)),a.push(ge.fadeAction(this.targetModel,0,s)),e.addBehavior(new At("Toggle_"+n.name+"_ToggleTo"+(s?"On":"Off"),Ft.tapTrigger(n),a.length>1?ge.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),un.add(r,e)}}afterSerialize(e,t){this.gameObject[ze.wasVisible]!==void 0&&(this.gameObject.visible=this.gameObject[ze.wasVisible],delete this.gameObject[ze.wasVisible]),this.target&&this.target[ze.wasVisible]!==void 0&&(this.target.visible=this.target[ze.wasVisible],delete this.target[ze.wasVisible]),delete this.gameObject[ze.toggleClone],delete this.gameObject[ze.reverseToggleClone]}};Be([u(O)],Yc.prototype,"target"),Be([u()],Yc.prototype,"toggleOnClick"),Be([u()],Yc.prototype,"targetState"),Be([u()],Yc.prototype,"hideSelf");let fy=Yc;class un extends M{static _fadeBehaviour;static _fadeObjects=[];static add(e,t){const i=Array.isArray(e)?e:[e];for(const n of i)un._fadeObjects.includes(n)||(console.log("adding hide on start",n),un._fadeObjects.push(n));un._fadeBehaviour===void 0&&(un._fadeBehaviour=new At("HideOnStart",Ft.sceneStartTrigger(),ge.fadeAction(un._fadeObjects,0,!1)),t.addBehavior(un._fadeBehaviour))}start(){x.setActive(this.gameObject,!1)}createBehaviours(e,t,i){t.uuid===this.gameObject.uuid&&(this.wasVisible||un.add(t,e))}wasVisible=!1;beforeCreateDocument(){this.wasVisible=x.isActiveSelf(this.gameObject)}}class ml extends M{target;duration=.5;motionType="bounce";beforeCreateDocument(){}createBehaviours(e,t,i){if(this.target&&t.uuid===this.gameObject.uuid){const n=new At("emphasize "+this.name,Ft.tapTrigger(this.gameObject),ge.emphasize(this.target,this.duration,this.motionType,void 0,"basic"));e.addBehavior(n)}}afterCreateDocument(e,t){}}Be([u()],ml.prototype,"target"),Be([u()],ml.prototype,"duration"),Be([u()],ml.prototype,"motionType");class Is extends M{target;clip="";toggleOnClick=!1;trigger="tap";start(){Qc(this.gameObject)}ensureAudioSource(){if(!this.target){const e=this.gameObject.addComponent(Ei);e&&(this.target=e,e.spatialBlend=1,e.volume=1,e.loop=!1,e.preload=!0)}}onPointerEnter(){this.context.input.setCursor("pointer")}onPointerExit(){this.context.input.unsetCursor("pointer")}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 s=this.target?this.target.gameObject:this.gameObject;fa.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 G&&p.visible&&(l=!0)}),l=!0;const c=e.addAudioClip(n);let h=ge.playAudioAction(s,c,"play",r,a);this.target&&this.target.loop&&(h=ge.sequence(h).makeLooping());const d=this.name?"_"+this.name:"";if(l&&this.trigger==="tap"){this.toggleOnClick&&(h.multiplePerformOperation="stop");const p=new At("playAudio"+d,Ft.tapTrigger(t),h);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 At("playAudioOnStart"+d,Ft.sceneStartTrigger(),h);e.addBehavior(p)}}}}Be([u(Ei)],Is.prototype,"target"),Be([u(URL)],Is.prototype,"clip"),Be([u()],Is.prototype,"toggleOnClick");const yy=class yo extends M{animator;stateName;trigger="tap";animation;get target(){return this.animator?.gameObject||this.animation?.gameObject}start(){Qc(this.gameObject)}onPointerEnter(){this.context.input.setCursor("pointer")}onPointerExit(){this.context.input.unsetCursor("pointer")}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(yo.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()&&ye(e),console.warn(e,...yo.rootsWithExclusivePlayback)}yo.animationActions=[],yo.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 sp);if(!n)return;const s=n.getClipCount(this.target)>1;s&&(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."),yo.rootsWithExclusivePlayback.add(this.target));const r=this.name?this.name:"";i.traverse(a=>{if(a.uuid===this.target?.uuid){const l=yo.getActionForSequences(i,a,this.animationSequence,this.animationLoopAfterSequence,this.randomOffsetNormalized),c=new At(this.trigger+"_"+r+"_toPlayAnimation_"+this.stateName+"_on_"+this.target?.name,this.trigger=="tap"?Ft.tapTrigger(this.selfModel):Ft.sceneStartTrigger(),l);s&&c.makeExclusive(!0),e.addBehavior(c)}})}static getActionForSequences(e,t,i,n,s){const r=(l,c)=>{let h=yo.animationActions.find(d=>d.affectedObjects==l&&d.start==c.start&&d.duration==c.duration&&d.animationSpeed==c.speed);return h||(h=ge.startAnimationAction(l,c),yo.animationActions.push(h)),h},a=ge.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:ge.sequence();for(const c of n)l.addAction(r(t,c));l.makeLooping(),a!==l&&a.addAction(l)}return s&&s>0&&a.actions.unshift(ge.waitAction(s)),a}static getAndRegisterAnimationSequences(e,t,i){if(!t)return;const n=t.getComponent(yt),s=t.getComponent(jt);if(!n&&!s)return;if(n&&!i)throw new Error("PlayAnimationOnClick: No stateName specified for animator "+n.name+" on "+t.name);let r=[],a=[];if(s){const f=e.registerAnimation(t,s.clip);f&&(s.loop?a.push(f):r.push(f));let g=0;if(s.minMaxOffsetNormalized){const y=s.minMaxOffsetNormalized.x,_=s.minMaxOffsetNormalized.y;g=(s.clip?.duration||1)*(y+Math.random()*(_-y))}return{animationSequence:r,animationLoopAfterSequence:a,randomTimeOffset:g}}const l=n?.runtimeAnimatorController;let c=l?.findState(i),h=[],d=[];if(l&&c){const f=new Array;f.push(c);let g=!1;for(;f.length<100;){if(!c||c===null||!c.transitions||c.transitions.length===0){c.motion?.isLooping&&(g=!0);break}const y=c.transitions.find(w=>w.conditions.length===0),_=y?l.getState(y.destinationState,0):null;if(_&&f.includes(_)){c=_,g=!0;break}else if(y){if(c=_,!c)break;f.push(c)}else{g=c.motion?.isLooping??!1;break}}if(g&&c){const y=f.indexOf(c);h=f.slice(0,y),d=f.slice(y),Hx&&console.log("found loop from "+i,"states until loop",h,"states looping",d)}else h=f,d=[],Hx&&console.log("found no loop from "+i,"states",h);if(!d.length){const y=h[h.length-1],_=y.motion?.clip;if(_){let w;if(e.holdClipMap.has(_))w=e.holdClipMap.get(_);else{const P=y.name+"_hold";w=_.clone(),w.duration=1,w.name=P;const R=_.duration;w.tracks=_.tracks.map(k=>{const j=k.clone();j.times=new Float32Array([0,R]);const L=k.values.length,W=k.getValueSize(),N=k.values.slice(L-W,L);return j.values=new Float32Array(2*W),j.values.set(N,0),j.values.set(N,W),j}),w.name=P,e.holdClipMap.set(_,w)}if(w){const P={name:w.name,motion:{clip:w,isLooping:!1,name:w.name},speed:1,transitions:[],behaviours:[],hash:y.hash+1};d.push(P)}}}}if(h.length===1&&(!h[0].motion?.clip||h[0].motion?.clip.tracks?.length===0)){r=new Array;const f=e.registerAnimation(t,null);f&&r.push(f);return}if(h=h.filter(f=>f.motion?.clip&&f.motion?.clip.tracks?.length>0),d=d.filter(f=>f.motion?.clip&&f.motion?.clip.tracks?.length>0),h.length===0&&d.length===0){console.warn("No clips found for state "+i+" on "+n?.name+", can't export animation data");return}const p=(f,g)=>{if(!t)return;const y=e.registerAnimation(t,f.motion.clip??null);y?(y.speed=f.speed,g.push(y)):console.warn("Couldn't register animation for state "+f.name+" on "+n?.name)};if(h.length>0){r=new Array;for(const f of h)p(f,r)}if(d.length>0){a=new Array;for(const f of d)p(f,a)}let m=0;if(n&&l&&n.minMaxOffsetNormalized){const f=n.minMaxOffsetNormalized.x,g=n.minMaxOffsetNormalized.y;m=((h.length?h[0]:d.length?d[0]:null)?.motion.clip?.duration||1)*(f+Math.random()*(g-f))}return{animationSequence:r,animationLoopAfterSequence:a,randomTimeOffset:m}}createAnimation(e,t,i){if(!this.target||!this.animator&&!this.animation)return;const n=yo.getAndRegisterAnimationSequences(e,this.target,this.stateName);n&&(this.animationSequence=n.animationSequence,this.animationLoopAfterSequence=n.animationLoopAfterSequence,this.randomOffsetNormalized=n.randomTimeOffset,this.stateAnimationModel=t)}};Be([u(yt)],yy.prototype,"animator"),Be([u()],yy.prototype,"stateName");let Zc=yy;class gl extends M{getType(){}target;getDuration(){}}Be([u(O)],gl.prototype,"target");class Kc extends M{target}Be([u(gl)],Kc.prototype,"target");class Jc extends gl{type=1;duration=1;getType(){switch(this.type){case 1:return"hide";case 0:return"show"}}getDuration(){return this.duration}}Be([u()],Jc.prototype,"type"),Be([u()],Jc.prototype,"duration");class by extends Kc{}class or{static _instance;static create(){return new or}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 Fn.getOrCreate().createQRCode()}createQuicklookButton(){if(this._quicklookButton)return this._quicklookButton;const e=document.createElement("button");this._quicklookButton=e,e.dataset.needle="quicklook-button";const t=q.supportsQuickLookAR();e.innerText="View in AR",e.prepend(Pt("view_in_ar"));let i=!1,n=null;return e.addEventListener("click",()=>{n=Wa(Tn),n||(i=!0,n=new Tn),i&&(n.objectToExport=z.Current.scene),n?(e.classList.add("this-mode-is-requested"),n.exportAndOpen().then(()=>{e.classList.remove("this-mode-is-requested")}).catch(s=>{e.classList.remove("this-mode-is-requested"),console.error(s)})):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(Pt("view_in_ar")),i.title="Click to start an AR session",i.addEventListener("click",()=>Z.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)"),q.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(Pt("panorama_photosphere")),i.title="Click to start a VR session",i.addEventListener("click",()=>Z.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)"),q.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(Pt("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&&Te("This page doesn't allow popups. Please paste "+n+" into your browser.")}),this.listenToXRSessionState(t),this.hideElementDuringXRSession(t),q.isMozillaXR()||navigator.xr?.addEventListener("devicechange",()=>{navigator.xr?.isSessionSupported("immersive-vr")?t.style.display="none":t.style.display=""}),t}createQRCode(){return Fn.getOrCreate().createQRCode()}updateSessionSupported(e,t){if(!("xr"in navigator)){e.style.display="none";return}Z.isSessionSupported(t).then(i=>{e.style.display=i?"":"none",A()&&!i&&console.log('[WebXR] "'+t+'" is not supported on this device \u2013 make sure your server runs using HTTPS and you have a device connected that supports '+t)})}hideElementDuringXRSession(e){zd(t=>{e["previous-display"]=e.style.display,e.style.display="none"}),cg(t=>{e["previous-display"]!=null&&(e.style.display=e["previous-display"])})}listenToXRSessionState(e,t){t&&(Z.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"))}),Z.onSessionRequestEnd(i=>{e.classList.remove("this-mode-is-requested"),e.classList.remove("other-mode-is-requested"),e.disabled=e["was-disabled"]}))}}var hE=Object.defineProperty,dE=Object.getOwnPropertyDescriptor,_t=(o,e,t,i)=>{for(var n=i>1?void 0:i?dE(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&hE(e,t,n),n};const eh=v("debugspriterenderer"),uE=v("wireframe");class ba{static cache={};static getOrCreateGeometry(e){if(e.__cached_geometry)return e.__cached_geometry;if(e.guid&&ba.cache[e.guid])return eh&&console.log("Take cached geometry for sprite",e.guid),ba.cache[e.guid];const t=new gn;e.__cached_geometry=t;const i=new Float32Array(e.triangles.length*3),n=new Float32Array(e.triangles.length*2);for(let s=0;s<e.triangles.length;s+=1){const r=e.triangles[s];i[s*3]=-e.vertices[r].x,i[s*3+1]=e.vertices[r].y,i[s*3+2]=0;const a=e.uv[r];n[s*2]=a.x,n[s*2+1]=1-a.y}return t.setAttribute("position",new mt(i,3)),t.setAttribute("uv",new mt(n,2)),e.guid&&(this.cache[e.guid]=t),eh&&console.log("Built sprite geometry",e,t),t}}class pE{x;y}function Gx(o){o&&(o.colorSpace!=Co&&(o.colorSpace=Co,o.needsUpdate=!0),o.minFilter==Sd&&o.magFilter==Sd&&(o.anisotropy=1,o.needsUpdate=!0))}let Wo=class{constructor(o){o&&(this.texture=o,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 G(ba.getOrCreateGeometry(this),this.material)),this._mesh}_mesh;get material(){return this._material||(this.texture&&Gx(this.texture),this._material=new xe({map:this.texture,color:16777215,side:Si,transparent:!0})),this._material}_material;getGeometry(){return ba.getOrCreateGeometry(this)}};_t([u()],Wo.prototype,"guid",2),_t([u(Le)],Wo.prototype,"texture",2),_t([qe()],Wo.prototype,"triangles",2),_t([qe()],Wo.prototype,"uv",2),_t([qe()],Wo.prototype,"vertices",2);const _y=Symbol("spriteOwner");class fl{sprites;constructor(){this.sprites=[]}}_t([u(Wo)],fl.prototype,"sprites",2);const vy=class X0{static create(){const e=new X0;return e.spriteSheet=new fl,e}constructor(){}clone(){const e=new X0;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 fl,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&&(Gx(n),!i.__hasLoadedProgressive)){i.__hasLoadedProgressive=!0;const s=n;$e.assignTextureLOD(n,0).then(r=>{r instanceof Le&&(i.texture=r,e?.map===s&&(e.map=r,e.needsUpdate=!0))})}}};_t([u(fl)],vy.prototype,"spriteSheet",2),_t([u()],vy.prototype,"index",2);let yl=vy;class ui extends M{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=yl.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.round(e);eh&&console.log("[SpriteSheet] Set index to "+t+" (was "+this.spriteIndex+")",e),this.spriteIndex=t}else e instanceof Wo?(this._spriteSheet||(this._spriteSheet=yl.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=yl.create(),eh&&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 eh&&console.warn("Sprite not found",this.spriteIndex,t.spriteSheet.sprites),!1;if(this._currentSprite)this._currentSprite.geometry=ba.getOrCreateGeometry(i),this._currentSprite.material.map=i.texture;else{const n=new xe({color:16777215,side:Si});if(uE&&(n.wireframe=!0),this.color&&(n.color||(n.color=new ne),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 s=i.texture;s[_y]!==void 0&&s[_y]!==this&&this.spriteFrames>1&&(s=i.texture=s.clone()),s[_y]=this,n.map=s}this.sharedMaterial=n,this._currentSprite=new G(ba.getOrCreateGeometry(i),n),this._currentSprite.renderOrder=Math.round(this.renderOrder),$e.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}}_t([u()],ui.prototype,"drawMode",2),_t([u(pE)],ui.prototype,"size",2),_t([u(oe)],ui.prototype,"color",2),_t([u(ve)],ui.prototype,"sharedMaterial",2),_t([u()],ui.prototype,"transparent",2),_t([u()],ui.prototype,"cutoutThreshold",2),_t([u()],ui.prototype,"castShadows",2),_t([u()],ui.prototype,"renderOrder",2),_t([u()],ui.prototype,"toneMapped",2),_t([u(yl)],ui.prototype,"sprite",1);const qx=v("debugwebxr"),mE=new K().makeRotationY(Math.PI);class Ni extends M{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 K;_createdPlacementObject=null;_reparentedComponents=[];_placementScene=new vi;_reticle=[];_hits=[];_placementStartTime=-1;_rigPlacementMatrix;_anchor=null;userInput;onEnable(){this.customReticle?.preload()}supportsXR(e){return e==="immersive-ar"}onEnterXR(e){qx&&console.log("ENTER WEBXR: SessionRoot start..."),this._anchor=null,Ni._hasPlaced=!1,this.gameObject.updateMatrixWorld(),this._startOffset.copy(this.gameObject.matrixWorld);const t=new O;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=Gt(this._placementScene.children),n=i.getCenter(new b),s=i.getSize(new b),r=new K;r.makeTranslation(n.x,n.y-s.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)Zi(i);this._reticle.length=0,this._isPlacing=!0,this.context.input.addEventListener("pointerup",this.onPlaceScene,{queue:oi.Early})}onLeaveXR(){this.context.input.removeEventListener("pointerup",this.onPlaceScene,{queue:oi.Early}),this.onRevertSceneChanges(),this._anchor=null,Ni._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 s=n.getHitTest();s&&(i=!0,this.updateReticleAndHits(e.xr,n.index,s,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 hm(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 s=this._reticle[t];if(!s){if(this.customReticle)if(this.customReticle.asset)s=Ga(this.customReticle.asset);else{this.customReticle.loadAssetAsync();return}else s=new G(new bC(.07,.09,32).rotateX(-Math.PI/2),new xe({side:Si,depthTest:!1,depthWrite:!1,transparent:!0,opacity:1,color:15658734})),s.name="AR Placement Reticle";if(qx){const r=new xi(1);r.position.y+=.01,s.add(r)}this._reticle[t]=s,s.matrixAutoUpdate=!1,s.visible=!1}if(s.lastPos=s.lastPos||i.position.clone(),s.lastQuat=s.lastQuat||i.quaternion.clone(),s.position.copy(s.lastPos.lerp(i.position,this.context.time.deltaTime/.1)),s.lastPos.copy(s.position),s.quaternion.copy(s.lastQuat.slerp(i.quaternion,this.context.time.deltaTime/.05)),s.lastQuat.copy(s.quaternion),s.scale.set(n,n,n),this.customReticle&&this.applyViewBasedTransform(s),s.updateMatrix(),s.visible=!0,s.parent!==this.context.scene&&this.context.scene.add(s),this._placementStartTime<0&&(this._placementStartTime=this.context.time.realtimeSinceStartup),this.autoPlace)if(this.upVec.set(0,1,0).applyQuaternion(s.quaternion),this.upVec.dot(D(0,1,0))>.9){let r=s["autoplace:timer"]||0;r>=1?(s.visible=!1,this.onPlaceScene(null)):(r+=this.context.time.deltaTime,s["autoplace:timer"]=r)}else s["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(Z.active?.isTrackingImages){console.warn("Scene Placement is disabled while images are being tracked");return}let i=this._hits[0];if(e&&e.origin instanceof hg){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),Ni._hasPlaced=!0,this.useXRAnchor&&this.onCreateAnchor(Z.active,i),this.context.xr)for(const n of this.context.xr.controllers)n.cancelHitTestSource()};onSetScale(){if(!Ni._hasPlaced)return;const e=Z.active?.rig?.gameObject;if(e){const t=Z.active?.rigScale||1,i=1/this._arScale*t,n=new K().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()&&ye("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 b(0,1,0);lookPoint=new b;worldUpVec=new b(0,1,0);applyViewBasedTransform(e){const t=this.context.mainCamera,i=e,n=t.worldPosition,s=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=s.y,e.lookAt(n))}onApplyPose(e){const t=Z.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(mE),t.matrix.premultiply(this._startOffset),t.matrix.decompose(t.position,t.quaternion,t.scale),i.add(t)}}class hm{static up=new b(0,1,0);static zero=new b(0,0,0);static one=new b(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 K,this.plane=new hr,this.plane.setFromNormalAndCoplanarPoint(hm.up,hm.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:oi.Early}),this.context.input.addEventListener("pointerdown",this.onPointerDownLate,{queue:oi.Late}),this.context.input.addEventListener("pointerup",this.onPointerUpEarly,{queue:oi.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:oi.Early}),this.context.input.removeEventListener("pointerdown",this.onPointerDownLate,{queue:oi.Late}),this.context.input.removeEventListener("pointerup",this.onPointerUpEarly,{queue:oi.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=q.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 s=this.prev.get(i.identifier);if(s){const r=this.getPositionOnPlane(i.clientX,i.clientY);s.x=r.x,s.z=r.z,s.screenx=i.clientX,s.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),s=n.x-i.x,r=n.z-i.z;if(s===0&&r===0)return;this.oneFingerDrag&&this.addMovement(s,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),s=this.prev.get(i.identifier);if(!n||!s)return;if(this.twoFingerRotate){const r=Math.atan2(t.clientY-i.clientY,t.clientX-i.clientX),a=Math.atan2(n.screeny-s.screeny,n.screenx-s.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),c=n.screenx-s.screenx,h=n.screeny-s.screeny,d=Math.sqrt(c*c+h*h),p=l-d;Math.abs(p)>2&&this.addScale(p)}n.screenx=t.clientX,n.screeny=t.clientY,s.screenx=i.clientX,s.screeny=i.clientY}}};_raycaster=new yd;_intersection=new b;_screenPos=new b;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 K;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 Ls=v("debugautosync"),wy=Symbol("syncerId");class gE{_syncers={};getOrCreateSyncer(e){if(!e.guid)return null;if(this._syncers[e.guid])return this._syncers[e.guid];const t=new fE(e);return t[wy]=e.guid,this._syncers[t[wy]]=t,t}removeSyncer(e){delete this._syncers[e[wy]]}}const xy=new gE;class fE{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||(Ls&&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];Ls&&console.log("SEND",this.comp.guid,this.networkingKey),e.send(this.networkingKey,{guid:this.comp.guid,property:t,data:i},vn.Queued),delete this.changedProperties[t]}};onHandleReceiving=e=>{if(Ls&&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 yE(o,e){let t=e!==o;return!t&&o&&e&&(Array.isArray(o)&&Array.isArray(e)||typeof o=="object"&&typeof e=="object")&&(t=!0),t}const th=Symbol("AutoSyncHandler");function bE(o){if(o[th])return o[th];const e=xy.getOrCreateSyncer(o);return e?.init(o),o[th]=e,e}function _E(o){const e=o[th];e&&(xy.removeSyncer(e),e.destroy(),delete o[th])}const Sy=function(o=null){return function(e,t){let i="";typeof t=="string"?i=t:i=t.name;let n=null,s;typeof o=="string"?s=e[o]:typeof o=="function"&&(s=o),s==null&&(A()||Ls)&&o!=null&&console.warn('syncField: no callback function found for property "'+i+'"','"'+o+'"');const r=e,a=r.__internalAwake;if(typeof a!="function"){(Ls||A())&&console.error('@syncField can currently only used on Needle Engine Components, custom object of type "'+e?.constructor?.name+'" is not supported',e);return}Ls&&console.log(i);const l=Symbol(i);r.__internalAwake=function(){if(this[l]===void 0){if(this[l]=this[i],n=xy.getOrCreateSyncer(this),Object.getOwnPropertyDescriptor(this,i)?.set===void 0){let h=!1;Object.defineProperty(this,i,{set:function(d){const p=this[l];if(this[l]=d,h){(A()||Ls)&&console.warn("Recursive call detected",i);return}h=!0;try{const m=yE(d,p);Ls&&console.log("SyncField assignment",i,"changed?",m,d,s),m&&s?.call(this,d,p)!==!1&&bE(this)?.notifyChanged(i,d)}finally{h=!1}},get:function(){return this[l]},configurable:!0,enumerable:!0})}n?.init(this),a.call(this)}};const c=r.__internalDestroy;r.__internalDestroy=function(){_E(this),c.call(this)}}};var vE=Object.defineProperty,ap=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&vE(e,t,n),n};const Jt=v("debugplayersync"),lp=class gS extends M{static async setupFrom(e,t){const i=ie.getOrCreateFromUrl(e);if(!i.asset){const r=await i.loadAssetAsync();r&&x.getOrAddComponent(r,kn)}const n=new gS;n._internalInit(t),n.asset=i;const s=new O;return s.guid=e,x.addComponent(s,n),n}autoSync=!0;asset;onPlayerSpawned;_localInstance;awake(){this.watchTabVisible(),this.onPlayerSpawned||(this.onPlayerSpawned=new he)}onEnable(){this.context.connection.beginListen(te.RoomStateSent,this.onJoinedRoom),this.context.connection.beginListen(te.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(te.LeftRoom,this.destroyInstance),this.context.connection.isInRoom&&this.onJoinedRoom()}onDisable(){this.context.connection.stopListen(te.RoomStateSent,this.onJoinedRoom),this.context.connection.stopListen(te.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(te.LeftRoom,this.destroyInstance)}onJoinedRoom=()=>{Jt&&console.log("PlayerSync.joinedRoom. autoSync is set to "+this.autoSync),this.autoSync&&this.getInstance()};async getInstance(){if(this._localInstance)return this._localInstance;if(Jt&&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,kn);if(Jt&&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=>{Jt&&console.log("PlayerSync.destroyInstance",e),vc(e,this.context.connection,!0,{saveInRoom:!1})}),this._localInstance=void 0};watchTabVisible(){window.addEventListener("visibilitychange",e=>{if(document.visibilityState==="visible")for(let t=kn.all.length-1;t>=0;t--){const i=kn.all[t];(!i.owner||!this.context.connection.userIsInRoom(i.owner))&&i.doDestroy()}})}};ap([u()],lp.prototype,"autoSync"),ap([u(ie)],lp.prototype,"asset"),ap([u(he)],lp.prototype,"onPlayerSpawned");let Cy=lp;var Xx=(o=>(o.OwnerChanged="ownerChanged",o))(Xx||{});const Py=class Tt extends M{static _all=[];static get all(){return Tt._all}static _local=[];static get local(){return Tt._local}static getFor(e){if(e instanceof O)return x.getComponentInParent(e,Tt);if(e instanceof M)return x.getComponentInParent(e.gameObject,Tt)}static isLocalPlayer(e){return Tt.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 he;onFirstOwnerChangeEvent=new he;hasOwner=!1;owner;dontDestroy=!1;get isLocalPlayer(){return this.owner===this.context.connection.connectionId}onOwnerChange(e,t){Jt&&console.log(`PlayerSync.onOwnerChange: ${t} \u2192 ${e} (me: ${this.context.connection.connectionId})`);const i=Tt._local.indexOf(this);i>=0&&Tt._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){Tt._local.push(this);const r=new CustomEvent("local-owner-changed",{detail:n});this.dispatchEvent(r)}const s=new CustomEvent("owner-changed",{detail:n});this.dispatchEvent(s),Tt.dispatchEvent("ownerChanged",s)}awake(){Tt.all.push(this),Jt&&console.log("Registered new PlayerState",this.guid,Tt.all.length-1,Tt.all),this.context.connection.beginListen(te.UserLeftRoom,this.onUserLeftRoom)}async start(){Jt&&console.log("PLAYERSTATE.START, owner: "+this.owner,this.context.connection.usersInRoom([])),this.owner?(this.context.connection.isInRoom||await Wn(300),this.context.connection.userIsInRoom(this.owner)==!1&&(Jt&&console.log(`PlayerSync.start \u2192 doDestroy "${this.name}" because user "${this.owner}" is not in room anymore...`,"Currently in room:",...this.context.connection.usersInRoom()),this.doDestroy())):this.owner||(Jt&&console.warn("PlayerState.start \u2192 owner is undefined!",this.name),setTimeout(()=>{!this.destroyed&&!this.owner?this.dontDestroy?Jt&&console.warn("PlayerState.start \u2192 owner is still undefined but dontDestroy is set to true",this.name):(Jt&&console.warn(`PlayerState.start \u2192 owner is still undefined: destroying "${this.name}" instance now`),this.doDestroy()):Jt&&console.log("PlayerState.start \u2192 owner is assigned",this.owner)},2e3))}doDestroy(){Jt&&console.log("PlayerSync.doDestroy \u2192 syncDestroy",this.name),vc(this.gameObject,this.context.connection,!0,{saveInRoom:!1})}onDestroy(){if(Jt&&console.warn("PlayerState.onDestroy",this.owner),this.context.connection.stopListen(te.UserLeftRoom,this.onUserLeftRoom),Tt.all.splice(Tt.all.indexOf(this),1),this.isLocalPlayer){const e=Tt._local.indexOf(this);e>=0&&Tt._local.splice(e,1)}}onUserLeftRoom=e=>{if(e.userId===this.owner){Jt&&console.log("PLAYERSYNC LEFT",this.owner),this.doDestroy();return}}};ap([Sy(Py.prototype.onOwnerChange)],Py.prototype,"owner");let kn=Py;var wE=Object.defineProperty,bl=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&wE(e,t,n),n};class ro extends M{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&&(q.isMobileDevice()||this.context.menu.showQRCodeButton(!0))}}bl([u()],ro.prototype,"position"),bl([u()],ro.prototype,"showNeedleLogo"),bl([u()],ro.prototype,"showSpatialMenu"),bl([u()],ro.prototype,"createFullscreenButton"),bl([u()],ro.prototype,"createMuteButton"),bl([u()],ro.prototype,"createQRCodeButton");var xE=Object.defineProperty,Oy=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&xE(e,t,n),n};const ih=v("debugwebxr"),Qx=new U().setFromAxisAngle(new b(0,1,0),Math.PI);class js extends M{head;leftHand;rightHand;_leftHandMeshes;_rightHandMeshes;_syncTransforms;async onEnterXR(e){if(!this.activeAndEnabled)return;ih&&console.warn("AVATAR ENTER XR",this.guid,this.sourceId,this,this.activeAndEnabled),this._syncTransforms&&(this._syncTransforms.length=0),await this.prepareAvatar();const t=kn.getFor(this);if(t?.owner){const i=this.gameObject.addComponent(Ie);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(Ie);t&&t.destroy()}onUpdateXR(e){if(!this.activeAndEnabled)return;const t=kn.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 c=x.getComponentsInChildren(this.head.asset,en);for(const h of c)h.enabled=!1,h.gameObject.visible=!1}}const n=e.xr.leftController,s=this.leftHand?.asset;n&&s?(s.position.copy(n.gripPosition),s.quaternion.copy(n.gripQuaternion),s.quaternion.multiply(Qx),s.visible=n.isTracking,this.updateHandVisibility(n,s,this._leftHandMeshes)):s&&s.visible&&(s.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(Qx),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(s=>{Ao(s,!n)})}}updateRemoteAvatarVisibility(){if(this.context.connection.isConnected){const e=kn.getFor(this);if(e&&e.isLocalPlayer==!1){const t=Z.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,en);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};G_.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 O&&(this.head=new ie("",this.sourceId,this.head));else{const e=new O;e.name="Head";const t=xr.createPrimitive(wr.Cube);e.add(t),this.gameObject.add(e),this.head=new ie("",this.sourceId,e),ih&&console.log("Create head",e)}if(this.rightHand)this.rightHand instanceof O&&(this.rightHand=new ie("",this.sourceId,this.rightHand));else{const e=new O;e.name="Right Hand",this.gameObject.add(e),this.rightHand=new ie("",this.sourceId,e),ih&&console.log("Create right hand",e)}if(this.leftHand)this.leftHand instanceof O&&(this.leftHand=new ie("",this.sourceId,this.leftHand));else{const e=new O;e.name="Left Hand",this.gameObject.add(e),this.leftHand=new ie("",this.sourceId,e),ih&&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)}),kn.isLocalPlayer(this.gameObject)&&(this._syncTransforms=x.getComponentsInChildren(this.gameObject,Pn))}async loadAvatarObjects(e,t,i){const n=e.loadAssetAsync(),s=t.loadAssetAsync(),r=i.loadAssetAsync(),a=new Array;n&&a.push(n),s&&a.push(s),r&&a.push(r);const l=await zm(a);ih&&console.log("Avatar loaded results:",l)}}Oy([u(ie)],js.prototype,"head"),Oy([u(ie)],js.prototype,"leftHand"),Oy([u(ie)],js.prototype,"rightHand");var SE=Object.defineProperty,cp=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&SE(e,t,n),n};const Ds=v("debugwebxr"),Bs=new Array;class $o extends M{createControllerModel=!0;createHandModel=!0;customLeftHand;customRightHand;static factory=new QC;supportsXR(e){return e==="immersive-vr"||e==="immersive-ar"}_models=new Array;async onXRControllerAdded(e){if(!(e.xr.isVR||e.xr.isPassThrough))return;console.debug("XR Controller Added",e.controller.side,e.controller.index);const{controller:t}=e;if(this.createControllerModel||this.createHandModel){if(t.hand){if(this.createHandModel){const i=await this.loadHandModel(this,t);if(!i||!t.connected||!t.isHand){i?.handObject&&Ha(i.handObject,!1),i?.handObject?.destroy();return}this._models.push({controller:t,model:i.handObject,handmesh:i.handmesh}),this._models.sort((n,s)=>n.controller.index-s.controller.index),this.scene.add(i.handObject),t.model=i.handObject}}else if(this.createControllerModel){const i=await t.getModelUrl();if(i){const n=await this.loadModel(t,i);if(!n||!t.connected||t.isHand)return;this._models.push({controller:t,model:n}),this._models.sort((s,r)=>s.controller.index-r.controller.index),this.scene.add(n),n.traverse(s=>{s.layers.set(2),s.matrixAutoUpdate=!1,s.updateMatrix()}),t.model=n}else t.targetRayMode!=="transient-pointer"&&console.warn("XRControllerModel: no model found for "+t.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&&(Ha(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&&(Ha(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(Z.active&&(Ds&&(Bs[0]=Date.now()),this.updateRendering(Z.active),Ds)){const e=Date.now()-Bs[0];Bs.push(e),Bs.length>=30&&(Bs[0]=0,Bs.reduce((t,i)=>t+i,0)/Bs.length,Bs.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){Ds&&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 s=e.referenceSpace,r=this.context.renderer.xr.getHand(n.index);if(s&&e.frame.getJointPose){for(const a of n.inputSource.hand.values()){const l=r.joints[a.jointName];if(l){const c=n.getHandJointPose(a);if(c){const h=c.transform.position,d=c.transform.orientation;l.position.copy(h),l.quaternion.copy(d),l.matrixAutoUpdate=!1}l.visible=c!=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(La))}}}}async loadModel(e,t){if(!e.connected)return console.warn("XRControllerModel.onXRControllerAdded: controller is not connected anymore",e.side),null;const i=await ie.getOrCreate("",t).instantiate();return Ha(i),Z.active?.isPassThrough&&i.traverseVisible(n=>{this.makeOccluder(n)}),i}async loadHandModel(e,t){const i=this.context,n=i.renderer.xr.getHand(t.index);n||(Ds?B.DrawLabel(t.rayWorldPosition,"No hand found for index "+t.index,.05,5):console.warn("No hand found for index "+t.index));const s=new Po;pf(s,i),await Gu(s,i,this.sourceId??"",this.sourceId??"");const r=Hf(s);let a="";const l=t.side==="left"?this.customLeftHand:this.customRightHand;l?(a=l.url.split(".").slice(0,-1).join("."),s.setPath("")):(a=t.inputSource.handedness==="left"?"left":"right",s.setPath("https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles/generic-hand/"));const c=new O;Ha(c);const h=new YC(c,n,s.path,a,s,d=>{const p=r?.gltf;p?.scene.children?.length===0&&(p.scene.children[0]=d),r?.gltf&&_n().createBuiltinComponents(e.context,e.sourceId||a,r.gltf,null,r),d.traverse(m=>{m.layers.set(2),Z.active?.isPassThrough&&!l&&this.makeOccluder(m),m instanceof G&&$e.assignMeshLOD(m,0)}),t.connected||(Ds&&B.DrawLabel(t.rayWorldPosition,"Hand is loaded but not connected anymore",.05,5),d.removeFromParent())});if(Ds&&c.add(new xi(.5)),t.inputSource.hand){Ds&&console.log(t.inputSource.hand);for(const d of t.inputSource.hand.values())if(n.joints[d.jointName]===void 0){const p=new xo;p.matrixAutoUpdate=!1,p.visible=!0,n.joints[d.jointName]=p,n.add(p)}}else Ds&&B.DrawLabel(t.rayWorldPosition,"No inputSource.hand found for index "+t.index,.05,5);return{handObject:c,handmesh:h}}makeOccluder(e){if(e instanceof G){let t=e.material;t instanceof ve&&(t=e.material=t.clone(),t.depthWrite=!0,t.depthTest=!0,t.colorWrite=!1,e.receiveShadow=!1,e.renderOrder=-100)}}}cp([u()],$o.prototype,"createControllerModel"),cp([u()],$o.prototype,"createHandModel"),cp([u(ie)],$o.prototype,"customLeftHand"),cp([u(ie)],$o.prototype,"customRightHand");class hp extends M{}var CE=Object.defineProperty,Fs=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&CE(e,t,n),n};const ky=v("debugwebxr");class Ii extends M{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=D(i.x,0,i.y);n.multiplyScalar(this.context.time.deltaTimeUnscaled*this.movementSpeed);const s=He(t);n.multiplyScalar(s.x),n.applyQuaternion(e.xr.poseOrientation),n.y=0,n.applyQuaternion(t.worldQuaternion),A()&&Number.isNaN(n.x)&&console.error("Stick movement resulted in NaN",{stick:i,vec:n}),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 i=e.getStick("xr-standard-thumbstick").x;if(this._didApplyRotation)Math.abs(i)<.3&&(this._didApplyRotation=!1);else if(Math.abs(i)>.5){this._didApplyRotation=!0;const n=i>0?1:-1,s=J(this.context.mainCamera).clone();t.rotateY(n*I.toRadians(this.rotationStep));const r=J(this.context.mainCamera).clone().sub(s);r.y=0,t.position.sub(r)}}_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 s=e.getGesture("pinch");s&&(i=s.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 ka){const r=n.normal?.dot(D(0,1,0));if(r!==void 0&&r<.4)return}let s=n?.point;if(!s&&!this.useTeleportTarget){this._plane||(this._plane=new hr(new b(0,1,0),0));const r=t.worldPosition;this._plane.setFromNormalAndCoplanarPoint(new b(0,1,0),r);const a=e.ray;s=r.clone(),this._plane.intersectLine(new _C(a.origin,D(a.direction).multiplyScalar(1e4).add(a.origin)),s),s.distanceTo(r)>t.scale.x*10&&(s=null)}if(s){if(this.useTeleportTarget&&!x.getComponentInParent(n.object,hp))return;const r=s.clone();if(ky&&B.DrawSphere(s,.025,16711680,5),this.context.mainCamera?.position){const a=this.context.xr?.getUserOffsetInRig();a&&(a.y=0,r.sub(a),ky&&B.DrawWireSphere(a.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 s=i.rayWorldPosition,r=i.rayWorldQuaternion;n.position.copy(s),n.quaternion.copy(r);const a=e.rigScale,l=this.usePinchToTeleport&&i.isTeleportGesture,c=this._lastHitDistances[t],h=this._hitDistances[t]!=null,d=c??a;n.scale.set(a,a,d),n.visible=!0,n.layers.disableAll(),n.layers.enable(2);let p=n.material.opacity;l?p=1:this.showHits&&d<e.rigScale*.5?p=0:i.getButton("primary")?.pressed?p=.5:p=h?.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],s=!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,s=!1);const a=this.context.time.smoothedFps>=59?1:10;if((this.context.time.frame+i.index)%a!==0&&(s=!1),!s){const h=this._hitDiscs[t];h&&h.visible&&h.hit&&this.updateHitPointerPosition(i,h,h.hit.distance);continue}const l=this.context.physics.raycastFromRay(i.ray,{testObject:this.hitPointRaycastFilter,precise:!1});let c=l.find(h=>this.usePinchToTeleport&&i.isTeleportGesture?!0:this.isObjectWithInteractiveComponent(h.object));if(c||(c=l[0]),n&&(n.controller=i,n.hit=c),this._hitDistances[t]=c?.distance||null,c){this._lastHitDistances[t]=c.distance;const h=e.rigScale??1;ky&&(B.DrawWireSphere(c.point,.025*h,16711680),B.DrawLabel(D(0,.2,0).add(c.point),c.object.name,.02,0)),n||(n=this.createHitPointObject(),this._hitDiscs[t]=n),n.hit=c,n.visible=c.distance>h*.05;let d=.01*(h+c.distance);const p=i.getButton("primary")?.pressed;p&&(d*=1.1),n.scale.set(d,d,d),n.layers.set(2);let m=n.material.opacity;if(p?m=1:m=c.distance<.15*h?.2:.6,n.material.opacity=I.lerp(n.material.opacity,m,this.context.time.deltaTimeUnscaled/.1),n.visible){if(c.normal){this.updateHitPointerPosition(i,n,c.distance);const f=c.normal.applyQuaternion(be(c.object));n.quaternion.setFromUnitVectors(PE,f)}else this.updateHitPointerPosition(i,n,c.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 Tu(e)||e.isUI===!0?!0:e.isScene?!1:e.parent?this.isObjectWithInteractiveComponent(e.parent,t+1):!1}updateHitPointerPosition(e,t,i){const n=D(e.rayWorldPosition);n.add(D(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 G(new fd(.3,6,6),new xe({color:15658734,opacity:.7,transparent:!0,depthTest:!1,depthWrite:!1,side:Si}));return e.layers.disableAll(),e.layers.enable(2),e}createRayLineObject(){const e=new ZC;e.layers.disableAll(),e.layers.enable(2);const t=new KC;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 s=new JC({color:16777215,vertexColors:!0,worldUnits:!0,linewidth:.004,transparent:!0,depthWrite:!1,blending:hb,dashed:!1});return e.material=s,e}}Fs([u()],Ii.prototype,"movementSpeed"),Fs([u()],Ii.prototype,"rotationStep"),Fs([u()],Ii.prototype,"useTeleport"),Fs([u()],Ii.prototype,"usePinchToTeleport"),Fs([u()],Ii.prototype,"useTeleportTarget"),Fs([u()],Ii.prototype,"useTeleportFade"),Fs([u()],Ii.prototype,"showRays"),Fs([u()],Ii.prototype,"showHits");const PE=new b(0,1,0);var OE=Object.defineProperty,vt=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&OE(e,t,n),n};const nh=v("debugwebxr"),kE=v("debugusdz"),at=class Vl extends M{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(){Z.getXRSync(this.context)}onEnable(){window.location.protocol!=="https:"&&ye('<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(Tn)||(nh&&console.log("WebXR: Adding USDZExporter"),this._usdzExporter=x.addComponent(this.gameObject,Tn),this._usdzExporter.objectToExport=this.context.scene,this._usdzExporter.autoExportAnimations=!0,this._usdzExporter.autoExportAudioSources=!0)),this.handleCreatingHTML(),this.handleOfferSession(),this.defaultAvatar===!0&&(nh&&console.warn("WebXR: No default avatar set, using static default avatar"),this.defaultAvatar=new ie("https://cdn.needle.tools/static/avatars/DefaultAvatar.glb")),this.defaultAvatar&&(this._playerSync=this.gameObject.getOrAddComponent(Cy),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 Z.isVRSupported()&&this.createVRButton?Z.offerSession("immersive-vr","default",this.context):this.createARButton&&await Z.isARSupported()&&this.createARButton?Z.offerSession("immersive-ar","default",this.context):!1}get session(){return Z.active??null}get sessionMode(){return Z.activeMode??null}get arSessionRoot(){return this._activeWebARSessionRoot}async enterVR(e){return Z.start("immersive-vr",e,this.context)}async enterAR(e){return Z.start("immersive-ar",e,this.context)}exitXR(){Z.stop()}_exitXRMenuButton;_previousXRState=0;_spatialGrabRaycaster;_activeWebARSessionRoot=null;get isActiveWebXR(){return!Vl.activeWebXRComponent||Vl.activeWebXRComponent===this}onBeforeXR(e,t){if(!this.isActiveWebXR){console.warn(`WebXR: another WebXR component is already active (${Vl.activeWebXRComponent?.name}). This is ignored: ${this.name}`);return}if(this.activeAndEnabled===!1||this.destroyed){console.debug("[WebXR] onBeforeXR called on disabled or destroyed component");return}Vl.activeWebXRComponent=this,e=="immersive-ar"&&this.useDepthSensing&&(t.optionalFeatures=t.optionalFeatures||[],t.optionalFeatures.push("depth-sensing"))}async onEnterXR(e){if(!this.isActiveWebXR)return;nh&&console.log("WebXR onEnterXR"),this._previousXRState=ti.Global.Mask;const t=e.xr.isVR;if(ti.Global.Set(t?eo.VR:eo.AR),e.xr.isAR){let i=x.findObjectOfType(Ni);if(!i)if(this.usePlacementReticle){const n=new O;for(const s of this.context.scene.children)n.add(s);this.context.scene.add(n),i=x.addComponent(n,Ni),this._createdComponentsInSession.push(i)}else(nh||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(ga)??void 0,this._spatialGrabRaycaster||(this._spatialGrabRaycaster=this.gameObject.addComponent(ga))),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){ti.Global.Set(this._previousXRState),this._playerSync?.destroyInstance();for(const t of this._createdComponentsInSession)t.destroy();this._createdComponentsInSession.length=0,this._activeWebARSessionRoot=null,this.handleOfferSession(),tc(1).then(()=>Vl.activeWebXRComponent=null)}}setDefaultMovementEnabled(e){let t=this.gameObject.getComponent(Ii);return!t&&e&&(t=this.gameObject.addComponent(Ii),this._createdComponentsInSession.push(t)),t&&(t.enabled=e),t}setDefaultControllerRenderingEnabled(e){let t=this.gameObject.getComponent($o);return!t&&e&&(t=this.gameObject.addComponent($o),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=>{nh&&console.log("WebXR.onAvatarSpawned",e);let t=x.getComponentInChildren(e,js);t??=x.addComponent(e,js)};getButtonsContainer(){return this.getButtonsFactory()}getButtonsFactory(){return this._buttonFactory||(this._buttonFactory=or.getOrCreate()),this._buttonFactory}_buttonFactory;handleCreatingHTML(){if(this.createARButton||this.createVRButton||this.useQuicklookExport){if((q.isiOS()&&q.isSafari()||kE)&&this.useQuicklookExport){const e=x.findObjectOfType(Tn);if(!e||e&&e.allowCreateQuicklookButton){const t=this.getButtonsFactory().createQuicklookButton();this.addButton(t,50)}}if(this.createARButton){const e=this.getButtonsFactory().createARButton();this.addButton(e,50)}if(this.createVRButton){const e=this.getButtonsFactory().createVRButton();this.addButton(e,50)}}if(this.createSendToQuestButton&&!q.isQuest()&&Z.isVRSupported().then(e=>{if(!e){const t=this.getButtonsFactory().createSendToQuestButton();this.addButton(t,50)}}),this.createQRCode){const e=Wa(ro);if(e&&e.createQRCodeButton===!1)A()&&console.warn("WebXR: QRCode button is disabled in the Needle Menu component");else if(!q.isMobileDevice()){const t=Fn.getOrCreate().createQRCode();this.addButton(t,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}};vt([u()],at.prototype,"createVRButton"),vt([u()],at.prototype,"createARButton"),vt([u()],at.prototype,"createSendToQuestButton"),vt([u()],at.prototype,"createQRCode"),vt([u()],at.prototype,"useDefaultControls"),vt([u()],at.prototype,"showControllerModels"),vt([u()],at.prototype,"showHandModels"),vt([u()],at.prototype,"usePlacementReticle"),vt([u(ie)],at.prototype,"customARPlacementReticle"),vt([u()],at.prototype,"usePlacementAdjustment"),vt([u()],at.prototype,"arScale"),vt([u()],at.prototype,"useXRAnchor"),vt([u()],at.prototype,"autoPlace"),vt([u()],at.prototype,"autoCenter"),vt([u()],at.prototype,"useQuicklookExport"),vt([u()],at.prototype,"useDepthSensing"),vt([u()],at.prototype,"useSpatialGrab"),vt([u(ie)],at.prototype,"defaultAvatar");let dp=at;const up=v("debugusdzbehaviours");class My{get extensionName(){return"Behaviour"}behaviours=[];addBehavior(e){this.behaviours.push(e)}addAudioClip(e){if(!e||typeof e!="string")return"";const t="audio/"+fa.getName(e);return this.audioClips.push({clipUrl:e,filesKey:t}),t}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 s=n;if(typeof s.createBehaviours=="function"||typeof s.beforeCreateDocument=="function"||typeof s.afterCreateDocument=="function"||typeof s.afterSerialize=="function"){this.behaviourComponents.push(s);const r=s.beforeCreateDocument?.call(s,this,e);r instanceof Promise&&t.push(r)}},!1)}),up&&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 d of this.behaviourComponents)typeof d.afterCreateDocument=="function"&&d.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,s=new Set,r=up;let a=`graph LR
|
|
1276
1276
|
`,l="";function c(d){if(d instanceof Hr){r&&(a+=`subgraph Group_${d.id}
|
|
1277
1277
|
`);for(const p of d.actions)r&&(a+=`${d.id}[${d.id}] -- ${d.type},loops:${d.loops} --> ${p.id}[${p.id}]
|
|
1278
1278
|
`),c(p);r&&(a+=`end
|