Replace invalid ddeleteOriginalAssets with deleteOriginalAssets: false so vite-plugin-compression2 keeps uncompressed JS/CSS alongside .gz files. Without this, index.html referenced missing chunks and the scene failed to load. Rebuild MenuScene and SampleScene production bundles. Made-with: Cursor
325 lines
332 KiB
JavaScript
325 lines
332 KiB
JavaScript
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./needle-engine.dep.BzZBR-mM.js","./needle-engine.D6xdy26G.js","./three@0.169.19.js","./rolldown-runtime.CYVBeYYp.js"])))=>i.map(i=>d[i]);
|
||
import{d as e}from"./materialx.CnHmG--Y.js";import{$t as t,A as n,Ar as r,At as i,Bt as a,Cn as o,Cr as s,Dt as c,Et as l,Fr as u,G as d,Gt as f,Ir as p,It as m,Jt as h,K as g,Kn as _,Mt as ee,On as te,Qn as ne,Qt as v,R as re,S as ie,Sn as ae,Vt as oe,Wn as y,Wt as se,Xn as ce,Xt as b,Yn as le,Zn as ue,Zt as x,_ as de,_n as fe,_r as pe,a as me,an as he,b as ge,d as _e,dt as ve,er as ye,fn as S,gn as be,gr as xe,gt as Se,ht as Ce,i as we,in as Te,jr as C,kr as Ee,l as De,lt as Oe,m as ke,mn as Ae,nt as je,pt as Me,qt as Ne,r as Pe,rn as Fe,sr as Ie,tn as Le,tr as Re,tt as ze,u as Be,ur as Ve,vn as He,wn as Ue,wr as We,x as Ge,xr as Ke}from"./three@0.169.19.js";import{$a as qe,$i as Je,$r as Ye,Aa as Xe,An as Ze,Ba as Qe,Bi as $e,Bn as et,Bo as tt,Br as w,C as nt,Co as rt,Cr as it,Ct as at,Di as ot,Ei as st,Er as ct,Fi as lt,Gi as ut,Gn as dt,Ho as ft,Ht as pt,Ia as mt,Jn as ht,Jt as gt,Ka as T,Kt as _t,L as vt,Lr as yt,Lt as bt,Ma as xt,Mr as St,N as Ct,Ni as wt,Nr as Tt,Nt as Et,Oa as Dt,P as Ot,Q as kt,Qi as At,Qn as jt,Qr as Mt,Qt as Nt,Rr as Pt,Sn as Ft,Sr as It,Tt as Lt,Ua as Rt,Uo as zt,Vt as Bt,Wn as Vt,Wo as Ht,X as Ut,Xi as E,Xn as Wt,Yn as Gt,Yt as Kt,Zi as qt,Zr as Jt,_a as Yt,_n as Xt,_t as Zt,an as Qt,ba as $t,c as en,co as D,cr as O,ct as k,dn as tn,ei as nn,eo as A,fi as rn,fn as j,gn as an,gr as on,hn as sn,j as cn,jo as ln,kn as un,kt as dn,la as fn,ln as pn,m as M,ma as mn,mi as hn,mr as gn,mt as _n,na as vn,ni as yn,nn as bn,o as xn,oo as Sn,ot as N,p as Cn,pa as wn,pn as Tn,q as En,qi as Dn,qt as On,ra as kn,s as An,so as jn,sr as Mn,ta as Nn,ti as Pn,to as Fn,tr as In,un as Ln,va as Rn,vi as zn,wi as Bn,wr as Vn,x as Hn,y as Un,yn as Wn,yt as Gn,z as Kn,zn as qn,zo as Jn}from"./needle-engine-ui.B3WhUziG.js";import{a as Yn,c as Xn,i as Zn,o as Qn,p as $n,s as er}from"./three-examples.extras@0.169.19.js";import{a as tr,c as nr,i as rr,n as P,o as ir,r as ar,s as or}from"./gltf-progressive.U_EoiMHF.js";import{S as sr,c as cr,d as lr,f as ur,l as dr,p as fr,r as pr,s as mr,u as hr}from"./three-examples@0.169.19.js";var gr=D(`debugwebxr`),_r=class{static tryFindAvatarObjects(e,t,n){if(n.head&&n.leftHand&&n.rightHand)return;let r=e.name.toLocaleLowerCase();!n.head&&r.includes(`head`)&&(gr&&console.log(`FOUND AVATAR HEAD`,e.name),n.head=new w(``,t,e)),r.includes(`hand`)&&(!n.leftHand&&r.includes(`left`)&&(gr&&console.log(`FOUND AVATAR LEFT HAND`,e.name),n.leftHand=new w(``,t,e)),!n.rightHand&&r.includes(`right`)&&(gr&&console.log(`FOUND AVATAR RIGHT HAND`,e.name),n.rightHand=new w(``,t,e)));for(let r=0;r<e.children.length;r++){if(n.head&&n.leftHand&&n.rightHand)return;let i=e.children[r];this.tryFindAvatarObjects(i,t,n)}}},vr=function(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},yr=D(`debuganimation`),br=class{x;y},xr=class extends N{get isAnimationComponent(){return!0}addClip(e){this.animations||=[],this.animations.includes(e)||this.animations.push(e)}playAutomatically=!0;randomStartTime=!1;minMaxSpeed;minMaxOffsetNormalized;loop=!0;clampWhenFinished=!1;get time(){if(this.actions){for(let e of this.actions)if(e.isRunning())return e.time}return 0}set time(e){if(this.actions)for(let t of this.actions)t.time=e}get duration(){if(this.actions){for(let e of this.actions)if(e.isRunning())return e.getClip().duration}return 0}_tempAnimationClipBeforeGameObjectExisted=null;get clip(){return this.animations?.length?this.animations[0]:null}set clip(e){if(!this.__didAwake){yr&&console.warn(`Assign clip during serialization`,e),this._tempAnimationClipBeforeGameObjectExisted=e;return}e&&(this.gameObject.animations||(this.gameObject.animations=[]),!this.animations.includes(e)&&(this.animations.length>0?this.animations.splice(0,0,e):this.animations.push(e)))}set clips(e){this.animations=e}_tempAnimationsArray;set animations(e){e==null||!Array.isArray(e)||(this.gameObject?this.gameObject.animations=e:this._tempAnimationsArray=e)}get animations(){return this.gameObject?.animations||this._tempAnimationsArray||[]}mixer=void 0;get actions(){return this._actions}set actions(e){this._actions=e}_actions;_handles;awake(){this.mixer=void 0,yr&&console.log(`Animation Awake`,this.name,this),this._tempAnimationsArray&&=(this.animations=this._tempAnimationsArray,void 0),this._tempAnimationClipBeforeGameObjectExisted&&=(this.clip=this._tempAnimationClipBeforeGameObjectExisted,null),this.actions=[],this._handles=[]}onEnable(){if(this.playAutomatically&&this.animations?.length>0){let e=Math.floor(Math.random()*this.animations.length),t=this.animations[e];this.play(e,{exclusive:!0,fadeDuration:0,startTime:this.randomStartTime?Math.random()*t.duration:0,loop:this.loop,clampWhenFinished:this.clampWhenFinished})}}update(){this.mixer&&(this.mixer.update(this.context.time.deltaTime),this._handles.forEach(e=>e.update()))}onDisable(){this.mixer&&this.mixer.stopAllAction()}onDestroy(){this.context.animations.unregisterAnimationMixer(this.mixer)}getAction(e){return this.actions?.find(t=>t.getClip().name===e)||null}get isPlaying(){if(this.actions){for(let e=0;e<this.actions.length;e++)if(this.actions[e].isRunning())return!0}return!1}stopAll(e){if(this.actions)for(let t of this.actions)e?.fadeDuration?t.fadeOut(e.fadeDuration):t.stop()}stop(e,t){if(e===void 0){this.stopAll();return}else if(typeof e==`number`){if(e>=this.animations.length){yr&&console.log(`No animation at index`,e);return}e=this.animations[e]}else typeof e==`string`&&(e=this.animations.find(t=>t.name===e));if(!e){console.error(`Could not find clip`,e);return}let n=this.actions.find(t=>t.getClip()===e);if(!n){console.error(`Could not find action`,e);return}t?.fadeDuration?n.fadeOut(t.fadeDuration):n.stop()}pause(e,t=!1){if(e===void 0){for(let e of this.actions)e.paused=!t;return}else if(typeof e==`number`){if(e>=this.animations.length){yr&&console.log(`No animation at index`,e);return}e=this.animations[e]}else typeof e==`string`&&(e=this.animations.find(t=>t.name===e));if(!e){console.error(`Could not find clip`,e);return}let n=this.actions.find(t=>t.getClip()===e);if(!n){console.error(`Could not find action`,e);return}n.paused=!t}resume(){for(let e of this.actions)e.paused=!1}play(e=0,t){if(yr&&console.log(`PLAY`,e),this.ensureMixer(),!this.mixer){yr&&console.warn(`Missing mixer`,this);return}e===void 0&&(e=0);let n=e;if(typeof e==`number`){if(e>=this.animations.length){yr&&console.log(`No animation at index`,e);return}n=this.animations[e]}else typeof e==`string`&&(n=this.animations.find(t=>t.name===e));if(!n){console.error(`Could not find clip`,e);return}t||={};for(let e of this.actions)if(e.getClip()===n)return this.internalOnPlay(e,t);if(!n.tracks){console.warn(`Clip is no AnimationClip`,n);return}let r=this.mixer.clipAction(n);return this.actions.push(r),this.internalOnPlay(r,t)}internalOnPlay(e,t){var n=this.actions.find(t=>t===e);if(n===e&&n.isRunning()&&n.time<n.getClip().duration){let t=this.tryFindHandle(e);if(n.paused&&=!1,t)return t.waitForFinish()}if(t.loop===void 0&&(t.loop=this.loop),t.clampWhenFinished===void 0&&(t.clampWhenFinished=this.clampWhenFinished),t.minMaxOffsetNormalized===void 0&&this.randomStartTime&&(t.minMaxOffsetNormalized=this.minMaxOffsetNormalized),t.minMaxSpeed===void 0&&(t.minMaxSpeed=this.minMaxSpeed),t?.exclusive??!0)for(let e of this.actions)e!=n&&(t.fadeDuration?e.fadeOut(t.fadeDuration):e.stop());if(t?.fadeDuration&&e.fadeIn(t.fadeDuration),e.enabled=!0,t?.startTime!=null)e.time=t.startTime;else if(t?.minMaxOffsetNormalized&&t.minMaxOffsetNormalized.x!=0&&t.minMaxOffsetNormalized.y!=0){let n=e.getClip();e.time=Rt.lerp(t.minMaxOffsetNormalized.x,t.minMaxOffsetNormalized.y,Math.random())*n.duration}else e.time>=e.getClip().duration&&(e.time=0);t?.minMaxSpeed?e.timeScale=Rt.lerp(t.minMaxSpeed.x,t.minMaxSpeed.y,Math.random()):e.timeScale=t?.speed??1,t?.loop==null?e.loop=se:e.loop=t.loop?f:se,t?.clampWhenFinished&&(e.clampWhenFinished=!0),e.paused=!1,e.play(),window.requestAnimationFrame(()=>At.testIfRootCanAnimate(e)),yr&&console.log(`PLAY`,e.getClip().name,e);let r=new Sr(e,this.mixer,t,e=>{this._handles.splice(this._handles.indexOf(r),1)});return this._handles.push(r),r.waitForFinish()}tryFindHandle(e){for(let t of this._handles)if(t.action===e)return t}ensureMixer(){if(!this.mixer){let e=`animationMixer`;this.gameObject[e]&&(this.mixer=this.gameObject[e]),(!this.mixer||!this.mixer.clipAction)&&(this.mixer=new me(this.gameObject),this.gameObject[e]=this.mixer)}this.context.animations.registerAnimationMixer(this.mixer)}};vr([E()],xr.prototype,`playAutomatically`,void 0),vr([E()],xr.prototype,`randomStartTime`,void 0),vr([E(br)],xr.prototype,`minMaxSpeed`,void 0),vr([E(br)],xr.prototype,`minMaxOffsetNormalized`,void 0),vr([E()],xr.prototype,`loop`,void 0),vr([E()],xr.prototype,`clampWhenFinished`,void 0),vr([E(we)],xr.prototype,`clips`,null);var Sr=class{mixer;action;promise=null;_options;_resolveCallback=null;_resolvedOrRejectedCallback;constructor(e,t,n,r){this.action=e,this.mixer=t,this._resolvedOrRejectedCallback=r,this._options=n}waitForFinish(){return this.promise?this.promise:(this.promise=new Promise(e=>{this._resolveCallback=e}),this.mixer.addEventListener(`finished`,this.onFinished),this.promise)}update(){this._options&&this._options.endTime!==void 0&&this.action.time>this._options.endTime&&(this._options.loop===!0?this.action.time=this._options.startTime??0:(this.action.time=this._options.endTime,this.action.timeScale=0,this.onResolve()))}onResolve(){this.dispose(),this._resolvedOrRejectedCallback?.call(this,this),this._resolveCallback?.call(this,this.action)}onFinished=e=>{e.action===this.action&&this.onResolve()};dispose(){this.mixer.removeEventListener(`finished`,this.onFinished)}},Cr=class extends N{get listener(){return this._listener??=new De,this._listener}_listener=null;onEnable(){yt.registerWaitForInteraction(this.onInteraction),this.addListenerIfItExists()}onDisable(){yt.unregisterWaitForInteraction(this.onInteraction),this.removeListenerIfItExists()}onInteraction=()=>{this.destroyed||this.listener!=null&&this.addListenerIfItExists()};addListenerIfItExists(){let e=this._listener;if(!e||e?.parent)return;let t=this.context.mainCameraComponent||k.getComponentInParent(this.gameObject,nt);t?.threeCamera?t.threeCamera.add(e):this.gameObject.add(e),e.filter?(e.gain.connect(e.filter),e.filter.connect(e.context.destination)):e.gain.connect(e.context.destination)}removeListenerIfItExists(){let e=this._listener;e&&(e.removeFromParent(),e.filter&&e.filter.disconnect(),e.gain&&e.gain.disconnect())}},wr=function(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},F=D(`debugaudio`),Tr;(function(e){e[e.Logarithmic=0]=`Logarithmic`,e[e.Linear=1]=`Linear`,e[e.Custom=2]=`Custom`})(Tr||={});var I=class e extends N{static get userInteractionRegistered(){return yt.userInteractionRegistered}static registerWaitForAllowAudio(e){yt.registerWaitForInteraction(e)}clip=``;playOnAwake=!1;preload=!0;playInBackground=!0;get isPlaying(){return this.sound?.isPlaying??!1}get duration(){return this.sound?.buffer?.duration}get time01(){let e=this.duration;return e&&this.sound?this.sound?.context.currentTime/e:0}set time01(e){let t=this.duration;t&&this.sound&&(this.time=e*t)}get time(){return this.sound?.source?this.sound.source?.context.currentTime-this._lastContextTime+this.sound.offset:0}set time(e){if(this.sound){if(e===this.sound.offset)return;let t=this.isPlaying;this.stop(),this.sound.offset=e,t&&this.play()}}get loop(){return this.sound&&(this._loop=this.sound.getLoop()),this._loop}set loop(e){this._loop=e,this.sound&&this.sound.setLoop(e)}get spatialBlend(){return this._spatialBlend}set spatialBlend(e){e!==this._spatialBlend&&(this._spatialBlend=e,this._needUpdateSpatialDistanceSettings=!0)}get minDistance(){return this._minDistance}set minDistance(e){this._minDistance!==e&&(this._minDistance=e,this._needUpdateSpatialDistanceSettings=!0)}get maxDistance(){return this._maxDistance}set maxDistance(e){this._maxDistance!==e&&(this._maxDistance=e,this._needUpdateSpatialDistanceSettings=!0)}_spatialBlend=0;_minDistance=1;_maxDistance=100;get volume(){return this._volume}set volume(e){this._volume=e,this.sound&&!this.context.application.muted&&(F&&console.log(this.name,`audio set volume`,e),this.sound.setVolume(e))}_volume=1;set pitch(e){this.sound&&this.sound.setPlaybackRate(e)}get pitch(){return this.sound?this.sound.getPlaybackRate():1}rollOffMode=0;_loop=!1;sound=null;helper=null;wasPlaying=!1;audioLoader=null;shouldPlay=!1;_lastClipStartedLoading=null;_audioElement=null;get Sound(){if(!this.sound&&e.userInteractionRegistered){let e=this.gameObject.getComponent(Cr)??this.context.mainCamera.getComponent(Cr)??Zt(Cr,this.context,!1);!e&&this.context.mainCamera&&(e=this.context.mainCamera.addComponent(Cr)),e?.listener?(this.sound=new ae(e.listener),this.gameObject?.add(this.sound)):F&&console.warn(`No audio listener found in scene - can not play audio`)}return this.sound}get ShouldPlay(){return this.shouldPlay}get audioContext(){return this.sound?.context}awake(){F&&console.log(`[AudioSource]`,this),this.audioLoader=new Be,this.playOnAwake&&(this.shouldPlay=!0),this.preload&&typeof this.clip==`string`&&this.audioLoader.load(this.clip,this.createAudio,()=>{},console.error)}onEnable(){this.sound&&this.gameObject.add(this.sound),e.userInteractionRegistered?this.playOnAwake&&this.context.application.isVisible&&this.play():e.registerWaitForAllowAudio(()=>{this.enabled&&!this.destroyed&&this.shouldPlay&&this.onNewClip(this.clip)}),globalThis.addEventListener(`visibilitychange`,this.onVisibilityChanged),this.context.application.addEventListener(Pt.MuteChanged,this.onApplicationMuteChanged)}onDisable(){globalThis.removeEventListener(`visibilitychange`,this.onVisibilityChanged),this.context.application.removeEventListener(Pt.MuteChanged,this.onApplicationMuteChanged),this.pause()}onVisibilityChanged=()=>{switch(document.visibilityState){case`hidden`:(this.playInBackground===!1||A.isMobileDevice())&&(this.wasPlaying=this.isPlaying,this.isPlaying&&this.pause());break;case`visible`:F&&console.log(`visible`,this.enabled,this.playOnAwake,!this.isPlaying,e.userInteractionRegistered,this.wasPlaying),this.enabled&&this.playOnAwake&&!this.isPlaying&&e.userInteractionRegistered&&this.wasPlaying&&this.play();break}};onApplicationMuteChanged=()=>{this.context.application.muted?this.sound?.setVolume(0):this.sound?.setVolume(this.volume)};createAudio=t=>{if(this.destroyed){F&&console.warn(`AudioSource destroyed, not creating audio`,this.name);return}F&&console.log(`AudioBuffer finished loading`,t);let n=this.Sound;if(!n){F&&console.warn(`Failed getting sound?`,this.name);return}n.isPlaying&&n.stop(),t&&n.setBuffer(t),n.loop=this._loop,this.context.application.muted?n.setVolume(0):n.setVolume(this.volume),n.autoplay=this.shouldPlay&&e.userInteractionRegistered,this.applySpatialDistanceSettings(),n.isPlaying&&n.stop(),e.registerWaitForAllowAudio(this.__onAllowAudioCallback)};__onAllowAudioCallback=()=>{this.shouldPlay&&this.play()};applySpatialDistanceSettings(){let e=this.sound;if(!e)return;this._needUpdateSpatialDistanceSettings=!1;let t=Rt.lerp(10*this._maxDistance/Math.max(1e-4,this.spatialBlend),this._minDistance,this.spatialBlend);switch(F&&console.log(this.name,this._minDistance,this._maxDistance,this.spatialBlend,`Ref distance=`+t),e.setRefDistance(t),e.setMaxDistance(Math.max(.01,this._maxDistance)),this.rollOffMode){case Tr.Logarithmic:e.setDistanceModel(`exponential`);break;case Tr.Linear:e.setDistanceModel(`linear`);break;case Tr.Custom:console.warn(`Custom rolloff for AudioSource is not supported: `+this.name);break}this.spatialBlend>0?F&&!this.helper&&(this.helper=new dr(e,e.getRefDistance()),e.add(this.helper)):this.helper&&this.helper.parent&&this.helper.removeFromParent()}async onNewClip(e){if(e&&(this.clip=e),typeof e==`string`)if(F&&console.log(e),e.endsWith(`.mp3`)||e.endsWith(`.wav`)){if(this.audioLoader||=new Be,this.shouldPlay=!0,this._lastClipStartedLoading===e){F&&console.log(`Is currently loading:`,this._lastClipStartedLoading,this);return}this._lastClipStartedLoading=e,F&&console.log(`load audio`,e);let t=await this.audioLoader.loadAsync(e).catch(console.error);if(this.destroyed)return;this._lastClipStartedLoading===e&&(this._lastClipStartedLoading=null),t&&this.createAudio(t)}else console.warn(`Unsupported audio clip type`,e);else this.shouldPlay=!0,this.createAudio()}play(e=void 0){!e&&this.clip&&(e=this.clip),e!==void 0&&typeof e!=`string`&&!(e instanceof MediaStream)&&(T()&&console.warn(`Called play on AudioSource with unknown argument type:`,e+`
|
||
Using the assigned clip instead:`,this.clip),e=this.clip);let t=!this.sound||e&&e!==this.clip;if(typeof e==`string`&&!this.audioLoader&&(t=!0),(e instanceof MediaStream||typeof e==`string`)&&(this.clip=e),t){this.shouldPlay=!0,this.onNewClip(e);return}if(this.shouldPlay=!0,this._hasEnded=!1,F&&console.log(`play`,this.sound?.getVolume(),this.sound),this.sound&&!this.sound.isPlaying){let e=this.context.application.muted;e&&this.sound.setVolume(0),this.gameObject?.add(this.sound),this.clip instanceof MediaStream?(this.sound.setMediaStreamSource(this.clip),this._audioElement||(this._audioElement=document.createElement(`audio`),this._audioElement.style.display=`none`),this._audioElement.parentNode||this.context.domElement.shadowRoot?.append(this._audioElement),this._audioElement.srcObject=this.clip,this._audioElement.autoplay=!1):(this._audioElement&&this._audioElement.remove(),this.sound.play(e?.1:0))}}pause(){F&&console.log(`Pause`,this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.isPlaying&&this.sound.source&&(this._lastContextTime=this.sound?.context.currentTime,this.sound.pause()),this._audioElement?.remove()}stop(){F&&console.log(`Pause`,this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.source&&(this._lastContextTime=this.sound?.context.currentTime,F&&console.log(this._lastContextTime),this.sound.stop()),this._audioElement?.remove()}_lastContextTime=0;_hasEnded=!0;_needUpdateSpatialDistanceSettings=!1;update(){this.helper&&(this.isPlaying&&this.helper.update(),this.helper.visible=this.isPlaying),this._needUpdateSpatialDistanceSettings&&this.applySpatialDistanceSettings(),this.sound&&!this.sound.isPlaying&&this.shouldPlay&&!this._hasEnded&&(this._hasEnded=!0,F&&console.log(`Audio clip ended`,this.clip),this.dispatchEvent(new CustomEvent(`ended`,{detail:this})))}};wr([E(URL)],I.prototype,`clip`,void 0),wr([E()],I.prototype,`playOnAwake`,void 0),wr([E()],I.prototype,`preload`,void 0),wr([E()],I.prototype,`playInBackground`,void 0),wr([E()],I.prototype,`loop`,null),wr([E()],I.prototype,`spatialBlend`,null),wr([E()],I.prototype,`minDistance`,null),wr([E()],I.prototype,`maxDistance`,null),wr([E()],I.prototype,`volume`,null),wr([E()],I.prototype,`pitch`,null),wr([E()],I.prototype,`rollOffMode`,void 0);var Er=D(`debugautosync`),Dr=Symbol(`syncerId`),Or=new class{_syncers={};getOrCreateSyncer(e){if(!e.guid)return null;if(this._syncers[e.guid])return this._syncers[e.guid];let t=new kr(e);return t[Dr]=e.guid,this._syncers[t[Dr]]=t,t}removeSyncer(e){delete this._syncers[e[Dr]]}},kr=class{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);let 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,!1)}notifyChanged(e,t){this._isReceiving||(Er&&console.log(`Property changed: `+e,t),this.hasChanges=!0,this.changedProperties[e]=t)}onHandleSending=()=>{if(!this.hasChanges)return;this.hasChanges=!1;let e=this.comp.context.connection;if(!e||!e.isConnected||!e.isInRoom){for(let e in this.changedProperties)delete this.changedProperties[e];return}for(let t in this.changedProperties){let n=this.changedProperties[t];Er&&console.log(`SEND`,this.comp.guid,this.networkingKey),e.send(this.networkingKey,{guid:this.comp.guid,property:t,data:n},hn.Queued),delete this.changedProperties[t]}};onHandleReceiving=e=>{if(Er&&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(e){console.error(e)}finally{this._isReceiving=!1}}};function Ar(e,t){let n=t!==e;return!n&&e&&t&&(Array.isArray(e)&&Array.isArray(t)||typeof e==`object`&&typeof t==`object`)&&(n=!0),n}var jr=Symbol(`AutoSyncHandler`);function Mr(e){if(e[jr])return e[jr];let t=Or.getOrCreateSyncer(e);return t?.init(e),e[jr]=t,t}function Nr(e){let t=e[jr];t&&(Or.removeSyncer(t),t.destroy(),delete e[jr])}var Pr=function(e=null){return function(t,n){let r=``;r=typeof n==`string`?n:n.name;let i=null,a;typeof e==`string`?a=t[e]:typeof e==`function`&&(a=e),a==null&&(T()||Er)&&e!=null&&console.warn(`syncField: no callback function found for property "`+r+`"`,`"`+e+`"`);let o=t,s=o.__internalAwake;if(typeof s!=`function`){(Er||T())&&console.error(`@syncField can currently only used on Needle Engine Components, custom object of type "`+t?.constructor?.name+`" is not supported`,t);return}Er&&console.log(r);let c=Symbol(r);o.__internalAwake=function(){if(this[c]===void 0){if(this[c]=this[r],i=Or.getOrCreateSyncer(this),Object.getOwnPropertyDescriptor(this,r)?.set===void 0){let e=!1;Object.defineProperty(this,r,{set:function(t){let n=this[c];if(this[c]=t,e){(T()||Er)&&console.warn(`Recursive call detected`,r);return}e=!0;try{let e=Ar(t,n);Er&&console.log(`SyncField assignment`,r,`changed?`,e,t,a),e&&a?.call(this,t,n)!==!1&&Mr(this)?.notifyChanged(r,t)}finally{e=!1}},get:function(){return this[c]},configurable:!0,enumerable:!0})}i?.init(this),s.call(this)}};let l=o.__internalDestroy;o.__internalDestroy=function(){Nr(this),l.call(this)}}},Fr=new Map;function Ir(e,t){if(Fr.has(e))return Fr.get(e);let n=Lr(new URL(e,window.location.href),t);return Fr.set(e,n),n.finally(()=>{Fr.delete(e)}),n}async function Lr(e,t){if(!e)return Promise.resolve(null);let n=e.pathname,r=e.toString().toLowerCase().includes(`pmrem`)||e.searchParams.get(`pmrem`)!=null,i=n.endsWith(`.exr`),a=n.endsWith(`.hdr`),o=n.endsWith(`.ktx2`),s;if(i)s=new lr;else if(a)s=new hr;else if(o){let{ktx2Loader:e}=ir(t);s=e}else s=new pe;let c=e.toString();return await s.loadAsync(c).then(e=>{if(e){let t=n.lastIndexOf(`/`);e.name=n.substring(t>=0?t+1:0),r?e.mapping=306:e.mapping=304,s instanceof pe&&(e.colorSpace=ue)}return e}).catch(t=>(console.warn(`Failed to load texture from url:`,e),null))}var Rr=D(`debugavatar`),zr=class e extends N{static getAvatar(t){return t>=0&&t<e.instances.length?e.instances[t]:null}static instances=[];static onAvatarMarkerCreated(t){return e._onNewAvatarMarkerAdded.push(t),t}static onAvatarMarkerDestroyed(t){return e._onAvatarMarkerDestroyed.push(t),t}static _onNewAvatarMarkerAdded=[];static _onAvatarMarkerDestroyed=[];connectionId;avatar;awake(){e.instances.push(this),Rr&&console.log(this);for(let t of e._onNewAvatarMarkerAdded)t({avatarMarker:this,gameObject:this.gameObject})}onDestroy(){e.instances.splice(e.instances.indexOf(this),1);for(let t of e._onAvatarMarkerDestroyed)t({avatarMarker:this,gameObject:this.gameObject})}isLocalAvatar(){return this.connectionId===this.context.connection.connectionId}},Br=class{static Pois=[];static LastChangeTime=0;static Add(e,t,n=null){if(t){for(let e of this.Pois)if(e.obj===t)return;this.Pois.push({obj:t,avatar:n}),this.LastChangeTime=e.time.time}}static Remove(e,t){if(t){for(let n of this.Pois)if(n.obj===t){this.Pois.splice(this.Pois.indexOf(n),1),this.LastChangeTime=e?.time.time??Xt.Current?.time.time;return}}}},Vr;(function(e){e.TargetChanged=`avatar-look-target-changed`})(Vr||={});var Hr=class{guid;position=new r},Ur=class extends N{set controlledTarget(e){this.target=e;let t=Je.get(`MoveRandom`);if(t&&this.target){let e=k.getComponent(this.target,t);e&&e.destroy()}}target=null;avatar=null;_model=null;_targetModel=new Hr;_currentTargetObject=null;_lastUpdateTime=0;_lookDuration=0;_lastPoiChangedTime=0;awake(){if(this.avatar=k.getComponentInParent(this.gameObject,zr),this.avatar){let e=k.getComponentInParent(this.gameObject,zr);this._model=new Mn(this.context.connection,this.guid),e?.isLocalAvatar&&this._model.requestOwnership()}this.context.connection.beginListen(Vr.TargetChanged,e=>{this.target&&e&&e.guid===this.avatar?.guid&&Xe(this.target,e.position)})}update(){if((!this.context.connection.isConnected||this._model?.hasOwnership)&&(Br.LastChangeTime!==this._lastPoiChangedTime&&(this._lastPoiChangedTime=Br.LastChangeTime,this._lookDuration=0),this.selectTarget(),this._currentTargetObject&&this.context.time.frameCount%10==0&&this.target)){let e=Yt(this._currentTargetObject);Xe(this.target,e),this.context.connection.isConnected&&this.avatar&&(this.context.connection.send(Vr.TargetChanged,this._targetModel),this._targetModel.guid=this.avatar.guid,this._targetModel.position.copy(e))}}selectTarget(){if(this.context.time.time-this._lastUpdateTime>this._lookDuration){this._lastUpdateTime=this.context.time.time,this._lookDuration=Math.random()*.5+.2;let e=Br.Pois;if(e.length>0){let t=e[Math.floor(Math.random()*e.length)];if(t&&t.obj){if(t.avatar&&t.avatar===this.avatar)return;this._currentTargetObject=t.obj}}}}},L=D(`debugnetworkingstreams`),R;(function(e){e.Connected=`peer-user-connected`,e.StreamReceived=`receive-stream`,e.StreamEnded=`call-ended`,e.Disconnected=`peer-user-disconnected`,e.UserJoined=`user-joined`})(R||={});var Wr=class{type=R.StreamEnded;userId;direction;constructor(e,t){this.userId=e,this.direction=t}},Gr=class{type=R.StreamReceived;userId;stream;target;constructor(e,t,n){this.userId=e,this.stream=t,this.target=n}},Kr=class{guid;peerId;dontSave=!0;constructor(e,t){this.guid=e.id,this.peerId=t}},qr;(function(e){e.Incoming=`incoming`,e.Outgoing=`outgoing`})(qr||={});var Jr=class extends je{peerId;userId;direction;call;get stream(){return this._stream}_stream=null;_isDisposed=!1;close(){this._isDisposed||(this._isDisposed=!0,this.call.close(),Qr(this._stream))}get isOpen(){return this.call.peerConnection?.connectionState===`connected`}get isOpening(){return this.call.peerConnection?.connectionState===`connecting`}get isClosed(){return!this.isOpen||this._isDisposed}constructor(e,t,n,r=null){super(),this.peerId=t.peer,this.userId=e,this.call=t,this.direction=n,this._stream=r,t.on(`stream`,t=>{if(L&&console.log(`Receive stream`,`
|
||
Audio:`,t.getAudioTracks(),`
|
||
Video:`,t.getVideoTracks()),this._stream=t,n===qr.Incoming){let n=new Gr(e,t,this);this.dispatchEvent(n)}}),t.on(`close`,()=>{this.dispatchEvent(new Wr(e,n))})}};function Yr(e){return e=e.replace(`a=fmtp:111 minptime=10;useinbandfec=1`,`a=fmtp:111 ptime=5;useinbandfec=1;stereo=1;maxplaybackrate=48000;maxaveragebitrat=128000;sprop-stereo=1`),e}var Xr=class e extends je{static instances=new Map;static getOrCreate(t,n){if(e.instances.has(n))return e.instances.get(n);let r=new e(t,n);return e.instances.set(n,r),r}getMyPeerId(){if(this.context.connection.connectionId)return this.getPeerIdFromUserId(this.context.connection.connectionId)}getPeerIdFromUserId(e){return this.id+`-`+e}getUserIdFromPeerId(e){return e.substring(this.id.length+1)}makeCall(e,t){if(!t?.id){L?console.warn(`Can not make a call: mediastream has no id or is undefined`):console.debug(`Can not make a call: mediastream has no id or is undefined`);return}let n={metadata:{userId:this.context.connection.connectionId,streamId:t.id},sdpTransform:e=>Yr(e)},r=this._peer?.call(e,t,n);if(r){let n=this.registerCall(r,qr.Outgoing,t);return L&&console.warn(`📞 CALL ${e}`,`
|
||
Outgoing:`,this._outgoingCalls,`
|
||
Incoming:`,this._incomingCalls),n}else L&&console.error(`Failed to make call`,e,t,this._peer)}closeAll(){for(let e of this._incomingCalls)e.close();for(let e of this._outgoingCalls)e.close();this.updateCalls()}updateCalls=()=>{for(let e=this._incomingCalls.length-1;e>=0;e--){let t=this._incomingCalls[e];t.isClosed&&!t.isOpening&&this._incomingCalls.splice(e,1)}for(let e=this._outgoingCalls.length-1;e>=0;e--){let t=this._outgoingCalls[e],n=!1;t.isClosed&&!t.isOpening&&(t.stream?.active?L&&console.warn(`!!! Stream is still active, don't remove call`,t.userId,`Your id: `+this.context.connection.connectionId):(L&&console.warn(`!!! Remove closed call`,t.userId),n=!0)),this.context.connection.userIsInRoom(t.userId)===!1&&(L&&console.warn(`!!! User is not in room anymore, remove call`,t.userId),n=!0),n&&(t.close(),this._outgoingCalls.splice(e,1))}};get peer(){return this._peer}get incomingCalls(){return this._incomingCalls}id;context;_incomingCalls=[];_outgoingCalls=[];_peer;constructor(e,t){super(),this.context=e,this.id=t,this.setupPeer();let n=Object.getOwnPropertyDescriptor(navigator,`getUserMedia`)?.writable;try{n?navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia:L&&console.warn(`[PeerJs] getUserMedia is not writable`)}catch(e){L&&console.error(`[PeerJs] Error setting getUserMedia`,e)}}_enabled=!1;_enabledPeer=!1;onConnectRoomFn=this.onConnectRoom.bind(this);enable(){this._enabled||(this._enabled=!0,this.context.connection.beginListen(O.JoinedRoom,this.onConnectRoomFn),this.subscribePeerEvents())}disable(){this._enabled&&(this._enabled=!1,this.context.connection.stopListen(O.JoinedRoom,this.onConnectRoomFn),this.unsubscribePeerEvents())}onConnectRoom(){this.setupPeer()}async setupPeer(){if(this.context.connection.connectionId&&!this._enabledPeer){if(this._enabledPeer=!0,!this._peer){let e=this.getMyPeerId();e?this._peer=await gn(e):console.error(`Failed to setup peerjs because we dont have a connection id`,this.context.connection.connectionId)}this._enabled&&this.subscribePeerEvents()}}subscribePeerEvents(){this._peer&&(this._peer.on(`open`,this.onPeerConnect),this._peer.on(`close`,this.onPeerClose),this._peer.on(`call`,this.onPeerReceivingCall),this._peer.on(`disconnected`,this.onPeerDisconnected),this._peer.on(`error`,this.onPeerError))}unsubscribePeerEvents(){this._peer&&(this._peer.off(`open`,this.onPeerConnect),this._peer.off(`close`,this.onPeerClose),this._peer.off(`call`,this.onPeerReceivingCall),this._peer.off(`disconnected`,this.onPeerDisconnected),this._peer.off(`error`,this.onPeerError))}onPeerConnect=e=>{if(L&&console.log(`PEER opened as`,e),e===null){console.error(`Peer connection failed`,e);return}this.context.connection.send(R.Connected,new Kr(this,e))};onPeerClose=()=>{L&&console.log(`PEER closed`),this.updateCalls()};onPeerDisconnected=()=>{L&&console.log(`PEER disconnected`),this.updateCalls()};onPeerError=e=>{L&&console.error(`PEER error`,e)};onPeerReceivingCall=e=>{e.answer(void 0,{sdpTransform:e=>Yr(e)}),this.registerCall(e,qr.Incoming,null)};registerCall(e,t,n){let r=e.metadata;(!r||!r.userId)&&console.error(`Missing call metadata`,e);let i=r.userId;t===qr.Incoming&&L?console.warn(`← Receive call from`,e.metadata,e.connectionId):L&&console.warn(`→ Make call to`,e.metadata);let a=t===qr.Incoming?this._incomingCalls:this._outgoingCalls,o=new Jr(i,e,t,n);return a.push(o),e.on(`error`,e=>{console.error(`Call error`,e)}),e.on(`close`,()=>{L&&console.log(`Call ended`,e.metadata);let n=a.indexOf(o);n!==-1&&a.splice(n,1),o.close(),this.dispatchEvent(new Wr(i,t))}),o.addEventListener(R.StreamEnded,e=>{this.dispatchEvent(e)}),t===qr.Incoming&&(o.addEventListener(R.StreamReceived,e=>{this.dispatchEvent(e)}),e.on(`stream`,()=>{L&&console.log(`Received stream for call`,e.metadata);let t=0,n=setInterval(()=>{let r=t===0;!o.isOpen&&r&&(L&&console.warn(`Close call because stream is not active`,e.metadata),t+=1,clearInterval(n),o.close())},2e3)})),o}},Zr=class e extends je{static create(t,n){let r=Xr.getOrCreate(t.context,n||t.context.connection.connectionId||t.guid);return new e(t.context,r)}context;peer;_sendingStreams=new Map;debug=!1;constructor(e,t){if(super(),lt(e)){let n=e;e=n.context,t=Xr.getOrCreate(n.context,n.guid)}else typeof t==`string`&&(t=Xr.getOrCreate(e,t));if(!e)throw Error(`Failed to create NetworkedStreams because context is undefined`);if(!(e instanceof Xt))throw Error(`Failed to create NetworkedStreams because context is not an instance of Context`);if(!t)throw Error(`Failed to create NetworkedStreams because peer is undefined`);this.context=e,this.peer=t,L&&(this.debug=!0)}startSendingStream(e){this._sendingStreams.has(e)?console.warn(`Received start sending stream with stream that is already being sent`):(this._sendingStreams.set(e,[]),this.updateSendingCalls())}stopSendingStream(e){if(e){let t=this._sendingStreams.get(e);if(t){for(let e of t)e.close();t.length=0}this._sendingStreams.delete(e),t&&this.debug&&this.debugLogCurrentState()}this.updateSendingCalls()}_enabled=!1;get enabled(){return this._enabled}enable(){this._enabled||(this._enabled=!0,this.peer.enable(),this.peer.addEventListener(R.StreamReceived,this.onCallStreamReceived),this.peer.addEventListener(R.StreamEnded,this.onCallEnded),this.context.connection.beginListen(R.Connected,this.onUserConnected),this.context.connection.beginListen(O.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(O.UserJoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(O.UserLeftRoom,this.onUserLeft),this.context.connection.beginListen(O.LeftRoom,this.onLeftRoom),this._tickIntervalId=setInterval(this.tick,5e3))}disable(){this._enabled&&(this._enabled=!1,this.peer.disable(),this.peer.removeEventListener(R.StreamReceived,this.onCallStreamReceived),this.peer.removeEventListener(R.StreamEnded,this.onCallEnded),this.context.connection.stopListen(R.Connected,this.onUserConnected),this.context.connection.stopListen(O.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(O.UserJoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(O.UserLeftRoom,this.onUserLeft),this.context.connection.stopListen(O.LeftRoom,this.onLeftRoom),this._tickIntervalId!=null&&(clearInterval(this._tickIntervalId),this._tickIntervalId=void 0))}_tickIntervalId;tick=()=>{this.updateSendingCalls()};onJoinedRoom=e=>{this._sendingStreams.size>0&&(this.debug&&console.warn(`${e?.userId?`User ${e.userId}`:`You`} joined room`,e,this._sendingStreams.size),this.updateSendingCalls())};onLeftRoom=e=>{this.debug&&console.warn(`${e?.userId||`You`} left room`,e),this.stopCallsToUsersThatAreNotInTheRoomAnymore(),this.peer.closeAll()};onCallStreamReceived=e=>{this.debug&&console.log(`Call with `+e.userId+` started`),this.dispatchEvent({type:R.StreamReceived,target:this,stream:e.stream,userId:e.userId}),this.debug&&this.debugLogCurrentState()};onCallEnded=e=>{this.debug&&console.log(`Call with `+e.userId+` ended`),this.dispatchEvent(e),this.debug&&this.debugLogCurrentState()};onUserConnected=e=>{if(this.peer.id===e.guid){this.debug&&console.log(`PEER USER CONNECTED`,e.guid,e,this._sendingStreams.size);let t=this._sendingStreams.keys().next().value;if(!t)return;this.peer.makeCall(e.peerId,t)}else L&&console.log(`Unknown user connected`,e.guid,e.peerId)};onUserLeft=e=>{this.debug&&console.log(`User left room: `+e.userId),this.stopCallsToUsersThatAreNotInTheRoomAnymore()};updateSendingCalls(){let e=this.context.connection.connectionId;for(let t of this._sendingStreams.keys()){let n=this._sendingStreams.get(t)||[];for(let r of this.context.connection.usersInRoom()){if(r===e)continue;let i=this.peer.getPeerIdFromUserId(r);if(n.find(e=>e.peerId===i&&e.direction===qr.Outgoing&&!e.isClosed&&e.stream?.active))L&&console.debug(`Already have a call with user `+r+` / peer `+i);else{let e=this.peer.makeCall(i,t);e&&n.push(e)}}this._sendingStreams.set(t,n)}this.stopCallsToUsersThatAreNotInTheRoomAnymore()}stopCallsToUsersThatAreNotInTheRoomAnymore(){for(let e of this._sendingStreams.keys()){let t=this._sendingStreams.get(e);if(t)for(let e=t.length-1;e>=0;e--){let n=t[e];this.context.connection.userIsInRoom(n.userId)?L&&(this.context.connection.connectionId===n.userId?console.warn(`You are still in the room [${e}] ${n.userId}`):console.log(`User is still in room [${e}] ${n.userId}`)):(L&&console.log(`Remove call ${[e]} to user that is not in room anymore ${n.userId}`),n.close(),t.splice(e,1))}}this.peer.updateCalls(),this.debug&&this.debugLogCurrentState()}debugLogCurrentState(){console.warn(`You (${this.context.connection.connectionId}) are currently sending ${this._sendingStreams.size} and receiving ${this.peer.incomingCalls.length} calls (${this.peer.incomingCalls.map(e=>e.userId).join(`, `)})`,this.peer.incomingCalls)}};function Qr(e){if(e&&e instanceof MediaStream)for(let t of e.getTracks())t.stop()}var $r=function(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},ei=`noVoip`,ti=D(`debugvoip`),ni=class extends N{autoConnect=!0;runInBackground=!0;createMenuButton=!0;debug=!1;_net;_menubutton;awake(){ti&&(this.debug=!0),this.debug&&(console.log(`VOIP debugging: press 'v' to toggle mute or 'c' to toggle connect/disconnect`),window.addEventListener(`keydown`,async e=>{switch(e.key.toLowerCase()){case`v`:console.log(`MUTE?`,!this.isMuted),this.setMuted(!this.isMuted);break;case`c`:this.isSending?this.disconnect():this.connect();break}}),window.addEventListener(`blur`,()=>{console.log(`VOIP: MUTE ON BLUR`),this.setMuted(!0)}),window.addEventListener(`focus`,()=>{console.log(`VOIP: UNMUTE ON FOCUS`),this.setMuted(!1)}))}onEnable(){this._net||=Zr.create(this),this.debug&&(this._net.debug=!0),this._net.addEventListener(R.StreamReceived,this.onReceiveStream),this._net.addEventListener(R.StreamEnded,this.onStreamEnded),this._net.enable(),this.autoConnect&&this.context.connection.isConnected&&this.connect(),this.context.connection.beginListen(O.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(O.LeftRoom,this.onLeftRoom),this.onEnabledChanged(),this.updateButton(),window.addEventListener(`visibilitychange`,this.onVisibilityChanged)}onDisable(){this._net&&(this._net.stopSendingStream(this._outputStream),this._net.removeEventListener(R.StreamReceived,this.onReceiveStream),this._net.removeEventListener(R.StreamEnded,this.onStreamEnded),this._net?.disable()),this.context.connection.stopListen(O.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(O.LeftRoom,this.onLeftRoom),this.onEnabledChanged(),this.updateButton(),window.removeEventListener(`visibilitychange`,this.onVisibilityChanged)}onDestroy(){this._menubutton?.remove(),this._menubutton=void 0}_allowSending=!0;_outputStream=null;get isSending(){return this._outputStream!=null&&this._outputStream.active}async connect(e){return this._net?this.context.connection.isConnected?await A.microphonePermissionsGranted()?(this._allowSending=!0,this._net?.stopSendingStream(this._outputStream),Qr(this._outputStream),this._outputStream=await this.getAudioStream(e),this._outputStream?(this.debug&&console.log(`VOIP: Got audio stream`),this._net?.startSendingStream(this._outputStream),this.updateButton(),!0):(this.updateButton(),await A.microphonePermissionsGranted()?console.error(`VOIP: Could not get audio stream - please make sure to connect an audio device and grant microphone permissions`):Nn(`Microphone permissions not granted: Please grant microphone permissions to use voice chat`),(this.debug||T())&&console.log(`VOIP: Failed to get audio stream`),!1)):(console.error(`Cannot connect to voice chat - microphone permissions not granted`),this.updateButton(),!1):(console.error(`Cannot connect to voice chat - not connected to server`),this.updateButton(),!1):(console.error(`Cannot connect to voice chat - NetworkedStreams not initialized. Make sure the component is enabled before calling this method.`),!1)}disconnect(e){e?.remember&&(this._allowSending=!1),this._net?.stopSendingStream(this._outputStream),Qr(this._outputStream),this._outputStream=null,this.updateButton()}setMuted(e){let t=this._outputStream?.getAudioTracks();if(t)for(let n of t)n.enabled=!e}get isMuted(){if(this._outputStream===null)return!1;let e=this._outputStream?.getAudioTracks();if(e){for(let t of e)if(!t.enabled)return!0}return!1}async updateButton(){if(this.createMenuButton){if(this._menubutton||(this._menubutton=document.createElement(`button`),this._menubutton.addEventListener(`click`,()=>{this.isSending?this.disconnect({remember:!0}):this.connect(),A.microphonePermissionsGranted().then(e=>{e||kn(`<strong>Microphone permissions not granted</strong>. Please allow your browser to use the microphone to be able to talk. Click on the button on the left side of your browser's address bar to allow microphone permissions.`)})})),this._menubutton){this.context.menu.appendChild(this._menubutton),this.activeAndEnabled?this._menubutton.style.display=``:this._menubutton.style.display=`none`,this._menubutton.title=this.isSending?`Click to disable your microphone`:`Click to enable your microphone`;let e=(this.isSending,``),t=this.isSending?`mic`:`mic_off`;await A.microphonePermissionsGranted()||(e=`No Permission`,t=`mic_off`,this._menubutton.title=`Microphone permissions not granted. Please allow your browser to use the microphone to be able to talk. This can usually be done in the addressbar of the webpage.`),this._menubutton.innerText=e,this._menubutton.prepend(Ze(t)),this.context.connection.isConnected==0?this._menubutton.setAttribute(`disabled`,``):this._menubutton.removeAttribute(`disabled`)}}else this.activeAndEnabled||this._menubutton?.remove()}getFrequency(e){return this.unsupported_getfrequency||(this.unsupported_getfrequency=!0,T()&&kn(`VOIP: getFrequency is currently not supported`),console.warn(`VOIP: getFrequency is currently not supported`)),null}async getAudioStream(e){if(!navigator.mediaDevices.getUserMedia)return console.error(`No getDisplayMedia support`),null;let t=async e=>await navigator.mediaDevices.getUserMedia({audio:e??!0,video:!1}).catch(e=>(console.warn(`VOIP failed getting audio stream`,e),null)),n=await t(e);if(!n)return null;if(A.isiOS()&&e?.deviceId===void 0){let n=(await navigator.mediaDevices.enumerateDevices()).find(e=>(e.kind===`audioinput`||e.kind===`audiooutput`)&&!e.label.includes(`iPhone`));if(n){let r=Object.assign({},e);return r.deviceId=n.deviceId,await t(r)}}return n}onJoinedRoom=async()=>{this.debug&&console.log(`VOIP: Joined room`),await Sn(300),this.autoConnect&&!this.isSending&&this._allowSending&&this.connect()};onLeftRoom=()=>{this.debug&&console.log(`VOIP: Left room`),this.disconnect();for(let e of this._incomingStreams.values())Qr(e.srcObject);this._incomingStreams.clear()};_incomingStreams=new Map;onReceiveStream=e=>{let t=e.target.userId,n=e.stream,r=this._incomingStreams.get(t);r||(r=new Audio,this._incomingStreams.set(t,r)),r.srcObject=n,r.setAttribute(`autoplay`,`true`),yt.registerWaitForInteraction(()=>{r?.play().catch(e=>{console.error(`VOIP: Failed to play audio`,e)})})};onStreamEnded=e=>{Qr(this._incomingStreams.get(e.userId)?.srcObject),this._incomingStreams.delete(e.userId)};onEnabledChanged=()=>{for(let e of this._incomingStreams){let t=e[1];t.muted=!this.enabled}};onVisibilityChanged=()=>{if(this.runInBackground)return;let e=document.visibilityState!==`visible`;this.setMuted(e);for(let t of this._incomingStreams){let n=t[1];n.muted=e}}};$r([E()],ni.prototype,`autoConnect`,void 0),$r([E()],ni.prototype,`runInBackground`,void 0),$r([E()],ni.prototype,`createMenuButton`,void 0);var ri=function(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},ii=D(`debugmouth`),ai=class extends N{idle=[];talking=[];marker=null;voip=null;lastMouthChangeTime=0;mouthChangeLength=0;awake(){setTimeout(()=>{this.voip=k.findObjectOfType(ni,this.context),this.marker||=k.getComponentInParent(this.gameObject,zr)},3e3)}update(){if(!this.voip||this.context.time.frameCount%10!=0)return;let e=this.marker?.connectionId??null;if(!e){ii&&(e=null);return}let t=this.voip.getFrequency(e)??0;this.updateLips(t)}updateLips(e){if(this.context.time.time-this.lastMouthChangeTime>this.mouthChangeLength){if(this.mouthChangeLength=.05+Math.random()*.1,this.talking&&this.talking.length>0&&e>30){this.lastMouthChangeTime=this.context.time.time;let e=Math.floor(Math.random()*this.talking.length);this.setMouthShapeActive(this.talking,e)}else if(this.idle.length>0&&this.context.time.time-this.lastMouthChangeTime>.5){this.lastMouthChangeTime=this.context.time.time;let e=Math.floor(Math.random()*this.idle.length);this.setMouthShapeActive(this.idle,e)}}}setMouthShapeActive(e,t){if(e){e==this.idle?this.talking.map(e=>e.visible=!1):this.idle.map(e=>e.visible=!1);for(let n=0;n<e.length;n++){let r=e[n];r&&(r.visible=n===t)}}}};ri([E(S)],ai.prototype,`idle`,void 0),ri([E(S)],ai.prototype,`talking`,void 0);var oi=class extends N{voip=null;marker=null;_startPosition=null;awake(){this.voip=k.findObjectOfType(ni,this.context),this.marker=k.getComponentInParent(this.gameObject,zr)}update(){if(!this.voip||!this.marker||this.context.time.frameCount%10!=0)return;let e=this.marker.connectionId,t=this.voip.getFrequency(e);if(t==null)return;this._startPosition||=this.gameObject.position.clone();let n=t/100;this.gameObject.position.y=this._startPosition.y+n*.07}},si=function(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},ci=D(`debugxrflags`),li=D(`disablexrflags`);li&&console.warn(`XRFlags are disabled`);var ui;(function(e){e[e.Never=0]=`Never`,e[e.Browser=1]=`Browser`,e[e.AR=2]=`AR`,e[e.VR=4]=`VR`,e[e.FirstPerson=8]=`FirstPerson`,e[e.ThirdPerson=16]=`ThirdPerson`,e[e.All=4294967295]=`All`})(ui||={});var di=class e{static Global=new e;Mask=ui.Browser|ui.ThirdPerson;Has(e){return(this.Mask&e)!==0}Set(e){ci&&console.warn(`Set XR flag state to`,e),this.Mask=e,fi.Apply()}Enable(e){this.Mask|=e,fi.Apply()}Disable(e){this.Mask&=~e,fi.Apply()}Toggle(e){this.Mask^=e,fi.Apply()}EnableAll(){this.Mask=-1,fi.Apply()}DisableAll(){this.Mask=0,fi.Apply()}},fi=class e extends N{static registry=[];static Apply(){for(let e of this.registry)e.UpdateVisible(di.Global)}static firstApply;static buffer=new di;visibleIn;awake(){e.registry.push(this)}onEnable(){e.firstApply?this.UpdateVisible(di.Global):(e.firstApply=!0,e.Apply())}onDestroy(){let t=e.registry.indexOf(this);t>=0&&e.registry.splice(t,1)}get isOn(){return this.gameObject.visible}UpdateVisible(t=null){if(li)return;let n,r=t;if(r&&typeof r==`number`&&(console.assert(typeof r==`number`,`XRFlag.UpdateVisible: state must be a number`,r),ci&&console.log(r),e.buffer.Mask=r,t=e.buffer),t instanceof di?(ci&&console.warn(this.name,`use passed in mask`,t.Mask,this.visibleIn),n=t.Has(this.visibleIn)):(ci&&console.log(this.name,`use global mask`),di.Global.Has(this.visibleIn)),n!==void 0)if(n)ci&&console.log(this.name,`is visible`,this.gameObject.uuid),k.setActive(this.gameObject,!0);else{if(ci&&console.log(this.name,`is not visible`,this.gameObject.uuid),!this.gameObject.visible)return;this.gameObject.visible=!1}}};si([E()],fi.prototype,`visibleIn`,void 0);var pi=function(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},mi=class extends N{eyes=[];lastBlinkTime=0;blinkLength=0;eyesOpen=!0;state=null;awake(){this.state=k.getComponentInParent(this.gameObject,fi)}update(){if(!(!this.gameObject||!this.gameObject.visible)&&!(!this.eyes||!Array.isArray(this.eyes)||this.eyes.length===0)&&this.context.time.time-this.lastBlinkTime>this.blinkLength){if(this.lastBlinkTime=this.context.time.time,this.state&&!this.state.isOn||!this.activeAndEnabled)return;if(this.eyesOpen=!this.eyesOpen,this.blinkLength=Math.random(),this.eyesOpen?(this.blinkLength*=3,this.blinkLength+=.5,Math.random()<.1&&(this.blinkLength=.1+Math.random()*.2)):(this.blinkLength*=Math.random()*.2,this.blinkLength+=.1),Math.random()<.1&&(this.blinkLength*=3),this.blinkLength=Math.max(.2,this.blinkLength),this.blinkLength=Math.min(3,this.blinkLength),this.eyes)for(let e of this.eyes)e&&(e.visible=this.eyesOpen)}}};pi([E(S)],mi.prototype,`eyes`,void 0),pi([E()],mi.prototype,`lastBlinkTime`,void 0),pi([E()],mi.prototype,`blinkLength`,void 0),pi([E()],mi.prototype,`eyesOpen`,void 0);var hi=function(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},gi=class e extends N{head=null;eyes=null;target=null;brain=null;awake(){this.brain||=k.getComponentInParent(this.gameObject,Ur),this.brain||=k.addComponent(this.gameObject,Ur),this.brain&&this.target&&(this.brain.controlledTarget=this.target)}vec=new r;static forward=new r(0,0,1);currentTargetPoint=new r;update(){let t=this.target;if(t&&this.head){let n=this.eyes;if(n){let r=Yt(t);this.currentTargetPoint.lerp(r,this.context.time.deltaTime/.1);let i=Yt(this.head),a=this.vec.copy(this.currentTargetPoint).sub(i).normalize();if(a.length()<.1)return;let o=e.forward;if(o.set(0,0,1),o.applyQuaternion(Rn(this.head)),o.dot(a)>.45)for(let e=0;e<n.length;e++)n[e].lookAt(this.currentTargetPoint)}}}};hi([E(S)],gi.prototype,`head`,void 0),hi([E(S)],gi.prototype,`eyes`,void 0),hi([E(S)],gi.prototype,`target`,void 0);var _i=function(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},vi=class extends N{get isCollider(){return!0}attachedRigidbody=null;isTrigger=!1;sharedMaterial;membership=[0];filter;awake(){super.awake(),this.attachedRigidbody||=this.gameObject.getComponentInParent(vt)}start(){this.attachedRigidbody||=this.gameObject.getComponentInParent(vt)}onEnable(){this.attachedRigidbody||=this.gameObject.getComponentInParent(vt)}onDisable(){this.context.physics.engine?.setColliderEnabled(this,!1)||this.context.physics.engine?.removeBody(this)}onDestroy(){this.context.physics.engine?.removeBody(this)}get body(){return this.context.physics.engine?.getBody(this)}updateProperties=()=>{this.context.physics.engine?.updateProperties(this)};updatePhysicsMaterial(){this.context.physics.engine?.updatePhysicsMaterial(this)}};_i([E(vt)],vi.prototype,`attachedRigidbody`,void 0),_i([E()],vi.prototype,`isTrigger`,void 0),_i([E()],vi.prototype,`sharedMaterial`,void 0),_i([E()],vi.prototype,`membership`,void 0),_i([E()],vi.prototype,`filter`,void 0);var yi=class extends vi{radius=.5;center=new r(0,0,0);onEnable(){super.onEnable(),this.context.physics.engine?.setColliderEnabled(this,!0)||this.context.physics.engine?.addSphereCollider(this),tt(this.gameObject.scale,this.updateProperties)}onDisable(){super.onDisable(),Jn(this.gameObject.scale,this.updateProperties)}onValidate(){this.updateProperties()}};_i([Kn(),E()],yi.prototype,`radius`,void 0),_i([E(r)],yi.prototype,`center`,void 0);var bi=class e extends vi{static add(t,n){let r=_n(t,e);return r.autoFit(),n?.rigidbody===!0&&_n(t,vt,{isKinematic:!1}),r}size=new r(1,1,1);center=new r(0,0,0);onEnable(){super.onEnable(),this.context.physics.engine?.setColliderEnabled(this,!0)||this.context.physics.engine?.addBoxCollider(this,this.size),tt(this.gameObject.scale,this.updateProperties)}onDisable(){super.onDisable(),Jn(this.gameObject.scale,this.updateProperties)}onValidate(){this.updateProperties()}autoFit(e){let t=this.gameObject,n=t.position.clone(),i=t.quaternion.clone(),a=t.scale.clone(),o=t.parent;t.position.set(0,0,0),t.quaternion.set(0,0,0,1),t.scale.set(1,1,1),t.parent=null,t.updateMatrix();let s=fn([t]);t.position.copy(n),t.quaternion.copy(i),t.scale.copy(a),t.parent=o,e?.debug===!0&&Ln.DrawWireBox3(s,16768256,20),this.size=s.getSize(new r)||new r(1,1,1),this.center=s.getCenter(new r)||new r(0,0,0),this.size.length()<=0&&this.size.set(.01,.01,.01)}};_i([Kn(),E(r)],bi.prototype,`size`,void 0),_i([E(r)],bi.prototype,`center`,void 0);var xi=class extends vi{sharedMesh;convex=!1;onEnable(){if(super.onEnable(),!(!this.context.physics.engine||this.context.physics.engine.setColliderEnabled(this,!0)))if(this.sharedMesh?.isMesh||(this.gameObject instanceof x||this.gameObject instanceof ve)&&(this.sharedMesh=this.gameObject),this.sharedMesh?.isMesh)this.context.physics.engine.addMeshCollider(this,this.sharedMesh,this.convex),P.assignMeshLOD(this.sharedMesh,0).then(e=>{e&&this.activeAndEnabled&&this.context.physics.engine&&this.sharedMesh&&(this.context.physics.engine.removeBody(this),this.sharedMesh.geometry=e,this.context.physics.engine.addMeshCollider(this,this.sharedMesh,this.convex))});else{let e=this.sharedMesh;if(e?.isGroup){console.warn(`MeshCollider mesh is a group \"${this.sharedMesh?.name||this.gameObject.name}\", adding all children as colliders. This is currently not fully supported (colliders can not be removed from world again)`,this);let t=[];for(let n in e.children){let r=e.children[n];r.isMesh&&(this.context.physics.engine.addMeshCollider(this,r,this.convex),t.push(P.assignMeshLOD(r,0)))}Promise.all(t).then(e=>{if(e.some(e=>e)==0)return;this.context.physics.engine?.removeBody(this);let t=new x;for(let n of e)n&&this.activeAndEnabled&&(t.geometry=n,this.context.physics.engine?.addMeshCollider(this,t,this.convex))})}else (T()||D(`showcolliders`))&&console.warn(`[MeshCollider] A MeshCollider mesh is assigned to an unknown object on \"${this.gameObject.name}\", but it's neither a Mesh nor a Group. Please double check that you attached the collider component to the right object and report a bug otherwise!`,this)}}};_i([E(x)],xi.prototype,`sharedMesh`,void 0),_i([E()],xi.prototype,`convex`,void 0);var Si=class extends vi{center=new r(0,0,0);radius=.5;height=2;onEnable(){super.onEnable(),this.context.physics.engine?.setColliderEnabled(this,!0)||this.context.physics.engine?.addCapsuleCollider(this,this.height,this.radius)}};_i([E(r)],Si.prototype,`center`,void 0),_i([E()],Si.prototype,`radius`,void 0),_i([E()],Si.prototype,`height`,void 0);var Ci=Symbol(`customVisibilityFlag`);function wi(e,t){e.layers[Ci]=t}var Ti=Symbol(`DidPatchLayers`);function Ei(){let e=i.prototype;if(e[Ti])return;e[Ti]=!0;let t=e.test;e.test=function(e){return this[Ci]===!1?!1:t.call(this,e)}}var Di=function(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},Oi=D(`debugcontactshadows`);Bn(e=>{let t=e.domElement.getAttribute(`contactshadows`)||e.domElement.getAttribute(`contact-shadows`);if(t!=null&&t!=`0`&&t!=`false`){console.debug("Auto-creating ContactShadows because of `contactshadows` attribute");let n=ki.auto(e),r=parseFloat(t);isNaN(r)||(n.opacity=r,n.darkness=r)}});var ki=class e extends N{static _instances=new Map;static auto(t,n){if(t||=Xt.Current,!t)throw Error(`No context provided and no current context set.`);let r=this._instances.get(t);if(!r||r.destroyed){let n=new S;n.name=`ContactShadows`,r=_n(n,e,{autoFit:!1,occludeBelowGround:!1}),this._instances.set(t,r)}return t.scene.add(r.gameObject),r.fitShadows(n),r}autoFit=!1;darkness=.5;opacity=.5;blur=4;occludeBelowGround=!1;backfaceShadows=!0;minSize;manualUpdate=!1;set needsUpdate(e){this._needsUpdate=e}get needsUpdate(){return this._needsUpdate}_needsUpdate=!1;shadowsRoot=new S;shadowCamera;shadowGroup=new ve;renderTarget;renderTargetBlur;plane;occluderMesh;blurPlane;planeMaterial;depthMaterial;horizontalBlurMaterial;verticalBlurMaterial;textureSize=512;fitShadows(e={}){Oi&&console.warn(`Fitting shadows to scene`),Qe(this.shadowsRoot,!1);let t=fn(e.object||this.context.scene,[this.shadowsRoot]),n=Math.max(1,this.blur/32),i=t.max.x-t.min.x,a=t.max.z-t.min.z;t.expandByVector(new r(n*i,0,n*a)),Oi&&Ln.DrawWireBox3(t,16776960,60),this.gameObject.parent&&t.applyMatrix4(this.gameObject.parent.matrixWorld.clone().invert());let o=t.min,s=Math.max(1e-5,(t.max.y-o.y)*.002);t.max.y+=s,this.shadowsRoot.position.set((o.x+t.max.x)/2,o.y-s,(o.z+t.max.z)/2),this.shadowsRoot.scale.set(t.max.x-o.x,t.max.y-o.y,t.max.z-o.z),e.positionOffset&&(e.positionOffset.x!==void 0&&(this.shadowsRoot.position.x+=e.positionOffset.x),e.positionOffset.y!==void 0&&(this.shadowsRoot.position.y+=e.positionOffset.y),e.positionOffset.z!==void 0&&(this.shadowsRoot.position.z+=e.positionOffset.z)),e.scaleFactor&&(e.scaleFactor.x!==void 0&&(this.shadowsRoot.scale.x*=e.scaleFactor.x),e.scaleFactor.y!==void 0&&(this.shadowsRoot.scale.y*=e.scaleFactor.y),e.scaleFactor.z!==void 0&&(this.shadowsRoot.scale.z*=e.scaleFactor.z)),this.applyMinSize(),this.shadowsRoot.matrixWorldNeedsUpdate=!0,Oi&&console.log(`Fitted shadows to scene`,this.shadowsRoot.scale.clone())}awake(){e._instances.set(this.context,this),this.shadowsRoot.hideFlags=wt.DontExport,Qe(this.shadowsRoot,!1)}start(){Oi&&console.log(`Create ContactShadows on `+this.gameObject.name,this),this.gameObject.add(this.shadowsRoot),this.shadowsRoot.add(this.shadowGroup),this.renderTarget=new u(this.textureSize,this.textureSize),this.renderTarget.texture.generateMipmaps=!1,this.renderTargetBlur=new u(this.textureSize,this.textureSize),this.renderTargetBlur.texture.generateMipmaps=!1;let e=new He(1,1).rotateX(Math.PI/2);this.gameObject instanceof x&&(console.warn(`ContactShadows can not be added to a Mesh. Please add it to a Group or an empty Object`),wi(this.gameObject,!1)),this.plane=new x(e,this.planeMaterial=new v({map:this.renderTarget.texture,opacity:this.opacity,color:0,transparent:!0,depthWrite:!1,side:0})),this.plane.scale.y=-1,this.plane.layers.set(2),this.shadowsRoot.add(this.plane),this.plane&&(this.plane.renderOrder=1),this.occluderMesh=new x(this.plane.geometry,new v({depthWrite:!0,stencilWrite:!0,colorWrite:!1,side:1})).translateY(-1e-4),this.occluderMesh.renderOrder=-100,this.occluderMesh.layers.set(2),this.shadowsRoot.add(this.occluderMesh),this.blurPlane=new x(e),this.blurPlane.visible=!1,this.shadowGroup.add(this.blurPlane),this.shadowCamera=new Ae(-1/2,1/2,1/2,-1/2,0,1),this.shadowCamera.layers.enableAll(),this.shadowCamera.rotation.x=Math.PI/2,this.shadowCamera.matrixWorldAutoUpdate=!1,this.shadowGroup.add(this.shadowCamera),this.shadowCamera.updateMatrix(),this.depthMaterial=new t,this.depthMaterial.userData.darkness={value:this.darkness},this.depthMaterial.blending=5,this.depthMaterial.blendEquation=104,this.depthMaterial.onBeforeCompile=e=>{this.depthMaterial&&(e.uniforms.darkness=this.depthMaterial.userData.darkness,e.fragmentShader=`
|
||
uniform float darkness;
|
||
${e.fragmentShader.replace(`gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );`,`gl_FragColor = vec4( vec3( 1.0 ), ( 1.0 - fragCoordZ ) * darkness * opacity * (gl_FrontFacing ? 1.0 : 0.66) );`)}
|
||
`)},this.depthMaterial.depthTest=!1,this.depthMaterial.depthWrite=!1,this.horizontalBlurMaterial=new Re(cr),this.horizontalBlurMaterial.depthTest=!1,this.verticalBlurMaterial=new Re(mr),this.verticalBlurMaterial.depthTest=!1,this.shadowGroup.visible=!1,this.autoFit?this.fitShadows():this.applyMinSize()}onEnable(){this._needsUpdate=!0}onDestroy(){e._instances.get(this.context)===this&&e._instances.delete(this.context),this.renderTarget?.dispose(),this.renderTargetBlur?.dispose(),this.depthMaterial?.dispose(),this.horizontalBlurMaterial?.dispose(),this.verticalBlurMaterial?.dispose(),this.blurPlane?.geometry.dispose(),this.plane?.geometry.dispose(),this.occluderMesh?.geometry.dispose()}onBeforeRender(e){if(this.manualUpdate&&!this._needsUpdate)return;if(this._needsUpdate=!1,!this.renderTarget||!this.renderTargetBlur||!this.depthMaterial||!this.shadowCamera||!this.blurPlane||!this.shadowGroup||!this.plane||!this.horizontalBlurMaterial||!this.verticalBlurMaterial||!this.planeMaterial){Oi&&console.error(`ContactShadows: not initialized yet`);return}this.depthMaterial.userData.darkness.value=this.darkness,this.planeMaterial.opacity=this.opacity;let t=this.context.scene,n=this.context.renderer,r=n.getRenderTarget();this.shadowGroup.visible=!0,this.occluderMesh&&(this.occluderMesh.visible=!1);let i=this.plane.visible;this.plane.visible=!1,this.gameObject instanceof x&&wi(this.gameObject,!1);let a=t.background;t.background=null,t.overrideMaterial=this.depthMaterial,this.backfaceShadows?this.depthMaterial.side=2:this.depthMaterial.side=0;let o=n.getClearAlpha();n.setClearAlpha(0);let s=n.xr.enabled;n.xr.enabled=!1;let c=this.context.scene.matrixWorldAutoUpdate;this.context.scene.matrixWorldAutoUpdate=!1;let l=n.renderLists.get(t,0),u=l.transparent;Ai.length=0,l.transparent=Ai,ji.length=0;for(let e of l.opaque){if(!e.object.visible)continue;let t=e.material,n=e.material.colorWrite==0||t.wireframe===!0||mn(e.object)===!1;!n&&e.material.isLineMaterial&&(n=!0),!n&&e.material.isPointsMaterial&&(n=!0),n&&(ji.push(e.object),e.object[`needle:visible`]=e.object.visible,e.object.visible=!1)}this.shadowCamera.parent?this.shadowCamera.matrixWorld.multiplyMatrices(this.shadowCamera.parent.matrixWorld,this.shadowCamera.matrix):this.shadowCamera.matrixWorld.copy(this.shadowCamera.matrix),this.shadowCamera.matrixWorldInverse.copy(this.shadowCamera.matrixWorld).invert(),n.setRenderTarget(this.renderTarget),n.clear(),n.render(t,this.shadowCamera),l.transparent=u;for(let e of ji)e[`needle:visible`]!=null&&(e.visible=e[`needle:visible`]);t.overrideMaterial=null;let d=Math.max(this.blur,.05);this.blurShadow(d*2),this.blurShadow(d*.5),this.shadowGroup.visible=!1,this.occluderMesh&&(this.occluderMesh.visible=this.occludeBelowGround),this.plane.visible=i,n.setRenderTarget(r),n.setClearAlpha(o),t.background=a,n.xr.enabled=s,this.context.scene.matrixWorldAutoUpdate=c}blurShadow(e){if(!this.blurPlane||!this.shadowCamera||!this.renderTarget||!this.renderTargetBlur||!this.horizontalBlurMaterial||!this.verticalBlurMaterial)return;this.blurPlane.visible=!0;let t=this.shadowsRoot.worldScale,n=(t.x+t.z)/2,r=t.z/n,i=t.x/n;this.blurPlane.material=this.horizontalBlurMaterial,this.blurPlane.material.uniforms.tDiffuse.value=this.renderTarget.texture,this.horizontalBlurMaterial.uniforms.h.value=e*1/this.textureSize*r;let a=this.context.renderer,o=a.getRenderTarget();a.setRenderTarget(this.renderTargetBlur),a.render(this.blurPlane,this.shadowCamera),this.blurPlane.material=this.verticalBlurMaterial,this.blurPlane.material.uniforms.tDiffuse.value=this.renderTargetBlur.texture,this.verticalBlurMaterial.uniforms.v.value=e*1/this.textureSize*i,a.setRenderTarget(this.renderTarget),a.render(this.blurPlane,this.shadowCamera),this.blurPlane.visible=!1,a.setRenderTarget(o)}applyMinSize(){this.minSize&&this.shadowsRoot.scale.set(Math.max(this.minSize.x||0,this.shadowsRoot.scale.x),Math.max(this.minSize.y||0,this.shadowsRoot.scale.y),Math.max(this.minSize.z||0,this.shadowsRoot.scale.z))}};Di([E()],ki.prototype,`autoFit`,void 0),Di([E()],ki.prototype,`darkness`,void 0),Di([E()],ki.prototype,`opacity`,void 0),Di([E()],ki.prototype,`blur`,void 0),Di([E()],ki.prototype,`occludeBelowGround`,void 0),Di([E()],ki.prototype,`backfaceShadows`,void 0);var Ai=[],ji=[],Mi=D(`debugstencil`);function Ni(e,t){return(e&1<<t.layer)!=0}var Pi=Symbol(`stencils`),Fi=class e{get name(){return`NEEDLE_render_objects`}static stencils={};static applyStencil(t){if(!t)return;let n=t.sourceId;if(Mi&&console.log(n,e.stencils),!n)return;let r=e.stencils[n];if(r)for(let e=r.length-1;e>=0;e--){let n=r[e];if(Ni(n.layer,t)){Mi&&console.log(n),setTimeout(()=>{ft()&&bt(t.gameObject)&&(kn(`Stencil not supported on instanced objects`),console.warn(`Stencil not supported on instanced objects`,t))},500);for(let e=0;e<t.sharedMaterials.length;e++){let r=t.sharedMaterials[e];r&&(r=r.clone(),r[Pi]=!0,r.stencilWrite=!0,r.stencilWriteMask=255,r.stencilFuncMask=255,r.stencilRef=n.value,r.stencilFunc=n.compareFunc,r.stencilZPass=n.passOp,r.stencilFail=n.failOp,r.stencilZFail=n.zFailOp,t.sharedMaterials[e]=r)}t.gameObject.renderOrder=n.event*1e3+n.index*50;break}}}parser;source;constructor(e,t){this.parser=e,this.source=t}afterRoot(t){let n=this.parser.json.extensions;if(n){let t=n[Bi];if(t){Mi&&console.log(t);let n=t.stencil;if(n&&Array.isArray(n))for(let t of n){let n={...t};n.compareFunc=zi(n.compareFunc),n.passOp=Ri(n.passOp),n.failOp=Ri(n.failOp),n.zFailOp=Ri(n.zFailOp),e.stencils[this.source]||(e.stencils[this.source]=[]),e.stencils[this.source].push(n)}}}return null}},Ii;(function(e){e[e.Keep=0]=`Keep`,e[e.Zero=1]=`Zero`,e[e.Replace=2]=`Replace`,e[e.IncrementSaturate=3]=`IncrementSaturate`,e[e.DecrementSaturate=4]=`DecrementSaturate`,e[e.Invert=5]=`Invert`,e[e.IncrementWrap=6]=`IncrementWrap`,e[e.DecrementWrap=7]=`DecrementWrap`})(Ii||={});var Li;(function(e){e[e.Disabled=0]=`Disabled`,e[e.Never=1]=`Never`,e[e.Less=2]=`Less`,e[e.Equal=3]=`Equal`,e[e.LessEqual=4]=`LessEqual`,e[e.Greater=5]=`Greater`,e[e.NotEqual=6]=`NotEqual`,e[e.GreaterEqual=7]=`GreaterEqual`,e[e.Always=8]=`Always`})(Li||={});function Ri(e){switch(e){case Ii.Keep:return c;case Ii.Zero:return 0;case Ii.Replace:return le;case Ii.IncrementSaturate:return Ce;case Ii.DecrementSaturate:return d;case Ii.IncrementWrap:return Se;case Ii.DecrementWrap:return g;case Ii.Invert:return l}return 0}function zi(e){switch(e){case Li.Never:return 512;case Li.Less:return 513;case Li.Equal:return 514;case Li.LessEqual:return 515;case Li.Greater:return 516;case Li.NotEqual:return 517;case Li.GreaterEqual:return 518;case Li.Always:return 519}return 512}var Bi=`NEEDLE_render_objects`,Vi=new class{objectToBlock=new WeakMap;meshToOwners=new WeakMap;meshToOriginalCallbacks=new WeakMap;getBlock(e){return this.objectToBlock.get(e)}setBlock(e,t){this.objectToBlock.set(e,t)}deleteBlock(e){this.objectToBlock.delete(e)}isHooked(e,t){return this.meshToOwners.get(e)?.has(t)??!1}addHook(e,t){let n=this.meshToOwners.get(e);n||(n=new Set,this.meshToOwners.set(e,n)),n.add(t)}removeHook(e,t){let n=this.meshToOwners.get(e);n&&(n.delete(t),n.size===0&&this.meshToOwners.delete(e))}getOriginalCallbacks(e){return this.meshToOriginalCallbacks.get(e)}setOriginalCallbacks(e,t){this.meshToOriginalCallbacks.set(e,t)}},Hi=class e{_overrides=[];_defines={};_object=null;get object(){return this._object}constructor(e=null){this._object=e}static get(t){let n=Vi.getBlock(t);return n||(n=new e(t),Vi.setBlock(t,n),$i(t,n)),n}static hasOverrides(e){let t=Vi.getBlock(e);return t?t.hasOverrides():!1}dispose(){this._object&&Vi.deleteBlock(this._object),this._overrides=[],this._object=null}setOverride(e,t,n){let r=this._overrides.find(t=>t.name===e);r?(r.value=t,r.textureTransform=n):this._overrides.push({name:e,value:t,textureTransform:n})}getOverride(e){return this._overrides.find(t=>t.name===e)}removeOveride(e){let t=this._overrides.findIndex(t=>t.name===e);t>=0&&this._overrides.splice(t,1)}clearAllOverrides(){this._overrides=[]}get overrides(){return this._overrides}hasOverrides(){return this._overrides.length>0}setDefine(e,t){this._defines[e]=t}clearDefine(e){this._defines[e]=void 0}getDefines(){return this._defines}getCacheKey(){let e=[],t=Object.keys(this._defines).sort();for(let n of t){let t=this._defines[n];t!==void 0&&e.push(`d:${n}=${t}`)}for(let t of this._overrides){if(t.value===null)continue;let n=``;if(t.value instanceof xe){if(n=t.value.uuid||`texture`,t.textureTransform){let e=t.textureTransform;e.offset&&(n+=`;to:${e.offset.x},${e.offset.y}`),e.repeat&&(n+=`;tr:${e.repeat.x},${e.repeat.y}`)}}else if(Array.isArray(t.value))n=t.value.join(`,`);else if(t.value&&typeof t.value==`object`&&`r`in t.value){let e=t.value;n=`${e.r},${e.g},${e.b},${e.a===void 0?``:e.a}`}else if(t.value&&typeof t.value==`object`&&`x`in t.value){let e=t.value;n=`${e.x},${e.y}${e.z===void 0?``:`,${e.z}`}${e.w===void 0?``:`,${e.w}`}`}else n=String(t.value);e.push(`${t.name}=${n}`)}return e.join(`;`)}},Ui=Symbol(`originalValues`),Wi=Symbol(`savedTextureTransforms`);function Gi(e){let t=Vi.getBlock(e);if(t)return{block:t,owner:e};if(e.parent&&e.parent.type===`Group`&&(t=Vi.getBlock(e.parent),t))return{block:t,owner:e.parent}}var Ki=Symbol(`beforeRenderingFlag`),qi=new WeakMap,Ji=new WeakMap,Yi=function(e,t,n,r){let i=Gi(this)?.block;if(i&&i.hasOverrides()){let e=i.getOverride(`transmission`)?.value,t=i.getOverride(`transparent`)?.value;e!==void 0&&typeof e==`number`&&`transmission`in n&&e!==n.transmission&&(Ji.set(this,n.transmission),n.transmission=e),t!==void 0&&typeof t==`boolean`&&t!==n.transparent&&(qi.set(this,n.transparent),n.transparent=t)}},Xi=function(e,t,n,r){let i=qi.get(e);i!==void 0&&(qi.delete(e),n.transparent=i);let a=Ji.get(e);a!==void 0&&(Ji.delete(e),n.transmission=a)},Zi=function(e,t,n,r,i,a){let o=this.material;if(!o)return;if(Array.isArray(o)){if(!o.includes(i))return}else if(o!==i)return;this[Ki]===void 0&&(this[Ki]=new WeakSet),this[Ki].add(i);let s=Gi(this);if(!s)return;let{block:c,owner:l}=s,u=c.overrides,d=i,f=c.getDefines(),p=Object.keys(f);if(p.length>0){d.defines||={};for(let e of p){let t=f[e];t!==void 0&&(d.defines[e]=t)}}if(u.length===0&&p.length===0)return;let m=p.length>0;d[Ui]||(d[Ui]=[]);let h=d[Ui];for(let e of u){if(e.value===null)continue;let t=d[e.name],n=h.find(t=>t.name===e.name);if(n?n.value=t:h.push({name:e.name,value:t}),!m&&!!t!=!!e.value&&(m=!0),d[e.name]=e.value,e.textureTransform&&e.value instanceof xe){let t=e.value;d[Wi]||(d[Wi]=[]),d[Wi].push({name:e.name,offsetX:t.offset.x,offsetY:t.offset.y,repeatX:t.repeat.x,repeatY:t.repeat.y});let n=e.textureTransform;n.offset&&t.offset.copy(n.offset),n.repeat&&t.repeat.copy(n.repeat)}}m&&(d.needsUpdate=!0),d._forceRefresh=!0},Qi=function(e,t,n,r,i,a){if(this[Ki]===void 0||!this[Ki].has(i))return;this[Ki].delete(i);let o=Gi(this);if(!o)return;let{block:s,owner:c}=o,l=s.overrides,u=i,d=u[Ui],f=s.getDefines(),p=Object.keys(f),m=!1;if(p.length>0&&u.defines){for(let e of p)delete u.defines[e];m=!0}if(l.length===0){m&&(u.needsUpdate=!0,u._forceRefresh=!0);return}if(!d)return;let h=u[Wi];if(h&&h.length>0){for(let e of h){let t=l.find(t=>t.name===e.name);t?.value instanceof xe&&(t.value.offset.set(e.offsetX,e.offsetY),t.value.repeat.set(e.repeatX,e.repeatY))}h.length=0}for(let e of l){let t=d.find(t=>t.name===e.name);t&&(!m&&!!e.value!=!!t.value&&(m=!0),u[e.name]=t.value)}m&&(u.needsUpdate=!0),u._forceRefresh=!0};function $i(e,t){e.type===`Group`?e.children.forEach(n=>{(n.type===`Mesh`||n.type===`SkinnedMesh`)&&ea(n,e,t)}):(e.type===`Mesh`||e.type===`SkinnedMesh`)&&ea(e,e,t)}function ea(e,t,n){if(!Vi.isHooked(e,t)){if(Vi.addHook(e,t),e[`needle:materialPropertyBlock`]=n,!e.onBeforeRender)e.onBeforeRender=Zi;else{let t=e.onBeforeRender;e.onBeforeRender=function(e,n,r,i,a,o){t.call(this,e,n,r,i,a,o),Zi.call(this,e,n,r,i,a,o)}}if(!e.onAfterRender)e.onAfterRender=Qi;else{let t=e.onAfterRender;e.onAfterRender=function(e,n,r,i,a,o){Qi.call(this,e,n,r,i,a,o),t.call(this,e,n,r,i,a,o)}}e.onBeforeRenderListPush=Yi,e.onAfterRenderListPush=Xi}}var ta=function(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},na=D(`debugreflectionprobe`),ra=D(`noreflectionprobe`),ia=null;new Ue;var aa=Symbol(`reflectionProbeKey`),oa=class e extends N{static _probes=new Map;static testBox=new de;static isUsingReflectionProbe(e){return!!e[aa]}static onEnabled=new Ut;static onDisabled=new Ut;static get(t,n,r,i){if(!t||t.isObject3D!==!0||ra)return null;let a=e._probes.get(n);if(a){for(let e of a)if(e.__didAwake||e.__internalAwake(),e.activeAndEnabled){if(i){if(e.gameObject===i)return e}else if(e.isInBox(t))return na&&console.log(`Found reflection probe`,t.name,e.name),e}}return na&&console.debug(`Did not find reflection probe`,t.name,r,t),null}_texture;_textureUrlInFlight;set texture(e){if(this._texture!==e){if(typeof e==`string`){na&&console.debug(`[ReflectionProbe] Loading reflection probe texture from URL: ${e}`),this._textureUrlInFlight=e,Ir(ln(this.sourceId,e),this.context.renderer).then(t=>{this._textureUrlInFlight===e&&t&&(this._textureUrlInFlight=void 0,na&&console.debug(`[ReflectionProbe] Successfully loaded reflection probe texture: ${e}`),this.texture=t)});return}this.__didAwake&&(this._textureUrlInFlight=void 0),this._texture=e,na&&console.debug(`[ReflectionProbe] Set reflection probe texture `+(e?.name||`(removed)`)),e&&(e instanceof re||e.mapping===306||e.mapping!==303&&(e.mapping=303),e.colorSpace=a,e.needsUpdate=!0)}}get texture(){return this._texture}intensity=1;center=new r;size=new r(1,1,1);__lightmapIntensityScale=!0;isInBox(t){return ia??=new de,ia.setFromCenterAndSize(this.gameObject.worldPosition.add(this.center),this.size),fn([t],void 0,void 0,e.testBox),e.testBox.isEmpty()?ia.containsPoint(t.worldPosition):ia?.intersectsBox(e.testBox)}constructor(){super(),e._probes.has(this.context)||e._probes.set(this.context,[]),e._probes.get(this.context)?.push(this)}awake(){this._texture&&(this._texture.mapping!==306&&(this._texture.mapping=303),this._texture.colorSpace=a,this._texture.needsUpdate=!0)}update(){na&&(ia??=new de,ia.setFromCenterAndSize(this.gameObject.worldPosition.add(this.center),this.size),Ln.DrawWireBox3(ia,5592320))}onEnable(){e.onEnabled?.invoke(this)}onDisable(){e.onDisabled?.invoke(this)}start(){this._texture||console.warn(`[ReflectionProbe] Missing texture. Please assign a custom cubemap texture. To use reflection probes assign them to your renderer's "anchor" property.`)}onDestroy(){let t=e._probes.get(this.context);if(t){let e=t.indexOf(this);e>=0&&t.splice(e,1)}}apply(e){if(ra||!this.enabled||!this.texture)return;let t=Hi.get(e);t.setOverride(`envMap`,this.texture),t.setOverride(`envMapRotation`,this.gameObject.rotation);let n=this.intensity;this.__lightmapIntensityScale&&t.getOverride(`lightMap`)&&(n/=Math.PI),t.setOverride(`envMapIntensity`,n)}unapply(e){let t=Hi.get(e);t&&t.getOverride(`envMap`)?.value===this.texture&&t.removeOveride(`envMap`)}};ta([E([xe,String])],oa.prototype,`texture`,null),ta([E()],oa.prototype,`intensity`,void 0),ta([E(r)],oa.prototype,`center`,void 0),ta([E(r)],oa.prototype,`size`,void 0);var sa=D(`debugexr`),ca=class{get name(){return`EXT_texture_exr`}parser;constructor(e){this.parser=e,sa&&console.log(e)}loadTexture(e){let t=this.name,n=this.parser,r=n.json.textures[e];if(sa&&console.log(`EXT_texture_exr.loadTexture`,e,r),!r.extensions||!r.extensions[t])return null;let i=r.extensions[t],a=new lr(n.options.manager);return sa&&console.log(`EXT_texture_exr.loadTexture`,i),n.loadTextureImage(e,i.source,a)}};typeof window<`u`&&window.addEventListener(`unhandledrejection`,e=>{});var la=Pn,ua=`$___Export_Components`,da=`NEEDLE_components`,fa=class{[Dn]},pa=class{node;nodeIndex;nodeDef;constructor(e,t,n){this.node=e,this.nodeIndex=t,this.nodeDef=n}},ma=class{get name(){return da}exportContext;objectToNodeMap={};context;writer;registerExport(e){e.register(e=>{if(`serializeUserData`in e){let t=e.serializeUserData.bind(e);this.writer=e,e.serializeUserData=(n,r)=>{try{this.serializeUserData(n,r)&&(e.extensionsUsed[this.name]=!0),t(n,r)}finally{this.afterSerializeUserData(n,r)}}}return this})}beforeParse(){this.exportContext={},this.objectToNodeMap={}}serializeUserData(e,t){let n=e.userData?.components;return!n||n.length<=0?!1:(delete e.userData.components,e[ua]=n,!0)}afterSerializeUserData(e,t){if(e.type===`Scene`&&la&&console.log(`DONE`,JSON.stringify(t)),e[ua]===void 0)return;let n=e[ua];delete e[ua],n!==null&&(e.userData.components=n)}writeNode(e,t){let n=this.writer.json.nodes.length;la&&console.log(e.name,n,e.uuid);let r=new pa(e,n,t);this.exportContext[n]=r,this.objectToNodeMap[e.uuid]=n}afterParse(e){la&&console.log(`AFTER`,e);for(let e in this.exportContext){let t=this.exportContext[e],n=t.node,r=t.nodeDef,i=t.nodeIndex,a=n.userData?.components;if(!a||a.length<=0)continue;let o=new fa;r.extensions=r.extensions||{},r.extensions[this.name]=o,this.context.object=n,this.context.nodeId=i,this.context.objectToNode=this.objectToNodeMap;let s=[];for(let e of a){this.context.target=e;let t=ot().writeBuiltinComponentData(e,this.context);t!==null&&s.push(t)}s.length>0&&(o[Dn]=s,la&&console.log(`DID WRITE`,n,`nodeIndex`,i,s))}}parser;nodeToObjectMap={};gltf=null;beforeRoot(){return la&&console.log(`BEGIN LOAD`),this.nodeToObjectMap={},null}async afterRoot(e){this.gltf=e;let t=e.parser,n=t?.extensions;if(!n)return;let r=n[this.name];la&&console.log(`After root`,e,this.parser,n);let i=[];if(r===!0){let n=t.json.nodes;if(n){for(let e=0;e<n.length;e++){let n=await t.getDependency(`node`,e);this.nodeToObjectMap[e]=n}for(let r=0;r<n.length;r++){let a=n[r],o=r,s=a.extensions;if(!s)continue;let c=s[this.name];if(!c)continue;la&&console.log(`NODE`,a);let l=this.nodeToObjectMap[o];if(!l){console.error(`Could not find object for node index: `+o,a,t);continue}pt(l),i.push(this.createComponents(e,a,l,c))}}}await Promise.all(i);for(let e of t.associations.keys()){let n=t.associations.get(e);n?.materials!=null&&Ye(e,`/materials/`+n.materials)}}async createComponents(e,t,n,r){if(!r)return;let i=r[Dn];if(i){let r=[];la&&console.log(n.name,i);for(let a in i){let o=i[a];if(la&&console.log(`Serialized data`,JSON.parse(JSON.stringify(o))),(o?.name===`MeshRenderer`||o?.name===`SkinnedMeshRenderer`)&&!o.sharedMaterials){let r=!1;if(`mesh`in t){let n=t.mesh;if(typeof n==`number`&&e.parser){let t=e.parser.json.meshes?.[n];t?.primitives&&(o.sharedMaterials=t.primitives.map(e=>`/materials/`+(e.material??0)),r=!0)}}!r&&(la||T())&&console.warn(`[NEEDLE_components] Component '${o.name}' on object '${n.name}' is not added to a mesh or failed to retrieve materials from glTF.`)}o&&this.parser&&r.push(nn(this.parser,o).catch(e=>console.error(`Error while resolving references (see console for details)
|
||
`,e,n,o))),n.userData=n.userData||{},n.userData[Dn]=n.userData.builtin_components||[],n.userData[Dn].push(o)}await Promise.all(r).catch(e=>{console.error(`Error while loading components`,e)})}}},ha=`NEEDLE_gameobject_data`,ga=class{get name(){return ha}parser;constructor(e){this.parser=e}afterRoot(e){let t=[];for(let e=0;e<this.parser.json.nodes?.length;e++){let n=this.parser.json.nodes[e];if(n&&n.extensions){let r=n.extensions[ha];if(r){let n=this.findAndApplyExtensionData(e,r);t.push(n)}}}return Promise.all(t).then(()=>null)}async findAndApplyExtensionData(e,t){let n=await this.parser.getDependency(`node`,e);n&&this.applyExtensionData(n,t)}applyExtensionData(e,t){t.layers===void 0&&(t.layers=0),e.userData.layer=t.layers,e.layers.disableAll(),e.layers.set(t.layers),e.userData.tag=t.tag??`none`,e.hideFlags=0,e.userData.static=t.static??!1,e.visible=t.activeSelf??!0,e.guid=t.guid}},_a=`NEEDLE_lighting_settings`,va=D(`debugenvlight`),ya=class{get name(){return _a}parser;sourceId;context;constructor(e,t,n){this.parser=e,this.sourceId=t,this.context=n}afterRoot(e){let t=this.parser.json.extensions;if(t){let r=t[_a];if(r){va&&console.log(`Loaded "`+this.name+`", src: "`+this.sourceId+`"`,r);let t;if(e.scene.children.length===1){let n=e.scene.children[0];t=k.addComponent(n,ba,{},{callAwake:!1})}else{let n=new S;n.name=`LightSettings `+this.sourceId,e.scene.add(n),t=k.addComponent(n,ba,{},{callAwake:!1})}t.sourceId=this.sourceId,t.ambientIntensity=r.ambientIntensity,t.ambientLight=new n().fromArray(r.ambientLight),Array.isArray(r.ambientTrilight)&&(t.ambientTrilight=r.ambientTrilight.map(e=>new n().fromArray(e))),t.ambientMode=r.ambientMode,t.environmentReflectionSource=r.environmentReflectionSource}}return null}};Ht.registerCallback(zt.ContextCreated,e=>{let t=e.context,n=k.findObjectOfType(ba,t);n?.sourceId&&(n.enabled=!0)});var ba=class extends N{ambientMode=Vt.Skybox;ambientLight;ambientTrilight;ambientIntensity=1;environmentReflectionSource=dt.Skybox;_hasReflection=!1;_ambientLightObj;_hemisphereLightObj;awake(){if(this.sourceId){let e=this.environmentReflectionSource===dt.Skybox?It.Skybox:It.Reflection,t=this.context.lightmaps.tryGet(this.sourceId,e,0);this._hasReflection=t!=null,t&&this.context.sceneLighting.internalRegisterReflection(this.sourceId,t)}this.enabled=!1,this.context.sceneLighting.internalRegisterSceneLightSettings(this),va&&window.addEventListener(`keydown`,e=>{if(!this.destroyed)switch(e.key){case`l`:this.enabled=!this.enabled;break}});let e=this.gameObject.userData?.components;if(e){let t=e.indexOf(this);e.splice(t,1),e.push(this)}}onDestroy(){this.context.sceneLighting.internalUnregisterSceneLightSettings(this)}calculateIntensityFactor(e){let t=Math.max(e.r,e.g,e.b);return 2.2*Rt.lerp(0,1.33,t)}onEnable(){if(va&&console.warn(`💡🟡 >>> Enable lighting`,this.sourceId,this.enabled,this),this.ambientMode==Vt.Flat){if(this.ambientLight&&!this._ambientLightObj){let e=this.calculateIntensityFactor(this.ambientLight);this._ambientLightObj=new Pe(this.ambientLight,this.ambientIntensity*e),va&&console.log(`Created ambient light`,this.sourceId,this._ambientLightObj,this.ambientIntensity,e)}this._ambientLightObj&&this.gameObject.add(this._ambientLightObj)}else if(this.ambientMode===Vt.Trilight){if(this.ambientTrilight){let e=this.ambientTrilight[0],t=this.ambientTrilight[this.ambientTrilight.length-1],n=this.calculateIntensityFactor(t);this._hemisphereLightObj=new Me(t,e,this.ambientIntensity*n),this.gameObject.add(this._hemisphereLightObj),va&&console.log(`Created hemisphere ambient light`,this.sourceId,this._hemisphereLightObj,this.ambientIntensity,n)}}else this._ambientLightObj&&this._ambientLightObj.removeFromParent(),this._hemisphereLightObj&&this._hemisphereLightObj.removeFromParent();this.sourceId&&(this.context.domElement.getAttribute(`environment-image`)||this.context.sceneLighting.internalEnableReflection(this.sourceId))}onDisable(){va&&console.warn(`💡⚫ <<< Disable lighting:`,this.sourceId,this),this._ambientLightObj&&this._ambientLightObj.removeFromParent(),this._hemisphereLightObj&&this._hemisphereLightObj.removeFromParent(),this.sourceId&&this.context.sceneLighting.internalDisableReflection(this.sourceId)}},xa;(function(e){async function t(e,t){if(!e)throw Error(`URL or XML string is required to load a MaterialX material`);let n=await on.MaterialX.load(),r=e.trimStart().startsWith(`<`),i=r?e:await fetch(e).then(e=>e.text()).catch(console.error);if(!i)return console.warn(`Failed to load MaterialX file from url`,e),null;let a;if(t?.url||!r){let n=(t?.url||e).split(`/`);n.pop(),a=n.join(`/`)}let o=new pe;return n.Experimental_API.createMaterialXMaterial(i,t?.materialNameOrIndex??0,{getTexture:async e=>(!e.startsWith(`http`)&&!e.startsWith(`data:`)&&!e.startsWith(`blob:`)&&!e.startsWith(`file:`)&&a&&(e=a+`/`+e),o.loadAsync(e).catch(t=>{console.warn(`Failed to load texture for MaterialX material ${e}`,t)}))},{cacheKey:e})}e.loadFromUrl=t})(xa||={});var Sa=class extends oe{loadAsync(e,t){return new Promise((n,r)=>{this.load(e,n,t,r)})}load(e,t,n,r){n?.({type:`progress`,loaded:0,total:0}),xa.loadFromUrl(e,{}).then(n=>{n?t(this.onLoaded(n)):r?.(Error(`Failed to load MaterialX material from url: `+e))})}onLoaded(e){return St.createPrimitive(`ShaderBall`,{material:e})}},Ca=class{context;loader;url;parser;get name(){return`materialx-loading-helper`}constructor(e,t,n,r){this.context=e,this.loader=t,this.url=n,this.parser=r}mtlxLoader;async beforeRoot(){if(this.parser.json.extensions?.NEEDLE_materials_mtlx){let e=await on.MaterialX.load();try{this.mtlxLoader=new e.MaterialXLoader(this.parser,{cacheKey:`${this.url}:materialx`,parameters:{precision:this.context.renderer?.capabilities.precision}},{getFrame:()=>this.context.time.frame,getTime:()=>this.context.time.time})}catch(e){console.error(e)}}}loadMaterial(e){return this.mtlxLoader?this.mtlxLoader.loadMaterial(e):null}},wa;(function(e){e[e.Fragment=35632]=`Fragment`,e[e.Vertex=35633]=`Vertex`})(wa||={});var Ta;(function(e){e[e.INT=5124]=`INT`,e[e.FLOAT=5126]=`FLOAT`,e[e.FLOAT_VEC2=35664]=`FLOAT_VEC2`,e[e.FLOAT_VEC3=35665]=`FLOAT_VEC3`,e[e.FLOAT_VEC4=35666]=`FLOAT_VEC4`,e[e.INT_VEC2=35667]=`INT_VEC2`,e[e.INT_VEC3=35668]=`INT_VEC3`,e[e.INT_VEC4=35669]=`INT_VEC4`,e[e.BOOL=35670]=`BOOL`,e[e.BOOL_VEC2=35671]=`BOOL_VEC2`,e[e.BOOL_VEC3=35672]=`BOOL_VEC3`,e[e.BOOL_VEC4=35673]=`BOOL_VEC4`,e[e.FLOAT_MAT2=35674]=`FLOAT_MAT2`,e[e.FLOAT_MAT3=35675]=`FLOAT_MAT3`,e[e.FLOAT_MAT4=35676]=`FLOAT_MAT4`,e[e.SAMPLER_2D=35678]=`SAMPLER_2D`,e[e.SAMPLER_3D=35680]=`SAMPLER_3D`,e[e.SAMPLER_CUBE=35681]=`SAMPLER_CUBE`,e[e.UNKNOWN=0]=`UNKNOWN`})(Ta||={});var Ea=D(`debugcustomshader`),Da=`NEEDLE_techniques_webgl`,Oa;(function(e){e[e.INT=5124]=`INT`,e[e.FLOAT=5126]=`FLOAT`,e[e.FLOAT_VEC2=35664]=`FLOAT_VEC2`,e[e.FLOAT_VEC3=35665]=`FLOAT_VEC3`,e[e.FLOAT_VEC4=35666]=`FLOAT_VEC4`,e[e.INT_VEC2=35667]=`INT_VEC2`,e[e.INT_VEC3=35668]=`INT_VEC3`,e[e.INT_VEC4=35669]=`INT_VEC4`,e[e.BOOL=35670]=`BOOL`,e[e.BOOL_VEC2=35671]=`BOOL_VEC2`,e[e.BOOL_VEC3=35672]=`BOOL_VEC3`,e[e.BOOL_VEC4=35673]=`BOOL_VEC4`,e[e.FLOAT_MAT2=35674]=`FLOAT_MAT2`,e[e.FLOAT_MAT3=35675]=`FLOAT_MAT3`,e[e.FLOAT_MAT4=35676]=`FLOAT_MAT4`,e[e.SAMPLER_2D=35678]=`SAMPLER_2D`,e[e.SAMPLER_3D=35680]=`SAMPLER_3D`,e[e.SAMPLER_CUBE=35681]=`SAMPLER_CUBE`,e[e.UNKNOWN=0]=`UNKNOWN`})(Oa||={});var ka=class{objectToWorldMatrix=new b;worldToObjectMatrix=new b;objectToWorld=[];worldToObject=[];updateFrom(e){this.objectToWorldMatrix.copy(e.matrixWorld),Wt(this.objectToWorldMatrix,this.objectToWorld),this.worldToObjectMatrix.copy(e.matrixWorld).invert(),Wt(this.worldToObjectMatrix,this.worldToObject)}},Aa;(function(e){e[e.Off=0]=`Off`,e[e.Front=1]=`Front`,e[e.Back=2]=`Back`})(Aa||={});var ja;(function(e){e[e.Never=1]=`Never`,e[e.Less=2]=`Less`,e[e.Equal=3]=`Equal`,e[e.LEqual=4]=`LEqual`,e[e.Greater=5]=`Greater`,e[e.NotEqual=6]=`NotEqual`,e[e.GEqual=7]=`GEqual`,e[e.Always=8]=`Always`})(ja||={});var Ma=class e extends y{identifier;onBeforeRenderSceneCallback=this.onBeforeRenderScene.bind(this);clone(){let e=super.clone();return Pa(e),e}constructor(e,...t){super(...t),this.identifier=e,Ea&&console.log(this),this.type=`NEEDLE_CUSTOM_SHADER`,this.uniforms[this._objToWorldName]||(this.uniforms[this._objToWorldName]={value:[]}),this.uniforms[this._worldToObjectName]||(this.uniforms[this._worldToObjectName]={value:[]}),this.uniforms[this._viewProjectionName]||(this.uniforms[this._viewProjectionName]={value:[]}),this.uniforms[this._sphericalHarmonicsName],(this.depthTextureUniform||this.opaqueTextureUniform)&&Xt.Current.pre_render_callbacks.push(this.onBeforeRenderSceneCallback)}dispose(){super.dispose();let e=Xt.Current.pre_render_callbacks.indexOf(this.onBeforeRenderSceneCallback);e>=0&&Xt.Current.pre_render_callbacks.splice(e,1)}_sphericalHarmonicsName=`unity_SpecCube0`;_objToWorldName=`hlslcc_mtx4x4unity_ObjectToWorld`;_worldToObjectName=`hlslcc_mtx4x4unity_WorldToObject`;static viewProjection=new b;static _viewProjectionValues=[];_viewProjectionName=`hlslcc_mtx4x4unity_MatrixVP`;static viewMatrix=new b;static _viewMatrixValues=[];_viewMatrixName=`hlslcc_mtx4x4unity_MatrixV`;static _worldSpaceCameraPosName=`_WorldSpaceCameraPos`;static _worldSpaceCameraPos=new r;static _mainLightColor=new C;static _mainLightPosition=new r;static _lightData=new C;_rendererData=new ka;get depthTextureUniform(){if(this.uniforms)return this.uniforms._CameraDepthTexture}get opaqueTextureUniform(){if(this.uniforms)return this.uniforms._CameraOpaqueTexture}onBeforeRenderScene(){this.opaqueTextureUniform&&Xt.Current.setRequireColor(!0),this.depthTextureUniform&&Xt.Current.setRequireDepth(!0)}onBeforeRender(e,t,n,r,i,a){r.attributes.tangent||r.computeTangents(),this.onUpdateUniforms(n,i)}onUpdateUniforms(t,n){let r=Xt.Current;if(t&&(e.viewProjection&&this.uniforms[this._viewProjectionName]&&(e.viewProjection.copy(t.projectionMatrix).multiply(t.matrixWorldInverse),Wt(e.viewProjection,e._viewProjectionValues)),e.viewMatrix&&this.uniforms[this._viewMatrixName]&&(e.viewMatrix.copy(t.matrixWorldInverse),Wt(e.viewMatrix,e._viewMatrixValues)),this.uniforms[e._worldSpaceCameraPosName]&&e._worldSpaceCameraPos.setFromMatrixPosition(t.matrixWorld)),this.uniforms._TimeParameters&&(this.uniforms._TimeParameters.value=r.sceneLighting.timeVec4),this.uniforms._Time){let e=this.uniforms._Time.value;e.x=r.sceneLighting.timeVec4.x/20,e.y=r.sceneLighting.timeVec4.x,e.z=r.sceneLighting.timeVec4.x*2,e.w=r.sceneLighting.timeVec4.x*3}if(this.uniforms._SinTime){let e=this.uniforms._SinTime.value;e.x=Math.sin(r.sceneLighting.timeVec4.x/8),e.y=Math.sin(r.sceneLighting.timeVec4.x/4),e.z=Math.sin(r.sceneLighting.timeVec4.x/2),e.w=Math.sin(r.sceneLighting.timeVec4.x)}if(this.uniforms._CosTime){let e=this.uniforms._CosTime.value;e.x=Math.cos(r.sceneLighting.timeVec4.x/8),e.y=Math.cos(r.sceneLighting.timeVec4.x/4),e.z=Math.cos(r.sceneLighting.timeVec4.x/2),e.w=Math.cos(r.sceneLighting.timeVec4.x)}if(this.uniforms.unity_DeltaTime){let e=this.uniforms.unity_DeltaTime.value;e.x=r.time.deltaTime,e.y=1/r.time.deltaTime,e.z=r.time.smoothedDeltaTime,e.w=1/r.time.smoothedDeltaTime}let i=r.mainLight;if(i){let t=Yt(i.gameObject,e._mainLightPosition);this.uniforms._MainLightPosition={value:t.normalize()},e._mainLightColor.set(i.color.r,i.color.g,i.color.b,0),this.uniforms._MainLightColor={value:e._mainLightColor};let n=i.intensity;e._lightData.z=n,this.uniforms.unity_LightData={value:e._lightData}}if(t&&(e.viewProjection&&this.uniforms[this._viewProjectionName]&&(this.uniforms[this._viewProjectionName].value=e._viewProjectionValues),e.viewMatrix&&this.uniforms[this._viewMatrixName]&&(this.uniforms[this._viewMatrixName].value=e._viewMatrixValues),this.uniforms[e._worldSpaceCameraPosName]&&(this.uniforms[e._worldSpaceCameraPosName]={value:e._worldSpaceCameraPos}),r.mainCameraComponent)){if(this.uniforms._ProjectionParams){let e=this.uniforms._ProjectionParams.value;e.x=1,e.y=r.mainCameraComponent.nearClipPlane,e.z=r.mainCameraComponent.farClipPlane,e.w=1/e.z,this.uniforms._ProjectionParams.value=e}if(this.uniforms._ZBufferParams){let e=this.uniforms._ZBufferParams.value,t=r.mainCameraComponent;e.x=1-t.farClipPlane/t.nearClipPlane,e.y=t.farClipPlane/t.nearClipPlane,e.z=e.x/t.farClipPlane,e.w=e.y/t.farClipPlane,this.uniforms._ZBufferParams.value=e}if(this.uniforms._ScreenParams){let e=this.uniforms._ScreenParams.value;e.x=r.domWidth,e.y=r.domHeight,e.z=1+1/e.x,e.w=1+1/e.y,this.uniforms._ScreenParams.value=e}if(this.uniforms._ScaledScreenParams){let e=this.uniforms._ScaledScreenParams.value;e.x=r.domWidth,e.y=r.domHeight,e.z=1+1/e.x,e.w=1+1/e.y,this.uniforms._ScaledScreenParams.value=e}}let a=this.depthTextureUniform;a&&(a.value=r.depthTexture);let o=this.opaqueTextureUniform;if(o&&(o.value=r.opaqueColorTexture),n){let e=this._rendererData;e.updateFrom(n),this.uniforms[this._worldToObjectName].value=e.worldToObject,this.uniforms[this._objToWorldName].value=e.objectToWorld}this.uniformsNeedUpdate=!0}},Na=class{get name(){return Da}parser;identifier;constructor(e,t){this.parser=e,this.identifier=t}loadMaterial(e){let t=this.parser.json.materials[e];if(!t)return Ea&&console.log(e,this.parser.json.materials),null;if(!t.extensions||!t.extensions.NEEDLE_techniques_webgl)return Ea&&console.log(`Material ${e} does not use NEEDLE_techniques_webgl`),null;Ea&&console.log(`Material ${e} uses NEEDLE_techniques_webgl`,t);let n=t.extensions[Da].technique;if(n<0)return console.debug(`Material ${e} does not have a valid technique index`),null;let r=this.parser.json.extensions[Da];if(!r)return Ea?console.error(`Missing shader data`,this.parser.json.extensions):console.debug(`Missing custom shader data in parser.json.extensions`),null;Ea&&console.log(r);let i=r.techniques[n];return i?new Promise(async(e,o)=>{let s=await ht(r,i.program),c=s?.fragmentShader,l=s?.vertexShader;if(!c||!l)return o();Ea&&console.log(`loadMaterial`,t,s);let u={},d=i.uniforms;(l.includes(`_Time`)||c.includes(`_Time`))&&(u._Time={value:new C(0,0,0,0)}),(l.includes(`_SinTime`)||c.includes(`_SinTime`))&&(u._SinTime={value:new C(0,0,0,0)}),(l.includes(`_CosTime`)||c.includes(`_CosTime`))&&(u._CosTime={value:new C(0,0,0,0)}),(l.includes(`unity_DeltaTime`)||c.includes(`unity_DeltaTime`))&&(u.unity_DeltaTime={value:new C(0,0,0,0)});for(let e in d){let t=e;switch(t){case`_TimeParameters`:u[t]={value:new C};break;case`hlslcc_mtx4x4unity_MatrixV`:case`hlslcc_mtx4x4unity_MatrixVP`:u[t]={value:[]};break;case`_MainLightPosition`:case`_MainLightColor`:case`_WorldSpaceCameraPos`:u[t]={value:[0,0,0,1]};break;case`unity_OrthoParams`:break;case`unity_SpecCube0`:u[t]={value:null};break;default:case`_ScreenParams`:case`_ZBufferParams`:case`_ProjectionParams`:u[t]={value:[0,0,0,0]};break;case`_CameraOpaqueTexture`:case`_CameraDepthTexture`:u[t]={value:null};break}}let f=!1;if(t.extensions&&t.extensions.NEEDLE_techniques_webgl){let e=t.extensions[Da];if(e.technique===n){Ea&&console.log(t.name,`Material Properties`,e);for(let t in e.values){let n=e.values[t];if(typeof n==`string`){if(n.startsWith(`/textures/`)){let e=n.substring(10),r=Number.parseInt(e);if(r>=0){let e=await this.parser.getDependency(`texture`,r);e instanceof xe&&(e.colorSpace=a,e.needsUpdate=!0),u[t]={value:e};continue}}switch(t){case`alphaMode`:n===`BLEND`&&(f=!0);continue}}if(Array.isArray(n)&&n.length===4){u[t]={value:new C(n[0],n[1],n[2],n[3])};continue}u[t]={value:n}}}}let p=new Ma(this.identifier,{name:t.name??``,uniforms:u,vertexShader:l,fragmentShader:c,lights:!1});switch(p.glslVersion=Oe,p.vertexShader=p.vertexShader.replace(`#version 300 es`,``),p.fragmentShader=p.fragmentShader.replace(`#version 300 es`,``),u._Cull?.value){case Aa.Off:p.side=2;break;case Aa.Front:p.side=1;break;case Aa.Back:p.side=0;break;default:p.side=0;break}switch(u._ZTest?.value){case ja.Equal:p.depthTest=!0,p.depthFunc=4;break;case ja.NotEqual:p.depthTest=!0,p.depthFunc=7;break;case ja.Less:p.depthTest=!0,p.depthFunc=2;break;case ja.LEqual:p.depthTest=!0,p.depthFunc=3;break;case ja.Greater:p.depthTest=!0,p.depthFunc=6;break;case ja.GEqual:p.depthTest=!0,p.depthFunc=5;break;case ja.Always:p.depthTest=!1,p.depthFunc=1;break}p.transparent=f,f&&(p.depthWrite=!1),Gt(u),p.onUpdateUniforms();for(let e in d){let t=e,n=d[e].type;if(u[t]?.value===void 0)switch(n){case Ta.SAMPLER_2D:u[t]={value:jt},console.warn(`Missing/unassigned texture, fallback to white: `+t);break;default:t===`unity_OrthoParams`||console.warn(`TODO: EXPECTED UNIFORM / fallback NOT SET: `+t,d[e]);break}}Ea&&console.log(p.uuid,u),Pa(p),e(p)}):null}};function Pa(e){if(e.uniforms){Ea&&console.log(`Uniforms:`,e.uniforms);for(let n in e.uniforms)switch(t(n,n),n){case`_Color`:t(`color`,n);break;case`_map`:t(`map`,n);break}}function t(t,n){Object.getOwnPropertyDescriptor(e,t)||Object.defineProperty(e,t,{get:()=>e.uniforms[n].value,set:t=>{e.uniforms[n].value=t,e.needsUpdate=!0}})}}var Fa=D(`debugextensions`),Ia,La=e(()=>import(`./needle-engine.dep.BzZBR-mM.js`).then(async e=>(Ia=e.GLTFAnimationPointerExtension,Ia)),__vite__mapDeps([0,1,2,3]),import.meta.url).catch(e=>{console.warn(`Failed to import GLTFLoaderAnimationPointer. Please use @needle-tools/three-animationpointer for full KHR_animation support`,e)}),Ra=[];function za(e){Ra.includes(e)||Ra.push(e)}function Ba(e){let t=Ra.indexOf(e);t>=0&&Ra.splice(t,1)}function Va(e){if(e instanceof sr){let t=new ma;return e.register(e=>(t.parser=e,t)),t}return null}var Ha=class{resolvePath(e){return e.includes(`/extensions/builtin_components/`)?e.replace(`/extensions/builtin_components/`,`/userData/components/`):e.includes(`extensions/builtin_components/`)?e.replace(`extensions/builtin_components/`,`/userData/components/`):e}};async function Ua(e,t,n,r){let i=n.indexOf(`?`);i>=0&&(n=n.substring(0,i)),r||=n,(r.startsWith(`blob:`)||r.startsWith(`data:`))&&console.debug(`[GLTFLoader] Suspicious sourceId detected`),e.register(e=>new ga(e)),e.register(e=>new Jt(e)),e.register(e=>new it(e,t.lightmaps,r)),e.register(e=>new ya(e,r,t)),e.register(e=>new Na(e,r)),e.register(e=>new Fi(e,r)),e.register(e=>new P(e)),e.register(e=>new ca(e)),e.register(e=>new Vn(e)),e.register(r=>new Ca(t,e,n,r)),bn()&&e.register(e=>new Qt(e)),await La.catch(e=>{}),e.register(e=>{if(Ia){let t=new Ia(e);return t.setAnimationPointerResolver.bind(t)(new Ha),t}else return(Fa||T())&&console.error(`Missing KHR_animation_pointer extension...`),{name:`KHR_animation_pointer_NOT_AVAILABLE`}});for(let r of Ra)r.onImport&&r.onImport(e,n,t)}function Wa(e,t){for(let n of Ra)n.onExport&&n.onExport(e,t)}function Ga(e,t,n){for(let r of Ra)r.onLoaded&&r.onLoaded(e,t,n)}var z=D(`debuginstancing`),Ka=class e{static instance=new e;static getStartInstanceCount=e=>4;objs=[];setup(e,t,n,r,i,a=0){e.applySettings(t);let o=this.tryCreateOrAddInstance(t,n,i);if(o){r===null&&(r=[]),r.push(o);let e=o.object.material;Array.isArray(e)?e.forEach(e=>P.assignTextureLOD(e,0)):P.assignTextureLOD(e,0);let t=o.object,n=t.geometry;P.assignMeshLOD(t,0).then(e=>{e&&n!=e&&o.setGeometry(e)})}else if(a<=0&&t.type!==`Mesh`){let o=a+1;for(let a of t.children)r=this.setup(e,a,n,r,i,o)}return a===0&&i.useMatrixWorldAutoUpdate&&r&&r.length>=0&&this.autoUpdateInstanceMatrix(t),r}tryCreateOrAddInstance(t,n,r){if(t.type===`Mesh`){let i=r.foundMeshes;if(r.foundMeshes+=1,!r.rend.enableInstancing)return null;if(r.rend.enableInstancing!==!0){if(i>=r.rend.enableInstancing.length)return z&&console.error(`Something is wrong with instance setup`,t,r.rend.enableInstancing,i),null;if(!r.rend.enableInstancing[i])return null}let a=t,o=a.material;for(let e of this.objs)if(e.canAdd(a.geometry,o))return e.addInstance(a);let s=e.getStartInstanceCount(t);(!s||s<0)&&(s=4);let c=t.name;c?.length||(c=rt());let l=new Ja(c,a.geometry,o,s,n);return this.objs.push(l),l.addInstance(a)}return null}autoUpdateInstanceMatrix(e){let t=e.matrixWorld.multiplyMatrices.bind(e.matrixWorld),n=e.matrixWorld.clone(),r=(r,i)=>{let a=t(r,i);return(e[Kt]||n.equals(a)===!1)&&(n.copy(a),e[Kt]=!0),a};e.matrixWorld.multiplyMatrices=r}},qa=class e{static all=[];get name(){return this.object.name}get isActive(){return this.__instanceIndex>=0}get vertexCount(){return this.object.geometry.attributes.position.count}get maxVertexCount(){return Math.max(this.meshInformation.vertexCount,this.vertexCount)}get reservedVertexCount(){return this.__reservedVertexRange}get indexCount(){return this.object.geometry.index?this.object.geometry.index.count:0}get maxIndexCount(){return Math.max(this.meshInformation.indexCount,this.indexCount)}get reservedIndexCount(){return this.__reservedIndexRange}object;renderer;__instanceIndex=-1;__reservedVertexRange=0;__reservedIndexRange=0;__geometryIndex=-1;meshInformation;constructor(t,n){this.__instanceIndex=-1,this.object=t,this.renderer=n,t[On]=n,this.meshInformation=Ya(t.geometry),e.all.push(this)}updateMeshInformation(){let e=Ya(this.object.geometry),t=this.meshInformation.vertexCount,n=this.meshInformation.indexCount;return Object.assign(this.meshInformation,e),t!==this.meshInformation.vertexCount||n!==this.meshInformation.indexCount}updateInstanceMatrix(e=!1,t=!0){this.__instanceIndex<0||(t&&this.object.updateWorldMatrix(!0,e),this.renderer.updateInstance(this.object.matrixWorld,this.__instanceIndex))}setMatrix(e){this.__instanceIndex<0||this.renderer.updateInstance(e,this.__instanceIndex)}setGeometry(e){if(this.__geometryIndex<0)return!1;let t=this;if(this.vertexCount>this.__reservedVertexRange)return n(`Instancing: Can not update geometry (${this.name}), reserved vertex range is too small: ${this.__reservedVertexRange.toLocaleString()} < ${this.vertexCount.toLocaleString()} vertices for ${this.name}`);if(this.indexCount>this.__reservedIndexRange)return n(`Instancing: Can not update geometry (${this.name}), reserved index range is too small: ${this.__reservedIndexRange.toLocaleString()} < ${this.indexCount.toLocaleString()} indices for ${this.name}`);return this.renderer.updateGeometry(e,this.__geometryIndex);function n(e){return t.updateMeshInformation()&&(t.renderer.remove(t,!0),t.renderer.add(t))?!0:((T()||z)&&console.error(e),!1)}}add(){this.__instanceIndex>=0||(this.renderer.add(this),k.markAsInstancedRendered(this.object,!0))}remove(t){if(!(this.__instanceIndex<0)&&(this.renderer.remove(this,t),k.markAsInstancedRendered(this.object,!1),t)){let t=e.all.indexOf(this);t>=0&&e.all.splice(t,1)}}},Ja=class{get batchedMesh(){return this._batchedMesh}get visible(){return this._batchedMesh.visible}set visible(e){this._batchedMesh.visible=e}get castShadow(){return this._batchedMesh.castShadow}set castShadow(e){this._batchedMesh.castShadow=e}set receiveShadow(e){this._batchedMesh.receiveShadow=e}allowResize=!0;name=``;geometry;material;get count(){return this._currentInstanceCount}updateBounds(e=!0,t=!0){if(this._needUpdateBounds=!1,e&&this._batchedMesh.computeBoundingBox(),t&&this._batchedMesh.computeBoundingSphere(),z&&this._batchedMesh.boundingSphere){let e=this._batchedMesh.boundingSphere;Ln.DrawWireSphere(e.center,e.radius,65280)}}_context;_batchedMesh;_handles=[];_geometryIds=new WeakMap;_maxInstanceCount;_currentInstanceCount=0;_currentVertexCount=0;_currentIndexCount=0;_maxVertexCount;_maxIndexCount;static nullMatrix=new b;canAdd(e,t){return this._maxVertexCount>1e7||t!==this.material||!this.validateGeometry(e)?!1:!!(!this.mustGrow(e)||this.allowResize)}_needUpdateBounds=!1;_debugMaterial=null;getBatchedMeshName(){return this.name?`${this.name} (BatchedMesh)`:`BatchedMesh`}constructor(e,t,n,r,i){this.name=e,this.geometry=t,this.material=n,this._context=i,this._maxInstanceCount=Math.max(2,r),z&&(this._debugMaterial=Xa());let a=this.tryEstimateVertexCountSize(this._maxInstanceCount,[t],r);this._maxVertexCount=a.vertexCount,this._maxIndexCount=a.indexCount,this._batchedMesh=new ke(this._maxInstanceCount,this._maxVertexCount,this._maxIndexCount,this._debugMaterial??this.material),this._batchedMesh.name=this.getBatchedMeshName(),this._batchedMesh[_t]=!0,this._batchedMesh.visible=!0,this._context.scene.add(this._batchedMesh),n instanceof y&&(n.defines.USE_INSTANCING=!0,n.needsUpdate=!0),i.pre_render_callbacks.push(this.onBeforeRender),i.post_render_callbacks.push(this.onAfterRender),z&&console.log(`Instanced renderer (${this.name}) created with ${this._maxInstanceCount} instances, ${this._maxVertexCount} max vertices and ${this._maxIndexCount} max indices for \"${e}\"`)}dispose(){z&&console.warn(`Dispose instanced renderer`,this.name),this._context.scene.remove(this._batchedMesh),this._batchedMesh.dispose(),this._batchedMesh=null,this._handles=[]}addInstance(e){let t=new qa(e,this);e.castShadow===!0&&this._batchedMesh.castShadow===!1&&(this._batchedMesh.castShadow=!0),e.receiveShadow===!0&&this._batchedMesh.receiveShadow===!1&&(this._batchedMesh.receiveShadow=!0);try{this.add(t)}catch(t){return console.error(`Failed adding mesh to instancing (object name: \"${e.name}\", instances: ${this._currentInstanceCount.toLocaleString()}/${this._maxInstanceCount.toLocaleString()}, vertices: ${this._currentVertexCount.toLocaleString()}/${this._maxVertexCount.toLocaleString()}, indices: ${this._currentIndexCount.toLocaleString()}/${this._maxIndexCount.toLocaleString()})\n`,t),T()&&Nn(`Failed instancing mesh. See the browser console for details.`),null}return t}add(e){let t=e.object.geometry;if(!t||!t.attributes)return console.error(`Cannot add object to instancing without geometry`,e.name),!1;if(this._currentInstanceCount+1>this._maxInstanceCount||this.mustGrow(t))if(this.allowResize)this.grow(t);else return console.error(`Cannot add instance, max count reached`,this.name,this.count,this._maxInstanceCount),!1;return e.object.updateWorldMatrix(!0,!0),this.addGeometry(e),this._handles[e.__instanceIndex]=e,this._currentInstanceCount+=1,this.markNeedsUpdate(),this._currentInstanceCount>0&&(this._batchedMesh.visible=!0),!0}remove(e,t){e&&(e.__instanceIndex<0||this._handles[e.__instanceIndex]!=e||this._currentInstanceCount<=0||(this.removeGeometry(e,t),this._handles[e.__instanceIndex]=null,e.__instanceIndex=-1,this._currentInstanceCount>0&&--this._currentInstanceCount,this._currentInstanceCount<=0&&(this._batchedMesh.visible=!1),this.markNeedsUpdate()))}updateInstance(e,t){this._batchedMesh.setMatrixAt(t,e),this.markNeedsUpdate()}updateGeometry(e,t){return this.validateGeometry(e)?(this.mustGrow()&&this.grow(e),z&&console.debug(`[Instancing] UPDATE GEOMETRY at `+t,this._batchedMesh._geometryCount,e.name,Ya(e),e.attributes.position.count,e.index?e.index.count:0),this._batchedMesh.setGeometryAt(t,e),this._geometryIds.set(e,t),this.markNeedsUpdate(),!0):!1}onBeforeRender=()=>{this._batchedMesh.layers.enableAll(),this._needUpdateBounds&&this._batchedMesh[_t]===!0&&(z===`verbose`&&console.log(`Update instancing bounds`,this.name,this._batchedMesh.matrixWorldNeedsUpdate),this.updateBounds())};onAfterRender=()=>{this._batchedMesh.layers.disableAll()};validateGeometry(e){let t=this.geometry;for(let n in t.attributes)if(n!==`batchId`&&!e.hasAttribute(n))return T()&&console.warn(`BatchedMesh: Added geometry missing "${n}". All geometries must have consistent attributes.`),!1;return!0}markNeedsUpdate(){z===`verbose`&&console.warn(`Marking instanced mesh dirty`,this.name),this._needUpdateBounds=!0}mustGrow(e){if(this.count>=this._maxInstanceCount)return!0;if(!e||!e.attributes||this._geometryIds.has(e))return!1;let t=Ya(e),n=t.vertexCount,r=t.indexCount;return this._currentVertexCount+n>this._maxVertexCount||this._currentIndexCount+r>this._maxIndexCount}_growId=0;grow(e){let t=++this._growId,n=this.count>=this._maxInstanceCount?Math.ceil(this._maxInstanceCount*2):this._maxInstanceCount,r=this.tryEstimateVertexCountSize(n,[e]),i=1.25,a=Math.max(this._maxVertexCount,Math.ceil(r.vertexCount*i)),o=Math.max(this._maxIndexCount,Math.ceil(r.indexCount*i));if(z){let t=Ya(e);console.warn(`[Instancing] Growing Buffer\nMesh: \"${this.name}${e.name?.length?`/`+e.name:``}\" (${t.vertexCount.toLocaleString()} vertices, ${t.indexCount.toLocaleString()} indices)\nMax count ${this._maxInstanceCount.toLocaleString()} → ${n.toLocaleString()}\nMax vertex count ${this._maxVertexCount.toLocaleString()} -> ${a.toLocaleString()}\nMax index count ${this._maxIndexCount.toLocaleString()} -> ${o.toLocaleString()}`),this._debugMaterial=Xa()}else T()&&console.debug(`[Instancing] Growing Buffer\nMesh: \"${this.name}${e.name?.length?`/`+e.name:``}\"\nMax count ${this._maxInstanceCount} → ${n}\nMax vertex count ${this._maxVertexCount.toLocaleString()} -> ${a.toLocaleString()}\nMax index count ${this._maxIndexCount.toLocaleString()} -> ${o.toLocaleString()}`);this._maxVertexCount=a,this._maxIndexCount=o;let s=new ke(n,this._maxVertexCount,this._maxIndexCount,this._debugMaterial??this.material);s.name=this.getBatchedMeshName(),s.layers=this._batchedMesh.layers,s.castShadow=this._batchedMesh.castShadow,s.receiveShadow=this._batchedMesh.receiveShadow,s.visible=this._batchedMesh.visible,s[_t]=this._batchedMesh[_t],s.matrixAutoUpdate=this._batchedMesh.matrixAutoUpdate,s.matrixWorldNeedsUpdate=this._batchedMesh.matrixWorldNeedsUpdate,s.matrixAutoUpdate=this._batchedMesh.matrixAutoUpdate,s.matrixWorld.copy(this._batchedMesh.matrixWorld),s.matrix.copy(this._batchedMesh.matrix),this._batchedMesh.dispose(),this._batchedMesh.removeFromParent(),this._geometryIds=new WeakMap,this._batchedMesh=s,this._maxInstanceCount=n;let c=[...this._handles];this._handles=[];for(let e of c){if(t!==this._growId){z&&console.warn(`[Instancing] Aborting grow since another grow happened in the meantime`);return}e&&e.__instanceIndex>=0&&(this.addGeometry(e),this._handles[e.__instanceIndex]=e)}this._context.scene.add(s)}tryEstimateVertexCountSize(e,t,n=1){let r=new Map;for(let e of this._handles)if(e&&e.__instanceIndex>=0&&e.object.geometry){if(r.has(e.object.geometry)){let t=r.get(e.object.geometry);t.count+=1}else{let t={count:1,...Ya(e.object.geometry)};r.set(e.object.geometry,t)}if(t&&t?.length>0){let n=t.indexOf(e.object.geometry);n!==-1&&t.splice(n,1)}}let i=0,a=0,o=0;for(let[e,t]of r)o+=1,i+=t.vertexCount,a+=t.indexCount;let s=Math.ceil(i/Math.max(1,o))*o,c=Math.ceil(a/Math.max(1,o))*o;if(t)for(let e of t){let t=Ya(e);t!=null&&(s+=t.vertexCount*n,c+=t.indexCount*n)}return z&&console.log(`[Instancing] Estimated size for new buffer ${this.name}\nGeometries: ${o} (New: ${t?.length||0})\nInstances: ${e}\nEstimated Vertices: ${s.toLocaleString()}\nEstimated Indices: ${c.toLocaleString()}`),{vertexCount:s,indexCount:c}}addGeometry(e){let t=e.object.geometry;if(!t)return;let n=this._geometryIds.get(t);n==null?(z&&console.warn(`[Instancing] > ADD NEW GEOMETRY \"${e.name} (${t.name}; ${t.uuid})\"\nCurrent Instances: ${this._currentInstanceCount}\nMax Vertices: ${e.maxVertexCount.toLocaleString()}\nMax Indices: ${e.maxIndexCount.toLocaleString()}\nMax Triangles: ${(e.maxIndexCount/3).toLocaleString()}`),n=this._batchedMesh.addGeometry(t,e.maxVertexCount,e.maxIndexCount),this._geometryIds.set(t,n),this._currentVertexCount+=e.maxVertexCount,this._currentIndexCount+=e.maxIndexCount):z===`verbose`&&console.log(`[Instancing] > ADD INSTANCE \"${e.name}\"\nGEOMETRY_ID=${n}\n${this._currentInstanceCount} instances`);let r=this._batchedMesh.addInstance(n);e.__geometryIndex=n,e.__instanceIndex=r,e.__reservedVertexRange=e.maxVertexCount,e.__reservedIndexRange=e.maxIndexCount,this._batchedMesh.setMatrixAt(r,e.object.matrixWorld),z&&console.debug(`[Instancing] > ADDED INSTANCE \"${e.name}\"\nGEOMETRY_ID=${n}\n${this._currentInstanceCount} instances\nIndex: ${e.__instanceIndex}\nVertices: ${this._currentVertexCount.toLocaleString()}/${this._maxVertexCount.toLocaleString()},\nIndices: ${this._currentIndexCount.toLocaleString()}/${this._maxIndexCount.toLocaleString()}`)}removeGeometry(e,t){if(e.__instanceIndex<0){console.warn(`Cannot remove geometry, instance index is invalid`,e.name);return}z&&console.debug(`[Instancing] < REMOVE INSTANCE \"${e.name}\" at [${e.__instanceIndex}]\nGEOMETRY_ID=${e.__geometryIndex}\n${this._currentInstanceCount} instances\nIndex: ${e.__instanceIndex}`),this._batchedMesh.deleteInstance(e.__instanceIndex)}};function Ya(e){if(!e)return T()&&console.error(`Cannot get mesh information from null geometry`),{vertexCount:0,indexCount:0};let t=e.attributes?.position?.count||0,n=e.index?e.index.count:0,r=P.getMeshLODExtension(e);if(r){let e=r.lods[0],i=e.vertexCount,a=e.indexCount,o=Math.min(200,Math.ceil(i*.05));i+=o,a+=20,t=Math.max(t,i),n=Math.max(n,a)}return t=Math.ceil(t),n=Math.ceil(n),{vertexCount:t,indexCount:n}}function Xa(){let e=new Te({color:new n(Math.random(),Math.random(),Math.random())});return e.emissive=e.color,e.emissiveIntensity=.3,D(`wireframe`)&&(e.wireframe=!0),e}var Za=D(`debuglightmaps`),Qa=Symbol(`lightmapKey`),$a=class{get lightmap(){return this.lightmapTexture}set lightmap(e){e!==this.lightmapTexture&&(this.lightmapTexture=e,this.applyLightmap(),this.updatePropertyBlockTexture(),this.lightmapTexture&&P.assignTextureLOD(this.lightmapTexture,0).then(e=>{e?.isTexture&&(this.lightmapTexture=e,this.updatePropertyBlockTexture())}))}lightmapIndex=-1;lightmapScaleOffset=new C(1,1,0,0);renderer;_isApplied=!1;get context(){return this.renderer.context}get gameObject(){return this.renderer.gameObject}lightmapTexture=null;constructor(e){this.renderer=e}init(e,t,n){console.assert(this.gameObject!==void 0&&this.gameObject!==null,`Missing gameobject`,this),this.lightmapIndex=e,!(this.lightmapIndex<0)&&(this.lightmapScaleOffset=t,this.lightmapTexture=n,P.assignTextureLOD(n,0).then(e=>{e?.isTexture&&(this.lightmapTexture=e,this.updatePropertyBlockTexture())}),Za==`show`?(console.log(`Lightmap:`,this.gameObject.name,e,`
|
||
ScaleOffset:`,t,`
|
||
Texture:`,n),this.setLightmapDebugMaterial()):Za&&console.log(`Use debuglightmaps=show to render lightmaps only in the scene.`),this.applyLightmap())}updateLightmapUniforms(e){}applyLightmap(){if(this._isApplied)return;if(this.gameObject.type===`Object3D`){Za&&console.warn(`Can not add lightmap. Is this object missing a renderer?`,this.gameObject.name);return}let e=this.gameObject;if(this.ensureLightmapUvs(e),this.lightmapIndex>=0&&this.lightmapTexture){this.lightmapTexture.channel=1;let e=this.lightmapScaleOffset;for(let t=0;t<this.renderer.sharedMaterials.length;t++){let n=this.renderer.sharedMaterials[t];n&&n.lightMap!==void 0&&(Za&&console.log(`Setting lightmap on material`,n.name,`for renderer`,this.renderer.name),Hi.get(this.gameObject).setOverride(`lightMap`,this.lightmapTexture,{offset:new Ee(e.z,1-e.y-e.w),repeat:new Ee(e.x,e.y)}),n[Qa]=!0)}this._isApplied=!0}}updatePropertyBlockTexture(){if(!this._isApplied||!this.lightmapTexture)return;this.lightmapTexture.channel=1;let e=this.lightmapScaleOffset;Hi.get(this.gameObject).setOverride(`lightMap`,this.lightmapTexture,{offset:new Ee(e.z,1-e.y-e.w),repeat:new Ee(e.x,e.y)})}onUnset(){for(let e=0;e<this.renderer.sharedMaterials.length;e++){let t=this.renderer.sharedMaterials[e];t&&delete t[Qa]}let e=Hi.get(this.gameObject);e&&e.removeOveride(`lightMap`)}ensureLightmapUvs(e){if(e instanceof x)e.geometry.getAttribute(`uv1`)||e.geometry.setAttribute(`uv1`,e.geometry.getAttribute(`uv`));else if(e instanceof ve)for(let t of e.children)this.ensureLightmapUvs(t)}setLightmapDebugMaterial(){let e=this.lightmapScaleOffset;this.gameObject.material=new Re({vertexShader:`
|
||
varying vec2 vUv1;
|
||
void main()
|
||
{
|
||
vUv1 = uv1;
|
||
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
||
}
|
||
`,fragmentShader:`
|
||
uniform sampler2D lightMap;
|
||
uniform float lightMapIntensity;
|
||
varying vec2 vUv1;
|
||
|
||
// took from threejs 05fc79cd52b79e8c3e8dec1e7dca72c5c39983a4
|
||
vec4 conv_sRGBToLinear( in vec4 value ) {
|
||
return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a );
|
||
}
|
||
|
||
void main() {
|
||
vec2 lUv = vUv1.xy * vec2(${e.x.toFixed(6)}, ${e.y.toFixed(6)}) + vec2(${e.z.toFixed(6)}, ${(1-e.y-e.w).toFixed(6)});
|
||
|
||
vec4 lightMapTexel = texture2D( lightMap, lUv);
|
||
gl_FragColor = lightMapTexel;
|
||
gl_FragColor.a = 1.;
|
||
}
|
||
`,defines:{USE_LIGHTMAP:``}})}},eo=function(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},to=D(`debugrenderer`),no=D(`debugskinnedmesh`),ro=D(`noinstancing`),io=D(`wireframe`),ao;(function(e){e[e.Off=0]=`Off`,e[e.BlendProbes=1]=`BlendProbes`,e[e.BlendProbesAndSkybox=2]=`BlendProbesAndSkybox`,e[e.Simple=3]=`Simple`})(ao||={});var oo=class{path=null;asset=null;default},so;(function(e){e[e.Both=0]=`Both`,e[e.Back=1]=`Back`,e[e.Front=2]=`Front`})(so||={});var co=class{_renderer;_targets=[];_indexMapMaxIndex;_indexMap;_changed=!1;get changed(){return this._changed}set changed(e){e===!0&&to&&console.warn(`SharedMaterials have changed: `+this._renderer.name),this._changed=e}is(e){return this._renderer===e}constructor(e,t){this._renderer=e;let n=this.setMaterial.bind(this),r=this.getMaterial.bind(this),i=e.gameObject;if(this._targets=[],i)switch(i.type){case`Group`:this._targets=[...i.children];break;case`SkinnedMesh`:case`Mesh`:this._targets.push(i);break}let a=!1,o,s=0;for(let e=0;e<this._targets.length;e++){let n=this._targets[e];if(!n)continue;let r=n.material;if(r){r.shadowSide=r.side;for(let n=0;n<t.length;n++){let i=t[n];if(!i){a=!0;continue}if(r.name===i.name){o===void 0&&(o=new Map),o.set(n,e),s=Math.max(s,n);break}}}}if(a){this._indexMapMaxIndex=s,this._indexMap=o;let t=`Renderer ${e.name} was initialized with missing materials - this may lead to unexpected behaviour when trying to access sharedMaterials by index.`;console.warn(t),ft()&&kn(`Found renderer with missing materials: please check the console for details.`)}return new Proxy(this,{get(e,t){if(typeof t==`string`){let e=parseInt(t);if(!isNaN(e))return r(e)}return e[t]},set(e,t,r){return typeof t==`string`&&n(r,Number.parseInt(t)),Reflect.set(e,t,r)?(r instanceof Ne&&(e.changed=!0),!0):!1}})}get length(){return this._indexMapMaxIndex===void 0?this._targets.length:this._indexMapMaxIndex+1}*[Symbol.iterator](){for(let e=0;e<this.length;e++)yield this.getMaterial(e)}resolveIndex(e){let t=this._indexMap;return t&&t.has(e)?t.get(e):e}setMaterial(e,t){if(t=this.resolveIndex(t),t<0||t>=this._targets.length)return;let n=this._targets[t];!n||n.material===void 0||(n.material=e,this.changed=!0)}getMaterial(e){if(e=this.resolveIndex(e),e<0)return null;let t=this._targets;if(e>=t.length)return null;let n=t[e];return n?n.material:null}},B=class e extends N{static setInstanced(t,n){let r=Lt(t,e);return r.setInstancingEnabled(n),r}static isInstanced(t){let n=Gn(t,e);return n?n.isInstancingActive:gt.isUsingInstancing(t)}static setVisible(e,t){wi(e,t)}receiveShadows=!1;shadowCastingMode=fo.Off;lightmapIndex=-1;lightmapScaleOffset=new C(1,1,0,0);enableInstancing=void 0;renderOrder=void 0;allowOcclusionWhenDynamic=!0;probeAnchor;reflectionProbeUsage=ao.Off;_lightmaps;get sharedMesh(){if(this.gameObject.type===`Mesh`||this.gameObject.type===`SkinnesMesh`)return this.gameObject;if(this.gameObject.type===`Group`)return this.gameObject.children[0]}_sharedMeshes=[];get sharedMeshes(){if(this.destroyed||!this.gameObject)return this._sharedMeshes;if(this._sharedMeshes.length=0,this.gameObject.type===`Group`)for(let e of this.gameObject.children)(e.type===`Mesh`||e.type===`SkinnedMesh`)&&this._sharedMeshes.push(e);else (this.gameObject.type===`Mesh`||this.gameObject.type===`SkinnedMesh`)&&this._sharedMeshes.push(this.gameObject);return this._sharedMeshes}get sharedMaterial(){return this.sharedMaterials?.[0]}set sharedMaterial(e){this.sharedMaterials[0]!==e&&(this.sharedMaterials[0]=e,this.applyLightmapping())}get material(){return this.sharedMaterials?.[0]}set material(e){this.sharedMaterial=e}_sharedMaterials;_originalMaterials;_probeAnchorLastFrame;set sharedMaterials(e){if(!this._originalMaterials)this._originalMaterials=e;else if(e){let t=!1;for(let n=0;n<this._sharedMaterials.length;n++){let r=n<e.length?e[n]:null;r&&r instanceof Ne?this.sharedMaterials[n]=r:t||(t=!0,console.warn(`Can not assign null as material: `+this.name,r))}}}get sharedMaterials(){if(this._originalMaterials===void 0)if(this.__didAwake)this._originalMaterials=[];else return null;return(!this._sharedMaterials||!this._sharedMaterials.is(this))&&(this._originalMaterials||=[],this._sharedMaterials=new co(this,this._originalMaterials)),this._sharedMaterials}static get shouldSuppressInstancing(){return ro}_lightmapTextureOverride=void 0;get lightmap(){return this._lightmaps?.length?this._lightmaps[0].lightmap:null}set lightmap(e){if(this._lightmapTextureOverride=e,e===void 0&&(e=this.context.lightmaps.tryGetLightmap(this.sourceId,this.lightmapIndex)),this._lightmaps?.length)for(let t of this._lightmaps)t.lightmap=e}get hasLightmap(){return this.lightmap!=null}allowProgressiveLoading=!0;_firstFrame=-1;registering(){this.enabled||this.setVisibility(!1)}awake(){if(this._firstFrame=this.context.time.frame,to&&console.log(`Renderer `,this.name,this),this.clearInstancingState(),this.probeAnchor&&to&&this.probeAnchor.add(new _e(.2)),this._reflectionProbe=null,this.isMultiMaterialObject(this.gameObject)){for(let e of this.gameObject.children)this.context.addBeforeRenderListener(e,this.onBeforeRenderThree),e.layers.mask=this.gameObject.layers.mask;if(this.renderOrder!==void 0){let t=0;for(let n=0;n<this.gameObject.children.length;n++){let r=this.gameObject.children[n];if(!(!this.isMeshOrSkinnedMesh(r)||k.getComponent(r,e))){if(this.renderOrder.length<=t){console.warn(`Incorrect renderOrder element count`,this,this.renderOrder.length+` but expected `+this.gameObject.children.length,`Index: `+t,`ChildElement:`,r);continue}r.renderOrder=this.renderOrder[t],t+=1}}}}else this.isMeshOrSkinnedMesh(this.gameObject)?(this.context.addBeforeRenderListener(this.gameObject,this.onBeforeRenderThree),this.renderOrder!==void 0&&this.renderOrder.length>0&&(this.gameObject.renderOrder=this.renderOrder[0])):this.context.addBeforeRenderListener(this.gameObject,this.onBeforeRenderThree);if(this._lightmaps=void 0,this.applyLightmapping(),io)for(let e=0;e<this.sharedMaterials.length;e++){let t=this.sharedMaterials[e];t&&(t.wireframe=!0)}}applyLightmapping(){if(this.lightmapIndex>=0&&!this._lightmaps){let e=this._lightmapTextureOverride===void 0?this.context.lightmaps.tryGetLightmap(this.sourceId,this.lightmapIndex):this._lightmapTextureOverride;if(e){this._lightmaps||=[];let t=new $a(this);t.init(this.lightmapIndex,this.lightmapScaleOffset,e),this._lightmaps.push(t)}else to&&console.warn(`[Renderer] No lightmaps found ${this.name} (${this.sourceId}, ${this.lightmapIndex})`)}}_isInstancingEnabled=!1;_handles=void 0;get isInstancingActive(){return this._handles!=null&&this._handles.length>0&&this._isInstancingEnabled}get instances(){if(!this._handles||this._handles.length<=0)return null;if(this._handlesTempArray.length=0,this._handles)for(let e of this._handles)this._handlesTempArray.push(e);return this._handlesTempArray}_handlesTempArray=[];setInstancingEnabled(e){if(this._isInstancingEnabled===e)return e&&(this._handles===void 0||this._handles!=null&&this._handles.length>0);if(this._isInstancingEnabled=e,e){if(this.enableInstancing===void 0&&(this.enableInstancing=!0),this._handles===void 0){if(this._handles=Ka.instance.setup(this,this.gameObject,this.context,null,{rend:this,foundMeshes:0,useMatrixWorldAutoUpdate:this.useInstanceMatrixWorldAutoUpdate()}),this._handles)return k.markAsInstancedRendered(this.gameObject,!0),!0}else if(this._handles!==null){for(let e of this._handles)e.updateInstanceMatrix(!0),e.add();return k.markAsInstancedRendered(this.gameObject,!0),!0}}else{if(this._handles)for(let e of this._handles)e.remove(this.destroyed);return!0}return!1}clearInstancingState(){this._isInstancingEnabled=!1,this._handles=void 0}useInstanceMatrixWorldAutoUpdate(){return!0}start(){if(this.enableInstancing&&!ro&&(this.setInstancingEnabled(!0),gt.markDirty(this.gameObject)),this.gameObject.frustumCulled=this.allowOcclusionWhenDynamic,this.isMultiMaterialObject(this.gameObject))for(let e=0;e<this.gameObject.children.length;e++){let t=this.gameObject.children[e];t.frustumCulled=this.allowOcclusionWhenDynamic}}onEnable(){this.sharedMeshes,this.setVisibility(!0),this._isInstancingEnabled||this.enableInstancing==1||Array.isArray(this.enableInstancing)&&this.enableInstancing.some(e=>e)?this.__internalDidAwakeAndStart&&this.setInstancingEnabled(!0):this.enabled&&this.applyStencil(),this.updateReflectionProbe(),oa.onEnabled.addEventListener(this.onReflectionProbeEnabled),oa.onDisabled.addEventListener(this.onReflectionProbeDisabled)}onDisable(){this.setVisibility(!1),oa.onEnabled.removeEventListener(this.onReflectionProbeEnabled),oa.onDisabled.removeEventListener(this.onReflectionProbeDisabled),this._handles&&this._handles.length>0&&this.setInstancingEnabled(!1)}onDestroy(){if(this._handles=null,this.isMultiMaterialObject(this.gameObject))for(let e of this.gameObject.children)this.context.removeBeforeRenderListener(e,this.onBeforeRenderThree);else this.context.removeBeforeRenderListener(this.gameObject,this.onBeforeRenderThree)}onReflectionProbeEnabled=()=>{this.updateReflectionProbe()};onReflectionProbeDisabled=e=>{this._reflectionProbe===e&&(this._reflectionProbe.unapply(this.gameObject),this._reflectionProbe=null)};onBeforeRender(){if(this.gameObject){if((this._probeAnchorLastFrame!==this.probeAnchor||this._reflectionProbe?.activeAndEnabled===!1)&&(this._reflectionProbe?.unapply(this.gameObject),this.updateReflectionProbe()),to==this.name&&this.gameObject instanceof x){this.gameObject.geometry.computeBoundingSphere();let e=wn(this.gameObject.geometry.boundingSphere.center).applyMatrix4(this.gameObject.matrixWorld);Ln.DrawWireSphere(e,this.gameObject.geometry.boundingSphere.radius,56831)}if(this.isMultiMaterialObject(this.gameObject)&&this.gameObject.children?.length>0)for(let e of this.gameObject.children)this.applySettings(e);else this.applySettings(this.gameObject);if(this.sharedMaterials?.changed&&(this.sharedMaterials.changed=!1,this.applyLightmapping()),this._handles?.length&&this.gameObject[Kt]===!0){this.gameObject[Kt]=!1;for(let e=this._handles.length-1;e>=0;e--)this._handles[e].updateInstanceMatrix();this.gameObject.matrixWorldNeedsUpdate=!1}if(this._handles&&this._handles.length<=0&&k.markAsInstancedRendered(this.gameObject,!1),this._isInstancingEnabled&&this._handles)for(let e=0;e<this._handles.length;e++){let t=this._handles[e];wi(t.object,!1)}if(this.reflectionProbeUsage!==ao.Off&&this._reflectionProbe?this._reflectionProbe.apply(this.gameObject):this.reflectionProbeUsage===ao.Off&&this._reflectionProbe&&this._reflectionProbe.unapply(this.gameObject),this._sharedMaterials)for(let e of this._sharedMaterials)e&&`envMap`in e&&`envMapIntensity`in e&&!oa.isUsingReflectionProbe(e)&&(e.envMap=this.context.scene.environment,e.envMapRotation=this.context.scene.environmentRotation);else to&&console.warn(`[Renderer] sharedMaterials not initialized yet: `+this.name)}}onBeforeRenderThree=(e,t,n,r,i,a)=>{if(i.envMapIntensity!==void 0){let e=this.hasLightmap?Math.PI:1,t=this.context.scene.environmentIntensity;i.envMapIntensity=Math.max(0,t*this.context.sceneLighting.environmentIntensity/e)}if(this._lightmaps)for(let e of this._lightmaps)e.updateLightmapUniforms(i),e.applyLightmap()};onAfterRender(){if(this._isInstancingEnabled&&this._handles)for(let e=0;e<this._handles.length;e++){let t=this._handles[e];wi(t.object,!0)}this._reflectionProbe?.activeAndEnabled===!1&&this._reflectionProbe.unapply(this.gameObject),this.static&&this.gameObject.matrixAutoUpdate&&this.context.time.frame-this._firstFrame>=10&&(this.gameObject.matrixAutoUpdate=!1)}applyStencil(){Fi.applyStencil(this)}applySettings(e){e.receiveShadow=this.receiveShadows,this.shadowCastingMode==fo.On?e.castShadow=!0:e.castShadow=!1}_reflectionProbe=null;updateReflectionProbe(){this._reflectionProbe=null,this.reflectionProbeUsage!==ao.Off&&(this.startCoroutine(this._updateReflectionProbe(),Wn.LateUpdate),this._probeAnchorLastFrame=this.probeAnchor)}*_updateReflectionProbe(){let e=this.probeAnchor||this.gameObject,t=!!this.probeAnchor;this._reflectionProbe=oa.get(e,this.context,t,this.probeAnchor)}setVisibility(e){if(!this.isMultiMaterialObject(this.gameObject))wi(this.gameObject,e);else for(let t of this.gameObject.children)this.isMeshOrSkinnedMesh(t)&&wi(t,e)}isMultiMaterialObject(e){return e.type===`Group`}isMeshOrSkinnedMesh(e){return e.type===`Mesh`||e.type===`SkinnedMesh`}};eo([E()],B.prototype,`receiveShadows`,void 0),eo([E()],B.prototype,`shadowCastingMode`,void 0),eo([E()],B.prototype,`lightmapIndex`,void 0),eo([E(C)],B.prototype,`lightmapScaleOffset`,void 0),eo([E()],B.prototype,`enableInstancing`,void 0),eo([E()],B.prototype,`renderOrder`,void 0),eo([E()],B.prototype,`allowOcclusionWhenDynamic`,void 0),eo([E(S)],B.prototype,`probeAnchor`,void 0),eo([E()],B.prototype,`reflectionProbeUsage`,void 0);var lo=class extends B{},uo=class extends lo{_needUpdateBoundingSphere=!1;awake(){super.awake(),no&&console.log(`SkinnedMeshRenderer for "`+this.name+`"`,this),this.allowOcclusionWhenDynamic=!1;for(let e of this.sharedMeshes)e.parent?.updateWorldMatrix(!1,!0),this.markBoundsDirty()}onAfterRender(){if(super.onAfterRender(),this._needUpdateBoundingSphere){for(let e of this.sharedMeshes)if(e instanceof Ie){this._needUpdateBoundingSphere=!1;try{let t=e.geometry,n=ar(e);n&&(e.geometry=n),e.computeBoundingSphere(),e.geometry=t}catch(t){console.error(`Error updating bounding sphere for ${e.name}`,t)}}}if(no){for(let e of this.sharedMeshes)if(e instanceof Ie&&e.boundingSphere){let t=wn(e.boundingSphere.center).applyMatrix4(e.matrixWorld);Ln.DrawWireSphere(t,e.boundingSphere.radius,`red`)}}}markBoundsDirty(){this._needUpdateBoundingSphere=!0}},fo;(function(e){e[e.Off=0]=`Off`,e[e.On=1]=`On`,e[e.TwoSided=2]=`TwoSided`,e[e.ShadowsOnly=3]=`ShadowsOnly`})(fo||={});function po(){`OffscreenCanvas`in globalThis||(globalThis.OffscreenCanvas=class{canvas;constructor(e,t){return this.canvas=document.createElement(`canvas`),this.canvas.width=e,this.canvas.height=t,this.canvas.convertToBlob=(e,t)=>new Promise(n=>{this.canvas.toBlob(n,e,t)}),this.canvas}})}var mo=D(`debugprogress`);function ho(e){e||=new Date;let t=e.getMonth()+1,n=e.getDate(),r=e.getHours(),i=e.getMinutes(),a=e.getSeconds(),o=(t<10?`0`:``)+t,s=(n<10?`0`:``)+n,c=(r<10?`0`:``)+r,l=(i<10?`0`:``)+i,u=(a<10?`0`:``)+a;return e.getFullYear()+o+s+`-`+c+l+u}var V=class{static start(e,t){typeof t==`string`&&(t={parentScope:t});let n=new _o(e,t);go.set(e,n)}static report(e,t){let n=go.get(e);if(!n){console.warn(`Reporting progress for non-existing scope`,e);return}typeof t==`string`&&(t={message:t,autoStep:!0}),n.report(t)}static end(e){let t=go.get(e);t&&(t.end(),go.delete(e))}},go=new Map,_o=class{scopeLabel;parentScope;childScopes=[];parentDepth=0;lastStep=0;lastAutoStepWeight=1;lastTotalSteps=0;onProgress;showLogs=!1;selfProgress=0;totalProgress=0;selfReports=0;totalReports=0;constructor(e,t){this.parentScope=t?.parentScope?go.get(t.parentScope):void 0,this.parentScope&&(this.parentScope.childScopes.push(this),this.parentDepth=this.parentScope.parentDepth+1),this.scopeLabel=` `.repeat(this.parentDepth*2)+e,this.showLogs=t?.logTimings??!!mo,this.showLogs&&console.time(this.scopeLabel),this.onProgress=t?.onProgress}report(e,t=!1){if(e){if(e.totalSteps!==void 0&&(this.lastTotalSteps=e.totalSteps),e.currentStep!==void 0&&(this.lastStep=e.currentStep),e.autoStep!==void 0){if(e.currentStep===void 0){this.lastStep===void 0&&(this.lastStep=0);let t=typeof e.autoStep==`number`?e.autoStep:1;this.lastStep+=this.lastAutoStepWeight,this.lastAutoStepWeight=t,e.currentStep=this.lastStep}e.totalSteps=this.lastTotalSteps}e.progress===void 0?e.currentStep!==void 0&&e.totalSteps!==void 0&&(this.selfProgress=e.currentStep/e.totalSteps):this.selfProgress=e.progress}if(this.childScopes.length>0){let e=0,t=0;for(let n of this.childScopes)e+=n.selfProgress,t+=1;t>0&&(e/=t);let n=this.lastAutoStepWeight/(this.lastTotalSteps??1);this.totalProgress=this.selfProgress+e*n}else this.totalProgress=this.selfProgress;this.selfProgress=Math.min(1,this.selfProgress),this.totalProgress=Math.min(1,this.totalProgress);let n=(this.totalProgress*100).toFixed(3)+`%`;this.childScopes.length>0&&(n+=` (`+(this.selfProgress*100).toFixed(3)+`% self)`),e?.message&&(n=e.message+` – `+n),this.lastStep!==void 0&&this.lastTotalSteps!==void 0&&(n=`Step `+(this.lastStep+(this.lastAutoStepWeight==1?``:`–`+(this.lastStep+this.lastAutoStepWeight))+`/`+this.lastTotalSteps)+` `+n),t||this.selfReports++,this.totalReports++,this.showLogs&&console.timeLog(this.scopeLabel,n),this.onProgress&&this.onProgress(this.totalProgress),this.parentScope&&this.parentScope.report(void 0,!0)}end(){this.report({progress:1,autoStep:!0},!0),this.showLogs&&(console.timeLog(this.scopeLabel,`Total reports: `+this.totalReports,`Self reports: `+this.selfReports),console.timeEnd(this.scopeLabel));let e=!1;for(let t of this.childScopes)if(!(t.selfProgress>=1)){e=!0;break}e&&console.warn(`Progress end with child scopes that are still running`,this),this.onProgress=void 0}},H=`</StageRoot/Materials`;function vo(e,t,n){let r=new Map,i=e=>{let t=e.type___needle,n=r.get(t)||new Map;if(r.set(t,n),!n.has(e)){let r=`${t}${n.size?`_${n.size}`:``}`;n.set(e,r)}return n.get(e)},a=e.colorNode?yo(e.colorNode):[],o=e.colorNode?`color3f inputs:diffuseColor.connect = ${H}/${t}/${i(a.values().next().value)}.outputs:out>`:``,s=e.roughnessNode?yo(e.roughnessNode):[],c=e.roughnessNode?`float inputs:roughness.connect = ${H}/${t}/${i(s.values().next().value)}.outputs:out>`:``,l=e.normalNode?yo(e.normalNode):[],u=e.normalNode?`float3 inputs:normal.connect = ${H}/${t}/${i(l.values().next().value)}.outputs:out>`:``,d=e.metalnessNode?yo(e.metalnessNode):[],f=e.metalnessNode?`float inputs:metallic.connect = ${H}/${t}/${i(d.values().next().value)}.outputs:out>`:``,p=So(new Set([...a,...s,...l,...d]),t,n,i);return console.debug(p),`
|
||
|
||
def Material "${t}" ${e.name?`(
|
||
displayName = "${e.name}"
|
||
)`:``}
|
||
{
|
||
token outputs:mtlx:surface.connect = ${H}/${t}/N_mtlxsurface.outputs:surface>
|
||
|
||
def Shader "N_mtlxsurface"
|
||
{
|
||
uniform token info:id = "ND_UsdPreviewSurface_surfaceshader"
|
||
${o}
|
||
${c}
|
||
${u}
|
||
${f}
|
||
token outputs:surface
|
||
}
|
||
|
||
${p}
|
||
|
||
}`}function yo(e){let t=e=>{if(e.nodeType)return e.nodeType;switch(e.type){case`TimerNode`:return`float`;case`TextureNode`:return;case`ConvertNode`:return e.convertTo;default:return}},n=e=>{let n=new Set,r=e=>{if(!(!e.isNode||n.has(e))){e.nodeType___needle||=t(e),e.shaderNode?(e.type___needle=`ShaderCallNodeInternal`,e.shaderNodeLayoutName___needle=e.shaderNode.layout.name.slice(3)):e.type___needle=e.type,n.add(e);for(let t in e)e[t]?.isNode&&(r(e[t]),e.nodeType___needle||=e[t].nodeType___needle),Array.isArray(e[t])&&e[t].forEach(t=>{t.isNode&&(r(t),e.nodeType___needle||=t.nodeType___needle)})}};return r(e),n},r=e=>{if(e.type===`ConvertNode`){if(e.convertTo===e.node.nodeType___needle)return!0;if(e.node.type===`ConstNode`){if(e.convertTo===`vec4`&&e.node.value.isVector4||e.convertTo===`vec3`&&e.node.value.isVector3||e.convertTo===`vec2`&&e.node.value.isVector2||e.convertTo===`color`&&e.node.value.isColor||e.convertTo===`float`&&typeof e.node.value==`number`)return!0}else if(e.node.type==`SplitNode`&&e.convertTo==`float`&&e.node.components.length===1)return!0}return!1},i=e=>{for(;a(e);)e=!e.node&&e.shaderNode?e.inputNodes[0]:e.node??e.aNode??e.bNode??e.cNode;return e},a=e=>!e||r(e)||[`UniformNode`,`UniformGroupNode`,`ShaderNodeInternal`].includes(e.type___needle)||e.type___needle===void 0,o=(e,t)=>{for(let n of t)for(let t in n)if(n[t]?.isNode&&n[t]===e||Array.isArray(n[t])&&n[t].find(t=>t.isNode&&t===e))return{parent:n,label:t};return null},s=(e,t)=>{if(e.shaderNode)e.inputNodes[0]=i(e.inputNodes[0]);else if(Array.isArray(e.nodes))for(let t=0;t<e.nodes.length;t++)e.nodes[t]&&a(e.nodes[t])&&(e.nodes[t]=i(e.nodes[t]));else t.forEach(t=>{e[t]&&a(e[t])&&(e[t]=i(e[t]))})},c=e=>{e.type===`MathNode`&&e.method===`mix`&&(e.cNode.nodeType___needle=`float`,e.cNode.type===`ConvertNode`&&(e.cNode.convertTo=`float`))},l=(e,t)=>{t.label===`cNode`&&t.parent.type===`MathNode`&&t.parent.method===`mix`||(t.parent.type===`JoinNode`?e.nodeType___needle=`float`:e.nodeType___needle=t.parent.nodeType___needle)},u=e=>e?.type===`ConvertNode`&&e.nodeType___needle===`color`&&e.node.nodeType___needle===`vec4`,d=(e,t)=>{e.convertTo=`vec3`,e.nodeType___needle=`vec3`;let n={type:`ConvertNode`,convertTo:`color`,node:e,isNode:!0,nodeType___needle:`color`,type___needle:`ConvertNode`},r=o(e,t);return r?.parent&&(r.parent[r.label]=n),n},f=e=>e?.type===`ConvertNode`&&e.node.type===`TextureNode`&&e.nodeType___needle!==e.node.nodeType___needle;return(e=>{let t=new Set;for(let n of e)if(!a(n)){if(c(n),n.type==`SplitNode`){let t=o(n,e);if(n.components.length===1)n.nodeType___needle=`float`;else if(t)n.nodeType___needle=t.parent.nodeType___needle;else throw Error(`SplitNode without parent found, this should not happen`)}if(s(n,[`node`,`aNode`,`bNode`,`cNode`]),n.type==`ConstNode`&&n.nodeType==null&&l(n,o(n,e)),u(n)&&t.add(d(n,e)),f(n)){n.node.nodeType___needle=n.convertTo;let t=o(n,e);t?.parent&&(t.parent[t.label]=n.node),n=n.node}t.add(n)}return t})(n(e))}function bo(e,t){switch(t){case`float4`:return e.isVector4?`(${e.x}, ${e.y}, ${e.z}, ${e.w})`:`(${e}, ${e}, ${e}, ${e})`;case`float3`:return e.isVector3?`(${e.x}, ${e.y}, ${e.z})`:`(${e}, ${e}, ${e})`;case`float2`:return e.isVector2?`(${e.x}, ${e.y})`:`(${e}, ${e})`;case`color3f`:return e.isColor?`(${e.r}, ${e.g}, ${e.b})`:`(${e}, ${e}, ${e})`;default:return e.isVector4||e.isVector3||e.isVector2?`${e.x}`:e.isColor?`${e.r}`:`${e}`}}function xo(e,t,n,r){let i=` `,a=e=>({float:`float`,vec2:`vector2`,vec3:`vector3`,vec4:`vector4`,color:`color3`})[e]||`float`,o=e=>({float:`float`,vec2:`float2`,vec3:`float3`,vec4:`float4`,color:`color3f`})[e]||`float`,s=e.type___needle,c=e.nodeType___needle,l=a(c),u=o(c),d=``,f=[];switch(s){case`UniformGroupNode`:case`UniformNode`:return``;case`TimerNode`:d=`time_float`;break;case`ConstNode`:d=`constant_`+l,f.push(`${u} inputs:value = ${bo(e.value,u)}`);break;case`JoinNode`:d=`combine`+e.nodes.length+`_`+l;let i=1;for(let r of e.nodes)f.push(`float inputs:in${i++}.connect = ${H}/${t}/${n(r)}.outputs:out>`);break;case`ConvertNode`:d=`convert_`+a(e.node.nodeType___needle)+`_`+l,e.node&&f.push(`${o(e.node.nodeType___needle)} inputs:in.connect = ${H}/${t}/${n(e.node)}.outputs:out>`);break;case`MathNode`:d=e.method+`_`+l,e.aNode&&!e.bNode&&f.push(`${o(e.aNode.nodeType___needle)} inputs:in.connect = ${H}/${t}/${n(e.aNode)}.outputs:out>`),e.aNode&&e.bNode&&!e.cNode&&(f.push(`${o(e.aNode.nodeType___needle)} inputs:in1.connect = ${H}/${t}/${n(e.aNode)}.outputs:out>`),f.push(`${o(e.bNode.nodeType___needle)} inputs:in2.connect = ${H}/${t}/${n(e.bNode)}.outputs:out>`)),e.aNode&&e.bNode&&e.cNode&&e.method==`clamp`&&(f.push(`${o(e.aNode.nodeType___needle)} inputs:in.connect = ${H}/${t}/${n(e.aNode)}.outputs:out>`),f.push(`${o(e.bNode.nodeType___needle)} inputs:low.connect = ${H}/${t}/${n(e.bNode)}.outputs:out>`),f.push(`${o(e.cNode.nodeType___needle)} inputs:high.connect = ${H}/${t}/${n(e.cNode)}.outputs:out>`)),e.aNode&&e.bNode&&e.cNode&&e.method==`mix`&&(f.push(`${o(e.aNode.nodeType___needle)} inputs:fg.connect = ${H}/${t}/${n(e.bNode)}.outputs:out>`),f.push(`${o(e.bNode.nodeType___needle)} inputs:bg.connect = ${H}/${t}/${n(e.aNode)}.outputs:out>`),f.push(`float inputs:mix.connect = ${H}/${t}/${n(e.cNode)}.outputs:out>`));break;case`OperatorNode`:let s=``;switch(e.op){case`*`:s=`multiply`;break;case`/`:s=`divide`;break;case`+`:s=`add`;break;case`-`:s=`subtract`;break}if(d=s+`_`+l,e.aNode&&!e.bNode&&f.push(`${o(e.aNode.nodeType___needle)} inputs:in.connect = ${H}/${t}/${n(e.aNode)}.outputs:out>`),e.aNode&&e.bNode){let r=o(e.aNode.nodeType___needle),i=o(e.bNode.nodeType___needle);(r===`color3f`&&i===`float`||i===`float`&&i===`color3f`)&&(d=s+`_color3FA`),f.push(`${r} inputs:in1.connect = ${H}/${t}/${n(e.aNode)}.outputs:out>`),f.push(`${i} inputs:in2.connect = ${H}/${t}/${n(e.bNode)}.outputs:out>`)}break;case`TextureNode`:e.uvNode?(d=`tiledimage_`+l,f.push(`float2 inputs:texcoord.connect = ${H}/${t}/${n(e.uvNode)}.outputs:out>`)):d=`image_`+l;let c=e._value,p=Ts.includes(c.format),m=Co(c);f.push(`asset inputs:file = @textures/${m}.${p?`png`:`jpg`}@`),r[m]={texture:c,scale:void 0};break;case`NormalMapNode`:u=`float3`,d=`normalmap`,f.push(`${u} inputs:in.connect = ${H}/${t}/${n(e.node)}.outputs:out>`);break;case`AttributeNode`:d=`geompropvalue_`+l,f.push(`string inputs:geomprop = "st"`);break;case`ShaderCallNodeInternal`:d=e.shaderNodeLayoutName___needle+`_`+l,f.push(`${u} inputs:in.connect = ${H}/${t}/${n(e.inputNodes[0])}.outputs:out>`);break;case`SplitNode`:d=`swizzle_`+a(e.node.nodeType___needle)+`_`+l,f.push(`${o(e.node.nodeType___needle)} inputs:in.connect = ${H}/${t}/${n(e.node)}.outputs:out>`),f.push(`string inputs:channels = "${e.components}"`);break}return`
|
||
${i}def Shader "${n(e)}"
|
||
${i}{
|
||
${i}uniform token info:id = "ND_${d}"
|
||
${i}${u} outputs:out
|
||
${i}${f.length>0?f.join(`
|
||
`):``}
|
||
${i}}
|
||
`}function So(e,t,n,r){let i=``;for(let a of e)i+=xo(a,t,r,n);return i}function Co(e){return wo(e.name)+`_`+(e.source?.id??e.id)}function wo(e){return e=e.replace(/[^a-zA-Z0-9_]/g,``),e.match(/^[a-zA-Z_]/)||(e=`_`+e),e}function To(e){return e=e.replace(`"`,`\\"`),e}function Eo(e){if(e.length===0)return null;let t=e.map(e=>{let t=[];for(;e.parent;)t.unshift(e.parent),e=e.parent;return t});return t[0].findLast(e=>t.every(t=>t.includes(e)))||null}function Do(e){let t=Eo(e),n=new Set;for(let r of e){let i=r.parent;for(;i&&i!==t;)e.includes(i)||n.add(i),i=i.parent}return n}var Oo=new r,ko=new Ue,Ao=new r(1,1,1),jo=class e{static USDObject_export_id=0;uuid;name;type;extraSchemas=[];displayName;visibility;getMatrix(){if(!this.transform)return new b;let{position:e,quaternion:t,scale:n}=this.transform,r=new b;return r.compose(e||Oo,t||ko,n||Ao),r}setMatrix(e){if(!e||!(e instanceof b)){this.transform=null;return}let t=new r,n=new Ue,i=new r;e.decompose(t,n,i),this.transform={position:t,quaternion:n,scale:i}}get matrix(){return this.getMatrix()}set matrix(e){this.setMatrix(e)}transform=null;_isDynamic;get isDynamic(){return this._isDynamic}set isDynamic(e){this._isDynamic=e}geometry;material;camera;parent;skinnedMesh;children=[];animations;_eventListeners;needsTranslate=!1;needsOrient=!1;needsScale=!1;static createEmptyParent(t){let n=new e(h.generateUUID(),t.name+`_empty_`+ e.USDObject_export_id++,t.transform),r=t.parent;return r&&r.add(n),n.add(t),n.isDynamic=!0,t.transform=null,n}static createEmpty(){let t=new e(h.generateUUID(),`Empty_`+ e.USDObject_export_id++);return t.isDynamic=!0,t}constructor(e,t,n=null,r=null,i=null,a=null,o=null,s=null){this.uuid=e,this.name=wo(t),this.displayName=t,n?this.transform={position:n.position?.clone()||null,quaternion:n.quaternion?.clone()||null,scale:n.scale?.clone()||null}:this.transform=null,this.geometry=r,this.material=i,this.camera=a,this.parent=null,this.children=[],this._eventListeners={},this._isDynamic=!1,this.skinnedMesh=o,this.animations=s}is(e){return e?this.uuid===e.uuid:!1}isEmpty(){return!this.geometry}clone(){let t=new e(h.generateUUID(),this.name,this.transform,this.geometry,this.material);return t.isDynamic=this.isDynamic,t}deepClone(){let e=this.clone();for(let t of this.children)t&&e.add(t.deepClone());return e}getPath(){let e=this.parent,t=this.name;for(;e;)t=(e.parent?e.name:e.name+`/Scenes/Scene`)+`/`+t,e=e.parent;return`</`+t+`>`}add(e){e.parent&&e.parent.remove(e),e.parent=this,this.children.push(e)}remove(e){let t=this.children.indexOf(e);t>=0&&(e.parent===this&&(e.parent=null),this.children.splice(t,1))}addEventListener(e,t){this._eventListeners[e]||(this._eventListeners[e]=[]),this._eventListeners[e].push(t)}removeEventListener(e,t){if(!this._eventListeners[e])return;let n=this._eventListeners[e].indexOf(t);n>=0&&this._eventListeners[e].splice(n,1)}onSerialize(e,t){let n=this._eventListeners.serialize;n&&n.forEach(n=>n(e,t))}},Mo=class extends jo{stageLength;get isDocumentRoot(){return!0}get isDynamic(){return!1}constructor(){super(void 0,`StageRoot`,null,null,null,null),this.children=[],this.stageLength=200}add(e){e.parent=this,this.children.push(e)}remove(e){let t=this.children.indexOf(e);t>=0&&(e.parent===this&&(e.parent=null),this.children.splice(t,1))}traverse(e,t=null){if(t===null?t=this:e(t),t.children)for(let n of t.children)this.traverse(e,n)}findById(e){let t=!1;function n(r){if(!t){if(r.uuid===e)return t=!0,r;if(r.children)for(let e of r.children){if(!e)continue;let t=n(e);if(t)return t}}}return n(this)}buildHeader(e){let t=e.extensions?.find(e=>e?.extensionName===`animation`),n=e.extensions?.find(e=>e?.extensionName===`Behaviour`),r=e.extensions?.find(e=>e?.extensionName===`Physics`),i=t?.getStartTimeCode()??0,a=t?.getEndTimeCode()??0,o=``,s=t?.registeredClips;if(s)for(let e of s)o+=`\t# Animation: ${e.name}, start=${t.getStartTimeByClip(e)*60}, length=${e.duration*60}\n`;let c=o;return`#usda 1.0
|
||
(
|
||
customLayerData = {
|
||
string creator = "Needle Engine ${ut}"
|
||
dictionary Needle = {
|
||
bool animations = ${+!!t}
|
||
bool interactive = ${+!!n}
|
||
bool physics = ${+!!r}
|
||
bool quickLookCompatible = ${+!!e.quickLookCompatible}
|
||
}
|
||
}
|
||
defaultPrim = "${wo(this.name)}"
|
||
metersPerUnit = 1
|
||
upAxis = "Y"
|
||
startTimeCode = ${i}
|
||
endTimeCode = ${a}
|
||
timeCodesPerSecond = 60
|
||
framesPerSecond = 60
|
||
doc = """Generated by Needle Engine USDZ Exporter ${ut}"""
|
||
${c}
|
||
)
|
||
`}},No=`
|
||
`,Po=`</StageRoot/Materials`,Fo=class{str;indent;constructor(){this.str=``,this.indent=0}clear(){this.str=``,this.indent=0}beginBlock(e=void 0,t=`{`,n=!0){e===void 0?this.str+=this.applyIndent(t):(e=this.applyIndent(e),this.str+=e,n?(this.str+=No,this.str+=this.applyIndent(t)):this.str+=` `+t),this.str+=No,this.indent+=1}closeBlock(e=`}`){--this.indent,this.str+=this.applyIndent(e)+No}beginArray(e){e=this.applyIndent(e+` = [`),this.str+=e,this.str+=No,this.indent+=1}closeArray(){--this.indent,this.str+=this.applyIndent(`]`)+No}appendLine(e=``){e=this.applyIndent(e),this.str+=e,this.str+=No}toString(){return this.str}applyIndent(e){let t=``;for(let e=0;e<this.indent;e++)t+=` `;return t+e}},Io=class{root;exporter;extensions=[];quickLookCompatible;exportInvisible;materials;textures;files;document;output;animations;constructor(e,t,n){this.root=e||void 0,this.exporter=t,this.quickLookCompatible=n.quickLookCompatible,this.exportInvisible=n.exportInvisible,n.extensions&&(this.extensions=n.extensions),this.materials=new Map,this.textures={},this.files={},this.document=new Mo,this.output=``,this.animations=[]}makeNameSafe(e){return wo(e)}},Lo=()=>({ar:{anchoring:{type:`plane`},planeAnchoring:{alignment:`horizontal`}},quickLookCompatible:!1,extensions:[],maxTextureSize:4096,exportInvisible:!1}),Ro=class{debug;pruneUnusedNodes;sceneAnchoringOptions=Lo();extensions=[];keepObject;beforeWritingDocument;constructor(){this.debug=!1,this.pruneUnusedNodes=!0}async parse(e,t=Lo()){t=Object.assign({},t),this.sceneAnchoringOptions=t;let n=new Io(e,this,t);this.extensions=n.extensions;let r=n.files,i=`model.usda`;r[i]=null,n.materials;let a=n.textures;V.report(`export-usdz`,`Invoking onBeforeBuildDocument`),await Wo(n,`onBeforeBuildDocument`),V.report(`export-usdz`,`Done onBeforeBuildDocument`),V.report(`export-usdz`,`Reparent bones to common ancestor`);let o=[],s=new Set;e?.traverse(e=>{if(!(!t.exportInvisible&&!e.visible)&&e instanceof Ie){let t=e.skeleton.bones,n=Eo(t);if(n){let t={object:e,originalParent:e.parent,newParent:n};o.push(t),s.add(t.object.uuid),t.newParent&&s.add(t.newParent.uuid),t.originalParent&&s.add(t.originalParent.uuid)}}});for(let e of o){let{object:t,originalParent:n,newParent:r}=e;r.add(t)}V.report(`export-usdz`,`Traversing hierarchy`),e&&zo(e,n.document,n,this.keepObject),V.report(`export-usdz`,`Invoking onAfterBuildDocument`),await Wo(n,`onAfterBuildDocument`);let c=n.extensions.find(e=>e.extensionName===`Behaviour`)?.getAllTargetUuids()??new Set;if(this.pruneUnusedNodes){let e={allBehaviorTargets:c,debug:!1,boneReparentings:s,quickLookCompatible:n.quickLookCompatible};this.debug&&Bo(n.document,`Hierarchy BEFORE pruning`,e),Vo(n.document,e),this.debug&&Bo(n.document,`Hierarchy AFTER pruning`)}else this.debug&&console.log(`Pruning of empty nodes is disabled. This may result in a larger USDZ file.`);V.report(`export-usdz`,{message:`Parsing document`,autoStep:10}),await Ho(n,t),V.report(`export-usdz`,`Invoking onAfterSerialize`),await Wo(n,`onAfterSerialize`);for(let e of o){let{object:t,originalParent:n,newParent:r}=e;n&&n.add(t)}n.exporter?.beforeWritingDocument?.();let l=n.document.buildHeader(n)+`
|
||
`+n.output;this.debug&&console.debug(l),r[i]=ur(l),n.output=``,V.report(`export-usdz`,{message:`Exporting textures`,autoStep:10}),V.start(`export-usdz-textures`,{parentScope:`export-usdz`,logTimings:!1});let u=new p({antialias:!1,alpha:!0,premultipliedAlpha:!1,preserveDrawingBuffer:!0}),d=Object.keys(a).length;V.report(`export-usdz-textures`,{totalSteps:d*3,currentStep:0});let f=async e=>{let n=a[e],i=n.texture,o=Ts.includes(i.format),s={imageData:i.image};V.report(`export-usdz-textures`,{message:`read back texture`,autoStep:!0});let c=n.scale!==void 0&&n.scale.x!==1&&n.scale.y!==1&&n.scale.z!==1&&n.scale.w!==1;(i.isCompressedTexture||i.isRenderTargetTexture||c)&&(s=await Xo(i,t.maxTextureSize,u,n.scale)),V.report(`export-usdz-textures`,{message:`convert texture to canvas`,autoStep:!0});let l=await Qo(s.imageBitmap||s.imageData,t.maxTextureSize).catch(e=>{console.error(`Error converting texture to canvas`,i,e)});if(l){V.report(`export-usdz-textures`,{message:`convert canvas to blob`,autoStep:!0});let t=await l.convertToBlob({type:o?`image/png`:`image/jpeg`,quality:.95});r[`textures/${e}.${o?`png`:`jpg`}`]=new Uint8Array(await t.arrayBuffer())}else console.warn("Can`t export texture: ",i)};for(let e in a)await f(e);u.dispose(),V.end(`export-usdz-textures`);let m=0;for(let e in r){let t=r[e],n=34+e.length;m+=n;let i=m&63;if(i!==4){let n=64-i;r[e]=[t,{extra:{12345:new Uint8Array(n)}}]}m=t.length}return V.report(`export-usdz`,`zip archive`),fr(r,{level:0})}};function zo(e,t,n,r){if(!n.exportInvisible&&!e.visible)return;let i,a,o,s={position:e.position,quaternion:e.quaternion,scale:e.scale};if(e.position.x===0&&e.position.y===0&&e.position.z===0&&(s.position=null),e.quaternion.x===0&&e.quaternion.y===0&&e.quaternion.z===0&&e.quaternion.w===1&&(s.quaternion=null),e.scale.x===1&&e.scale.y===1&&e.scale.z===1&&(s.scale=null),(e instanceof x||e instanceof Ie)&&(a=e.geometry,o=e.material),r&&!r(e)&&(a=void 0,o=void 0),(e instanceof x||e instanceof Ie)&&o&&typeof o==`object`&&(o instanceof Te||o instanceof v||o.isMeshPhysicalNodeMaterial||o instanceof Ne&&o.type===`MeshLineMaterial`)){let t=ns(e),n=e instanceof Ie?e:null;i=new jo(e.uuid,t,s,a,o,void 0,n,e.animations)}else if(e instanceof be||e instanceof Ae){let t=ns(e);i=new jo(e.uuid,t,s,void 0,void 0,e)}else{let t=ns(e);i=new jo(e.uuid,t,s,void 0,void 0,void 0,void 0,e.animations)}if(i){if(i.displayName=e.userData?.name||e.name,i.visibility=e.visible?void 0:`invisible`,t&&t.add(i),t=i,n.extensions)for(let t of n.extensions)t.onExportObject&&t.onExportObject.call(t,e,i,n)}else{let n=ns(e),r=new jo(e.uuid,n,{position:e.position,quaternion:e.quaternion,scale:e.scale});t&&t.add(r),t=r}for(let i of e.children)zo(i,t,n,r)}function Bo(e,t,...n){let r={},i=0;function a(e,t){i++;let n=e.displayName||e.name;n+=` (`+e.uuid+`)`,(e.geometry||e.material||e.camera||e.skinnedMesh)&&(n+=` (`+(e.geometry?`geo, `:``)+(e.material?`mat, `:``)+(e.camera?`cam, `:``)+(e.skinnedMesh?`skin, `:``)+`)`),t[n]={};let r={object:e};e.material&&(r.mat=!0),e.geometry&&(r.geo=!0),e.camera&&(r.cam=!0),e.skinnedMesh&&(r.skin=!0),t[n]._self=r;for(let r of e.children)r&&a(r,t[n])}a(e,r),console.log(t+` (`+i+` nodes)`,r,...n)}function Vo(e,t){let n=!0,r=[],i=[];if(e.children.length===0)n=!0;else{let a=[...e.children];for(let e of a)if(e){let a=Vo(e,t);t.debug&&(a?r.push(e):i.push(e)),n&&=a}}let a=t.allBehaviorTargets.has(e.uuid),o=e.geometry||e.material||e.camera&&!t.quickLookCompatible||e.skinnedMesh||!1,s=t.boneReparentings.has(e.uuid),c=n&&!a&&!o&&!s;return c?(t.debug&&console.log(`Pruned object:`,(e.displayName||e.name)+` (`+e.uuid+`)`,{isVisible:o,isBehaviorSourceOrTarget:a,allChildsWerePruned:n,isBoneReparenting:s,object:e,prunedChilds:r,keptChilds:i}),e.parent?.remove(e)):t.debug&&console.log(`Kept object:`,(e.displayName||e.name)+` (`+e.uuid+`)`,{isVisible:o,isBehaviorSourceOrTarget:a,allChildsWerePruned:n,isBoneReparenting:s,object:e,prunedChilds:r,keptChilds:i}),c}async function Ho(e,t){V.start(`export-usdz-resources`,`export-usdz`);let n=[];for(let t of e.document.children)Uo(t,e,n);let r=n.length;for(let e=0;e<r;e++)V.report(`export-usdz-resources`,{totalSteps:r,currentStep:e}),await new Promise((t,r)=>{n[e](),t()});V.end(`export-usdz-resources`);let i=new Fo,a=e.exporter.sceneAnchoringOptions.ar;i.beginBlock(`def Xform "${e.document.name}"`),i.beginBlock(`def Scope "Scenes" (
|
||
kind = "sceneLibrary"
|
||
)`),i.beginBlock(`def Xform "Scene"`,`(`,!1),i.appendLine(`apiSchemas = ["Preliminary_AnchoringAPI"]`),i.appendLine(`customData = {`),i.appendLine(` bool preliminary_collidesWithEnvironment = 0`),i.appendLine(` string sceneName = "Scene"`),i.appendLine(`}`),i.appendLine(`sceneName = "Scene"`),i.closeBlock(`)`),i.beginBlock(),i.appendLine(`token preliminary:anchoring:type = "${a.anchoring.type}"`),a.anchoring.type===`plane`&&i.appendLine(`token preliminary:planeAnchoring:alignment = "${a.planeAnchoring.alignment}"`),a.anchoring.type===`image`&&i.appendLine(`rel preliminary:imageAnchoring:referenceImage = </${e.document.name}/Scenes/Scene/AnchoringReferenceImage>`),i.appendLine();let o=e=>{if(!e)return 0;let t=1;for(let n of e.children)t+=o(n);return t},s=o(e.document);V.start(`export-usdz-xforms`,`export-usdz`),V.report(`export-usdz-xforms`,{totalSteps:s,currentStep:1});for(let t of e.document.children)ss(t,i,e);V.end(`export-usdz-xforms`),V.report(`export-usdz`,`invoke onAfterHierarchy`),await Wo(e,`onAfterHierarchy`,i),i.closeBlock(),i.closeBlock(),V.report(`export-usdz`,`Building materials`);let c=ys(e.materials,e.textures,t.quickLookCompatible);i.appendLine(c),i.closeBlock(),V.report(`export-usdz`,`write to string`),e.output+=i.toString()}function Uo(e,t,n){if(!e)return;let r=e.geometry,i=e.material;if(r)if(i&&(`isMeshStandardMaterial`in i&&i.isMeshStandardMaterial||`isMeshBasicMaterial`in i&&i.isMeshBasicMaterial||i.type===`MeshLineMaterial`)){let i=`geometries/`+is(r,e.name)+`.usda`;i in t.files||n.push(()=>{let n=us(r,e.skinnedMesh?.skeleton?.bones,t.quickLookCompatible);t.files[i]=ts(n,t)})}else console.warn(`NeedleUSDZExporter: Unsupported material type (USDZ only supports MeshStandardMaterial)`,i?.name);i&&t.materials.get(i.uuid)===void 0&&(t.materials[i.uuid]=i);for(let r of e.children)Uo(r,t,n)}async function Wo(e,t,n=null){if(e.extensions){for(let r of e.extensions)if(r&&typeof r[t]==`function`){let i=r[t].call(r,e,n);i instanceof Promise&&await i}}}var Go=null,Ko=null,qo,Jo,Yo;async function Xo(e,t=1/0,n=null,r=void 0){qo||=new He(2,2,1,1),Jo||=new Re({uniforms:{blitTexture:new Ke(e),flipY:new Ke(!1),scale:new Ke(new C(1,1,1,1))},vertexShader:`
|
||
varying vec2 vUv;
|
||
uniform bool flipY;
|
||
void main(){
|
||
vUv = uv;
|
||
if (flipY)
|
||
vUv.y = 1. - vUv.y;
|
||
gl_Position = vec4(position.xy * 1.0,0.,.999999);
|
||
}`,fragmentShader:`
|
||
uniform sampler2D blitTexture;
|
||
uniform vec4 scale;
|
||
varying vec2 vUv;
|
||
|
||
void main(){
|
||
gl_FragColor = vec4(vUv.xy, 0, 1);
|
||
|
||
#ifdef IS_SRGB
|
||
gl_FragColor = sRGBTransferOETF( texture2D( blitTexture, vUv) );
|
||
#else
|
||
gl_FragColor = texture2D( blitTexture, vUv);
|
||
#endif
|
||
|
||
gl_FragColor.rgba *= scale.rgba;
|
||
}`});let i=Jo.uniforms;i.blitTexture.value=e,i.flipY.value=!1,i.scale.value=new C(1,1,1,1),r!==void 0&&i.scale.value.copy(r),Jo.defines.IS_SRGB=e.colorSpace==ue,Jo.needsUpdate=!0,Yo||(Yo=new x(qo,Jo),Yo.frustumCulled=!1);let a=new be,o=new ne;o.add(Yo),n||=Go=new p({antialias:!1,alpha:!0,premultipliedAlpha:!1,preserveDrawingBuffer:!0});let s=Math.min(e.image.width,t),c=Math.min(e.image.height,t);Ko&&(Ko.width!==s||Ko.height!==c)&&(Ko.dispose(),Ko=null),Ko||=new u(s,c,{format:te,type:We,minFilter:m,magFilter:m}),n.setRenderTarget(Ko),n.setSize(s,c),n.clear(),n.render(o,a),Go&&=(Go.dispose(),null);let l=new Uint8ClampedArray(Ko.width*Ko.height*4);n.readRenderTargetPixels(Ko,0,0,Ko.width,Ko.height,l);let d=new ImageData(l,Ko.width,Ko.height,void 0);return{imageData:d,imageBitmap:await createImageBitmap(d,{premultiplyAlpha:`none`})}}function Zo(e){return typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||typeof OffscreenCanvas<`u`&&e instanceof OffscreenCanvas||typeof ImageBitmap<`u`&&e instanceof ImageBitmap}async function Qo(e,t=4096){let n=t/Math.max(e.width,e.height),r=e.width*Math.min(1,n),i=e.height*Math.min(1,n),a=new OffscreenCanvas(r,i),o={premultiplyAlpha:`none`};e.width!==r&&(o.resizeWidth=r),e.height!==i&&(o.resizeHeight=i);let s=await createImageBitmap(e,o),c=a.getContext(`bitmaprenderer`);return c&&c.transferFromImageBitmap(s),a}async function $o(e,t=void 0,n=!1,r=4096){if(Zo(e)){let i=r/Math.max(e.width,e.height),a=new OffscreenCanvas(e.width*Math.min(1,i),e.height*Math.min(1,i)),o=a.getContext(`2d`,{alpha:!0,premultipliedAlpha:!1});if(!o)throw Error(`Could not get canvas 2D context`);if(n===!0&&(o.translate(0,a.height),o.scale(1,-1)),o.drawImage(e,0,0,a.width,a.height),t!==void 0){let e=t.x,n=t.y,r=t.z,i=t.w,s=o.getImageData(0,0,a.width,a.height),c=s.data;for(let t=0;t<c.length;t+=4)c[t+0]=c[t+0]*e,c[t+1]=c[t+1]*n,c[t+2]=c[t+2]*r,c[t+3]=c[t+3]*i;o.putImageData(s,0,0)}return a}else throw Error(`NeedleUSDZExporter: No valid image data found. Unable to process texture.`)}var U=7;function es(){return`#usda 1.0
|
||
(
|
||
customLayerData = {
|
||
string creator = "Needle Engine USDZExporter"
|
||
}
|
||
metersPerUnit = 1
|
||
upAxis = "Y"
|
||
)
|
||
`}function ts(e,t){let n=es();return n+=e,ur(n)}function ns(e){return e.name.replace(/[-<>\(\)\[\]§$%&\/\\\=\?\,\;]/g,``)+`_`+e.id}function rs(e){return wo(e.name||`bone_`+e.uuid)}function is(e,t){return wo(e.name||`Geometry`)+`_`+e.id}function as(e){return wo(e.name||`Material`)+`_`+e.id}function os(e,t){let n=rs(e),r=e.parent;for(;r&&r!==t;)n=rs(r)+`/`+n,r=r.parent;return n}function ss(e,t,n){if(e==null)return;V.report(`export-usdz-xforms`,{message:`buildXform `+e.displayName||e.name,autoStep:!0});let r=e.transform,i=e.geometry,a=e.material,o=e.camera,s=e.name;if(e.animations)for(let t of e.animations)n.animations.push(t);let c=i&&i.isBufferGeometry&&i.attributes.skinIndex!==void 0&&i.attributes.skinIndex.count>0,l=c?`SkelRoot`:`Xform`,u=[],d=a&&a instanceof v&&a.color&&a.color.r===1&&a.color.g===1&&a.color.b===1&&!a.map&&a.opacity===1&&i?.attributes.color;if(i?.attributes.color&&!d&&console.warn(`NeedleUSDZExporter: Geometry has vertex colors. Vertex colors will only be shown in QuickLook for unlit materials with white color and no texture. Otherwise, they will be ignored.`,e.displayName),t.appendLine(),i?(t.beginBlock(`def ${l} "${s}"`,`(`,!1),n.quickLookCompatible&&a&&a.side===2&&!c?t.appendLine(`prepend references = @./geometries/${is(i,s)}.usda@</Geometry_doubleSided>`):t.appendLine(`prepend references = @./geometries/${is(i,s)}.usda@</Geometry>`),d||u.push(`MaterialBindingAPI`),c&&u.push(`SkelBindingAPI`)):o&&!n.quickLookCompatible?t.beginBlock(`def Camera "${s}"`,`(`,!1):e.type===void 0?t.beginBlock(`def Xform "${s}"`,`(`,!1):t.beginBlock(`def ${e.type} "${s}"`),e.type===void 0&&(e.extraSchemas?.length&&u.push(...e.extraSchemas),u.length&&t.appendLine(`prepend apiSchemas = [${u.map(e=>`"${e}"`).join(`, `)}]`)),e.displayName&&t.appendLine(`displayName = "${To(e.displayName)}"`),(o||e.type===void 0)&&(t.closeBlock(`)`),t.beginBlock()),i&&a){if(!d){let e=as(a);t.appendLine(`rel material:binding = </StageRoot/Materials/${e}>`)}!n.quickLookCompatible&&a.side===2&&(t.beginBlock(`over "Geometry" `),t.appendLine(`uniform bool doubleSided = 1`),t.closeBlock())}let f=!1;if(c?(t.appendLine(`rel skel:skeleton = <Rig>`),t.appendLine(`rel skel:animationSource = <Rig/_anim>`),f=!1):e.type===void 0&&r&&(f=f||r.position!==null||r.quaternion!==null||r.scale!==null,r.position&&(e.needsTranslate=!0,t.appendLine(`double3 xformOp:translate = (${W(r.position.x)}, ${W(r.position.y)}, ${W(r.position.z)})`)),r.quaternion&&(e.needsOrient=!0,t.appendLine(`quatf xformOp:orient = (${W(r.quaternion.w)}, ${W(r.quaternion.x)}, ${W(r.quaternion.y)}, ${W(r.quaternion.z)})`)),r.scale&&(e.needsScale=!0,t.appendLine(`double3 xformOp:scale = (${W(r.scale.x)}, ${W(r.scale.y)}, ${W(r.scale.z)})`))),e.visibility!==void 0&&t.appendLine(`token visibility = "${e.visibility}"`),o&&!n.quickLookCompatible&&(`isOrthographicCamera`in o&&o.isOrthographicCamera?(t.appendLine(`float2 clippingRange = (${o.near}, ${o.far})`),t.appendLine(`float horizontalAperture = ${((Math.abs(o.left)+Math.abs(o.right))*10).toPrecision(U)}`),t.appendLine(`float verticalAperture = ${((Math.abs(o.top)+Math.abs(o.bottom))*10).toPrecision(U)}`),t.appendLine(`token projection = "orthographic"`)):`isPerspectiveCamera`in o&&o.isPerspectiveCamera&&(t.appendLine(`float2 clippingRange = (${o.near.toPrecision(U)}, ${o.far.toPrecision(U)})`),t.appendLine(`float focalLength = ${o.getFocalLength().toPrecision(U)}`),t.appendLine(`float focusDistance = ${o.focus.toPrecision(U)}`),t.appendLine(`float horizontalAperture = ${o.getFilmWidth().toPrecision(U)}`),t.appendLine(`token projection = "perspective"`),t.appendLine(`float verticalAperture = ${o.getFilmHeight().toPrecision(U)}`))),e.onSerialize&&e.onSerialize(t,n),e.type===void 0){let n=[];e.needsTranslate&&n.push(`"xformOp:translate"`),e.needsOrient&&n.push(`"xformOp:orient"`),e.needsScale&&n.push(`"xformOp:scale"`),n.length&&t.appendLine(`uniform token[] xformOpOrder = [${n.join(`, `)}]`)}if(e.children){t.appendLine();for(let r of e.children)ss(r,t,n)}t.closeBlock()}function W(e){return Number.isInteger(e)?e.toString():e.toFixed(10)}function cs(e){let t=e.elements;return`( ${ls(t,0)}, ${ls(t,4)}, ${ls(t,8)}, ${ls(t,12)} )`}function ls(e,t){return`(${W(e[t+0])}, ${W(e[t+1])}, ${W(e[t+2])}, ${W(e[t+3])})`}function us(e,t=[],n=!0){return`
|
||
def "Geometry"
|
||
${ds(e,t,n)}
|
||
`}function ds(e,t=[],n=!0){let r=`Geometry`,i=e.attributes,a=i.position.count,o=t&&t.length>0,s=[],c=[],l=[],u=i.skinIndex;if(o){let e=[];for(let n of t)s.push({bone:n,index:t.indexOf(n)}),e.push(n.uuid);let n=1e4;for(;e.length<t.length&&n-- >0;)for(let n of s){let r=n.bone.children;for(let n of r)e.indexOf(n.uuid)===-1&&t.indexOf(n)!==-1&&(s.push({bone:n,index:t.indexOf(n)}),e.push(n.uuid))}n<=0&&console.error(`Failed to sort bones in skinned mesh`,s,t,e);for(let e of Do(t))s.push({bone:e,index:s.length});let r=s[0].bone.parent;s.sort((e,t)=>os(e.bone,r)>os(t.bone,r)?1:-1),s.map(e=>`"`+os(e.bone,r)+`"`).join(`, `);for(let e in s)c[s[e].index]=parseInt(e);let a=i.skinIndex;l=[];for(let e=0;e<a.count;e++){let t=a.getX(e),n=a.getY(e),r=a.getZ(e),i=a.getW(e);l.push(c[t],c[n],c[r],c[i])}u=new Ge(new Uint16Array(l),4)}let d=i.skinWeight&&i.skinIndex;return`
|
||
{
|
||
def Mesh "${r}" ${d?`(
|
||
prepend apiSchemas = ["SkelBindingAPI"]
|
||
)`:``}
|
||
{
|
||
int[] faceVertexCounts = [${fs(e)}]
|
||
int[] faceVertexIndices = [${ps(e)}]
|
||
${i.normal||n?`normal3f[] normals = [${hs(i.normal,a)}] (
|
||
interpolation = "vertex"
|
||
)`:``}
|
||
point3f[] points = [${hs(i.position,a)}]
|
||
${i.uv?`texCoord2f[] primvars:st = [${vs(i.uv,a,!0)}] (
|
||
interpolation = "vertex"
|
||
)`:``}
|
||
${i.uv1?ms(`st1`,i.uv1):``}
|
||
${i.uv2?ms(`st2`,i.uv2):``}
|
||
${i.uv3?ms(`st3`,i.uv3):``}
|
||
${d?`matrix4d primvars:skel:geomBindTransform = ( (1, 0, 0, 0), (0, 1, 0, 0), (0, 0, 1, 0), (0, 0, 0, 1) ) (
|
||
elementSize = 1
|
||
interpolation = "constant"
|
||
)`:``}
|
||
${i.skinIndex?`int[] primvars:skel:jointIndices = [${_s(u,!0)}] (
|
||
elementSize = 4
|
||
interpolation = "vertex"
|
||
)`:``}
|
||
${i.skinWeight?`float[] primvars:skel:jointWeights = [${_s(i.skinWeight)}] (
|
||
elementSize = 4
|
||
interpolation = "vertex"
|
||
)`:``}
|
||
${i.color?`color3f[] primvars:displayColor = [${hs(i.color,a)}] (
|
||
interpolation = "vertex"
|
||
)`:``}
|
||
uniform token subdivisionScheme = "none"
|
||
}
|
||
}
|
||
${n?`
|
||
# This is a workaround for QuickLook/RealityKit not supporting the doubleSided attribute. We're adding a second
|
||
# geometry definition here, that uses the same mesh data but appends extra faces with reversed winding order.
|
||
def "${r}_doubleSided" (
|
||
prepend references = </Geometry>
|
||
)
|
||
{
|
||
over "Geometry"
|
||
{
|
||
int[] faceVertexCounts = [${fs(e)+`, `+fs(e)}]
|
||
int[] faceVertexIndices = [${ps(e)+`, `+ps(e,!0)}]
|
||
}
|
||
}
|
||
`:``}
|
||
`}function fs(e){let t=e.index===null?e.attributes.position.count:e.index.count;return Array(Math.floor(t/3)).fill(3).join(`, `)}function ps(e,t=!1){let n=e.index,r=[];if(n!==null)for(let e=0;e<n.count;e++){let i=e;t&&(i=e%3==0?e+2:e%3==2?e-2:e),r.push(n.getX(i))}else{let n=e.attributes.position.count;for(let e=0;e<n;e++){let n=e;t&&(n=e%3==0?e+2:e%3==2?e-2:e),r.push(n)}}return r.join(`, `)}function ms(e,t){let n=t.itemSize;switch(n){case 2:return`texCoord2f[] primvars:${e} = [${vs(t,n,!0)}] (
|
||
interpolation = "vertex"
|
||
)`;case 3:return`texCoord3f[] primvars:${e} = [${hs(t,n)}] (
|
||
interpolation = "vertex"
|
||
)`;case 4:return`double4[] primvars:${e} = [${gs(t,n)}] (
|
||
interpolation = "vertex"
|
||
)`;default:return console.warn(`USDZExporter: Attribute with `+n+` components are currently not supported. Results may be undefined for `+e+`.`),``}}function hs(e,t){if(e===void 0)return console.warn(`USDZExporter: A mesh attribute is missing and will be set with placeholder data. The result may look incorrect.`),Array(t).fill(`(0, 0, 1)`).join(`, `);let n=[];for(let t=0;t<e.count;t++){let r=e.getX(t),i=e.getY(t),a=e.getZ(t);n.push(`(${r.toPrecision(U)}, ${i.toPrecision(U)}, ${a.toPrecision(U)})`)}return n.join(`, `)}function gs(e,t){if(e===void 0)return console.warn(`USDZExporter: Attribute is missing. Results may be undefined.`),Array(t).fill(`(0, 0, 0, 0)`).join(`, `);let n=[];for(let t=0;t<e.count;t++){let r=e.getX(t),i=e.getY(t),a=e.getZ(t)||0,o=e.getW(t)||0;n.push(`(${r.toPrecision(U)}, ${i.toPrecision(U)}, ${a.toPrecision(U)}, ${o.toPrecision(U)})`)}return n.join(`, `)}function _s(e,t=!1){let n=[];for(let r=0;r<e.count;r++){let i=e.getX(r),a=e.getY(r),o=e.getZ(r),s=e.getW(r);n.push(`${t?i:i.toPrecision(U)}`),n.push(`${t?a:a.toPrecision(U)}`),n.push(`${t?o:o.toPrecision(U)}`),n.push(`${t?s:s.toPrecision(U)}`)}return n.join(`, `)}function vs(e,t,n=!1){if(e===void 0)return console.warn(`USDZExporter: UVs missing.`),Array(t).fill(`(0, 0)`).join(`, `);let r=[];for(let t=0;t<e.count;t++){let i=e.getX(t),a=e.getY(t);n&&(a=1-a),r.push(`(${i.toPrecision(U)}, ${a.toPrecision(U)})`)}return r.join(`, `)}function ys(e,t,n=!1){let r=[];for(let i in e){let a=e[i];r.push(Ss(a,t,n))}return`
|
||
def "Materials"
|
||
{
|
||
${r.join(``)}
|
||
}`}function bs(e){return wo(e.name)+`_`+(e.source?.id??e.id)}function xs(e,t,n,r,i,a,o=void 0,s=void 0){let c=bs(e),l=c+(s!==void 0&&s!==1?`_`+s:``),u=n&&s!==void 0&&s!==1,d=u?new C(1,1,1,s):void 0;s===void 0&&(s=1),u&&(s=1),d&&d.w<=.05&&(d.w=.05),r[l]={texture:e,scale:d};let f=e.channel>0?`st`+e.channel:`st`;a.add(e.channel);let p=Ts.includes(e.format),m={1e3:`repeat`,1001:`clamp`,1002:`mirror`},h=e.repeat.clone(),g=e.offset.clone(),_=e.rotation,ee=Math.sin(_),te=Math.cos(_);g.y=1-g.y-h.y,n?(h.x===0&&(h.x=1e-4),h.y===0&&(h.y=1e-4),g.x/=h.x,g.y/=h.y,g.x+=ee/h.x,g.y+=te-1):(g.x+=ee*h.x,g.y+=(1-te)*h.y);let ne=as(i),v=h.x!=1||h.y!=1||g.x!=0||g.y!=0||_!=0,re=`${Po}/${ne}/${`uvReader_`+f}.outputs:result>`,ie=`${Po}/${ne}/Transform2d_${t}.outputs:result>`,ae=t!==`normal`&&o&&(o.r!==1||o.g!==1||o.b!==1||s!==1)||!1,oe=t===`normal`,y=i instanceof Te&&i.normalScale?i.normalScale.x*2:2,se=y.toFixed(U),ce=(y/2*-1).toFixed(U),b=(1-y).toFixed(U);return`
|
||
${v?`def Shader "Transform2d_${t}" (
|
||
sdrMetadata = {
|
||
string role = "math"
|
||
}
|
||
)
|
||
{
|
||
uniform token info:id = "UsdTransform2d"
|
||
float2 inputs:in.connect = ${re}
|
||
float2 inputs:scale = ${ws(h)}
|
||
float2 inputs:translation = ${ws(g)}
|
||
float inputs:rotation = ${(_/Math.PI*180).toFixed(U)}
|
||
float2 outputs:result
|
||
}
|
||
`:``}
|
||
def Shader "${c}_${t}"
|
||
{
|
||
uniform token info:id = "UsdUVTexture"
|
||
asset inputs:file = @textures/${l}.${p?`png`:`jpg`}@
|
||
token inputs:sourceColorSpace = "${e.colorSpace===`srgb`?`sRGB`:`raw`}"
|
||
float2 inputs:st.connect = ${v?ie:re}
|
||
${ae?`
|
||
float4 inputs:scale = (${o?o.r+`, `+o.g+`, `+o.b:`1, 1, 1`}, ${s})
|
||
`:``}
|
||
${oe?`
|
||
float4 inputs:scale = (${se}, ${se}, ${se}, 1)
|
||
float4 inputs:bias = (${ce}, ${ce}, ${b}, 0)
|
||
`:``}
|
||
token inputs:wrapS = "${m[e.wrapS]}"
|
||
token inputs:wrapT = "${m[e.wrapT]}"
|
||
float outputs:r
|
||
float outputs:g
|
||
float outputs:b
|
||
float3 outputs:rgb
|
||
${i.transparent||i.alphaTest>0?`float outputs:a`:``}
|
||
}`}function Ss(e,t,r=!1){let i=as(e);if(e.colorWrite===!1||e.userData?.isShadowCatcherMaterial||e.userData?.isLightBlendMaterial){let t=e.userData.isLightBlendMaterial||e.userData.isShadowCatcherMaterial?`ND_realitykit_shadowreceiver_surfaceshader`:`ND_realitykit_occlusion_surfaceshader`;return`
|
||
|
||
def Material "${i}" ${e.name?`(
|
||
displayName = "${e.name}"
|
||
)`:``}
|
||
{
|
||
token outputs:mtlx:surface.connect = ${Po}/${i}/Occlusion.outputs:out>
|
||
|
||
def Shader "Occlusion"
|
||
{
|
||
uniform token info:id = "${t}"
|
||
token outputs:out
|
||
}
|
||
}`}let a=` `,o=[],s=[],c=new Set;if(e.isMeshPhysicalNodeMaterial===!0)return vo(e,i,t);let l=e.transparent||e.alphaTest?e.opacity:1,u=!1,d=!1;if(e instanceof Fe&&e.transmission!==void 0&&(l*=1-e.transmission*(1-e.roughness*.5)),e.map?(o.push(`${a}color3f inputs:diffuseColor.connect = ${Po}/${i}/${bs(e.map)}_diffuse.outputs:rgb>`),e instanceof v&&e.transparent&&e.alphaTest==0&&r?(o.push(`${a}float inputs:opacity.connect = ${Po}/${i}/${bs(e.map)}_diffuse.outputs:a>`),u=!0,o.push(`${a}float inputs:opacityThreshold = 1e-10`),d=!0):e.transparent?(o.push(`${a}float inputs:opacity.connect = ${Po}/${i}/${bs(e.map)}_diffuse.outputs:a>`),u=!0):e.alphaTest>0&&(o.push(`${a}float inputs:opacity.connect = ${Po}/${i}/${bs(e.map)}_diffuse.outputs:a>`),u=!0,o.push(`${a}float inputs:opacityThreshold = ${e.alphaTest}`),d=!0),s.push(xs(e.map,`diffuse`,r,t,e,c,e.color,l))):o.push(`${a}color3f inputs:diffuseColor = ${Cs(e.color)}`),e.alphaHash&&r&&(d?console.warn(`Opacity threshold for `+e.name+` was already connected. Skipping alphaHash opacity threshold.`):(o.push(`${a}float inputs:opacityThreshold = 0.0000000001`),d=!0)),e.aoMap&&(o.push(`${a}float inputs:occlusion.connect = ${Po}/${i}/${bs(e.aoMap)}_occlusion.outputs:r>`),s.push(xs(e.aoMap,`occlusion`,r,t,e,c))),e.alphaMap?(o.push(`${a}float inputs:opacity.connect = ${Po}/${i}/${bs(e.alphaMap)}_opacity.outputs:r>`),o.push(`${a}float inputs:opacityThreshold = 0.0000000001`),u=!0,d=!0,s.push(xs(e.alphaMap,`opacity`,r,t,e,c,new n(1,1,1),l))):(u?console.warn(`Opacity for `+e.name+` was already connected. Skipping default opacity.`):(o.push(`${a}float inputs:opacity = ${l}`),u=!0),e.alphaTest>0&&(d?console.warn(`Opacity threshold for `+e.name+` was already connected. Skipping default opacity threshold.`):(o.push(`${a}float inputs:opacityThreshold = ${e.alphaTest}`),d=!0))),e instanceof Te){if(e.emissiveMap){o.push(`${a}color3f inputs:emissiveColor.connect = ${Po}/${i}/${bs(e.emissiveMap)}_emissive.outputs:rgb>`);let n=e.emissive.clone();n.multiplyScalar(e.emissiveIntensity),s.push(xs(e.emissiveMap,`emissive`,r,t,e,c,n))}else if(e.emissive?.getHex()>0){let t=e.emissive.clone();t.multiplyScalar(e.emissiveIntensity),o.push(`${a}color3f inputs:emissiveColor = ${Cs(t)}`)}e.normalMap&&(o.push(`${a}normal3f inputs:normal.connect = ${Po}/${i}/${bs(e.normalMap)}_normal.outputs:rgb>`),s.push(xs(e.normalMap,`normal`,r,t,e,c))),e.roughnessMap&&e.roughness===1?(o.push(`${a}float inputs:roughness.connect = ${Po}/${i}/${bs(e.roughnessMap)}_roughness.outputs:g>`),s.push(xs(e.roughnessMap,`roughness`,r,t,e,c))):o.push(`${a}float inputs:roughness = ${e.roughness===void 0?1:e.roughness}`),e.metalnessMap&&e.metalness===1?(o.push(`${a}float inputs:metallic.connect = ${Po}/${i}/${bs(e.metalnessMap)}_metallic.outputs:b>`),s.push(xs(e.metalnessMap,`metallic`,r,t,e,c))):o.push(`${a}float inputs:metallic = ${e.metalness===void 0?0:e.metalness}`)}return e instanceof Fe&&(o.push(`${a}float inputs:clearcoat = ${e.clearcoat}`),o.push(`${a}float inputs:clearcoatRoughness = ${e.clearcoatRoughness}`),o.push(`${a}float inputs:ior = ${e.ior}`),!e.transparent&&!(e.alphaTest>0)&&e.transmissionMap&&(o.push(`${a}float inputs:opacity.connect = ${Po}/${i}/${bs(e.transmissionMap)}_transmission.outputs:r>`),s.push(xs(e.transmissionMap,`transmission`,r,t,e,c)))),c.size>2?console.warn(`USDZExporter: Material `+e.name+` uses more than 2 UV channels. Currently, only UV0 and UV1 are supported.`):c.size===2&&(!c.has(0)||!c.has(1))&&console.warn(`USDZExporter: Material `+e.name+` uses UV channels other than 0 and 1. Currently, only UV0 and UV1 are supported.`),`
|
||
|
||
def Material "${i}" ${e.name?`(
|
||
displayName = "${To(e.name)}"
|
||
)`:``}
|
||
{
|
||
token outputs:surface.connect = ${Po}/${i}/PreviewSurface.outputs:surface>
|
||
|
||
def Shader "PreviewSurface"
|
||
{
|
||
uniform token info:id = "UsdPreviewSurface"
|
||
${o.join(`
|
||
`)}
|
||
int inputs:useSpecularWorkflow = ${e instanceof v?`1`:`0`}
|
||
token outputs:surface
|
||
}
|
||
${s.length>0?`
|
||
${c.has(0)?`
|
||
def Shader "uvReader_st"
|
||
{
|
||
uniform token info:id = "UsdPrimvarReader_float2"
|
||
string inputs:varname = "st"
|
||
float2 inputs:fallback = (0.0, 0.0)
|
||
float2 outputs:result
|
||
}
|
||
`:``}
|
||
${c.has(1)?`
|
||
def Shader "uvReader_st1"
|
||
{
|
||
uniform token info:id = "UsdPrimvarReader_float2"
|
||
string inputs:varname = "st1"
|
||
float2 inputs:fallback = (0.0, 0.0)
|
||
float2 outputs:result
|
||
}
|
||
`:``}
|
||
${s.join(`
|
||
`)}`:``}
|
||
}`}function Cs(e){return`(${e.r}, ${e.g}, ${e.b})`}function ws(e){return`(${e.x}, ${e.y})`}var Ts=[1023,33777,33778,33779,35842,35843,37496,37808,37809,37810,37811,37812,37813,37814,37815,37816,37817,37818,37819,37820,37821,36492];D(`debugusdz`);var Es=class e{static global_id=0;id;trigger;action;exclusive=!1;makeExclusive(e){return this.exclusive=e,this}constructor(t,n,r){this.id=`Behavior_`+wo(t)+`_`+ e.global_id++,this.trigger=n,this.action=r}writeTo(e,t,n){if(!this.trigger||!this.action)return;n.beginBlock(`def Preliminary_Behavior "${this.id}"`);let r=``;if(Array.isArray(this.trigger)){r=`[`;for(let e=0;e<this.trigger.length;e++){let t=this.trigger[e];r+=`<`+t.id+`>`,e+1<this.trigger.length&&(r+=`, `)}r+=`]`}else r=`<${this.trigger.id}>`;if(n.appendLine(`rel triggers = ${r}`),n.appendLine(`rel actions = <${this.action.id}>`),n.appendLine(`uniform bool exclusive = ${+!!this.exclusive}`),n.appendLine(),Array.isArray(this.trigger))for(let e of this.trigger)e.writeTo(t,n),n.appendLine();else this.trigger.writeTo(t,n);n.appendLine(),this.action.writeTo(t,n),n.closeBlock()}},Ds=new Set;function Os(e,t){let n=``;if(Array.isArray(e)){Ds.clear();let r=`[ `;for(let n=0;n<e.length;n++){let i=e[n];if(!i){console.warn(`Invalid target object in behavior`,e+`. Is the object exported?`);continue}if(typeof i==`string`){if(Ds.has(i))continue;r+=i,Ds.add(i)}else if(typeof i==`object`){if(i.isObject3D&&(i=t.findById(i.uuid),!i)){console.warn(`Invalid target object in behavior`,e+`. Is the object exported?`);continue}let n=i.getPath?.call(i);if(Ds.has(n))continue;r+=n,Ds.add(n)}n+1<e.length&&(r+=`, `)}r+=` ]`,n=r,Ds.clear()}else if(typeof e==`object`){let r=e;if(r.isObject3D&&(e=t.findById(r.uuid)),!e)throw console.error(`Invalid target object in behavior, the target object is likely missing from USDZ export. Is the object exported?`,r),Error(`Invalid target object in behavior, the target object is likely missing from USDZ export. Please report a bug. uuid: ${r.uuid}.`);n=e.getPath?.call(e)}return n}var ks=class e{static global_id=0;id;targetId;tokenId;type;distance;constructor(t,n){t&&(this.targetId=t),n?this.id=n:this.id=`Trigger_`+ e.global_id++}writeTo(e,t){t.beginBlock(`def Preliminary_Trigger "${this.id}"`),this.targetId&&(typeof this.targetId!=`string`&&(this.targetId=Os(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 As(e,t={direct:!0,indirect:!0}){let n=jo.createEmpty();n.name=`InputTarget_`+n.name,n.displayName=void 0,n.type=`RealityKitComponent`,n.onSerialize=e=>{e.appendLine(`bool allowsDirectInput = `+ +!!t.direct),e.appendLine(`bool allowsIndirectInput = `+ +!!t.indirect),e.appendLine(`uniform token info:id = "RealityKit.InputTarget"`)},e.add(n)}var js=class{static __sceneStartTrigger;static sceneStartTrigger(){if(this.__sceneStartTrigger!==void 0)return this.__sceneStartTrigger;let e=new ks(void 0,`SceneStart`);return e.tokenId=`SceneTransition`,e.type=`enter`,this.__sceneStartTrigger=e,e}static tapTrigger(e,t={direct:!0,indirect:!0}){let n=new ks(e);if(Array.isArray(e)&&e.length>1)for(let n of e)n instanceof jo&&As(n,t);else e instanceof jo&&As(e,t);return n.tokenId=`TapGesture`,n}static isTapTrigger(e){return e?.tokenId===`TapGesture`}static proximityToCameraTrigger(e,t){let n=new ks(e);return n.tokenId=`ProximityToCamera`,n.distance=t,n}},Ms=class{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(let e of this.actions){if(!e)continue;let n=e===this.actions[this.actions.length-1];t.appendLine(`<`+e.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(let n of this.actions)n&&(n.writeTo(e,t),t.appendLine());t.closeBlock()}},Ns=class e{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(){let t=new e,n=t.id;return Object.assign(t,this),t.id=n,t}constructor(t,n){t&&(this.affectedObjects=t),n?this.id=n:this.id=`Action`,this.id+=`_`+ e.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=Os(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=Os(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()}},Ps=class e{x=0;y=0;z=0;constructor(e,t,n){this.x=e,this.y=t,this.z=n}static get up(){return new e(0,1,0)}static get right(){return new e(1,0,0)}static get forward(){return new e(0,0,1)}static get back(){return new e(0,0,-1)}static get zero(){return new e(0,0,0)}},G=class e{static sequence(...e){return new Ms(`Group_`+Ms.getId(),e).makeSequence()}static parallel(...e){return new Ms(`Group_`+Ms.getId(),e).makeParallel()}static fadeAction(e,t,n){let r=new Ns(e);return r.tokenId=`Visibility`,r.type=n?`show`:`hide`,r.duration=t,r.style=`basic`,r.motionType=`none`,r.moveDistance=0,r.easeType=`none`,r}static startAnimationAction(t,n,r=!1,i=!1){let a=new Ns(t);a.tokenId=`StartAnimation`;let o=n.start,s=n.duration,c=n.speed,l=n.clipName;if(a.comment=`Animation: ${l}, start=${o*60}, length=${s*60}, end=${(o+s)*60}`,a.animationName=l,a.start=o,a.duration=s,a.animationSpeed=c,a.reversed=r,a.pingPong=i,a.multiplePerformOperation=`allow`,r&&(a.start-=s),i){a.pingPong=!1;let t=a.clone();return t.reversed=!r,t.start=a.start,t.reversed&&(t.start-=s),e.sequence(a,t)}return a}static waitAction(e){let t=new Ns;return t.tokenId=`Wait`,t.duration=e,t.motionType=void 0,t}static lookAtCameraAction(e,t,n,r){let i=new Ns(e);return i.tokenId=`LookAtCamera`,i.duration=t===void 0?9999999999999:t,i.front=n??Ps.forward,i.up=r??Ps.up,i}static emphasize(e,t,n=`bounce`,r=1,i=`basic`){let a=new Ns(e);return a.tokenId=`Emphasize`,a.duration=t,a.style=i??`basic`,a.motionType=n,a.moveDistance=r,a}static transformAction(e,t,n,r,i=`inout`){let a=new Ns(e);return a.tokenId=`Transform`,a.duration=n,a.duration=Math.max(1e-6,n),a.type=r,a.easeType=n>0?i:`none`,Array.isArray(t)&&console.error(`Transform target must not be an array`,t),a.xFormTarget=t,a}static playAudioAction(e,t,n=`play`,r=1,i=`spatial`){let a=new Ns(e);return a.tokenId=`Audio`,a.type=n,a.audio=t,a.gain=r,a.auralMode=i,a.multiplePerformOperation=`allow`,a}static impulseAction(e,t){let n=new Ns(e);return n.tokenId=`Impulse`,n.velocity=t,n}},Fs=D(`debugusdzanimation`),Is=D(`debugusdzanimationserialization`),Ls=class e{_start;get start(){return this._start===void 0&&(this._start=this.ext.getStartTimeByClip(this.clip)),this._start}get duration(){return this.clip?.duration??K.restPoseClipDuration}get nearestAnimatedRoot(){return this._nearestAnimatedRoot}get clipName(){return this.clip?.name??`rest`}ext;root;_nearestAnimatedRoot=void 0;clip;speed;constructor(e,t,n){this.ext=e,this.root=t,this.clip=n,this._nearestAnimatedRoot=this.getNearestAnimatedRoot()}static isDescendantOf(e,t){let n=t;if(!n||!e)return!1;for(;n;){if(!n)return!1;if(n===e)return!0;n=n.parent}return!1}getNearestAnimatedRoot(){let t;try{for(let n of this.clip?.tracks??[]){let r=o.parseTrackName(n.name),i=o.findNode(this.root,r.nodeName);if(i)if(!t)t=i;else{if(i===t||e.isDescendantOf(t,i))continue;if(!e.isDescendantOf(i,t)){for(;!e.isDescendantOf(i,t)&&i.parent;)i=i.parent;e.isDescendantOf(i,t)||console.error(`USDZExporter: Animation clip targets multiple roots that are not parent/child. Please report a bug`,this.root,this.clip,t,i)}t=i}}}catch(e){console.error(`USDZExporter: Exception when trying to find nearest animated root. Please report a bug`,e),t=void 0}return t}},K=class e{clip;pos;rot;scale;root;target;duration=0;useRootMotion=!1;static frameRate=60;static animationDurationPadding=6/60;static restPoseClipDuration=6/60;constructor(t,n,r){if(this.root=t,this.target=n,this.clip=r,r?this.duration=r.duration:this.duration=e.restPoseClipDuration,r&&r.tracks){let e=Math.max(...r.tracks.map(e=>e.times[e.times.length-1]));e!==this.duration&&(console.warn(`USDZExporter: Animation clip duration does not match the maximum time value in the tracks.`,r,e,this.duration),this.duration=e)}let i=k.getComponent(t,kt);i&&(this.useRootMotion=i.applyRootMotion)}addTrack(e){if(!this.clip){console.error(`This is a rest clip but you're trying to add tracks to it – this is likely a bug`);return}e.name.endsWith(`position`)?this.pos=e:e.name.endsWith(`quaternion`)?this.rot=e:e.name.endsWith(`scale`)?this.scale=e:(e.name.endsWith(`activeSelf`)?console.warn(`[USDZ] Animation of enabled/disabled state is not supported for USDZ export and will NOT be exported: `+e.name+` on `+(this.root?.name??this.target.name)+`. Animate scale 0/1 instead.`):console.warn(`[USDZ] Animation track type not supported for USDZ export and will NOT be exported: `+e.name+` on `+(this.root?.name??this.target.name)+`. Only .position, .rotation, .scale are supported.`),T()&&kn(`[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,n=!0){if(!this.clip)return[0,this.duration];let r=this.pos?.times,i=this.rot?.times,a=this.scale?.times,o=[];if(e&&r)for(let e of r)o.push(e);if(t&&i)for(let e of i)o.push(e);if(n&&a)for(let e of a)o.push(e);return o.includes(0)||o.push(0),o.sort((e,t)=>e-t),[...new Set(o)]}*getValues(t,n=!0,i=!0,a=!0){let o=new r,s=new Ue,c=new r(1,1,1),l=this.target,u=n?this.pos?.createInterpolant():void 0,d=i?this.rot?.createInterpolant():void 0,f=a?this.scale?.createInterpolant():void 0;u||o.set(l.position.x,l.position.y,l.position.z),d||s.set(l.quaternion.x,l.quaternion.y,l.quaternion.z,l.quaternion.w),f||c.set(l.scale.x,l.scale.y,l.scale.z),u&&u.valueSize!==3&&(u.valueSize=3),d&&d.valueSize!==4&&(d.valueSize=4),f&&f.valueSize!==3&&(f.valueSize=3);for(let n=0;n<t.length+0;n++){let r=0,i=0;if(n<0?(r=t[0],i=r-e.animationDurationPadding/2+1/60):n>=t.length?(r=t[t.length-1],i=r+e.animationDurationPadding/2-1/60):(r=t[n],i=r),u){let e=u.evaluate(r);o.set(e[0],e[1],e[2])}if(d){let e=d.evaluate(r);s.set(e[0],e[1],e[2],e[3])}if(f){let e=f.evaluate(r);c.set(e[0],e[1],e[2])}if(this.useRootMotion&&l===this.root){let e=new b;e.compose(o,s,c),e.multiply(l.matrix),e.decompose(o,s,c)}yield{time:i,translation:o,rotation:s,scale:c,index:n}}}},Rs=class{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:(K.restPoseClipDuration+K.animationDurationPadding)*60}getEndTimeCode(){let e=0;for(let[t,n]of this.rootAndClipToRegisteredAnimationMap){let t=n.start+n.duration;t>e&&(e=t)}return e*60}getClipCount(e){return this.rootToRegisteredClip.get(e)?.length??0??0}getStartTimeByClip(e){return e?this.clipToStartTime.has(e)?this.clipToStartTime.get(e):(console.error(`USDZExporter: Missing start time for clip – please report a bug.`,e),0):0}registerAnimation(e,t){if(!e)return null;this.rootTargetMap.has(e)||this.rootTargetMap.set(e,[]);let n=e.uuid+(t?.uuid??`-rest`);if(this.rootAndClipToRegisteredAnimationMap.has(n))return this.rootAndClipToRegisteredAnimationMap.get(n);Fs&&console.log(`registerAnimation`,e,t);let r=+!!this.injectRestPoses,i=(this.rootToRegisteredClip.get(e)?.length??0)+r,a=this.rootTargetMap.get(e),s=new Set(a);if(t&&t.tracks)for(let n of t.tracks){let r=o.parseTrackName(n.name),c=o.findNode(e,r.nodeName);if(!c){console.warn(`no object found for track`,n.name,`using `+e.name+` instead`);continue}this.dict.has(c)||this.dict.set(c,[]);let l=this.dict.get(c);if(!l){console.warn(`no transform data found for target `,c,`at slot `+i+`, this is likely a bug`);continue}s.delete(c),this.injectRestPoses&&!l[0]&&(console.log(`Injecting rest pose`,c,t,`at slot`,i),l[0]=new K(null,c,null));let u=l[i];u||(u=new K(e,c,t),l[i]=u),u.addTrack(n),a?.includes(c)||a?.push(c)}Fs&&console.log(`Unregistered nodes for this clip`,s,`clip`,t,`at slot`,i,`for root`,e,`targets`,a);for(let n of s){let r=this.dict.get(n);if(!r)continue;this.injectRestPoses&&!r[0]&&(console.warn(`Adding rest pose for `,n,t,`at slot`,i,`This is likely a bug, should have been added earlier.`),r[0]=new K(null,n,null));let a=r[i];a||(Fs&&console.log(`Adding padding clip for `,n,t,`at slot`,i),a=new K(e,n,t),r[i]=a)}let c=new Ls(this,e,t);if(this.rootAndClipToRegisteredAnimationMap.set(n,c),Fs&&console.log({root:e,clip:t,info:c}),t){let n=this.rootToRegisteredClip.get(e);if(n?n.push(t):this.rootToRegisteredClip.set(e,[t]),!this.clipToStartTime.get(t)){this.lastClipEndTime??=K.restPoseClipDuration;let e=this.lastClipEndTime+K.animationDurationPadding,n=e+t.duration,r=Math.round(e*60)/60,i=Math.round(n*60)/60;Math.abs(r-e)<.01&&(e=r),Math.abs(i-n)<.01&&(n=i),e=Math.ceil(e),n=e+t.duration,this.clipToStartTime.set(t,e),this.lastClipEndTime=n}}return c}onAfterHierarchy(e){Fs&&console.log(`Animation clips per animation target node`,this.dict)}onAfterBuildDocument(e){Fs&&console.log(`Animation data`,{dict:this.dict,rootTargetMap:this.rootTargetMap,rootToRegisteredClip:this.rootToRegisteredClip});for(let e of this.rootTargetMap.keys()){let t=this.rootTargetMap.get(e);if(!t)continue;let n,r=[];for(let i of t){let t=this.dict.get(i);if(!t){console.error(`No data found for target on USDZ export – please report a bug!`,i);continue}n===void 0&&(n=t?.length),n!==t?.length&&console.error(`Different array lengths for targets – please report a bug!`,t);for(let n=0;n<t.length;n++){let a=t[n];if(!a){let r=n-+!!this.injectRestPoses;t[n]=new K(null,i,this.rootToRegisteredClip.get(e)[r]),a=t[n]}let o=a.getDuration();if(r[n]===void 0)r[n]=o;else if(r[n]!==o){console.error(`Error during UDSZ export: Encountered different animation durations for animated targets. Please report a bug!`,{datas:t,target:i}),r[n]=o;continue}}}}for(let e of this.serializers){let t=e.model?.parent,n=t?.isDynamic===!0;Is&&console.log(n,e.model?.parent),n&&e.registerCallback(t)}}onExportObject(e,t,n){k.foreachComponent(e,e=>{let r=e;typeof r.createAnimation==`function`&&r.createAnimation(this,t,n)},!1);let r=new zs(e,this);this.serializers.push(r),r.registerCallback(t)}},zs=class{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.onSerialize.bind(this),Is&&console.log(`REPARENT`,e),this.model=e,this.callback&&this.model.addEventListener(`serialize`,this.callback)}skinnedMeshExport(e,t,n){let r=this.model,i=this.animationData;if(r&&r.skinnedMesh){let a=r.skinnedMesh.skeleton,o=[],s=[],c=[];for(let e of a.bones){s.push(e),c.push(e.uuid);let t=a.boneInverses[a.bones.indexOf(e)];o.push({bone:e,inverse:t})}let l=1e4;for(;c.length<a.bones.length&&l-- >0;)for(let e of s){let t=e.children;for(let e of t)if(c.indexOf(e.uuid)===-1&&a.bones.indexOf(e)!==-1){s.push(e),c.push(e.uuid);let t=a.boneInverses[a.bones.indexOf(e)];o.push({bone:e,inverse:t})}}l<=0&&console.error(`Failed to sort bones in skinned mesh`,r.skinnedMesh,a.bones,c);for(let e of Do(a.bones))o.push({bone:e,inverse:e.matrixWorld.clone().invert()});let u=o[0].bone.parent;u||console.error(`No bone parent found for skinned mesh during USDZ export`,r.skinnedMesh),o.sort((e,t)=>os(e.bone,u)>os(t.bone,u)?1:-1);function d(e){let t=[];for(let[n,r]of e){let e=`${n} : [`,i=[];for(let e of r)i.push(`(${W(e.x)}, ${W(e.y)}, ${W(e.z)})`);e=e.concat(i.join(`, `)),e=e.concat(`],`),t.push(e)}return t}function f(e){let t=[];for(let[n,r]of e){let e=`${n} : [`,i=[];for(let e of r)i.push(`(${W(e.w)}, ${W(e.x)}, ${W(e.y)}, ${W(e.z)})`);e=e.concat(i.join(`, `)),e=e.concat(`],`),t.push(e)}return t}function p(e){let t,r=!0,i=new Map;for(let[n,a]of e){t===void 0&&(t=a.length),t!==a.length&&(r=!1);let e=0;for(let t of a)e++,t||(i.has(n)||i.set(n,[]),i.get(n).push(e))}Fs&&console.log(`Bone count: `,e.size,`TransformData entries per bone: `,t,`Undefined bone entries: `,i),console.assert(r,`All bones should have the same number of TransformData entries`,e),console.assert(i.size===0,`All TransformData entries should be set`,i);let a=[];for(let[t,r]of e)for(let e=0;e<r.length;e++){let t=r[e],i=n.getStartTimeByClip(t.clip);a.length<=e&&a.push({pos:[],rot:[],scale:[],timeOffset:i});let o=a[e];o.pos.push(...t.getSortedTimesArray(!0,!1,!1)),o.rot.push(...t.getSortedTimesArray(!1,!0,!1)),o.scale.push(...t.getSortedTimesArray(!1,!1,!0))}for(let e of a)e.pos.sort((e,t)=>e-t),e.rot.sort((e,t)=>e-t),e.scale.sort((e,t)=>e-t),e.pos=[...new Set(e.pos)],e.rot=[...new Set(e.rot)],e.scale=[...new Set(e.scale)];return a}function m(e,t,n){let r=new Map,i=new Map,a=new Map,o=t.length;for(let s of n){let n=e.get(s),c;n?console.assert(n.length===o,`We should have the same number of TransformData entries for each bone`,n,t):c=new K(null,s,null);for(let e=0;e<o;e++){let o=n?n[e]:c,s=t[e];for(let{time:e,translation:t}of o.getValues(s.pos,!0,!1,!1)){let n=(e+s.timeOffset)*60;r.has(n)||r.set(n,[]),r.get(n).push(t.clone())}for(let{time:e,rotation:t}of o.getValues(s.rot,!1,!0,!1)){let n=(e+s.timeOffset)*60;i.has(n)||i.set(n,[]),i.get(n).push(t.clone())}for(let{time:e,scale:t}of o.getValues(s.scale,!1,!1,!0)){let n=(e+s.timeOffset)*60;a.has(n)||a.set(n,[]),a.get(n).push(t.clone())}}}return{position:r.size==0?void 0:r,quaternion:i.size==0?void 0:i,scale:a.size==0?void 0:a}}function h(e){let t=[];for(let n of e)t.push(`(${W(n.x)}, ${W(n.y)}, ${W(n.z)})`);return t.join(`, `)}function g(e){let t=[];for(let n of e)t.push(`(${W(n.w)}, ${W(n.x)}, ${W(n.y)}, ${W(n.z)})`);return t.join(`, `)}function _(e){let t=new Map;if(Fs){let e=[];for(let[t,n]of i)e.push(t.uuid+`: `+n.length+` `+n.map(e=>e.clip?.uuid.substring(0,6)).join(` `));console.log(`getPerBoneTransformData
|
||
`+e.join(`
|
||
`))}for(let n of e){let e=i.get(n);e&&t.set(n,e)}return t}function ee(e){let t=_(e);return m(t,p(t),e)}let te=t.quickLookCompatible,ne=[],v=[],re=[],ie=[];for(let{bone:e}of o){if(te){let t=e.scale;t.x==0&&(t.x=1e-5),t.y==0&&(t.y=1e-5),t.z==0&&(t.z=1e-5),ne.push(new b().compose(e.position,e.quaternion,e.scale))}else ne.push(e.matrix.clone());v.push(e.position),re.push(e.quaternion),ie.push(e.scale)}let ae=o.map(e=>`"`+os(e.bone,u)+`"`).join(`, `),oe=o.map(e=>cs(e.inverse.clone().invert())).join(`, `);e.beginBlock(`def Skeleton "Rig"`),e.appendLine(`uniform matrix4d[] bindTransforms = [${oe}]`),e.appendLine(`uniform token[] joints = [${ae}]`),e.appendLine(`uniform token purpose = "guide"`),e.appendLine(`uniform matrix4d[] restTransforms = [${ne.map(e=>cs(e)).join(`, `)}]`);let y=ee(o.map(e=>e.bone));if(Fs){let e=1e7,t=0;for(let n of y.position?.keys()??[])e=Math.min(e,n),t=Math.max(t,n);console.log(`Time samples`,e,t,y)}if(e.beginBlock(`def SkelAnimation "_anim"`),e.appendLine(`uniform token[] joints = [${ae}]`),e.appendLine(`quatf[] rotations = [${g(re)}]`),y&&y.quaternion){e.beginBlock(`quatf[] rotations.timeSamples = {`,``);let t=f(y.quaternion);for(let n of t)e.appendLine(n);e.closeBlock()}if(e.appendLine(`half3[] scales = [${h(ie)}]`),y&&y.scale){e.beginBlock(`half3[] scales.timeSamples = {`,``);let t=d(y.scale);for(let n of t)e.appendLine(n);e.closeBlock()}if(e.appendLine(`float3[] translations = [${h(v)}]`),y&&y.position){e.beginBlock(`float3[] translations.timeSamples = {`,``);let t=d(y.position);for(let n of t)e.appendLine(n);e.closeBlock()}e.closeBlock(),e.closeBlock()}}onSerialize(e,t){if(!this.model)return;let n=this.animationData.get(this.object);if(n)for(let e=0;e<n.length;e++)n[e]===void 0&&(n[e]=new K(null,this.object,null));let r=this.ext;this.skinnedMeshExport(e,t,r);let i=this.object,a=this.model,o=this.animationData.get(i);if(!o||i.isSkinnedMesh)return;Is&&console.log(`SERIALIZE`,this.model.name,this.object.type,o);let s=Intl.NumberFormat(`en-US`,{maximumFractionDigits:3,minimumFractionDigits:0,useGrouping:!1});function c(t,n){if(t.some(e=>e&&{position:e.pos,rotation:e.rot,scale:e.scale}[n])){switch(n){case`position`:a.needsTranslate=!0,e.beginBlock(`double3 xformOp:translate.timeSamples = {`,``);break;case`rotation`:a.needsOrient=!0,e.beginBlock(`quatf xformOp:orient.timeSamples = {`,``);break;case`scale`:a.needsScale=!0,e.beginBlock(`double3 xformOp:scale.timeSamples = {`,``);break}for(let a=0;a<t.length;a++){let o=t[a];if(!o)continue;let c=r.getStartTimeByClip(o.clip),l=o.getSortedTimesArray(n===`position`,n===`rotation`,n===`scale`);if(!l||l.length===0){console.error(`got an animated object but no time values?`,i,o);continue}let u=!o.clip,d=n===`position`&&(o.pos||u),f=n===`rotation`&&(o.rot||u),p=n===`scale`&&(o.scale||u);if(d||f||p){let n=o.clip?.name??`rest`,r=o.getDuration();Fs&&console.log(`Write .timeSamples:`,n,c,r,t),e.appendLine(`# `+n+`: start=`+s.format(c*K.frameRate)+`, length=`+s.format(r*K.frameRate)+`, frames=`+o.getFrames())}if(d)for(let{time:t,translation:n}of o.getValues(l,!0,!1,!1)){let r=`${s.format((c+t)*K.frameRate)}: (${W(n.x)}, ${W(n.y)}, ${W(n.z)}),`;e.appendLine(r)}if(f)for(let{time:t,rotation:n}of o.getValues(l,!1,!0,!1)){let r=`${s.format((c+t)*K.frameRate)}: (${W(n.w)}, ${W(n.x)}, ${W(n.y)}, ${W(n.z)}),`;e.appendLine(r)}if(p)for(let{time:t,scale:n}of o.getValues(l,!1,!1,!0)){let r=`${s.format((c+t)*K.frameRate)}: (${W(n.x)}, ${W(n.y)}, ${W(n.z)}),`;e.appendLine(r)}}e.closeBlock()}}c(o,`position`),c(o,`rotation`),c(o,`scale`)}},Bs=D(`debugusdz`),Vs=class e{static getName(e){let t=e.split(`.`).pop(),n=e.split(`.`).slice(0,-1).join(`.`).split(`/`).pop()?.replace(`.`,`_`);return n||=`Audio_`+Math.random().toString(36).substring(2,15),wo(n)+`.`+t}get extensionName(){return`Audio`}files=[];onExportObject(t,n,r){let i=k.getComponents(t,I);if(i.length)for(let t of i){if(!t.clip||typeof t.clip!=`string`||!t.playOnAwake)continue;let i=t.clip.split(`/`).pop()||`Audio`,a=e.getName(t.clip),o=wo(a);if(!this.files.some(e=>e.path===t.clip)){this.files.push({path:t.clip,name:a});let e=a.toLowerCase();r.quickLookCompatible&&!e.endsWith(`.mp3`)&&!e.endsWith(`.wav`)&&!e.endsWith(`.m4a`)&&console.error(`Audio file `+t.clip+` from `+t.name+` is not an MP3 or WAV file. QuickLook may not support playing it.`)}r.quickLookCompatible||n.addEventListener(`serialize`,(e,n)=>{e.appendLine(),e.beginBlock(`def SpatialAudio "${o}"`,`(`,!1),e.appendLine(`displayName = "${i}"`),e.closeBlock(`)`),e.beginBlock(),e.appendLine(`uniform asset filePath = @audio/${a}@`),e.appendLine(`uniform token auralMode = "${t.spatialBlend>0?`spatial`:`nonSpatial`}"`),e.appendLine(`uniform token playbackMode = "${t.loop?`loopFromStage`:`onceFromStart`}"`),e.appendLine(`uniform float gain = ${t.volume}`),e.closeBlock()})}}async onAfterSerialize(e){for(let t of this.files){let n=`audio/`+t.name;if(e.files[n]){Bs&&console.warn(`Audio file with name `+n+` already exists in the context. Skipping.`);continue}let r=await(await(await fetch(t.path)).blob()).arrayBuffer(),i=new Uint8Array(r);e.files[n]=i}}},q=function(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},Hs=D(`debugusdzbehaviours`),Us=class extends N{object;target;duration=1;relativeMotion=!1;coroutine=null;targetPos=new r;targetRot=new Ue;targetScale=new r;onEnable(){this.context.accessibility.updateElement(this,{role:`button`,label:`Move `+(this.object?.name||`object`)+` to `+(this.target?.name||`target`)+` on click`,hidden:!1})}onDisable(){this.context.accessibility.updateElement(this,{hidden:!0})}onDestroy(){this.context.accessibility.removeElement(this)}onPointerEnter(){this.context.input.setCursor(`pointer`)}onPointerExit(){this.context.input.unsetCursor(`pointer`)}onPointerClick(e){let t=this.object?.getComponentsInChildren(vt);if(t)for(let e of t)e.resetVelocities(),e.resetForcesAndTorques();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;let e=Yt(this.object).clone(),t=Yt(this.target).clone(),n=Rn(this.object).clone(),r=Rn(this.target).clone(),i=$t(this.object).clone(),a=$t(this.target).clone(),o=e.distanceTo(t),s=n.angleTo(r),c=i.distanceTo(a);if(o<.01&&s<.01&&c<.01){Xe(this.object,t),xt(this.object,r),mt(this.object,a),this.coroutine=null;return}let l=0,u=0;for(;l<1;)l+=this.context.time.deltaTime/this.duration,l>1&&(l=1),u=l<.5?4*l*l*l:1-(-2*l+2)**3/2,this.targetPos.lerpVectors(e,t,u),this.targetRot.slerpQuaternions(n,r,u),this.targetScale.lerpVectors(i,a,u),Xe(this.object,this.targetPos),xt(this.object,this.targetRot),mt(this.object,this.targetScale),yield;this.coroutine=null}*moveRelative(){if(!this.target||!this.object)return;let e=this.object.position.clone(),t=this.object.quaternion.clone(),n=this.object.scale.clone(),r=this.target.position.clone(),i=this.target.quaternion.clone(),a=this.target.scale.clone();r.applyQuaternion(this.object.quaternion),this.targetPos.copy(this.object.position).add(r),this.targetRot.copy(this.object.quaternion).multiply(i),this.targetScale.copy(this.object.scale).multiply(a);let o=0,s=0;for(;o<1;)o+=this.context.time.deltaTime/this.duration,o>1&&(o=1),s=o<.5?4*o*o*o:1-(-2*o+2)**3/2,this.object.position.lerpVectors(e,this.targetPos,s),this.object.quaternion.slerpQuaternions(t,this.targetRot,s),this.object.scale.lerpVectors(n,this.targetScale,s),yield;this.coroutine=null}beforeCreateDocument(e){if(this.target&&this.object&&this.gameObject){let t=new Es(`Move to `+this.target?.name,js.tapTrigger(this.gameObject),G.transformAction(this.object,this.target,this.duration,this.relativeMotion?`relative`:`absolute`));e.addBehavior(t)}}};q([E(S)],Us.prototype,`object`,void 0),q([E(S)],Us.prototype,`target`,void 0),q([E()],Us.prototype,`duration`,void 0),q([E()],Us.prototype,`relativeMotion`,void 0);var Ws=class e extends N{materialToSwitch;variantMaterial;fadeDuration=0;start(){this._objectsWithThisMaterial=this.objectsWithThisMaterial,T()&&this._objectsWithThisMaterial.length<=0&&console.warn(`ChangeMaterialOnClick: No objects found with material "`+this.materialToSwitch?.name+`"`)}onEnable(){this.context.accessibility.updateElement(this,{role:`button`,label:`Change material to `+(this.variantMaterial?.name||`unknown material`),hidden:!1})}onDisable(){this.context.accessibility.updateElement(this,{hidden:!0})}onDestroy(){this.context.accessibility.removeElement(this)}onPointerEnter(e){this.context.input.setCursor(`pointer`)}onPointerExit(e){this.context.input.unsetCursor(`pointer`)}onPointerClick(e){if(e.use(),this.variantMaterial)for(let e=0;e<this.objectsWithThisMaterial.length;e++){let t=this.objectsWithThisMaterial[e];t.material=this.variantMaterial}}_objectsWithThisMaterial=null;get objectsWithThisMaterial(){return this._objectsWithThisMaterial==null?(this._objectsWithThisMaterial=[],this.variantMaterial&&this.materialToSwitch&&this.context.scene.traverse(e=>{if(e instanceof x)if(Array.isArray(e.material)){for(let t of e.material)if(t===this.materialToSwitch){this.objectsWithThisMaterial.push(e);break}}else (e.material===this.materialToSwitch||Mt(e.material,this.materialToSwitch))&&this.objectsWithThisMaterial.push(e)}),this._objectsWithThisMaterial):this._objectsWithThisMaterial}selfModel;targetModels;static _materialTriggersPerId={};static _startHiddenBehaviour=null;static _parallelStartHiddenActions=[];async beforeCreateDocument(t,n){this.targetModels=[],e._materialTriggersPerId={},e.variantSwitchIndex=0,this.materialToSwitch&&await P.assignTextureLOD(this.materialToSwitch,0),this.variantMaterial&&await P.assignTextureLOD(this.variantMaterial,0)}createBehaviours(t,n,r){this.objectsWithThisMaterial.find(e=>e.uuid===n.uuid)&&this.targetModels.push(n),this.gameObject.uuid===n.uuid&&(this.selfModel=n,this.materialToSwitch&&(e._materialTriggersPerId[this.materialToSwitch.uuid]||(e._materialTriggersPerId[this.materialToSwitch.uuid]=[]),e._materialTriggersPerId[this.materialToSwitch.uuid].push(this)))}afterCreateDocument(t,n){if(!this.materialToSwitch)return;let r=e._materialTriggersPerId[this.materialToSwitch.uuid];if(r){let e={};for(let t of r){let n=t.createVariants();n&&n.length>0&&(e[t.selfModel.uuid]=n)}for(let n of r){let r=[];for(let t in e)t!==n.selfModel.uuid&&r.push(...e[t]);n.createAndAttachBehaviors(t,e[n.selfModel.uuid],r)}}delete e._materialTriggersPerId[this.materialToSwitch.uuid]}createAndAttachBehaviors(t,n,r){let i=[],a=Math.max(0,this.fadeDuration);i.push(G.fadeAction([...this.targetModels,...r],a,!1)),i.push(G.fadeAction(n,a,!0)),t.addBehavior(new Es(`Select_`+this.selfModel.name,js.tapTrigger(this.selfModel),G.parallel(...i))),e._parallelStartHiddenActions.push(...n),e._startHiddenBehaviour||(e._startHiddenBehaviour=new Es(`StartHidden_`+this.selfModel.name,js.sceneStartTrigger(),G.fadeAction(e._parallelStartHiddenActions,a,!1)),t.addBehavior(e._startHiddenBehaviour))}static getMaterialName(e){return wo(e.name||`Material`)+`_`+e.id}static variantSwitchIndex=0;createVariants(){if(!this.variantMaterial)return null;let t=[];for(let n of this.targetModels){let r=n.clone();r.name+=`_Variant_`+ e.variantSwitchIndex+++`_`+e.getMaterialName(this.variantMaterial),r.displayName=r.displayName+`: Variant with material `+this.variantMaterial.name,r.material=this.variantMaterial,r.geometry=n.geometry,r.transform=n.transform,(!n.parent||!n.parent.isEmpty())&&jo.createEmptyParent(n),n.parent&&n.parent.add(r),t.push(r)}return t}};q([E(Ne)],Ws.prototype,`materialToSwitch`,void 0),q([E(Ne)],Ws.prototype,`variantMaterial`,void 0),q([E()],Ws.prototype,`fadeDuration`,void 0);var Gs=class e extends N{target;toggleOnClick=!1;targetState=!0;hideSelf=!0;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,n){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[e.wasVisible]===void 0&&(this.gameObject[e.wasVisible]=this.gameObject.activeSelf),this.target[e.wasVisible]===void 0&&(this.target[e.wasVisible]=this.target.activeSelf),this.stateBeforeCreatingDocument=this.gameObject[e.wasVisible],this.targetStateBeforeCreatingDocument=this.target[e.wasVisible],this.gameObject.visible=!0,this.target.visible=!0)}afterCreateDocument(t,n){if(!this.target)return;this.targetModel=n.document.findById(this.target.uuid);let r=this.selfModel;if(this.selfModel&&this.targetModel){let n=this.selfModel,i=this.targetState;if(this.toggleOnClick)if(i=!this.targetStateBeforeCreatingDocument,!this.selfModelClone.geometry)(!this.selfModel.parent||this.selfModel.parent.isEmpty())&&Mo.createEmptyParent(this.selfModel),this.toggleModel=this.selfModel.deepClone(),this.toggleModel.name+=`_toggle`,this.selfModel.parent.add(this.toggleModel);else{if(!this.gameObject[e.toggleClone]){let t=this.selfModelClone.clone();t.setMatrix(new b),t.name+=`_toggle`+ e.clonedToggleIndex++,r.add(t),this.gameObject[e.toggleClone]=t,console.warn(`USDZExport: Toggle `+this.gameObject.name+` doesn't have geometry. It will be deep cloned and nested behaviours will likely not work.`)}let t=this.gameObject[e.toggleClone];if(!this.gameObject[e.reverseToggleClone]){let t=this.selfModelClone.clone();t.setMatrix(new b),t.name+=`_toggleReverse`+ e.clonedToggleIndex++,r.add(t),this.gameObject[e.reverseToggleClone]=t}this.toggleModel=this.gameObject[e.reverseToggleClone],(!this.toggleModel.geometry||!t.geometry)&&console.error(`triggers without childs and without geometry won't work!`,this,r.geometry),n=t,r.geometry=null,r.material=null}if(!this.toggleModel){let e=[];this.hideSelf&&e.push(G.fadeAction(n,0,!1)),e.push(G.fadeAction(this.targetModel,0,i)),t.addBehavior(new Es(`Toggle_`+n.name+`_ToggleTo`+(i?`On`:`Off`),js.tapTrigger(n),e.length>1?G.parallel(...e):e[0]))}else if(this.toggleOnClick){let e=[];e.push(G.fadeAction(n,0,!1)),e.push(G.fadeAction(this.toggleModel,0,!0)),e.push(G.fadeAction(this.targetModel,0,i)),t.addBehavior(new Es(`Toggle_`+n.name+`_ToggleTo`+(i?`On`:`Off`),js.tapTrigger(n),G.parallel(...e)));let r=[];r.push(G.fadeAction(this.toggleModel,0,!1)),r.push(G.fadeAction(n,0,!0)),r.push(G.fadeAction(this.targetModel,0,!i)),t.addBehavior(new Es(`Toggle_`+n.name+`_ToggleTo`+(i?`Off`:`On`),js.tapTrigger(this.toggleModel),G.parallel(...r)))}let a=[];this.targetStateBeforeCreatingDocument||a.push(this.targetModel),this.stateBeforeCreatingDocument||a.push(r),this.toggleModel&&a.push(this.toggleModel),Ks.add(a,t)}}afterSerialize(t,n){this.gameObject[e.wasVisible]!==void 0&&(this.gameObject.visible=this.gameObject[e.wasVisible],delete this.gameObject[e.wasVisible]),this.target&&this.target[e.wasVisible]!==void 0&&(this.target.visible=this.target[e.wasVisible],delete this.target[e.wasVisible]),delete this.gameObject[e.toggleClone],delete this.gameObject[e.reverseToggleClone]}};q([E(S)],Gs.prototype,`target`,void 0),q([E()],Gs.prototype,`toggleOnClick`,void 0),q([E()],Gs.prototype,`targetState`,void 0),q([E()],Gs.prototype,`hideSelf`,void 0);var Ks=class e extends N{static _fadeBehaviour;static _fadeObjects=[];static add(t,n){let r=Array.isArray(t)?t:[t];for(let t of r)e._fadeObjects.includes(t)||(console.log(`adding hide on start`,t),e._fadeObjects.push(t));e._fadeBehaviour===void 0&&(e._fadeBehaviour=new Es(`HideOnStart`,js.sceneStartTrigger(),G.fadeAction(e._fadeObjects,0,!1)),n.addBehavior(e._fadeBehaviour))}start(){k.setActive(this.gameObject,!1)}createBehaviours(t,n,r){n.uuid===this.gameObject.uuid&&(this.wasVisible||e.add(n,t))}wasVisible=!1;beforeCreateDocument(){this.wasVisible=k.isActiveSelf(this.gameObject)}},qs=class extends N{target;duration=.5;motionType=`bounce`;onEnable(){this.context.accessibility.updateElement(this,{role:`button`,label:`Emphasize `+this.target?.name+` on click`,hidden:!1})}onDisable(){this.context.accessibility.updateElement(this,{hidden:!0})}onDestroy(){this.context.accessibility.removeElement(this)}beforeCreateDocument(){}createBehaviours(e,t,n){if(this.target&&t.uuid===this.gameObject.uuid){let t=new Es(`emphasize `+this.name,js.tapTrigger(this.gameObject),G.emphasize(this.target,this.duration,this.motionType,void 0,`basic`));e.addBehavior(t)}}afterCreateDocument(e,t){}};q([E()],qs.prototype,`target`,void 0),q([E()],qs.prototype,`duration`,void 0),q([E()],qs.prototype,`motionType`,void 0);var Js=class extends N{target;clip=``;toggleOnClick=!1;trigger=`tap`;ensureAudioSource(){if(!this.target){let e=this.gameObject.addComponent(I);e&&(this.target=e,e.spatialBlend=1,e.volume=1,e.loop=!1,e.preload=!0)}}onEnable(){this.context.accessibility.updateElement(this,{role:`button`,label:`Play audio: `+(this.clip||this.target?.clip||`unknown clip`),hidden:!1})}onDisable(){this.context.accessibility.updateElement(this,{hidden:!0})}onDestroy(){this.context.accessibility.removeElement(this)}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,n){if(!(!this.target&&!this.clip)&&t.uuid===this.gameObject.uuid){let n=this.clip?this.clip:this.target?this.target.clip:void 0;if(!n||typeof n!=`string`)return;let r=this.target?this.target.gameObject:this.gameObject;Vs.getName(n);let i=this.target?this.target.volume:1,a=this.target&&this.target.spatialBlend==0?`nonSpatial`:`spatial`,o=!1;this.gameObject.traverse(e=>{e instanceof x&&e.visible&&(o=!0)}),o=!0;let s=e.addAudioClip(n),c=G.playAudioAction(r,s,`play`,i,a);this.target&&this.target.loop&&(c=G.sequence(c).makeLooping());let l=this.name?`_`+this.name:``;if(o&&this.trigger===`tap`){this.toggleOnClick&&(c.multiplePerformOperation=`stop`);let n=new Es(`playAudio`+l,js.tapTrigger(t),c);e.addBehavior(n)}if(this.target&&this.target.playOnAwake&&this.target.enabled)if(o&&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{let t=new Es(`playAudioOnStart`+l,js.sceneStartTrigger(),c);e.addBehavior(t)}}}};q([E(I)],Js.prototype,`target`,void 0),q([E(URL)],Js.prototype,`clip`,void 0),q([E()],Js.prototype,`toggleOnClick`,void 0);var Ys=class e extends N{animator;stateName;trigger=`tap`;animation;get target(){return this.animator?.gameObject||this.animation?.gameObject}onEnable(){this.context.accessibility.updateElement(this,{role:`button`,label:`Plays animation `+(this.stateName||``)+` on `+(this.target?this.target.name:``),hidden:!1})}onDisable(){this.context.accessibility.updateElement(this,{hidden:!0})}onDestroy(){this.context.accessibility.removeElement(this)}onPointerEnter(){this.context.input.setCursor(`pointer`),this.context.accessibility.hover(this,`Click to play animation `+(this.stateName||``)+` on `+(this.target?this.target.name:``))}onPointerExit(){this.context.input.unsetCursor(`pointer`)}onPointerClick(e){e.use(),this.target&&this.stateName&&(this.context.accessibility.focus(this),this.animator?.play(this.stateName,0,0,.1))}selfModel;stateAnimationModel;animationSequence=[];animationLoopAfterSequence=[];randomOffsetNormalized=0;createBehaviours(e,t,n){t.uuid===this.gameObject.uuid&&(this.selfModel=t)}static animationActions=[];static rootsWithExclusivePlayback=new Set;afterSerialize(){if(e.rootsWithExclusivePlayback.size>1){let t=`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.`;T()&&kn(t),console.warn(t,...e.rootsWithExclusivePlayback)}e.animationActions=[],e.rootsWithExclusivePlayback=new Set}afterCreateDocument(t,n){if(this.animationSequence===void 0&&this.animationLoopAfterSequence===void 0||!this.stateAnimationModel||!this.target)return;let r=n.document,i=n.extensions.find(e=>e instanceof Rs);if(!i)return;let a=i.getClipCount(this.target)>1;a&&(T()&&console.warn(`Setting exclusive playback for `+this.target.name+`@`+this.stateName+` because it has `+i.getClipCount(this.target)+` animations. This works around QuickLook bug FB13410767.`),e.rootsWithExclusivePlayback.add(this.target));let o=this.name?this.name:``;r.traverse(n=>{if(n.uuid===this.target?.uuid){let i=e.getActionForSequences(r,n,this.animationSequence,this.animationLoopAfterSequence,this.randomOffsetNormalized),s=new Es(this.trigger+`_`+o+`_toPlayAnimation_`+this.stateName+`_on_`+this.target?.name,this.trigger==`tap`?js.tapTrigger(this.selfModel):js.sceneStartTrigger(),i);a&&s.makeExclusive(!0),t.addBehavior(s)}})}static getActionForSequences(t,n,r,i,a){let o=(t,n)=>{let r=e.animationActions.find(e=>e.affectedObjects==t&&e.start==n.start&&e.duration==n.duration&&e.animationSpeed==n.speed);return r||(r=G.startAnimationAction(t,n),e.animationActions.push(r)),r},s=G.sequence();if(r&&r.length>0)for(let e of r)s.addAction(o(n,e));if(i&&i.length>0){let e=s.actions.length==0?s:G.sequence();for(let t of i)e.addAction(o(n,t));e.makeLooping(),s!==e&&s.addAction(e)}return a&&a>0&&s.actions.unshift(G.waitAction(a)),s}static getAndRegisterAnimationSequences(e,t,n){if(!t)return;let r=t.getComponent(kt),i=t.getComponent(xr);if(!r&&!i)return;if(r&&!n)throw Error(`PlayAnimationOnClick: No stateName specified for animator `+r.name+` on `+t.name);let a=[],o=[];if(i){let n=e.registerAnimation(t,i.clip);n&&(i.loop?o.push(n):a.push(n));let r=0;if(i.minMaxOffsetNormalized){let e=i.minMaxOffsetNormalized.x,t=i.minMaxOffsetNormalized.y;r=(i.clip?.duration||1)*(e+Math.random()*(t-e))}return{animationSequence:a,animationLoopAfterSequence:o,randomTimeOffset:r}}let s=r?.runtimeAnimatorController,c=s?.findState(n),l=[],u=[];if(s&&c){let t=[];t.push(c);let r=!1;for(;t.length<100;){if(!c||c===null||!c.transitions||c.transitions.length===0){c.motion?.isLooping&&(r=!0);break}let e=c.transitions.find(e=>e.conditions.length===0),n=e?s.getState(e.destinationState,0):null;if(n&&t.includes(n)){c=n,r=!0;break}else if(e){if(c=n,!c)break;t.push(c)}else{r=c.motion?.isLooping??!1;break}}if(r&&c){let e=t.indexOf(c);l=t.slice(0,e),u=t.slice(e),Hs&&console.log(`found loop from `+n,`states until loop`,l,`states looping`,u)}else l=t,u=[],Hs&&console.log(`found no loop from `+n,`states`,l);if(!u.length){let t=l[l.length-1],n=t.motion?.clip;if(n){let r;if(e.holdClipMap.has(n))r=e.holdClipMap.get(n);else{let i=t.name+`_hold`;r=n.clone(),r.duration=1,r.name=i;let a=n.duration;r.tracks=n.tracks.map(e=>{let t=e.clone();t.times=new Float32Array([0,a]);let n=e.values.length,r=e.getValueSize(),i=e.values.slice(n-r,n);return t.values=new Float32Array(2*r),t.values.set(i,0),t.values.set(i,r),t}),r.name=i,e.holdClipMap.set(n,r)}if(r){let e={name:r.name,motion:{clip:r,isLooping:!1,name:r.name},speed:1,transitions:[],behaviours:[],hash:t.hash+1};u.push(e)}}}}if(l.length===1&&(!l[0].motion?.clip||l[0].motion?.clip.tracks?.length===0)){a=[];let n=e.registerAnimation(t,null);n&&a.push(n);return}if(l=l.filter(e=>e.motion?.clip&&e.motion?.clip.tracks?.length>0),u=u.filter(e=>e.motion?.clip&&e.motion?.clip.tracks?.length>0),l.length===0&&u.length===0){console.warn(`No clips found for state `+n+` on `+r?.name+`, can't export animation data`);return}let d=(n,i)=>{if(!t)return;let a=e.registerAnimation(t,n.motion.clip??null);a?(a.speed=n.speed,i.push(a)):console.warn(`Couldn't register animation for state `+n.name+` on `+r?.name)};if(l.length>0){a=[];for(let e of l)d(e,a)}if(u.length>0){o=[];for(let e of u)d(e,o)}let f=0;if(r&&s&&r.minMaxOffsetNormalized){let e=r.minMaxOffsetNormalized.x,t=r.minMaxOffsetNormalized.y;f=((l.length?l[0]:u.length?u[0]:null)?.motion.clip?.duration||1)*(e+Math.random()*(t-e))}return{animationSequence:a,animationLoopAfterSequence:o,randomTimeOffset:f}}createAnimation(t,n,r){if(!this.target||!this.animator&&!this.animation)return;let i=e.getAndRegisterAnimationSequences(t,this.target,this.stateName);i&&(this.animationSequence=i.animationSequence,this.animationLoopAfterSequence=i.animationLoopAfterSequence,this.randomOffsetNormalized=i.randomTimeOffset,this.stateAnimationModel=n)}};q([E(kt)],Ys.prototype,`animator`,void 0),q([E()],Ys.prototype,`stateName`,void 0);var Xs=class extends N{getType(){}target;getDuration(){}};q([E(S)],Xs.prototype,`target`,void 0);var Zs=class extends N{target};q([E(Xs)],Zs.prototype,`target`,void 0);var Qs=class extends Xs{type=ec.Hide;duration=1;getType(){switch(this.type){case ec.Hide:return`hide`;case ec.Show:return`show`}}getDuration(){return this.duration}};q([E()],Qs.prototype,`type`,void 0),q([E()],Qs.prototype,`duration`,void 0);var $s=class extends Zs{},ec;(function(e){e[e.Show=0]=`Show`,e[e.Hide=1]=`Hide`})(ec||={});var tc;function nc(e){tc=e}function rc(){if(!tc)return null;let e=tc.find();return e?{handler:e,created:!1}:{handler:tc.create(),created:!0}}var ic=100,ac=200,oc=300,sc=class e{static _instance;static create(){return new e}static getOrCreate(){return 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 un.getOrCreate().createQRCode()}createQuicklookButton(){if(this._quicklookButton)return this._quicklookButton;let e=document.createElement(`button`);this._quicklookButton=e,e.dataset.needle=`quicklook-button`;let t=A.supportsQuickLookAR(),n=`View in AR`;A.isVisionOS()?n=`View in AR`:(t||A.isiOS())&&(n=`Open in Quicklook`),e.innerText=n,e.prepend(Ze(`view_in_ar`)),Ft.setElementPriority(e,ac);let r=!1,i=null;return e.addEventListener(`click`,()=>{let t=rc();t&&(i=t.handler,r=t.created),r&&i&&(i.objectToExport=Xt.Current.scene),i?(e.classList.add(`this-mode-is-requested`),i.exportAndOpen().then(()=>{e.classList.remove(`this-mode-is-requested`)}).catch(t=>{e.classList.remove(`this-mode-is-requested`),console.error(t)})):console.warn(`No USDZExporter component found in the scene`)}),this.hideElementDuringXRSession(e),e}createARButton(e){if(this._arButton)return this._arButton;let t=`immersive-ar`,n=document.createElement(`button`);return this._arButton=n,n.classList.add(`webxr-button`),n.dataset.needle=`webxr-ar-button`,n.innerText=`Enter AR`,n.prepend(Ze(`view_in_ar`)),n.title=`Click to start an AR session`,n.addEventListener(`click`,()=>j.start(t,e)),Ft.setElementPriority(n,oc),this.updateSessionSupported(n,t),this.listenToXRSessionState(n,t),this.hideElementDuringXRSession(n),this.isSecureConnection||(n.disabled=!0,n.title=`WebXR requires a secure connection (HTTPS)`),A.isMozillaXR()||navigator.xr?.addEventListener(`devicechange`,()=>this.updateSessionSupported(n,t)),n}createVRButton(e){if(this._vrButton)return this._vrButton;let t=`immersive-vr`,n=document.createElement(`button`);return this._vrButton=n,n.classList.add(`webxr-button`),n.dataset.needle=`webxr-vr-button`,n.innerText=`Enter VR`,n.prepend(Ze(`panorama_photosphere`)),n.title=`Click to start a VR session`,n.addEventListener(`click`,()=>j.start(t,e)),Ft.setElementPriority(n,ic),this.updateSessionSupported(n,t),this.listenToXRSessionState(n,t),this.hideElementDuringXRSession(n),this.isSecureConnection||(n.disabled=!0,n.title=`WebXR requires a secure connection (HTTPS)`),A.isMozillaXR()||navigator.xr?.addEventListener(`devicechange`,()=>this.updateSessionSupported(n,t)),n}createSendToQuestButton(){if(this._sendToQuestButton)return this._sendToQuestButton;let e=document.createElement(`button`);return this._sendToQuestButton=e,e.dataset.needle=`webxr-sendtoquest-button`,e.innerText=`Open on Quest`,e.prepend(Ze(`share_windows`)),e.title=`Click to send this page to the Oculus Browser on your Quest`,e.addEventListener(`click`,()=>{let e=`https://oculus.com/open_url/?url=`+encodeURIComponent(window.location.href);window.open(e)??vn(`This page doesn't allow popups. Please paste `+e+` into your browser.`)}),this.listenToXRSessionState(e),this.hideElementDuringXRSession(e),A.isMozillaXR()||navigator.xr?.addEventListener(`devicechange`,()=>{navigator.xr?.isSessionSupported(`immersive-vr`)?e.style.display=`none`:e.style.display=``}),e}createQRCode(){return un.getOrCreate().createQRCode()}updateSessionSupported(e,t){if(!(t===`immersive-ar`&&A.isiOS()&&!A.isVisionOS())){if(!(`xr`in navigator)){e.style.display=`none`;return}j.isSessionSupported(t).then(n=>{e.style.display=n?``:`none`,T()&&!n&&console.log(`[WebXR] "`+t+`" is not supported on this device. Make sure your server runs using HTTPS and you have a device connected that supports `+t)})}}hideElementDuringXRSession(e){et(t=>{e[`previous-display`]=e.style.display,e.style.setProperty(`display`,`none`,`important`)}),qn(t=>{e[`previous-display`]!=null&&(e.style.display=e[`previous-display`])})}listenToXRSessionState(e,t){t&&(j.onSessionRequestStart(n=>{n.mode===t?e.classList.add(`this-mode-is-requested`):(e[`was-disabled`]=e.disabled,e.disabled=!0,e.classList.add(`other-mode-is-requested`))}),j.onSessionRequestEnd(t=>{e.classList.remove(`this-mode-is-requested`),e.classList.remove(`other-mode-is-requested`),e.disabled=e[`was-disabled`]}))}},J=function(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},cc=D(`debugspriterenderer`),lc=D(`wireframe`),uc=class e{static cache={};static getOrCreateGeometry(t){if(t.__cached_geometry)return t.__cached_geometry;if(t.guid&&e.cache[t.guid])return cc&&console.log(`Take cached geometry for sprite`,t.guid),e.cache[t.guid];let n=new ie;t.__cached_geometry=n;let r=new Float32Array(t.triangles.length*3),i=new Float32Array(t.triangles.length*2);for(let e=0;e<t.triangles.length;e+=1){let n=t.triangles[e];r[e*3]=-t.vertices[n].x,r[e*3+1]=t.vertices[n].y,r[e*3+2]=0;let a=t.uv[n];i[e*2]=a.x,i[e*2+1]=1-a.y}return n.setAttribute(`position`,new Ge(r,3)),n.setAttribute(`uv`,new Ge(i,2)),t.guid&&(this.cache[t.guid]=n),cc&&console.log(`Built sprite geometry`,t,n),n}},dc;(function(e){e[e.Simple=0]=`Simple`,e[e.Sliced=1]=`Sliced`,e[e.Tiled=2]=`Tiled`})(dc||={});var fc=class{x;y};function pc(e){e&&(e.colorSpace!=`srgb`&&(e.colorSpace=ue,e.needsUpdate=!0),e.minFilter==1003&&e.magFilter==1003&&(e.anisotropy=1,e.needsUpdate=!0))}var mc=class{constructor(e){e&&(this.texture=e,this.triangles=[0,1,2,0,2,3],this.uv=[{x:0,y:0},{x:1,y:0},{x:1,y:1},{x:0,y:1}],this.vertices=[{x:-.5,y:-.5},{x:.5,y:-.5},{x:.5,y:.5},{x:-.5,y:.5}])}guid;texture;triangles;uv;vertices;__cached_geometry;get mesh(){return this._mesh||=new x(uc.getOrCreateGeometry(this),this.material),this._mesh}_mesh;get material(){return this._material||=(this.texture&&pc(this.texture),new v({map:this.texture,color:16777215,side:2,transparent:!0})),this._material}_material;getGeometry(){return uc.getOrCreateGeometry(this)}};J([E()],mc.prototype,`guid`,void 0),J([E(xe)],mc.prototype,`texture`,void 0),J([qt()],mc.prototype,`triangles`,void 0),J([qt()],mc.prototype,`uv`,void 0),J([qt()],mc.prototype,`vertices`,void 0);var hc=Symbol(`spriteOwner`),gc=class{sprites;constructor(){this.sprites=[]}};J([E(mc)],gc.prototype,`sprites`,void 0);var _c=class e{static create(){let t=new e;return t.spriteSheet=new gc,t}constructor(){}clone(){let t=new e;return t.index=this.index,t.spriteSheet=this.spriteSheet,t}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 gc,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;let t=this.index;if(t<0||t>=this.spriteSheet.sprites.length)return;let n=this.spriteSheet.sprites[t],r=n?.texture;if(r&&(pc(r),!n.__hasLoadedProgressive)){n.__hasLoadedProgressive=!0;let t=r;P.assignTextureLOD(r,0).then(r=>{r instanceof xe&&(n.texture=r,e?.map===t&&(e.map=r,e.needsUpdate=!0))})}}};J([E(gc)],_c.prototype,`spriteSheet`,void 0),J([E()],_c.prototype,`index`,void 0);var vc=class extends N{drawMode=dc.Simple;size={x:1,y:1};color;sharedMaterial;transparent=!0;cutoutThreshold=0;castShadows=!1;renderOrder=0;toneMapped=!0;set texture(e){if(!this._spriteSheet)return;let t=this._spriteSheet.spriteSheet?.sprites[this.spriteIndex];t&&(t.texture=e,this.updateSprite())}addSprite(e,t=!1){if(this._spriteSheet||=_c.create(),!this._spriteSheet.spriteSheet)return-1;this._spriteSheet.spriteSheet?.sprites.push(e);let n=this._spriteSheet.spriteSheet?.sprites.length-1;return t&&(this.spriteIndex=n),n}get sprite(){return this._spriteSheet}set sprite(e){if(e!==this._spriteSheet)if(typeof e==`number`){let t=Math.round(e);cc&&console.log(`[SpriteSheet] Set index to `+t+` (was `+this.spriteIndex+`)`,e),this.spriteIndex=t}else e instanceof mc?(this._spriteSheet||=_c.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=_c.create(),cc&&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;let t=this._spriteSheet;if(!t?.spriteSheet?.sprites)return console.warn(`SpriteRenderer has no data or spritesheet assigned...`),!1;let r=t.spriteSheet.sprites[this.spriteIndex];if(!r)return cc&&console.warn(`Sprite not found`,this.spriteIndex,t.spriteSheet.sprites),!1;if(this._currentSprite)this._currentSprite.geometry=uc.getOrCreateGeometry(r),this._currentSprite.material.map=r.texture;else{let e=new v({color:16777215,side:2});if(lc&&(e.wireframe=!0),this.color&&(e.color||=new n,e.color.copy(this.color),e.opacity=this.color.alpha),e.transparent=!0,e.toneMapped=this.toneMapped,e.depthWrite=!1,r.texture&&!e.wireframe){let t=r.texture;t[hc]!==void 0&&t[hc]!==this&&this.spriteFrames>1&&(t=r.texture=t.clone()),t[hc]=this,e.map=t}this.sharedMaterial=e,this._currentSprite=new x(uc.getOrCreateGeometry(r),e),this._currentSprite.renderOrder=Math.round(this.renderOrder),P.assignTextureLOD(e,0)}return this._currentSprite.parent!==this.gameObject&&(this.drawMode===dc.Tiled&&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}};J([E()],vc.prototype,`drawMode`,void 0),J([E(fc)],vc.prototype,`size`,void 0),J([E(tn)],vc.prototype,`color`,void 0),J([E(Ne)],vc.prototype,`sharedMaterial`,void 0),J([E()],vc.prototype,`transparent`,void 0),J([E()],vc.prototype,`cutoutThreshold`,void 0),J([E()],vc.prototype,`castShadows`,void 0),J([E()],vc.prototype,`renderOrder`,void 0),J([E()],vc.prototype,`toneMapped`,void 0),J([E(_c)],vc.prototype,`sprite`,null);var yc=D(`debugwebxr`),bc=new b().makeRotationY(Math.PI),xc=class e extends N{static _eventListeners={};static onPlaced(e){let t=`placed`;return this._eventListeners[t]||(this._eventListeners[t]=[]),this._eventListeners[t].push(e),()=>{let n=this._eventListeners[t].indexOf(e);n>=0&&this._eventListeners[t].splice(n,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 b;_createdPlacementObject=null;_reparentedComponents=[];_placementScene=new ne;_reticle=[];_hits=[];_placementStartTime=-1;_rigPlacementMatrix;_anchor=null;userInput;onEnable(){this.customReticle?.preload()}supportsXR(e){return e===`immersive-ar`}onEnterXR(t){yc&&console.log(`ENTER WEBXR: SessionRoot start...`),this._anchor=null,e._hasPlaced=!1,this.gameObject.updateMatrixWorld(),this._startOffset.copy(this.gameObject.matrixWorld);let n=new S;this._createdPlacementObject=n,n.name=`AR Session Root`,this._placementScene.name=`AR Placement Scene`,this._placementScene.children.length=0;for(let e=this.context.scene.children.length-1;e>=0;e--){let t=this.context.scene.children[e];this._placementScene.add(t)}if(this.context.scene.add(n),this.autoCenter){let e=fn(this._placementScene.children),t=e.getCenter(new r),n=e.getSize(new r),i=new b;i.makeTranslation(t.x,t.y-n.y*.5,t.z),this._startOffset.multiply(i)}this._reparentedComponents.length=0,this._reparentedComponents.push({comp:this,originalObject:this.gameObject}),k.addComponent(n,this);for(let e of this._reticle)dn(e);this._reticle.length=0,this._isPlacing=!0,this.context.input.addEventListener(`pointerup`,this.onPlaceScene,{queue:ct.Early})}onLeaveXR(){this.context.input.removeEventListener(`pointerup`,this.onPlaceScene,{queue:ct.Early}),this.onRevertSceneChanges(),this._anchor=null,e._hasPlaced=!1,this._rigPlacementMatrix=void 0}onUpdateXR(e){if(e.xr.isTrackingImages){for(let e of this._reticle)e.visible=!1;return}if(this._isPlacing){let t=e.xr.rig?.gameObject;t&&t.parent!==this.context.scene&&this.context.scene.add(t);let n=!1;if(e.xr.isPassThrough&&e.xr.controllers.length>0&&!this.autoPlace)for(let t of e.xr.controllers){let r=t.getHitTest();r&&(n=!0,this.updateReticleAndHits(e.xr,t.index,r,e.xr.rigScale))}if(!n){let t=e.xr.getHitTest();t&&this.updateReticleAndHits(e.xr,0,t,e.xr.rigScale)}}else{if(this._anchor&&e.xr.referenceSpace){let t=e.xr.frame.getPose(this._anchor.anchorSpace,e.xr.referenceSpace);if(t&&this.context.time.frame%20==0){let n=e.xr.convertSpace(t.transform),r=this._reticle[0];r&&(r.position.copy(n.position),r.quaternion.copy(n.quaternion),this.onApplyPose(r))}}if(this.arTouchTransform?(this.userInput||=new Sc(this.context),this.userInput?.enable()):this.userInput?.disable(),this.arTouchTransform&&this.userInput?.hasChanged){if(e.xr.rig){let 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,n,r){this._hits[t]=n.hit;let i=this._reticle[t];if(!i){if(this.customReticle)if(this.customReticle.asset)i=Et(this.customReticle.asset);else{this.customReticle.loadAssetAsync();return}else i=new x(new ce(.07,.09,32).rotateX(-Math.PI/2),new v({side:2,depthTest:!1,depthWrite:!1,transparent:!0,opacity:1,color:15658734})),i.name=`AR Placement Reticle`;if(yc){let e=new _e(1);e.position.y+=.01,i.add(e)}this._reticle[t]=i,i.matrixAutoUpdate=!1,i.visible=!1}if(i.lastPos=i.lastPos||n.position.clone(),i.lastQuat=i.lastQuat||n.quaternion.clone(),i.position.copy(i.lastPos.lerp(n.position,this.context.time.deltaTime/.1)),i.lastPos.copy(i.position),i.quaternion.copy(i.lastQuat.slerp(n.quaternion,this.context.time.deltaTime/.05)),i.lastQuat.copy(i.quaternion),i.scale.set(r,r,r),this.customReticle&&this.applyViewBasedTransform(i),i.updateMatrix(),i.visible=!0,i.parent!==this.context.scene&&this.context.scene.add(i),this._placementStartTime<0&&(this._placementStartTime=this.context.time.realtimeSinceStartup),this.autoPlace)if(this.upVec.set(0,1,0).applyQuaternion(i.quaternion),this.upVec.dot(wn(0,1,0))>.9){let e=i[`autoplace:timer`]||0;e>=1?(i.visible=!1,this.onPlaceScene(null)):(e+=this.context.time.deltaTime,i[`autoplace:timer`]=e)}else i[`autoplace:timer`]=0}onPlaceScene=t=>{if(this._isPlacing==0||t?.used)return;let n=this._reticle[0];if(!n){console.warn(`No reticle to place...`);return}if(!n.visible&&!this.autoPlace){console.warn(`Reticle is not visible (can not place)`);return}if(j.active?.isTrackingImages){console.warn(`Scene Placement is disabled while images are being tracked`);return}let r=this._hits[0];if(t&&t.origin instanceof sn){let e=this._reticle[t.origin.index];e&&(n=e,r=this._hits[t.origin.index])}if(t&&(t.stopImmediatePropagation(),t.stopPropagation(),t.use()),this._isPlacing=!1,this.context.input.removeEventListener(`pointerup`,this.onPlaceScene),this.onRevertSceneChanges(),n.position.copy(n.lastPos),n.quaternion.copy(n.lastQuat),this.onApplyPose(n),e._hasPlaced=!0,this.useXRAnchor&&this.onCreateAnchor(j.active,r),this.context.xr)for(let e of this.context.xr.controllers)e.cancelHitTestSource()};onSetScale(){if(!e._hasPlaced)return;let t=j.active?.rig?.gameObject;if(t){let e=j.active?.rigScale||1,n=1/this._arScale*e,r=new b().makeScale(n,n,n).invert();t.matrix.premultiply(r),t.matrix.decompose(t.position,t.quaternion,t.scale)}}onRevertSceneChanges(){for(let 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--){let t=this._placementScene.children[e];this.context.scene.add(t)}this._createdPlacementObject?.removeFromParent();for(let e of this._reparentedComponents)k.addComponent(e.originalObject,e.comp)}async onCreateAnchor(e,t){if(t.createAnchor===void 0){console.warn(`Hit does not support creating an anchor`,t),T()&&kn(`Hit does not support creating an anchor`);return}else{let n=await t.createAnchor(e.viewerPose.transform);e.running&&n&&(this._anchor=n)}}upVec=new r(0,1,0);lookPoint=new r;worldUpVec=new r(0,1,0);applyViewBasedTransform(e){let t=this.context.mainCamera,n=e,r=t.worldPosition,i=n.worldPosition;this.upVec.set(0,1,0).applyQuaternion(e.quaternion);let a=t.worldPosition;a&&e.position.clone().sub(a).angleTo(this.upVec)<Math.PI/2&&this.upVec.negate();let o=this.upVec.angleTo(this.worldUpVec)*180/Math.PI;o>30&&o<150||o<-30&&o>-150?(this.lookPoint.copy(e.position).add(this.upVec),this.lookPoint.y=e.position.y,e.lookAt(this.lookPoint)):(r.y=i.y,e.lookAt(r))}onApplyPose(e){let t=j.active?.rig?.gameObject;if(!t){console.warn(`No rig object to place`);return}let n=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(bc),t.matrix.premultiply(this._startOffset),t.matrix.decompose(t.position,t.quaternion,t.scale),n.add(t)}},Sc=class e{static up=new r(0,1,0);static zero=new r(0,0,0);static one=new r(1,1,1);oneFingerDrag=!0;twoFingerRotate=!0;twoFingerScale=!0;factor=1;context;offset;plane;_scale=1;_hasChanged=!1;get scale(){return this._scale}constructor(t){this.context=t,this.offset=new b,this.plane=new fe,this.plane.setFromNormalAndCoplanarPoint(e.up,e.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:ct.Early}),this.context.input.addEventListener(`pointerdown`,this.onPointerDownLate,{queue:ct.Late}),this.context.input.addEventListener(`pointerup`,this.onPointerUpEarly,{queue:ct.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:ct.Early}),this.context.input.removeEventListener(`pointerdown`,this.onPointerDownLate,{queue:ct.Late}),this.context.input.removeEventListener(`pointerup`,this.onPointerUpEarly,{queue:ct.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++){let n=e.changedTouches[t],r=A.isAndroidDevice()&&n.clientY<window.innerHeight*.1;this.prev.has(n.identifier)||this.prev.set(n.identifier,{ignore:r,x:0,z:0,screenx:0,screeny:0});let i=this.prev.get(n.identifier);if(i){let e=this.getPositionOnPlane(n.clientX,n.clientY);i.x=e.x,i.z=e.z,i.screenx=n.clientX,i.screeny=n.clientY}}};touchEnd=e=>{e.touches.length<=0&&(this._didMultitouch=!1);for(let t=0;t<e.changedTouches.length;t++){let n=e.changedTouches[t];this.prev.delete(n.identifier)}};touchMove=e=>{if(!e.defaultPrevented&&this.isActive){if(e.touches.length===1){if(this._didMultitouch)return;let t=e.touches[0],n=this.prev.get(t.identifier);if(!n||n.ignore)return;let r=this.getPositionOnPlane(t.clientX,t.clientY),i=r.x-n.x,a=r.z-n.z;if(i===0&&a===0)return;this.oneFingerDrag&&this.addMovement(i,a),n.x=r.x,n.z=r.z,n.screenx=t.clientX,n.screeny=t.clientY;return}else if(e.touches.length===2){this._didMultitouch=!0;let t=e.touches[0],n=e.touches[1],r=this.prev.get(t.identifier),i=this.prev.get(n.identifier);if(!r||!i)return;if(this.twoFingerRotate){let e=Math.atan2(t.clientY-n.clientY,t.clientX-n.clientX)-Math.atan2(r.screeny-i.screeny,r.screenx-i.screenx);Math.abs(e)>.001&&this.addRotation(e)}if(this.twoFingerScale){let e=t.clientX-n.clientX,a=t.clientY-n.clientY,o=Math.sqrt(e*e+a*a),s=r.screenx-i.screenx,c=r.screeny-i.screeny,l=o-Math.sqrt(s*s+c*c);Math.abs(l)>2&&this.addScale(l)}r.screenx=t.clientX,r.screeny=t.clientY,i.screenx=n.clientX,i.screeny=n.clientY}}};_raycaster=new _;_intersection=new r;_screenPos=new r;getPositionOnPlane(e,t){let n=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(n),this._raycaster.set(n.position,this._screenPos.sub(n.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 b;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)}},Cc=function(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},wc=D(`debugplayersync`),Tc=class e extends N{static async setupFrom(t,n){let r=w.getOrCreateFromUrl(t);if(!r.asset){let e=await r.loadAssetAsync();e&&k.getOrAddComponent(e,Dc)}let i=new e;i._internalInit(n),i.asset=r;let a=new S;return a.guid=t,k.addComponent(a,i),i}autoSync=!0;asset;onPlayerSpawned;_localInstance;awake(){this.watchTabVisible(),this.onPlayerSpawned||=new Ut}onEnable(){this.context.connection.beginListen(O.RoomStateSent,this.onJoinedRoom),this.context.connection.beginListen(O.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(O.LeftRoom,this.destroyInstance),this.context.connection.isInRoom&&this.onJoinedRoom()}onDisable(){this.context.connection.stopListen(O.RoomStateSent,this.onJoinedRoom),this.context.connection.stopListen(O.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(O.LeftRoom,this.destroyInstance)}onJoinedRoom=()=>{wc&&console.log(`PlayerSync.joinedRoom. autoSync is set to `+this.autoSync),this.autoSync&&this.getInstance()};async getInstance(){if(this._localInstance)return this._localInstance;if(wc&&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);let e=await this._localInstance;if(e){let t=k.getComponentsInChildren(e,Dc);if(wc&&console.log(`PlayerSync.createInstance: found ${t?.length} PlayerState components. Owner: ${this.context.connection.connectionId}`),t?.length){for(let e of t)e.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!`),k.destroySynced(e)}else this._localInstance=void 0,console.warn(`PlayerSync: failed instantiating asset!`);return this._localInstance}destroyInstance=()=>{this._localInstance?.then(e=>{wc&&console.log(`PlayerSync.destroyInstance`,e),rn(e,this.context.connection,!0,{saveInRoom:!1})}),this._localInstance=void 0};watchTabVisible(){window.addEventListener(`visibilitychange`,e=>{if(document.visibilityState===`visible`)for(let e=Dc.all.length-1;e>=0;e--){let t=Dc.all[e];(!t.owner||!this.context.connection.userIsInRoom(t.owner))&&t.doDestroy()}})}};Cc([E()],Tc.prototype,`autoSync`,void 0),Cc([E(w)],Tc.prototype,`asset`,void 0),Cc([E(Ut)],Tc.prototype,`onPlayerSpawned`,void 0);var Ec;(function(e){e.OwnerChanged=`ownerChanged`})(Ec||={});var Dc=class e extends N{static _all=[];static get all(){return e._all}static _local=[];static get local(){return e._local}static getFor(t){if(t instanceof S)return k.getComponentInParent(t,e);if(t instanceof N)return k.getComponentInParent(t.gameObject,e)}static isLocalPlayer(t){return e.getFor(t)?.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;let n=this._callbacks[e].indexOf(t);n>=0&&this._callbacks[e].splice(n,1)}static dispatchEvent(e,t){if(this._callbacks[e])for(let n of this._callbacks[e])n(t)}onOwnerChangeEvent=new Ut;onFirstOwnerChangeEvent=new Ut;hasOwner=!1;owner;dontDestroy=!1;get isLocalPlayer(){return this.owner===this.context.connection.connectionId}onOwnerChange(t,n){wc&&console.log(`PlayerSync.onOwnerChange: ${n} → ${t} (me: ${this.context.connection.connectionId})`);let r=e._local.indexOf(this);r>=0&&e._local.splice(r,1);let i={playerState:this,oldValue:n,newValue:t};if(this.hasOwner||(this.hasOwner=!0,this.onFirstOwnerChangeEvent?.invoke(i)),this.onOwnerChangeEvent?.invoke(i),this.owner===this.context.connection.connectionId){e._local.push(this);let t=new CustomEvent(`local-owner-changed`,{detail:i});this.dispatchEvent(t)}let a=new CustomEvent(`owner-changed`,{detail:i});this.dispatchEvent(a),e.dispatchEvent(Ec.OwnerChanged,a)}awake(){e.all.push(this),wc&&console.log(`Registered new PlayerState`,this.guid,e.all.length-1,e.all),this.context.connection.beginListen(O.UserLeftRoom,this.onUserLeftRoom)}async start(){wc&&console.log(`PLAYERSTATE.START, owner: `+this.owner,this.context.connection.usersInRoom([])),this.owner?(this.context.connection.isInRoom||await Sn(300),this.context.connection.userIsInRoom(this.owner)==0&&(wc&&console.log(`PlayerSync.start → doDestroy \"${this.name}\" because user \"${this.owner}\" is not in room anymore...`,`Currently in room:`,...this.context.connection.usersInRoom()),this.doDestroy())):this.owner||(wc&&console.warn(`PlayerState.start → owner is undefined!`,this.name),setTimeout(()=>{!this.destroyed&&!this.owner?this.dontDestroy?wc&&console.warn(`PlayerState.start → owner is still undefined but dontDestroy is set to true`,this.name):(wc&&console.warn(`PlayerState.start → owner is still undefined: destroying \"${this.name}\" instance now`),this.doDestroy()):wc&&console.log(`PlayerState.start → owner is assigned`,this.owner)},2e3))}doDestroy(){wc&&console.log(`PlayerSync.doDestroy → syncDestroy`,this.name),rn(this.gameObject,this.context.connection,!0,{saveInRoom:!1})}onDestroy(){if(wc&&console.warn(`PlayerState.onDestroy`,this.owner),this.context.connection.stopListen(O.UserLeftRoom,this.onUserLeftRoom),e.all.splice(e.all.indexOf(this),1),this.isLocalPlayer){let t=e._local.indexOf(this);t>=0&&e._local.splice(t,1)}}onUserLeftRoom=e=>{if(e.userId===this.owner){wc&&console.log(`PLAYERSYNC LEFT`,this.owner),this.doDestroy();return}}};Cc([Pr(Dc.prototype.onOwnerChange)],Dc.prototype,`owner`,void 0);var Oc=function(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},kc=class extends N{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&&(A.isMobileDevice()||this.context.menu.showQRCodeButton(!0))}};Oc([E()],kc.prototype,`position`,void 0),Oc([E()],kc.prototype,`showNeedleLogo`,void 0),Oc([E()],kc.prototype,`showSpatialMenu`,void 0),Oc([E()],kc.prototype,`createFullscreenButton`,void 0),Oc([E()],kc.prototype,`createMuteButton`,void 0),Oc([E()],kc.prototype,`createQRCodeButton`,void 0);var Ac=function(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},jc=D(`debugwebxr`),Mc=new Ue().setFromAxisAngle(new r(0,1,0),Math.PI),Nc=class extends N{head;leftHand;rightHand;_leftHandMeshes;_rightHandMeshes;_syncTransforms;async onEnterXR(e){if(!this.activeAndEnabled)return;jc&&console.warn(`AVATAR ENTER XR`,this.guid,this.sourceId,this,this.activeAndEnabled),this._syncTransforms&&(this._syncTransforms.length=0),await this.prepareAvatar();let t=Dc.getFor(this);if(t?.owner){let e=this.gameObject.addComponent(zr);e.avatar=this.gameObject,e.connectionId=t.owner,this.context.players.setPlayerView(t.owner,this.head?.asset,In.Headset)}else this.context.connection.isConnected?console.error(`No player state found for avatar`,this):t&&!this.context.connection.isConnected&&(t.dontDestroy=!0)}onLeaveXR(e){let t=this.gameObject.getComponent(zr);t&&t.destroy()}onUpdateXR(e){if(!this.activeAndEnabled)return;let t=Dc.isLocalPlayer(this);if(!t)return;let n=e.xr;if(n.rig&&n.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),n.rig.gameObject.add(this.gameObject)),this._syncTransforms&&t)for(let e of this._syncTransforms)e.fastMode=!0,e.isOwned()||e.requestOwnership();if(this.head&&this.context.mainCamera){let e=this.head.asset;if(e.position.copy(this.context.mainCamera.position),e.position.x*=-1,e.position.z*=-1,e.quaternion.copy(this.context.mainCamera.quaternion),e.quaternion.x*=-1,this.context.time.frameCount%10==0&&this.head.asset){let e=k.getComponentsInChildren(this.head.asset,fi);for(let t of e)t.enabled=!1,t.gameObject.visible=!1}}let r=e.xr.leftController,i=this.leftHand?.asset;r&&i?(i.position.copy(r.gripPosition),i.quaternion.copy(r.gripQuaternion),i.quaternion.multiply(Mc),i.visible=r.isTracking,this.updateHandVisibility(r,i,this._leftHandMeshes)):i&&i.visible&&(i.visible=!1);let a=e.xr.rightController,o=this.rightHand?.asset;a&&o?(o.position.copy(a.gripPosition),o.quaternion.copy(a.gripQuaternion),o.quaternion.multiply(Mc),o.visible=a.isTracking,this.updateHandVisibility(a,o,this._rightHandMeshes)):o&&o.visible&&(o.visible=!1)}onBeforeRender(){this.context.xr&&this.context.time.frame%10==0&&this.updateRemoteAvatarVisibility()}updateHandVisibility(e,t,n){if(n){let r=e.model&&e.model.visible&&e.model!==t;n.forEach(e=>{wi(e,!r)})}}updateRemoteAvatarVisibility(){if(this.context.connection.isConnected){let e=Dc.getFor(this);if(e&&e.isLocalPlayer==0){let t=j.getXRSync(this.context);if(t&&t.hasState(e.owner)){this.tryFindAvatarObjectsIfMissing();let n=this.leftHand?.asset;n&&(n.visible=t?.isTracking(e.owner,`left`)??!1);let r=this.rightHand?.asset;r&&(r.visible=t?.isTracking(e.owner,`right`)??!1)}if(this.head?.asset){let e=k.getComponentsInChildren(this.head.asset,fi);for(let t of e)t.enabled=!1,t.gameObject.visible=!0}}}}tryFindAvatarObjectsIfMissing(){if(!this.head||!this.leftHand||!this.rightHand){let e={head:this.head,leftHand:this.leftHand,rightHand:this.rightHand};_r.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 S&&(this.head=new w(``,this.sourceId,this.head));else{let e=new S;e.name=`Head`;let t=St.createPrimitive(Tt.Cube);e.add(t),this.gameObject.add(e),this.head=new w(``,this.sourceId,e),jc&&console.log(`Create head`,e)}if(this.rightHand)this.rightHand instanceof S&&(this.rightHand=new w(``,this.sourceId,this.rightHand));else{let e=new S;e.name=`Right Hand`,this.gameObject.add(e),this.rightHand=new w(``,this.sourceId,e),jc&&console.log(`Create right hand`,e)}if(this.leftHand)this.leftHand instanceof S&&(this.leftHand=new w(``,this.sourceId,this.leftHand));else{let e=new S;e.name=`Left Hand`,this.gameObject.add(e),this.leftHand=new w(``,this.sourceId,e),jc&&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)}),Dc.isLocalPlayer(this.gameObject)&&(this._syncTransforms=k.getComponentsInChildren(this.gameObject,Ot))}async loadAvatarObjects(e,t,n){let r=e.loadAssetAsync(),i=t.loadAssetAsync(),a=n.loadAssetAsync(),o=[];r&&o.push(r),i&&o.push(i),a&&o.push(a);let s=await Fn(o);jc&&console.log(`Avatar loaded results:`,s)}};Ac([E(w)],Nc.prototype,`head`,void 0),Ac([E(w)],Nc.prototype,`leftHand`,void 0),Ac([E(w)],Nc.prototype,`rightHand`,void 0);var Pc=D(`debugdecoders`),Fc=null;function Ic(){if(!Fc){let e=ir(null);Fc={dracoLoader:e.dracoLoader,ktx2Loader:e.ktx2Loader,meshoptDecoder:e.meshoptDecoder}}return Fc}function Lc(e){e!==void 0&&typeof e==`string`&&or(e)}function Rc(e){if(e!==void 0&&typeof e==`string`&&e!==`js`){let t=Ic();Pc&&console.log(`Setting draco decoder type to`,e),t.dracoLoader.setDecoderConfig({type:e})}}function zc(e){e!==void 0&&typeof e==`string`&&nr(e)}function Bc(e,t){let n=Ic();return t.renderer?n.ktx2Loader.detectSupport(t.renderer):console.warn(`No renderer provided to detect ktx2 support - loading KTX2 textures will probably fail`),rr(e),e.dracoLoader||e.setDRACOLoader(n.dracoLoader),e.ktx2Loader||e.setKTX2Loader(n.ktx2Loader),e.meshoptDecoder||e.setMeshoptDecoder(n.meshoptDecoder),tr(e,{progressive:!0}),e}var Vc=function(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},Hc=D(`debugwebxr`),Uc=[],Wc=class extends N{createControllerModel=!0;createHandModel=!0;customLeftHand;customRightHand;static factory=new Xn;supportsXR(e){return e===`immersive-vr`||e===`immersive-ar`}_models=[];async onXRControllerAdded(e){if(!(e.xr.isVR||e.xr.isPassThrough))return;console.debug(`XR Controller Added`,e.controller.side,e.controller.index);let{controller:t}=e;if(this.createControllerModel||this.createHandModel){if(t.hand){if(this.createHandModel){let e=await this.loadHandModel(this,t);if(!e||!t.connected||!t.isHand){e?.handObject&&Bt(e.handObject,!1),e?.handObject?.destroy();return}this._models.push({controller:t,model:e.handObject,handmesh:e.handmesh}),this._models.sort((e,t)=>e.controller.index-t.controller.index),this.scene.add(e.handObject),t.model=e.handObject}}else if(this.createControllerModel){let e=await t.getModelUrl();if(e){let n=await this.loadModel(t,e);if(!n||!t.connected||t.isHand)return;this._models.push({controller:t,model:n}),this._models.sort((e,t)=>e.controller.index-t.controller.index),this.scene.add(n),n.traverse(e=>{e.layers.set(2),e.matrixAutoUpdate=!1,e.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);let t=this._models.findIndex(t=>t.controller===e.controller),n=this._models[t];n&&(this._models.splice(t,1),n.model&&=(Bt(n.model,!1),n.model.destroy(),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(let e of this._models)e&&(e.model&&=(Bt(e.model,!1),e.model.destroy(),void 0),e.controller.model===e.model&&(e.controller.model=null));this._models.length=0}onBeforeRender(){if(j.active&&(Hc&&(Uc[0]=Date.now()),this.updateRendering(j.active),Hc)){let e=Date.now()-Uc[0];Uc.push(e),Uc.length>=30&&(Uc[0]=0,Uc.reduce((e,t)=>e+t,0)/Uc.length,Uc.length=0)}}updateRendering(e){for(let t=0;t<this._models.length;t++){let n=this._models[t];if(!n)continue;let r=n.controller;if(!r.connected){Hc&&console.warn(`XRControllerModel.onUpdateXR: controller is not connected anymore`,r.side,r.hand);continue}if(n.model&&!n.handmesh)n.model.matrixAutoUpdate=!1,n.model.matrix.copy(r.gripMatrix),n.model.visible=r.isTracking,e.rig?.gameObject.add(n.model);else if(r.inputSource.hand&&n.handmesh){let t=e.referenceSpace,i=this.context.renderer.xr.getHand(r.index);if(t&&e.frame.getJointPose){for(let e of r.inputSource.hand.values()){let t=i.joints[e.jointName];if(t){let n=r.getHandJointPose(e);if(n){let e=n.transform.position,r=n.transform.orientation;t.position.copy(e),t.quaternion.copy(r),t.matrixAutoUpdate=!1}t.visible=n!=null}}n.model&&(n.model.visible=r.isTracking,n.model.visible&&n.model.parent!==e.rig?.gameObject&&e.rig?.gameObject.add(n.model)),n.model?.visible&&(n.handmesh?.updateMesh(),n.model.matrixAutoUpdate=!1,n.model.matrix.identity(),n.model.applyMatrix4(an))}}}}async loadModel(e,t){if(!e.connected)return console.warn(`XRControllerModel.onXRControllerAdded: controller is not connected anymore`,e.side),null;let n=await w.getOrCreate(``,t).instantiate();return Bt(n),j.active?.isPassThrough&&n.traverseVisible(e=>{this.makeOccluder(e)}),n}async loadHandModel(e,t){let n=this.context,r=n.renderer.xr.getHand(t.index);r||(Hc?Ln.DrawLabel(t.rayWorldPosition,`No hand found for index `+t.index,.05,5):console.warn(`No hand found for index `+t.index));let i=new sr;Bc(i,n),await Ua(i,n,this.sourceId??``,this.sourceId??``);let a=Va(i),o=``,s=t.side===`left`?this.customLeftHand:this.customRightHand;s?(o=s.url.split(`.`).slice(0,-1).join(`.`),i.setPath(``)):(o=t.inputSource.handedness===`left`?`left`:`right`,i.setPath(`https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles/generic-hand/`));let c=new S;Bt(c);let l=new er(c,r,i.path,o,i,n=>{let r=a?.gltf;r?.scene.children?.length===0&&(r.scene.children[0]=n),a?.gltf&&ot().createBuiltinComponents(e.context,e.sourceId||o,a.gltf,null,a),n.traverse(e=>{e.layers.set(2),j.active?.isPassThrough&&!s&&this.makeOccluder(e),e instanceof x&&P.assignMeshLOD(e,0)}),t.connected||(Hc&&Ln.DrawLabel(t.rayWorldPosition,`Hand is loaded but not connected anymore`,.05,5),n.removeFromParent())});if(Hc&&c.add(new _e(.5)),t.inputSource.hand){Hc&&console.log(t.inputSource.hand);for(let e of t.inputSource.hand.values())if(r.joints[e.jointName]===void 0){let t=new ve;t.matrixAutoUpdate=!1,t.visible=!0,r.joints[e.jointName]=t,r.add(t)}}else Hc&&Ln.DrawLabel(t.rayWorldPosition,`No inputSource.hand found for index `+t.index,.05,5);return{handObject:c,handmesh:l}}makeOccluder(e){if(e instanceof x){let t=e.material;t instanceof Ne&&(t=e.material=t.clone(),t.depthWrite=!0,t.depthTest=!0,t.colorWrite=!1,e.receiveShadow=!1,e.renderOrder=-100)}}};Vc([E()],Wc.prototype,`createControllerModel`,void 0),Vc([E()],Wc.prototype,`createHandModel`,void 0),Vc([E(w)],Wc.prototype,`customLeftHand`,void 0),Vc([E(w)],Wc.prototype,`customRightHand`,void 0);var Gc=class extends N{},Kc=function(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},qc=D(`debugwebxr`),Jc=class extends N{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){let t=e.xr.rig;if(!t?.gameObject||e.xr.isPassThrough)return;let n=e.xr.leftController,r=e.xr.rightController;n&&this.onHandleMovement(n,t.gameObject),r&&(this.onHandleRotation(r,t.gameObject),this.useTeleport&&this.onHandleTeleport(r,t.gameObject))}onLeaveXR(e){for(let e of this._lines)e.removeFromParent();for(let e of this._hitDiscs)e?.removeFromParent()}onBeforeRender(){this.context.xr?.running&&(this.showRays&&this.renderRays(this.context.xr),this.showHits&&this.renderHits(this.context.xr))}onHandleMovement(e,t){let n=e.getStick(`xr-standard-thumbstick`);if(n.x!=0||n.y!=0){let r=wn(n.x,0,n.y);r.multiplyScalar(this.context.time.deltaTimeUnscaled*this.movementSpeed);let i=$t(t);r.multiplyScalar(i.x),r.applyQuaternion(e.xr.poseOrientation),r.y=0,r.applyQuaternion(t.worldQuaternion),T()&&Number.isNaN(r.x)&&console.error(`Stick movement resulted in NaN`,{stick:n,vec:r}),t.position.add(r),t.updateWorldMatrix(!1,!1);for(let e of t.children)e.updateWorldMatrix(!1,!1)}}onHandleRotation(e,t){if(e._isMxInk)return;let n=e.getStick(`xr-standard-thumbstick`).x;if(this._didApplyRotation)Math.abs(n)<.3&&(this._didApplyRotation=!1);else if(Math.abs(n)>.5){this._didApplyRotation=!0;let e=n>0?1:-1,r=Yt(this.context.mainCamera).clone();t.rotateY(e*Rt.toRadians(this.rotationStep));let i=Yt(this.context.mainCamera).clone().sub(r);i.y=0,t.position.sub(i)}}_teleportBuffer=[];onHandleTeleport(e,t){let n=0;if(e.hand&&this.usePinchToTeleport&&e.isTeleportGesture){let t=e.getPointerId(`primary`);if(t!=null&&this.context.input.getIsPointerIdInUse(t))return;let r=e.getGesture(`pinch`);r&&(n=r.value)}else n=e.getStick(`xr-standard-thumbstick`)?.y;if(this._didTeleport)(n>=0&&n<.4||n<0&&n>-.4)&&(this._didTeleport=!1);else if(n>.8){this._didTeleport=!0;let n=this.context.physics.raycastFromRay(e.ray)[0];if(n&&n.object instanceof $n){let e=n.normal?.dot(wn(0,1,0));if(e!==void 0&&e<.4)return}let i=n?.point;if(!i&&!this.useTeleportTarget){this._plane||=new fe(new r(0,1,0),0);let n=t.worldPosition;this._plane.setFromNormalAndCoplanarPoint(new r(0,1,0),n);let a=e.ray;i=n.clone(),this._plane.intersectLine(new ee(a.origin,wn(a.direction).multiplyScalar(1e4).add(a.origin)),i),i.distanceTo(n)>t.scale.x*10&&(i=null)}if(i){if(this.useTeleportTarget&&!k.getComponentInParent(n.object,Gc))return;let r=i.clone();if(qc&&Ln.DrawSphere(i,.025,16711680,5),this.context.mainCamera?.position){let e=this.context.xr?.getUserOffsetInRig();e&&(e.y=0,r.sub(e),qc&&Ln.DrawWireSphere(e.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(n<-.8&&(this._didTeleport=!0,this._teleportBuffer.length>0)){let e=this._teleportBuffer.pop();e&&e.decompose(t.position,t.quaternion,t.scale)}}_plane=null;_lines=[];_hitDiscs=[];_hitDistances=[];_lastHitDistances=[];renderRays(e){for(let e=0;e<this._lines.length;e++){let t=this._lines[e];t&&(t.visible=!1)}for(let t=0;t<e.controllers.length;t++){let n=e.controllers[t],r=this._lines[t];if(!n.connected||!n.isTracking||!n.ray||n.targetRayMode===`transient-pointer`||!n.hasSelectEvent){r&&(r.visible=!1);continue}r||(r=this.createRayLineObject(),r.scale.z=.5,this._lines[t]=r),n.updateRayWorldPosition(),n.updateRayWorldQuaternion();let i=n.rayWorldPosition,a=n.rayWorldQuaternion;r.position.copy(i),r.quaternion.copy(a);let o=e.rigScale,s=this.usePinchToTeleport&&n.isTeleportGesture,c=this._lastHitDistances[t],l=this._hitDistances[t]!=null,u=c??o;r.scale.set(o,o,u),r.visible=!0,r.layers.disableAll(),r.layers.enable(2);let d=r.material.opacity;d=s?1:this.showHits&&u<e.rigScale*.5?0:n.getButton(`primary`)?.pressed?.5:l?.2:.1,r.material.opacity=Rt.lerp(r.material.opacity,d,this.context.time.deltaTimeUnscaled/.1),r.parent!==this.context.scene&&this.context.scene.add(r)}}renderHits(e){for(let e of this._hitDiscs){if(!e)continue;let t=e.controller;if(!t||!t.connected||!t.isTracking){e.visible=!1;continue}}for(let t=0;t<e.controllers.length;t++){let n=e.controllers[t];if(!n.connected||!n.isTracking||!n.ray||!n.hasSelectEvent)continue;let r=this._hitDiscs[t],i=!0,a=n.getPointerId(`primary`);a!=null&&this.context.input.getIsPointerIdInUse(a)&&(r&&(r.visible=!1),this._hitDistances[t]=null,this._lastHitDistances[t]=0,i=!1);let o=this.context.time.smoothedFps>=59?1:10;if((this.context.time.frame+n.index)%o!==0&&(i=!1),!i){let e=this._hitDiscs[t];e&&e.visible&&e.hit&&this.updateHitPointerPosition(n,e,e.hit.distance);continue}let s=this.context.physics.raycastFromRay(n.ray,{testObject:this.hitPointRaycastFilter,precise:!1}),c=s.find(e=>this.usePinchToTeleport&&n.isTeleportGesture?!0:this.isObjectWithInteractiveComponent(e.object));if(c||=s[0],r&&(r.controller=n,r.hit=c),this._hitDistances[t]=c?.distance||null,c){this._lastHitDistances[t]=c.distance;let i=e.rigScale??1;qc&&(Ln.DrawWireSphere(c.point,.025*i,16711680),Ln.DrawLabel(wn(0,.2,0).add(c.point),c.object.name,.02,0)),r||(r=this.createHitPointObject(),this._hitDiscs[t]=r),r.hit=c,r.visible=c.distance>i*.05;let a=.01*(i+c.distance),o=n.getButton(`primary`)?.pressed;o&&(a*=1.1),r.scale.set(a,a,a),r.layers.set(2);let s=r.material.opacity;if(s=o?1:c.distance<.15*i?.2:.6,r.material.opacity=Rt.lerp(r.material.opacity,s,this.context.time.deltaTimeUnscaled/.1),r.visible){if(c.normal){this.updateHitPointerPosition(n,r,c.distance);let e=c.normal.applyQuaternion(Rn(c.object));r.quaternion.setFromUnitVectors(Yc,e)}else this.updateHitPointerPosition(n,r,c.distance);r.parent!==this.context.scene&&this.context.scene.add(r)}}else this._hitDiscs[t]&&(this._hitDiscs[t].visible=!1)}}isObjectWithInteractiveComponent(e,t=0){return Ct(e)||e.isUI===!0?!0:e.isScene?!1:e.parent?this.isObjectWithInteractiveComponent(e.parent,t+1):!1}updateHitPointerPosition(e,t,n){let r=wn(e.rayWorldPosition);r.add(wn(0,0,n-.01).applyQuaternion(e.rayWorldQuaternion)),t.position.lerp(r,this.context.time.deltaTimeUnscaled/.05)}hitPointRaycastFilter=e=>e.type===`SkinnedMesh`?`continue in children`:!0;createHitPointObject(){let e=new x(new Ve(.3,6,6),new v({color:15658734,opacity:.7,transparent:!0,depthTest:!1,depthWrite:!1,side:2}));return e.layers.disableAll(),e.layers.enable(2),e}createRayLineObject(){let e=new Zn;e.layers.disableAll(),e.layers.enable(2);let t=new Yn;e.geometry=t;let n=new Float32Array(9);n.set([0,0,.02,0,0,.4,0,0,1]),t.setPositions(n);let r=new Float32Array(9);return r.set([1,1,1,.1,.1,.1,0,0,0]),t.setColors(r),e.material=new Qn({color:16777215,vertexColors:!0,worldUnits:!0,linewidth:.004,transparent:!0,depthWrite:!1,blending:2,dashed:!1}),e}};Kc([E()],Jc.prototype,`movementSpeed`,void 0),Kc([E()],Jc.prototype,`rotationStep`,void 0),Kc([E()],Jc.prototype,`useTeleport`,void 0),Kc([E()],Jc.prototype,`usePinchToTeleport`,void 0),Kc([E()],Jc.prototype,`useTeleportTarget`,void 0),Kc([E()],Jc.prototype,`useTeleportFade`,void 0),Kc([E()],Jc.prototype,`showRays`,void 0),Kc([E()],Jc.prototype,`showHits`,void 0);var Yc=new r(0,1,0),Y=function(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},Xc=D(`debugwebxr`),Zc=D(`debugusdz`),X=class e extends N{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(){j.getXRSync(this.context)}onEnable(){window.location.protocol!==`https:`&&kn(`<a href="https://developer.mozilla.org/en-US/docs/Web/API/WebXR_Device_API" target="_blank">WebXR</a> only works on secure connections (https).`),navigator.xr?.isSessionSupported(`immersive-ar`).catch(()=>!1).then(e=>{let t=A.isVisionOS()&&!e;(this.useQuicklookExport||t)&&(k.findObjectOfType($)||(Xc&&console.log(`WebXR: Adding USDZExporter`),this._usdzExporter=k.addComponent(this.gameObject,$),this._usdzExporter.objectToExport=this.context.scene,this._usdzExporter.autoExportAnimations=!0,this._usdzExporter.autoExportAudioSources=!0))}),this.handleCreatingHTML(),this.handleOfferSession(),this.defaultAvatar===!0&&(Xc&&console.warn(`WebXR: No default avatar set, using static default avatar`),this.defaultAvatar=new w(`https://cdn.needle.tools/static/avatars/DefaultAvatar.glb`)),this.defaultAvatar&&(this._playerSync=this.gameObject.getOrAddComponent(Tc),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 j.isVRSupported()&&this.createVRButton?j.offerSession(`immersive-vr`,`default`,this.context):this.createARButton&&await j.isARSupported()&&this.createARButton?j.offerSession(`immersive-ar`,`default`,this.context):!1}get session(){return j.active??null}get sessionMode(){return j.activeMode??null}get arSessionRoot(){return this._activeWebARSessionRoot}async enterVR(e){return j.start(`immersive-vr`,e,this.context)}async enterAR(e){return j.start(`immersive-ar`,e,this.context)}exitXR(){j.stop()}_exitXRMenuButton;_previousXRState=0;_spatialGrabRaycaster;_activeWebARSessionRoot=null;get isActiveWebXR(){return!e.activeWebXRComponent||e.activeWebXRComponent===this}onBeforeXR(t,n){if(!this.isActiveWebXR){console.warn(`WebXR: another WebXR component is already active (${e.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}e.activeWebXRComponent=this,t==`immersive-ar`&&this.useDepthSensing&&(n.optionalFeatures=n.optionalFeatures||[],n.optionalFeatures.push(`depth-sensing`))}async onEnterXR(e){if(!this.isActiveWebXR)return;Xc&&console.log(`WebXR onEnterXR`),this._previousXRState=di.Global.Mask;let t=e.xr.isVR;if(di.Global.Set(t?ui.VR:ui.AR),e.xr.isAR){let e=k.findObjectOfType(xc,this.context,!1);if(!e)if(this.usePlacementReticle){let t=new S;for(let e of this.context.scene.children)t.add(e);this.context.scene.add(t),e=k.addComponent(t,xc),this._createdComponentsInSession.push(e)}else (Xc||T())&&console.warn(`WebXR: No WebARSessionRoot found in scene and usePlacementReticle is disabled in WebXR component.`);this._activeWebARSessionRoot=e,e&&(e.customReticle=this.customARPlacementReticle,e.arScale=this.arScale,e.arTouchTransform=this.usePlacementAdjustment,e.autoPlace=this.autoPlace,e.autoCenter=this.autoCenter,e.useXRAnchor=this.useXRAnchor)}this.useDefaultControls&&this.setDefaultMovementEnabled(!0),(this.showControllerModels||this.showHandModels)&&this.setDefaultControllerRenderingEnabled(!0),this.useSpatialGrab&&(this._spatialGrabRaycaster=k.findObjectOfType(cn)??void 0,this._spatialGrabRaycaster||=this.gameObject.addComponent(cn)),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(t){if(this._exitXRMenuButton?.remove(),this.isActiveWebXR){di.Global.Set(this._previousXRState),this._playerSync?.destroyInstance();for(let e of this._createdComponentsInSession)e.destroy();this._createdComponentsInSession.length=0,this._activeWebARSessionRoot=null,this.handleOfferSession(),jn(1).then(()=>e.activeWebXRComponent=null)}}setDefaultMovementEnabled(e){let t=this.gameObject.getComponent(Jc);return!t&&e&&(t=this.gameObject.addComponent(Jc),this._createdComponentsInSession.push(t)),t&&(t.enabled=e),t}setDefaultControllerRenderingEnabled(e){let t=this.gameObject.getComponent(Wc);return!t&&e&&(t=this.gameObject.addComponent(Wc),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=>{Xc&&console.log(`WebXR.onAvatarSpawned`,e);let t=k.getComponentInChildren(e,Nc);t??=k.addComponent(e,Nc)};getButtonsContainer(){return this.getButtonsFactory()}getButtonsFactory(){return this._buttonFactory||=sc.getOrCreate(),this._buttonFactory}_buttonFactory;handleCreatingHTML(){if(this.createARButton||this.createVRButton||this.useQuicklookExport){if((A.isiOS()&&A.isSafari()||Zc)&&this.useQuicklookExport){let e=k.findObjectOfType($);if(!e||e&&e.allowCreateQuicklookButton){let e=this.getButtonsFactory().createQuicklookButton();this.addButton(e)}}if(this.createARButton){let e=this.getButtonsFactory().createARButton();this.addButton(e)}if(this.createVRButton){let e=this.getButtonsFactory().createVRButton();this.addButton(e)}}if(this.createSendToQuestButton&&!A.isQuest()&&j.isVRSupported().then(e=>{if(!e){let e=this.getButtonsFactory().createSendToQuestButton();this.addButton(e)}}),this.createQRCode){let e=Zt(kc);if(e&&e.createQRCodeButton===!1)T()&&console.warn(`WebXR: QRCode button is disabled in the Needle Menu component`);else if(!A.isMobileDevice()){let e=un.getOrCreate().createQRCode();this.addButton(e)}}}_buttons=[];addButton(e){this._buttons.push(e),this.context.menu.appendChild(e)}removeButtons(){for(let e of this._buttons)e.remove();this._buttons.length=0}};Y([E()],X.prototype,`createVRButton`,void 0),Y([E()],X.prototype,`createARButton`,void 0),Y([E()],X.prototype,`createSendToQuestButton`,void 0),Y([E()],X.prototype,`createQRCode`,void 0),Y([E()],X.prototype,`useDefaultControls`,void 0),Y([E()],X.prototype,`showControllerModels`,void 0),Y([E()],X.prototype,`showHandModels`,void 0),Y([E()],X.prototype,`usePlacementReticle`,void 0),Y([E(w)],X.prototype,`customARPlacementReticle`,void 0),Y([E()],X.prototype,`usePlacementAdjustment`,void 0),Y([E()],X.prototype,`arScale`,void 0),Y([E()],X.prototype,`useXRAnchor`,void 0),Y([E()],X.prototype,`autoPlace`,void 0),Y([E()],X.prototype,`autoCenter`,void 0),Y([E()],X.prototype,`useQuicklookExport`,void 0),Y([E()],X.prototype,`useDepthSensing`,void 0),Y([E()],X.prototype,`useSpatialGrab`,void 0),Y([E(w)],X.prototype,`defaultAvatar`,void 0);var Qc=D(`debugusdzbehaviours`),$c=class{get extensionName(){return`Behaviour`}behaviours=[];addBehavior(e){this.behaviours.push(e)}addAudioClip(e){if(!e||typeof e!=`string`)return``;let t=`audio/`+Vs.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();let t=[];return e.root.traverse(n=>{k.foreachComponent(n,n=>{let r=n;if(typeof r.createBehaviours==`function`||typeof r.beforeCreateDocument==`function`||typeof r.afterCreateDocument==`function`||typeof r.afterSerialize==`function`){this.behaviourComponents.push(r);let n=r.beforeCreateDocument?.call(r,this,e);n instanceof Promise&&t.push(n)}},!1)}),Qc&&console.log(`onBeforeBuildDocument: all components`,this.behaviourComponents),Promise.all(t)}onExportObject(e,t,n){for(let e of this.behaviourComponents)e.createBehaviours?.call(e,this,t,n)}onAfterBuildDocument(e){for(let t of this.behaviourComponents)typeof t.afterCreateDocument==`function`&&t.afterCreateDocument(this,e);this.behaviourComponentsCopy=this.behaviourComponents.slice(),this.behaviourComponents.length=0,this.audioClipsCopy=this.audioClips.slice(),this.audioClips.length=0;let t=new Set,n=new Set,r=new Set,i=new Set,a=Qc,o=`graph LR
|
||
`,s=``;function c(e){if(e instanceof Ms){a&&(o+=`subgraph Group_${e.id}\n`);for(let t of e.actions)a&&(o+=`${e.id}[${e.id}] -- ${e.type},loops:${e.loops} --> ${t.id}[${t.id}]\n`),c(t);a&&(o+=`end
|
||
`)}else if(e instanceof Ns){e.tokenId===`StartAnimation`&&i.add(e);let t=e.tokenId;e.type!==void 0&&(t+=`:`+e.type);let r=e.affectedObjects;if(r)if(Array.isArray(r))for(let i of r)n.add(i),a&&(s+=`${e.id}[${e.id}\n${t}] -- ${t} --> ${i.uuid}(("${i.displayName||i.name||i.uuid}"))\n`);else typeof r==`object`?(n.add(r),a&&(s+=`${e.id}[${e.id}\n${t}] -- ${t} --> ${r.uuid}(("${r.displayName||r.name||r.uuid}"))\n`)):typeof r==`string`&&n.add({uuid:r});let o=e.xFormTarget;o&&(typeof o==`object`?(n.add(o),a&&(s+=`${e.id}[${e.id}\n${t}] -- ${t} --> ${o.uuid}(("${o.displayName||o.name||o.uuid}"))\n`)):typeof o==`string`&&n.add({uuid:o}))}}function l(e,n){if(Array.isArray(e))for(let t of e)l(t,n);else if(e instanceof ks){let r=e.tokenId;e.type!==void 0&&(r+=`:`+e.type),typeof e.targetId==`object`&&(t.add(e.targetId),a&&(s+=`${e.targetId.uuid}(("${e.targetId.displayName}")) --> ${e.id}[${e.id}\n${r}]\n`)),a&&(o+=`${e.id}((${e.id})) -- ${r} --> ${n.id}[${n.tokenId||n.id}]\n`)}}for(let e of this.behaviours)a&&(o+=`subgraph ${e.id}\n`),c(e.action),l(e.trigger,e.action),a&&(o+=`end
|
||
`);a&&(o+=`
|
||
`+s),a&&(console.log(`All USDZ behaviours`,this.behaviours),this.behaviours.length&&(console.warn(`The Mermaid graph can be pasted into https://massive-mermaid.glitch.me/ or https://mermaid.live/edit. It should be in your clipboard already!`),console.log(o),navigator.clipboard.writeText(o)));{let e=`gantt
|
||
title Animations
|
||
dateFormat X
|
||
axisFormat %s
|
||
`,t=Array.from(i),n=new Set;for(let r of t)if(r.affectedObjects&&typeof r.affectedObjects!=`string`){if(Array.isArray(r.affectedObjects))for(let e of r.affectedObjects)n.add(e);else n.add(r.affectedObjects);a&&(e+=`section ${r.animationName} (${r.id})\n`,e+=`${r.id} : ${r.start}, ${r.duration}s\n`)}a&&i.size&&console.log(e);let r=new Set;for(let e of n){e.getPath||console.error(`USDZExporter: Animation target object has no getPath method. This is likely a bug`,e);let t=e.getPath();t.startsWith(`<`)&&(t=t.substring(1)),t.endsWith(`>`)&&(t=t.substring(0,t.length-1)),r.add({path:t,obj:e})}let o=Array.from(r).sort((e,t)=>e.path.length-t.path.length),s=[];for(let e=0;e<o.length;e++)for(let t=e+1;t<o.length;t++)if(o[t].path.startsWith(o[e].path)){let n=o[t],r=o[e];s.push({child:n.obj.displayName+` (`+n.path+`)`,parent:r.obj.displayName+` (`+r.path+`)`})}s.length&&console.warn(`USDZExporter: There are overlapping PlayAnimation actions. This can lead to undefined runtime behaviour when playing multiple animations. Please restructure the hierarchy so that animations don't overlap.`,{overlappingTargets:s,playAnimationActions:i})}for(let e of new Set([...t,...n]))if(Array.isArray(e))for(let t of e)r.add(t.uuid);else r.add(e.uuid);Qc&&console.log(`All Behavior trigger sources and action targets`,t,n,r),this.targetUuids=new Set(r)}onAfterHierarchy(e,t){if(this.behaviours?.length){t.beginBlock(`def Scope "Behaviors"`);for(let n of this.behaviours)n.writeTo(this,e.document,t);t.closeBlock()}}async onAfterSerialize(e){Qc&&console.log(`onAfterSerialize behaviours`,this.behaviourComponentsCopy);for(let t of this.behaviourComponentsCopy)typeof t.afterSerialize==`function`&&(t.afterSerialize.constructor.name===`AsyncFunction`?await t.afterSerialize(this,e):t.afterSerialize(this,e));for(let{clipUrl:t,filesKey:n}of this.audioClipsCopy){if(e.files[n])return;let r=await(await(await fetch(t)).blob()).arrayBuffer(),i=new Uint8Array(r);e.files[n]=i}this.behaviourComponentsCopy.length=0,this.audioClipsCopy.length=0}},el=class{get extensionName(){return`Physics`}onExportObject(e,t,n){let r=k.getComponents(e,vt).filter(e=>e.enabled),i=k.getComponents(e,vi).filter(e=>e.enabled&&!e.isTrigger),a=r.length>0?r[0]:null,o=i.length>0?i[0]:null;o&&!a&&(a=new vt,a.isKinematic=!0),a&&t.addEventListener(`serialize`,(e,t)=>{if(a){if(e.appendLine(),e.beginBlock(`def RealityKitComponent "RigidBody"`,`{`,!0),a.useGravity||e.appendLine(`bool gravityEnabled = 0`),e.appendLine(`uniform token info:id = "RealityKit.RigidBody"`),a.isKinematic&&e.appendLine(`token motionType = "Kinematic"`),e.beginBlock(`def RealityKitStruct "massFrame"`,`{`,!0),e.appendLine(`float m_mass = ${a.mass}`),e.beginBlock(`def RealityKitStruct "m_pose"`,`{`,!0),e.appendLine(`float3 position = (${a.centerOfMass.x}, ${a.centerOfMass.y}, ${a.centerOfMass.z})`),e.closeBlock(`}`),e.closeBlock(`}`),i.length>0){let t=i[0];e.beginBlock(`def RealityKitStruct "material"`,`{`,!0);let n=t.sharedMaterial;n&&n.dynamicFriction!==void 0&&e.appendLine(`double dynamicFriction = ${t.sharedMaterial?.dynamicFriction}`),n&&n.bounciness!==void 0&&e.appendLine(`double restitution = ${t.sharedMaterial?.bounciness}`),n&&n.staticFriction!==void 0&&e.appendLine(`double staticFriction = ${t.sharedMaterial?.staticFriction}`),e.closeBlock(`}`)}e.closeBlock(`}`)}}),o&&(t.addEventListener(`serialize`,(e,t)=>{e.beginBlock(`def RealityKitComponent "Collider"`,`{`,!0),e.appendLine(`uint group = 1`),e.appendLine(`uniform token info:id = "RealityKit.Collider"`),e.appendLine(`uint mask = 4294967295`);let n=o.isTrigger?`Trigger`:`Default`;if(e.appendLine(`token type = "${n}"`),e.beginBlock(`def RealityKitStruct "Shape"`,`{`,!0),o instanceof yi){let t=o;e.appendLine(`token shapeType = "Sphere"`),e.appendLine(`float radius = ${t.radius}`)}else if(o instanceof bi){let t=o;e.appendLine(`token shapeType = "Box"`),e.appendLine(`float3 extent = (${t.size.x}, ${t.size.y}, ${t.size.z})`)}else if(o instanceof Si){let t=o;e.appendLine(`token shapeType = "Capsule"`),e.appendLine(`float radius = ${t.radius}`),e.appendLine(`float height = ${t.height}`)}else if(o instanceof xi&&o.sharedMesh?.geometry){let t=o.sharedMesh.geometry;t.boundingBox||t.computeBoundingBox();let n=o.sharedMesh.geometry.boundingBox;n&&(e.appendLine(`token shapeType = "Box"`),e.appendLine(`float3 extent = (${n.max.x-n.min.x}, ${n.max.y-n.min.y}, ${n.max.z-n.min.z})`),console.log(`[USDZ] Only Box, Sphere, and Capsule colliders are supported in visionOS/iOS. MeshCollider will be exported as Box`,o))}else console.warn(`[USDZ] Only Box, Sphere, and Capsule colliders are supported in visionOS/iOS. Ignoring collider:`,o);e.beginBlock(`def RealityKitStruct "pose"`,`{`,!0),e.closeBlock(`}`),e.closeBlock(`}`),e.closeBlock(`}`)}),i.length>1&&console.log(`WARNING: Multiple colliders detected. visionOS / iOS can only support objects with a single collider, only exporting the first collider: `,o))}},tl;(function(e){e.singleLine=`singleLine`,e.hardBreaks=`hardBreaks`,e.flowing=`flowing`})(tl||={});var nl;(function(e){e.left=`left`,e.center=`center`,e.right=`right`,e.justified=`justified`})(nl||={});var rl;(function(e){e.top=`top`,e.middle=`middle`,e.lowerMiddle=`lowerMiddle`,e.baseline=`baseline`,e.bottom=`bottom`})(rl||={});var il=class{static global_id=0;static getId(){return this.global_id++}id;content=``;font=[];pointSize=144;width;height;depth;wrapMode;horizontalAlignment;verticalAlignment;material;setDepth(e){return this.depth=e,this}setPointSize(e){return this.pointSize=e,this}setHorizontalAlignment(e){return this.horizontalAlignment=e,this}setVerticalAlignment(e){return this.verticalAlignment=e,this}constructor(e){this.id=e}writeTo(e,t){t.beginBlock(`def Preliminary_Text "${this.id}"`,`(`,!1),t.appendLine(`prepend apiSchemas = ["MaterialBindingAPI"]`),t.closeBlock(`)`),t.beginBlock(),this.content&&t.appendLine(`string content = "${this.content}"`),(!this.font||this.font.length<=0)&&(this.font||=[],this.font?.push(`sans-serif`));let n=this.font.map(e=>`"${e}"`).join(`, `);t.appendLine(`string[] font = [ ${n} ]`),t.appendLine(`double pointSize = ${this.pointSize}`),typeof this.width==`number`&&t.appendLine(`double width = ${this.width}`),typeof this.height==`number`&&t.appendLine(`double height = ${this.height}`),typeof this.depth==`number`&&t.appendLine(`double depth = ${this.depth}`),this.wrapMode&&t.appendLine(`token wrapMode = "${this.wrapMode}"`),this.horizontalAlignment&&t.appendLine(`token horizontalAlignment = "${this.horizontalAlignment}"`),this.verticalAlignment&&t.appendLine(`token verticalAlignment = "${this.verticalAlignment}"`),this.material!==void 0&&t.appendLine(`rel material:binding = </StageRoot/Materials/${as(this.material)}>`),t.closeBlock()}},al=class{static singleLine(e,t,n){let r=new il(`text_`+il.getId());return r.content=e,t&&(r.pointSize=t),n&&(r.depth=n),r}static multiLine(e,t,n,r,i,a){let o=new il(`text_`+il.getId());return o.content=e,o.width=t,o.height=n,o.horizontalAlignment=r,o.verticalAlignment=i,a!==void 0&&(o.wrapMode=a),o}},ol=new b().makeRotationY(Math.PI),sl=new b().makeScale(-1,1,-1),cl=class{get extensionName(){return`text`}exportText(e,t,n){let r=k.getComponent(e,Cn);if(!r)return;let i=k.getComponent(e,Un),a=100,o=100;i&&(a=i.width,o=i.height);let s=ol.clone();i&&s.premultiply(sl),t.setMatrix(s);let c=r.color.clone();t.material=new Te({color:c,emissive:c}),t.addEventListener(`serialize`,(e,n)=>{let i=r.text;i=i.replace(/\r/g,``),i=i.replace(/\n/g,`\\n`);let s=al.multiLine(i,a,o,nl.center,rl.bottom,tl.flowing);this.setTextAlignment(s,r.alignment),this.setOverflow(s,r),t.material&&(s.material=t.material),s.pointSize=this.convertToTextSize(r.fontSize),s.depth=.001,s.writeTo(void 0,e)})}convertToTextSize(e){return 1/.0502*144*e}setOverflow(e,t){t.horizontalOverflow?e.wrapMode=tl.singleLine:e.wrapMode=tl.flowing}setTextAlignment(e,t){switch(t){case M.LowerLeft:case M.MiddleLeft:case M.UpperLeft:e.horizontalAlignment=nl.left;break;case M.LowerCenter:case M.MiddleCenter:case M.UpperCenter:e.horizontalAlignment=nl.center;break;case M.LowerRight:case M.MiddleRight:case M.UpperRight:e.horizontalAlignment=nl.right;break}switch(t){case M.LowerLeft:case M.LowerCenter:case M.LowerRight:e.verticalAlignment=rl.bottom;break;case M.MiddleLeft:case M.MiddleCenter:case M.MiddleRight:e.verticalAlignment=rl.middle;break;case M.UpperLeft:case M.UpperCenter:case M.UpperRight:e.verticalAlignment=rl.top;break}}},ll=class{get extensionName(){return`tmui`}onExportObject(e,t,r){let i=k.getComponent(e,An);if(i&&i.enabled&&i.renderMode===en.WorldSpace){let i=new cl,a=k.getComponent(e,Un),o=k.getComponent(e,xn),s=[];if(a){if(!k.isActiveSelf(e)){let t=k.isActiveSelf(e);k.setActive(e,!0),a.onEnable(),a.updateTransform(),s.push(()=>{a.onDisable(),k.setActive(e,t)})}e.traverse(e=>{if(!k.isActiveInHierarchy(e)){let t=k.isActiveSelf(e);k.setActive(e,!0);let n=k.getComponent(e,Hn);n&&(n.onEnable(),s.push(()=>{n.onDisable()}));let r=k.getComponent(e,Un);r&&(r.onEnable(),r.updateTransform(),r.onApplyTransform(),s.push(()=>{r.onDisable()}));let i=k.getComponent(e,Cn);i&&(i.onEnable(),s.push(()=>{i.onDisable()})),s.push(()=>{k.setActive(e,t)})}}),a.width,a.height;let c=jo.createEmpty(),l=a.shadowComponent;if(t.add(c),l){let e=l.matrix;c.setMatrix(e);let t=new Map,a=new Map;t.set(l,c),a.set(l,o?o.alpha:1),l.traverse(e=>{if(e===l)return;let o=jo.createEmpty();o.setMatrix(e.matrix);let s=e.parent,c=!!s&&typeof s.textContent==`string`&&s.textContent.length>0,u=a.get(s)||1,d=k.getComponent(e,xn);if(d&&(u*=d.alpha),e instanceof x&&c){let t=e[$e];t?i.exportText(t.gameObject,o,r):console.error(`Error when exporting UI: shadow component owner not found. This is likely a bug.`,e)}if(e instanceof x&&!c){let t=e.geometry.clone();t.scale(1,1,-1),this.flipWindingOrder(t),o.geometry=t;let r=new n,i=e.material.opacity;r.copy(e.material.color),o.material=new v({color:r,opacity:i*u,map:e.material.map,transparent:!0})}t.set(e,o),a.set(e,u);let f=t.get(s);if(!f){console.error(`Error when exporting UI: shadow component parent not found!`,e,e.parent);return}f.add(o)})}}for(let e of s)e()}}flipWindingOrder(e){let t=e.index.array;for(let e=0,n=t.length/3;e<n;e++){let n=t[e*3];t[e*3]=t[e*3+2],t[e*3+2]=n}e.index.needsUpdate=!0}},ul=D(`debugusdz`);function dl(e,t){let n=[],r=k.getComponentsInChildren(e,kt),i=k.getComponentsInChildren(e,xr),a=[],o=[];if(t.injectImplicitBehaviours)for(let t of r){if(!t||!t.runtimeAnimatorController||!t.enabled)continue;let n=t.runtimeAnimatorController.activeState;if(!n||!n.motion||!n.motion.clip||n.motion.clip.tracks?.length<1||a.includes(t))continue;let r=new Ys;r.animator=t,r.stateName=n.name,r.trigger=`start`,r.name=`PlayAnimationOnClick_implicitAtStart_`+r.stateName;let i=new S;k.addComponent(i,r),o.push(i),a.push(t),e.add(i)}else for(let e of r){if(!e||!e.runtimeAnimatorController||!e.enabled)continue;ul&&console.log(e);let t=[];for(let n of e.runtimeAnimatorController.enumerateActions()){ul&&console.log(n);let e=n.getClip();t.includes(e)||t.push(e)}n.push({root:e.gameObject,clips:t})}if(t.injectImplicitBehaviours)for(let t of i){if(!t||!t.clip||!t.enabled||!t.playAutomatically||a.includes(t))continue;let n=new Ys;n.animation=t,n.stateName=t.clip.name,n.trigger=`start`,n.name=`PlayAnimationOnClick_implicitAtStart_`+n.stateName;let r=new S;k.addComponent(r,n),o.push(r),a.push(t),e.add(r)}else for(let e of i){ul&&console.log(e);let t=[];for(let n of e.animations)t.includes(n)||t.push(n);n.push({root:e.gameObject,clips:t})}ul&&n?.length>0&&console.log(`USDZ Animation Clips without behaviours`,n);for(let e of n)for(let n of e.clips)t.registerAnimation(e.root,n);return o}function fl(e,t){let n=k.getComponentsInChildren(e,I),r=k.getComponentsInChildren(e,Js),i=[],a=[];ul&&console.log({audioSources:n,playAudioOnClicks:r});for(let e of r){if(!e.target)continue;let t=n.indexOf(e.target);t>-1&&n.splice(t,1)}for(let t of n){if(!t||!t.clip||t.volume<=0||i.includes(t))continue;let n=new Js;n.target=t,n.name=`PlayAudioOnClick_implicitAtStart_`,n.trigger=`start`;let r=new S;k.addComponent(r,n),console.log(`implicit PlayAudioOnStart`,r,n),a.push(r),i.push(t),e.add(r)}return a}function pl(e){return new Es(`DisableAtStart`,js.sceneStartTrigger(),G.fadeAction(e,0,!1))}function ml(e,t){let n=e.domElement.shadowRoot.querySelector(`link[rel='ar']`);if(n)return n;let r=document.createElement(`div`);r.classList.add(`menu`),r.classList.add(`quicklook-menu`),r.style.display=`none`,r.style.visibility=`hidden`;let i=document.createElement(`button`);i.id=`open-in-ar`,t?(i.innerText=`View in AR`,i.title=`View this scene in AR. The scene will be exported to USDZ and opened with Apple's QuickLook.`):(i.innerText=`View in AR`,i.title=`Download this scene for AR. Open the downloaded USDZ file to view it in AR using Apple's QuickLook.`),r.appendChild(i);let a=document.createElement(`a`);a.id=`needle-usdz-link`,a.style.display=`none`,a.rel=`ar`,a.href=``,a.target=`_blank`,r.appendChild(a);let o=document.createElement(`img`);return o.id=`button`,a.appendChild(o),e.domElement.shadowRoot.appendChild(r),a}var Z=function(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},Q=D(`debugusdz`),hl=D(`debugusdzpruning`),gl=class{callToAction;checkoutTitle;checkoutSubtitle;callToActionURL};Z([E()],gl.prototype,`callToAction`,void 0),Z([E()],gl.prototype,`checkoutTitle`,void 0),Z([E()],gl.prototype,`checkoutSubtitle`,void 0),Z([E()],gl.prototype,`callToActionURL`,void 0);var $=class e extends N{static beforeExport=new Ut;static afterExport=new Ut;static beforeLODExport=new Ut;objectToExport=void 0;autoExportAnimations=!0;autoExportAudioSources=!0;exportFileName=void 0;customUsdzFile=void 0;customBranding;anchoringType=`plane`;maxTextureSize=2048;planeAnchoringAlignment=`horizontal`;interactive=!0;physics=!0;allowCreateQuicklookButton=!0;quickLookCompatible=!0;extensions=[];link;button;start(){Q&&(console.log(`USDZExporter`,this),console.log(`Debug USDZ Mode. Press 'T' to export`),window.addEventListener(`keydown`,e=>{switch(e.key){case`t`:this.exportAndOpen();break}})),this.objectToExport||=this.gameObject,!this.objectToExport?.children?.length&&!this.objectToExport?.isMesh&&(this.objectToExport=this.context.scene)}onEnable(){let e=A.supportsQuickLookAR(),t=A.isiOS()||A.isiPad();!this.button&&(Q||e||t)&&(this.allowCreateQuicklookButton&&(this.button=this.createQuicklookButton()),this.lastCallback=this.quicklookCallback.bind(this),this.link=ml(this.context,e),this.link.addEventListener(`message`,this.lastCallback)),Q&&vn(`USDZ Exporter enabled: `+this.name),document.getElementById(`open-in-ar`)?.addEventListener(`click`,this.onClickedOpenInARElement),Tn.registerExporter(this)}onDisable(){this.button?.remove(),this.link?.removeEventListener(`message`,this.lastCallback),Q&&vn(`USDZ Exporter disabled: `+this.name),document.getElementById(`open-in-ar`)?.removeEventListener(`click`,this.onClickedOpenInARElement),Tn.unregisterExporter(this)}onClickedOpenInARElement=e=>{e.preventDefault(),this.exportAndOpen()};async exportAsync(){return this.exportAndOpen()}async exportAndOpen(){let t=this.exportFileName??this.objectToExport?.name??this.name;if(t+=`-`+ho(),zn()||(t!==``&&(t+=`-`),t+=`MadeWithNeedle`),this.link||=ml(this.context,A.supportsQuickLookAR()),this.customUsdzFile)return Q&&console.log(`Exporting custom usdz`,this.customUsdzFile),this.openInQuickLook(this.customUsdzFile,t),null;if(!this.objectToExport)return console.warn(`No object to export`,this),null;e.beforeExport.invoke({exporter:this});let n=await this.export(this.objectToExport).finally(()=>{e.afterExport.invoke({exporter:this})});return n?(Q&&console.log(`USDZ generation done. Downloading as `+t),this.openInQuickLook(n,t),n):(console.error(`USDZ generation failed. Please report a bug`,this),null)}async export(e){if(!e)return console.warn(`No object to export`),null;let t=this._currentExportTasks.get(e);if(t)return t;let n=this.internalExport(e);return n instanceof Promise?(this._currentExportTasks.set(e,n),n.then(t=>(this._currentExportTasks.delete(e),t)).catch(t=>(this._currentExportTasks.delete(e),console.error(`Error during USDZ export – please report a bug!`,t),null))):n}_currentExportTasks=new Map;_previousTimeScale=1;async internalExport(t){V.start(`export-usdz`,{onProgress:e=>{this.dispatchEvent(new CustomEvent(`export-progress`,{detail:{progress:e}}))}}),V.report(`export-usdz`,{message:`Starting export`,totalSteps:40,currentStep:0}),V.report(`export-usdz`,{message:`Load progressive textures`,autoStep:5}),V.start(`export-usdz-textures`,`export-usdz`);let n=k.getComponentsInChildren(t,vc);for(let e of n)e&&e.enabled&&e.updateSprite(!0);let r=k.getComponentsInChildren(t,B),i=[],a=0;for(let t of r){for(let n of t.sharedMeshes)if(n){let r=0,o={exporter:this,type:`mesh`,object:t.gameObject,mesh:n};if(e.beforeLODExport.invoke(o),o.overrideLevel!==void 0)if(o.overrideLevel===-1){Q&&console.warn(`Skipping LOD export for mesh due to overrideLevel -1`,t.gameObject,n);continue}else o.overrideLevel>=0&&(r=o.overrideLevel,Q&&console.log(`Overriding LOD level for mesh export to level `+r+` `+n.name));let s=P.assignMeshLOD(n,r);s instanceof Promise&&i.push(new Promise((e,t)=>{s.then(()=>{a++,V.report(`export-usdz-textures`,{message:`Loaded progressive mesh`,currentStep:a,totalSteps:i.length}),e()}).catch(e=>t(e))}))}for(let n of t.sharedMaterials)if(n){let r=0,o={exporter:this,type:`texture`,object:t.gameObject,material:n};if(e.beforeLODExport.invoke(o),o.overrideLevel!==void 0)if(o.overrideLevel===-1){Q&&console.warn(`Skipping LOD assignment due to overrideLevel -1`,t.gameObject,n);continue}else o.overrideLevel>=0&&(r=o.overrideLevel,Q&&console.log(`Overriding LOD level for texture export to level `+r+` `+n.name));let s=P.assignTextureLOD(n,r);s instanceof Promise&&i.push(new Promise((e,t)=>{s.then(()=>{a++,V.report(`export-usdz-textures`,{message:`Loaded progressive texture`,currentStep:a,totalSteps:i.length}),e()}).catch(e=>t(e))}))}}Q&&vn(`Progressive Loading: `+i.length),await Promise.all(i),Q&&vn(`Progressive Loading: done`),V.end(`export-usdz-textures`);let o=di.Global.Mask;di.Global.Set(ui.AR);let s=new Ro,c=new Rs(this.quickLookCompatible),l,u=[];this.interactive&&(u.push(new $c),u.push(new Vs),globalThis.NEEDLE_USE_RAPIER&&k.getComponentsInChildren(t,vt).length>0&&(this.physics?(l=new el,u.push(l)):T()&&console.warn(`USDZExporter: Physics export is disabled, but there are active Rigidbody components in the scene. They will not be exported.`)),u.push(new cl),u.push(new ll));let d=[c,...u,...this.extensions],f={self:this,exporter:s,extensions:d,object:t};V.report(`export-usdz`,`Invoking before-export`),this.dispatchEvent(new CustomEvent(`before-export`,{detail:f})),this.applyWebARSessionRoot(),this._previousTimeScale=this.context.time.timeScale,this.context.time.timeScale=0,V.report(`export-usdz`,`auto export animations and audio sources`);let p=[];this.autoExportAnimations&&p.push(...dl(t,c));let m=d.find(e=>e.extensionName===`Audio`);m&&this.autoExportAudioSources&&p.push(...fl(t,m)),s.debug=Q,s.pruneUnusedNodes=!hl;let h=Ka.instance.objs.map(e=>e.batchedMesh);s.keepObject=e=>{let t=!0,n=k.getComponent(e,B);return n&&!n.enabled&&(t=!1),t&&h.includes(e)&&(t=!1),t&&k.getComponentInParent(e,ki)&&(t=!1),t&&k.getComponentInParent(e,En)&&(t=!1),Q&&!t&&console.log(`USDZExporter: Discarding object`,e),t},s.beforeWritingDocument=()=>{if(T()&&c&&l){let e=c.animatedRoots;for(let t of e){let e=k.getComponentsInChildren(t,vt).filter(e=>e.enabled),n=k.getComponents(t,vi).filter(e=>e.enabled&&!e.isTrigger);(e.length>0||n.length>0)&&console.error(`An animated object has physics components in its child hierarchy. This can lead to undefined behaviour due to a bug in Apple's QuickLook (FB15925487). Remove the physics components from child objects or verify that you get the expected results.`,t)}}};let g=[];this.objectToExport&&this.quickLookCompatible&&this.interactive&&this.objectToExport.traverse(e=>{e.visible||g.push(e)});let _=d.find(e=>e.extensionName===`Behaviour`);this.interactive&&_&&g.length>0&&_.addBehavior(pl(g));let ee=!0;this.quickLookCompatible&&!this.interactive&&(ee=!1),this.anchoringType!==`plane`&&this.anchoringType!==`none`&&this.anchoringType!==`image`&&this.anchoringType!==`face`&&(this.anchoringType=`plane`),this.planeAnchoringAlignment!==`horizontal`&&this.planeAnchoringAlignment!==`vertical`&&this.planeAnchoringAlignment!==`any`&&(this.planeAnchoringAlignment=`horizontal`),V.report(`export-usdz`,`Invoking exporter.parse`);let te=await s.parse(this.objectToExport,{ar:{anchoring:{type:this.anchoringType},planeAnchoring:{alignment:this.planeAnchoringAlignment}},extensions:d,quickLookCompatible:this.quickLookCompatible,maxTextureSize:this.maxTextureSize,exportInvisible:ee}),ne=new Blob([te],{type:`model/vnd.usdz+zip`});this.revertWebARSessionRoot(),this.context.time.timeScale=this._previousTimeScale,V.report(`export-usdz`,`Invoking after-export`),this.dispatchEvent(new CustomEvent(`after-export`,{detail:f}));for(let e of p)k.destroy(e);return di.Global.Set(o),V.end(`export-usdz`),ne}openInQuickLook(e,t){let n=e instanceof Blob?URL.createObjectURL(e):e,r=this.buildQuicklookOverlay();Q&&console.log(`QuickLook Overlay`,r);let i=r.callToAction?encodeURIComponent(r.callToAction):``,a=r.checkoutTitle?encodeURIComponent(r.checkoutTitle):``,o=r.checkoutSubtitle?encodeURIComponent(r.checkoutSubtitle):``;this.link.href=n+`#callToAction=${i}&checkoutTitle=${a}&checkoutSubtitle=${o}&callToActionURL=${r.callToActionURL}`,this.lastCallback||(this.lastCallback=this.quicklookCallback.bind(this),this.link.addEventListener(`message`,this.lastCallback)),this.link.download=t+`.usdz`,this.link.click()}download(t,n){e.save(t,n)}static save(e,t){let n=document.createElement(`a`);n.style.display=`none`,document.body.appendChild(n),typeof e==`string`?n.href=e:n.href=URL.createObjectURL(e),n.download=t,n.click(),n.remove()}lastCallback;quicklookCallback(e){if(e?.data==`_apple_ar_quicklook_button_tapped`){Q&&kn(`Quicklook closed via call to action button`);var t=new CustomEvent(`quicklook-button-tapped`,{detail:this});if(this.dispatchEvent(t),!t.defaultPrevented){let e=new URLSearchParams(this.link.href);if(e){let t=e.get(`callToActionURL`);Q&&vn(`Quicklook url: `+t),t&&(zn()?globalThis.open(t,`_blank`):console.warn(`Quicklook closed: custom redirects require a Needle Engine Pro license: https://needle.tools/pricing`,t))}}}}buildQuicklookOverlay(){let e={};return this.customBranding&&Object.assign(e,this.customBranding),zn()||(console.log(`Custom Quicklook banner text requires pro license: https://needle.tools/pricing`),e.callToAction=`Close`,e.checkoutTitle=`🌵 Made with Needle`,e.checkoutSubtitle=`_`),(e.callToAction?.length||e.checkoutTitle?.length||e.checkoutSubtitle?.length)&&(e.callToAction?.length||(e.callToAction=`\0`),e.checkoutTitle?.length||(e.checkoutTitle=`\0`),e.checkoutSubtitle?.length||(e.checkoutSubtitle=`\0`)),this.dispatchEvent(new CustomEvent(`quicklook-overlay`,{detail:e})),e}static invertForwardMatrix=new b().makeRotationY(Math.PI);static invertForwardQuaternion=new Ue().setFromEuler(new ze(0,Math.PI,0));_rootSessionRootWasAppliedTo=null;_rootPositionBeforeExport=new r;_rootRotationBeforeExport=new Ue;_rootScaleBeforeExport=new r;getARScaleAndTarget(){if(!this.objectToExport)return{scale:1,_invertForward:!1,target:this.gameObject,sessionRoot:null};let e=k.findObjectOfType(X),t=k.getComponentInParent(this.objectToExport,xc);t||=k.getComponentInChildren(this.objectToExport,xc);let n=1,r=!1,i=this.objectToExport;return e?n=e.arScale:t&&(n=t.arScale,r=t.invertForward),{scale:1/n,_invertForward:r,target:i,sessionRoot:t?.gameObject??null}}applyWebARSessionRoot(){if(!this.objectToExport)return;let{scale:t,_invertForward:n,target:r,sessionRoot:i}=this.getARScaleAndTarget(),a=i?.matrixWorld.clone().invert();this._rootSessionRootWasAppliedTo=r,this._rootPositionBeforeExport.copy(r.position),this._rootRotationBeforeExport.copy(r.quaternion),this._rootScaleBeforeExport.copy(r.scale),r.scale.multiplyScalar(t),n&&r.quaternion.multiply(e.invertForwardQuaternion),r.updateMatrix(),r.updateMatrixWorld(!0),i&&a&&r.matrix.premultiply(a)}revertWebARSessionRoot(){if(!this.objectToExport||!this._rootSessionRootWasAppliedTo)return;let e=this._rootSessionRootWasAppliedTo;e.position.copy(this._rootPositionBeforeExport),e.quaternion.copy(this._rootRotationBeforeExport),e.scale.copy(this._rootScaleBeforeExport),e.updateMatrix(),e.updateMatrixWorld(!0),this._rootSessionRootWasAppliedTo=null}createQuicklookButton(){let e=sc.getOrCreate().createQuicklookButton();return e.parentNode||this.context.menu.appendChild(e),e}};Z([E(S)],$.prototype,`objectToExport`,void 0),Z([E()],$.prototype,`autoExportAnimations`,void 0),Z([E()],$.prototype,`autoExportAudioSources`,void 0),Z([E()],$.prototype,`exportFileName`,void 0),Z([E(URL)],$.prototype,`customUsdzFile`,void 0),Z([E(gl)],$.prototype,`customBranding`,void 0),Z([E()],$.prototype,`anchoringType`,void 0),Z([E()],$.prototype,`maxTextureSize`,void 0),Z([E()],$.prototype,`planeAnchoringAlignment`,void 0),Z([E()],$.prototype,`interactive`,void 0),Z([E()],$.prototype,`physics`,void 0),Z([E()],$.prototype,`allowCreateQuicklookButton`,void 0),Z([E()],$.prototype,`quickLookCompatible`,void 0),nc({find:()=>Zt($),create:()=>new $});var _l=function(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},vl=class extends N{objectBounds=!1;color;isGizmo=!0;_gizmoObject=null;_boxHelper=null;onEnable(){this.isGizmo&&!yn||(this._gizmoObject||(this.objectBounds?this._gizmoObject=new ge(this.gameObject,this.color??16776960):(this.objectBounds=!1,this._gizmoObject=pn(this.color??16776960))),this.objectBounds?(this.scene.add(this._gizmoObject),this._boxHelper=this._gizmoObject,this.startCoroutine(this.syncObjectBounds(),Wn.OnBeforeRender)):this.gameObject.add(this._gizmoObject))}onDisable(){this._gizmoObject&&this.gameObject.remove(this._gizmoObject)}*syncObjectBounds(){for(;this._boxHelper;)this._boxHelper?.update(),yield}};_l([E()],vl.prototype,`objectBounds`,void 0),_l([E(n)],vl.prototype,`color`,void 0),_l([E()],vl.prototype,`isGizmo`,void 0);var yl=function(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},bl=class extends N{get activeAndEnabled(){return!0}side=`none`;controller=!0;hands=!1;controlVisibility=!0;useGripSpace=!1;resetTransformAfterXRSession=!0;_startPosition=new r;_startRotation=new Ue;_startScale=new r;onEnterXR(e){this._startPosition.copy(this.gameObject.position),this._startRotation.copy(this.gameObject.quaternion),this._startScale.copy(this.gameObject.scale)}onUpdateXR(e){if(!this.enabled)return;let t=e.xr.getController(this.side);if(t){if(t.hand&&!this.hands){this.controlVisibility&&(this.gameObject.visible=!1);return}else if(!this.controller){this.controlVisibility&&(this.gameObject.visible=!1);return}this.controlVisibility&&(this.gameObject.visible=!0),this.useGripSpace||t.targetRayMode===`transient-pointer`?(this.gameObject.worldPosition=t.gripWorldPosition,this.gameObject.worldQuaternion=t.gripWorldQuaternion,this.gameObject.worldScale=wn(t.xr.rigScale,t.xr.rigScale,t.xr.rigScale).multiply(this._startScale)):(this.gameObject.worldPosition=t.rayWorldPosition,this.gameObject.worldQuaternion=t.rayWorldQuaternion,this.gameObject.worldScale=wn(t.xr.rigScale,t.xr.rigScale,t.xr.rigScale).multiply(this._startScale))}}onLeaveXR(e){this.resetTransformAfterXRSession&&(this.gameObject.position.copy(this._startPosition),this.gameObject.quaternion.copy(this._startRotation),this.gameObject.scale.copy(this._startScale))}};yl([E()],bl.prototype,`side`,void 0),yl([E()],bl.prototype,`controller`,void 0),yl([E()],bl.prototype,`hands`,void 0),yl([E()],bl.prototype,`controlVisibility`,void 0),yl([E()],bl.prototype,`useGripSpace`,void 0),yl([E()],bl.prototype,`resetTransformAfterXRSession`,void 0);function xl(e,t){let n=e.xr.getFrame();if(!n)return console.warn(`No XRFrame available`),!1;let r=n.session.enabledFeatures;if(r&&!r.some(e=>e===`camera-access`))return console.error(`No camera feed available - please request the 'camera-access' feature before starting WebXR or add the ARCameraBackground component to your scene.
|
||
|
||
Example to request camera-access in global scope:
|
||
NeedleXRSession.onSessionRequestStart(evt => {
|
||
evt.init.optionalFeatures = evt.init.optionalFeatures || [];
|
||
evt.init.optionalFeatures.push('camera-access');
|
||
});
|
||
`),T()&&Nn(`No camera feed available - please request the 'camera-access' feature before starting WebXR or add the ARCameraBackground component to your scene`),!1;let i=n.getViewerPose(e.xr.getReferenceSpace());if(i)for(let r of i.views)if(`camera`in r&&r.camera){let i=e.xr.getBinding();if(i||=new XRWebGLBinding(n.session,e.getContext()),i){let n=null;if(`getCameraImage`in i){Cl(e,t);let a=e.properties.get(t);if(a)return n=i.getCameraImage(r.camera),a.__webglTexture=n,!0;console.warn(`No texture properties found for target texture`)}}else console.error(r.camera,e.xr)}else console.error(`NO CAMERA IN VIEW`);else console.error(e.xr.getReferenceSpace(),n);return!1}var Sl=new WeakMap;function Cl(e,t){let n=Sl.get(t)||new WeakSet;if(n.has(e))return;n.add(e),Sl.set(t,n),console.debug(`Initialize texture for camera feed`);let r=new v,i=new He,a=new ne;a.add(new x(i,r));let o=new be;r.map=t,e.render(a,o)}function wl(e,t,n,r=`image/webp`,i){return Tl({context:e,width:t,height:n,mimeType:r,camera:i})}function Tl(e){e||={};let{transparent:t=!1}=e,{mimeType:r,context:i,width:a,height:o,camera:s}=e;if(!i&&(i=Ht.Current,!i))return console.error(`Can not save screenshot: No needle-engine context found or provided.`),null;if(!s&&(s=i.mainCamera,!s))return console.error(`No camera found`),null;let c=i.renderer,l=c.xr.enabled&&c.xr.isPresenting;if(l&&i.currentFrameEvent!=Wn.EarlyUpdate)return console.warn(`Screenshot: defer to access XR frame`),new Promise(t=>{st(n=>{t(Tl(e))},Wn.EarlyUpdate,{once:!0})});let d=c.domElement,f=d.width,p=d.height;a||=f,o||=p;let m=a,h=o,g=window.devicePixelRatio||1,_=1;_=i.devicePixelRatio===`auto`||i.devicePixelRatio===`manual`?1:i.devicePixelRatio/window.devicePixelRatio,g*=_,a/=g,o/=g,a=Math.floor(a),o=Math.floor(o),c.xr.isPresenting&&c.xr.getFrame();let ee=c.xr.enabled;c.xr.enabled=!1,c.xr.isPresenting=!1,d.style.width=`${a}px`,d.style.height=`${o}px`;let te=c.getRenderTarget(),ne=c.getClearColor(new n),v=c.getClearAlpha(),re=i.scene.background,ie=`aspect`in s?s.aspect:null;try{let n=e.render_events!==!1,f=[];n&&(at(i.scene,B,f),f.forEach(e=>{if(e?.onBeforeRender(),e.isInstancingActive&&e.instances)for(let t=0;t<e.instances?.length;t++){let n=e.instances[t];wi(n.object,!0)}})),t&&(i.scene.background=null,c.setClearColor(0,0)),e.background&&(i.scene.background=null,c.setClearColor(e.background),e.background instanceof tn&&c.setClearAlpha(e.background.a)),t&&c.setClearAlpha(0),c.setSize(a,o,!1),`cam`in s&&(s=s.threeCamera),s instanceof be&&(s.aspect=a/o,s.updateProjectionMatrix());let p=`type`in e&&e.type===`texture`,g=null;p&&(g=new u(a,o,{wrapS:he,wrapT:he,format:1023}),c.setRenderTarget(g));let _=d;if(l?(g&&console.error(`Taking XR screenshots with { type: "texture" } is currently not supported.`),_=kl.compositeWithCameraImage({width:m,height:h,scene:i.scene,camera:s,renderer:c})):i.renderNow(s||null),s instanceof be&&ie!=null&&(s.aspect=ie,s.updateProjectionMatrix()),n&&f.forEach(e=>e.onAfterRender()),!r&&`download_filename`in e&&e.download_filename)switch(e.download_filename.split(`.`).pop()?.toLowerCase()){case`png`:r=`image/png`;break;case`jpg`:case`jpeg`:r=`image/jpeg`;break;case`webp`:r=`image/webp`;break}if(t&&e.trim===!0){let e=El(_);e&&(_=e)}if(`type`in e){if(e.type===`texture`)return g?(e.target&&(e.target.image=g?.texture.image,e.target.needsUpdate=!0),g.texture.offset.set(0,-1),g.texture.needsUpdate=!0,g.texture):(console.error(`No target texture found`),null);if(e.type===`blob`)return new Promise((e,t)=>{_.toBlob(t=>{e(t)},r)});if(e.type===`share`)return new Promise((t,n)=>{_.toBlob(n=>{if(n&&`share`in navigator){let i=`file_type`in e&&e.file_type||r;r||(i=`image/png`);let a=i?.split(`/`)[1]||`png`,o=new File([n],`filename`in e&&e.filename||`screenshot.${a}`,{type:i});return navigator.share({title:`title`in e?e.title:void 0,text:`text`in e?e.text:void 0,url:`url`in e?e.url:void 0,files:[o]}).catch(e=>{console.warn(`User cancelled share`,e.message)}).finally(()=>{t({blob:n,shared:!0})})}return{blob:n,shared:!1}},r)})}let ee=_.toDataURL(r);if(`download_filename`in e&&e.download_filename){let t=e.download_filename;if(A.isMobileDevice()&&typeof window<`u`){let e=t+`_screenshots`,n=t.split(`.`),r=n.pop()?.toLowerCase(),i=0;localStorage.getItem(e)&&(i=parseInt(sessionStorage.getItem(e)||`0`)),i>0&&(t=`${n.join()}-${i}.${r}`),i+=1,sessionStorage.setItem(e,i.toString())}Ol(ee,t)}return ee}finally{c.setRenderTarget(te),i.scene.background=re,c.setSize(f,p,!1),c.setClearColor(ne,v),ie!=null&&s instanceof be&&(s.aspect=ie,s.updateProjectionMatrix()),c.xr.enabled=ee,c.xr.isPresenting=l,l||i.updateSize(!0)}return null}function El(e){if(!(`document`in globalThis))return null;let t=document.createElement(`canvas`);t.width=e.width,t.height=e.height;let n=t.getContext(`2d`);if(!n)return null;n.drawImage(e,0,0);let r=t.width,i=t.height,a=n.getImageData(0,0,r,i).data,o=i,s=r,c=0,l=0;for(let e=0;e<i;e++)for(let t=0;t<r;t++)a[(e*r+t)*4+3]!==0&&(t<s&&(s=t),t>l&&(l=t),e<o&&(o=e),e>c&&(c=e));let u=l-s+1,d=c-o+1,f=document.createElement(`canvas`),p=f.getContext(`2d`);return p?(f.width=u,f.height=d,p.drawImage(t,s,o,u,d,0,0,u,d),f):null}var Dl=null;function Ol(e,t){if(e){if(!e.startsWith(`data:image`)){console.error(`Can not save image: Data url is not an image`,e);return}Dl||=document.createElement(`a`),Dl.href=e,Dl.download=t,Dl.click()}}var kl;(function(e){let t=null,n=null,r=null,i=null,a=null;function o(e){let{renderer:o,width:s,height:l}=e,d=o.xr.enabled,f=o.getRenderTarget(),p=o.autoClear,m=s,h=l,g=s/l;(!r||r.width!==m||r.height!==h)&&(r??=new u(m,h,{colorSpace:ue}),r.width=m,r.height=h,r.samples=4,r.texture.repeat.y=-1,r.texture.offset.y=1),(!a||a.width!==m||a.height!==h)&&(a=document.createElement(`canvas`),a.width=m,a.height=h,a.style.position=`fixed`,a.style.top=`0px`,a.style.right=`0px`,a.style.width=`300px`,a.style.height=`${300/g}px`,a.style.zIndex=`1000`,a.style.pointerEvents=`none`,a.style.opacity=`1.0`,a.style.willChange=`contents`),t||=c({defines:{DECODE_VIDEO_TEXTURE:!0}}),n||=c(),i||=new xe,o.xr.updateCamera(e.camera),o.xr.enabled=!1,o.autoClear=!1,o.clear(),o.setSize(m,h),o.setRenderTarget(r),xl(e.renderer,i)||console.error(`Could not update texture from XR frame`);let _=k.findObjectOfType(Ml);return _?_.setTexture(i):(t.setTexture(i),o.render(t,e.camera)),o.clearDepth(),o.setSize(m,h),o.render(e.scene,e.camera),o.setRenderTarget(null),n.setTexture(r.texture),o.render(n,e.camera),a.getContext(`2d`,{alpha:!1}).drawImage(o.domElement,0,0,a.width,a.height),o.setRenderTarget(f),o.xr.enabled=d,o.autoClear=p,a}e.compositeWithCameraImage=o;function c(e){let t=e?.material||new Re({name:`BackgroundMaterial`,uniforms:s.clone(ye.background.uniforms),vertexShader:ye.background.vertexShader,fragmentShader:`
|
||
uniform sampler2D t2D;
|
||
varying vec2 vUv;
|
||
|
||
void main() {
|
||
|
||
vec4 texColor = texture2D( t2D, vUv );
|
||
|
||
#ifdef DECODE_VIDEO_TEXTURE
|
||
|
||
// inline sRGB decode (TODO: Remove this code when https://crbug.com/1256340 is solved)
|
||
texColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w );
|
||
|
||
#endif
|
||
|
||
gl_FragColor = texColor;
|
||
#include <tonemapping_fragment>
|
||
#include <colorspace_fragment>
|
||
}
|
||
`,defines:e?.defines,side:0,depthTest:!1,depthWrite:!1,fog:!1});Object.defineProperty(t,`map`,{get:function(){return this.threeTexture}});let n=new x(new He(2,2),t);return Qe(n,!1),n.geometry.deleteAttribute(`normal`),n.renderOrder=-1e6,n.setTexture=function(e){t.uniforms.t2D.value=e},n}e.makeFullscreenPlane=c})(kl||={});var Al=function(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},jl=D(`debugarcamera`),Ml=class extends N{onBeforeXR(e,t){e===`immersive-ar`&&(t.optionalFeatures=t.optionalFeatures||[],t.optionalFeatures.push(`camera-access`),jl&&console.warn(`Requesting camera-access`))}onEnterXR(e){e.xr.mode===`immersive-ar`&&(this.backgroundPlane&&(this.context.scene.add(this.backgroundPlane),this.backgroundPlane.visible=!1),this.backgroundPlane&&this.context.scene.add(this.backgroundPlane),this.context.pre_render_callbacks.push(this.preRender))}onLeaveXR(e){this.backgroundPlane&&this.backgroundPlane.removeFromParent();let t=this.context.pre_render_callbacks.indexOf(this.preRender);t>=0&&this.context.pre_render_callbacks.splice(t,1)}backgroundTint=new tn(1,1,1,1);get background(){return this.backgroundPlane}backgroundPlane;threeTexture;forceTextureInitialization=function(){let e=new v,t=new He,n=new ne;n.add(new x(t,e));let r=new be;return function(t,i){e.map=i,t.render(n,r),jl&&console.warn(`Force texture initialization`)}}();preRender=()=>{if(!(!this||!this.gameObject)&&this.context.renderer.xr.getFrame()){if(!this.threeTexture&&this.context.renderer&&(this.threeTexture=new xe,this.forceTextureInitialization(this.context.renderer,this.threeTexture)),this.backgroundPlane===void 0){let e=this.backgroundTint;this.backgroundPlane=kl.makeFullscreenPlane({material:new Re({name:`BackgroundMaterial`,uniforms:{...s.clone(ye.background.uniforms),tint:{value:new C(e.r,e.g,e.b,e.a)}},vertexShader:ye.background.vertexShader,fragmentShader:Nl,side:2,depthTest:!1,depthWrite:!1,fog:!1})})}this.backgroundPlane.parent!==this.scene&&this.scene.add(this.backgroundPlane),this.backgroundPlane.material instanceof Re&&this.backgroundPlane.material.uniforms.tint.value.set(this.backgroundTint.r,this.backgroundTint.g,this.backgroundTint.b,this.backgroundTint.a),this.updateFromFrame()}};onBeforeRender(e){this.updateFromFrame()}updateFromFrame(){this.threeTexture&&this.context.xr?.mode===`immersive-ar`&&(xl(this.context.renderer,this.threeTexture),this.setTexture(this.threeTexture))}setTexture(e){this.backgroundPlane&&(this.threeTexture=e,this.backgroundPlane.setTexture(this.threeTexture),this.backgroundPlane.visible=!0)}};Al([E(tn)],Ml.prototype,`backgroundTint`,void 0);var Nl=`
|
||
uniform sampler2D t2D;
|
||
uniform vec4 tint;
|
||
|
||
varying vec2 vUv;
|
||
|
||
void main() {
|
||
|
||
vec4 texColor = texture2D( t2D, vUv );
|
||
texColor.w = 1.0;
|
||
|
||
// inline sRGB decode
|
||
texColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w );
|
||
|
||
gl_FragColor = texColor * tint;
|
||
|
||
#include <tonemapping_fragment>
|
||
#include <colorspace_fragment>
|
||
}
|
||
`,Pl=function(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},Fl=D(`debugimagetracking`),Il=class e{get url(){return this._trackedImage.image??``}get widthInMeters(){return this._trackedImage.widthInMeters??void 0}get bitmap(){return this._bitmap}get model(){return this._trackedImage}measuredSize;state;getPosition(e){return this.ensureTransformData(),e.copy(this._position),e}getQuaternion(e){return this.ensureTransformData(),e.copy(this._rotation),e}applyToObject(e,t=void 0){this.ensureTransformData();let n=e.position.distanceToSquared(this._position)/.05+e.quaternion.angleTo(this._rotation)/.05;t&&(t*=Math.max(1,n)),t===void 0||t>=1?(e.position.copy(this._position),e.quaternion.copy(this._rotation)):(t=Math.max(0,Math.min(1,t)),e.position.lerp(this._position,t),e.quaternion.slerp(this._rotation,t))}static _positionBuffer=new qe(()=>new r,20);static _rotationBuffer=new qe(()=>new Ue,20);_position;_rotation;ensureTransformData(){if(!this._position){this._position=e._positionBuffer.get(),this._rotation=e._rotationBuffer.get();let t=this._pose.transform,n=j.active.convertSpace(t);this._position.copy(n?.position),this._rotation.copy(n?.quaternion)}}_trackingComponent;_trackedImage;_bitmap;_pose;constructor(e,t,n,r,i,a){this._trackingComponent=e,this._trackedImage=t,this._bitmap=n,this.measuredSize=r,this.state=i,this._pose=a}},Ll=class{constructor(e){this.image=e.url,this.widthInMeters=e.widthInMeters,e.object instanceof S?this.object=new w({asset:e.object}):this.object=e.object,e.createObjectInstance!==void 0&&(this.createObjectInstance=e.createObjectInstance),e.imageDoesNotMove!==void 0&&(this.imageDoesNotMove=e.imageDoesNotMove),e.hideWhenTrackingIsLost!==void 0&&(this.hideWhenTrackingIsLost=e.hideWhenTrackingIsLost)}image;widthInMeters=.25;object;createObjectInstance=!1;imageDoesNotMove=!1;hideWhenTrackingIsLost=!0;getNameFromUrl(){if(this.image){let e=this.image.split(`/`);return e[e.length-1]}return null}};Pl([E(URL)],Ll.prototype,`image`,void 0),Pl([E()],Ll.prototype,`widthInMeters`,void 0),Pl([E(w)],Ll.prototype,`object`,void 0),Pl([E()],Ll.prototype,`createObjectInstance`,void 0),Pl([E()],Ll.prototype,`imageDoesNotMove`,void 0),Pl([E()],Ll.prototype,`hideWhenTrackingIsLost`,void 0);var Rl=class{exporter;component;isImageTrackingExtension=!0;get extensionName(){return`image-tracking`}constructor(e,t){this.exporter=e,this.component=t,Fl&&console.log(this),this.exporter.anchoringType=`image`}shouldExport=!0;filename=null;imageModel=null;onBeforeBuildDocument(e){this.shouldExport=this.exporter.extensions.filter(e=>{let t=e;return t.isImageTrackingExtension&&t.component.activeAndEnabled&&t.component.trackedImages?.length>0}).indexOf(this)===0,this.shouldExport&&this.component.trackedImages?.length>1&&(Fl||T())&&(kn(`USDZ: Only one tracked image is supported.`),console.warn(`USDZ: Only one tracked image is supported. Will choose the first one in the trackedImages list`))}onAfterHierarchy(e,t){if(!this.shouldExport)return;let n=A.getiOSVersion(),r=(n?parseInt(n.split(`.`)[0]):18)>=18?1:100;t.beginBlock(`def Preliminary_ReferenceImage "AnchoringReferenceImage"`),t.appendLine(`uniform asset image = @image_tracking/`+this.filename+`@`),t.appendLine(`uniform double physicalWidth = `+(this.imageModel.widthInMeters*r).toFixed(8)),t.closeBlock()}async onAfterSerialize(e){if(!this.shouldExport)return;let t=this.imageModel,n=await(await(await $o(Bl.get(t.image))).convertToBlob({type:`image/png`})).arrayBuffer();e.files[`image_tracking/`+this.filename]=new Uint8Array(n)}onExportObject(e,t,n){if(!this.shouldExport)return;let i=this.component;if(!i||!i.trackedImages?.length||!i.activeAndEnabled)return;let a=i.trackedImages[0];if(a.object?.asset===e){this.imageModel=a,this.filename=a.getNameFromUrl()||`marker.png`;let{scale:n,target:i}=this.exporter.getARScaleAndTarget(),o=e,s=new b;if(e!==i)for(;o&&o.parent&&o.parent!==i;)o=o.parent,s.premultiply(o.matrix);let c=s.clone().invert();t.setMatrix(c.scale(new r(n,n,n)))}}},zl=class extends N{setPrimaryImage(e){let t=this.trackedImages.indexOf(e);if(t>=0){let n=this.trackedImages[0];n!==e&&(this.trackedImages[0]=e,this.trackedImages[t]=n)}else console.warn(`[WebXRImageTracking] Can not set primary: image not found in 'trackedImages' array ${e.image}`)}addImage(e,t=!1){this.trackedImages.includes(e)||(this.trackedImages.push(e),Hl(e.image)),t&&this.setPrimaryImage(e)}trackedImages=[];smooth=!0;trackedImageIndexMap=new Map;get supported(){return this._supported}_supported=!0;awake(){if(Fl&&console.log(this),this.trackedImages)for(let e of this.trackedImages)e.image&&Hl(e.image)}onEnable(){$.beforeExport.addEventListener(this.onBeforeUSDZExport)}onDisable(){$.beforeExport.removeEventListener(this.onBeforeUSDZExport)}onBeforeUSDZExport=e=>{this.activeAndEnabled&&this.trackedImages?.length&&e.exporter.extensions.push(new Rl(e.exporter,this))};onBeforeXR(e,t){if(this.trackedImages){t.optionalFeatures=t.optionalFeatures||[],t.optionalFeatures.includes(`image-tracking`)||t.optionalFeatures.push(`image-tracking`),t.trackedImages||=[];for(let e of this.trackedImages)if(e.image?.length&&e.widthInMeters>0){let n=Bl.get(e.image);n&&(this.trackedImageIndexMap.set(t.trackedImages.length,e),t.trackedImages.push({image:n,widthInMeters:e.widthInMeters}))}}}onEnterXR(e){if(this.trackedImages){for(let e of this.trackedImages)if(e.object?.asset){let t=e.object.asset;t.userData||={};let n={visible:t.visible,parent:t.parent,matrix:t.matrix.clone()};t.userData[`image-tracking`]=n}}for(let e of this.imageToObjectMap.values())e.frames=0}onLeaveXR(e){if(!this.supported&&A.isAndroidDevice()&&kn(this.webXRIncubationsWarning),this.trackedImages){for(let e of this.trackedImages)if(e.object?.asset){let t=e.object.asset;if(t.userData){let e=t.userData[`image-tracking`];e&&(t.visible=e.visible,e.parent?.add(t),t.matrix.copy(e.matrix),t.matrix.decompose(t.position,t.quaternion,t.scale)),delete t.userData[`image-tracking`]}}}}imageToObjectMap=new Map;currentImages=[];webXRIncubationsWarning=`Image tracking is currently not supported on this device. On Chrome for Android, you can enable the <a target="_blank" href="#" onclick="() => console.log('I')">chrome://flags/#webxr-incubations</a> flag.`;onUpdateXR(e){this.currentImages.length=0;let t=e.xr.frame;if(!t)return;if(!(`getImageTrackingResults`in t)){this.didPrintWarning||(this.didPrintWarning=!0,console.log(this.webXRIncubationsWarning)),this._supported=!1,kn(this.webXRIncubationsWarning);return}else if(e.xr.session.enabledFeatures?.includes(`image-tracking`)===!1)return;else if(t.session&&typeof t.getImageTrackingResults==`function`){let e=t.getImageTrackingResults();if(e.length>0){let n=this.context.renderer.xr.getReferenceSpace();if(n){for(let r of e){let e=r.trackingState,i=r.index,a=this.trackedImageIndexMap.get(i);if(a){let i=t.getPose(r.imageSpace,n),o=new Il(this,a,r.image,r.measuredSize,e,i);this.currentImages.push(o)}else Fl&&console.warn(`No tracked image for index`,i)}if(this.currentImages.length>0)try{this.dispatchEvent(new CustomEvent(`image-tracking`,{detail:this.currentImages})),this.onImageTrackingUpdate(this.currentImages)}catch(e){console.error(e)}}}}let n=1e3;for(let[e,t]of this.imageToObjectMap){if(!t.object||!e||e.hideWhenTrackingIsLost===!1)continue;let r=!1;for(let i of this.currentImages)if(i.model===e){let a=Date.now()-t.lastTrackingTime;if(Fl&&vn(e.image+`, State: `+i.state+(e.imageDoesNotMove?` (static)`:``)+(a<=n?` (hysteresis)`:``)),e.imageDoesNotMove||i.state===`tracked`||a<=n){r=!0;break}}r||k.setActive(t.object,!1)}}onImageTrackingUpdate=e=>{let t=j.active;if(t)for(let n of e){let e=n.model,r=n.state===`tracked`;if(!e.object)continue;let i=this.imageToObjectMap.get(e);if(i===void 0)i={object:null,frames:0,lastTrackingTime:Date.now()},this.imageToObjectMap.set(e,i),e.object.loadAssetAsync().then(r=>{if(e.createObjectInstance&&r&&(r=k.instantiate(r)),r){i.object=r;for(let e of r.getComponentsInChildren(B))e.setInstancingEnabled(!1);t.rig?(t.rig.gameObject.add(r),n.applyToObject(r),r.activeSelf||k.setActive(r,!0)):console.warn(`XRImageTracking: missing XRRig`)}});else{if(i.frames++,r&&(i.lastTrackingTime=Date.now()),e.imageDoesNotMove&&i.frames>10||!i.object)continue;t.rig&&(t.rig.gameObject.add(i.object),n.applyToObject(i.object,this.smooth?this.context.time.deltaTimeUnscaled*3:void 0),i.object.activeSelf||k.setActive(i.object,!0))}}}};Pl([E(Ll)],zl.prototype,`trackedImages`,void 0),Pl([E()],zl.prototype,`smooth`,void 0);var Bl=new Map,Vl=new Map;async function Hl(e){if(Bl.has(e))return Vl.has(e)?Vl.get(e):Promise.resolve(!0);let t=new Promise(t=>{Bl.set(e,null);let n=document.createElement(`img`);n.src=e,n.addEventListener(`load`,async()=>{let r=await createImageBitmap(n);Bl.set(e,r),t(!0)})});return Vl.set(e,t),t.finally(()=>{Vl.delete(e)}),t}var Ul=function(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},Wl=D(`debugplanetracking`),Gl=class extends N{dataTemplate;occluder=!0;initiateRoomCaptureIfNoData=!0;usePlaneData=!0;useMeshData=!0;runInVR=!0;get trackedPlanes(){return this._allPlanes.values()}get trackedMeshes(){return this._allMeshes.values()}onBeforeXR(e,t){e===`immersive-vr`&&!this.runInVR||(t.optionalFeatures=t.optionalFeatures||[],this.usePlaneData&&!t.optionalFeatures.includes(`plane-detection`)&&t.optionalFeatures.push(`plane-detection`),this.useMeshData&&!t.optionalFeatures.includes(`mesh-detection`)&&t.optionalFeatures.push(`mesh-detection`))}onEnterXR(e){for(let e of this._allPlanes.keys())this.removeData(e,this._allPlanes);for(let e of this._allMeshes.keys())this.removeData(e,this._allMeshes)}onLeaveXR(e){for(let e of this._allPlanes.keys())this.removeData(e,this._allPlanes);for(let e of this._allMeshes.keys())this.removeData(e,this._allMeshes)}onUpdateXR(e){if(!this.runInVR&&e.xr.isVR)return;let t=e.xr.rig;if(!t){console.warn(`No XR rig found, cannot parent tracked planes to it`);return}let n=e.xr.frame;if(!this.context.renderer.xr.getReferenceSpace())return;let r=n.detectedPlanes,i=n.detectedMeshes,a=r!==void 0&&r.size>0,o=i!==void 0&&i.size>0;if(this.initiateRoomCaptureIfNoData&&(!a&&!o&&this.firstTimeNoPlanesDetected<-10&&(this.firstTimeNoPlanesDetected=Date.now()),(a||o)&&(this.firstTimeNoPlanesDetected=-1),this.firstTimeNoPlanesDetected>0&&Date.now()-this.firstTimeNoPlanesDetected>2500&&`initiateRoomCapture`in n.session&&(n.session.initiateRoomCapture(),this.firstTimeNoPlanesDetected=-1)),r!==void 0&&this.processFrameData(e.xr,t.gameObject,n,r,this._allPlanes),i!==void 0&&this.processFrameData(e.xr,t.gameObject,n,i,this._allMeshes),Wl){let e=this.context.mainCameraComponent.gameObject.worldPosition;for(let t of this._allPlanes.values())!t.mesh||!t.mesh.visible||(this.bounds.makeEmpty(),t.mesh.traverse(e=>{e instanceof x&&this.bounds.expandByObject(e)}),this.bounds.getCenter(this.center),this.labelOffset.copy(e).sub(this.center).normalize().multiplyScalar(.1),Ln.DrawLabel(this.center.add(this.labelOffset),(t.xrData.semanticLabel||`plane`).toUpperCase()+`
|
||
`+t.xrData.lastChangedTime.toFixed(2),.02))}}bounds=new de;center=new r;labelOffset=new r;removeData(e,t){let n=t.get(e);if(!n)return;t.delete(e),Wl&&console.log(`Plane no longer tracked, id=`+n.id),n.mesh&&(n.mesh.removeFromParent(),n.mesh.traverse(e=>{let t=e.userData.normalsHelper;t?(t.dispose(),t.removeFromParent()):Wl&&console.warn(`No normals helper found for mesh`,n.mesh)}),dn(n.mesh,!0,!0));let r=new CustomEvent(`plane-tracking`,{detail:{type:`plane-removed`,context:n}});this.dispatchEvent(r)}_dataId=1;_allPlanes=new Map;_allMeshes=new Map;firstTimeNoPlanesDetected=-100;makeOccluder=(e,t,n=!1)=>{if(t){if(t instanceof Array){for(let r of t)this.makeOccluder(e,r,n);return}!n&&!t.name.toLowerCase().includes(`occlu`)||(t.colorWrite=!1,t.depthTest=!0,t.depthWrite=!0,t.transparent=!1,t.polygonOffset=!0,t.polygonOffsetFactor=1,t.polygonOffsetUnits=.1,e.renderOrder=-1e3)}};processFrameData(e,t,n,r,i){let a=this.context.renderer.xr.getReferenceSpace();if(a){for(let e of i.keys())r.has(e)||this.removeData(e,i);for(let e of r){let r=`planeSpace`in e?e.planeSpace:`meshSpace`in e?e.meshSpace:void 0;if(!r)continue;let o=n.getPose(r,a),s;if(i.has(e)){let t=i.get(e);if(s=t.mesh,t.timestamp<e.lastChangedTime){if(t.timestamp=e.lastChangedTime,t.mesh){let n=this.createGeometry(e);if(t.mesh instanceof x)t.mesh.geometry.dispose(),t.mesh.geometry=n,this.makeOccluder(t.mesh,t.mesh.material);else if(t.mesh instanceof ve)for(let e of t.mesh.children)e instanceof x&&(e.geometry.dispose(),e.geometry=n,this.makeOccluder(e,e.material));if(t.collider){let e=t.mesh;t.collider.sharedMesh=e,t.collider.convex=this.checkIfContextShouldBeConvex(e,t.xrData),t.collider.onDisable(),t.collider.onEnable()}Wl&&(console.log(`Plane updated, id=`+t.id,t),t.mesh.traverse(e=>{if(!(e instanceof x))return;let t=e.userData.normalsHelper;t&&t.update()}))}let n=new CustomEvent(`plane-tracking`,{detail:{type:`plane-updated`,context:t}});this.dispatchEvent(n)}}else{if(!this.dataTemplate){let e=new x;Wl?e.material=new Le:this.occluder?(e.material=new v,this.makeOccluder(e,e.material,!0)):e.material=new v({wireframe:!0,opacity:.5,transparent:!0,color:3355443}),this.dataTemplate=new w(``,``,e)}if(!this.dataTemplate.asset)this.dataTemplate.loadAssetAsync();else{let n=k.instantiate(this.dataTemplate.asset);if(n.name=`xr-tracked-plane`,s=n,Dt(n,!1),n instanceof x)Nt(n.geometry),n.geometry=this.createGeometry(e),this.makeOccluder(n,n.material,this.occluder&&!this.dataTemplate);else if(n instanceof ve)for(let t of n.children)t instanceof x&&(Nt(t.geometry),t.geometry=this.createGeometry(e),this.makeOccluder(t,t.material,this.occluder&&!this.dataTemplate));let r=n.getComponent(xi);if(r){let t=n;r.sharedMesh=t,r.convex=this.checkIfContextShouldBeConvex(t,e),r.onDisable(),r.onEnable()}n.matrixAutoUpdate=!1,n.matrixWorldNeedsUpdate=!0,t.add(n);let a={id:this._dataId++,xrData:e,timestamp:e.lastChangedTime,mesh:n,collider:r};i.set(e,a),Wl&&console.log(`New plane detected, id=`+a.id,a,{hasCollider:!!r,isGroup:n instanceof ve});try{let e=new CustomEvent(`plane-tracking`,{detail:{type:`plane-added`,context:a}});this.dispatchEvent(e)}catch(e){console.error(e)}}}s&&(o?(s.visible=!0,s.matrix.fromArray(o.transform.matrix),s.matrix.premultiply(this._flipForwardMatrix)):s.visible=!1,Wl&&s.traverse(e=>{if(e instanceof x)if(e.userData.normalsHelper)e.userData.normalsHelper.update();else{let t=new pr(e,.05,255);t.layers.disableAll(),t.layers.set(2),this.context.scene.add(t),e.userData.normalsHelper=t}}))}}}_flipForwardMatrix=new b().makeRotationY(Math.PI);checkIfContextShouldBeConvex(e,t){if(!e)return!0;if(e){let n=new de;n.expandByObject(e);let i=new r;n.getSize(i);let a=!0;return i.x>2&&i.y>2&&i.z>1.5&&(a=!1),a&&`semanticLabel`in t&&t.semanticLabel===`wall`&&(a=!0),a}return!0}createGeometry(e){return`polygon`in e?this.createPlaneGeometry(e.polygon):`vertices`in e&&`indices`in e?this.createMeshGeometry(e.vertices,e.indices):new ie}_verticesCache=new Map;createMeshGeometry(e,t){let n=e.toString()+`_`+t.toString();if(this._verticesCache.has(n))return this._verticesCache.get(n);let r=new ie;r.setIndex(new Ge(t,1)),r.setAttribute(`position`,new Ge(e,3));let i=[];for(let t=0;t<e.length;t+=3)i.push(e[t],e[t+2]);return r.setAttribute(`uv`,new Ge(e,3)),r.computeVertexNormals(),this._verticesCache.set(n,r),r}createPlaneGeometry(e){let t=new ie,n=[],i=[];e.forEach(e=>{n.push(e.x,e.y,e.z),i.push(e.x,e.z)});let a=new r(n[0],n[1],n[2]),o=new r(n[3],n[4],n[5]),s=new r(n[6],n[7],n[8]),c=new r,l=new r;c.subVectors(o,a),l.subVectors(s,a),c.cross(l),c.normalize();let u=[];for(let e=0;e<n.length/3;e++)u.push(c.x,c.y,c.z);let d=[];for(let t=2;t<e.length;++t)d.push(0,t-1,t);return t.setAttribute(`position`,new Ge(new Float32Array(n),3)),t.setAttribute(`uv`,new Ge(new Float32Array(i),2)),t.setAttribute(`normal`,new Ge(new Float32Array(u),3)),t.setIndex(d),t.computeBoundingBox(),t.computeBoundingSphere(),t}};Ul([E(w)],Gl.prototype,`dataTemplate`,void 0),Ul([E()],Gl.prototype,`occluder`,void 0),Ul([E()],Gl.prototype,`initiateRoomCaptureIfNoData`,void 0),Ul([E()],Gl.prototype,`usePlaneData`,void 0),Ul([E()],Gl.prototype,`useMeshData`,void 0),Ul([E()],Gl.prototype,`runInVR`,void 0);var Kl=function(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},ql=D(`debugwebxr`),Jl=class extends N{priority=0;get isActive(){return this.activeAndEnabled&&this.gameObject.visible}setAsActiveXRRig(){j.active?.setRigActive(this)}setPriority(e){this.priority=e}awake(){if(ql){let e=new S;e.position.y+=.5,this.gameObject.add(e);let t=e.addNewComponent(vl);t&&(t.isGizmo=!1);let n=new _e(.5);this.gameObject.add(n)}}isXRRig(){return!0}supportsXR(e){return!0}_startScale;onEnterXR(e){this._startScale=this.gameObject.scale.clone(),e.xr.addRig(this),ql&&console.log(`WebXR: add Rig`,this.name,this.priority)}onLeaveXR(e){e.xr.removeRig(this),this._startScale&&this.gameObject&&this.gameObject.scale.copy(this._startScale)}};Kl([E()],Jl.prototype,`priority`,void 0);export{Ls as $,ei as $t,kc as A,Ba as At,Ws as B,bi as Bt,Gc as C,qa as Ct,Rc as D,Va as Dt,Lc as E,Ga as Et,mc as F,ma as Ft,Js as G,gi as Gt,qs as H,vi as Ht,_c as I,oa as It,Gs as J,di as Jt,Xs as K,mi as Kt,vc as L,Hi as Lt,Ec as M,xa as Mt,Tc as N,Sa as Nt,zc as O,Wa as Ot,xc as P,ba as Pt,Rs as Q,ni as Qt,gc as R,ki as Rt,Jc as S,$a as St,Bc as T,za as Tt,Ks as U,xi as Ut,Us as V,Si as Vt,Ys as W,yi as Wt,Qs as X,oi as Xt,$s as Y,ui as Yt,Vs as Z,ai as Zt,cl as _,po as _t,Il as a,Gr as an,js as at,$c as b,B as bt,Ol as c,Br as cn,Mo as ct,bl as d,Pr as dn,Ro as dt,qr as en,K as et,vl as f,I as fn,Xo as ft,al as g,ho as gt,ll as h,_r as hn,V as ht,Ll as i,Wr as in,Ms as it,Dc as j,Ma as jt,Nc as k,Ua as kt,wl as l,zr as ln,jo as lt,$ as m,xr as mn,wo as mt,Gl as n,Zr as nn,Ns as nt,Ml as o,Qr as on,ks as ot,gl as p,Cr as pn,$o as pt,Zs as q,fi as qt,zl as r,Xr as rn,Es as rt,kl as s,Ur as sn,Ps as st,Jl as t,R as tn,G as tt,Tl as u,Ir as un,Fo as ut,il as v,oo as vt,Wc as w,Ka as wt,X as x,uo as xt,el as y,lo as yt,sc as z,Ei as zt}; |